Search is not available for this dataset
content
stringlengths
60
399M
max_stars_repo_name
stringlengths
6
110
<|start_filename|>package.json<|end_filename|> { "name": "secure-filters", "version": "1.1.0", "description": "Anti-XSS filters for security", "main": "index.js", "scripts": { "test": "`npm bin`/mocha test.js && `npm bin`/mocha-phantomjs -R dot static/test.html" }, "homepage": "http://salesforce.github.io/secure-filters/", "repository": "<EMAIL>:salesforce/secure-filters.git", "author": "Sales<EMAIL>, Inc.", "license": "BSD-3-Clause", "engines": { "node": ">= 0.10.0" }, "keywords": [ "security", "xss", "ejs", "escape", "encode" ], "devDependencies": { "chai": "^1.9.2", "mocha": "^1.21.4", "mocha-phantomjs": "^4.1.0", "underscore": "^1.8.0" } } <|start_filename|>test.js<|end_filename|> /*! * Copyright (c) 2014, Salesforce.com, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of Salesforce.com, nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL 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. */ (function(root) { 'use strict'; var assert; var secureFilters; var _; if (typeof module !== 'undefined' && module.exports) { assert = require('assert'); secureFilters = require('./index'); _ = require('underscore'); } else { assert = root.assert; secureFilters = root.secureFilters; _ = root._; } // Test character inside the Unicode BMP: var SNOWMAN = "\u2603"; // Test character outside of the Unicode BMP: var FACE_WITHOUT_MOUTH = "\uD83D\uDE36"; // U+1F636, UTF-16: D83D DE36, UTF-8: F0 9F 98 B6 var ASCII = "\0"; for (var i = 1; i <= 0x7F; i++) { ASCII += String.fromCharCode(i); } var ALL_CASES = [ { input: '&&amp;\'d', html: '&amp;&amp;amp&#59;&#39;d', js: '\\x26\\x26amp\\x3B\\x27d', jsAttr: '&#92;x26&#92;x26amp&#92;x3B&#92;x27d', uri: '%26%26amp%3B%27d', css: '\\26 \\26 amp\\3b \\27 d', style: '&#92;26 &#92;26 amp&#92;3b &#92;27 d' }, { input: '\' onload="alert(1)"', html: '&#39; onload&#61;&quot;alert&#40;1&#41;&quot;', js: '\\x27\\x20onload\\x3D\\x22alert\\x281\\x29\\x22', jsAttr: '&#92;x27&#92;x20onload&#92;x3D&#92;x22alert&#92;x281&#92;x29&#92;x22', uri: '%27%20onload%3D%22alert%281%29%22', css: '\\27 \\20 onload\\3d \\22 alert\\28 1\\29 \\22 ', style: '&#92;27 &#92;20 onload&#92;3d &#92;22 alert&#92;28 1&#92;29 &#92;22 ' }, { input: '<ha>, \'ha\', "ha"', html: '&lt;ha&gt;, &#39;ha&#39;, &quot;ha&quot;', js: '\\x3Cha\\x3E,\\x20\\x27ha\\x27,\\x20\\x22ha\\x22', jsAttr: '&#92;x3Cha&#92;x3E,&#92;x20&#92;x27ha&#92;x27,&#92;x20&#92;x22ha&#92;x22', uri: '%3Cha%3E%2C%20%27ha%27%2C%20%22ha%22', css: '\\3c ha\\3e \\2c \\20 \\27 ha\\27 \\2c \\20 \\22 ha\\22 ', style: '&#92;3c ha&#92;3e &#92;2c &#92;20 &#92;27 ha&#92;27 &#92;2c &#92;20 &#92;22 ha&#92;22 ' }, { label: "ESAPI bad JS chars", input: "!@$%()=+{}[]", html: "&#33;&#64;&#36;&#37;&#40;&#41;&#61;&#43;&#x7B;&#x7D;&#91;&#93;", js: "\\x21\\x40\\x24\\x25\\x28\\x29\\x3D\\x2B\\x7B\\x7D\\x5B\\x5D", jsAttr: "&#92;x21&#92;x40&#92;x24&#92;x25&#92;x28&#92;x29&#92;x3D&#92;x2B&#92;x7B&#92;x7D&#92;x5B&#92;x5D", uri: "%21%40%24%25%28%29%3D%2B%7B%7D%5B%5D", css: '\\21 \\40 \\24 \\25 \\28 \\29 \\3d \\2b \\7b \\7d \\5b \\5d ', style: '&#92;21 &#92;40 &#92;24 &#92;25 &#92;28 &#92;29 &#92;3d &#92;2b &#92;7b &#92;7d &#92;5b &#92;5d ' }, { label: "ESAPI maybe bad chars", input: " ,.-_ ", html: " ,.-_ ", js: "\\x20,.-_\\x20", jsAttr: "&#92;x20,.-_&#92;x20", uri: "%20%2C.-_%20", css: '\\20 \\2c \\2e \\2d \\5f \\20 ', style: '&#92;20 &#92;2c &#92;2e &#92;2d &#92;5f &#92;20 ' }, { label: "ASCII punctuation", input: '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~', // punctuation in ASCII range (lexical order) html: '&#33;&quot;&#35;&#36;&#37;&amp;&#39;&#40;&#41;&#42;&#43;,-.&#47;&#58;&#59;&lt;&#61;&gt;&#63;&#64;&#91;&#92;&#93;&#94;_&#96;&#x7B;&#x7C;&#x7D;&#x7E;', js: '\\x21\\x22\\x23\\x24\\x25\\x26\\x27\\x28\\x29\\x2A\\x2B,-.\\x2F\\x3A\\x3B\\x3C\\x3D\\x3E\\x3F\\x40\\x5B\\x5C\\x5D\\x5E_\\x60\\x7B\\x7C\\x7D\\x7E', jsAttr: '&#92;x21&#92;x22&#92;x23&#92;x24&#92;x25&#92;x26&#92;x27&#92;x28&#92;x29&#92;x2A&#92;x2B,-.&#92;x2F&#92;x3A&#92;x3B&#92;x3C&#92;x3D&#92;x3E&#92;x3F&#92;x40&#92;x5B&#92;x5C&#92;x5D&#92;x5E_&#92;x60&#92;x7B&#92;x7C&#92;x7D&#92;x7E', uri: '%21%22%23%24%25%26%27%28%29%2A%2B%2C-.%2F%3A%3B%3C%3D%3E%3F%40%5B%5C%5D%5E_%60%7B%7C%7D%7E', css: '\\21 \\22 \\23 \\24 \\25 \\26 \\27 \\28 \\29 \\2a \\2b \\2c \\2d \\2e \\2f \\3a \\3b \\3c \\3d \\3e \\3f \\40 \\5b \\5c \\5d \\5e \\5f \\60 \\7b \\7c \\7d \\7e ', style: '&#92;21 &#92;22 &#92;23 &#92;24 &#92;25 &#92;26 &#92;27 &#92;28 &#92;29 &#92;2a &#92;2b &#92;2c &#92;2d &#92;2e &#92;2f &#92;3a &#92;3b &#92;3c &#92;3d &#92;3e &#92;3f &#92;40 &#92;5b &#92;5c &#92;5d &#92;5e &#92;5f &#92;60 &#92;7b &#92;7c &#92;7d &#92;7e ' }, { label: 'every ASCII char', input: ASCII, html: ' \t\n \r '+ // most controls -> space (including NUL) ' '+ // 0x10 to 0x1F -> space ' ' + // space preserved '&#33;&quot;&#35;&#36;&#37;&amp;&#39;&#40;&#41;&#42;&#43;'+ ',-.'+ // safe punctuation '&#47;'+ '0123456789'+ // in alphanum '&#58;&#59;&lt;&#61;&gt;&#63;&#64;'+ 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'+ // in alphanum '&#91;&#92;&#93;&#94;'+ '_'+ // safe punctuation '&#96;'+ 'abcdefghijklmnopqrstuvwxyz'+ // in alphanum '&#x7B;&#x7C;&#x7D;&#x7E;'+ ' ', // 0x7f -> space js: '\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\x09\\x0A\\x0B\\x0C\\x0D\\x0E\\x0F\\x10\\x11\\x12\\x13\\x14\\x15\\x16\\x17\\x18\\x19\\x1A\\x1B\\x1C\\x1D\\x1E\\x1F\\x20\\x21\\x22\\x23\\x24\\x25\\x26\\x27\\x28\\x29\\x2A\\x2B'+ ',-.'+ // safe punctuation '\\x2F'+ '0123456789'+ // in alphanum '\\x3A\\x3B\\x3C\\x3D\\x3E\\x3F\\x40'+ 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'+ // in alphanum '\\x5B\\x5C\\x5D\\x5E'+ '_'+ // safe punctuation '\\x60'+ 'abcdefghijklmnopqrstuvwxyz'+ // in alphanum '\\x7B\\x7C\\x7D\\x7E\\x7F', jsAttr: '&#92;x00&#92;x01&#92;x02&#92;x03&#92;x04&#92;x05&#92;x06&#92;x07&#92;x08&#92;x09&#92;x0A&#92;x0B&#92;x0C&#92;x0D&#92;x0E&#92;x0F&#92;x10&#92;x11&#92;x12&#92;x13&#92;x14&#92;x15&#92;x16&#92;x17&#92;x18&#92;x19&#92;x1A&#92;x1B&#92;x1C&#92;x1D&#92;x1E&#92;x1F&#92;x20&#92;x21&#92;x22&#92;x23&#92;x24&#92;x25&#92;x26&#92;x27&#92;x28&#92;x29&#92;x2A&#92;x2B'+ ',-.'+ '&#92;x2F'+ '0123456789'+ '&#92;x3A&#92;x3B&#92;x3C&#92;x3D&#92;x3E&#92;x3F&#92;x40'+ 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'+ '&#92;x5B&#92;x5C&#92;x5D&#92;x5E'+ '_'+ '&#92;x60'+ 'abcdefghijklmnopqrstuvwxyz'+ '&#92;x7B&#92;x7C&#92;x7D&#92;x7E&#92;x7F', uri: '%00%01%02%03%04%05%06%07%08%09%0A%0B%0C%0D%0E%0F%10%11%12%13%14%15%16%17%18%19%1A%1B%1C%1D%1E%1F%20%21%22%23%24%25%26%27%28%29%2A%2B%2C'+ '-.'+ // uri-safe punctuation '%2F'+ '0123456789'+ // in alphanum '%3A%3B%3C%3D%3E%3F%40'+ 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'+ // in alphanum '%5B%5C%5D%5E'+ '_'+ // uri-safe punctuation '%60'+ 'abcdefghijklmnopqrstuvwxyz'+ // in alphanum '%7B%7C%7D%7E%7F', css: '\\fffd '+ // undefined behaviour '\\1 \\2 \\3 \\4 \\5 \\6 \\7 \\8 \\9 \\a \\b \\c \\d \\e \\f \\10 \\11 \\12 \\13 \\14 \\15 \\16 \\17 \\18 \\19 \\1a \\1b \\1c \\1d \\1e \\1f \\20 \\21 \\22 \\23 \\24 \\25 \\26 \\27 \\28 \\29 \\2a \\2b \\2c \\2d \\2e \\2f '+ '0123456789'+ // alphanum '\\3a \\3b \\3c \\3d \\3e \\3f \\40 '+ 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'+ // alphanum '\\5b \\5c \\5d \\5e \\5f \\60 '+ 'abcdefghijklmnopqrstuvwxyz'+ // alphanum '\\7b \\7c \\7d \\7e \\7f ', style: '&#92;fffd '+ // undefined behaviour '&#92;1 &#92;2 &#92;3 &#92;4 &#92;5 &#92;6 &#92;7 &#92;8 &#92;9 &#92;a &#92;b &#92;c &#92;d &#92;e &#92;f &#92;10 &#92;11 &#92;12 &#92;13 &#92;14 &#92;15 &#92;16 &#92;17 &#92;18 &#92;19 &#92;1a &#92;1b &#92;1c &#92;1d &#92;1e &#92;1f &#92;20 &#92;21 &#92;22 &#92;23 &#92;24 &#92;25 &#92;26 &#92;27 &#92;28 &#92;29 &#92;2a &#92;2b &#92;2c &#92;2d &#92;2e &#92;2f '+ '0123456789'+ // alphanum '&#92;3a &#92;3b &#92;3c &#92;3d &#92;3e &#92;3f &#92;40 '+ 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'+ // alphanum '&#92;5b &#92;5c &#92;5d &#92;5e &#92;5f &#92;60 '+ 'abcdefghijklmnopqrstuvwxyz'+ // alphanum '&#92;7b &#92;7c &#92;7d &#92;7e &#92;7f ' }, { label: "URI-encoded input", input: '%3Cscript%3E', // i.e., already uri-encoded html: '&#37;3Cscript&#37;3E', js: '\\x253Cscript\\x253E', jsAttr: '&#92;x253Cscript&#92;x253E', uri: '%253Cscript%253E', css: '\\25 3Cscript\\25 3E', style: '&#92;25 3Cscript&#92;25 3E' }, { input: "é, ß, "+SNOWMAN+", "+FACE_WITHOUT_MOUTH, html: "é, ß, "+SNOWMAN+", "+FACE_WITHOUT_MOUTH, js: "\\u00E9,\\x20\\u00DF,\\x20\\u2603,\\x20\\uD83D\\uDE36", jsAttr: "&#92;u00E9,&#92;x20&#92;u00DF,&#92;x20&#92;u2603,&#92;x20&#92;uD83D&#92;uDE36", uri: '%C3%A9%2C%20%C3%9F%2C%20%E2%98%83%2C%20%F0%9F%98%B6', css: '\\e9 \\2c \\20 \\df \\2c \\20 \\2603 \\2c \\20 '+FACE_WITHOUT_MOUTH, // U+10000 and up are preserved style: '&#92;e9 &#92;2c &#92;20 &#92;df &#92;2c &#92;20 &#92;2603 &#92;2c &#92;20 '+FACE_WITHOUT_MOUTH }, { label: 'CDATA', input: '<![CDATA[ blah ]]>', html: '&lt;&#33;&#91;CDATA&#91; blah &#93;&#93;&gt;', js: '\\x3C\\x21\\x5BCDATA\\x5B\\x20blah\\x20\\x5D\\x5D\\x3E', jsAttr: '&#92;x3C&#92;x21&#92;x5BCDATA&#92;x5B&#92;x20blah&#92;x20&#92;x5D&#92;x5D&#92;x3E', uri: '%3C%21%5BCDATA%5B%20blah%20%5D%5D%3E', css: '\\3c \\21 \\5b CDATA\\5b \\20 blah\\20 \\5d \\5d \\3e ', style: '&#92;3c &#92;21 &#92;5b CDATA&#92;5b &#92;20 blah&#92;20 &#92;5d &#92;5d &#92;3e ' }, { label: 'nbsp', input: '\u00A0', html: '\u00A0', // un-encoded js: '\\u00A0', jsAttr: '&#92;u00A0', uri: '%C2%A0', css: '\\a0 ', style: '&#92;a0 ' }, { label: 'README html example', input: '"><script>alert(\'pwn\')</script>', html: '&quot;&gt;&lt;script&gt;alert&#40;&#39;pwn&#39;&#41;&lt;&#47;script&gt;' }, { label: 'README html example 2', input: "x' onerror='alert(1)", html: 'x&#39; onerror&#61;&#39;alert&#40;1&#41;' }, { label: 'integer literal', input: 1234, html: "1234", js: "1234", jsAttr: "1234", uri: "1234", jsObj: "1234", css: "1234", style: "1234" }, { label: 'boolean literal', input: true, html: "true", js: "true", jsAttr: "true", uri: "true", jsObj: "true", css: "true", style: "true" }, { label: 'float literal', input: 1234.5678, html: "1234.5678", js: "1234.5678", jsAttr: "1234.5678", uri: "1234.5678", jsObj: "1234.5678", css: "1234\\2e 5678", style: "1234&#92;2e 5678" }, { label: 'object literal', input: {key:"</script><script>alert(\"hah!\")"}, jsObj: '{"key":"\\x3C\\x2Fscript\\x3E\\x3Cscript\\x3Ealert\\x28\\"hah\\x21\\"\\x29"}' }, { label: 'object literal w/ unicode', input: {key:"snowman:"+SNOWMAN}, jsObj: '{"key":"snowman:\\u2603"}' }, { label: 'object w/ LINE SEPARATOR U+2028 and PARAGRAPH SEPARATOR U+2029', input: {"line\u2028sep":"para\u2029sep"}, jsObj: '{"line\\u2028sep":"para\\u2029sep"}' }, { label: 'array literal', input: [1,2.3,"ouch",'</script><script>alert(\"hah!\")'], jsObj: '[1,2.3,"ouch","\\x3C\\x2Fscript\\x3E\\x3Cscript\\x3Ealert\\x28\\"hah\\x21\\"\\x29"]' }, { label: 'CDATA in object', input: {"open":"<![CDATA[", "close": "]]>"}, jsObj: '{"open":"\\x3C\\x21[CDATA[","close":"\\x5D\\x5D\\x3E"}' }, { label: "nested array doesn't trigger CDATA protection", input: [[['a']],['b']], jsObj: '[[["a"]],["b"]]' } ]; describe('secure filters', function() { _.each(ALL_CASES, function(c) { var input = c.input; var label = c.label || 'input "'+c.input+'"'; describe('for '+label, function() { _.each(c, function(expect, filterName) { if (filterName === 'input' || filterName === 'label') { return; } var func = secureFilters[filterName]; assert(func); assert.strictEqual(typeof func, "function"); it('filter '+filterName+' produces "'+expect+'"', function() { var output = func(input); assert.strictEqual(output, expect); }); }); }); }); }); describe('exporting to EJS', function() { function checkAllFilters(ejs) { assert(ejs.filters); assert(ejs.filters instanceof Object); var keys = _.keys(ejs.filters); assert.equal(keys.length, 7); assert('html' in ejs.filters); assert('js' in ejs.filters); assert('jsAttr' in ejs.filters); assert('uri' in ejs.filters); assert('jsObj' in ejs.filters); assert('css' in ejs.filters); assert('style' in ejs.filters); } it('.configure()s an empty object', function() { var mockEjs = {}; secureFilters.configure(mockEjs); checkAllFilters(mockEjs); }); it('.configure()s an object with .filters', function() { var mockEjs = { filters: {} }; secureFilters.configure(mockEjs); checkAllFilters(mockEjs); }); }); }(this));
salesforce/secure-filters
<|start_filename|>portmidi/pm_mac/pmmac.c<|end_filename|> /* pmmac.c -- PortMidi os-dependent code */ /* This file only needs to implement: pm_init(), which calls various routines to register the available midi devices, Pm_GetDefaultInputDeviceID(), and Pm_GetDefaultOutputDeviceID(). It is seperate from pmmacosxcm because we might want to register non-CoreMIDI devices. */ #include "stdlib.h" #include "portmidi.h" #include "pmmacosxcm.h" PmError pm_init() { return pm_macosxcm_init(); } void pm_term(void) { pm_macosxcm_term(); } PmDeviceID pm_default_input_device_id = -1; PmDeviceID pm_default_output_device_id = -1; PmDeviceID Pm_GetDefaultInputDeviceID() { return pm_default_input_device_id; } PmDeviceID Pm_GetDefaultOutputDeviceID() { return pm_default_output_device_id; } void *pm_alloc(size_t s) { return malloc(s); } void pm_free(void *ptr) { free(ptr); } <|start_filename|>portmidi/pm_mac/pmmacosxcm.h<|end_filename|> /* system-specific definitions */ PmError pm_macosxcm_init(void); void pm_macosxcm_term(void);
xprl-gjf/PortMidi
<|start_filename|>testinstall/testmod.c<|end_filename|> /* * Copyright (c) 2021 <NAME> and contributors * * 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. */ /* A very simple native module */ #include <janet.h> static Janet cfun_get_five(int32_t argc, Janet *argv) { (void) argv; janet_fixarity(argc, 0); return janet_wrap_number(5.0); } static const JanetReg array_cfuns[] = { {"get5", cfun_get_five, NULL}, {NULL, NULL, NULL} }; JANET_MODULE_ENTRY(JanetTable *env) { janet_cfuns(env, NULL, array_cfuns); } <|start_filename|>testinstall/testmod3.cpp<|end_filename|> /* * Copyright (c) 2021 <NAME> and contributors * * 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. */ /* A very simple native module */ #include <janet.h> #include <iostream> static Janet cfun_get_seven(int32_t argc, Janet *argv) { (void) argv; janet_fixarity(argc, 0); std::cout << "Hello!" << std::endl; return janet_wrap_number(7.0); } static const JanetReg array_cfuns[] = { {"get7", cfun_get_seven, NULL}, {NULL, NULL, NULL} }; JANET_MODULE_ENTRY(JanetTable *env) { janet_cfuns(env, NULL, array_cfuns); }
uvtc/jpm
<|start_filename|>js/search.js<|end_filename|> function search() { var searchTerm = document.getElementById("searchTerm").value ; var website = 'https://www.google.com/search?q='; var inURL = ' -inurl:(jsp|pl|php|html|aspx|htm|cf|shtml)'; var videoFormats = ' +(wmv|mpg|avi|mp4|mkv|mov)'; var audioFormats = ' (ac3|flac|m4a|mp3|ogg|wav|wma)'; var imageFormats = ' (bmp|gif|jpg|png|psd|tif|tiff)'; var archiveFormats = ' +(.rar|.tar|.7z|.zip|.si)'; var bookFormats = ' (pdf|epub|mob)'; var inText = 'intext:"' + searchTerm + '"'; if(document.getElementById("o1").checked){ link = website + inText + ' intitle:"index.of"' + inURL; } else if(document.getElementById("o2").checked){ link = website + inText + ' intitle:"index.of"' + videoFormats + inURL; } else if(document.getElementById("o3").checked){ link = website + inText + ' intitle:"index.of"' + audioFormats + inURL; } else if(document.getElementById("o4").checked){ link = website + inText + ' intitle:"index.of"' + bookFormats + inURL; } else if(document.getElementById("o5").checked){ link = website + inText + ' intitle:"index.of"' + imageFormats + inURL; } else if(document.getElementById("o6").checked){ link = website + 'intitle:"' + searchTerm + '"' + archiveFormats + inURL; } window.open(link,'_blank'); }
IceWreck/OpenDirectorySearchTool
<|start_filename|>src/AssemblyVersionAuto.cs<|end_filename|> using System.Reflection; [assembly: AssemblyCopyright("Copyright � 2017 Episerver")] [assembly: AssemblyVersion("11.2.6.0")] [assembly: AssemblyInformationalVersion("11.2.6")] [assembly: AssemblyFileVersion("11.2.6.2664")] <|start_filename|>src/MusicFestival.Vue.Template/Assets/Scripts/directives/epiEdit.js<|end_filename|> /** * The directive `v-epi-edit` is used similarly to @Html.EditAttributes() in * Razor views. It enables On-Page Editing on elements using the `data-epi-edit` * property (introduced in Episerver CMS UI 11.X.0) and disables the DOM * updating from the CMS so that Vue can keep the responsibility over the DOM. * * It's enabled by the `isEditable` value that is stored in the Vuex store, but * can be overwritten by a component having a property named * `epiDisableEditing` being true. * * Usage can be found on most Vue components, such as ArtistDetailsPage.vue. */ import store from '@/Scripts/store'; function toggleEditAttributes(el, binding, vnode) { const siteIsEditable = store.state.epiContext.isEditable; const componentIsEditable = !vnode.context.epiDisableEditing; if (siteIsEditable && componentIsEditable) { el.setAttribute('data-epi-edit', binding.value); } else { el.removeAttribute('data-epi-edit'); } } export default { bind: toggleEditAttributes, update: toggleEditAttributes }; <|start_filename|>src/MusicFestival.Vue.Template/Assets/Scripts/store/modules/appContext.js<|end_filename|> /** * The module responsible for handling app-wide context state that is * interesting for several components that otherwise doesn't share state. */ //mutations for the appContext module export const SHOW_MODAL = 'appContext/SHOW_MODAL'; export const HIDE_MODAL = 'appContext/HIDE_MODAL'; const state = { modalShowing: false }; const mutations = { [SHOW_MODAL](state) { state.modalShowing = true; }, [HIDE_MODAL](state) { state.modalShowing = false; } }; export default { state, mutations }; <|start_filename|>src/MusicFestival.Vue.Template/Infrastructure/Owin/Startup.cs<|end_filename|> using System; using Microsoft.Owin; using Microsoft.Owin.Security.Cookies; using Owin; using EPiServer.Cms.UI.AspNetIdentity; using Microsoft.AspNet.Identity.Owin; using EPiServer.Web.Routing; using EPiServer.Core; using Microsoft.AspNet.Identity; using EPiServer.ContentApi.Core; [assembly: OwinStartup(typeof(MusicFestival.Template.Infrastructure.Owin.Startup))] namespace MusicFestival.Template.Infrastructure.Owin { public class Startup { public Startup() { // Parameterless constructor required by OWIN. } public void Configuration(IAppBuilder app) { app.AddCmsAspNetIdentity<ApplicationUser>(new ApplicationOptions() { ConnectionStringName = "EPiServerDB" }); // Enable the application to use a cookie to store information for the signed in user // and to use a cookie to temporarily store information about a user logging in with a third party login provider. // Configure the sign in cookie. app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, LoginPath = new PathString("/util/login.aspx"), Provider = new CookieAuthenticationProvider { // Enables the application to validate the security stamp when the user logs in. // This is a security feature which is used when you change a password or add an external login to your account. OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager<ApplicationUser>, ApplicationUser>( validateInterval: TimeSpan.FromMinutes(30), regenerateIdentity: (manager, user) => manager.GenerateUserIdentityAsync(user)), OnApplyRedirect = (context => { if (!IsContentApiRequest(context.Request.Uri)) { context.Response.Redirect(context.RedirectUri); } }), OnResponseSignOut = (context => context.Response.Redirect(UrlResolver.Current.GetUrl(ContentReference.StartPage))), }, }); app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie); } private bool IsContentApiRequest(Uri requestUri) { if (requestUri == null) return false; if (requestUri.IsAbsoluteUri) { return requestUri.PathAndQuery.StartsWith("/" + RouteConstants.BaseContentApiRoute); } else { return requestUri.ToString().StartsWith("/" + RouteConstants.BaseContentApiRoute); } } } } <|start_filename|>src/MusicFestival.Vue.Template/Controllers/DefaultPageController.cs<|end_filename|> using System.Web.Mvc; using MusicFestival.Template.Models.Pages; using EPiServer.Web.Mvc; namespace MusicFestival.Template.Controllers { public class DefaultPageController : PageController<BasePage> { public ViewResult Index(BasePage currentPage) { return View("~/Views/DefaultPage/Index.cshtml", currentPage); } } } <|start_filename|>src/MusicFestival.Vue.Template/Assets/Scripts/store/index.js<|end_filename|> /** * The main vuex store. This holds the state of the URL and makes sure that * when the URL is updated, the model gets updated too. */ import Vue from 'vue'; import Vuex from 'vuex'; // the module handling model state import epiDataModel from '@/Scripts/store/modules/epiDataModel'; // the module handling episerver specific state import epiContext from '@/Scripts/store/modules/epiContext'; // the module handling app specific state import appContext from '@/Scripts/store/modules/appContext'; Vue.use(Vuex); const store = new Vuex.Store({ modules: { appContext, epiDataModel, epiContext } }); export default store; <|start_filename|>src/MusicFestival.Vue.Template/Infrastructure/SiteInitialization.cs<|end_filename|> using EPiServer.Framework; using EPiServer.Framework.Initialization; using EPiServer.ServiceLocation; using System.Web.Mvc; using System.Web; using EPiServer.Web; using MusicFestival.Template.Models; using EPiServer.Web.Routing; using EPiServer.Core; using EPiServer.ContentApi.Core.Serialization; using EPiServer.ContentApi.Cms; using EPiServer.ContentApi.Core.Configuration; using EPiServer.ContentApi.Routing; using MusicFestival.Template.Infrastructure.Routing; namespace MusicFestival.Template.Infrastructure { [InitializableModule] [ModuleDependency(typeof(ServiceContainerInitialization), typeof(ContentApiCmsInitialization))] public class SiteInitialization : IConfigurableModule { public void ConfigureContainer(ServiceConfigurationContext context) { // Register the extended content model mapper to be able to provide custom models from content api context.Services.Intercept<IContentModelMapper>((locator, defaultModelMapper) => new ExtendedContentModelMapper( locator.GetInstance<IUrlResolver>(), defaultModelMapper, locator.GetInstance<ServiceAccessor<HttpContextBase>>(), locator.GetInstance<IContentVersionRepository>() ) ); DependencyResolver.SetResolver(new StructureMapDependencyResolver(context.StructureMap())); context.Services.AddTransient<IPropertyModelConverter, BuyTicketBlockPropertyModelConverter>(); context.Services.AddTransient<RoutingEventHandler, CustomContentApiRoutingEventHandler>(); // set minimumRoles to empty to allow anonymous calls (for visitors to view site in view mode) context.Services.Configure<ContentApiConfiguration>(config => { config.Default().SetMinimumRoles(string.Empty); }); } public void Initialize(InitializationEngine context) { var options = ServiceLocator.Current.GetInstance<DisplayOptions>(); options .Add("full", "Full", ContentAreaTags.FullWidth, "", "epi-icon__layout--full") .Add("wide", "Wide", ContentAreaTags.TwoThirdsWidth, "", "epi-icon__layout--two-thirds") .Add("half", "Half", ContentAreaTags.HalfWidth, "", "epi-icon__layout--half") .Add("narrow", "Narrow", ContentAreaTags.OneThirdWidth, "", "epi-icon__layout--one-third"); AreaRegistration.RegisterAllAreas(); } public void Uninitialize(InitializationEngine context) { } public static class ContentAreaTags { public const string FullWidth = "u-md-sizeFull"; public const string TwoThirdsWidth = "u-md-size2of3"; public const string HalfWidth = "u-md-size1of2"; public const string OneThirdWidth = "u-md-size1of3"; public const string NoRenderer = "norenderer"; } } } <|start_filename|>src/MusicFestival.Vue.Template/Assets/Scripts/store/modules/epiContext.js<|end_filename|> /** * The module responsible to handling Episerver specific state that is relevant * when editing content in edit mode. */ // mutation for the epiContext module export const UPDATE_CONTEXT = 'epiContext/UPDATE_CONTEXT'; const state = { inEditMode: false, isEditable: false }; const mutations = { [UPDATE_CONTEXT](state, newContext) { state.isEditable = newContext.isEditable; state.inEditMode = newContext.inEditMode; } }; export default { state, mutations }; <|start_filename|>src/MusicFestival.Vue.Template/Controllers/PreviewController.cs<|end_filename|> using System.Web.Mvc; using MusicFestival.Template.Models.Preview; using EPiServer.Core; using EPiServer.Framework.DataAnnotations; using EPiServer.Framework.Web; using EPiServer.Framework.Web.Mvc; using EPiServer.Web; using EPiServer.Web.Mvc; using EPiServer; namespace MusicFestival.Template.Controllers { [TemplateDescriptor(Inherited = true, TemplateTypeCategory = TemplateTypeCategories.MvcController, Tags = new[] { RenderingTags.Preview, RenderingTags.Edit }, AvailableWithoutTag = false)] [RequireClientResources] public class PreviewController : ActionControllerBase, IRenderTemplate<BlockData> { private readonly IContentRepository _contentRepository; public PreviewController(IContentRepository contentRepository) { _contentRepository = contentRepository; } public ActionResult Index(IContent currentContent) { var startPage = _contentRepository.Get<PageData>(ContentReference.StartPage); var model = new BlockEditPageViewModel(startPage, currentContent); return View(model); } } } <|start_filename|>src/MusicFestival.Vue.Template/Models/Preview/PreviewBlock.cs<|end_filename|> using EPiServer.Core; namespace MusicFestival.Template.Models.Preview { public class PreviewBlock : PageData { public IContent PreviewContent { get; } public PreviewBlock(PageData currentPage, IContent previewContent) : base(currentPage) { PreviewContent = previewContent; } } } <|start_filename|>src/MusicFestival.Vue.Template/Global.asax.cs<|end_filename|> using System.Web.Mvc; using System.Web.Routing; namespace MusicFestival.Template { public class EPiServerApplication : EPiServer.Global { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); } protected override void RegisterRoutes(RouteCollection routes) { base.RegisterRoutes(routes); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { action = "Index", id = UrlParameter.Optional }); } } } <|start_filename|>src/MusicFestival.Vue.Template/Assets/Scripts/router.js<|end_filename|> /** * Sets up the router that is used in View mode. When the site is loaded in * CMS editing mode, the whole page is always reloaded and the router only gets * the current page. The router will not be used for navigating between pages. */ import Vue from 'vue'; import Router from 'vue-router'; import store from '@/Scripts/store'; import { UPDATE_MODEL_BY_URL } from '@/Scripts/store/modules/epiDataModel'; import PageComponentSelector from '@/Scripts/components/PageComponentSelector.vue'; Vue.use(Router); const router = new Router({ // Use the HTML HistoryAPI so the # isn't needed in the URL, and // Vue routing will work even when going directly to a URL. mode: 'history', routes: [ { path: '*', component: PageComponentSelector } ] }); router.beforeEach((to, from, next) => { // URL is updated by vue-route-sync, and when time travelling with the // debugger we don't want to trigger a model commit as the model is already // part of the store holding the url update. if (store.state.epiDataModel.model.url !== to.fullPath) { store.dispatch(UPDATE_MODEL_BY_URL, to.fullPath); } next(); }); export default router; <|start_filename|>src/MusicFestival.Vue.Template/Models/Pages/ArtistContainerPage.cs<|end_filename|> using MusicFestival.Template.Models; using MusicFestival.Template.Models.Pages; using EPiServer.DataAbstraction; using EPiServer.DataAnnotations; namespace MusicFestival.Template.Content.Pages { /// <summary> /// Model for Assets/Scripts/components/pages/ArtistContainerPage.vue /// </summary> [ContentType(DisplayName = "Artist Container Page", GUID = "0a5b7b88-d0ec-4a2a-83d4-13a66d6d581d", Description = "Container page for artists")] [SiteImageUrl] [AvailableContentTypes(Availability.Specific, Include = new[] { typeof(ArtistDetailsPage) })] public class ArtistContainerPage : BasePage { } } <|start_filename|>src/MusicFestival.Vue.Template/Assets/Scripts/store/modules/epiDataModel.js<|end_filename|> /** * The module that is responsible for handling the state of the current content * that is being either viewed or edited. This module will handle talking to * the API when the model needs to be updated when navigating or editing the * site. */ import api from '@/Scripts/api/api'; //actions for the epiDataModel module export const UPDATE_MODEL_BY_URL = 'epiDataModel/UPDATE_MODEL_BY_URL'; export const UPDATE_MODEL_BY_CONTENT_LINK = 'epiDataModel/UPDATE_MODEL_BY_CONTENT_LINK'; const state = { model: {}, modelLoaded: false }; const UPDATE_MODEL = 'epiDataModel/UPDATE_MODEL'; const mutations = { [UPDATE_MODEL](state, newModel) { state.model = newModel; state.modelLoaded = true; }, }; const parameters = { expand: '*' }; const actions = { [UPDATE_MODEL_BY_URL]({commit}, friendlyUrl) { /** * When updating a model by friendly URL we assume that the friendly URL * contains every querystring parameter that we might need on the server. */ return api.getContentByFriendlyUrl(friendlyUrl, parameters).then(response => { commit(UPDATE_MODEL, response.data); }); }, [UPDATE_MODEL_BY_CONTENT_LINK]({commit, rootState}, contentLink) { /** * Updating a model by content link is done when something is being * edited and when viewing a block. In order to be sure that we get the * correct model, we need to keep any previously existing query string * from the friendly URL. * * See the implementation of ExtendedContentModelMapper.GetContextMode * for additional details. */ const params = Object.assign({}, parameters, rootState.route.query ); return api.getContentByContentLink(contentLink, params).then(response => { commit(UPDATE_MODEL, response.data); }); } }; export default { state, mutations, actions }; <|start_filename|>src/MusicFestival.Vue.Template/Assets/Scripts/api/getComponentTypeForContent.js<|end_filename|> /** * Will check the content's content type against the inheritance chain list in * components. * * Used to get the Vue component matching the loaded content's type by * `BlockComponentSelector` and `PageComponentSelector`. * * @param {*} content The content object that has a contentType property, which * holds the inheritance chain from the C# models for the content with the last * item being the actual implementation. * @param {Array} components The list of registered Vue components. * @returns The matching content type, or `null`. */ export default function getComponentTypeForContent(content, components) { // Here we will try to find a component that matches the content type name. for (let i = (content.contentType.length - 1); i >= 0; i--) { if (components[content.contentType[i]]) { return content.contentType[i]; } } return null; } <|start_filename|>src/MusicFestival.Vue.Template/Views/Shared/_BaseLayout.cshtml<|end_filename|> @using EPiServer.Editor @using EPiServer.Framework.Web.Mvc.Html <!DOCTYPE html> <html [email protected]("~")> <head> <meta name="viewport" content="width=device-width" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <link rel="shortcut icon" href="~/favicon.ico" type="image/x-icon"> <link href="~/Assets/bundled/main.bundle.css" rel="stylesheet" /> </head> <body> <div class="Page" id="App"> @RenderBody() </div> @Html.RenderEPiServerQuickNavigator() <script src="~/Assets/bundled/main.bundle.js"></script> @Html.RequiredClientResources("Footer") </body> </html> <|start_filename|>src/MusicFestival.Vue.Template/Models/Media/ImageFile.cs<|end_filename|> using EPiServer.Core; using EPiServer.DataAnnotations; using EPiServer.Framework.DataAnnotations; namespace MusicFestival.Template.Models.Media { /// <summary> /// Model for Assets/Scripts/components/media/ImageFile.vue /// </summary> [ContentType(DisplayName = "Image File", GUID = "a736bc13-d17c-46e2-ad5d-e37bd3af086b", AvailableInEditMode = false)] [MediaDescriptor(ExtensionString = "jpg,jpeg,jpe,ico,gif,bmp,png")] public class ImageFile : ImageData { } } <|start_filename|>src/MusicFestival.Vue.Template/Infrastructure/BuyTicketBlockPropertyModelConverter.cs<|end_filename|> using System.Collections.Generic; using System.Globalization; using MusicFestival.Template.Models.Blocks; using EPiServer.Core; using EPiServer.DataAbstraction; using EPiServer.SpecializedProperties; using EPiServer.ContentApi.Core.Serialization; using EPiServer.ContentApi.Core.Serialization.Models; namespace MusicFestival.Template.Infrastructure { /// <summary> /// Used to support conversion of <see cref="MusicFestival.Template.Infrastructure.BuyTicketBlockPropertyModel"/> /// which is returned from API as a property of LandingPage /// </summary> public class BuyTicketBlockPropertyModelConverter: IPropertyModelConverter { /// <summary> /// Verifies that the instance of <see cref="IPropertyModelConverter"/> has the correct <see cref="IPropertyModel"/> registered for the provided PropertyData type. /// </summary> /// <param name="propertyData">An instance of PropertyData to check</param> /// <returns></returns> public bool HasPropertyModelAssociatedWith(PropertyData propertyData) { var blockPropertyData = propertyData as PropertyBlock; if (!(blockPropertyData?.Value is BuyTicketBlock)) { return false; } return true; } /// <summary> /// Converts an instance of <see cref="PropertyData"/> into a specific Property Model /// </summary> /// <param name="propertyData">An instance of PropertyData</param> public IPropertyModel ConvertToPropertyModel(PropertyData propertyData, CultureInfo language, bool excludePersonalizedContent, bool expand) { return new BuyTicketBlockPropertyModel((PropertyBlock) propertyData); } public int SortOrder => 1000; public IEnumerable<TypeModel> ModelTypes => new List<TypeModel> { new TypeModel() { ModelType = typeof(BlockPropertyDefinitionType), ModelTypeString = nameof(BlockPropertyDefinitionType), PropertyType = typeof(BuyTicketBlock) } }; } } <|start_filename|>src/MusicFestival.Vue.Template/Models/Blocks/ContentBlock.cs<|end_filename|> using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using EPiServer; using EPiServer.Core; using EPiServer.DataAbstraction; using EPiServer.DataAnnotations; using EPiServer.Shell.ObjectEditing; using EPiServer.Web; namespace MusicFestival.Template.Models.Blocks { /// <summary> /// Model for Assets/Scripts/components/blocks/ContentBlock.vue /// </summary> [ContentType(DisplayName = "Content Block", GUID = "ed70e2a6-1d80-4a51-9aa7-bb91609ccf1b", Description = "Generic content block with text and image")] [SiteImageUrl] public class ContentBlock : BlockData { [CultureSpecific] [Display( Name = "Title", GroupName = SystemTabNames.Content, Order = 10)] public virtual string Title { get; set; } [Display( Name = "Image", GroupName = SystemTabNames.Content, Order = 10)] [UIHint(UIHint.Image)] public virtual Url Image { get; set; } [Display( Name = "Image Alignment", GroupName = SystemTabNames.Content, Order = 10)] [SelectOne(SelectionFactoryType = typeof(ImageAlignmentSelectionFactory))] [Required] public virtual string ImageAlignment { get; set; } [CultureSpecific] [Display( Name = "Content", GroupName = SystemTabNames.Content, Order = 10)] public virtual XhtmlString Content { get; set; } } public class ImageAlignmentSelectionFactory : ISelectionFactory { public IEnumerable<ISelectItem> GetSelections(ExtendedMetadata metadata) { return new ISelectItem[] { new SelectItem() { Text = "Left", Value = "Left" }, new SelectItem() { Text = "Right", Value = "Right" } }; } } } <|start_filename|>src/MusicFestival.Vue.Template/Models/Pages/BasePage.cs<|end_filename|> using EPiServer.Core; namespace MusicFestival.Template.Models.Pages { public abstract class BasePage : PageData { } } <|start_filename|>build/automation/ProvisionDatabase_MVC.cs<|end_filename|> using EPiServer.Cms.Shell; using EPiServer.Cms.UI.AspNetIdentity; using EPiServer.Core; using EPiServer.DataAbstraction; using EPiServer.Framework; using EPiServer.Framework.Initialization; using EPiServer.Personalization; using EPiServer.Security; using EPiServer.ServiceLocation; using EPiServer.Shell.Security; using Microsoft.AspNet.Identity.EntityFramework; using System.Collections; using System.Collections.Generic; using System.Web.Security; namespace MusicFestival.App_Code { /// <summary> /// Provision the database for easier development by: /// * Adding some default users /// /// This file is preferably deployed in the App_Code folder, where it will be picked up and executed automatically. /// </summary> [InitializableModule] [ModuleDependency(typeof(EPiServer.Web.InitializationModule))] public class ProvisionDatabase : IInitializableModule { UIUserProvider _userProvider; UIRoleProvider _roleProvider; public void Initialize(InitializationEngine context) { // Assume that everything is setup if the WebAdmins role has been created if (UIRoleProvider.RoleExists("WebAdmins")) { return; } AddUsersAndRoles(context.Locate.Advanced.GetInstance<IContentSecurityRepository>()); } public void Uninitialize(InitializationEngine context) { } #region Users and Roles private void AddUsersAndRoles(IContentSecurityRepository securityRepository) { var password = "<PASSWORD>"; AddRole("WebAdmins", AccessLevel.FullAccess, securityRepository); AddRole("WebEditors", AccessLevel.FullAccess ^ AccessLevel.Administer, securityRepository); AddUser("cmsadmin", "Administrator Administrator", password, new[] { "WebEditors", "WebAdmins" }); AddUser("alfred", "<NAME>", password, new[] { "WebEditors", "WebAdmins" }); AddUser("emil", "<NAME>", password, new[] { "WebEditors" }); AddUser("ida", "<NAME>", password, new[] { "WebEditors" }); AddUser("lina", "<NAME>", password, new[] { "WebEditors" }); } private void AddUser(string userName, string fullName, string passWord, string[] roleNames) { if (UIUserProvider.GetUser(userName) == null) { var email = string.Format("<EMAIL>", userName); IEnumerable<string> erros; UIUserCreateStatus status; var user = UIUserProvider.CreateUser(userName, passWord, email, null, null, true, out status, out erros); UIRoleProvider.AddUserToRoles(user.Username, roleNames); var profile = EPiServerProfile.Get(user.Username); var nameParts = fullName.Split(' '); profile["FirstName"] = nameParts[0]; profile["LastName"] = nameParts[1]; // E-mail must be part of profile properties to be resolved by QueryableNotificationUsersImpl profile["Email"] = email; profile.Save(); } } private void AddRole(string roleName, AccessLevel accessLevel, IContentSecurityRepository securityRepository) { if (!UIRoleProvider.RoleExists(roleName)) { UIRoleProvider.CreateRole(roleName); var permissions = (IContentSecurityDescriptor)securityRepository.Get(ContentReference.RootPage).CreateWritableClone(); permissions.AddEntry(new AccessControlEntry(roleName, accessLevel)); securityRepository.Save(ContentReference.RootPage, permissions, SecuritySaveType.Replace); securityRepository.Save(ContentReference.WasteBasket, permissions, SecuritySaveType.Replace); } } public UIUserProvider GetDefaultUserProvider() { UIUserProvider userProvider = null; try { // Owin is not configured that becuase we have catch (membership provider there is not problem) ServiceLocator.Current.TryGetExistingInstance<UIUserProvider>(out userProvider); return userProvider; } catch { } // in the case of aspnet identity the rpovider is not in the service locator before owin is sets up then we create own. var userManager = new ApplicationUserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext<ApplicationUser>("EPiServerDB"))); userProvider = new ApplicationUserProvider<ApplicationUser>(() => userManager); return userProvider; } public UIRoleProvider GetDefaultRoleProvider() { UIRoleProvider roleProvider = null; try { // Owin is not configured that becuase we have catch (membership provider there is not problem) ServiceLocator.Current.TryGetExistingInstance<UIRoleProvider>(out roleProvider); return roleProvider; } catch { } // in the case of aspnet identity the rpovider is not in the service locator before owin is sets up then we create own. var userManager = new ApplicationUserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext<ApplicationUser>("EPiServerDB"))); var roleManager = new ApplicationRoleManager<ApplicationUser>(new RoleStore<IdentityRole>(new ApplicationDbContext<ApplicationUser>("EPiServerDB"))); roleProvider = new ApplicationRoleProvider<ApplicationUser>(() => userManager, () => roleManager); return roleProvider; } UIUserProvider UIUserProvider { get { return _userProvider ?? (_userProvider = GetDefaultUserProvider()); } } UIRoleProvider UIRoleProvider { get { return _roleProvider ?? (_roleProvider = GetDefaultRoleProvider()); } } #endregion } } <|start_filename|>src/MusicFestival.Vue.Template/Models/Pages/LandingPage.cs<|end_filename|> using System.ComponentModel.DataAnnotations; using MusicFestival.Template.Models.Blocks; using MusicFestival.Template.Content.Pages; using EPiServer.Core; using EPiServer.DataAbstraction; using EPiServer.DataAnnotations; using EPiServer.Web; using EPiServer; using MusicFestival.Template.Models.Media; namespace MusicFestival.Template.Models.Pages { /// <summary> /// Model for Assets/Scripts/components/pages/LandingPage.vue /// </summary> [ContentType(DisplayName = "Landing Page", GUID = "46278700-3173-4945-b143-befe071f0f71", Description = "Starting page for the site")] [SiteImageUrl] [AvailableContentTypes(Availability.Specific, Include = new [] { typeof(ArtistContainerPage) })] public class LandingPage : BasePage { [Display( Name = "Buy Ticket", GroupName = SystemTabNames.Content, Order = 5)] public virtual BuyTicketBlock BuyTicketBlock { get; set; } [CultureSpecific] [Display( Name = "Hero Image", GroupName = SystemTabNames.Content, Order = 10)] [UIHint(UIHint.Image)] public virtual Url HeroImage { get; set; } [CultureSpecific] [Display( Name = "Title", GroupName = SystemTabNames.Content, Order = 20)] public virtual string Title { get; set; } [CultureSpecific] [Display( Name = "Subtitle", GroupName = SystemTabNames.Content, Order = 30)] public virtual string Subtitle { get; set; } [Required] [Display( Name = "Link to Artists list", GroupName = SystemTabNames.Content, Order = 35)] public virtual PageReference ArtistsLink { get; set; } [CultureSpecific] [Display( Name = "Main Content Area", GroupName = SystemTabNames.Content, Order = 40)] [AllowedTypes(typeof(ContentBlock), typeof(ImageFile))] public virtual ContentArea MainContentArea { get; set; } [CultureSpecific] [Display( Name = "Footer Content Area", GroupName = SystemTabNames.Content, Order = 50)] [AllowedTypes(typeof(ContentBlock), typeof(ImageFile))] public virtual ContentArea FooterContentArea { get; set; } } }
vatchi/Episerver-vue-template
<|start_filename|>app/src/main/java/me/grishka/videotranscoder/QualcommFormatConverter.java<|end_filename|> package me.grishka.videotranscoder; /** * Created by grishka on 20.01.15. * Ported to Java from https://github.com/videolan/vlc/blob/master/modules/codec/omxil/qcom.c */ public class QualcommFormatConverter { /* * The format is called QOMX_COLOR_FormatYUV420PackedSemiPlanar64x32Tile2m8ka. * First wtf: why call it YUV420? It is NV12 (interleaved U&V). * Second wtf: why this format at all? */ private static final int TILE_WIDTH=64; private static final int TILE_HEIGHT=32; private static final int TILE_SIZE=(TILE_WIDTH * TILE_HEIGHT); private static final int TILE_GROUP_SIZE=(4 * TILE_SIZE); /* get frame tile coordinate. XXX: nothing to be understood here, don't try. */ private static int tile_pos(int x, int y, int w, int h) { int flim = x + (y & ~1) * w; if ((y & 1)>0) { flim += (x & ~3) + 2; } else if ((h & 1) == 0 || y != (h - 1)) { flim += (x + 2) & ~3; } if(flim<0) flim&=Integer.MAX_VALUE; return flim; } public static void qcom_convert(final byte[] src, byte[] pic, final int width, final int _height) { int pitch = width; int height=_height; final int tile_w = (width - 1) / TILE_WIDTH + 1; final int tile_w_align = (tile_w + 1) & ~1; final int tile_h_luma = (height - 1) / TILE_HEIGHT + 1; final int tile_h_chroma = (height / 2 - 1) / TILE_HEIGHT + 1; int luma_size = tile_w_align * tile_h_luma * TILE_SIZE; if((luma_size % TILE_GROUP_SIZE) != 0) luma_size = (((luma_size - 1) / TILE_GROUP_SIZE) + 1) * TILE_GROUP_SIZE; for(int y = 0; y < tile_h_luma; y++) { int row_width = width; for(int x = 0; x < tile_w; x++) { /* luma source pointer for this tile */ // const uint8_t *src_luma = src // + tile_pos(x, y,tile_w_align, tile_h_luma) * TILE_SIZE; int src_luma=tile_pos(x, y,tile_w_align, tile_h_luma) * TILE_SIZE; /* chroma source pointer for this tile */ // const uint8_t *src_chroma = src + luma_size // + tile_pos(x, y/2, tile_w_align, tile_h_chroma) * TILE_SIZE; int src_chroma=luma_size+tile_pos(x, y/2, tile_w_align, tile_h_chroma) * TILE_SIZE; if ((y & 1)>0) src_chroma += TILE_SIZE/2; /* account for right columns */ int tile_width = row_width; if (tile_width > TILE_WIDTH) tile_width = TILE_WIDTH; /* account for bottom rows */ int tile_height = height; if (tile_height > TILE_HEIGHT) tile_height = TILE_HEIGHT; /* dest luma memory index for this tile */ int luma_idx = y * TILE_HEIGHT * pitch + x * TILE_WIDTH; /* dest chroma memory index for this tile */ /* XXX: remove divisions */ int chroma_idx = (luma_idx / pitch) * pitch/2 + (luma_idx % pitch); tile_height /= 2; // we copy 2 luma lines at once while (tile_height-- > 0) { //memcpy(&pic->p[0].p_pixels[luma_idx], src_luma, tile_width); System.arraycopy(src, src_luma, pic, luma_idx, tile_width); src_luma += TILE_WIDTH; luma_idx += pitch; //memcpy(&pic->p[0].p_pixels[luma_idx], src_luma, tile_width); System.arraycopy(src, src_luma, pic, luma_idx, tile_width); src_luma += TILE_WIDTH; luma_idx += pitch; //memcpy(&pic->p[1].p_pixels[chroma_idx], src_chroma, tile_width); System.arraycopy(src, src_chroma, pic, chroma_idx+(width*_height), tile_width); src_chroma += TILE_WIDTH; chroma_idx += pitch; } row_width -= TILE_WIDTH; } height -= TILE_HEIGHT; } } } <|start_filename|>app/src/main/java/me/grishka/videotranscoder/VideoConverter.java<|end_filename|> package me.grishka.videotranscoder; import android.app.Activity; import android.content.Context; import android.media.MediaCodec; import android.media.MediaCodecInfo; import android.media.MediaExtractor; import android.media.MediaFormat; import android.media.MediaMetadataRetriever; import android.media.MediaMuxer; import android.net.Uri; import android.opengl.GLSurfaceView; import android.util.Log; import android.widget.FrameLayout; import java.io.File; import java.io.FileOutputStream; import java.nio.ByteBuffer; import java.util.ArrayList; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.opengles.GL10; /** * Created by grishka on 21.01.15. */ public class VideoConverter { private static final String TAG="videoconverter"; private ArrayList<PendingSample> pendingSamples=new ArrayList<>(); private String srcFile, dstFile; private int videoBitrate, audioBitrate, videoSize; private boolean canceled, running; private Callback callback; private boolean isQualcomm; private Context context; public VideoConverter(String srcFile, String dstFile, int videoBitrate, int audioBitrate, int videoSize, Callback callback, final Activity act){ this.srcFile=srcFile; this.dstFile=dstFile; this.videoBitrate=videoBitrate; this.audioBitrate=audioBitrate; this.videoSize=videoSize; this.callback=callback; context=act; if(this.srcFile.startsWith("/")) this.srcFile="file://"+this.srcFile; //if(Build.VERSION.SDK_INT<Build.VERSION_CODES.LOLLIPOP) { final GLSurfaceView gsv = new GLSurfaceView(act); gsv.setRenderer(new GLSurfaceView.Renderer() { @Override public void onSurfaceCreated(GL10 gl, EGLConfig config) { isQualcomm = "Qualcomm".equals(gl.glGetString(GL10.GL_VENDOR)); act.runOnUiThread(new Runnable() { @Override public void run() { ((FrameLayout) act.getWindow().getDecorView()).removeView(gsv); } }); VideoConverter.this.callback.onReady(); } @Override public void onSurfaceChanged(GL10 gl, int width, int height) { } @Override public void onDrawFrame(GL10 gl) { } }); ((FrameLayout) act.getWindow().getDecorView()).addView(gsv); /*}else{ act.getWindow().getDecorView().post(new Runnable() { @Override public void run() { VideoConverter.this.callback.onReady(); } }); }*/ } public void start(){ if(running) return; new Thread(new ConverterRunnable()).start(); } public void cancel(){ canceled=true; } private class ConverterRunnable implements Runnable{ @Override public void run() { running=true; try { MediaMetadataRetriever mmr=new MediaMetadataRetriever(); mmr.setDataSource(context, Uri.parse(srcFile)); int rotation=Integer.parseInt(mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_ROTATION)); mmr.release(); MediaExtractor extractor = new MediaExtractor(); extractor.setDataSource(context, Uri.parse(srcFile), null); new File(dstFile).delete(); MediaMuxer muxer=new MediaMuxer(dstFile, MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4); muxer.setOrientationHint(rotation); int numTracks=extractor.getTrackCount(); int audioTrack=-1, videoTrack=-1; for(int i=0;i<numTracks;i++){ MediaFormat f=extractor.getTrackFormat(i); Log.i(TAG, "Track " + i + " = " + f); if(f.getString(MediaFormat.KEY_MIME).startsWith("video/")){ if(videoTrack==-1){ Log.i(TAG, "Selected video track "+i); videoTrack=i; //extractor.selectTrack(i); } }else if(f.getString(MediaFormat.KEY_MIME).startsWith("audio/")){ if(audioTrack==-1){ Log.i(TAG, "Selected audio track "+i); audioTrack=i; //extractor.selectTrack(i); } } } if(audioTrack==-1 || videoTrack==-1){ Log.e(TAG, "Some tracks are missing"); callback.onConversionFailed("File should contain both audio and video"); extractor.release(); return; } // detect FPS float fps=0; long lastFramePTS=-1; extractor.selectTrack(videoTrack); for(int i=0;i<100;i++){ fps++; if(extractor.getSampleTime()>1000000) break; lastFramePTS=extractor.getSampleTime(); extractor.advance(); } fps*=(lastFramePTS/1000000f); fps=Math.round(fps); Log.i(TAG, "Detected FPS is "+fps); extractor.seekTo(0, MediaExtractor.SEEK_TO_CLOSEST_SYNC); extractor.selectTrack(audioTrack); MediaFormat audioFormat=extractor.getTrackFormat(audioTrack); MediaFormat videoFormat=extractor.getTrackFormat(videoTrack); int videoW=videoFormat.getInteger(MediaFormat.KEY_WIDTH); int videoH=videoFormat.getInteger(MediaFormat.KEY_HEIGHT); int maxSize=Math.max(videoW, videoH); int sampleSize=Math.round(maxSize/videoSize); long lastTS=0; int yuvDataSize=videoW*videoH*2; int resizedYuvDataSize=(videoW/sampleSize)*(videoH/sampleSize)*2; MediaCodec audioDecoder=MediaCodec.createDecoderByType(audioFormat.getString(MediaFormat.KEY_MIME)); audioDecoder.configure(audioFormat, null, null, 0); MediaCodec videoDecoder=MediaCodec.createDecoderByType(videoFormat.getString(MediaFormat.KEY_MIME)); videoDecoder.configure(videoFormat, null, null, 0); MediaCodecInfo vInfo=videoDecoder.getCodecInfo(); MediaCodecInfo.CodecCapabilities caps=vInfo.getCapabilitiesForType(videoFormat.getString(MediaFormat.KEY_MIME)); MediaCodec audioEncoder=MediaCodec.createEncoderByType("audio/mp4a-latm"); MediaFormat audioEncFormat=MediaFormat.createAudioFormat("audio/mp4a-latm", audioFormat.getInteger(MediaFormat.KEY_SAMPLE_RATE), audioFormat.getInteger(MediaFormat.KEY_CHANNEL_COUNT)); audioEncFormat.setInteger(MediaFormat.KEY_BIT_RATE, audioBitrate*1024); audioEncoder.configure(audioEncFormat, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE); MediaCodec videoEncoder=MediaCodec.createEncoderByType("video/avc"); MediaFormat videoEncFormat=MediaFormat.createVideoFormat("video/avc", videoW/sampleSize, videoH/sampleSize); videoEncFormat.setInteger(MediaFormat.KEY_BIT_RATE, videoBitrate*1024); videoEncFormat.setInteger(MediaFormat.KEY_COLOR_FORMAT, MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420SemiPlanar); videoEncFormat.setFloat(MediaFormat.KEY_FRAME_RATE, fps); videoEncFormat.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, 5); videoEncoder.configure(videoEncFormat, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE); videoEncoder.start(); ByteBuffer[] videoEncIn=videoEncoder.getInputBuffers(); ByteBuffer[] videoEncOut=videoEncoder.getOutputBuffers(); audioEncoder.start(); ByteBuffer[] audioEncIn=audioEncoder.getInputBuffers(); ByteBuffer[] audioEncOut=audioEncoder.getOutputBuffers(); videoDecoder.start(); ByteBuffer[] videoIn=videoDecoder.getInputBuffers(); ByteBuffer[] videoOut=videoDecoder.getOutputBuffers(); audioDecoder.start(); ByteBuffer[] audioIn=audioDecoder.getInputBuffers(); ByteBuffer[] audioOut=audioDecoder.getOutputBuffers(); int outAudioTrack=-1; int outVideoTrack=-1; boolean muxerRunning=false; lastFramePTS=-1; MediaCodec.BufferInfo info=new MediaCodec.BufferInfo(); ByteBuffer buffer=ByteBuffer.allocate(videoW*videoH*3); byte[] buf=new byte[videoW*videoH*3]; byte[] frameBuffer=new byte[videoW*videoH*3]; int read=0; long pts=-1; do{ read = extractor.readSampleData(buffer, 0); int track=extractor.getSampleTrackIndex(); long time=extractor.getSampleTime(); //if(time>30000000) break; if((time/1000000)!=pts) { //Log.d(TAG, "Track: " + (track == audioTrack ? "audio" : "video") + ", read " + read + ", time " +(time/1000000)); callback.onProgressUpdated((int)(time/1000), (int)(videoFormat.getLong(MediaFormat.KEY_DURATION)/1000)); pts=(time/1000000); } //buffer.position(0); if(track==audioTrack){ int inIndex = audioDecoder.dequeueInputBuffer(1000); if(inIndex>=0) { buffer.position(0); buffer.get(buf, 0, read); audioIn[inIndex].position(0); audioIn[inIndex].put(buf, 0, read); audioDecoder.queueInputBuffer(inIndex, 0, read, extractor.getSampleTime(), extractor.getSampleFlags()); } int outIndex = audioDecoder.dequeueOutputBuffer(info, 1000); if (outIndex >= 0) { //Log.v(TAG, "decoded audio " + info.size+", off "+info.offset); audioOut[outIndex].position(info.offset); audioOut[outIndex].get(buf, 0, info.size); //outAudio.write(buf, 0, info.size); audioDecoder.releaseOutputBuffer(outIndex, false); inIndex=audioEncoder.dequeueInputBuffer(-1); if(inIndex>=0){ audioEncIn[inIndex].position(0); audioEncIn[inIndex].put(buf, 0, info.size); audioEncoder.queueInputBuffer(inIndex, 0, info.size, info.presentationTimeUs, 0); }else{ throw new Exception("What dafuq"); } }else if (outIndex == MediaCodec.INFO_OUTPUT_BUFFERS_CHANGED) { audioOut = audioDecoder.getOutputBuffers(); } }else if(track==videoTrack){ int inIndex = videoDecoder.dequeueInputBuffer(1000); if(inIndex>=0) { buffer.position(0); buffer.get(buf, 0, read); videoIn[inIndex].position(0); videoIn[inIndex].put(buf, 0, read); videoDecoder.queueInputBuffer(inIndex, 0, read, extractor.getSampleTime(), extractor.getSampleFlags()); } int outIndex = videoDecoder.dequeueOutputBuffer(info, 1000); if (outIndex >= 0) { //Log.v(TAG, "decoded video " + info.size+", off "+info.offset); videoOut[outIndex].position(info.offset); videoOut[outIndex].get(buf, 0, info.size); //outAudio.write(buf, 0, info.size); videoDecoder.releaseOutputBuffer(outIndex, false); if(isQualcomm) QualcommFormatConverter.qcom_convert(buf, frameBuffer, videoW, videoH); else System.arraycopy(buf, 0, frameBuffer, 0, buf.length); resizeYuvFrame(frameBuffer, buf, videoW, videoH, sampleSize); inIndex = videoEncoder.dequeueInputBuffer(-1); if (inIndex >= 0) { videoEncIn[inIndex].position(0); int canWrite = Math.min(resizedYuvDataSize, videoEncIn[inIndex].remaining()); videoEncIn[inIndex].put(buf, 0, canWrite); videoEncoder.queueInputBuffer(inIndex, 0, canWrite, info.presentationTimeUs, 0); } else { throw new Exception("What dafuq"); } }else if (outIndex == MediaCodec.INFO_OUTPUT_BUFFERS_CHANGED) { videoOut = videoDecoder.getOutputBuffers(); } } int outIndex = audioEncoder.dequeueOutputBuffer(info, 100); if (outIndex >= 0) { //Log.v(TAG, "encoded audio " + info.size+", off "+info.offset); audioEncOut[outIndex].position(info.offset); if(outAudioTrack!=-1 && outVideoTrack!=-1) { if(pendingSamples.size()>0){ while(pendingSamples.size()>0 && pendingSamples.get(0).ptime<info.presentationTimeUs){ pendingSamples.get(0).writeToMuxer(muxer, outVideoTrack, outAudioTrack); pendingSamples.remove(0); Log.i(TAG, "Remaining pending samples: "+pendingSamples.size()); } } if(info.presentationTimeUs>=lastFramePTS) muxer.writeSampleData(outAudioTrack, audioEncOut[outIndex], info); else Log.w(TAG, "Dropped audio frame with wrong timestamp! "+info.presentationTimeUs); lastFramePTS=info.presentationTimeUs; }else{ PendingSample ps=new PendingSample(); ps.data=new byte[info.size]; ps.flags=info.flags; ps.ptime=info.presentationTimeUs; ps.track=1; audioEncOut[outIndex].get(ps.data, 0, info.size); pendingSamples.add(ps); } //audioEncOut[outIndex].position(info.offset); //audioEncOut[outIndex].get(buf, 0, info.size); //outAudio.write(buf, 0, info.size); audioEncoder.releaseOutputBuffer(outIndex, false); }else if (outIndex == MediaCodec.INFO_OUTPUT_BUFFERS_CHANGED) { audioEncOut = audioEncoder.getOutputBuffers(); }else if(outIndex==MediaCodec.INFO_OUTPUT_FORMAT_CHANGED){ Log.e(TAG, "!!!! AUDIO OUT FORMAT CHANGED "+audioEncoder.getOutputFormat()); if(outAudioTrack==-1){ outAudioTrack=muxer.addTrack(audioEncoder.getOutputFormat()); } } outIndex = videoEncoder.dequeueOutputBuffer(info, 100); if (outIndex >= 0) { //Log.v(TAG, "encoded video " + info.size+", off "+info.offset); if(outVideoTrack!=-1 && outAudioTrack!=-1) { if(pendingSamples.size()>0){ while(pendingSamples.size()>0 && pendingSamples.get(0).ptime<info.presentationTimeUs){ pendingSamples.get(0).writeToMuxer(muxer, outVideoTrack, outAudioTrack); pendingSamples.remove(0); Log.i(TAG, "Remaining pending samples: "+pendingSamples.size()); } } //if(info.presentationTimeUs>=lastFramePTS) muxer.writeSampleData(outVideoTrack, videoEncOut[outIndex], info); //else // Log.w(TAG, "Dropped video frame with wrong timestamp!"); //lastFramePTS=info.presentationTimeUs; }else{ PendingSample ps=new PendingSample(); ps.data=new byte[info.size]; ps.flags=info.flags; ps.ptime=info.presentationTimeUs; ps.track=2; videoEncOut[outIndex].get(ps.data, 0, info.size); pendingSamples.add(ps); } //audioEncOut[outIndex].position(info.offset); //audioEncOut[outIndex].get(buf, 0, info.size); //outAudio.write(buf, 0, info.size); videoEncoder.releaseOutputBuffer(outIndex, false); }else if (outIndex == MediaCodec.INFO_OUTPUT_BUFFERS_CHANGED) { videoEncOut = audioEncoder.getOutputBuffers(); }else if(outIndex==MediaCodec.INFO_OUTPUT_FORMAT_CHANGED){ Log.e(TAG, "!!!! VIDEO OUT FORMAT CHANGED "+videoEncoder.getOutputFormat()); if(outVideoTrack==-1){ outVideoTrack=muxer.addTrack(videoEncoder.getOutputFormat()); } } if(outVideoTrack!=-1 && outAudioTrack!=-1 && !muxerRunning){ muxerRunning=true; muxer.start(); /*Log.i(TAG, "Adding "+pendingSamples.size()+" pending samples..."); for(PendingSample ps:pendingSamples){ Log.v(TAG, "Sample time = "+ps.ptime+", size="+ps.data.length); info.set(0, ps.data.length, ps.ptime, ps.flags); buffer.position(0); buffer.limit(buffer.capacity()); buffer.put(ps.data); muxer.writeSampleData(ps.track==1 ? outVideoTrack : outAudioTrack, buffer, info); } pendingSamples.clear();*/ } }while(extractor.advance() && !canceled); extractor.release(); audioDecoder.stop(); audioDecoder.release(); videoDecoder.stop(); videoDecoder.release(); audioEncoder.stop(); audioEncoder.release(); videoEncoder.stop(); videoEncoder.release(); muxer.stop(); muxer.release(); Log.i(TAG, "End of stream!"); if(canceled){ new File(dstFile).delete(); return; } callback.onConversionCompleted(); }catch(Exception x){ callback.onConversionFailed(x.getMessage()); Log.w(TAG, x); } running=false; } } public static interface Callback{ public void onProgressUpdated(int done, int total); public void onConversionCompleted(); public void onConversionFailed(String error); public void onReady(); } private static void resizeYuvFrame(byte[] from, byte[] to, int w, int h, int sample){ int tw=w/sample; int th=h/sample; // Y for(int y=0;y<th;y++){ for(int x=0;x<tw;x++){ to[y*tw+x]=from[y*sample*w+x*sample]; } } // UV int offset=tw*th; for(int y=0;y<th/2;y++){ for(int x=0;x<tw/2;x++){ int uIndex=y*sample*w+x*sample*2; to[offset]=from[w*h+uIndex]; // u to[offset+1]=from[w*h+uIndex+1]; // v offset+=2; } } } private static class PendingSample{ int flags; long ptime; byte[] data; int track; public void writeToMuxer(MediaMuxer muxer, int audioTrack, int videoTrack){ MediaCodec.BufferInfo info=new MediaCodec.BufferInfo(); info.set(0, data.length, ptime, flags); ByteBuffer buffer=ByteBuffer.wrap(data); muxer.writeSampleData(track==1 ? videoTrack : audioTrack, buffer, info); } } } <|start_filename|>app/src/main/java/me/grishka/videotranscoder/MainActivity.java<|end_filename|> package me.grishka.videotranscoder; import android.app.Activity; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.Intent; import android.media.MediaMetadataRetriever; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.SeekBar; import android.widget.TextView; import android.widget.Toast; import java.io.File; public class MainActivity extends Activity{ private VideoConverter videoConverter; private String chosenFile=null; private SeekBar videoBitrateSlider, audioBitrateSlider, scalingFactorSlider; private TextView videoBitrateValue, audioBitrateValue, scalingFactorValue; private SeekBar.OnSeekBarChangeListener seekBarListener=new SeekBar.OnSeekBarChangeListener(){ @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser){ switch(seekBar.getId()){ case R.id.video_bitrate_slider: videoBitrateValue.setText(progress+""); break; case R.id.audio_bitrate_slider: audioBitrateValue.setText(progress+""); break; case R.id.scaling_factor_slider: scalingFactorValue.setText((progress+1)+""); break; } } @Override public void onStartTrackingTouch(SeekBar seekBar){ } @Override public void onStopTrackingTouch(SeekBar seekBar){ } }; private static final int PICK_RESULT=101; @Override protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); findViewById(R.id.btn_pick).setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v){ Intent intent=new Intent(Intent.ACTION_PICK); intent.setType("video/*"); startActivityForResult(intent, PICK_RESULT); } }); findViewById(R.id.btn_start).setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v){ doConvert(chosenFile, ((TextView)findViewById(R.id.edit_output_file)).getText().toString()); } }); videoBitrateSlider=(SeekBar)findViewById(R.id.video_bitrate_slider); audioBitrateSlider=(SeekBar)findViewById(R.id.audio_bitrate_slider); scalingFactorSlider=(SeekBar)findViewById(R.id.scaling_factor_slider); videoBitrateValue=(TextView)findViewById(R.id.video_bitrate_value); audioBitrateValue=(TextView)findViewById(R.id.audio_bitrate_value); scalingFactorValue=(TextView)findViewById(R.id.scaling_factor_value); videoBitrateSlider.setOnSeekBarChangeListener(seekBarListener); audioBitrateSlider.setOnSeekBarChangeListener(seekBarListener); scalingFactorSlider.setOnSeekBarChangeListener(seekBarListener); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data){ if(requestCode==PICK_RESULT && resultCode==RESULT_OK){ chosenFile=data.getData().toString(); ((TextView)findViewById(R.id.file_name)).setText(chosenFile); findViewById(R.id.btn_start).setEnabled(true); } } private void doConvert(String fromFile, String toFile){ final ProgressDialog progress=new ProgressDialog(this); progress.setTitle("Compressing video"); progress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); progress.setCancelable(false); progress.setButton(ProgressDialog.BUTTON_POSITIVE, "Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { videoConverter.cancel(); progress.dismiss(); } }); progress.show(); VideoConverter.Callback callback=new VideoConverter.Callback() { @Override public void onProgressUpdated(final int done, final int total) { runOnUiThread(new Runnable() { @Override public void run() { progress.setMax(total); progress.setProgress(done); } }); } @Override public void onConversionCompleted() { runOnUiThread(new Runnable() { @Override public void run() { progress.dismiss(); videoConverter=null; Toast.makeText(MainActivity.this, "Done!", Toast.LENGTH_SHORT).show(); } }); } @Override public void onConversionFailed(final String error) { runOnUiThread(new Runnable() { @Override public void run() { progress.dismiss(); new AlertDialog.Builder(MainActivity.this) .setTitle("Error") .setMessage(error) .setPositiveButton("OK", null) .show(); } }); } @Override public void onReady() { videoConverter.start(); } }; int scalingFactor=scalingFactorSlider.getProgress()+1; MediaMetadataRetriever mmr=new MediaMetadataRetriever(); mmr.setDataSource(this, Uri.parse(fromFile)); int vw=Integer.parseInt(mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH)); int vh=Integer.parseInt(mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT)); mmr.release(); videoConverter=new VideoConverter(fromFile, toFile, videoBitrateSlider.getProgress(), audioBitrateSlider.getProgress(), Math.max(vw, vh)/scalingFactor, callback, this); } }
grishka/android-video-transcoder
<|start_filename|>node_modules/silly-datetime/package.json<|end_filename|> { "name": "silly-datetime", "version": "0.1.2", "description": "simple datetime formater", "main": "dest/index.js", "jsnext:main": "src/index.js", "scripts": { "prepublish": "node rollup.js", "test": "istanbul cover ./node_modules/mocha/bin/_mocha --report lcovonly -- -R spec && cat ./coverage/lcov.info | ./node_modules/coveralls/bin/coveralls.js && rm -rf ./coverage" }, "repository": { "type": "git", "url": "https://github.com/csbun/silly-datetime.git" }, "keywords": [ "datetime", "format" ], "author": "<NAME>", "license": "MIT", "bugs": { "url": "https://github.com/csbun/silly-datetime/issues" }, "homepage": "https://github.com/csbun/silly-datetime", "devDependencies": { "babel-preset-es2015-rollup": "^1.0.0", "coveralls": "^2.11.3", "istanbul": "^0.3.17", "mocha": "^2.2.5", "mocha-lcov-reporter": "0.0.2", "rollup": "^0.21.0", "rollup-plugin-babel": "^2.1.0" } }
shaodushu/snacksapi
<|start_filename|>app/reducers/settings.js<|end_filename|> const settings = (state = {}, action) => { switch (action.type) { case 'CLEAR_CURRENT_FILEID': return { ...state, currentFileId: undefined }; case 'SET_EMAIL_ADDRESS': return { ...state, emailAddress: action.emailAddress }; case 'SET_CURRENT_FILEID': return { ...state, currentFileId: action.fileId }; case 'SET_CURRENT_SHEETID': return { ...state, currentSheetId: action.currentSheetId }; case 'SET_DEFAULT_THUMB_COUNT': return { ...state, defaultThumbCount: action.defaultThumbCount }; case 'SET_DEFAULT_COLUMN_COUNT': return { ...state, defaultColumnCount: action.defaultColumnCount }; case 'SET_DEFAULT_THUMBNAIL_SCALE': return { ...state, defaultThumbnailScale: action.defaultThumbnailScale }; case 'SET_DEFAULT_MOVIEPRINT_WIDTH': return { ...state, defaultMoviePrintWidth: action.defaultMoviePrintWidth }; case 'SET_DEFAULT_MARGIN': return { ...state, defaultMarginRatio: action.defaultMarginRatio }; case 'SET_DEFAULT_SHOW_HEADER': return { ...state, defaultShowHeader: action.defaultShowHeader }; case 'SET_DEFAULT_SHOW_IMAGES': return { ...state, defaultShowImages: action.defaultShowImages }; case 'SET_DEFAULT_PATH_IN_HEADER': return { ...state, defaultShowPathInHeader: action.defaultShowPathInHeader }; case 'SET_DEFAULT_DETAILS_IN_HEADER': return { ...state, defaultShowDetailsInHeader: action.defaultShowDetailsInHeader }; case 'SET_DEFAULT_TIMELINE_IN_HEADER': return { ...state, defaultShowTimelineInHeader: action.defaultShowTimelineInHeader }; case 'SET_DEFAULT_ROUNDED_CORNERS': return { ...state, defaultRoundedCorners: action.defaultRoundedCorners }; case 'SET_DEFAULT_THUMB_INFO': return { ...state, defaultThumbInfo: action.defaultThumbInfo }; case 'SET_DEFAULT_OUTPUT_PATH': return { ...state, defaultOutputPath: action.defaultOutputPath }; case 'SET_DEFAULT_OUTPUT_FORMAT': return { ...state, defaultOutputFormat: action.defaultOutputFormat }; case 'SET_DEFAULT_OUTPUT_JPG_QUALITY': return { ...state, defaultOutputJpgQuality: action.defaultOutputJpgQuality }; case 'SET_DEFAULT_THUMB_FORMAT': return { ...state, defaultThumbFormat: action.defaultThumbFormat }; case 'SET_DEFAULT_THUMB_JPG_QUALITY': return { ...state, defaultThumbJpgQuality: action.defaultThumbJpgQuality }; case 'SET_DEFAULT_CACHED_FRAMES_SIZE': return { ...state, defaultCachedFramesSize: action.defaultCachedFramesSize }; case 'SET_DEFAULT_SAVE_OPTION_OVERWRITE': return { ...state, defaultSaveOptionOverwrite: action.defaultSaveOptionOverwrite }; case 'SET_DEFAULT_SAVE_OPTION_INCLUDE_INDIVIDUAL': return { ...state, defaultSaveOptionIncludeIndividual: action.defaultSaveOptionIncludeIndividual, }; case 'SET_DEFAULT_EMBED_FRAMENUMBERS': return { ...state, defaultEmbedFrameNumbers: action.defaultEmbedFrameNumbers }; case 'SET_DEFAULT_EMBED_FILEPATH': return { ...state, defaultEmbedFilePath: action.defaultEmbedFilePath }; case 'SET_DEFAULT_SHOW_PAPER_PREVIEW': return { ...state, defaultShowPaperPreview: action.defaultShowPaperPreview }; case 'SET_DEFAULT_PAPER_ASPECT_RATIO_INV': return { ...state, defaultPaperAspectRatioInv: action.defaultPaperAspectRatioInv }; case 'SET_DEFAULT_DETECT_INOUTPOINT': return { ...state, defaultDetectInOutPoint: action.defaultDetectInOutPoint }; case 'SET_DEFAULT_SCENE_DETECTION_THRESHOLD': return { ...state, defaultSceneDetectionThreshold: action.defaultSceneDetectionThreshold }; case 'SET_DEFAULT_TIMELINEVIEW_SECONDS_PER_ROW': return { ...state, defaultTimelineViewSecondsPerRow: action.defaultTimelineViewSecondsPerRow }; case 'SET_DEFAULT_TIMELINEVIEW_MIN_DISPLAY_SCENE_LENGTH_IN_FRAMES': return { ...state, defaultTimelineViewMinDisplaySceneLengthInFrames: action.defaultTimelineViewMinDisplaySceneLengthInFrames, }; case 'SET_DEFAULT_TIMELINEVIEW_PIXEL_PER_FRAME_RATIO': return { ...state, defaultTimelineViewWidthScale: action.defaultTimelineViewWidthScale }; case 'SET_DEFAULT_TIMELINEVIEW_FLOW': return { ...state, defaultTimelineViewFlow: action.defaultTimelineViewFlow }; case 'SET_DEFAULT_OUTPUT_PATH_FROM_MOVIE': return { ...state, defaultOutputPathFromMovie: action.defaultOutputPathFromMovie }; case 'SET_DEFAULT_SHOT_DETECTION_METHOD': return { ...state, defaultShotDetectionMethod: action.defaultShotDetectionMethod }; case 'SET_DEFAULT_MOVIEPRINT_BACKGROUND_COLOR': return { ...state, defaultMoviePrintBackgroundColor: action.defaultMoviePrintBackgroundColor }; case 'SET_DEFAULT_FRAMEINFO_BACKGROUND_COLOR': return { ...state, defaultFrameinfoBackgroundColor: action.defaultFrameinfoBackgroundColor }; case 'SET_DEFAULT_FRAMEINFO_COLOR': return { ...state, defaultFrameinfoColor: action.defaultFrameinfoColor }; case 'SET_DEFAULT_FRAMEINFO_POSITION': return { ...state, defaultFrameinfoPosition: action.defaultFrameinfoPosition }; case 'SET_DEFAULT_FRAMEINFO_SCALE': return { ...state, defaultFrameinfoScale: action.defaultFrameinfoScale }; case 'SET_DEFAULT_FRAMEINFO_MARGIN': return { ...state, defaultFrameinfoMargin: action.defaultFrameinfoMargin }; case 'SET_DEFAULT_MOVIEPRINT_NAME': return { ...state, defaultMoviePrintName: action.defaultMoviePrintName }; case 'SET_DEFAULT_SINGLETHUMB_NAME': return { ...state, defaultSingleThumbName: action.defaultSingleThumbName }; case 'SET_DEFAULT_ALLTHUMBS_NAME': return { ...state, defaultAllThumbsName: action.defaultAllThumbsName }; case 'SET_DEFAULT_OPEN_FILE_EXPLORER_AFTER_SAVING': return { ...state, defaultOpenFileExplorerAfterSaving: action.defaultOpenFileExplorerAfterSaving }; case 'SET_DEFAULT_FACE_SIZE_THRESHOLD': return { ...state, defaultFaceSizeThreshold: action.defaultFaceSizeThreshold }; case 'SET_DEFAULT_FACE_CONFIDENCE_THRESHOLD': return { ...state, defaultFaceConfidenceThreshold: action.defaultFaceConfidenceThreshold }; case 'SET_DEFAULT_FACE_UNIQUENESS_THRESHOLD': return { ...state, defaultFaceUniquenessThreshold: action.defaultFaceUniquenessThreshold }; case 'SET_DEFAULT_SHOW_FACERECT': return { ...state, defaultShowFaceRect: action.defaultShowFaceRect }; default: return state; } }; export default settings; <|start_filename|>app/utils/utilsForMain.js<|end_filename|> import log from 'electron-log'; import path from 'path'; export const clearCache = win => { log.debug('clearCache'); win.webContents.session .getCacheSize() .then(cacheSizeBefore => { log.debug(`cacheSize before: ${cacheSizeBefore}`); return win.webContents.session.clearCache(); }) .then(() => { return win.webContents.session.clearStorageData(); }) .then(() => { return win.webContents.session.getCacheSize(); }) .then(cacheSizeAfter => { log.debug(`cacheSize after: ${cacheSizeAfter}`); // and reload to use initialStateJSON win.webContents.reload(); return undefined; }) .catch(error => { log.error(`There has been a problem with your clearCache operation: ${error.message}`); }); }; export const resetApplication = (mainWindow, workerWindow, opencvWorkerWindow, databaseWorkerWindow) => { mainWindow.webContents.send('delete-all-tables'); setTimeout(() => { clearCache(mainWindow); workerWindow.webContents.reload(); opencvWorkerWindow.webContents.reload(); databaseWorkerWindow.webContents.reload(); // needs reload to open indexedDB connection }, 1000); }; // soft reset only deletes the indexedDB table, and does not clear cache nor all storage data // and also does not reload the windows export const softResetApplication = mainWindow => { mainWindow.webContents.send('delete-all-tables'); }; export const reloadApplication = (mainWindow, workerWindow, opencvWorkerWindow, databaseWorkerWindow) => { mainWindow.webContents.reload(); workerWindow.webContents.reload(); opencvWorkerWindow.webContents.reload(); databaseWorkerWindow.webContents.reload(); }; export const getPathOfLogFileAndFolder = (processPlatform, appName) => { let pathOfLogFolder; switch (processPlatform) { case 'darwin': pathOfLogFolder = path.resolve(process.env.HOME || process.env.USERPROFILE, 'Library/Logs/', `${appName}/`); break; default: pathOfLogFolder = path.resolve( process.env.HOME || process.env.USERPROFILE, 'AppData\\Roaming\\', `${appName}`, 'logs/', ); } const pathOfLogFile = path.resolve(pathOfLogFolder, 'main.log'); return { pathOfLogFile, pathOfLogFolder }; }; <|start_filename|>app/components/FileList.css<|end_filename|> * {margin: 0; padding: 0;} /* div { margin: 20px; }*/ ul { list-style-type: none; /*width: 350px;*/ } h3 { font: bold 1em Helvetica, Verdana, sans-serif; } .croppedThumb { float: left; width: 76px !important; height: 76px !important; background-size: cover; background-position: center; overflow: hidden; position: relative; border-radius: 8px; margin-right: 0px !important; margin-bottom: 0px !important; } .ThumbLabel { position: absolute; right: 4px; bottom: 4px; opacity: 0.6; } li p { font: 0.8em Georgia, Times New Roman, serif; } .MainList > li { margin: 8px 0px 8px 8px; padding: 8px 8px 0px 8px; /* width: 336px; */ /* overflow: hidden; */ overflow-wrap: break-word; word-wrap: break-word; border-width: 1px; border-style: solid; border-color: transparent; /* border-radius: 4px; */ } .MainList > li:hover { border-color: transparent; border-width: 1px; border-style: solid; border-radius: 4px; cursor: pointer; box-shadow: 0 0 64px 0 rgba(0,0,0,0.5); background: #1e1e1e; border-radius: 0; border-left: 1px solid rgba(255, 133, 27, 0.6); } .Highlight { background: #1e1e1e; width: 342px; padding-right: 12px; /* (342-336)*2 */ border-radius: 0; border-left: 1px solid rgba(255, 133, 27, 1) !important; } .Title { /* padding-top: 4px; */ padding-left: 84px; padding-right: 16px; height: 32px; opacity: 0.8; color: #EEEEEE; font-family: "Roboto Condensed"; font-size: 14px; /* font-weight: bold; */ line-height: 16px; } .Path { padding-top: 4px; padding-left: 84px; /*height: 14px;*/ /*width: 336px;*/ opacity: 0.5; color: #EEEEEE; font-family: "Roboto Condensed"; font-size: 10px; font-weight: 300; line-height: 14px; } .Detail { padding-left: 84px; padding-right: 4px; padding-top: 4px; /*height: 13px;*/ width: 100%; color: #FFD3BF; font-family: Ubuntu; font-size: 12px; font-weight: 300; line-height: 13px; } .DetailLeft { float: left; text-align: left; } .DetailCenter { margin: 0 auto; text-align: center; } .DetailRight { float: right; text-align: right; } .SheetLabel { margin-left: 8px !important; background-color: rgba(232, 232, 232, 0.5) !important; position: absolute; right: 24px; top: 6px; } .shotBased { background-color: #ff9365 !important; } .facesBased { background-color: #93ff65 !important; } .SheetList { margin: 18px 0 0 0; } .SheetList > li { margin: 8px -8px 8px 0px; padding: 4px 4px 4px 4px; /* margin-left: 84px; */ /* width: 336px; */ /* overflow: hidden; */ overflow-wrap: break-word; word-wrap: break-word; border-width: 1px; border-style: solid; border-color: transparent; border-radius: 4px; color: rgba(255, 255, 255, 0.3); } .SheetList > li:hover { border-color: transparent; border-width: 1px; border-style: solid; border-radius: 4px; cursor: pointer; background: #1e1e1e; border-radius: 0; /* border-left: 1px solid rgba(0, 0, 0, 1); */ background-color: rgba(0, 0, 0, 0.6); /* background-color: rgba(255, 133, 27, 0.1); */ color: rgba(255, 255, 255, 1); } .SheetHighlight { border-radius: 0; border-left: 1px solid rgba(255, 133, 27, 1); background-color: rgba(0, 0, 0, 1); /* background-color: #eeeeee; */ color: rgba(255, 255, 255, 1) !important; } .SheetName { /* padding-top: 4px; */ /* padding-left: 84px; */ /* padding-right: 16px; */ /* height: 32px; */ margin-left: 8px; margin-right: 100px; text-overflow: ellipsis; overflow: hidden; display: block; white-space: nowrap; opacity: 0.8; color: #EEEEEE; font-family: "Roboto Condensed"; font-size: 14px; /* font-weight: bold; */ /* line-height: 16px; */ } .SheetNameInputContainer { margin-left: 8px; } .SheetNameInput { /* margin-left: 2px; */ padding-left: 2px; height: 19px; background-color: rgba(255,211,193,0.05); margin-right: 32px; display: inline-block !important; width: 260px !important; /* opacity: 0.8; */ } .SheetNameInput > input { color: #EEEEEE !important; font-family: "Roboto Condensed" !important; font-size: 14px !important; width: 260px !important; } .SheetNameInput > input::selection { background: white; color: black; } .overflow { z-index: 1; position: absolute !important; right: 0px; margin-right: 4px !important; margin-top: -1px !important; } .overflowHidden { /* generally hide, only display on hover. !important to override display value from icon */ display: none !important; } .SheetListItem { position: relative; } .SheetListItem:hover > .overflow { /* show overflow only on hover. !important to override display value from overflow */ display:block !important; margin-top: -20px !important; margin-right: 4px !important; } .FileListItem:hover > .overflow { /* show overflow only on hover. !important to override display value from overflow */ display:block !important; } .Missing { border-left: 1px solid rgba(255, 0, 0, 1.0) !important; background-color: rgba(255, 0, 0, 0.1); } .emptyFilelist { margin-top: 50%; margin-left: 50%; text-align: center; transform: translate(-50%, -50%); } .fileMissingContainer { margin-left: 8px; margin-bottom: 16px; display: flex; /* justify-content: space-between; */ } .fileMissing { color: rgba(255, 0, 0, 1.0); margin-top: 4px; font-size: 12px; } .fileMissingButton { margin-left: 16px !important; } <|start_filename|>app/reducers/index.js<|end_filename|> import { combineReducers } from 'redux'; import undoable, { excludeAction, groupByActionTypes } from 'redux-undo'; import sheetsByFileId from './sheetsByFileId'; import files from './files'; import settings from './settings'; import visibilitySettings from './visibilitySettings'; import { UNDO_STEPS_LIMIT } from '../utils/constants'; const rootReducer = combineReducers({ visibilitySettings, undoGroup: undoable( combineReducers({ settings, sheetsByFileId, files, }), { filter: excludeAction([ // 'UPDATE_MOVIE_LIST_ITEM_USERATIO' ]), groupBy: groupByActionTypes([ 'UPDATE_MOVIE_LIST_ITEM_USERATIO', 'UPDATE_FRAMENUMBER_AND_COLORARRAY_OF_THUMB', 'UPDATE_OBJECTURL_FROM_THUMBLIST', 'UPDATE_SHEET_COLUMNCOUNT', 'SET_DEFAULT_MARGIN', 'SET_DEFAULT_SHOW_HEADER', 'SET_DEFAULT_ROUNDED_CORNERS', ]), limit: UNDO_STEPS_LIMIT, }, ), }); export default rootReducer; <|start_filename|>app/components/FloatingMenu.css<|end_filename|> .floatingMenu { transition: transform 0.5s ease; position: fixed; transform: translate(-50%); top: 8px; left: calc(50% + 10px); z-index: 990; width: 760px; /* background-color: rgba(255, 0, 0, 0.5); */ } .imageButton { color: white !important; /* background-color: rgba(30, 15, 0, 1.0) !important; */ background: rgba(0,0,0,0.8) !important; /* box-shadow: none !important; */ padding-left: 11px !important; padding-right: 11px !important; /* padding-top: 10px !important; */ /* padding-bottom: 9px !important; */ } .imageButton:hover { /* background-color: rgba(60, 30, 0, 1.0) !important; */ background-color: rgba(255, 80, 6, 1.0) !important; } .dropDownButton { color: white !important; /* background-color: rgba(30, 15, 0, 1.0) !important; */ background: rgba(0,0,0,0.8) !important; /* box-shadow: none !important; */ padding-left: 15px !important; padding-right: 11px !important; /* padding-top: 11px !important; */ /* padding-bottom: 10px !important; */ font-size: 16px !important; } .dropDownButton:hover { /* background-color: rgba(60, 30, 0, 1.0) !important; */ background-color: rgba(255, 80, 6, 1.0) !important; } .dropDownButton i{ opacity: 0.9 !important; } .dropDownMenu { /* background-color: rgba(60, 30, 0, 1.0) !important; */ } .dropDownMenuFilter { width: 260px; } .dropDownItem { height: 40px !important; } .dropDownItem img{ margin-top: -2px !important; } .dropDownItemIconInvert img{ filter: invert(100%); } .dropDownItemCheckbox{ height: 40px !important; } .dropDownItemCheckboxAndSlider{ height: 72px !important; } .dropDownItemRadioGroup{ height: 40px !important; margin: 16px; } .dropDownItemHidden { visibility: hidden; /* height: 32px !important; */ } .dropDownItemRadioGroup > div{ margin-right: 16px; } .slider{ margin-top: 8px !important; } .normalButton { color: white !important; /* background-color: rgba(30, 15, 0, 1.0) !important; */ background: rgba(0,0,0,0.8) !important; font-family: Lato, 'Helvetica Neue', Arial, Helvetica, sans-serif !important; box-shadow: none !important; } .normalButton:hover { /* background-color: rgba(60, 30, 0, 1.0) !important; */ background-color: rgba(255, 80, 6, 1.0) !important; } .textButton { color: white !important; background-color: rgba(0, 0, 0, 0.2) !important; font-family: Lato, 'Helvetica Neue', Arial, Helvetica, sans-serif !important; font-weight: 600 !important; font-size: 14px !important; height: 34px !important; border-radius: 0 !important; padding-top: 11px !important; } .textButton:hover { background-color: rgba(60, 30, 0, 1.0) !important; } .selected { background-color: rgba(255, 80, 6, 0.5) !important; color: white !important; } .selected:hover { background-color: rgba(255, 80, 6, 1.0) !important; /* background-color: rgba(60, 30, 0, 1.0) !important; */ color: white !important; } .hidden { visibility: hidden; } .noBackground { background-color: none !important; box-shadow: none !important; padding: 0px 16px 16px 16px !important; opacity: 0.5 !important; } <|start_filename|>app/img/listOfNames.json<|end_filename|> [ {"firstName": "Adriana", "fullName": "<NAME>"}, {"firstName": "Agnieszka", "fullName": "<NAME>"}, {"firstName": "Agnès", "fullName": "<NAME>"}, {"firstName": "Agnès", "fullName": "<NAME>"}, {"firstName": "Akie", "fullName": "<NAME>"}, {"firstName": "Alice", "fullName": "<NAME>"}, {"firstName": "Andrea", "fullName": "<NAME>"}, {"firstName": "Anna", "fullName": "<NAME>"}, {"firstName": "Anne", "fullName": "<NAME>"}, {"firstName": "Archana", "fullName": "<NAME>"}, {"firstName": "Autumn", "fullName": "<NAME>"}, {"firstName": "Barbara", "fullName": "<NAME>"}, {"firstName": "Barbra", "fullName": "<NAME>"}, {"firstName": "Candida", "fullName": "<NAME>"}, {"firstName": "Carmen", "fullName": "<NAME>"}, {"firstName": "Caroline", "fullName": "<NAME>"}, {"firstName": "Caroline", "fullName": "<NAME>"}, {"firstName": "Chantal", "fullName": "<NAME>"}, {"firstName": "Claire", "fullName": "<NAME>"}, {"firstName": "Deepa", "fullName": "<NAME>"}, {"firstName": "Dolores", "fullName": "<NAME>"}, {"firstName": "Dominique", "fullName": "<NAME>"}, {"firstName": "Doris", "fullName": "<NAME>"}, {"firstName": "Dorota", "fullName": "<NAME>"}, {"firstName": "Dorothy", "fullName": "<NAME>"}, {"firstName": "Edith", "fullName": "<NAME>"}, {"firstName": "Elaine", "fullName": "<NAME>"}, {"firstName": "Eleanor", "fullName": "<NAME>"}, {"firstName": "Ellen", "fullName": "<NAME>"}, {"firstName": "Elvira", "fullName": "<NAME>"}, {"firstName": "Eriko", "fullName": "<NAME>"}, {"firstName": "G.B.", "fullName": "<NAME>"}, {"firstName": "Gabriela", "fullName": "<NAME>"}, {"firstName": "Germaine", "fullName": "<NAME>"}, {"firstName": "Gilda", "fullName": "<NAME>"}, {"firstName": "Gunvor", "fullName": "<NAME>"}, {"firstName": "Helen", "fullName": "<NAME>"}, {"firstName": "Hyeong", "fullName": "<NAME>"}, {"firstName": "Icíar", "fullName": "<NAME>"}, {"firstName": "Ida", "fullName": "<NAME>"}, {"firstName": "Ida", "fullName": "<NAME>"}, {"firstName": "Isabel", "fullName": "<NAME>"}, {"firstName": "Jane", "fullName": "<NAME>"}, {"firstName": "Jasmila", "fullName": "<NAME>"}, {"firstName": "Jennifer", "fullName": "<NAME>"}, {"firstName": "Jessica", "fullName": "<NAME>"}, {"firstName": "Joanna", "fullName": "<NAME>"}, {"firstName": "Jocelyn", "fullName": "<NAME>"}, {"firstName": "Julie", "fullName": "<NAME>"}, {"firstName": "Kate", "fullName": "<NAME>"}, {"firstName": "Kathryn", "fullName": "<NAME>"}, {"firstName": "Katia", "fullName": "<NAME>"}, {"firstName": "Kirsten", "fullName": "<NAME>"}, {"firstName": "Larisa", "fullName": "<NAME>"}, {"firstName": "Laurel", "fullName": "<NAME>"}, {"firstName": "Leni", "fullName": "<NAME>"}, {"firstName": "Lina", "fullName": "<NAME>"}, {"firstName": "Liz", "fullName": "<NAME>"}, {"firstName": "Lois", "fullName": "<NAME>"}, {"firstName": "Lone", "fullName": "<NAME>"}, {"firstName": "Louise", "fullName": "<NAME>"}, {"firstName": "Lucrecia", "fullName": "<NAME>"}, {"firstName": "Mabel", "fullName": "<NAME>"}, {"firstName": "Malgorzata", "fullName": "<NAME>"}, {"firstName": "Margarethe", "fullName": "<NAME>"}, {"firstName": "Marie", "fullName": "<NAME>"}, {"firstName": "Marjane", "fullName": "<NAME>"}, {"firstName": "Mary", "fullName": "<NAME>"}, {"firstName": "Maryse", "fullName": "<NAME>"}, {"firstName": "Maya", "fullName": "<NAME>"}, {"firstName": "Mimi", "fullName": "<NAME>"}, {"firstName": "Mira", "fullName": "<NAME>"}, {"firstName": "Muriel", "fullName": "<NAME>"}, {"firstName": "Nadine", "fullName": "<NAME>"}, {"firstName": "Natasha", "fullName": "<NAME>"}, {"firstName": "Niki", "fullName": "<NAME>"}, {"firstName": "Olga", "fullName": "<NAME>"}, {"firstName": "Rachel", "fullName": "<NAME>"}, {"firstName": "Randa", "fullName": "<NAME>"}, {"firstName": "Reed", "fullName": "<NAME>"}, {"firstName": "Sofia", "fullName": "<NAME>"}, {"firstName": "Susanne", "fullName": "<NAME>"}, {"firstName": "Toni", "fullName": "<NAME>"}, {"firstName": "Vera", "fullName": "<NAME>"} ] <|start_filename|>app/utils/utilsForSqlite.js<|end_filename|> import Database from 'better-sqlite3'; import log from 'electron-log'; import { getFrameScanTableName } from './utils'; import { FRAMESDB_PATH } from './constants'; // latest database version const moviePrintDBVersion = 2; const moviePrintDB = new Database(FRAMESDB_PATH, { verbose: log.debug }); moviePrintDB.pragma('journal_mode = WAL'); // get users database version const moviePrintDBUserVersion = moviePrintDB.pragma('user_version', { simple: true }); log.debug(`Users database version: ${moviePrintDBUserVersion}`); // check if migration is necessary if (moviePrintDBUserVersion === 0) { log.info( `Database migration necessary - users database version: ${moviePrintDBUserVersion} - latest database version: ${moviePrintDBVersion}`, ); // run migration script migrationFrom0To1(); migrationFrom1To2(); } else if (moviePrintDBUserVersion === 1) { log.info( `Database migration necessary - users database version: ${moviePrintDBUserVersion} - latest database version: ${moviePrintDBVersion}`, ); // run migration script migrationFrom1To2(); } // create redux store table export const createTableReduxState = () => { const stmt = moviePrintDB.prepare( 'CREATE TABLE IF NOT EXISTS reduxstate(stateId TEXT PRIMARY KEY, timeStamp TEXT, state TEXT)', ); stmt.run(); }; // delete redux state table export const deleteTableReduxState = () => { const stmt = moviePrintDB.prepare('DROP TABLE IF EXISTS reduxstate'); stmt.run(); }; // update redux state export const updateReduxState = moviePrintDB.transaction(item => { const insert = moviePrintDB.prepare( 'REPLACE INTO reduxstate (stateId, timeStamp, state) VALUES (@stateId, @timeStamp, @state)', ); insert.run(item); }); // get redux state export const getReduxState = stateId => { const stmt = moviePrintDB.prepare(`SELECT stateId, timeStamp, state FROM reduxstate WHERE stateId = ?`); return stmt.get(stateId); }; // movies table actions // create movies table export const createTableMovielist = () => { const stmt = moviePrintDB.prepare( 'CREATE TABLE IF NOT EXISTS movielist(id TEXT, lastModified INTEGER, name TEXT, path TEXT, size INTEGER, type TEXT, posterFrameId TEXT)', ); stmt.run(); }; // delete movies table export const deleteTableMovielist = () => { const stmt = moviePrintDB.prepare('DROP TABLE IF EXISTS movielist'); stmt.run(); }; // insert movie export const insertMovie = moviePrintDB.transaction(item => { const insert = moviePrintDB.prepare( 'INSERT INTO movielist (id, lastModified, name, path, size, type, posterFrameId) VALUES (@id, @lastModified, @name, @path, @size, @type, @posterFrameId)', ); insert.run(item); }); // framescan table actions // create framescan table export const createTableFrameScanList = fileId => { const tableName = getFrameScanTableName(fileId); const stmt = moviePrintDB.prepare( `CREATE TABLE IF NOT EXISTS ${tableName}(frameNumber INTEGER PRIMARY KEY, differenceValue REAL, meanColor TEXT, faceObject TEXT)`, ); stmt.run(); }; // delete framescan table export const deleteTableFrameScanList = (fileId = undefined) => { // delete all tables if (fileId === undefined) { // get tableNames const stmtToGetTableNames = moviePrintDB.prepare( 'SELECT name FROM sqlite_master WHERE type = "table" ORDER BY name', ); const arrayOfTables = stmtToGetTableNames.all(); // run through all tableNames for (const item of arrayOfTables) { const tableName = item.name; // only delete frameScan tables if (tableName.startsWith('frameScan_')) { // prepare delete table statement const stmtToDeleteTable = moviePrintDB.prepare(`DROP TABLE IF EXISTS ${tableName}`); stmtToDeleteTable.run(); } } } else { // delete single table const tableName = getFrameScanTableName(fileId); const stmt = moviePrintDB.prepare(`DROP TABLE IF EXISTS ${tableName}`); stmt.run(); } }; // // insert frame // export const insertFrameScan = moviePrintDB.transaction((item) => { // const insert = moviePrintDB.prepare('INSERT INTO frameScanList (frameNumber, differenceValue, meanColor) VALUES (@frameNumber, @differenceValue, @meanColor)'); // insert.run(item) // }); // insert multiple frames from frame scan export const insertFrameScanArray = moviePrintDB.transaction((fileId, array) => { // create table if it does not exist const tableName = getFrameScanTableName(fileId); if (doesTableExist(tableName) === false) { createTableFrameScanList(fileId); } const upsert = moviePrintDB.prepare( `INSERT INTO ${tableName} (frameNumber, differenceValue, meanColor) VALUES (@frameNumber, @differenceValue, @meanColor) ON CONFLICT (frameNumber) DO UPDATE SET differenceValue = @differenceValue, meanColor = @meanColor`, ); for (const item of array) upsert.run(item); }); // insert multiple frames from face scan export const insertFaceScanArray = moviePrintDB.transaction((fileId, array) => { // create table if it does not exist const tableName = getFrameScanTableName(fileId); if (doesTableExist(tableName) === false) { createTableFrameScanList(fileId); } const upsert = moviePrintDB.prepare( `INSERT INTO ${tableName} (frameNumber, faceObject) VALUES (@frameNumber, @faceObject) ON CONFLICT (frameNumber) DO UPDATE SET faceObject = @faceObject`, ); for (const item of array) { const frameNumber = item.frameNumber; // delete item.frameNumber; const faceObject = JSON.stringify(item); upsert.run({ faceObject, frameNumber, }); } }); // get all frames by fileId export const getFrameScanByFileId = fileId => { const tableName = getFrameScanTableName(fileId); if (doesTableExist(tableName)) { const stmt = moviePrintDB.prepare( `SELECT frameNumber, differenceValue, meanColor FROM ${tableName} WHERE differenceValue IS NOT NULL ORDER BY frameNumber ASC`, ); return stmt.all(); } return []; // if table does not exist, return empty array }; // get all detected faces by fileId export const getFaceScanByFileId = (fileId, arrayOfFrameNumbers = undefined) => { const tableName = getFrameScanTableName(fileId); if (doesTableExist(tableName)) { let stmt; if (arrayOfFrameNumbers === undefined) { stmt = moviePrintDB.prepare( `SELECT faceObject FROM ${tableName} WHERE faceObject IS NOT NULL ORDER BY frameNumber ASC`, ); } else { const implodedArrayString = arrayOfFrameNumbers.join(); stmt = moviePrintDB.prepare( `SELECT faceObject FROM ${tableName} WHERE frameNumber IN (${implodedArrayString}) AND faceObject IS NOT NULL ORDER BY frameNumber ASC`, ); } const returnArray = stmt.all(); // console.log(returnArray); const newArray = returnArray.map(item => JSON.parse(item.faceObject)); // console.log(newArray); return newArray; } return []; // if table does not exist, return empty array }; // get how many frames have scan data export const getFrameScanCount = fileId => { const tableName = getFrameScanTableName(fileId); if (doesTableExist(tableName)) { const stmt = moviePrintDB.prepare(`SELECT count(frameNumber) FROM ${tableName} WHERE differenceValue IS NOT NULL`); return Object.values(stmt.get())[0]; } return undefined; }; // check if a table exists function doesTableExist(tableName) { const stmtToCheckForTable = moviePrintDB.prepare( `SELECT count(name) FROM sqlite_master WHERE type = "table" AND name="${tableName}"`, ); const result = Object.values(stmtToCheckForTable.get())[0] === 1; // turn resulting object into value and then into boolean log.debug(stmtToCheckForTable.get()); log.debug(`doesTableExist tableName = ${doesTableExist}: ${result}`); return result; } // migration scripts // from 0 to 1 function migrationFrom0To1() { log.debug('migrationFrom0To1'); const tableName = 'frameScanList'; const oldColumnName = 'meanValue'; const newColumnName = 'differenceValue'; try { // check if old or new column already exists const tableInfo = moviePrintDB.pragma(`table_info = ${tableName}`); const oldColumnExists = tableInfo.findIndex(column => column.name === oldColumnName) > -1; const newColumnExists = tableInfo.findIndex(column => column.name === newColumnName) > -1; // migrate if it is still the old column name if (oldColumnExists) { moviePrintDB.exec(`ALTER TABLE "${tableName}" RENAME COLUMN "${oldColumnName}" TO "${newColumnName}"`); // set user_version to 1 after database has been migrated moviePrintDB.pragma('user_version = 1'); log.info( `Database migration successful - users database version is now: ${moviePrintDB.pragma('user_version', { simple: true, })}`, ); } // only update user_version if column name was already update, but user_version had not been updated if (newColumnExists) { // set user_version to 1 after database has been migrated moviePrintDB.pragma('user_version = 1'); log.info( `Database was already migrated, but user_version had not been updated - users database version is now: ${moviePrintDB.pragma( 'user_version', { simple: true }, )}`, ); } } catch (err) { log.error(err); } } // from 1 to 2 function migrationFrom1To2() { log.debug('migrationFrom1To2'); const tableName = 'frameScanList'; try { // check if table exists if (doesTableExist(tableName)) { // split frameScanList into separate tables // get distinct fileIds const stmtDistinctFileIds = moviePrintDB.prepare(`SELECT DISTINCT fileid FROM ${tableName}`); const arrayOfFileIdObjects = stmtDistinctFileIds.all(); log.debug(arrayOfFileIdObjects); // loop through distinct fileIds /* eslint no-restricted-syntax: off */ for (const fileIdObject of arrayOfFileIdObjects) { const distinctFileId = fileIdObject.fileId; log.debug(`distinctFileId: ${distinctFileId}`); // create table for fileId const newTableName = `frameScan_${distinctFileId.replace(/-/g, '_')}`; log.debug(`newTableName: ${newTableName}`); const stmtToCreateTable = moviePrintDB.prepare( `CREATE TABLE IF NOT EXISTS ${newTableName}(frameNumber INTEGER PRIMARY KEY, differenceValue REAL, meanColor TEXT, faceObject TEXT)`, ); stmtToCreateTable.run(); // copy its values over const stmtToGetValues = moviePrintDB.prepare( `SELECT * FROM ${tableName} WHERE fileId = "${distinctFileId}" ORDER BY frameNumber ASC`, ); const arrayOfValuesForFileId = stmtToGetValues.all(); const insert = moviePrintDB.prepare( `INSERT INTO ${newTableName} (frameNumber, differenceValue, meanColor) VALUES (@frameNumber, @differenceValue, @meanColor)`, ); for (const item of arrayOfValuesForFileId) { insert.run(item); } } // delete table frameScanList const stmtToDeleteTable = moviePrintDB.prepare(`DROP TABLE IF EXISTS ${tableName}`); stmtToDeleteTable.run(); } moviePrintDB.pragma('user_version = 2'); log.info( `Database migration successful - users database version is now: ${moviePrintDB.pragma('user_version', { simple: true, })}`, ); } catch (err) { log.error(err); } } <|start_filename|>app/components/HeaderComponent.js<|end_filename|> import React from 'react'; import PropTypes from 'prop-types'; import { Menu, Dropdown, Icon, Popup } from 'semantic-ui-react'; import { MENU_HEADER_HEIGHT } from '../utils/constants'; import styles from './Menu.css'; import stylesPop from './Popup.css'; const Header = ({ file, visibilitySettings, openMoviesDialog, onOpenFeedbackForm, onImportMoviePrint, fileCount, onClearMovieList, checkForUpdates, isCheckingForUpdates, }) => { return ( <div className={`${styles.container}`} style={{ height: MENU_HEADER_HEIGHT, }} > <Menu size="tiny" inverted className={`${styles.menu}`} // widths={3} > <Popup trigger={ <Menu.Item data-tid="openMoviesBtn" onClick={openMoviesDialog}> <Icon name="folder open outline" /> {file ? 'Add Movies' : 'Add Movies'} </Menu.Item> } mouseEnterDelay={1000} on={['hover']} position="bottom center" className={stylesPop.popup} content={ <span> Add one or more movies <mark>A</mark> </span> } /> <Popup trigger={ <Dropdown data-tid="moviesOverflowDropdown" item icon="ellipsis vertical"> <Dropdown.Menu> <Popup trigger={ <Dropdown.Item data-tid="importMoviesOverflowOption" icon="folder open" text="Import MoviePrint (png/json)" onClick={() => onImportMoviePrint()} /> } mouseEnterDelay={1000} on={['hover']} position="right center" className={stylesPop.popup} content="Import a MoviePrint from JSON file or a PNG file with embedded data" /> {fileCount > 0 && ( <Popup trigger={ <Dropdown.Item data-tid="clearMovieListOverflowOption" icon="delete" text="Clear Movie list" onClick={onClearMovieList} /> } mouseEnterDelay={1000} on={['hover']} position="right center" className={stylesPop.popup} content="Clear Movie list - THIS CAN NOT BE UNDONE!" /> )} </Dropdown.Menu> </Dropdown> } mouseEnterDelay={1000} on={['hover']} position="right center" className={stylesPop.popup} content="more options" /> <Menu.Menu position="right"> <Popup trigger={ <Menu.Item data-tid="checkForUpdatesBtn" onClick={checkForUpdates} disabled={isCheckingForUpdates}> <Icon name="redo" /> Check for updates </Menu.Item> } mouseEnterDelay={1000} on={['hover']} position="bottom center" className={stylesPop.popup} content="Check online if there are updates available" /> <Popup trigger={ <Menu.Item data-tid="onOpenFeedbackFormBtn" name="send" onClick={onOpenFeedbackForm}> <Icon name="mail" /> Contact us </Menu.Item> } mouseEnterDelay={1000} on={['hover']} position="bottom right" offset="0,8px" className={stylesPop.popup} content="Feedback or feature request? Click here or contact us at <EMAIL>" /> </Menu.Menu> </Menu> </div> ); }; Header.defaultProps = { file: undefined, }; Header.propTypes = { file: PropTypes.object, }; export default Header; <|start_filename|>app/components/Scene.js<|end_filename|> /* eslint no-param-reassign: ["error"] */ // @flow import React from 'react'; import PropTypes from 'prop-types'; import { SortableHandle } from 'react-sortable-hoc'; import { Popup } from 'semantic-ui-react'; import { MINIMUM_WIDTH_TO_SHRINK_HOVER, MINIMUM_WIDTH_TO_SHOW_HOVER, SHEET_VIEW, VIEW } from '../utils/constants'; import styles from './SceneGrid.css'; import stylesPop from './Popup.css'; import transparent from '../img/Thumb_TRANSPARENT.png'; const DragHandle = React.memo( SortableHandle(({ width, height, sceneId }) => ( <Popup trigger={ <button data-tid={`thumbDragHandleBtn_${sceneId}`} className={`${styles.dragHandleButton}`} style={{ width, height: Math.floor(height), }} > <img src={transparent} style={{ width, height: Math.floor(height), }} alt="" /> </button> } mouseEnterDelay={2000} on={['hover']} bottomed offset="-50%r, -50%r" position="top right" basic className={stylesPop.popupSmall} content="Drag thumb" /> )), ); const Scene = React.memo( ({ allowSceneToBeSelected, aspectRatioInv, borderRadius, color, controllersAreVisible, sheetView, view, dim, doLineBreak, hexColor, hidden, index, indexForId, inputRefThumb, key, keyObject, margin, onAddAfter, onAddBefore, onBack, onCutAfter, onCutBefore, onExpand, onForward, onHoverAddThumbAfter, onHoverAddThumbBefore, onHoverInPoint, onHoverOutPoint, onHideAfter, onHideBefore, onLeaveInOut, onOut, onOver, onSaveThumb, onScrub, onSelect, onThumbDoubleClick, onToggle, sceneId, selected, showAddThumbAfterController, showAddThumbBeforeController, thumbHeight, thumbId, thumbImageObjectUrl, base64, thumbInfoRatio, thumbInfoValue, thumbWidth, transparentThumb, }) => { function over(e) { e.stopPropagation(); e.target.style.opacity = 1; } function out(e) { e.stopPropagation(); e.target.style.opacity = 0.2; } function onToggleWithStop(e) { e.stopPropagation(); onToggle(); } function onSaveThumbWithStop(e) { e.stopPropagation(); onSaveThumb(); } function onHoverAddThumbBeforeWithStop(e) { e.stopPropagation(); e.target.style.opacity = 1; onHoverAddThumbBefore(); } function onHoverAddThumbAfterWithStop(e) { e.stopPropagation(); e.target.style.opacity = 1; onHoverAddThumbAfter(); } function onHoverInPointWithStop(e) { e.stopPropagation(); console.log('onHoverInPointWithStop'); e.target.style.opacity = 1; onHoverInPoint(); } function onHoverOutPointWithStop(e) { e.stopPropagation(); e.target.style.opacity = 1; onHoverOutPoint(); } function onLeaveInOutWithStop(e) { e.stopPropagation(); e.target.style.opacity = 0.2; if (typeof onLeaveInOut === 'function') { onLeaveInOut(); } } function onScrubWithStop(e) { e.stopPropagation(); onScrub(); } function onAddBeforeWithStop(e) { e.stopPropagation(); onAddBefore(); } function onAddAfterWithStop(e) { e.stopPropagation(); onAddAfter(); } function onHideBeforeWithStop(e) { e.stopPropagation(); onHideBefore(); } function onHideAfterWithStop(e) { e.stopPropagation(); onHideAfter(); } function onForwardWithStop(e) { e.stopPropagation(); onForward(); } function onBackWithStop(e) { e.stopPropagation(); onBack(); } function onThumbDoubleClickWithStop(e) { e.stopPropagation(); if (controllersAreVisible) { // if (sheetView === SHEET_VIEW.TIMELINEVIEW) { // onSelect(); // } onThumbDoubleClick(); } } function onSelectWithStop(e) { console.log('onSelectWithStop'); e.stopPropagation(); if (controllersAreVisible) { onSelect(); } } function onExpandWithStop(e) { e.stopPropagation(); if (controllersAreVisible) { onExpand(); } } function onOverWithStop(e) { e.stopPropagation(); // check if function is not null (passed from thumbgrid) if (onOver) { onOver(); } } function onOutWithStop(e) { e.stopPropagation(); // check if function is not null (passed from thumbgrid) if (onOut) { onOut(); } } function onCutAfterWithStop(e) { console.log('onCutAfter'); e.stopPropagation(); onCutAfter(); } function onCutBeforeWithStop(e) { console.log('onCutBefore'); e.stopPropagation(); onCutBefore(); } return ( <div ref={inputRefThumb} role="button" tabIndex={index} onMouseOver={onOverWithStop} onMouseLeave={onOutWithStop} onFocus={onOverWithStop} onBlur={onOutWithStop} onClick={e => { allowSceneToBeSelected ? onSelectWithStop(e) : null; }} // onKeyPress={onSelectWithStop} onDoubleClick={onThumbDoubleClickWithStop} id={`scene${indexForId}`} className={`${styles.gridItem} ${doLineBreak ? styles.lineBreak : ''} ${dim ? styles.dim : ''} ${ view === VIEW.PLAYERVIEW && selected ? styles.gridItemSelected : '' } ${view !== VIEW.PLAYERVIEW && selected ? styles.sceneExpanded : ''}`} // width={`${thumbWidth}px`} // height={`${(thumbWidth * aspectRatioInv)}px`} style={{ filter: `${controllersAreVisible ? 'brightness(80%)' : ''}`, opacity: hidden ? '0.2' : '1', width: `${thumbWidth}px`, height: `${thumbHeight}px`, // width: width, margin: `${margin}px`, outlineWidth: `${view === VIEW.STANDARDVIEW ? margin : Math.max(1, margin)}px`, borderRadius: `${selected ? 0 : Math.ceil(borderRadius)}px`, // Math.ceil so the edge is not visible underneath the image backgroundColor: hexColor, backgroundImage: transparentThumb ? undefined : thumbImageObjectUrl === undefined ? `url(data:image/jpeg;base64,${base64})` : `url(${thumbImageObjectUrl}`, backgroundSize: `auto ${thumbHeight + 20}px`, borderWidth: '0px', }} > <div> {thumbInfoValue !== undefined && ( <div data-tid={`thumbInfoText_${sceneId}`} className={styles.frameNumber} style={{ transform: `scale(${(thumbInfoRatio * thumbWidth * aspectRatioInv) / 10})`, }} > {thumbInfoValue} </div> )} <div style={{ display: controllersAreVisible ? 'block' : 'none', }} > {/* {sheetView === SHEET_VIEW.TIMELINEVIEW && <DragHandle width={thumbWidth - 1} // shrink it to prevent rounding issues height={(thumbWidth * aspectRatioInv) - 1} sceneId={sceneId} /> } */} <Popup trigger={ <button data-tid={`ExpandThumbBtn_${sceneId}`} type="button" style={{ display: thumbWidth > MINIMUM_WIDTH_TO_SHOW_HOVER ? 'block' : 'none', transformOrigin: 'left top', transform: `translateY(10%) scale(${thumbWidth > MINIMUM_WIDTH_TO_SHRINK_HOVER ? 1 : 0.7})`, position: 'absolute', top: 0, left: 0, marginLeft: '8px', }} className={`${styles.hoverButton} ${styles.textButton}`} onClick={onExpandWithStop} onMouseOver={over} onMouseLeave={out} onFocus={over} onBlur={out} > EXPAND </button> } mouseEnterDelay={1000} on={['hover']} position="bottom center" className={stylesPop.popup} content="Create a new MoviePrint using In- and Outpoints of this scene" /> <Popup trigger={ <button data-tid={`${hidden ? 'show' : 'hide'}ThumbBtn_${sceneId}`} type="button" style={{ display: thumbWidth > MINIMUM_WIDTH_TO_SHOW_HOVER ? 'block' : 'none', transformOrigin: 'center top', transform: `translate(-50%, 10%) scale(${thumbWidth > MINIMUM_WIDTH_TO_SHRINK_HOVER ? 1 : 0.7})`, position: 'absolute', top: 0, left: '50%', }} className={`${styles.hoverButton} ${styles.textButton}`} onClick={onToggleWithStop} onMouseOver={over} onMouseLeave={out} onFocus={over} onBlur={out} > {hidden ? 'SHOW' : 'HIDE'} </button> } mouseEnterDelay={1000} on={['hover']} position="bottom center" className={stylesPop.popup} content="Hide thumb" /> {!hidden && ( <div> <Popup trigger={ <button data-tid={`setInPointSceneBtn_${sceneId}`} type="button" style={{ display: thumbWidth > MINIMUM_WIDTH_TO_SHOW_HOVER ? 'block' : 'none', transformOrigin: 'left bottom', transform: `scale(${thumbWidth > MINIMUM_WIDTH_TO_SHRINK_HOVER ? 1 : 0.7})`, position: 'absolute', bottom: 0, left: 0, marginLeft: '8px', }} className={`${styles.hoverButton} ${styles.textButton}`} onClick={onHideBeforeWithStop} onMouseOver={onHoverInPointWithStop} onMouseLeave={onLeaveInOutWithStop} onFocus={over} onBlur={out} > IN </button> } mouseEnterDelay={1000} on={['hover']} position="bottom center" className={stylesPop.popup} content={<span>Hide all scenes before</span>} /> {view === VIEW.STANDARDVIEW && ( <Popup // only show in standard view trigger={ <button data-tid={`cutBeforeBtn_${sceneId}`} type="button" className={`${styles.hoverButton} ${styles.textButton} ${styles.overlayAddAfter} ${ thumbWidth < MINIMUM_WIDTH_TO_SHRINK_HOVER ? styles.overlayShrink : '' }`} style={{ display: thumbWidth > MINIMUM_WIDTH_TO_SHOW_HOVER ? 'block' : 'none', transformOrigin: 'left center', transform: `translateY(-50%) scale(${thumbWidth > MINIMUM_WIDTH_TO_SHRINK_HOVER ? 1 : 0.7})`, position: 'absolute', top: '50%', left: 0, marginLeft: '8px', }} onClick={onCutBeforeWithStop} onMouseOver={over} onMouseLeave={out} onFocus={over} onBlur={out} > || </button> } mouseEnterDelay={1000} on={['hover']} position="bottom center" className={stylesPop.popup} content={<span>Jump to cut at the beginning of this scene</span>} /> )} {/* <Popup trigger={ <button data-tid={`scrubBtn_${sceneId}`} type='button' style={{ display: (thumbWidth > MINIMUM_WIDTH_TO_SHOW_HOVER) ? 'block' : 'none', transformOrigin: 'center bottom', transform: `translateX(-50%) scale(${(thumbWidth > MINIMUM_WIDTH_TO_SHRINK_HOVER) ? 1 : 0.7})`, position: 'absolute', bottom: 0, left: '50%', }} className={`${styles.hoverButton} ${styles.textButton}`} // onClick={onScrubWithStop} onMouseDown={onScrubWithStop} onMouseOver={over} onMouseLeave={out} onFocus={over} onBlur={out} > {'<'}|{'>'} </button> } mouseEnterDelay={1000} on={['hover']} position='bottom center' className={stylesPop.popup} content={<span>Click and drag left and right to change the frame (<mark>SHIFT</mark> add new thumb before, <mark>ALT</mark> add new thumb after, <mark>CTRL</mark> display original as overlay)</span>} /> */} <Popup trigger={ <button data-tid={`cutAfterBtn_${sceneId}`} type="button" className={`${styles.hoverButton} ${styles.textButton} ${styles.overlayAddAfter} ${ thumbWidth < MINIMUM_WIDTH_TO_SHRINK_HOVER ? styles.overlayShrink : '' }`} style={{ display: thumbWidth > MINIMUM_WIDTH_TO_SHOW_HOVER ? 'block' : 'none', transformOrigin: 'right center', transform: `translateY(-50%) scale(${thumbWidth > MINIMUM_WIDTH_TO_SHRINK_HOVER ? 1 : 0.7})`, position: 'absolute', top: '50%', right: 0, marginRight: '8px', }} onClick={onCutAfterWithStop} onMouseOver={over} onMouseLeave={out} onFocus={over} onBlur={out} > || </button> } mouseEnterDelay={1000} on={['hover']} position="bottom center" className={stylesPop.popup} content={<span>Jump to cut at the end of this scene</span>} /> <Popup trigger={ <button data-tid={`setOutPointSceneBtn_${sceneId}`} type="button" style={{ display: thumbWidth > MINIMUM_WIDTH_TO_SHOW_HOVER ? 'block' : 'none', transformOrigin: 'right bottom', transform: `scale(${thumbWidth > MINIMUM_WIDTH_TO_SHRINK_HOVER ? 1 : 0.7})`, position: 'absolute', bottom: 0, right: 0, marginRight: '8px', }} className={`${styles.hoverButton} ${styles.textButton}`} onClick={onHideAfterWithStop} onMouseOver={onHoverOutPointWithStop} onMouseLeave={onLeaveInOutWithStop} onFocus={over} onBlur={out} > OUT </button> } mouseEnterDelay={1000} on={['hover']} position="bottom center" className={stylesPop.popup} content={<span>Hide all scenes after</span>} /> </div> )} </div> </div> </div> ); }, ); Scene.defaultProps = {}; Scene.propTypes = {}; export default Scene; <|start_filename|>app/components/Footer.js<|end_filename|> import React from 'react'; import PropTypes from 'prop-types'; import { Menu, Popup, Icon, Dropdown } from 'semantic-ui-react'; import { MENU_FOOTER_HEIGHT, SHEET_VIEW, VIEW } from '../utils/constants'; import styles from './Menu.css'; import stylesPop from './Popup.css'; const Footer = ({ defaultView, file, onSaveAllMoviePrints, onOpenFileExplorer, onSaveMoviePrint, savingMoviePrint, sheetView, }) => { return ( <div className={`${styles.container}`} style={{ height: MENU_FOOTER_HEIGHT, }} > <Menu size="tiny" inverted className={`${styles.menu}`} // widths={3} > <Menu.Menu position="right"> {file && (sheetView === SHEET_VIEW.GRIDVIEW || sheetView === SHEET_VIEW.TIMELINEVIEW) && defaultView === VIEW.STANDARDVIEW && ( <Popup trigger={ <Menu.Item data-tid="saveMoviePrintBtn" name="save" onClick={onSaveMoviePrint} color="orange" active={!savingMoviePrint} className={styles.saveButton} > {savingMoviePrint ? <div className="ui active inline loader mini" /> : <Icon name="download" />} Save MoviePrint </Menu.Item> } mouseEnterDelay={1000} on={['hover']} position="top center" offset="0,8px" pinned className={stylesPop.popup} content={ <span> Save MoviePrint <mark>M</mark> </span> } /> )} {file && ( <Dropdown data-tid="saveMoviePrintMoreOptionsDropdown" item floating pointing="bottom right" upward compact icon="caret down" color="orange" > <Dropdown.Menu> <Dropdown.Item data-tid="openFileExplorerItemOption" icon="external alternate" text="Open output location" onClick={() => onOpenFileExplorer()} /> <Dropdown.Item data-tid="saveAllMoviePrintsOption" icon="download" text="Save All MoviePrints" onClick={onSaveAllMoviePrints} /> </Dropdown.Menu> </Dropdown> )} </Menu.Menu> </Menu> </div> ); }; Footer.defaultProps = {}; Footer.propTypes = { file: PropTypes.object, }; export default Footer; <|start_filename|>app/components/EditTransformModal.js<|end_filename|> import React, { useEffect, useRef, useState } from 'react'; import { Button, Modal, Divider, Grid, Form, Header } from 'semantic-ui-react'; import { CROP_OPTIONS, ROTATION_OPTIONS, TRANSFORMOBJECT_INIT, ASPECT_RATIO_OPTIONS, EDIT_TRANSFORM_CANVAS_WIDTH, EDIT_TRANSFORM_CANVAS_HEIGHT, } from '../utils/constants'; import { getCropWidthAndHeight } from '../utils/utils'; import styles from '../containers/App.css'; const EditTransformModal = ({ fileId, objectUrl, onClose, onChangeTransform, showTransformModal, transformObject = TRANSFORMOBJECT_INIT, // initialise if undefined originalWidth = EDIT_TRANSFORM_CANVAS_WIDTH, originalHeight = EDIT_TRANSFORM_CANVAS_HEIGHT, width = EDIT_TRANSFORM_CANVAS_WIDTH, height = EDIT_TRANSFORM_CANVAS_HEIGHT, }) => { // console.log('EditTransformModal is mounted'); // console.log(transformObject); const [transformObjectState, setTransformObjectState] = useState(transformObject); const [canvasWidth, setCanvasWidth] = useState(EDIT_TRANSFORM_CANVAS_WIDTH); const [canvasHeight, setCanvasHeight] = useState(EDIT_TRANSFORM_CANVAS_HEIGHT); const [cropDropdownValue, setCropDropdownValue] = useState(undefined); const [aspectRatioDropdownValue, setAspectRatioDropdownValue] = useState(transformObject.aspectRatioInv); const canvasRef = useRef(); const originalAspectRatioInv = (originalHeight * 1.0) / originalWidth; function getRadians(rotationFlag) { let degrees = 0; switch (rotationFlag) { case 0: degrees = 90; break; case 1: degrees = 180; break; case 2: degrees = 270; break; default: } return (degrees * Math.PI) / 180; } useEffect(() => { // console.log(transformObjectState); const { cropTop, cropLeft, rotationFlag } = transformObjectState; if (canvasRef.current !== undefined && canvasRef.current !== null) { const ctx = canvasRef.current.getContext('2d'); ctx.clearRect(0, 0, EDIT_TRANSFORM_CANVAS_WIDTH, EDIT_TRANSFORM_CANVAS_HEIGHT); // load image from data url const imageObj = new Image(); imageObj.src = objectUrl; // draw original image const posterImageToCanvasScaleFactor = originalAspectRatioInv <= 1 ? EDIT_TRANSFORM_CANVAS_WIDTH / imageObj.width : EDIT_TRANSFORM_CANVAS_HEIGHT / imageObj.height; const scaledWidth = imageObj.width * posterImageToCanvasScaleFactor; const scaledHeight = imageObj.height * posterImageToCanvasScaleFactor; const centeredXPos = (EDIT_TRANSFORM_CANVAS_WIDTH - scaledWidth) / 2.0; const centeredYPos = (EDIT_TRANSFORM_CANVAS_HEIGHT - scaledHeight) / 2.0; ctx.setTransform(1, 0, 0, 1, EDIT_TRANSFORM_CANVAS_WIDTH / 2, EDIT_TRANSFORM_CANVAS_HEIGHT / 2); // sets scale and origin ctx.rotate(getRadians(rotationFlag)); ctx.drawImage( imageObj, 0, 0, imageObj.width, imageObj.height, centeredXPos - EDIT_TRANSFORM_CANVAS_WIDTH / 2, centeredYPos - EDIT_TRANSFORM_CANVAS_HEIGHT / 2, scaledWidth, scaledHeight, ); ctx.setTransform(1, 0, 0, 1, 0, 0); // sets scale and origin // draw cropped image const imageToCanvasScaleFactor = originalAspectRatioInv <= 1 ? EDIT_TRANSFORM_CANVAS_WIDTH / originalWidth : EDIT_TRANSFORM_CANVAS_HEIGHT / originalHeight; let { cropWidth, cropHeight } = getCropWidthAndHeight(transformObjectState, originalWidth, originalHeight); let displayCropLeft = cropLeft * imageToCanvasScaleFactor; let displayCropTop = cropTop * imageToCanvasScaleFactor; let displayCropWidth = cropWidth * imageToCanvasScaleFactor; let displayCropHeight = cropHeight * imageToCanvasScaleFactor; let cropCenteredXPos = centeredXPos + displayCropLeft; let cropCenteredYPos = centeredYPos + displayCropTop; // if 90 or 270 degrees if (rotationFlag === 0 || rotationFlag === 2) { const { cropWidth: newCropWidth, cropHeight: newCropHeight } = getCropWidthAndHeight( transformObjectState, originalHeight, // switched width and height originalWidth, ); cropWidth = newCropWidth; cropHeight = newCropHeight; displayCropLeft = cropLeft * imageToCanvasScaleFactor; displayCropTop = cropTop * imageToCanvasScaleFactor; displayCropWidth = cropWidth * imageToCanvasScaleFactor; displayCropHeight = cropHeight * imageToCanvasScaleFactor; cropCenteredXPos = centeredYPos + displayCropLeft; cropCenteredYPos = centeredXPos + displayCropTop; } ctx.beginPath(); ctx.rect(cropCenteredXPos, cropCenteredYPos, displayCropWidth, displayCropHeight); ctx.lineWidth = 2; ctx.strokeStyle = '#00FF00'; ctx.stroke(); } }); const handleCropDropdownChange = (e, { value }) => { const { rotationFlag } = transformObjectState; console.log(value); setCropDropdownValue(value); let newOriginalWidth = originalWidth; let newOriginalHeight = originalHeight; let newAspectRatio = originalAspectRatioInv; // if 90 or 270 degrees swap width and height and calculate new aspectRatioInv if (rotationFlag === 0 || rotationFlag === 2) { [newOriginalWidth, newOriginalHeight] = [newOriginalHeight, newOriginalWidth]; newAspectRatio = (newOriginalHeight * 1.0) / newOriginalWidth; } if (value === null) { setTransformObjectState({ ...transformObjectState, cropTop: 0, cropBottom: 0, cropLeft: 0, cropRight: 0, }); } else if (value <= newAspectRatio) { const newHeight = value * newOriginalWidth; const cropTopAndBottom = (newOriginalHeight - newHeight) / 2; setTransformObjectState({ ...transformObjectState, cropTop: parseInt(cropTopAndBottom, 10), cropBottom: parseInt(cropTopAndBottom, 10), cropLeft: 0, cropRight: 0, }); } else { const newWidth = newOriginalHeight / value; const cropLeftAndRight = (newOriginalWidth - newWidth) / 2; setTransformObjectState({ ...transformObjectState, cropLeft: parseInt(cropLeftAndRight, 10), cropRight: parseInt(cropLeftAndRight, 10), cropTop: 0, cropBottom: 0, }); } }; const handleAspectRatioDropdownChange = (e, { value }) => { const { rotationFlag } = transformObjectState; const aspectRatioInv = value; console.log(value); setAspectRatioDropdownValue(value); setTransformObjectState({ ...transformObjectState, aspectRatioInv, }); if (aspectRatioInv === null) { setCanvasWidth(EDIT_TRANSFORM_CANVAS_WIDTH); setCanvasHeight(EDIT_TRANSFORM_CANVAS_HEIGHT); } else { const imageToCanvasScaleFactor = originalAspectRatioInv <= 1 ? EDIT_TRANSFORM_CANVAS_WIDTH / originalWidth : EDIT_TRANSFORM_CANVAS_HEIGHT / originalHeight; let { cropWidth, cropHeight } = getCropWidthAndHeight(transformObjectState, originalWidth, originalHeight); // if 90 or 270 degrees if (rotationFlag === 0 || rotationFlag === 2) { const { cropWidth: newCropWidth, cropHeight: newCropHeight } = getCropWidthAndHeight( transformObjectState, originalHeight, // switched width and height originalWidth, ); cropWidth = newCropWidth; cropHeight = newCropHeight; } const displayCropWidth = cropWidth * imageToCanvasScaleFactor; const displayCropHeight = cropHeight * imageToCanvasScaleFactor; const displayCropWidthNew = displayCropHeight / aspectRatioInv; const scaleRatio = displayCropWidthNew / displayCropWidth; const newCanvasWidth = scaleRatio * EDIT_TRANSFORM_CANVAS_WIDTH; const newCanvasHeight = EDIT_TRANSFORM_CANVAS_HEIGHT / scaleRatio; if (scaleRatio <= 1) { setCanvasWidth(newCanvasWidth); setCanvasHeight(EDIT_TRANSFORM_CANVAS_HEIGHT); } else { setCanvasHeight(newCanvasHeight); setCanvasWidth(EDIT_TRANSFORM_CANVAS_WIDTH); } } }; const handleCropInputChange = (e, { name, value }) => { const { cropTop, cropBottom, cropLeft, cropRight, rotationFlag } = transformObjectState; console.log(name); console.log(value); let newValue = parseInt(value, 10); // check for legal cropping values let newOriginalWidth = originalWidth; let newOriginalHeight = originalHeight; // if 90 or 270 degrees swap width and height if (rotationFlag === 0 || rotationFlag === 2) { [newOriginalWidth, newOriginalHeight] = [newOriginalHeight, newOriginalWidth]; } switch (name) { case 'cropLeft': newValue = Math.min(newValue, newOriginalWidth - cropRight - 1); break; case 'cropRight': newValue = Math.min(newValue, newOriginalWidth - cropLeft - 1); break; case 'cropTop': newValue = Math.min(newValue, newOriginalHeight - cropBottom - 1); break; case 'cropBottom': newValue = Math.min(newValue, newOriginalHeight - cropTop - 1); break; default: } setTransformObjectState({ ...transformObjectState, [name]: newValue, }); }; const handleRotationChange = (e, { name, value }) => { console.log(name); console.log(value); if (value === 4) { setTransformObjectState({ ...transformObjectState, [name]: null, }); } else { setTransformObjectState({ ...transformObjectState, [name]: parseInt(value, 10), }); } }; return ( <div onKeyDown={e => e.stopPropagation()} onClick={e => e.stopPropagation()} onFocus={e => e.stopPropagation()} onMouseOver={e => e.stopPropagation()} > <Modal open={showTransformModal} onClose={onClose} closeIcon as={Form} onSubmit={() => onChangeTransform(fileId, transformObjectState)} > <Modal.Header>Set rotation, cropping and aspect ratio</Modal.Header> <Modal.Content image> <Modal.Description> <Grid> <Grid.Row> <Grid.Column width={4}> <Header as="h3">Rotation</Header> <Form.Select name="rotationFlag" // label="Rotation" options={ROTATION_OPTIONS} // placeholder="Select" onChange={handleRotationChange} defaultValue={transformObjectState.rotationFlag} /> <Header as="h3">Crop</Header> <Form.Select name="cropDropdown" label="Crop presets" options={CROP_OPTIONS} placeholder="Select" onChange={handleCropDropdownChange} defaultValue={undefined} value={cropDropdownValue} /> <Form.Group widths="equal"> <Form.Input name="cropTop" label="From top" placeholder="top" required type="number" min="0" width={4} value={transformObjectState.cropTop} onChange={handleCropInputChange} /> <Form.Input name="cropBottom" label="From bottom" placeholder="bottom" required type="number" min="0" width={4} value={transformObjectState.cropBottom} onChange={handleCropInputChange} /> </Form.Group> <Form.Group widths="equal"> <Form.Input name="cropLeft" label="From left" placeholder="left" required type="number" width={4} value={transformObjectState.cropLeft} onChange={handleCropInputChange} /> <Form.Input name="cropRight" label="From right" placeholder="right" required type="number" min="0" width={4} value={transformObjectState.cropRight} onChange={handleCropInputChange} /> </Form.Group> <Header as="h3">Aspect ratio</Header> <Form.Select name="aspectRatio" // label="Rotation" options={ASPECT_RATIO_OPTIONS} placeholder="Select" onChange={handleAspectRatioDropdownChange} value={aspectRatioDropdownValue} /> </Grid.Column> <Grid.Column width={12} color="black" className={styles.editTransformCanvasContainer}> <canvas ref={canvasRef} className={styles.editTransformCanvas} width={EDIT_TRANSFORM_CANVAS_WIDTH} height={EDIT_TRANSFORM_CANVAS_HEIGHT} style={{ width: `${canvasWidth}px`, height: `${canvasHeight}px`, }} /> </Grid.Column> </Grid.Row> </Grid> </Modal.Description> </Modal.Content> <Modal.Actions> <span className={styles.smallInfo}>All thumbs of this movie will be updated. This can take a bit.</span> <Button type="submit" content="Update transform" /> </Modal.Actions> </Modal> </div> ); }; export default EditTransformModal; <|start_filename|>app/utils/utilsForOpencv.js<|end_filename|> import log from 'electron-log'; import { VideoCaptureProperties, ImwriteFlags, RotateFlags } from './openCVProperties'; import { getCropWidthAndHeight, setPosition } from './utils'; import { DEFAULT_THUMB_JPG_QUALITY, DEFAULT_THUMB_FORMAT, OUTPUT_FORMAT, SHOT_DETECTION_METHOD, TRANSFORMOBJECT_INIT } from './constants'; import // updateFrameBase64, './utilsForSqlite'; const opencv = require('opencv4nodejs'); const { ipcRenderer } = require('electron'); export const recaptureThumbs = ( frameSize, fileId, filePath, useRatio, frameIdArray, frameNumberArray, onlyReplace, transformObject = TRANSFORMOBJECT_INIT, ) => { try { const vid = new opencv.VideoCapture(filePath); const cropRect = getCropRect(vid, transformObject); for (let i = 0; i < frameNumberArray.length; i += 1) { const frameNumber = frameNumberArray[i]; setPosition(vid, frameNumber, useRatio); const mat = vid.read(); const frameId = frameIdArray[i]; if (mat.empty) { log.info('opencvWorkerWindow | frame is empty'); ipcRenderer.send( 'message-from-opencvWorkerWindow-to-databaseWorkerWindow', 'send-base64-frame', frameId, fileId, frameNumber, '', onlyReplace, ); } else { // optional transform const matTransformed = transformMat(mat, transformObject, cropRect); // optional resize using resizeToMax const matResult = resizeMatToMax(vid, matTransformed, frameSize); // opencv.imshow('matRescaled', matRescaled); const outBase64 = opencv.imencode('.jpg', matResult).toString('base64'); // for internal usage frame jpg is used ipcRenderer.send( 'message-from-opencvWorkerWindow-to-databaseWorkerWindow', 'send-base64-frame', frameId, fileId, frameNumber, outBase64, onlyReplace, ); } } } catch (e) { log.error(e); } }; export const getBase64Object = ( filePath, useRatio, arrayOfThumbs, frameSize = 0, transformObject = TRANSFORMOBJECT_INIT, thumbFormatObject = undefined, useAspectRatio = false, ) => { try { const vid = new opencv.VideoCapture(filePath); const cropRect = getCropRect(vid, transformObject); const objectUrlObjects = {}; arrayOfThumbs.map(thumb => { setPosition(vid, thumb.frameNumber, useRatio); const mat = vid.read(); let base64 = ''; if (!mat.empty) { // optional transform const matTransformed = transformMat(mat, transformObject, cropRect); // optional resize using resizeToMax const matRescaled = resizeMatToMax(vid, matTransformed, frameSize); // optional resize due to aspectRatioInv const matResult = resizeMat(vid, matRescaled, transformObject, useAspectRatio); let fileFormat = DEFAULT_THUMB_FORMAT; let encodingFlags = []; // default for png quality 1 (lossless - best speed setting), default for jpg -> 95% quality // https://justadudewhohacks.github.io/opencv4nodejs/docs/cv#imencode // https://docs.opencv.org/3.4.9/d4/da8/group__imgcodecs.html if (thumbFormatObject !== undefined) { const { defaultThumbFormat = DEFAULT_THUMB_FORMAT, defaultThumbJpgQuality = DEFAULT_THUMB_JPG_QUALITY, } = thumbFormatObject; fileFormat = defaultThumbFormat; if (fileFormat === OUTPUT_FORMAT.JPG) { encodingFlags = [ImwriteFlags.IMWRITE_JPEG_QUALITY, defaultThumbJpgQuality]; // 1 for IMWRITE_JPEG_QUALITY } } base64 = opencv.imencode(`.${fileFormat}`, matResult, encodingFlags).toString('base64'); } else { log.debug('getBase64Object | frame is empty'); } objectUrlObjects[thumb.frameId] = base64; return undefined; }); return objectUrlObjects; } catch (e) { log.error(e); } }; export const getDominantColor = (image, k = 4) => { // takes an image as input // returns the dominant color of the image as a list // // dominant color is found by running k means on the // pixels & returning the centroid of the largest cluster // // processing time is sped up by working with a smaller image; // this resizing can be done with the imageProcessingSize param // which takes a tuple of image dims as input // // >>> get_dominant_color(my_image, k=4, imageProcessingSize = (25, 25)) // [56.2423442, 34.0834233, 70.1234123] const matAsArray = image.getDataAsArray(); const njArray = nj.array(matAsArray); const reshapedArray = njArray.reshape(matAsArray.rows * matAsArray.cols, 3); const { labels, centers } = opencv.kmeans( [ new opencv.Vec3(255, 0, 0), new opencv.Vec3(255, 0, 0), new opencv.Vec3(255, 0, 255), new opencv.Vec3(255, 0, 255), new opencv.Vec3(255, 255, 255), ], 2, new opencv.TermCriteria(opencv.termCriteria.EPS | opencv.termCriteria.MAX_ITER, 10, 0.1), 5, opencv.KMEANS_RANDOM_CENTERS, ); // // count labels to find most popular // label_counts = Counter(labels) // // // subset out most popular centroid // dominant_color = clt.cluster_centers_[label_counts.most_common(1)[0][0]] // // return list(dominant_color) }; export const HSVtoRGB = (h, s, v) => { // console.log(`h: ${h}, s: ${s}, v: ${v}`); let r; let g; let b; const i = Math.floor((h / 180) * 6); const f = (h / 180) * 6 - i; const p = (v / 255) * (1 - s / 255); const q = (v / 255) * (1 - f * (s / 255)); const t = (v / 255) * (1 - (1 - f) * (s / 255)); switch (i % 6) { case 0: (r = v / 255), (g = t), (b = p); break; case 1: (r = q), (g = v / 255), (b = p); break; case 2: (r = p), (g = v / 255), (b = t); break; case 3: (r = p), (g = q), (b = v / 255); break; case 4: (r = t), (g = p), (b = v / 255); break; case 5: (r = v / 255), (g = p), (b = q); break; default: break; } const rgbArray = [Math.round(r * 255), Math.round(g * 255), Math.round(b * 255)]; // console.log(rgbArray); return rgbArray; }; // export const hsvToHsl = (h, s, v) => { // // // // does not work!!!!!! // // results are wrong // // // // both hsv and hsl values are in [0, 1] // const l = (2 - s) * v / 2; // let newS; // if (l !== 0) { // if (l === 1) { // newS = 0 // } else if (l < 0.5) { // newS = s * v / (l * 2) // } else { // newS = s * v / (2 - l * 2) // } // } // return [h, newS, l] // } export const detectCut = (previousData, currentFrame, threshold, method) => { switch (method) { case SHOT_DETECTION_METHOD.MEAN: { // resize and convert to HSV const convertedFrame = currentFrame.resizeToMax(240).cvtColor(opencv.COLOR_BGR2HSV); const frameMean = convertedFrame.mean(); const colorArray = HSVtoRGB(frameMean.w, frameMean.x, frameMean.y); const { lastValue = new opencv.Vec(null, null, null, null) } = previousData; const deltaFrameMean = frameMean.absdiff(lastValue); const differenceValue = deltaFrameMean.y; const isCut = differenceValue >= threshold; return { isCut, // lastValue: meanValue, differenceValue, lastColorRGB: colorArray, lastValue: frameMean, }; // log.error('no previousData detected'); } case SHOT_DETECTION_METHOD.HIST: { // resize and convert to HSV const resizedFrame = currentFrame.resizeToMax(240); const convertedFrame = resizedFrame.cvtColor(opencv.COLOR_BGR2HSV); const frameMean = resizedFrame.mean(); const lastColorRGB = [frameMean.y, frameMean.x, frameMean.w]; const { lastValue } = previousData; // all axes for 3D hist const getAllAxes = () => [ { channel: 0, bins: 32, ranges: [0, 256], }, { channel: 1, bins: 32, ranges: [0, 256], }, { channel: 2, bins: 32, ranges: [0, 256], }, ]; // get combined histogram for all channels const vHist = opencv.calcHist(convertedFrame, getAllAxes()).convertTo(opencv.CV_32F); const vHistNormalized = vHist.normalize(); // when lastValue is undefined (when run for the first time) compare to itself const differenceValue = vHistNormalized.compareHist(lastValue || vHistNormalized, opencv.HISTCMP_CHISQR_ALT); // const blue = new opencv.Vec(255, 0, 0); // const green = new opencv.Vec(0, 255, 0); // const red = new opencv.Vec(0, 0, 255); // // // plot channel histograms // const plot = new opencv.Mat(300, 600, opencv.CV_8UC3, [255, 255, 255]); // opencv.plot1DHist(vHist, plot, blue, opencv.LINE_8, 2); // // // opencv.imshow('rgb image', currentFrame); // opencv.imshow('hsv image', convertedFrame); // opencv.imshow('hsv histogram', plot); // opencv.waitKey(); const isCut = differenceValue >= threshold; return { isCut, lastValue: vHistNormalized, differenceValue, lastColorRGB, }; // log.error('no previousData detected'); } default: } }; export const transformMat = (mat, transformObject, cropRect) => { // optional transform let matTransformed = mat; // getCropWidthAndHeight const { rotationFlag = RotateFlags.NO_ROTATION } = transformObject; // first rotate if necessary let matRotated = mat; if (rotationFlag !== RotateFlags.NO_ROTATION) { matRotated = matTransformed.rotate(rotationFlag); } matTransformed = matRotated; if (cropRect !== undefined) { matTransformed = matRotated.getRegion(cropRect); } return matTransformed; }; export const resizeMatToMax = (vid, mat, frameSize) => { // optional resize using resizeToMax let matResizedToMax = mat; if (frameSize !== 0) { // 0 stands for keep original size matResizedToMax = mat.resizeToMax(frameSize); } return matResizedToMax; }; export const resizeMat = (vid, mat, transformObject, useAspectRatio) => { // optional resize using resize const { aspectRatioInv = null } = transformObject; if (useAspectRatio && aspectRatioInv !== null) { let width = mat.cols; let height = mat.rows; if (aspectRatioInv <= 1) { height = width * aspectRatioInv; } else { width = height * aspectRatioInv; } const matResized = mat.resize(Math.round(height), Math.round(width)); return matResized; } return mat; }; export const getVideoWidthAndHeightDependingOnRotation = (vid, rotationFlag) => { // swap width and height for possible cropping, if rotation is 90 or 270 degrees let videoWidth = vid.get(VideoCaptureProperties.CAP_PROP_FRAME_WIDTH); let videoHeight = vid.get(VideoCaptureProperties.CAP_PROP_FRAME_HEIGHT); if (rotationFlag === RotateFlags.ROTATE_90_CLOCKWISE || rotationFlag === RotateFlags.ROTATE_90_COUNTERCLOCKWISE) { [videoWidth, videoHeight] = [videoHeight, videoWidth]; // swapping of width and height } return { videoWidth, videoHeight, }; }; // mutable function export const getCropRect = (vid, transformObject) => { // add isCroppingNeeded let cropRect; const { cropTop = 0, cropLeft = 0, cropBottom = 0, cropRight = 0 } = transformObject; const isCroppingNeeded = cropTop > 0 || cropLeft > 0 || cropBottom > 0 || cropRight > 0; if (isCroppingNeeded) { // get videoWidth and videoHeight depending on rotation const { videoWidth, videoHeight } = getVideoWidthAndHeightDependingOnRotation(vid, transformObject.rotationFlag); const { cropWidth, cropHeight } = getCropWidthAndHeight(transformObject, videoWidth, videoHeight); cropRect = new opencv.Rect(cropLeft, cropTop, cropWidth, cropHeight); } return cropRect; }; <|start_filename|>app/utils/db.js<|end_filename|> import Dexie from 'dexie'; import log from 'electron-log'; // import FileObject from './fileObject'; // Force debug mode to get async stacks from exceptions. if (process.env.NODE_ENV === 'production') { Dexie.debug = false; } else { Dexie.debug = true; // In production, set to false to increase performance a little. } const imageDB = new Dexie('ImageDatabase'); imageDB.version(1).stores({ frameList: '&frameId, fileId, frameNumber, [fileId+frameNumber]', // fileScanList: '&fileId', }); const FileObject = imageDB.frameList.defineClass({ frameId: String, fileId: String, frameNumber: Number, data: Blob }); FileObject.prototype.objectUrl = ''; FileObject.prototype.getObjectUrl2 = () => { console.log(this); const objectUrl = window.URL.createObjectURL(this.data); return objectUrl; }; FileObject.prototype.getObjectUrl = () => { if (this.objectUrl !== '' && !this.disposed) { return this.objectUrl; } if (!this.disposed) { this.objectUrl = window.URL.createObjectURL(this.data); return this.objectUrl; } log.warn('File disposed!'); throw 'File disposed!'; }; FileObject.prototype.revokeObjectURL = () => { URL.revokeObjectURL(this.objectUrl); this.objectUrl = ''; }; FileObject.prototype.disposed = false; FileObject.prototype.disposeData = () => { URL.revokeObjectURL(this.objectUrl); this.objectUrl = ''; this.data = null; this.disposed = true; }; export default imageDB; <|start_filename|>app/components/VideoPlayer.css<|end_filename|> .player { /* position: absolute; top: 0; left: 0; right: 0; bottom: 6rem; */ background: #1e1e1e; } .video { /* width: 100%; height: 100%; */ object-fit: contain; } .videoOverlay { position: absolute; transform-origin: center bottom; transform: translate(-50%, 0%); top: 0; left: 50%; width: 640px; object-fit: contain; background-color: rgba(0,0,0,0.8); /* Black w/ opacity */ z-index: 2; } .frameNumberOrTimeCode { position: absolute; top: 0; left: 0; background: #eee; border-radius:2px; font-family: 'Open sans'; font-size: 14px; line-height: 14px; padding: 1px; color: #000000; -webkit-user-select:none; z-index: 3; } .moveToMiddle { left: 50%; } .controlsWrapper button, .rightMenu button, .leftMenu button { /* background: black; */ border-radius: .3em; /* color: rgba(0, 0, 0, 0.7); */ fontSize: 60%; vertical-align: middle; /* padding: .2em .4em; */ /* margin: 0 .5em; */ border: none; } .controlsWrapper { left: 0; right: 0; bottom: 0; /* height: 5.75rem; */ /* background: #6b6b6b; */ text-align: center; margin-top: 4px; } #currentTimeDisplay { text-align: center; color: rgba(255, 255, 255, 0.3); /* padding: .5em; */ } .buttonWrapper { width: 100%; position: relative; /* background-color: #444; */ height: 32px; margin-top: 4px; padding: 4px; } .overVideoButtonWrapper { width: 100%; position: absolute; transform: translate(0%, -100%); height: 36px; /* background-color: rgba(0, 0, 0, 0.05); */ } .hoverButton { border: 0; cursor: pointer; background-color: transparent; outline:none; -webkit-user-select:none; } .inPoint { position: absolute; bottom: 0; left: 0; opacity: 0.5; } .outPoint { position: absolute; bottom: 0; right: 0; opacity: 0.5; } .choose { position: absolute; bottom: 0; /* left: calc(50% - 24px); */ /* top: 50%; */ left: 50%; transform: translate(-50%, 0%); opacity: 0.5; /* cursor: col-resize; */ } .previousScene { position: absolute; bottom: 0; left: 30%; transform-origin: center bottom; transform: translate(-100%, 0%); opacity: 0.5; } .nextScene { position: absolute; bottom: 0; right: 28%; transform-origin: center bottom; transform: translate(50%, 0%); opacity: 0.5; } .hundredFramesBack { position: absolute; bottom: 0; left: 35%; transform-origin: center bottom; transform: translate(-50%, 0%); opacity: 0.5; } .tenFramesBack { position: absolute; bottom: 0; left: 40%; transform-origin: center bottom; transform: translate(-50%, 0%); opacity: 0.5; } .oneFrameBack { position: absolute; bottom: 0; left: 44%; transform-origin: center bottom; transform: translate(-50%, 0%); opacity: 0.5; } .hundredFramesForward { position: absolute; bottom: 0; right: 35%; transform-origin: center bottom; transform: translate(-50%, 0%); opacity: 0.5; } .tenFramesForward { position: absolute; bottom: 0; right: 40%; transform-origin: center bottom; transform: translate(-50%, 0%); opacity: 0.5; } .oneFrameForward { position: absolute; bottom: 0; right: 44%; transform-origin: center bottom; transform: translate(-50%, 0%); opacity: 0.5; } .html5Button { position: absolute; top: 0; left: 0; margin-top: 8px; margin-left: 8px; z-Index: 1; } .saveFrameButton { position: absolute; bottom: 92px; left: 50%; margin-top: 8px; margin-right: 8px; z-Index: 1; } .centerTheButton { transform: translate(-50%, 0%); } .backButton { position: absolute; top: 0; right: 0; margin-top: 8px; margin-right: 8px; z-Index: 1; } .cutMergeButton { position: absolute; bottom: 0; left: 50%; transform-origin: center bottom; transform: translateX(-60%); /* display: block; */ } .changeModeButton { position: absolute; bottom: 0; left: 0; margin-left: 8px; } .textButton { font-family: 'Franchise', 'Roboto Condensed'; color: #ffffff; font-size: 30px; opacity: 0.5; -webkit-user-select:none; /* text-shadow: 1px 1px 80px rgba(0,0,0,0.6); */ } .noVideoText { position: absolute; top: 30%; left: 50%; transform-origin: center center; transform: translateX(-50%); z-Index: 1; } <|start_filename|>app/containers/VisibleSceneGrid.js<|end_filename|> import React, { Component } from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import { arrayMove } from 'react-sortable-hoc'; import scrollIntoView from 'scroll-into-view'; import { toggleThumb, updateOrder, changeThumb, toggleScene, toggleSceneArray } from '../actions'; import styles from '../components/ThumbGrid.css'; import SortableSceneGrid from '../components/SceneGrid'; import { getLowestFrame, getHighestFrame } from '../utils/utils'; import { CHANGE_THUMB_STEP } from '../utils/constants'; class SortedVisibleSceneGrid extends Component { constructor(props) { super(props); this.state = { }; this.scrollIntoViewElement = React.createRef(); this.scrollThumbIntoView = this.scrollThumbIntoView.bind(this); this.onSelectClick = this.onSelectClick.bind(this); this.onDeselectClick = this.onDeselectClick.bind(this); } componentDidMount() { setTimeout(() => { this.scrollThumbIntoView(); }, 500); } componentDidUpdate(prevProps) { if (prevProps.selectedThumbsArray.length !== 0 && this.props.selectedThumbsArray.length !== 0 && (prevProps.selectedThumbsArray[0].thumbId !== this.props.selectedThumbsArray[0].thumbId)) { this.scrollThumbIntoView(); } // delay when switching to gridView so it waits for the sheetView to be ready if ((prevProps.view !== this.props.view) && prevProps.view) { setTimeout(() => { this.scrollThumbIntoView(); }, 500); } } onSelectClick = (sceneId, frameNumber) => { this.props.onSelectThumbMethod(sceneId, frameNumber); } onDeselectClick = () => { console.log('deselect') this.props.onDeselectThumbMethod(); } scrollThumbIntoView = () => { if (this.scrollIntoViewElement && this.scrollIntoViewElement.current !== null) { scrollIntoView(this.scrollIntoViewElement.current, { time: 300, align: { left: 0.5, } }); } }; render() { return ( <SortableSceneGrid useBase64={this.props.useBase64} sheetView={this.props.sheetView} view={this.props.view} sheetType={this.props.sheetType} currentSheetId={this.props.currentSheetId} file={this.props.file} inputRefThumb={this.scrollIntoViewElement} // for the thumb scrollIntoView function frameCount={this.props.file ? this.props.file.frameCount : undefined} keyObject={this.props.keyObject} onAddThumbClick={this.props.onAddThumbClick} onJumpToCutSceneClick={this.props.onJumpToCutSceneClick} onBackClick={this.props.onBackClick} onForwardClick={this.props.onForwardClick} onInPointSceneClick={this.props.onInPointSceneClick} onOutPointSceneClick={this.props.onOutPointSceneClick} onSaveThumbClick={this.props.onSaveThumbClick} onThumbDoubleClick={this.props.onThumbDoubleClick} onScrubClick={this.props.onScrubClick} onSelectClick={this.onSelectClick} onDeselectClick={this.onDeselectClick} onExpandClick={this.props.onExpandClick} onToggleClick={this.props.onToggleClick} onHideBeforeAfterClick={this.props.onHideBeforeAfterClick} minSceneLength={this.props.settings.defaultTimelineViewMinDisplaySceneLengthInFrames} scaleValueObject={this.props.scaleValueObject} scenes={this.props.scenes} selectedThumbsArray={this.props.selectedThumbsArray} settings={this.props.settings} showMovielist={this.props.showMovielist} showSettings={this.props.showSettings} thumbCount={this.props.thumbCount} objectUrlObjects={this.props.objectUrlObjects} thumbs={this.props.thumbs} useDragHandle axis="xy" distance={1} helperClass={styles.whileDragging} onSortEnd={this.props.onSortEnd} /> ); } } const mapStateToProps = state => ({}); const mapDispatchToProps = (dispatch, ownProps) => { return { onSortEnd: ({ oldIndex, newIndex }) => { const { settings, sheetsByFileId } = ownProps; const newOrderedThumbs = arrayMove(sheetsByFileId[settings.currentFileId][settings.currentSheetId].thumbsArray, oldIndex, newIndex); dispatch(updateOrder( settings.currentFileId, settings.currentSheetId, newOrderedThumbs)); }, onToggleClick: (fileId, sceneId) => { dispatch(toggleScene(fileId, ownProps.settings.currentSheetId, sceneId)); }, onHideBeforeAfterClick: (fileId, sheetId, thumbIdArray) => { dispatch(toggleSceneArray( fileId, sheetId, thumbIdArray )); }, }; }; SortedVisibleSceneGrid.contextTypes = { }; SortedVisibleSceneGrid.defaultProps = { selectedThumbsArray: [], }; SortedVisibleSceneGrid.propTypes = { selectedThumbsArray: PropTypes.array, }; export default connect(mapStateToProps, mapDispatchToProps)(SortedVisibleSceneGrid); <|start_filename|>app/store/configureStore.prod.js<|end_filename|> // @flow import { createStore, applyMiddleware } from 'redux'; import thunk from 'redux-thunk'; import { createHashHistory } from 'history'; import { routerMiddleware } from 'connected-react-router'; import throttle from 'lodash/throttle'; import rootReducer from '../reducers'; import { loadState, saveState } from './localStorage'; const history = createHashHistory(); const router = routerMiddleware(history); const enhancer = applyMiddleware(thunk, router); function configureStore(initialState) { let persistedState; if (initialState === undefined) { persistedState = loadState(); } else { persistedState = initialState; } // Create Store const store = createStore(rootReducer, persistedState, enhancer); // eslint-disable-line store.subscribe(throttle(() => { saveState(store.getState()); // // only store thumbs in localStorage // saveState({ // thumbs: store.getState().thumbs // }); }, 1000)); return store; } export default { configureStore, history }; <|start_filename|>app/utils/utils.js<|end_filename|> import pathR from 'path'; import fsR from 'fs'; import log from 'electron-log'; import sanitize from 'sanitize-filename'; import { VideoCaptureProperties } from './openCVProperties'; import sheetNames from '../img/listOfNames.json'; import { SCENE_DETECTION_MIN_SCENE_LENGTH, SHEET_TYPE, SHEET_VIEW, THUMB_SELECTION, TRANSFORMOBJECT_INIT, VIDEOPLAYER_CUTGAP, VIDEOPLAYER_SLICEGAP, } from './constants'; const randomColor = require('randomcolor'); const { app } = require('electron').remote; export const doesFileFolderExist = fileName => { return fsR.existsSync(fileName); }; export const getFileStatsObject = filename => { if (doesFileFolderExist(filename) === false) { return undefined; } const stats = fsR.statSync(filename); const { mtime, size } = stats; return { size, lastModified: Date.parse(mtime), }; }; export const ensureDirectoryExistence = (filePath, isDirectory = true) => { let dirname; if (isDirectory) { dirname = filePath; } else { dirname = pathR.dirname(filePath); } // log.debug(dirname); if (doesFileFolderExist(dirname)) { return true; } ensureDirectoryExistence(dirname, false); fsR.mkdirSync(dirname); }; // prevent typeerrors when accessing nested props of a none-existing object // usage getObjectProperty(() => objectA.propertyB) export const getObjectProperty = fn => { let value; try { value = fn(); return value; } catch (e) { value = undefined; return value; } }; export const mapRange = (value, low1, high1, low2, high2, returnInt = true) => { // special case, prevent division by 0 if (high1 - low1 === 0) { return 0; } // * 1.0 added to force float division let newValue = low2 + (high2 - low2) * (((value - low1) * 1.0) / (high1 - low1)); newValue = Math.round(newValue * 1000 + Number.EPSILON) / 1000; // rounds the number with 3 decimals let limitedNewValue = Math.min(Math.max(newValue, low2), high2); if (returnInt) { limitedNewValue = Math.round(limitedNewValue); } return limitedNewValue; }; export const limitRange = (value, lowerLimit, upperLimit) => // value || 0 makes sure that NaN s are turned into a number to work with Math.min(Math.max(value || 0, lowerLimit || 0), upperLimit || 0); export const truncate = (n, len) => { const ext = n.substring(n.lastIndexOf('.') + 1, n.length).toLowerCase(); let filename = n.substring(0, n.lastIndexOf('.')); if (filename.length <= len) { return n; } filename = filename.substr(0, len) + (n.length > len ? '...' : ''); return `${filename}.${ext}`; }; export const truncatePath = (n, len) => { // check if length of string is actually longer than truncate length // if not return the original string without truncation // value of 3 compensates for ... (the 3 dots) if (n.length - 3 > len) { const front = n.slice(0, len / 2 - 1); // compensate for dots const back = n.slice(-len / 2 - 2); // compensate for dots return `${front}...${back}`; } return n; }; export const pad = (num, size) => { if (size !== undefined) { let s = num !== undefined ? num.toString() : ''; while (s.length < size) s = `${num !== undefined ? '0' : '–'}${s}`; return s; } return undefined; }; export const secondsToFrameCount = (seconds = 0, fps = 25) => { const frames = Math.round(seconds * fps * 1.0); return frames; }; export const frameCountToSeconds = (frames, fps = 25) => { const seconds = frames !== undefined ? (frames * 1.0) / fps : 0; return seconds; }; export const frameCountToMinutes = (frames, fps = 25) => { const seconds = frames !== undefined ? (frames * 1.0) / (fps * 60) : 0; return seconds; }; export const frameCountToTimeCode = (frames, fps = 25, separator = ':') => { // fps = (fps !== undefined ? fps : 30); if (frames !== undefined) { const paddedValue = input => (input < 10 ? `0${input}` : input); const seconds = frames !== undefined ? frames / fps : 0; return [ paddedValue(Math.floor(seconds / 3600)), paddedValue(Math.floor((seconds % 3600) / 60)), paddedValue(Math.floor(seconds % 60)), paddedValue(Math.floor(frames % fps)), ].join(separator); } return `––${separator}––${separator}––${separator}––`; }; export const secondsToTimeCode = (seconds = 0, fps = 25) => { const pad = input => (input < 10 ? `0${input}` : input); return [ pad(Math.floor(seconds / 3600)), pad(Math.floor((seconds % 3600) / 60)), pad(Math.floor(seconds % 60)), pad(Math.floor((seconds * fps) % fps)), // pad(Math.floor((seconds - Math.floor(seconds)) * 1000), 3, '0') ].join(':'); }; export const formatBytes = (bytes, decimals = 1) => { if (bytes === 0) return '0 Bytes'; const k = 1024; const dm = decimals || 2; const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']; const i = Math.floor(Math.log(bytes) / Math.log(k)); // return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i]; return `${parseFloat((bytes / k ** i).toFixed(dm))} ${sizes[i]}`; }; export const getMimeType = outputFormat => { switch (outputFormat) { case 'png': return 'image/png'; case 'jpg': return 'image/jpeg'; default: return 'image/png'; } }; export const getMoviePrintColor = count => { // log.debug(`creating new newColorArray[${count}]`); const newColorArray = randomColor({ count, hue: '#FF5006', }); return newColorArray; }; export const typeInTextarea = (el, textToAdd) => { const start = el.selectionStart; const end = el.selectionEnd; const text = el.value; const before = text.substring(0, start); const after = text.substring(end, text.length); const newText = (el.value = before + textToAdd + after); el.selectionStart = el.selectionEnd = start + textToAdd.length; el.focus(); return newText; }; const fillTemplate = function(templateString, templateVars) { return new Function(`return \`${templateString}\`;`).call(templateVars); }; export const getCustomFileName = (fileName, sheetName, frameNumber, fileNameTemplate, fps = 25) => { const paddedFrameNumber = frameNumber === undefined ? '' : pad(frameNumber, 6); const timeCode = frameNumber === undefined ? '' : frameCountToTimeCode(frameNumber, fps, '_'); const movieName = pathR.parse(fileName).name; const movieExtension = pathR.parse(fileName).ext.substr(1); // remove dot from extension try { // prepare fileNameTemplate const mapObj = { '[MN]': '${this.movieName}', '[ME]': '${this.movieExtension}', '[MPN]': '${this.moviePrintName}', '[FN]': '${this.paddedFrameNumber}', '[TC]': '${this.timeCode}', }; const preparedFileNameTemplate = fileNameTemplate.replace(/\[MN\]|\[ME\]|\[MPN\]|\[FN\]|\[TC\]/gi, function(matched) { return mapObj[matched]; }); // fill fileNameTemplate with parameters const templateVars = { movieName, movieExtension, moviePrintName: sheetName, paddedFrameNumber, timeCode, }; const customFileName = fillTemplate(preparedFileNameTemplate, templateVars); const validFilename = customFileName.replace(/[/\\?%*:|"<>]/g, '-'); return validFilename; } catch (e) { log.error(e); return undefined; } }; export const getFilePathObject = ( fileName, sheetName, frameNumber, fileNameTemplate, outputFormat, // exportPath = '', exportPath = app.getPath('desktop'), overwrite = false, fps = 25, ) => { const validFilename = getCustomFileName(fileName, sheetName, frameNumber, fileNameTemplate, fps); if (validFilename !== undefined) { let newFilePathAndName = pathR.join(exportPath, `${validFilename}.${outputFormat}`); if (!overwrite) { if (doesFileFolderExist(newFilePathAndName)) { for (let i = 1; i < 1000; i += 1) { newFilePathAndName = pathR.join(exportPath, `${validFilename} edit ${i}.${outputFormat}`); if (doesFileFolderExist(newFilePathAndName) === false) { break; } } } } return pathR.parse(newFilePathAndName); } // validFilename === undefined, return default name const standardFilePathAndName = pathR.join(exportPath, `MoviePrint.${outputFormat}`); return pathR.parse(standardFilePathAndName); }; export const getThumbInfoValue = (type, frames, framesPerSecond) => { switch (type) { case 'frames': return pad(frames, 4); case 'timecode': return frameCountToTimeCode(frames, framesPerSecond); case 'hideInfo': return undefined; default: return undefined; } }; export const getLowestFrame = thumbs => { if (thumbs && thumbs.length > 0) { return thumbs.reduce((min, p) => (p.frameNumber < min ? p.frameNumber : min), thumbs[0].frameNumber); } return undefined; }; export const getHighestFrame = thumbs => { if (thumbs && thumbs.length > 0) { return thumbs.reduce((max, p) => (p.frameNumber > max ? p.frameNumber : max), thumbs[0].frameNumber); } return undefined; }; export const getAllFrameNumbers = thumbs => { if (thumbs && thumbs.length > 0) { return thumbs.map(thumb => thumb.frameNumber); } return []; }; export const getLowestFrameFromScenes = scenes => { if (scenes && scenes.length > 0) { return scenes.reduce((min, p) => (p.start < min ? p.start : min), scenes[0].start); } return undefined; }; export const getHighestFrameFromScenes = scenes => { if (scenes && scenes.length > 0) { return scenes.reduce( (max, p) => (p.start + p.length - 1 > max ? p.start + p.length - 1 : max), scenes[0].start + scenes[0].length - 1, ); } return undefined; }; export const getPreviousScenes = (scenes, sceneId) => { if (scenes) { if (sceneId) { // get index of array as scene does not have an own index const currentIndex = scenes.findIndex(scene => scene.sceneId === sceneId); return scenes.filter( (scene, index) => (scene.hidden === false || scene.hidden === undefined) && index < currentIndex, ); } return scenes; // return last item if no sceneId provided } return undefined; // return undefined if no scenes provided }; export const getNextScenes = (scenes, sceneId) => { if (scenes) { if (sceneId) { // get index of array as scene does not have an own index const currentIndex = scenes.findIndex(scene => scene.sceneId === sceneId); return scenes.filter( (scene, index) => (scene.hidden === false || scene.hidden === undefined) && index > currentIndex, ); } return scenes; // return last item if no sceneId provided } return undefined; // return undefined if no thumbs provided }; export const getInvertedThumbs = (thumbs, thumbId) => { if (thumbs) { if (thumbId) { // get index of thumb return thumbs.filter( thumb => (thumb.hidden === false || thumb.hidden === undefined) && thumb.thumbId !== thumbId, ); } return thumbs; // return last item if no thumbId provided } return undefined; // return undefined if no thumbs provided }; export const getPreviousThumbs = (thumbs, thumbId) => { if (thumbs) { if (thumbId) { // get index of thumb const currentIndex = thumbs.find(thumb => thumb.thumbId === thumbId).index; return thumbs.filter( thumb => (thumb.hidden === false || thumb.hidden === undefined) && thumb.index < currentIndex, ); } return thumbs; // return last item if no thumbId provided } return undefined; // return undefined if no thumbs provided }; export const getNextThumbs = (thumbs, thumbId) => { if (thumbs) { if (thumbId) { // get index of thumb const currentIndex = thumbs.find(thumb => thumb.thumbId === thumbId).index; return thumbs.filter( thumb => (thumb.hidden === false || thumb.hidden === undefined) && thumb.index > currentIndex, ); } return thumbs; // return last item if no thumbId provided } return undefined; // return undefined if no thumbs provided }; export const getPreviousThumb = (thumbs, thumbId, filter = THUMB_SELECTION.ALL_THUMBS) => { if (thumbs) { if (thumbId) { // get index of thumb const thumbsToUse = getVisibleThumbs(thumbs, filter); const currentIndex = thumbsToUse.findIndex(thumb => thumb.thumbId === thumbId); const foundThumb = thumbsToUse[currentIndex]; if (foundThumb === undefined) { return thumbsToUse[thumbsToUse.length - 1]; // return last item if no thumb found } const newIndex = currentIndex - 1 >= 0 ? currentIndex - 1 : thumbsToUse.length - 1; // log.debug(thumbs[newIndex]); return thumbsToUse[newIndex]; } return thumbs[thumbs.length - 1]; // return last item if no thumbId provided } return undefined; // return undefined if no thumbs provided }; // use filter to get for example next visible thumb export const getNextThumb = (thumbs, thumbId, filter = THUMB_SELECTION.ALL_THUMBS) => { if (thumbs) { if (thumbId) { // get index of thumb const thumbsToUse = getVisibleThumbs(thumbs, filter); const currentIndex = thumbsToUse.findIndex(thumb => thumb.thumbId === thumbId); const foundThumb = thumbsToUse[currentIndex]; if (foundThumb === undefined) { return thumbsToUse[0]; // return first item if no thumb found } const newIndex = currentIndex + 1 < thumbsToUse.length ? currentIndex + 1 : 0; // log.debug(thumbsToUse[newIndex]); return thumbsToUse[newIndex]; } return thumbs[0]; // return first item if no thumbId provided } return undefined; // return undefined if no thumbs provided }; export const getVisibleThumbs = (thumbs, filter) => { if (thumbs === undefined) { return thumbs; } switch (filter) { case THUMB_SELECTION.ALL_THUMBS: return thumbs; case THUMB_SELECTION.HIDDEN_THUMBS: return thumbs.filter(t => t.hidden); case THUMB_SELECTION.VISIBLE_THUMBS: return thumbs.filter(t => !t.hidden); default: return thumbs; } }; export const getAspectRatio = file => { if (file === undefined || file.width === undefined || file.height === undefined) { return (16 * 1.0) / 9; // default 16:9 } return (file.width * 1.0) / file.height; }; export const getRandomSheetName = () => { // return random name from sheetNames array const randomNameObject = sheetNames[Math.floor(Math.random() * sheetNames.length)]; return randomNameObject.fullName; }; export const getNewSheetName = (sheetCount = 0, defaultName = 'MoviePrint-') => { // return random name from sheetNames array const sheetName = `${defaultName}${sheetCount + 1}`; return sheetName; }; export const getSheetId = (sheetsByFileId, fileId) => { if (sheetsByFileId[fileId] === undefined) { // there is no file yet, so return undefined return undefined; } const sheetIdArray = Object.getOwnPropertyNames(sheetsByFileId[fileId]); if (sheetIdArray.length === 0) { // there are no sheetIds yet, so return undefined return undefined; } // return first sheetId in array return sheetIdArray[0]; }; export const getParentSheetId = (sheetsByFileId, fileId, sheetId) => { if ( sheetsByFileId === undefined || sheetsByFileId[fileId] === undefined || sheetsByFileId[fileId][sheetId] === undefined || sheetsByFileId[fileId][sheetId].parentSheetId === undefined ) { return undefined; } return sheetsByFileId[fileId][sheetId].parentSheetId; }; export const doesSheetExist = (sheetsByFileId, fileId, sheetId) => { if ( sheetsByFileId === undefined || sheetsByFileId[fileId] === undefined || sheetsByFileId[fileId][sheetId] === undefined ) { return false; } return true; }; export const getFramenumbers = (sheet, visibilityFilter) => { if (sheet.thumbsArray === undefined) { return undefined; } const { thumbsArray } = sheet; if (visibilityFilter === THUMB_SELECTION.VISIBLE_THUMBS) { const frameNumberArray = thumbsArray.filter(thumb => thumb.hidden === false).map(thumb => thumb.frameNumber); return frameNumberArray; } return thumbsArray.map(thumb => thumb.frameNumber); }; export const getFramenumbersOfSheet = (sheetsByFileId, fileId, sheetId, visibilitySettings) => { if ( sheetsByFileId[fileId] === undefined || fileId === undefined || sheetId === undefined || sheetsByFileId[fileId][sheetId] === undefined || sheetsByFileId[fileId][sheetId].thumbsArray === undefined ) { return undefined; } const { thumbsArray } = sheetsByFileId[fileId][sheetId]; if (visibilitySettings.visibilityFilter === THUMB_SELECTION.VISIBLE_THUMBS) { const frameNumberArray = thumbsArray.filter(thumb => thumb.hidden === false).map(thumb => thumb.frameNumber); return frameNumberArray; } return thumbsArray.map(thumb => thumb.frameNumber); }; export const getSceneArrayForExport = (sceneArray, thumbsArray) => { return sceneArray.map(scene => { const { frameNumber } = thumbsArray.find(thumb => thumb.thumbId === scene.sceneId); return { start: scene.start, length: scene.length, frameNumber, colorArray: scene.colorArray, }; }); }; export const getFrameNumberWithSceneOrThumbId = (sheetsByFileId, fileId, sheetId, thumbId) => { if ( thumbId === undefined || fileId === undefined || sheetId === undefined || sheetsByFileId === undefined || sheetsByFileId[fileId] === undefined || sheetsByFileId[fileId][sheetId] === undefined || sheetsByFileId[fileId][sheetId].thumbsArray === undefined ) { return undefined; } const { thumbsArray } = sheetsByFileId[fileId][sheetId]; const thumb = thumbsArray.find(item => item.thumbId === thumbId); const { frameNumber } = thumb; return frameNumber; }; export const getEDLscenes = (sheetsByFileId, fileId, sheetId, visibilitySettings, fps) => { if ( sheetsByFileId[fileId] === undefined || fileId === undefined || sheetId === undefined || sheetsByFileId[fileId][sheetId] === undefined || sheetsByFileId[fileId][sheetId].sceneArray === undefined ) { return undefined; } const { sceneArray } = sheetsByFileId[fileId][sheetId]; if (visibilitySettings.visibilityFilter === THUMB_SELECTION.VISIBLE_THUMBS) { const frameNumberArray = sceneArray .filter(scene => scene.hidden === false) .map( (scene, index) => `${pad(index + 1, 3)} ${pad(index % 2, 3)} V C ${frameCountToTimeCode( scene.start, fps, )} ${frameCountToTimeCode(scene.start + scene.length, fps)} ${frameCountToTimeCode( scene.start, fps, )} ${frameCountToTimeCode(scene.start + scene.length, fps)}`, ); return frameNumberArray; } return sceneArray.map( (scene, index) => `${pad(index + 1, 3)} ${pad(index % 2, 3)} V C ${frameCountToTimeCode( scene.start, fps, )} ${frameCountToTimeCode(scene.start + scene.length, fps)} ${frameCountToTimeCode( scene.start, fps, )} ${frameCountToTimeCode(scene.start + scene.length, fps)}`, ); }; export const getSheetCount = (files, fileId) => { const file = getFile(files, fileId); // console.log(file); if (file === undefined) { // there is no file yet, so return undefined return 0; } return file.sheetCounter; }; export const getFile = (files, fileId) => { const file = files.find(file2 => file2.id === fileId); // console.log(file); if (file === undefined) { // there is no file yet, so return undefined return undefined; } return file; }; export const getFileName = (files, fileId) => { const file = getFile(files, fileId); // console.log(file); if (file === undefined) { // there is no file yet, so return undefined return 0; } return file.name; }; export const getFilePath = (files, fileId) => { const file = getFile(files, fileId); // console.log(file); if (file === undefined) { // there is no file yet, so return undefined return 0; } return file.path; }; export const getFrameCount = (files, fileId) => { const file = getFile(files, fileId); // console.log(file); if (file === undefined) { // there is no file yet, so return undefined return 0; } return file.frameCount; }; export const getFileTransformObject = (files, fileId) => { const file = getFile(files, fileId); // console.log(file); if (file === undefined) { // there is no file yet, so return undefined return undefined; } return file.transformObject || TRANSFORMOBJECT_INIT; }; export const getSheetIdArray = (sheetsByFileId, fileId) => { if (sheetsByFileId[fileId] === undefined) { // there is no file yet, so return undefined return undefined; } const sheetIdArray = Object.getOwnPropertyNames(sheetsByFileId[fileId]); if (sheetIdArray.length === 0) { // there are no sheetIds yet, so return undefined return undefined; } // return first sheetId in array return sheetIdArray; }; export const getSheet = (sheetsByFileId, fileId, sheetId) => { if (sheetsByFileId === undefined || sheetsByFileId[fileId] === undefined) { return undefined; } return sheetsByFileId[fileId][sheetId]; }; export const getSheetName = (sheetsByFileId, fileId, sheetId) => { if ( sheetsByFileId === undefined || sheetsByFileId[fileId] === undefined || sheetsByFileId[fileId][sheetId] === undefined || sheetsByFileId[fileId][sheetId].name === undefined ) { return 'MoviePrint'; } return sheetsByFileId[fileId][sheetId].name; }; export const getSheetFilter = (sheetsByFileId, fileId, sheetId) => { if ( sheetsByFileId === undefined || sheetsByFileId[fileId] === undefined || sheetsByFileId[fileId][sheetId] === undefined || sheetsByFileId[fileId][sheetId].filter === undefined ) { return {}; // empty object means no filter } return sheetsByFileId[fileId][sheetId].filter; }; export const getSheetView = (sheetsByFileId, fileId, sheetId) => { if ( sheetsByFileId === undefined || sheetsByFileId[fileId] === undefined || sheetsByFileId[fileId][sheetId] === undefined || sheetsByFileId[fileId][sheetId].sheetView === undefined ) { return SHEET_VIEW.GRIDVIEW; } return sheetsByFileId[fileId][sheetId].sheetView; }; export const getSheetType = (sheetsByFileId, fileId, sheetId, settings) => { if ( sheetsByFileId === undefined || sheetsByFileId[fileId] === undefined || sheetsByFileId[fileId][sheetId] === undefined || sheetsByFileId[fileId][sheetId].type === undefined ) { return settings.defaultSheetType; } return sheetsByFileId[fileId][sheetId].type; }; export const getColumnCount = (sheetsByFileId, fileId, sheetId, settings) => { if ( sheetsByFileId === undefined || sheetsByFileId[fileId] === undefined || sheetsByFileId[fileId][sheetId] === undefined || sheetsByFileId[fileId][sheetId].columnCount === undefined ) { return settings.defaultColumnCount; } return sheetsByFileId[fileId][sheetId].columnCount; }; export const getSecondsPerRow = (sheetsByFileId, fileId, sheetId, settings) => { if ( sheetsByFileId === undefined || sheetsByFileId[fileId] === undefined || sheetsByFileId[fileId][sheetId] === undefined || sheetsByFileId[fileId][sheetId].secondsPerRow === undefined ) { return settings.defaultTimelineViewSecondsPerRow; } return sheetsByFileId[fileId][sheetId].secondsPerRow; }; export const getThumbsCount = (sheetsByFileId, fileId, sheetId, settings, visibilityFilter, noDefault = false) => { if ( fileId === undefined || sheetsByFileId[fileId] === undefined || sheetId === undefined || sheetsByFileId[fileId][sheetId] === undefined || sheetsByFileId[fileId][sheetId].thumbsArray === undefined ) { return noDefault ? 0 : settings.defaultThumbCount; } if (visibilityFilter === THUMB_SELECTION.VISIBLE_THUMBS) { return sheetsByFileId[fileId][sheetId].thumbsArray.filter(thumb => thumb.hidden === false).length; } return sheetsByFileId[fileId][sheetId].thumbsArray.length; }; export const getThumbsCountOfArray = (thumbsArray, visibilityFilter) => { if (visibilityFilter === THUMB_SELECTION.VISIBLE_THUMBS) { return thumbsArray.filter(thumb => thumb.hidden === false).length; } return thumbsArray.length; }; export const getShotNumber = (sceneId, sheetsByFileId, fileId, sheetId) => { if ( fileId === undefined || sheetsByFileId[fileId] === undefined || sheetId === undefined || sceneId === undefined || sheetsByFileId[fileId][sheetId] === undefined || sheetsByFileId[fileId][sheetId].sceneArray === undefined ) { return undefined; } const shotNumber = sheetsByFileId[fileId][sheetId].sceneArray.findIndex(scene => scene.sceneId === sceneId) + 1; // index is zero based return shotNumber; }; export const setPosition = (vid, frameNumberToCapture, useRatio) => { if (vid !== undefined) { if (useRatio) { const positionRatio = (frameNumberToCapture * 1.0) / (vid.get(VideoCaptureProperties.CAP_PROP_FRAME_COUNT) - 1); // log.debug(`setPosition using positionRatio: ${positionRatio}`); vid.set(VideoCaptureProperties.CAP_PROP_POS_AVI_RATIO, positionRatio); } else { // log.debug(`setPosition using frame position: ${frameNumberToCapture}`); vid.set(VideoCaptureProperties.CAP_PROP_POS_FRAMES, frameNumberToCapture); } } }; export const renderImage = (img, canvas, cv) => { const matRGBA = img.channels === 1 ? img.cvtColor(cv.COLOR_GRAY2RGBA) : img.cvtColor(cv.COLOR_BGR2RGBA); canvas.height = img.rows; canvas.width = img.cols; const imgData = new ImageData(new Uint8ClampedArray(matRGBA.getData()), img.cols, img.rows); const ctx = canvas.getContext('2d'); ctx.putImageData(imgData, 0, 0); }; export const getScrubFrameNumber = ( mouseX, keyObject, scaleValueObject, frameCount, scrubThumb, scrubThumbLeft, scrubThumbRight, leftOfScrubMovie, rightOfScrubMovie, ) => { let scrubFrameNumber; // when scrubbing all the way to the left/right sideMargin gives space // when selecting the first/last frame close to the window border const sideMargin = 10; // depending on if scrubbing over ScrubMovie change mapping range // scrubbing over ScrubMovie scrubbs over scene, with ctrl pressed scrubbing left or right of it scrubs over whole movie // depending on if add before (shift) or after (alt) changing the mapping range const tempLeftFrameNumber = keyObject.altKey ? scrubThumb.frameNumber : scrubThumbLeft.frameNumber; const tempRightFrameNumber = keyObject.shiftKey ? scrubThumb.frameNumber : scrubThumbRight.frameNumber; // check if scrubbed thumb is first/last thumb // in this case take range movie start/end same as when pressing ctrl const isFirstThumb = scrubThumb.frameNumber === scrubThumbLeft.frameNumber; const isLastThumb = scrubThumb.frameNumber === scrubThumbRight.frameNumber; if (mouseX < leftOfScrubMovie) { if (keyObject.ctrlKey || isFirstThumb) { scrubFrameNumber = mapRange(mouseX, 0 + sideMargin, leftOfScrubMovie, 0, tempLeftFrameNumber); } else { scrubFrameNumber = tempLeftFrameNumber; } } else if (mouseX > rightOfScrubMovie) { if (keyObject.ctrlKey || isLastThumb) { scrubFrameNumber = mapRange( mouseX, rightOfScrubMovie, scaleValueObject.containerWidth - sideMargin, tempRightFrameNumber, frameCount - 1, ); } else { scrubFrameNumber = tempRightFrameNumber; } } else { scrubFrameNumber = mapRange(mouseX, leftOfScrubMovie, rightOfScrubMovie, tempLeftFrameNumber, tempRightFrameNumber); } return scrubFrameNumber; }; export const getSceneScrubFrameNumber = ( mouseX, scaleValueObject, scrubThumb, scrubScene, leftOfScrubMovie, rightOfScrubMovie, ) => { let scrubFrameNumber; const tempLeftFrameNumber = scrubScene.start; const tempRightFrameNumber = scrubScene.start + scrubScene.length - 1; if (mouseX < leftOfScrubMovie) { scrubFrameNumber = tempLeftFrameNumber; } else if (mouseX > rightOfScrubMovie) { scrubFrameNumber = tempRightFrameNumber; } else { scrubFrameNumber = mapRange(mouseX, leftOfScrubMovie, rightOfScrubMovie, tempLeftFrameNumber, tempRightFrameNumber); } return scrubFrameNumber; }; export const deleteProperty = ({ [key]: _, ...newObj }, key) => newObj; export const isEquivalent = (a, b) => { // Create arrays of property names const aProps = Object.getOwnPropertyNames(a); const bProps = Object.getOwnPropertyNames(b); // If number of properties is different, // objects are not equivalent if (aProps.length !== bProps.length) { return false; } for (let i = 0; i < aProps.length; i += 1) { const propName = aProps[i]; // If values of same property are not equal, // objects are not equivalent if (a[propName] !== b[propName]) { return false; } } // If we made it this far, objects // are considered equivalent return true; }; export const fourccToString = fourcc => `${String.fromCharCode(fourcc & 0xff)}${String.fromCharCode((fourcc & 0xff00) >> 8)}${String.fromCharCode( (fourcc & 0xff0000) >> 16, )}${String.fromCharCode((fourcc & 0xff000000) >> 24)}`; export const roundNumber = (number, decimals = 2) => Math.round(number * 10 ** decimals + Number.EPSILON) / 10 ** decimals; // rounds the number with 3 decimals export const getTextWidth = (text, font) => { // re-use canvas object for better performance const canvas = getTextWidth.canvas || (getTextWidth.canvas = document.createElement('canvas')); const context = canvas.getContext('2d'); context.font = font; const metrics = context.measureText(text); return metrics.width; }; export const limitFrameNumberWithinMovieRange = (file, frameNumber) => { const limitedFrameNumber = Math.min(file.frameCount - 1, Math.max(0, frameNumber)); // limit it on lower and on upper end return limitedFrameNumber; }; export const arrayToObject = (array, keyField) => { if (array === undefined) { return {}; } return array.reduce((obj, item) => { obj[item[keyField]] = item; return obj; }, {}); }; export const getScenesInRows = (sceneArray, secondsPerRow) => { // get scenes in rows if (sceneArray.length === 0) { return []; } const framesPerRow = secondsPerRow * 25; // console.log(framesPerRow); const sceneLengthsInRowArray = []; // sceneLengthsInRowArray.push(sceneArray[0].length); const rowArray = []; let previousSceneOutPoint = sceneArray[0].start; // get first sceneStart // console.log(sceneArray); sceneArray.map((scene, index) => { // console.log(`${scene.start}, ${scene.length}, ${index}`); const sceneOutPoint = previousSceneOutPoint + scene.length; sceneLengthsInRowArray.push(scene.length); if (sceneLengthsInRowArray.reduce((a, b) => a + b, 0) > framesPerRow) { if (sceneLengthsInRowArray.length === 1) { // if only 1 scene rowArray.push({ index, sceneOutPoint, rowItemCount: sceneLengthsInRowArray.length, // get length rowLength: sceneLengthsInRowArray.reduce((a, b) => a + b, 0), // get sum of all lengths sceneLengthsInRow: sceneLengthsInRowArray.slice(), // pass copy of array }); sceneLengthsInRowArray.length = 0; // clear array } else { // if more than 1 scene rowArray.push({ index: index - 1, sceneOutPoint: previousSceneOutPoint, rowItemCount: sceneLengthsInRowArray.slice(0, -1).length, // remove last and get length rowLength: sceneLengthsInRowArray.slice(0, -1).reduce((a, b) => a + b, 0), // remove last and get sum of all lengths sceneLengthsInRow: sceneLengthsInRowArray.slice(0, -1), // remove last and pass copy of array }); sceneLengthsInRowArray.splice(0, sceneLengthsInRowArray.length - 1); // only keep last } } if (sceneArray.length === index + 1) { // last scene rowArray.push({ index, sceneOutPoint, rowItemCount: sceneLengthsInRowArray.length, rowLength: sceneLengthsInRowArray.reduce((a, b) => a + b, 0), // sum of all lengths sceneLengthsInRow: sceneLengthsInRowArray.slice(), // pass copy of array }); } previousSceneOutPoint = sceneOutPoint; return undefined; }); // console.log(rowArray); return rowArray; }; export const getWidthOfSingleRow = (scenes, thumbMargin, pixelPerFrameRatio, minSceneLength) => { if (scenes === undefined) { return undefined; } const sceneLengthArray = scenes.map(scene => Math.max(scene.length, minSceneLength)); const sumSceneLengths = sceneLengthArray.reduce((a, b) => a + b, 0); const widthOfSingleRow = sumSceneLengths * pixelPerFrameRatio + scenes.length * thumbMargin * 2; return widthOfSingleRow; }; // export const getWidthOfLongestRow = (rowArray, thumbMargin, pixelPerFrameRatio, minSceneLengthInFrames) => { // // calculate width through getting longest row // // console.log(rowArray); // // console.log(thumbMargin); // // console.log(pixelPerFrameRatio); // if (rowArray.length === 0) { // return undefined; // } // const rowLengthArray = []; // rowArray.map((row) => { // // console.log(row.sceneLengthsInRow); // // calculate width // let rowWidth = 0; // row.sceneLengthsInRow.map((sceneLength) => { // // const widthOfScene = Math.max(sceneLength, minSceneLengthInFrames) * pixelPerFrameRatio + thumbMargin * 2; // const widthOfScene = Math.max(sceneLength, minSceneLengthInFrames) * pixelPerFrameRatio + thumbMargin * 2 * pixelPerFrameRatio; // rowWidth += widthOfScene; // // console.log(widthOfScene); // return undefined; // }); // rowLengthArray.push(Math.ceil(rowWidth)); // return undefined; // }) // const maxWidth = Math.max(...rowLengthArray); // // console.log(rowLengthArray); // // console.log(maxWidth); // return maxWidth // } export const getPixelPerFrameRatio = (rowArray, thumbMargin, width, minSceneLengthInFrames) => { // calculate width through getting longest row // console.log(rowArray); // console.log(thumbMargin); // console.log(width); if (rowArray.length === 0) { return undefined; } const pixelPerFrameRatioArray = []; rowArray.map(row => { const numOfScenesInRow = row.sceneLengthsInRow.length; const minScenesArray = row.sceneLengthsInRow.filter(item => item <= minSceneLengthInFrames); const numOfMinScenes = minScenesArray.length; const lengthOfMinScenes = minScenesArray.reduce((a, b) => a + b, 0); const lengthOfAllScenes = row.rowLength; const lengthOfOtherScenes = lengthOfAllScenes - lengthOfMinScenes; // console.log(numOfScenesInRow); // console.log(numOfMinScenes); // console.log(lengthOfOtherScenes); // console.log(lengthOfAllScenes); // calculate pixelPerFrameRatio const pixelPerFrameRatio = (width - numOfScenesInRow * thumbMargin * 2) / (+numOfMinScenes * minSceneLengthInFrames + lengthOfOtherScenes); // console.log(pixelPerFrameRatio); pixelPerFrameRatioArray.push(pixelPerFrameRatio); return undefined; }); const minPixelPerFrameRatio = Math.min(...pixelPerFrameRatioArray); // console.log(pixelPerFrameRatioArray); // console.log(minPixelPerFrameRatio); return minPixelPerFrameRatio; }; export const createSceneArray = (sheetsByFileId, fileId, sheetId) => { if ( sheetsByFileId[fileId] !== undefined && sheetsByFileId[fileId][sheetId] !== undefined && sheetsByFileId[fileId][sheetId].thumbsArray !== undefined ) { const { thumbsArray } = sheetsByFileId[fileId][sheetId]; if (thumbsArray.length > 0) { const visibleThumbsArray = getVisibleThumbs(thumbsArray, THUMB_SELECTION.VISIBLE_THUMBS); visibleThumbsArray.sort((t1, t2) => t1.frameNumber - t2.frameNumber); // console.log(visibleThumbsArray); const sceneArray = []; let sceneStart = visibleThumbsArray[0].frameNumber; // first sceneStart value let sceneLength = Math.floor((visibleThumbsArray[1].frameNumber - visibleThumbsArray[0].frameNumber) / 2) + 1; // first sceneLength value visibleThumbsArray.map((thumb, index, array) => { if (index !== 0) { // everything except the first thumb sceneStart += sceneLength; if (index < array.length - 1) { // then until second to last const nextThumb = array[index + 1]; sceneLength = Math.floor((nextThumb.frameNumber - thumb.frameNumber) / 2) + thumb.frameNumber - sceneStart + 1; } else { // last thumb sceneLength = thumb.frameNumber - sceneStart; } } sceneArray.push({ sceneId: thumb.thumbId, fileId, sheetId, start: sceneStart, length: sceneLength, colorArray: [40, 40, 40], }); return undefined; }); // console.log(sceneArray); return sceneArray; } return []; } return []; }; // export const getSliceWidthArrayForScrub = (vid, sliceArraySize = 19, sliceWidthOutsideMin = 20) => { // const width = vid.get(VideoCaptureProperties.CAP_PROP_FRAME_WIDTH); // // const height = vid.get(VideoCaptureProperties.CAP_PROP_FRAME_HEIGHT); // const sliceWidthInMiddle = width; // const sliceWidthArray = []; // const halfArraySize = Math.ceil(sliceArraySize / 2); // for (let i = 0; i < sliceArraySize; i += 1) { // const factor = i < halfArraySize ? halfArraySize - (i + 1) : i + 1 - halfArraySize; // const sliceWidth = Math.floor(sliceWidthInMiddle / 2 ** factor); // sliceWidthArray.push(Math.max(sliceWidth, sliceWidthOutsideMin)); // } // return sliceWidthArray; // }; export const getSliceWidthArrayForCut = (canvasWidth, videoWidth, sliceArraySize = 20) => { const isAsymmetrical = sliceArraySize % 2 === 1; const halfArraySize = Math.floor(sliceArraySize / 2); const newCanvasWidth = canvasWidth - VIDEOPLAYER_CUTGAP - VIDEOPLAYER_SLICEGAP * sliceArraySize; const sliceWidthInMiddle = Math.floor(newCanvasWidth / (isAsymmetrical ? 3 : 4)); const sliceWidthArray = []; let factor; for (let i = 0; i < sliceArraySize; i += 1) { if (isAsymmetrical) { factor = i < halfArraySize ? halfArraySize - (i + 1) : i + 1 - halfArraySize; } else { factor = i < halfArraySize ? halfArraySize - (i + 1) : i - halfArraySize; } const sliceWidth = Math.floor(sliceWidthInMiddle / 2 ** factor); sliceWidthArray.push(limitRange(sliceWidth, 1, videoWidth)); // keep minimum of 1px or videoWidth for portrait videos } return sliceWidthArray; }; export const getSceneFromFrameNumber = (scenes, frameNumber) => { if (scenes === undefined) { return undefined; } const scene = scenes.find(scene1 => scene1.start <= frameNumber && scene1.start + scene1.length > frameNumber); if (scene !== undefined || scenes.length < 1) { return scene; } const maxFrameNumberScene = scenes.reduce((prev, current) => prev.start + prev.length > current.start + current.length ? prev : current, ); const minFrameNumberScene = scenes.reduce((prev, current) => (prev.start < current.start ? prev : current)); const maxFrameNumber = maxFrameNumberScene.start + maxFrameNumberScene.length - 1; const minFrameNumber = minFrameNumberScene.start; const newFrameNumberToSearch = Math.min(maxFrameNumber, Math.max(minFrameNumber, frameNumber)); const closestScene = scenes.find( scene1 => scene1.start <= newFrameNumberToSearch && scene1.start + scene1.length > newFrameNumberToSearch, ); return closestScene; }; export const getLeftAndRightThumb = (thumbs, thumbCenterId) => { if (thumbs === undefined || thumbCenterId === undefined) { return undefined; } // get thumb left and right of scrubThumb const indexOfThumb = thumbs.findIndex(thumb => thumb.thumbId === thumbCenterId); const thumbCenter = thumbs[indexOfThumb]; const tempLeftThumb = thumbs[Math.max(0, indexOfThumb - 1)]; const tempRightThumb = thumbs[Math.min(thumbs.length - 1, indexOfThumb + 1)]; // the three thumbs might not be in ascending order, left has to be lower, right has to be higher // create an array to compare the three thumbs const arrayToCompare = [tempLeftThumb, tempRightThumb, thumbCenter]; // copy the first array with slice so I can run it a second time (reduce mutates the array) const thumbLeft = arrayToCompare .slice() .reduce((prev, current) => (prev.frameNumber < current.frameNumber ? prev : current)); const thumbRight = arrayToCompare.reduce((prev, current) => prev.frameNumber > current.frameNumber ? prev : current, ); return { thumbCenter, thumbLeft, thumbRight, }; }; export const getAdjacentSceneIndicesFromCut = (scenes, frameNumber) => { // return an array of 2 adjacent scenes if the frameNumber is the cut in between // else return undefined const sceneIndex = scenes.findIndex(scene1 => scene1.start === frameNumber); console.log(frameNumber); console.log(scenes); if (sceneIndex <= 0) { return undefined; } const adjacentSceneIndicesArray = [sceneIndex - 1, sceneIndex]; console.log(adjacentSceneIndicesArray); return adjacentSceneIndicesArray; }; export const getBucketValueOfPercentage = (percentage, amountOfBuckets) => { // take percentage and return bucketed percentage value, like a histogram value or bin return (Math.floor((percentage * 100.0) / (100.0 / (amountOfBuckets - 1))) * (100.0 / (amountOfBuckets - 1))) / 100.0; }; export const getFrameInPercentage = (frameNumber, frameCount) => { if (frameCount > 1) { return (frameNumber / ((frameCount - 1) * 1.0)) * 100.0; } return 0; }; export const calculateSceneListFromDifferenceArray = (fileId, differenceArray, meanColorArray, threshold) => { let lastSceneCut = null; let differenceValueFromLastSceneCut; const sceneList = []; differenceArray.map((differenceValue, index) => { // initialise first scene cut if (lastSceneCut === null) { lastSceneCut = index; } if (differenceValue >= threshold) { if (index - lastSceneCut >= SCENE_DETECTION_MIN_SCENE_LENGTH) { // check if differenceValue is not within SCENE_DETECTION_MIN_SCENE_LENGTH const start = lastSceneCut; // start const length = index - start; // length const colorArray = meanColorArray[start + Math.floor(length / 2)]; sceneList.push({ fileId, start, length, colorArray, }); lastSceneCut = index; } else if (differenceValue > differenceValueFromLastSceneCut) { // check if there is a more distinct cut within SCENE_DETECTION_MIN_SCENE_LENGTH // if so, remove the previous one and use the new one // only if sceneList not empty (otherwise pop returns undefined) if (sceneList.length !== 0) { const lastScene = sceneList.pop(); const { start } = lastScene; // get start from lastScene const length = index - start; // length const colorArray = meanColorArray[start + Math.floor(length / 2)]; sceneList.push({ fileId, start, length, colorArray, }); lastSceneCut = index; } else { // if first scene within SCENE_DETECTION_MIN_SCENE_LENGTH const start = 0; const length = index - start; // length const colorArray = meanColorArray[start + Math.floor(length / 2)]; sceneList.push({ fileId, start, length, colorArray, }); lastSceneCut = index; } } } differenceValueFromLastSceneCut = differenceValue; // console.log(`${index} - ${lastSceneCut} = ${index - lastSceneCut} - ${differenceValue >= threshold}`); return true; }); // add last scene const length = differenceArray.length - lastSceneCut; // meanArray.length should be frameCount sceneList.push({ fileId, start: lastSceneCut, // start length, colorArray: [128, 128, 128], // [frameMean.w, frameMean.x, frameMean.y], // color }); // console.log(sceneList); return sceneList; }; // repairs missing frames in frameScanData in place export const repairFrameScanData = (arrayOfFrameScanData, frameCount) => { // frameScanData is not complete // create new array and fill in the blanks for (let i = 0; i < frameCount; i += 1) { if (i !== arrayOfFrameScanData[i].frameNumber) { // if frame is missing, take previous data, // fix framenumber, insert it and decrease i again // so it loops through it again to check // if first frame missing fill it with default object let correctedDuplicate; if (i === 0) { correctedDuplicate = { frameNumber: 0, meanColor: '[0,0,0]', differenceValue: 0, }; } else { correctedDuplicate = { ...arrayOfFrameScanData[i - 1] }; correctedDuplicate.frameNumber = i; } log.info(`repaired frameScanData at: ${i}`); arrayOfFrameScanData.splice(i, 0, correctedDuplicate); i -= 1; } } // no return is needed as arrayOfFrameScanData gets repaired in place }; export const sanitizeString = str => { const cleanedString = sanitize(str, '-'); // const cleanedString = str.replace(/[^a-z0-9áéíóúñü$. ,_-]/gim,""); return cleanedString.trim(); }; // generates the frameScan table name and makes it sql compatible export const getFrameScanTableName = fileId => { if (fileId === undefined) { return undefined; } const tableName = `frameScan_${fileId.replace(/-/g, '_')}`; return tableName; }; export const getCropWidthAndHeight = (transformObject, videoWidth, videoHeight) => { let cropTop = 0; let cropBottom = 0; let cropLeft = 0; let cropRight = 0; if (transformObject !== undefined && transformObject !== null) { // log.debug(transformObject); cropTop = transformObject.cropTop; cropBottom = transformObject.cropBottom; cropLeft = transformObject.cropLeft; cropRight = transformObject.cropRight; } const cropWidth = Math.max(1, videoWidth - cropLeft - cropRight); const cropHeight = Math.max(1, videoHeight - cropTop - cropBottom); return { cropWidth, cropHeight, }; }; export const getSizeOfString = stringToMeasure => { const sizeInByte = Buffer.byteLength(stringToMeasure, 'utf8'); return formatBytes(sizeInByte); }; export const areOneOrMoreFiltersEnabled = filters => { for (const key of Object.keys(filters)) { if (filters[key].enabled) { return true; } } return false; }; export const prepareDataToExportOrEmbed = (file, sheet, visibilityFilter, embedFilePath = true, embedFrameData = true) => { const { path: filePath, transformObject = TRANSFORMOBJECT_INIT } = file; const { columnCount, sceneArray, thumbsArray, type: sheetType } = sheet; const frameNumberArray = getFramenumbers(sheet, visibilityFilter); let sceneArrayForExport; if (sheetType === SHEET_TYPE.SCENES) { sceneArrayForExport = getSceneArrayForExport(sceneArray, thumbsArray); } const frameData = { transformObject, columnCount, ...(sheetType !== SHEET_TYPE.SCENES && { frameNumberArray }), // only include frameNumberArray if not scenes sceneArray: sceneArrayForExport, }; return { ...(embedFilePath && { filePath }), ...(embedFrameData && frameData), }; }; <|start_filename|>app/utils/saveMoviePrint.js<|end_filename|> import pathR from 'path'; import fsR from 'fs'; import html2canvas from 'html2canvas'; import log from 'electron-log'; import extract from 'png-chunks-extract'; import encode from 'png-chunks-encode'; import text from 'png-chunk-text'; import { getFilePathObject, getMimeType } from './utils'; import saveThumb from './saveThumb'; import { DEFAULT_MOVIEPRINT_BACKGROUND_COLOR, DEFAULT_MOVIEPRINT_NAME, DEFAULT_ALLTHUMBS_NAME, DEFAULT_OUTPUT_JPG_QUALITY, DEFAULT_THUMB_FORMAT, DEFAULT_THUMB_JPG_QUALITY, } from './constants'; const { ipcRenderer } = require('electron'); const { app } = require('electron').remote; const saveBlob = (blob, sheetId, fileName, dataToEmbed = undefined) => { const reader = new FileReader(); reader.onload = () => { if (reader.readyState === 2) { const buffer = Buffer.from(reader.result); let chunkBuffer = buffer; // if there is data to embed, create chunks and add them in the end if (dataToEmbed !== undefined) { const { filePath, transformObject, columnCount, frameNumberArray, sceneArray } = dataToEmbed; // Create chunks const version = text.encode('version', app.getVersion()); const filePathChunk = text.encode('filePath', encodeURIComponent(filePath)); const transformObjectChunk = text.encode('transformObject', JSON.stringify(transformObject)); const columnCountChunk = text.encode('columnCount', columnCount); const frameNumberArrayChunk = text.encode('frameNumberArray', JSON.stringify(frameNumberArray)); const sceneArrayChunk = text.encode('sceneArray', JSON.stringify(sceneArray)); const chunks = extract(buffer); // Add new chunks before the IEND chunk chunks.splice(-1, 0, version); chunks.splice(-1, 0, filePathChunk); chunks.splice(-1, 0, transformObjectChunk); chunks.splice(-1, 0, columnCountChunk); chunks.splice(-1, 0, frameNumberArrayChunk); chunks.splice(-1, 0, sceneArrayChunk); chunkBuffer = Buffer.from(encode(chunks)); } fsR.writeFile(fileName, chunkBuffer, err => { if (err) { console.log(err); ipcRenderer.send('message-from-workerWindow-to-mainWindow', 'received-saved-file-error', err.message); // mainWindow.webContents.send('received-saved-file-error', err.message); } else { ipcRenderer.send('message-from-workerWindow-to-mainWindow', 'received-saved-file', sheetId, fileName); // mainWindow.webContents.send('received-saved-file', sheetId, fileName); } ipcRenderer.send('message-from-workerWindow-to-workerWindow', 'action-saved-MoviePrint-done'); // window.webContents.send('action-saved-MoviePrint-done'); }); // ipcRenderer.send('send-save-file', sheetId, fileName, chunkBuffer, true); log.debug(`Saving ${JSON.stringify({ fileName, size: blob.size })}`); } }; try { reader.readAsArrayBuffer(blob); } catch (e) { ipcRenderer.send('send-save-file-error', true); } }; const saveMoviePrint = ( elementId, exportPath, file, sheetId, sheetName, scale, outputFormat, overwrite, saveIndividualThumbs = false, thumbs, dataToEmbed, backgroundColor = DEFAULT_MOVIEPRINT_BACKGROUND_COLOR, moviePrintName = DEFAULT_MOVIEPRINT_NAME, allThumbsName = DEFAULT_ALLTHUMBS_NAME, defaultOutputJpgQuality = DEFAULT_OUTPUT_JPG_QUALITY, defaultThumbFormat = DEFAULT_THUMB_FORMAT, defaultThumbJpgQuality = DEFAULT_THUMB_JPG_QUALITY, ) => { log.debug(file); const node = document.getElementById(elementId); const { name: fileName, fps } = file; const frameNumber = undefined; const newFilePathObject = getFilePathObject( fileName, sheetName, frameNumber, moviePrintName, outputFormat, exportPath, overwrite, fps, ); const newFilePathAndName = pathR.join(newFilePathObject.dir, newFilePathObject.base); const qualityArgument = defaultOutputJpgQuality / 100.0; // only applicable for jpg // log.debug(newFilePathAndName); // log.debug(node); // only embed data for PNGs const passOnDataToEmbed = outputFormat === 'png' ? dataToEmbed : undefined; const backgroundColorDependentOnFormat = outputFormat === 'png' // set alpha only for PNG ? `rgba(${backgroundColor.r}, ${backgroundColor.g}, ${backgroundColor.b}, ${backgroundColor.a})` : `rgb(${backgroundColor.r}, ${backgroundColor.g}, ${backgroundColor.b})`; html2canvas(node, { backgroundColor: backgroundColorDependentOnFormat, allowTaint: true, foreignObjectRendering: true, scale, }) .then(canvas => { canvas.toBlob( blob => { saveBlob(blob, sheetId, newFilePathAndName, passOnDataToEmbed); }, getMimeType(outputFormat), qualityArgument, ); return undefined; }) .catch(err => { log.error(err); }); const newFilePathAndNameWithoutExtension = pathR.join(newFilePathObject.dir, newFilePathObject.name); if (saveIndividualThumbs) { thumbs.map(thumb => { saveThumb( file.path, file.useRatio, fileName, sheetName, thumb.frameNumber, allThumbsName, thumb.frameId, file.transformObject, newFilePathAndNameWithoutExtension, overwrite, defaultThumbFormat, defaultThumbJpgQuality, fps, ); }); } }; export default saveMoviePrint; <|start_filename|>app/components/Scrub.css<|end_filename|> .scrubContainerBackground { /* outline-style: solid; outline-color: #0c3158; outline-width: 15px; outline-offset: -15px; */ position: fixed; /* Stay in place */ left: 0; top: 0; width: 100%; /* Full width */ height: 100%; /* Full height */ background-color: rgba(0,0,0,0.8); /* Black w/ opacity */ z-index: 999; cursor: col-resize; } .scrubInfo { position: absolute; top: 30px; left: 50%; transform: translateX(-50%); background-color: rgba(0,0,0,1); /* Black w/ opacity */ font-family: 'Franchise', 'Roboto Condensed'; color: #ffffff; font-size: 30px; opacity: 0.5; -webkit-user-select:none; } .scrubContainer { position: absolute; top: 50%; left: 50%; transform: translate(-50%,-50%); background-color: rgba(0,0,0,1); /* Black w/ opacity */ } .scrubInnerContainer { position: absolute; top: 50%; left: 50%; transform: translate(-50%,-50%); } .scrubThumb { position: relative; } .scrubThumbLeft { /* position: absolute; */ left: 0; display: inline-block; background-position: right center; background-size: cover; /* margin-right: 2px; */ /* height: 24px; */ /* width: 24px; */ object-fit: cover; transform: translateY(-50%); } .scrubThumbRight { /* position: absolute; */ right: 0; display: inline-block; background-position: left center; background-size: cover; /* margin-left: 2px; */ /* height: 24px; */ /* width: 24px; */ object-fit: cover; transform: translateY(-50%); } .scrubCancelBar { position: absolute; bottom: 0; width: 100%; background-color: rgba(100, 0, 0, 1); z-index: 1000; text-align: center; padding-top: 6px; cursor: pointer; } .scrubDescription { position: absolute; top: 0; width: 100%; /* background-color: #333333; */ z-index: 1000; text-align: center; padding-top: 6px; } .scrubLine { position: absolute; top: 0; height: 100%; width: 1px; background-color: #FF5006; z-index: 2000; } .frameNumberOrTimeCode { position: absolute; /* top: 0; */ left: 0; top: 0; transform: translate(-50%, -20px); background: #eee; border-radius:2px; font-family: 'Open sans'; font-size: 14px; line-height: 14px; padding: 1px; color: #000000; -webkit-user-select:none; z-index: 2001; } .scrubThumbLine { position: absolute; top: 0; height: 100%; width: 1px; background-color: rgba(255, 255, 255, 0.2); z-index: 2000; } .scrubThumbframeNumberOrTimeCode { position: absolute; /* top: 0; */ left: 0; top: 0; transform: translate(-50%, -20px); background-color: rgba(100, 100, 100, 1); border-radius:2px; font-family: 'Open sans'; font-size: 14px; line-height: 14px; padding: 1px; color: #000000; -webkit-user-select:none; z-index: 1999; /* opacity: 0.5; */ } .timelineWrapper { bottom: -24px; width: 100%; position: absolute; background-color: #421400; height: 24px; } .timelineCut { position: absolute; background-color: rgba(255, 80, 6, 0.4); height: 24px; } .timelinePlayhead { position: absolute; /* bottom: 0; */ /* top: 0; */ width: 2px; background-color: rgba(255, 80, 6, 1); height: 20px; margin-top: 2px; } .timelineScrubThumb { position: absolute; /* bottom: 0; */ /* top: 0; */ width: 1px; background-color: rgba(255, 255, 255, 0.2); height: 20px; margin-top: 2px; } /* .timelineWrapper .currentTime { background-color: #FF5006; z-index: 2; } */ /* .timelineWrapper .cutStartTime { background-color: rgba(0, 0, 0, 0.3); border-left: 1px solid black; border-right: 1px solid black; z-index: 1; } */ <|start_filename|>app/containers/Settings.css<|end_filename|> .slider { width: 90%; margin: 10px; background-color: #3e3e3e; } .label { color: white !important; } .subCheckbox { margin-left: 30px; } .input { height: 34px; width: 80px; } .edit { padding-left: 4px; } .colorPickerColor { position: relative; width: 190px; height: 32px; border-radius: 2px; } .colorPickerSwatch { padding: 2px; background: #fff; border-radius: 1px; box-shadow: 0 0 0 1px rgba(0,0,0,.1); display: inline-block; cursor: pointer; } .colorPickerPopover { position: absolute; z-index: 2; } .colorPickerCover { position: fixed; top: 0px; right: 0px; bottom: 0px; left: 0px; } .colorPickerText { padding: 6px; font-size: 20px; font-family: 'Open sans'; text-align: center; } .smallText { margin-top: 8px; font-size: 0.9rem; } .previewCustomName { background-color: rgba(0,0,0,0.8) !important; color: rgba(255,255,255,0.5) !important; font-style: italic !important; font-weight: 200 !important; letter-spacing: 0.3px; line-height: 1.2rem !important; } .smallDivider { margin: 0.4rem 0 !important; } .attributeButton { margin: 1px !important; } .accordion > :global(.active) { background-color: rgba(255,255,255,0.05) !important; } .accordion :global(.title) { border-width: 1px 0 0 0 !important; border-style: solid !important; border-color: rgba(255,255,255,0.05) !important; } <|start_filename|>app/worker_opencv.js<|end_filename|> import React from 'react'; import { render } from 'react-dom'; import log from 'electron-log'; import uuidV4 from 'uuid/v4'; import * as tf from '@tensorflow/tfjs-node'; import { VideoCaptureProperties } from './utils/openCVProperties'; import { limitRange, setPosition, fourccToString } from './utils/utils'; import { detectAllFaces } from './utils/faceDetection'; import { getCropRect, HSVtoRGB, detectCut, recaptureThumbs, resizeMatToMax, transformMat } from './utils/utilsForOpencv'; import { IN_OUT_POINT_SEARCH_LENGTH, IN_OUT_POINT_SEARCH_THRESHOLD } from './utils/constants'; import { insertFrameScanArray, insertFaceScanArray } from './utils/utilsForSqlite'; import Queue from './utils/queue'; process.env.OPENCV4NODEJS_DISABLE_EXTERNAL_MEM_TRACKING = 1; const opencv = require('opencv4nodejs'); const unhandled = require('electron-unhandled'); // const assert = require('assert'); unhandled(); const searchLimit = 25; // how long to go forward or backward to find a none-empty frame const { ipcRenderer } = require('electron'); // to cancel file scan let fileScanRunning = false; // set up queues // sceneQueue stores scene data, is used for preview purpose and is pulled from mainWindow const sceneQueue = new Queue(); // imageQueue stores image data, is used when grabbing images and is pulled from databaseWorkerWindow const imageQueue = new Queue(); log.debug('I am the opencvWorkerWindow - responsible for capturing the necessary frames from the video using opencv'); window.addEventListener('error', event => { log.error(event); ipcRenderer.send( 'message-from-opencvWorkerWindow-to-mainWindow', 'progressMessage', 'error', `There has been an error while loading the Opencv Worker. Please contact us for support: ${event.message}`, false, ); event.preventDefault(); }); window.addEventListener('uncaughtException', event => { log.error(event); ipcRenderer.send( 'message-from-opencvWorkerWindow-to-mainWindow', 'progressMessage', 'error', `There has been an uncaughtException while loading the Opencv Worker. Please contact us for support: ${event.message}`, false, ); event.preventDefault(); }); window.addEventListener('unhandledrejection', event => { log.error(event); ipcRenderer.send( 'message-from-opencvWorkerWindow-to-mainWindow', 'progressMessage', 'error', `There has been an unhandledrejection while loading the Opencv Worker. Please contact us for support: ${event.message}`, false, ); event.preventDefault(); }); // handle crashes and kill events process.on('uncaughtException', err => { // log the message and stack trace log.error(err); // fs.writeFileSync('crash.log', err + "\n" + err.stack); }); // handle crashes and kill events process.on('SIGTERM', err => { // log the message and stack trace log.error(err); // fs.writeFileSync('shutdown.log', 'Received SIGTERM signal'); }); setInterval(() => { // objectUrlQueue // console.log(imageQueue.size()) const size = imageQueue.size(); if (size !== 0) { log.debug(`the imageQueue size is: ${size}`); // start requestIdleCallback for imageQueue ipcRenderer.send( 'message-from-opencvWorkerWindow-to-databaseWorkerWindow', 'start-setIntervalForImages-for-imageQueue', ); } }, 1000); ipcRenderer.on('cancelFileScan', () => { log.debug('cancelling fileScan'); fileScanRunning = false; }); ipcRenderer.on( 'recapture-frames', (event, files, sheetsByFileId, frameSize, fileId = undefined, onlyReplace = true) => { log.debug('opencvWorkerWindow | on recapture frames'); log.debug(`opencvWorkerWindow | frameSize: ${frameSize}`); // define toastId so it can be updated const toastId = fileId || uuidV4(); ipcRenderer.send( 'message-from-opencvWorkerWindow-to-mainWindow', 'progressMessage', 'info', 'Updating frame cache', false, toastId, ); // if fileId, then only recapture those, else recapture all let filteredArray = files; if (fileId !== undefined) { filteredArray = files.filter(file2 => file2.id === fileId); } log.debug(filteredArray); filteredArray.map(file => { log.debug(`opencvWorkerWindow | ${file.path}`); log.debug(`opencvWorkerWindow | useRatio: ${file.useRatio}`); // iterate through all sheets const sheets = sheetsByFileId[file.id]; if (sheets !== undefined) { Object.keys(sheets).map(sheetId => { const currentSheetArray = sheets[sheetId].thumbsArray; if (currentSheetArray === undefined) { return false; } const frameNumberArray = currentSheetArray.map(frame => frame.frameNumber); const frameIdArray = currentSheetArray.map(frame => frame.frameId); recaptureThumbs( frameSize, file.id, file.path, file.useRatio, frameIdArray, frameNumberArray, onlyReplace, file.transformObject, ); // recapture posterFrame without transform recaptureThumbs( frameSize, file.id, file.path, file.useRatio, [file.posterFrameId], [Math.floor(file.frameCount / 2)], onlyReplace, ); return true; // finished capturing one sheet }); } return true; // finished capturing one file }); ipcRenderer.send( 'message-from-opencvWorkerWindow-to-mainWindow', 'progressMessage', 'success', 'Finished updating frame cache', 3000, toastId, true, ); }, ); ipcRenderer.on( 'send-get-file-details', (event, fileId, filePath, posterFrameId, onlyReplace = false, onlyImport = false) => { log.debug('opencvWorkerWindow | on send-get-file-details'); // log.debug(fileId); log.debug(`opencvWorkerWindow | ${filePath}`); try { const vid = new opencv.VideoCapture(filePath); const frameCount = vid.get(VideoCaptureProperties.CAP_PROP_FRAME_COUNT); const width = vid.get(VideoCaptureProperties.CAP_PROP_FRAME_WIDTH); const height = vid.get(VideoCaptureProperties.CAP_PROP_FRAME_HEIGHT); const fps = vid.get(VideoCaptureProperties.CAP_PROP_FPS); const fourCC = fourccToString(vid.get(VideoCaptureProperties.CAP_PROP_FOURCC)); log.debug(`opencvWorkerWindow | width: ${width}`); log.debug(`opencvWorkerWindow | height: ${height}`); log.debug(`opencvWorkerWindow | FPS: ${vid.get(VideoCaptureProperties.CAP_PROP_FPS)}`); log.debug(`opencvWorkerWindow | codec: ${fourccToString(vid.get(VideoCaptureProperties.CAP_PROP_FOURCC))}`); ipcRenderer.send( 'message-from-opencvWorkerWindow-to-mainWindow', 'receive-get-file-details', fileId, filePath, posterFrameId, frameCount, width, height, fps, fourCC, onlyReplace, onlyImport, ); } catch (e) { ipcRenderer.send('message-from-opencvWorkerWindow-to-mainWindow', 'failed-to-open-file', fileId); ipcRenderer.send( 'message-from-opencvWorkerWindow-to-mainWindow', 'progressMessage', 'error', `Failed to open ${filePath}`, 10000, ); log.error(e); } }, ); ipcRenderer.on( 'send-get-poster-frame', (event, fileId, filePath, posterFrameId, onlyReplace = false, onlyImport = false) => { log.debug('opencvWorkerWindow | on send-get-poster-frame'); // log.debug(fileId); log.debug(`opencvWorkerWindow | ${filePath}`); try { const vid = new opencv.VideoCapture(filePath); const frameNumberToCapture = Math.floor(vid.get(VideoCaptureProperties.CAP_PROP_FRAME_COUNT) / 2); // capture frame in the middle vid.readAsync(err1 => { const read = function read() { setPosition(vid, frameNumberToCapture, false); vid.readAsync((err, mat) => { log.debug( `opencvWorkerWindow | ${frameNumberToCapture}/${vid.get(VideoCaptureProperties.CAP_PROP_POS_FRAMES) - 1}(${vid.get(VideoCaptureProperties.CAP_PROP_POS_MSEC)}ms) of ${vid.get( VideoCaptureProperties.CAP_PROP_FRAME_COUNT, )}`, ); let useRatio = false; // frames not match if (frameNumberToCapture !== vid.get(VideoCaptureProperties.CAP_PROP_POS_FRAMES) - 1) { log.debug( 'opencvWorkerWindow | ########################### Playhead not at correct position: set useRatio to TRUE ###########################', ); useRatio = true; } if (mat.empty === false) { const outBase64 = opencv.imencode('.jpg', mat).toString('base64'); // for poster frame jpg is used const frameNumber = vid.get(VideoCaptureProperties.CAP_PROP_POS_FRAMES); ipcRenderer.send( 'message-from-opencvWorkerWindow-to-databaseWorkerWindow', 'send-base64-frame', posterFrameId, fileId, frameNumber, outBase64, onlyReplace, ); ipcRenderer.send( 'message-from-opencvWorkerWindow-to-mainWindow', 'receive-get-poster-frame', fileId, filePath, posterFrameId, frameNumber, useRatio, onlyReplace, onlyImport, ); } // iterator += 1; // if (iterator < frameNumberArray.length) { // read(); // } }); }; if (err1) throw err1; // let iterator = 0; setPosition(vid, frameNumberToCapture, false); read(); }); } catch (e) { log.error(e); } }, ); ipcRenderer.on('send-get-in-and-outpoint', (event, fileId, filePath, useRatio, detectInOutPoint) => { log.debug('opencvWorkerWindow | on send-get-in-and-outpoint'); // log.debug(fileId); log.debug(`opencvWorkerWindow | ${filePath}`); try { console.time(`${fileId}-inPointDetection`); const vid = new opencv.VideoCapture(filePath); const videoLength = vid.get(VideoCaptureProperties.CAP_PROP_FRAME_COUNT) - 1; // log.debug(videoLength); if (detectInOutPoint) { console.time(`${fileId}-inOutPointDetection`); const timeBeforeInOutPointDetection = Date.now(); ipcRenderer.send( 'message-from-opencvWorkerWindow-to-mainWindow', 'progressMessage', 'info', 'Detecting in and outpoint', ); const searchLength = Math.min(IN_OUT_POINT_SEARCH_LENGTH, videoLength / 2); const threshold = IN_OUT_POINT_SEARCH_THRESHOLD; let searchInpoint = true; const meanArrayIn = []; const meanArrayOut = []; let fadeInPoint; let fadeOutPoint; vid.readAsync(err1 => { const read = () => { vid.readAsync((err, mat) => { const frame = vid.get(VideoCaptureProperties.CAP_PROP_POS_FRAMES); log.debug( `opencvWorkerWindow | readAsync: frame:${frame} (${vid.get( VideoCaptureProperties.CAP_PROP_POS_MSEC, )}ms) of ${vid.get(VideoCaptureProperties.CAP_PROP_FRAME_COUNT)}`, ); let frameMean = 0; if (mat.empty === false) { // console.time('meanCalculation'); // scale to quarter of size, convert to HSV, calculate mean, get only V channel frameMean = mat .rescale(0.25) .cvtColor(opencv.COLOR_BGR2HSV) .mean().y; // console.timeEnd('meanCalculation'); // // single axis for 1D hist // const binCount = 17; // const getHistAxis = channel => ([ // { // channel, // bins: binCount, // ranges: [0, 256] // } // ]); // const matHSV = mat.cvtColor(opencv.COLOR_BGR2HSV); // const frameHist = opencv.calcHist(matHSV, getHistAxis(2)); // log.debug(frameHist.at(0)); // log.debug(frameHist.at(0) > (binCount * 256)); if (searchInpoint) { meanArrayIn.push({ frame: vid.get(VideoCaptureProperties.CAP_PROP_POS_FRAMES) - 1, mean: frameMean, }); } else { meanArrayOut.push({ frame: vid.get(VideoCaptureProperties.CAP_PROP_POS_FRAMES) - 1, mean: frameMean, }); } if ( (searchInpoint && frameMean >= threshold) || (frame >= searchLength && frame < videoLength - searchLength) ) { // only run if still searching inpoint and frameMean over threshold or done scanning inpoint searchInpoint = false; // done searching inPoint log.debug('opencvWorkerWindow | resetting playhead'); setPosition(vid, videoLength - searchLength, useRatio); read(); } else if (frame < searchLength || (frame >= videoLength - searchLength && frame <= videoLength)) { // half the amount of ipc events if (iterator % 2) { const progressBarPercentage = (iterator / (searchLength * 2)) * 100; ipcRenderer.send( 'message-from-opencvWorkerWindow-to-mainWindow', 'progress', fileId, progressBarPercentage, ); // first half of progress } iterator += 1; read(); } } else { log.error( `opencvWorkerWindow | empty frame: iterator:${iterator} frame:${frame} (${vid.get( VideoCaptureProperties.CAP_PROP_POS_MSEC, )}ms) of ${vid.get(VideoCaptureProperties.CAP_PROP_FRAME_COUNT)}`, ); } if (frame > videoLength || mat.empty === true) { const meanArrayInReduced = meanArrayIn.reduce( (prev, current) => { let largerObject = prev.mean > current.mean ? prev : current; if (prev.frameThreshold === undefined) { largerObject = current.mean > threshold ? { ...largerObject, ...{ frameThreshold: current.frame }, } : largerObject; } else { largerObject = { ...largerObject, ...{ frameThreshold: prev.frameThreshold }, }; } return largerObject; }, { frame: 0, mean: 0 }, ); const meanArrayOutReduced = meanArrayOut.reduceRight( (prev, current) => { let largerObject = prev.mean > current.mean ? prev : current; if (prev.frameThreshold === undefined) { largerObject = current.mean > threshold ? { ...largerObject, ...{ frameThreshold: current.frame }, } : largerObject; } else { largerObject = { ...largerObject, ...{ frameThreshold: prev.frameThreshold }, }; } return largerObject; }, { frame: videoLength, mean: 0 }, ); // log.debug(meanArrayInReduced); // log.debug(meanArrayOutReduced); // use frame when threshold is reached and if undefined use frame with highest mean fadeInPoint = meanArrayInReduced.frameThreshold !== undefined ? meanArrayInReduced.frameThreshold : meanArrayInReduced.frame; fadeOutPoint = meanArrayOutReduced.frameThreshold !== undefined ? meanArrayOutReduced.frameThreshold : meanArrayOutReduced.frame; const timeAfterInOutPointDetection = Date.now(); console.timeEnd(`${fileId}-inOutPointDetection`); log.debug(`opencvWorkerWindow | fadeInPoint: ${fadeInPoint}`); log.debug(`opencvWorkerWindow | fadeOutPoint: ${fadeOutPoint}`); ipcRenderer.send('message-from-opencvWorkerWindow-to-mainWindow', 'progress', fileId, 100); // set to full ipcRenderer.send( 'message-from-opencvWorkerWindow-to-mainWindow', 'progressMessage', 'info', `In and Outpoint detection finished - ${timeAfterInOutPointDetection - timeBeforeInOutPointDetection}ms`, 3000, ); ipcRenderer.send( 'message-from-opencvWorkerWindow-to-mainWindow', 'receive-get-in-and-outpoint', fileId, fadeInPoint, fadeOutPoint, ); } else { log.error( `opencvWorkerWindow | something wrong: frame:${frame} > videoLength:${videoLength} || mat.empty ${mat.empty}`, ); // log.debug(meanArrayIn); // log.debug(meanArrayOut); log.error( `opencvWorkerWindow | something wrong: iterator:${iterator} frame:${frame} (${vid.get( VideoCaptureProperties.CAP_PROP_POS_MSEC, )}ms) of ${vid.get(VideoCaptureProperties.CAP_PROP_FRAME_COUNT)}`, ); } }); }; const startFrame = 0; let iterator = 0; if (err1) throw err1; setPosition(vid, startFrame, useRatio); read(); // start reading frames }); } else { log.debug('opencvWorkerWindow | in-out-point-detection DEACTIVATED'); ipcRenderer.send( 'message-from-opencvWorkerWindow-to-mainWindow', 'receive-get-in-and-outpoint', fileId, 0, videoLength, ); } } catch (e) { log.error(e); } }); ipcRenderer.on( 'send-get-file-scan', (event, fileId, filePath, useRatio, threshold = 20.0, sheetId, transformObject, shotDetectionMethod) => { log.debug('opencvWorkerWindow | on send-get-file-scan'); // log.debug(fileId); log.debug(`opencvWorkerWindow | ${filePath}`); try { fileScanRunning = true; // start requestIdleCallback for sceneQueue ipcRenderer.send('message-from-opencvWorkerWindow-to-mainWindow', 'start-requestIdleCallback-for-sceneQueue'); const timeBeforeSceneDetection = Date.now(); console.time(`${fileId}-fileScanning`); const vid = new opencv.VideoCapture(filePath); const minSceneLength = 15; const frameMetrics = []; let previousData = {}; let lastSceneCut = null; const cropRect = getCropRect(vid, transformObject); vid.readAsync(err1 => { const read = () => { vid.readAsync((err, mat) => { const frame = vid.get(VideoCaptureProperties.CAP_PROP_POS_FRAMES) - 1; if (iterator % 100 === 0) { const progressBarPercentage = (iterator / vid.get(VideoCaptureProperties.CAP_PROP_FRAME_COUNT)) * 100; ipcRenderer.send( 'message-from-opencvWorkerWindow-to-mainWindow', 'progress', fileId, progressBarPercentage, ); // first half of progress log.debug( `opencvWorkerWindow | readAsync: frame:${frame} (${vid.get( VideoCaptureProperties.CAP_PROP_POS_MSEC, )}ms) of ${vid.get(VideoCaptureProperties.CAP_PROP_FRAME_COUNT)}`, ); } if (mat.empty === false) { // optional transform const matTransformed = transformMat(mat, transformObject, cropRect); const resultingData = detectCut(previousData, matTransformed, threshold, shotDetectionMethod); const { isCut, lastColorRGB, differenceValue } = resultingData; // initialise first scene cut if (lastSceneCut === null) { lastSceneCut = frame; } if (isCut) { if (frame - lastSceneCut >= minSceneLength) { // add scene // sceneQueue is used for preview purpose and is pulled from mainWindow const length = frame - lastSceneCut; // length sceneQueue.add({ fileId, sheetId, start: lastSceneCut, // start length, colorArray: lastColorRGB, }); lastSceneCut = frame; } } previousData = { ...resultingData }; log.debug(differenceValue); const meanColor = JSON.stringify(lastColorRGB); frameMetrics.push({ fileId, frameNumber: frame, differenceValue, meanColor, }); } else { log.error( `empty frame: iterator:${iterator} frame:${frame} (${vid.get( VideoCaptureProperties.CAP_PROP_POS_MSEC, )}ms) of ${vid.get(VideoCaptureProperties.CAP_PROP_FRAME_COUNT)}`, ); frameMetrics.push({ fileId, frameNumber: frame, differenceValue: undefined, meanColor: undefined, }); } iterator += 1; if (!fileScanRunning) { const messageToSend = `opencvWorkerWindow | File scanning cancelled at frame ${frame}`; log.debug(messageToSend); console.timeEnd(`${fileId}-fileScanning`); ipcRenderer.send( 'message-from-opencvWorkerWindow-to-mainWindow', 'progressMessage', 'error', messageToSend, 6000, ); } else if (iterator < vid.get(VideoCaptureProperties.CAP_PROP_FRAME_COUNT)) { read(); } else { const timeAfterSceneDetection = Date.now(); const scanDurationInSeconds = (timeAfterSceneDetection - timeBeforeSceneDetection) / 1000; const scanDurationString = scanDurationInSeconds > 180 ? `${Math.floor(scanDurationInSeconds / 60)} minutes` : `${Math.floor(scanDurationInSeconds)} seconds`; const messageToSend = `File scanning took ${scanDurationString} (${Math.floor( vid.get(VideoCaptureProperties.CAP_PROP_FRAME_COUNT) / scanDurationInSeconds, )} fps)`; log.info(`opencvWorkerWindow | ${filePath} - ${shotDetectionMethod} - ${messageToSend}`); console.timeEnd(`${fileId}-fileScanning`); // add last scene const { lastColorRGB } = previousData; const length = vid.get(VideoCaptureProperties.CAP_PROP_FRAME_COUNT) - lastSceneCut; // length sceneQueue.add({ fileId, sheetId, start: lastSceneCut, // start length, colorArray: lastColorRGB, }); // sceneQueue was only necessary for preview // clear sceneQueue so it is not accidentally pulled in from mainWindow sceneQueue.clear(); // insert all frames into sqlite3 const timeBeforeInsertFrameScanArray = Date.now(); insertFrameScanArray(fileId, frameMetrics); const timeAfterInsertFrameScanArray = Date.now(); log.debug( `opencvWorkerWindow | insertFrameScanArray duration: ${timeAfterInsertFrameScanArray - timeBeforeInsertFrameScanArray}`, ); ipcRenderer.send( 'message-from-opencvWorkerWindow-to-mainWindow', 'received-get-file-scan', fileId, filePath, useRatio, sheetId, ); ipcRenderer.send('message-from-opencvWorkerWindow-to-mainWindow', 'progress', fileId, 100); // set to full ipcRenderer.send( 'message-from-opencvWorkerWindow-to-mainWindow', 'progressMessage', 'info', messageToSend, 5000, ); } }); }; const startFrame = 0; let iterator = 0; if (err1) throw err1; // before scene detection starts clearScenes ipcRenderer.send('message-from-opencvWorkerWindow-to-mainWindow', 'clearScenes', fileId, sheetId); setPosition(vid, startFrame, useRatio); read(); // start reading frames }); } catch (e) { log.error(e); } }, ); // get faces async ipcRenderer.on( // 'send-get-thumbs-async', 'send-get-faces', ( event, fileId, filePath, sheetId, frameNumberArray, useRatio, defaultCachedFramesSize, transformObject, defaultFaceConfidenceThreshold, defaultFaceSizeThreshold, defaultFaceUniquenessThreshold, faceSortMethod, updateSheet = false, ) => { log.debug('opencvWorkerWindow | on send-get-faces'); log.debug(`opencvWorkerWindow | ${filePath}`); try { fileScanRunning = true; const frameNumberArrayLength = frameNumberArray.length; const timeBeforeFaceDetection = Date.now(); console.time(`${fileId}-faceScanning`); const vid = new opencv.VideoCapture(filePath); const detectionArray = []; let detectionPromise; const cropRect = getCropRect(vid, transformObject); vid.readAsync(err1 => { const read = () => { // limit frameNumberToCapture between 0 and movie length const frameNumberToCapture = limitRange( frameNumberArray[iterator], 0, vid.get(VideoCaptureProperties.CAP_PROP_FRAME_COUNT) - 1, ); setPosition(vid, frameNumberToCapture, useRatio); vid.readAsync((err, mat) => { const progressBarPercentage = (iterator / frameNumberArrayLength) * 100; ipcRenderer.send( 'message-from-opencvWorkerWindow-to-mainWindow', 'progress', fileId, progressBarPercentage, ); log.debug( `opencvWorkerWindow | readAsync: ${iterator}, ${frameNumberToCapture}/${vid.get( VideoCaptureProperties.CAP_PROP_POS_FRAMES, ) - 1}(${vid.get(VideoCaptureProperties.CAP_PROP_POS_MSEC)}ms) of ${vid.get( VideoCaptureProperties.CAP_PROP_FRAME_COUNT, )}`, ); if (mat.empty === false) { // opencv.imshow('mat', mat); // optional transform const matTransformed = transformMat(mat, transformObject, cropRect); // optional resize using resizeToMax const matResult = resizeMatToMax(vid, matTransformed, 720); const outJpg = opencv.imencode('.jpg', matResult); // for detection jpg is used const input = tf.node.decodeJpeg(outJpg); detectionPromise = detectAllFaces( input, frameNumberToCapture, detectionArray, defaultFaceConfidenceThreshold, defaultFaceSizeThreshold, defaultFaceUniquenessThreshold, ); // console.log(detectionPromise); } else { log.debug('opencvWorkerWindow | frame is empty'); } iterator += 1; if (!fileScanRunning) { const messageToSend = `opencvWorkerWindow | File scanning cancelled at frame ${frameNumberToCapture}`; log.debug(messageToSend); console.timeEnd(`${fileId}-fileScanning`); ipcRenderer.send( 'message-from-opencvWorkerWindow-to-mainWindow', 'progressMessage', 'error', messageToSend, 6000, ); } else if (iterator < frameNumberArrayLength) { read(); } else { detectionPromise // wait for last detectionPromise .then(() => { log.debug('lastThumb'); console.log(detectionArray); console.log(detectionArray.length); let totalFaceCount = 0; detectionArray.forEach(frame => { const { faceCount, facesArray } = frame; if (faceCount > 0 && facesArray !== undefined) { totalFaceCount += facesArray.length; } }); // insert all frames into sqlite3 insertFaceScanArray(fileId, detectionArray); const timeAfterFaceDetection = Date.now(); const scanDurationInSeconds = (timeAfterFaceDetection - timeBeforeFaceDetection) / 1000; const scanDurationString = scanDurationInSeconds > 180 ? `${Math.floor(scanDurationInSeconds / 60)} minutes` : `${Math.floor(scanDurationInSeconds)} seconds`; const messageToSend = `Face scanning took ${scanDurationString} (${Math.floor( vid.get(VideoCaptureProperties.CAP_PROP_FRAME_COUNT) / scanDurationInSeconds, )} fps) ${totalFaceCount} faces found in ${detectionArray.length} of ${frameNumberArray.length} scanned frames`; log.info(`opencvWorkerWindow | ${filePath} - ${messageToSend}`); console.timeEnd(`${fileId}-fileScanning`); ipcRenderer.send( 'message-from-opencvWorkerWindow-to-mainWindow', 'finished-getting-faces', fileId, sheetId, detectionArray, faceSortMethod, updateSheet, ); ipcRenderer.send('message-from-opencvWorkerWindow-to-mainWindow', 'progress', fileId, 100); // set to full ipcRenderer.send( 'message-from-opencvWorkerWindow-to-mainWindow', 'progressMessage', 'info', messageToSend, 10000, ); return undefined; }) .catch(err2 => { log.error(err2); }); } }); }; if (err1) throw err1; let iterator = 0; setPosition(vid, frameNumberArray[iterator], useRatio); read(); }); } catch (e) { log.error(e); } }, ); // read async ipcRenderer.on( // 'send-get-thumbs-async', 'send-get-thumbs', ( event, fileId, filePath, sheetId, thumbIdArray, frameIdArray, frameNumberArray, useRatio, frameSize, transformObject, ) => { log.debug('opencvWorkerWindow | on send-get-thumbs'); // log.debug(frameNumberArray); log.debug(`opencvWorkerWindow | ${filePath}`); log.debug(`opencvWorkerWindow | useRatio: ${useRatio}`); log.debug(`opencvWorkerWindow | imageQueue size: ${imageQueue.size()}`); log.debug('send-get-thumbs'); log.debug(transformObject); try { const frameNumberArrayLength = frameNumberArray.length; const vid = new opencv.VideoCapture(filePath); const timeBefore = Date.now(); const frameNumberAndColorArray = []; let frameIsEmpty = false; const cropRect = getCropRect(vid, transformObject); vid.readAsync(err1 => { const read = (frameOffset = 0) => { // limit frameNumberToCapture between 0 and movie length const frameNumberToCapture = limitRange( frameNumberArray[iterator] + frameOffset, 0, vid.get(VideoCaptureProperties.CAP_PROP_FRAME_COUNT) - 1, ); setPosition(vid, frameNumberToCapture, useRatio); vid.readAsync((err, mat) => { // debugger; log.debug( `opencvWorkerWindow | readAsync: ${iterator}, frameOffset: ${frameOffset}, ${frameNumberToCapture}/${vid.get( VideoCaptureProperties.CAP_PROP_POS_FRAMES, ) - 1}(${vid.get(VideoCaptureProperties.CAP_PROP_POS_MSEC)}ms) of ${vid.get( VideoCaptureProperties.CAP_PROP_FRAME_COUNT, )}`, ); if (mat.empty === false) { frameIsEmpty = false; // opencv.imshow('mat', mat); // optional transform const matTransformed = transformMat(mat, transformObject, cropRect); // optional resize using resizeToMax const matResult = resizeMatToMax(vid, matTransformed, frameSize); // opencv.imshow('matRescaled', matRescaled); const outBase64 = opencv.imencode('.jpg', matResult).toString('base64'); // for internal usage frame jpg is used const frameNumber = vid.get(VideoCaptureProperties.CAP_PROP_POS_FRAMES) - 1; const frameId = frameIdArray[iterator]; // get color const frameMean = matResult .resizeToMax(240) .cvtColor(opencv.COLOR_BGR2HSV) .mean(); const colorArray = HSVtoRGB(frameMean.w, frameMean.x, frameMean.y); imageQueue.add({ frameId, fileId, frameNumber, outBase64, }); frameNumberAndColorArray.push({ fileId, sheetId, thumbId: thumbIdArray[iterator], frameNumber, colorArray, }); iterator += 1; } else { log.debug('opencvWorkerWindow | frame is empty'); frameIsEmpty = true; // assumption is that the we might find frames forward or backward which work if (Math.abs(frameOffset) < searchLimit) { // if frameNumberToCapture is close to the end go backward else go forward if (frameNumberToCapture < vid.get(VideoCaptureProperties.CAP_PROP_FRAME_COUNT) - searchLimit) { log.debug('opencvWorkerWindow | will try to read one frame forward'); read(frameOffset + 1); } else { log.debug('opencvWorkerWindow | will try to read one frame backward'); read(frameOffset - 1); } } else { log.debug('opencvWorkerWindow | still empty, will stop and send an empty frame back'); const frameNumber = vid.get(VideoCaptureProperties.CAP_PROP_POS_FRAMES) - 1; const frameId = frameIdArray[iterator]; imageQueue.add({ frameId, fileId, frameNumber, base64: '', }); frameNumberAndColorArray.push({ fileId, sheetId, thumbId: thumbIdArray[iterator], frameNumber, colorArray: [0, 0, 0], }); frameIsEmpty = false; // reset frameIsEmpty iterator += 1; } } if (!frameIsEmpty) { // do not read or jump to last thumb if frameIsEmpty as it has its own read function if (iterator < frameNumberArrayLength) { read(); } else { log.debug('lastThumb'); const duration = Date.now() - timeBefore; log.debug('lastThumb'); ipcRenderer.send( 'message-from-opencvWorkerWindow-to-mainWindow', 'update-frameNumber-and-colorArray', frameNumberAndColorArray, ); ipcRenderer.send( 'message-from-opencvWorkerWindow-to-mainWindow', 'finished-getting-thumbs', fileId, sheetId, ); ipcRenderer.send( 'message-from-opencvWorkerWindow-to-mainWindow', 'progressMessage', 'info', `Loading of frames took ${duration / 1000.0}s`, 3000, ); } } }); }; if (err1) throw err1; let iterator = 0; setPosition(vid, frameNumberArray[iterator], useRatio); read(); }); } catch (e) { log.error(e); } }, ); ipcRenderer.on('clear-sceneQueue', () => { log.debug(`opencvWorkerWindow | on clear-sceneQueue ${sceneQueue.size()}`); sceneQueue.clear(); }); ipcRenderer.on('get-some-scenes-from-sceneQueue', (event, amount) => { log.debug(`opencvWorkerWindow | on get-some-scenes-from-sceneQueue ${sceneQueue.size()}`); const someScenes = sceneQueue.removeLastMany(amount); ipcRenderer.send('message-from-opencvWorkerWindow-to-mainWindow', 'receive-some-scenes-from-sceneQueue', someScenes); log.debug(sceneQueue.size()); }); ipcRenderer.on('get-some-images-from-imageQueue', (event, amount) => { log.debug(`opencvWorkerWindow | on get-some-images-from-imageQueue ${imageQueue.size()}`); const someImages = imageQueue.removeLastMany(amount); ipcRenderer.send( 'message-from-opencvWorkerWindow-to-databaseWorkerWindow', 'receive-some-images-from-imageQueue', someImages, ); log.debug(imageQueue.size()); }); render( <div> <h1>I am the opencv worker window.</h1> <canvas id="myCanvas" /> {/* <img id="myImg" alt='' src='https://spaexecutive.com/wp-content/uploads/2019/06/Yumi.jpg'/> */} </div>, document.getElementById('worker_opencv'), ); <|start_filename|>app/utils/openCVProperties.js<|end_filename|> export const VideoCaptureProperties = Object.freeze({ CAP_PROP_POS_MSEC: 0, CAP_PROP_POS_FRAMES: 1, CAP_PROP_POS_AVI_RATIO: 2, CAP_PROP_FRAME_WIDTH: 3, CAP_PROP_FRAME_HEIGHT: 4, CAP_PROP_FPS: 5, CAP_PROP_FOURCC: 6, CAP_PROP_FRAME_COUNT: 7, CAP_PROP_FORMAT: 8, CAP_PROP_MODE: 9, CAP_PROP_BRIGHTNESS: 10, CAP_PROP_CONTRAST: 11, CAP_PROP_SATURATION: 12, CAP_PROP_HUE: 13, CAP_PROP_GAIN: 14, CAP_PROP_EXPOSURE: 15, CAP_PROP_CONVERT_RGB: 16, CAP_PROP_WHITE_BALANCE_BLUE_U: 17, CAP_PROP_RECTIFICATION: 18, CAP_PROP_MONOCHROME: 19, CAP_PROP_SHARPNESS: 20, CAP_PROP_AUTO_EXPOSURE: 21, CAP_PROP_GAMMA: 22, CAP_PROP_TEMPERATURE: 23, CAP_PROP_TRIGGER: 24, CAP_PROP_TRIGGER_DELAY: 25, CAP_PROP_WHITE_BALANCE_RED_V: 26, CAP_PROP_ZOOM: 27, CAP_PROP_FOCUS: 28, CAP_PROP_GUID: 29, CAP_PROP_ISO_SPEED: 30, CAP_PROP_BACKLIGHT: 32, CAP_PROP_PAN: 33, CAP_PROP_TILT: 34, CAP_PROP_ROLL: 35, CAP_PROP_IRIS: 36, CAP_PROP_SETTINGS: 37, CAP_PROP_BUFFERSIZE: 38, CAP_PROP_AUTOFOCUS: 39, }); export const ImwriteFlags = Object.freeze({ IMWRITE_JPEG_QUALITY: 1, IMWRITE_JPEG_PROGRESSIVE: 2, IMWRITE_JPEG_OPTIMIZE: 3, IMWRITE_JPEG_RST_INTERVAL: 4, IMWRITE_JPEG_LUMA_QUALITY: 5, IMWRITE_JPEG_CHROMA_QUALITY: 6, IMWRITE_PNG_COMPRESSION: 16, IMWRITE_PNG_STRATEGY: 17, IMWRITE_PNG_BILEVEL: 18, IMWRITE_PXM_BINARY: 32, // IMWRITE_EXR_TYPE: (3 << 4) + 0, IMWRITE_WEBP_QUALITY: 64, IMWRITE_PAM_TUPLETYPE: 128, IMWRITE_TIFF_RESUNIT: 256, IMWRITE_TIFF_XDPI: 257, IMWRITE_TIFF_YDPI: 258, IMWRITE_TIFF_COMPRESSION: 259, }); export const RotateFlags = Object.freeze({ ROTATE_90_CLOCKWISE: 0, // Rotate 90 degrees clockwise ROTATE_180: 1, // Rotate 180 degrees clockwise ROTATE_90_COUNTERCLOCKWISE: 2, // Rotate 270 degrees clockwise NO_ROTATION: 3, // No rotation - Artifical no rotation flag for opencv! }); <|start_filename|>app/utils/fileObject.js<|end_filename|> // import Dexie from 'dexie'; import log from 'electron-log'; import imageDB from './db'; const FileObject = imageDB.frameList.defineClass({ frameId: String, lastModified: Number, lastModifiedDate: String, name: String, path: String, size: Number, frameNumber: Number, type: String, webkitRelativePath: String, base64: String, data: Blob }); FileObject.prototype.objectUrl = ''; FileObject.prototype.getObjectUrl2 = () => { console.log(this); const objectUrl = window.URL.createObjectURL(this.data); return objectUrl; }; FileObject.prototype.getObjectUrl = () => { if (this.objectUrl !== '' && !this.disposed) { return this.objectUrl; } if (!this.disposed) { this.objectUrl = window.URL.createObjectURL(this.data); return this.objectUrl; } log.warn('File disposed!'); throw 'File disposed!'; }; FileObject.prototype.revokeObjectURL = () => { URL.revokeObjectURL(this.objectUrl); this.objectUrl = ''; }; FileObject.prototype.disposed = false; FileObject.prototype.disposeData = () => { URL.revokeObjectURL(this.objectUrl); this.objectUrl = ''; this.data = null; this.disposed = true; }; export default FileObject; <|start_filename|>app/store/localStorage.js<|end_filename|> import log from 'electron-log'; import { // DEFAULT_OUTPUT_PATH, DEFAULT_ALLTHUMBS_NAME, DEFAULT_BORDER_MARGIN, DEFAULT_BORDER_RADIUS_RATIO, DEFAULT_CACHED_FRAMES_SIZE, DEFAULT_COLUMN_COUNT, DEFAULT_DETECT_INOUTPOINT, DEFAULT_EMBED_FILEPATH, DEFAULT_EMBED_FRAMENUMBERS, DEFAULT_FRAMEINFO_BACKGROUND_COLOR, DEFAULT_FRAMEINFO_COLOR, DEFAULT_FRAMEINFO_MARGIN, DEFAULT_FRAMEINFO_POSITION, DEFAULT_FRAMEINFO_SCALE, DEFAULT_HEADER_HEIGHT_RATIO, DEFAULT_MARGIN_RATIO, DEFAULT_MARGIN_SLIDER_FACTOR, DEFAULT_MOVIEPRINT_BACKGROUND_COLOR, DEFAULT_MOVIEPRINT_NAME, DEFAULT_MOVIEPRINT_WIDTH, DEFAULT_OUTPUT_FORMAT, DEFAULT_OUTPUT_PATH_FROM_MOVIE, DEFAULT_PAPER_ASPECTRATIOINV, DEFAULT_ROUNDED_CORNERS, DEFAULT_SAVE_OPTION_INCLUDE_INDIVIDUAL, DEFAULT_SAVE_OPTION_OVERWRITE, DEFAULT_SCENE_DETECTION_THRESHOLD, DEFAULT_SCRUB_CONTAINER_MAXHEIGHTRATIO, DEFAULT_SCRUB_WINDOW_HEIGHTRATIO, DEFAULT_SCRUB_WINDOW_MARGIN, DEFAULT_SCRUB_WINDOW_WIDTHRATIO, DEFAULT_OUTPUT_JPG_QUALITY, DEFAULT_THUMB_FORMAT, DEFAULT_THUMB_JPG_QUALITY, DEFAULT_SHEET_TYPE, DEFAULT_SHEETVIEW, DEFAULT_SHOW_DETAILS_IN_HEADER, DEFAULT_SHOW_FACERECT, DEFAULT_SHOW_HEADER, DEFAULT_SHOW_IMAGES, DEFAULT_SHOW_PAPER_PREVIEW, DEFAULT_SHOW_PATH_IN_HEADER, DEFAULT_SHOW_TIMELINE_IN_HEADER, DEFAULT_SINGLETHUMB_NAME, DEFAULT_THUMB_COUNT, DEFAULT_THUMB_INFO_RATIO, DEFAULT_THUMB_INFO, DEFAULT_THUMBNAIL_SCALE, DEFAULT_TIMELINEVIEW_FLOW, DEFAULT_TIMELINEVIEW_MIN_DISPLAY_SCENE_LENGTH_IN_FRAMES, DEFAULT_TIMELINEVIEW_SECONDS_PER_ROW, DEFAULT_TIMELINEVIEW_WIDTH_SCALE, DEFAULT_VIDEO_PLAYER_HEIGHT, DEFAULT_VIDEO_PLAYER_WIDTH, DEFAULT_VIEW, FACE_UNIQUENESS_THRESHOLD, SHOT_DETECTION_METHOD, SHOW_MOVIELIST, SHOW_SETTINGS, STATEID, VISIBILITY_FILTER, ZOOM_SCALE, } from '../utils/constants'; import { createTableReduxState, updateReduxState, getReduxState } from '../utils/utilsForSqlite'; import { getSizeOfString } from '../utils/utils'; const { app } = require('electron').remote; createTableReduxState(); // create table if not exist // needs to have the same file structure as in combineReducers const initialStateJSON = { visibilitySettings: { visibilityFilter: VISIBILITY_FILTER, showMovielist: SHOW_MOVIELIST, showSettings: SHOW_SETTINGS, defaultView: DEFAULT_VIEW, defaultSheetView: DEFAULT_SHEETVIEW, defaultZoomLevel: ZOOM_SCALE, }, undoGroup: { settings: { defaultThumbCount: DEFAULT_THUMB_COUNT, defaultColumnCount: DEFAULT_COLUMN_COUNT, defaultThumbnailScale: DEFAULT_THUMBNAIL_SCALE, defaultMoviePrintWidth: DEFAULT_MOVIEPRINT_WIDTH, defaultMarginRatio: DEFAULT_MARGIN_RATIO, defaultMarginSliderFactor: DEFAULT_MARGIN_SLIDER_FACTOR, defaultBorderRadiusRatio: DEFAULT_BORDER_RADIUS_RATIO, defaultHeaderHeightRatio: DEFAULT_HEADER_HEIGHT_RATIO, defaultSheetType: DEFAULT_SHEET_TYPE, defaultShowHeader: DEFAULT_SHOW_HEADER, defaultShowImages: DEFAULT_SHOW_IMAGES, defaultShowPathInHeader: DEFAULT_SHOW_PATH_IN_HEADER, defaultShowDetailsInHeader: DEFAULT_SHOW_DETAILS_IN_HEADER, defaultShowTimelineInHeader: DEFAULT_SHOW_TIMELINE_IN_HEADER, defaultRoundedCorners: DEFAULT_ROUNDED_CORNERS, defaultThumbInfo: DEFAULT_THUMB_INFO, defaultThumbInfoRatio: DEFAULT_THUMB_INFO_RATIO, defaultOutputPath: app.getPath('desktop'), defaultOutputPathFromMovie: DEFAULT_OUTPUT_PATH_FROM_MOVIE, defaultOutputFormat: DEFAULT_OUTPUT_FORMAT, defaultOutputJpgQuality: DEFAULT_OUTPUT_JPG_QUALITY, defaultThumbFormat: DEFAULT_THUMB_FORMAT, defaultThumbJpgQuality: DEFAULT_THUMB_JPG_QUALITY, defaultSaveOptionOverwrite: DEFAULT_SAVE_OPTION_OVERWRITE, defaultSaveOptionIncludeIndividual: DEFAULT_SAVE_OPTION_INCLUDE_INDIVIDUAL, defaultVideoPlayerHeight: DEFAULT_VIDEO_PLAYER_HEIGHT, defaultVideoPlayerWidth: DEFAULT_VIDEO_PLAYER_WIDTH, defaultBorderMargin: DEFAULT_BORDER_MARGIN, defaultShowPaperPreview: DEFAULT_SHOW_PAPER_PREVIEW, defaultPaperAspectRatioInv: DEFAULT_PAPER_ASPECTRATIOINV, defaultDetectInOutPoint: DEFAULT_DETECT_INOUTPOINT, defaultScrubContainerMaxHeightRatio: DEFAULT_SCRUB_CONTAINER_MAXHEIGHTRATIO, defaultScrubWindowWidthRatio: DEFAULT_SCRUB_WINDOW_WIDTHRATIO, defaultScrubWindowHeightRatio: DEFAULT_SCRUB_WINDOW_HEIGHTRATIO, defaultScrubWindowMargin: DEFAULT_SCRUB_WINDOW_MARGIN, defaultSceneDetectionThreshold: DEFAULT_SCENE_DETECTION_THRESHOLD, defaultTimelineViewSecondsPerRow: DEFAULT_TIMELINEVIEW_SECONDS_PER_ROW, defaultTimelineViewMinDisplaySceneLengthInFrames: DEFAULT_TIMELINEVIEW_MIN_DISPLAY_SCENE_LENGTH_IN_FRAMES, defaultTimelineViewWidthScale: DEFAULT_TIMELINEVIEW_WIDTH_SCALE, defaultTimelineViewFlow: DEFAULT_TIMELINEVIEW_FLOW, defaultCachedFramesSize: DEFAULT_CACHED_FRAMES_SIZE, defaultEmbedFrameNumbers: DEFAULT_EMBED_FRAMENUMBERS, defaultEmbedFilePath: DEFAULT_EMBED_FILEPATH, defaultShotDetectionMethod: SHOT_DETECTION_METHOD.MEAN, defaultMoviePrintBackgroundColor: DEFAULT_MOVIEPRINT_BACKGROUND_COLOR, defaultFrameinfoBackgroundColor: DEFAULT_FRAMEINFO_BACKGROUND_COLOR, defaultFrameinfoColor: DEFAULT_FRAMEINFO_COLOR, defaultFrameinfoPosition: DEFAULT_FRAMEINFO_POSITION, defaultFrameinfoScale: DEFAULT_FRAMEINFO_SCALE, defaultFrameinfoMargin: DEFAULT_FRAMEINFO_MARGIN, defaultMoviePrintName: DEFAULT_MOVIEPRINT_NAME, defaultSingleThumbName: DEFAULT_SINGLETHUMB_NAME, defaultAllThumbsName: DEFAULT_ALLTHUMBS_NAME, defaultShowFaceRect: DEFAULT_SHOW_FACERECT, defaultFaceUniquenessThreshold: FACE_UNIQUENESS_THRESHOLD, emailAddress: '', }, sheetsByFileId: {}, files: [], }, }; export const loadState = () => { try { const row = getReduxState(STATEID); if (row === undefined || row.state === undefined || row.state === null) { // return undefined; return initialStateJSON; } log.debug(`Loading reduxstate from ${row.timeStamp}`); const serializedState = row.state; log.debug(`Size of reduxstate: ${getSizeOfString(serializedState)}`); const stateObject = JSON.parse(serializedState); return stateObject; } catch (err) { log.error('localStorage.js - error in loadState'); log.error(err); } }; export const saveState = state => { try { // only save present state and not any history (undo) const { undoGroup, ...allPropertiesExceptUndoGroup } = state; // separating the undoGroup const { past, future, ...rest } = undoGroup; // destructuring past and future out and only take rest const stateWithoutHistory = { ...allPropertiesExceptUndoGroup, undoGroup: { past: [], ...rest, future: [], }, }; // rebuilding state object const serializedState = JSON.stringify(stateWithoutHistory); const timeStamp = Date(); updateReduxState({ stateId: STATEID, timeStamp, state: serializedState, }); const timeBeforeUnix = new Date(timeStamp); const timeAfter = new Date(); const timeAfterUnix = timeAfter.getTime(); log.debug(`Size of reduxstate: ${getSizeOfString(serializedState)}`); log.debug(`Saving reduxstate in sqlite3 took ${timeAfterUnix - timeBeforeUnix} milliseconds`); // localStorage.setItem('state', serializedState); } catch (err) { log.error('localStorage.js - error in saveState'); log.error(err); // Ignore write errors } }; <|start_filename|>app/menu.js<|end_filename|> // @flow import { app, Menu, shell, BrowserWindow } from 'electron'; import path from 'path'; import fs from 'fs'; import { getPathOfLogFileAndFolder, resetApplication, reloadApplication, softResetApplication } from './utils/utilsForMain'; export default class MenuBuilder { mainWindow: BrowserWindow; workerWindow: BrowserWindow; constructor( mainWindow: BrowserWindow, workerWindow: BrowserWindow, opencvWorkerWindow: BrowserWindow, databaseWorkerWindow: BrowserWindow, ) { this.mainWindow = mainWindow; this.workerWindow = workerWindow; this.opencvWorkerWindow = opencvWorkerWindow; this.databaseWorkerWindow = databaseWorkerWindow; } buildMenu() { if ( process.env.NODE_ENV === 'development' || process.env.DEBUG_PROD === 'true' || process.argv.findIndex(value => value === '--debug') > -1 ) { this.setupDevelopmentEnvironment(); } const template = process.platform === 'darwin' ? this.buildDarwinTemplate() : this.buildDefaultTemplate(); const menu = Menu.buildFromTemplate(template); Menu.setApplicationMenu(menu); return menu; } setupDevelopmentEnvironment() { this.mainWindow.openDevTools(); this.mainWindow.webContents.on('context-menu', (e, props) => { const { x, y } = props; Menu.buildFromTemplate([ { label: 'Inspect element', click: () => { this.mainWindow.inspectElement(x, y); }, }, ]).popup(this.mainWindow); }); } buildDarwinTemplate() { const subMenuAbout = { label: 'Electron', submenu: [ { label: 'About MoviePrint_v004', selector: 'orderFrontStandardAboutPanel:' }, { type: 'separator' }, { label: 'Services', submenu: [] }, { type: 'separator' }, { label: 'Hide MoviePrint_v004', accelerator: 'Command+H', selector: 'hide:' }, { label: 'Hide Others', accelerator: 'Command+Shift+H', selector: 'hideOtherApplications:' }, { label: 'Show All', selector: 'unhideAllApplications:' }, { type: 'separator' }, { label: 'Quit', accelerator: 'Command+Q', click: () => { app.quit(); }, }, ], }; const subMenuEdit = { label: 'Edit', submenu: [ { label: 'Undo', accelerator: 'Command+Z', click: () => { this.mainWindow.send('undo'); }, }, { label: 'Redo', accelerator: 'Shift+Command+Z', click: () => { this.mainWindow.send('redo'); }, }, // { label: 'Undo', accelerator: 'Command+Z', selector: 'undo:' }, // { label: 'Redo', accelerator: 'Shift+Command+Z', selector: 'redo:' }, { type: 'separator' }, { label: 'Cut', accelerator: 'Command+X', selector: 'cut:' }, { label: 'Copy', accelerator: 'Command+C', selector: 'copy:' }, { label: 'Paste', accelerator: 'Command+V', selector: 'paste:' }, { label: 'Select All', accelerator: 'Command+A', selector: 'selectAll:' }, ], }; const subMenuDev = { label: 'Development', submenu: [ { label: 'Reset application', accelerator: 'Shift+Alt+Command+C', click: () => { resetApplication(this.mainWindow, this.workerWindow, this.opencvWorkerWindow, this.databaseWorkerWindow); }, }, { label: 'Soft reset application', accelerator: 'Shift+Alt+Command+V', click: () => { softResetApplication( this.mainWindow, this.workerWindow, this.opencvWorkerWindow, this.databaseWorkerWindow, ); }, }, { label: 'Reload application', accelerator: 'Command+R', click: () => { reloadApplication(this.mainWindow, this.workerWindow, this.opencvWorkerWindow, this.databaseWorkerWindow); }, }, { label: 'Reload mainWindow', accelerator: 'Ctrl+Command+R', click: () => { this.mainWindow.webContents.reload(); }, }, { label: 'Reload Worker', accelerator: 'Alt+Command+R', click: () => { this.workerWindow.webContents.reload(); }, }, { label: 'Reload Opencv Worker', accelerator: 'Shift+Command+R', click: () => { this.opencvWorkerWindow.webContents.reload(); }, }, { label: 'Reload Database Worker', accelerator: 'Alt+Shift+Command+R', click: () => { this.databaseWorkerWindow.webContents.reload(); }, }, { label: 'Toggle Developer Tools', accelerator: 'Alt+Command+I', click: () => { this.mainWindow.toggleDevTools(); }, }, { label: 'Toggle Developer Tools for Worker', accelerator: 'Alt+Command+J', click: () => { this.workerWindow.toggleDevTools(); }, }, { label: 'Toggle Developer Tools for Opencv Worker', accelerator: 'Alt+Command+K', click: () => { this.opencvWorkerWindow.toggleDevTools(); }, }, { label: 'Toggle Developer Tools for Database Worker', accelerator: 'Alt+Shift+Command+K', click: () => { this.databaseWorkerWindow.toggleDevTools(); }, }, { label: 'Show Worker', click: () => { this.workerWindow.show(); }, }, { label: 'Show OpenCv Worker', click: () => { this.opencvWorkerWindow.show(); }, }, { label: 'Show Database Worker', click: () => { this.databaseWorkerWindow.show(); }, }, { label: 'Show log file', click: () => { const { pathOfLogFile, pathOfLogFolder} = getPathOfLogFileAndFolder(process.platform, app.getName()); if (fs.existsSync(pathOfLogFile)) { shell.showItemInFolder(pathOfLogFile); } else { shell.showItemInFolder(pathOfLogFolder); } }, }, { label: 'Show database file', click: () => { const moviePrintDBPath = path.join(app.getPath('userData'), 'moviePrint_frames.db'); if (fs.existsSync(moviePrintDBPath)) { shell.showItemInFolder(moviePrintDBPath); } else { shell.showItemInFolder(app.getPath('userData')); } }, }, ], }; const subMenuView = { label: 'View', submenu: [ { label: 'Toggle Full Screen', accelerator: 'Ctrl+Command+F', click: () => { this.mainWindow.setFullScreen(!this.mainWindow.isFullScreen()); }, }, { label: 'Fit MoviePrint', accelerator: 'Command+0', click: () => { this.mainWindow.webContents.send('send-zoom-level', 'resetZoom'); }, }, { label: 'Zoom In', accelerator: 'Command+=', click: () => { this.mainWindow.webContents.send('send-zoom-level', 'zoomIn'); }, }, { label: 'Zoom Out', accelerator: 'Command+-', click: () => { this.mainWindow.webContents.send('send-zoom-level', 'zoomOut'); }, }, { type: 'separator' }, { label: 'Reload application', accelerator: 'Command+R', click: () => { reloadApplication(this.mainWindow, this.workerWindow, this.opencvWorkerWindow, this.databaseWorkerWindow); }, }, { label: 'Reset application', accelerator: 'Shift+Alt+Command+C', click: () => { resetApplication(this.mainWindow, this.workerWindow, this.opencvWorkerWindow, this.databaseWorkerWindow); }, }, { type: 'separator' }, { label: 'Restart in debug mode', accelerator: 'Shift+Alt+Ctrl+X', click: () => { app.relaunch({ args: process.argv.slice(1).concat(['--debug']), }); app.exit(0); }, }, ], }; const subMenuWindow = { label: 'Window', submenu: [ { label: 'Main window', click: () => { this.mainWindow.show(); }, }, { label: 'Minimize', accelerator: 'Command+M', selector: 'performMiniaturize:' }, { label: 'Close', accelerator: 'Command+W', selector: 'performClose:' }, { type: 'separator' }, { label: 'Bring All to Front', selector: 'arrangeInFront:' }, ], }; const subMenuHelp = { label: 'Help', submenu: [ { label: 'Help', click() { shell.openExternal('https://movieprint.org/help/'); }, }, { type: 'separator' }, { label: 'Development', click() { shell.openExternal('https://github.com/fakob/MoviePrint_v004'); }, }, { label: 'Search Issues', click() { shell.openExternal('https://github.com/fakob/MoviePrint_v004/issues'); }, }, { type: 'separator' }, { label: `MoviePrint version: ${app.getVersion()}`, enabled: false, }, { label: 'Changelog', click() { shell.openExternal('https://movieprint.org/download/'); }, }, { label: 'Credits', click() { shell.openExternal('https://movieprint.org/credits/'); }, }, ], }; const menuArray = process.env.NODE_ENV === 'development' || process.env.DEBUG_PROD === 'true' || process.argv.findIndex(value => value === '--debug') > -1 ? [subMenuAbout, subMenuEdit, subMenuView, subMenuWindow, subMenuHelp, subMenuDev] : [subMenuAbout, subMenuEdit, subMenuView, subMenuWindow, subMenuHelp]; return menuArray; } buildDefaultTemplate() { const subMenuAbout = { label: '&File', submenu: [ // { // label: '&Open', // accelerator: 'Ctrl+O' // }, { type: 'separator' }, { label: '&Close', accelerator: 'Ctrl+W', click: () => { app.quit(); }, }, ], }; const subMenuEdit = { label: 'Edit', submenu: [ { label: 'Undo', accelerator: 'Ctrl+Z', click: () => { this.mainWindow.send('undo'); }, }, { label: 'Redo', accelerator: 'Shift+Ctrl+Z', click: () => { this.mainWindow.send('redo'); }, }, { type: 'separator' }, { label: 'Cut', accelerator: 'Ctrl+X', selector: 'cut:' }, { label: 'Copy', accelerator: 'Ctrl+C', selector: 'copy:' }, { label: 'Paste', accelerator: 'Ctrl+V', selector: 'paste:' }, { label: 'Select All', accelerator: 'Ctrl+A', selector: 'selectAll:' }, ], }; const subMenuDev = { label: 'Development', submenu: [ { label: 'Reset application', accelerator: 'Shift+Alt+Ctrl+C', click: () => { resetApplication(this.mainWindow, this.workerWindow, this.opencvWorkerWindow, this.databaseWorkerWindow); }, }, { label: 'Soft reset application', accelerator: 'Shift+Alt+Ctrl+V', click: () => { softResetApplication( this.mainWindow, this.workerWindow, this.opencvWorkerWindow, this.databaseWorkerWindow, ); }, }, { label: '&Reload application', accelerator: 'Ctrl+R', click: () => { reloadApplication(this.mainWindow, this.workerWindow, this.opencvWorkerWindow, this.databaseWorkerWindow); }, }, { label: 'Reload mainWindow', accelerator: 'Ctrl+R', click: () => { this.mainWindow.webContents.reload(); }, }, { label: 'Reload Worker', accelerator: 'Alt+Ctrl+R', click: () => { this.workerWindow.webContents.reload(); }, }, { label: 'Reload Opencv Worker', accelerator: 'Shift+Ctrl+R', click: () => { this.opencvWorkerWindow.webContents.reload(); }, }, { label: 'Reload Database Worker', accelerator: 'Alt+Shift+Ctrl+R', click: () => { this.databaseWorkerWindow.webContents.reload(); }, }, { label: 'Toggle Developer Tools', accelerator: 'Alt+Ctrl+I', click: () => { this.mainWindow.toggleDevTools(); }, }, { label: 'Toggle Developer Tools for Worker', accelerator: 'Alt+Ctrl+J', click: () => { this.workerWindow.toggleDevTools(); }, }, { label: 'Toggle Developer Tools for Opencv Worker', accelerator: 'Alt+Ctrl+K', click: () => { this.opencvWorkerWindow.toggleDevTools(); }, }, { label: 'Toggle Developer Tools for Database Worker', accelerator: 'Alt+Shift+Ctrl+K', click: () => { this.databaseWorkerWindow.toggleDevTools(); }, }, { label: 'Show Worker', click: () => { this.workerWindow.show(); }, }, { label: 'Show OpenCv Worker', click: () => { this.opencvWorkerWindow.show(); }, }, { label: 'Show Database Worker', click: () => { this.databaseWorkerWindow.show(); }, }, { label: 'Show log file', click: () => { const { pathOfLogFile, pathOfLogFolder} = getPathOfLogFileAndFolder(process.platform, app.getName()); if (fs.existsSync(pathOfLogFile)) { shell.showItemInFolder(pathOfLogFile); } else { shell.showItemInFolder(pathOfLogFolder); } }, }, { label: 'Show database file', click: () => { const moviePrintDBPath = path.join(app.getPath('userData'), 'moviePrint_frames.db'); if (fs.existsSync(moviePrintDBPath)) { shell.showItemInFolder(moviePrintDBPath); } else { shell.showItemInFolder(app.getPath('userData')); } }, }, ], }; const subMenuView = { label: 'View', submenu: [ { label: 'Toggle &Full Screen', accelerator: 'F11', click: () => { this.mainWindow.setFullScreen(!this.mainWindow.isFullScreen()); }, }, { label: 'Fit MoviePrint', accelerator: 'Ctrl+0', click: () => { this.mainWindow.webContents.send('send-zoom-level', 'resetZoom'); }, }, { label: 'Zoom In', accelerator: 'Ctrl+=', click: () => { this.mainWindow.webContents.send('send-zoom-level', 'zoomIn'); }, }, { label: 'Zoom Out', accelerator: 'Ctrl+-', click: () => { this.mainWindow.webContents.send('send-zoom-level', 'zoomOut'); }, }, { type: 'separator' }, { label: 'Reload application', accelerator: 'Ctrl+R', click: () => { reloadApplication(this.mainWindow, this.workerWindow, this.opencvWorkerWindow, this.databaseWorkerWindow); }, }, { label: 'Reset application', accelerator: 'Shift+Alt+Ctrl+C', click: () => { resetApplication(this.mainWindow, this.workerWindow, this.opencvWorkerWindow, this.databaseWorkerWindow); }, }, { type: 'separator' }, { label: 'Restart in debug mode', accelerator: 'Shift+Alt+Ctrl+X', click: () => { app.relaunch({ args: process.argv.slice(1).concat(['--debug']), }); app.exit(0); }, }, ], }; const subMenuWindow = { label: 'Window', submenu: [ { label: 'Main window', click: () => { this.mainWindow.show(); }, }, { label: 'Minimize', accelerator: 'Ctrl+M', selector: 'performMiniaturize:' }, { type: 'separator' }, { label: 'Bring All to Front', selector: 'arrangeInFront:' }, ], }; const subMenuHelp = { label: 'Help', submenu: [ { label: 'Help', click() { shell.openExternal('https://movieprint.org/help/'); }, }, { type: 'separator' }, { label: 'Development', click() { shell.openExternal('https://github.com/fakob/MoviePrint_v004'); }, }, { label: 'Search Issues', click() { shell.openExternal('https://github.com/fakob/MoviePrint_v004/issues'); }, }, { type: 'separator' }, { label: `MoviePrint version: ${app.getVersion()}`, enabled: false, }, { label: 'Changelog', click() { shell.openExternal('https://movieprint.org/download/'); }, }, { label: 'Credits', click() { shell.openExternal('https://movieprint.org/credits/'); }, }, ], }; const menuArray = process.env.NODE_ENV === 'development' || process.env.DEBUG_PROD === 'true' || process.argv.findIndex(value => value === '--debug') > -1 ? [subMenuAbout, subMenuEdit, subMenuView, subMenuWindow, subMenuHelp, subMenuDev] : [subMenuAbout, subMenuEdit, subMenuView, subMenuWindow, subMenuHelp]; return menuArray; } } <|start_filename|>app/app.global.css<|end_filename|> /* * @NOTE: Prepend a `~` to css file paths that are in your node_modules * See https://github.com/webpack-contrib/sass-loader#imports */ @import '~semantic-ui-css/semantic.min.css'; @import '~react-toastify/dist/ReactToastify.min.css'; @import '~typeface-open-sans'; @import '~typeface-roboto-condensed'; @import '~typeface-ubuntu'; @import '~rc-slider/assets/index.css'; @font-face { font-family: Franchise; src: url("./dist/Franchise-Bold.woff"); } .rc-slider-tooltip { z-index: 1000; } .rc-slider-disabled { opacity: 0.3; background-color: transparent; } body { color: white; } label { color: white; } mark { margin-left: 4px; margin-right: 4px; background-color: rgba(255, 80, 6, 0.9); color: white; white-space: nowrap; } mark::before { content: '\00a0\00a0'; } mark::after { content: '\00a0\00a0'; } /* width */ ::-webkit-scrollbar { width: 6px !important; } /* Track */ ::-webkit-scrollbar-track { background: #1e1e1e !important; } /* Handle */ ::-webkit-scrollbar-thumb { background: #1e1e1e !important; } /* Handle on hover */ ::-webkit-scrollbar-thumb:hover { background: #2c2c2c !important; } h6 { font-size: 0.7rem; } <|start_filename|>app/utils/saveThumb.js<|end_filename|> import pathR from 'path'; import log from 'electron-log'; import { DEFAULT_THUMB_JPG_QUALITY, DEFAULT_THUMB_FORMAT } from './constants'; import { ensureDirectoryExistence, getFilePathObject } from './utils'; import { getBase64Object } from './utilsForOpencv'; const { ipcRenderer } = require('electron'); const { app } = require('electron').remote; const saveThumb = ( filePath, fileUseRatio, movieFileName, sheetName, frameNumber, fileNameTemplate, frameId, transformObject, saveToFolder = '', overwrite = false, defaultThumbFormat = DEFAULT_THUMB_FORMAT, defaultThumbJpgQuality = DEFAULT_THUMB_JPG_QUALITY, fps = 25, ) => { // save thumbs in folder with the same name as moviePrint let newFolderName = app.getPath('desktop'); if (saveToFolder) { newFolderName = saveToFolder; ensureDirectoryExistence(newFolderName); } const frameSize = 0; // save frame in original size const newFilePathObject = getFilePathObject( movieFileName, sheetName, frameNumber, fileNameTemplate, defaultThumbFormat, newFolderName, overwrite, fps, ); const newFilePathAndName = pathR.join(newFilePathObject.dir, newFilePathObject.base); const thumbFormatObject = { defaultThumbFormat, defaultThumbJpgQuality, }; const base64Object = getBase64Object( filePath, fileUseRatio, [ { frameId, frameNumber, }, ], frameSize, transformObject, thumbFormatObject, true, ); const base64 = base64Object[frameId]; if (base64 === '') { ipcRenderer.send('message-from-workerWindow-to-mainWindow', 'received-saved-file-error', 'Frame is empty'); } else { const buf = Buffer.from(base64, 'base64'); ipcRenderer.send('send-save-file', frameId, newFilePathAndName, buf); log.debug(`Saving ${JSON.stringify({ newFilePathAndName, size: buf.length })}`); } }; export default saveThumb; <|start_filename|>app/components/ErrorBoundary.js<|end_filename|> import React, { Component } from 'react'; import { Button, Divider } from 'semantic-ui-react'; import log from 'electron-log'; import styles from './ErrorBoundary.css'; const { ipcRenderer } = require('electron'); class ErrorBoundary extends Component { constructor(props) { super(props); this.state = { hasError: false }; this.onReloadClick = this.onReloadClick.bind(this); this.onResetClick = this.onResetClick.bind(this); } componentDidCatch(error, info) { // Display fallback UI this.setState({ hasError: true }); // You can also log the error to an error reporting service log.error(error); log.warn(info); } onReloadClick() { log.info('reloadclick'); ipcRenderer.send('reload-application'); } onResetClick() { log.info('resetclick'); ipcRenderer.send('reset-application'); } render() { if (this.state.hasError) { // You can render any custom fallback UI return ( <div className={`${styles.ErrorContainer}`}> <div className={`${styles.ErrorContent}`}> SOMETHING WENT WRONG {/* <Divider /> */} <Button.Group size="huge" // compact style={{ // marginRight: '20px' }} > <Button content="Reset" onClick={this.onResetClick} /> <Button.Or /> <Button positive content="Reload" onClick={this.onReloadClick} /> </Button.Group> </div> </div> ); } return this.props.children; } } export default ErrorBoundary; <|start_filename|>app/components/ThumbGridHeader.js<|end_filename|> import React from 'react'; import PropTypes from 'prop-types'; import log from 'electron-log'; import { truncatePath, getTextWidth } from '../utils/utils'; import { DEFAULT_MIN_MOVIEPRINTWIDTH_MARGIN } from '../utils/constants'; import styles from './ThumbGrid.css'; // import movieprint from './../img/Thumb_MOVIEPRINT.png'; import movieprint from './../img/MoviePrint-titleimage.svg'; const ThumbGridHeader = ({ filePath, fileName, fileDetails, showPathInHeader, showDetailsInHeader, showTimelineInHeader, moviePrintWidth, headerHeight, logoHeight, thumbMargin, inPointPositionOnTimeline, cutWidthOnTimeLine, allFrameNumbersInPercentArray, isViewForPrinting, }) => { const headerMarginRatioTop = 0.25; // 25% of height const headerImageRatio = 0.5; // 50% of height const textRatio = 0.25; // 25% of height // calculate title text size const widthOfFileNameL = 20 + // 20 is an estimated value found via manual calibration getTextWidth(fileName, `bold ${logoHeight * textRatio * 1.5}px "Open sans"`); const widthOfFileNameS = 0 + // 20 is an estimated value found via manual calibration getTextWidth(fileName, `bold ${logoHeight * textRatio * 1.2}px "Open sans"`); const logoAspectRatio = 385 / 69.0; const spaceForFileName = moviePrintWidth - (logoHeight * textRatio * 8) - // padding left and right and some extra (logoHeight * headerImageRatio * logoAspectRatio) // logo width let fileNameRatio; let titleTextSize; let titleText = fileName; if (spaceForFileName > widthOfFileNameL) { // log.debug('enough space for title'); fileNameRatio = 1; titleTextSize = logoHeight * textRatio * 1.5; } else if (spaceForFileName > widthOfFileNameS) { // log.debug('shrink font size a bit'); fileNameRatio = spaceForFileName / widthOfFileNameL; // log.debug(fileNameRatio); titleTextSize = logoHeight * textRatio * 1.5 * fileNameRatio; } else { // log.debug('use small font size a truncate text'); fileNameRatio = spaceForFileName / widthOfFileNameS; titleTextSize = logoHeight * textRatio * 1.2; const lengthOfFileName = fileName.length; const newLengthOfFileName = Math.floor(fileNameRatio * lengthOfFileName); titleText = truncatePath(fileName, newLengthOfFileName); } return ( <div data-tid='thumbGridHeaderDiv' className={styles.gridHeader} style={{ height: headerHeight, marginBottom: thumbMargin, marginLeft: thumbMargin, marginRight: thumbMargin * 2 + (isViewForPrinting ? 0 : DEFAULT_MIN_MOVIEPRINTWIDTH_MARGIN), }} > <div className={styles.gridHeaderImageAndText} style={{ transform: `translate(0px, ${logoHeight * headerMarginRatioTop}px)`, width: '100%', }} > <img data-tid='gridHeaderImg' className={styles.gridHeaderImage} src={movieprint} alt="" height={`${logoHeight * headerImageRatio}px`} style={{ paddingLeft: `${logoHeight * textRatio}px`, }} /> <div className={styles.gridHeaderText} style={{ fontSize: `${logoHeight * textRatio}px`, float: 'right', paddingRight: `${logoHeight * textRatio}px`, lineHeight: `${logoHeight * textRatio * 1.8}px`, }} > <div data-tid='movieTitleText' className={styles.gridHeaderTextName} style={{ fontSize: `${titleTextSize}px`, marginBottom: `${logoHeight * textRatio * 0.5}px`, }} > {titleText} </div> {showPathInHeader && <div data-tid='filePathText' style={{ lineHeight: `${logoHeight * textRatio * 1.5}px`, textAlign: 'right', }} > {(filePath !== '') && `${filePath.substr(0, filePath.lastIndexOf('/'))}/`} </div>} {showDetailsInHeader && <div data-tid='fileDetailsText' style={{ lineHeight: `${logoHeight * textRatio * 1.5}px`, textAlign: 'right', }} > {fileDetails} </div>} </div> {showTimelineInHeader && <div data-tid='timelineWrapperDiv' className={styles.timelineWrapper} style={{ height: `${logoHeight * textRatio * 1.2}px`, marginLeft: `${logoHeight * textRatio}px`, marginRight: `${logoHeight * textRatio}px`, }} > <div className={`${styles.timelineCut}`} style={{ left: `${inPointPositionOnTimeline}%`, width: `${cutWidthOnTimeLine}%`, }} /> {allFrameNumbersInPercentArray.map(frameInPercent => ( <div key={frameInPercent} className={`${styles.timelineThumbIndicator}`} style={{ left: `${frameInPercent}%`, height: `${logoHeight * textRatio * 1.2}px`, }} /> ) )} </div>} </div> </div> ); }; ThumbGridHeader.defaultProps = { }; ThumbGridHeader.propTypes = { filePath: PropTypes.string.isRequired, fileName: PropTypes.string.isRequired, fileDetails: PropTypes.string.isRequired, headerHeight: PropTypes.number.isRequired, logoHeight: PropTypes.number.isRequired, thumbMargin: PropTypes.number.isRequired, }; export default ThumbGridHeader; <|start_filename|>app/components/FileListElement.js<|end_filename|> // @flow import React, { useEffect, useRef, useState } from 'react'; import PropTypes from 'prop-types'; import { Button, Image, Input, Icon, Popup, Dropdown, Label } from 'semantic-ui-react'; import { truncate, truncatePath, frameCountToTimeCode, formatBytes, sanitizeString } from '../utils/utils'; import styles from './FileList.css'; import stylesPop from './Popup.css'; import { EXPORT_FORMAT_OPTIONS, SHEET_TYPE, SHEET_VIEW } from '../utils/constants'; const FileListElement = ({ currentFileId, currentSheetId, fileId, fileMissingStatus, fileScanStatus, fps, frameCount, height, name, objectUrl, onAddIntervalSheetClick, onChangeSheetViewClick, onDeleteSheetClick, onConvertToIntervalBasedClick, onDuplicateSheetClick, onEditTransformListItemClick, onExportSheetClick, onFileListElementClick, onOpenFileExplorer, onRemoveMovieListItem, onReplaceMovieListItemClick, onScanMovieListItemClick, onSetSheetClick, onSubmitMoviePrintNameClick, path, sheetsObject, size, width, }) => { const inputRef = useRef(null); const [input, setInput] = useState({ isRenaming: false, // initial state isHovering: false, // initial state }); const sheetsArray = Object.getOwnPropertyNames(sheetsObject); const onSubmitMoviePrintName = (e, sheetId) => { // console.log(e.currentTarget.value); if (e.key === 'Enter' || e.key === undefined) { const value = sanitizeString(e.target.value); // console.log(value); e.stopPropagation(); onSubmitMoviePrintNameClick(fileId, sheetId, value); setInput({ ...input, [e.currentTarget.name]: value, isRenaming: false, // reset isRenaming isHovering: false, // reset isHovering }); } }; useEffect(() => { if (input.isRenaming) { inputRef.current.select(); } }, [input.isRenaming]); const onStartRenameClickWithStop = (e, sheetId) => { e.stopPropagation(); let valueToSet; if (input.isRenaming === sheetId) { valueToSet = false; } else { valueToSet = sheetId; } setInput({ ...input, isRenaming: valueToSet, }); }; const onMouseEnterElement = (e, sheetId) => { e.stopPropagation(); // let valueToSet; // if (input.isHovering === sheetId) { // valueToSet = false; // } else { // valueToSet = sheetId; // } setInput({ ...input, isHovering: sheetId, }); }; const onMouseLeaveElement = (e, sheetId) => { e.stopPropagation(); // let valueToSet; // if (input.isHovering === sheetId) { // valueToSet = false; // } else { // valueToSet = sheetId; // } setInput({ ...input, isHovering: false, }); }; function getSheetIcon(sheetView) { switch (sheetView) { case SHEET_VIEW.GRIDVIEW: return 'grid layout'; case SHEET_VIEW.TIMELINEVIEW: return 'barcode'; default: return 'exclamation'; } } function onRemoveMovieListItemClickWithStop(e, fileId) { e.stopPropagation(); onRemoveMovieListItem(fileId); } function onSheetClickWithStop(e, fileId, sheetId, sheetView) { e.stopPropagation(); onSetSheetClick(fileId, sheetId, sheetView); } function onChangeSheetViewClickWithStop(e, fileId, sheetId, sheetView) { e.stopPropagation(); onChangeSheetViewClick(fileId, sheetId, sheetView); } function onConvertToIntervalBasedClickWithStop(e, fileId, sheetId) { e.stopPropagation(); onConvertToIntervalBasedClick(fileId, sheetId); } function onDuplicateSheetClickWithStop(e, fileId, sheetId) { e.stopPropagation(); onDuplicateSheetClick(fileId, sheetId); } function onExportSheetClickWithStop(e, fileId, sheetId, exportType) { e.stopPropagation(); onExportSheetClick(fileId, sheetId, exportType, fps); } function onDeleteSheetClickWithStop(e, fileId, sheetId) { e.stopPropagation(); onDeleteSheetClick(fileId, sheetId); } function onFileListElementClickWithStop(e, fileId) { e.stopPropagation(); onFileListElementClick(fileId); } function onScanMovieListItemClickWithStop(e, fileId) { e.stopPropagation(); onScanMovieListItemClick(fileId); } function onAddIntervalSheetClickWithStop(e, fileId) { e.stopPropagation(); onAddIntervalSheetClick(fileId); } function onEditTransformListItemClickWithStop(e, fileId) { e.stopPropagation(); onEditTransformListItemClick(fileId); } function onReplaceMovieListItemClickWithStop(e, fileId) { e.stopPropagation(); onReplaceMovieListItemClick(fileId); } return ( <li data-tid={`fileListItem_${fileId}`} onClick={e => (fileMissingStatus === true ? null : onFileListElementClickWithStop(e, fileId))} className={`${styles.FileListItem} ${currentFileId === fileId ? styles.Highlight : ''} ${ fileMissingStatus === true ? styles.Missing : '' }`} > {fileMissingStatus === true && ( <div className={`${styles.fileMissingContainer}`}> <div className={`${styles.fileMissing}`}>Movie is missing</div> <Popup trigger={ <Button data-tid="findfileBtn" size="mini" inverted className={`${styles.fileMissingButton}`} onClick={e => onReplaceMovieListItemClickWithStop(e, fileId)} > Locate movie </Button> } mouseEnterDelay={1000} on={['hover']} position="bottom center" className={stylesPop.popup} content="Locate the missing movie" /> <Popup trigger={ <Button data-tid="removeFileBtn" size="mini" inverted className={`${styles.fileMissingButton}`} onClick={e => onRemoveMovieListItemClickWithStop(e, fileId)} > Remove </Button> } mouseEnterDelay={1000} on={['hover']} position="bottom center" className={stylesPop.popup} content="Remove movie from list" /> </div> )} <Dropdown data-tid="movieListItemOptionsDropdown" item direction="left" icon="ellipsis vertical" className={`${styles.overflow} ${styles.overflowHidden}`} > <Dropdown.Menu> {fileMissingStatus !== true && ( <Dropdown.Item data-tid="changeCroppingListItemOption" icon="crop" text="Edit rotation, cropping and aspect ratio" onClick={e => onEditTransformListItemClickWithStop(e, fileId)} /> )} <Dropdown.Item data-tid="openFileExplorerItemOption" icon="external alternate" text="Open file location" onClick={() => onOpenFileExplorer(path)} /> <Dropdown.Item data-tid="replaceMovieListItemOption" icon="exchange" text="Replace movie" onClick={e => onReplaceMovieListItemClickWithStop(e, fileId)} /> <Dropdown.Item data-tid="removeMovieListItemOption" icon="delete" text="Remove from list" onClick={e => onRemoveMovieListItemClickWithStop(e, fileId)} /> </Dropdown.Menu> </Dropdown> <Image as="div" floated="left" className={`${styles.croppedThumb}`} style={{ backgroundColor: '#1e1e1e', backgroundImage: `url(${objectUrl})`, }} > {fileScanStatus && ( <Label as="a" color="orange" size="mini" circular alt="Movie has been scanned" className={`${styles.ThumbLabel}`} > S </Label> )} </Image> <div className={`${styles.Title}`} title={`${fileMissingStatus === true ? 'MISSING: ' : ''}${name}`}> {truncate(name, 48)} </div> <div className={`${styles.Path}`} title={`${fileMissingStatus === true ? 'MISSING: ' : ''}${path.slice(0, path.lastIndexOf('/'))}`} > {truncatePath(path.slice(0, path.lastIndexOf('/')), 40)} </div> <div className={`${styles.Detail}`}> <div className={`${styles.DetailLeft}`}>{frameCountToTimeCode(frameCount, fps)}</div> <div className={`${styles.DetailRight}`}>{formatBytes(size, 1)}</div> <div className={`${styles.DetailCenter}`}> {width} x {height} </div> </div> <ul className={`${styles.SheetList}`}> {sheetsArray.map((sheetId, index) => ( <li key={sheetId} index={index} data-tid={`sheetListItem_${fileId}`} onClick={e => onSheetClickWithStop(e, fileId, sheetId, sheetsObject[sheetId].sheetView)} className={`${styles.SheetListItem} ${currentSheetId === sheetId ? styles.SheetHighlight : ''}`} title={`${sheetsObject[sheetId].type} based`} > {/* {(currentSheetId === sheetId) && <Label size='mini' horizontal className={`${styles.SheetLabel}`} > Selected sheet </Label>} */} {input.isRenaming !== sheetId && ( <> <span className={`${styles.SheetName}`} title={sheetsObject[sheetId].name}> <Icon onMouseEnter={e => onMouseEnterElement(e, sheetId)} onMouseLeave={e => onMouseLeaveElement(e)} name={input.isHovering !== sheetId ? getSheetIcon(sheetsObject[sheetId].sheetView) : 'edit'} inverted onClick={e => onStartRenameClickWithStop(e, sheetId)} role="button" /> &nbsp;{sheetsObject[sheetId].name} </span> <Label size="mini" horizontal className={`${styles.SheetLabel} ${ sheetsObject[sheetId].type === SHEET_TYPE.SCENES ? styles.shotBased : sheetsObject[sheetId].type === SHEET_TYPE.FACES ? styles.facesBased : '' }`} > {`${sheetsObject[sheetId].type} based`} </Label> </> )} {input.isRenaming === sheetId && ( <span className={`${styles.SheetNameInputContainer}`}> <Icon name="edit" inverted // size='small' /> <Input data-tid="moviePrintNameInput" name="moviePrintNameInput" focus ref={inputRef} className={`${styles.SheetNameInput}`} transparent placeholder="Name this MoviePrint" defaultValue={sheetsObject[sheetId].name} onBlur={e => onSubmitMoviePrintName(e, sheetId)} onKeyUp={e => onSubmitMoviePrintName(e, sheetId)} /> </span> )} {fileMissingStatus !== true && ( <Dropdown data-tid="sheetItemOptionsDropdown" item direction="left" icon="ellipsis vertical" className={`${styles.overflow} ${styles.overflowHidden}`} > <Dropdown.Menu> <Dropdown.Item data-tid="renameSheetItemOption" icon="edit" text="Rename" onClick={e => onStartRenameClickWithStop(e, sheetId)} /> {sheetsObject[sheetId].sheetView === SHEET_VIEW.TIMELINEVIEW && ( <Dropdown.Item data-tid="changeViewSheetToGridViewItemOption" icon="grid layout" text="Switch to grid view" onClick={e => onChangeSheetViewClickWithStop(e, fileId, sheetId, SHEET_VIEW.GRIDVIEW)} /> )} {sheetsObject[sheetId].sheetView === SHEET_VIEW.GRIDVIEW && ( <Dropdown.Item data-tid="changeViewSheetToTimelineViewItemOption" icon="barcode" text="Switch to timeline view" disabled={sheetsObject[sheetId].type === SHEET_TYPE.FACES} onClick={e => onChangeSheetViewClickWithStop(e, fileId, sheetId, SHEET_VIEW.TIMELINEVIEW)} /> )} <Dropdown.Item data-tid="convertToIntervalBasedItemOption" icon="copy" text="Convert to interval based" disabled={sheetsObject[sheetId].type === SHEET_TYPE.INTERVAL} onClick={e => onConvertToIntervalBasedClickWithStop(e, fileId, sheetId)} /> <Dropdown.Item data-tid="duplicateSheetItemOption" icon="copy" text="Duplicate" onClick={e => onDuplicateSheetClickWithStop(e, fileId, sheetId)} /> <Dropdown.Item data-tid="exportSheetItemOption" icon="download" text="Export JSON" onClick={e => onExportSheetClickWithStop(e, fileId, sheetId, EXPORT_FORMAT_OPTIONS.JSON)} /> {sheetsObject[sheetId].type === SHEET_TYPE.SCENES && ( <Dropdown.Item data-tid="exportSheetItemOption" icon="download" text="Export EDL" onClick={e => onExportSheetClickWithStop(e, fileId, sheetId, EXPORT_FORMAT_OPTIONS.EDL)} /> )} <Dropdown.Item data-tid="deleteSheetItemOption" icon="delete" text="Delete" onClick={e => onDeleteSheetClickWithStop(e, fileId, sheetId)} /> </Dropdown.Menu> </Dropdown> )} </li> ))} </ul> </li> ); }; FileListElement.propTypes = { fileId: PropTypes.string.isRequired, frameCount: PropTypes.number, fps: PropTypes.number, width: PropTypes.number, height: PropTypes.number, objectUrl: PropTypes.string, currentFileId: PropTypes.string, name: PropTypes.string.isRequired, path: PropTypes.string.isRequired, size: PropTypes.number.isRequired, onFileListElementClick: PropTypes.func.isRequired, }; export default FileListElement; <|start_filename|>app/actions/index.js<|end_filename|> import uuidV4 from 'uuid/v4'; import log from 'electron-log'; import imageDB from '../utils/db'; import { deleteTableFramelist } from '../utils/utilsForIndexedDB'; import { deleteTableFrameScanList } from '../utils/utilsForSqlite'; import { limitRange } from '../utils/utils'; import { getIntervalArray, sortArray } from '../utils/utilsSortAndFilter'; import { TRANSFORMOBJECT_INIT } from '../utils/constants'; const { ipcRenderer } = require('electron'); // visibilitySettings export const setVisibilityFilter = filter => { log.debug(`action: setVisibilityFilter - ${filter}`); return { type: 'SET_VISIBILITY_FILTER', filter, }; }; export const toggleMovielist = () => { log.debug('action: toggleMovielist'); return { type: 'TOGGLE_MOVIELIST', }; }; export const showMovielist = () => { log.debug('action: showMovielist'); return { type: 'SHOW_MOVIELIST', }; }; export const hideMovielist = () => { log.debug('action: hideMovielist'); return { type: 'HIDE_MOVIELIST', }; }; export const toggleSettings = () => { log.debug('action: toggleSettings'); return { type: 'TOGGLE_SETTINGS', }; }; export const showSettings = () => { log.debug('action: showSettings'); return { type: 'SHOW_SETTINGS', }; }; export const hideSettings = () => { log.debug('action: hideSettings'); return { type: 'HIDE_SETTINGS', }; }; export const setView = defaultView => { log.debug(`action: setView - ${defaultView}`); return { type: 'SET_VIEW', defaultView, }; }; // defaultSheetView is used for player mode (cut or thumb view) export const setDefaultSheetView = defaultSheetView => { log.debug(`action: setDefaultSheetView - ${defaultSheetView}`); return { type: 'SET_SHEETVIEW', defaultSheetView, }; }; export const setZoomLevel = defaultZoomLevel => { log.debug(`action: setZoomLevel - ${defaultZoomLevel}`); return { type: 'SET_ZOOMLEVEL', defaultZoomLevel, }; }; // settings export const setCurrentSheetId = currentSheetId => { log.debug(`action: setCurrentSheetId - ${currentSheetId}`); return { type: 'SET_CURRENT_SHEETID', currentSheetId, }; }; export const setCurrentFileId = fileId => { log.debug(`action: setCurrentFileId - ${fileId}`); return { type: 'SET_CURRENT_FILEID', fileId, }; }; export const setDefaultThumbCount = defaultThumbCount => { log.debug(`action: setDefaultThumbCount - ${defaultThumbCount}`); return { type: 'SET_DEFAULT_THUMB_COUNT', defaultThumbCount, }; }; export const setDefaultColumnCount = defaultColumnCount => { log.debug(`action: setDefaultColumnCount - ${defaultColumnCount}`); return { type: 'SET_DEFAULT_COLUMN_COUNT', defaultColumnCount, }; }; export const setDefaultThumbnailScale = defaultThumbnailScale => { log.debug(`action: setDefaultThumbnailScale - ${defaultThumbnailScale}`); return { type: 'SET_DEFAULT_THUMBNAIL_SCALE', defaultThumbnailScale, }; }; export const setDefaultMoviePrintWidth = defaultMoviePrintWidth => { log.debug(`action: setDefaultMoviePrintWidth - ${defaultMoviePrintWidth}`); return { type: 'SET_DEFAULT_MOVIEPRINT_WIDTH', defaultMoviePrintWidth, }; }; export const setDefaultMarginRatio = defaultMarginRatio => { log.debug(`action: setDefaultMarginRatio - ${defaultMarginRatio}`); return { type: 'SET_DEFAULT_MARGIN', defaultMarginRatio, }; }; export const setDefaultShowHeader = defaultShowHeader => { log.debug(`action: setDefaultShowHeader - ${defaultShowHeader}`); return { type: 'SET_DEFAULT_SHOW_HEADER', defaultShowHeader, }; }; export const setDefaultShowImages = defaultShowImages => { log.debug(`action: setDefaultShowImages - ${defaultShowImages}`); return { type: 'SET_DEFAULT_SHOW_IMAGES', defaultShowImages, }; }; export const setDefaultShowPathInHeader = defaultShowPathInHeader => { log.debug(`action: setDefaultShowPathInHeader - ${defaultShowPathInHeader}`); return { type: 'SET_DEFAULT_PATH_IN_HEADER', defaultShowPathInHeader, }; }; export const setDefaultShowDetailsInHeader = defaultShowDetailsInHeader => { log.debug(`action: setDefaultShowDetailsInHeader - ${defaultShowDetailsInHeader}`); return { type: 'SET_DEFAULT_DETAILS_IN_HEADER', defaultShowDetailsInHeader, }; }; export const setDefaultShowTimelineInHeader = defaultShowTimelineInHeader => { log.debug(`action: setDefaultShowTimelineInHeader - ${defaultShowTimelineInHeader}`); return { type: 'SET_DEFAULT_TIMELINE_IN_HEADER', defaultShowTimelineInHeader, }; }; export const setDefaultRoundedCorners = defaultRoundedCorners => { log.debug(`action: setDefaultRoundedCorners - ${defaultRoundedCorners}`); return { type: 'SET_DEFAULT_ROUNDED_CORNERS', defaultRoundedCorners, }; }; export const setDefaultThumbInfo = defaultThumbInfo => { log.debug(`action: setDefaultThumbInfo - ${defaultThumbInfo}`); return { type: 'SET_DEFAULT_THUMB_INFO', defaultThumbInfo, }; }; export const setDefaultOutputPath = defaultOutputPath => { log.debug(`action: setDefaultOutputPath - ${defaultOutputPath}`); return { type: 'SET_DEFAULT_OUTPUT_PATH', defaultOutputPath, }; }; export const setDefaultOutputFormat = defaultOutputFormat => { log.debug(`action: setDefaultOutputFormat - ${defaultOutputFormat}`); return { type: 'SET_DEFAULT_OUTPUT_FORMAT', defaultOutputFormat, }; }; export const setDefaultOutputJpgQuality = defaultOutputJpgQuality => { log.debug(`action: setDefaultOutputJpgQuality - ${defaultOutputJpgQuality}`); return { type: 'SET_DEFAULT_OUTPUT_JPG_QUALITY', defaultOutputJpgQuality, }; }; export const setDefaultThumbFormat = defaultThumbFormat => { log.debug(`action: setDefaultThumbFormat - ${defaultThumbFormat}`); return { type: 'SET_DEFAULT_THUMB_FORMAT', defaultThumbFormat, }; }; export const setDefaultThumbJpgQuality = defaultThumbJpgQuality => { log.debug(`action: setDefaultThumbJpgQuality - ${defaultThumbJpgQuality}`); return { type: 'SET_DEFAULT_THUMB_JPG_QUALITY', defaultThumbJpgQuality, }; }; export const setDefaultCachedFramesSize = defaultCachedFramesSize => { log.debug(`action: setDefaultCachedFramesSize - ${defaultCachedFramesSize}`); return { type: 'SET_DEFAULT_CACHED_FRAMES_SIZE', defaultCachedFramesSize, }; }; export const setDefaultSaveOptionOverwrite = defaultSaveOptionOverwrite => { log.debug(`action: setDefaultSaveOptionOverwrite - ${defaultSaveOptionOverwrite}`); return { type: 'SET_DEFAULT_SAVE_OPTION_OVERWRITE', defaultSaveOptionOverwrite, }; }; export const setDefaultSaveOptionIncludeIndividual = defaultSaveOptionIncludeIndividual => { log.debug(`action: setDefaultSaveOptionIncludeIndividual - ${defaultSaveOptionIncludeIndividual}`); return { type: 'SET_DEFAULT_SAVE_OPTION_INCLUDE_INDIVIDUAL', defaultSaveOptionIncludeIndividual, }; }; export const setDefaultEmbedFrameNumbers = defaultEmbedFrameNumbers => { log.debug(`action: setDefaultEmbedFrameNumbers - ${defaultEmbedFrameNumbers}`); return { type: 'SET_DEFAULT_EMBED_FRAMENUMBERS', defaultEmbedFrameNumbers, }; }; export const setDefaultEmbedFilePath = defaultEmbedFilePath => { log.debug(`action: setDefaultEmbedFilePath - ${defaultEmbedFilePath}`); return { type: 'SET_DEFAULT_EMBED_FILEPATH', defaultEmbedFilePath, }; }; export const setDefaultShowPaperPreview = defaultShowPaperPreview => { log.debug(`action: setDefaultShowPaperPreview - ${defaultShowPaperPreview}`); return { type: 'SET_DEFAULT_SHOW_PAPER_PREVIEW', defaultShowPaperPreview, }; }; export const setDefaultPaperAspectRatioInv = defaultPaperAspectRatioInv => { log.debug(`action: setDefaultPaperAspectRatioInv - ${defaultPaperAspectRatioInv}`); return { type: 'SET_DEFAULT_PAPER_ASPECT_RATIO_INV', defaultPaperAspectRatioInv, }; }; export const setDefaultDetectInOutPoint = defaultDetectInOutPoint => { log.debug(`action: setDefaultDetectInOutPoint - ${defaultDetectInOutPoint}`); return { type: 'SET_DEFAULT_DETECT_INOUTPOINT', defaultDetectInOutPoint, }; }; export const setEmailAddress = emailAddress => { log.debug(`action: setEmailAddress - ${emailAddress}`); return { type: 'SET_EMAIL_ADDRESS', emailAddress, }; }; export const setDefaultSceneDetectionThreshold = defaultSceneDetectionThreshold => { log.debug(`action: setDefaultSceneDetectionThreshold - ${defaultSceneDetectionThreshold}`); return { type: 'SET_DEFAULT_SCENE_DETECTION_THRESHOLD', defaultSceneDetectionThreshold, }; }; export const setDefaultTimelineViewSecondsPerRow = defaultTimelineViewSecondsPerRow => { log.debug(`action: setDefaultTimelineViewSecondsPerRow - ${defaultTimelineViewSecondsPerRow}`); return { type: 'SET_DEFAULT_TIMELINEVIEW_SECONDS_PER_ROW', defaultTimelineViewSecondsPerRow, }; }; export const setDefaultTimelineViewMinDisplaySceneLengthInFrames = defaultTimelineViewMinDisplaySceneLengthInFrames => { log.debug( `action: setDefaultTimelineViewMinDisplaySceneLengthInFrames - ${defaultTimelineViewMinDisplaySceneLengthInFrames}`, ); return { type: 'SET_DEFAULT_TIMELINEVIEW_MIN_DISPLAY_SCENE_LENGTH_IN_FRAMES', defaultTimelineViewMinDisplaySceneLengthInFrames, }; }; export const setDefaultTimelineViewWidthScale = defaultTimelineViewWidthScale => { log.debug(`action: setDefaultTimelineViewWidthScale - ${defaultTimelineViewWidthScale}`); return { type: 'SET_DEFAULT_TIMELINEVIEW_PIXEL_PER_FRAME_RATIO', defaultTimelineViewWidthScale, }; }; export const setDefaultTimelineViewFlow = defaultTimelineViewFlow => { log.debug(`action: setDefaultTimelineViewFlow - ${defaultTimelineViewFlow}`); return { type: 'SET_DEFAULT_TIMELINEVIEW_FLOW', defaultTimelineViewFlow, }; }; export const setDefaultOutputPathFromMovie = defaultOutputPathFromMovie => { log.debug(`action: setDefaultOutputPathFromMovie - ${defaultOutputPathFromMovie}`); return { type: 'SET_DEFAULT_OUTPUT_PATH_FROM_MOVIE', defaultOutputPathFromMovie, }; }; export const setDefaultShotDetectionMethod = defaultShotDetectionMethod => { log.debug(`action: setDefaultShotDetectionMethod - ${defaultShotDetectionMethod}`); return { type: 'SET_DEFAULT_SHOT_DETECTION_METHOD', defaultShotDetectionMethod, }; }; export const setDefaultMoviePrintBackgroundColor = defaultMoviePrintBackgroundColor => { log.debug(`action: setDefaultMoviePrintBackgroundColor - ${defaultMoviePrintBackgroundColor}`); return { type: 'SET_DEFAULT_MOVIEPRINT_BACKGROUND_COLOR', defaultMoviePrintBackgroundColor, }; }; export const setDefaultFrameinfoBackgroundColor = defaultFrameinfoBackgroundColor => { log.debug(`action: setDefaultFrameinfoBackgroundColor - ${defaultFrameinfoBackgroundColor}`); return { type: 'SET_DEFAULT_FRAMEINFO_BACKGROUND_COLOR', defaultFrameinfoBackgroundColor, }; }; export const setDefaultFrameinfoColor = defaultFrameinfoColor => { log.debug(`action: setDefaultFrameinfoColor - ${defaultFrameinfoColor}`); return { type: 'SET_DEFAULT_FRAMEINFO_COLOR', defaultFrameinfoColor, }; }; export const setDefaultFrameinfoPosition = defaultFrameinfoPosition => { log.debug(`action: setDefaultFrameinfoPosition - ${defaultFrameinfoPosition}`); return { type: 'SET_DEFAULT_FRAMEINFO_POSITION', defaultFrameinfoPosition, }; }; export const setDefaultFrameinfoScale = defaultFrameinfoScale => { log.debug(`action: setDefaultFrameinfoScale - ${defaultFrameinfoScale}`); return { type: 'SET_DEFAULT_FRAMEINFO_SCALE', defaultFrameinfoScale, }; }; export const setDefaultFrameinfoMargin = defaultFrameinfoMargin => { log.debug(`action: setDefaultFrameinfoMargin - ${defaultFrameinfoMargin}`); return { type: 'SET_DEFAULT_FRAMEINFO_MARGIN', defaultFrameinfoMargin, }; }; export const setDefaultMoviePrintName = defaultMoviePrintName => { log.debug(`action: setDefaultMoviePrintName - ${defaultMoviePrintName}`); return { type: 'SET_DEFAULT_MOVIEPRINT_NAME', defaultMoviePrintName, }; }; export const setDefaultSingleThumbName = defaultSingleThumbName => { log.debug(`action: setDefaultSingleThumbName - ${defaultSingleThumbName}`); return { type: 'SET_DEFAULT_SINGLETHUMB_NAME', defaultSingleThumbName, }; }; export const setDefaultAllThumbsName = defaultAllThumbsName => { log.debug(`action: setDefaultAllThumbsName - ${defaultAllThumbsName}`); return { type: 'SET_DEFAULT_ALLTHUMBS_NAME', defaultAllThumbsName, }; }; export const setDefaultOpenFileExplorerAfterSaving = defaultOpenFileExplorerAfterSaving => { log.debug(`action: setDefaultOpenFileExplorerAfterSaving - ${defaultOpenFileExplorerAfterSaving}`); return { type: 'SET_DEFAULT_OPEN_FILE_EXPLORER_AFTER_SAVING', defaultOpenFileExplorerAfterSaving, }; }; export const setDefaultFaceSizeThreshold = defaultFaceSizeThreshold => { log.debug(`action: setDefaultFaceSizeThreshold - ${defaultFaceSizeThreshold}`); return { type: 'SET_DEFAULT_FACE_SIZE_THRESHOLD', defaultFaceSizeThreshold, }; }; export const setDefaultFaceConfidenceThreshold = defaultFaceConfidenceThreshold => { log.debug(`action: setDefaultFaceConfidenceThreshold - ${defaultFaceConfidenceThreshold}`); return { type: 'SET_DEFAULT_FACE_CONFIDENCE_THRESHOLD', defaultFaceConfidenceThreshold, }; }; export const setDefaultFaceUniquenessThreshold = defaultFaceUniquenessThreshold => { log.debug(`action: setDefaultFaceUniquenessThreshold - ${defaultFaceUniquenessThreshold}`); return { type: 'SET_DEFAULT_FACE_UNIQUENESS_THRESHOLD', defaultFaceUniquenessThreshold, }; }; export const setDefaultShowFaceRect = defaultShowFaceRect => { log.debug(`action: setDefaultShowFaceRect - ${defaultShowFaceRect}`); return { type: 'SET_DEFAULT_SHOW_FACERECT', defaultShowFaceRect, }; }; // sheetsByFileId export const clearScenes = (fileId, sheetId) => { log.debug('action: clearScenes'); return { type: 'CLEAR_SCENES', payload: { fileId, sheetId, }, }; }; export const addScene = (fileId, sheetId, start, length, colorArray, sceneId = uuidV4()) => { return dispatch => { log.debug('action: addScene'); log.debug('dispatch: ADD_SCENE'); dispatch({ type: 'ADD_SCENE', payload: { sceneId, fileId, sheetId, start, length, colorArray, hidden: false, }, }); }; }; export const addScenesWithoutCapturingThumbs = (sceneArray, clearOldScenes = false) => { return dispatch => { log.debug('action: addScenesWithoutCapturingThumbs'); // add scenes log.debug('dispatch: ADD_SCENES'); dispatch({ type: 'ADD_SCENES', payload: { sceneArray, fileId: sceneArray[0].fileId, sheetId: sceneArray[0].sheetId, clearOldScenes, }, }); }; }; export const addScenesFromSceneList = (file, sceneList, clearOldScenes = false, frameSize, newSheetId) => { return dispatch => { log.debug('action: addScenesFromSceneList'); // add scenes const sceneArray = sceneList.map(scene => { scene.sceneId = uuidV4(); scene.fileId = file.id; scene.sheetId = newSheetId; scene.hidden = false; return scene; }); log.debug('dispatch: ADD_SCENES'); dispatch({ type: 'ADD_SCENES', payload: { sceneArray, fileId: file.id, sheetId: newSheetId, clearOldScenes, }, }); // for adding thumbs suggest thumbIdArray const thumbIdArray = sceneArray.map(scene => scene.sceneId); // add thumbs const frameNumberArray = sceneList.map(scene => scene.start + Math.floor(scene.length / 2)); dispatch(addThumbs(file, newSheetId, frameNumberArray, frameSize, thumbIdArray)); // dispatch(addThumbs(file, newSheetId, frameNumberArray, frameSize, thumbIdArray)).then(() => { // // console.log(resolve); // // add sceneId to thumbs after addThumbs returned // const sceneIdArray = sceneArray.map(scene => scene.sceneId); // // console.log(sceneIdArray); // return dispatch({ // type: 'ADD_SCENEIDS_TO_THUMBS', // payload: { // sceneIdArray, // frameNumberArray, // fileId: file.id, // sheetId: newSheetId, // } // }); // }).catch((err) => { // log.error(err); // }); }; }; export const toggleScene = (fileId, sheetId, sceneId) => { log.debug(`action: toggleScene - ${sceneId}`); return { type: 'TOGGLE_SCENE', payload: { fileId, sheetId, sceneId, }, }; }; export const toggleSceneArray = (fileId, sheetId, sceneIdArray) => { log.debug(`action: toggleSceneArray - ${sceneIdArray}`); return { type: 'TOGGLE_SCENE_ARRAY', payload: { fileId, sheetId, sceneIdArray, }, }; }; export const updateSceneArray = (fileId, sheetId, sceneArray) => { log.debug(`action: updateSceneArray - ${sheetId}`); return { type: 'UPDATE_SCENEARRAY', payload: { fileId, sheetId, sceneArray, }, }; }; export const insertScene = (fileId, sheetId, index, start, length, colorArray, newSceneId) => { log.debug(`action: insertScene - ${newSceneId}`); return { type: 'INSERT_SCENE', payload: { fileId, sheetId, index, start, length, colorArray, sceneId: newSceneId, hidden: false, }, }; }; export const deleteScene = (fileId, sheetId, index) => { log.debug(`action: deleteScene - ${index}`); return { type: 'DELETE_SCENE', payload: { fileId, sheetId, index, }, }; }; export const updateSceneLength = (fileId, sheetId, sceneId, length) => { log.debug(`action: updateSceneLength - ${sceneId}`); return { type: 'UPDATE_SCENE_LENGTH', payload: { fileId, sheetId, sceneId, length, }, }; }; export const cutScene = (thumbs, allScenes, file, sheetId, scene, frameToCut) => { log.debug(`action: cutScene - ${scene.sceneId} - ${frameToCut}`); return dispatch => { // split one scene in 2 const firstSceneSceneLength = frameToCut - scene.start; const firstSceneNewFrameNumber = scene.start + Math.floor(firstSceneSceneLength / 2); const firstSceneIndex = allScenes.findIndex(scene2 => scene2.sceneId === scene.sceneId); const nextSceneId = uuidV4(); const nextSceneSceneStart = frameToCut; const nextSceneSceneLength = scene.start + scene.length - nextSceneSceneStart; const nextSceneNewFrameNumber = nextSceneSceneStart + Math.floor(nextSceneSceneLength / 2); dispatch(updateSceneLength(file.id, sheetId, scene.sceneId, firstSceneSceneLength)); dispatch( insertScene( file.id, sheetId, firstSceneIndex + 1, nextSceneSceneStart, nextSceneSceneLength, scene.colorArray, nextSceneId, ), ); dispatch(changeThumb(sheetId, file, scene.sceneId, firstSceneNewFrameNumber)); const firstThumbIndex = thumbs.findIndex(thumb => thumb.thumbId === scene.sceneId); dispatch(addThumb(file, sheetId, nextSceneNewFrameNumber, firstThumbIndex + 1, nextSceneId)); }; }; export const mergeScenes = (thumbs, allScenes, file, sheetId, adjacentSceneIndicesArray) => { log.debug(`action: mergeScenes - ${adjacentSceneIndicesArray[0]} - ${adjacentSceneIndicesArray[1]}`); return dispatch => { // merge 2 scenes into 1 const firstScene = allScenes[adjacentSceneIndicesArray[0]]; const firstSceneId = firstScene.sceneId; const secondScene = allScenes[adjacentSceneIndicesArray[1]]; const secondSceneId = secondScene.sceneId; const newSceneSceneLength = firstScene.length + secondScene.length; const newSceneNewFrameNumber = firstScene.start + Math.floor(newSceneSceneLength / 2); // change length of first scene dispatch(updateSceneLength(file.id, sheetId, firstSceneId, newSceneSceneLength)); // delete second scene dispatch(deleteScene(file.id, sheetId, adjacentSceneIndicesArray[1])); // delete second thumb const secondThumbIndex = thumbs.findIndex(thumb => thumb.thumbId === secondSceneId); dispatch(deleteThumb(file.id, sheetId, secondThumbIndex)); // change first thumb dispatch(changeThumb(sheetId, file, firstSceneId, newSceneNewFrameNumber)); }; }; export const addThumb = (file, sheetId, frameNumber, index, thumbId = uuidV4(), frameSize = 0) => { return dispatch => { log.debug('action: addThumb'); const frameId = uuidV4(); const newFrameNumberWithinBoundaries = limitRange(frameNumber, 0, file.frameCount - 1); return imageDB.frameList .where('[fileId+frameNumber]') .equals([file.id, newFrameNumberWithinBoundaries]) .toArray() .then(frames => { log.debug(frames.length); if (frames.length === 0) { log.debug(`frame number: ${frameNumber} not yet in database - need(s) to be captured`); ipcRenderer.send( 'message-from-mainWindow-to-opencvWorkerWindow', 'send-get-thumbs', file.id, file.path, sheetId, [thumbId], [frameId], [newFrameNumberWithinBoundaries], file.useRatio, frameSize, file.transformObject || TRANSFORMOBJECT_INIT, // need INIT value as undefined is translated to null via IPC ); log.debug('dispatch: ADD_THUMB'); dispatch({ type: 'ADD_THUMB', payload: { sheetId, thumbId, frameId, frameNumber, fileId: file.id, index, hidden: false, }, }); return thumbId; } log.debug(`frame number: ${frameNumber} already in database`); log.debug('dispatch: ADD_THUMB'); dispatch({ type: 'ADD_THUMB', payload: { sheetId, thumbId, frameId: frames[0].frameId, frameNumber, fileId: file.id, index, hidden: false, }, }); return thumbId; }) .catch(error => { log.error(`There has been a problem with your fetch operation: ${error.message}`); }); }; }; export const deleteThumb = (fileId, sheetId, index) => { log.debug(`action: deleteThumb - ${index}`); return { type: 'DELETE_THUMB', payload: { fileId, sheetId, index, }, }; }; export const toggleThumb = (fileId, sheetId, thumbId) => { log.debug(`action: toggleThumb - ${thumbId}`); return { type: 'TOGGLE_THUMB', payload: { fileId, sheetId, thumbId, }, }; }; export const showAllThumbs = (fileId, sheetId) => { log.debug(`action: showAllThumbs - ${sheetId}`); return { type: 'SHOW_ALL_THUMBS', payload: { fileId, sheetId, }, }; }; export const toggleThumbsByThumbIdArray = (fileId, sheetId, thumbIdArray) => { log.debug(`action: toggleThumbsByThumbIdArray - ${thumbIdArray}`); return { type: 'TOGGLE_THUMBS_BY_THUMBIDARRAY', payload: { fileId, sheetId, thumbIdArray, }, }; }; export const showThumbsByFrameNumberArray = (fileId, sheetId, frameNumberArray) => { log.debug(`action: showThumbsByFrameNumberArray - ${frameNumberArray}`); return { type: 'SHOW_THUMBS_BY_FRAMENUMBERARRAY', payload: { fileId, sheetId, frameNumberArray, }, }; }; export const changeAndSortThumbArray = ( fileId, sheetId, faceScanArray, sortMethod = undefined, optionalSortProperties = undefined, ) => { log.debug(`action: changeAndSortThumbArray - ${sheetId}`); return (dispatch, getState) => { dispatch(changeThumbArray(fileId, sheetId, faceScanArray)); // return immediately if no sorting is needed if (sortMethod === undefined) { return undefined; } const sortedArray = sortArray(faceScanArray, sortMethod, undefined, optionalSortProperties); // extract frameNumbers const frameNumberArrayFromFaceDetection = sortedArray.map(item => item.frameNumber); const thumbsArrayBeforeSorting = getState().undoGroup.present.sheetsByFileId[fileId][sheetId].thumbsArray; console.log(thumbsArrayBeforeSorting); const thumbsArrayAfterSorting = thumbsArrayBeforeSorting.slice().sort((a, b) => { return ( frameNumberArrayFromFaceDetection.indexOf(a.frameNumber) - frameNumberArrayFromFaceDetection.indexOf(b.frameNumber) ); }); console.log(thumbsArrayAfterSorting); return dispatch(updateOrder(fileId, sheetId, thumbsArrayAfterSorting)); }; }; export const changeThumbArray = (fileId, sheetId, dataToUpdateArray) => { log.debug(`action: changeThumbArray - ${sheetId}`); return { type: 'CHANGE_THUMB_ARRAY', payload: { fileId, sheetId, dataToUpdateArray, }, }; }; export const updateOrder = (currentFileId, sheetId, array) => { log.debug('action: updateOrder'); return { type: 'UPDATE_ORDER', payload: { fileId: currentFileId, sheetId, array, }, }; }; // export const updateSceneId = (fileId, sheetId, thumbId, sceneId) => { // log.debug('action: updateSceneId'); // return { // type: 'UPDATE_SCENEID_OF_THUMB', // payload: { // fileId, // sheetId, // thumbId, // sceneId // } // }; // }; export const updateFrameNumberAndColorArray = frameNumberAndColorArray => { log.debug('action: updateFrameNumberAndColorArray'); if (frameNumberAndColorArray !== undefined) { const { fileId, sheetId } = frameNumberAndColorArray[0]; return { type: 'UPDATE_FRAMENUMBER_AND_COLORARRAY_OF_THUMB', payload: { fileId, sheetId, frameNumberAndColorArray, }, }; } }; export const duplicateSheet = (fileId, sheetId, newSheetId) => { log.debug('action: duplicateSheet'); return { type: 'DUPLICATE_SHEET', payload: { fileId, sheetId, newSheetId, }, }; }; // export const deleteSceneSheets = (fileId) => { // log.debug('action: deleteSceneSheets'); // return { // type: 'DELETE_SCENE_SHEETS', // payload: { // fileId, // } // }; // }; export const deleteSheets = (fileId = undefined, sheetId = undefined) => { log.debug('action: deleteSheets'); return { type: 'DELETE_SHEETS', payload: { fileId, sheetId, }, }; }; export const deleteThumbsArray = (fileId = undefined, sheetId = undefined) => { log.debug('action: deleteThumbsArray'); if (fileId === undefined || sheetId === undefined) { return undefined; } return { type: 'DELETE_THUMBSARRAY', payload: { fileId, sheetId, }, }; }; export const addIntervalSheet = ( file, sheetId, amountOfThumbs = 20, start = 10, stop = file.frameCount - 1, frameSize, limitToRange = false, ) => { return dispatch => { log.debug('action: addIntervalSheet'); if (file.frameCount !== undefined) { const frameNumberArray = getIntervalArray( amountOfThumbs, start, stop, file.frameCount, limitToRange, // in some cases it can be allowed to go over ); dispatch(deleteThumbsArray(file.id, sheetId)); return dispatch(addThumbs(file, sheetId, frameNumberArray, frameSize)); } log.error('in addIntervalSheet: file.frameCount === undefined'); return Promise.reject(new Error('in addIntervalSheet: file.frameCount === undefined')); }; }; export const addThumbs = (file, sheetId, frameNumberArray, frameSize = 0, thumbIdArray = undefined) => { return dispatch => { log.debug('action: addThumbs'); // create compound array to search for both fileId and frameNumber // log.debug(frameNumberArray); const fileIdAndFrameNumberArray = frameNumberArray.map(item => [file.id, item]); return imageDB.frameList .where('[fileId+frameNumber]') .anyOf(fileIdAndFrameNumberArray) .toArray() .then(frames => { log.debug(frames.length); log.debug(frames); let alreadyExistingFrameIdsArray = []; let alreadyExistingThumbIdsArray = []; let alreadyExistingFrameNumbersArray = []; let notExistingFrameIdArray = []; let notExistingThumbIdsArray = []; let notExistingFrameNumberArray = []; // create array where notExisting === false and alreadyExisting === true const filterArray = frameNumberArray.map(frameNumber => frames.map(item => item.frameNumber).includes(frameNumber), ); if (frames.length !== 0) { // remove duplicates in case there are already some in imageDB const uniqueFrames = frames.filter( (item, index, self) => index === self.findIndex(t => t.frameNumber === item.frameNumber), ); // extract frameNumbers and frameIds into separate arrays alreadyExistingFrameNumbersArray = uniqueFrames.map(item => item.frameNumber); alreadyExistingFrameIdsArray = uniqueFrames.map(item => item.frameId); // if thumbIdArray then use these, else create new ids if (thumbIdArray !== undefined) { alreadyExistingThumbIdsArray = thumbIdArray.filter((thumbId, index) => filterArray[index]); } else { alreadyExistingThumbIdsArray = alreadyExistingFrameIdsArray.map(() => uuidV4()); } log.debug(`${alreadyExistingFrameIdsArray.length} frame(s) are already in database`); } // remove the already existing frameNumbers // log.debug(frameNumberArray); // log.debug(alreadyExistingFrameNumbersArray); notExistingFrameNumberArray = frameNumberArray.filter((frameNumber, index) => !filterArray[index]); // log.debug(notExistingFrameNumberArray); // if all thumbs already exist skip capturing if (notExistingFrameNumberArray.length !== 0) { log.debug(`${notExistingFrameNumberArray.length} frame(s) are not yet in database - need(s) to be captured`); // add new thumbs notExistingFrameIdArray = notExistingFrameNumberArray.map(() => uuidV4()); // if thumbIdArray then use these, else create new ids if (thumbIdArray) { notExistingThumbIdsArray = thumbIdArray.filter((thumbId, index) => !filterArray[index]); } else { notExistingThumbIdsArray = notExistingFrameIdArray.map(() => uuidV4()); } // call worker_opencv to get missing thumbs ipcRenderer.send( 'message-from-mainWindow-to-opencvWorkerWindow', 'send-get-thumbs', file.id, file.path, sheetId, notExistingThumbIdsArray, notExistingFrameIdArray, notExistingFrameNumberArray, file.useRatio, frameSize, file.transformObject || TRANSFORMOBJECT_INIT, // need INIT value as undefined is translated to null via IPC ); } else { // send finished-getting-thumbs if no thumbs have to be captured // otherwise this is sent from worker_opencv after last thumb was captured ipcRenderer.send('message-from-mainWindow-to-mainWindow', 'finished-getting-thumbs', file.id, sheetId); } const concatenatedFrameIdArray = notExistingFrameIdArray.concat(alreadyExistingFrameIdsArray); const concatenatedThumbIdArray = notExistingThumbIdsArray.concat(alreadyExistingThumbIdsArray); const concatenatedFrameNumberArray = notExistingFrameNumberArray.concat(alreadyExistingFrameNumbersArray); log.debug('dispatch: ADD_THUMBS'); dispatch({ type: 'ADD_THUMBS', payload: { sheetId, thumbIdArray: concatenatedThumbIdArray, frameIdArray: concatenatedFrameIdArray, frameNumberArray: concatenatedFrameNumberArray, fileId: file.id, width: file.width, height: file.height, }, }); return Promise.resolve(frames); }) .catch(err => { log.error(err); }); }; }; // adding new thumbs keeping the order, but not checking if frames already exist in indexedDB export const addNewThumbsWithOrder = (file, sheetId, frameNumberArray, frameSize = 0) => { return dispatch => { log.debug('action: addNewThumbsWithOrder'); // remove duplicates in case there are already some in imageDB const uniqueFrameNumberArray = frameNumberArray.filter((item, index, array) => array.indexOf(item) === index); const thumbIdArray = frameNumberArray.map(() => uuidV4()); const uniqueFrameNumberAndFrameIdArray = uniqueFrameNumberArray.map(frameNumber => ({ frameNumber, frameId: uuidV4(), })); const frameIdArray = frameNumberArray.map( frameNumber => uniqueFrameNumberAndFrameIdArray.find(item => item.frameNumber === frameNumber).frameId, ); ipcRenderer.send( 'message-from-mainWindow-to-opencvWorkerWindow', 'send-get-thumbs', file.id, file.path, sheetId, thumbIdArray, frameIdArray, frameNumberArray, file.useRatio, frameSize, file.transformObject || TRANSFORMOBJECT_INIT, // need INIT value as undefined is translated to null via IPC ); log.debug('dispatch: ADD_THUMBS'); dispatch({ type: 'ADD_THUMBS', payload: { sheetId, thumbIdArray, frameIdArray, frameNumberArray, fileId: file.id, width: file.width, height: file.height, noReorder: true, }, }); }; }; export const changeThumb = (sheetId, file, thumbId, newFrameNumber, frameSize = 0) => { return dispatch => { log.debug(`action: changeThumb - ${newFrameNumber}`); const newFrameId = uuidV4(); const newFrameNumberWithinBoundaries = limitRange(newFrameNumber, 0, file.frameCount - 1); imageDB.frameList .where('[fileId+frameNumber]') .equals([file.id, newFrameNumberWithinBoundaries]) .toArray() .then(frames => { if (frames.length === 0) { log.debug(`frame number: ${newFrameNumber} not yet in database - need(s) to be captured`); ipcRenderer.send( 'message-from-mainWindow-to-opencvWorkerWindow', 'send-get-thumbs', file.id, file.path, sheetId, [thumbId], [newFrameId], [newFrameNumberWithinBoundaries], file.useRatio, frameSize, file.transformObject || TRANSFORMOBJECT_INIT, // need INIT value as undefined is translated to null via IPC ); log.debug('dispatch: CHANGE_THUMB'); return dispatch({ type: 'CHANGE_THUMB', payload: { sheetId, newFrameId, thumbId, newFrameNumber: newFrameNumberWithinBoundaries, fileId: file.id, }, }); } log.debug(`frame number: ${newFrameNumber} already in database`); log.debug('dispatch: CHANGE_THUMB'); return dispatch({ type: 'CHANGE_THUMB', payload: { sheetId, newFrameId: frames[0].frameId, thumbId, newFrameNumber: frames[0].frameNumber, fileId: file.id, }, }); }) .catch(err => { log.error(err); }); }; }; // files export const removeMovieListItem = fileId => { return dispatch => { log.debug(`action: removeMovieListItem - ${fileId}`); // remove from file list dispatch({ type: 'REMOVE_MOVIE_LIST_ITEM', payload: { fileId, }, }); // remove fileId from sheetsByFileId dispatch({ type: 'DELETE_SHEETS', payload: { fileId, }, }); // remove frameScan table from sqlite3 deleteTableFrameScanList(fileId); // remove frames from indexedDB imageDB.frameList .where('fileId') .equals(fileId) .delete() .then(deleteCount => { console.log(`Deleted ${deleteCount} objects`); return Promise.resolve(deleteCount); }) .catch(err => { log.error(err); }); }; }; export const updateSheetFilter = (fileId, sheetId, filter) => { return dispatch => { log.debug(`action: updateSheetFilter - ${filter}`); dispatch({ type: 'UPDATE_SHEET_FILTER', payload: { fileId, sheetId, filter, }, }); }; }; export const updateSheetSecondsPerRow = (fileId, sheetId, secondsPerRow) => { return dispatch => { log.debug(`action: updateSheetSecondsPerRow - ${secondsPerRow}`); dispatch({ type: 'UPDATE_SHEET_SECONDSPERROW', payload: { fileId, sheetId, secondsPerRow, }, }); }; }; export const updateSheetColumnCount = (fileId, sheetId, columnCount) => { return dispatch => { log.debug(`action: updateSheetColumnCount - ${columnCount}`); dispatch({ type: 'UPDATE_SHEET_COLUMNCOUNT', payload: { fileId, sheetId, columnCount, }, }); }; }; export const updateSheetName = (fileId, sheetId, name) => { return dispatch => { log.debug(`action: updateSheetName - ${name}`); dispatch({ type: 'UPDATE_SHEET_NAME', payload: { fileId, sheetId, name, }, }); }; }; export const updateSheetView = (fileId, sheetId, sheetView) => { return dispatch => { log.debug(`action: updateSheetView - ${sheetView}`); dispatch({ type: 'UPDATE_SHEET_VIEW', payload: { fileId, sheetId, sheetView, }, }); }; }; export const updateSheetType = (fileId, sheetId, type) => { return dispatch => { log.debug(`action: updateSheetType - ${type}`); dispatch({ type: 'UPDATE_SHEET_TYPE', payload: { fileId, sheetId, type, }, }); }; }; export const updateSheetParent = (fileId, sheetId, parentSheetId) => { return dispatch => { log.debug(`action: updateSheetParent - ${parentSheetId}`); dispatch({ type: 'UPDATE_SHEET_PARENT', payload: { fileId, sheetId, parentSheetId, }, }); }; }; export const updateFileScanStatus = (fileId, fileScanStatus) => { return dispatch => { log.debug('action: updateFileScanStatus'); dispatch({ type: 'UPDATE_FILESCAN_STATUS', payload: { fileId, fileScanStatus, }, }); }; }; export const updateFileMissingStatus = (fileId, fileMissingStatus) => { return dispatch => { log.debug('action: updateFileMissingStatus'); dispatch({ type: 'UPDATE_FILE_MISSING_STATUS', payload: { fileId, fileMissingStatus, }, }); }; }; export const updateSheetCounter = (fileId, incrementValue = 1) => { return dispatch => { log.debug('action: updateSheetCounter'); dispatch({ type: 'UPDATE_SHEETCOUNTER', payload: { fileId, incrementValue, }, }); }; }; export const updateFileDetailUseRatio = (fileId, useRatio) => { return dispatch => { log.debug('action: updateFileDetailUseRatio'); dispatch({ type: 'UPDATE_MOVIE_LIST_ITEM_USERATIO', payload: { fileId, useRatio, }, }); }; }; export const updateFileDetails = (fileId, frameCount, width, height, fps, fourCC) => { return dispatch => { log.debug('action: updateFileDetails'); dispatch({ type: 'UPDATE_MOVIE_LIST_ITEM', payload: { fileId, frameCount, width, height, fps, fourCC, }, }); }; }; export const replaceFileDetails = (fileId, path, name, size, lastModified) => { return dispatch => { log.debug('action: updateFileDetails'); dispatch({ type: 'REPLACE_MOVIE_LIST_ITEM', payload: { fileId, path, name, size, lastModified, }, }); }; }; export const setTransform = (fileId, rotationFlag, cropTop, cropBottom, cropLeft, cropRight) => { return dispatch => { log.debug('action: setTransform'); dispatch({ type: 'SET_TRANSFORM', payload: { fileId, transformObject: { rotationFlag, cropTop, cropBottom, cropLeft, cropRight, }, }, }); }; }; export const updateCropping = (fileId, rotationFlag, cropTop, cropBottom, cropLeft, cropRight, aspectRatioInv) => { return dispatch => { log.debug('action: updateCropping'); dispatch({ type: 'UPDATE_CROPPING', payload: { fileId, transformObject: { rotationFlag, cropTop, cropBottom, cropLeft, cropRight, aspectRatioInv, }, }, }); }; }; export const updateAspectRatio = (fileId, aspectRatioInv) => { return dispatch => { log.debug('action: updateAspectRatio'); dispatch({ type: 'UPDATE_ASPECT_RATIO', payload: { fileId, aspectRatioInv, }, }); }; }; export const rotateWidthAndHeight = (fileId, shouldRotate) => { return dispatch => { log.debug('action: rotateWidthAndHeight'); dispatch({ type: 'ROTATE_WIDTH_AND_HEIGHT', payload: { fileId, shouldRotate, }, }); }; }; export const updateInOutPoint = (fileId, fadeInPoint, fadeOutPoint) => { return dispatch => { log.debug('action: updateInOutPoint'); dispatch({ type: 'UPDATE_IN_OUT_POINT', payload: { fileId, fadeInPoint, fadeOutPoint, }, }); }; }; export const addMoviesToList = (files, clearList) => { return dispatch => { log.debug('action: addMoviesToList'); // create array with new files const newFiles = []; Object.keys(files).map(key => { // file match need(s) to be in sync with onDrop() and accept in App.js !!! if (files[key].type.match('video.*') || files[key].name.match(/.divx|.mkv|.ogg|.VOB/i)) { const id = uuidV4(); const posterFrameId = uuidV4(); const fileToAdd = { id, lastModified: files[key].lastModified, // lastModifiedDate: files[key].lastModifiedDate.toDateString(), name: files[key].name, path: files[key].path, size: files[key].size, type: files[key].type, posterFrameId, transformObject: TRANSFORMOBJECT_INIT, }; // insertMovie(fileToAdd); newFiles.push(fileToAdd); } // return a copy of the array return newFiles.slice(); }); if (clearList) { dispatch(clearMovieList()); } dispatch({ type: 'ADD_MOVIE_LIST_ITEMS', // type: 'LOAD_MOVIE_LIST_FROM_DROP', payload: newFiles, }); return Promise.resolve(newFiles); }; }; export const clearMovieList = () => { return dispatch => { dispatch({ type: 'CLEAR_CURRENT_FILEID', }); log.debug('dispatch: CLEAR_CURRENT_FILEID'); dispatch({ type: 'CLEAR_MOVIE_LIST', }); log.debug('dispatch: CLEAR_MOVIE_LIST'); dispatch(deleteSheets()); log.debug('dispatch: deleteSheets'); deleteTableFrameScanList(); log.debug('delete all frameScan tables in sqlite3'); deleteTableFramelist(); log.debug('clear frameList in indexedDB'); }; }; <|start_filename|>app/containers/Root.js<|end_filename|> // @flow import React from 'react'; import { Provider } from 'react-redux'; import { hot } from 'react-hot-loader/root'; import App from './App'; import ErrorBoundary from '../components/ErrorBoundary'; type Props = { store: Store, history: {} }; const Root = ({ store, history }: Props) => ( <Provider store={store}> <ErrorBoundary> <App history={history} /> </ErrorBoundary> </Provider> ); export default hot(Root); <|start_filename|>app/utils/mainConstants.js<|end_filename|> // const { app } = require('electron').remote; // throws error as it would be packed into main.js where this is can not be required <|start_filename|>app/main.dev.js<|end_filename|> /* eslint global-require: off */ /** * This module executes inside of electron's main process. You can start * electron renderer process from here and communicate with the other processes * through IPC. * * When running `yarn build` or `yarn build-main`, this file is compiled to * `./app/main.prod.js` using webpack. This gives us some performance wins. * * @flow */ import { app, BrowserWindow, ipcMain, shell } from 'electron'; import path from 'path'; import fs from 'fs'; import log from 'electron-log'; import { clearCache, resetApplication, reloadApplication, softResetApplication } from './utils/utilsForMain'; import MenuBuilder from './menu'; const { openProcessManager } = require('electron-process-manager'); let mainWindow = null; let workerWindow = null; let opencvWorkerWindow = null; let databaseWorkerWindow = null; let appAboutToQuit = false; log.info(process.versions); if (process.env.NODE_ENV === 'production') { const sourceMapSupport = require('source-map-support'); sourceMapSupport.install(); } if ( process.env.NODE_ENV === 'development' || process.env.DEBUG_PROD === 'true' || process.argv.findIndex(value => value === '--debug') > -1 ) { require('electron-debug')(); const p = path.join(__dirname, '..', 'app', 'node_modules'); require('module').globalPaths.push(p); } // set log level to 'debug' when launched in debug mode if (process.argv.findIndex(value => value === '--debug') > -1) { log.transports.file.level = 'debug'; log.transports.console.level = 'debug'; } // set log level from environment variable const { LOG_LEVEL } = process.env; // only change the log level if there is an environment variable // otherwise keep the default ('warn') if (LOG_LEVEL) { log.transports.file.level = LOG_LEVEL; log.transports.console.level = LOG_LEVEL; } // set log format log.transports.console.format = '{level} | {h}:{i}:{s}:{ms} {text}'; const installExtensions = async () => { const installer = require('electron-devtools-installer'); const forceDownload = !!process.env.UPGRADE_EXTENSIONS; const extensions = ['REACT_DEVELOPER_TOOLS', 'REDUX_DEVTOOLS']; return Promise.all(extensions.map(name => installer.default(installer[name], forceDownload))).catch(console.log); }; /** * Add event listeners... */ app.on('before-quit', () => { // set variable so windows know that they should close and not hide appAboutToQuit = true; }); app.on('window-all-closed', () => { // Respect the OSX convention of having the application in memory even // after all windows have been closed log.debug('mainThread | window-all-closed'); if (process.platform !== 'darwin') { app.quit(); } }); app.on('ready', async () => { if (process.env.NODE_ENV === 'development' || process.env.DEBUG_PROD === 'true') { await installExtensions(); } mainWindow = new BrowserWindow({ backgroundColor: '#1e1e1e', show: false, width: 1366, height: 768, webPreferences: { nodeIntegration: true, webviewTag: true, }, }); mainWindow.loadURL(`file://${__dirname}/app.html`); // @TODO: Use 'ready-to-show' event // https://github.com/electron/electron/blob/master/docs/api/browser-window.md#using-ready-to-show-event mainWindow.once('ready-to-show', () => { if (!mainWindow) { throw new Error('"mainWindow" is not defined'); } mainWindow.show(); mainWindow.focus(); // clear cache if started with --reset arg if (process.argv.findIndex(value => value === '--reset') > -1) { setTimeout(() => { log.info('resetApplication via --reset'); resetApplication(mainWindow, workerWindow, opencvWorkerWindow, databaseWorkerWindow); }, 1000); } // clear cache if started with --softreset arg if (process.argv.findIndex(value => value === '--softreset') > -1) { softResetApplication(mainWindow, workerWindow, opencvWorkerWindow, databaseWorkerWindow); } }); // openProcessManager(); mainWindow.on('close', event => { if (process.platform !== 'darwin') { app.quit(); } else if (!appAboutToQuit) { // only hide window and prevent default if app not quitting mainWindow.hide(); event.preventDefault(); } }); mainWindow.webContents.on('crashed', event => { log.error('mainThread | mainWindow just crashed, will try to reload window'); log.error(event); mainWindow.webContents.reload(); }); mainWindow.webContents.on('unresponsive', event => { log.warn('mainThread | mainWindow is unresponsive'); log.warn(event); }); mainWindow.webContents.on('responsive', event => { log.warn('mainThread | mainWindow is responsive again'); log.warn(event); }); opencvWorkerWindow = new BrowserWindow({ webPreferences: { nodeIntegration: true, }, }); opencvWorkerWindow.hide(); // opencvWorkerWindow.webContents.openDevTools(); opencvWorkerWindow.loadURL(`file://${__dirname}/worker_opencv.html`); opencvWorkerWindow.on('close', event => { // only hide window and prevent default if app not quitting if (!appAboutToQuit) { opencvWorkerWindow.hide(); event.preventDefault(); } }); opencvWorkerWindow.webContents.on('crashed', event => { log.error('mainThread | opencvWorkerWindow just crashed, will try to reload window'); log.error(event); opencvWorkerWindow.webContents.reload(); }); opencvWorkerWindow.webContents.on('unresponsive', event => { log.warn('mainThread | opencvWorkerWindow is unresponsive'); log.warn(event); }); opencvWorkerWindow.webContents.on('responsive', event => { log.warn('mainThread | opencvWorkerWindow is responsive again'); log.warn(event); }); databaseWorkerWindow = new BrowserWindow({ webPreferences: { nodeIntegration: true, }, }); databaseWorkerWindow.hide(); // databaseWorkerWindow.webContents.openDevTools(); databaseWorkerWindow.loadURL(`file://${__dirname}/worker_database.html`); databaseWorkerWindow.on('close', event => { // only hide window and prevent default if app not quitting if (!appAboutToQuit) { databaseWorkerWindow.hide(); event.preventDefault(); } }); databaseWorkerWindow.webContents.on('crashed', event => { log.error('mainThread | databaseWorkerWindow just crashed, will try to reload window'); log.error(event); databaseWorkerWindow.webContents.reload(); }); databaseWorkerWindow.webContents.on('unresponsive', event => { log.warn('mainThread | databaseWorkerWindow is unresponsive'); log.warn(event); }); databaseWorkerWindow.webContents.on('responsive', event => { log.warn('mainThread | databaseWorkerWindow is responsive again'); log.warn(event); }); workerWindow = new BrowserWindow({ webPreferences: { nodeIntegration: true, }, }); workerWindow.hide(); // workerWindow.webContents.openDevTools(); workerWindow.loadURL(`file://${__dirname}/worker.html`); workerWindow.on('close', event => { // only hide window and prevent default if app not quitting if (!appAboutToQuit) { workerWindow.hide(); event.preventDefault(); } }); workerWindow.webContents.on('crashed', event => { log.error('mainThread | workerWindow just crashed, will try to reload window'); log.error(event); workerWindow.webContents.reload(); }); workerWindow.webContents.on('unresponsive', event => { log.warn('mainThread | workerWindow is unresponsive'); log.warn(event); }); workerWindow.webContents.on('responsive', event => { log.warn('mainThread | workerWindow is responsive again'); log.warn(event); }); const menuBuilder = new MenuBuilder( mainWindow, workerWindow, opencvWorkerWindow, databaseWorkerWindow, ); menuBuilder.buildMenu(); }); ipcMain.on('reset-application', event => { log.info('resetApplication'); resetApplication(mainWindow, workerWindow, opencvWorkerWindow, databaseWorkerWindow); }); ipcMain.on('soft-reset-application', event => { log.info('softResetApplication'); softResetApplication(mainWindow, workerWindow, opencvWorkerWindow, databaseWorkerWindow); }); ipcMain.on('reload-application', event => { log.info('reloadApplication'); reloadApplication(mainWindow, workerWindow, opencvWorkerWindow, databaseWorkerWindow); }); ipcMain.on('reload-workerWindow', event => { workerWindow.webContents.reload(); }); ipcMain.on('reload-opencvWorkerWindow', event => { opencvWorkerWindow.webContents.reload(); }); ipcMain.on('reload-databaseWorkerWindow', event => { databaseWorkerWindow.webContents.reload(); }); ipcMain.on('send-save-json-to-file', (event, id, filePath, json) => { fs.writeFile(filePath, json, err => { if (err) { mainWindow.webContents.send('received-saved-file-error', err.message); } else { // mainWindow.webContents.send('received-saved-file', id, filePath); log.debug(`MoviePrint JSON exported successfully: ${filePath}`); mainWindow.webContents.send( 'progressMessage', 'info', `MoviePrint JSON exported successfully: ${filePath}`, 3000, ); } }); }); ipcMain.on('send-save-file', (event, id, filePath, buffer) => { // only used when saving thumbs. writeFile for moviePrint is done in saveMoviePrint (workerWindow) const isSingleThumb = true; fs.writeFile(filePath, buffer, err => { if (err) { console.log(err); mainWindow.webContents.send('received-saved-file-error', err.message); } else { mainWindow.webContents.send('received-saved-file', id, filePath, isSingleThumb); } }); }); ipcMain.on('send-save-file-error', (event, saveMoviePrint = false) => { mainWindow.webContents.send( 'received-saved-file-error', 'MoviePrint could not be saved due to sizelimit (width + size > 32767)', ); if (saveMoviePrint) { workerWindow.webContents.send('action-saved-MoviePrint-done'); } }); ipcMain.on('open-file-explorer', (event, filePath, isFolder = false) => { if (isFolder) { shell.openItem(filePath); } else { shell.showItemInFolder(filePath); } }); ipcMain.on('message-from-mainWindow-to-workerWindow', (e, ipcName, ...args) => { log.debug(`mainThread | passing ${ipcName} from mainWindow to workerWindow`); log.debug(`mainThread | passing ${ipcName} from mainWindow to workerWindow`); // log.debug(...args); workerWindow.webContents.send(ipcName, ...args); }); ipcMain.on('message-from-workerWindow-to-mainWindow', (e, ipcName, ...args) => { log.debug(`mainThread | passing ${ipcName} from workerWindow to mainWindow`); // log.debug(...args); mainWindow.webContents.send(ipcName, ...args); }); ipcMain.on('message-from-workerWindow-to-workerWindow', (e, ipcName, ...args) => { log.debug(`mainThread | passing ${ipcName} from workerWindow to workerWindow`); // log.debug(...args); workerWindow.webContents.send(ipcName, ...args); }); ipcMain.on('message-from-mainWindow-to-opencvWorkerWindow', (e, ipcName, ...args) => { log.debug(`mainThread | passing ${ipcName} from mainWindow to opencvWorkerWindow`); // log.debug(...args); opencvWorkerWindow.webContents.send(ipcName, ...args); }); ipcMain.on('message-from-databaseWorkerWindow-to-opencvWorkerWindow', (e, ipcName, ...args) => { log.debug(`mainThread | passing ${ipcName} from databaseWorkerWindow to opencvWorkerWindow`); // log.debug(...args); opencvWorkerWindow.webContents.send(ipcName, ...args); }); ipcMain.on('message-from-mainWindow-to-databaseWorkerWindow', (e, ipcName, ...args) => { log.debug(`mainThread | passing ${ipcName} from mainWindow to databaseWorkerWindow`); // log.debug(...args); databaseWorkerWindow.webContents.send(ipcName, ...args); }); ipcMain.on('message-from-opencvWorkerWindow-to-mainWindow', (e, ipcName, ...args) => { log.debug(`mainThread | passing ${ipcName} from opencvWorkerWindow to mainWindow`); // log.debug(...args); mainWindow.webContents.send(ipcName, ...args); }); ipcMain.on('message-from-opencvWorkerWindow-to-databaseWorkerWindow', (e, ipcName, ...args) => { log.debug(`mainThread | passing ${ipcName} from opencvWorkerWindow to databaseWorkerWindow`); // log.debug(...args); databaseWorkerWindow.webContents.send(ipcName, ...args); }); ipcMain.on('message-from-databaseWorkerWindow-to-mainWindow', (e, ipcName, ...args) => { log.debug(`mainThread | passing ${ipcName} from databaseWorkerWindow to mainWindow`); // log.debug(...args); mainWindow.webContents.send(ipcName, ...args); }); ipcMain.on('message-from-mainWindow-to-mainWindow', (e, ipcName, ...args) => { log.debug(`mainThread | passing ${ipcName} from mainWindow to mainWindow`); // log.debug(...args); mainWindow.webContents.send(ipcName, ...args); }); // // retransmit it to workerWindow // ipcMain.on('printPDF', (event: any, content: any) => { // workerWindow.webContents.send('printPDF', content); // }); // // when worker window is ready // ipcMain.on('readyToPrintPDF', event => { // const pdfPath = path.join(os.tmpdir(), 'print.pdf'); // // Use default printing options // setTimeout(() => { // workerWindow.webContents.printToPDF( // { // marginsType: 0, // printBackground: false, // printSelectionOnly: false, // }, // (error, data) => { // if (error) throw error; // fs.writeFile(pdfPath, data, err => { // if (err) { // throw err; // } // shell.openItem(pdfPath); // event.sender.send('wrote-pdf', pdfPath); // // workerWindow.webContents.print(); // }); // }, // ); // }, 1000); // }); <|start_filename|>app/components/Timeline.css<|end_filename|> .container { } .timelineWrapperSelection { width: 100%; position: relative; /* background-color: #421400; */ background-color: rgba(142, 44, 2, 1.0); height: 28px; margin-bottom: 4px; cursor: col-resize; } .timelineWrapper { width: 100%; position: relative; /* background-color: #421400; */ height: 16px; /* cursor: col-resize; */ } .timelinePlayheadSelection { position: absolute; /* bottom: 0; */ /* top: 0; */ width: 2px; background-color: rgba(255, 80, 6, 1); height: 24px; margin-top: 2px; } .timelinePlayhead { position: absolute; /* bottom: 0; */ /* top: 0; */ width: 2px; background-color: rgba(255, 80, 6, 1); height: 16px; margin-top: 0px; } .timelineCutSelection { position: absolute; background-color: rgba(255, 80, 6, 0.4); height: 16px; cursor: col-resize; } .timelineCut { position: absolute; background-color: #421400; height: 16px; cursor: col-resize; } .timelineWrapper .currentTime { background-color: #FF5006; z-index: 2; } .timelineWrapper .cutStartTime { background-color: rgba(0, 0, 0, 0.3); border-left: 1px solid black; border-right: 1px solid black; z-index: 1; } <|start_filename|>app/components/Scrub.js<|end_filename|> // @flow import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { Popup } from 'semantic-ui-react'; import log from 'electron-log'; import styles from './Scrub.css'; import stylesPop from './Popup.css'; import { getScrubFrameNumber, getSceneScrubFrameNumber, mapRange, getThumbInfoValue, setPosition, } from '../utils/utils'; import { getCropRect, transformMat } from '../utils/utilsForOpencv'; import transparent from '../img/Thumb_TRANSPARENT.png'; import { RotateFlags } from '../utils/openCVProperties'; import { MENU_FOOTER_HEIGHT, MENU_HEADER_HEIGHT, SHEET_TYPE, TRANSFORMOBJECT_INIT } from '../utils/constants'; const opencv = require('opencv4nodejs'); class Scrub extends Component { constructor(props) { super(props); this.state = { cropRect: undefined, leftOfScrubMovie: undefined, rightOfScrubMovie: undefined, scrubFrameNumber: undefined, scrubInfo: undefined, scrubLineOnTimelineValue: undefined, scrubLineValue: undefined, scrubThumbLineValue: undefined, timeLineCutIn: undefined, timeLineCutOut: undefined, timeLineScrubThumb: undefined, }; this.onScrubMouseMoveWithStop = this.onScrubMouseMoveWithStop.bind(this); this.onScrubCancel = this.onScrubCancel.bind(this); this.onScrubClickWithStop = this.onScrubClickWithStop.bind(this); this.getInitialStateObject = this.getInitialStateObject.bind(this); } componentDidMount() { const myInitialState = this.getInitialStateObject(); this.updateOpencvVideoCanvas(0); this.setState(myInitialState); console.log('Scrub.js - componentDidMount'); } getInitialStateObject() { const { file, opencvVideo, scaleValueObject, scrubThumb, scrubThumbLeft, scrubThumbRight, settings } = this.props; const { transformObject = TRANSFORMOBJECT_INIT } = file; const timeLineCutIn = mapRange(scrubThumbLeft.frameNumber, 0, file.frameCount, 0, scaleValueObject.containerWidth); const timeLineScrubThumb = mapRange(scrubThumb.frameNumber, 0, file.frameCount, 0, scaleValueObject.containerWidth); const timeLineCutOut = mapRange( scrubThumbRight.frameNumber, 0, file.frameCount, 0, scaleValueObject.containerWidth, ); const leftOfScrubMovie = scaleValueObject.containerWidth / 2 - scaleValueObject.scrubMovieWidth / 2; const rightOfScrubMovie = leftOfScrubMovie + scaleValueObject.scrubMovieWidth; const scrubThumbLineValue = mapRange( scrubThumb.frameNumber, scrubThumbLeft.frameNumber, scrubThumbRight.frameNumber, leftOfScrubMovie, rightOfScrubMovie, ); // show timecode if hideInfo const scrubInfo = settings.defaultThumbInfo === 'hideInfo' ? 'timecode' : settings.defaultThumbInfo; const cropRect = getCropRect(opencvVideo, transformObject); console.log(transformObject); return { cropRect, leftOfScrubMovie, rightOfScrubMovie, scrubInfo, scrubThumbLineValue, thisTransformObject: transformObject, timeLineCutIn, timeLineCutOut, timeLineScrubThumb, }; } onScrubMouseMoveWithStop(e) { const { file, keyObject, containerHeight, scaleValueObject, scrubScene, scrubThumb, scrubThumbLeft, scrubThumbRight, sheetType, } = this.props; const { leftOfScrubMovie, rightOfScrubMovie } = this.state; e.stopPropagation(); if (e.clientY < MENU_HEADER_HEIGHT + containerHeight) { const scrubLineValue = e.clientX; let scrubFrameNumber; if (sheetType === SHEET_TYPE.INTERVAL) { scrubFrameNumber = getScrubFrameNumber( scrubLineValue, keyObject, scaleValueObject, file.frameCount, scrubThumb, scrubThumbLeft, scrubThumbRight, leftOfScrubMovie, rightOfScrubMovie, ); } else { scrubFrameNumber = getSceneScrubFrameNumber( scrubLineValue, scaleValueObject, scrubThumb, scrubScene, leftOfScrubMovie, rightOfScrubMovie, ); } const scrubLineOnTimelineValue = mapRange( scrubFrameNumber, 0, file.frameCount, 0, scaleValueObject.containerWidth, ); this.setState({ scrubLineValue, scrubFrameNumber, scrubLineOnTimelineValue, }); this.updateOpencvVideoCanvas(scrubFrameNumber); } else { this.onScrubCancel(); } } onScrubClickWithStop(e) { const { onScrubReturn, scrubWindowTriggerTime } = this.props; const { scrubFrameNumber } = this.state; e.stopPropagation(); // for the scrub window the user has to click and drag while keeping the mouse pressed // use triggerTime to keep scrub window open if users just click and release the mouse within 1000ms const timeSinceClick = Date.now() - scrubWindowTriggerTime; if (timeSinceClick > 1000) { log.debug(`onScrubReturn, new frameNumber: ${scrubFrameNumber}`); onScrubReturn(scrubFrameNumber); } } onScrubCancel() { const { onScrubReturn } = this.props; log.debug('Cancel scrubbing'); onScrubReturn(); } updateOpencvVideoCanvas(currentFrame) { const { file, opencvVideo, scaleValueObject } = this.props; const { cropRect, thisTransformObject = TRANSFORMOBJECT_INIT } = this.state; setPosition(opencvVideo, currentFrame, file.useRatio); const mat = opencvVideo.read(); if (!mat.empty) { // optional transformation const matTransformed = transformMat(mat, thisTransformObject, cropRect); const img = matTransformed.resizeToMax( scaleValueObject.aspectRatioInv < 1 ? parseInt(scaleValueObject.scrubMovieWidth, 10) : parseInt(scaleValueObject.scrubMovieHeight, 10), ); const matRGBA = img.channels === 1 ? img.cvtColor(opencv.COLOR_GRAY2RGBA) : img.cvtColor(opencv.COLOR_BGR2RGBA); this.opencvVideoCanvasRef.height = img.rows; this.opencvVideoCanvasRef.width = img.cols; const imgData = new ImageData(new Uint8ClampedArray(matRGBA.getData()), img.cols, img.rows); const ctx = this.opencvVideoCanvasRef.getContext('2d'); ctx.putImageData(imgData, 0, 0); } } render() { const { file, keyObject, objectUrlObjects, scaleValueObject, scrubThumb, scrubThumbLeft, scrubThumbRight, settings, sheetType, } = this.props; const { leftOfScrubMovie, rightOfScrubMovie, scrubFrameNumber, scrubInfo, scrubLineOnTimelineValue, scrubLineValue, scrubThumbLineValue, timeLineCutIn = 0, timeLineCutOut = 0, timeLineScrubThumb = 0, } = this.state; let addBefore = false; let addAfter = false; // only allow add before and add after when interval type if (sheetType === SHEET_TYPE.INTERVAL) { addBefore = keyObject.shiftKey; addAfter = keyObject.altKey; } return ( <div className={styles.scrubContainerBackground} onMouseMove={this.onScrubMouseMoveWithStop} onMouseUp={this.onScrubClickWithStop} // onClick={this.onScrubClickWithStop} > <div className={styles.scrubInfo}> {addBefore && 'ADD BEFORE'} {addAfter && 'ADD AFTER'} {!addBefore && !addAfter && 'CHANGE TO'} </div> <div className={styles.scrubContainer} style={{ height: scaleValueObject.scrubContainerHeight, width: scaleValueObject.scrubContainerWidth, }} > <div className={styles.scrubInnerContainer} style={{ width: scaleValueObject.scrubInnerContainerWidth, }} > <span className={styles.scrubThumbLeft} style={{ backgroundImage: `url(${ addAfter ? objectUrlObjects[scrubThumb.frameId] : objectUrlObjects[scrubThumbLeft.frameId] || transparent })`, height: scaleValueObject.scrubInOutMovieHeight, width: scaleValueObject.scrubInOutMovieWidth, margin: settings.defaultScrubWindowMargin, }} /> {/* keyObject.ctrlKey && <div style={{ content: '', zIndex: 1, backgroundImage: `url(${objectUrlObjects[scrubThumb.frameId]})`, backgroundSize: 'cover', opacity: '0.4', position: 'absolute', height: scaleValueObject.scrubMovieHeight, width: scaleValueObject.scrubMovieWidth, margin: settings.defaultScrubWindowMargin, top: 0, left: scaleValueObject.scrubInOutMovieWidth, }} /> */} <span className={styles.scrubThumb} style={{ height: scaleValueObject.scrubMovieHeight, width: scaleValueObject.scrubMovieWidth, }} > <canvas ref={el => { this.opencvVideoCanvasRef = el; }} /> </span> <span className={styles.scrubThumbRight} style={{ backgroundImage: `url(${ addBefore ? objectUrlObjects[scrubThumb.frameId] : objectUrlObjects[scrubThumbRight.frameId] || transparent })`, height: scaleValueObject.scrubInOutMovieHeight, width: scaleValueObject.scrubInOutMovieWidth, margin: settings.defaultScrubWindowMargin, }} /> </div> <span id="currentTimeDisplay" className={styles.frameNumberOrTimeCode} style={{ left: `${scrubLineValue}px`, }} > {getThumbInfoValue(scrubInfo, scrubFrameNumber, file.fps)} </span> <div className={styles.scrubLine} style={{ left: `${scrubLineValue}px`, }} /> <span className={styles.scrubThumbframeNumberOrTimeCode} style={{ left: `${leftOfScrubMovie}px`, }} > {getThumbInfoValue(scrubInfo, addAfter ? scrubThumb.frameNumber : scrubThumbLeft.frameNumber, file.fps)} </span> {!addBefore && !addAfter && ( <span className={styles.scrubThumbframeNumberOrTimeCode} style={{ left: `${scrubThumbLineValue}px`, }} > {getThumbInfoValue(scrubInfo, scrubThumb.frameNumber, file.fps)} </span> )} <span className={styles.scrubThumbframeNumberOrTimeCode} style={{ left: `${rightOfScrubMovie}px`, }} > {getThumbInfoValue(scrubInfo, addBefore ? scrubThumb.frameNumber : scrubThumbRight.frameNumber, file.fps)} </span> <div className={styles.scrubThumbLine} style={{ left: `${scrubThumbLineValue}px`, }} /> <div id="timeLine" className={`${styles.timelineWrapper}`}> <div className={`${styles.timelinePlayhead}`} style={{ left: `${scrubLineOnTimelineValue}px`, }} /> <div className={`${styles.timelineScrubThumb}`} style={{ left: `${timeLineScrubThumb}px`, }} /> <div className={`${styles.timelineCut}`} style={{ left: timeLineCutIn, width: timeLineCutOut - timeLineCutIn, }} /> </div> </div> {/* <div className={`${styles.scrubDescription} ${styles.textButton}`} style={{ height: `${MENU_HEADER_HEIGHT}px`, }} > {addAfter ? 'Add after' : (addBefore ? 'Add before' : 'Change')} </div> */} <Popup trigger={ <div className={styles.scrubCancelBar} onMouseOver={this.onScrubCancel} style={{ height: `${MENU_FOOTER_HEIGHT}px`, }} > Cancel </div> } open basic inverted wide position="top left" offset="-50%, 8px" className={stylesPop.popup} content={ sheetType === SHEET_TYPE.INTERVAL ? ( <span> Choose frame: drag left and right <br /> Allow dragging over whole movie: <mark>CTRL</mark> <br /> Add new thumb before: <mark>SHIFT</mark> <br /> Add new thumb after: <mark>ALT</mark> <br /> Confirm frame: click/release mouse <br /> Cancel: Move mouse over cancel zone </span> ) : ( <span> Choose frame: drag left and right <br /> Confirm frame: click/release mouse <br /> Cancel: Move mouse over cancel zone </span> ) } /> </div> ); } } Scrub.defaultProps = { // thumbImageObjectUrl: empty, }; Scrub.propTypes = { file: PropTypes.shape({ id: PropTypes.string, frameCount: PropTypes.number, width: PropTypes.number, height: PropTypes.number, columnCount: PropTypes.number, path: PropTypes.string, useRatio: PropTypes.bool, }), keyObject: PropTypes.object.isRequired, scaleValueObject: PropTypes.object.isRequired, settings: PropTypes.object.isRequired, objectUrlObjects: PropTypes.object.isRequired, containerHeight: PropTypes.number.isRequired, containerWidth: PropTypes.number.isRequired, scrubThumb: PropTypes.object.isRequired, scrubThumbLeft: PropTypes.object.isRequired, scrubThumbRight: PropTypes.object.isRequired, opencvVideo: PropTypes.object.isRequired, }; export default Scrub; <|start_filename|>scripts/opencv.js<|end_filename|> /* eslint no-inner-declarations: 0 */ import path from 'path'; import log from 'electron-log'; const shell = require('shelljs'); // cross platform variables const projectRoot = shell.pwd().stdout; if (process.platform === 'darwin') { // Include all opencv dependencies including ffmpeg log.info( 'running opencv script to copy all its dependencies including ffmpeg library files into the opencv folder for later packaging and relink them if necessary' ); function fixDeps(dirPath, dependencyDirName) { log.info(`checking all dylib files in ${dirPath}, copy dependencies into ${dependencyDirName} and change the dylib linking`); const dylibs = shell.ls(dirPath) const allDeps = [] dylibs .filter(file => file.indexOf('dylib') !== -1) .forEach(dylibFilename => { const dylib = path.join(dirPath, dylibFilename); console.log(`checking outer dependencies of file ${dylib}`); const outerDeps = shell .exec(`otool -l ${dylib} | grep 'name /usr/local'`) .stdout.split('\n') .filter(dep => dep !== ''); if (outerDeps.length > 0) { shell.exec(`install_name_tool -add_rpath @loader_path/${dependencyDirName}`); } outerDeps.forEach(depLine => { const regex = /name (.+?(?=\ \(offset))/g; // transform "name /usr/lib/libc++.1.dylib (offset 24)" -> "/usr/lib/libc++.1.dylib" const depfilePath = regex.exec(depLine)[1]; // "/usr/lib/libc++.1.dylib" const depfileName = depfilePath.replace(/^.*[\\\/]/, ''); if (!allDeps.find(e => e === depfilePath)) { // if not added already -> add it allDeps.push(depfilePath); console.log(` copying outer dependency ${depfilePath} to ${outerDependencyDir}`); shell.cp('-n', depfilePath, outerDependencyDir); } shell.chmod('-v', '666', dylib); const fixCommand = `install_name_tool -change ${depfilePath} @loader_path/${dependencyDirName}/${depfileName} ${dylib}`; console.log(` fix with command: ${fixCommand}`); shell.exec(fixCommand); }) console.log(`\n\n`); }) console.info('All outer dependencies:'); console.log(allDeps); return allDeps; } // osx path variables const opencvLibDir = path.resolve( projectRoot, 'app/node_modules/opencv-build/opencv/build/lib/' ); const dependencyDir = 'dependencies' const outerDependencyDir = path.join(opencvLibDir, dependencyDir); log.debug(`projectRoot: ${projectRoot}`); log.debug(`outerDependencyDir: ${outerDependencyDir}`); log.debug(`opencvLibDir: ${opencvLibDir}`); // create dependencies folder shell.mkdir('-p', outerDependencyDir); fixDeps(opencvLibDir, dependencyDir); fixDeps(outerDependencyDir, ''); fixDeps(outerDependencyDir, ''); fixDeps(outerDependencyDir, ''); } else if (process.platform === 'win32') { // it seems that on windows opencv is already bundled with ffmpeg // but the redistributable files need to be copied into the the apps root folder // I did not manage to configure electron-builder to copy the dll's directly // therefore this is done in a 2 step process // 1. this script copies the dll's into the dist folder // 2. electron-builder copies the dll's into the root folder when packaging const distDir = path.resolve(projectRoot, 'app/dist/redistributable/'); shell.mkdir('-p', distDir); // create folder if it does not exist yet // copy necessary redistributable files shell.cp('-n', '/Windows/system32/CONCRT140.dll',distDir ); shell.cp('-n', '/Windows/system32/MSVCP140.dll',distDir ); shell.cp('-n', '/Windows/system32/VCRUNTIME140.dll',distDir ); } <|start_filename|>app/worker_database.js<|end_filename|> import React from 'react'; import { render } from 'react-dom'; import log from 'electron-log'; import { addFrameToIndexedDB, getObjectUrlsFromFramelist, openDBConnection, updateFrameInIndexedDB, } from './utils/utilsForIndexedDB'; import { getOccurrencesOfFace } from './utils/utilsSortAndFilter'; import { getFaceScanByFileId } from './utils/utilsForSqlite'; import Queue from './utils/queue'; const unhandled = require('electron-unhandled'); // const assert = require('assert'); unhandled(); const { ipcRenderer } = require('electron'); log.debug('I am the databaseWorkerWindow - responsible for storing things in indexedDB'); // openDB if not already open // to avoid errors as Chrome sometimes closes the connection after a while openDBConnection(); // set up a queue and check it in a regular interval const objectUrlQueue = new Queue(); let setIntervalForImagesHandle; window.addEventListener('error', event => { log.error(event); ipcRenderer.send( 'message-from-opencvWorkerWindow-to-mainWindow', 'progressMessage', 'error', `There has been an error while loading the Database Worker. Please contact us for support: ${event.message}`, false, ); event.preventDefault(); }); window.addEventListener('uncaughtException', event => { log.error(event); ipcRenderer.send( 'message-from-opencvWorkerWindow-to-mainWindow', 'progressMessage', 'error', `There has been an uncaughtException while loading the Database Worker. Please contact us for support: ${event.message}`, false, ); event.preventDefault(); }); window.addEventListener('unhandledrejection', event => { log.error(event); ipcRenderer.send( 'message-from-opencvWorkerWindow-to-mainWindow', 'progressMessage', 'error', `There has been an unhandledrejection while loading the Database Worker. Please contact us for support: ${event.message}`, false, ); event.preventDefault(); }); // handle crashes and kill events process.on('uncaughtException', err => { // log the message and stack trace log.error(err); // fs.writeFileSync('crash.log', err + "\n" + err.stack); }); // handle crashes and kill events process.on('SIGTERM', err => { // log the message and stack trace log.error(err); // fs.writeFileSync('shutdown.log', 'Received SIGTERM signal'); }); const pullImagesFromOpencvWorker = () => { log.debug('now I am running pullImagesFromOpencvWorker'); ipcRenderer.send( 'message-from-databaseWorkerWindow-to-opencvWorkerWindow', 'get-some-images-from-imageQueue', 1000, // amount ); }; setInterval(() => { // objectUrlQueue // console.log(objectUrlQueue.size()) const size = objectUrlQueue.size(); if (size !== 0) { log.debug(`the objectUrlQueue size is: ${size}`); // start requestIdleCallback in mainWindow for objectUrlQueue ipcRenderer.send('message-from-opencvWorkerWindow-to-mainWindow', 'start-requestIdleCallback-for-objectUrlQueue'); } }, 1000); ipcRenderer.on('send-base64-frame', (event, frameId, fileId, frameNumber, outBase64, onlyReplace = false) => { log.debug('databaseWorkerWindow | on send-base64-frame'); if (onlyReplace) { const fastTrack = onlyReplace; // make this one use fastTrack so it gets updated right away updateFrameInIndexedDB(frameId, outBase64, objectUrlQueue, fastTrack); } else { addFrameToIndexedDB(frameId, fileId, frameNumber, outBase64, objectUrlQueue); } }); ipcRenderer.on('update-base64-frame', (event, frameId, outBase64) => { log.debug('databaseWorkerWindow | on update-base64-frame'); updateFrameInIndexedDB(frameId, outBase64, objectUrlQueue); }); ipcRenderer.on('get-arrayOfObjectUrls', () => { log.debug('databaseWorkerWindow | on get-arrayOfObjectUrls'); getObjectUrlsFromFramelist(objectUrlQueue); }); ipcRenderer.on('get-some-objectUrls-from-objectUrlQueue', () => { log.debug('databaseWorkerWindow | on get-some-objectUrls-from-objectUrlQueue'); const arrayOfObjectUrls = objectUrlQueue.data; log.debug(arrayOfObjectUrls); // start requestIdleCallback in mainWindow for objectUrlQueue ipcRenderer.send('message-from-databaseWorkerWindow-to-mainWindow', 'send-arrayOfObjectUrls', arrayOfObjectUrls); objectUrlQueue.clear(); }); ipcRenderer.on('start-setIntervalForImages-for-imageQueue', () => { log.debug('databaseWorkerWindow | on start-setIntervalForImages-for-imageQueue'); // start setIntervalForImages until it is cancelled if (setIntervalForImagesHandle === undefined) { // start interval to pull images from the opencvWorkerWindow setIntervalForImagesHandle = window.setInterval(() => { pullImagesFromOpencvWorker(); }, 1000); log.debug('now I start setIntervalForImages'); } else { log.debug('setIntervalForImages already running. no new setIntervalForImages will be started.'); } }); ipcRenderer.on('receive-some-images-from-imageQueue', (event, someImages) => { log.debug(`databaseWorkerWindow | on receive-some-images-from-imageQueue: ${someImages.length}`); if (someImages.length > 0) { // add images in reveres as they are stored inverse in the queue someImages.reverse().map(async image => { // log.debug(image.frameNumber); return addFrameToIndexedDB(image.frameId, image.fileId, image.frameNumber, image.outBase64, objectUrlQueue); }); } log.debug('now I cancel setIntervalForImages'); setIntervalForImagesHandle = window.clearInterval(setIntervalForImagesHandle); }); ipcRenderer.on( 'send-find-face', (event, fileId, sheetId, parentSheetId, frameNumber, defaultFaceUniquenessThreshold) => { log.debug(`databaseWorkerWindow | on send-find-face: ${frameNumber}`); const faceScanArray = getFaceScanByFileId(fileId); console.log(faceScanArray); // get frameNumbers of occurrences of a faceGroup const { faceIdOfOrigin, foundFrames } = getOccurrencesOfFace( faceScanArray, frameNumber, defaultFaceUniquenessThreshold, ); console.log(faceIdOfOrigin); console.log(foundFrames); ipcRenderer.send( 'message-from-databaseWorkerWindow-to-mainWindow', 'receive-find-face', fileId, sheetId, parentSheetId, frameNumber, faceIdOfOrigin, foundFrames, ); }, ); render( <div> <h1>I am the Database worker window.</h1> </div>, document.getElementById('worker_database'), ); <|start_filename|>app/containers/App.js<|end_filename|> import React, { Component } from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import Dropzone from 'react-dropzone'; import fs from 'fs'; import { Button, Container, Dimmer, Divider, Form, Grid, Header, Icon, Loader, Modal, Popup, Progress, } from 'semantic-ui-react'; import uuidV4 from 'uuid/v4'; import { Line, defaults } from 'react-chartjs-2'; import path from 'path'; import log from 'electron-log'; import os from 'os'; import Database from 'better-sqlite3'; import extract from 'png-chunks-extract'; import text from 'png-chunk-text'; import { Zoom, ToastContainer, toast } from 'react-toastify'; import axios from 'axios'; import '../app.global.css'; import FileList from './FileList'; import SettingsList from './SettingsList'; import SortedVisibleThumbGrid from './VisibleThumbGrid'; import SortedVisibleSceneGrid from './VisibleSceneGrid'; import Conditional from '../components/Conditional'; import HeaderComponent from '../components/HeaderComponent'; import EditTransformModal from '../components/EditTransformModal'; import FloatingMenu from '../components/FloatingMenu'; import Footer from '../components/Footer'; import VideoPlayer from '../components/VideoPlayer'; import Scrub from '../components/Scrub'; import getScaleValueObject from '../utils/getScaleValueObject'; import { calculateSceneListFromDifferenceArray, createSceneArray, doesFileFolderExist, doesSheetExist, getAdjacentSceneIndicesFromCut, getColumnCount, getEDLscenes, getFrameNumberWithSceneOrThumbId, getFile, getFileName, getFilePath, getFileStatsObject, getFileTransformObject, getFrameCount, getFramenumbersOfSheet, getHighestFrame, getLeftAndRightThumb, getLowestFrame, getMoviePrintColor, getNewSheetName, getObjectProperty, getParentSheetId, getSceneFromFrameNumber, getSecondsPerRow, getSheet, getSheetCount, getSheetFilter, getSheetId, getSheetIdArray, getSheetName, getSheetType, getSheetView, getShotNumber, getThumbsCount, getThumbsCountOfArray, getVisibleThumbs, isEquivalent, limitFrameNumberWithinMovieRange, limitRange, pad, prepareDataToExportOrEmbed, repairFrameScanData, } from '../utils/utils'; import { deleteFaceDescriptorFromFaceScanArray, determineAndInsertFaceGroupNumber, filterArray, getFaceIdArrayFromThumbs, getIntervalArray, insertFaceOccurrence, sortArray, sortThumbsArray, } from '../utils/utilsSortAndFilter'; import { RotateFlags } from '../utils/openCVProperties'; import styles from './App.css'; import stylesPop from '../components/Popup.css'; import { addIntervalSheet, addMoviesToList, addNewThumbsWithOrder, addScenesFromSceneList, addScenesWithoutCapturingThumbs, addThumb, addThumbs, changeThumb, changeThumbArray, changeAndSortThumbArray, clearMovieList, clearScenes, cutScene, deleteSheets, duplicateSheet, hideMovielist, hideSettings, mergeScenes, removeMovieListItem, replaceFileDetails, setCurrentFileId, setCurrentSheetId, setDefaultCachedFramesSize, setDefaultColumnCount, setDefaultDetectInOutPoint, setDefaultEmbedFilePath, setDefaultEmbedFrameNumbers, setDefaultFaceSizeThreshold, setDefaultFaceConfidenceThreshold, setDefaultFaceUniquenessThreshold, setDefaultFrameinfoBackgroundColor, setDefaultFrameinfoColor, setDefaultFrameinfoMargin, setDefaultFrameinfoPosition, setDefaultFrameinfoScale, setDefaultMarginRatio, setDefaultOutputJpgQuality, setDefaultThumbJpgQuality, setDefaultMoviePrintBackgroundColor, setDefaultMoviePrintName, setDefaultSingleThumbName, setDefaultAllThumbsName, setDefaultMoviePrintWidth, setDefaultOpenFileExplorerAfterSaving, setDefaultOutputFormat, setDefaultThumbFormat, setDefaultOutputPath, setDefaultOutputPathFromMovie, setDefaultPaperAspectRatioInv, setDefaultRoundedCorners, setDefaultSaveOptionIncludeIndividual, setDefaultSaveOptionOverwrite, setDefaultSceneDetectionThreshold, setDefaultSheetView, setDefaultShotDetectionMethod, setDefaultShowDetailsInHeader, setDefaultShowHeader, setDefaultShowImages, setDefaultShowFaceRect, setDefaultShowPaperPreview, setDefaultShowPathInHeader, setDefaultShowTimelineInHeader, setDefaultThumbCount, setDefaultThumbInfo, setDefaultThumbnailScale, setDefaultTimelineViewFlow, setDefaultTimelineViewMinDisplaySceneLengthInFrames, setDefaultTimelineViewSecondsPerRow, setDefaultTimelineViewWidthScale, setEmailAddress, setView, setVisibilityFilter, setZoomLevel, showAllThumbs, showMovielist, showSettings, showThumbsByFrameNumberArray, rotateWidthAndHeight, updateAspectRatio, updateCropping, updateFileDetails, updateFileDetailUseRatio, updateFileMissingStatus, updateFileScanStatus, updateFrameNumberAndColorArray, updateInOutPoint, updateOrder, updateSceneArray, updateSheetColumnCount, updateSheetCounter, updateSheetFilter, updateSheetName, updateSheetParent, updateSheetSecondsPerRow, updateSheetType, updateSheetView, } from '../actions'; import { DEFAULT_COLUMN_COUNT, DEFAULT_MIN_MOVIEPRINTWIDTH_MARGIN, DEFAULT_THUMB_COUNT_MAX, DEFAULT_THUMB_COUNT, DEFAULT_TIMELINEVIEW_SECONDS_PER_ROW, DEFAULT_VIDEO_PLAYER_CONTROLLER_HEIGHT, EXPORT_FORMAT_OPTIONS, FILTER_METHOD, FRAMESDB_PATH, MENU_FOOTER_HEIGHT, MENU_HEADER_HEIGHT, ROTATION_OPTIONS, SCALE_VALUE_ARRAY, SHEET_TYPE, SHEET_VIEW, SHOT_DETECTION_METHOD, SORT_METHOD, THUMB_SELECTION, TRANSFORMOBJECT_INIT, URL_CHANGE_LOG, URL_FEEDBACK_FORM, URL_REST_API_CHECK_FOR_UPDATES, VIEW, WINDOW_HEIGHT, WINDOW_WIDTH, ZOOM_SCALE, } from '../utils/constants'; import { deleteTableFramelist } from '../utils/utilsForIndexedDB'; import { deleteTableFrameScanList, deleteTableReduxState, getFaceScanByFileId, getFrameScanByFileId, getFrameScanCount, } from '../utils/utilsForSqlite'; import startupImg from '../img/MoviePrint-steps.svg'; const compareVersions = require('compare-versions'); const { ipcRenderer } = require('electron'); const { dialog, app, shell } = require('electron').remote; const opencv = require('opencv4nodejs'); const moviePrintDB = new Database(FRAMESDB_PATH, { verbose: console.log }); moviePrintDB.pragma('journal_mode = WAL'); // const DEV_OPENCV_SCENE_DETECTION = process.env.DEV_OPENCV_SCENE_DETECTION === 'true'; // Disable animating charts by default. defaults.global.animation = false; const returnSheetProperties = ( columnCount = DEFAULT_COLUMN_COUNT, thumbCount = DEFAULT_THUMB_COUNT, secondsPerRowTemp = undefined, ) => { return { columnCountTemp: columnCount, thumbCountTemp: thumbCount, columnCount, thumbCount, secondsPerRowTemp, }; }; class App extends Component { constructor() { super(); this.webviewRef = React.createRef(); this.dropzoneRef = React.createRef(); this.videoPlayer = React.createRef(); const emptyColorsArray = getMoviePrintColor(DEFAULT_THUMB_COUNT_MAX); this.state = { containerHeight: 360, containerWidth: 640, secondsPerRowTemp: DEFAULT_TIMELINEVIEW_SECONDS_PER_ROW, columnCountTemp: DEFAULT_COLUMN_COUNT, thumbCountTemp: DEFAULT_THUMB_COUNT, columnCount: DEFAULT_COLUMN_COUNT, thumbCount: DEFAULT_THUMB_COUNT, reCapture: true, emptyColorsArray, scaleValueObject: undefined, savingMoviePrint: false, selectedThumbsArray: [], jumpToFrameNumber: undefined, // file match needs to be in sync with addMoviesToList(), onReplaceMovieListItemClick() and onDrop() !!! accept: 'video/*,.divx,.mkv,.ogg,.VOB,', dropzoneActive: false, loadingFirstFile: false, keyObject: { shiftKey: false, altKey: false, ctrlKey: false, metaKey: false, which: undefined, }, filesToLoad: [], showFeedbackForm: false, feedbackFormIsLoading: false, intendToCloseFeedbackForm: false, opencvVideo: undefined, showScrubWindow: false, scrubThumb: undefined, scrubScene: undefined, showChart: false, chartData: { labels: ['Inpoint', 'Outpoint'], datasets: [ { label: 'Empty dataset', backgroundColor: 'rgb(0, 99, 132)', data: [0, 0], }, ], }, fileScanRunning: false, sheetsToPrint: [], sheetsToUpdate: [], savingAllMoviePrints: false, showTransformModal: false, transformObject: {}, objectUrlObjects: {}, fileIdToBeRecaptured: undefined, fileIdToBeCaptured: undefined, requestIdleCallbackForScenesHandle: undefined, requestIdleCallbackForObjectUrlHandle: undefined, }; this.handleKeyPress = this.handleKeyPress.bind(this); this.handleKeyUp = this.handleKeyUp.bind(this); this.onSelectThumbMethod = this.onSelectThumbMethod.bind(this); this.onDeselectThumbMethod = this.onDeselectThumbMethod.bind(this); this.showMovielist = this.showMovielist.bind(this); this.hideMovielist = this.hideMovielist.bind(this); this.toggleMovielist = this.toggleMovielist.bind(this); this.toggleSettings = this.toggleSettings.bind(this); this.showSettings = this.showSettings.bind(this); this.hideSettings = this.hideSettings.bind(this); this.onShowAllThumbs = this.onShowAllThumbs.bind(this); this.onViewToggle = this.onViewToggle.bind(this); this.onChangeThumb = this.onChangeThumb.bind(this); this.onAddThumb = this.onAddThumb.bind(this); this.onScrubReturn = this.onScrubReturn.bind(this); this.onScrubClick = this.onScrubClick.bind(this); this.onExpandClick = this.onExpandClick.bind(this); this.onAddThumbClick = this.onAddThumbClick.bind(this); this.onJumpToCutThumbClick = this.onJumpToCutThumbClick.bind(this); this.onJumpToCutSceneClick = this.onJumpToCutSceneClick.bind(this); this.onCutSceneClick = this.onCutSceneClick.bind(this); this.onMergeSceneClick = this.onMergeSceneClick.bind(this); this.openMoviesDialog = this.openMoviesDialog.bind(this); this.onOpenFeedbackForm = this.onOpenFeedbackForm.bind(this); this.onCloseFeedbackForm = this.onCloseFeedbackForm.bind(this); this.onSaveMoviePrint = this.onSaveMoviePrint.bind(this); this.onSaveAllMoviePrints = this.onSaveAllMoviePrints.bind(this); this.updatecontainerWidthAndHeight = this.updatecontainerWidthAndHeight.bind(this); this.updateScaleValue = this.updateScaleValue.bind(this); this.recaptureAllFrames = this.recaptureAllFrames.bind(this); this.onFileListElementClick = this.onFileListElementClick.bind(this); this.onBackToParentClick = this.onBackToParentClick.bind(this); this.onAddIntervalSheet = this.onAddIntervalSheet.bind(this); this.onAddIntervalSheetClick = this.onAddIntervalSheetClick.bind(this); this.onAddFaceSheetClick = this.onAddFaceSheetClick.bind(this); this.onErrorPosterFrame = this.onErrorPosterFrame.bind(this); this.getThumbsForFile = this.getThumbsForFile.bind(this); this.onFinishedGettingFaces = this.onFinishedGettingFaces.bind(this); this.optimiseGridLayout = this.optimiseGridLayout.bind(this); this.onChangeRow = this.onChangeRow.bind(this); this.onChangeColumn = this.onChangeColumn.bind(this); this.onChangeColumnAndApply = this.onChangeColumnAndApply.bind(this); this.onChangeShowFaceRectClick = this.onChangeShowFaceRectClick.bind(this); this.onShowPaperPreviewClick = this.onShowPaperPreviewClick.bind(this); this.onOutputPathFromMovieClick = this.onOutputPathFromMovieClick.bind(this); this.onPaperAspectRatioClick = this.onPaperAspectRatioClick.bind(this); this.onDetectInOutPointClick = this.onDetectInOutPointClick.bind(this); this.onReCaptureClick = this.onReCaptureClick.bind(this); this.onApplyNewGridClick = this.onApplyNewGridClick.bind(this); this.onCancelClick = this.onCancelClick.bind(this); this.onChangeMargin = this.onChangeMargin.bind(this); this.onChangeOutputJpgQuality = this.onChangeOutputJpgQuality.bind(this); this.onChangeThumbJpgQuality = this.onChangeThumbJpgQuality.bind(this); this.onChangeFaceSizeThreshold = this.onChangeFaceSizeThreshold.bind(this); this.onChangeFaceConfidenceThreshold = this.onChangeFaceConfidenceThreshold.bind(this); this.onChangeFaceUniquenessThreshold = this.onChangeFaceUniquenessThreshold.bind(this); this.onChangeDefaultZoomLevel = this.onChangeDefaultZoomLevel.bind(this); this.onChangeFrameinfoScale = this.onChangeFrameinfoScale.bind(this); this.onChangeFrameinfoMargin = this.onChangeFrameinfoMargin.bind(this); this.onChangeMinDisplaySceneLength = this.onChangeMinDisplaySceneLength.bind(this); this.onChangeSceneDetectionThreshold = this.onChangeSceneDetectionThreshold.bind(this); this.onChangeTimelineViewSecondsPerRow = this.onChangeTimelineViewSecondsPerRow.bind(this); this.onChangeTimelineViewWidthScale = this.onChangeTimelineViewWidthScale.bind(this); this.onTimelineViewFlowClick = this.onTimelineViewFlowClick.bind(this); this.onToggleHeaderClick = this.onToggleHeaderClick.bind(this); this.onToggleImagesClick = this.onToggleImagesClick.bind(this); this.onToggleFaceRectClick = this.onToggleFaceRectClick.bind(this); this.onShowPathInHeaderClick = this.onShowPathInHeaderClick.bind(this); this.onShowDetailsInHeaderClick = this.onShowDetailsInHeaderClick.bind(this); this.onShowTimelineInHeaderClick = this.onShowTimelineInHeaderClick.bind(this); this.onRoundedCornersClick = this.onRoundedCornersClick.bind(this); this.onToggleShowHiddenThumbsClick = this.onToggleShowHiddenThumbsClick.bind(this); this.onUpdateSheetFilter = this.onUpdateSheetFilter.bind(this); this.onShowHiddenThumbsClick = this.onShowHiddenThumbsClick.bind(this); this.onThumbInfoClick = this.onThumbInfoClick.bind(this); this.onSetViewClick = this.onSetViewClick.bind(this); this.onImportMoviePrint = this.onImportMoviePrint.bind(this); this.onOpenFileExplorer = this.onOpenFileExplorer.bind(this); this.onClearMovieList = this.onClearMovieList.bind(this); this.onChangeSheetViewClick = this.onChangeSheetViewClick.bind(this); this.onSubmitMoviePrintNameClick = this.onSubmitMoviePrintNameClick.bind(this); this.toggleSheetView = this.toggleSheetView.bind(this); this.setOrToggleDefaultSheetView = this.setOrToggleDefaultSheetView.bind(this); this.onSetSheetClick = this.onSetSheetClick.bind(this); this.onDuplicateSheetClick = this.onDuplicateSheetClick.bind(this); this.onConvertToIntervalBasedClick = this.onConvertToIntervalBasedClick.bind(this); this.onExportSheetClick = this.onExportSheetClick.bind(this); this.onScanMovieListItemClick = this.onScanMovieListItemClick.bind(this); this.onReplaceMovieListItemClick = this.onReplaceMovieListItemClick.bind(this); this.onEditTransformListItemClick = this.onEditTransformListItemClick.bind(this); this.onChangeTransform = this.onChangeTransform.bind(this); this.onRemoveMovieListItem = this.onRemoveMovieListItem.bind(this); this.onDeleteSheetClick = this.onDeleteSheetClick.bind(this); this.onChangeDefaultMoviePrintName = this.onChangeDefaultMoviePrintName.bind(this); this.onChangeOutputPathClick = this.onChangeOutputPathClick.bind(this); this.onFrameinfoPositionClick = this.onFrameinfoPositionClick.bind(this); this.onOutputFormatClick = this.onOutputFormatClick.bind(this); this.onThumbFormatClick = this.onThumbFormatClick.bind(this); this.onCachedFramesSizeClick = this.onCachedFramesSizeClick.bind(this); this.onOverwriteClick = this.onOverwriteClick.bind(this); this.onIncludeIndividualClick = this.onIncludeIndividualClick.bind(this); this.onEmbedFrameNumbersClick = this.onEmbedFrameNumbersClick.bind(this); this.onEmbedFilePathClick = this.onEmbedFilePathClick.bind(this); this.onOpenFileExplorerAfterSavingClick = this.onOpenFileExplorerAfterSavingClick.bind(this); this.onThumbnailScaleClick = this.onThumbnailScaleClick.bind(this); this.onMoviePrintWidthClick = this.onMoviePrintWidthClick.bind(this); this.onShotDetectionMethodClick = this.onShotDetectionMethodClick.bind(this); this.runSceneDetection = this.runSceneDetection.bind(this); this.cancelFileScan = this.cancelFileScan.bind(this); this.calculateSceneList = this.calculateSceneList.bind(this); this.onToggleDetectionChart = this.onToggleDetectionChart.bind(this); this.onSortSheet = this.onSortSheet.bind(this); this.onFilterSheet = this.onFilterSheet.bind(this); this.addFaceData = this.addFaceData.bind(this); this.getFaceData = this.getFaceData.bind(this); this.onHideDetectionChart = this.onHideDetectionChart.bind(this); this.checkForUpdates = this.checkForUpdates.bind(this); this.pullScenesFromOpencvWorker = this.pullScenesFromOpencvWorker.bind(this); // moving ipcRenderer into constructor so it gets executed even when // the component can not mount and the ErrorBoundary kicks in ipcRenderer.on('delete-all-tables', () => { log.debug('delete-all-tables'); deleteTableFrameScanList(); deleteTableReduxState(); deleteTableFramelist(); }); } static getDerivedStateFromProps(props, state) { const { currentFileId, currentSheetId, file, settings, sheetsByFileId, scenes, visibilitySettings } = props; const { defaultShowPaperPreview } = settings; const { containerWidth } = state; // update scaleValueObject, sheetProperties, opencvVideo if file/sheet/thumbcount changes if (file !== undefined) { const newThumbCount = getThumbsCount( sheetsByFileId, file.id, currentSheetId, settings, visibilitySettings.visibilityFilter, ); if ( state.currentFileIdInState !== currentFileId || state.currentSheetIdInState !== currentSheetId || state.currentThumbCountInState !== newThumbCount ) { const { columnCountTemp, thumbCountTemp, containerHeight, currentSecondsPerRow } = state; let opencvVideo; if (getObjectProperty(() => file.path)) { try { opencvVideo = new opencv.VideoCapture(file.path); } catch (e) { log.error(e); } } const secondsPerRow = getSecondsPerRow(sheetsByFileId, currentFileId, currentSheetId, settings); const columnCount = getColumnCount(sheetsByFileId, file.id, currentSheetId, settings); const sheetProperties = returnSheetProperties(columnCount, newThumbCount, secondsPerRow); const scaleValueObject = getScaleValueObject( file, settings, visibilitySettings, columnCountTemp, thumbCountTemp, containerWidth, containerHeight, undefined, defaultShowPaperPreview, undefined, scenes, currentSecondsPerRow, ); return { opencvVideo, scaleValueObject, currentFilePathInState: file.path, currentFileIdInState: currentFileId, currentSheetIdInState: currentSheetId, currentThumbCountInState: newThumbCount, ...sheetProperties, }; } } // initial scaleValueObject let scaleValueObject; if (state.scaleValueObject === undefined) { scaleValueObject = getScaleValueObject( undefined, settings, visibilitySettings, undefined, undefined, containerWidth, ); } return { ...(scaleValueObject !== undefined && { scaleValueObject }), // don't add it if it is undefined, it would overwrite itself }; } componentDidMount() { const { currentFileId, currentSecondsPerRow, currentSheetId, dispatch, file, files, scenes, settings, sheetsByFileId, visibilitySettings, } = this.props; const { columnCountTemp, thumbCountTemp, containerWidth, containerHeight } = this.state; const { defaultZoomLevel = ZOOM_SCALE, visibilityFilter } = visibilitySettings; ipcRenderer.on('progress', (event, fileId, progressBarPercentage) => { this.setState({ progressBarPercentage: Math.ceil(progressBarPercentage), }); if (progressBarPercentage === 100) { toast.update(fileId, { className: `${stylesPop.toast} ${stylesPop.toastSuccess}`, progress: null, render: 'Detection finished', hideProgressBar: true, autoClose: 3000, closeButton: true, closeOnClick: true, }); } else { toast.update(fileId, { progress: progressBarPercentage / 100.0, }); } }); ipcRenderer.on( 'progressMessage', ( event, status, message, time = 3000, toastId = undefined, shouldMessageUpdate = false, additionalProperties = undefined, ) => { if (shouldMessageUpdate && toastId !== undefined) { this.updateMessage(message, time, status, toastId, additionalProperties); } this.showMessage(message, time, status, toastId, additionalProperties); }, ); ipcRenderer.on('error-savingMoviePrint', () => { if (this.state.savingMoviePrint) { setTimeout(this.setState({ savingMoviePrint: false }), 1000); // adding timeout to prevent clicking multiple times } ipcRenderer.send('reload-workerWindow'); }); ipcRenderer.on( 'receive-get-file-details', ( event, fileId, filePath, posterFrameId, frameCount, width, height, fps, fourCC, onlyReplace = false, onlyImport = false, ) => { dispatch(updateFileDetails(fileId, frameCount, width, height, fps, fourCC)); ipcRenderer.send( 'message-from-mainWindow-to-opencvWorkerWindow', 'send-get-poster-frame', fileId, filePath, posterFrameId, onlyReplace, onlyImport, ); }, ); // poster frames don't have thumbId ipcRenderer.on( 'receive-get-poster-frame', (event, fileId, filePath, posterFrameId, frameNumber, useRatio, onlyReplace = false, onlyImport = false) => { dispatch(updateFileDetailUseRatio(fileId, useRatio)); // get all posterframes if (!onlyReplace || !onlyImport) { ipcRenderer.send( 'message-from-mainWindow-to-opencvWorkerWindow', 'send-get-in-and-outpoint', fileId, filePath, useRatio, settings.defaultDetectInOutPoint, ); } }, ); ipcRenderer.on('receive-get-in-and-outpoint', (event, fileId, fadeInPoint, fadeOutPoint) => { const { filesToLoad } = this.state; dispatch(updateInOutPoint(fileId, fadeInPoint, fadeOutPoint)); // check if this was not the last file coming back from the renderer if (filesToLoad.length > 0) { // check if the movie just coming back from the renderer should be displayed // this parameter is set in onDrop (when files are added) if (filesToLoad[0].displayMe) { this.onAddIntervalSheetClick(filesToLoad[0].id); } // state should be immutable, therefor // make a copy with slice, then remove the first item with shift, then set new state const copyOfFilesToLoad = filesToLoad.slice(); copyOfFilesToLoad.shift(); this.setState({ filesToLoad: copyOfFilesToLoad, loadingFirstFile: false, }); } }); ipcRenderer.on('failed-to-open-file', (event, fileId) => { if (this.state.filesToLoad.length > 0) { // state should be immutable, therefor // make a copy with slice, then remove the first item with shift, then set new state const copyOfFilesToLoad = this.state.filesToLoad.slice(); copyOfFilesToLoad.shift(); this.setState({ filesToLoad: copyOfFilesToLoad, }); dispatch(removeMovieListItem(fileId)); } }); ipcRenderer.on('update-objectUrl', (event, frameId, objectUrl) => { const { objectUrlObjects } = this.state; // create copy so the state does not get mutated const copyOfObject = { ...objectUrlObjects }; // Update object's name property. copyOfObject[frameId] = objectUrl; this.setState({ objectUrlObjects: copyOfObject, }); }); ipcRenderer.on('send-arrayOfObjectUrls', (event, arrayOfObjectUrls) => { const { objectUrlObjects, requestIdleCallbackForObjectUrlHandle } = this.state; // if arrayOfObjectUrls not empty setState and renew if (arrayOfObjectUrls.length !== 0) { // create copy so the state does not get mutated const copyOfObject = { ...objectUrlObjects }; arrayOfObjectUrls.map(item => { copyOfObject[item.frameId] = item.objectUrl; return undefined; }); this.setState({ objectUrlObjects: copyOfObject, }); const newRequestIdleCallbackHandle = window.requestIdleCallback(this.pullObjectUrlFromdatabaseWorkerWindow); this.setState({ requestIdleCallbackForObjectUrlHandle: newRequestIdleCallbackHandle, }); log.debug('now I requestIdleCallbackForObjectUrl again'); } else { // cancel pullObjectUrlFromdatabaseWorkerWindow window.cancelIdleCallback(requestIdleCallbackForObjectUrlHandle); this.setState({ requestIdleCallbackForObjectUrlHandle: undefined, }); } }); ipcRenderer.on('start-requestIdleCallback-for-objectUrlQueue', event => { const { requestIdleCallbackForObjectUrlHandle } = this.state; // start requestIdleCallback until it is cancelled if (requestIdleCallbackForObjectUrlHandle === undefined) { const newRequestIdleCallbackHandle = window.requestIdleCallback(this.pullObjectUrlFromdatabaseWorkerWindow); this.setState({ requestIdleCallbackForObjectUrlHandle: newRequestIdleCallbackHandle, }); log.debug('now I requestIdleCallbackForObjectUrl'); } else { log.debug( 'requestIdleCallbackForObjectUrl already running. no new requestIdleCallbackForObjectUrl will be started.', ); } }); ipcRenderer.on('update-frameNumber-and-colorArray', (event, frameNumberAndColorArray) => { dispatch(updateFrameNumberAndColorArray(frameNumberAndColorArray)); }); ipcRenderer.on('update-sort-order', (event, detectionArray) => { // dispatch(updateFrameNumberAndColorArray(detectionArray)); }); ipcRenderer.on( 'finished-getting-faces', (event, fileId, sheetId, detectionArray, faceSortMethod, updateSheet = false) => { this.onFinishedGettingFaces(fileId, sheetId, detectionArray, faceSortMethod, updateSheet); }, ); ipcRenderer.on('finished-getting-thumbs', (event, fileId, sheetId) => { const { settings, sheetsByFileId } = this.props; // check if this is savingAllMoviePrints // if so change its status from gettingThumbs to readyForPrinting if (this.state.savingAllMoviePrints && this.state.sheetsToPrint.length > 0) { if ( this.state.sheetsToPrint.findIndex(item => item.fileId === fileId && item.status === 'gettingThumbs') > -1 ) { // log.debug(this.state.sheetsToPrint); // state should be immutable, therefor const sheetsToPrint = this.state.sheetsToPrint.map(item => { if (item.fileId !== fileId) { // This isn't the item we care about - keep it as-is return item; } // Otherwise, this is the one we want - return an updated value return { ...item, status: 'readyForPrinting', }; }); // log.debug(sheetsToPrint); this.setState({ sheetsToPrint, }); } } // update artificial sceneArray if interval scene if (getSheetType(sheetsByFileId, fileId, sheetId, settings) === SHEET_TYPE.INTERVAL) { const sceneArray = createSceneArray(sheetsByFileId, fileId, sheetId); dispatch(updateSceneArray(fileId, sheetId, sceneArray)); } }); ipcRenderer.on('clearScenes', (event, fileId, sheetId) => { dispatch(clearScenes(fileId, sheetId)); }); ipcRenderer.on('received-get-file-scan', (event, fileId, filePath, useRatio, sheetId) => { const { files } = this.props; const { requestIdleCallbackForScenesHandle } = this.state; const file = getFile(files, fileId); // cancel pullScenesFromOpencvWorker window.cancelIdleCallback(requestIdleCallbackForScenesHandle); this.setState({ requestIdleCallbackForScenesHandle: undefined, }); log.debug('now I cancelIdleCallbackForScenes'); this.setState({ fileScanRunning: false, }); dispatch(updateFileScanStatus(fileId, true)); this.runSceneDetection(fileId, filePath, useRatio, undefined, sheetId, file.transformObject); }); ipcRenderer.on('receive-some-scenes-from-sceneQueue', (event, someScenes) => { const { requestIdleCallbackForScenesHandle } = this.state; // log.debug(someScenes); if (someScenes.length > 0) { // add scenes in reveres as they are stored inverse in the queue dispatch(addScenesWithoutCapturingThumbs(someScenes.reverse())); } // schedule the next one until scan is done and requestIdleCallback is cancelled if (requestIdleCallbackForScenesHandle !== undefined) { const newRequestIdleCallbackHandle = window.requestIdleCallback(this.pullScenesFromOpencvWorker); this.setState({ requestIdleCallbackForScenesHandle: newRequestIdleCallbackHandle, }); log.debug('now I requestIdleCallbackForScenes'); } else { log.debug('requestIdleCallback already cancelled. no new requestIdleCallbackForScenes will be started.'); } }); ipcRenderer.on( 'receive-find-face', (event, fileId, sheetId, parentSheetId, frameNumber, faceIdOfOrigin, foundFrames) => { const { files, sheetsByFileId } = this.props; const { sheetsToUpdate } = this.state; console.log(foundFrames); const theFile = getFile(files, fileId); const frameNumberArray = foundFrames.map(frame => frame.frameNumber); const faceIdArray = getFaceIdArrayFromThumbs(foundFrames); // get thumbs dispatch(addNewThumbsWithOrder(theFile, sheetId, frameNumberArray, settings.defaultCachedFramesSize)); sheetsToUpdate.push({ fileId, sheetId, status: 'addFaceData', payload: { faceScanArray: foundFrames, sortMethod: SORT_METHOD.DISTTOORIGIN, optionalSortProperties: { faceIdOfOrigin, }, }, }); const parentSheetName = getSheetName(sheetsByFileId, fileId, parentSheetId); dispatch(updateSheetName(fileId, sheetId, `${parentSheetName} face in ${pad(frameNumber, 4)}`)); // set name on file // dispatch(updateSheetCounter(fileId)); dispatch(updateSheetType(fileId, sheetId, SHEET_TYPE.FACES)); // set filter this.onUpdateSheetFilter( { [FILTER_METHOD.FACEID]: { enabled: true, faceIdOfOrigin, frameNumberOfOrigin: frameNumber, faceIdArray, }, }, fileId, sheetId, ); // update columnCount this.optimiseGridLayout(fileId, sheetId, frameNumberArray.length); dispatch(updateSheetParent(fileId, sheetId, parentSheetId)); dispatch(updateSheetView(fileId, sheetId, SHEET_VIEW.GRIDVIEW)); dispatch(setCurrentSheetId(sheetId)); }, ); ipcRenderer.on('start-requestIdleCallback-for-sceneQueue', event => { const { requestIdleCallbackForScenesHandle } = this.state; // start requestIdleCallback until it is cancelled if (requestIdleCallbackForScenesHandle === undefined) { const newRequestIdleCallbackHandle = window.requestIdleCallback(this.pullScenesFromOpencvWorker); this.setState({ requestIdleCallbackForScenesHandle: newRequestIdleCallbackHandle, }); log.debug('now I requestIdleCallbackForScenes'); } else { log.debug('requestIdleCallbackForScenes already running. no new requestIdleCallbackForScenes will be started.'); } }); ipcRenderer.on('received-saved-file', (event, id, path, isSingleThumb = false) => { const { settings } = this.props; const { defaultOpenFileExplorerAfterSaving } = settings; // ignore when saved file event was triggered from saving a single thumb if (!isSingleThumb) { if (this.state.savingMoviePrint) { setTimeout(this.setState({ savingMoviePrint: false }), 1000); // adding timeout to prevent clicking multiple times // open file explorer if checked if (defaultOpenFileExplorerAfterSaving) { this.onOpenFileExplorer(path); } } else if (this.state.savingAllMoviePrints) { // check if the sheet which was saved has been printing, then set status to done if (this.state.sheetsToPrint.findIndex(item => item.status === 'printing') > -1) { // state should be immutable, therefor const sheetsToPrint = this.state.sheetsToPrint.map(item => { if (item.status !== 'printing') { // This isn't the item we care about - keep it as-is return item; } // Otherwise, this is the one we want - return an updated value return { ...item, status: 'done', }; }); log.debug(sheetsToPrint); this.setState({ sheetsToPrint, }); // check if all files have been printed, then set savingAllMoviePrints to false if ( this.state.sheetsToPrint.filter(item => item.status === 'done').length === this.state.sheetsToPrint.filter(item => item.status !== 'undefined').length ) { this.setState({ savingAllMoviePrints: false }); // open file explorer if checked if (defaultOpenFileExplorerAfterSaving) { this.onOpenFileExplorer(path); } } } } } log.debug(`Saved file: ${path}`); }); ipcRenderer.on('received-saved-file-error', (event, message) => { this.showMessage(message, 5000, 'error'); setTimeout(this.setState({ savingMoviePrint: false }), 1000); // adding timeout to prevent clicking multiple times log.error(`Saved file error: ${message}`); }); ipcRenderer.on('send-zoom-level', (event, value) => { this.onChangeDefaultZoomLevel(value); }); document.addEventListener('keydown', this.handleKeyPress); document.addEventListener('keyup', this.handleKeyUp); this.updatecontainerWidthAndHeight(); window.addEventListener('resize', this.updatecontainerWidthAndHeight); log.debug('App.js reports: componentDidMount'); log.debug(`Operating system: ${process.platform}-${os.release()}`); log.debug(`App version: ${app.getName()}-${app.getVersion()}`); log.debug(`Chromium version: ${process.versions.chrome}`); // check if all movies exist // if not then mark them with fileMissingStatus if (files.length > 0) { files.map(item => { if (doesFileFolderExist(item.path) === false) { console.log(item.path); dispatch(updateFileMissingStatus(item.id, true)); } }); } // load opencvVideo for scrub and playerView if (getObjectProperty(() => file.path)) { try { this.setState({ opencvVideo: new opencv.VideoCapture(file.path), }); } catch (e) { log.error(e); } } // get objecturls from all frames in imagedb ipcRenderer.send('message-from-mainWindow-to-databaseWorkerWindow', 'get-arrayOfObjectUrls'); } componentDidUpdate(prevProps, prevState) { // log.debug('App.js componentDidUpdate'); const { dispatch } = this.props; const { filesToLoad, sheetsToPrint, sheetsToUpdate } = this.state; const { files, file, settings, sheetsByFileId, visibilitySettings } = this.props; const { defaultMoviePrintWidth, defaultPaperAspectRatioInv, defaultEmbedFilePath, defaultEmbedFrameNumbers, } = settings; const { visibilityFilter } = visibilitySettings; if (filesToLoad.length !== 0 && prevState.filesToLoad.length !== filesToLoad.length) { ipcRenderer.send( 'message-from-mainWindow-to-opencvWorkerWindow', 'send-get-file-details', filesToLoad[0].id, filesToLoad[0].path, filesToLoad[0].posterFrameId, ); } // check if all files have been initially loaded (have gotten file details like frameCount) console.log(filesToLoad); if (filesToLoad.length === 0) { // run if there was a change in the sheetsToPrint array if (sheetsToPrint.length !== 0) { const filesToUpdateStatus = []; // run if there is a sheet which needsThumbs, but not if there is one already gettingThumbs if ( sheetsToPrint.findIndex(item => item.status === 'gettingThumbs') === -1 && sheetsToPrint.findIndex(item => item.status === 'needsThumbs') > -1 ) { // log.debug(sheetsToPrint); const sheetToGetThumbsFor = sheetsToPrint.find(item => item.status === 'needsThumbs'); // log.debug(sheetToGetThumbsFor); const tempFile = getFile(files, sheetToGetThumbsFor.fileId); // log.debug(tempFile); // check if file could be found within files to cover the following case // files who could be added to the filelist, but then could not be read by opencv get removed again from the FileList if (tempFile !== undefined) { this.getThumbsForFile(sheetToGetThumbsFor.fileId, sheetToGetThumbsFor.sheetId); dispatch( updateSheetName( sheetToGetThumbsFor.fileId, sheetToGetThumbsFor.sheetId, getNewSheetName(getSheetCount(files, sheetToGetThumbsFor.fileId)), ), ); dispatch(updateSheetCounter(sheetToGetThumbsFor.fileId)); dispatch(updateSheetType(sheetToGetThumbsFor.fileId, sheetToGetThumbsFor.sheetId, SHEET_TYPE.INTERVAL)); dispatch(updateSheetView(sheetToGetThumbsFor.fileId, sheetToGetThumbsFor.sheetId, SHEET_VIEW.GRIDVIEW)); filesToUpdateStatus.push({ fileId: sheetToGetThumbsFor.fileId, sheetId: sheetToGetThumbsFor.sheetId, status: 'gettingThumbs', }); } else { // status of file which could not be found gets set to undefined filesToUpdateStatus.push({ fileId: sheetToGetThumbsFor.fileId, sheetId: sheetToGetThumbsFor.sheetId, status: 'undefined', }); } // log.debug(filesToUpdateStatus); } // run if there is a file readyForPrinting, but not if there is one already printing if ( sheetsToPrint.findIndex(item => item.status === 'printing') === -1 && sheetsToPrint.findIndex(item => item.status === 'readyForPrinting') > -1 ) { // log.debug(sheetsToPrint); const sheetToPrint = sheetsToPrint.find(item => item.status === 'readyForPrinting'); // get sheet to print const sheet = getSheet(sheetsByFileId, sheetToPrint.fileId, sheetToPrint.sheetId); // define what sheetView to print depending on type const { sheetView } = sheet; // get file to print const tempFile = getFile(files, sheetToPrint.fileId); // get scenes to print let tempScenes; if ( sheetView === SHEET_VIEW.TIMELINEVIEW && sheetsByFileId[sheetToPrint.fileId] !== undefined && sheetsByFileId[sheetToPrint.fileId][sheetToPrint.sheetId] !== undefined ) { tempScenes = getVisibleThumbs( sheetsByFileId[sheetToPrint.fileId][sheetToPrint.sheetId].sceneArray, visibilitySettings.visibilityFilter, ); } const secondsPerRow = getSecondsPerRow(sheetsByFileId, sheetToPrint.fileId, sheetToPrint.sheetId, settings); const scaleValueObject = getScaleValueObject( tempFile, settings, visibilitySettings, getColumnCount(sheetsByFileId, sheetToPrint.fileId, sheetToPrint.sheetId, settings), file.thumbCount, defaultMoviePrintWidth, sheetView === SHEET_VIEW.TIMELINEVIEW ? defaultMoviePrintWidth * defaultPaperAspectRatioInv : undefined, 1, undefined, true, tempScenes, secondsPerRow, ); // console.log(scaleValueObject); const dataToEmbed = prepareDataToExportOrEmbed( tempFile, sheet, visibilitySettings, defaultEmbedFilePath, defaultEmbedFrameNumbers, ); const dataToSend = { elementId: sheetView !== SHEET_VIEW.TIMELINEVIEW ? 'ThumbGrid' : 'SceneGrid', file: tempFile, sheetId: sheetToPrint.sheetId, moviePrintWidth: defaultMoviePrintWidth, settings, sheet, visibilityFilter, scaleValueObject, scenes: tempScenes, secondsPerRow, dataToEmbed, }; filesToUpdateStatus.push({ fileId: sheetToPrint.fileId, sheetId: sheetToPrint.sheetId, status: 'printing', }); // console.log(filesToUpdateStatus); // console.log(dataToSend); ipcRenderer.send('message-from-mainWindow-to-workerWindow', 'action-save-MoviePrint', dataToSend); } // only update sheetsToPrint if there is any update if (filesToUpdateStatus.length !== 0) { const newSheetsToPrint = sheetsToPrint.map(el => { const found = filesToUpdateStatus.find(s => s.sheetId === el.sheetId); if (found) { return Object.assign(el, found); } return el; }); this.setState({ sheetsToPrint: newSheetsToPrint, }); } } } // run if there was a change in the sheetsToUpdate array if (sheetsToUpdate.length !== 0) { const copyOfSheetsToUpdate = sheetsToUpdate.slice(); // read the first item const { fileId: myFileId, sheetId: mySheetId, status: myStatus, payload: myPayload } = copyOfSheetsToUpdate[0]; const thumbCount = getThumbsCount( sheetsByFileId, myFileId, mySheetId, settings, visibilitySettings.visibilityFilter, true, ); if (thumbCount !== 0) { if (myStatus === 'addFaceData') { this.addFaceData(myFileId, mySheetId, myPayload); // remove the first item copyOfSheetsToUpdate.shift(); this.setState({ sheetsToUpdate: copyOfSheetsToUpdate, }); } } } // updatecontainerWidthAndHeight checks if the containerWidth or height has changed // and if so calls updateScaleValue this.updatecontainerWidthAndHeight(); // update scaleValue when these parameters change if ( (prevProps.file === undefined || this.props.file === undefined ? false : prevProps.file.width !== this.props.file.width) || (prevProps.file === undefined || this.props.file === undefined ? false : prevProps.file.height !== this.props.file.height) || prevProps.settings.defaultThumbnailScale !== this.props.settings.defaultThumbnailScale || prevProps.settings.defaultMoviePrintWidth !== this.props.settings.defaultMoviePrintWidth || prevProps.settings.defaultMarginRatio !== this.props.settings.defaultMarginRatio || prevProps.settings.defaultTimelineViewSecondsPerRow !== this.props.settings.defaultTimelineViewSecondsPerRow || prevProps.settings.defaultTimelineViewMinDisplaySceneLengthInFrames !== this.props.settings.defaultTimelineViewMinDisplaySceneLengthInFrames || prevProps.settings.defaultTimelineViewWidthScale !== this.props.settings.defaultTimelineViewWidthScale || (prevProps.scenes ? prevProps.scenes.length !== this.props.scenes.length : false) || prevProps.settings.defaultShowHeader !== this.props.settings.defaultShowHeader || prevProps.settings.defaultShowPathInHeader !== this.props.settings.defaultShowPathInHeader || prevProps.settings.defaultShowDetailsInHeader !== this.props.settings.defaultShowDetailsInHeader || prevProps.settings.defaultShowTimelineInHeader !== this.props.settings.defaultShowTimelineInHeader || prevProps.settings.defaultRoundedCorners !== this.props.settings.defaultRoundedCorners || prevProps.settings.defaultShowPaperPreview !== this.props.settings.defaultShowPaperPreview || prevProps.settings.defaultPaperAspectRatioInv !== this.props.settings.defaultPaperAspectRatioInv || prevProps.visibilitySettings.defaultView !== this.props.visibilitySettings.defaultView || prevProps.visibilitySettings.defaultSheetView !== this.props.visibilitySettings.defaultSheetView || prevProps.visibilitySettings.defaultZoomLevel !== this.props.visibilitySettings.defaultZoomLevel || prevState.secondsPerRowTemp !== this.state.secondsPerRowTemp || prevState.columnCountTemp !== this.state.columnCountTemp || prevState.thumbCountTemp !== this.state.thumbCountTemp || prevState.columnCount !== this.state.columnCount || prevState.thumbCount !== this.state.thumbCount ) { this.updateScaleValue(); } // replace all frames for this fileId -> fileIdToBeRecaptured if ( this.state.fileIdToBeRecaptured !== undefined && prevState.fileIdToBeRecaptured !== this.state.fileIdToBeRecaptured ) { ipcRenderer.send( 'message-from-mainWindow-to-opencvWorkerWindow', 'recapture-frames', files, sheetsByFileId, settings.defaultCachedFramesSize, this.state.fileIdToBeRecaptured, ); this.setState({ fileIdToBeRecaptured: undefined, }); } // capture all frames for this fileId -> fileIdToBeCaptured if (this.state.fileIdToBeCaptured !== undefined && prevState.fileIdToBeCaptured !== this.state.fileIdToBeCaptured) { ipcRenderer.send( 'message-from-mainWindow-to-opencvWorkerWindow', 'recapture-frames', files, sheetsByFileId, settings.defaultCachedFramesSize, this.state.fileIdToBeCaptured, false, // onlyReplace ); this.setState({ fileIdToBeCaptured: undefined, }); } } componentWillUnmount() { const { dispatch } = this.props; document.removeEventListener('keydown', this.handleKeyPress); document.removeEventListener('keyup', this.handleKeyUp); window.removeEventListener('resize', this.updatecontainerWidthAndHeight); // close the database connection moviePrintDB.close(err => { if (err) { log.error(err.message); return console.error(err.message); } console.log('Close the database connection.'); log.debug('Close the database connection.'); }); } handleKeyPress(event) { // you may also add a filter here to skip keys, that do not have an effect for your app // this.props.keyPressAction(event.keyCode); // only listen to key events when feedback form is not shown if (!this.state.showFeedbackForm && event.target.tagName !== 'INPUT') { const { dispatch } = this.props; const { currentFileId, currentSheetId, currentSheetType, file, settings, sheetsByFileId, visibilitySettings, } = this.props; if (event) { switch (event.which) { case 32: // press 'space bar' if (visibilitySettings.defaultView === VIEW.PLAYERVIEW && currentSheetType === SHEET_TYPE.SCENES) { this.setOrToggleDefaultSheetView(); } break; case 49: // press 1 this.toggleMovielist(); break; case 50: // press 2 if (visibilitySettings.defaultView === VIEW.STANDARDVIEW) { this.onSetViewClick(VIEW.PLAYERVIEW); } else { this.onSetViewClick(VIEW.STANDARDVIEW); } break; case 51: // press 3 if (visibilitySettings.showSettings) { this.onCancelClick(); } else { this.showSettings(); } break; case 52: // press '4' break; case 53: // press '5' break; case 54: // press '6' break; case 55: // press '7' break; case 56: // press '8' break; case 65: // press 'a' this.openMoviesDialog(); break; case 67: // press 'c' - Careful!!! might also be triggered when doing reset application Shift+Alt+Command+C // this.recaptureAllFrames(); break; case 68: // press 'd' break; case 69: // press 'e' break; case 70: // press 'f' if (currentFileId) { this.onToggleDetectionChart(); } break; case 71: // press 'g' this.toggleSheetView(currentFileId, currentSheetId); break; case 77: // press 'm' this.onSaveMoviePrint(); break; case 80: // press 'p' break; case 81: // press 'q' // // display toast and set toastId to fileId // toast(({ closeToast }) => ( // <div> // This is a test toast // <Button // compact // floated='right' // content='Cancel' // onClick={() => { // closeToast(); // }} // /> // </div> // ), { // className: `${stylesPop.toast} ${stylesPop.toastInfo}`, // hideProgressBar: false, // autoClose: 100000, // closeButton: false, // closeOnClick: false, // }); break; case 83: // press 's' break; default: } this.setState({ keyObject: { shiftKey: event.shiftKey, altKey: event.altKey, ctrlKey: event.ctrlKey, metaKey: event.metaKey, which: event.which, }, }); } } } async onFinishedGettingFaces(fileId, sheetId, detectionArray, faceSortMethod, updateSheet = false) { const { sheetsToUpdate } = this.state; const { dispatch, files, settings, sheetsByFileId, visibilitySettings } = this.props; console.log(detectionArray); console.log(faceSortMethod); console.log(sheetId); const file = getFile(files, fileId); let thumbCount = getThumbsCount( sheetsByFileId, fileId, sheetId, settings, visibilitySettings.visibilityFilter, true, ); console.log(thumbCount); this.setState({ fileScanRunning: false, }); if (detectionArray.length === 0 && thumbCount === 0) { // dispatch(deleteSheets(fileId, sheetId)); log.info('No faces detected!'); toast('No faces detected!', { className: `${stylesPop.toast}`, autoClose: 10000, closeButton: true, closeOnClick: true, }); } else { // add new thumbs // only addThumbs if there are new thumbs and if the sheet should not just be updated if (detectionArray.length !== 0 && !updateSheet) { const frameNumberArrayFromFaceDetection = detectionArray .filter(item => item.faceCount !== 0) .map(item => item.frameNumber); await dispatch(addThumbs(file, sheetId, frameNumberArrayFromFaceDetection)); // update thumbCount thumbCount += frameNumberArrayFromFaceDetection.length; console.log(thumbCount); } const faceScanArray = this.getFaceData(fileId, sheetId); sheetsToUpdate.push({ fileId, sheetId, status: 'addFaceData', payload: { faceScanArray, sortMethod: faceSortMethod, }, }); this.optimiseGridLayout(fileId, sheetId, thumbCount); } } optimiseGridLayout(fileId = undefined, sheetId = undefined, thumbCountOverride = undefined) { const { currentFileId, currentSheetId, dispatch, settings, sheetsByFileId, visibilitySettings } = this.props; const noDefault = true; const theFileId = fileId || currentFileId; const theSheetId = sheetId || currentSheetId; const thumbCount = thumbCountOverride || getThumbsCount(sheetsByFileId, theFileId, theSheetId, settings, visibilitySettings.visibilityFilter, noDefault); const newSheetColumnCount = Math.ceil(Math.sqrt(Math.max(1, thumbCount))); // updateSheetColumnCount dispatch(updateSheetColumnCount(theFileId, theSheetId, newSheetColumnCount)); this.setState({ columnCountTemp: newSheetColumnCount }); } /* eslint class-methods-use-this: off */ showMessage(message, time, status = 'info', toastId = undefined) { toast(message, { className: `${stylesPop.toast} ${status === 'info' ? stylesPop.toastInfo : ''} ${ status === 'error' ? stylesPop.toastError : '' } ${status === 'success' ? stylesPop.toastSuccess : ''}`, autoClose: time, toastId, closeOnClick: status !== 'error', }); } /* eslint class-methods-use-this: off */ updateMessage(message, time, status = 'info', toastId) { toast.update(toastId, { render: message, className: `${stylesPop.toast} ${status === 'info' ? stylesPop.toastInfo : ''} ${ status === 'error' ? stylesPop.toastError : '' } ${status === 'success' ? stylesPop.toastSuccess : ''}`, autoClose: time, closeOnClick: status !== 'error', }); } recaptureAllFrames() { const { files, settings, sheetsByFileId } = this.props; // clear objectUrlObjects this.setState({ objectUrlObjects: {}, }); ipcRenderer.send( 'message-from-mainWindow-to-opencvWorkerWindow', 'recapture-frames', files, sheetsByFileId, settings.defaultCachedFramesSize, ); } handleKeyUp(event) { if (event) { this.setState({ keyObject: { shiftKey: false, altKey: false, ctrlKey: false, metaKey: false, which: undefined, }, }); } } onDragEnter() { this.setState({ dropzoneActive: true, }); } onDragLeave() { this.setState({ dropzoneActive: false, }); } onDrop(droppedFiles) { const { dispatch, files } = this.props; // when user presses alt key on drop then clear list and add movies const clearList = this.state.keyObject.altKey; this.setState({ dropzoneActive: false, loadingFirstFile: true, }); log.debug('Files where dropped'); log.debug(droppedFiles); // file match needs to be in sync with addMoviesToList() and accept !!! if (Array.from(droppedFiles).some(file => file.type.match('video.*') || file.name.match(/.divx|.mkv|.ogg|.VOB/i))) { dispatch(setDefaultSheetView(SHEET_VIEW.GRIDVIEW)); dispatch(addMoviesToList(droppedFiles, clearList)) .then(response => { // add a property to first movie indicating that it should be displayed when ready response[0].displayMe = true; // add newly dropped files to filesToLoad this.setState(state => { const addedToFilesToLoad = [...state.filesToLoad, ...response]; return { filesToLoad: addedToFilesToLoad, }; }); if (clearList) { this.setState({ objectUrlObjects: {}, // clear objectUrlObjects }); } log.debug(response); // showMovielist if more than one movie if (response.length > 1 || (!clearList && files !== undefined && files.length > 0)) { dispatch(showMovielist()); } return response; }) .catch(error => { log.error(error); }); } return false; } checkForUpdates() { // check for updates this.setState({ isCheckingForUpdates: true, }); let latestVersion = null; const { platform } = process; axios .get(URL_REST_API_CHECK_FOR_UPDATES, { timeout: 30000, }) .then(response => { log.debug(response.data.acf); if (platform === 'darwin') { latestVersion = response.data.acf.mac_version_number; } else if (platform === 'win32') { latestVersion = response.data.acf.windows_version_number; } const thisVersion = app.getVersion(); const updateAvailable = compareVersions(latestVersion, thisVersion); log.debug( `this version: ${thisVersion}, latest version: ${latestVersion}, update available: ${updateAvailable}`, ); if (updateAvailable > 0) { toast( ({ closeToast }) => ( <div> An update is available: {latestVersion} <br /> Your version is: {thisVersion} <br /> <br /> <Button compact fluid content="See what's new" onClick={() => { shell.openExternal(URL_CHANGE_LOG); closeToast(); }} /> </div> ), { className: `${stylesPop.toast} ${stylesPop.toastSuccess}`, autoClose: false, }, ); } else { this.showMessage(`Your version is up to date: ${thisVersion}`, 3000, 'info'); } this.setState({ isCheckingForUpdates: undefined, }); return undefined; }) .catch(error => { this.showMessage( `There has been an error while checking for updates: ${error}`, 3000, 'error', ); log.error(error); this.setState({ isCheckingForUpdates: undefined, }); }); } applyMimeTypes(event) { this.setState({ accept: event.target.value, }); } updateScaleValue(optionalNewAspectRatioInv = undefined) { const { columnCountTemp, thumbCountTemp, containerWidth, containerHeight } = this.state; const { currentFileId, currentSheetId, currentSecondsPerRow, file, scenes, settings, sheetsByFileId, visibilitySettings, } = this.props; const { defaultZoomLevel = ZOOM_SCALE } = visibilitySettings; // log.debug(`inside updateScaleValue and containerWidth: ${this.state.containerWidth}`); const scaleValueObject = getScaleValueObject( file, settings, visibilitySettings, columnCountTemp, thumbCountTemp, containerWidth, containerHeight, SCALE_VALUE_ARRAY[defaultZoomLevel], settings.defaultShowPaperPreview, undefined, scenes, currentSecondsPerRow, optionalNewAspectRatioInv, ); this.setState({ scaleValueObject, }); } updatecontainerWidthAndHeight() { // wrapped in try catch as in a global error case this.siteContent ref is not set try { // set default values for clientWidth and clientHeight // as on start up this.siteContent ref is not set yet const { clientWidth = WINDOW_WIDTH, clientHeight = WINDOW_HEIGHT } = this.siteContent; const { file, visibilitySettings } = this.props; const { containerHeight, containerWidth } = this.state; const containerWidthInner = clientWidth - (visibilitySettings.showMovielist ? 350 : 0) - (visibilitySettings.showSettings ? 350 : 0) - (file ? 0 : 300); // for startup const containerHeightInner = clientHeight - (file ? 0 : 100); // for startup if ( Math.abs(containerHeight - containerHeightInner) > 10 || Math.abs(containerWidth - containerWidthInner) > 10 ) { log.debug(`new container size: ${containerWidthInner}x${containerHeightInner}`); this.setState( { containerHeight: containerHeightInner, containerWidth: containerWidthInner, }, () => this.updateScaleValue(), ); } return true; } catch (e) { log.error(e); return undefined; } } onDeselectThumbMethod() { this.setState({ selectedThumbsArray: [], }); } onSelectThumbMethod(thumbId, frameNumber = undefined) { this.setState({ selectedThumbsArray: [ { thumbId, }, ], jumpToFrameNumber: frameNumber, }); } showMovielist() { const { dispatch } = this.props; dispatch(showMovielist()); } hideMovielist() { const { dispatch } = this.props; dispatch(hideMovielist()); } toggleMovielist() { if (this.props.visibilitySettings.showMovielist) { this.hideMovielist(); } else { this.showMovielist(); } } showSettings() { const { dispatch } = this.props; const { currentFileId, currentSheetId, currentSecondsPerRow, file, settings, sheetsByFileId, visibilitySettings, } = this.props; dispatch(showSettings()); const sheetProperties = returnSheetProperties( getColumnCount(sheetsByFileId, currentFileId, currentSheetId, settings), getThumbsCount(sheetsByFileId, currentFileId, currentSheetId, settings, visibilitySettings.visibilityFilter), currentSecondsPerRow, ); this.setState(sheetProperties); } hideSettings() { const { dispatch } = this.props; dispatch(hideSettings()); this.onHideDetectionChart(); } toggleSettings() { if (this.props.visibilitySettings.showSettings) { this.hideSettings(); } else { this.showSettings(); } } onShowAllThumbs() { const { currentFileId, currentSheetId, dispatch, settings, sheetsByFileId } = this.props; dispatch(showAllThumbs(currentFileId, currentSheetId)); const noDefault = true; const thumbCount = getThumbsCount( sheetsByFileId, currentFileId, currentSheetId, settings, THUMB_SELECTION.ALL_THUMBS, noDefault, ); console.log(thumbCount); this.optimiseGridLayout(currentFileId, currentSheetId, thumbCount); } onHideDetectionChart() { this.setState({ showChart: false, }); } onToggleDetectionChart() { this.setState({ showChart: !this.state.showChart, }); } onSortSheet(sortMethod, filterRange = undefined, fileId = undefined, sheetId = undefined) { const { currentFileId, currentSheetId, dispatch, settings, sheetsByFileId, visibilitySettings } = this.props; const { visibilityFilter } = visibilitySettings; const theFilterRange = filterRange || visibilityFilter; const theFileId = fileId || currentFileId; const theSheetId = sheetId || currentSheetId; const { thumbsArray } = sheetsByFileId[theFileId][theSheetId]; const sheetType = getSheetType(sheetsByFileId, theFileId, theSheetId, settings); const isFaceType = sheetType === SHEET_TYPE.FACES; if (sortMethod !== SORT_METHOD.REVERSE) { const baseArray = getVisibleThumbs(thumbsArray, theFilterRange); // get sortOrderArray const sortOrderArray = sortArray(baseArray, sortMethod); // console.log(sortOrderArray); // sort thumbs array const sortedThumbsArray = sortThumbsArray(thumbsArray, sortOrderArray); // update the thumb order dispatch(updateOrder(theFileId, theSheetId, sortedThumbsArray)); // hide other thumbs as filtering could happen const frameNumberArray = sortOrderArray.map(item => item.frameNumber); dispatch(showThumbsByFrameNumberArray(theFileId, theSheetId, frameNumberArray)); // change column count for optimisation this.optimiseGridLayout(currentFileId, currentSheetId, frameNumberArray.length); // add detection information to thumbs if (isFaceType) { deleteFaceDescriptorFromFaceScanArray(baseArray); dispatch(changeAndSortThumbArray(theFileId, theSheetId, baseArray, sortMethod)); } } else { // for reverse take all thumbs not just visible ones const baseArray = thumbsArray; // reverse thumbsArray const sortedThumbsArray = baseArray.slice().reverse(); // update the thumb order dispatch(updateOrder(theFileId, theSheetId, sortedThumbsArray)); // if show all, then unhide all thumbs if (theFilterRange === THUMB_SELECTION.ALL_THUMBS) { this.onShowAllThumbs(); // const frameNumberArray = baseArray.map(item => item.frameNumber); // dispatch(showThumbsByFrameNumberArray(theFileId, theSheetId, frameNumberArray)); } } } onFilterSheet(filters, fileId = undefined, sheetId = undefined, faceUniquenessThreshold = undefined) { const { currentFileId, currentSheetId, dispatch, settings, sheetsByFileId, visibilitySettings } = this.props; const { defaultFaceUniquenessThreshold } = settings; const { visibilityFilter } = visibilitySettings; const theFileId = fileId || currentFileId; const theSheetId = sheetId || currentSheetId; const { thumbsArray } = sheetsByFileId[theFileId][theSheetId]; const sheetType = getSheetType(sheetsByFileId, theFileId, theSheetId, settings); const isFaceType = sheetType === SHEET_TYPE.FACES; if (isFaceType) { const theFaceUniquenessThreshold = faceUniquenessThreshold || defaultFaceUniquenessThreshold; let baseArray = thumbsArray; let thumbsFrameNumbers; // for an expanded face sheet only get face scan data of these thumbs if (filters[FILTER_METHOD.FACEID] !== undefined) { thumbsFrameNumbers = thumbsArray.map(thumb => thumb.frameNumber); } // for all others get all face scan data baseArray = getFaceScanByFileId(theFileId, thumbsFrameNumbers); // faceGroupNumber and occurrence is not necessary for expanded face sheet if (filters[FILTER_METHOD.FACEID] === undefined) { const baseArrayWithFaceGroupNumber = determineAndInsertFaceGroupNumber(baseArray, theFaceUniquenessThreshold); insertFaceOccurrence(baseArrayWithFaceGroupNumber); baseArray = baseArrayWithFaceGroupNumber; // console.log(baseArray); } // get sortOrderArray const sortOrderArray = filterArray(baseArray, filters); // console.log(sortOrderArray); // sort thumbs array const sortedThumbsArray = sortThumbsArray(thumbsArray, sortOrderArray); // update the thumb order dispatch(updateOrder(theFileId, theSheetId, sortedThumbsArray)); // add updated faceArray info to thumbs dispatch(changeThumbArray(theFileId, theSheetId, sortOrderArray)); // change column count for optimisation const visibleThumbsCount = getThumbsCountOfArray(sortOrderArray, visibilityFilter); this.optimiseGridLayout(currentFileId, currentSheetId, visibleThumbsCount); } } onUpdateSheetFilter = (filter, fileId = undefined, sheetId = undefined, overwrite = true) => { const { currentFileId, currentSheetId, currentSheetFilter, dispatch, sheetsByFileId } = this.props; const theFileId = fileId || currentFileId; const theSheetId = sheetId || currentSheetId; let previousFilter = currentSheetFilter; let newFilter; if (overwrite) { // if update is false, the previousFilter will be ignored newFilter = filter; } else { // load specific previousFilter if fileId and sheetId are provided if (fileId !== undefined && sheetId !== undefined) { previousFilter = getSheetFilter(sheetsByFileId, fileId, sheetId); } newFilter = { ...previousFilter, ...filter, }; } dispatch(updateSheetFilter(theFileId, theSheetId, newFilter)); }; getFaceData(fileId, sheetId) { const { settings, sheetsByFileId, visibilitySettings } = this.props; const { defaultFaceUniquenessThreshold } = settings; const arrayOfFrameNumbers = getFramenumbersOfSheet(sheetsByFileId, fileId, sheetId, visibilitySettings); // console.log(arrayOfFrameNumbers); const faceScanArray = getFaceScanByFileId(fileId, arrayOfFrameNumbers); // calculate occurrences const faceScanArrayWithFaceGroupNumber = determineAndInsertFaceGroupNumber( faceScanArray, defaultFaceUniquenessThreshold, ); insertFaceOccurrence(faceScanArrayWithFaceGroupNumber); deleteFaceDescriptorFromFaceScanArray(faceScanArrayWithFaceGroupNumber); return faceScanArrayWithFaceGroupNumber; } addFaceData(fileId, sheetId, payload) { const { dispatch } = this.props; const { faceScanArray, sortMethod = undefined, optionalSortProperties = undefined } = payload; console.log(faceScanArray); // add detection information to thumbs dispatch(changeAndSortThumbArray(fileId, sheetId, faceScanArray, sortMethod, optionalSortProperties)); // this.onSortSheet(fileId, sheetId, sortMethod); } pullObjectUrlFromdatabaseWorkerWindow(deadline) { // it pulls objectUrls from worker_database objectUrlQueue during idle time log.debug('now I am not busy - requestIdleCallbackForObjectUrl'); ipcRenderer.send( 'message-from-mainWindow-to-databaseWorkerWindow', 'get-some-objectUrls-from-objectUrlQueue', 100, // amount ); } runSceneDetection( fileId, filePath, useRatio, threshold = this.props.settings.defaultSceneDetectionThreshold, sheetId = uuidV4(), transformObject = TRANSFORMOBJECT_INIT, ) { const { dispatch } = this.props; const { settings } = this.props; const { defaultShotDetectionMethod = SHOT_DETECTION_METHOD.MEAN } = settings; const { fileScanRunning } = this.state; const timeBeforeGetFrameScanByFileId = Date.now(); const arrayOfFrameScanData = getFrameScanByFileId(fileId); const timeAfterGetFrameScanByFileId = Date.now(); log.debug(`getFrameScanByFileId duration: ${timeAfterGetFrameScanByFileId - timeBeforeGetFrameScanByFileId}`); // only start creating a sheet if there is already scanned data or // there is no fileScanRunning if (arrayOfFrameScanData.length !== 0 || fileScanRunning === false) { this.onHideDetectionChart(); dispatch(setDefaultSheetView(SHEET_VIEW.TIMELINEVIEW)); dispatch(setCurrentSheetId(sheetId)); dispatch(updateSheetType(fileId, sheetId, SHEET_TYPE.SCENES)); dispatch(updateSheetView(fileId, sheetId, SHEET_VIEW.TIMELINEVIEW)); // get meanArray if it is stored else return false // console.log(arrayOfFrameScanData); // if meanArray not stored, runFileScan if (arrayOfFrameScanData.length === 0) { this.setState({ fileScanRunning: true }); // display toast and set toastId to fileId toast( ({ closeToast }) => ( <div> Shot detection in progress <Button compact floated="right" content="Cancel" onClick={() => { this.cancelFileScan(fileId, sheetId); closeToast(); }} /> </div> ), { toastId: fileId, className: `${stylesPop.toast} ${stylesPop.toastInfo}`, hideProgressBar: false, autoClose: false, closeButton: false, closeOnClick: false, }, ); ipcRenderer.send( 'message-from-mainWindow-to-opencvWorkerWindow', 'send-get-file-scan', fileId, filePath, useRatio, threshold, sheetId, transformObject || TRANSFORMOBJECT_INIT, // need INIT value as undefined is translated to null via IPC defaultShotDetectionMethod, ); } else { // console.log(meanColorArray); this.calculateSceneList(fileId, arrayOfFrameScanData, threshold, sheetId); } } else { this.showMessage('Sorry, only one shot detection at a time.', 3000, 'error'); } return true; } pullScenesFromOpencvWorker(deadline) { // this is used to show a scene detection preview // it pulls scenes from worker_opencv sceneQueue during idle time log.debug('now I am not busy - requestIdleCallbackForScenes'); ipcRenderer.send( 'message-from-mainWindow-to-opencvWorkerWindow', 'get-some-scenes-from-sceneQueue', 10, // amount ); } calculateSceneList( fileId, arrayOfFrameScanData, threshold = this.props.settings.defaultSceneDetectionThreshold, sheetId, ) { const { dispatch } = this.props; const { files, settings } = this.props; // check if frameScanData is complete const frameCount = getFrameCount(files, fileId); const frameScanDataLength = getFrameScanCount(fileId); console.log(getFrameScanCount(fileId)); if (frameScanDataLength / frameCount < 0.9) { // consider less than 90% as incomplete // frameScanData is not complete // arrayOfFrameScanData will be repaired in place log.error(`frameScanData is not complete: ${frameCount}:${frameScanDataLength}`); repairFrameScanData(arrayOfFrameScanData, frameCount); } const differenceValueArray = arrayOfFrameScanData.map(frame => frame.differenceValue); const meanColorArray = arrayOfFrameScanData.map(frame => JSON.parse(frame.meanColor)); // calculate threshold with kmeans // convert differenceValueArray into histogram const matFromArray = new opencv.Mat([differenceValueArray], opencv.CV_8UC1); const vHist = opencv .calcHist(matFromArray, [ { channel: 0, bins: 256, ranges: [0, 256], }, ]) .convertTo(opencv.CV_32F); // convert histogram to array of points const histAsArray = vHist.getDataAsArray(); const points2 = histAsArray.map(([x], index) => new opencv.Point(index, x)); // run kmeans const { labels: kmeansLabels, centers } = opencv.kmeans( points2, 3, // k new opencv.TermCriteria(opencv.termCriteria.EPS || opencv.termCriteria.MAX_ITER, 10, 0.1), // termCriteria 5, // attempts opencv.KMEANS_RANDOM_CENTERS, // flags ); // get mainCenter const centersYArray = centers.map(center => center.y); // get index of max value const mainCenterIndex = centersYArray.indexOf(Math.max(...centersYArray)); // double to get boundary + 1 to compensate for starting with 0 const calcThreshold = Math.round(centers[mainCenterIndex].x) * 2 + 1; console.log(calcThreshold); const sceneList = calculateSceneListFromDifferenceArray(fileId, differenceValueArray, meanColorArray, threshold); console.log(sceneList.map(shot => shot.start)); const labels = [...Array(differenceValueArray.length).keys()].map(x => String(x)); const thresholdLine = [ { x: String(0), y: String(threshold), }, { x: String(differenceValueArray.length - 1), y: String(threshold), }, ]; const calcThresholdLine = [ { x: String(0), y: String(calcThreshold), }, { x: String(differenceValueArray.length - 1), y: String(calcThreshold), }, ]; const newChartData = { labels, datasets: [ { label: 'Difference', backgroundColor: 'rgb(255, 80, 6)', pointRadius: 2, data: differenceValueArray, }, { label: 'Threshold', borderColor: 'rgba(255, 0, 0, 1)', borderWidth: 1, pointRadius: 0, data: thresholdLine, }, { label: 'Calculated Threshold', borderColor: 'rgba(0, 255, 0, 1)', borderWidth: 1, pointRadius: 0, data: calcThresholdLine, }, ], }; this.setState({ chartData: newChartData, }); // dispatch(clearScenes(fileId, sheetId)); // check if scenes detected if (sceneList.length !== 0) { const tempFile = getFile(files, fileId); const clearOldScenes = true; dispatch(updateSheetType(tempFile.id, sheetId, SHEET_TYPE.SCENES)); dispatch(updateSheetView(tempFile.id, sheetId, SHEET_VIEW.TIMELINEVIEW)); dispatch(updateSheetName(tempFile.id, sheetId, getNewSheetName(getSheetCount(files, tempFile.id)))); dispatch(updateSheetCounter(tempFile.id)); dispatch(setCurrentSheetId(sheetId)); this.optimiseGridLayout(tempFile.id, sheetId, sceneList.length); dispatch(setDefaultSheetView(SHEET_VIEW.TIMELINEVIEW)); console.log(sceneList); dispatch(addScenesFromSceneList(tempFile, sceneList, clearOldScenes, settings.defaultCachedFramesSize, sheetId)); } else { this.showMessage('No scenes detected', 3000); } } cancelFileScan(fileId, sheetId = undefined) { const { currentSheetId, dispatch, sheetsByFileId } = this.props; const { requestIdleCallbackForScenesHandle } = this.state; log.error(`Cancel file scan for: ${fileId}`); // cancel pullScenesFromOpencvWorker window.cancelIdleCallback(requestIdleCallbackForScenesHandle); this.setState({ requestIdleCallbackForScenesHandle: undefined, }); log.debug('now I cancelIdleCallback'); ipcRenderer.send('message-from-mainWindow-to-opencvWorkerWindow', 'cancelFileScan', fileId); this.setState({ fileScanRunning: false, }); toast.update(fileId, { className: `${stylesPop.toast} ${stylesPop.toastError}`, // hideProgressBar: false, render: 'Detection was cancelled !', autoClose: 3000, closeButton: true, closeOnClick: true, }); // if there was a sheet in progress, delete it again if (sheetId !== undefined) { dispatch(deleteSheets(fileId, sheetId)); // if the currentSheet is deleted then switch to the first sheet of the file if (currentSheetId === sheetId) { const newSheetId = getSheetId(sheetsByFileId, fileId); dispatch(setCurrentSheetId(newSheetId)); } } } onScrubClick(file, scrubThumb, scrubWindowTriggerTime) { const { dispatch } = this.props; const { allScenes, thumbs } = this.props; dispatch(hideMovielist()); dispatch(hideSettings()); let scrubScene; if (allScenes !== undefined) { scrubScene = allScenes.find(scene => scene.sceneId === scrubThumb.thumbId); } const { thumbLeft: scrubThumbLeft, thumbRight: scrubThumbRight } = getLeftAndRightThumb(thumbs, scrubThumb.thumbId); this.setState({ showScrubWindow: true, scrubWindowTriggerTime, scrubThumb, scrubScene, scrubThumbLeft, scrubThumbRight, }); } onScrubReturn(scrubFrameNumber = undefined) { const { dispatch, file, settings, thumbs } = this.props; const { keyObject, scrubThumb, sheetType } = this.state; console.log(scrubFrameNumber); if (scrubFrameNumber !== undefined) { if (sheetType === SHEET_TYPE.SCENES) { this.onChangeThumb( file, settings.currentSheetId, scrubThumb.thumbId, scrubFrameNumber, settings.defaultCachedFramesSize, ); } else if (keyObject.altKey || keyObject.shiftKey) { const newThumbId = uuidV4(); if (keyObject.altKey) { dispatch( addThumb( file, settings.currentSheetId, scrubFrameNumber, thumbs.find(thumb => thumb.thumbId === scrubThumb.thumbId).index + 1, newThumbId, settings.defaultCachedFramesSize, ), ); } else { // if shiftKey dispatch( addThumb( file, settings.currentSheetId, scrubFrameNumber, thumbs.find(thumb => thumb.thumbId === scrubThumb.thumbId).index, newThumbId, settings.defaultCachedFramesSize, ), ); } } else { // if normal set new thumb this.onChangeThumb( file, settings.currentSheetId, scrubThumb.thumbId, scrubFrameNumber, settings.defaultCachedFramesSize, ); } } this.setState({ showScrubWindow: false, scrubWindowTriggerTime: undefined, }); } onExpandClick(file, sceneOrThumbId, parentSheetId, sheetType = undefined) { const { dispatch } = this.props; const { files, scenes, sheetsArray, sheetsByFileId, settings } = this.props; const { defaultFaceUniquenessThreshold } = settings; const { sheetsToUpdate } = this.state; const { id: fileId } = file; // console.log(file); // console.log(sceneOrThumbId); // console.log(parentSheetId); // open movie list so user sees that a new sheet got added this.showMovielist(); // create scenesArray if it does not exist let sceneArray = scenes; if (sceneArray === undefined || sceneArray.length === 0) { sceneArray = createSceneArray(sheetsByFileId, fileId, parentSheetId); dispatch(updateSceneArray(fileId, parentSheetId, sceneArray)); } // console.log(sceneArray); // get sceneArray const sceneIndex = sceneArray.findIndex(item => item.sceneId === sceneOrThumbId); const sheetId = sceneOrThumbId; // console.log(sheetId); // create new sheet if it does not already exist if (sheetsArray.findIndex(item => item === sheetId) === -1) { // expand face type if (sheetType === SHEET_TYPE.FACES) { // get frameNumber const frameNumber = getFrameNumberWithSceneOrThumbId(sheetsByFileId, fileId, parentSheetId, sceneOrThumbId); console.log(frameNumber); ipcRenderer.send( 'message-from-mainWindow-to-databaseWorkerWindow', 'send-find-face', fileId, sheetId, parentSheetId, frameNumber, defaultFaceUniquenessThreshold, ); } else { const startFrame = sceneArray[sceneIndex].start; const endFrame = startFrame + sceneArray[sceneIndex].length - 1; let sheetName = `Sequence ${startFrame} - ${endFrame}`; if (sheetType === SHEET_TYPE.SCENES) { const shotNumber = getShotNumber(sceneOrThumbId, sheetsByFileId, fileId, parentSheetId); if (shotNumber !== undefined) { sheetName = `Shot #${shotNumber}`; } } dispatch( addIntervalSheet( file, sheetId, DEFAULT_THUMB_COUNT, // use constant value instead of defaultThumbCount startFrame, endFrame, settings.defaultCachedFramesSize, true, // limitToRange -> do not get more thumbs then between in and out available ), ); dispatch(updateSheetName(fileId, sheetId, sheetName)); // set name on file dispatch(updateSheetCounter(fileId)); dispatch(updateSheetType(fileId, sheetId, SHEET_TYPE.INTERVAL)); // update columnCount this.optimiseGridLayout(fileId, sheetId, DEFAULT_THUMB_COUNT); dispatch(updateSheetParent(fileId, sheetId, parentSheetId)); } } dispatch(updateSheetView(fileId, sheetId, SHEET_VIEW.GRIDVIEW)); dispatch(setCurrentSheetId(sheetId)); } onAddThumbClick(file, existingThumb, insertWhere) { const { dispatch } = this.props; // get thumb left and right of existingThumb const indexOfAllThumbs = this.props.allThumbs.findIndex(thumb => thumb.thumbId === existingThumb.thumbId); const indexOfVisibleThumbs = this.props.thumbs.findIndex(thumb => thumb.thumbId === existingThumb.thumbId); const existingThumbFrameNumber = existingThumb.frameNumber; const leftThumbFrameNumber = this.props.thumbs[Math.max(0, indexOfVisibleThumbs - 1)].frameNumber; const rightThumbFrameNumber = this.props.thumbs[Math.min(this.props.thumbs.length - 1, indexOfVisibleThumbs + 1)] .frameNumber; const newFrameNumberAfter = limitFrameNumberWithinMovieRange( file, existingThumbFrameNumber + Math.round((rightThumbFrameNumber - existingThumbFrameNumber) / 2), ); const newFrameNumberBefore = limitFrameNumberWithinMovieRange( file, leftThumbFrameNumber + Math.round((existingThumbFrameNumber - leftThumbFrameNumber) / 2), ); const newThumbId = uuidV4(); if (insertWhere === 'after') { dispatch( addThumb( this.props.file, this.props.settings.currentSheetId, newFrameNumberAfter, indexOfAllThumbs + 1, newThumbId, this.props.settings.defaultCachedFramesSize, ), ) .then(thumbId => { console.log(thumbId); this.onSelectThumbMethod(thumbId); // select new thumb return undefined; }) .catch(error => { log.error(`There has been a problem with addThumb operation: ${error.message}`); }); } else if (insertWhere === 'before') { // if shiftKey dispatch( addThumb( this.props.file, this.props.settings.currentSheetId, newFrameNumberBefore, indexOfAllThumbs, newThumbId, this.props.settings.defaultCachedFramesSize, ), ) .then(thumbId => { console.log(thumbId); this.onSelectThumbMethod(thumbId); // select new thumb return undefined; }) .catch(error => { log.error(`There has been a problem with addThumb operation: ${error.message}`); }); } } onJumpToCutThumbClick(file, thumbId, otherSceneIs) { const { currentSheetId } = this.props; this.onChangeSheetViewClick(file.id, currentSheetId, SHEET_VIEW.TIMELINEVIEW); this.onJumpToCutSceneClick(file, thumbId, otherSceneIs); } onJumpToCutSceneClick(file, thumbId, otherSceneIs) { const { dispatch } = this.props; const { allScenes, currentSheetId, sheetsByFileId, visibilitySettings } = this.props; dispatch(setView(VIEW.PLAYERVIEW)); // get all scenes let otherScene; let cutFrameNumber; const selectedThumbsArray = []; const clickedScene = allScenes.find(scene => scene.sceneId === thumbId); const indexOfVisibleScenes = allScenes.findIndex(scene => scene.sceneId === thumbId); // get scene before or after if (otherSceneIs === 'after') { // only set if before last scene if (indexOfVisibleScenes < allScenes.length - 1) { otherScene = allScenes[indexOfVisibleScenes + 1]; cutFrameNumber = otherScene.start; selectedThumbsArray.push({ thumbId: otherScene.sceneId, }); } } else if (otherSceneIs === 'before') { // only set if after first scene if (indexOfVisibleScenes > 0) { cutFrameNumber = clickedScene.start; selectedThumbsArray.push({ thumbId: clickedScene.sceneId, }); } } this.setState({ selectedThumbsArray, jumpToFrameNumber: cutFrameNumber, }); } onCutSceneClick(frameToCut) { const { dispatch } = this.props; const { allScenes, currentSheetId, file, thumbs } = this.props; const scene = getSceneFromFrameNumber(allScenes, frameToCut); // only cut if there isn't already a cut if (frameToCut !== scene.start) { dispatch(cutScene(thumbs, allScenes, file, currentSheetId, scene, frameToCut)); } else { const message = 'There is already a cut'; log.debug(message); this.showMessage(message, 3000); } } onMergeSceneClick(frameToCut) { const { dispatch } = this.props; const { allScenes, currentSheetId, file, thumbs } = this.props; const adjacentSceneIndicesArray = getAdjacentSceneIndicesFromCut(allScenes, frameToCut); // console.log(adjacentSceneIndicesArray); if (adjacentSceneIndicesArray.length === 2) { dispatch(mergeScenes(thumbs, allScenes, file, currentSheetId, adjacentSceneIndicesArray)); } const firstSceneId = allScenes[adjacentSceneIndicesArray[0]].sceneId; // console.log(firstSceneId); this.onSelectThumbMethod(firstSceneId); // select first scene } onChangeThumb(file, sheetId, thumbId, frameNumber, defaultCachedFramesSize) { const { dispatch } = this.props; dispatch(changeThumb(sheetId, file, thumbId, frameNumber, defaultCachedFramesSize)); } onAddThumb(file, sheetId, newThumbId, frameNumber, index, defaultCachedFramesSize) { const { dispatch } = this.props; dispatch(addThumb(file, sheetId, frameNumber, index, newThumbId, defaultCachedFramesSize)); } onViewToggle() { const { dispatch } = this.props; if (this.props.visibilitySettings.defaultView === VIEW.STANDARDVIEW) { this.hideSettings(); this.hideMovielist(); dispatch(setView(VIEW.PLAYERVIEW)); } else { dispatch(setView(VIEW.STANDARDVIEW)); } } onSaveMoviePrint() { const { currentFileId, currentSheetId, currentSecondsPerRow, currentSheetView, file, settings, scenes, sheetsByFileId, visibilitySettings, } = this.props; const { defaultMoviePrintWidth, defaultPaperAspectRatioInv, defaultEmbedFilePath, defaultEmbedFrameNumbers, } = settings; const { visibilityFilter } = visibilitySettings; const sheet = sheetsByFileId[file.id][currentSheetId]; const scaleValueObject = getScaleValueObject( file, settings, visibilitySettings, getColumnCount(sheetsByFileId, file.id, currentSheetId, settings), file.thumbCount, defaultMoviePrintWidth, currentSheetView === SHEET_VIEW.TIMELINEVIEW ? defaultMoviePrintWidth * defaultPaperAspectRatioInv : undefined, 1, undefined, true, currentSheetView !== SHEET_VIEW.TIMELINEVIEW ? undefined : scenes, currentSecondsPerRow, ); const dataToEmbed = prepareDataToExportOrEmbed( file, sheet, visibilitySettings, defaultEmbedFilePath, defaultEmbedFrameNumbers, ); const dataToSend = { // scale: 1, elementId: currentSheetView !== SHEET_VIEW.TIMELINEVIEW ? 'ThumbGrid' : 'SceneGrid', file, sheetId: currentSheetId, moviePrintWidth: defaultMoviePrintWidth, settings, sheet, visibilityFilter, scaleValueObject, scenes: currentSheetView !== SHEET_VIEW.TIMELINEVIEW ? undefined : scenes, currentSecondsPerRow, dataToEmbed, }; // log.debug(dataToSend); this.setState( { savingMoviePrint: true }, ipcRenderer.send('message-from-mainWindow-to-workerWindow', 'action-save-MoviePrint', dataToSend), ); } onSaveAllMoviePrints() { log.debug('inside onSaveAllMoviePrints'); const { files, sheetsByFileId } = this.props; const tempFileIds = files.map(file => file.id); const tempSheetObjects = []; files.map(file => { const fileId = file.id; const sheetIdArray = getSheetIdArray(sheetsByFileId, fileId); if (sheetIdArray !== undefined) { sheetIdArray.map(sheetId => { tempSheetObjects.push({ fileId, sheetId, }); return undefined; }); } else { // if there are no sheets yet, add a new sheetId which tempSheetObjects.push({ fileId, sheetId: uuidV4(), }); } return undefined; }); log.debug(tempFileIds); log.debug(tempSheetObjects); const sheetsToPrint = []; tempSheetObjects.forEach(sheet => { if ( sheetsByFileId[sheet.fileId] === undefined || sheetsByFileId[sheet.fileId][sheet.sheetId] === undefined || sheetsByFileId[sheet.fileId][sheet.sheetId].thumbsArray === undefined ) { // if no thumbs were found then initiate to getThumbsForFile sheetsToPrint.push({ fileId: sheet.fileId, sheetId: sheet.sheetId, status: 'needsThumbs', }); } else { // if thumbs were found then go directly to sheetsToPrint sheetsToPrint.push({ fileId: sheet.fileId, sheetId: sheet.sheetId, status: 'readyForPrinting', }); } }); this.setState({ sheetsToPrint, savingAllMoviePrints: true, }); } onAddIntervalSheet(sheetsByFileId, fileId, settings, thumbCount = undefined, columnCount = undefined) { const { dispatch } = this.props; const { files } = this.props; const newSheetId = uuidV4(); // set columnCount as it is not defined yet this.getThumbsForFile(fileId, newSheetId, thumbCount); const newColumnCount = columnCount || getColumnCount(sheetsByFileId, fileId, newSheetId, settings); dispatch(updateSheetColumnCount(fileId, newSheetId, newColumnCount)); dispatch(updateSheetName(fileId, newSheetId, getNewSheetName(getSheetCount(files, fileId)))); dispatch(updateSheetCounter(fileId)); dispatch(updateSheetType(fileId, newSheetId, SHEET_TYPE.INTERVAL)); dispatch(updateSheetView(fileId, newSheetId, SHEET_VIEW.GRIDVIEW)); return newSheetId; } onAddIntervalSheetClick(fileId = undefined, thumbCount = undefined, columnCount = undefined) { // log.debug(`FileListElement clicked: ${file.name}`); const { dispatch } = this.props; const { currentFileId, sheetsByFileId, settings, visibilitySettings } = this.props; // if fileId is undefined then use currentFileId const theFileId = fileId || currentFileId; dispatch(setCurrentFileId(theFileId)); const newSheetId = this.onAddIntervalSheet(sheetsByFileId, theFileId, settings, thumbCount, columnCount); const sheetView = getSheetView(sheetsByFileId, theFileId, newSheetId, visibilitySettings); this.onSetSheetClick(theFileId, newSheetId, sheetView); } async onAddFaceSheetClick(scanRange = 'scanBetweenInAndOut', scanResolution = undefined) { // log.debug(`FileListElement clicked: ${file.name}`); const { currentFileId, currentSheetId, dispatch, file, files, sheetsByFileId, settings, visibilitySettings, } = this.props; const { defaultFaceConfidenceThreshold, defaultFaceSizeThreshold, defaultFaceUniquenessThreshold } = settings; console.log(currentFileId); console.log(file); const { frameCount, path: filePath, useRatio, transformObject } = file; const updateSheet = false; const sheetId = uuidV4(); const faceSortMethod = SORT_METHOD.FACESIZE; let frameNumberArray; switch (scanRange) { case 'scanFramesOfSheet': // updateSheet = true; // sheetId = currentSheetId; frameNumberArray = getVisibleThumbs( sheetsByFileId[currentFileId] === undefined ? undefined : sheetsByFileId[currentFileId][currentSheetId].thumbsArray, visibilitySettings.visibilityFilter, ).map(thumb => thumb.frameNumber); break; case 'scanBetweenInAndOut': /* eslint no-case-declarations: "off" */ const lowestFrame = getLowestFrame( getVisibleThumbs( sheetsByFileId[currentFileId] === undefined ? undefined : sheetsByFileId[currentFileId][currentSheetId].thumbsArray, visibilitySettings.visibilityFilter, ), ); const highestFrame = getHighestFrame( getVisibleThumbs( sheetsByFileId[currentFileId] === undefined ? undefined : sheetsByFileId[currentFileId][currentSheetId].thumbsArray, visibilitySettings.visibilityFilter, ), ); const frameCountOfSelection = Math.abs(highestFrame - lowestFrame); console.log(`${lowestFrame} | ${highestFrame} | ${frameCountOfSelection}`); frameNumberArray = getIntervalArray( Math.round(Math.max(1, frameCountOfSelection * scanResolution)), // at least 1 lowestFrame, highestFrame, frameCount, ); break; case 'scanWholeMovie': frameNumberArray = getIntervalArray(Math.round(frameCount * scanResolution), 0, frameCount, frameCount); break; default: } if (!updateSheet) { // create sheet const sheetCount = getSheetCount(files, currentFileId); const newSheetName = getNewSheetName(sheetCount); dispatch(updateSheetName(currentFileId, sheetId, newSheetName)); dispatch(updateSheetCounter(currentFileId)); dispatch(updateSheetType(currentFileId, sheetId, SHEET_TYPE.FACES)); dispatch(updateSheetView(currentFileId, sheetId, SHEET_VIEW.GRIDVIEW)); dispatch(setCurrentSheetId(sheetId)); } // filter the frameNumberArray to only include frames which do not have face scan data // console.log(frameNumberArray); // these frames are already scanned const faceScanArray = getFaceScanByFileId(currentFileId, frameNumberArray); // console.log(faceScanArray); const extractedFrameNumbers = faceScanArray.map(item => item.frameNumber); // console.log(extractedFrameNumbers); // these frames need to be scanned const frameArrayToScan = frameNumberArray.filter(item => !extractedFrameNumbers.includes(item)); // console.log(frameArrayToScan); // these frames are already scanned and have faces const extractedFrameNumbersWithFaces = faceScanArray .filter(item => item.faceCount !== 0) .map(item => item.frameNumber); // console.log(extractedFrameNumbersWithFaces); if (extractedFrameNumbersWithFaces.length !== 0 && !updateSheet) { // add thumbs which already have face scan data await dispatch(addThumbs(file, sheetId, extractedFrameNumbersWithFaces)); } if (frameArrayToScan.length !== 0) { this.setState({ fileScanRunning: true }); // display toast and set toastId to fileId toast( ({ closeToast }) => ( <div> Face detection in progress <Button compact floated="right" content="Cancel" onClick={() => { this.cancelFileScan(currentFileId, sheetId); closeToast(); }} /> </div> ), { toastId: currentFileId, className: `${stylesPop.toast} ${stylesPop.toastInfo}`, hideProgressBar: false, autoClose: false, closeButton: false, closeOnClick: false, }, ); ipcRenderer.send( 'message-from-mainWindow-to-opencvWorkerWindow', 'send-get-faces', currentFileId, filePath, sheetId, frameArrayToScan, useRatio, settings.defaultCachedFramesSize, transformObject || TRANSFORMOBJECT_INIT, // need INIT value as undefined is translated to null via IPC defaultFaceConfidenceThreshold, defaultFaceSizeThreshold, defaultFaceUniquenessThreshold, faceSortMethod, updateSheet, ); } else { // no frames to scan, jump directly to finished getting faces this.onFinishedGettingFaces(currentFileId, sheetId, frameArrayToScan, faceSortMethod, updateSheet); } } onFileListElementClick(fileId) { // log.debug(`FileListElement clicked: ${file.name}`); const { dispatch } = this.props; const { sheetsByFileId, settings, visibilitySettings } = this.props; dispatch(setCurrentFileId(fileId)); let newSheetId = getSheetId(sheetsByFileId, fileId); // When clicking on a filelist element for the first time if (newSheetId === undefined) { newSheetId = this.onAddIntervalSheet(sheetsByFileId, fileId, settings); } const sheetView = getSheetView(sheetsByFileId, fileId, newSheetId, visibilitySettings); // console.log(sheetView); this.onSetSheetClick(fileId, newSheetId, sheetView); } onBackToParentClick() { const { currentFileId, currentSheetId, sheetsByFileId, visibilitySettings } = this.props; const parentSheetId = getParentSheetId(sheetsByFileId, currentFileId, currentSheetId); const isParentSheet = doesSheetExist(sheetsByFileId, currentFileId, parentSheetId); if (isParentSheet) { const sheetView = getSheetView(sheetsByFileId, currentFileId, parentSheetId, visibilitySettings); this.onSetSheetClick(currentFileId, parentSheetId, sheetView); } else { toast('The parent MoviePrint does not exist anymore', { className: `${stylesPop.toast} ${stylesPop.toastError}`, autoClose: 3000, closeButton: true, closeOnClick: true, }); } } onErrorPosterFrame(file) { const { dispatch } = this.props; // dispatch(updateThumbObjectUrlFromDB(file.id, undefined, undefined, file.posterFrameId, true)); } getThumbsForFile(fileId, newSheetId = uuidV4(), thumbCount = this.props.settings.defaultThumbCount) { log.debug(`inside getThumbsForFileId: ${fileId}`); const { dispatch } = this.props; const { files, sheetsByFileId, settings } = this.props; const file = getFile(files, fileId); if ( sheetsByFileId[fileId] === undefined || sheetsByFileId[fileId][newSheetId] === undefined || sheetsByFileId[fileId][newSheetId].thumbsArray === undefined ) { log.debug(`addIntervalSheet as no thumbs were found for: ${file.name}`); dispatch( addIntervalSheet( file, newSheetId, thumbCount, file.fadeInPoint, file.fadeOutPoint, settings.defaultCachedFramesSize, ), ).catch(error => { log.error(error); }); } } openMoviesDialog() { log.debug('inside openMoviesDialog'); // console.log(this); // console.log(this.dropzoneRef); this.dropzoneRef.current.open(); } onOpenFeedbackForm() { log.debug('onOpenFeedbackForm'); this.setState({ showFeedbackForm: true, feedbackFormIsLoading: true, }); } onCloseFeedbackForm() { log.debug('onCloseFeedbackForm'); this.setState({ showFeedbackForm: false }); } onChangeRow = value => { this.setState({ thumbCountTemp: this.state.columnCountTemp * value }); this.updateScaleValue(); }; onChangeColumn = value => { const { dispatch } = this.props; const tempRowCount = Math.ceil(this.state.thumbCountTemp / this.state.columnCountTemp); this.setState({ columnCountTemp: value }); if (this.state.reCapture) { this.setState({ thumbCountTemp: tempRowCount * value }); } if (this.props.file !== undefined) { dispatch(updateSheetColumnCount(this.props.file.id, this.props.currentSheetId, value)); dispatch(setDefaultColumnCount(value)); } this.updateScaleValue(); }; onChangeColumnAndApply = value => { const { dispatch } = this.props; this.setState({ columnCountTemp: value, columnCount: value, }); if (this.props.file !== undefined) { dispatch(updateSheetColumnCount(this.props.file.id, this.props.currentSheetId, value)); dispatch(setDefaultColumnCount(value)); } this.updateScaleValue(); }; onToggleFaceRectClick = value => { const { dispatch } = this.props; if (value === undefined) { const { settings } = this.props; const { defaultShowFaceRect } = settings; dispatch(setDefaultShowFaceRect(!defaultShowFaceRect)); } else { dispatch(setDefaultShowFaceRect(value)); } }; onChangeShowFaceRectClick = checked => { const { dispatch } = this.props; dispatch(setDefaultShowFaceRect(checked)); }; onShowPaperPreviewClick = checked => { const { dispatch } = this.props; dispatch(setDefaultShowPaperPreview(checked)); }; onOutputPathFromMovieClick = checked => { const { dispatch } = this.props; dispatch(setDefaultOutputPathFromMovie(checked)); }; onPaperAspectRatioClick = value => { const { dispatch } = this.props; dispatch(setDefaultPaperAspectRatioInv(value)); }; onDetectInOutPointClick = value => { const { dispatch } = this.props; dispatch(setDefaultDetectInOutPoint(value)); }; onReCaptureClick = checked => { // log.debug(`${this.state.columnCount} : ${this.state.columnCountTemp} || ${this.state.thumbCount} : ${this.state.thumbCountTemp}`); if (!checked) { this.setState({ thumbCountTemp: this.state.thumbCount }); } else { const newThumbCount = this.state.columnCountTemp * Math.ceil(this.state.thumbCountTemp / this.state.columnCountTemp); this.setState({ thumbCountTemp: newThumbCount }); } this.setState({ reCapture: checked }); }; onApplyNewGridClick = () => { const { dispatch } = this.props; // log.debug(`${this.state.columnCount} : ${this.state.columnCountTemp} || ${this.state.thumbCount} : ${this.state.thumbCountTemp}`); this.setState({ columnCount: this.state.columnCountTemp }); if (this.state.reCapture) { this.setState({ thumbCount: this.state.thumbCountTemp }); this.onThumbCountChange(this.state.columnCountTemp, this.state.thumbCountTemp); } if (this.props.file !== undefined) { dispatch(updateSheetColumnCount(this.props.file.id, this.props.currentSheetId, this.state.columnCountTemp)); } // this.hideSettings(); }; onCancelClick = () => { // log.debug(this.state.columnCount); // log.debug(this.state.thumbCount); this.setState({ columnCountTemp: this.state.columnCount }); this.setState({ thumbCountTemp: this.state.thumbCount }); this.hideSettings(); }; onThumbCountChange = (columnCount, thumbCount) => { const { dispatch } = this.props; dispatch(setDefaultColumnCount(columnCount)); dispatch(setDefaultThumbCount(thumbCount)); if (this.props.currentFileId !== undefined) { dispatch( addIntervalSheet( this.props.file, this.props.settings.currentSheetId, thumbCount, getLowestFrame( getVisibleThumbs( this.props.sheetsByFileId[this.props.currentFileId] === undefined ? undefined : this.props.sheetsByFileId[this.props.currentFileId][this.props.settings.currentSheetId].thumbsArray, this.props.visibilitySettings.visibilityFilter, ), ), getHighestFrame( getVisibleThumbs( this.props.sheetsByFileId[this.props.currentFileId] === undefined ? undefined : this.props.sheetsByFileId[this.props.currentFileId][this.props.settings.currentSheetId].thumbsArray, this.props.visibilitySettings.visibilityFilter, ), ), this.props.settings.defaultCachedFramesSize, ), ); } }; onChangeMinDisplaySceneLength = value => { const { dispatch } = this.props; dispatch(setDefaultTimelineViewMinDisplaySceneLengthInFrames(Math.round(value * this.props.file.fps))); }; onChangeMargin = value => { const { dispatch, settings } = this.props; dispatch(setDefaultMarginRatio(value / settings.defaultMarginSliderFactor)); }; onChangeOutputJpgQuality = value => { const { dispatch } = this.props; dispatch(setDefaultOutputJpgQuality(value)); }; onChangeThumbJpgQuality = value => { const { dispatch } = this.props; dispatch(setDefaultThumbJpgQuality(value)); }; onChangeFaceSizeThreshold = value => { const { dispatch } = this.props; dispatch(setDefaultFaceSizeThreshold(value)); }; onChangeFaceConfidenceThreshold = value => { const { dispatch } = this.props; dispatch(setDefaultFaceConfidenceThreshold(value)); }; onChangeFaceUniquenessThreshold = value => { const { dispatch } = this.props; dispatch(setDefaultFaceUniquenessThreshold(value)); }; onChangeDefaultZoomLevel = value => { const { dispatch, visibilitySettings } = this.props; const { defaultZoomLevel = ZOOM_SCALE } = visibilitySettings; let zoomLevel = defaultZoomLevel; switch (value) { case 'resetZoom': zoomLevel = 4; break; case 'zoomIn': zoomLevel += 1; break; case 'zoomOut': zoomLevel -= 1; break; default: if (typeof value === 'number') { zoomLevel = value; } } // make sure that it doesn't exceed the arrays limits const limitedZoomLevel = limitRange(zoomLevel, 0, SCALE_VALUE_ARRAY.length - 1); dispatch(setZoomLevel(limitedZoomLevel)); }; onChangeFrameinfoScale = value => { const { dispatch } = this.props; dispatch(setDefaultFrameinfoScale(value)); }; onChangeFrameinfoMargin = value => { const { dispatch } = this.props; dispatch(setDefaultFrameinfoMargin(value)); }; onChangeSceneDetectionThreshold = value => { const { dispatch } = this.props; dispatch(setDefaultSceneDetectionThreshold(value)); }; onChangeTimelineViewSecondsPerRow = value => { const { dispatch } = this.props; const { file, currentSheetId } = this.props; if (file !== undefined) { dispatch(updateSheetSecondsPerRow(file.id, currentSheetId, value)); } dispatch(setDefaultTimelineViewSecondsPerRow(value)); }; onChangeTimelineViewWidthScale = value => { const { dispatch } = this.props; dispatch(setDefaultTimelineViewWidthScale(value)); }; onTimelineViewFlowClick = value => { const { dispatch } = this.props; dispatch(setDefaultTimelineViewFlow(value)); }; onToggleHeaderClick = value => { const { dispatch } = this.props; if (value === undefined) { const { settings } = this.props; const { defaultShowHeader } = settings; dispatch(setDefaultShowHeader(!defaultShowHeader)); } else { dispatch(setDefaultShowHeader(value)); } }; onToggleImagesClick = value => { const { dispatch } = this.props; if (value === undefined) { const { settings } = this.props; const { defaultShowImages } = settings; dispatch(setDefaultShowImages(!defaultShowImages)); } else { dispatch(setDefaultShowImages(value)); } }; onShowPathInHeaderClick = value => { const { dispatch } = this.props; dispatch(setDefaultShowPathInHeader(value)); }; onShowDetailsInHeaderClick = value => { const { dispatch } = this.props; dispatch(setDefaultShowDetailsInHeader(value)); }; onShowTimelineInHeaderClick = value => { const { dispatch } = this.props; dispatch(setDefaultShowTimelineInHeader(value)); }; onRoundedCornersClick = value => { const { dispatch } = this.props; dispatch(setDefaultRoundedCorners(value)); }; onMoviePrintBackgroundColorClick = (colorLocation, color) => { const { dispatch } = this.props; switch (colorLocation) { case 'moviePrintBackgroundColor': dispatch(setDefaultMoviePrintBackgroundColor(color)); break; case 'frameninfoBackgroundColor': dispatch(setDefaultFrameinfoBackgroundColor(color)); break; case 'frameinfoColor': dispatch(setDefaultFrameinfoColor(color)); break; default: dispatch(setDefaultMoviePrintBackgroundColor(color)); } }; onToggleShowHiddenThumbsClick = () => { const { dispatch } = this.props; if (this.props.visibilitySettings.visibilityFilter === THUMB_SELECTION.ALL_THUMBS) { dispatch(setVisibilityFilter(THUMB_SELECTION.VISIBLE_THUMBS)); } else { dispatch(setVisibilityFilter(THUMB_SELECTION.ALL_THUMBS)); } }; onShowHiddenThumbsClick = value => { const { dispatch } = this.props; if (value) { dispatch(setVisibilityFilter(THUMB_SELECTION.ALL_THUMBS)); } else { dispatch(setVisibilityFilter(THUMB_SELECTION.VISIBLE_THUMBS)); } }; onThumbInfoClick = value => { const { dispatch } = this.props; dispatch(setDefaultThumbInfo(value)); }; onRemoveMovieListItem = fileId => { const { dispatch } = this.props; const { files } = this.props; if (files.length === 1) { dispatch(hideMovielist()); } dispatch(removeMovieListItem(fileId)); // dispatch(setCurrentSheetId(newSheetId)); }; onEditTransformListItemClick = fileId => { this.setState({ showTransformModal: true, fileIdToTransform: fileId, }); }; onChangeTransform = (fileId, transformObjectState) => { const { currentFileId, dispatch, files } = this.props; const { fileIdToTransform } = this.state; const { aspectRatioInv, cropTop, cropBottom, cropLeft, cropRight, rotationFlag } = transformObjectState; console.log(transformObjectState); const transformObjectBefore = getFileTransformObject(files, fileId); console.log(transformObjectBefore); const wasThereAChange = transformObjectBefore.rotationFlag !== rotationFlag || transformObjectBefore.cropTop !== cropTop || transformObjectBefore.cropBottom !== cropBottom || transformObjectBefore.cropLeft !== cropLeft || transformObjectBefore.cropRight !== cropRight; const wasThereAChangeInAspectRatio = transformObjectBefore.aspectRatioInv !== aspectRatioInv; console.log(wasThereAChange); console.log(wasThereAChangeInAspectRatio); if (wasThereAChange) { // always update rotation before cropping as this is the same order it is applied when capturing a thumb if (rotationFlag === RotateFlags.ROTATE_90_CLOCKWISE || rotationFlag === RotateFlags.ROTATE_90_COUNTERCLOCKWISE) { dispatch(rotateWidthAndHeight(fileId, true)); } else { dispatch(rotateWidthAndHeight(fileId, false)); } dispatch(updateCropping(fileId, rotationFlag, cropTop, cropBottom, cropLeft, cropRight, aspectRatioInv)); if (wasThereAChangeInAspectRatio && currentFileId === fileId) { // only update if currentFileId, else it will be updated next time when the user switches to this fileId this.updateScaleValue(aspectRatioInv); } } else if (wasThereAChangeInAspectRatio) { dispatch(updateAspectRatio(fileId, aspectRatioInv)); if (currentFileId === fileId) { // only update if currentFileId, else it will be updated next time when the user switches to this fileId this.updateScaleValue(aspectRatioInv); } } this.setState({ showTransformModal: false, fileIdToTransform: undefined, ...(wasThereAChange && { fileIdToBeRecaptured: fileIdToTransform }), }); }; onScanMovieListItemClick = fileId => { const { currentFileId, files } = this.props; // if fileId is undefined then use currentFileId const theFileId = fileId || currentFileId; const file = getFile(files, theFileId); this.runSceneDetection(theFileId, file.path, file.useRatio, undefined, undefined, file.transformObject); }; onReplaceMovieListItemClick = fileId => { const { dispatch } = this.props; const { files, settings, sheetsByFileId } = this.props; const file = getFile(files, fileId); const { path: originalFilePath, lastModified: lastModifiedOfPrevious } = file; const newPathArray = dialog.showOpenDialogSync({ title: 'Replace movie', defaultPath: originalFilePath, buttonLabel: 'Replace with', filters: [{ name: 'All Files', extensions: ['*'] }], properties: ['openFile'], }); const newFilePath = newPathArray !== undefined ? newPathArray[0] : undefined; if (newFilePath) { log.debug(newFilePath); const fileName = path.basename(newFilePath); const { lastModified, size } = getFileStatsObject(newFilePath); dispatch(replaceFileDetails(fileId, newFilePath, fileName, size, lastModified)); // change video for videoPlayer to the new one try { this.setState({ opencvVideo: new opencv.VideoCapture(newFilePath), }); } catch (e) { log.error(e); } // // change fileScanStatus // dispatch(updateFileScanStatus(fileId, false)); // // remove entries from frameScanList sqlite3 // deleteFileIdFromFrameScanList(fileId); dispatch(updateFileMissingStatus(fileId, false)); // use lastModified as indicator if the movie which will be replaced existed // if lastModified is undefined, then do not onlyReplace let onlyReplace = true; if (lastModifiedOfPrevious === undefined) { log.debug('lastModifiedOfPrevious is undefined'); onlyReplace = false; } ipcRenderer.send( 'message-from-mainWindow-to-opencvWorkerWindow', 'send-get-file-details', fileId, newFilePath, file.posterFrameId, onlyReplace, ); if (onlyReplace) { this.setState({ fileIdToBeRecaptured: fileId, }); } else { this.setState({ fileIdToBeCaptured: fileId, }); } } }; onDuplicateSheetClick = (fileId, sheetId) => { const { dispatch } = this.props; const { currentFileId, currentSheetId, files, settings, sheetsByFileId } = this.props; // if fileId and or sheetId are undefined then use currentFileId and or currentSheetId const theFileId = fileId || currentFileId; const theSheetId = sheetId || currentSheetId; const newSheetId = uuidV4(); dispatch(duplicateSheet(theFileId, theSheetId, newSheetId)); dispatch(updateSheetName(theFileId, newSheetId, getNewSheetName(getSheetCount(files, theFileId)))); // set name on firstFile dispatch(updateSheetCounter(theFileId)); dispatch(setCurrentSheetId(newSheetId)); // if interval scene then create artificial sceneArray if (getSheetType(sheetsByFileId, theFileId, theSheetId, settings) === SHEET_TYPE.INTERVAL) { const sceneArray = createSceneArray(sheetsByFileId, theFileId, newSheetId); dispatch(updateSceneArray(theFileId, newSheetId, sceneArray)); } }; onConvertToIntervalBasedClick = (fileId, sheetId) => { const { dispatch } = this.props; dispatch(updateSheetType(fileId, sheetId, SHEET_TYPE.INTERVAL)); }; onExportSheetClick = (fileId, sheetId, exportType, fps) => { const { files, settings, sheetsByFileId, visibilitySettings } = this.props; log.debug(`onExportSheetClick: ${exportType}`); const sheet = getSheet(sheetsByFileId, fileId, sheetId); const sheetName = getSheetName(sheetsByFileId, fileId, sheetId); const fileName = getFileName(files, fileId); const filePath = getFilePath(files, fileId); // not sure if that is needed so I deactivated it for now // const isDropFrame = (roundNumber(fps) === 29.97) || (roundNumber(fps) === 59.94); const isDropFrame = false; let exportObject; if (exportType === EXPORT_FORMAT_OPTIONS.JSON) { const file = getFile(files, fileId); const dataToExport = prepareDataToExportOrEmbed(file, sheet, visibilitySettings); exportObject = JSON.stringify(dataToExport, null, '\t'); // for pretty print with tab } else if (exportType === EXPORT_FORMAT_OPTIONS.EDL) { const sceneArray = getEDLscenes(sheetsByFileId, fileId, sheetId, visibilitySettings, fps); exportObject = sceneArray.join(` * FROM CLIP NAME: ${fileName} `); exportObject = `TITLE: ${fileName} FCM: ${isDropFrame ? 'DROP FRAME' : 'NON-DROP FRAME'} ${exportObject}`; } const filePathDirectory = path.dirname(filePath); const outputPath = settings.defaultOutputPathFromMovie ? filePathDirectory : settings.defaultOutputPath; const filePathAndName = path.join(outputPath, `${fileName}-${sheetName}.${exportType}`); const newFilePathAndName = dialog.showSaveDialogSync({ defaultPath: filePathAndName, buttonLabel: 'Export', showsTagField: false, }); if (newFilePathAndName !== undefined) { log.debug(exportObject); ipcRenderer.send('send-save-json-to-file', sheetId, newFilePathAndName, exportObject); } }; onImportMoviePrint = (filePath = undefined) => { const { dispatch } = this.props; const { files, settings } = this.props; log.debug('onImportMoviePrint'); let newPath = filePath; // skip dialog if filePath already available if (filePath === undefined) { const newPathArray = dialog.showOpenDialogSync({ filters: [{ name: 'PNG or JSON', extensions: ['png', 'json'] }], properties: ['openFile'], }); newPath = newPathArray !== undefined ? newPathArray[0] : undefined; } if (newPath) { log.debug(newPath); fs.readFile(newPath, (err, data) => { if (err) { return log.error(err); } const fileExtension = path.extname(newPath).toLowerCase(); let newFilePath; let transformObject; let columnCount; let frameNumberArray; let sceneArray; let dataAvailable = false; if (fileExtension === '.png') { const chunks = extract(data); const textChunks = chunks.filter(chunk => chunk.name === 'tEXt').map(chunk => text.decode(chunk.data)); log.debug(`The png file ${newPath} has the following data embedded:`); log.debug(textChunks); if (textChunks.length !== 0) { newFilePath = decodeURIComponent(textChunks.find(chunk => chunk.keyword === 'filePath').text); const transformObjectString = textChunks.find(chunk => chunk.keyword === 'transformObject').text; transformObject = transformObjectString !== 'undefined' ? JSON.parse(transformObjectString) : undefined; columnCount = Number(textChunks.find(chunk => chunk.keyword === 'columnCount').text); const frameNumberArrayString = textChunks.find(chunk => chunk.keyword === 'frameNumberArray').text; frameNumberArray = frameNumberArrayString !== 'undefined' ? JSON.parse(frameNumberArrayString) : undefined; const sceneArrayString = textChunks.find(chunk => chunk.keyword === 'sceneArray').text; sceneArray = sceneArrayString !== 'undefined' ? JSON.parse(sceneArrayString) : undefined; if ( (frameNumberArray !== undefined && frameNumberArray.length > 0) || (sceneArray !== undefined && sceneArray.length > 0) ) { dataAvailable = true; } } } else { const jsonData = JSON.parse(data); log.debug(`The json file ${newPath} has the following data:`); log.debug(jsonData); newFilePath = jsonData.filePath; transformObject = jsonData.transformObject; columnCount = Number(jsonData.columnCount); frameNumberArray = jsonData.frameNumberArray; sceneArray = jsonData.sceneArray; if ( newFilePath !== undefined && columnCount !== undefined && ((frameNumberArray !== undefined && frameNumberArray.length > 0) || (sceneArray !== undefined && sceneArray.length > 0)) ) { dataAvailable = true; } } if (dataAvailable) { this.showMessage('Data was found! Loading...', 3000, 'success'); const fileName = path.basename(newFilePath); const { lastModified, size } = getFileStatsObject(newFilePath) || {}; const fileId = uuidV4(); const posterFrameId = uuidV4(); const sheetId = uuidV4(); let transformObjectToAdd; if (transformObject !== undefined) { transformObjectToAdd = { // rotationFlag: transformObject.rotationFlag || RotateFlags.NO_ROTATION, rotationFlag: RotateFlags.NO_ROTATION, // ignoring rotationFlag for now as the capturing in the correct orientation is not yet solved cropTop: transformObject.cropTop || 0, cropBottom: transformObject.cropBottom || 0, cropLeft: transformObject.cropLeft || 0, cropRight: transformObject.cropRight || 0, aspectRatioInv: transformObject.aspectRatioInv || null, }; } const fileToAdd = { id: fileId, lastModified, name: fileName, path: newFilePath, size, fileMissingStatus: lastModified === undefined, // if lastModified is undefined than file missing posterFrameId, transformObject: transformObjectToAdd, }; dispatch({ type: 'ADD_MOVIE_LIST_ITEMS', payload: [fileToAdd], }); // sceneArray // colorArray: (3) [134, 134, 98] // fileId: "099371a6-5ec7-4a06-8c65-dd853b64df5e" // hidden: false // length: 430 // sceneId: "7cba705c-a003-48e4-8b1a-963e6bb9ad3b" // sheetId: "4f545281-815b-4ab2-b8bd-ae2377daabc1" // start: 0 // make interval sheet if frameNumberArray else shot based sheet if (frameNumberArray !== undefined) { dispatch(addNewThumbsWithOrder(fileToAdd, sheetId, frameNumberArray, settings.defaultCachedFramesSize)); dispatch(updateSheetType(fileId, sheetId, SHEET_TYPE.INTERVAL)); dispatch(updateSheetView(fileId, sheetId, SHEET_VIEW.GRIDVIEW)); } else { const clearOldScenes = true; dispatch( addScenesFromSceneList(fileToAdd, sceneArray, clearOldScenes, settings.defaultCachedFramesSize, sheetId), ); dispatch(updateSheetType(fileId, sheetId, SHEET_TYPE.SCENES)); dispatch(updateSheetView(fileId, sheetId, SHEET_VIEW.TIMELINEVIEW)); } dispatch(updateSheetName(fileId, sheetId, getNewSheetName(getSheetCount(files, fileId)))); // set name on file dispatch(updateSheetCounter(fileId)); dispatch(setCurrentSheetId(sheetId)); dispatch(updateSheetColumnCount(fileId, sheetId, columnCount)); dispatch(setCurrentFileId(fileId)); ipcRenderer.send( 'message-from-mainWindow-to-opencvWorkerWindow', 'send-get-file-details', fileId, newFilePath, posterFrameId, false, true, ); } else { this.showMessage('No fitting data found or embedded', 3000, 'error'); } }); } }; onOpenFileExplorer = (value = undefined) => { const { file, settings } = this.props; const { defaultOutputPath, defaultOutputPathFromMovie } = settings; // open default output path if undefined let path; let isFolder = false; if (value === undefined) { path = defaultOutputPathFromMovie ? file.path : defaultOutputPath; isFolder = !defaultOutputPathFromMovie; } else { path = value; } ipcRenderer.send('open-file-explorer', path, isFolder); }; onClearMovieList = () => { const { dispatch } = this.props; dispatch(setView(VIEW.STANDARDVIEW)); dispatch(clearMovieList()); dispatch(hideMovielist()); dispatch(hideSettings()); }; onDeleteSheetClick = (fileId, sheetId) => { const { dispatch } = this.props; const { currentSheetId, sheetsByFileId } = this.props; dispatch(deleteSheets(fileId, sheetId)); // if the currentSheet is deleted then switch to the first sheet of the file if (currentSheetId === sheetId) { const newSheetId = getSheetId(sheetsByFileId, fileId); dispatch(setCurrentSheetId(newSheetId)); } }; onSetSheetClick = (fileId, sheetId, sheetView) => { const { dispatch } = this.props; const { currentFileId } = this.props; if (fileId !== currentFileId) { dispatch(setCurrentFileId(fileId)); } dispatch(setCurrentSheetId(sheetId)); if (sheetView === SHEET_VIEW.TIMELINEVIEW) { this.onReCaptureClick(false); } dispatch(setDefaultSheetView(sheetView)); }; onSubmitMoviePrintNameClick = (fileId, sheetId, newName) => { const { dispatch } = this.props; dispatch(updateSheetName(fileId, sheetId, newName)); }; onChangeSheetViewClick = (fileId, sheetId, sheetView) => { const { dispatch } = this.props; const { currentFileId, currentSheetId, sheetsByFileId, settings } = this.props; // if fileId and or sheetId are undefined then use currentFileId and or currentSheetId const theFileId = fileId || currentFileId; const theSheetId = sheetId || currentSheetId; // if sheet type interval then create 'artificial' scene Array const sheetType = getSheetType(sheetsByFileId, theFileId, theSheetId, settings); if (sheetType === SHEET_TYPE.INTERVAL) { const sceneArray = createSceneArray(sheetsByFileId, theFileId, theSheetId); dispatch(updateSceneArray(theFileId, theSheetId, sceneArray)); } dispatch(updateSheetView(theFileId, theSheetId, sheetView)); if (sheetView === SHEET_VIEW.TIMELINEVIEW) { this.onReCaptureClick(false); } }; toggleSheetView = (fileId, sheetId) => { const { sheetsByFileId, visibilitySettings } = this.props; const sheetView = getSheetView(sheetsByFileId, fileId, sheetId, visibilitySettings); let newSheetView; if (sheetView === SHEET_VIEW.GRIDVIEW) { newSheetView = SHEET_VIEW.TIMELINEVIEW; } else { newSheetView = SHEET_VIEW.GRIDVIEW; } this.onChangeSheetViewClick(fileId, sheetId, newSheetView); }; setOrToggleDefaultSheetView = (sheetView = undefined) => { const { dispatch } = this.props; const { visibilitySettings } = this.props; let newSheetView = sheetView; if (newSheetView === undefined) { if (visibilitySettings.defaultSheetView === SHEET_VIEW.GRIDVIEW) { newSheetView = SHEET_VIEW.TIMELINEVIEW; } else if (visibilitySettings.defaultSheetView === SHEET_VIEW.TIMELINEVIEW) { newSheetView = SHEET_VIEW.GRIDVIEW; } } dispatch(setDefaultSheetView(newSheetView)); }; onSetViewClick = value => { const { dispatch } = this.props; const { currentFileId, currentSheetId, currentSheetType, scenes, sheetsByFileId, settings } = this.props; if (value === VIEW.PLAYERVIEW) { this.hideSettings(); this.hideMovielist(); } // change defaultSheetView to gridview for interval type as it should not have // a cut mode (timelineview) in playerview if (currentSheetType === SHEET_TYPE.INTERVAL) { dispatch(setDefaultSheetView(SHEET_VIEW.GRIDVIEW)); } // remove selection when switching back to standard view if (value === VIEW.STANDARDVIEW) { this.onDeselectThumbMethod(); } dispatch(setView(value)); }; onChangeDefaultMoviePrintName = value => { const { dispatch } = this.props; // log.debug(value); dispatch(setDefaultMoviePrintName(value)); }; onChangeDefaultSingleThumbName = value => { const { dispatch } = this.props; // log.debug(value); dispatch(setDefaultSingleThumbName(value)); }; onChangeDefaultAllThumbsName = value => { const { dispatch } = this.props; // log.debug(value); dispatch(setDefaultAllThumbsName(value)); }; onChangeOutputPathClick = () => { const { dispatch } = this.props; const newPathArray = dialog.showOpenDialogSync({ properties: ['openDirectory'], }); const newPath = newPathArray !== undefined ? newPathArray[0] : undefined; if (newPath) { // log.debug(newPath); dispatch(setDefaultOutputPath(newPath)); } }; onOutputFormatClick = value => { const { dispatch } = this.props; // log.debug(value); dispatch(setDefaultOutputFormat(value)); }; onThumbFormatClick = value => { const { dispatch } = this.props; dispatch(setDefaultThumbFormat(value)); }; onFrameinfoPositionClick = value => { const { dispatch } = this.props; // log.debug(value); dispatch(setDefaultFrameinfoPosition(value)); }; onCachedFramesSizeClick = value => { const { dispatch } = this.props; // log.debug(value); dispatch(setDefaultCachedFramesSize(value)); }; onOverwriteClick = value => { const { dispatch } = this.props; dispatch(setDefaultSaveOptionOverwrite(value)); }; onIncludeIndividualClick = value => { const { dispatch } = this.props; dispatch(setDefaultSaveOptionIncludeIndividual(value)); }; onEmbedFrameNumbersClick = value => { const { dispatch } = this.props; dispatch(setDefaultEmbedFrameNumbers(value)); }; onEmbedFilePathClick = value => { const { dispatch } = this.props; dispatch(setDefaultEmbedFilePath(value)); }; onOpenFileExplorerAfterSavingClick = value => { const { dispatch } = this.props; dispatch(setDefaultOpenFileExplorerAfterSaving(value)); }; onThumbnailScaleClick = value => { const { dispatch } = this.props; dispatch(setDefaultThumbnailScale(value)); }; onMoviePrintWidthClick = value => { const { dispatch } = this.props; dispatch(setDefaultMoviePrintWidth(value)); }; onShotDetectionMethodClick = value => { const { dispatch } = this.props; dispatch(setDefaultShotDetectionMethod(value)); }; render() { const { dropzoneActive, feedbackFormIsLoading, objectUrlObjects, scaleValueObject, opencvVideo, showScrubWindow, } = this.state; const { dispatch } = this.props; const { allScenes, allThumbs, currentFileId, currentHasParent, currentSecondsPerRow, currentSheetFilter, currentSheetName, currentSheetType, currentSheetView, currentSheetId, file, files, scenes, sheetsByFileId, settings, visibilitySettings, } = this.props; const { [FILTER_METHOD.AGE]: ageFilter = { enabled: false, }, [FILTER_METHOD.DISTTOORIGIN]: uniqueFilter = { enabled: false, }, [FILTER_METHOD.FACECOUNT]: faceCountFilter = { enabled: false, }, [FILTER_METHOD.FACEOCCURRENCE]: faceOccurrenceFilter = { enabled: false, }, [FILTER_METHOD.FACESIZE]: sizeFilter = { enabled: false, }, [FILTER_METHOD.GENDER]: genderFilter = { enabled: false, }, [FILTER_METHOD.FACEID]: faceIdFilter = { enabled: false, }, } = currentSheetFilter; const { defaultSheetView } = visibilitySettings; const fileCount = files.length; let isGridView = true; if (currentSheetView === SHEET_VIEW.TIMELINEVIEW) { isGridView = false; } // get objectUrls by reading all currently visible thumbs and get the corresponding objectUrls from the objectUrlObjects let filteredObjectUrlObjects; if (allThumbs !== undefined && objectUrlObjects.length !== 0) { // create array of all currently visible frameIds const arrayOfFrameIds = allThumbs.map(thumb => thumb.frameId); // filter objectUrlObjects with arrayOfFrameIds filteredObjectUrlObjects = Object.keys(objectUrlObjects) .filter(key => arrayOfFrameIds.includes(key)) .reduce((obj, key) => { return { ...obj, [key]: objectUrlObjects[key], }; }, {}); // console.log(filteredObjectUrlObjects); } let filteredPosterFrameObjectUrlObjects; if (files !== undefined && objectUrlObjects.length !== 0) { // get objectUrls by reading all files and get the corresponding objectUrls from the objectUrlObjects // create array of all currently visible frameIds const arrayOfPosterFrameIds = files.map(file => file.posterFrameId); // filter objectUrlObjects with arrayOfPosterFrameIds filteredPosterFrameObjectUrlObjects = Object.keys(objectUrlObjects) .filter(key => arrayOfPosterFrameIds.includes(key)) .reduce((obj, key) => { return { ...obj, [key]: objectUrlObjects[key], }; }, {}); // console.log(filteredPosterFrameObjectUrlObjects); } // const chartHeight = this.state.containerHeight / 4; const chartHeight = 250; // only for savingAllMoviePrints // get name of file currently printing let fileToPrint; if (this.state.savingAllMoviePrints) { fileToPrint = getObjectProperty( () => this.props.files.find( file => file.id === getObjectProperty(() => this.state.sheetsToPrint.find(item => item.status === 'printing').fileId), ).name, ); } // for EditTransformModal let fileToTransform; if (this.state.fileIdToTransform !== undefined) { fileToTransform = files.find(file => file.id === this.state.fileIdToTransform); } return ( <Dropzone ref={this.dropzoneRef} noClick noKeyboard style={{ position: 'relative' }} accept={this.state.accept} onDrop={this.onDrop.bind(this)} onDragEnter={this.onDragEnter.bind(this)} onDragLeave={this.onDragLeave.bind(this)} className={styles.dropzoneshow} acceptClassName={styles.dropzoneshowAccept} rejectClassName={styles.dropzoneshowReject} > {({ getRootProps, getInputProps, isDragAccept, isDragReject }) => { return ( <div {...getRootProps()}> <input {...getInputProps()} /> <div className={`${styles.Site}`}> <HeaderComponent visibilitySettings={visibilitySettings} settings={settings} file={file} fileCount={fileCount} toggleMovielist={this.toggleMovielist} toggleSettings={this.toggleSettings} onToggleShowHiddenThumbsClick={this.onToggleShowHiddenThumbsClick} onThumbInfoClick={this.onThumbInfoClick} onImportMoviePrint={this.onImportMoviePrint} onClearMovieList={this.onClearMovieList} onSetViewClick={this.onSetViewClick} openMoviesDialog={this.openMoviesDialog} checkForUpdates={this.checkForUpdates} onOpenFeedbackForm={this.onOpenFeedbackForm} isCheckingForUpdates={this.state.isCheckingForUpdates} scaleValueObject={scaleValueObject} isGridView /> {file && ( <FloatingMenu key={currentSheetId} // adding key so component updates on sheet change visibilitySettings={visibilitySettings} settings={settings} scaleValueObject={scaleValueObject} sheetType={currentSheetType} sheetView={currentSheetView} fileMissingStatus={file.fileMissingStatus} toggleMovielist={this.toggleMovielist} onAddIntervalSheetClick={this.onAddIntervalSheetClick} onChangeFaceUniquenessThreshold={this.onChangeFaceUniquenessThreshold} onAddFaceSheetClick={this.onAddFaceSheetClick} onScanMovieListItemClick={this.onScanMovieListItemClick} onSortSheet={this.onSortSheet} onFilterSheet={this.onFilterSheet} onDuplicateSheetClick={this.onDuplicateSheetClick} onChangeSheetViewClick={this.onChangeSheetViewClick} hasParent={currentHasParent} onBackToParentClick={this.onBackToParentClick} onChangeDefaultZoomLevel={this.onChangeDefaultZoomLevel} onSetViewClick={this.onSetViewClick} onShowAllThumbs={this.onShowAllThumbs} currentSheetFilter={currentSheetFilter} onUpdateSheetFilter={this.onUpdateSheetFilter} onToggleShowHiddenThumbsClick={this.onToggleShowHiddenThumbsClick} onThumbInfoClick={this.onThumbInfoClick} onToggleHeaderClick={this.onToggleHeaderClick} onToggleImagesClick={this.onToggleImagesClick} onToggleFaceRectClick={this.onToggleFaceRectClick} optimiseGridLayout={this.optimiseGridLayout} toggleSettings={this.toggleSettings} /> )} <div className={`${styles.SiteContent}`} ref={el => { this.siteContent = el; }} style={{ height: `calc(100vh - ${MENU_HEADER_HEIGHT + MENU_FOOTER_HEIGHT}px)`, }} > <Popup trigger={ <div className={`${styles.openCloseMovieList} ${styles.ItemMovielist} ${ visibilitySettings.showMovielist ? styles.ItemMovielistAnim : '' }`} onClick={this.toggleMovielist} data-tid={visibilitySettings.showMovielist === false ? 'showMovieListBtn' : 'hideMovieListBtn'} > <Icon className={`${styles.normalButton} ${ visibilitySettings.showMovielist === false ? '' : styles.selected }`} style={{ marginRight: '16px', marginTop: '18px', marginLeft: '50px', }} size="large" name={visibilitySettings.showMovielist ? 'angle left' : 'angle right'} /> </div> } mouseEnterDelay={1000} on={['hover']} position="right center" className={stylesPop.popup} content={ visibilitySettings.showMovielist === false ? ( <span> Show Movie and Sheets list <mark>1</mark> </span> ) : ( <span> Hide Movie list <mark>1</mark> </span> ) } /> <div className={`${styles.ItemSideBar} ${styles.ItemMovielist} ${ visibilitySettings.showMovielist ? styles.ItemMovielistAnim : '' }`} > <FileList files={files} settings={settings} visibilitySettings={visibilitySettings} onFileListElementClick={this.onFileListElementClick} onOpenFileExplorer={this.onOpenFileExplorer} onAddIntervalSheetClick={this.onAddIntervalSheetClick} posterobjectUrlObjects={filteredPosterFrameObjectUrlObjects} sheetsByFileId={sheetsByFileId} onChangeSheetViewClick={this.onChangeSheetViewClick} onSubmitMoviePrintNameClick={this.onSubmitMoviePrintNameClick} onSetSheetClick={this.onSetSheetClick} onDuplicateSheetClick={this.onDuplicateSheetClick} onConvertToIntervalBasedClick={this.onConvertToIntervalBasedClick} onExportSheetClick={this.onExportSheetClick} onScanMovieListItemClick={this.onScanMovieListItemClick} onReplaceMovieListItemClick={this.onReplaceMovieListItemClick} onEditTransformListItemClick={this.onEditTransformListItemClick} onRemoveMovieListItem={this.onRemoveMovieListItem} onDeleteSheetClick={this.onDeleteSheetClick} currentSheetId={currentSheetId} /> </div> <Popup trigger={ <div className={`${styles.openCloseSettings} ${styles.ItemSettings} ${ visibilitySettings.showSettings ? styles.ItemSettingsAnim : '' }`} onClick={this.toggleSettings} data-tid={visibilitySettings.showSettings === false ? 'moreSettingsBtn' : 'hideSettingsBtn'} > <Icon className={`${styles.normalButton} ${ visibilitySettings.showSettings === false ? '' : styles.selected }`} style={{ // marginRight: '16px', marginTop: '18px', marginLeft: '6px', }} size="large" name={visibilitySettings.showSettings ? 'angle right' : 'angle left'} /> </div> } mouseEnterDelay={1000} on={['hover']} position="left center" className={stylesPop.popup} content={ visibilitySettings.showSettings === false ? ( <span> Show settings <mark>3</mark> </span> ) : ( <span> Hide settings <mark>3</mark> </span> ) } /> <div className={`${styles.ItemSideBar} ${styles.ItemSettings} ${ visibilitySettings.showSettings ? styles.ItemSettingsAnim : '' }`} > <SettingsList settings={settings} visibilitySettings={visibilitySettings} file={file} sheetType={currentSheetType} sheetName={currentSheetName} columnCountTemp={this.state.columnCountTemp} thumbCountTemp={this.state.thumbCountTemp} thumbCount={this.state.thumbCount} rowCountTemp={Math.ceil(this.state.thumbCountTemp / this.state.columnCountTemp)} columnCount={this.state.columnCount} rowCount={Math.ceil(this.state.thumbCount / this.state.columnCount)} reCapture={this.state.reCapture} onChangeColumn={this.onChangeColumn} onChangeColumnAndApply={this.onChangeColumnAndApply} onChangeRow={this.onChangeRow} onChangeShowFaceRectClick={this.onChangeShowFaceRectClick} onShowPaperPreviewClick={this.onShowPaperPreviewClick} onOutputPathFromMovieClick={this.onOutputPathFromMovieClick} onPaperAspectRatioClick={this.onPaperAspectRatioClick} onDetectInOutPointClick={this.onDetectInOutPointClick} onReCaptureClick={this.onReCaptureClick} onApplyNewGridClick={this.onApplyNewGridClick} onCancelClick={this.onCancelClick} onChangeMargin={this.onChangeMargin} onChangeOutputJpgQuality={this.onChangeOutputJpgQuality} onChangeThumbJpgQuality={this.onChangeThumbJpgQuality} onChangeFaceSizeThreshold={this.onChangeFaceSizeThreshold} onChangeFaceConfidenceThreshold={this.onChangeFaceConfidenceThreshold} onChangeFaceUniquenessThreshold={this.onChangeFaceUniquenessThreshold} onChangeFrameinfoScale={this.onChangeFrameinfoScale} onChangeFrameinfoMargin={this.onChangeFrameinfoMargin} onChangeMinDisplaySceneLength={this.onChangeMinDisplaySceneLength} sceneArray={scenes} secondsPerRowTemp={currentSecondsPerRow} onChangeSceneDetectionThreshold={this.onChangeSceneDetectionThreshold} onChangeTimelineViewSecondsPerRow={this.onChangeTimelineViewSecondsPerRow} onChangeTimelineViewWidthScale={this.onChangeTimelineViewWidthScale} onTimelineViewFlowClick={this.onTimelineViewFlowClick} onToggleHeaderClick={this.onToggleHeaderClick} onShowPathInHeaderClick={this.onShowPathInHeaderClick} onShowDetailsInHeaderClick={this.onShowDetailsInHeaderClick} onShowTimelineInHeaderClick={this.onShowTimelineInHeaderClick} onRoundedCornersClick={this.onRoundedCornersClick} onShowHiddenThumbsClick={this.onShowHiddenThumbsClick} onThumbInfoClick={this.onThumbInfoClick} onChangeDefaultMoviePrintName={this.onChangeDefaultMoviePrintName} onChangeDefaultSingleThumbName={this.onChangeDefaultSingleThumbName} onChangeDefaultAllThumbsName={this.onChangeDefaultAllThumbsName} onChangeOutputPathClick={this.onChangeOutputPathClick} onFrameinfoPositionClick={this.onFrameinfoPositionClick} onOutputFormatClick={this.onOutputFormatClick} onThumbFormatClick={this.onThumbFormatClick} onCachedFramesSizeClick={this.onCachedFramesSizeClick} onOverwriteClick={this.onOverwriteClick} onIncludeIndividualClick={this.onIncludeIndividualClick} onEmbedFrameNumbersClick={this.onEmbedFrameNumbersClick} onEmbedFilePathClick={this.onEmbedFilePathClick} onOpenFileExplorerAfterSavingClick={this.onOpenFileExplorerAfterSavingClick} onThumbnailScaleClick={this.onThumbnailScaleClick} onMoviePrintWidthClick={this.onMoviePrintWidthClick} onShotDetectionMethodClick={this.onShotDetectionMethodClick} onMoviePrintBackgroundColorClick={this.onMoviePrintBackgroundColorClick} scaleValueObject={scaleValueObject} runSceneDetection={this.runSceneDetection} fileScanRunning={this.state.fileScanRunning} showChart={this.state.showChart} onToggleDetectionChart={this.onToggleDetectionChart} recaptureAllFrames={this.recaptureAllFrames} isGridView={isGridView} /> </div> <div className={`${styles.ItemVideoPlayer} ${ visibilitySettings.showMovielist ? styles.ItemMainLeftAnim : '' }`} style={{ top: `${MENU_HEADER_HEIGHT + settings.defaultBorderMargin}px`, transform: visibilitySettings.defaultView === VIEW.PLAYERVIEW ? `translate(0px, 0px)` : `translate(0, ${(scaleValueObject.videoPlayerHeight + DEFAULT_VIDEO_PLAYER_CONTROLLER_HEIGHT) * -1}px)`, overflow: visibilitySettings.defaultView === VIEW.PLAYERVIEW ? 'visible' : 'hidden', }} > {opencvVideo !== undefined && file && ( <VideoPlayer ref={this.videoPlayer} settings={settings} sheetName={currentSheetName} file={file} fileWidth={file.width} fileHeight={file.height} frameCount={file.frameCount} useRatio={file.useRatio} fps={file.fps} path={file.path || ''} currentSheetId={settings.currentSheetId} frameSize={settings.defaultCachedFramesSize} defaultSheetView={defaultSheetView} sheetType={currentSheetType} keyObject={this.state.keyObject} opencvVideo={opencvVideo} containerWidth={this.state.containerWidth} aspectRatioInv={scaleValueObject.aspectRatioInv} height={scaleValueObject.videoPlayerHeight} width={scaleValueObject.videoPlayerWidth} objectUrlObjects={filteredObjectUrlObjects} arrayOfCuts={this.props.arrayOfCuts} allScenes={allScenes} scenes={scenes} thumbs={allThumbs} selectedThumb={ this.state.selectedThumbsArray.length !== 0 ? this.state.selectedThumbsArray[0] : undefined } jumpToFrameNumber={this.state.jumpToFrameNumber} setOrToggleDefaultSheetView={this.setOrToggleDefaultSheetView} onThumbDoubleClick={this.onViewToggle} onChangeThumb={this.onChangeThumb} onAddThumb={this.onAddThumb} onSelectThumbMethod={this.onSelectThumbMethod} onCutSceneClick={this.onCutSceneClick} onMergeSceneClick={this.onMergeSceneClick} /> )} </div> <div ref={r => { this.divOfSortedVisibleThumbGridRef = r; }} className={`${styles.ItemMain} ${visibilitySettings.showMovielist ? styles.ItemMainLeftAnim : ''} ${ visibilitySettings.showSettings ? styles.ItemMainRightAnim : '' } ${visibilitySettings.showSettings ? styles.ItemMainEdit : ''} ${ visibilitySettings.defaultView === VIEW.PLAYERVIEW ? styles.ItemMainTopAnim : '' }`} style={{ width: // use window width if any of these are true defaultSheetView === SHEET_VIEW.TIMELINEVIEW || file === undefined || scaleValueObject.newMoviePrintWidth < this.state.containerWidth // if smaller, width has to be undefined otherwise the center align does not work ? undefined : scaleValueObject.newMoviePrintWidth, marginTop: visibilitySettings.defaultView !== VIEW.PLAYERVIEW ? undefined : `${scaleValueObject.videoPlayerHeight + settings.defaultBorderMargin * 2}px`, minHeight: visibilitySettings.defaultView !== VIEW.PLAYERVIEW ? `calc(100vh - ${MENU_HEADER_HEIGHT + MENU_FOOTER_HEIGHT}px)` : undefined, // backgroundImage: `url(${paperBorderPortrait})`, backgroundImage: (visibilitySettings.showSettings && settings.defaultShowPaperPreview) || (file && visibilitySettings.defaultView !== VIEW.PLAYERVIEW && settings.defaultShowPaperPreview) ? `url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='${ settings.defaultPaperAspectRatioInv < scaleValueObject.moviePrintAspectRatioInv ? scaleValueObject.newMoviePrintHeight / settings.defaultPaperAspectRatioInv : scaleValueObject.newMoviePrintWidth }' height='${ settings.defaultPaperAspectRatioInv < scaleValueObject.moviePrintAspectRatioInv ? scaleValueObject.newMoviePrintHeight : scaleValueObject.newMoviePrintWidth * settings.defaultPaperAspectRatioInv }' style='background-color: rgba(245,245,245,${ visibilitySettings.showSettings ? 1 : 0.02 });'></svg>")` : undefined, backgroundRepeat: 'no-repeat', backgroundPosition: `calc(50% - ${DEFAULT_MIN_MOVIEPRINTWIDTH_MARGIN / 2}px) 50%`, }} > {file || visibilitySettings.showSettings || this.state.loadingFirstFile ? ( <> <Conditional // when in playerview use defaultSheetview which is used as cut and change modes, else use sheetView from sheet if={ visibilitySettings.defaultView === VIEW.PLAYERVIEW ? defaultSheetView !== SHEET_VIEW.TIMELINEVIEW : currentSheetView !== SHEET_VIEW.TIMELINEVIEW } > <SortedVisibleThumbGrid emptyColorsArray={this.state.emptyColorsArray} sheetView={currentSheetView} sheetType={currentSheetType} sheetName={currentSheetName} view={visibilitySettings.defaultView} currentSheetId={settings.currentSheetId} settings={settings} sheetsByFileId={sheetsByFileId} file={file} inputRef={r => { this.sortedVisibleThumbGridRef = r; }} keyObject={this.state.keyObject} onAddThumbClick={this.onAddThumbClick} onJumpToCutThumbClick={this.onJumpToCutThumbClick} onScrubClick={this.onScrubClick} onExpandClick={this.onExpandClick} onThumbDoubleClick={this.onViewToggle} scaleValueObject={scaleValueObject} moviePrintWidth={scaleValueObject.newMoviePrintWidth} selectedThumbsArray={this.state.selectedThumbsArray} onSelectThumbMethod={this.onSelectThumbMethod} defaultOutputPath={settings.defaultOutputPath} defaultOutputPathFromMovie={settings.defaultOutputPathFromMovie} defaultShowDetailsInHeader={settings.defaultShowDetailsInHeader} defaultShowHeader={settings.defaultShowHeader} defaultShowImages={settings.defaultShowImages} defaultShowPathInHeader={settings.defaultShowPathInHeader} defaultShowTimelineInHeader={settings.defaultShowTimelineInHeader} defaultThumbInfo={settings.defaultThumbInfo} defaultThumbInfoRatio={settings.defaultThumbInfoRatio} showMovielist={visibilitySettings.showMovielist} showSettings={visibilitySettings.showSettings} thumbCount={this.state.thumbCountTemp} objectUrlObjects={filteredObjectUrlObjects} thumbs={this.props.thumbs} isViewForPrinting={false} frameSize={settings.defaultCachedFramesSize} isGridView={isGridView} ageFilterEnabled={ageFilter.enabled} uniqueFilterEnabled={uniqueFilter.enabled} faceCountFilterEnabled={faceCountFilter.enabled} faceOccurrenceFilterEnabled={faceOccurrenceFilter.enabled} sizeFilterEnabled={sizeFilter.enabled} genderFilterEnabled={genderFilter.enabled} isExpanded={faceIdFilter.enabled} /> </Conditional> <Conditional // when in playerview use defaultSheetview which is used as cut and change modes, else use sheetView from sheet if={ visibilitySettings.defaultView === VIEW.PLAYERVIEW ? defaultSheetView === SHEET_VIEW.TIMELINEVIEW : currentSheetView === SHEET_VIEW.TIMELINEVIEW } > <SortedVisibleSceneGrid sheetView={currentSheetView} sheetType={currentSheetType} view={visibilitySettings.defaultView} file={file} sheetsByFileId={sheetsByFileId} currentSheetId={settings.currentSheetId} frameCount={file ? file.frameCount : undefined} inputRef={r => { this.sortedVisibleThumbGridRef = r; }} keyObject={this.state.keyObject} selectedThumbsArray={this.state.selectedThumbsArray} onSelectThumbMethod={this.onSelectThumbMethod} onDeselectThumbMethod={this.onDeselectThumbMethod} onThumbDoubleClick={this.onViewToggle} onJumpToCutSceneClick={this.onJumpToCutSceneClick} onExpandClick={this.onExpandClick} moviePrintWidth={scaleValueObject.newMoviePrintTimelineWidth} moviePrintRowHeight={scaleValueObject.newTimelineRowHeight} scaleValueObject={scaleValueObject} scenes={visibilitySettings.defaultView === VIEW.PLAYERVIEW ? allScenes : scenes} settings={settings} showMovielist={visibilitySettings.showMovielist} showSettings={visibilitySettings.showSettings} objectUrlObjects={filteredObjectUrlObjects} thumbs={this.props.allThumbs} currentSheetId={settings.currentSheetId} /> </Conditional> {false && ( <div style={{ // background: 'green', pointerEvents: 'none', border: '5px solid green', width: scaleValueObject.newMoviePrintTimelineWidth, height: scaleValueObject.newMoviePrintTimelineHeight, position: 'absolute', left: visibilitySettings.showSettings ? '' : '50%', top: '50%', marginLeft: visibilitySettings.showSettings ? '' : scaleValueObject.newMoviePrintTimelineWidth / -2, marginTop: scaleValueObject.newMoviePrintTimelineHeight / -2, }} /> )} </> ) : ( <div className={styles.ItemMainStartupContainer}> <img data-tid="startupImg" src={startupImg} style={{ width: `calc(100vw - ${MENU_HEADER_HEIGHT + MENU_FOOTER_HEIGHT}px)`, height: `calc(100vh - ${MENU_HEADER_HEIGHT + MENU_FOOTER_HEIGHT}px)`, maxWidth: 1000, maxHeight: 500, margin: 'auto', }} alt="" /> </div> )} </div> </div> <Modal open={this.state.showFeedbackForm} onClose={() => this.setState({ intendToCloseFeedbackForm: true })} closeIcon // closeOnEscape={false} // closeOnRootNodeClick={false} // basic // size='fullscreen' // style={{ // marginTop: 0, // height: '80vh', // }} className={styles.feedbackFormModal} onMount={() => { setTimeout(() => { this.webviewRef.current.addEventListener('ipc-message', event => { // log.debug(event); log.debug(event.channel); if (event.channel === 'wpcf7mailsent') { const rememberEmail = event.args[0].findIndex(argument => argument.name === 'checkbox-remember-email[]') >= 0; if (rememberEmail) { const emailAddressFromForm = event.args[0].find(argument => argument.name === 'your-email') .value; dispatch(setEmailAddress(emailAddressFromForm)); } this.onCloseFeedbackForm(); } }); // stop showing loader when done loading this.webviewRef.current.addEventListener('did-stop-loading', () => { this.setState({ feedbackFormIsLoading: false, }); }); }, 300); // wait a tiny bit until webview is mounted }} > <Modal.Content // scrolling style={ { // overflow: 'auto', // height: '80vh', } } > {feedbackFormIsLoading && ( <Dimmer active inverted> <Loader inverted>Loading</Loader> </Dimmer> )} <webview autosize="true" // nodeintegration='true' // disablewebsecurity='true' className={styles.feedbackFormWebView} preload="./webViewPreload.js" ref={this.webviewRef} src={`${URL_FEEDBACK_FORM}?app-version=${ process.platform }-${os.release()}-${app.getName()}-${app.getVersion()}&your-email=${settings.emailAddress}`} /> <Modal open={this.state.intendToCloseFeedbackForm} basic size="mini" style={{ position: 'absolute', left: '50%', top: '50%', transform: 'translate(-50%, -50%)', margin: 'auto !important', }} > <Modal.Content> <p>Close the feedback form?</p> </Modal.Content> <Modal.Actions> <Button basic color="red" inverted onClick={() => this.setState({ intendToCloseFeedbackForm: false })} > <Icon name="remove" /> Cancel </Button> <Button color="green" inverted onClick={() => this.setState({ showFeedbackForm: false, intendToCloseFeedbackForm: false })} > <Icon name="checkmark" /> Close </Button> </Modal.Actions> </Modal> </Modal.Content> </Modal> <Footer visibilitySettings={visibilitySettings} file={file} onSaveMoviePrint={this.onSaveMoviePrint} onSaveAllMoviePrints={this.onSaveAllMoviePrints} onOpenFileExplorer={this.onOpenFileExplorer} savingMoviePrint={this.state.savingMoviePrint} savingAllMoviePrints={this.state.savingAllMoviePrints} sheetView={currentSheetView} defaultView={visibilitySettings.defaultView} /> </div> {opencvVideo !== undefined && showScrubWindow && ( <Scrub opencvVideo={opencvVideo} file={file} settings={settings} sheetType={currentSheetType} objectUrlObjects={filteredObjectUrlObjects} keyObject={this.state.keyObject} scrubWindowTriggerTime={this.state.scrubWindowTriggerTime} scrubScene={this.state.scrubScene} scrubThumb={this.state.scrubThumb} scrubThumbLeft={this.state.scrubThumbLeft} scrubThumbRight={this.state.scrubThumbRight} scaleValueObject={scaleValueObject} containerWidth={this.state.containerWidth} containerHeight={this.state.containerHeight} onScrubReturn={this.onScrubReturn} /> )} {this.state.showChart && ( <div className={styles.chart} style={{ height: `${chartHeight}px`, }} > <Line data={this.state.chartData} // width={scaleValueObject.newMoviePrintWidth} // width={this.state.containerWidth} height={chartHeight} options={{ responsive: true, maintainAspectRatio: false, barPercentage: 1.0, categoryPercentage: 1.0, elements: { line: { tension: 0, // disables bezier curves }, }, animation: { duration: 0, // general animation time }, hover: { animationDuration: 0, // duration of animations when hovering an item }, responsiveAnimationDuration: 0, // animation duration after a resize }} /> </div> )} {this.state.showTransformModal && ( <EditTransformModal showTransformModal={this.state.showTransformModal} onClose={() => this.setState({ showTransformModal: false })} onChangeTransform={this.onChangeTransform} fileId={this.state.fileIdToTransform} transformObject={fileToTransform !== undefined ? fileToTransform.transformObject : undefined} originalWidth={fileToTransform !== undefined ? fileToTransform.originalWidth : undefined} originalHeight={fileToTransform !== undefined ? fileToTransform.originalHeight : undefined} width={fileToTransform !== undefined ? fileToTransform.width : undefined} height={fileToTransform !== undefined ? fileToTransform.height : undefined} objectUrl={ fileToTransform !== undefined ? filteredPosterFrameObjectUrlObjects[fileToTransform.posterFrameId] : undefined } /> )} <Modal open={this.state.savingAllMoviePrints} basic size="tiny" style={{ position: 'absolute', left: '50%', top: '50%', transform: 'translate(-50%, -50%)', margin: 'auto !important', }} > <Container textAlign="center"> <Header as="h2" inverted> {`Saving ${this.state.sheetsToPrint.filter(item => item.status === 'done').length + 1} of ${ this.state.sheetsToPrint.filter(item => item.status !== 'undefined').length } MoviePrints`} </Header> {!fileToPrint && <Loader active size="mini" inline />} {fileToPrint || ' '} <Progress percent={ ((this.state.sheetsToPrint.filter(item => item.status === 'done').length + 1.0) / this.state.sheetsToPrint.filter(item => item.status !== 'undefined').length) * 100 } size="tiny" indicating inverted /> <Divider hidden /> <Button color="red" onClick={() => this.setState({ savingAllMoviePrints: false })}> <Icon name="remove" /> Cancel </Button> </Container> </Modal> <ToastContainer transition={Zoom} draggable={false} hideProgressBar progressClassName={stylesPop.toastProgress} /> {dropzoneActive && ( <div className={`${styles.dropzoneshow} ${isDragAccept ? styles.dropzoneshowAccept : ''} ${ isDragReject ? styles.dropzoneshowReject : '' }`} > <div className={styles.dropzoneshowContent}> {`${ isDragAccept ? this.state.keyObject.altKey ? 'CLEAR LIST AND ADD MOVIES' : 'ADD MOVIES TO LIST' : '' } ${isDragReject ? 'NOT ALLOWED' : ''}`} <div className={styles.dropZoneSubline}> {`${ isDragAccept ? this.state.keyObject.altKey ? '' : 'PRESS ALT TO CLEAR LIST AND ADD MOVIES' : '' }`} </div> </div> </div> )} </div> ); }} </Dropzone> ); } } const mapStateToProps = state => { const { visibilitySettings } = state; const { settings, sheetsByFileId, files } = state.undoGroup.present; const { currentFileId, currentSheetId } = settings; const sheetsArray = sheetsByFileId[currentFileId] === undefined ? [] : Object.getOwnPropertyNames(sheetsByFileId[currentFileId]); const allThumbs = sheetsByFileId[currentFileId] === undefined || sheetsByFileId[currentFileId][settings.currentSheetId] === undefined ? undefined : sheetsByFileId[currentFileId][settings.currentSheetId].thumbsArray; const allScenes = sheetsByFileId[currentFileId] === undefined || sheetsByFileId[currentFileId][settings.currentSheetId] === undefined ? undefined : sheetsByFileId[currentFileId][settings.currentSheetId].sceneArray; const arrayOfCuts = allScenes === undefined ? [] : allScenes.map(scene => scene.start); const currentSecondsPerRow = getSecondsPerRow(sheetsByFileId, currentFileId, currentSheetId, settings); const currentSheetFilter = getSheetFilter(sheetsByFileId, currentFileId, currentSheetId); const currentSheetName = getSheetName(sheetsByFileId, currentFileId, currentSheetId); const currentSheetType = getSheetType(sheetsByFileId, currentFileId, currentSheetId, settings); const currentSheetView = getSheetView(sheetsByFileId, currentFileId, currentSheetId, visibilitySettings); const currentHasParent = getParentSheetId(sheetsByFileId, currentFileId, currentSheetId) !== undefined; return { sheetsArray, sheetsByFileId, thumbs: getVisibleThumbs(allThumbs, visibilitySettings.visibilityFilter), allThumbs, currentFileId, currentHasParent, currentSecondsPerRow, currentSheetFilter, currentSheetName, currentSheetType, currentSheetView, currentSheetId, files, file: files.find(file => file.id === currentFileId), allScenes, scenes: getVisibleThumbs(allScenes, visibilitySettings.visibilityFilter), arrayOfCuts, settings, visibilitySettings, defaultThumbCount: settings.defaultThumbCount, defaultColumnCount: settings.defaultColumnCount, }; }; App.contextTypes = { store: PropTypes.object, }; App.defaultProps = { currentFileId: undefined, currentSheetId: undefined, file: undefined, files: [], thumbs: [], sheetsByFileId: {}, scenes: [], }; App.propTypes = { dispatch: PropTypes.func.isRequired, currentFileId: PropTypes.string, currentSheetId: PropTypes.string, file: PropTypes.shape({ id: PropTypes.string, width: PropTypes.number, height: PropTypes.number, columnCount: PropTypes.number, path: PropTypes.string, useRatio: PropTypes.bool, }), settings: PropTypes.object.isRequired, files: PropTypes.array, thumbs: PropTypes.array, sheetsByFileId: PropTypes.object, allScenes: PropTypes.array, scenes: PropTypes.array, visibilitySettings: PropTypes.object.isRequired, }; export default connect(mapStateToProps)(App); <|start_filename|>app/reducers/visibilitySettings.js<|end_filename|> const visibilitySettings = (state = {}, action) => { switch (action.type) { case 'SET_VISIBILITY_FILTER': return { ...state, visibilityFilter: action.filter }; case 'TOGGLE_MOVIELIST': return { ...state, showMovielist: !state.showMovielist }; case 'SHOW_MOVIELIST': return { ...state, showMovielist: true }; case 'HIDE_MOVIELIST': return { ...state, showMovielist: false }; case 'TOGGLE_SETTINGS': return { ...state, showSettings: !state.showSettings }; case 'SHOW_SETTINGS': return { ...state, showSettings: true }; case 'HIDE_SETTINGS': return { ...state, showSettings: false }; case 'SET_VIEW': return { ...state, defaultView: action.defaultView }; case 'SET_SHEETVIEW': return { ...state, defaultSheetView: action.defaultSheetView }; case 'SET_ZOOMLEVEL': return { ...state, defaultZoomLevel: action.defaultZoomLevel }; // case 'TOGGLE_ZOOM_OUT': // return { ...state, zoomOut: !state.zoomOut }; // case 'ZOOM_OUT': // return { ...state, zoomOut: true }; // case 'ZOOM_IN': // return { ...state, zoomOut: false }; default: return state; } }; export default visibilitySettings; <|start_filename|>app/components/VideoPlayer.js<|end_filename|> /* eslint no-param-reassign: "error" */ /* eslint no-nested-ternary: "off" */ import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { Popup } from 'semantic-ui-react'; import uuidV4 from 'uuid/v4'; import log from 'electron-log'; import path from 'path'; import { VideoCaptureProperties } from '../utils/openCVProperties'; import { CHANGE_THUMB_STEP, DEFAULT_SINGLETHUMB_NAME, DEFAULT_VIDEO_PLAYER_CONTROLLER_HEIGHT, MOVIEPRINT_COLORS, SHEET_TYPE, SHEET_VIEW, TRANSFORMOBJECT_INIT, VIDEOPLAYER_CUTGAP, VIDEOPLAYER_SLICE_ARRAY_SIZE, VIDEOPLAYER_SLICEGAP, } from '../utils/constants'; import { secondsToFrameCount, frameCountToSeconds, getHighestFrame, getLowestFrame, getLowestFrameFromScenes, getHighestFrameFromScenes, getSceneFromFrameNumber, getPreviousThumb, getNextThumb, getSliceWidthArrayForCut, limitRange, mapRange, setPosition, } from '../utils/utils'; import { getCropRect, transformMat } from '../utils/utilsForOpencv'; import saveThumb from '../utils/saveThumb'; import Timeline from './Timeline'; import styles from './VideoPlayer.css'; import stylesPop from './Popup.css'; const pathModule = require('path'); const opencv = require('opencv4nodejs'); class VideoPlayer extends Component { constructor(props) { super(props); this.state = { currentFrame: 0, // in frames currentScene: { start: 0, length: 0, }, // in frames videoHeight: 360, videoWidth: 640, playHeadPositionPerc: 0, // in pixel playHeadPositionPercSelection: 0, // in pixel currentTime: 0, // in seconds duration: 0, // in seconds showPlaybar: true, loadVideo: false, showHTML5Player: false, }; // this.onSaveThumbClick = this.onSaveThumbClick.bind(this); this.handleKeyPress = this.handleKeyPress.bind(this); this.getCurrentFrameNumber = this.getCurrentFrameNumber.bind(this); this.onBackForwardClick = this.onBackForwardClick.bind(this); this.updateOpencvVideoCanvas = this.updateOpencvVideoCanvas.bind(this); this.updatePositionWithStep = this.updatePositionWithStep.bind(this); this.onDurationChange = this.onDurationChange.bind(this); this.updateTimeFromFrameNumber = this.updateTimeFromFrameNumber.bind(this); this.updatePositionFromTime = this.updatePositionFromTime.bind(this); this.updatePositionFromFrame = this.updatePositionFromFrame.bind(this); this.updateTimeFromPosition = this.updateTimeFromPosition.bind(this); this.updateTimeFromPositionSelection = this.updateTimeFromPositionSelection.bind(this); this.onVideoError = this.onVideoError.bind(this); this.onLoadedData = this.onLoadedData.bind(this); this.toggleHTML5Player = this.toggleHTML5Player.bind(this); this.saveFrame = this.saveFrame.bind(this); this.onNextSceneClickWithStop = this.onNextSceneClickWithStop.bind(this); this.onNextThumbClickWithStop = this.onNextThumbClickWithStop.bind(this); this.onMergeSceneClickWithStop = this.onMergeSceneClickWithStop.bind(this); this.onCutSceneClickWithStop = this.onCutSceneClickWithStop.bind(this); this.setOrToggleDefaultSheetViewWithStop = this.setOrToggleDefaultSheetViewWithStop.bind(this); this.onChangeThumbClick = this.onChangeThumbClick.bind(this); this.onChangeOrAddClick = this.onChangeOrAddClick.bind(this); } static getDerivedStateFromProps(props) { const { aspectRatioInv, height, containerWidth, defaultSheetView, file, fileHeight, fileWidth, opencvVideo, } = props; const { transformObject = TRANSFORMOBJECT_INIT } = file; const videoHeight = parseInt(height - DEFAULT_VIDEO_PLAYER_CONTROLLER_HEIGHT, 10); const videoWidth = videoHeight / aspectRatioInv; let sliceArraySize = VIDEOPLAYER_SLICE_ARRAY_SIZE; if (defaultSheetView === SHEET_VIEW.GRIDVIEW) { sliceArraySize -= 1; } // needs to check for video aspect ratio!!! const rescaleFactor = aspectRatioInv <= 1 ? videoHeight / fileHeight : videoWidth / fileWidth; const sliceWidthArray = getSliceWidthArrayForCut(containerWidth, videoWidth, sliceArraySize); const cropRect = getCropRect(opencvVideo, transformObject); return { cropRect, rescaleFactor, sliceArraySize, sliceWidthArray, thisTransformObject: transformObject, videoHeight, videoWidth, }; } componentDidMount() { const { containerWidth, jumpToFrameNumber } = this.props; const { videoHeight } = this.state; if (jumpToFrameNumber !== undefined) { this.updateTimeFromFrameNumber(jumpToFrameNumber); } document.addEventListener('keydown', this.handleKeyPress); } componentDidUpdate(prevProps, prevState) { const { jumpToFrameNumber, containerWidth, path, frameCount, allScenes, width } = this.props; const { currentFrame, videoHeight } = this.state; if (jumpToFrameNumber !== undefined) { if (prevProps.jumpToFrameNumber !== jumpToFrameNumber) { this.updateTimeFromFrameNumber(jumpToFrameNumber); } } if ( prevProps.allScenes.length !== allScenes.length || prevProps.frameCount !== frameCount || prevProps.path !== path || prevState.videoHeight !== videoHeight ) { this.updateTimeFromFrameNumber(Math.min(currentFrame, frameCount - 1)); } } componentWillUnmount() { document.removeEventListener('keydown', this.handleKeyPress); } handleKeyPress(event) { // you may also add a filter here to skip keys, that do not have an effect for your app // this.props.keyPressAction(event.keyCode); event.stopPropagation(); const { arrayOfCuts, onCutSceneClick, onMergeSceneClick, sheetType, defaultSheetView } = this.props; const { currentFrame } = this.state; const thisFrameIsACut = arrayOfCuts.some(item => item === currentFrame); // only listen to key events when feedback form is not shown if (event.target.tagName !== 'INPUT') { let stepValue = 1; const [stepValue0, stepValue1, stepValue2] = CHANGE_THUMB_STEP; if (event) { switch (event.which) { case 13: // press enter if (defaultSheetView === SHEET_VIEW.TIMELINEVIEW) { if (thisFrameIsACut) { log.debug(`merging scenes at ${currentFrame}`); onMergeSceneClick(currentFrame); } else { log.debug(`cutting scene at ${currentFrame}`); onCutSceneClick(currentFrame); } } if (sheetType === SHEET_TYPE.SCENES && defaultSheetView === SHEET_VIEW.GRIDVIEW) { this.onChangeThumbClick(); } if (sheetType === SHEET_TYPE.INTERVAL && defaultSheetView === SHEET_VIEW.GRIDVIEW) { this.onChangeOrAddClick(); } break; case 37: // press arrow left stepValue = stepValue1 * -1; if (event.shiftKey) { stepValue = stepValue0 * -1; } if (event.altKey) { stepValue = stepValue2 * -1; } if (event.shiftKey && event.altKey) { if (defaultSheetView === SHEET_VIEW.TIMELINEVIEW) { this.onNextSceneClickWithStop(undefined, 'back', currentFrame); } else { this.onNextThumbClickWithStop(undefined, 'back', currentFrame); } } else { this.updatePositionWithStep(stepValue); } break; case 39: // press arrow right stepValue = stepValue1 * 1; if (event.shiftKey) { stepValue = stepValue0 * 1; } if (event.altKey) { stepValue = stepValue2 * 1; } if (event.shiftKey && event.altKey) { if (defaultSheetView === SHEET_VIEW.TIMELINEVIEW) { this.onNextSceneClickWithStop(undefined, 'forward', currentFrame); } else { this.onNextThumbClickWithStop(undefined, 'forward', currentFrame); } } else { this.updatePositionWithStep(stepValue); } break; case 83: // press 's' this.saveFrame(); break; default: } } } } getCurrentFrameNumber() { const { currentFrame } = this.state; const newFrameNumber = currentFrame; return newFrameNumber; } onBackForwardClick(e, step) { e.target.blur(); // remove focus so button gets not triggered when clicking enter e.stopPropagation(); this.updatePositionWithStep(step); } onDurationChange(duration) { const { playHeadPositionPerc, playHeadPositionPercSelection } = this.state; // setState is asynchronious // updatePosition needs to wait for setState, therefore it is put into callback of setState this.setState({ duration }, () => { this.updateTimeFromPosition(playHeadPositionPerc); this.updateTimeFromPositionSelection(playHeadPositionPercSelection); }); } updateOpencvVideoCanvas(currentFrame) { const { arrayOfCuts, fileHeight, fileWidth, containerWidth, useRatio, defaultSheetView, opencvVideo } = this.props; const { cropRect, rescaleFactor, sliceArraySize, sliceWidthArray, thisTransformObject, videoHeight } = this.state; const ctx = this.opencvVideoPlayerCanvasRef.getContext('2d'); // check if the video was found and is loaded if (opencvVideo !== undefined) { let offsetCorrection = 0; if (defaultSheetView === SHEET_VIEW.GRIDVIEW) { offsetCorrection = 1; } // maybe this can be optimised so it is not set on every updateOpencvVideoCanvas, but // setting this in componentDidUpdate ended in not showing the canvas at allow // so I am keeping it for now // apparently this sets/resets the canvas this.opencvVideoPlayerCanvasRef.height = videoHeight; this.opencvVideoPlayerCanvasRef.width = containerWidth; // offset currentFrame due to main frame is in middle of sliceArraySize const sliceArraySizeHalf = Math.floor(sliceArraySize / 2); const offsetFrameNumber = currentFrame - parseInt(sliceArraySizeHalf, 10) + offsetCorrection; const startFrameToRead = Math.max(0, offsetFrameNumber); setPosition(opencvVideo, startFrameToRead, useRatio); let canvasXPos = 0; for (let i = 0; i < sliceArraySize; i += 1) { const sliceWidth = sliceWidthArray[i]; const sliceXPos = Math.max(Math.floor((fileWidth * rescaleFactor) / 2) - Math.floor(sliceWidth / 2), 0); const thisFrameIsACut = arrayOfCuts.some(item => item === offsetFrameNumber + i + 1); if (offsetFrameNumber + i >= 0) { const mat = opencvVideo.read(); if (!mat.empty) { // optional transformation const matTransformed = transformMat(mat, thisTransformObject, cropRect); const matResized = matTransformed.rescale(rescaleFactor); const cropRectForSlice = new opencv.Rect( sliceXPos, 0, Math.min(matResized.cols, sliceWidth), Math.min(matResized.rows, Math.abs(videoHeight)), ); // log.debug(cropRectForSlice); // log.debug(`${fileWidth}, ${fileHeight}, ${rescaleFactor}, ${fileWidth * rescaleFactor}, ${fileHeight * rescaleFactor}, ${i}: ${canvasXPos}, ${sliceXPos}, ${cropRectForSlice.width}`) const matCropped = matResized.getRegion(cropRectForSlice); const matRGBA = matResized.channels === 1 ? matCropped.cvtColor(opencv.COLOR_GRAY2RGBA) : matCropped.cvtColor(opencv.COLOR_BGR2RGBA); const imgData = new ImageData(new Uint8ClampedArray(matRGBA.getData()), matCropped.cols, matCropped.rows); ctx.putImageData(imgData, canvasXPos, 0); } else { log.debug('frame empty'); } } canvasXPos += sliceWidthArray[i] + (thisFrameIsACut ? VIDEOPLAYER_CUTGAP : VIDEOPLAYER_SLICEGAP); } } } updatePositionWithStep(step) { const { frameCount, fps } = this.props; const { currentTime, loadVideo, showHTML5Player } = this.state; const currentFramePlusStep = limitRange(this.getCurrentFrameNumber() + step, 0, frameCount - 1); const currentTimePlusStep = currentTime + frameCountToSeconds(step, fps); this.updatePositionFromFrame(currentFramePlusStep); this.updateOpencvVideoCanvas(currentFramePlusStep); if (loadVideo && showHTML5Player) { this.video.currentTime = currentTimePlusStep; } } updatePositionFromTime(currentTime) { const { fps, onSelectThumbMethod, allScenes } = this.props; const { currentScene, duration } = this.state; if (currentTime) { // rounds the number with 3 decimals const roundedCurrentTime = Math.round(currentTime * 1000 + Number.EPSILON) / 1000; const currentFrame = secondsToFrameCount(currentTime, fps); const newScene = getSceneFromFrameNumber(allScenes, currentFrame); if (currentScene !== undefined && newScene !== undefined && currentScene.sceneId !== newScene.sceneId) { this.setState({ currentScene: newScene, }); onSelectThumbMethod(newScene.sceneId); // call to update selection when scrubbing } const xPos = mapRange(roundedCurrentTime, 0, duration, 0, 1.0, false); const { inPoint, outPoint } = this.getInOutObject(newScene); const xPosSelection = mapRange(roundedCurrentTime, inPoint, outPoint, 0, 1.0, false); this.setState({ currentFrame, currentTime: roundedCurrentTime, playHeadPositionPerc: xPos, playHeadPositionPercSelection: xPosSelection, }); this.updateOpencvVideoCanvas(currentFrame); // log.debug(`${currentTime} : ${xPos} : ${containerWidth} : ${duration}`); } } updatePositionFromFrame(currentFrame) { const { frameCount, onSelectThumbMethod, allScenes } = this.props; const { currentScene } = this.state; if (currentFrame !== undefined) { const newScene = getSceneFromFrameNumber(allScenes, currentFrame); if (newScene !== undefined && (currentScene === undefined || currentScene.sceneId !== newScene.sceneId)) { this.setState({ currentScene: newScene, }); onSelectThumbMethod(newScene.sceneId); // call to update selection when scrubbing } const xPos = mapRange(currentFrame, 0, frameCount - 1, 0, 1.0, false); const { inPoint, outPoint } = this.getInOutObject(newScene); const xPosSelection = mapRange(currentFrame, inPoint, outPoint, 0, 1.0, false); this.setState({ currentFrame, playHeadPositionPerc: xPos, playHeadPositionPercSelection: xPosSelection, }); } } updateTimeFromFrameNumber(currentFrame) { const { frameCount, fps, allScenes } = this.props; const { loadVideo, showHTML5Player } = this.state; const currentScene = getSceneFromFrameNumber(allScenes, currentFrame); if (currentScene !== undefined) { this.setState({ currentScene, }); } const xPos = mapRange(currentFrame, 0, frameCount - 1, 0, 1.0, false); const { inPoint, outPoint } = this.getInOutObject(currentScene); const xPosSelection = mapRange(currentFrame, inPoint, outPoint, 0, 1.0, false); const currentTime = frameCountToSeconds(currentFrame, fps); this.setState({ currentFrame, currentTime, playHeadPositionPerc: xPos, playHeadPositionPercSelection: xPosSelection, }); if (loadVideo && showHTML5Player) { this.video.currentTime = currentTime; } this.updateOpencvVideoCanvas(currentFrame); } getInOutObject = currentScene => { let inPoint = 0; let outPoint = 0; if (currentScene !== undefined) { inPoint = currentScene.start; outPoint = currentScene.start + currentScene.length - 1; } return { inPoint, outPoint, }; }; updateTimeFromPosition(xPos) { const { frameCount, allScenes, onSelectThumbMethod } = this.props; const { currentScene, duration, loadVideo, showHTML5Player } = this.state; if (xPos !== undefined) { const currentFrame = mapRange(xPos, 0, 1.0, 0, frameCount - 1); const newScene = getSceneFromFrameNumber(allScenes, currentFrame); if (currentScene !== undefined && newScene !== undefined && currentScene.sceneId !== newScene.sceneId) { this.setState({ currentScene: newScene, }); onSelectThumbMethod(newScene.sceneId); // call to update selection when scrubbing } const { inPoint, outPoint } = this.getInOutObject(newScene); const xPosSelection = mapRange(currentFrame, inPoint, outPoint, 0, 1.0, false); this.setState({ playHeadPositionPerc: xPos, playHeadPositionPercSelection: xPosSelection, currentFrame, }); this.updateOpencvVideoCanvas(currentFrame); const currentTime = mapRange(xPos, 0, 1.0, 0, duration, false); // log.debug(`${currentTime} : ${xPos} : ${containerWidth} : ${duration}`); this.setState({ currentTime }); if (loadVideo && showHTML5Player) { this.video.currentTime = currentTime; } } } updateTimeFromPositionSelection(xPosSelection) { const { frameCount, allScenes, onSelectThumbMethod } = this.props; const { currentScene, duration, loadVideo, showHTML5Player } = this.state; if (xPosSelection !== undefined) { const { inPoint, outPoint } = this.getInOutObject(currentScene); const currentFrame = mapRange(xPosSelection, 0, 1.0, inPoint, outPoint); const xPos = mapRange(currentFrame, 0, frameCount - 1, 0, 1.0, false); const newScene = getSceneFromFrameNumber(allScenes, currentFrame); if (currentScene !== undefined && newScene !== undefined && currentScene.sceneId !== newScene.sceneId) { this.setState({ currentScene: newScene, }); onSelectThumbMethod(newScene.sceneId); // call to update selection when scrubbing } this.setState({ playHeadPositionPerc: xPos, playHeadPositionPercSelection: xPosSelection, currentFrame, }); this.updateOpencvVideoCanvas(currentFrame); const currentTime = mapRange(xPos, 0, 1.0, 0, duration, false); // log.debug(`${currentTime} : ${xPos} : ${containerWidth} : ${duration}`); this.setState({ currentTime }); if (loadVideo && showHTML5Player) { this.video.currentTime = currentTime; } } } onMergeSceneClickWithStop(e, currentFrame) { const { onMergeSceneClick } = this.props; e.target.blur(); // remove focus so button gets not triggered when clicking enter e.stopPropagation(); onMergeSceneClick(currentFrame); log.debug(`Mouse click: merging scenes at ${currentFrame}`); } onCutSceneClickWithStop(e, currentFrame) { const { onCutSceneClick } = this.props; e.target.blur(); // remove focus so button gets not triggered when clicking enter e.stopPropagation(); log.debug(`Mouse click: cutting scene at ${currentFrame}`); onCutSceneClick(currentFrame); } setOrToggleDefaultSheetViewWithStop(e) { const { setOrToggleDefaultSheetView } = this.props; e.target.blur(); // remove focus so button gets not triggered when clicking enter e.stopPropagation(); setOrToggleDefaultSheetView(); } onNextThumbClickWithStop(e, direction) { const { currentScene } = this.state; const { frameCount, onSelectThumbMethod, allScenes, selectedThumb, thumbs, sheetType } = this.props; if (e !== undefined) { e.target.blur(); // remove focus so button gets not triggered when clicking enter e.stopPropagation(); } if (sheetType === SHEET_TYPE.SCENES) { let newSceneToSelect; if (direction === 'back') { newSceneToSelect = getSceneFromFrameNumber(allScenes, currentScene.start - 1); } else if (direction === 'forward') { newSceneToSelect = getSceneFromFrameNumber(allScenes, currentScene.start + currentScene.length); } const newThumbToSelect = thumbs.find(thumb => thumb.thumbId === newSceneToSelect.sceneId); if (newSceneToSelect !== undefined) { onSelectThumbMethod(newSceneToSelect.sceneId); // call to update selection } if (newThumbToSelect !== undefined) { let newFrameNumberToJumpTo = newThumbToSelect.frameNumber; newFrameNumberToJumpTo = limitRange(newFrameNumberToJumpTo, 0, frameCount - 1); this.updatePositionFromFrame(newFrameNumberToJumpTo); this.updateOpencvVideoCanvas(newFrameNumberToJumpTo); } } else if (sheetType === SHEET_TYPE.INTERVAL || sheetType === SHEET_TYPE.FACES) { const selectedThumbId = selectedThumb === undefined ? undefined : selectedThumb.thumbId; let newThumbToSelect; if (direction === 'back') { newThumbToSelect = getPreviousThumb(thumbs, selectedThumbId); } else if (direction === 'forward') { newThumbToSelect = getNextThumb(thumbs, selectedThumbId); } if (newThumbToSelect !== undefined) { onSelectThumbMethod(newThumbToSelect.thumbId); // call to update selection let newFrameNumberToJumpTo = newThumbToSelect.frameNumber; newFrameNumberToJumpTo = limitRange(newFrameNumberToJumpTo, 0, frameCount - 1); this.updatePositionFromFrame(newFrameNumberToJumpTo); this.updateOpencvVideoCanvas(newFrameNumberToJumpTo); } } } onNextSceneClickWithStop(e, direction, frameNumber) { const { currentScene } = this.state; const { frameCount, onSelectThumbMethod, allScenes } = this.props; if (e !== undefined) { e.target.blur(); // remove focus so button gets not triggered when clicking enter e.stopPropagation(); } let newFrameNumberToJumpTo; let newSceneToSelect; // if going back and frameNumber is within the scene not at the cut // then just update position else jumpToScene if (direction === 'back' && frameNumber !== currentScene.start) { newFrameNumberToJumpTo = currentScene.start; } else { if (direction === 'back') { newSceneToSelect = getSceneFromFrameNumber(allScenes, currentScene.start - 1); newFrameNumberToJumpTo = newSceneToSelect.start; } else if (direction === 'forward') { newFrameNumberToJumpTo = currentScene.start + currentScene.length; newSceneToSelect = getSceneFromFrameNumber(allScenes, newFrameNumberToJumpTo); } if (newSceneToSelect !== undefined) { onSelectThumbMethod(newSceneToSelect.sceneId); // call to update selection } } newFrameNumberToJumpTo = limitRange(newFrameNumberToJumpTo, 0, frameCount - 1); this.updatePositionFromFrame(newFrameNumberToJumpTo); this.updateOpencvVideoCanvas(newFrameNumberToJumpTo); } onChangeThumbClick() { const { currentFrame, currentScene } = this.state; const { currentSheetId, file, onChangeThumb } = this.props; if (currentScene !== undefined && currentFrame !== undefined) { onChangeThumb(file, currentSheetId, currentScene.sceneId, currentFrame); } } onChangeOrAddClick = () => { const { currentFrame } = this.state; const { currentSheetId, file, frameSize, keyObject, onAddThumb, onChangeThumb, onSelectThumbMethod, selectedThumb, thumbs, } = this.props; // only do changes if there is a thumb selected if (thumbs.find(thumb => thumb.thumbId === selectedThumb.thumbId) !== undefined) { if (keyObject.altKey || keyObject.shiftKey) { const newThumbId = uuidV4(); if (keyObject.altKey) { onAddThumb( file, currentSheetId, newThumbId, currentFrame, thumbs.find(thumb => thumb.thumbId === selectedThumb.thumbId).index + 1, frameSize, ); } else { // if shiftKey onAddThumb( file, currentSheetId, newThumbId, currentFrame, thumbs.find(thumb => thumb.thumbId === selectedThumb.thumbId).index, frameSize, ); } // delay selection so it waits for add thumb to be ready setTimeout(() => { onSelectThumbMethod(newThumbId, currentFrame); }, 500); } else { // if normal set new thumb onChangeThumb(file, currentSheetId, selectedThumb.thumbId, currentFrame, frameSize); } } }; toggleHTML5Player(e) { e.target.blur(); // remove focus so button gets not triggered when clicking enter e.stopPropagation(); this.setState(prevState => ({ showHTML5Player: !prevState.showHTML5Player, })); } saveFrame(e = undefined) { if (e !== undefined) { e.target.blur(); // remove focus so button gets not triggered when clicking enter e.stopPropagation(); } const { currentFrame } = this.state; const { file, fps, useRatio, path: filePath, sheetName, settings } = this.props; const { name, transformObject } = file; const { defaultOutputPathFromMovie, defaultOutputPath, defaultSingleThumbName, defaultThumbFormat, defaultThumbJpgQuality, } = settings; const filePathDirectory = path.dirname(filePath); const outputPath = defaultOutputPathFromMovie ? filePathDirectory : defaultOutputPath; saveThumb( filePath, useRatio, name, sheetName, currentFrame, defaultSingleThumbName || DEFAULT_SINGLETHUMB_NAME, undefined, transformObject, outputPath, true, defaultThumbFormat, defaultThumbJpgQuality, fps, ); } onVideoError = () => { const { frameCount } = this.props; log.error('onVideoError'); // log.debug(this); this.onDurationChange(frameCountToSeconds(frameCount)); this.setState({ loadVideo: false, }); }; onLoadedData = () => { // log.debug('onLoadedData'); // log.debug(this); this.setState({ loadVideo: true, }); }; render() { const { currentFrame, currentScene, playHeadPositionPerc, playHeadPositionPercSelection } = this.state; const { arrayOfCuts, containerWidth, defaultSheetView, file, frameCount, path, keyObject, scenes, sheetType, thumbs, } = this.props; const { showHTML5Player, showPlaybar, videoHeight, videoWidth } = this.state; function over(event) { event.target.style.opacity = 1; } function out(event) { event.target.style.opacity = 0.5; } const thisFrameIsACut = arrayOfCuts.some(item => item === currentFrame); return ( <div> <div className={`${styles.player}`} style={{ // height: videoHeight, width: containerWidth, }} > <Popup trigger={ <button type="button" className={`${styles.hoverButton} ${styles.textButton} ${styles.html5Button}`} onClick={e => this.toggleHTML5Player(e)} onMouseOver={over} onMouseLeave={out} onFocus={over} onBlur={out} > html5 player </button> } mouseEnterDelay={1000} on={['hover']} position="bottom center" className={stylesPop.popup} content={showHTML5Player ? 'Hide HTML5 Player' : 'Show HTML5 Player'} /> {showHTML5Player && ( <> <div className={`${styles.noVideoText}`}>The video format is not supported by this player</div> <video ref={el => { this.video = el; }} className={`${styles.videoOverlay}`} controls={showPlaybar ? true : undefined} muted src={`${pathModule.dirname(path)}/${encodeURIComponent(pathModule.basename(path))}`} width={videoWidth} height={videoHeight} onDurationChange={e => this.onDurationChange(e.target.duration)} onTimeUpdate={e => this.updatePositionFromTime(e.target.currentTime)} onLoadedData={this.onLoadedData} onError={this.onVideoError} > <track kind="captions" /> </video> </> )} <Popup trigger={ <button type="button" className={`${styles.hoverButton} ${styles.textButton} ${styles.saveFrameButton} ${ defaultSheetView === SHEET_VIEW.GRIDVIEW ? styles.centerTheButton : '' }`} onClick={e => this.saveFrame(e)} onMouseOver={over} onMouseLeave={out} onFocus={over} onBlur={out} > save frame </button> } mouseEnterDelay={1000} on={['hover']} position="bottom center" className={stylesPop.popup} content="Save frame" /> <canvas ref={el => { this.opencvVideoPlayerCanvasRef = el; }} /> <div id="currentTimeDisplay" className={`${styles.frameNumberOrTimeCode} ${styles.moveToMiddle}`}> {currentFrame} </div> </div> <div className={`${styles.controlsWrapper}`}> <Timeline playHeadPositionPercSelection={playHeadPositionPercSelection} containerWidth={containerWidth} playHeadPositionPerc={playHeadPositionPerc} frameCount={frameCount} currentScene={currentScene} sheetType={sheetType} updateTimeFromPosition={this.updateTimeFromPosition} updateTimeFromPositionSelection={this.updateTimeFromPositionSelection} lowestFrame={sheetType === SHEET_TYPE.SCENES ? getLowestFrameFromScenes(scenes) : getLowestFrame(thumbs)} highestFrame={sheetType === SHEET_TYPE.SCENES ? getHighestFrameFromScenes(scenes) : getHighestFrame(thumbs)} /> {(sheetType === SHEET_TYPE.SCENES || defaultSheetView === SHEET_VIEW.GRIDVIEW) && ( <div className={`${styles.buttonWrapper}`}> {sheetType === SHEET_TYPE.SCENES && ( <Popup trigger={ <button type="button" className={`${styles.hoverButton} ${styles.textButton} ${styles.changeModeButton}`} onClick={e => this.setOrToggleDefaultSheetViewWithStop(e)} onMouseOver={over} onMouseLeave={out} onFocus={over} onBlur={out} > {defaultSheetView === SHEET_VIEW.TIMELINEVIEW ? 'thumb mode' : 'cut mode'} </button> } mouseEnterDelay={1000} on={['hover']} position="bottom center" className={stylesPop.popup} content={ <span> Switch between cut/merge shots and change thumb mode <mark>SPACE</mark> </span> } /> )} {defaultSheetView === SHEET_VIEW.TIMELINEVIEW && ( <Popup trigger={ <button type="button" className={`${styles.hoverButton} ${styles.textButton} ${styles.previousScene}`} onClick={e => this.onNextSceneClickWithStop(e, 'back', currentFrame)} onMouseOver={over} onMouseLeave={out} onFocus={over} onBlur={out} > previous cut </button> } mouseEnterDelay={1000} on={['hover']} position="bottom center" className={stylesPop.popup} content={ <span> Jump to previous cut <mark>SHIFT + ALT + Arrow left</mark> </span> } /> )} {defaultSheetView === SHEET_VIEW.GRIDVIEW && ( <Popup trigger={ <button type="button" className={`${styles.hoverButton} ${styles.textButton} ${styles.previousScene}`} onClick={e => this.onNextThumbClickWithStop(e, 'back', currentFrame)} onMouseOver={over} onMouseLeave={out} onFocus={over} onBlur={out} > previous thumb </button> } mouseEnterDelay={1000} on={['hover']} position="bottom center" className={stylesPop.popup} content={ <span> Jump to previous thumb <mark>SHIFT + ALT + Arrow left</mark> </span> } /> )} <Popup trigger={ <button type="button" className={`${styles.hoverButton} ${styles.textButton} ${styles.hundredFramesBack}`} onClick={e => this.onBackForwardClick(e, -100)} onMouseOver={over} onMouseLeave={out} onFocus={over} onBlur={out} > {'<<<'} </button> } mouseEnterDelay={1000} on={['hover']} position="bottom center" className={stylesPop.popup} content={ <span> Move 100 frames back <mark>ALT + Arrow left</mark> </span> } /> <Popup trigger={ <button type="button" className={`${styles.hoverButton} ${styles.textButton} ${styles.tenFramesBack}`} onClick={e => this.onBackForwardClick(e, -10)} onMouseOver={over} onMouseLeave={out} onFocus={over} onBlur={out} > {'<<'} </button> } mouseEnterDelay={1000} on={['hover']} position="bottom center" className={stylesPop.popup} content={ <span> Move 10 frames back <mark>Arrow left</mark> </span> } /> <Popup trigger={ <button type="button" className={`${styles.hoverButton} ${styles.textButton} ${styles.oneFrameBack}`} onClick={e => this.onBackForwardClick(e, -1)} onMouseOver={over} onMouseLeave={out} onFocus={over} onBlur={out} > {'<'} </button> } mouseEnterDelay={1000} on={['hover']} position="bottom center" className={stylesPop.popup} content={ <span> Move 1 frame back <mark>SHIFT + Arrow left</mark> </span> } /> {sheetType === SHEET_TYPE.SCENES && defaultSheetView === SHEET_VIEW.TIMELINEVIEW && currentFrame !== 0 && ( <Popup trigger={ <button type="button" className={`${styles.hoverButton} ${styles.textButton} ${styles.cutMergeButton}`} onClick={ thisFrameIsACut ? e => this.onMergeSceneClickWithStop(e, currentFrame) : e => this.onCutSceneClickWithStop(e, currentFrame) } onMouseOver={over} onMouseLeave={out} onFocus={over} onBlur={out} style={{ color: MOVIEPRINT_COLORS[0], }} > {thisFrameIsACut ? 'MERGE' : 'CUT'} </button> } mouseEnterDelay={1000} on={['hover']} position="bottom center" className={stylesPop.popup} content={ thisFrameIsACut ? ( <span> Merge scenes <mark>ENTER</mark> </span> ) : ( <span> Cut scene <mark>ENTER</mark> </span> ) } /> )} {sheetType === SHEET_TYPE.SCENES && defaultSheetView === SHEET_VIEW.GRIDVIEW && currentFrame !== 0 && ( <Popup trigger={ <button type="button" className={`${styles.hoverButton} ${styles.textButton} ${styles.cutMergeButton}`} onClick={this.onChangeThumbClick} onMouseOver={over} onMouseLeave={out} onFocus={over} onBlur={out} style={{ color: MOVIEPRINT_COLORS[0], }} > CHANGE </button> } mouseEnterDelay={1000} on={['hover']} position="bottom center" className={stylesPop.popup} content={ <span> Change the thumb to use this frame <mark>ENTER</mark> </span> } /> )} {sheetType === SHEET_TYPE.INTERVAL && ( <Popup trigger={ <button type="button" className={`${styles.hoverButton} ${styles.textButton} ${styles.cutMergeButton}`} onClick={this.onChangeOrAddClick} onMouseOver={over} onMouseLeave={out} onFocus={over} onBlur={out} style={{ color: MOVIEPRINT_COLORS[0], }} > {keyObject.altKey ? 'ADD AFTER' : keyObject.shiftKey ? 'ADD BEFORE' : 'CHANGE'} </button> } mouseEnterDelay={1000} on={['hover']} position="bottom center" className={stylesPop.popup} content={ keyObject.altKey ? ( <span> Add a new thumb <mark>after</mark> selection </span> ) : keyObject.shiftKey ? ( <span> Add a new thumb <mark>before</mark> selection </span> ) : ( <span> Change the thumb to use this frame <mark>ENTER</mark> | with <mark>SHIFT</mark> add a thumb before selection | with <mark>ALT</mark> add a thumb after selection </span> ) } /> )} <Popup trigger={ <button type="button" className={`${styles.hoverButton} ${styles.textButton} ${styles.oneFrameForward}`} onClick={e => this.onBackForwardClick(e, 1)} onMouseOver={over} onMouseLeave={out} onFocus={over} onBlur={out} > {'>'} </button> } mouseEnterDelay={1000} on={['hover']} position="bottom center" className={stylesPop.popup} content={ <span> Move 1 frame forward <mark>SHIFT + Arrow right</mark> </span> } /> <Popup trigger={ <button type="button" className={`${styles.hoverButton} ${styles.textButton} ${styles.tenFramesForward}`} onClick={e => this.onBackForwardClick(e, 10)} onMouseOver={over} onMouseLeave={out} onFocus={over} onBlur={out} > {'>>'} </button> } mouseEnterDelay={1000} on={['hover']} position="bottom center" className={stylesPop.popup} content={ <span> Move 10 frames forward<mark>Arrow right</mark> </span> } /> <Popup trigger={ <button type="button" className={`${styles.hoverButton} ${styles.textButton} ${styles.hundredFramesForward}`} onClick={e => this.onBackForwardClick(e, 100)} onMouseOver={over} onMouseLeave={out} onFocus={over} onBlur={out} > {'>>>'} </button> } mouseEnterDelay={1000} on={['hover']} position="bottom center" className={stylesPop.popup} content={ <span> Move 100 frames forward <mark>ALT + Arrow right</mark> </span> } /> {defaultSheetView === SHEET_VIEW.GRIDVIEW && ( <Popup trigger={ <button type="button" className={`${styles.hoverButton} ${styles.textButton} ${styles.nextScene}`} onClick={e => this.onNextThumbClickWithStop(e, 'forward', currentFrame)} onMouseOver={over} onMouseLeave={out} onFocus={over} onBlur={out} > next thumb </button> } mouseEnterDelay={1000} on={['hover']} position="bottom center" className={stylesPop.popup} content={ <span> Jump to next thumb <mark>SHIFT + ALT + Arrow right</mark> </span> } /> )} {defaultSheetView === SHEET_VIEW.TIMELINEVIEW && ( <Popup trigger={ <button type="button" className={`${styles.hoverButton} ${styles.textButton} ${styles.nextScene}`} onClick={e => this.onNextSceneClickWithStop(e, 'forward', currentFrame)} onMouseOver={over} onMouseLeave={out} onFocus={over} onBlur={out} > next cut </button> } mouseEnterDelay={1000} on={['hover']} position="bottom center" className={stylesPop.popup} content={ <span> Jump to next cut <mark>SHIFT + ALT + Arrow right</mark> </span> } /> )} </div> )} </div> </div> ); } } VideoPlayer.contextTypes = { thumbId: PropTypes.number, positionRatio: PropTypes.number, setNewFrame: PropTypes.func, closeModal: PropTypes.func, }; VideoPlayer.defaultProps = { file: { id: undefined, width: 640, height: 360, columnCount: 4, frameCount: 16, fps: 25, path: '', }, height: 360, width: 640, thumbs: undefined, scenes: [], allScenes: [], }; VideoPlayer.propTypes = { aspectRatioInv: PropTypes.number.isRequired, selectedThumb: PropTypes.shape({ thumbId: PropTypes.string, }), file: PropTypes.shape({ id: PropTypes.string, width: PropTypes.number, height: PropTypes.number, columnCount: PropTypes.number, frameCount: PropTypes.number, fps: PropTypes.number, path: PropTypes.string, useRatio: PropTypes.bool, }), height: PropTypes.number, setOrToggleDefaultSheetView: PropTypes.func.isRequired, defaultSheetView: PropTypes.string, sheetType: PropTypes.string, jumpToFrameNumber: PropTypes.number, onChangeThumb: PropTypes.func.isRequired, onMergeSceneClick: PropTypes.func.isRequired, onCutSceneClick: PropTypes.func.isRequired, onSelectThumbMethod: PropTypes.func.isRequired, containerWidth: PropTypes.number.isRequired, width: PropTypes.number, scenes: PropTypes.array, allScenes: PropTypes.array, thumbs: PropTypes.array, }; export default VideoPlayer; <|start_filename|>app/components/SceneGrid.css<|end_filename|> .grid { display: block; height: 100%; white-space: nowrap; border: 0; overflow: auto; margin: auto; outline: none; position: relative; } .gridItem { float: left; /*width: 168px;*/ /*padding: 8px;*/ /*background: #3b3b3b;*/ /* border: 0; */ margin: 0.5px; position: relative; outline: none; -webkit-user-select: none; background-repeat: no-repeat; /* background-size: cover; */ /* background-size: auto 100%; */ /* background-size: auto calc(100% + 20px); */ background-position: center; /* background-blend-mode: overlay; */ /* background-repeat: space; */ /* background-clip: padding-box; */ /* border: 4px solid rgba(0,0,0,0.1); */ border-style: solid; border-color: rgba(0,0,0,0.1); } .gridHeader { background: #3b3b3b; color: #eee; font-family: 'Open sans'; padding-left: 4px; overflow: hidden; position: relative; line-height: 0; } .gridHeaderImageAndText { float: left; transform-origin: 'left bottom'; vertical-align: baseline; } .gridHeaderImage { /* display: inline-block; */ position: absolute; } .gridHeaderText { display: inline-block; white-space: normal; color: #ff925e; } .gridHeaderTextName { font-size: 12px; font-weight: bold; color: #ffd3bf; letter-spacing: 0.3px; text-align: right; } .timelineWrapper { position: relative; background: rgba(255, 219, 204, 0.2); clear: both; } .timelineCut { position: absolute; background: #e85d22; height: 100%; } .timelineThumbIndicator { position: absolute; min-width: 1px; background: #ffdbcc; } .gridItemSelected { outline-style: solid; outline-color: #ff5006; background-color: #ff5006; /* box-shadow: 5px 0px 0px 0px #FF5006 */ } .sceneExpanded { outline-style: solid; outline-color: #ffd3bf; /* outline-color: #ff5006; */ outline-offset: -1px; /* background-color: #ff5006; */ /* box-shadow: 5px 0px 0px 0px #FF5006 */ } /* .gridItemSelected:after { content: ""; background-color: #FF5006; position: absolute; width: 5px; height: 100%; top: 0; right: 0; display: block; transform: translateX(10px); } */ .gridItem:hover { /* background: #eee; */ cursor: pointer; } .image { float: left; /*width: 168px;*/ /*padding: 8px;*/ /*background: #3b3b3b;*/ /*border: 0;*/ /*margin: 4px;*/ /* border-radius:8px; */ /*position: relative;*/ } .gridForPrinting { margin-left: -50px; } .frameNumber { position: absolute; top: 0; left: 0; background: #eee; border-radius: 2px; font-family: 'Open sans'; font-size: 10px; line-height: 10px; padding: 1px; color: #000000; transform-origin: left top; /*opacity: 0.5;*/ } .dragHandleButton { position: absolute; /* top: calc(50% - 28px); left: calc(50% - 72px); */ top: 50%; left: 50%; transform: translate(-50%, -50%) scale(0.95); /* width: 144px; */ /* height: 80%; */ opacity: 1; cursor: move; background-color: transparent; border: 0; outline: none; } .dragHandleIcon { position: absolute; /* top: calc(50% - 28px); left: calc(50% - 72px); */ top: 50%; left: 50%; transform: translate(-50%, -50%); width: 144px; opacity: 1; /* cursor: move; */ } .whileDragging { box-shadow: 0px 0px 80px 10px rgba(0, 0, 0, 0.5); z-index: 1000; /* has to be higher than dropzoneshow*/ } .hide { position: absolute; outline: none; top: 0; left: 50%; opacity: 0.5; background-color: transparent; } .inPoint { position: absolute; outline: none; bottom: 0; left: 0; opacity: 0.5; } /* .back { position: absolute; outline:none; bottom: 0; left: calc(50% - 24px - 48px); opacity: 0.5; } */ .save { position: absolute; outline: none; top: 0; right: 0; opacity: 0.5; } .textButton { font-family: 'Franchise'; color: #ffffff; font-size: 30px; opacity: 0.5; } /* .forward { position: absolute; outline:none; bottom: 0; left: calc(50% + 24px); opacity: 0.5; } */ .outPoint { position: absolute; outline: none; bottom: 0; right: 0; opacity: 0.5; } .dim { transition: opacity 0.3s; opacity: 0.2 !important; transition-delay: 0.5s; } .hoverButton { border: 0; cursor: pointer; background-color: transparent; outline: none; -webkit-user-select: none; } .opaque { opacity: 1 !important; } .lineBreak { clear: both; } .sheetTypeSwitchButton { position: fixed; transform-origin: center center; transform: translateY(-50%); top: 80%; left: 0; margin-top: 8px; padding-left: 8px; z-Index: 1; } <|start_filename|>app/components/Thumb.js<|end_filename|> /* eslint no-param-reassign: ["error"] */ /* eslint no-nested-ternary: "off" */ // @flow import React from 'react'; import PropTypes from 'prop-types'; import { SortableHandle } from 'react-sortable-hoc'; import { Popup } from 'semantic-ui-react'; import { SHEET_TYPE, VIEW } from '../utils/constants'; import styles from './ThumbGrid.css'; import stylesPop from './Popup.css'; import AllFaces from './AllFaces'; import transparent from '../img/Thumb_TRANSPARENT.png'; const DragHandle = React.memo( SortableHandle(({ width, height, thumbId }) => ( <Popup trigger={ <button type="button" data-tid={`thumbDragHandleBtn_${thumbId}`} className={`${styles.dragHandleButton}`} style={{ width, height: Math.floor(height), }} > <img src={transparent} style={{ width, height: Math.floor(height), }} alt="" /> </button> } mouseEnterDelay={2000} on={['hover']} pinned offset="-50%r, -50%r" position="top right" basic className={stylesPop.popupSmall} content="Drag thumb" /> )), ); const Thumb = React.memo( ({ base64, borderRadius, color, controllersAreVisible, defaultShowFaceRect, dim, facesArray, frameinfoColor, frameinfoMargin, frameinfoPosition, frameninfoBackgroundColor, hidden, index, indexForId, inputRefThumb, isExpanded, keyObject, margin, onOver, onSelect, onThumbDoubleClick, selected, sheetType, thumbCSSTranslate, thumbHeight, thumbId, thumbImageObjectUrl, thumbInfoValue, thumbWidth, transparentThumb, ageFilterEnabled, uniqueFilterEnabled, faceCountFilterEnabled, faceOccurrenceFilterEnabled, sizeFilterEnabled, genderFilterEnabled, view, }) => { function onThumbDoubleClickWithStop(e) { e.stopPropagation(); if (controllersAreVisible) { if (view === VIEW.PLAYERVIEW) { onSelect(); } else { onThumbDoubleClick(); } } } function onSelectWithStop(e) { e.stopPropagation(); if (controllersAreVisible) { onSelect(); } } function onOverWithStop(e) { // e.stopPropagation(); // check if function is not null (passed from thumbgrid) if (onOver) { onOver(e); } } function onOutWithStop(e) { e.stopPropagation(); // check if function is not null (passed from thumbgrid) // if (onOut) { // onOut(e); // } } return ( <div ref={inputRefThumb} role="button" tabIndex={index} onMouseEnter={onOverWithStop} onMouseLeave={onOutWithStop} onFocus={onOverWithStop} onBlur={onOutWithStop} onClick={onSelectWithStop} onKeyPress={onSelectWithStop} onDoubleClick={onThumbDoubleClickWithStop} id={`thumb${indexForId}`} className={`${styles.gridItem} ${ view === VIEW.PLAYERVIEW && selected && !(keyObject.altKey || keyObject.shiftKey) ? styles.gridItemSelected : '' }`} width={`${thumbWidth}px`} height={`${thumbHeight}px`} style={{ // width: thumbWidth, margin, outlineWidth: margin, borderRadius: `${selected && view === VIEW.PLAYERVIEW ? 0 : Math.ceil(borderRadius)}px`, // Math.ceil so the edge is not visible underneath the image backgroundColor: transparentThumb || thumbImageObjectUrl === undefined || thumbImageObjectUrl === 'blob:file:///fakeURL' ? color : undefined, }} > <img data-tid={`thumbImg_${thumbId}`} src={ transparentThumb ? transparent : thumbImageObjectUrl !== undefined ? thumbImageObjectUrl : base64 !== undefined ? `data:image/jpeg;base64, ${base64}` : transparent } id={`thumbImage${indexForId}`} className={`${styles.image} ${dim ? styles.dim : ''}`} alt="" width={`${thumbWidth}px`} height={`${thumbHeight}px`} style={{ filter: `${controllersAreVisible ? 'brightness(80%)' : ''}`, opacity: hidden ? '0.2' : facesArray !== undefined && defaultShowFaceRect ? '0.7' : '1.0', borderRadius: `${selected && view === VIEW.PLAYERVIEW ? 0 : borderRadius}px`, }} /> {facesArray !== undefined && !controllersAreVisible && defaultShowFaceRect && ( <AllFaces facesArray={facesArray} thumbWidth={thumbWidth} thumbHeight={thumbHeight} ageFilterEnabled={ageFilterEnabled} uniqueFilterEnabled={uniqueFilterEnabled} faceCountFilterEnabled={faceCountFilterEnabled} faceOccurrenceFilterEnabled={faceOccurrenceFilterEnabled} sizeFilterEnabled={sizeFilterEnabled} genderFilterEnabled={genderFilterEnabled} isExpanded={isExpanded} /> )} {thumbInfoValue !== undefined && ( <div data-tid={`thumbInfoText_${thumbId}`} className={`${styles.frameinfo} ${styles[frameinfoPosition]}`} style={{ margin: frameinfoMargin, transform: thumbCSSTranslate, backgroundColor: frameninfoBackgroundColor, color: frameinfoColor, }} > {thumbInfoValue} </div> )} <div style={{ display: controllersAreVisible ? 'block' : 'none', }} > {sheetType !== SHEET_TYPE.SCENES && ( <DragHandle width={thumbWidth - 1} // shrink it to prevent rounding issues height={thumbHeight - 1} thumbId={thumbId} /> )} </div> </div> ); }, ); Thumb.defaultProps = { controllersAreVisible: false, dim: undefined, hidden: false, index: undefined, indexForId: undefined, keyObject: {}, onOver: null, onSelect: null, selected: false, thumbImageObjectUrl: undefined, thumbInfoValue: undefined, }; Thumb.propTypes = { borderRadius: PropTypes.number.isRequired, color: PropTypes.string.isRequired, controllersAreVisible: PropTypes.bool, dim: PropTypes.object, hidden: PropTypes.bool, inputRefThumb: PropTypes.object, keyObject: PropTypes.object, margin: PropTypes.string.isRequired, onOver: PropTypes.func, onSelect: PropTypes.func, onThumbDoubleClick: PropTypes.func, selected: PropTypes.bool, sheetType: PropTypes.string.isRequired, index: PropTypes.number, indexForId: PropTypes.number, thumbImageObjectUrl: PropTypes.string, thumbInfoValue: PropTypes.string, thumbWidth: PropTypes.number.isRequired, }; export default Thumb; <|start_filename|>app/components/Timeline.js<|end_filename|> import React, { useCallback, useEffect, useRef, useState } from 'react'; import PropTypes from 'prop-types'; import { TIMELINE_PLAYHEAD_MINIMUM_WIDTH, TIMELINE_SCENE_MINIMUM_WIDTH, } from '../utils/constants'; import { getBucketValueOfPercentage, } from '../utils/utils'; import styles from './Timeline.css'; // import stylesPop from './Popup.css'; const Timeline = ({ playHeadPositionPercSelection, containerWidth, playHeadPositionPerc, sheetType, updateTimeFromPosition, updateTimeFromPositionSelection, frameCount, currentScene, lowestFrame, highestFrame, }) => { // initialise refs const refTimeline = useRef(null); const refTimelineSelection = useRef(null); // initialise react hooks const [leftBoundsTimeline, setLeftBoundsTimeline] = useState(0); const [widthTimeline, setWidthTimeline] = useState(0); const [mouseStartDragInsideTimelineSelection, setMouseStartDragInsideTimelineSelection] = useState(false); const [mouseStartDragInsideTimeline, setMouseStartDragInsideTimeline] = useState(false); const sceneInOutObject = getSceneInOutOnTimelineObject(frameCount, containerWidth, currentScene, lowestFrame, highestFrame); // componentDidMount // initial call to getBoundingClientRect useEffect(() => { setLeftBoundsTimeline(refTimelineSelection.current.getBoundingClientRect().left); setWidthTimeline(refTimelineSelection.current.getBoundingClientRect().width); }); // componentDidMount // add updating getBoundingClientRect on resize useEffect(() => { const handleResize = () => { setLeftBoundsTimeline(refTimelineSelection.current.getBoundingClientRect().left); setWidthTimeline(refTimelineSelection.current.getBoundingClientRect().width); } window.addEventListener('resize', handleResize); return () => { window.removeEventListener('resize', handleResize); }; }); function onTimelineSelectionClick(e) { const xPerc = ((e.clientX - leftBoundsTimeline) * 1.0) / (widthTimeline - widthOfSingleFrameSelection); const xPercBucket = getBucketValueOfPercentage(xPerc, sceneInOutObject.length); updateTimeFromPositionSelection(xPercBucket); } function onTimelineClick(e) { const xPerc = ((e.clientX - leftBoundsTimeline) * 1.0) / (widthTimeline - widthOfSingleFrame); updateTimeFromPosition(xPerc); } function onTimelineMouseOver(e) { if (mouseStartDragInsideTimeline) { // check if dragging over timeline const xPerc = ((e.clientX - leftBoundsTimeline) * 1.0) / (widthTimeline - widthOfSingleFrame); updateTimeFromPosition(xPerc); } if (mouseStartDragInsideTimelineSelection) { // check if dragging over timeline const xPerc = ((e.clientX - leftBoundsTimeline) * 1.0) / (widthTimeline - widthOfSingleFrameSelection); const xPercBucket = getBucketValueOfPercentage(xPerc, sceneInOutObject.length); updateTimeFromPositionSelection(xPercBucket); } } function onTimelineSelectionDrag() { setMouseStartDragInsideTimelineSelection(true); } function onTimelineDrag() { setMouseStartDragInsideTimeline(true); } function onTimelineDragStop() { setMouseStartDragInsideTimeline(false); setMouseStartDragInsideTimelineSelection(false); } function onTimelineExit() { if (mouseStartDragInsideTimeline) { setMouseStartDragInsideTimeline(false); } if (mouseStartDragInsideTimelineSelection) { setMouseStartDragInsideTimelineSelection(false); } } function getSceneInOutOnTimelineObject(frameCountOfMovie, widthInPixel, scene, lowestFrame, highestFrame) { let inPoint = 0; let outPoint = 0; let length = 0; if (scene !== undefined) { inPoint = scene.start; outPoint = scene.start + scene.length - 1; length = scene.length; } const inPointPositionOnTimeline = ((widthInPixel * 1.0) / frameCountOfMovie) * inPoint; const outPointPositionOnTimeline = ((widthInPixel * 1.0) / frameCountOfMovie) * outPoint; const selectionWidthOnTimeLine = Math.max( outPointPositionOnTimeline - inPointPositionOnTimeline, TIMELINE_SCENE_MINIMUM_WIDTH ); const lowestFrameOnTimeline = ((widthInPixel * 1.0) / frameCountOfMovie) * lowestFrame; const highestFrameOnTimeline = ((widthInPixel * 1.0) / frameCountOfMovie) * highestFrame; const cutWidthOnTimeLine = Math.max( highestFrameOnTimeline - lowestFrameOnTimeline, TIMELINE_SCENE_MINIMUM_WIDTH ); return { inPoint, outPoint, length, inPointPositionOnTimeline, selectionWidthOnTimeLine, lowestFrameOnTimeline, cutWidthOnTimeLine, } } const widthOfSingleFrameSelection = Math.max(Math.floor(containerWidth / sceneInOutObject.length), TIMELINE_PLAYHEAD_MINIMUM_WIDTH); const playHeadPositionSelection = Math.floor(playHeadPositionPercSelection * (widthTimeline - widthOfSingleFrameSelection)); const widthOfSingleFrame = Math.max((containerWidth * 1.0 / frameCount), TIMELINE_PLAYHEAD_MINIMUM_WIDTH); const playHeadPosition = playHeadPositionPerc * (widthTimeline - widthOfSingleFrame); return ( <div className={`${styles.container}`} style={{ }} onMouseMove={onTimelineMouseOver} onMouseLeave={onTimelineExit} onMouseUp={onTimelineDragStop} > <div id="timeLineSelection" className={`${styles.timelineWrapperSelection}`} onClick={onTimelineSelectionClick} onMouseDown={onTimelineSelectionDrag} onMouseUp={onTimelineDragStop} ref={refTimelineSelection} style={{ // backgroundImage: `url(${timelineFrameBackground})`, backgroundImage: `url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='${widthOfSingleFrameSelection*2}' height='64' fill='none'><rect opacity='0.015' width='${widthOfSingleFrameSelection}' height='64' fill='white'/></svg>")`, }} > <div className={`${styles.timelinePlayheadSelection}`} style={{ left: Number.isFinite(playHeadPositionSelection) ? playHeadPositionSelection : 0, width: Number.isFinite(widthOfSingleFrameSelection) ? widthOfSingleFrameSelection : 0, }} /> </div> <div id="timeLine" className={`${styles.timelineWrapper}`} onClick={onTimelineClick} onMouseDown={onTimelineDrag} onMouseUp={onTimelineDragStop} ref={refTimeline} > <div className={`${styles.timelineCut}`} style={{ left: Number.isFinite(sceneInOutObject.lowestFrameOnTimeline) ? sceneInOutObject.lowestFrameOnTimeline : 0, width: Number.isFinite(sceneInOutObject.cutWidthOnTimeLine) ? sceneInOutObject.cutWidthOnTimeLine : 0, }} /> <div className={`${styles.timelineCutSelection}`} style={{ left: Number.isFinite(sceneInOutObject.inPointPositionOnTimeline) ? sceneInOutObject.inPointPositionOnTimeline : 0, width: Number.isFinite(sceneInOutObject.selectionWidthOnTimeLine) ? sceneInOutObject.selectionWidthOnTimeLine : 0, }} /> <div className={`${styles.timelinePlayhead}`} style={{ left: Number.isFinite(playHeadPosition) ? playHeadPosition : 0, }} /> </div> </div> ); }; Timeline.defaultProps = { }; Timeline.propTypes = { }; export default Timeline; <|start_filename|>scripts/includeInDist.js<|end_filename|> import path from 'path'; import log from 'electron-log'; const shell = require('shelljs'); // as the dist folder is not synced on github, we copy files into it before packaging log.info('running includeInDist script to copy some files into the dist folder for later packaging'); // set variables const moviePrintDir = shell.pwd().stdout; const distDir = path.resolve(moviePrintDir, 'app/dist/'); const resourcesDir = path.resolve(moviePrintDir, 'resources/'); // log.debug(moviePrintDir); // log.debug(distDir); // log.debug(resourcesDir); // copy files shell.set('-v'); // verbose shell.mkdir('-p', distDir); // create folder if it does not exist yet shell.cp('-nf', path.resolve(resourcesDir, 'font/Franchise-Bold.woff'), distDir); shell.cp('-nfr', path.resolve(resourcesDir, 'weights/'), distDir); <|start_filename|>app/worker.js<|end_filename|> import React from 'react'; import { render } from 'react-dom'; import { AppContainer } from 'react-hot-loader'; import { ActionCreators as UndoActionCreators } from 'redux-undo'; import WorkerRoot from './containers/WorkerRoot'; import { configureStore, history } from './store/configureStore'; const store = configureStore(); render( <AppContainer> <WorkerRoot store={store} history={history} /> </AppContainer>, document.getElementById('worker') ); if (module.hot) { module.hot.accept('./containers/WorkerRoot', () => { const NextWorkerRoot = require('./containers/WorkerRoot').default; // eslint-disable-line global-require render( <AppContainer> <NextWorkerRoot store={store} history={history} /> </AppContainer>, document.getElementById('worker') ); }); } <|start_filename|>app/utils/queue.js<|end_filename|> /* eslint func-names: ["error", "never"] */ // import log from 'electron-log'; // the queue adds all new ones in front // const q = new Queue(): // q.add(1); // q.add(2); // q.add(3); // console.log(q); // // [3,2,1] function Queue() { this.data = []; } Queue.prototype.add = function(record) { this.data.unshift(record); } Queue.prototype.addArray = function(arrayOfRecords) { const combinedArray = [...this.data, ...arrayOfRecords]; this.data = combinedArray; } Queue.prototype.removeFirst = function() { return this.data.shift(); } Queue.prototype.removeFirstMany = function(amount) { return this.data.splice(0, amount); } Queue.prototype.removeLastMany = function(amount) { return this.data.splice(amount * -1, amount); } Queue.prototype.removeLast = function() { return this.data.pop(); } Queue.prototype.clear = function() { this.data = []; } Queue.prototype.first = function() { return this.data[0]; } Queue.prototype.last = function() { return this.data[this.data.length - 1]; } Queue.prototype.size = function() { return this.data.length; } export default Queue; <|start_filename|>app/containers/App.css<|end_filename|> .Site { display: flex; flex-direction: column; height: 100vh; } .SiteHeader { flex: 0 0 auto; background-color: #3b3b3b; height: 3em; } .SiteContent { flex: 1 1 auto; position: relative;/* need this to position inner content */ overflow-y: auto; background-color: #1e1e1e; } .SiteFooter { flex: 0 0 auto; background-color: #3b3b3b; height: 3em; } .dropzonehide { display: none; /*background-color: red;*/ } .dropzoneshowAccept { /* outline-color: #00FF00; */ background-color: rgba(0,134,0,0.7) !important; } .dropzoneshowReject { /* outline-color: #FF0000; */ background-color: rgba(134,0,0,0.7) !important; } .dropzoneshow { /* outline-style: solid; outline-color: #0c3158; outline-width: 15px; outline-offset: -15px; */ position: fixed; /* Stay in place */ left: 0; top: 0; width: 100%; /* Full width */ height: 100%; /* Full height */ overflow: auto; /* Enable scroll if needed */ /* background-color: rgba(255,80,6,0.7); */ background-color: rgb(27,28,29); z-index: 999; } .dropzoneshowContent { position: absolute; top: 50%; left: 50%; right: auto; bottom: auto; margin-right: -50%; transform: translate(-50%, -50%); outline: 0; font-size: 100px; font-weight: 600; line-height: 100px; text-align: center; color: #fff; letter-spacing: 1px; margin: auto; font-family: 'Franchise', 'Roboto Condensed'; } .dropZoneSubline { font-size: 40px; } .SidebarPushable { /*overflow-y: scroll;*/ /*overflow-x: hidden;*/ } .ItemMain { overflow-x: auto; transition: margin 0.5s ease; clear: both; display: flex; } .ItemMainMinHeight { min-height: calc(100vh); } .ItemVideoPlayer { transition: all 0.5s ease; position: fixed; /* left: 50%; */ /* right: auto; */ /* bottom: auto; */ /* margin-right: -50%; */ } .ItemMainEdit { /* border: 5px solid #8f542e; */ } .ItemMainTopAnim { margin-top: 350px; } .ItemMainLeftAnim { margin-left: 350px; } .ItemMainRightAnim { margin-right: 350px; } .openCloseMovieList { position: fixed; z-index: 10; transition: transform 0.5s ease, left 0.5s ease; left: 300px; top: calc(50% - 28px); background-color: rgba(255, 80, 6, 0.5) !important; height: 56px; width: 80px; border-radius: 40px; cursor: pointer; } .openCloseMovieList:hover { background-color: rgba(255, 80, 6, 1.0) !important; left: 315px; } .openCloseSettings { position: fixed; z-index: 10; transition: transform 0.5s ease, left 0.5s ease; left: -30px; top: calc(50% - 28px); background-color: rgba(255, 80, 6, 0.5) !important; height: 56px; width: 80px; border-radius: 40px; cursor: pointer; } .openCloseSettings:hover { background-color: rgba(255, 80, 6, 1.0) !important; left: -45px; } .ItemSideBar { min-height: calc(100vh); /* background: linear-gradient(270deg, #444242 0%, #3B3B3B 100%); */ background: rgba(0,0,0,0.8); width: 350px; position: fixed; transition: transform 0.5s ease; z-index: 102; overflow-y: auto; overflow-x: hidden; max-height: 100%; box-shadow: inset 0 0 64px rgba(0,0,0,0.5); } .ItemMovielist { transform: translate(-350px, 0); /* direction:rtl; /* move scrollbar to the left (needs compensation on next level) */ } .ItemSettings { transform: translate(100vw, 0); } .ItemMovielistAnim{ transform: translate(0, 0); } .ItemSettingsAnim{ transform: translate(calc(100vw - 350px), 0); } .ItemMainStartupContainer{ margin: auto; width: 100%; display: flex; align-items: baseline; } .ItemMainStartupItem{ width: 300px; margin: auto; text-align: center; font-size: 40px; font-weight: 600; line-height: 40px; text-align: center; color: #fff; letter-spacing: 1px; margin: auto; font-family: 'Franchise', 'Roboto Condensed'; } /* Remove scroll on the body when react-modal is open */ .ReactModal__Body--open { overflow: hidden; } .ReactModalOverlay { position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0, 0, 0, 0.75); } .ReactModalContent { position: absolute; top: 50%; left: 50%; right: auto; bottom: auto; margin-right: -50%; transform: translate(-50%, -50%); outline: 0; box-shadow: 0px 0px 0px 20px rgba(255, 255, 255, 0.1); /* border: 1px solid #ccc; */ /* background: #fff; */ /* overflow: auto; */ /* border-radius: 4px; */ /* outline: none; */ /* padding: 20px */ } .chart { position: fixed; /* Stay in place */ left: 50%; top: 50%; width: 100%; background-color: rgba(0, 0, 0, 1); z-index: 3000 !important; transform: translate(-50%, -50%); } .feedbackFormModal { height: 90vh; width: 50vw !important; min-width: 680px; transform: translate(-50%); left: 50% !important } .feedbackFormWebView { height: 85vh; } .smallInfo { color: rgba(0,0,0,.87); } .editTransformCanvasContainer { margin: auto !important; } .editTransformCanvas { margin: auto; display: block; } <|start_filename|>app/components/SceneGrid.js<|end_filename|> // @flow import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { SortableContainer, SortableElement } from 'react-sortable-hoc'; import { Icon, Popup } from 'semantic-ui-react'; import Scene from './Scene'; import styles from './SceneGrid.css'; import stylesApp from '../containers/App.css'; import stylesPop from './Popup.css'; import { getWidthOfSingleRow, getPreviousScenes, getNextScenes } from '../utils/utils'; import { VIDEOPLAYER_FIXED_PIXEL_PER_FRAME_RATIO, VIDEOPLAYER_SCENE_MARGIN, VIEW, SHEET_TYPE, } from '../utils/constants'; const SortableScene = SortableElement(Scene); class SceneGrid extends Component { constructor(props) { super(props); this.state = { controllersVisible: undefined, scenesToDim: [], }; this.resetHover = this.resetHover.bind(this); } componentWillMount() {} componentDidMount() {} componentDidUpdate(prevProps) {} resetHover() { this.setState({ scenesToDim: [], controllersVisible: undefined, }); } render() { const { file, currentSheetId, minSceneLength, scaleValueObject, scenes, selectedThumbsArray, settings, sheetType, thumbs, view, } = this.props; const { scenesInRows } = scaleValueObject; const isPlayerView = view !== VIEW.STANDARDVIEW; const breakOnWidth = isPlayerView || settings.defaultTimelineViewFlow; const thumbMarginTimeline = isPlayerView ? VIDEOPLAYER_SCENE_MARGIN : Math.floor(scaleValueObject.thumbMarginTimeline); const rowHeight = scaleValueObject.newMoviePrintTimelineRowHeight; const rowHeightForPlayer = scaleValueObject.videoPlayerHeight / 2 - settings.defaultBorderMargin * 3; const realWidth = rowHeight / scaleValueObject.aspectRatioInv; const realWidthForPlayer = rowHeightForPlayer / scaleValueObject.aspectRatioInv; const newPixelPerFrameRatio = isPlayerView ? VIDEOPLAYER_FIXED_PIXEL_PER_FRAME_RATIO : scaleValueObject.newMoviePrintTimelinePixelPerFrameRatio; // set fixed pixel per frame ratio for player const indexRowArray = scenesInRows.map(item => item.index); // for VideoPlayer const widthOfSingleRow = getWidthOfSingleRow(scenes, thumbMarginTimeline, newPixelPerFrameRatio, minSceneLength) + realWidthForPlayer + thumbMarginTimeline; return ( <div data-tid="sceneGridDiv" className={styles.grid} id="SceneGrid" style={ { // paddingLeft: isPlayerView ? '48px' : undefined, } } > <div data-tid="sceneGridBodyDiv" style={{ width: isPlayerView ? widthOfSingleRow : undefined, // if VideoPlayer then single row }} > {scenes.map((scene, index) => { // minutes per row idea const selected = selectedThumbsArray.length > 0 ? selectedThumbsArray.some(item => item.thumbId === scene.sceneId) : false; const rWidth = isPlayerView ? realWidthForPlayer : realWidth; const width = selected ? Math.floor(rWidth) : Math.floor(Math.max(newPixelPerFrameRatio * scene.length, newPixelPerFrameRatio * minSceneLength)); // console.log(width); let doLineBreak = false; if (indexRowArray.findIndex(item => item === index - 1) > -1) { doLineBreak = true; // rowCounter += 1; } let thumb; if (thumbs !== undefined) { thumb = thumbs.find(foundThumb => foundThumb.thumbId === scene.sceneId); } return ( <SortableScene hidden={scene.hidden} controllersAreVisible={ scene.sceneId === undefined ? false : scene.sceneId === this.state.controllersVisible } selected={selected} doLineBreak={!breakOnWidth && doLineBreak} sheetView={this.props.sheetView} view={view} keyObject={this.props.keyObject} indexForId={index} index={index} key={scene.sceneId} sceneId={scene.sceneId} margin={thumbMarginTimeline} dim={this.state.scenesToDim.find(sceneToDim => sceneToDim.sceneId === scene.sceneId)} // only allow expanding of scenes which are not already large enough and deselecting allowSceneToBeSelected={isPlayerView || selected || width < realWidth * 0.95} // use minimum value to make sure that scene does not disappear thumbWidth={Math.max(1, width)} thumbHeight={isPlayerView ? rowHeightForPlayer : Math.max(1, rowHeight)} hexColor={`#${( (1 << 24) + (Math.round(scene.colorArray[0]) << 16) + (Math.round(scene.colorArray[1]) << 8) + Math.round(scene.colorArray[2]) ) .toString(16) .slice(1)}`} transparentThumb={!settings.defaultShowImages} thumbImageObjectUrl={ // used for data stored in IndexedDB this.props.useBase64 === undefined && this.props.objectUrlObjects !== undefined && thumb !== undefined ? this.props.objectUrlObjects[thumb.frameId] : undefined } base64={ // used for live captured data when saving movieprint this.props.useBase64 !== undefined && this.props.objectUrlObjects !== undefined && thumb !== undefined ? this.props.objectUrlObjects[thumb.frameId] : undefined } onOver={() => { // only setState if controllersVisible has changed if (this.state.controllersVisible !== scene.sceneId) { this.setState({ controllersVisible: scene.sceneId, }); } }} onOut={this.resetHover} onThumbDoubleClick={this.props.onThumbDoubleClick} onToggle={ scene.sceneId !== this.state.controllersVisible ? null : () => this.props.onToggleClick(file.id, scene.sceneId) } onHideBefore={ scene.sceneId !== this.state.controllersVisible ? null : () => { const previousScenes = getPreviousScenes(scenes, scene.sceneId); const previousSceneIds = previousScenes.map(s => s.sceneId); this.props.onHideBeforeAfterClick(file.id, currentSheetId, previousSceneIds); this.props.onDeselectClick(); this.resetHover(); } } onHideAfter={ scene.sceneId !== this.state.controllersVisible ? null : () => { const nextScenes = getNextScenes(scenes, scene.sceneId); const nextSceneIds = nextScenes.map(s => s.sceneId); this.props.onHideBeforeAfterClick(file.id, currentSheetId, nextSceneIds); this.props.onDeselectClick(); this.resetHover(); } } onHoverInPoint={ scene.sceneId !== this.state.controllersVisible ? null : () => { const previousScenes = getPreviousScenes(scenes, scene.sceneId); this.setState({ scenesToDim: getPreviousScenes(scenes, scene.sceneId), }); } } onHoverOutPoint={ scene.sceneId !== this.state.controllersVisible ? null : () => { this.setState({ scenesToDim: getNextScenes(scenes, scene.sceneId), }); } } onLeaveInOut={ scene.sceneId !== this.state.controllersVisible ? null : () => { this.setState({ scenesToDim: [], }); } } onSelect={ scene.sceneId !== this.state.controllersVisible ? null : !isPlayerView && selected ? () => { this.props.onDeselectClick(); } : () => { this.props.onSelectClick(scene.sceneId, scene.start); } } onCutBefore={ scene.sceneId !== this.state.controllersVisible ? null : () => { this.props.onJumpToCutSceneClick(file, scene.sceneId, 'before'); } } onCutAfter={ scene.sceneId !== this.state.controllersVisible ? null : () => { this.props.onJumpToCutSceneClick(file, scene.sceneId, 'after'); } } onExpand={ scene.sceneId !== this.state.controllersVisible ? null : () => { this.props.onExpandClick(file, scene.sceneId, currentSheetId); } } inputRefThumb={ this.props.selectedThumbsArray.length !== 0 && this.props.selectedThumbsArray[0].thumbId === scene.sceneId ? this.props.inputRefThumb : undefined } // for the thumb scrollIntoView function /> ); })} </div> </div> ); } } SceneGrid.defaultProps = { scenes: [], selectedThumbsArray: [], scenesToDim: [], }; SceneGrid.propTypes = { scenes: PropTypes.array, selectedThumbsArray: PropTypes.array, scenesToDim: PropTypes.array, }; const SortableSceneGrid = SortableContainer(SceneGrid); export default SortableSceneGrid; <|start_filename|>app/components/AllFaces.js<|end_filename|> /* eslint no-param-reassign: ["error"] */ /* eslint no-nested-ternary: "off" */ // @flow import React from 'react'; // import PropTypes from 'prop-types'; // import { Popup } from 'semantic-ui-react'; // import { SHEET_TYPE, VIEW } from '../utils/constants'; import styles from './ThumbGrid.css'; const AllFaces = ({ facesArray, thumbWidth, thumbHeight, ageFilterEnabled, uniqueFilterEnabled, faceCountFilterEnabled, faceOccurrenceFilterEnabled, sizeFilterEnabled, genderFilterEnabled, isExpanded, thumbHover = false, }) => facesArray.map(face => { if (!face.faceIsHidden) { return ( <FaceRect key={face.faceId} ageFilterEnabled={ageFilterEnabled} uniqueFilterEnabled={uniqueFilterEnabled} faceCountFilterEnabled={faceCountFilterEnabled} faceOccurrenceFilterEnabled={faceOccurrenceFilterEnabled} sizeFilterEnabled={sizeFilterEnabled} genderFilterEnabled={genderFilterEnabled} isExpanded={isExpanded} face={face} thumbWidth={thumbWidth} thumbHeight={thumbHeight} thumbHover={thumbHover} /> ); } return undefined; }); const FaceRect = React.memo( ({ face: { box, ...faceExceptForBox }, thumbWidth, thumbHeight, ageFilterEnabled, uniqueFilterEnabled, faceCountFilterEnabled, faceOccurrenceFilterEnabled, sizeFilterEnabled, genderFilterEnabled, isExpanded, thumbHover, }) => { const left = box.x * thumbWidth; const top = box.y * thumbHeight; const width = box.width * thumbWidth; const height = box.height * thumbHeight; const cornerLength = Math.max(2, Math.min(width, height) / 8) * -1; // embedding styles directly as html2Canvas ignores css styling of SVGs const svgStylingFill = 'none'; const svgStylingStroke = 'rgba(255,80,6,1)'; const svgStylingStrokeWidth = '1'; const leftCornerLength = Math.max(1, left - cornerLength); const topCornerLength = Math.max(1, top - cornerLength); const leftWidth = Math.min(thumbWidth - 1, left + width); const topHeight = Math.min(thumbHeight - 1, top + height); const topHeightCornerLength = Math.min(thumbHeight - 1, topHeight + cornerLength); const leftWidthCornerLength = Math.min(thumbWidth - 1, leftWidth + cornerLength); const polylineLine0 = `${leftCornerLength}, ${top}, ${left}, ${top}, ${left}, ${topCornerLength}`; const polylineLine1 = `${leftWidth}, ${topCornerLength}, ${leftWidth}, ${top}, ${leftWidthCornerLength}, ${top}`; const polylineLine2 = `${leftCornerLength}, ${topHeight}, ${left}, ${topHeight}, ${left}, ${topHeightCornerLength}`; const polylineLine3 = `${leftWidth}, ${topHeightCornerLength}, ${leftWidth}, ${topHeight}, ${leftWidthCornerLength}, ${topHeight}`; return ( <> <div className={`${thumbHover ? styles.faceHover : ''} ${styles.faceRect}`} title={JSON.stringify(faceExceptForBox)} style={{ width: `${box.width * thumbWidth}px`, height: `${box.height * thumbHeight}px`, left: `${box.x * thumbWidth}px`, top: `${box.y * thumbHeight}px`, }} /> <div className={styles.faceRectSVG} title={JSON.stringify(faceExceptForBox)}> <svg width={thumbWidth} height={thumbHeight}> <polyline points={polylineLine0} fill={svgStylingFill} stroke={svgStylingStroke} strokeWidth={svgStylingStrokeWidth} /> <polyline points={polylineLine1} fill={svgStylingFill} stroke={svgStylingStroke} strokeWidth={svgStylingStrokeWidth} /> <polyline points={polylineLine2} fill={svgStylingFill} stroke={svgStylingStroke} strokeWidth={svgStylingStrokeWidth} /> <polyline points={polylineLine3} fill={svgStylingFill} stroke={svgStylingStroke} strokeWidth={svgStylingStrokeWidth} /> </svg> </div> {thumbHover && ( <div className={styles.faceRectTag} style={{ left: `${box.x * thumbWidth + box.width * thumbWidth}px`, top: `${box.y * thumbHeight}px`, }} > {!isExpanded && <div className={`${uniqueFilterEnabled || faceOccurrenceFilterEnabled ? styles.opacity100 : ''}`} >{`found: ${faceExceptForBox.faceOccurrence}x`}</div>} <div className={`${sizeFilterEnabled ? styles.opacity100 : ''}`}>{`size: ${faceExceptForBox.size}%`}</div> <div className={`${ageFilterEnabled ? styles.opacity100 : ''}`}>{`age: ${faceExceptForBox.age}`}</div> <div className={`${genderFilterEnabled ? styles.opacity100 : ''}`}>{`${ faceExceptForBox.gender === 'female' ? '\u2640' : '\u2642' }`}</div> <br /> </div> )} </> ); }, ); // Thumb.defaultProps = { // controllersAreVisible: false, // dim: undefined, // hidden: false, // index: undefined, // indexForId: undefined, // keyObject: {}, // onOver: null, // onSelect: null, // selected: false, // thumbImageObjectUrl: undefined, // thumbInfoValue: undefined, // }; // // Thumb.propTypes = { // aspectRatioInv: PropTypes.number.isRequired, // borderRadius: PropTypes.number.isRequired, // color: PropTypes.string.isRequired, // controllersAreVisible: PropTypes.bool, // dim: PropTypes.object, // hidden: PropTypes.bool, // inputRefThumb: PropTypes.object, // keyObject: PropTypes.object, // margin: PropTypes.string.isRequired, // onOver: PropTypes.func, // onSelect: PropTypes.func, // onThumbDoubleClick: PropTypes.func, // selected: PropTypes.bool, // sheetType: PropTypes.string.isRequired, // index: PropTypes.number, // indexForId: PropTypes.number, // thumbImageObjectUrl: PropTypes.string, // thumbInfoValue: PropTypes.string, // thumbWidth: PropTypes.number.isRequired, // }; export default AllFaces; <|start_filename|>app/utils/getScaleValueObject.js<|end_filename|> import log from 'electron-log'; import { DEFAULT_COLUMN_COUNT, DEFAULT_MIN_MOVIEPRINTWIDTH_MARGIN, DEFAULT_MOVIE_HEIGHT, DEFAULT_MOVIE_WIDTH, DEFAULT_THUMB_COUNT, DEFAULT_VIDEO_PLAYER_CONTROLLER_HEIGHT, MARGIN_ADJUSTMENT_SCALE, PAPER_ADJUSTMENT_SCALE, SCALE_VALUE_ARRAY, VIDEOPLAYER_THUMB_MARGIN, VIEW, ZOOM_SCALE, } from './constants'; import { getScenesInRows, getPixelPerFrameRatio } from './utils'; const getScaleValueObject = ( file, settings, visibilitySettings, columnCount = DEFAULT_COLUMN_COUNT, thumbCount = DEFAULT_THUMB_COUNT, containerWidth, containerHeight = 99999, // very high value so it is not taken into account when not set zoomScale = SCALE_VALUE_ARRAY[ZOOM_SCALE], showPaperPreview = false, forPrinting = false, sceneArray = [], secondsPerRow = 120.0, newMovieAspectRatioInv = undefined, // used when updating aspectRatioInv of the currentFileId ) => { const { defaultBorderMargin, defaultBorderRadiusRatio, defaultHeaderHeightRatio, defaultMarginRatio, defaultMoviePrintWidth, defaultPaperAspectRatioInv, defaultRoundedCorners, defaultScrubContainerMaxHeightRatio, defaultScrubWindowMargin, defaultScrubWindowWidthRatio, defaultShowDetailsInHeader, defaultShowHeader, defaultShowPathInHeader, defaultShowTimelineInHeader, defaultThumbnailScale, defaultTimelineViewMinDisplaySceneLengthInFrames, defaultTimelineViewWidthScale, } = settings; const { defaultView } = visibilitySettings; const movieWidth = file !== undefined && file.width !== undefined ? file.width : DEFAULT_MOVIE_WIDTH; const movieHeight = file !== undefined && file.height !== undefined ? file.height : DEFAULT_MOVIE_HEIGHT; const movieAspectRatioInv = (newMovieAspectRatioInv !== undefined && newMovieAspectRatioInv !== null) ? newMovieAspectRatioInv : (file !== undefined && file.transformObject !== undefined && file.transformObject.aspectRatioInv !== undefined && file.transformObject.aspectRatioInv !== null) ? file.transformObject.aspectRatioInv : (movieHeight * 1.0) / movieWidth; const rowCount = Math.ceil(thumbCount / columnCount); const showPlayerView = defaultView === VIEW.PLAYERVIEW; const containerAspectRatioInv = (containerHeight * 1.0) / containerWidth; // headerHeight gets increased depending on how much information is shown inside const headerHeightMultiplier = 1 + (defaultShowPathInHeader + defaultShowDetailsInHeader + defaultShowTimelineInHeader) / 3.0; const headerHeight = defaultShowHeader ? movieHeight * defaultHeaderHeightRatio * headerHeightMultiplier * defaultThumbnailScale : 0; const logoHeight = movieHeight * defaultHeaderHeightRatio * defaultThumbnailScale; const thumbWidth = movieWidth * defaultThumbnailScale; const thumbMargin = movieWidth * defaultMarginRatio * defaultThumbnailScale; const borderRadius = defaultRoundedCorners ? movieWidth * defaultBorderRadiusRatio * defaultThumbnailScale : 0; const thumbnailWidthPlusMargin = thumbWidth + thumbMargin * 2; const thumbnailHeightPlusMargin = thumbWidth * movieAspectRatioInv + thumbMargin * 2; const originalMoviePrintWidth = columnCount * thumbnailWidthPlusMargin + thumbMargin; const originalMoviePrintWidthForPrinting = columnCount * thumbnailWidthPlusMargin - thumbMargin; const originalMoviePrintHeightBody = rowCount * thumbnailHeightPlusMargin; const originalMoviePrintHeight = headerHeight + thumbMargin * 2 + originalMoviePrintHeightBody; const moviePrintAspectRatioInv = (originalMoviePrintHeight * 1.0) / originalMoviePrintWidth; // for playerView const videoHeight = (containerHeight * 2) / 3 - DEFAULT_VIDEO_PLAYER_CONTROLLER_HEIGHT; const videoWidth = videoHeight / movieAspectRatioInv; let videoPlayerHeight = videoHeight + DEFAULT_VIDEO_PLAYER_CONTROLLER_HEIGHT; let videoPlayerWidth = videoWidth; if (videoWidth > containerWidth) { videoPlayerWidth = containerWidth - defaultBorderMargin * 2; videoPlayerHeight = videoPlayerWidth * movieAspectRatioInv + DEFAULT_VIDEO_PLAYER_CONTROLLER_HEIGHT; } const thumbnailHeightForThumbView = videoPlayerHeight / 2 - defaultBorderMargin * 3; const thumbnailWidthForThumbView = thumbnailHeightForThumbView / movieAspectRatioInv; const borderRadiusForThumbView = thumbnailWidthForThumbView * defaultBorderRadiusRatio; const thumbMarginForThumbView = VIDEOPLAYER_THUMB_MARGIN; // const thumbMarginForThumbView = Math.max(2, thumbnailWidthForThumbView * defaultMarginRatio); const thumbnailWidthPlusMarginForThumbView = thumbnailWidthForThumbView + thumbMarginForThumbView * 2; const moviePrintWidthForThumbView = thumbCount * thumbnailWidthPlusMarginForThumbView + thumbnailWidthForThumbView / 2; // only one row // for playerView // for scrubView const scrubContainerHeight = Math.min( Math.floor(containerHeight * defaultScrubContainerMaxHeightRatio), containerWidth * defaultScrubWindowWidthRatio * movieAspectRatioInv, ); const scrubContainerWidth = containerWidth; const scrubInnerContainerWidth = Math.min( (scrubContainerHeight / movieAspectRatioInv + defaultScrubWindowMargin * 2) * 2, scrubContainerWidth, ); const scrubMovieHeight = scrubContainerHeight; const scrubMovieWidth = Math.min( Math.floor(scrubInnerContainerWidth * defaultScrubWindowWidthRatio), scrubContainerHeight / movieAspectRatioInv, ); const scrubInOutMovieWidth = Math.floor( (scrubInnerContainerWidth - scrubMovieWidth) / 2 - defaultScrubWindowMargin * 2, ); const scrubInOutMovieHeight = Math.floor(scrubInOutMovieWidth * movieAspectRatioInv); // for scrubView // calculate paperpreview size for gridview let paperMoviePrintWidth = originalMoviePrintWidth; let paperMoviePrintHeight = originalMoviePrintHeight; let paperAdjustmentScale = 1; if (showPaperPreview) { paperAdjustmentScale = PAPER_ADJUSTMENT_SCALE; if (defaultPaperAspectRatioInv < moviePrintAspectRatioInv) { paperMoviePrintWidth = paperMoviePrintHeight / defaultPaperAspectRatioInv; // log.debug(`calculate new paperMoviePrintWidth ${paperMoviePrintWidth}`); } else { paperMoviePrintHeight = paperMoviePrintWidth * defaultPaperAspectRatioInv; // log.debug(`calculate new paperMoviePrintHeight ${paperMoviePrintHeight}`); } } // calculate paperpreview size for gridview // calculate scaleValue for gridview const scaleValueForPrinting = containerWidth / originalMoviePrintWidthForPrinting; // scaleValue for gridView printing const scaleValueWidth = containerWidth / (showPaperPreview ? paperMoviePrintWidth : originalMoviePrintWidth); const scaleValueHeight = containerHeight / (showPaperPreview ? paperMoviePrintHeight : originalMoviePrintHeight); // default is SHEET_FIT.BOTH which is used when showSettings and forPrinting const scaleValue = Math.min(scaleValueWidth, scaleValueHeight) * zoomScale * paperAdjustmentScale; paperMoviePrintWidth *= scaleValue; paperMoviePrintHeight *= scaleValue; // calculate scaleValue for gridview // calculate new values for gridview const newMoviePrintWidth = showPlayerView ? moviePrintWidthForThumbView : originalMoviePrintWidth * scaleValue + DEFAULT_MIN_MOVIEPRINTWIDTH_MARGIN; const newMoviePrintHeight = showPlayerView ? originalMoviePrintHeight : newMoviePrintWidth * moviePrintAspectRatioInv; const newMoviePrintWidthForPrinting = originalMoviePrintWidthForPrinting * scaleValueForPrinting; const newThumbMargin = showPlayerView ? thumbMarginForThumbView : thumbMargin * scaleValue; const newThumbWidth = showPlayerView ? thumbnailWidthForThumbView : thumbWidth * scaleValue; const newBorderRadius = showPlayerView ? borderRadiusForThumbView : borderRadius * scaleValue; const newHeaderHeight = showPlayerView ? headerHeight : headerHeight * scaleValue; const newLogoHeight = showPlayerView ? logoHeight : logoHeight * scaleValue; // calculate new values for gridview // timeline view // * set original size // * calculate aspect ratio // * calculate new width and height depending on container or paper // convert 0-50-100 to 0.1-1-10 const scale = defaultTimelineViewWidthScale <= 50 ? defaultTimelineViewWidthScale / 55.5555 + 0.1 : (defaultTimelineViewWidthScale - 50) / 5.55555 + 1.0; const scenesInRows = getScenesInRows(sceneArray, secondsPerRow); const timelineViewRowCount = scenesInRows.length; const originalTimelineMoviePrintHeight = defaultMoviePrintWidth; // use default width as height; const originalTimelineMoviePrintWidth = originalTimelineMoviePrintHeight * scale; const timelineMoviePrintAspectRatioInv = (originalTimelineMoviePrintHeight * 1.0) / originalTimelineMoviePrintWidth; const adjustmentScale = showPaperPreview ? PAPER_ADJUSTMENT_SCALE * MARGIN_ADJUSTMENT_SCALE : MARGIN_ADJUSTMENT_SCALE; // used to create a small margin around let previewMoviePrintTimelineHeight; let previewMoviePrintTimelineWidth; // if container ratio is smaller then calculate new width and then height from it // if container ratio is larger then calculate new height and then width from it const containerOrPaperAspectRatioInv = showPaperPreview ? defaultPaperAspectRatioInv : containerAspectRatioInv; if (containerOrPaperAspectRatioInv < timelineMoviePrintAspectRatioInv) { // use containerWidth if paper/container ratio is smaller than container ratio else calculate width from container height and paper/container ratio const containerOrPaperWidth = containerOrPaperAspectRatioInv > containerAspectRatioInv ? containerHeight / containerOrPaperAspectRatioInv : containerWidth; previewMoviePrintTimelineHeight = containerOrPaperWidth * containerOrPaperAspectRatioInv * adjustmentScale; previewMoviePrintTimelineWidth = ((containerOrPaperWidth * containerOrPaperAspectRatioInv) / timelineMoviePrintAspectRatioInv) * adjustmentScale; // log.debug(`calculate new previewMoviePrintTimelineWidth ${previewMoviePrintTimelineWidth}/${((containerOrPaperWidth * containerOrPaperAspectRatioInv) / timelineMoviePrintAspectRatioInv)} // ${previewMoviePrintTimelineHeight}/${containerOrPaperWidth * containerOrPaperAspectRatioInv}`); } else { // use containerHeight if paper/container ratio is larger than container ratio else calculate height from container width and paper/container ratio const containerOrPaperHeight = containerOrPaperAspectRatioInv < containerAspectRatioInv ? containerWidth * containerOrPaperAspectRatioInv : containerHeight; previewMoviePrintTimelineWidth = (containerOrPaperHeight / containerOrPaperAspectRatioInv) * adjustmentScale; previewMoviePrintTimelineHeight = (containerOrPaperHeight / containerOrPaperAspectRatioInv) * timelineMoviePrintAspectRatioInv * adjustmentScale; // log.debug(`calculate new previewMoviePrintTimelineHeight ${previewMoviePrintTimelineHeight}/${(containerOrPaperHeight / containerOrPaperAspectRatioInv) * timelineMoviePrintAspectRatioInv} // ${previewMoviePrintTimelineWidth}/${containerOrPaperHeight / containerOrPaperAspectRatioInv}`); } // get values depending on if printing or not const newMoviePrintTimelineWidth = forPrinting ? originalTimelineMoviePrintWidth : previewMoviePrintTimelineWidth; const newMoviePrintTimelineHeight = forPrinting ? originalTimelineMoviePrintHeight : previewMoviePrintTimelineHeight; // the value 50.0 compensates for the low value range of defaultMarginRatio as it is also used for the thumbview const thumbMarginTimeline = forPrinting ? (originalTimelineMoviePrintHeight / 1024) * defaultMarginRatio * 50.0 : defaultMarginRatio * 50.0; // calculate rest const newMoviePrintTimelineRowHeight = Math.floor( (newMoviePrintTimelineHeight - thumbMarginTimeline * timelineViewRowCount * 2) / timelineViewRowCount, ); // console.log(scenesInRows); const newMoviePrintTimelinePixelPerFrameRatio = getPixelPerFrameRatio( scenesInRows, thumbMarginTimeline, newMoviePrintTimelineWidth, defaultTimelineViewMinDisplaySceneLengthInFrames, ); // console.log(newMoviePrintTimelinePixelPerFrameRatio); // timeline view const scaleValueObject = { containerWidth, containerHeight, containerAspectRatioInv, aspectRatioInv: movieAspectRatioInv, newMoviePrintWidth, newMoviePrintHeight, moviePrintAspectRatioInv, newThumbMargin, newThumbWidth, newBorderRadius, newHeaderHeight, newLogoHeight, videoPlayerHeight, videoPlayerWidth, scrubMovieWidth, scrubMovieHeight, scrubInOutMovieWidth, scrubInOutMovieHeight, scrubContainerHeight, scrubContainerWidth, scrubInnerContainerWidth, newMoviePrintWidthForPrinting, newMoviePrintTimelineWidth, newMoviePrintTimelineHeight, newMoviePrintTimelineRowHeight, newMoviePrintTimelinePixelPerFrameRatio, timelineMoviePrintAspectRatioInv, thumbMarginTimeline, scenesInRows, paperMoviePrintWidth, paperMoviePrintHeight, }; // log.debug(scaleValueObject); return scaleValueObject; }; export default getScaleValueObject; <|start_filename|>app/utils/utilsSortAndFilter.js<|end_filename|> import log from 'electron-log'; import * as faceapi from 'face-api.js'; import { areOneOrMoreFiltersEnabled, limitRange, roundNumber, mapRange } from './utils'; import { FILTER_METHOD, SORT_METHOD, FILTER_METHOD_AGE, FILTER_METHOD_FACESIZE, FILTER_METHOD_FACEOCCURRENCE, FILTER_METHOD_FACECOUNT, } from './constants'; // sort detectionArray by ... export const sortArray = ( detectionArray, sortMethod = SORT_METHOD.FACESIZE, reverseSortOrder = false, optionalSortProperties = undefined, ) => { let sortedArray = []; const sortOrderMultiplier = reverseSortOrder ? -1 : 1; switch (sortMethod) { case SORT_METHOD.FRAMENUMBER: sortedArray = detectionArray .slice() .sort((a, b) => (a.frameNumber > b.frameNumber ? sortOrderMultiplier * 1 : sortOrderMultiplier * -1)); // .map(item => item.frameNumber); break; case SORT_METHOD.FACECOUNT: sortedArray = detectionArray .slice() .filter(item => item.faceCount !== 0) // filter out frames with no faces .sort((a, b) => (a.faceCount < b.faceCount ? sortOrderMultiplier * 1 : sortOrderMultiplier * -1)); // .map(item => item.frameNumber); break; case SORT_METHOD.FACESIZE: { // filtered and flatten the detectionArray const detectionArrayFiltered = detectionArray.filter(item => item.faceCount !== 0); // filter out frames with no faces const flattenedArray = getFlattenedArray(detectionArrayFiltered); const flattenedArrayFiltered = flattenedArray.filter(item => !item.faceIsHidden); // filter out faces which are hidden // sort flattenedArrayFiltered.sort((a, b) => (a.size < b.size ? sortOrderMultiplier * 1 : sortOrderMultiplier * -1)); // only keep first faceOccurrence of frameNumber sortedArray = flattenedArrayFiltered.filter( (item, index, self) => index === self.findIndex(t => t.frameNumber === item.frameNumber), ); // sortedArray = break; } case SORT_METHOD.FACECONFIDENCE: { // filtered and flatten the detectionArray const detectionArrayFiltered = detectionArray.filter(item => item.faceCount !== 0); // filter out frames with no faces const flattenedArray = getFlattenedArray(detectionArrayFiltered); const flattenedArrayFiltered = flattenedArray.filter(item => !item.faceIsHidden); // filter out faces which are hidden // sort flattenedArrayFiltered.sort((a, b) => (a.score < b.score ? sortOrderMultiplier * 1 : sortOrderMultiplier * -1)); // only keep first faceOccurrence of frameNumber sortedArray = flattenedArrayFiltered.filter( (item, index, self) => index === self.findIndex(t => t.frameNumber === item.frameNumber), ); // sortedArray = break; } case SORT_METHOD.FACEOCCURRENCE: { // filtered and flatten the detectionArray const detectionArrayFiltered = detectionArray.filter(item => item.faceCount !== 0); // filter out frames with no faces const flattenedArray = getFlattenedArray(detectionArrayFiltered); const flattenedArrayFiltered = flattenedArray.filter(item => !item.faceIsHidden); // filter out faces which are hidden // console.log(flattenedArray.map(item => ({ faceGroupNumber: item.faceGroupNumber, size: item.size, faceOccurrence: item.faceOccurrence }))); // sort by count, size and then score flattenedArrayFiltered.sort((a, b) => { // Sort by count number if (a.faceOccurrence < b.faceOccurrence) return sortOrderMultiplier * 1; if (a.faceOccurrence > b.faceOccurrence) return sortOrderMultiplier * -1; // If the count number is the same between both items, sort by size if (a.size < b.size) return sortOrderMultiplier * 1; if (a.size > b.size) return sortOrderMultiplier * -1; // If the count number is the same between both items, sort by size if (a.score < b.score) return sortOrderMultiplier * 1; if (a.score > b.score) return sortOrderMultiplier * -1; return -1; }); // only keep first faceOccurrence of frameNumber sortedArray = flattenedArrayFiltered.filter( (item, index, self) => index === self.findIndex(t => t.frameNumber === item.frameNumber), ); break; } case SORT_METHOD.DISTTOORIGIN: { // filtered and flatten the detectionArray const detectionArrayFiltered = detectionArray.filter(item => item.faceCount !== 0); // filter out frames with no faces const { faceIdOfOrigin } = optionalSortProperties; if (detectionArrayFiltered.length > 0 && faceIdOfOrigin !== undefined) { // console.log(faceIdOfOrigin); if (faceIdOfOrigin !== undefined) { const flattenedArray = getFlattenedArray(detectionArrayFiltered); const flattenedArrayFiltered = flattenedArray.filter(item => !item.faceIsHidden); // filter out faces which are hidden // console.log(flattenedArray); // filter array to only include faceIdOfOrigin flattenedArrayFiltered.filter(item => item.faceGroupNumber === faceIdOfOrigin); // sort by distToOrigin flattenedArrayFiltered.sort((a, b) => { // Sort by distToOrigin if (a.distToOrigin > b.distToOrigin) return sortOrderMultiplier * 1; if (a.distToOrigin < b.distToOrigin) return sortOrderMultiplier * -1; return -1; }); // only keep first faceOccurrence of frameNumber sortedArray = flattenedArrayFiltered.filter( (item, index, self) => index === self.findIndex(t => t.frameNumber === item.frameNumber), ); } } break; } default: } // console.log(sortedArray); return sortedArray; }; // filter detectionArray by ... export const filterArray = (detectionArray, filters) => { // console.log(filters); // if there are no filters, return untouched if (!areOneOrMoreFiltersEnabled(filters)) { // remove faceDescriptor and unhide thumbs deleteFaceDescriptorFromFaceScanArray(detectionArray, true); return detectionArray; } const detectionArrayFiltered = detectionArray.filter(item => item.faceCount !== 0); // filter out frames with no faces const flattenedArray = getFlattenedArray(detectionArrayFiltered); // filteredAndSortedArray = flattenedArray.filter(item => item.distToOrigin === 0); /* eslint no-restricted-syntax: ["error", "FunctionExpression", "WithStatement", "BinaryExpression[operator='in']"] */ // NOTE: mutating array flattenedArray.forEach(item => { // start by unhiding all faces item.faceIsHidden = false; for (const key of Object.keys(filters)) { // console.log(key) // console.log(filters[key]) // console.log(item[key]) // only filter if enabled if (filters[key].enabled) { // set new max value if upper equals max to not exclude top values on age, size ... let newMaxValue; let rangeFilter = false; let valueFilter = false; let arrayFilter = false; switch (key) { // rangeFilters case FILTER_METHOD.AGE: newMaxValue = filters[key].upper === FILTER_METHOD_AGE.MAX ? FILTER_METHOD_AGE.MAXMAX : filters[key].upper; rangeFilter = true; break; case FILTER_METHOD.FACECOUNT: newMaxValue = filters[key].upper === FILTER_METHOD_FACECOUNT.MAX ? FILTER_METHOD_FACECOUNT.MAXMAX : filters[key].upper; rangeFilter = true; break; case FILTER_METHOD.FACEOCCURRENCE: newMaxValue = filters[key].upper === FILTER_METHOD_FACEOCCURRENCE.MAX ? FILTER_METHOD_FACEOCCURRENCE.MAXMAX : filters[key].upper; rangeFilter = true; break; case FILTER_METHOD.FACESIZE: newMaxValue = filters[key].upper === FILTER_METHOD_FACESIZE.MAX ? FILTER_METHOD_FACESIZE.MAXMAX : filters[key].upper; rangeFilter = true; break; // valueFilters case FILTER_METHOD.GENDER: valueFilter = true; break; case FILTER_METHOD.DISTTOORIGIN: valueFilter = true; break; // arrayFilter case FILTER_METHOD.FACEID: arrayFilter = true; break; default: } // if rangeFilter hide face if it is not within range if ( rangeFilter && (item[key] === undefined || !(filters[key].lower <= item[key] && item[key] <= newMaxValue)) ) { item.faceIsHidden = true; break; // break out of for loop and go to next item } // if valueFilter hide face if it is not a specific value if (valueFilter && (item[key] === undefined || item[key] !== filters[key].value)) { item.faceIsHidden = true; break; // break out of for loop and go to next item } // if arrayFilter hide face if it is not a specific value if ( arrayFilter && (item[key] === undefined || !filters[key].faceIdArray.some(faceId => faceId === item[key])) ) { item.faceIsHidden = true; break; // break out of for loop and go to next item } } } return undefined; }); const unflattenedArray = unflattenArray(flattenedArray); // console.log(filteredAndSortedArray); return unflattenedArray; }; export const unflattenArray = flattenedArray => { // construct a new unflattened Array const unflattenedArray = []; // console.log(unflattenedArray); flattenedArray.map(face => { const indexOfOtherFrame = unflattenedArray.findIndex(item => item.frameNumber === face.frameNumber); const newFaceObject = { faceIsHidden: face.faceIsHidden, score: face.score, size: face.size, box: face.box, gender: face.gender, age: face.age, faceId: face.faceId, faceGroupNumber: face.faceGroupNumber, faceOccurrence: face.faceOccurrence, distToOrigin: face.distToOrigin, }; if (indexOfOtherFrame > -1) { // if it already exists push new face and in case faceIsHidden is false update hidden property to show thumb unflattenedArray[indexOfOtherFrame].facesArray.push(newFaceObject); if (!face.faceIsHidden) { unflattenedArray[indexOfOtherFrame].hidden = false; } } else { unflattenedArray.push({ frameNumber: face.frameNumber, faceCount: face.faceCount, largestSize: face.largestSize, facesArray: [newFaceObject], hidden: face.faceIsHidden, }); } // console.log(face.frameNumber); return undefined; }); // console.log(unflattenedArray); return unflattenedArray; }; export const getFlattenedArray = detectionArray => { const flattenedArray = []; detectionArray.map(item => { const { facesArray, ...rest } = item; if (facesArray !== undefined) { facesArray.map(face => { flattenedArray.push({ ...face, ...rest }); return undefined; }); } return undefined; }); return flattenedArray; }; export const getArrayOfOccurrences = detectionArray => { // flatten the detectionArray const flattenedArray = getFlattenedArray(detectionArray); const arrayOfOccurrences = flattenedArray.reduce((acc, curr) => { if (acc[curr.faceGroupNumber] === undefined) { acc[curr.faceGroupNumber] = { count: 1, faceGroupNumber: curr.faceGroupNumber }; } else { acc[curr.faceGroupNumber].count += 1; } return acc; }, {}); // console.log(arrayOfOccurrences); // console.log(typeof arrayOfOccurrences); return arrayOfOccurrences; }; // NOTE: this is a mutating function export const determineAndInsertFaceGroupNumber = (detectionArray, defaultFaceUniquenessThreshold) => { // this function determines unique faces and adds the faceGroupNumber into the detectionArray // flatten array const flattenedArray = getFlattenedArray(detectionArray); // sort by size so the original faces to compare against are large ones const sortedFlattenedArray = flattenedArray.sort((a, b) => (a.size < b.size ? 1 : -1)); // console.log(sortedFlattenedArray); // determine facegroups let faceGroupNumber = 0; const uniqueFaceArray = []; sortedFlattenedArray.forEach(face => { if (face.faceCount !== 0) { const currentFaceDescriptor = Object.values(face.faceDescriptor); const uniqueFaceArrayLength = uniqueFaceArray.length; if (uniqueFaceArrayLength === 0) { uniqueFaceArray.push(currentFaceDescriptor); // convert array face.faceGroupNumber = faceGroupNumber; face.distToOrigin = 0; } else { // compare descriptor value with all values in the array for (let i = 0; i < uniqueFaceArrayLength; i += 1) { const dist = faceapi.euclideanDistance(currentFaceDescriptor, uniqueFaceArray[i]); // console.log(dist); // check how close the faces are if (dist < defaultFaceUniquenessThreshold) { // faces are similar or equal // console.log( // dist === 0 // ? `this and face ${i} are identical: ${dist}` // : `this and face ${i} are probably the same: ${dist}`, // ); faceGroupNumber = i; face.faceGroupNumber = faceGroupNumber; face.distToOrigin = roundNumber(dist); break; } else if (i === uniqueFaceArrayLength - 1) { // face is unique // if no match was found add the current descriptor to the array marking a new unique face // console.log(`this face is unique: ${dist}`); uniqueFaceArray.push(currentFaceDescriptor); // convert array faceGroupNumber = uniqueFaceArrayLength; face.faceGroupNumber = faceGroupNumber; face.distToOrigin = 0; } } } } return undefined; }); // console.log(flattenedArray); // unflatten array const unflattenedArray = unflattenArray(flattenedArray); // console.log(unflattenedArray); // apply former sorting using intitial detectionArray const sortedThumbsArray = sortThumbsArray(unflattenedArray, detectionArray); // console.log(sortedThumbsArray); return sortedThumbsArray; }; export const getOccurrencesOfFace = (detectionArray, frameNumber, defaultFaceUniquenessThreshold) => { // returns an array of foundFrames where this face occurrs // initialise the foundFrames const foundFrames = []; const frameOfFace = detectionArray.find(frame => frame.frameNumber === frameNumber); // console.log(frameOfFace); if (frameOfFace === undefined || frameOfFace.facesArray === undefined || frameOfFace.facesArray.length === 0) { return []; // return an empty array as there where no faceOccurrences } // use first face in array to search for // later it would be nice if one can specify which face on an array to search for const faceIdOfOrigin = frameOfFace.facesArray[0].faceId; const faceDescriptorOfFace = Object.values(frameOfFace.facesArray[0].faceDescriptor); detectionArray.forEach(frame => { if (frame.faceCount !== 0) { const foundFaces = []; frame.facesArray.forEach(face => { const currentFaceDescriptor = Object.values(face.faceDescriptor); // compare descriptor value with faceDescriptorOfFace const dist = faceapi.euclideanDistance(currentFaceDescriptor, faceDescriptorOfFace); // console.log(dist); // if no match was found add the current descriptor to the array marking a unique face if (dist < defaultFaceUniquenessThreshold) { // console.log(dist === 0 ? `this face is identical: ${dist}` : `this face is probably the same: ${dist}`); foundFaces.push({ ...face, distToOrigin: dist, faceDescriptor: undefined }); } else if (foundFaces.length > 0) { // only add other faces if one face is similar // console.log(`this face is different: ${dist}`); foundFaces.push({ ...face, faceDescriptor: undefined }); } return undefined; }); if (foundFaces.length > 0) { foundFrames.push({ ...frame, facesArray: foundFaces }); } } return undefined; }); return { faceIdOfOrigin, foundFrames, }; }; export const insertFaceOccurrence = detectionArray => { // this function determines faceOccurrences and adds them to the detectionArray // insert faceOccurrence into detectionArray const arrayOfOccurrences = getArrayOfOccurrences(detectionArray); // console.log(arrayOfOccurrences); detectionArray.forEach(frame => { if (frame.facesArray !== undefined) { frame.facesArray.forEach(face => { // convert object to array and find faceOccurrence and add to item const { count } = Object.values(arrayOfOccurrences).find(item => item.faceGroupNumber === face.faceGroupNumber); /* eslint no-param-reassign: ["error", { "props": false }] */ face.faceOccurrence = count; }); } }); }; export const getIntervalArray = ( amount, start, stop, maxValue, limitToMaxValue = false, // in some cases it can be allowed to go over ) => { // amount should not be more than the maxValue // stop - start should be at least amount let newStart = start; let newStop = stop; const range = stop - start; let newAmount = Math.min(amount, maxValue - 1); if (range < newAmount) { if (limitToMaxValue) { newAmount = range + 1; } else { newStop = start + newAmount; if (newStop > maxValue - 1) { newStart = Math.max(0, maxValue - 1 - newAmount); newStop = newStart + newAmount; } } } // log.debug(`${amount} : ${newAmount} : ${start} : ${newStart} : ${stop} : ${newStop} : `); const startWithBoundaries = limitRange(newStart, 0, maxValue - 1); const stopWithBoundaries = limitRange(newStop, 0, maxValue - 1); const frameNumberArray = Array.from(Array(newAmount).keys()).map(x => mapRange(x, 0, newAmount - 1, startWithBoundaries, stopWithBoundaries, true), ); return frameNumberArray; }; export const sortThumbsArray = (thumbsArray, sortOrderArray) => { // extract frameNumbers const frameNumberArrayFromFaceDetection = sortOrderArray.map(item => item.frameNumber); // console.log(frameNumberArrayFromFaceDetection); // console.log(thumbsArray); // let filteredArray = thumbsArray; // if (hideOthers) { // // filter thumbsArray by frameNumberArrayFromFaceDetection // filteredArray = thumbsArray.filter(item => frameNumberArrayFromFaceDetection.includes(item.frameNumber)); // } const thumbsArrayAfterSorting = thumbsArray.slice().sort((a, b) => { return ( frameNumberArrayFromFaceDetection.indexOf(a.frameNumber) - frameNumberArrayFromFaceDetection.indexOf(b.frameNumber) ); }); // console.log(thumbsArrayAfterSorting); return thumbsArrayAfterSorting; }; // NOTE: this is a mutating function export const deleteFaceDescriptorFromFaceScanArray = (faceScanArray, unhide = false) => { faceScanArray.map(frame => { // loop through all frames if (unhide) { frame.hidden = false; } if (frame.facesArray !== undefined) { frame.facesArray.map(face => { // loop through all faces delete face.faceDescriptor; return undefined; }); } return undefined; }); return faceScanArray; }; export const getFaceIdArrayFromThumbs = thumbArray => { const flattenedArray = getFlattenedArray(thumbArray); // get faceId of all faces with distToOrigin parameter (used for expanded face prints) const faceIdArray = flattenedArray.filter(face => face.distToOrigin !== undefined).map(face => face.faceId); return faceIdArray; }; <|start_filename|>app/containers/SettingsList.js<|end_filename|> // @flow import React, { Component, Fragment } from 'react'; import PropTypes from 'prop-types'; import Slider, { Handle, createSliderWithTooltip } from 'rc-slider'; import Tooltip from 'rc-tooltip'; import { SketchPicker } from 'react-color'; import throttle from 'lodash/throttle'; import { Checkboard } from 'react-color/lib/components/common'; import { Accordion, Button, Icon, Label, Radio, Dropdown, Container, Statistic, Divider, Checkbox, Grid, List, Message, Popup, Input, } from 'semantic-ui-react'; import styles from './Settings.css'; import stylesPop from '../components/Popup.css'; import { frameCountToMinutes, getCustomFileName, limitRange, sanitizeString, typeInTextarea } from '../utils/utils'; import { CACHED_FRAMES_SIZE_OPTIONS, COLOR_PALETTE_PICO_EIGHT, DEFAULT_ALLTHUMBS_NAME, DEFAULT_FRAMEINFO_BACKGROUND_COLOR, DEFAULT_FRAMEINFO_COLOR, DEFAULT_FRAMEINFO_MARGIN, DEFAULT_FRAMEINFO_POSITION, DEFAULT_FRAMEINFO_SCALE, DEFAULT_MOVIE_HEIGHT, DEFAULT_MOVIE_WIDTH, DEFAULT_MOVIEPRINT_BACKGROUND_COLOR, DEFAULT_MOVIEPRINT_NAME, DEFAULT_SHOW_FACERECT, DEFAULT_SINGLETHUMB_NAME, DEFAULT_OUTPUT_JPG_QUALITY, DEFAULT_THUMB_FORMAT, DEFAULT_THUMB_JPG_QUALITY, FACE_CONFIDENCE_THRESHOLD, FACE_SIZE_THRESHOLD, FACE_UNIQUENESS_THRESHOLD, FRAMEINFO_POSITION_OPTIONS, MENU_FOOTER_HEIGHT, MENU_HEADER_HEIGHT, MOVIEPRINT_WIDTH_HEIGHT, MOVIEPRINT_WIDTH_HEIGHT_SIZE_LIMIT, OUTPUT_FORMAT_OPTIONS, OUTPUT_FORMAT, PAPER_LAYOUT_OPTIONS, SHEET_TYPE, SHOT_DETECTION_METHOD_OPTIONS, THUMB_SELECTION, } from '../utils/constants'; import getScaleValueObject from '../utils/getScaleValueObject'; const SliderWithTooltip = createSliderWithTooltip(Slider); const handle = props => { const { value, dragging, index, ...restProps } = props; return ( <Tooltip prefixCls="rc-slider-tooltip" overlay={value} visible placement="top" key={index}> <Handle value={value} {...restProps} /> </Tooltip> ); }; const getOutputSizeOptions = ( baseSizeArray, file = { width: DEFAULT_MOVIE_WIDTH, height: DEFAULT_MOVIE_HEIGHT, }, columnCountTemp, thumbCountTemp, settings, visibilitySettings, sceneArray, secondsPerRowTemp, isGridView, ) => { const newScaleValueObject = getScaleValueObject( file, settings, visibilitySettings, columnCountTemp, thumbCountTemp, 4096, undefined, 1, undefined, undefined, sceneArray, secondsPerRowTemp, ); // set base size options const moviePrintSize = MOVIEPRINT_WIDTH_HEIGHT.map(item => { const otherDim = isGridView ? Math.round(item * newScaleValueObject.moviePrintAspectRatioInv) : Math.round(item / newScaleValueObject.timelineMoviePrintAspectRatioInv); return { value: item, otherdim: otherDim, text: isGridView ? `${item}px (×${otherDim}px)` : `${otherDim}px (×${item}px)`, 'data-tid': `${item}-option`, }; }); // add max option if ( isGridView ? newScaleValueObject.moviePrintAspectRatioInv > 1 : newScaleValueObject.timelineMoviePrintAspectRatioInv < 1 ) { const maxDim = isGridView ? Math.round(MOVIEPRINT_WIDTH_HEIGHT_SIZE_LIMIT / newScaleValueObject.moviePrintAspectRatioInv) : Math.round(MOVIEPRINT_WIDTH_HEIGHT_SIZE_LIMIT * newScaleValueObject.timelineMoviePrintAspectRatioInv); // to avoid duplicates due to rounding if (maxDim !== MOVIEPRINT_WIDTH_HEIGHT_SIZE_LIMIT) { moviePrintSize.push({ value: maxDim, otherdim: MOVIEPRINT_WIDTH_HEIGHT_SIZE_LIMIT, text: isGridView ? `${maxDim}px (×${MOVIEPRINT_WIDTH_HEIGHT_SIZE_LIMIT}px)` : `${MOVIEPRINT_WIDTH_HEIGHT_SIZE_LIMIT}px (×${maxDim}px)`, 'data-tid': `other-max-option`, }); } } // filter options const moviePrintSizeArray = moviePrintSize.filter(item => { const useOtherDim = isGridView ? newScaleValueObject.moviePrintAspectRatioInv > 1 : newScaleValueObject.timelineMoviePrintAspectRatioInv < 1; return useOtherDim ? item.otherdim <= MOVIEPRINT_WIDTH_HEIGHT_SIZE_LIMIT : item.value <= MOVIEPRINT_WIDTH_HEIGHT_SIZE_LIMIT; }); // console.log(moviePrintSizeArray); return moviePrintSizeArray; }; class SettingsList extends Component { constructor(props) { super(props); this.state = { changeSceneCount: false, showSliders: true, displayColorPicker: { moviePrintBackgroundColor: false, frameninfoBackgroundColor: false, frameinfoColor: false, }, previewMoviePrintName: DEFAULT_MOVIEPRINT_NAME, previewSingleThumbName: DEFAULT_SINGLETHUMB_NAME, previewAllThumbsName: DEFAULT_ALLTHUMBS_NAME, focusReference: undefined, activeIndex: -1, }; this.onChangeDefaultMoviePrintNameThrottled = throttle( value => this.props.onChangeDefaultMoviePrintName(value), 1000, { leading: false }, ); this.onChangeDefaultMoviePrintNameThrottled = this.onChangeDefaultMoviePrintNameThrottled.bind(this); this.onChangeDefaultSingleThumbNameThrottled = throttle( value => this.props.onChangeDefaultSingleThumbName(value), 1000, { leading: false }, ); this.onChangeDefaultSingleThumbNameThrottled = this.onChangeDefaultSingleThumbNameThrottled.bind(this); this.onChangeDefaultAllThumbsNameThrottled = throttle( value => this.props.onChangeDefaultAllThumbsName(value), 1000, { leading: false }, ); this.onChangeDefaultAllThumbsNameThrottled = this.onChangeDefaultAllThumbsNameThrottled.bind(this); // this.onToggleSliders = this.onToggleSliders.bind(this); this.onGetPreviewCustomFileName = this.onGetPreviewCustomFileName.bind(this); this.onShowSliders = this.onShowSliders.bind(this); this.onChangeSceneCount = this.onChangeSceneCount.bind(this); this.onChangePaperAspectRatio = this.onChangePaperAspectRatio.bind(this); this.onChangeShowPaperPreview = this.onChangeShowPaperPreview.bind(this); this.onChangeOutputPathFromMovie = this.onChangeOutputPathFromMovie.bind(this); this.onChangeTimelineViewFlow = this.onChangeTimelineViewFlow.bind(this); this.onChangeDetectInOutPoint = this.onChangeDetectInOutPoint.bind(this); this.onChangeReCapture = this.onChangeReCapture.bind(this); this.onChangeShowHeader = this.onChangeShowHeader.bind(this); this.onChangeShowPathInHeader = this.onChangeShowPathInHeader.bind(this); this.onChangeShowDetailsInHeader = this.onChangeShowDetailsInHeader.bind(this); this.onChangeShowTimelineInHeader = this.onChangeShowTimelineInHeader.bind(this); this.onChangeRoundedCorners = this.onChangeRoundedCorners.bind(this); this.onChangeShowHiddenThumbs = this.onChangeShowHiddenThumbs.bind(this); this.onChangeThumbInfo = this.onChangeThumbInfo.bind(this); this.onChangeOutputFormat = this.onChangeOutputFormat.bind(this); this.onChangeThumbFormat = this.onChangeThumbFormat.bind(this); this.onChangeFrameinfoPosition = this.onChangeFrameinfoPosition.bind(this); this.onChangeCachedFramesSize = this.onChangeCachedFramesSize.bind(this); this.onChangeOverwrite = this.onChangeOverwrite.bind(this); this.onChangeIncludeIndividual = this.onChangeIncludeIndividual.bind(this); this.onChangeEmbedFrameNumbers = this.onChangeEmbedFrameNumbers.bind(this); this.onChangeEmbedFilePath = this.onChangeEmbedFilePath.bind(this); this.onChangeOpenFileExplorerAfterSaving = this.onChangeOpenFileExplorerAfterSaving.bind(this); this.onChangeThumbnailScale = this.onChangeThumbnailScale.bind(this); this.onChangeMoviePrintWidth = this.onChangeMoviePrintWidth.bind(this); this.onChangeShotDetectionMethod = this.onChangeShotDetectionMethod.bind(this); this.onSubmitDefaultMoviePrintName = this.onSubmitDefaultMoviePrintName.bind(this); this.onSubmitDefaultSingleThumbName = this.onSubmitDefaultSingleThumbName.bind(this); this.setFocusReference = this.setFocusReference.bind(this); this.addAttributeIntoInput = this.addAttributeIntoInput.bind(this); this.onSubmitDefaultAllThumbsName = this.onSubmitDefaultAllThumbsName.bind(this); this.onChangeColumnCountViaInput = this.onChangeColumnCountViaInput.bind(this); this.onChangeColumnCountViaInputAndApply = this.onChangeColumnCountViaInputAndApply.bind(this); this.onChangeRowViaInput = this.onChangeRowViaInput.bind(this); this.onChangeTimelineViewSecondsPerRowViaInput = this.onChangeTimelineViewSecondsPerRowViaInput.bind(this); this.handleClick = this.handleClick.bind(this); } componentDidUpdate(prevProps) { const { file, sheetName, settings } = this.props; if ( file !== undefined && prevProps.file !== undefined && prevProps.file.name !== undefined && file.name !== undefined ) { if (file.name !== prevProps.file.name || sheetName !== prevProps.sheetName) { const { defaultMoviePrintName = DEFAULT_MOVIEPRINT_NAME, defaultSingleThumbName = DEFAULT_SINGLETHUMB_NAME, defaultAllThumbsName = DEFAULT_ALLTHUMBS_NAME, } = settings; this.setState({ previewMoviePrintName: this.onGetPreviewCustomFileName(defaultMoviePrintName), previewSingleThumbName: this.onGetPreviewCustomFileName(defaultSingleThumbName), previewAllThumbsName: this.onGetPreviewCustomFileName(defaultAllThumbsName), }); } } } // onToggleSliders = () => { // this.setState(state => ({ // showSliders: !state.showSliders // })); // } handleClick = (e, titleProps) => { const { index } = titleProps; const { activeIndex } = this.state; const newIndex = activeIndex === index ? -1 : index; this.setState({ activeIndex: newIndex }); }; onGetPreviewCustomFileName = (customFileName, props = this.props) => { const { file, settings, sheetName } = props; const previewName = getCustomFileName(file !== undefined ? file.name : '', sheetName, `000000`, customFileName); return previewName; }; onShowSliders = (e, { checked }) => { this.setState({ showSliders: !checked, }); }; setFocusReference = e => { const ref = e.target; this.setState({ focusReference: ref, }); }; addAttributeIntoInput = attribute => { const { focusReference } = this.state; if (focusReference !== undefined) { // console.log(focusReference); const newText = typeInTextarea(focusReference, attribute); const previewName = this.onGetPreviewCustomFileName(newText); switch (focusReference.name) { case 'defaultMoviePrintNameInput': this.setState({ previewMoviePrintName: previewName, }); break; case 'defaultSingleThumbNameInput': this.setState({ previewSingleThumbName: previewName, }); break; case 'defaultAllThumbsNameInput': this.setState({ previewAllThumbsName: previewName, }); break; default: } } }; onSubmitDefaultMoviePrintName = e => { const value = sanitizeString(e.target.value); const previewMoviePrintName = this.onGetPreviewCustomFileName(value); this.setState({ previewMoviePrintName, }); this.onChangeDefaultMoviePrintNameThrottled(value); }; onSubmitDefaultSingleThumbName = e => { const value = sanitizeString(e.target.value); const previewSingleThumbName = this.onGetPreviewCustomFileName(value); this.setState({ previewSingleThumbName, }); this.onChangeDefaultSingleThumbNameThrottled(value); }; onSubmitDefaultAllThumbsName = e => { const value = sanitizeString(e.target.value); const previewAllThumbsName = this.onGetPreviewCustomFileName(value); this.setState({ previewAllThumbsName, }); this.onChangeDefaultAllThumbsNameThrottled(value); }; onChangeColumnCountViaInput = e => { if (e.key === 'Enter') { const value = limitRange(Math.floor(e.target.value), 1, 100); this.props.onChangeColumn(value); } }; onChangeColumnCountViaInputAndApply = e => { if (e.key === 'Enter') { const value = limitRange(Math.floor(e.target.value), 1, 100); this.props.onChangeColumnAndApply(value); } }; onChangeRowViaInput = e => { if (e.key === 'Enter') { const value = limitRange(Math.floor(e.target.value), 1, 100); this.props.onChangeRow(value); } }; onChangeTimelineViewSecondsPerRowViaInput = e => { if (e.key === 'Enter') { const value = limitRange(Math.floor(e.target.value), 1, 20000); // 1 second to 5 hours this.props.onChangeTimelineViewSecondsPerRow(value); } }; onChangeSceneCount = (e, { checked }) => { this.setState({ changeSceneCount: checked }); }; onChangeTimelineViewFlow = (e, { checked }) => { this.props.onTimelineViewFlowClick(checked); }; onChangeShowPaperPreview = (e, { checked }) => { this.props.onShowPaperPreviewClick(checked); }; onChangeOutputPathFromMovie = (e, { checked }) => { this.props.onOutputPathFromMovieClick(checked); }; onChangePaperAspectRatio = (e, { value }) => { this.props.onPaperAspectRatioClick(value); }; onChangeDetectInOutPoint = (e, { checked }) => { this.props.onDetectInOutPointClick(checked); }; onChangeReCapture = (e, { checked }) => { this.props.onReCaptureClick(checked); }; onChangeShowHeader = (e, { checked }) => { this.props.onToggleHeaderClick(checked); }; onChangeShowPathInHeader = (e, { checked }) => { this.props.onShowPathInHeaderClick(checked); }; onChangeShowFaceRect = (e, { checked }) => { this.props.onChangeShowFaceRectClick(checked); }; onChangeShowDetailsInHeader = (e, { checked }) => { this.props.onShowDetailsInHeaderClick(checked); }; onChangeShowTimelineInHeader = (e, { checked }) => { this.props.onShowTimelineInHeaderClick(checked); }; onChangeRoundedCorners = (e, { checked }) => { this.props.onRoundedCornersClick(checked); }; onChangeShowHiddenThumbs = (e, { checked }) => { this.props.onShowHiddenThumbsClick(checked); }; onChangeThumbInfo = (e, { value }) => { this.props.onThumbInfoClick(value); }; onChangeOutputFormat = (e, { value }) => { this.props.onOutputFormatClick(value); }; onChangeThumbFormat = (e, { value }) => { this.props.onThumbFormatClick(value); }; onChangeFrameinfoPosition = (e, { value }) => { this.props.onFrameinfoPositionClick(value); }; onChangeCachedFramesSize = (e, { value }) => { this.props.onCachedFramesSizeClick(value); }; onChangeOverwrite = (e, { checked }) => { this.props.onOverwriteClick(checked); }; onChangeIncludeIndividual = (e, { checked }) => { this.props.onIncludeIndividualClick(checked); }; onChangeEmbedFrameNumbers = (e, { checked }) => { this.props.onEmbedFrameNumbersClick(checked); }; onChangeEmbedFilePath = (e, { checked }) => { this.props.onEmbedFilePathClick(checked); }; onChangeOpenFileExplorerAfterSaving = (e, { checked }) => { this.props.onOpenFileExplorerAfterSavingClick(checked); }; onChangeThumbnailScale = (e, { value }) => { this.props.onThumbnailScaleClick(value); }; onChangeMoviePrintWidth = (e, { value }) => { this.props.onMoviePrintWidthClick(value); }; onChangeShotDetectionMethod = (e, { value }) => { this.props.onShotDetectionMethodClick(value); }; colorPickerHandleClick = (e, id) => { e.stopPropagation(); this.setState({ displayColorPicker: { ...this.state.displayColorPicker, [id]: !this.state.displayColorPicker[id], }, }); }; colorPickerHandleClose = (e, id) => { e.stopPropagation(); this.setState({ displayColorPicker: { ...this.state.displayColorPicker, [id]: false, }, }); }; colorPickerHandleChange = (colorLocation, color) => { console.log(colorLocation); console.log(color); this.props.onMoviePrintBackgroundColorClick(colorLocation, color.rgb); }; render() { const { columnCountTemp, file, fileScanRunning, isGridView, onApplyNewGridClick, onChangeColumn, onChangeColumnAndApply, onChangeMargin, onChangeOutputJpgQuality, onChangeThumbJpgQuality, onChangeFaceSizeThreshold, onChangeFaceConfidenceThreshold, onChangeFrameinfoMargin, onChangeFrameinfoScale, onChangeMinDisplaySceneLength, onChangeOutputPathClick, onChangeRow, onChangeSceneDetectionThreshold, onChangeTimelineViewWidthScale, onToggleDetectionChart, reCapture, recaptureAllFrames, rowCountTemp, sceneArray, secondsPerRowTemp, settings, sheetType, sheetName, showChart, thumbCount, thumbCountTemp, visibilitySettings, } = this.props; const { activeIndex, displayColorPicker, focusReference, outputSizeOptions, previewMoviePrintName, previewSingleThumbName, previewAllThumbsName, showSliders, } = this.state; const { defaultCachedFramesSize = 0, defaultDetectInOutPoint, defaultEmbedFilePath, defaultEmbedFrameNumbers, defaultShowFaceRect = DEFAULT_SHOW_FACERECT, defaultFaceSizeThreshold = FACE_SIZE_THRESHOLD, defaultFaceConfidenceThreshold = FACE_CONFIDENCE_THRESHOLD, defaultFaceUniquenessThreshold = FACE_UNIQUENESS_THRESHOLD, defaultFrameinfoBackgroundColor = DEFAULT_FRAMEINFO_BACKGROUND_COLOR, defaultFrameinfoColor = DEFAULT_FRAMEINFO_COLOR, defaultFrameinfoPosition = DEFAULT_FRAMEINFO_POSITION, defaultFrameinfoScale = DEFAULT_FRAMEINFO_SCALE, defaultFrameinfoMargin = DEFAULT_FRAMEINFO_MARGIN, defaultMarginRatio, defaultOutputJpgQuality = DEFAULT_OUTPUT_JPG_QUALITY, defaultThumbJpgQuality = DEFAULT_THUMB_JPG_QUALITY, defaultMarginSliderFactor, defaultMoviePrintBackgroundColor = DEFAULT_MOVIEPRINT_BACKGROUND_COLOR, defaultMoviePrintWidth, defaultOpenFileExplorerAfterSaving, defaultOutputFormat, defaultThumbFormat = DEFAULT_THUMB_FORMAT, defaultOutputPath, defaultOutputPathFromMovie, defaultPaperAspectRatioInv, defaultRoundedCorners, defaultSaveOptionIncludeIndividual, defaultSaveOptionOverwrite, defaultSceneDetectionThreshold, defaultShotDetectionMethod, defaultShowDetailsInHeader, defaultShowHeader, defaultShowPaperPreview, defaultShowPathInHeader, defaultShowTimelineInHeader, defaultThumbInfo, defaultTimelineViewFlow, defaultTimelineViewMinDisplaySceneLengthInFrames, defaultTimelineViewWidthScale, defaultMoviePrintName = DEFAULT_MOVIEPRINT_NAME, defaultSingleThumbName = DEFAULT_SINGLETHUMB_NAME, defaultAllThumbsName = DEFAULT_ALLTHUMBS_NAME, } = settings; const fileFps = file !== undefined ? file.fps : 25; const minutes = file !== undefined ? frameCountToMinutes(file.frameCount, fileFps) : undefined; const minutesRounded = Math.round(minutes); const cutsPerMinuteRounded = Math.round((thumbCountTemp - 1) / minutes); const frameNumberOrTimecode = ['[FN]', '[TC]']; const defaultSingleThumbNameContainsFrameNumberOrTimeCode = frameNumberOrTimecode.some(item => defaultSingleThumbName.includes(item), ); const defaultAllThumbsNameContainsFrameNumberOrTimeCode = frameNumberOrTimecode.some(item => defaultAllThumbsName.includes(item), ); const moviePrintBackgroundColorDependentOnFormat = defaultOutputFormat === OUTPUT_FORMAT.JPG // set alpha only for PNG ? { r: defaultMoviePrintBackgroundColor.r, g: defaultMoviePrintBackgroundColor.g, b: defaultMoviePrintBackgroundColor.b, } : defaultMoviePrintBackgroundColor; const moviePrintBackgroundColorDependentOnFormatString = defaultOutputFormat === OUTPUT_FORMAT.JPG // set alpha only for PNG ? `rgb(${defaultMoviePrintBackgroundColor.r}, ${defaultMoviePrintBackgroundColor.g}, ${defaultMoviePrintBackgroundColor.b})` : `rgba(${defaultMoviePrintBackgroundColor.r}, ${defaultMoviePrintBackgroundColor.g}, ${defaultMoviePrintBackgroundColor.b}, ${defaultMoviePrintBackgroundColor.a})`; const frameninfoBackgroundColorString = `rgba(${defaultFrameinfoBackgroundColor.r}, ${defaultFrameinfoBackgroundColor.g}, ${defaultFrameinfoBackgroundColor.b}, ${defaultFrameinfoBackgroundColor.a})`; const frameinfoColorString = `rgba(${defaultFrameinfoColor.r}, ${defaultFrameinfoColor.g}, ${defaultFrameinfoColor.b}, ${defaultFrameinfoColor.a})`; return ( <Container style={{ marginBottom: `${MENU_HEADER_HEIGHT + MENU_FOOTER_HEIGHT}px`, }} > <Grid padded inverted> {!isGridView && ( <Grid.Row> <Grid.Column width={16}> <Statistic inverted size="tiny"> <Statistic.Value>{thumbCountTemp}</Statistic.Value> <Statistic.Label>{thumbCountTemp === 1 ? 'Shot' : 'Shots'}</Statistic.Label> </Statistic> <Statistic inverted size="tiny"> <Statistic.Value>/</Statistic.Value> </Statistic> <Statistic inverted size="tiny"> <Statistic.Value>~{minutesRounded}</Statistic.Value> <Statistic.Label>{minutesRounded === 1 ? 'Minute' : 'Minutes'}</Statistic.Label> </Statistic> <Statistic inverted size="tiny"> <Statistic.Value>≈</Statistic.Value> </Statistic> <Statistic inverted size="tiny"> <Statistic.Value>{cutsPerMinuteRounded}</Statistic.Value> <Statistic.Label>cut/min</Statistic.Label> </Statistic> </Grid.Column> </Grid.Row> )} {isGridView && ( <Grid.Row> <Grid.Column width={16}> <Statistic inverted size="tiny"> <Statistic.Value>{columnCountTemp}</Statistic.Value> <Statistic.Label>{columnCountTemp === 1 ? 'Column' : 'Columns'}</Statistic.Label> </Statistic> <Statistic inverted size="tiny"> <Statistic.Value>×</Statistic.Value> </Statistic> <Statistic inverted size="tiny"> <Statistic.Value>{rowCountTemp}</Statistic.Value> <Statistic.Label>{rowCountTemp === 1 ? 'Row' : 'Rows'}</Statistic.Label> </Statistic> <Statistic inverted size="tiny"> <Statistic.Value>{columnCountTemp * rowCountTemp === thumbCountTemp ? '=' : '≈'}</Statistic.Value> </Statistic> <Statistic inverted size="tiny" color={reCapture ? 'orange' : undefined}> <Statistic.Value>{thumbCountTemp}</Statistic.Value> <Statistic.Label>{reCapture ? 'Count' : 'Count'}</Statistic.Label> </Statistic> </Grid.Column> </Grid.Row> )} {isGridView && ( <Grid.Row> <Grid.Column width={4}>Columns</Grid.Column> <Grid.Column width={12}> {showSliders && ( <SliderWithTooltip data-tid="columnCountSlider" className={styles.slider} min={1} max={20} defaultValue={columnCountTemp} value={columnCountTemp} marks={{ 1: '1', 20: '20', }} handle={handle} onChange={ sheetType === SHEET_TYPE.INTERVAL && reCapture && isGridView ? onChangeColumn : onChangeColumnAndApply } /> )} {!showSliders && ( <Input type="number" data-tid="columnCountInput" className={styles.input} defaultValue={columnCountTemp} onKeyDown={ reCapture && isGridView ? this.onChangeColumnCountViaInput : this.onChangeColumnCountViaInputAndApply } /> )} </Grid.Column> </Grid.Row> )} {sheetType === SHEET_TYPE.INTERVAL && isGridView && reCapture && ( <Grid.Row> <Grid.Column width={4}>Rows</Grid.Column> <Grid.Column width={12}> {showSliders && ( <SliderWithTooltip data-tid="rowCountSlider" disabled={!reCapture} className={styles.slider} min={1} max={20} defaultValue={rowCountTemp} value={rowCountTemp} {...(reCapture ? {} : { value: rowCountTemp })} marks={{ 1: '1', 20: '20', }} handle={handle} onChange={onChangeRow} /> )} {!showSliders && ( <Input type="number" data-tid="rowCountInput" className={styles.input} defaultValue={rowCountTemp} onKeyDown={this.onChangeRowViaInput} /> )} </Grid.Column> </Grid.Row> )} {!isGridView && ( <> <Grid.Row> <Grid.Column width={4}>Minutes per row</Grid.Column> <Grid.Column width={12}> {showSliders && ( <SliderWithTooltip data-tid="minutesPerRowSlider" className={styles.slider} min={10} max={1800} defaultValue={secondsPerRowTemp} value={secondsPerRowTemp} marks={{ 10: '0.1', 60: '1', 300: '5', 600: '10', 1200: '20', 1800: '30', }} handle={handle} onChange={this.props.onChangeTimelineViewSecondsPerRow} /> )} {!showSliders && ( <Input type="number" data-tid="minutesPerRowInput" className={styles.input} label={{ basic: true, content: 'sec' }} labelPosition="right" defaultValue={secondsPerRowTemp} onKeyDown={this.onChangeTimelineViewSecondsPerRowViaInput} /> )} </Grid.Column> </Grid.Row> {sheetType === SHEET_TYPE.SCENES && ( <Grid.Row> <Grid.Column width={4}></Grid.Column> <Grid.Column width={12}> <Checkbox data-tid="changeTimelineViewFlow" label={<label className={styles.label}>Natural flow</label>} checked={defaultTimelineViewFlow} onChange={this.onChangeTimelineViewFlow} /> </Grid.Column> </Grid.Row> )} {sheetType === SHEET_TYPE.SCENES && ( <Grid.Row> <Grid.Column width={4}>Count</Grid.Column> <Grid.Column width={12}> <Checkbox data-tid="changeSceneCountCheckbox" label={<label className={styles.label}>Change scene count</label>} checked={this.state.changeSceneCount} onChange={this.onChangeSceneCount} /> </Grid.Column> </Grid.Row> )} {sheetType === SHEET_TYPE.SCENES && this.state.changeSceneCount && ( <> <Grid.Row> <Grid.Column width={4}>Shot detection threshold</Grid.Column> <Grid.Column width={12}> <SliderWithTooltip // data-tid='sceneDetectionThresholdSlider' className={styles.slider} min={3} max={40} defaultValue={defaultSceneDetectionThreshold} marks={{ 3: '3', 15: '15', 30: '30', }} handle={handle} onChange={onChangeSceneDetectionThreshold} /> </Grid.Column> </Grid.Row> <Grid.Row> <Grid.Column width={4}></Grid.Column> <Grid.Column width={12}> <Popup trigger={ <Button data-tid="runSceneDetectionBtn" fluid color="orange" loading={fileScanRunning} disabled={fileScanRunning} onClick={() => this.props.runSceneDetection( file.id, file.path, file.useRatio, defaultSceneDetectionThreshold, ) } > Add new MoviePrint </Button> } mouseEnterDelay={1000} on={['hover']} position="bottom center" className={stylesPop.popup} content="Run shot detection with new threshold" /> </Grid.Column> </Grid.Row> </> )} </> )} {sheetType === SHEET_TYPE.INTERVAL && isGridView && ( <Grid.Row> <Grid.Column width={4}>Count</Grid.Column> <Grid.Column width={12}> <Checkbox data-tid="changeThumbCountCheckbox" label={<label className={styles.label}>Change thumb count</label>} checked={reCapture} onChange={this.onChangeReCapture} /> </Grid.Column> </Grid.Row> )} {sheetType === SHEET_TYPE.INTERVAL && isGridView && thumbCount !== thumbCountTemp && ( <Grid.Row> <Grid.Column width={4} /> <Grid.Column width={12}> <Message data-tid="applyNewGridMessage" color="orange" size="mini"> Applying a new grid will overwrite your previously selected thumbs. Don&apos;t worry, this can be undone. </Message> </Grid.Column> </Grid.Row> )} {sheetType === SHEET_TYPE.INTERVAL && isGridView && ( <Grid.Row> <Grid.Column width={4} /> <Grid.Column width={12}> <Popup trigger={ <Button data-tid="applyNewGridBtn" fluid color="orange" disabled={thumbCount === thumbCountTemp} onClick={onApplyNewGridClick} > Apply </Button> } mouseEnterDelay={1000} on={['hover']} position="bottom center" className={stylesPop.popup} content="Apply new grid for MoviePrint" /> </Grid.Column> </Grid.Row> )} <Grid.Row> <Grid.Column width={16}> <Accordion inverted className={styles.accordion}> <Accordion.Title active={activeIndex === 0} index={0} onClick={this.handleClick}> <Icon name="dropdown" /> Guide layout </Accordion.Title> <Accordion.Content active={activeIndex === 0}> <Grid padded inverted> <Grid.Row> <Grid.Column width={4} textAlign="right" verticalAlign="middle"> <Checkbox data-tid="showPaperPreviewCheckbox" checked={defaultShowPaperPreview} onChange={this.onChangeShowPaperPreview} /> </Grid.Column> <Grid.Column width={12}> <Dropdown data-tid="paperLayoutOptionsDropdown" placeholder="Select..." selection disabled={!defaultShowPaperPreview} options={PAPER_LAYOUT_OPTIONS} defaultValue={defaultPaperAspectRatioInv} onChange={this.onChangePaperAspectRatio} /> </Grid.Column> </Grid.Row> </Grid> </Accordion.Content> <Accordion.Title active={activeIndex === 1} index={1} onClick={this.handleClick}> <Icon name="dropdown" /> Styling </Accordion.Title> <Accordion.Content active={activeIndex === 1}> <Grid padded inverted> <Grid.Row> <Grid.Column width={4}>Grid margin</Grid.Column> <Grid.Column width={12}> <SliderWithTooltip // data-tid='marginSlider' className={styles.slider} min={0} max={20} defaultValue={defaultMarginRatio * defaultMarginSliderFactor} marks={{ 0: '0', 20: '20', }} handle={handle} onChange={onChangeMargin} /> </Grid.Column> </Grid.Row> {!isGridView && ( <Grid.Row> <Grid.Column width={4}>Scene width ratio</Grid.Column> <Grid.Column width={12}> <SliderWithTooltip data-tid="sceneWidthRatioSlider" className={styles.slider} min={0} max={100} defaultValue={defaultTimelineViewWidthScale} marks={{ 0: '-10', 50: '0', 100: '+10', }} handle={handle} onChange={onChangeTimelineViewWidthScale} /> </Grid.Column> </Grid.Row> )} {!isGridView && ( <Grid.Row> <Grid.Column width={4}>Min scene width</Grid.Column> <Grid.Column width={12}> <SliderWithTooltip data-tid="minSceneWidthSlider" className={styles.slider} min={0} max={10} defaultValue={Math.round( defaultTimelineViewMinDisplaySceneLengthInFrames / (fileFps * 1.0), )} marks={{ 0: '0', 10: '10', }} handle={handle} onChange={onChangeMinDisplaySceneLength} /> </Grid.Column> </Grid.Row> )} <Grid.Row> <Grid.Column width={4}>Options</Grid.Column> <Grid.Column width={12}> <List> {isGridView && ( <> <List.Item> <Checkbox data-tid="showHeaderCheckbox" label={<label className={styles.label}>Show header</label>} checked={defaultShowHeader} onChange={this.onChangeShowHeader} /> </List.Item> <List.Item> <Checkbox data-tid="showFilePathCheckbox" className={styles.subCheckbox} label={<label className={styles.label}>Show file path</label>} disabled={!defaultShowHeader} checked={defaultShowPathInHeader} onChange={this.onChangeShowPathInHeader} /> </List.Item> <List.Item> <Checkbox data-tid="showFileDetailsCheckbox" className={styles.subCheckbox} label={<label className={styles.label}>Show file details</label>} disabled={!defaultShowHeader} checked={defaultShowDetailsInHeader} onChange={this.onChangeShowDetailsInHeader} /> </List.Item> <List.Item> <Checkbox data-tid="showTimelineCheckbox" className={styles.subCheckbox} label={<label className={styles.label}>Show timeline</label>} disabled={!defaultShowHeader} checked={defaultShowTimelineInHeader} onChange={this.onChangeShowTimelineInHeader} /> </List.Item> <List.Item> <Checkbox data-tid="roundedCornersCheckbox" label={<label className={styles.label}>Rounded corners</label>} checked={defaultRoundedCorners} onChange={this.onChangeRoundedCorners} /> </List.Item> <List.Item> <Checkbox data-tid="showHiddenThumbsCheckbox" label={<label className={styles.label}>Show hidden thumbs</label>} checked={visibilitySettings.visibilityFilter === THUMB_SELECTION.ALL_THUMBS} onChange={this.onChangeShowHiddenThumbs} /> </List.Item> </> )} </List> </Grid.Column> </Grid.Row> <Divider inverted /> <Grid.Row> <Grid.Column width={4}>Frame info</Grid.Column> <Grid.Column width={12}> <List> <List.Item> <Radio data-tid="showFramesRadioBtn" label={<label className={styles.label}>Show frames</label>} name="radioGroup" value="frames" checked={defaultThumbInfo === 'frames'} onChange={this.onChangeThumbInfo} /> </List.Item> <List.Item> <Radio data-tid="showTimecodeRadioBtn" label={<label className={styles.label}>Show timecode</label>} name="radioGroup" value="timecode" checked={defaultThumbInfo === 'timecode'} onChange={this.onChangeThumbInfo} /> </List.Item> <List.Item> <Radio data-tid="hideInfoRadioBtn" label={<label className={styles.label}>Hide info</label>} name="radioGroup" value="hideInfo" checked={defaultThumbInfo === 'hideInfo'} onChange={this.onChangeThumbInfo} /> </List.Item> </List> </Grid.Column> </Grid.Row> <Grid.Row> <Grid.Column width={4}>Font color</Grid.Column> <Grid.Column width={12}> <div> <div className={styles.colorPickerSwatch} onClick={e => this.colorPickerHandleClick(e, 'frameinfoColor')} > <Checkboard /> <div className={`${styles.colorPickerColor} ${styles.colorPickerText}`} style={{ backgroundColor: frameninfoBackgroundColorString, color: frameinfoColorString, }} > 00:00:00:00 </div> </div> {displayColorPicker.frameinfoColor ? ( <div className={styles.colorPickerPopover} // onMouseLeave={(e) => this.colorPickerHandleClose(e, 'frameinfoColor')} > <div className={styles.colorPickerCover} onClick={e => this.colorPickerHandleClose(e, 'frameinfoColor')} /> <SketchPicker color={defaultFrameinfoColor} onChange={color => this.colorPickerHandleChange('frameinfoColor', color)} presetColors={COLOR_PALETTE_PICO_EIGHT} /> </div> ) : null} </div> </Grid.Column> </Grid.Row> <Grid.Row> <Grid.Column width={4}>Background color</Grid.Column> <Grid.Column width={12}> <div> <div className={styles.colorPickerSwatch} onClick={e => this.colorPickerHandleClick(e, 'frameninfoBackgroundColor')} > <Checkboard /> <div className={styles.colorPickerColor} style={{ backgroundColor: frameninfoBackgroundColorString, }} /> </div> {displayColorPicker.frameninfoBackgroundColor ? ( <div className={styles.colorPickerPopover} // onMouseLeave={(e) => this.colorPickerHandleClose(e, 'frameninfoBackgroundColor')} > <div className={styles.colorPickerCover} onClick={e => this.colorPickerHandleClose(e, 'frameninfoBackgroundColor')} /> <SketchPicker color={defaultFrameinfoBackgroundColor} onChange={color => this.colorPickerHandleChange('frameninfoBackgroundColor', color)} presetColors={COLOR_PALETTE_PICO_EIGHT} /> </div> ) : null} </div> </Grid.Column> </Grid.Row> <Grid.Row> <Grid.Column width={4}>Position</Grid.Column> <Grid.Column width={12}> <Dropdown data-tid="changeFrameinfoPositionDropdown" placeholder="Select..." selection options={FRAMEINFO_POSITION_OPTIONS} defaultValue={defaultFrameinfoPosition} onChange={this.onChangeFrameinfoPosition} /> </Grid.Column> </Grid.Row> <Grid.Row> <Grid.Column width={4}>Size</Grid.Column> <Grid.Column width={12}> <SliderWithTooltip data-tid="frameinfoScaleSlider" className={styles.slider} min={1} max={100} defaultValue={defaultFrameinfoScale} marks={{ 1: '1', 10: '10', 100: '100', }} handle={handle} onChange={onChangeFrameinfoScale} /> </Grid.Column> </Grid.Row> <Grid.Row> <Grid.Column width={4}>Margin</Grid.Column> <Grid.Column width={12}> <SliderWithTooltip data-tid="frameinfoMarginSlider" className={styles.slider} min={0} max={50} defaultValue={defaultFrameinfoMargin} marks={{ 0: '0', 50: '50', }} handle={handle} onChange={onChangeFrameinfoMargin} /> </Grid.Column> </Grid.Row> </Grid> </Accordion.Content> <Accordion.Title active={activeIndex === 2} index={2} onClick={this.handleClick}> <Icon name="dropdown" /> Output </Accordion.Title> <Accordion.Content active={activeIndex === 2}> <Grid padded inverted> <Grid.Row> <Grid.Column width={4}>File path</Grid.Column> <Grid.Column width={12}> <List> <List.Item> <div style={{ wordWrap: 'break-word', opacity: defaultOutputPathFromMovie ? '0.5' : '1.0', }} > {defaultOutputPath} </div> </List.Item> <List.Item> <Button data-tid="changeOutputPathBtn" onClick={onChangeOutputPathClick} disabled={defaultOutputPathFromMovie} > Change... </Button> </List.Item> <List.Item> <Checkbox data-tid="showPaperPreviewCheckbox" label={<label className={styles.label}>Same as movie file</label>} style={{ marginTop: '8px', }} checked={defaultOutputPathFromMovie} onChange={this.onChangeOutputPathFromMovie} /> </List.Item> </List> </Grid.Column> </Grid.Row> <Divider inverted /> <Grid.Row> <Grid.Column width={16}> <h4>MoviePrint</h4> </Grid.Column> </Grid.Row> <Grid.Row> <Grid.Column width={4}>Size</Grid.Column> <Grid.Column width={12}> <Dropdown data-tid="changeMoviePrintWidthDropdown" placeholder="Select..." selection options={getOutputSizeOptions( MOVIEPRINT_WIDTH_HEIGHT, file, columnCountTemp, thumbCountTemp, settings, visibilitySettings, sceneArray, secondsPerRowTemp, isGridView, )} defaultValue={defaultMoviePrintWidth} onChange={this.onChangeMoviePrintWidth} /> </Grid.Column> </Grid.Row> <Grid.Row> <Grid.Column width={4}>Format</Grid.Column> <Grid.Column width={12}> <Dropdown data-tid="changeOutputFormatDropdown" placeholder="Select..." selection options={OUTPUT_FORMAT_OPTIONS} defaultValue={defaultOutputFormat} onChange={this.onChangeOutputFormat} /> </Grid.Column> </Grid.Row> {defaultOutputFormat === OUTPUT_FORMAT.JPG && ( <Grid.Row> <Grid.Column width={4}>JPG quality</Grid.Column> <Grid.Column width={12}> <SliderWithTooltip data-tid="outputJpgQualitySlider" className={styles.slider} min={0} max={100} defaultValue={defaultOutputJpgQuality} marks={{ 0: '0', 80: '80', 100: '100', }} handle={handle} onChange={onChangeOutputJpgQuality} /> </Grid.Column> </Grid.Row> )} <Grid.Row> <Grid.Column width={4}>Background color</Grid.Column> <Grid.Column width={12}> <div> <div className={styles.colorPickerSwatch} onClick={e => this.colorPickerHandleClick(e, 'moviePrintBackgroundColor')} > <Checkboard /> <div className={styles.colorPickerColor} style={{ backgroundColor: moviePrintBackgroundColorDependentOnFormatString, }} /> </div> {displayColorPicker.moviePrintBackgroundColor ? ( <div className={styles.colorPickerPopover} // onMouseLeave={(e) => this.colorPickerHandleClose(e, 'moviePrintBackgroundColor')} > <div className={styles.colorPickerCover} onClick={e => this.colorPickerHandleClose(e, 'moviePrintBackgroundColor')} /> <SketchPicker color={moviePrintBackgroundColorDependentOnFormat} onChange={color => this.colorPickerHandleChange('moviePrintBackgroundColor', color)} disableAlpha={defaultOutputFormat === OUTPUT_FORMAT.JPG} presetColors={COLOR_PALETTE_PICO_EIGHT} /> </div> ) : null} </div> </Grid.Column> </Grid.Row> <Grid.Row> <Grid.Column width={4}>Save options</Grid.Column> <Grid.Column width={12}> <List> <List.Item> <Checkbox data-tid="overwriteExistingCheckbox" label={<label className={styles.label}>Overwrite existing</label>} checked={defaultSaveOptionOverwrite} onChange={this.onChangeOverwrite} /> </List.Item> <List.Item> <Checkbox data-tid="includeIndividualFramesCheckbox" label={<label className={styles.label}>Include individual thumbs</label>} checked={defaultSaveOptionIncludeIndividual} onChange={this.onChangeIncludeIndividual} /> </List.Item> <List.Item> <Checkbox data-tid="embedFrameNumbersCheckbox" label={<label className={styles.label}>Embed frameNumbers (only PNG)</label>} checked={defaultEmbedFrameNumbers} onChange={this.onChangeEmbedFrameNumbers} /> </List.Item> <List.Item> <Checkbox data-tid="embedFilePathCheckbox" label={<label className={styles.label}>Embed filePath (only PNG)</label>} checked={defaultEmbedFilePath} onChange={this.onChangeEmbedFilePath} /> </List.Item> <List.Item> <Checkbox data-tid="embedFilePathCheckbox" label={<label className={styles.label}>Open File Explorer after saving</label>} checked={defaultOpenFileExplorerAfterSaving} onChange={this.onChangeOpenFileExplorerAfterSaving} /> </List.Item> </List> </Grid.Column> </Grid.Row> <Divider inverted /> <Grid.Row> <Grid.Column width={16}> <h4>Thumbs</h4> </Grid.Column> </Grid.Row> <Grid.Row> <Grid.Column width={4}>Format</Grid.Column> <Grid.Column width={12}> <Dropdown data-tid="changeThumbFormatDropdown" placeholder="Select..." selection options={OUTPUT_FORMAT_OPTIONS} defaultValue={defaultThumbFormat} onChange={this.onChangeThumbFormat} /> </Grid.Column> </Grid.Row> {defaultThumbFormat === OUTPUT_FORMAT.JPG && ( <Grid.Row> <Grid.Column width={4}>JPG quality</Grid.Column> <Grid.Column width={12}> <SliderWithTooltip data-tid="thumbJpgQualitySlider" className={styles.slider} min={0} max={100} defaultValue={defaultThumbJpgQuality} marks={{ 0: '0', 95: '95', 100: '100', }} handle={handle} onChange={onChangeThumbJpgQuality} /> </Grid.Column> </Grid.Row> )} </Grid> </Accordion.Content> <Accordion.Title active={activeIndex === 3} index={3} onClick={this.handleClick}> <Icon name="dropdown" /> Naming scheme </Accordion.Title> <Accordion.Content active={activeIndex === 3}> <Grid padded inverted> <Grid.Row> <Grid.Column width={16}> <label>File name when saving a MoviePrint</label> <Input // ref={this.inputDefaultMoviePrintName} data-tid="defaultMoviePrintNameInput" name="defaultMoviePrintNameInput" // needed for addAttributeIntoInput fluid placeholder="MoviePrint name" defaultValue={defaultMoviePrintName} onFocus={this.setFocusReference} onBlur={this.onSubmitDefaultMoviePrintName} onKeyUp={this.onSubmitDefaultMoviePrintName} /> <Label className={styles.previewCustomName}> {previewMoviePrintName}.{defaultOutputFormat} </Label> <Divider hidden className={styles.smallDivider} /> <label>File name of thumb when saving a single thumb</label> <Input // ref={this.inputDefaultSingleThumbName} data-tid="defaultSingleThumbNameInput" name="defaultSingleThumbNameInput" // needed for addAttributeIntoInput fluid placeholder="Name when saving a single thumb" defaultValue={defaultSingleThumbName} onFocus={this.setFocusReference} onBlur={this.onSubmitDefaultSingleThumbName} onKeyUp={this.onSubmitDefaultSingleThumbName} /> <Label className={styles.previewCustomName} color={defaultSingleThumbNameContainsFrameNumberOrTimeCode ? undefined : 'orange'} pointing={defaultSingleThumbNameContainsFrameNumberOrTimeCode ? undefined : true} > {defaultSingleThumbNameContainsFrameNumberOrTimeCode ? undefined : 'The framenumber attribute is missing. This can lead to the thumb being overwritten. | '} {previewSingleThumbName}.jpg </Label> <Divider hidden className={styles.smallDivider} /> <label> File name of thumbs when <em>Include individual thumbs</em> is selected </label> <Input // ref={this.inputDefaultAllThumbsName} data-tid="defaultAllThumbsNameInput" name="defaultAllThumbsNameInput" // needed for addAttributeIntoInput fluid placeholder="Name when including individual thumbs" defaultValue={defaultAllThumbsName} onFocus={this.setFocusReference} onBlur={this.onSubmitDefaultAllThumbsName} onKeyUp={this.onSubmitDefaultAllThumbsName} /> <Label className={styles.previewCustomName} color={defaultAllThumbsNameContainsFrameNumberOrTimeCode ? undefined : 'orange'} pointing={defaultAllThumbsNameContainsFrameNumberOrTimeCode ? undefined : true} > {defaultAllThumbsNameContainsFrameNumberOrTimeCode ? undefined : 'The framenumber attribute is missing. This can lead to the thumb being overwritten. | '} {previewAllThumbsName}.jpg </Label> <h6>Available attributes</h6> <Button data-tid="addAttribute[MN]IntoInputButton" className={styles.attributeButton} onClick={() => this.addAttributeIntoInput('[MN]')} disabled={focusReference === undefined} size="mini" > [MN] Movie name </Button> <Button data-tid="addAttribute[ME]IntoInputButton" className={styles.attributeButton} onClick={() => this.addAttributeIntoInput('[ME]')} disabled={focusReference === undefined} size="mini" > [ME] Movie extension </Button> <Button data-tid="addAttribute[MPN]IntoInputButton" className={styles.attributeButton} onClick={() => this.addAttributeIntoInput('[MPN]')} disabled={focusReference === undefined} size="mini" > [MPN] MoviePrint name </Button> <Button data-tid="addAttribute[FN]IntoInputButton" className={styles.attributeButton} onClick={() => this.addAttributeIntoInput('[FN]')} disabled={focusReference === undefined} size="mini" > [FN] Frame number </Button> <Button data-tid="addAttribute[TC]IntoInputButton" className={styles.attributeButton} onClick={() => this.addAttributeIntoInput('[TC]')} disabled={focusReference === undefined} size="mini" > [TC] Timecode </Button> </Grid.Column> </Grid.Row> </Grid> </Accordion.Content> <Accordion.Title active={activeIndex === 4} index={4} onClick={this.handleClick}> <Icon name="dropdown" /> Face detection </Accordion.Title> <Accordion.Content active={activeIndex === 4}> <Grid padded inverted> <Grid.Row> <Grid.Column width={4}>Face confidence threshold</Grid.Column> <Grid.Column width={12}> <SliderWithTooltip data-tid="faceConfidenceThresholdSlider" className={styles.slider} min={0} max={100} defaultValue={defaultFaceConfidenceThreshold} marks={{ 0: '0', 50: '50', 100: '100', }} handle={handle} onChange={onChangeFaceConfidenceThreshold} /> </Grid.Column> </Grid.Row> <Grid.Row> <Grid.Column width={4}>Face size threshold</Grid.Column> <Grid.Column width={12}> <SliderWithTooltip data-tid="faceSizeThresholdSlider" className={styles.slider} min={0} max={100} defaultValue={defaultFaceSizeThreshold} marks={{ 0: '0', 50: '50', 100: '100', }} handle={handle} onChange={onChangeFaceSizeThreshold} /> <br /> <em>Changes take effect on next face scan.</em> </Grid.Column> </Grid.Row> </Grid> </Accordion.Content> <Accordion.Title active={activeIndex === 5} index={5} onClick={this.handleClick}> <Icon name="dropdown" /> Frame cache </Accordion.Title> <Accordion.Content active={activeIndex === 5}> <Grid padded inverted> <Grid.Row> <Grid.Column width={4}>Max size</Grid.Column> <Grid.Column width={12}> <Dropdown data-tid="changeCachedFramesSizeDropdown" placeholder="Select..." selection options={CACHED_FRAMES_SIZE_OPTIONS} defaultValue={defaultCachedFramesSize} onChange={this.onChangeCachedFramesSize} /> </Grid.Column> </Grid.Row> <Grid.Row> <Grid.Column width={4} /> <Grid.Column width={12}> <Popup trigger={ <Button data-tid="updateFrameCacheBtn" onClick={recaptureAllFrames}> Update frame cache </Button> } mouseEnterDelay={1000} on={['hover']} position="bottom center" className={stylesPop.popup} content="Recapture all frames and store it in the frame cache (uses max size)" /> </Grid.Column> </Grid.Row> </Grid> </Accordion.Content> <Accordion.Title active={activeIndex === 6} index={6} onClick={this.handleClick}> <Icon name="dropdown" /> Experimental </Accordion.Title> <Accordion.Content active={activeIndex === 6}> <Grid padded inverted> <Grid.Row> <Grid.Column width={4}>Shot detection method</Grid.Column> <Grid.Column width={12}> <Dropdown data-tid="shotDetectionMethodOptionsDropdown" placeholder="Select..." selection options={SHOT_DETECTION_METHOD_OPTIONS} defaultValue={defaultShotDetectionMethod} onChange={this.onChangeShotDetectionMethod} /> </Grid.Column> </Grid.Row> <Grid.Row> <Grid.Column width={4}>Detection chart</Grid.Column> <Grid.Column width={12}> <Popup trigger={ <Button data-tid="showDetectionChartBtn" // fluid onClick={onToggleDetectionChart} > {showChart ? 'Hide detection chart' : 'Show detection chart'} </Button> } mouseEnterDelay={1000} on={['hover']} position="bottom center" className={stylesPop.popup} content="Show detection chart with mean and difference values per frame" /> </Grid.Column> </Grid.Row> <Grid.Row> <Grid.Column width={4}>Import options</Grid.Column> <Grid.Column width={12}> <Checkbox data-tid="automaticDetectionInOutPointCheckbox" label={<label className={styles.label}>Automatic detection of In and Outpoint</label>} checked={defaultDetectInOutPoint} onChange={this.onChangeDetectInOutPoint} /> </Grid.Column> </Grid.Row> <Grid.Row> <Grid.Column width={4}>Expert</Grid.Column> <Grid.Column width={12}> <Checkbox data-tid="showSlidersCheckbox" label={<label className={styles.label}>Show input field instead of slider</label>} checked={!this.state.showSliders} onChange={this.onShowSliders} /> </Grid.Column> </Grid.Row> </Grid> </Accordion.Content> </Accordion> </Grid.Column> </Grid.Row> </Grid> </Container> ); } } SettingsList.contextTypes = { store: PropTypes.object, }; export default SettingsList; <|start_filename|>app/package.json<|end_filename|> { "name": "MoviePrint_v004", "productName": "MoviePrint_v004", "version": "0.2.23", "description": "A tool which lets you create screenshots of entire movies in an instant.", "main": "./main.prod.js", "author": { "name": "<NAME>", "email": "<EMAIL>", "url": "https://movieprint.org" }, "license": "MIT", "bugs": { "url": "https://github.com/fakob/MoviePrint_v004/issues" }, "keywords": [ "opencv", "screenshot", "movie" ], "homepage": "https://github.com/fakob/MoviePrint_v004#readme", "scripts": { "electron-rebuild": "node -r ../internals/scripts/BabelRegister.js ../internals/scripts/ElectronRebuild.js", "postinstall": "yarn electron-rebuild -w opencv4nodejs,better-sqlite3,@tensorflow/tfjs-node" }, "dependencies": { "@tensorflow/tfjs-node": "^1.5.2", "better-sqlite3": "^5.4.0", "face-api.js": "^0.22.1", "opencv4nodejs": "^4.9.1", "typeface-open-sans": "^0.0.54", "typeface-roboto-condensed": "^0.0.54", "typeface-ubuntu": "^0.0.65" } } <|start_filename|>app/utils/utilsForIndexedDB.js<|end_filename|> import log from 'electron-log'; import imageDB from './db'; const { ipcRenderer } = require('electron'); export const openDBConnection = () => { // dexie documentation: // Even though open() is asynchronous, // you can already now start interact with the database. // The operations will be pending until open() completes. // If open() succeeds, the operations below will resume. // If open() fails, the below operations below will fail and if (!imageDB.isOpen()) { imageDB.open().catch(err => { log.error(`Failed to open imageDB: ${err.stack || err}`); }); } }; export const deleteTableFramelist = () => imageDB.frameList.clear().catch(err => { log.error(`Failed to delete all objects in frameList: ${err.stack || err}`); }); export const addFrameToIndexedDB = (frameId, fileId, frameNumber, outBase64, objectUrlQueue) => { const url = `data:image/jpg;base64,${outBase64}`; return fetch(url) .then(res => res.blob()) .then(blob => { try { return imageDB .transaction('rw', imageDB.frameList, async () => { await imageDB.frameList.put({ frameId, fileId, frameNumber, data: blob, }); const key = await imageDB.frameList.get(frameId); // console.log(key); return key; }) .catch(e => { log.error('error inside addFrameToIndexedDB - transaction'); log.error(e.stack || e); }); } catch (e) { log.error(e.stack || e); return undefined; } }) .then(frame => { // console.log(frame); const objectUrl = window.URL.createObjectURL(frame.data); objectUrlQueue.add({ frameId, objectUrl, }); return objectUrl; }) .catch(e => { log.error(e.stack || e); }); }; export const updateFrameInIndexedDB = (frameId, outBase64, objectUrlQueue, fastTrack) => { if (outBase64 === '') { return undefined; } const url = `data:image/jpg;base64,${outBase64}`; fetch(url) .then(res => res.blob()) .then(blob => { return imageDB .transaction('rw', imageDB.frameList, async () => { await imageDB.frameList .where('frameId') .equals(frameId) .modify({ data: blob, }); const key = await imageDB.frameList.get(frameId); console.log(key); return key; }) .then(key => { console.log('Transaction committed'); return key; }) .catch(e => { log.error('error inside updateFrameInIndexedDB - transaction'); log.error(e.stack || e); }); }) .then(frame => { console.log(frame); if (frame !== undefined) { const objectUrl = window.URL.createObjectURL(frame.data); if (fastTrack) { ipcRenderer.send('message-from-databaseWorkerWindow-to-mainWindow', 'update-objectUrl', frameId, objectUrl); } else { objectUrlQueue.add({ frameId, objectUrl, }); } return objectUrl; } return undefined; }) .catch(e => { log.error(e.stack || e); }); }; export const getObjectUrlsFromFramelist = objectUrlQueue => { console.log('inside getObjectUrlsFromFramelist'); try { log.warn(imageDB.isOpen()); imageDB .transaction('r', imageDB.frameList, async () => { try { console.log(imageDB.isOpen()); const array = await imageDB.frameList.toArray().catch(e => { log.error('error inside promise catch'); log.error(e.stack || e); }); if (array.length === 0) { return []; } const arrayOfObjectUrls = []; array.map(frame => { const objectUrl = window.URL.createObjectURL(frame.data); if (objectUrl !== undefined) { arrayOfObjectUrls.push({ frameId: frame.frameId, objectUrl: window.URL.createObjectURL(frame.data), }); } return undefined; }); objectUrlQueue.addArray(arrayOfObjectUrls); return undefined; } catch (e) { log.error('error inside the inner try catch'); log.error(e.stack || e); } }) .catch(e => { log.error('error inside promise catch'); log.error(e.stack || e); }); } catch (e) { log.error('error inside try catch'); log.error(e.stack || e); } }; <|start_filename|>app/utils/faceDetection.js<|end_filename|> /* eslint import/prefer-default-export: "off" */ import path from 'path'; import * as faceapi from 'face-api.js'; import log from 'electron-log'; import uuidV4 from 'uuid/v4'; import { roundNumber } from './utils'; import { FACE_CONFIDENCE_THRESHOLD, FACE_SIZE_THRESHOLD } from './constants'; const { ipcRenderer } = require('electron'); const { app } = require('electron').remote; const appPath = app.getAppPath(); const weightsPath = path.join(appPath, './dist/weights'); const loadNet = async () => { const toastId = 'loadNet'; ipcRenderer.send( 'message-from-opencvWorkerWindow-to-mainWindow', 'progressMessage', 'info', 'Initialising face detection', false, toastId, ); log.debug(weightsPath); log.debug(faceapi.nets); const detectionNet = faceapi.nets.ssdMobilenetv1; log.debug(detectionNet); await detectionNet.loadFromDisk(weightsPath); await faceapi.nets.faceLandmark68Net.loadFromDisk(weightsPath); await faceapi.nets.ageGenderNet.loadFromDisk(weightsPath); await faceapi.nets.faceRecognitionNet.loadFromDisk(weightsPath); ipcRenderer.send( 'message-from-opencvWorkerWindow-to-mainWindow', 'progressMessage', 'success', 'Face detection successfully initialised', 3000, toastId, true, ); return detectionNet; }; loadNet() .then(detectionNet => { log.debug(detectionNet); return undefined; }) .catch(error => { log.error(`There has been a problem with your loadNet operation: ${error.message}`); ipcRenderer.send( 'message-from-opencvWorkerWindow-to-mainWindow', 'progressMessage', 'error', `There has been a problem with your loadNet operation: ${error.message}`, false, 'loadNet', true, ); }); export const detectAllFaces = async ( image, frameNumber, detectionArray, defaultFaceConfidenceThreshold = FACE_SIZE_THRESHOLD, defaultFaceSizeThreshold = FACE_CONFIDENCE_THRESHOLD, ) => { // detect expression const detections = await faceapi .detectAllFaces(image) .withFaceLandmarks() .withAgeAndGender() .withFaceDescriptors(); console.log(frameNumber); const faceCount = detections.length; if (faceCount === 0) { console.log('no face detected!'); detectionArray.push({ frameNumber, faceCount, }); return detections; } console.log(`Face count: ${faceCount}`); console.log(detections); const facesArray = []; detections.forEach(face => { const { age, gender, descriptor, detection } = face; const { relativeBox, score } = detection; const size = Math.round(relativeBox.height * 100); const scoreInPercent = Math.round(score * 100); // create full copy of array to be pushed later const copyOfDescriptor = descriptor.slice(); // console.log(detection); // console.log(uniqueFaceArray); // console.log(copyOfDescriptor); // console.log(face); if (size < defaultFaceSizeThreshold || scoreInPercent < defaultFaceConfidenceThreshold) { console.log('detected face below size or confidence threshold!'); return undefined; } const simpleBox = { x: roundNumber(relativeBox.x, 4), y: roundNumber(relativeBox.y, 4), width: roundNumber(relativeBox.width, 4), height: roundNumber(relativeBox.height, 4), }; facesArray.push({ score: scoreInPercent, size, box: simpleBox, gender, age: Math.round(age), faceId: uuidV4(), faceDescriptor: copyOfDescriptor, }); // const drawBox = new faceapi.draw.DrawBox(box, { // // label: Math.round(age), // label: faceId, // lineWidth: 1, // boxColor: 'red' // }) // drawBox.draw(image); }); if (facesArray.length === 0) { // no faces stored as they are below thresholds detectionArray.push({ frameNumber, faceCount, }); return detections; } // sort faces by size with the largest one first facesArray.sort((face1, face2) => face2.size - face1.size); console.log(facesArray); detectionArray.push({ frameNumber, faceCount, largestSize: facesArray[0].size, facesArray, }); return detections; }; <|start_filename|>app/components/ErrorBoundary.css<|end_filename|> .ErrorContainer{ position: relative;/* need this to position inner content */ background-color: #1e1e1e; width: 100%; /* Full width */ height: 100vh; /* Full height */ } .ErrorContent{ position: absolute; top: 50%; left: 50%; right: auto; bottom: auto; margin-right: -50%; transform: translate(-50%, -50%); outline: 0; font-size: 100px; font-weight: 600; line-height: 100px; text-align: center; color: #fff; letter-spacing: 1px; margin: auto; font-family: 'Franchise', 'Roboto Condensed'; } <|start_filename|>app/utils/constants.js<|end_filename|> import path from 'path'; import { RotateFlags } from './openCVProperties'; const { app } = require('electron').remote; // throws error as it would be packed into main.js where this is can not be required // tried it again and it seems to work, lets see export const URL_CHANGE_LOG = 'https://movieprint.org/download/'; export const URL_REST_API_CHECK_FOR_UPDATES = 'https://movieprint.org/wp-json/wp/v2/pages/114'; // _Latest_Release page export const URL_FEEDBACK_FORM = 'http://movieprint.org/contact-us-from-movieprint-app'; export const SHOT_DETECTION_METHOD = { MEAN: 'meanAverage', HIST: 'histogram', }; export const THUMB_SELECTION = { ALL_THUMBS: 'allThumbs', VISIBLE_THUMBS: 'visibleThumbs', HIDDEN_THUMBS: 'hiddenThumbs', }; export const SHOT_DETECTION_METHOD_OPTIONS = [ { value: SHOT_DETECTION_METHOD.MEAN, text: 'Mean average', 'data-tid': 'shotDetectionMethodOptionsMean' }, { value: SHOT_DETECTION_METHOD.HIST, text: 'Histogram', 'data-tid': 'shotDetectionMethodOptionsHist' }, ]; export const OUTPUT_FORMAT = { PNG: 'png', JPG: 'jpg', }; export const MOVIEPRINT_WIDTH_HEIGHT_SIZE_LIMIT = 16384; // due to browser limitations https://html2canvas.hertzen.com/faq export const MOVIEPRINT_WIDTH_HEIGHT = [ 1024, 2048, 3072, 4096, 5120, 6144, 7168, 8192, 9216, 10240, 11264, 12288, 13312, 14336, 15360, 16384, ]; export const SCALE_VALUE_ARRAY = [0.25, 0.33, 0.5, 0.75, 1, 2, 3, 4, 5, 6, 7, 8]; export const COLOR_PALETTE_PICO_EIGHT = [ 'transparent', '#000000', '#FFFFFF', '#0C0C0C', '#1E1E1E', '#FF5006', '#FF9365', '#B44E23', '#D14003', '#1D2B53', '#7E2553', '#008751', '#AB5236', '#5F574F', '#C2C3C7', '#FFF1E8', '#FF004D', '#FFA300', '#FFEC27', '#00E436', '#29ADFF', '#83769C', '#FF77A8', '#FFCCAA', ]; export const FRAMEINFO_POSITION = { TOPLEFT: 'topLeft', TOPCENTER: 'topCenter', TOPRIGHT: 'topRight', CENTERCENTER: 'centerCenter', BOTTOMLEFT: 'bottomLeft', BOTTOMCENTER: 'bottomCenter', BOTTOMRIGHT: 'bottomRight', }; export const FRAMEINFO_POSITION_OPTIONS = [ { value: FRAMEINFO_POSITION.TOPLEFT, text: 'Top Left', 'data-tid': 'frameinfoPositionOptionTopLeft' }, { value: FRAMEINFO_POSITION.TOPCENTER, text: 'Top Center', 'data-tid': 'frameinfoPositionOptionTopCenter' }, { value: FRAMEINFO_POSITION.TOPRIGHT, text: 'Top Right', 'data-tid': 'frameinfoPositionOptionTopRight' }, { value: FRAMEINFO_POSITION.CENTERCENTER, text: 'Center Center', 'data-tid': 'frameinfoPositionOptionCenterCenter' }, { value: FRAMEINFO_POSITION.BOTTOMLEFT, text: 'Bottom Left', 'data-tid': 'frameinfoPositionOptionBottomLeft' }, { value: FRAMEINFO_POSITION.BOTTOMCENTER, text: 'Bottom Center', 'data-tid': 'frameinfoPositionOptionBottomCenter' }, { value: FRAMEINFO_POSITION.BOTTOMRIGHT, text: 'Bottom Right', 'data-tid': 'frameinfoPositionOptionBottomRight' }, ]; export const SHEET_FIT = { WIDTH: 'width', HEIGHT: 'height', BOTH: 'both', NOSCALE: 'noScale', }; export const SHEET_TYPE = { INTERVAL: 'interval', SCENES: 'shot', FACES: 'faces', }; export const SHEET_TYPE_OPTIONS = [ { value: SHEET_TYPE.INTERVAL, text: 'Interval', 'data-tid': 'sheetTypeOptionsInterval' }, { value: SHEET_TYPE.SCENES, text: 'Scenes', 'data-tid': 'sheetTypeOptionsScenes' }, { value: SHEET_TYPE.FACES, text: 'Faces', 'data-tid': 'sheetTypeOptionsFaces' }, ]; export const THUMB_INFO = { FRAMES: 'frames', TIMECODE: 'timecode', HIDEINFO: 'hideInfo', }; export const THUMB_INFO_OPTIONS = [ { value: THUMB_INFO.FRAMES, text: 'Show frames', 'data-tid': 'framesOption' }, { value: THUMB_INFO.TIMECODE, text: 'Show timecode', 'data-tid': 'timecodeOption' }, { value: THUMB_INFO.HIDEINFO, text: 'Hide info', 'data-tid': 'hideInfoOption' }, ]; export const SHEET_VIEW = { GRIDVIEW: 'gridView', TIMELINEVIEW: 'timelineView', }; export const VIEW = { PLAYERVIEW: 'playerView', STANDARDVIEW: 'standardView', }; export const MOVIEPRINT_COLORS = ['#FF5006', '#FFb799', '#FF9365', '#FFa883', '#FFd3c1']; export const PAPER_LAYOUT_OPTIONS = [ { value: 0.71, text: 'A0-A5 (Landscape)', 'data-tid': 'A0-A5-L' }, { value: 1.41, text: 'A0-A5 (Portrait)', 'data-tid': 'A0-A5-P' }, { value: 0.77, text: 'Letter (Landscape)', 'data-tid': 'Letter-L' }, { value: 1.29, text: 'Letter (Portrait)', 'data-tid': 'Letter-P' }, { value: 0.61, text: 'Legal (Landscape)', 'data-tid': 'Legal-L' }, { value: 1.65, text: 'Legal (Portrait)', 'data-tid': 'Legal-P' }, { value: 0.65, text: 'Tabloid (Landscape)', 'data-tid': 'Tabloid-L' }, { value: 1.55, text: 'Tabloid (Portrait)', 'data-tid': 'Tabloid-P' }, { value: 1.0, text: 'Square', 'data-tid': 'Square' }, { value: 0.75, text: '4:3', 'data-tid': '4:3' }, { value: 0.625, text: '16:10', 'data-tid': '16:10' }, { value: 0.5625, text: '16:9', 'data-tid': '16:9' }, { value: 0.5, text: '2:1', 'data-tid': '2:1' }, { value: 1.778, text: '9:16', 'data-tid': '9:16' }, { value: 2.0, text: '1:2', 'data-tid': '1:2' }, ]; export const OUTPUT_FORMAT_OPTIONS = [ { value: OUTPUT_FORMAT.PNG, text: 'PNG', 'data-tid': 'pngOption' }, { value: OUTPUT_FORMAT.JPG, text: 'JPG', 'data-tid': 'jpgOption' }, ]; export const EXPORT_FORMAT_OPTIONS = { JSON: 'json', EDL: 'edl', }; export const CACHED_FRAMES_SIZE_OPTIONS = [ { value: 0, text: 'Original size', 'data-tid': 'originalSizeOption' }, // 0 stands for original size { value: 80, text: '80px', 'data-tid': '80option' }, { value: 160, text: '160px', 'data-tid': '160option' }, { value: 320, text: '320px', 'data-tid': '320option' }, { value: 640, text: '640px', 'data-tid': '640option' }, { value: 720, text: '720px', 'data-tid': '720option' }, ]; // start initialStateJSON export const VISIBILITY_FILTER = THUMB_SELECTION.VISIBLE_THUMBS; export const SHOW_MOVIELIST = false; export const SHOW_SETTINGS = false; export const DEFAULT_VIEW = VIEW.STANDARDVIEW; export const DEFAULT_SHEETVIEW = SHEET_VIEW.GRIDVIEW; export const DEFAULT_SHEET_TYPE = SHEET_TYPE.INTERVAL; export const DEFAULT_SHEET_FIT = SHEET_FIT.BOTH; export const DEFAULT_THUMB_COUNT_MAX = 10000; export const DEFAULT_THUMB_COUNT = 16; export const DEFAULT_COLUMN_COUNT = 4; export const DEFAULT_THUMBNAIL_SCALE = 0.25; export const DEFAULT_MOVIEPRINT_WIDTH = 4096; export const DEFAULT_MARGIN_RATIO = 0.02; export const DEFAULT_MARGIN_SLIDER_FACTOR = 200.0; export const DEFAULT_BORDER_RADIUS_RATIO = 0.04; export const DEFAULT_HEADER_HEIGHT_RATIO = 0.25; export const DEFAULT_SHOW_HEADER = false; export const DEFAULT_SHOW_PATH_IN_HEADER = true; export const DEFAULT_SHOW_DETAILS_IN_HEADER = true; export const DEFAULT_SHOW_TIMELINE_IN_HEADER = true; export const DEFAULT_ROUNDED_CORNERS = true; export const DEFAULT_THUMB_INFO = 'hideInfo'; export const DEFAULT_THUMB_INFO_RATIO = 0.075; // export const DEFAULT_OUTPUT_PATH = app.getPath('desktop'); // throws error see above export const DEFAULT_OUTPUT_PATH_FROM_MOVIE = false; export const DEFAULT_OUTPUT_FORMAT = OUTPUT_FORMAT.PNG; export const DEFAULT_OUTPUT_JPG_QUALITY = 80; export const DEFAULT_THUMB_FORMAT = OUTPUT_FORMAT.JPG; export const DEFAULT_THUMB_JPG_QUALITY = 95; export const DEFAULT_SAVE_OPTION_OVERWRITE = false; export const DEFAULT_SAVE_OPTION_INCLUDE_INDIVIDUAL = false; export const DEFAULT_VIDEO_PLAYER_HEIGHT = 360; export const DEFAULT_VIDEO_PLAYER_WIDTH = 640; export const DEFAULT_VIDEO_PLAYER_CONTROLLER_HEIGHT = 84; export const DEFAULT_BORDER_MARGIN = 24; export const DEFAULT_SHOW_PAPER_PREVIEW = false; export const DEFAULT_PAPER_ASPECTRATIOINV = 0.71; export const DEFAULT_DETECT_INOUTPOINT = false; export const DEFAULT_SCRUB_CONTAINER_MAXHEIGHTRATIO = 0.8; export const DEFAULT_SCRUB_WINDOW_WIDTHRATIO = 0.5; export const DEFAULT_SCRUB_WINDOW_HEIGHTRATIO = 0.5; export const DEFAULT_SCRUB_WINDOW_MARGIN = 2; export const DEFAULT_SCENE_DETECTION_THRESHOLD = 6.0; export const DEFAULT_TIMELINEVIEW_SECONDS_PER_ROW = 120.0; export const DEFAULT_TIMELINEVIEW_MIN_DISPLAY_SCENE_LENGTH_IN_FRAMES = 10; export const DEFAULT_TIMELINEVIEW_WIDTH_SCALE = 50; export const DEFAULT_TIMELINEVIEW_FLOW = false; export const DEFAULT_CACHED_FRAMES_SIZE = 640; // 0 stands for original size export const DEFAULT_EMBED_FRAMENUMBERS = true; export const DEFAULT_EMBED_FILEPATH = true; export const DEFAULT_SHOW_IMAGES = true; export const DEFAULT_MOVIEPRINT_BACKGROUND_COLOR = { r: 0, g: 0, b: 0, a: 0 }; export const DEFAULT_FRAMEINFO_BACKGROUND_COLOR = { r: 238, g: 238, b: 238, a: 1 }; export const DEFAULT_FRAMEINFO_COLOR = { r: 0, g: 0, b: 0, a: 1 }; export const DEFAULT_FRAMEINFO_POSITION = FRAMEINFO_POSITION.TOPLEFT; export const DEFAULT_FRAMEINFO_SCALE = 10.0; export const DEFAULT_FRAMEINFO_MARGIN = 0; export const DEFAULT_MOVIEPRINT_NAME = '[MN].[ME]-[MPN]'; export const DEFAULT_SINGLETHUMB_NAME = '[MN].[ME]-frame[FN]'; export const DEFAULT_ALLTHUMBS_NAME = '[MN].[ME]-[FN]'; export const DEFAULT_OPEN_FILE_EXPLORER_AFTER_SAVING = false; export const DEFAULT_SHOW_FACERECT = true; // end initialStateJSON // fallback window measures export const WINDOW_WIDTH = 1366; // main window width and height is set in main.dev.js export const WINDOW_HEIGHT = 768; export const MENU_HEADER_HEIGHT = 35; export const MENU_FOOTER_HEIGHT = 35; export const ZOOM_SCALE = 4; // index of SCALE_VALUE_ARRAY export const PAPER_ADJUSTMENT_SCALE = 0.9; export const MARGIN_ADJUSTMENT_SCALE = 0.95; export const DEFAULT_MOVIE_WIDTH = 1920; export const DEFAULT_MOVIE_HEIGHT = 1080; export const DEFAULT_MOVIE_ASPECTRATIO = 1.778; // fixes jumping of thumbs due to hoverButton by giving the moviePrint some extra space around // should be 0 for printing export const DEFAULT_MIN_MOVIEPRINTWIDTH_MARGIN = 10; export const MINIMUM_WIDTH_TO_SHRINK_HOVER = 160; // if smaller then scale hover to 0.7 export const MINIMUM_WIDTH_TO_SHOW_HOVER = 100; // if smaller then do not show hover elements over thumb export const CHANGE_THUMB_STEP = [1, 10, 100]; export const IN_OUT_POINT_SEARCH_LENGTH = 300; export const IN_OUT_POINT_SEARCH_THRESHOLD = 20; // previous 15 export const SCENE_DETECTION_MIN_SCENE_LENGTH = 10; // for scene detection export const DEFAULT_FRAME_SCALE = 1; // scale of frames to be stored in the database if 1 then original size is stored export const FRAMESDB_PATH = path.join(app.getPath('userData'), 'moviePrint_frames.db'); export const STATEID = '1'; export const SCRUBCUT_SLICE_ARRAY_SIZE = 19; // videoPlayer export const VIDEOPLAYER_SLICEGAP = 1; export const VIDEOPLAYER_CUTGAP = 8; export const VIDEOPLAYER_SLICE_ARRAY_SIZE = 20; export const VIDEOPLAYER_SCENE_MARGIN = 4; export const VIDEOPLAYER_THUMB_MARGIN = 4; export const VIDEOPLAYER_FIXED_PIXEL_PER_FRAME_RATIO = 0.3; export const TIMELINE_SCENE_MINIMUM_WIDTH = 2; // heightOfInOutPointButtons export const TIMELINE_PLAYHEAD_MINIMUM_WIDTH = 2; // face detection export const FACE_SIZE_THRESHOLD = 10; // faces smaller than this percentage of the movie height are ignored export const FACE_CONFIDENCE_THRESHOLD = 70; // detected faces with a lower score are ignored export const FACE_UNIQUENESS_THRESHOLD = 0.6; // faces with a euclideanDistance larger than this are considered unique export const SORT_METHOD = { AGE: 'age', DISTTOORIGIN: 'distToOrigin', FACECONFIDENCE: 'score', FACECOUNT: 'faceCount', FACEOCCURRENCE: 'faceOccurrence', FACESIZE: 'size', FRAMENUMBER: 'frameNumber', GENDER: 'gender', REVERSE: 'reverse', }; export const SORT_METHOD_OPTIONS = [ { value: SORT_METHOD.FRAMENUMBER, text: 'framenumber', 'data-tid': 'sortMethodOptionsFrameNumber' }, { value: SORT_METHOD.FACESIZE, text: 'size of face', 'data-tid': 'sortMethodOptionsFaceSize' }, { value: SORT_METHOD.FACECOUNT, text: 'number of faces', 'data-tid': 'sortMethodOptionsFaceCount' }, { value: SORT_METHOD.FACEOCCURRENCE, text: 'occurrence of face', 'data-tid': 'sortMethodOptionsFaceOccurrence' }, { value: SORT_METHOD.DISTTOORIGIN, text: 'distance to origin', 'data-tid': 'sortMethodOptionsDistToOrigin' }, { value: SORT_METHOD.FACECONFIDENCE, text: 'confidence of face', 'data-tid': 'sortMethodOptionsFaceConfidence' }, { value: SORT_METHOD.REVERSE, text: 'reverse order', 'data-tid': 'sortMethodOptionsReverse' }, ]; export const FILTER_METHOD = { AGE: 'age', // range DISTTOORIGIN: 'distToOrigin', // equals/range FACECONFIDENCE: 'score', // range FACECOUNT: 'faceCount', // range FACEID: 'faceId', // equals array FACEOCCURRENCE: 'faceOccurrence', // range FACESIZE: 'size', // range GENDER: 'gender', // equals }; export const FILTER_METHOD_AGE = { MIN: 0, LOWER: 20, UPPER: 40, MAX: 100, // slider max value MAXMAX: 200, // max value when filtering to not exclude top values }; export const FILTER_METHOD_FACECOUNT = { MIN: 1, LOWER: 1, UPPER: 3, MAX: 10, // slider max value MAXMAX: 100, // max value when filtering to not exclude top values }; export const FILTER_METHOD_FACEOCCURRENCE = { MIN: 1, LOWER: 10, UPPER: 100, MAX: 100, // slider max value MAXMAX: 10000, // max value when filtering to not exclude top values }; export const FILTER_METHOD_FACESIZE = { // MIN: 1, // no MIN value -> handled by defaultFaceSizeThreshold LOWER: 50, UPPER: 100, MEDIUM: 30, CLOSE: 75, MAX: 100, // slider max value MAXMAX: 1000, // max value when filtering to not exclude top values }; // app settings export const UNDO_STEPS_LIMIT = 50; // undo redo // edit transform export const TRANSFORMOBJECT_INIT = { cropTop: 0, cropLeft: 0, cropBottom: 0, cropRight: 0, rotationFlag: RotateFlags.NO_ROTATION, aspectRatioInv: null, }; export const EDIT_TRANSFORM_CANVAS_WIDTH = 480; export const EDIT_TRANSFORM_CANVAS_HEIGHT = 480; export const ROTATION_OPTIONS = [ { value: RotateFlags.NO_ROTATION, text: 'No rotation', 'data-tid': 'rotationOptions0' }, { value: RotateFlags.ROTATE_90_CLOCKWISE, text: '90º clockwise', 'data-tid': 'rotationOptions90' }, { value: RotateFlags.ROTATE_180, text: '180º', 'data-tid': 'rotationOptions180' }, { value: RotateFlags.ROTATE_90_COUNTERCLOCKWISE, text: '90º counterclockwise', 'data-tid': 'rotationOptions270', }, ]; export const ASPECT_RATIO_OPTIONS = [ { value: null, text: 'Reset', 'data-tid': 'Reset' }, { value: 0.5625, text: '16:9', 'data-tid': '16:9' }, { value: 0.75, text: '4:3', 'data-tid': '4:3' }, { value: 1.0, text: '1:1', 'data-tid': '1:1' }, { value: 0.625, text: '16:10', 'data-tid': '16:10' }, { value: 0.5405, text: '1.85:1', 'data-tid': '1.85:1' }, { value: 0.5525, text: '2.21:1', 'data-tid': '2.21:1' }, { value: 0.4255, text: '2.35:1', 'data-tid': '2.35:1' }, { value: 0.4184, text: '2.39:1', 'data-tid': '2.39:1' }, { value: 0.6, text: '5:3', 'data-tid': '5:3' }, { value: 0.8, text: '5:4', 'data-tid': '5:4' }, ]; export const CROP_OPTIONS = [ { value: null, text: 'Reset', 'data-tid': 'Reset' }, { value: 0.625, text: '16:10', 'data-tid': '16:10' }, { value: 0.5625, text: '16:9', 'data-tid': '16:9' }, { value: 0.75, text: '4:3', 'data-tid': '4:3' }, { value: 0.5405, text: '1.85:1', 'data-tid': '1.85:1' }, { value: 0.5525, text: '2.21:1', 'data-tid': '2.21:1' }, { value: 0.4255, text: '2.35:1', 'data-tid': '2.35:1' }, { value: 0.4184, text: '2.39:1', 'data-tid': '2.39:1' }, { value: 0.5, text: '2:1', 'data-tid': '2:1' }, { value: 0.6, text: '5:3', 'data-tid': '5:3' }, { value: 0.8, text: '5:4', 'data-tid': '5:4' }, { value: 1.0, text: '1:1', 'data-tid': '1:1' }, { value: 1.25, text: '4:5', 'data-tid': '4:5' }, { value: 1.5, text: '2:3', 'data-tid': '2:3' }, { value: 1.7778, text: '9:16', 'data-tid': '9:16' }, ]; <|start_filename|>app/containers/VisibleThumbGrid.js<|end_filename|> import React, { Component } from 'react'; import path from 'path'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import { arrayMove } from 'react-sortable-hoc'; import scrollIntoView from 'scroll-into-view'; import { toggleThumb, updateOrder, changeThumb, addIntervalSheet, toggleThumbsByThumbIdArray } from '../actions'; import styles from '../components/ThumbGrid.css'; import SortableThumbGrid from '../components/ThumbGrid'; import { getLowestFrame, getHighestFrame, getNextThumb } from '../utils/utils'; import saveThumb from '../utils/saveThumb'; import { CHANGE_THUMB_STEP, DEFAULT_SINGLETHUMB_NAME, THUMB_SELECTION } from '../utils/constants'; class SortedVisibleThumbGrid extends Component { constructor(props) { super(props); this.state = { isSorting: false, }; this.scrollIntoViewElement = React.createRef(); this.scrollThumbIntoView = this.scrollThumbIntoView.bind(this); this.onSelectClick = this.onSelectClick.bind(this); } componentDidMount() { setTimeout(() => { this.scrollThumbIntoView(); }, 500); } componentDidUpdate(prevProps) { const { selectedThumbsArray, view } = this.props; if ( prevProps.selectedThumbsArray.length !== 0 && selectedThumbsArray.length !== 0 && prevProps.selectedThumbsArray[0].thumbId !== selectedThumbsArray[0].thumbId ) { setTimeout(() => { this.scrollThumbIntoView(); }, 500); // this.scrollThumbIntoView(); } // delay when switching to gridView so it waits for the sheetView to be ready if (prevProps.view !== view && prevProps.view) { setTimeout(() => { this.scrollThumbIntoView(); }, 500); } } onSortStart = () => { this.setState({ isSorting: true, }); }; onSelectClick = (thumbId, frameNumber) => { const { onSelectThumbMethod } = this.props; onSelectThumbMethod(thumbId, frameNumber); }; scrollThumbIntoView = () => { if (this.scrollIntoViewElement && this.scrollIntoViewElement.current !== null) { scrollIntoView(this.scrollIntoViewElement.current, { time: 300, align: { left: 0.5, }, }); } }; render() { const { isSorting } = this.state; const { currentSheetId, ageFilterEnabled, uniqueFilterEnabled, faceCountFilterEnabled, faceOccurrenceFilterEnabled, sizeFilterEnabled, genderFilterEnabled, isExpanded, defaultShowDetailsInHeader, defaultShowHeader, defaultShowImages, defaultShowPathInHeader, defaultShowTimelineInHeader, defaultThumbInfo, defaultThumbInfoRatio, emptyColorsArray, file, inputRef, isGridView, isViewForPrinting, keyObject, moviePrintWidth, objectUrlObjects, onAddThumbClick, onBackClick, onExpandClick, onForwardClick, onHideBeforeAfterClick, onInPointClick, onJumpToCutThumbClick, onOutPointClick, onSaveThumbClick, onScrubClick, onSortEnd, onThumbDoubleClick, onToggleClick, scaleValueObject, selectedThumbsArray, settings, sheetType, sheetView, showMovielist, showSettings, thumbCount, thumbs, useBase64, view, } = this.props; return ( <SortableThumbGrid useBase64={useBase64} emptyColorsArray={emptyColorsArray} sheetView={sheetView} sheetType={sheetType} view={view} currentSheetId={currentSheetId} settings={settings} file={file} inputRefThumb={this.scrollIntoViewElement} // for the thumb scrollIntoView function keyObject={keyObject} onAddThumbClick={onAddThumbClick} onJumpToCutThumbClick={onJumpToCutThumbClick} onBackClick={onBackClick} onForwardClick={onForwardClick} onInPointClick={onInPointClick} onOutPointClick={onOutPointClick} onHideBeforeAfterClick={onHideBeforeAfterClick} onSaveThumbClick={onSaveThumbClick} onScrubClick={onScrubClick} onSelectClick={this.onSelectClick} onExpandClick={onExpandClick} onThumbDoubleClick={onThumbDoubleClick} onToggleClick={onToggleClick} ref={inputRef} // for the saveMoviePrint function scaleValueObject={scaleValueObject} moviePrintWidth={moviePrintWidth} selectedThumbsArray={selectedThumbsArray} defaultShowDetailsInHeader={defaultShowDetailsInHeader} defaultShowHeader={defaultShowHeader} defaultShowImages={defaultShowImages} defaultShowPathInHeader={defaultShowPathInHeader} defaultShowTimelineInHeader={defaultShowTimelineInHeader} defaultThumbInfo={defaultThumbInfo} defaultThumbInfoRatio={defaultThumbInfoRatio} showMovielist={showMovielist} showSettings={showSettings} thumbCount={thumbCount} objectUrlObjects={objectUrlObjects} thumbs={thumbs} isViewForPrinting={isViewForPrinting} isGridView={isGridView} isSorting={isSorting} ageFilterEnabled={ageFilterEnabled} uniqueFilterEnabled={uniqueFilterEnabled} faceCountFilterEnabled={faceCountFilterEnabled} faceOccurrenceFilterEnabled={faceOccurrenceFilterEnabled} sizeFilterEnabled={sizeFilterEnabled} genderFilterEnabled={genderFilterEnabled} isExpanded={isExpanded} useDragHandle axis="xy" distance={1} helperClass={styles.whileDragging} onSortStart={this.onSortStart.bind(this)} onSortEnd={sort => { this.setState({ isSorting: false, }); onSortEnd(sort); }} /> ); } } const mapStateToProps = state => ({}); const mapDispatchToProps = (dispatch, ownProps) => { return { onSortEnd: ({ oldIndex, newIndex }) => { const { currentSheetId, settings, sheetsByFileId } = ownProps; const newOrderedThumbs = arrayMove( sheetsByFileId[settings.currentFileId][currentSheetId].thumbsArray, oldIndex, newIndex, ); dispatch(updateOrder(settings.currentFileId, currentSheetId, newOrderedThumbs)); }, onToggleClick: (fileId, thumbId) => { dispatch(toggleThumb(fileId, ownProps.currentSheetId, thumbId)); const nextThumb = getNextThumb(ownProps.thumbs, thumbId, THUMB_SELECTION.VISIBLE_THUMBS); if (nextThumb !== undefined) { ownProps.onSelectThumbMethod(nextThumb.thumbId); } }, onInPointClick: (file, thumbs, thumbId, frameNumber) => { dispatch( addIntervalSheet( file, ownProps.currentSheetId, thumbs.length, frameNumber, getHighestFrame(thumbs), ownProps.frameSize, true, // limitToRange -> do not get more thumbs then between in and out available ), ); }, onOutPointClick: (file, thumbs, thumbId, frameNumber) => { dispatch( addIntervalSheet( file, ownProps.currentSheetId, thumbs.length, getLowestFrame(thumbs), frameNumber, ownProps.frameSize, true, // limitToRange -> do not get more thumbs then between in and out available ), ); }, onHideBeforeAfterClick: (fileId, sheetId, thumbIdArray) => { dispatch(toggleThumbsByThumbIdArray(fileId, sheetId, thumbIdArray)); }, onSaveThumbClick: (filePath, fileUseRatio, movieFileName, frameNumber, frameId, transformObject, fps = 25) => { const filePathDirectory = path.dirname(filePath); const outputPath = ownProps.defaultOutputPathFromMovie ? filePathDirectory : ownProps.defaultOutputPath; saveThumb( filePath, fileUseRatio, movieFileName, ownProps.sheetName, frameNumber, ownProps.settings.defaultSingleThumbName || DEFAULT_SINGLETHUMB_NAME, frameId, transformObject, outputPath, true, ownProps.settings.defaultThumbFormat, ownProps.settings.defaultThumbJpgQuality, fps, ); }, onBackClick: (file, thumbId, frameNumber) => { const [stepValue0, stepValue1, stepValue2] = CHANGE_THUMB_STEP; let stepValue = stepValue1; if (ownProps.keyObject.shiftKey) { stepValue = stepValue0; } if (ownProps.keyObject.altKey) { stepValue = stepValue2; } dispatch(changeThumb(ownProps.currentSheetId, file, thumbId, frameNumber - stepValue, ownProps.frameSize)); }, onForwardClick: (file, thumbId, frameNumber) => { const [stepValue0, stepValue1, stepValue2] = CHANGE_THUMB_STEP; let stepValue = stepValue1; if (ownProps.keyObject.shiftKey) { stepValue = stepValue0; } if (ownProps.keyObject.altKey) { stepValue = stepValue2; } dispatch(changeThumb(ownProps.currentSheetId, file, thumbId, frameNumber + stepValue, ownProps.frameSize)); }, }; }; SortedVisibleThumbGrid.contextTypes = { store: PropTypes.object, }; SortedVisibleThumbGrid.defaultProps = { currentSheetId: undefined, file: {}, selectedThumbsArray: [], thumbs: [], useBase64: undefined, }; SortedVisibleThumbGrid.propTypes = { file: PropTypes.shape({ id: PropTypes.string, width: PropTypes.number, height: PropTypes.number, }), thumbs: PropTypes.arrayOf( PropTypes.shape({ thumbId: PropTypes.string.isRequired, index: PropTypes.number.isRequired, hidden: PropTypes.bool.isRequired, frameNumber: PropTypes.number.isRequired, }).isRequired, ), currentSheetId: PropTypes.string, emptyColorsArray: PropTypes.array.isRequired, inputRef: PropTypes.func.isRequired, isGridView: PropTypes.bool.isRequired, defaultOutputPath: PropTypes.string, defaultOutputPathFromMovie: PropTypes.bool, defaultShowDetailsInHeader: PropTypes.bool, defaultShowHeader: PropTypes.bool, defaultShowImages: PropTypes.bool, defaultShowPathInHeader: PropTypes.bool, defaultShowTimelineInHeader: PropTypes.bool, defaultThumbInfo: PropTypes.string, defaultThumbInfoRatio: PropTypes.number, isViewForPrinting: PropTypes.bool.isRequired, keyObject: PropTypes.object.isRequired, moviePrintWidth: PropTypes.number.isRequired, objectUrlObjects: PropTypes.object, onAddThumbClick: PropTypes.func, onBackClick: PropTypes.func.isRequired, onExpandClick: PropTypes.func, onForwardClick: PropTypes.func.isRequired, onHideBeforeAfterClick: PropTypes.func.isRequired, onInPointClick: PropTypes.func.isRequired, onJumpToCutThumbClick: PropTypes.func, onOutPointClick: PropTypes.func.isRequired, onSaveThumbClick: PropTypes.func.isRequired, onScrubClick: PropTypes.func, onSelectThumbMethod: PropTypes.func, onThumbDoubleClick: PropTypes.func, onToggleClick: PropTypes.func.isRequired, scaleValueObject: PropTypes.object.isRequired, selectedThumbsArray: PropTypes.array, sheetType: PropTypes.string.isRequired, sheetView: PropTypes.string.isRequired, showMovielist: PropTypes.bool.isRequired, showSettings: PropTypes.bool.isRequired, thumbCount: PropTypes.number.isRequired, useBase64: PropTypes.bool, view: PropTypes.string.isRequired, }; export default connect(mapStateToProps, mapDispatchToProps)(SortedVisibleThumbGrid); <|start_filename|>app/webViewPreload.js<|end_filename|> const { ipcRenderer } = require('electron'); document.addEventListener( 'wpcf7mailsent', ( event ) => { // document.addEventListener( 'wpcf7submit', ( event ) => { ipcRenderer.sendToHost('wpcf7mailsent', event.detail.inputs); }, false ); <|start_filename|>app/components/ThumbGrid.js<|end_filename|> /* eslint no-nested-ternary: "off" */ /* eslint no-bitwise: "off" */ import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { SortableContainer, SortableElement } from 'react-sortable-hoc'; import { Popup } from 'semantic-ui-react'; import uuidV4 from 'uuid/v4'; import Thumb from './Thumb'; import AllFaces from './AllFaces'; import ThumbGridHeader from './ThumbGridHeader'; import styles from './ThumbGrid.css'; import stylesPop from './Popup.css'; import { getNextThumbs, getPreviousThumbs, getInvertedThumbs, mapRange, getThumbInfoValue, formatBytes, frameCountToTimeCode, getFrameInPercentage, getLowestFrame, getHighestFrame, getAllFrameNumbers, roundNumber, } from '../utils/utils'; import { DEFAULT_FRAMEINFO_BACKGROUND_COLOR, DEFAULT_FRAMEINFO_COLOR, DEFAULT_FRAMEINFO_MARGIN, DEFAULT_FRAMEINFO_POSITION, DEFAULT_FRAMEINFO_SCALE, DEFAULT_SHOW_FACERECT, MINIMUM_WIDTH_TO_SHOW_HOVER, MINIMUM_WIDTH_TO_SHRINK_HOVER, SHEET_TYPE, SHEET_VIEW, TIMELINE_SCENE_MINIMUM_WIDTH, VIDEOPLAYER_THUMB_MARGIN, VIEW, } from '../utils/constants'; const SortableThumb = SortableElement(Thumb); const over = e => { // console.log('over'); e.stopPropagation(); e.target.style.opacity = 1; }; const out = e => { // console.log('out'); e.stopPropagation(); e.target.style.opacity = 0.2; }; class ThumbGrid extends Component { constructor(props) { super(props); // stores all thumb refs in an object this.thumbsRef = {}; // is set when the count has changed and used // to trigger getting new refs on next componentDidUpdate this.countHasChanged = false; this.state = { thumbsToDim: [], controllersVisible: undefined, currentThumb: undefined, addThumbBeforeController: undefined, addThumbAfterController: undefined, hoverPos: undefined, }; // this.thumbGridDivRef = null; this.thumbGridBodyDivRef = null; // this.setThumbGridDivRef = element => { // this.thumbGridDivRef = element; // } this.setThumbGridBodyDivRef = element => { this.thumbGridBodyDivRef = element; }; this.resetDim = this.resetDim.bind(this); this.resetHover = this.resetHover.bind(this); this.onContainerOut = this.onContainerOut.bind(this); this.onExpand = this.onExpand.bind(this); this.onToggle = this.onToggle.bind(this); this.onSaveThumb = this.onSaveThumb.bind(this); this.onInPoint = this.onInPoint.bind(this); this.onOutPoint = this.onOutPoint.bind(this); this.onHideBefore = this.onHideBefore.bind(this); this.onHideAfter = this.onHideAfter.bind(this); this.onHoverExpand = this.onHoverExpand.bind(this); this.onHoverInPoint = this.onHoverInPoint.bind(this); this.onHoverOutPoint = this.onHoverOutPoint.bind(this); this.onLeaveInOut = this.onLeaveInOut.bind(this); this.onScrub = this.onScrub.bind(this); this.onAddBefore = this.onAddBefore.bind(this); this.onAddAfter = this.onAddAfter.bind(this); this.onJumpToCutBefore = this.onJumpToCutBefore.bind(this); this.onJumpToCutAfter = this.onJumpToCutAfter.bind(this); this.onBack = this.onBack.bind(this); this.onForward = this.onForward.bind(this); this.onHoverAddThumbBefore = this.onHoverAddThumbBefore.bind(this); this.onHoverAddThumbAfter = this.onHoverAddThumbAfter.bind(this); this.onLeaveAddThumb = this.onLeaveAddThumb.bind(this); } // componentWillMount() { // } // componentDidMount() { // } // componentWillReceiveProps(nextProps) { // } componentDidUpdate(prevProps) { const { moviePrintWidth, sheetView, thumbs } = this.props; const { hoverPos } = this.state; const prevThumbArraySize = prevProps.thumbs.length; const currentThumbArraySize = thumbs.length; if (this.countHasChanged) { if (hoverPos !== undefined) { const x = hoverPos.left - 10; const y = hoverPos.top - 10; let newClientRect; // console.log(Object.keys(this.thumbsRef).length) const foundThumbId = Object.keys(this.thumbsRef).find(thumbId => { newClientRect = this.thumbsRef[thumbId].ref.node.getBoundingClientRect(); // console.log(newClientRect); return newClientRect.y > y && newClientRect.x > x; }); // console.log(foundThumbId); // console.log(thumbs[foundThumbId]); if (foundThumbId === undefined) { newClientRect = undefined; } let currentThumb; if (foundThumbId !== undefined) { currentThumb = thumbs.find(thumb => thumb.thumbId === foundThumbId); } this.setState({ controllersVisible: foundThumbId, currentThumb, addThumbBeforeController: undefined, addThumbAfterController: undefined, hoverPos: newClientRect, }); } this.countHasChanged = false; } // when count has changed clear thumbsRef object and set countHasChanged // to trigger getting new refs on next componentDidUpdate if (prevThumbArraySize !== currentThumbArraySize) { this.countHasChanged = true; this.thumbsRef = {}; // console.log('countHasChanged'); } // resetHover on moviePrintWidth and view change if (prevProps.moviePrintWidth !== moviePrintWidth || prevProps.sheetView !== sheetView) { this.resetHover(); } } resetDim() { this.setState({ thumbsToDim: [], }); } resetHover() { this.setState({ controllersVisible: undefined, currentThumb: undefined, addThumbBeforeController: undefined, addThumbAfterController: undefined, hoverPos: undefined, }); } onContainerOut() { // console.log('onContainerOut'); // e.stopPropagation(); this.resetHover(); } onExpand(e) { // console.log('onExpand'); const { currentSheetId, file, onExpandClick, sheetType } = this.props; const { currentThumb } = this.state; e.stopPropagation(); onExpandClick(file, currentThumb.thumbId, currentSheetId, sheetType); this.resetDim(); } onToggle(e) { // console.log('onToggle'); const { file, onToggleClick } = this.props; const { controllersVisible } = this.state; e.stopPropagation(); onToggleClick(file.id, controllersVisible); } onSaveThumb(e) { // console.log('onSaveThumb'); const { file, onSaveThumbClick } = this.props; const { currentThumb } = this.state; e.stopPropagation(); onSaveThumbClick( file.path, file.useRatio, file.name, currentThumb.frameNumber, currentThumb.frameId, file.transformObject, file.fps, ); // this.resetHover(); } onInPoint(e) { // console.log('onInPoint'); const { file, onInPointClick, thumbs } = this.props; const { currentThumb } = this.state; e.stopPropagation(); onInPointClick(file, thumbs, currentThumb.thumbId, currentThumb.frameNumber); this.resetDim(); } onOutPoint(e) { // console.log('onOutPoint'); const { file, onOutPointClick, thumbs } = this.props; const { currentThumb } = this.state; e.stopPropagation(); onOutPointClick(file, thumbs, currentThumb.thumbId, currentThumb.frameNumber); this.resetDim(); } onHideBefore(e) { // console.log('onHideBefore'); const { currentSheetId, file, onHideBeforeAfterClick, thumbs } = this.props; const { currentThumb } = this.state; e.stopPropagation(); const previousThumbs = getPreviousThumbs(thumbs, currentThumb.thumbId); const previousThumbIds = previousThumbs.map(t => t.thumbId); onHideBeforeAfterClick(file.id, currentSheetId, previousThumbIds); this.resetDim(); } onHideAfter(e) { // console.log('onHideAfter'); const { currentSheetId, file, onHideBeforeAfterClick, thumbs } = this.props; const { currentThumb } = this.state; e.stopPropagation(); const previousThumbs = getNextThumbs(thumbs, currentThumb.thumbId); const previousThumbIds = previousThumbs.map(t => t.thumbId); onHideBeforeAfterClick(file.id, currentSheetId, previousThumbIds); this.resetDim(); } onBack(e) { // console.log('onBack'); const { file, onBackClick } = this.props; const { currentThumb } = this.state; e.stopPropagation(); onBackClick(file, currentThumb.thumbId, currentThumb.frameNumber); } onForward(e) { // console.log('onForward'); const { file, onForwardClick } = this.props; const { currentThumb } = this.state; e.stopPropagation(); onForwardClick(file, currentThumb.thumbId, currentThumb.frameNumber); } onHoverExpand(e) { // console.log('onHoverInPoint'); const { thumbs } = this.props; const { controllersVisible } = this.state; e.target.style.opacity = 1; e.stopPropagation(); this.setState({ thumbsToDim: getInvertedThumbs(thumbs, controllersVisible), }); } onHoverInPoint(e) { // console.log('onHoverInPoint'); const { thumbs } = this.props; const { controllersVisible } = this.state; e.target.style.opacity = 1; e.stopPropagation(); this.setState({ thumbsToDim: getPreviousThumbs(thumbs, controllersVisible), }); } onHoverOutPoint(e) { // console.log('onHoverOutPoint'); const { thumbs } = this.props; const { controllersVisible } = this.state; e.target.style.opacity = 1; e.stopPropagation(); this.setState({ thumbsToDim: getNextThumbs(thumbs, controllersVisible), }); } onLeaveInOut(e) { // console.log('onLeaveInOut'); e.target.style.opacity = 0.2; e.stopPropagation(); this.setState({ thumbsToDim: [], }); } onScrub(e, triggerTime) { // console.log('onScrub'); // for the scrub window the user has to click and drag while keeping the mouse pressed // use triggerTime to keep scrub window open if users just click and release the mouse within 1000ms const { file, onScrubClick } = this.props; const { currentThumb } = this.state; e.stopPropagation(); onScrubClick(file, currentThumb, triggerTime); } onAddBefore(e) { // console.log('onAddBefore'); const { file, onAddThumbClick } = this.props; const { currentThumb } = this.state; e.stopPropagation(); onAddThumbClick(file, currentThumb, 'before'); } onAddAfter(e) { // console.log('onAddAfter'); const { file, onAddThumbClick } = this.props; const { currentThumb } = this.state; e.stopPropagation(); onAddThumbClick(file, currentThumb, 'after'); } onJumpToCutBefore(e) { // console.log('onJumpToCutBefore'); const { file, onJumpToCutThumbClick } = this.props; const { currentThumb } = this.state; e.stopPropagation(); onJumpToCutThumbClick(file, currentThumb.thumbId, 'before'); } onJumpToCutAfter(e) { // console.log('onJumpToCutAfter'); const { file, onJumpToCutThumbClick } = this.props; const { currentThumb } = this.state; e.stopPropagation(); onJumpToCutThumbClick(file, currentThumb.thumbId, 'after'); } onHoverAddThumbBefore(e) { // console.log('onHoverAddThumbBefore'); const { controllersVisible } = this.state; e.target.style.opacity = 1; e.stopPropagation(); this.setState({ addThumbBeforeController: controllersVisible, }); } onHoverAddThumbAfter(e) { // console.log('onHoverAddThumbAfter'); const { controllersVisible } = this.state; e.target.style.opacity = 1; e.stopPropagation(); this.setState({ addThumbAfterController: controllersVisible, }); } onLeaveAddThumb(e) { // console.log('onLeaveAddThumb'); e.target.style.opacity = 0.2; e.stopPropagation(); this.setState({ addThumbBeforeController: undefined, addThumbAfterController: undefined, }); } render() { const { ageFilterEnabled, uniqueFilterEnabled, faceCountFilterEnabled, faceOccurrenceFilterEnabled, sizeFilterEnabled, genderFilterEnabled, isExpanded, defaultShowDetailsInHeader, defaultShowHeader, defaultShowImages, defaultShowPathInHeader, defaultShowTimelineInHeader, defaultThumbInfo, defaultThumbInfoRatio, emptyColorsArray, file, inputRefThumb, isSorting, isViewForPrinting, keyObject, moviePrintWidth, objectUrlObjects, onSelectClick, onThumbDoubleClick, scaleValueObject, selectedThumbsArray, settings, sheetType, sheetView, showSettings, thumbCount, thumbs, useBase64, view, } = this.props; const { addThumbAfterController, addThumbBeforeController, controllersVisible, currentThumb, hoverPos, thumbsToDim, } = this.state; let currentFaceArray; if (currentThumb !== undefined) { currentFaceArray = currentThumb.facesArray; } const isPlayerView = view !== VIEW.STANDARDVIEW; const isIntervalType = sheetType === SHEET_TYPE.INTERVAL; const isShotType = sheetType === SHEET_TYPE.SCENES; const isFaceType = sheetType === SHEET_TYPE.FACES; const isAltKey = keyObject.altKey; const { defaultFrameinfoBackgroundColor = DEFAULT_FRAMEINFO_BACKGROUND_COLOR, defaultFrameinfoColor = DEFAULT_FRAMEINFO_COLOR, defaultFrameinfoPosition = DEFAULT_FRAMEINFO_POSITION, defaultFrameinfoScale = DEFAULT_FRAMEINFO_SCALE, defaultFrameinfoMargin = DEFAULT_FRAMEINFO_MARGIN, defaultShowFaceRect = DEFAULT_SHOW_FACERECT, } = settings; const frameinfoBackgroundColorString = `rgba(${defaultFrameinfoBackgroundColor.r}, ${defaultFrameinfoBackgroundColor.g}, ${defaultFrameinfoBackgroundColor.b}, ${defaultFrameinfoBackgroundColor.a})`; const frameinfoColorString = `rgba(${defaultFrameinfoColor.r}, ${defaultFrameinfoColor.g}, ${defaultFrameinfoColor.b}, ${defaultFrameinfoColor.a})`; const fps = file !== undefined && file.fps !== undefined ? file.fps : 25; const fileDetails = file ? `${frameCountToTimeCode(file.frameCount, fps)} | ${roundNumber(fps)} FPS | ${file.width} × ${ file.height } | ${formatBytes(file.size, 1)} | ${file.fourCC}` : ''; // 00:06:48:12 (9789 frames) | 23.99 FPS | 1280 x 720 | 39.2 MB let thumbArray = thumbs; // calculate in and outpoint for the timeline in percent const inPoint = getLowestFrame(thumbs); const outPoint = getHighestFrame(thumbs); const inPointPositionOnTimeline = getFrameInPercentage(inPoint, file.frameCount); const outPointPositionOnTimeline = getFrameInPercentage(outPoint, file.frameCount); const cutWidthOnTimeLine = Math.max( outPointPositionOnTimeline - inPointPositionOnTimeline, TIMELINE_SCENE_MINIMUM_WIDTH, ); const allFrameNumbersArray = getAllFrameNumbers(thumbs); const allFrameNumbersInPercentArray = allFrameNumbersArray.map(frameNumber => getFrameInPercentage(frameNumber, file.frameCount), ); if (showSettings || thumbs.length === 0) { const tempArrayLength = thumbCount; thumbArray = Array(tempArrayLength); for (let i = 0; i < tempArrayLength; i += 1) { const mappedIterator = mapRange( i, 0, tempArrayLength - 1, 0, (thumbs !== undefined ? thumbs.length : tempArrayLength) - 1, ); let tempThumbObject = { id: String(mappedIterator), }; if (thumbs.length === 0) { tempThumbObject = { index: i, }; } else if (thumbs.length === tempArrayLength) { tempThumbObject = thumbs[i]; } else { if (objectUrlObjects !== undefined && (i === 0 || i === tempArrayLength - 1)) { tempThumbObject = thumbs[mappedIterator]; } else { tempThumbObject.transparentThumb = true; // set this to control displaying a thumb image or a color } tempThumbObject.index = i; } thumbArray[i] = tempThumbObject; } } const thumbWidth = scaleValueObject.newThumbWidth; const thumbHeight = thumbWidth * scaleValueObject.aspectRatioInv; const hoverThumbIndex = thumbArray.findIndex(thumb => thumb.thumbId === controllersVisible); const isHidden = hoverThumbIndex !== -1 ? thumbArray[hoverThumbIndex].hidden : undefined; const parentPos = this.thumbGridBodyDivRef !== null ? this.thumbGridBodyDivRef.getBoundingClientRect() : { left: 0, top: 0, }; // console.log(hoverPos); // console.log(parentPos); // console.log(hoverPos) const showBeforeController = controllersVisible === addThumbBeforeController; const showAfterController = controllersVisible === addThumbAfterController; const thumbMarginGridView = isPlayerView ? VIDEOPLAYER_THUMB_MARGIN : scaleValueObject.newThumbMargin; let thumbCSSTranslate; if (defaultFrameinfoPosition === 'topCenter' || defaultFrameinfoPosition === 'bottomCenter') { thumbCSSTranslate = `translateX(-50%) scale(${(defaultFrameinfoScale * 0.1 * (defaultThumbInfoRatio * thumbWidth * scaleValueObject.aspectRatioInv)) / 10})`; } else if (defaultFrameinfoPosition === 'centerCenter') { thumbCSSTranslate = `translate(-50%, -50%) scale(${(defaultFrameinfoScale * 0.1 * (defaultThumbInfoRatio * thumbWidth * scaleValueObject.aspectRatioInv)) / 10})`; } else { thumbCSSTranslate = `scale(${(defaultFrameinfoScale * 0.1 * (defaultThumbInfoRatio * thumbWidth * scaleValueObject.aspectRatioInv)) / 10})`; } let frameinfoMargin; if (defaultFrameinfoPosition === 'topCenter' || defaultFrameinfoPosition === 'bottomCenter') { frameinfoMargin = `${defaultFrameinfoMargin}px 0px`; } else if (defaultFrameinfoPosition === 'centerCenter') { frameinfoMargin = undefined; } else { frameinfoMargin = `${defaultFrameinfoMargin}px`; } const margin = `${view === VIEW.STANDARDVIEW ? thumbMarginGridView : Math.max(1, thumbMarginGridView)}px`; return ( <div data-tid="thumbGridDiv" className={styles.grid} style={{ width: moviePrintWidth, // paddingLeft: isPlayerView ? '48px' : undefined, }} id="ThumbGrid" onMouseLeave={this.onContainerOut} // ref={this.setThumbGridDivRef} > {!isPlayerView && defaultShowHeader && sheetView === SHEET_VIEW.GRIDVIEW && ( <ThumbGridHeader isViewForPrinting={isViewForPrinting} fileName={file.name || ''} filePath={file.path || ''} fileDetails={fileDetails} showPathInHeader={defaultShowPathInHeader} showDetailsInHeader={defaultShowDetailsInHeader} showTimelineInHeader={defaultShowTimelineInHeader} moviePrintWidth={moviePrintWidth} headerHeight={scaleValueObject.newHeaderHeight} logoHeight={scaleValueObject.newLogoHeight} thumbMargin={thumbMarginGridView} inPointPositionOnTimeline={inPointPositionOnTimeline} cutWidthOnTimeLine={cutWidthOnTimeLine} allFrameNumbersInPercentArray={allFrameNumbersInPercentArray} /> )} <div data-tid="thumbGridBodyDiv" ref={this.setThumbGridBodyDivRef}> {thumbArray.map(thumb => ( <SortableThumb ref={ref => (this.thumbsRef[thumb.thumbId] = ref)} sheetView={sheetView} sheetType={sheetType} view={view} keyObject={keyObject} key={thumb.thumbId || uuidV4()} thumbId={thumb.thumbId} index={thumb.index} indexForId={thumb.index} defaultShowFaceRect={defaultShowFaceRect} facesArray={thumb.facesArray !== undefined ? thumb.facesArray : undefined} dim={thumbsToDim.find(thumbToDim => thumbToDim.thumbId === thumb.thumbId)} inputRefThumb={ selectedThumbsArray.length !== 0 && selectedThumbsArray[0].thumbId === thumb.thumbId ? inputRefThumb : undefined } // for the thumb scrollIntoView function color={ // use thumb color, else emptyColor thumb.colorArray !== undefined ? `#${( (1 << 24) + (Math.round(thumb.colorArray[0]) << 16) + (Math.round(thumb.colorArray[1]) << 8) + Math.round(thumb.colorArray[2]) ) .toString(16) .slice(1)}` : emptyColorsArray !== undefined ? emptyColorsArray[thumb.index] : undefined } thumbImageObjectUrl={ // used for data stored in IndexedDB useBase64 === undefined && objectUrlObjects !== undefined ? objectUrlObjects[thumb.frameId] : undefined } base64={ // used for live captured data when saving movieprint useBase64 !== undefined && objectUrlObjects !== undefined ? objectUrlObjects[thumb.frameId] : undefined } transparentThumb={!defaultShowImages || thumb.transparentThumb || undefined} thumbWidth={thumbWidth} thumbHeight={thumbHeight} borderRadius={scaleValueObject.newBorderRadius} margin={margin} thumbInfoValue={getThumbInfoValue(defaultThumbInfo, thumb.frameNumber, fps)} thumbInfoRatio={defaultThumbInfoRatio} hidden={thumb.hidden} controllersAreVisible={thumb.thumbId === undefined ? false : thumb.thumbId === controllersVisible} selected={ selectedThumbsArray.length !== 0 ? selectedThumbsArray.some(item => item.thumbId === thumb.thumbId) : false } onOver={event => { // console.log('onOver from Thumb'); // only setState if controllersVisible has changed // console.log(event.target.getBoundingClientRect()); const hoverPosition = event.target.getBoundingClientRect(); // event.stopPropagation(); if (controllersVisible !== thumb.thumbId) { this.setState({ controllersVisible: thumb.thumbId, currentThumb: thumb, hoverPos: hoverPosition, }); } }} onOut={event => { // console.log('onOut from Thumb'); // this.resetHover(); // only setState if controllersVisible has changed // console.log(event.target.getBoundingClientRect()); // const hoverPos = event.target.getBoundingClientRect(); // event.stopPropagation(); // if (controllersVisible !== thumb.thumbId) { // this.resetHover(); // } }} onThumbDoubleClick={onThumbDoubleClick} onSelect={ thumb.thumbId !== controllersVisible ? null : () => { onSelectClick(thumb.thumbId, thumb.frameNumber); } } frameninfoBackgroundColor={frameinfoBackgroundColorString} frameinfoColor={frameinfoColorString} frameinfoPosition={defaultFrameinfoPosition} frameinfoScale={defaultFrameinfoScale} frameinfoMargin={frameinfoMargin} thumbCSSTranslate={thumbCSSTranslate} ageFilterEnabled={ageFilterEnabled} uniqueFilterEnabled={uniqueFilterEnabled} faceCountFilterEnabled={faceCountFilterEnabled} faceOccurrenceFilterEnabled={faceOccurrenceFilterEnabled} sizeFilterEnabled={sizeFilterEnabled} genderFilterEnabled={genderFilterEnabled} isExpanded={isExpanded} /> ))} </div> {!isSorting && // only show when not sorting hoverPos !== undefined && ( // only show when hoveringOver a thumb // !this.props.showSettings && // only show when not showSettings <div className={`${styles.overlayContainer} data-html2canvas-ignore`} // onMouseOut={this.onContainerOut} > <div className={styles.overlay} style={{ display: thumbWidth > MINIMUM_WIDTH_TO_SHOW_HOVER ? 'block' : 'none', left: hoverPos.left - parentPos.left, top: hoverPos.top - parentPos.top, width: `${thumbWidth}px`, height: `${thumbWidth * scaleValueObject.aspectRatioInv}px`, }} > {currentThumb !== undefined && currentThumb.facesArray !== undefined && ( <AllFaces facesArray={currentFaceArray} thumbWidth={thumbWidth} thumbHeight={thumbHeight} ageFilterEnabled={ageFilterEnabled} uniqueFilterEnabled={uniqueFilterEnabled} faceCountFilterEnabled={faceCountFilterEnabled} faceOccurrenceFilterEnabled={faceOccurrenceFilterEnabled} sizeFilterEnabled={sizeFilterEnabled} genderFilterEnabled={genderFilterEnabled} isExpanded={isExpanded} thumbHover={true} /> )} <Popup trigger={ <button data-tid={`ExpandThumbBtn_${controllersVisible}`} type="button" className={`${styles.hoverButton} ${styles.textButton} ${styles.overlayExit} ${ thumbWidth < MINIMUM_WIDTH_TO_SHRINK_HOVER ? styles.overlayShrink : '' }`} onClick={this.onExpand} onMouseOver={this.onHoverExpand} onMouseOut={this.onLeaveInOut} onFocus={over} onBlur={out} > {isFaceType ? (isExpanded ? '' : 'FIND') : 'EXPAND'} </button> } mouseEnterDelay={1000} on={['hover']} position="top center" className={stylesPop.popup} content={ isFaceType ? 'Create a new MoviePrint of all occurrences of the largest face in this thumb' : 'Create a new MoviePrint using In- and Outpoints of this scene' } /> <Popup trigger={ <button data-tid={`${isHidden ? 'show' : 'hide'}ThumbBtn_${controllersVisible}`} type="button" className={`${styles.hoverButton} ${styles.textButton} ${styles.overlayHide} ${ thumbWidth < MINIMUM_WIDTH_TO_SHRINK_HOVER ? styles.overlayShrink : '' }`} onClick={this.onToggle} onMouseOver={over} onMouseOut={out} onFocus={over} onBlur={out} > {isHidden ? 'SHOW' : 'HIDE'} </button> } mouseEnterDelay={1000} on={['hover']} position="top center" className={stylesPop.popup} content="Hide thumb" /> <Popup trigger={ <button data-tid={`saveThumbBtn_${controllersVisible}`} type="button" className={`${styles.hoverButton} ${styles.textButton} ${styles.overlaySave} ${ thumbWidth < MINIMUM_WIDTH_TO_SHRINK_HOVER ? styles.overlayShrink : '' }`} onClick={this.onSaveThumb} onMouseOver={over} onMouseOut={out} onFocus={over} onBlur={out} > SAVE </button> } mouseEnterDelay={1000} on={['hover']} position="top center" className={stylesPop.popup} content="Save thumb" /> {!isHidden && ( <div> <Popup trigger={ <button data-tid={`setInPointBtn_${controllersVisible}`} type="button" className={`${styles.hoverButton} ${styles.textButton} ${styles.overlayIn} ${ thumbWidth < MINIMUM_WIDTH_TO_SHRINK_HOVER ? styles.overlayShrink : '' }`} onClick={isIntervalType && !isAltKey ? this.onInPoint : this.onHideBefore} onMouseOver={this.onHoverInPoint} onMouseOut={this.onLeaveInOut} onFocus={over} onBlur={out} > IN </button> } mouseEnterDelay={1000} on={['hover']} position="bottom center" className={stylesPop.popup} content={ isIntervalType && !isAltKey ? ( <span> Set this thumb as new <mark>IN-point</mark> and re-capture in-between thumbs <br /> With <mark>ALT</mark> hide all thumbs before </span> ) : ( <span>Hide all thumbs before</span> ) } /> {!isFaceType && ( <Popup trigger={ <button data-tid={`addNewThumbBeforeBtn_${controllersVisible}`} type="button" className={`${styles.hoverButton} ${styles.textButton} ${styles.overlayAddBefore} ${ thumbWidth < MINIMUM_WIDTH_TO_SHRINK_HOVER ? styles.overlayShrink : '' }`} onClick={isShotType ? this.onJumpToCutBefore : this.onAddBefore} onMouseOver={this.onHoverAddThumbBefore} onMouseOut={this.onLeaveAddThumb} onFocus={over} onBlur={out} > {isShotType ? '||' : '+'} </button> } mouseEnterDelay={1000} on={['hover']} position="bottom center" className={stylesPop.popup} content={isShotType ? <span>Jump to cut</span> : <span>Insert new thumb before</span>} /> )} {!isFaceType && ( <Popup trigger={ <button data-tid={`scrubBtn_${controllersVisible}`} type="button" className={`${styles.hoverButton} ${styles.textButton} ${styles.overlayScrub} ${ thumbWidth < MINIMUM_WIDTH_TO_SHRINK_HOVER ? styles.overlayShrink : '' }`} onMouseDown={e => this.onScrub(e, Date.now())} onMouseOver={over} onMouseOut={out} onFocus={over} onBlur={out} > {'<|>'} </button> } mouseEnterDelay={1000} on={['hover']} position="bottom center" className={stylesPop.popup} content={ <span> Click and drag left and right to change the frame (then with <mark>SHIFT</mark> insert new thumb before, <mark>ALT</mark> insert new thumb after, <mark>CTRL</mark> allow dragging over whole movie) </span> } /> )} {!isFaceType && ( <Popup trigger={ <button data-tid={`addNewThumbAfterBtn_${controllersVisible}`} type="button" className={`${styles.hoverButton} ${styles.textButton} ${styles.overlayAddAfter} ${ thumbWidth < MINIMUM_WIDTH_TO_SHRINK_HOVER ? styles.overlayShrink : '' }`} onClick={isShotType ? this.onJumpToCutAfter : this.onAddAfter} onMouseOver={this.onHoverAddThumbAfter} onMouseOut={this.onLeaveAddThumb} onFocus={over} onBlur={out} > {isShotType ? '||' : '+'} </button> } mouseEnterDelay={1000} on={['hover']} position="bottom center" className={stylesPop.popup} content={isShotType ? <span>Jump to cut</span> : <span>Insert new thumb after</span>} /> )} <Popup trigger={ <button data-tid={`setOutPointBtn_${controllersVisible}`} type="button" className={`${styles.hoverButton} ${styles.textButton} ${styles.overlayOut} ${ thumbWidth < MINIMUM_WIDTH_TO_SHRINK_HOVER ? styles.overlayShrink : '' }`} onClick={isIntervalType && !isAltKey ? this.onOutPoint : this.onHideAfter} onMouseOver={this.onHoverOutPoint} onMouseOut={this.onLeaveInOut} onFocus={over} onBlur={out} > OUT </button> } mouseEnterDelay={1000} on={['hover']} position="bottom center" className={stylesPop.popup} content={ isIntervalType && !isAltKey ? ( <span> Set this thumb as new <mark>OUT-point</mark> and re-capture in-between thumbs <br /> With <mark>ALT</mark> hide all thumbs after </span> ) : ( <span>Hide all thumbs after</span> ) } /> </div> )} {sheetType !== SHEET_TYPE.SCENES && (showBeforeController || showAfterController) && thumbWidth > MINIMUM_WIDTH_TO_SHOW_HOVER && ( <div data-tid={`insertThumb${ !showAfterController && showBeforeController ? 'Before' : 'After' }Div_${controllersVisible}`} style={{ zIndex: 100, content: '', backgroundColor: '#FF5006', position: 'absolute', width: `${Math.max(1, thumbMarginGridView * 0.5)}px`, height: `${thumbWidth * scaleValueObject.aspectRatioInv}px`, // top: (Math.max(1, thumbMarginGridView * -1.0)), left: `${!showAfterController && showBeforeController ? 0 : undefined}`, right: `${showAfterController ? 0 : undefined}`, display: 'block', transform: `translateX(${Math.max(1, thumbMarginGridView) * (showAfterController ? 1.25 : -1.25)}px)`, }} /> )} </div> </div> )} </div> ); } } ThumbGrid.defaultProps = { currentSheetId: undefined, currentSheetFilter: {}, file: {}, selectedThumbsArray: [], thumbs: [], useBase64: undefined, }; ThumbGrid.propTypes = { file: PropTypes.shape({ id: PropTypes.string, name: PropTypes.string, path: PropTypes.string, width: PropTypes.number, height: PropTypes.number, fps: PropTypes.number, }), thumbs: PropTypes.arrayOf( PropTypes.shape({ thumbId: PropTypes.string.isRequired, index: PropTypes.number.isRequired, hidden: PropTypes.bool.isRequired, frameNumber: PropTypes.number.isRequired, }).isRequired, ), currentSheetId: PropTypes.string, currentSheetFilter: PropTypes.object, defaultShowDetailsInHeader: PropTypes.bool, defaultShowHeader: PropTypes.bool, defaultShowImages: PropTypes.bool, defaultShowPathInHeader: PropTypes.bool, defaultShowTimelineInHeader: PropTypes.bool, defaultThumbInfo: PropTypes.string, defaultThumbInfoRatio: PropTypes.number, emptyColorsArray: PropTypes.array.isRequired, inputRefThumb: PropTypes.object.isRequired, isSorting: PropTypes.bool.isRequired, isViewForPrinting: PropTypes.bool.isRequired, keyObject: PropTypes.object.isRequired, moviePrintWidth: PropTypes.number.isRequired, objectUrlObjects: PropTypes.object, onAddThumbClick: PropTypes.func.isRequired, onBackClick: PropTypes.func.isRequired, onExpandClick: PropTypes.func.isRequired, onForwardClick: PropTypes.func.isRequired, onHideBeforeAfterClick: PropTypes.func.isRequired, onInPointClick: PropTypes.func.isRequired, onJumpToCutThumbClick: PropTypes.func.isRequired, onOutPointClick: PropTypes.func.isRequired, onSaveThumbClick: PropTypes.func.isRequired, onScrubClick: PropTypes.func.isRequired, onSelectClick: PropTypes.func.isRequired, onThumbDoubleClick: PropTypes.func.isRequired, onToggleClick: PropTypes.func.isRequired, scaleValueObject: PropTypes.object.isRequired, selectedThumbsArray: PropTypes.array, sheetType: PropTypes.string.isRequired, sheetView: PropTypes.string.isRequired, showSettings: PropTypes.bool.isRequired, thumbCount: PropTypes.number.isRequired, useBase64: PropTypes.bool, view: PropTypes.string.isRequired, }; const SortableThumbGrid = SortableContainer(ThumbGrid); export default SortableThumbGrid; <|start_filename|>app/components/FloatingMenu.js<|end_filename|> import React from 'react'; import { Button, Checkbox, Divider, Dropdown, Popup, Radio } from 'semantic-ui-react'; import Slider, { Handle, createSliderWithTooltip } from 'rc-slider'; import Tooltip from 'rc-tooltip'; import { FACE_UNIQUENESS_THRESHOLD, FACE_SIZE_THRESHOLD, FILTER_METHOD, FILTER_METHOD_AGE, FILTER_METHOD_FACECOUNT, FILTER_METHOD_FACEOCCURRENCE, FILTER_METHOD_FACESIZE, SHEET_VIEW, SHEET_TYPE, SORT_METHOD, THUMB_INFO, THUMB_INFO_OPTIONS, THUMB_SELECTION, VIEW, } from '../utils/constants'; import { areOneOrMoreFiltersEnabled } from '../utils/utils'; import styles from './FloatingMenu.css'; import stylesPop from './Popup.css'; import iconCutView from '../img/icon-cut-view.svg'; import iconThumbView from '../img/icon-thumb-view.svg'; import iconHeader from '../img/icon-header.svg'; import iconHeaderEnabled from '../img/icon-header-enabled.svg'; import iconImage from '../img/icon-image.svg'; import iconNoImage from '../img/icon-no-image.svg'; import iconFrameInfo from '../img/icon-frame-info.svg'; import iconFrameInfoEnabled from '../img/icon-frame-info-enabled.svg'; import iconShowFaceRect from '../img/icon-show-face-rect.svg'; import iconShowFaceRectEnabled from '../img/icon-show-face-rect-enabled.svg'; import iconCaretDown from '../img/icon-caret-down.svg'; import iconArrowUp from '../img/icon-arrow-up.svg'; import iconHide from '../img/icon-hide.svg'; import iconUnhide from '../img/icon-unhide.svg'; import iconExpand from '../img/icon-expand.svg'; import iconZoomIn from '../img/icon-zoom-in.svg'; import iconZoomOut from '../img/icon-zoom-out.svg'; import iconResizeVertical from '../img/icon-resize-vertical.svg'; import iconResizeHorizontal from '../img/icon-resize-horizontal.svg'; import iconSort from '../img/icon-sort.svg'; import iconFilter from '../img/icon-filter.svg'; import iconFilterEnabled from '../img/icon-filter-enabled.svg'; import iconCopy from '../img/icon-copy.svg'; import iconGrid from '../img/icon-grid.svg'; import iconBarcode from '../img/icon-barcode.svg'; import iconAddInterval from '../img/icon-add-interval.svg'; import iconAddScene from '../img/icon-add-scene.svg'; import iconAddFace from '../img/icon-add-face.svg'; import icon2x2 from '../img/icon-2x2.svg'; import icon3x3 from '../img/icon-3x3.svg'; import icon4x4 from '../img/icon-4x4.svg'; import icon5x5 from '../img/icon-5x5.svg'; import icon6x6 from '../img/icon-6x6.svg'; const SliderWithTooltip = createSliderWithTooltip(Slider); const Range = createSliderWithTooltip(Slider.Range); const handle = props => { const { value, dragging, index, ...restProps } = props; return ( <Tooltip prefixCls="rc-slider-tooltip" overlay={value} visible placement="top" key={index}> <Handle value={value} {...restProps} /> </Tooltip> ); }; const FloatingMenu = ({ currentSheetFilter, fileMissingStatus, hasParent, onAddFaceSheetClick, onAddIntervalSheetClick, onBackToParentClick, onChangeDefaultZoomLevel, onChangeFaceUniquenessThreshold, onChangeSheetViewClick, onDuplicateSheetClick, onFilterSheet, onScanMovieListItemClick, onSetViewClick, onShowAllThumbs, onSortSheet, onThumbInfoClick, onToggleFaceRectClick, onToggleHeaderClick, onToggleImagesClick, onToggleShowHiddenThumbsClick, onUpdateSheetFilter, optimiseGridLayout, scaleValueObject, settings, sheetType, sheetView, visibilitySettings, }) => { const { defaultFaceUniquenessThreshold = FACE_UNIQUENESS_THRESHOLD, defaultFaceSizeThreshold = FACE_SIZE_THRESHOLD, defaultThumbInfo, defaultShowHeader, defaultShowImages, defaultShowFaceRect, } = settings; const { defaultView, defaultZoomLevel, visibilityFilter } = visibilitySettings; const { moviePrintAspectRatioInv, containerAspectRatioInv } = scaleValueObject; const isGridViewAndDefault = sheetView === SHEET_VIEW.GRIDVIEW && defaultView === VIEW.STANDARDVIEW; const isFaceType = sheetType === SHEET_TYPE.FACES; const isShotType = sheetType === SHEET_TYPE.SCENES; const sheetHasFilters = areOneOrMoreFiltersEnabled(currentSheetFilter); const { [FILTER_METHOD.AGE]: ageFilter = { enabled: false, lower: FILTER_METHOD_AGE.LOWER, upper: FILTER_METHOD_AGE.UPPER, }, [FILTER_METHOD.DISTTOORIGIN]: uniqueFilter = { enabled: false, value: 0, }, [FILTER_METHOD.FACECOUNT]: faceCountFilter = { enabled: false, lower: FILTER_METHOD_FACECOUNT.LOWER, upper: FILTER_METHOD_FACECOUNT.UPPER, }, [FILTER_METHOD.FACEOCCURRENCE]: faceOccurrenceFilter = { enabled: false, lower: FILTER_METHOD_FACEOCCURRENCE.LOWER, upper: FILTER_METHOD_FACEOCCURRENCE.UPPER, }, [FILTER_METHOD.FACESIZE]: sizeFilter = { enabled: false, lower: FILTER_METHOD_FACESIZE.LOWER, upper: FILTER_METHOD_FACESIZE.UPPER, }, [FILTER_METHOD.GENDER]: genderFilter = { enabled: false, value: 'female', }, [FILTER_METHOD.FACEID]: faceIdFilter = { enabled: false, }, } = currentSheetFilter; const onFilterChange = (filterMethod, valueObject) => { const newFilters = { ...currentSheetFilter, [filterMethod]: { ...currentSheetFilter[filterMethod], ...valueObject, }, }; onFilterSheet(newFilters); onUpdateSheetFilter(newFilters); }; return ( <div className={`${styles.floatingMenu}`}> <Popup trigger={ <Button className={`${styles.normalButton} ${styles.selected} ${ hasParent && defaultView === VIEW.STANDARDVIEW ? '' : styles.hidden }`} style={{ marginRight: '8px', marginLeft: '8px', }} size="large" circular data-tid="backToParentBtn" onClick={onBackToParentClick} icon={<img src={iconArrowUp} height="18px" alt="" />} /> } mouseEnterDelay={1000} on={['hover']} position="bottom center" className={stylesPop.popup} content={<span>Back to parent MoviePrint</span>} />{' '} <Button.Group className={`${defaultView === VIEW.STANDARDVIEW ? '' : styles.hidden}`}> <Popup trigger={ <Button className={styles.imageButton} size="large" data-tid="addShotDetectionMovieListItemBtn" onClick={() => onScanMovieListItemClick(undefined)} disabled={fileMissingStatus} icon={<img src={iconAddScene} height="18px" alt="" />} /> } mouseEnterDelay={1000} on={['hover']} position="bottom center" className={stylesPop.popup} content="Add MoviePrint (shot detection based)" /> <Popup trigger={ <Dropdown button className={styles.dropDownButton} floating disabled={fileMissingStatus} icon={<img src={iconAddInterval} height="18px" alt="" />} > <Dropdown.Menu className={styles.dropDownMenu}> <Dropdown.Item className={styles.dropDownItem} onClick={() => onAddIntervalSheetClick(undefined, 4, 2)}> <img src={icon2x2} height="18px" alt="" /> 2x2 </Dropdown.Item> <Dropdown.Item className={styles.dropDownItem} onClick={() => onAddIntervalSheetClick(undefined, 9, 3)}> <img src={icon3x3} height="18px" alt="" /> 3x3 </Dropdown.Item> <Dropdown.Item className={styles.dropDownItem} onClick={() => onAddIntervalSheetClick(undefined, 16, 4)} > <img src={icon4x4} height="18px" alt="" /> 4x4 </Dropdown.Item> <Dropdown.Item className={styles.dropDownItem} onClick={() => onAddIntervalSheetClick(undefined, 25, 5)} > <img src={icon5x5} height="18px" alt="" /> 5x5 </Dropdown.Item> <Dropdown.Item className={styles.dropDownItem} onClick={() => onAddIntervalSheetClick(undefined, 36, 6)} > <img src={icon6x6} height="18px" alt="" /> 6x6 </Dropdown.Item> </Dropdown.Menu> </Dropdown> } mouseEnterDelay={1000} on={['hover']} position="right center" className={stylesPop.popup} content="Add MoviePrint (interval based)" /> <Popup trigger={ <Dropdown button className={styles.dropDownButton} floating disabled={fileMissingStatus} icon={<img src={iconAddFace} height="18px" alt="" />} > <Dropdown.Menu className={styles.dropDownMenu}> <Dropdown.Item disabled={isFaceType} className={styles.dropDownItem} onClick={() => onAddFaceSheetClick('scanBetweenInAndOut', 0.01)} > Scan every 100th frame between IN and OUT </Dropdown.Item> <Dropdown.Item disabled={isFaceType} className={styles.dropDownItem} onClick={() => onAddFaceSheetClick('scanBetweenInAndOut', 0.1)} > Scan every 10th frame between IN and OUT </Dropdown.Item> <Dropdown.Divider /> <Dropdown.Item disabled={isFaceType} className={styles.dropDownItem} onClick={() => onAddFaceSheetClick('scanFramesOfSheet')} > Scan these thumbs </Dropdown.Item> </Dropdown.Menu> </Dropdown> } mouseEnterDelay={1000} on={['hover']} position="right center" className={stylesPop.popup} content="Add MoviePrint (faces based)" /> </Button.Group>{' '} <Button.Group className={`${defaultView === VIEW.STANDARDVIEW ? '' : styles.hidden}`}> <Popup trigger={ <Dropdown button className={styles.dropDownButton} floating // closeOnBlur={false} // closeOnChange={false} disabled={fileMissingStatus || isShotType} icon={<img src={iconSort} height="18px" alt="" />} > <Dropdown.Menu className={styles.dropDownMenu}> <Dropdown.Item className={styles.dropDownItem} onClick={() => { onSortSheet(SORT_METHOD.REVERSE); }} > Reverse sort </Dropdown.Item> <Dropdown.Item className={styles.dropDownItem} onClick={() => { onSortSheet(SORT_METHOD.FRAMENUMBER); }} > Framenumber </Dropdown.Item> <Dropdown.Item disabled={!isFaceType} className={styles.dropDownItem} onClick={() => { onSortSheet(SORT_METHOD.FACECOUNT); }} > Amount of faces in frame </Dropdown.Item> <Dropdown.Item disabled={!isFaceType} className={styles.dropDownItem} onClick={() => { onSortSheet(SORT_METHOD.FACESIZE); }} > Face size </Dropdown.Item> <Dropdown.Item disabled={!isFaceType} className={styles.dropDownItem} onClick={() => { onSortSheet(SORT_METHOD.FACEOCCURRENCE); }} > Occurrence of face </Dropdown.Item> <Dropdown.Item disabled={!isFaceType} className={styles.dropDownItem} onClick={() => { onSortSheet(SORT_METHOD.FACECONFIDENCE); }} > Confidence value of face </Dropdown.Item> </Dropdown.Menu> </Dropdown> } mouseEnterDelay={1000} on={['hover']} position="right center" className={stylesPop.popup} content="Sort" /> <Popup trigger={ <Dropdown button className={styles.dropDownButton} floating closeOnBlur={false} closeOnChange={true} disabled={fileMissingStatus || isShotType} icon={<img src={sheetHasFilters ? iconFilterEnabled : iconFilter} height="18px" alt="" />} > <Dropdown.Menu className={`${styles.dropDownMenu} ${styles.dropDownMenuFilter}`}> <Dropdown.Item disabled={!isFaceType} className={`${styles.dropDownItem} ${ faceCountFilter.enabled ? styles.dropDownItemCheckboxAndSlider : '' }`} onClick={e => e.stopPropagation()} > <Checkbox data-tid="enableSizeFilterCheckbox" label="Amount of faces in frame" checked={faceCountFilter.enabled} onChange={(e, { checked }) => { onFilterChange(FILTER_METHOD.FACECOUNT, { ...faceCountFilter, enabled: checked, }); }} /> <Range data-tid="faceCountRangeSlider" className={`${styles.slider} ${!faceCountFilter.enabled ? styles.dropDownItemHidden : ''}`} disabled={!isFaceType || !faceCountFilter.enabled} min={FILTER_METHOD_FACECOUNT.MIN} max={FILTER_METHOD_FACECOUNT.MAX} defaultValue={[faceCountFilter.lower, faceCountFilter.upper]} marks={{ [FILTER_METHOD_FACECOUNT.MIN]: FILTER_METHOD_FACECOUNT.MIN, [FILTER_METHOD_FACECOUNT.MAX]: 'max', }} handle={handle} onAfterChange={value => { onFilterChange(FILTER_METHOD.FACECOUNT, { ...faceCountFilter, lower: value[0], upper: value[1], }); }} /> </Dropdown.Item> <Dropdown.Item disabled={!isFaceType} className={`${styles.dropDownItem} ${ageFilter.enabled ? styles.dropDownItemCheckboxAndSlider : ''}`} onClick={e => e.stopPropagation()} > <Checkbox data-tid="enableAgeFilterCheckbox" label="Age" checked={ageFilter.enabled} onChange={(e, { checked }) => { onFilterChange(FILTER_METHOD.AGE, { ...ageFilter, enabled: checked, }); }} /> <Range data-tid="ageRangeSlider" className={`${styles.slider} ${!ageFilter.enabled ? styles.dropDownItemHidden : ''}`} disabled={!isFaceType || !ageFilter.enabled} min={FILTER_METHOD_AGE.MIN} max={FILTER_METHOD_AGE.MAX} defaultValue={[ageFilter.lower, ageFilter.upper]} marks={{ [FILTER_METHOD_AGE.MIN]: FILTER_METHOD_AGE.MIN, [FILTER_METHOD_AGE.MAX]: 'max', }} handle={handle} onAfterChange={value => { onFilterChange(FILTER_METHOD.AGE, { ...ageFilter, lower: value[0], upper: value[1], }); }} /> </Dropdown.Item> <Dropdown.Item disabled={!isFaceType} className={`${styles.dropDownItem} ${ faceOccurrenceFilter.enabled ? styles.dropDownItemCheckboxAndSlider : '' }`} onClick={e => e.stopPropagation()} > <Checkbox data-tid="enableFaceOccurrenceFilterCheckbox" label="Occurrence of face" checked={faceOccurrenceFilter.enabled} onChange={(e, { checked }) => { onFilterChange(FILTER_METHOD.FACEOCCURRENCE, { ...faceOccurrenceFilter, enabled: checked, }); }} /> <Range data-tid="faceOccurrenceRangeSlider" className={`${styles.slider} ${!faceOccurrenceFilter.enabled ? styles.dropDownItemHidden : ''}`} disabled={!isFaceType || !faceOccurrenceFilter.enabled} min={FILTER_METHOD_FACEOCCURRENCE.MIN} max={FILTER_METHOD_FACEOCCURRENCE.MAX} defaultValue={[faceOccurrenceFilter.lower, faceOccurrenceFilter.upper]} marks={{ [FILTER_METHOD_FACEOCCURRENCE.MIN]: FILTER_METHOD_FACEOCCURRENCE.MIN, [FILTER_METHOD_FACEOCCURRENCE.MAX]: 'max', }} handle={handle} onAfterChange={value => { onFilterChange(FILTER_METHOD.FACEOCCURRENCE, { ...faceOccurrenceFilter, lower: value[0], upper: value[1], }); }} /> </Dropdown.Item> <Dropdown.Item disabled={!isFaceType} className={`${styles.dropDownItem} ${sizeFilter.enabled ? styles.dropDownItemCheckboxAndSlider : ''}`} onClick={e => e.stopPropagation()} > <Checkbox data-tid="enableSizeFilterCheckbox" label="Face size" checked={sizeFilter.enabled} onChange={(e, { checked }) => { onFilterChange(FILTER_METHOD.FACESIZE, { ...sizeFilter, enabled: checked, }); }} /> <Range data-tid="sizeRangeSlider" className={`${styles.slider} ${!sizeFilter.enabled ? styles.dropDownItemHidden : ''}`} disabled={!isFaceType || !sizeFilter.enabled} min={defaultFaceSizeThreshold} max={FILTER_METHOD_FACESIZE.MAX} defaultValue={[sizeFilter.lower, sizeFilter.upper]} marks={{ [FILTER_METHOD_FACESIZE.MEDIUM]: 'medium', [FILTER_METHOD_FACESIZE.CLOSE]: 'close', [FILTER_METHOD_FACESIZE.MAX]: 'max', }} handle={handle} onAfterChange={value => { onFilterChange(FILTER_METHOD.FACESIZE, { ...sizeFilter, lower: value[0], upper: value[1], }); }} /> </Dropdown.Item> <Dropdown.Item disabled={!isFaceType} className={`${styles.dropDownItem} ${ genderFilter.enabled ? styles.dropDownItemCheckboxAndSlider : '' }`} onClick={e => e.stopPropagation()} > <Checkbox data-tid="enableGenderFilterCheckbox" label="Gender" checked={genderFilter.enabled} onChange={(e, { checked }) => { onFilterChange(FILTER_METHOD.GENDER, { ...genderFilter, enabled: checked, }); }} /> <div className={`${styles.dropDownItemRadioGroup} ${ !genderFilter.enabled ? styles.dropDownItemHidden : '' }`} > <Radio data-tid="genderFemaleRadioBtn" disabled={!genderFilter.enabled} label={<label className={styles.label}>Female</label>} name="genderGroup" value="female" checked={genderFilter.value === 'female'} onChange={(e, { value }) => { onFilterChange(FILTER_METHOD.GENDER, { ...genderFilter, value, }); }} /> <Radio data-tid="genderMaleRadioBtn" disabled={!genderFilter.enabled} label={<label className={styles.label}>Male</label>} name="genderGroup" value="male" checked={genderFilter.value === 'male'} onChange={(e, { value }) => { onFilterChange(FILTER_METHOD.GENDER, { value, }); }} /> </div> </Dropdown.Item> <Divider /> <Dropdown.Item disabled={!isFaceType || faceIdFilter.enabled} className={`${styles.dropDownItem} ${ uniqueFilter.enabled ? styles.dropDownItemCheckboxAndSlider : '' }`} onClick={e => e.stopPropagation()} > <Checkbox data-tid="enableUniqueFilterCheckbox" label="Unique faces" checked={uniqueFilter.enabled} onChange={(e, { checked }) => { onFilterChange(FILTER_METHOD.DISTTOORIGIN, { enabled: checked, value: 0, }); }} /> <SliderWithTooltip data-tid="faceUniquenessThresholdSlider" className={`${styles.slider} ${!uniqueFilter.enabled ? styles.dropDownItemHidden : ''}`} disabled={!isFaceType || !uniqueFilter.enabled || faceIdFilter.enabled} min={40} max={80} defaultValue={defaultFaceUniquenessThreshold * 100} marks={{ // 50: 'unique', 60: 'more unique faces | less unique faces ', // 70: 'similar', }} handle={handle} onAfterChange={value => { const valueFloat = value / 100.0; onChangeFaceUniquenessThreshold(valueFloat); onFilterSheet(currentSheetFilter, undefined, undefined, valueFloat); onUpdateSheetFilter(currentSheetFilter); }} /> </Dropdown.Item> {faceIdFilter.enabled && ( <Dropdown.Item disabled={!isFaceType || faceIdFilter.enabled} className={styles.dropDownItem} onClick={e => e.stopPropagation()} > <Checkbox data-tid="enablefaceIdFilterCheckbox" label="Same face" checked={faceIdFilter.enabled} /> </Dropdown.Item> )} </Dropdown.Menu> </Dropdown> } mouseEnterDelay={1000} on={['hover']} position="right center" className={stylesPop.popup} content="Filter" /> <Popup trigger={ <Button className={styles.imageButton} size="large" data-tid="duplicateSheetItemBtn" onClick={() => onDuplicateSheetClick(undefined, undefined)} disabled={fileMissingStatus} icon={<img src={iconCopy} height="18px" alt="" />} /> } mouseEnterDelay={1000} on={['hover']} position="bottom center" className={stylesPop.popup} content="Duplicate MoviePrint" /> {defaultView === VIEW.STANDARDVIEW && ( <Popup trigger={ <Button className={styles.normalButton} size="large" disabled={isFaceType} data-tid={ sheetView === SHEET_VIEW.GRIDVIEW ? 'changeViewSheetToTimelineViewBtn' : 'changeViewSheetToGridViewBtn' } onClick={() => onChangeSheetViewClick( undefined, undefined, sheetView === SHEET_VIEW.GRIDVIEW ? SHEET_VIEW.TIMELINEVIEW : SHEET_VIEW.GRIDVIEW, ) } icon={<img src={sheetView === SHEET_VIEW.GRIDVIEW ? iconBarcode : iconGrid} height="18px" alt="" />} /> } mouseEnterDelay={1000} on={['hover']} position="bottom center" className={stylesPop.popup} content={sheetView === SHEET_VIEW.GRIDVIEW ? 'Switch to timeline view' : 'Switch to grid view'} /> )} {defaultView !== VIEW.STANDARDVIEW && ( <Popup trigger={ <Button className={styles.imageButton} size="large" disabled={defaultView === VIEW.STANDARDVIEW} data-tid={ sheetView === SHEET_VIEW.GRIDVIEW ? 'changeViewSheetToTimelineViewBtn' : 'changeViewSheetToGridViewBtn' } onClick={() => onChangeSheetViewClick( undefined, undefined, sheetView === SHEET_VIEW.GRIDVIEW ? SHEET_VIEW.TIMELINEVIEW : SHEET_VIEW.GRIDVIEW, ) } icon={ <img src={sheetView === SHEET_VIEW.GRIDVIEW ? iconCutView : iconThumbView} height="18px" alt="" /> } /> } mouseEnterDelay={1000} on={['hover']} position="bottom center" className={stylesPop.popup} content={sheetView === SHEET_VIEW.GRIDVIEW ? 'Switch to cut view' : 'Switch to thumb view'} /> )} </Button.Group>{' '} <Popup trigger={ <Button className={`${styles.normalButton} ${defaultView === VIEW.STANDARDVIEW ? '' : styles.selected}`} style={{ marginRight: '8px', marginLeft: '8px', }} size="large" circular data-tid={defaultView === VIEW.STANDARDVIEW ? 'showPlayerBtn' : 'hidePlayerBtn'} disabled={fileMissingStatus} onClick={() => { if (defaultView === VIEW.STANDARDVIEW) { onSetViewClick(VIEW.PLAYERVIEW); } else { onSetViewClick(VIEW.STANDARDVIEW); } return undefined; }} icon={defaultView === VIEW.STANDARDVIEW ? 'video' : 'close'} /> } mouseEnterDelay={1000} on={['hover']} position="bottom center" className={stylesPop.popup} content={ defaultView === VIEW.STANDARDVIEW ? ( <span> Show player view <mark>2</mark> </span> ) : ( <span> Hide player view <mark>2</mark> </span> ) } />{' '} <Button.Group className={`${defaultView === VIEW.STANDARDVIEW ? '' : styles.hidden}`}> <Popup trigger={ <Button disabled={sheetView === SHEET_VIEW.TIMELINEVIEW} className={styles.normalButton} size="large" data-tid="zoomOutBtn" onClick={() => onChangeDefaultZoomLevel('zoomOut')} icon={<img src={iconZoomOut} height="18px" alt="" />} /> } mouseEnterDelay={1000} on={['hover']} position="bottom center" className={stylesPop.popup} content="Zoom Out" /> <Popup trigger={ <Button disabled={sheetView === SHEET_VIEW.TIMELINEVIEW} className={styles.normalButton} size="large" data-tid="zoomFitBtn" onClick={() => onChangeDefaultZoomLevel('resetZoom')} icon={<img src={iconExpand} height="18px" alt="" />} /> } mouseEnterDelay={1000} on={['hover']} position="bottom center" className={stylesPop.popup} content="Fit MoviePrint" /> <Popup trigger={ <Button disabled={sheetView === SHEET_VIEW.TIMELINEVIEW} className={styles.normalButton} size="large" data-tid="zoomInBtn" onClick={() => onChangeDefaultZoomLevel('zoomIn')} icon={<img src={iconZoomIn} height="18px" alt="" />} /> } mouseEnterDelay={1000} on={['hover']} position="bottom center" className={stylesPop.popup} content="Zoom In" /> </Button.Group>{' '} <Button.Group className={`${defaultView === VIEW.STANDARDVIEW ? '' : styles.hidden}`}> <Popup trigger={ <Button className={styles.normalButton} size="large" circular data-tid={visibilityFilter === THUMB_SELECTION.ALL_THUMBS ? 'showOnlyVisibleBtn' : 'showHiddenBtn'} onClick={onToggleShowHiddenThumbsClick} icon={ <img src={visibilityFilter === THUMB_SELECTION.ALL_THUMBS ? iconHide : iconUnhide} height="18px" alt="" /> } /> } mouseEnterDelay={1000} on={['hover']} position="bottom center" className={stylesPop.popup} content={visibilityFilter === THUMB_SELECTION.ALL_THUMBS ? 'Show visible thumbs only' : 'Show hidden thumbs'} /> <Popup trigger={ <Button className={styles.imageButton} size="large" disabled={!isGridViewAndDefault} data-tid="toggleHeaderBtn" onClick={() => onToggleHeaderClick()} > <img src={defaultShowHeader ? iconHeaderEnabled : iconHeader} height="18px" alt="" /> </Button> } mouseEnterDelay={1000} on={['hover']} position="bottom center" className={stylesPop.popup} content="Show header" /> <Popup trigger={ <Button className={styles.imageButton} size="large" disabled={!isGridViewAndDefault} data-tid="showThumbInfoBtn" onClick={() => { const current = defaultThumbInfo; const currentIndex = THUMB_INFO_OPTIONS.findIndex(item => item.value === current); const nextIndex = currentIndex < THUMB_INFO_OPTIONS.length - 1 ? currentIndex + 1 : 0; onThumbInfoClick(THUMB_INFO_OPTIONS[nextIndex].value); }} > <img src={defaultThumbInfo !== THUMB_INFO.HIDEINFO ? iconFrameInfoEnabled : iconFrameInfo} height="18px" alt="" /> </Button> } mouseEnterDelay={1000} on={['hover']} position="bottom center" className={stylesPop.popup} content="Show frames, timecode or none" /> <Popup trigger={ <Button className={styles.imageButton} size="large" data-tid="toggleFaceRectBtn" disabled={!isFaceType} onClick={() => onToggleFaceRectClick()} icon={<img src={defaultShowFaceRect ? iconShowFaceRectEnabled : iconShowFaceRect} height="18px" alt="" />} /> } mouseEnterDelay={1000} on={['hover']} position="bottom center" className={stylesPop.popup} content="Toggle face rectangle" /> <Popup trigger={ <Dropdown button className={styles.dropDownButton} floating closeOnBlur={false} closeOnChange={false} disabled={fileMissingStatus} icon={<img src={iconCaretDown} height="18px" alt="" />} > <Dropdown.Menu className={styles.dropDownMenu}> <Dropdown.Item className={`${styles.dropDownItem} ${styles.dropDownItemIconInvert}`} onClick={() => onToggleImagesClick()} icon={<img src={defaultShowImages ? iconNoImage : iconImage} height="18px" alt="" />} text="Toggle images" /> <Dropdown.Item className={styles.dropDownItem} onClick={() => optimiseGridLayout()} icon={<img src={icon3x3} height="18px" alt="" />} text="Optimise grid layout" /> </Dropdown.Menu> </Dropdown> } mouseEnterDelay={1000} on={['hover']} position="right center" className={stylesPop.popup} content="Additional settings" /> </Button.Group> </div> ); }; export default FloatingMenu; <|start_filename|>app/components/Menu.css<|end_filename|> .container { z-index: 200; background-color: rgba(30,30,30,1); } .menu { z-index: 200; /* background-color: #1e1e1e; */ background-color: rgba(30,30,30,1) !important; } .saveButton { background-color: rgba(255, 80, 6, 1.0) !important; } .saveButton:hover { background-color: rgba(255, 80, 6, 0.5) !important; } .saveButton :global(.ui.loader) { margin-right: 4.5px !important; } .saveButton :global(.ui.mini.loader) { height: 0.8rem !important; } .saveButton :global(.ui.loader:after) { border-color: #ffffff transparent transparent !important; } @keyframes rotating { from { -ms-transform: rotate(0deg); -moz-transform: rotate(0deg); -webkit-transform: rotate(0deg); -o-transform: rotate(0deg); transform: rotate(0deg); } to { -ms-transform: rotate(360deg); -moz-transform: rotate(360deg); -webkit-transform: rotate(360deg); -o-transform: rotate(360deg); transform: rotate(360deg); } } @keyframes loader{ from { -webkit-transform:rotate(0); transform:rotate(0) } to { -webkit-transform:rotate(360deg); transform:rotate(360deg) }} .spinner { animation:loader .6s linear; animation-iteration-count:infinite; border-radius:500rem; border-color:#767676 transparent transparent; border-style:solid; width: 4px; border-width:.2em; box-shadow:0 0 0 1px transparent } /* .headerItem { float: left; opacity: 0.5; } .headerItem:hover { cursor: pointer; opacity: 1; } .subHeader { float: left; opacity: 0.5; font-family: 'Open sans'; font-size: 12px; color: #eee; padding: 12px; } */ <|start_filename|>app/components/Popup.css<|end_filename|> .popup { margin-bottom: 0 !important; font-family: Lato, 'Helvetica Neue', Arial, Helvetica, sans-serif !important; font-weight: 100 !important; font-size: 12px !important; } .popupSmall { /* background-color: rgba(30, 30, 30, 0.9) !important; */ /* color: #ffffff !important; */ /* border: none !important; */ margin: 0 !important; padding: 4px 8px !important; font-family: Lato, 'Helvetica Neue', Arial, Helvetica, sans-serif !important; font-weight: 100 !important; font-size: 12px !important; } .popupSmall::before { display: none !important; } .toast { padding: 20px; border-radius: 4px; /* overflow-wrap: break-word; */ overflow-wrap: anywhere; hyphens: auto; } .toastInfo { /* background-color: rgba(60, 60, 60, 1.0); */ background-color: rgba(60, 60, 60, 0.97); box-shadow: 0px 0px 64px 0px rgba(255,255,255,0.1); color: white; } .toastSuccess { background-color: rgba(56, 143, 2, 0.97); /* background-color: #388F02; */ color: white; } .toastError { background-color: rgba(194, 0, 0, 0.97); /* background-color: #c20000; */ color: white; } .toastProgress { background: #f2711c; } <|start_filename|>.eslintrc.js<|end_filename|> module.exports = { extends: 'erb', settings: { 'import/resolver': 'webpack' } } <|start_filename|>app/containers/FileList.js<|end_filename|> // @flow import React, { Component } from 'react'; import PropTypes from 'prop-types'; import FileListElement from '../components/FileListElement'; import styles from '../components/FileList.css'; import { getObjectProperty, } from '../utils/utils'; import { MENU_HEADER_HEIGHT, MENU_FOOTER_HEIGHT } from '../utils/constants'; class SortedFileList extends Component { render() { const { files, settings, posterobjectUrlObjects, visibilitySettings } = this.props; return ( <div style={{ marginBottom: `${MENU_HEADER_HEIGHT + MENU_FOOTER_HEIGHT}px`, // direction: 'ltr', // compensate for rtl on ItemMovieList to get scroolbar appear on left hand side }} > <ul className={`${styles.MainList}`} > {files.length === 0 ? ( <div className={`${styles.emptyFilelist}`} > The movie list is empty. <br /><br /> Please drag in one or more movies. </div> ) : (files.map((file, index) => ( <FileListElement key={file.id} fileId={file.id} {...file} index={index} onFileListElementClick={this.props.onFileListElementClick} onOpenFileExplorer={this.props.onOpenFileExplorer} onAddIntervalSheetClick={this.props.onAddIntervalSheetClick} onSetSheetClick={this.props.onSetSheetClick} onChangeSheetViewClick={this.props.onChangeSheetViewClick} onSubmitMoviePrintNameClick={this.props.onSubmitMoviePrintNameClick} onDuplicateSheetClick={this.props.onDuplicateSheetClick} onConvertToIntervalBasedClick={this.props.onConvertToIntervalBasedClick} onExportSheetClick={this.props.onExportSheetClick} onScanMovieListItemClick={this.props.onScanMovieListItemClick} onReplaceMovieListItemClick={this.props.onReplaceMovieListItemClick} onEditTransformListItemClick={this.props.onEditTransformListItemClick} onRemoveMovieListItem={this.props.onRemoveMovieListItem} onDeleteSheetClick={this.props.onDeleteSheetClick} currentFileId={settings.currentFileId} currentSheetId={this.props.currentSheetId} objectUrl={posterobjectUrlObjects[file.posterFrameId]} sheetsObject={ this.props.sheetsByFileId[file.id] === undefined ? {} : this.props.sheetsByFileId[file.id] } /> ))) } </ul> </div> ); } } export default SortedFileList; <|start_filename|>app/reducers/files.js<|end_filename|> /* eslint no-case-declarations: "off" */ import log from 'electron-log'; import { RotateFlags } from '../utils/openCVProperties'; const file = (state = {}, type, payload, index) => { switch (type) { case 'UPDATE_SHEETCOUNTER': if (state.id !== payload.fileId) { return state; } return { ...state, sheetCounter: (state.sheetCounter || 0) + payload.incrementValue }; case 'UPDATE_FILESCAN_STATUS': if (state.id !== payload.fileId) { return state; } return { ...state, fileScanStatus: payload.fileScanStatus }; case 'UPDATE_FILE_MISSING_STATUS': if (state.id !== payload.fileId) { return state; } return { ...state, fileMissingStatus: payload.fileMissingStatus }; case 'UPDATE_MOVIE_LIST_ITEM_USERATIO': if (state.id !== payload.fileId) { return state; } return { ...state, useRatio: payload.useRatio }; case 'REPLACE_MOVIE_LIST_ITEM': if (state.id !== payload.fileId) { return state; } return { ...state, path: payload.path, name: payload.name, size: payload.size, lastModified: payload.lastModified, }; case 'UPDATE_MOVIE_LIST_ITEM': { if (state.id !== payload.fileId) { return state; } const { fps, fourCC, frameCount } = payload; let { height, width } = payload; const originalWidth = width; const originalHeight = height; // if transformObject already exists then calculate width and height from it const { transformObject } = state; console.log(state); if (transformObject !== undefined) { width = originalWidth - transformObject.cropLeft - transformObject.cropRight; height = originalHeight - transformObject.cropTop - transformObject.cropBottom; } return { ...state, frameCount, originalWidth, width, originalHeight, height, fps, fourCC, }; } case 'SET_TRANSFORM': if (state.id !== payload.fileId) { return state; } return { ...state, transformObject: payload.transformObject }; case 'ROTATE_WIDTH_AND_HEIGHT': { if (state.id !== payload.fileId) { return state; } const { shouldRotate } = payload; if (shouldRotate) { return { ...state, width: state.originalHeight, height: state.originalWidth }; } return { ...state, width: state.originalWidth, height: state.originalHeight }; } case 'UPDATE_CROPPING': { if (state.id !== payload.fileId) { return state; } const { transformObject } = payload; const { cropTop, cropLeft, cropBottom, cropRight, rotationFlag } = transformObject; let origWidth = state.originalWidth; let origHeight = state.originalHeight; if (rotationFlag === RotateFlags.ROTATE_90_CLOCKWISE || rotationFlag === RotateFlags.ROTATE_90_COUNTERCLOCKWISE) { [origWidth, origHeight] = [origHeight, origWidth]; // swapping of width and height } const newWidth = origWidth - cropLeft - cropRight; const newHeight = origHeight - cropTop - cropBottom; return { ...state, width: newWidth, height: newHeight, transformObject }; } case 'UPDATE_ASPECT_RATIO': if (state.id !== payload.fileId) { return state; } return { ...state, transformObject: { ...state.transformObject, aspectRatioInv: payload.aspectRatioInv } }; case 'UPDATE_IN_OUT_POINT': if (state.id !== payload.fileId) { return state; } return { ...state, fadeInPoint: payload.fadeInPoint, fadeOutPoint: payload.fadeOutPoint }; default: return state; } }; const files = (state = [], { type, payload }) => { switch (type) { case 'CLEAR_MOVIE_LIST': return []; case 'ADD_MOVIE_LIST_ITEMS': { log.debug(payload); log.debug(state); // combine state array and new files array const combinedArray = state.concat(payload); log.debug(combinedArray); return combinedArray; } case 'REMOVE_MOVIE_LIST_ITEM': { const newArray = state.slice(); const indexOfItemToRemove = newArray.findIndex(singleFile => singleFile.id === payload.fileId); newArray.splice(indexOfItemToRemove, 1); return newArray; } case 'REPLACE_MOVIE_LIST_ITEM': case 'UPDATE_MOVIE_LIST_ITEM_USERATIO': case 'UPDATE_MOVIE_LIST_ITEM': case 'SET_TRANSFORM': case 'ROTATE_WIDTH_AND_HEIGHT': case 'UPDATE_CROPPING': case 'UPDATE_ASPECT_RATIO': case 'UPDATE_IN_OUT_POINT': case 'UPDATE_FILE_MISSING_STATUS': case 'UPDATE_FILESCAN_STATUS': case 'UPDATE_SHEETCOUNTER': return state.map((t, index) => file(t, type, payload, index)); default: return state; } }; export default files; <|start_filename|>app/reducers/sheetsByFileId.js<|end_filename|> import log from 'electron-log'; import { deleteProperty } from './../utils/utils'; import {} from '../utils/constants'; const thumb = (state = {}, action, index) => { switch (action.type) { case 'TOGGLE_SCENE': if (state.sceneId !== action.payload.sceneId) { return state; } return Object.assign({}, state, { hidden: !state.hidden, }); case 'UPDATE_SCENE_LENGTH': if (state.sceneId !== action.payload.sceneId) { return state; } return Object.assign({}, state, { length: action.payload.length, }); case 'TOGGLE_SCENE_ARRAY': if (!action.payload.sceneIdArray.includes(state.sceneId)) { return state; } return Object.assign({}, state, { hidden: !state.hidden, }); case 'ADD_THUMB': return Object.assign({}, state, { index, }); case 'INSERT_SCENE': return Object.assign({}, state, { index, }); case 'ADD_THUMBS': return { thumbId: action.payload.thumbIdArray[index], frameId: action.payload.frameIdArray[index], frameNumber: action.payload.frameNumberArray[index], fileId: action.payload.fileId, index, hidden: false, }; case 'ADD_SCENEIDS_TO_THUMBS': // sceneIds are added as thumbId property return Object.assign({}, state, { thumbId: action.payload.sceneIdArray[index], }); case 'CHANGE_THUMB': if (state.thumbId !== action.payload.thumbId) { return state; } return Object.assign({}, state, { frameId: action.payload.newFrameId, frameNumber: action.payload.newFrameNumber, }); case 'TOGGLE_THUMB': if (state.thumbId !== action.payload.thumbId) { return state; } return Object.assign({}, state, { hidden: !state.hidden, }); case 'SHOW_ALL_THUMBS': return Object.assign({}, state, { hidden: false, }); case 'SHOW_THUMBS_BY_FRAMENUMBERARRAY': // hide thumbs not included in the frameNumberArray and show frames included if (action.payload.frameNumberArray.includes(state.frameNumber)) { return Object.assign({}, state, { hidden: false, }); } return Object.assign({}, state, { hidden: true, }); case 'TOGGLE_THUMBS_BY_THUMBIDARRAY': // hide thumbs included in the thumbIdArray if (!action.payload.thumbIdArray.includes(state.thumbId)) { return state; } return Object.assign({}, state, { hidden: !state.hidden, }); case 'CHANGE_THUMB_ARRAY': const foundItem = action.payload.dataToUpdateArray.find(item => item.frameNumber === state.frameNumber); if (foundItem === undefined) { return state; } return Object.assign({}, state, foundItem); // case 'UPDATE_SCENEID_OF_THUMB': // if (state.thumbId !== action.payload.thumbId) { // return state; // } // return Object.assign({}, state, { // sceneId: action.payload.sceneId // }); case 'UPDATE_FRAMENUMBER_AND_COLORARRAY_OF_THUMB': const indexOfArray = action.payload.frameNumberAndColorArray.findIndex(item => item.thumbId === state.thumbId); if (indexOfArray < 0) { return state; } return Object.assign({}, state, { frameNumber: action.payload.frameNumberAndColorArray[indexOfArray].frameNumber, colorArray: action.payload.frameNumberAndColorArray[indexOfArray].colorArray, // facesArray: undefined, }); case 'UPDATE_ORDER': // log.debug(state); // log.debug(state.id); // log.debug(index); // log.debug(action.payload.array[index].index); if (index === action.payload.array[index].index) { return state; } return Object.assign({}, action.payload.array[index], { index, }); default: return state; } }; const sheetsByFileId = (state = {}, action) => { switch (action.type) { case 'ADD_SCENE': { // load the current scenes array, if it does not exist it stays empty // log.debug(action.payload); // log.debug(state); let currentArray = []; if ( state[action.payload.fileId] !== undefined && state[action.payload.fileId][action.payload.sheetId] !== undefined && state[action.payload.fileId][action.payload.sheetId].sceneArray !== undefined ) { currentArray = state[action.payload.fileId][action.payload.sheetId].sceneArray.slice(); } const combinedArray = currentArray.concat(action.payload); return { ...state, [action.payload.fileId]: { ...state[action.payload.fileId], [action.payload.sheetId]: { // conditional adding of properties ...(state[action.payload.fileId] === undefined ? {} : state[action.payload.fileId][action.payload.sheetId]), sceneArray: combinedArray, }, }, }; } case 'INSERT_SCENE': { // load the current scene array, if it does not exist it stays empty // log.debug(action.payload); // log.debug(state); let currentArray = []; if ( state[action.payload.fileId] !== undefined && state[action.payload.fileId][action.payload.sheetId] !== undefined && state[action.payload.fileId][action.payload.sheetId].sceneArray !== undefined ) { currentArray = state[action.payload.fileId][action.payload.sheetId].sceneArray.slice(); } currentArray.splice(action.payload.index, 0, action.payload); const combinedArrayReordered = currentArray.map((t, index) => thumb(t, action, index)); return { ...state, [action.payload.fileId]: { ...state[action.payload.fileId], [action.payload.sheetId]: { // conditional adding of properties ...(state[action.payload.fileId] === undefined ? {} : state[action.payload.fileId][action.payload.sheetId]), sceneArray: combinedArrayReordered, }, }, }; } case 'DELETE_SCENE': { // load the current scene array, if it does not exist it stays empty // log.debug(action.payload); // log.debug(state); let currentArray = []; if ( state[action.payload.fileId] !== undefined && state[action.payload.fileId][action.payload.sheetId] !== undefined && state[action.payload.fileId][action.payload.sheetId].sceneArray !== undefined ) { currentArray = state[action.payload.fileId][action.payload.sheetId].sceneArray.slice(); } currentArray.splice(action.payload.index, 1); return { ...state, [action.payload.fileId]: { ...state[action.payload.fileId], [action.payload.sheetId]: { // conditional adding of properties ...(state[action.payload.fileId] === undefined ? {} : state[action.payload.fileId][action.payload.sheetId]), sceneArray: currentArray, }, }, }; } case 'ADD_SCENES': { // load the current scenes array, if it does not exist or it should be cleared it stays empty let currentArray = []; if (!action.payload.clearOldScenes) { if ( state[action.payload.fileId] !== undefined && state[action.payload.fileId][action.payload.sheetId] !== undefined && state[action.payload.fileId][action.payload.sheetId].sceneArray !== undefined ) { currentArray = state[action.payload.fileId][action.payload.sheetId].sceneArray.slice(); } } const combinedArray = currentArray.concat(action.payload.sceneArray); // log.debug(action.payload); // log.debug(state); // log.debug(combinedArray); return { ...state, [action.payload.fileId]: { ...state[action.payload.fileId], [action.payload.sheetId]: { // conditional adding of properties ...(state[action.payload.fileId] === undefined ? {} : state[action.payload.fileId][action.payload.sheetId]), sceneArray: combinedArray, }, }, }; } case 'UPDATE_SCENEARRAY': return { ...state, [action.payload.fileId]: { ...state[action.payload.fileId], [action.payload.sheetId]: { // conditional adding of properties // only add when fileId exists ...(state[action.payload.fileId] === undefined ? {} : state[action.payload.fileId][action.payload.sheetId]), sceneArray: action.payload.sceneArray, }, }, }; case 'TOGGLE_SCENE': case 'TOGGLE_SCENE_ARRAY': case 'UPDATE_SCENE_LENGTH': return { ...state, [action.payload.fileId]: { ...state[action.payload.fileId], [action.payload.sheetId]: { ...state[action.payload.fileId][action.payload.sheetId], sceneArray: state[action.payload.fileId][action.payload.sheetId].sceneArray.map((t, index) => thumb(t, action), ), }, }, }; case 'CLEAR_SCENES': return { ...state, [action.payload.fileId]: { ...state[action.payload.fileId], [action.payload.sheetId]: { // conditional adding of properties // only add when fileId exists ...(state[action.payload.fileId] === undefined ? {} : state[action.payload.fileId][action.payload.sheetId]), sceneArray: [], }, }, }; case 'ADD_THUMB': { // load the current thumbs array, if it does not exist it stays empty // log.debug(action.payload); // log.debug(state); let currentArray = []; if ( state[action.payload.fileId] !== undefined && state[action.payload.fileId][action.payload.sheetId] !== undefined && state[action.payload.fileId][action.payload.sheetId].thumbsArray !== undefined ) { currentArray = state[action.payload.fileId][action.payload.sheetId].thumbsArray.slice(); } currentArray.splice(action.payload.index, 0, action.payload); const combinedArrayReordered = currentArray.map((t, index) => thumb(t, action, index)); return { ...state, [action.payload.fileId]: { ...state[action.payload.fileId], [action.payload.sheetId]: { // conditional adding of properties ...(state[action.payload.fileId] === undefined ? {} : state[action.payload.fileId][action.payload.sheetId]), thumbsArray: combinedArrayReordered, }, }, }; } case 'DELETE_THUMB': { // load the current thumbs array, if it does not exist it stays empty // log.debug(action.payload); // log.debug(state); let currentArray = []; if ( state[action.payload.fileId] !== undefined && state[action.payload.fileId][action.payload.sheetId] !== undefined && state[action.payload.fileId][action.payload.sheetId].sceneArray !== undefined ) { currentArray = state[action.payload.fileId][action.payload.sheetId].thumbsArray.slice(); } currentArray.splice(action.payload.index, 1); return { ...state, [action.payload.fileId]: { ...state[action.payload.fileId], [action.payload.sheetId]: { // conditional adding of properties ...(state[action.payload.fileId] === undefined ? {} : state[action.payload.fileId][action.payload.sheetId]), thumbsArray: currentArray, }, }, }; } case 'ADD_THUMBS': { // load the current thumbs array, if it does not exist it stays empty // log.debug(action.payload); // log.debug(state); let currentArray = []; if ( state[action.payload.fileId] !== undefined && state[action.payload.fileId][action.payload.sheetId] !== undefined && state[action.payload.fileId][action.payload.sheetId].thumbsArray !== undefined ) { currentArray = state[action.payload.fileId][action.payload.sheetId].thumbsArray.slice(); } // create new thumbs array const newArray = Object.keys(action.payload.thumbIdArray).map((t, index) => thumb(undefined, action, index)); // combine current and new thumbs array const combinedArray = currentArray.concat(newArray); let reIndexedArray = combinedArray; if (action.payload.noReorder === undefined) { // sort and reindex combinedArray combinedArray.sort((a, b) => a.frameNumber - b.frameNumber); reIndexedArray = combinedArray.map((item, index) => { return { ...item, index: index }; }); } return { ...state, [action.payload.fileId]: { ...state[action.payload.fileId], [action.payload.sheetId]: { // conditional adding of properties ...(state[action.payload.fileId] === undefined ? {} : state[action.payload.fileId][action.payload.sheetId]), thumbsArray: reIndexedArray, }, }, }; } case 'ADD_SCENEIDS_TO_THUMBS': return { ...state, [action.payload.fileId]: { ...state[action.payload.fileId], [action.payload.sheetId]: { ...state[action.payload.fileId][action.payload.sheetId], thumbsArray: state[action.payload.fileId][action.payload.sheetId].thumbsArray.map((t, index) => thumb(t, action, index), ), }, }, }; case 'CHANGE_THUMB': case 'SHOW_ALL_THUMBS': case 'TOGGLE_THUMB': case 'SHOW_THUMBS_BY_FRAMENUMBERARRAY': case 'TOGGLE_THUMBS_BY_THUMBIDARRAY': case 'CHANGE_THUMB_ARRAY': return { ...state, [action.payload.fileId]: { ...state[action.payload.fileId], [action.payload.sheetId]: { ...state[action.payload.fileId][action.payload.sheetId], thumbsArray: state[action.payload.fileId][action.payload.sheetId].thumbsArray.map((t, index) => thumb(t, action), ), }, }, }; // case 'UPDATE_SCENEID_OF_THUMB': // return { // ...state, // [action.payload.fileId]: { // ...state[action.payload.fileId], // [action.payload.sheetId]: { // ...state[action.payload.fileId][action.payload.sheetId], // thumbsArray: state[action.payload.fileId][action.payload.sheetId].thumbsArray.map(t => // thumb(t, action) // ) // } // } // }; case 'UPDATE_FRAMENUMBER_AND_COLORARRAY_OF_THUMB': return { ...state, [action.payload.fileId]: { ...state[action.payload.fileId], [action.payload.sheetId]: { ...state[action.payload.fileId][action.payload.sheetId], thumbsArray: state[action.payload.fileId][action.payload.sheetId].thumbsArray.map(t => thumb(t, action)), }, }, }; case 'UPDATE_ORDER': return { ...state, [action.payload.fileId]: { ...state[action.payload.fileId], [action.payload.sheetId]: { ...state[action.payload.fileId][action.payload.sheetId], thumbsArray: state[action.payload.fileId][action.payload.sheetId].thumbsArray.map((t, index) => thumb(t, action, index), ), }, }, }; case 'DUPLICATE_SHEET': const sheetToDuplicate = state[action.payload.fileId][action.payload.sheetId]; const duplicatedSheet = Object.assign({}, sheetToDuplicate); return { ...state, [action.payload.fileId]: { ...state[action.payload.fileId], [action.payload.newSheetId]: { ...duplicatedSheet, }, }, }; case 'UPDATE_SHEET_FILTER': return { ...state, [action.payload.fileId]: { ...state[action.payload.fileId], [action.payload.sheetId]: { // conditional adding of properties // only add when fileId exists ...(state[action.payload.fileId] === undefined ? {} : state[action.payload.fileId][action.payload.sheetId]), filter: Object.assign({}, action.payload.filter), }, }, }; case 'UPDATE_SHEET_SECONDSPERROW': return { ...state, [action.payload.fileId]: { ...state[action.payload.fileId], [action.payload.sheetId]: { // conditional adding of properties // only add when fileId exists ...(state[action.payload.fileId] === undefined ? {} : state[action.payload.fileId][action.payload.sheetId]), secondsPerRow: action.payload.secondsPerRow, }, }, }; case 'UPDATE_SHEET_COLUMNCOUNT': return { ...state, [action.payload.fileId]: { ...state[action.payload.fileId], [action.payload.sheetId]: { // conditional adding of properties // only add when fileId exists ...(state[action.payload.fileId] === undefined ? {} : state[action.payload.fileId][action.payload.sheetId]), columnCount: action.payload.columnCount, }, }, }; case 'UPDATE_SHEET_NAME': return { ...state, [action.payload.fileId]: { ...state[action.payload.fileId], [action.payload.sheetId]: { // conditional adding of properties // only add when fileId exists ...(state[action.payload.fileId] === undefined ? {} : state[action.payload.fileId][action.payload.sheetId]), name: action.payload.name, }, }, }; case 'UPDATE_SHEET_VIEW': return { ...state, [action.payload.fileId]: { ...state[action.payload.fileId], [action.payload.sheetId]: { // conditional adding of properties // only add when fileId exists ...(state[action.payload.fileId] === undefined ? {} : state[action.payload.fileId][action.payload.sheetId]), sheetView: action.payload.sheetView, }, }, }; case 'UPDATE_SHEET_TYPE': return { ...state, [action.payload.fileId]: { ...state[action.payload.fileId], [action.payload.sheetId]: { // conditional adding of properties // only add when fileId exists ...(state[action.payload.fileId] === undefined ? {} : state[action.payload.fileId][action.payload.sheetId]), type: action.payload.type, }, }, }; case 'UPDATE_SHEET_PARENT': return { ...state, [action.payload.fileId]: { ...state[action.payload.fileId], [action.payload.sheetId]: { // conditional adding of properties // only add when fileId exists ...(state[action.payload.fileId] === undefined ? {} : state[action.payload.fileId][action.payload.sheetId]), parentSheetId: action.payload.parentSheetId, }, }, }; case 'DELETE_SHEETS': // if fileId is an empty string, then clear all sheets // else only clear sheets of specific fileId console.log(action.payload); if (action.payload.fileId === undefined) { // fileId is empty, so delete everything return {}; } if (state[action.payload.fileId] === undefined) { // fileId does not exist, so it does not have to be deleted return state; } const copyOfState = Object.assign({}, state); if (action.payload.sheetId === undefined) { // sheet is empty, so delete whole fileId delete copyOfState[action.payload.fileId]; return copyOfState; } if (state[action.payload.fileId][action.payload.sheetId] === undefined) { // sheet does not exist, so it does not have to be deleted return state; } delete copyOfState[action.payload.fileId][action.payload.sheetId]; return copyOfState; case 'DELETE_THUMBSARRAY': return { ...state, [action.payload.fileId]: { ...state[action.payload.fileId], [action.payload.sheetId]: { // conditional adding of properties // only add when fileId exists ...(state[action.payload.fileId] === undefined ? {} : state[action.payload.fileId][action.payload.sheetId]), thumbsArray: [], }, }, }; default: return state; } }; export default sheetsByFileId; <|start_filename|>test/e2e/e2e.spec.js<|end_filename|> /* eslint no-restricted-syntax: ["error", "WithStatement", "BinaryExpression[operator='in']"] */ import { Application } from 'spectron'; import electronPath from 'electron'; import fakeDialog from 'spectron-fake-dialog'; import path from 'path'; import fs from 'fs'; import '../../internals/scripts/CheckBuildsExist'; jasmine.DEFAULT_TIMEOUT_INTERVAL = 15000; const delay = time => new Promise(resolve => setTimeout(resolve, time)); describe('main window', function spec() { beforeAll(async () => { this.app = new Application({ path: electronPath, args: [path.join(__dirname, '..', '..', 'app'), '--softreset'] // args: [path.join(__dirname, '..', '..', 'app'), '--softreset', '--debug'] }); fakeDialog.apply(this.app); console.log(await this.app.getSettings()); await delay(3000); return this.app.start(); }); afterAll(() => { if (this.app && this.app.isRunning()) { return this.app.stop(); } }); // prepare to store window title and handle for later use const windowObject = {}; it('should open the 4 windows', async () => { const { client } = this.app; const windowHandles = await client.windowHandles(); const windowNames = []; for (const windowHandleValue of windowHandles.value) { await client.window(windowHandleValue); const title = await client.getTitle(); // only add to array if it has a title // this will exclude debug windows if (title !== '') { windowNames.push(title) // store window title and handle for later use windowObject[title] = windowHandleValue } } console.log(windowNames.sort()); expect(windowNames).toEqual([ 'MoviePrint', 'MoviePrint_databaseWorker', 'MoviePrint_opencvWorker', 'MoviePrint_worker' ]); }); it("shouldn't have any logs in console of all windows", async () => { const { client } = this.app; Object.values(windowObject).map(async windowHandleValue => { await client.window(windowHandleValue); const logs = await client.getRenderProcessLogs(); // Print renderer process logs for MoviePrint renderer logs.forEach(log => { if (log.level === 'SEVERE' && log.message !== 'data:image/jpeg;base64, undefined - Failed to load resource: net::ERR_INVALID_URL') { expect(log.level).not.toEqual('SEVERE'); } }); }) }); it('should load a movie and get all 16 thumbs', async () => { const { client } = this.app; await client.window(windowObject['MoviePrint']); // focus main window const dragndropInput = '[type="file"]'; // selecting the input div via type const pathOfMovie = path.join(__dirname, '..', '..', 'resources', 'test_files', 'test_movie_1.mp4'); await client.chooseFile(dragndropInput, pathOfMovie); const val = await client.getValue(dragndropInput) console.log(val); client.waitForExist('[data-tid="thumbGridDiv"]', 5000); expect(await client.isExisting('[data-tid="thumbGridDiv"]')).toBe(true); expect(await client.isExisting('#thumb15')).toBe(true); // await client.browserWindow.capturePage().then((imageBuffer) => { // fs.writeFile('end of should load a movie and get all 16 thumbs.png', imageBuffer); // return undefined; // }).catch((err) => { // console.error(err); // }); }); it('should increase thumb count to 20', async () => { const { client } = this.app; // show settings menu await client.waitForExist('[data-tid="moreSettingsBtn"]', 3000); await client.element('[data-tid="moreSettingsBtn"]').click(); // move down to switch sliders to inputs await client.moveToObject('[data-tid="changeCachedFramesSizeDropdown"]'); await client.waitForVisible('[data-tid="showSlidersCheckbox"]', 3000); await client.element('[data-tid="showSlidersCheckbox"]').click(); // move up and change column count await client.moveToObject('[data-tid="columnCountInput"]'); await client.waitForVisible('[data-tid="columnCountInput"]', 3000); await client.setValue('[data-tid="columnCountInput"] input', 5); await client.keys('Enter'); await client.element('[data-tid="applyNewGridBtn"]').click(); await client.waitForExist('#thumb19', 3000); expect(await client.isExisting('#thumb19')).toBe(true); }); // it('should open a dialog', async () => { // const { client } = this.app; // fakeDialog.mock([ { method: 'showOpenDialogSync', value: ['faked.txt'] } ]) // // await client.click('[data-tid=openMoviesBtn]'); // const pathOfMovie = await client.getText('#return-value'); // console.log(pathOfMovie); // expect(await findCounter().getText()).toBe('0'); // }); // const findThumbGridDiv = () => this.app.client.element('[data-tid="thumbGridDiv"]'); // const thumbs = $$(".//*[contains(@class,'ThumbGrid__gridItem')]") // const findThumbs = () => this.app.client.elements('.//*[contains(@class,"ThumbGrid__gridItem")]'); // const thumbs = await findThumbs(); // console.log(thumbs); // console.log(thumbs.value.length); // await delay(1500); // const findCounter = () => this.app.client.element('[data-tid="counter"]'); // // const findButtons = async () => { // const { value } = await this.app.client.elements('[data-tclass="btn"]'); // return value.map(btn => btn.ELEMENT); // }; }); <|start_filename|>app/containers/WorkerApp.js<|end_filename|> // @flow import React, { Component } from 'react'; import PropTypes from 'prop-types'; import log from 'electron-log'; import path from 'path'; // import imageDB from './../utils/db'; import '../app.global.css'; import styles from './App.css'; import SortedVisibleThumbGrid from './VisibleThumbGrid'; import SortedVisibleSceneGrid from './VisibleSceneGrid'; import Conditional from '../components/Conditional'; import ErrorBoundary from '../components/ErrorBoundary'; import { getMoviePrintColor, getVisibleThumbs } from '../utils/utils'; import saveMoviePrint from '../utils/saveMoviePrint'; import { DEFAULT_THUMB_COUNT_MAX, MOVIEPRINT_WIDTH_HEIGHT_SIZE_LIMIT, SHEET_VIEW, VIEW } from '../utils/constants'; import { getBase64Object } from '../utils/utilsForOpencv'; const { ipcRenderer } = require('electron'); // const moviePrintDB = new Database('./db/moviePrint.db', { verbose: console.log }); class WorkerApp extends Component { constructor() { super(); this.state = { savingMoviePrint: false, sentData: {}, thumbObjectBase64s: {}, debugKeepView: false, }; } componentDidMount() { log.debug('I am the worker window - responsible for saving a MoviePrint'); ipcRenderer.on('action-saved-MoviePrint-done', event => { const debugKeepView = false; // set to tru to keep view for debugging this.setState({ debugKeepView, savingMoviePrint: false, ...(!debugKeepView && { sentData: {} }), ...(!debugKeepView && { visibleThumbs: [] }), ...(!debugKeepView && { thumbObjectBase64s: {} }), }); }); ipcRenderer.on('action-save-MoviePrint', (event, sentData) => { log.debug('workerWindow | action-save-MoviePrint'); log.debug(sentData); if (sentData.moviePrintWidth > MOVIEPRINT_WIDTH_HEIGHT_SIZE_LIMIT) { ipcRenderer.send( 'message-from-workerWindow-to-mainWindow', 'received-saved-file-error', `MoviePrint could not be saved due to sizelimit (width > ${MOVIEPRINT_WIDTH_HEIGHT_SIZE_LIMIT})`, ); } else { const visibleThumbs = getVisibleThumbs(sentData.sheet.thumbsArray, sentData.visibilityFilter); // calculate which frameSize is needed to be captured // aspectRatioInv // need to check portrait thumbs as resizeToMax is used which is not width specific const { newThumbWidth, aspectRatioInv } = sentData.scaleValueObject; const { file } = sentData; const newThumbHeight = newThumbWidth * aspectRatioInv; // get twice the needed resolution for better antialiasing, but // prevent upsizing of image of more than the original size const frameSize = Math.floor( Math.max(Math.min(newThumbHeight * 2, file.originalHeight), Math.min(newThumbWidth * 2, file.originalWidth)), ); console.log(aspectRatioInv); console.log(newThumbWidth); console.log(newThumbHeight); console.log(frameSize); const base64Object = getBase64Object( sentData.file.path, sentData.file.useRatio, visibleThumbs, frameSize, file.transformObject, ); // console.log(base64Object); this.setState({ savingMoviePrint: true, sentData, visibleThumbs, thumbObjectBase64s: base64Object, }); } }); } componentDidUpdate() { const { sentData, savingMoviePrint, visibleThumbs } = this.state; if (savingMoviePrint) { log.debug('workerWindow | componentDidUpdate and savingMoviePrint true'); const { file } = sentData; // save to filePath when defaultOutputPathFromMovie checked const filePath = path.dirname(file.path); console.log(filePath); // const filePath = file.path.substring(0, file.path.lastIndexOf("/")); const outputPath = sentData.settings.defaultOutputPathFromMovie ? filePath : sentData.settings.defaultOutputPath; log.debug(`outputPath: ${filePath}`); saveMoviePrint( sentData.elementId, outputPath, sentData.file, sentData.sheetId, sentData.sheet.name, 1, // scale sentData.settings.defaultOutputFormat, sentData.settings.defaultSaveOptionOverwrite, sentData.settings.defaultSaveOptionIncludeIndividual, visibleThumbs, sentData.dataToEmbed, sentData.settings.defaultMoviePrintBackgroundColor, sentData.settings.defaultMoviePrintName, sentData.settings.defaultAllThumbsName, sentData.settings.defaultOutputJpgQuality, sentData.settings.defaultThumbFormat, sentData.settings.defaultThumbJpgQuality, ); } } render() { const { debugKeepView, sentData, savingMoviePrint, thumbObjectBase64s, visibleThumbs } = this.state; let sheetView; if (savingMoviePrint || debugKeepView) { sheetView = sentData.sheet.sheetView; console.log(sheetView); } return ( <ErrorBoundary> <div> {(savingMoviePrint || debugKeepView) && ( <div ref={r => { this.divOfSortedVisibleThumbGridRef = r; }} className={`${styles.ItemMain}`} style={{ width: `${ sheetView !== SHEET_VIEW.TIMELINEVIEW ? sentData.moviePrintWidth : Math.ceil(sentData.scaleValueObject.newMoviePrintTimelineWidth) + Math.ceil(sentData.scaleValueObject.thumbMarginTimeline) * 2 }px`, }} > <> <Conditional if={sheetView === SHEET_VIEW.GRIDVIEW}> <SortedVisibleThumbGrid isViewForPrinting inputRef={r => { this.sortedVisibleThumbGridRef = r; }} showSettings={false} settings={sentData.settings} file={sentData.file} thumbs={visibleThumbs} objectUrlObjects={thumbObjectBase64s} defaultOutputPath={sentData.settings.defaultOutputPath} defaultOutputPathFromMovie={sentData.settings.defaultOutputPathFromMovie} defaultShowDetailsInHeader={sentData.settings.defaultShowDetailsInHeader} defaultShowHeader={sentData.settings.defaultShowHeader} defaultShowImages={sentData.settings.defaultShowImages} defaultShowPathInHeader={sentData.settings.defaultShowPathInHeader} defaultShowTimelineInHeader={sentData.settings.defaultShowTimelineInHeader} defaultThumbInfo={sentData.settings.defaultThumbInfo} defaultThumbInfoRatio={sentData.settings.defaultThumbInfoRatio} selectedThumbId={undefined} colorArray={getMoviePrintColor(DEFAULT_THUMB_COUNT_MAX)} thumbCount={sentData.file.thumbCount} sheetView={sheetView} view={VIEW.STANDARDVIEW} currentSheetId={sentData.currentSheetId || sentData.settings.currentSheetId} scaleValueObject={sentData.scaleValueObject} moviePrintWidth={sentData.moviePrintWidth} keyObject={{}} useBase64 /> </Conditional> <Conditional if={sheetView === SHEET_VIEW.TIMELINEVIEW}> <SortedVisibleSceneGrid view={VIEW.STANDARDVIEW} sheetView={sheetView} file={sentData.file} frameCount={sentData.file ? sentData.file.frameCount : undefined} inputRef={r => { this.sortedVisibleThumbGridRef = r; }} keyObject={{}} selectedSceneId={undefined} selectedSceneIdArray={undefined} scaleValueObject={sentData.scaleValueObject} scenes={sentData.scenes} settings={sentData.settings} showSettings={false} objectUrlObjects={thumbObjectBase64s} thumbs={visibleThumbs} useBase64 /> </Conditional> </> </div> )} </div> </ErrorBoundary> ); } } export default WorkerApp; <|start_filename|>app/components/ThumbGrid.css<|end_filename|> .gridHeader { background: #3b3b3b; color: #eee; font-family: 'Open sans', sans-serif; padding-left: 4px; overflow: hidden; position: relative; line-height: 0; } .gridHeaderImageAndText { float: left; transform-origin: 'left bottom'; vertical-align: baseline; } .gridHeaderImage { /* display: inline-block; */ position: absolute; } .gridHeaderText { display: inline-block; white-space: normal; color: #FF925E; } .gridHeaderTextName { font-size: 12px; font-weight: bold; color: #FFD3BF; letter-spacing: 0.3px; text-align: right; } .timelineWrapper { position: relative; background: rgba(255, 219, 204, 0.2); clear: both; } .timelineCut { position: absolute; background: #E85D22; height: 100%; } .timelineThumbIndicator { position: absolute; min-width: 1px; background: #FFDBCC; } .gridItem { float: left; /*width: 168px;*/ /*padding: 8px;*/ /*background: #3b3b3b;*/ border: 0; margin: 4px; position: relative; outline:none; -webkit-user-select:none; overflow: hidden; } .gridItemSelected { outline-style: solid; outline-color: #FF5006; background-color: #FF5006; /* box-shadow: 5px 0px 0px 0px #FF5006 */ } /* .gridItemSelected:after { content: ""; background-color: #FF5006; position: absolute; width: 5px; height: 100%; top: 0; right: 0; display: block; transform: translateX(10px); } */ .gridItem:hover { /* background: #eee; */ cursor: pointer; } .image { float: left; /*width: 168px;*/ /*padding: 8px;*/ /*background: #3b3b3b;*/ /*border: 0;*/ /*margin: 4px;*/ /* border-radius:8px; */ /*position: relative;*/ } .grid { display: block; height: 100%; white-space: nowrap; border: 0; overflow: auto; margin: auto; outline:none; position: relative; } .gridForPrinting { margin-left: -50px } .faceRect { position: absolute; background-color: rgba(255, 80, 6, 0.05); } .faceHover { position: absolute; background-color: rgba(255, 80, 6, 0.3); /* z-index: 2000; */ } .faceRectSVG { position: absolute; } .opacity100 { color: rgba(255,255,255,1.0); } .faceRectTag { position: absolute; margin-left: 2px; margin-top: 0px; font-size: 9px; line-height: 11px; color: rgba(255,255,255,0.7); /* visibility: hidden; */ /* mix-blend-mode: difference; */ /* filter: invert(1) grayscale(1) contrast(9); */ /* color: rgba(255,80,6,1); */ } .frameinfo { position: absolute; border-radius:2px; /* font-family: 'Open sans'; */ font-size: 10px; line-height: 10px; padding: 1px; pointer-events: none; } .topLeft { top: 0; left: 0; transform-origin: left top; } .topCenter { top: 0; left: 50%; transform-origin: center top; } .topRight { top: 0; right: 0; transform-origin: right top; } .centerCenter { top: 50%; left: 50%; transform-origin: center center; } .bottomLeft { bottom: 0; left: 0; transform-origin: left bottom; } .bottomCenter { bottom: 0; left: 50%; transform-origin: center bottom; } .bottomRight { bottom: 0; right: 0; transform-origin: right bottom; } .dragHandleButton { position: absolute; /* top: calc(50% - 28px); left: calc(50% - 72px); */ top: 50%; left: 50%; transform: translate(-50%, -50%) scale(0.95); /* width: 144px; */ /* height: 80%; */ opacity: 1; cursor: move; background-color: transparent; border: 0; outline:none; } .dragHandleIcon { position: absolute; /* top: calc(50% - 28px); left: calc(50% - 72px); */ top: 50%; left: 50%; transform: translate(-50%, -50%); width: 144px; opacity: 1; /* cursor: move; */ } .whileDragging { box-shadow: 0px 0px 80px 10px rgba(0,0,0,0.5); z-index: 1000; /* has to be higher than dropzoneshow*/ } .hide { position: absolute; outline:none; top: 0; left: 50%; opacity: 0.5; background-color: transparent; } .inPoint { position: absolute; outline:none; bottom: 0; left: 0; opacity: 0.5; } /* .back { position: absolute; outline:none; bottom: 0; left: calc(50% - 24px - 48px); opacity: 0.5; } */ .save { position: absolute; outline:none; top: 0; right: 0; opacity: 0.5; } .textButton { font-family: 'Franchise'; color: #ffffff; font-size: 30px; opacity: 0.5; } /* .forward { position: absolute; outline:none; bottom: 0; left: calc(50% + 24px); opacity: 0.5; } */ .outPoint { position: absolute; outline:none; bottom: 0; right: 0; opacity: 0.5; } .dim { transition: opacity 0.3s; opacity: 0.2 !important; transition-delay: 0.1s; } .hoverButton { border: 0; cursor: pointer; background-color: transparent; outline:none; -webkit-user-select:none; pointer-events:auto; } .opaque { opacity: 1 !important; } .overlayContainer { position: relative; outline: none; border: 0; pointer-events: none; } .overlay { display: block; position: absolute; } /* .scaleOverlay { transform: scale(0.2); } */ .overlayItem { position: absolute; } .overlayExit { transform-origin: left top; transform: translateY(10%); position: absolute; top: 0; left: 0; margin-left: 8px; } .overlayHide { transform-origin: center top; transform: translate(-50%, 10%); position: absolute; top: 0; left: 50%; } .overlaySave { transform-origin: top right; transform: translateY(10%); position: absolute; top: 0; right: 0; margin-right: 8px; } .overlayIn { transform-origin: left bottom; position: absolute; bottom: 0; left: 0; margin-left: 8px; } .overlayAddBefore { transform-origin: left center; transform: translateY(-50%); position: absolute; top: 50%; left: 0; margin-left: 8px; } .overlayScrub { transform-origin: center bottom; transform: translateX(-50%); position: absolute; bottom: 0; left: 50%; } .overlayAddAfter { transform-origin: right center; transform: translateY(-50%); position: absolute; top: 50%; right: 0; margin-right: 8px; } .overlayOut { transform-origin: right bottom; position: absolute; bottom: 0; right: 0; margin-right: 8px; } .overlayShrink { font-size: 20px; } .sheetTypeSwitchButton { position: fixed; transform-origin: center center; transform: translateY(-50%); top: 80%; left: 0; margin-top: 8px; padding-left: 8px; z-Index: 1; }
fakob/MoviePrint_v004
<|start_filename|>userscript.user.js<|end_filename|> // ==UserScript== // @name ExHentai Archive // @match *://exhentai.org/* // @match *://e-hentai.org/* // @require https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js // ==/UserScript== var baseUrl = '//your.archive.url.com/'; var key = 'changeme'; function createArchiveLink(gid, token) { var link = $('<div><a href="#">Send to archive</a></div>'); link.data('gid', gid); link.data('token', token); link.on('click', function() { $.getJSON(baseUrl + 'api.php', { action: 'addgallery', gid: link.data('gid'), token: link.data('token'), key: key }, function(data, result) { if(data.ret === true && result === 'success') { $(link).css({ color: '#777', pointerEvents: 'none' }); } else { alert('An error occured while adding to archive'); } }); return false; }); return link; } $('div#gd5').each(function() { //archive button on gallery detail var container = $(this); $.getJSON(baseUrl + 'api.php', { action: 'hasgallery', gid: gid, key: key }, function(data, result) { if(data.data.exists) { var p = $('<p class="g2"><img src="//exhentai.org/img/mr.gif"> </p>'); var link = ""; if (data.data.deleted == 0) { link = $('<a href="#" target="_blank">Archived</a>'); } else if (data.data.deleted >= 1) { link = $('<a href="#">Deleted</a>'); } if(data.data.archived && data.data.deleted == 0) { link.prop('href', baseUrl + '?' + $.param({ action: 'gallery', id: data.data.id })); } else if (!data.data.archived) { link.on('click', function() { alert('Not yet downloaded'); return false; }); } link.appendTo(p); $('.g2', container).last().after(p); } else { var p = $('<p class="g2"><img src="//exhentai.org/img/mr.gif"> </p>'); var link = createArchiveLink(gid, token); link.appendTo(p); $('.g2', container).last().after(p); } }); }); $('div.itg').each(function() { //gallery search var container = $(this); var galleries = $('div.gl1t', container); var gids = [ ]; galleries.each(function() { var galleryContainer = $(this); var link = $('a', galleryContainer).prop('href'); var bits = link.split("/"); var gid = bits[4]; var token = bits[5]; gids.push(gid); galleryContainer.data('gid', gid); $.getJSON(baseUrl + 'api.php', { action: 'hasgallery', gid: gid, key: key }, function(data, result) { if (!data.data.exists) { var link = createArchiveLink(gid, token); link.css({ 'text-align': 'center', 'font-size': '12px' }); link.on('click', function() { galleryContainer.css({background: 'green'}); }); link.appendTo(galleryContainer); } else { var res = ''; if (data.data.archived && data.data.deleted == 0) { res = $('<div><p>Archived</p></div>'); galleryContainer.css({background: 'green'}); } if (data.data.deleted >= 1) { res = $('<div><p>Deleted</p></div>'); galleryContainer.css({background: '#AA0000'}); } res.appendTo(galleryContainer); } }); }); }); <|start_filename|>www/js/exhen.js<|end_filename|> function api(action, params, callback) { params = $.extend(params, { action: action }); var ret = $.ajax({ url: 'api.php', dataType: 'json', aysnc: true, data: params, success: function(resp) { if(!resp.ret) { alert('API error: ' + resp.message); } else { if($.isFunction(callback)) { callback(resp.data); } } } }); return ret; } function getConfig() { return $.ajax({ type: 'GET', url: 'config.json', dataType: 'json', success: function(data) { return data.responseJSON; }, data: {}, async: false }).responseJSON; } function getRotationDegrees(obj) { var matrix = obj.css("-webkit-transform") || obj.css("-moz-transform") || obj.css("-ms-transform") || obj.css("-o-transform") || obj.css("transform"); if(matrix !== 'none') { var values = matrix.split('(')[1].split(')')[0].split(','); var a = values[0]; var b = values[1]; var angle = Math.round(Math.atan2(b, a) * (180/Math.PI)); } else { var angle = 0; } return (angle < 0) ? angle + 360 : angle; } $.fn.animateRotate = function(angle, duration, easing, complete) { var args = $.speed(duration, easing, complete); var step = args.step; return this.each(function(i, e) { args.complete = $.proxy(args.complete, e); args.step = function(now) { $.style(e, 'transform', 'rotate(' + now + 'deg)'); if (step) return step.apply(e, arguments); }; var curdeg = getRotationDegrees($(this)); $({deg: curdeg}).animate({deg: angle}, args); }); }; $(document).ready(function() { var storage = false; // mpv: true/1 // spv: false/0 var mode = false; if (typeof(Storage) != "undefined") { storage = true; if (localStorage.getItem("viewType") === null) { localStorage.setItem("viewType", "spv"); } if (localStorage.getItem("viewType") == "spv") { $(".viewtype").prop("checked", false); mode = false; } else if (localStorage.getItem("viewType") == "mpv") { $(".viewtype").prop("checked", true); mode = true; } switchGalleryView(mode); } $(".viewtype").change(function() { if($(this).prop("checked")) { localStorage.setItem("viewType", "mpv"); mode = true; } else { localStorage.setItem("viewType", "spv"); mode = false; } location.reload(); }); function renderTags(container, tagGroups) { $('.tag', container).remove(); for(var ns in tagGroups) { var tags = tagGroups[ns]; for(var x in tags) { var tag = tags[x]; var tagItem = $('<a/>'); var tagSearch = escapeTag(ns + ':' + tag); var url = '?' + $.param({ search: tagSearch }); tagItem.prop('href', url); tagItem.text(tag); tagItem.addClass('tag tag-' + ns); tagItem.data('tag', tag); tagItem.data('ns', ns); tagItem.prop('title', ns + ':' + tag); container.prepend(tagItem); } } } function escapeTag(tag) { if(tag.indexOf(' ') >= 0) { return '"' + tag + '"' } else { return tag; } } function colorNameToRGBA(color) { if (color == "red") { return "rgba(244, 67, 54, 0.7)"; } if (color == "pink") { return "rgba(233, 30, 99, 0.7)"; } if (color == "purple") { return "rgba(156, 39, 176, 0.7)"; } if (color == "blue") { return "rgba(33, 150, 243, 0.7)"; } if (color == "green") { return "rgba(76, 175, 80, 0.7)"; } if (color == "black") { return "rgba(0, 0, 0, 0.7)"; } if (color == "white") { return "rgba(255, 255, 255, 0.7)"; } return "rgba(0, 0, 0, 0.7)"; } function gallerySourceToName(gallerySource) { switch(gallerySource) { case "0": return "ExHentai"; case "1": return "File"; default: return "Error"; } return "Super Error"; } function switchGalleryView(mode) { if (!mode && $(".pages-container").length) { console.log("Switching to Single Page Viewer"); $(".pages-container").remove(); $(".reader-container").append("<img src alt class='image-holder'>"); $(".reader-container").append("<div class='control-hotspot control-hotspot-prev'></div>"); $(".reader-container").append("<div class='control control-prev'></div>"); $(".reader-container").append("<div class='control-hotspot control-hotspot-next'></div>"); $(".reader-container").append("<div class='control control-next'></div>"); } else if (mode && $(".image-holder").length) { console.log("Switching to Multi Page Viewer"); $(".image-holder").remove(); $(".control-hotspot").remove(); $(".control").remove(); $(".reader-container").append("<div class='pages-container'><div class='inner'></div</div>"); } } $('.gallery-list').each(function() { var galleryList = $(this); var page = 0; var topPage = 0; var loading = false; var search = null; var xhr = null; var loadersBottom = $('.loaders-bottom'); var loadersTop = $('.loaders-top'); var searchCount = $('.search-count'); var searchForm = $('.search-form'); var order = 'posted'; var init = false; var end = false; var randomSeed = 0; var unarchived = false; var color = false; var read = false; var preloadedPages = { }; function loadPage(fwd) { loading = true; end = false; if(xhr) { xhr.abort(); } if(fwd) { loadersBottom.addClass('active'); $('.load-next').removeClass('active'); } else { loadersTop.addClass('active'); $('.load-previous').removeClass('active'); } var loadPage = page; if(!fwd) { topPage--; if(topPage < 0) { topPage = 0; } loadPage = topPage; } var params = { search: search, page: loadPage, order: order }; if(order === 'random') { params.seed = randomSeed; } if(unarchived) { params.unarchived = unarchived; } if(color) { params.color = color; } if(read !== false) { params.read = read; } function renderResult(result) { var collection = [ ]; var galleries = result.galleries; var topWeight = null; $.each(galleries, function(i, gallery) { var item = $('.template .gallery-item').clone(); item.data('gallery', gallery); item.attr("id", "gallery-" + gallery.id); if (gallery.archived == 1) { var url = '?' + $.param({ action: 'gallery', id: gallery.id, index: 0 }); } else { var url = 'https://exhentai.org/g/' + gallery.exhenid + '/' + gallery.hash; } if (!!+gallery.read) { $("#read-container", item).addClass("fi-book-bookmark"); } else { $("#read-container", item).addClass("fi-book"); } $("#read", item).prop("checked", !!+gallery.read); $("#read-container", item).click(function(e) { e.stopPropagation(); $("#read", item).trigger("click"); }); $("#read", item).change(function() { var result = $(this).prop("checked") ? 1 : 0; api("update", {id: gallery.id, readStatus: result}, function(data) { if (data.ret == false) { alert("Error updating read status of gallery."); } else { if (result) { $("#read-container", item).removeClass("fi-book"); $("#read-container", item).addClass("fi-book-bookmark"); } else { $("#read-container", item).removeClass("fi-book-bookmark"); $("#read-container", item).addClass("fi-book"); } } }); }); $(".color-select", item).val(gallery.color); $(".color-select", item).click(function(e) { e.stopPropagation(); }); $(".color-select", item).change(function() { var newColor = $(this).val(); console.log(newColor); api("updateColor", {id: gallery.id, color: newColor }, function(data) { if (data.ret == false) { alert("There was an error changing the color of this gallery."); } else { $(".top", item).css("background", colorNameToRGBA(newColor)); } }); }); $(item).click(function(e) { window.location.url = url; }); $(".top", item).css("background", colorNameToRGBA(gallery.color)); if (i == 0) { item.addClass('page-break'); item.data('page', loadPage); } if(gallery.archived == 0) { item.addClass('unarchived'); } var source = gallerySourceToName(gallery.source); $('.title', item).text("[" + source + "] " + gallery.name); $('.date', item).text(gallery.posted_formatted); if(gallery.ranked_weight) { if(topWeight === null) { topWeight = gallery.ranked_weight; } var pc = Math.round((gallery.ranked_weight / topWeight) * 100); $('.weight', item).show().text(pc + '%'); } else { $('.weight', item).hide(); } if(gallery.thumb) { if(gallery.thumb.landscape) { item.addClass('landscape'); } item.css({ backgroundImage: 'url(' + gallery.thumb.url + ')' }) } else { if(gallery.archived == 1) { var url = 'api.php?' + $.param({ action: 'gallerythumb', id: gallery.id, index: 0, type: 1 }); } else { var url = 'api.php?' + $.param({ action: 'exgallerythumb', id: gallery.id }); } item.css({ backgroundImage: 'url(' + url + ')' }); } var tagList = $('.tags', item); renderTags(tagList, gallery.tags); collection.push(item); }); if(fwd) { galleryList.append(collection); } else { galleryList.prepend(collection); } if(galleries.length > 0) { if(!history.state || history.state.action == 'galleries') { var state = buildHistoryState(); state.data.page = loadPage; setHistoryState(true, state); } if(fwd) { page++; } } if(!result.end) { $('.load-next').addClass('active'); } else { end = true; } var displayCount = $('.gallery-item', galleryList).length; var totalCount = result.meta.total; if(window['Intl'] && window['Intl']['NumberFormat']) { displayCount = Intl.NumberFormat().format(displayCount); totalCount = Intl.NumberFormat().format(totalCount); } searchCount.show().text('Displaying ' + displayCount + ' of ' + totalCount + ' results'); if(topPage != 0) { $('.load-previous').addClass('active'); } else { $('.load-previous').removeClass('active'); } loadersTop.removeClass('active'); loadersBottom.removeClass('active'); loading = false; if(fwd && !end) { delete preloadedPages[params.page]; params.page++; xhr = api('galleries', params, function(result) { preloadedPages[params.page] = result; }); } } if(preloadedPages[params.page]) { renderResult(preloadedPages[params.page]); } else { xhr = api('galleries', params, function(result) { renderResult(result); }); } } galleryList.on('click', '.gallery-item', function() { var galleryItem = $(this); var gallery = galleryItem.data('gallery'); if(gallery.archived == 0) { var url = 'https://exhentai.org/g/' + gallery.exhenid + '/' + gallery.hash; window.open(url); } else { reader.trigger('loadgallery', [ gallery ]); } return false; }); function setHistoryState(replace, state) { var urlParams = { }; if(state.data.search) urlParams.search = state.data.search; if(state.data.page && state.data.page > 0) urlParams.page = state.data.page; if(state.data.order != 'posted') urlParams.order = state.data.order; if(state.data.unarchived) urlParams.unarchived = state.data.unarchived; if(state.data.read) urlParams.read = state.data.read; if(state.data.color) urlParams.color = state.data.color; var url = Object.keys(urlParams).length > 0 ? '?' + $.param(urlParams) : '/'; if(replace) { history.replaceState(state, document.title, url); } else { history.pushState(state, document.title, url); } } function setHistory(replace) { var state = buildHistoryState(); setHistoryState(replace, state); } function buildHistoryState() { var state = { action: 'galleries', data: { search: search, page: page - 1, order: order, unarchived: unarchived, read: read, color: color } }; if(order === 'random') { state.data.seed = randomSeed; } return state; } galleryList.on('sethistory', function(e, replace) { setHistory(replace); }); searchForm.submit(function() { search = $('.search', searchForm).val(); searchCount.hide(); galleryList.empty(); page = 0; topPage = 0; preloadedPages = { }; randomiseSeed(); loadPage(true); setHistory(false); return false; }); function randomiseSeed() { randomSeed = Math.floor(Math.random() * 0x7ffffff).toString(36); } $('.unarchived').change(function() { unarchived = $(this).prop('checked'); searchForm.submit(); }); $('.read-switch').change(function() { if ($(this).val() != "false") { read = $(this).val(); } else { read = false; } searchForm.submit(); }); $('.color-switch').change(function() { if($(this).val() != "false") { color = $(this).val(); } else { color = false; } searchForm.submit(); }); $('.input-clear').on('click', function() { if(order === 'weight') { order = 'posted'; setOrderLabel(); } $('.search', searchForm).val(''); searchForm.submit(); }); $('.search-order ul li', searchForm).on('click', function() { var trigger = $(this); order = trigger.data('order'); var menu = $('.search-order', searchForm); $('.label', menu).text(trigger.text()); var menuOuter = $('.menu-outer', menu); menuOuter.hide(); setTimeout(function() { menuOuter.removeAttr('style'); }, 1); searchForm.submit(); return false; }); $('.toggle-button').on('click', function() { if ($('.search-under-options').is(':hidden')) { $('.search-under-options').stop(true, true).fadeIn({ duration: 400, queue: false }).css('display', 'none').slideDown(400); $('.toggle-button').stop(true, true).animateRotate(-180); } else { $('.toggle-button').stop(true, true).animateRotate(0); $('.search-under-options').stop(true, true).fadeOut({ duration: 400, queue: false }).slideUp(400); } return false; }); galleryList.on('click', '.tag', function() { var tag = $(this); var searchTag = tag.data('ns') + ':' + tag.data('tag'); searchTag = escapeTag(searchTag); $('.search').val(searchTag); $('.search-form').submit(); return false; }); function setOrderLabel() { var label = $('.search-order .label', searchForm); if(order != 'posted' || label.text() != 'Order') { var orderOpt = $('.search-order li[data-order="' + order + '"]'); label.text(orderOpt.text()); } } galleryList.on('loadstate', function(e, data) { init = true; data = $.extend({ search: '', page: 0, order: order }, data); search = data.search; page = data.page; topPage = page; order = data.order; randomSeed = data.seed; unarchived = data.unarchived; read = data.read; color = data.color; if(!randomSeed && order === 'random') { randomiseSeed(); } setOrderLabel(); $('.unarchived').prop('checked', unarchived); if (read) { $('.read-switch').val(read); } else { $('.read-switch').val("false"); } if (color) { $('.color-switch').val(color); } else { $('.color-switch').val("false"); } $('.search').val(search); searchCount.hide(); galleryList.empty(); loadPage(true); if(!history.state || history.state.action != 'galleries') { setHistory(false); } }); galleryList.on('init', function() { if(!init) { init = true; galleryList.trigger('loadstate', [ { page: 0, search: '' } ]); } if(!history.state || history.state.action != 'galleries') { setHistory(false); } }); $('.load-previous .inner').click(function() { loadPage(false); }); $('.load-next .inner').click(function() { loadPage(true); }); var win = $(window); var doc = $(document); win.scroll(function() { if(!end) { var winHeight = win.height(); if(win.scrollTop() + (winHeight * 1.2) >= doc.height()) { if(!loading) { loadPage(true); } } } }); var pageUpdateProc = null; win.scroll(function() { clearTimeout(pageUpdateProc); if(!history.state || history.state.action == 'galleries') { pageUpdateProc = setTimeout(function() { if(!history.state || history.state.action == 'galleries') { var scroll = win.scrollTop() + win.height(); var pageBreaks = $('.page-break', galleryList); var lastBreak = null; for(var i = 0; i < pageBreaks.length; i++) { var pageBreak = pageBreaks.eq(i); if(pageBreak.position().top > scroll) { break; } lastBreak = i; } if(lastBreak !== null) { var newPage = pageBreaks.eq(lastBreak).data('page'); var state = history.state; state.data.page = newPage; setHistoryState(true, state); } } }, 100); } }); }); $('.search').each(function() { var input = $(this); var keywordXhr = null; var list = $('.suggestions'); var term = null; var selectionStart = null; this.form.autocomplete = 'off'; function getTerm() { return input.val().slice(0, selectionStart).trim(); } input.keydown(function(e) { if(e.keyCode === 38) { //arrow up var selected = $('li.active', list); if(selected.length > 0) { if(selected.is(':not(:first-child)')) { selected.removeClass('active').prev().addClass('active'); } } else { $('li', list).first().addClass('active'); } return false; } else if(e.keyCode === 40) { //arrow down var selected = $('li.active', list); if(selected.length > 0) { if(selected.is(':not(:last-child)')) { selected.removeClass('active').next().addClass('active'); } } else { $('li', list).first().addClass('active'); } return false; } else if(e.keyCode === 13) { //enter var selected = $('li.active', list); if(selected.length > 0) { selected.click(); return false; } list.empty(); list.removeClass('active'); } else if(e.keyCode === 27) { //esc list.empty(); list.removeClass('active'); } }); input.keyup(function(e) { selectionStart = this.selectionStart; var newTerm = getTerm(); if(keywordXhr) { keywordXhr.abort(); } if(e.keyCode === 13 || e.keyCode === 27) { //enter, esc } else if(newTerm && newTerm.length > 1 && newTerm != term) { term = newTerm; keywordXhr = api('suggested', { term: term }, function(keywords) { list.empty(); list.removeClass('active'); if(keywords.length > 0) { var termBits = term.split(' '); for(var i in keywords) { var keyword = keywords[i]; var itemHtml = keyword; var ignoreWord = false; for(var x in termBits) { var tempTerm = termBits.slice(x).join(' '); if(keyword.indexOf(tempTerm) >= 0) { if(keyword !== tempTerm) { var regex = new RegExp(tempTerm); itemHtml = itemHtml.split(regex).join('<span class="highlight">' + tempTerm + '</span>'); } else { ignoreWord = true; } break; } } if(!ignoreWord) { var li = $('<li/>'); li.data('keyword', keyword); li.html(itemHtml); li.appendTo(list); } } if($('> *', list).length > 0) { list.addClass('active'); } } }); } else if(getTerm() != term) { list.empty(); list.removeClass('active'); } }); list.on('click', 'li', function() { var item = $(this); var keyword = item.data('keyword'); var value = input.val(); var pre = value.slice(0, selectionStart); var keywordBits = keyword.split(' '); var preBits = pre.split(' ').reverse(); var newPre = ''; for(var i in preBits) { if(i === 0) { continue; } var found = false; for(var x in keywordBits) { if(keywordBits[x].indexOf(preBits[i]) === 0) { found = true; delete keywordBits[x]; } } if(!found) { newPre = preBits.slice(i).reverse().join(' '); newPre += ' '; break; } } newPre += escapeTag(keyword); if(newPre) { var newValue = newPre + value.slice(selectionStart); input.val(newValue); list.removeClass('active'); input.focus(); $('.search-form').submit(); } return false; }); function closeList() { if(keywordXhr) { keywordXhr.abort(); } list.removeClass('active'); } input.parent('form').submit(closeList); }); var reader = $('.reader-container'); reader.each(function() { var container = $(this); var imageHolder = $('.image-holder', container); var thumbsList = $('.gallery-thumbs-outer .thumbs', container); var infoContainer = $('.gallery-info', container); var preload = $('<img/>'); var gallery = null; var currentIndex = 0; var firstImage = false; var endFlash = $('.end-flash'); var pagesContainer = $('.pages-container', container); var pages = null; var scrollProc = null; var scrolling = false; var configData = getConfig(); imageHolder.on('load', function() { if (this.width > 0 && this.height > 0) { var win = $(window); var pos = imageHolder.position(); if (firstImage) { if (this.width > win.width()) { imageHolder.width(win.width()); } if (this.height > win.height()) { imageHolder.width((this.width / this.height) * win.height()); } imageHolder.css({ left : (win.width() - this.width) / 2, top: (win.height() - this.height) / 2 }); imageHolder.removeClass('init'); firstImage = false; } else if (this.height > win.height() || pos.top < 0) { imageHolder.stop().animate({ top: 0 }, Math.abs(pos.top) * 0.7); } } preloadImage(currentIndex + 1); }); function onImageLoad() { if(this.width > 0 && this.height > 0) { var img = $(this); var page = img.parent('.page'); page.addClass('loaded'); page.removeClass('loading'); page.next('.spinner').remove(); } preloadImage(currentIndex + 1); } function preloadImage(index) { if(index < gallery.numfiles) { preload.data('index', index); preload.prop('src', getImageUrl(index)); } } preload.on('load', function() { var index = preload.data('index'); if(!index) { index = 0; } if (mode) { // Loads the first three images in MPV instead of preloading them. if((index - currentIndex) <= 3) { loadImage(index, false, false, false, false); } } preloadImage(index + 1); }); function createSpinner(index) { var spinner = $('.template .spinner').clone(); pages.eq(index).after(spinner); } function onScroll() { var scrollTop = pagesContainer.scrollTop(); var winHeight = $(window).innerHeight(); var inView = false; pages.each(function(i) { var page = pages.eq(i); var pageHeight = page.height(); if(page.hasClass('loaded')) { var pos = page.position(); if(scrollTop < (pos.top + pageHeight)) { if(scrollTop >= pos.top) { inView = i; } if((scrollTop + winHeight) >= (pos.top + pageHeight)) { var nextPage = page.next('.page'); if(nextPage.length > 0 && !nextPage.hasClass('loaded') && !nextPage.hasClass('loading')) { loadImage(i + 1, false, true, false, true); $('.page-count').text((parseInt(i) + 1) + "/" + gallery.numfiles); return false; } } } } }); if(inView) { currentIndex = inView; setHistoryState(inView, true); } } pagesContainer.scroll(function() { clearTimeout(scrollProc); if(!scrolling) { scrollProc = setTimeout(onScroll, 100); } }); function getImageUrl(index) { var params = { action: 'archiveimage', id: gallery.id, index: index }; if (!mode) { var trueWidth = Math.round(window.devicePixelRatio * window.screen.availWidth); if (trueWidth <= 1000) { params.resize = trueWidth; } } if (mode) { params.resize = Math.ceil(window.screen.availWidth / 128) * 128; } return 'api.php?' + $.param(params); } function scrollToPage(index) { scrolling = true; var page = pages.eq(index); pagesContainer.animate({ scrollTop: page.position().top }, 500, function() { scrolling = false; }); } function setHistoryState(index, replaceHistory) { if(replaceHistory) { history.replaceState({ action: 'gallery', data: { gallery: gallery, index: index } }, document.title, '?' + $.param({ action: 'gallery', id: gallery.id, index: index })); } else { history.pushState({ action: 'gallery', data: { gallery: gallery, index: index } }, document.title, '?' + $.param({ action: 'gallery', id: gallery.id, index: index })); } } function loadImage(index, setHistory, replaceHistory, scroll, updateCurIndex) { if(gallery && index < gallery.numfiles && index >= 0) { if (!mode) { var url = getImageUrl(index); imageHolder.prop('src', url); } if (mode) { var page = pages.eq(index); var img = page.find('img'); if(!page.hasClass('loading') && !page.hasClass('loaded')) { var preloadIndex = preload.data('index'); if (preloadIndex != index) { preload.prop('src', ''); } page.addClass('loading'); img.prop('src', img.data('src')); if (scroll) { scrollToPage(index); } createSpinner(index); } else { if (scroll) { scrollToPage(index); } } } if(setHistory) { setHistoryState(index, replaceHistory); } if(updateCurIndex) { currentIndex = index; } } else if(index >= gallery.numfiles) { endFlash.removeClass('transition').addClass('active'); setTimeout(function() { endFlash.addClass('transition').removeClass('active'); }, 0); } } endFlash.on('transitionend', function() { endFlash.removeClass('transition'); }); function close() { var id = gallery.id; var percentRead = ((currentIndex + 1) / gallery.numfiles) * 100; if (percentRead >= configData["base"]["autoReadPercentage"]) { api("update", {id: gallery.id, readStatus: 1}, function(data) { if (data.ret == false) { alert("Error updating read status of gallery."); } else { $("#gallery-" + id + " #read-container").removeClass("fi-book"); $("#gallery-" + id + " #read-container").addClass("fi-book-bookmark"); } }); } $('html').removeClass('reader-active'); imageHolder.prop('src', ''); gallery = null; $(window).off('.resize'); preload.data('index', 0).prop('src', ''); $('.gallery-list').trigger('init'); $(document).off('mousewheel.reader'); } $('.close', container).click(close); reader.on('close', close); $('.gallery-info .tags', container).on('click', '.tag', function() { var tag = $(this); var searchTag = tag.data('ns') + ':' + tag.data('tag'); searchTag = escapeTag(searchTag); close(); $('.gallery-list').trigger('loadstate', [ { search: searchTag } ]); }); reader.on('loadstate', function(e, data) { if(!gallery || data.gallery.id != gallery.id) { loadGallery(data.gallery, data.index); } else { loadImage(data.index, false, false, false, true); } }); function loadGallery(newGallery, index) { gallery = newGallery; imageHolder.width('auto').height('auto'); imageHolder.addClass('init'); $('html').addClass('reader-active'); if (mode) { thumbsList.empty(); for(var i = 0; i < gallery.numfiles; i++) { var url = 'api.php?' + $.param({ action: 'gallerythumb', id: gallery.id, index: i, type: 2 }); var thumb = $('<div class="gallery-thumb"/>'); thumb.data('index', i); thumb.css({ backgroundImage: 'url(' + url + ')' }); thumb.appendTo(thumbsList); } } var source = gallerySourceToName(gallery.source); $('.title', infoContainer).text("[" + source + "] "+ gallery.name); $('.page-count').text((parseInt(index) + 1) + "/" + gallery.numfiles); if(gallery.origtitle != gallery.name) { $('.origtitle', infoContainer).show().text(gallery.origtitle); } else { $('.origtitle', infoContainer).hide(); } renderTags($('.tags', infoContainer), gallery.tags); index = parseInt(index); if(!index || index >= gallery.numfiles) { index = 0; } $('.page-count').text((parseInt(index) + 1) + "/" + gallery.numfiles); if (mode) { var pagesTarget = $('.inner', pagesContainer); pagesTarget.empty(); for(var i = 0; i < gallery.numfiles; i++) { var page = $('.template .page').clone(); var pageImg = $('img', page); var url = getImageUrl(i); pageImg.data('src', url); pageImg.on('load', onImageLoad); $('.index', page).text(i + 1); pagesTarget.append(page); } pages = $('.page', pagesContainer); } $('.actions-menu ul li[data-action=\'source\']').text(gallerySourceToName(gallery.source)); firstImage = true; if(history.state && history.state.action != 'gallery') { loadImage(index, true, false, false, true); } else { loadImage(index, true, true, false, true); } } if (!mode) { var win = $(window); win.on('resize.reader', function() { var width = win.width(); var height = win.height(); var oldWidth = win.data('oldWidth'); var oldHeight = win.data('oldHeight'); if (oldWidth && oldHeight) { imageHolder.css({ top: '+=' + ((height - oldHeight) / 2), left: '+=' + ((width - oldWidth) / 2) }); } win.data('oldWidth', width) win.data('oldHeight', height); }); } container.on('loadgallery', function(e, newGallery, index) { loadGallery(newGallery, index); }); $('.control-next').click(function() { loadImage(currentIndex + 1, true, false, false, true); $('.page-count').text((currentIndex + 1) + "/" + gallery.numfiles); }); $('.control-prev').click(function() { loadImage(currentIndex - 1, true, false, false, true); $('.page-count').text((currentIndex + 1) + "/" + gallery.numfiles); }); thumbsList.on('click', '.gallery-thumb', function() { var index = $(this).data('index'); if (!mode) { loadImage(index, true, false, true, true); $('.page-count').text((index + 1) + "/" + gallery.numfiles); } else if (mode) { loadImage(index, true, false, false, true); $('.page-count').text((index + 1) + "/" + gallery.numfiles); } }); $(document).on('keyup.reader', 'html.reader-active', function(e) { if(e.keyCode === 39) { // right arrow or WAS(D) if (!mode) { loadImage(currentIndex + 1, true, true, true, true); $('.page-count').text((currentIndex + 1) + "/" + gallery.numfiles); } else if (mode) { loadImage(currentIndex + 1, true, true, false, true); $('.page-count').text((currentIndex + 1) + "/" + gallery.numfiles); } } }); $(document).on('keyup.reader', 'html.reader-active', function(e) { if(e.keyCode === 37) { // left arrow or W(A)SD if (!mode) { loadImage(currentIndex - 1, true, true, true, true); $('.page-count').text((currentIndex + 1) + "/" + gallery.numfiles); } else if (mode) { loadImage(currentIndex - 1, true, true, false, true); $('.page-count').text((currentIndex + 1) + "/" + gallery.numfiles); } } }); $(document).on('keydown.reader keyup.reader', 'html.reader-active', function(e) { if(e.keyCode === 27) { // ESC close(); } }); $('.actions-menu ul li', container).click(function() { var trigger = $(this); var action = trigger.data('action'); if(action == 'delete') { var key = prompt('Enter access key'); if(key) { api('deletegallery', { id: gallery.id, key: key }, function(data) { close(); }); } } else if(action == 'resize') { firstImage = true; imageHolder.width('auto').height('auto'); imageHolder.trigger('load'); } else if(action == 'download') { var url = '/api.php?' + $.param({ action: 'download', id: gallery.id }); window.open(url); } else if(action == 'similar') { var tagList = [ ]; for(var ns in gallery.tags) { for(var i in gallery.tags[ns]) { var tag = ns + ':' + gallery.tags[ns][i]; tag = tag.replace('"', '\\\\"'); tag = '"' + tag + '"'; tagList.push(tag); } } close(); var search = tagList.join(' | '); $('.gallery-list').trigger('loadstate', [ { search: search, order: 'weight' } ]); } else if(action == 'original') { if ($('.actions-menu ul li[data-action=\'source\']').text() == 'File') { alert('1-' + gallery.id + '.zip'); } else { var url = 'https://exhentai.org/g/' + gallery.exhenid + '/' + gallery.hash; window.open(url); } } return false; }); }); function setupDropdowns() { var dropdowns = $('.dropdown-button'); dropdowns.click(function() { $(this).toggleClass('active'); }); $(document).click(function(e) { if(dropdowns.hasClass('active') && dropdowns.has(e.target).length === 0) { dropdowns.removeClass('active'); } }); $('ul li', dropdowns).click(function() { $(this).parents('.dropdown-button').removeClass('active'); }); } setupDropdowns(); $(window).on('popstate', function(e) { if(e.originalEvent.state) { switch(e.originalEvent.state.action) { case 'galleries': { reader.trigger('close'); $('.gallery-list').trigger('loadstate', [ e.originalEvent.state.data ]); break; } case 'gallery': { reader.trigger('loadstate', [ e.originalEvent.state.data ]); break; } } } }); if(window.location.search == '') { $('.gallery-list').trigger('init'); } else { var query = decodeQuery(); if(!query.action || query.action == 'galleries') { $('.gallery-list').trigger('loadstate', [ { page: query.page, search: query.search, order: query.order, seed: query.seed, unarchived: query.unarchived, read: query.read, color: query.color } ]); } else if(query.action == 'gallery') { api('gallery', { id: query.id }, function(gallery) { reader.trigger('loadgallery', [ gallery, query.index ]) }); } } function decodeQuery() { var ret = {}; var bits = window.location.search.slice(1).replace(/\+/g, '%20').split('&'); for(var i in bits) { var keyvalue = bits[i].split('='); ret[decodeURIComponent(keyvalue[0])] = keyvalue.length == 1 ? false : decodeURIComponent(keyvalue[1]); } return ret; } }); <|start_filename|>www/css/exhen.css<|end_filename|> @font-face { font-family: 'Open Sans'; src: url('../font/OpenSans.eot'); src: url('../font/OpenSans.eot?#iefix') format('embedded-opentype'), url('../font/OpenSans.woff2') format('woff2'), url('../font/OpenSans.woff') format('woff'), url('../font/OpenSans.ttf') format('truetype'), url('../font/OpenSans.svg#OpenSansRegular') format('svg'); } body { margin: 0; font-family: 'Open Sans', sans-serif; background: #222; font-weight: 300; color: #ddd; } .cf:before, .cf:after { content: " "; display: table; } .cf:after { clear: both; } .gallery-item { padding-top: 24.20%; display: inline-block; position: relative; background: no-repeat center; background-size: cover; width: 16.666%; margin-bottom: -5px; overflow: hidden; cursor: pointer; color: inherit; } .gallery-item.landscape { background-size: 100% auto; } .gallery-item .top, .gallery-item .bottom { position: absolute; background: rgba(0, 0, 0, 0.7); padding: 10px; left: 0; opacity: 0; transition: opacity 50ms; width: 100%; } .gallery-item .top { top: 0; color: white; text-shadow: -1px -1px 0 #000, 1px -1px 0 #000, -1px 1px 0 #000, 1px 1px 0 #000; } .gallery-item .bottom { bottom: 0; max-height: 70%; overflow-y: auto; } .tags { font-size: 11px; } .tags .tag { display: inline-block; margin: 0 4px 4px 0; padding: 2px 4px; border-radius: 3px; transition: all 100ms; cursor: pointer; color: inherit; text-decoration: none; } .tags .tag:hover { box-shadow: 0px 0px 5px rgba(255, 255, 255, 0.51); } .tags .tag-character { background: rgba(134, 18, 18, 0.75); } .tags .tag-parody { background: rgba(90, 0, 133, 0.75); } .tags .tag-language { background: rgba(48, 48, 165, 0.75); } .tags .tag-group { background: rgba(48, 165, 53, 0.75); } .tags .tag-artist { background: rgba(48, 165, 156, 0.75); } .tags .tag-female { background: rgba(165, 48, 151, 0.75); } .tags .tag-male { background: rgba(134, 134, 134, 0.75); } .tags .tag-misc { background: rgba(165, 160, 54, 0.75); } .tags .tag-reclass { background: rgba(139, 110, 201, 0.75); } .tags .fi-book, .tags .fi-book-bookmark { font-size: 20px; color: white; text-shadow: -1px -1px 0 #000, 1px -1px 0 #000, -1px 1px 0 #000, 1px 1px 0 #000; cursor: pointer; } .tags #read { display: none; } .gallery-item .date, .gallery-item .weight { float: right; margin-top: 4px; } .gallery-item:hover .top, .gallery-item:hover .bottom { opacity: 1; } .template { display: none; } .reader-container { display: none; position: fixed; width: 100%; height: 100%; background: inherit; top: 0; left: 0; } html.reader-active .reader-container { display: block; } html.reader-active, html.reader-active body { overflow: hidden; } .reader-container .close.button { width: 40px; } .reader-container .image-holder { position: relative; top: 0; left: 0; -webkit-user-drag: none; -moz-user-drag: none; user-drag: none; -webkit-user-select: none; -moz-user-select: none; user-select: none; } .reader-container .image-holder.init { opacity: 0; } .reader-container .image-holder.ui-draggable-dragging { cursor: move; } header { text-align: center; padding: 20px 20px 50px 20px; } .search { padding: 8px 10px; padding-right: 40px; width: 100%; background: none; border: 1px solid #999; border-radius: 2px; font: inherit; font-size: 22px; margin: 0; height: 48px; color: inherit; } .button { font: inherit; font-size: 22px; background: none; border: 1px solid #999; border-radius: 2px; width: 126px; text-align: center; line-height: 46px; padding: 0; margin: 0; display: inline-block; color: inherit; cursor: pointer; -webkit-user-select: none; -moz-user-select: none; user-select: none; } .toggle-button { display: inline-block; width: 55px; vertical-align: top; position: absolute; left: 0; top: 0; } .search-under-options { display: none; padding-top: 50px; height: 200px; } .search-under-options > .switches-outer { right: auto !important; left: 0 !important; top: auto !important; position: absolute; } .search-form { display: flex; flex-direction: row; } * { box-sizing: border-box; -moz-box-sizing: border-box; } .search:focus, .search:active, .button:focus, .button:active { outline: none; border: 1px solid rgb(209, 135, 0); } .reader-container .control { position: absolute; top: 0; height: 100%; width: 100px; background: rgba(0, 0, 0, 0.74) url(/img/arrow-prev.png) no-repeat center; display: none; opacity: 0; -webkit-user-select: none; -moz-user-select: none; user-select: none; cursor: pointer; transition: opacity 200ms; } .reader-container .control-next { right: 0; background-image: url(/img/arrow-next.png); } .reader-container .control-hotspot { position: absolute; top: 0; width: 10px; height: 100%; } .reader-container .control-hotspot-next { right: 0; } .reader-container .control:hover, .reader-container .control-hotspot:hover + .control { display: block; opacity: 1; } .spinner { width: 50px; height: 30px; text-align: center; font-size: 10px; margin: 0 auto; } .spinner > div { background-color: #ddd; height: 100%; width: 6px; display: inline-block; -webkit-animation: stretchdelay 1.2s infinite ease-in-out; animation: stretchdelay 1.2s infinite ease-in-out; } .spinner .rect2 { -webkit-animation-delay: -1.1s; animation-delay: -1.1s; } .spinner .rect3 { -webkit-animation-delay: -1.0s; animation-delay: -1.0s; } .spinner .rect4 { -webkit-animation-delay: -0.9s; animation-delay: -0.9s; } .spinner .rect5 { -webkit-animation-delay: -0.8s; animation-delay: -0.8s; } @-webkit-keyframes stretchdelay { 0%, 40%, 100% { -webkit-transform: scaleY(0.4) } 20% { -webkit-transform: scaleY(1.0) } } @keyframes stretchdelay { 0%, 40%, 100% { transform: scaleY(0.4); -webkit-transform: scaleY(0.4); } 20% { transform: scaleY(1.0); -webkit-transform: scaleY(1.0); } } .spinner.spinner-top { display: none; } .load-previous, .load-next { display: none; text-align: center; font-size: 22px; padding: 15px 0 20px; } .load-previous.active, .load-next.active { display: block; } .load-next { padding-top: 20px; } .load-previous .inner:hover, .load-next .inner:hover { color: rgb(255, 169, 169); cursor: pointer; } .suggestions { position: absolute; list-style: none; background: #222; border: 1px solid #999; border-top: none; z-index: 1; margin: 0; text-align: left; padding: 0; font-size: 18px; display: none; } .suggestions li { padding: 10px 20px; } .suggestions.active { display: block; } .suggestions li:hover, .suggestions li.active { background: rgb(209, 135, 0); cursor: pointer; color: #222; } .suggestions li:hover .highlight, .suggestions li.active .highlight { color: rgb(255, 255, 255); } .reader-container .thumbs-hotspot { position: absolute; top: 0; width: 10px; height: 100%; } .gallery-thumbs-outer { position: absolute; top: 0; left: 0; height: 100%; background: rgba(0, 0, 0, 0.33); padding: 10px; transition: margin 200ms; transition-timing-function: ease-out; overflow: hidden; width: 180px; margin-left: -180px; } .gallery-thumbs-outer .gallery-thumb { width: 140px; height: 200px; display: block; background-size: 100% auto; background-repeat: no-repeat; background-position: center; cursor: pointer; } .gallery-thumbs-outer .gallery-thumb ~ .gallery-thumb { margin-top: 6px } .gallery-thumbs-outer .thumbs { overflow: auto; white-space: nowrap; max-height: 100%; padding-right: 20px; } .gallery-thumbs-outer:hover, .thumbs-hotspot:hover + .gallery-thumbs-outer { margin: 0; } .gallery-thumbs-outer:hover + .gallery-info, .thumbs-hotspot:hover + .gallery-thumbs-outer + .gallery-info { left: 180px; } .gallery-info { position: absolute; top: 0; left: 0; padding: 5px; z-index: 10; max-width: 540px; transition: left 200ms; transition-timing-function: ease-out; } .gallery-info:hover { z-index: 50 } .gallery-info .title { font-size: 12px; text-shadow: 1px 1px 1px #000; } .gallery-info .tags { padding: 5px 0; max-width: 60%; } .gallery-info .expand { display: none; } .gallery-info:hover .expand { display: block; } .gallery-info .origtitle { color: #aaa; font-size: 12px; } .pages-container { height: 100%; overflow: auto; padding: 0 20px; } .pages-container > .inner { margin: 0 auto; position: relative; z-index: 30; max-width: 1200px; text-align: center; font-size: 0; } .pages-container .page.loaded ~ .page.loaded { margin-top: 20px; } .pages-container .page > img { max-width: 100%; } .pages-container .spinner { margin: 100px auto 80px; } .pages-container .page.loaded .index { position: absolute; bottom: 0; right: -30px; display: block; font-size: 16px; width: 30px; text-align: center; } .pages-container .page { position: relative; } .suggestions .highlight { color: rgb(255, 169, 169); } .reader-container .gallery-actions { position: absolute; top: 10px; right: 120px; z-index: 99999; } .gallery-actions .page-count { font-size: 20px; margin-right: 10px; text-shadow: 1px 1px 2px #000; } .dropdown-button .menu-outer { display: none; position: absolute; } .dropdown-button .menu-outer ul { list-style: none; margin: 10px 0 0; padding: 0; border: 1px solid #999; border-radius: 2px; z-index: 111; position: relative; background: #222; } .dropdown-button .menu-outer ul li { font-size: 22px; padding: 4px 16px; } .dropdown-button .menu-outer ul li:hover { cursor: pointer; color: rgb(255, 169, 169); } .input-clear { display: none; width: 18px; height: 18px; background: url(/img/input-clear.png) no-repeat center; position: absolute; top: 50%; margin-top: -9px; right: 30px; cursor: pointer; } .search:hover + * + .input-clear, .search:focus ~ .input-clear, .input-clear:hover { display: inline-block; } *::-webkit-input-placeholder { color: #aaa; } *::-moz-placeholder { color: #aaa; } .end-flash { position: fixed; top: 50%; left: 50%; margin-left: -50px; font-size: 40px; background: rgba(0, 0, 0, 0.8); width: 100px; text-align: center; border-radius: 10px; opacity: 0; display: none; } .end-flash.active { opacity: 1; display: block; } .end-flash.transition { transition: opacity 800ms; display: block; } .dropdown-button.active .menu-outer { display: block; } .dropdown-button { display: inline-block; } .actions-menu { margin-right: 6px; } .reader-container .button { font-size: 20px; line-height: 38px; width: 100px; text-shadow: 1px 1px 2px #000; } .reader-container .dropdown-button .menu-outer ul li { font-size: 20px; padding: 4px 14px; } .gallery-item .weight:before { content: "|"; padding-left: 5px; padding-right: 5px; font-size: 10px; vertical-align: top; line-height: 15px; } .input-wrap { padding-right: 14px; flex-grow: 1; position: relative; } .search-options > * ~ * { margin-left: 10px; } .search-options { flex-shrink: 0; } .switches-outer { display: inline-block; vertical-align: top; position: absolute; top: 0; right: 0; } .switches-outer label { margin-left: 20px; } input[type="checkbox"].fancy-switch { position: absolute; opacity: 0; } input[type="checkbox"].fancy-switch + div { vertical-align: top; width: 45px; height: 22px; border-radius: 999px; background-color: rgba(0, 0, 0, 0.1); transition: .4s; box-shadow: inset 0 0 0 0px rgba(0, 0, 0, 0.4); border: 1px solid #999; display: inline-block; } input[type="checkbox"].fancy-switch:checked + div { width: 45px; background-position: 0 0; border: 1px solid rgb(209, 135, 0); } input[type="checkbox"].fancy-switch + div > div { float: left; width: 20px; height: 20px; border-radius: inherit; transition: transform .4s; box-shadow: 0px 2px 5px rgba(0, 0, 0, 0.3), 0px 0px 0 1px rgba(0, 0, 0, 0.4); pointer-events: none; margin-top: 0px; margin-left: 0px; border: 1px solid #999; } input[type="checkbox"].fancy-switch:checked + div > div { transform: translate3d(24px, 0, 0); box-shadow: 0px 0px 0 1px rgb(209, 135, 0); border: none; background: inherit; } /* * Second Thing */ input[type="checkbox"].viewtype + div { vertical-align: top; width: 45px; height: 22px; border-radius: 999px; background-color: rgba(0, 0, 0, 0.1); transition: .4s; box-shadow: inset 0 0 0 0px rgba(0, 0, 0, 0.4); border: 1px solid rgb(3, 155, 229); display: inline-block; } input[type="checkbox"].viewtype:checked + div { width: 45px; background-position: 0 0; border: 1px solid rgb(229, 57, 53); } input[type="checkbox"].viewtype + div > div { float: left; width: 20px; height: 20px; border-radius: inherit; transition: transform .4s; box-shadow: 0px 2px 5px rgba(0, 0, 0, 0.3), 0px 0px 0 1px rgba(0, 0, 0, 0.4); pointer-events: none; margin-top: 0px; margin-left: 0px; border: 1px solid rgb(3, 155, 229); } input[type="checkbox"].viewtype:checked + div > div { transform: translate3d(24px, 0, 0); box-shadow: 0px 0px 0 1px rgb(229, 57, 53); border: none; background: inherit; } .switches-outer label span { display: inline-block; margin-right: 10px; } .search-under { position: relative; height: 22px; margin-top: 20px; } .gallery-item.unarchived { background-size: contain; } .gallery-item.viewtype { background-size: contain; } .switches-outer label { cursor: pointer; } ::-webkit-scrollbar { width: 12px; } ::-webkit-scrollbar-track { border-radius: 10px; } ::-webkit-scrollbar-thumb { border-radius: 10px; border: 1px solid #ddd; } @media (max-width: 1400px) { .gallery-item { width: 20%; padding-top: 29%; } } @media (max-width: 1100px) { .gallery-item { width: 25%; padding-top: 36.35%; } } @media (max-width: 900px) { .gallery-item { width: 33.333333333%; padding-top: 48.4%; } .search-count { float: left; } } @media (max-width: 720px) { .gallery-item .top, .gallery-item .bottom { display: none !important; } .search-count { float: left; } .gallery-info { display: none; } } @media (max-width: 580px) { .search-form { flex-wrap: wrap; } .search-count { float: left; } .search-options { flex-grow: 1; margin-top: 12px; } }
Sn0wCrack/ExHentai-Archive
<|start_filename|>src/main/java/com/daxiang/controller/GlobalVarController.java<|end_filename|> package com.daxiang.controller; import com.daxiang.mbg.po.GlobalVar; import com.daxiang.model.PageRequest; import com.daxiang.model.PagedData; import com.daxiang.model.Response; import com.daxiang.model.vo.GlobalVarVo; import com.daxiang.service.GlobalVarService; import com.daxiang.validator.group.GlobalVarGroup; import com.daxiang.validator.group.UpdateGroup; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; import javax.validation.constraints.NotEmpty; import java.util.List; /** * Created by jiangyitao. */ @Validated({GlobalVarGroup.class}) @RestController @RequestMapping("/globalVar") public class GlobalVarController { @Autowired private GlobalVarService globalVarService; @PostMapping("/add") public Response add(@RequestBody @Validated({GlobalVarGroup.class}) GlobalVar globalVar) { globalVarService.add(globalVar); return Response.success("添加成功"); } @PostMapping("/addBatch") public Response addBatch(@RequestBody @NotEmpty(message = "全局变量不能为空") @Valid List<GlobalVar> globalVars) { globalVarService.addBatch(globalVars); return Response.success("添加成功"); } @DeleteMapping("/{globalVarId}") public Response delete(@PathVariable Integer globalVarId) { globalVarService.delete(globalVarId); return Response.success("删除成功"); } @PostMapping("/update") public Response update(@RequestBody @Validated({GlobalVarGroup.class, UpdateGroup.class}) GlobalVar globalVar) { globalVarService.update(globalVar); return Response.success("更新成功"); } @PostMapping("/list") public Response list(GlobalVar query, String orderBy, PageRequest pageRequest) { if (pageRequest.needPaging()) { PagedData<GlobalVarVo> pagedData = globalVarService.list(query, orderBy, pageRequest); return Response.success(pagedData); } else { List<GlobalVarVo> globalVarVos = globalVarService.getGlobalVarVos(query, orderBy); return Response.success(globalVarVos); } } } <|start_filename|>src/main/java/com/daxiang/utils/Tree.java<|end_filename|> package com.daxiang.utils; import org.springframework.util.CollectionUtils; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.function.Function; import java.util.stream.Collectors; /** * Created by jiangyitao. */ public class Tree { public interface TreeNode { Integer getId(); Integer getParentId(); List<TreeNode> getChildren(); void setChildren(List<TreeNode> children); } public static List<TreeNode> build(List<? extends TreeNode> nodes) { List<TreeNode> tree = new ArrayList<>(); if (CollectionUtils.isEmpty(nodes)) { return tree; } Map<Integer, TreeNode> nodeMap = nodes.stream() .collect(Collectors.toMap(TreeNode::getId, Function.identity(), (k1, k2) -> k1)); for (TreeNode node : nodes) { TreeNode parent = nodeMap.get(node.getParentId()); if (parent == null) { // node为根节点 tree.add(node); } else { // node为子节点 List<TreeNode> children = parent.getChildren(); if (children == null) { children = new ArrayList<>(); parent.setChildren(children); } children.add(node); } } return tree; } } <|start_filename|>src/main/java/com/daxiang/controller/AgentExtJarController.java<|end_filename|> package com.daxiang.controller; import com.daxiang.mbg.po.AgentExtJar; import com.daxiang.model.PageRequest; import com.daxiang.model.PagedData; import com.daxiang.model.Response; import com.daxiang.model.vo.AgentExtJarVo; import com.daxiang.service.AgentExtJarService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import java.util.List; /** * Created by jiangyitao. */ @RestController @RequestMapping("/agentExtJar") public class AgentExtJarController { @Autowired private AgentExtJarService agentExtJarService; @PostMapping("/upload") public Response upload(MultipartFile file) { agentExtJarService.upload(file); return Response.success("添加成功"); } @DeleteMapping("/{id}") public Response delete(@PathVariable Integer id) { agentExtJarService.delete(id); return Response.success("删除成功"); } @PostMapping("/list") public Response list(AgentExtJar query, String orderBy, PageRequest pageRequest) { if (pageRequest.needPaging()) { PagedData<AgentExtJarVo> pagedData = agentExtJarService.list(query, orderBy, pageRequest); return Response.success(pagedData); } else { List<AgentExtJarVo> appVos = agentExtJarService.getAgentExtJarVos(query, orderBy); return Response.success(appVos); } } @GetMapping("/lastUploadTimeList") public Response getLastUploadTimeList() { return Response.success(agentExtJarService.getLastUploadTimeList()); } } <|start_filename|>src/main/java/com/daxiang/dao/TestSuiteDao.java<|end_filename|> package com.daxiang.dao; import com.daxiang.mbg.po.TestSuite; import org.apache.ibatis.annotations.Param; import java.util.List; /** * Created by jiangyitao. */ public interface TestSuiteDao { List<TestSuite> selectByActionId(@Param("actionId") Integer actionId); } <|start_filename|>src/main/java/com/daxiang/security/UserDetailsServiceImpl.java<|end_filename|> package com.daxiang.security; import com.daxiang.model.dto.UserDto; import com.daxiang.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; @Service public class UserDetailsServiceImpl implements UserDetailsService { @Autowired private UserService userService; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { UserDto userDto = userService.getUserDtoByUsername(username); if (userDto == null) { throw new UsernameNotFoundException(username + " not found"); } return userDto; } } <|start_filename|>src/main/java/com/daxiang/controller/UserController.java<|end_filename|> package com.daxiang.controller; import com.daxiang.mbg.po.User; import com.daxiang.model.PageRequest; import com.daxiang.model.PagedData; import com.daxiang.model.Response; import com.daxiang.model.dto.UserDto; import com.daxiang.security.SecurityUtil; import com.daxiang.service.UserService; import com.daxiang.validator.group.SaveUserGroup; import com.daxiang.validator.group.UpdateGroup; import com.google.common.collect.ImmutableMap; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; import java.util.List; /** * Created by jiangyitao. */ @RestController @RequestMapping("/user") public class UserController { @Autowired private UserService userService; @PreAuthorize("hasAuthority('admin')") @PostMapping("/add") public Response add(@Validated({SaveUserGroup.class}) @RequestBody UserDto userDto) { userService.add(userDto); return Response.success("添加成功"); } @PreAuthorize("hasAuthority('admin')") @DeleteMapping("/{userId}") public Response delete(@PathVariable Integer userId) { userService.delete(userId); return Response.success("删除成功"); } @PreAuthorize("hasAuthority('admin')") @PostMapping("/update") public Response update(@Validated({SaveUserGroup.class, UpdateGroup.class}) @RequestBody UserDto userDto) { userService.update(userDto); return Response.success("更新成功"); } @PreAuthorize("hasAuthority('admin')") @PostMapping("/list") public Response list(User query, String orderBy, PageRequest pageRequest) { if (pageRequest.needPaging()) { PagedData<UserDto> pagedData = userService.list(query, orderBy, pageRequest); return Response.success(pagedData); } else { List<UserDto> userDtos = userService.getUserDtos(query, orderBy); return Response.success(userDtos); } } @PostMapping("/login") public Response login(@Valid @RequestBody User user) { String token = userService.login(user); return Response.success("登陆成功", ImmutableMap.of("token", token)); } @GetMapping("/info") public Response getInfo() { return Response.success(SecurityUtil.getCurrentUserDto()); } @PostMapping("/logout") public Response logout() { return Response.success(); } } <|start_filename|>src/main/java/com/daxiang/model/request/ActionDebugRequest.java<|end_filename|> package com.daxiang.model.request; import com.daxiang.mbg.po.Action; import lombok.Data; import javax.validation.Valid; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.NotNull; /** * Created by jiangyitao. */ @Data public class ActionDebugRequest { @NotNull(message = "action不能为空") @Valid private Action action; @Valid @NotNull(message = "缺少调试信息") private DebugInfo debugInfo; @Data public static class DebugInfo { @NotNull(message = "platform不能为空") private Integer platform; @NotEmpty(message = "agentIp不能为空") private String agentIp; @NotNull(message = "agentPort不能为空") private Integer agentPort; @NotNull(message = "环境不能为空") private Integer env; @NotBlank(message = "deviceId不能为空") private String deviceId; } } <|start_filename|>src/main/java/com/daxiang/security/JwtAuthenticationEntryPoint.java<|end_filename|> package com.daxiang.security; import com.alibaba.fastjson.JSON; import com.daxiang.model.Response; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.AuthenticationEntryPoint; import org.springframework.stereotype.Component; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * Created by jiangyitao. */ @Component public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint { @Override public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException { response.setCharacterEncoding("UTF-8"); response.setContentType("application/json"); response.getWriter().println(JSON.toJSONString(Response.unauthorized(e.getMessage()))); response.getWriter().flush(); } } <|start_filename|>src/main/java/com/daxiang/mbg/po/MobileExample.java<|end_filename|> package com.daxiang.mbg.po; import java.util.ArrayList; import java.util.Date; import java.util.List; public class MobileExample { protected String orderByClause; protected boolean distinct; protected List<Criteria> oredCriteria; public MobileExample() { oredCriteria = new ArrayList<Criteria>(); } public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } public String getOrderByClause() { return orderByClause; } public void setDistinct(boolean distinct) { this.distinct = distinct; } public boolean isDistinct() { return distinct; } public List<Criteria> getOredCriteria() { return oredCriteria; } public void or(Criteria criteria) { oredCriteria.add(criteria); } public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } protected abstract static class GeneratedCriteria { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andIdIsNull() { addCriterion("id is null"); return (Criteria) this; } public Criteria andIdIsNotNull() { addCriterion("id is not null"); return (Criteria) this; } public Criteria andIdEqualTo(String value) { addCriterion("id =", value, "id"); return (Criteria) this; } public Criteria andIdNotEqualTo(String value) { addCriterion("id <>", value, "id"); return (Criteria) this; } public Criteria andIdGreaterThan(String value) { addCriterion("id >", value, "id"); return (Criteria) this; } public Criteria andIdGreaterThanOrEqualTo(String value) { addCriterion("id >=", value, "id"); return (Criteria) this; } public Criteria andIdLessThan(String value) { addCriterion("id <", value, "id"); return (Criteria) this; } public Criteria andIdLessThanOrEqualTo(String value) { addCriterion("id <=", value, "id"); return (Criteria) this; } public Criteria andIdLike(String value) { addCriterion("id like", value, "id"); return (Criteria) this; } public Criteria andIdNotLike(String value) { addCriterion("id not like", value, "id"); return (Criteria) this; } public Criteria andIdIn(List<String> values) { addCriterion("id in", values, "id"); return (Criteria) this; } public Criteria andIdNotIn(List<String> values) { addCriterion("id not in", values, "id"); return (Criteria) this; } public Criteria andIdBetween(String value1, String value2) { addCriterion("id between", value1, value2, "id"); return (Criteria) this; } public Criteria andIdNotBetween(String value1, String value2) { addCriterion("id not between", value1, value2, "id"); return (Criteria) this; } public Criteria andNameIsNull() { addCriterion("name is null"); return (Criteria) this; } public Criteria andNameIsNotNull() { addCriterion("name is not null"); return (Criteria) this; } public Criteria andNameEqualTo(String value) { addCriterion("name =", value, "name"); return (Criteria) this; } public Criteria andNameNotEqualTo(String value) { addCriterion("name <>", value, "name"); return (Criteria) this; } public Criteria andNameGreaterThan(String value) { addCriterion("name >", value, "name"); return (Criteria) this; } public Criteria andNameGreaterThanOrEqualTo(String value) { addCriterion("name >=", value, "name"); return (Criteria) this; } public Criteria andNameLessThan(String value) { addCriterion("name <", value, "name"); return (Criteria) this; } public Criteria andNameLessThanOrEqualTo(String value) { addCriterion("name <=", value, "name"); return (Criteria) this; } public Criteria andNameLike(String value) { addCriterion("name like", value, "name"); return (Criteria) this; } public Criteria andNameNotLike(String value) { addCriterion("name not like", value, "name"); return (Criteria) this; } public Criteria andNameIn(List<String> values) { addCriterion("name in", values, "name"); return (Criteria) this; } public Criteria andNameNotIn(List<String> values) { addCriterion("name not in", values, "name"); return (Criteria) this; } public Criteria andNameBetween(String value1, String value2) { addCriterion("name between", value1, value2, "name"); return (Criteria) this; } public Criteria andNameNotBetween(String value1, String value2) { addCriterion("name not between", value1, value2, "name"); return (Criteria) this; } public Criteria andEmulatorIsNull() { addCriterion("emulator is null"); return (Criteria) this; } public Criteria andEmulatorIsNotNull() { addCriterion("emulator is not null"); return (Criteria) this; } public Criteria andEmulatorEqualTo(Integer value) { addCriterion("emulator =", value, "emulator"); return (Criteria) this; } public Criteria andEmulatorNotEqualTo(Integer value) { addCriterion("emulator <>", value, "emulator"); return (Criteria) this; } public Criteria andEmulatorGreaterThan(Integer value) { addCriterion("emulator >", value, "emulator"); return (Criteria) this; } public Criteria andEmulatorGreaterThanOrEqualTo(Integer value) { addCriterion("emulator >=", value, "emulator"); return (Criteria) this; } public Criteria andEmulatorLessThan(Integer value) { addCriterion("emulator <", value, "emulator"); return (Criteria) this; } public Criteria andEmulatorLessThanOrEqualTo(Integer value) { addCriterion("emulator <=", value, "emulator"); return (Criteria) this; } public Criteria andEmulatorIn(List<Integer> values) { addCriterion("emulator in", values, "emulator"); return (Criteria) this; } public Criteria andEmulatorNotIn(List<Integer> values) { addCriterion("emulator not in", values, "emulator"); return (Criteria) this; } public Criteria andEmulatorBetween(Integer value1, Integer value2) { addCriterion("emulator between", value1, value2, "emulator"); return (Criteria) this; } public Criteria andEmulatorNotBetween(Integer value1, Integer value2) { addCriterion("emulator not between", value1, value2, "emulator"); return (Criteria) this; } public Criteria andAgentIpIsNull() { addCriterion("agent_ip is null"); return (Criteria) this; } public Criteria andAgentIpIsNotNull() { addCriterion("agent_ip is not null"); return (Criteria) this; } public Criteria andAgentIpEqualTo(String value) { addCriterion("agent_ip =", value, "agentIp"); return (Criteria) this; } public Criteria andAgentIpNotEqualTo(String value) { addCriterion("agent_ip <>", value, "agentIp"); return (Criteria) this; } public Criteria andAgentIpGreaterThan(String value) { addCriterion("agent_ip >", value, "agentIp"); return (Criteria) this; } public Criteria andAgentIpGreaterThanOrEqualTo(String value) { addCriterion("agent_ip >=", value, "agentIp"); return (Criteria) this; } public Criteria andAgentIpLessThan(String value) { addCriterion("agent_ip <", value, "agentIp"); return (Criteria) this; } public Criteria andAgentIpLessThanOrEqualTo(String value) { addCriterion("agent_ip <=", value, "agentIp"); return (Criteria) this; } public Criteria andAgentIpLike(String value) { addCriterion("agent_ip like", value, "agentIp"); return (Criteria) this; } public Criteria andAgentIpNotLike(String value) { addCriterion("agent_ip not like", value, "agentIp"); return (Criteria) this; } public Criteria andAgentIpIn(List<String> values) { addCriterion("agent_ip in", values, "agentIp"); return (Criteria) this; } public Criteria andAgentIpNotIn(List<String> values) { addCriterion("agent_ip not in", values, "agentIp"); return (Criteria) this; } public Criteria andAgentIpBetween(String value1, String value2) { addCriterion("agent_ip between", value1, value2, "agentIp"); return (Criteria) this; } public Criteria andAgentIpNotBetween(String value1, String value2) { addCriterion("agent_ip not between", value1, value2, "agentIp"); return (Criteria) this; } public Criteria andAgentPortIsNull() { addCriterion("agent_port is null"); return (Criteria) this; } public Criteria andAgentPortIsNotNull() { addCriterion("agent_port is not null"); return (Criteria) this; } public Criteria andAgentPortEqualTo(Integer value) { addCriterion("agent_port =", value, "agentPort"); return (Criteria) this; } public Criteria andAgentPortNotEqualTo(Integer value) { addCriterion("agent_port <>", value, "agentPort"); return (Criteria) this; } public Criteria andAgentPortGreaterThan(Integer value) { addCriterion("agent_port >", value, "agentPort"); return (Criteria) this; } public Criteria andAgentPortGreaterThanOrEqualTo(Integer value) { addCriterion("agent_port >=", value, "agentPort"); return (Criteria) this; } public Criteria andAgentPortLessThan(Integer value) { addCriterion("agent_port <", value, "agentPort"); return (Criteria) this; } public Criteria andAgentPortLessThanOrEqualTo(Integer value) { addCriterion("agent_port <=", value, "agentPort"); return (Criteria) this; } public Criteria andAgentPortIn(List<Integer> values) { addCriterion("agent_port in", values, "agentPort"); return (Criteria) this; } public Criteria andAgentPortNotIn(List<Integer> values) { addCriterion("agent_port not in", values, "agentPort"); return (Criteria) this; } public Criteria andAgentPortBetween(Integer value1, Integer value2) { addCriterion("agent_port between", value1, value2, "agentPort"); return (Criteria) this; } public Criteria andAgentPortNotBetween(Integer value1, Integer value2) { addCriterion("agent_port not between", value1, value2, "agentPort"); return (Criteria) this; } public Criteria andSystemVersionIsNull() { addCriterion("system_version is null"); return (Criteria) this; } public Criteria andSystemVersionIsNotNull() { addCriterion("system_version is not null"); return (Criteria) this; } public Criteria andSystemVersionEqualTo(String value) { addCriterion("system_version =", value, "systemVersion"); return (Criteria) this; } public Criteria andSystemVersionNotEqualTo(String value) { addCriterion("system_version <>", value, "systemVersion"); return (Criteria) this; } public Criteria andSystemVersionGreaterThan(String value) { addCriterion("system_version >", value, "systemVersion"); return (Criteria) this; } public Criteria andSystemVersionGreaterThanOrEqualTo(String value) { addCriterion("system_version >=", value, "systemVersion"); return (Criteria) this; } public Criteria andSystemVersionLessThan(String value) { addCriterion("system_version <", value, "systemVersion"); return (Criteria) this; } public Criteria andSystemVersionLessThanOrEqualTo(String value) { addCriterion("system_version <=", value, "systemVersion"); return (Criteria) this; } public Criteria andSystemVersionLike(String value) { addCriterion("system_version like", value, "systemVersion"); return (Criteria) this; } public Criteria andSystemVersionNotLike(String value) { addCriterion("system_version not like", value, "systemVersion"); return (Criteria) this; } public Criteria andSystemVersionIn(List<String> values) { addCriterion("system_version in", values, "systemVersion"); return (Criteria) this; } public Criteria andSystemVersionNotIn(List<String> values) { addCriterion("system_version not in", values, "systemVersion"); return (Criteria) this; } public Criteria andSystemVersionBetween(String value1, String value2) { addCriterion("system_version between", value1, value2, "systemVersion"); return (Criteria) this; } public Criteria andSystemVersionNotBetween(String value1, String value2) { addCriterion("system_version not between", value1, value2, "systemVersion"); return (Criteria) this; } public Criteria andCpuInfoIsNull() { addCriterion("cpu_info is null"); return (Criteria) this; } public Criteria andCpuInfoIsNotNull() { addCriterion("cpu_info is not null"); return (Criteria) this; } public Criteria andCpuInfoEqualTo(String value) { addCriterion("cpu_info =", value, "cpuInfo"); return (Criteria) this; } public Criteria andCpuInfoNotEqualTo(String value) { addCriterion("cpu_info <>", value, "cpuInfo"); return (Criteria) this; } public Criteria andCpuInfoGreaterThan(String value) { addCriterion("cpu_info >", value, "cpuInfo"); return (Criteria) this; } public Criteria andCpuInfoGreaterThanOrEqualTo(String value) { addCriterion("cpu_info >=", value, "cpuInfo"); return (Criteria) this; } public Criteria andCpuInfoLessThan(String value) { addCriterion("cpu_info <", value, "cpuInfo"); return (Criteria) this; } public Criteria andCpuInfoLessThanOrEqualTo(String value) { addCriterion("cpu_info <=", value, "cpuInfo"); return (Criteria) this; } public Criteria andCpuInfoLike(String value) { addCriterion("cpu_info like", value, "cpuInfo"); return (Criteria) this; } public Criteria andCpuInfoNotLike(String value) { addCriterion("cpu_info not like", value, "cpuInfo"); return (Criteria) this; } public Criteria andCpuInfoIn(List<String> values) { addCriterion("cpu_info in", values, "cpuInfo"); return (Criteria) this; } public Criteria andCpuInfoNotIn(List<String> values) { addCriterion("cpu_info not in", values, "cpuInfo"); return (Criteria) this; } public Criteria andCpuInfoBetween(String value1, String value2) { addCriterion("cpu_info between", value1, value2, "cpuInfo"); return (Criteria) this; } public Criteria andCpuInfoNotBetween(String value1, String value2) { addCriterion("cpu_info not between", value1, value2, "cpuInfo"); return (Criteria) this; } public Criteria andMemSizeIsNull() { addCriterion("mem_size is null"); return (Criteria) this; } public Criteria andMemSizeIsNotNull() { addCriterion("mem_size is not null"); return (Criteria) this; } public Criteria andMemSizeEqualTo(String value) { addCriterion("mem_size =", value, "memSize"); return (Criteria) this; } public Criteria andMemSizeNotEqualTo(String value) { addCriterion("mem_size <>", value, "memSize"); return (Criteria) this; } public Criteria andMemSizeGreaterThan(String value) { addCriterion("mem_size >", value, "memSize"); return (Criteria) this; } public Criteria andMemSizeGreaterThanOrEqualTo(String value) { addCriterion("mem_size >=", value, "memSize"); return (Criteria) this; } public Criteria andMemSizeLessThan(String value) { addCriterion("mem_size <", value, "memSize"); return (Criteria) this; } public Criteria andMemSizeLessThanOrEqualTo(String value) { addCriterion("mem_size <=", value, "memSize"); return (Criteria) this; } public Criteria andMemSizeLike(String value) { addCriterion("mem_size like", value, "memSize"); return (Criteria) this; } public Criteria andMemSizeNotLike(String value) { addCriterion("mem_size not like", value, "memSize"); return (Criteria) this; } public Criteria andMemSizeIn(List<String> values) { addCriterion("mem_size in", values, "memSize"); return (Criteria) this; } public Criteria andMemSizeNotIn(List<String> values) { addCriterion("mem_size not in", values, "memSize"); return (Criteria) this; } public Criteria andMemSizeBetween(String value1, String value2) { addCriterion("mem_size between", value1, value2, "memSize"); return (Criteria) this; } public Criteria andMemSizeNotBetween(String value1, String value2) { addCriterion("mem_size not between", value1, value2, "memSize"); return (Criteria) this; } public Criteria andScreenWidthIsNull() { addCriterion("screen_width is null"); return (Criteria) this; } public Criteria andScreenWidthIsNotNull() { addCriterion("screen_width is not null"); return (Criteria) this; } public Criteria andScreenWidthEqualTo(Integer value) { addCriterion("screen_width =", value, "screenWidth"); return (Criteria) this; } public Criteria andScreenWidthNotEqualTo(Integer value) { addCriterion("screen_width <>", value, "screenWidth"); return (Criteria) this; } public Criteria andScreenWidthGreaterThan(Integer value) { addCriterion("screen_width >", value, "screenWidth"); return (Criteria) this; } public Criteria andScreenWidthGreaterThanOrEqualTo(Integer value) { addCriterion("screen_width >=", value, "screenWidth"); return (Criteria) this; } public Criteria andScreenWidthLessThan(Integer value) { addCriterion("screen_width <", value, "screenWidth"); return (Criteria) this; } public Criteria andScreenWidthLessThanOrEqualTo(Integer value) { addCriterion("screen_width <=", value, "screenWidth"); return (Criteria) this; } public Criteria andScreenWidthIn(List<Integer> values) { addCriterion("screen_width in", values, "screenWidth"); return (Criteria) this; } public Criteria andScreenWidthNotIn(List<Integer> values) { addCriterion("screen_width not in", values, "screenWidth"); return (Criteria) this; } public Criteria andScreenWidthBetween(Integer value1, Integer value2) { addCriterion("screen_width between", value1, value2, "screenWidth"); return (Criteria) this; } public Criteria andScreenWidthNotBetween(Integer value1, Integer value2) { addCriterion("screen_width not between", value1, value2, "screenWidth"); return (Criteria) this; } public Criteria andScreenHeightIsNull() { addCriterion("screen_height is null"); return (Criteria) this; } public Criteria andScreenHeightIsNotNull() { addCriterion("screen_height is not null"); return (Criteria) this; } public Criteria andScreenHeightEqualTo(Integer value) { addCriterion("screen_height =", value, "screenHeight"); return (Criteria) this; } public Criteria andScreenHeightNotEqualTo(Integer value) { addCriterion("screen_height <>", value, "screenHeight"); return (Criteria) this; } public Criteria andScreenHeightGreaterThan(Integer value) { addCriterion("screen_height >", value, "screenHeight"); return (Criteria) this; } public Criteria andScreenHeightGreaterThanOrEqualTo(Integer value) { addCriterion("screen_height >=", value, "screenHeight"); return (Criteria) this; } public Criteria andScreenHeightLessThan(Integer value) { addCriterion("screen_height <", value, "screenHeight"); return (Criteria) this; } public Criteria andScreenHeightLessThanOrEqualTo(Integer value) { addCriterion("screen_height <=", value, "screenHeight"); return (Criteria) this; } public Criteria andScreenHeightIn(List<Integer> values) { addCriterion("screen_height in", values, "screenHeight"); return (Criteria) this; } public Criteria andScreenHeightNotIn(List<Integer> values) { addCriterion("screen_height not in", values, "screenHeight"); return (Criteria) this; } public Criteria andScreenHeightBetween(Integer value1, Integer value2) { addCriterion("screen_height between", value1, value2, "screenHeight"); return (Criteria) this; } public Criteria andScreenHeightNotBetween(Integer value1, Integer value2) { addCriterion("screen_height not between", value1, value2, "screenHeight"); return (Criteria) this; } public Criteria andImgPathIsNull() { addCriterion("img_path is null"); return (Criteria) this; } public Criteria andImgPathIsNotNull() { addCriterion("img_path is not null"); return (Criteria) this; } public Criteria andImgPathEqualTo(String value) { addCriterion("img_path =", value, "imgPath"); return (Criteria) this; } public Criteria andImgPathNotEqualTo(String value) { addCriterion("img_path <>", value, "imgPath"); return (Criteria) this; } public Criteria andImgPathGreaterThan(String value) { addCriterion("img_path >", value, "imgPath"); return (Criteria) this; } public Criteria andImgPathGreaterThanOrEqualTo(String value) { addCriterion("img_path >=", value, "imgPath"); return (Criteria) this; } public Criteria andImgPathLessThan(String value) { addCriterion("img_path <", value, "imgPath"); return (Criteria) this; } public Criteria andImgPathLessThanOrEqualTo(String value) { addCriterion("img_path <=", value, "imgPath"); return (Criteria) this; } public Criteria andImgPathLike(String value) { addCriterion("img_path like", value, "imgPath"); return (Criteria) this; } public Criteria andImgPathNotLike(String value) { addCriterion("img_path not like", value, "imgPath"); return (Criteria) this; } public Criteria andImgPathIn(List<String> values) { addCriterion("img_path in", values, "imgPath"); return (Criteria) this; } public Criteria andImgPathNotIn(List<String> values) { addCriterion("img_path not in", values, "imgPath"); return (Criteria) this; } public Criteria andImgPathBetween(String value1, String value2) { addCriterion("img_path between", value1, value2, "imgPath"); return (Criteria) this; } public Criteria andImgPathNotBetween(String value1, String value2) { addCriterion("img_path not between", value1, value2, "imgPath"); return (Criteria) this; } public Criteria andPlatformIsNull() { addCriterion("platform is null"); return (Criteria) this; } public Criteria andPlatformIsNotNull() { addCriterion("platform is not null"); return (Criteria) this; } public Criteria andPlatformEqualTo(Integer value) { addCriterion("platform =", value, "platform"); return (Criteria) this; } public Criteria andPlatformNotEqualTo(Integer value) { addCriterion("platform <>", value, "platform"); return (Criteria) this; } public Criteria andPlatformGreaterThan(Integer value) { addCriterion("platform >", value, "platform"); return (Criteria) this; } public Criteria andPlatformGreaterThanOrEqualTo(Integer value) { addCriterion("platform >=", value, "platform"); return (Criteria) this; } public Criteria andPlatformLessThan(Integer value) { addCriterion("platform <", value, "platform"); return (Criteria) this; } public Criteria andPlatformLessThanOrEqualTo(Integer value) { addCriterion("platform <=", value, "platform"); return (Criteria) this; } public Criteria andPlatformIn(List<Integer> values) { addCriterion("platform in", values, "platform"); return (Criteria) this; } public Criteria andPlatformNotIn(List<Integer> values) { addCriterion("platform not in", values, "platform"); return (Criteria) this; } public Criteria andPlatformBetween(Integer value1, Integer value2) { addCriterion("platform between", value1, value2, "platform"); return (Criteria) this; } public Criteria andPlatformNotBetween(Integer value1, Integer value2) { addCriterion("platform not between", value1, value2, "platform"); return (Criteria) this; } public Criteria andStatusIsNull() { addCriterion("status is null"); return (Criteria) this; } public Criteria andStatusIsNotNull() { addCriterion("status is not null"); return (Criteria) this; } public Criteria andStatusEqualTo(Integer value) { addCriterion("status =", value, "status"); return (Criteria) this; } public Criteria andStatusNotEqualTo(Integer value) { addCriterion("status <>", value, "status"); return (Criteria) this; } public Criteria andStatusGreaterThan(Integer value) { addCriterion("status >", value, "status"); return (Criteria) this; } public Criteria andStatusGreaterThanOrEqualTo(Integer value) { addCriterion("status >=", value, "status"); return (Criteria) this; } public Criteria andStatusLessThan(Integer value) { addCriterion("status <", value, "status"); return (Criteria) this; } public Criteria andStatusLessThanOrEqualTo(Integer value) { addCriterion("status <=", value, "status"); return (Criteria) this; } public Criteria andStatusIn(List<Integer> values) { addCriterion("status in", values, "status"); return (Criteria) this; } public Criteria andStatusNotIn(List<Integer> values) { addCriterion("status not in", values, "status"); return (Criteria) this; } public Criteria andStatusBetween(Integer value1, Integer value2) { addCriterion("status between", value1, value2, "status"); return (Criteria) this; } public Criteria andStatusNotBetween(Integer value1, Integer value2) { addCriterion("status not between", value1, value2, "status"); return (Criteria) this; } public Criteria andLastOnlineTimeIsNull() { addCriterion("last_online_time is null"); return (Criteria) this; } public Criteria andLastOnlineTimeIsNotNull() { addCriterion("last_online_time is not null"); return (Criteria) this; } public Criteria andLastOnlineTimeEqualTo(Date value) { addCriterion("last_online_time =", value, "lastOnlineTime"); return (Criteria) this; } public Criteria andLastOnlineTimeNotEqualTo(Date value) { addCriterion("last_online_time <>", value, "lastOnlineTime"); return (Criteria) this; } public Criteria andLastOnlineTimeGreaterThan(Date value) { addCriterion("last_online_time >", value, "lastOnlineTime"); return (Criteria) this; } public Criteria andLastOnlineTimeGreaterThanOrEqualTo(Date value) { addCriterion("last_online_time >=", value, "lastOnlineTime"); return (Criteria) this; } public Criteria andLastOnlineTimeLessThan(Date value) { addCriterion("last_online_time <", value, "lastOnlineTime"); return (Criteria) this; } public Criteria andLastOnlineTimeLessThanOrEqualTo(Date value) { addCriterion("last_online_time <=", value, "lastOnlineTime"); return (Criteria) this; } public Criteria andLastOnlineTimeIn(List<Date> values) { addCriterion("last_online_time in", values, "lastOnlineTime"); return (Criteria) this; } public Criteria andLastOnlineTimeNotIn(List<Date> values) { addCriterion("last_online_time not in", values, "lastOnlineTime"); return (Criteria) this; } public Criteria andLastOnlineTimeBetween(Date value1, Date value2) { addCriterion("last_online_time between", value1, value2, "lastOnlineTime"); return (Criteria) this; } public Criteria andLastOnlineTimeNotBetween(Date value1, Date value2) { addCriterion("last_online_time not between", value1, value2, "lastOnlineTime"); return (Criteria) this; } public Criteria andUsernameIsNull() { addCriterion("username is null"); return (Criteria) this; } public Criteria andUsernameIsNotNull() { addCriterion("username is not null"); return (Criteria) this; } public Criteria andUsernameEqualTo(String value) { addCriterion("username =", value, "username"); return (Criteria) this; } public Criteria andUsernameNotEqualTo(String value) { addCriterion("username <>", value, "username"); return (Criteria) this; } public Criteria andUsernameGreaterThan(String value) { addCriterion("username >", value, "username"); return (Criteria) this; } public Criteria andUsernameGreaterThanOrEqualTo(String value) { addCriterion("username >=", value, "username"); return (Criteria) this; } public Criteria andUsernameLessThan(String value) { addCriterion("username <", value, "username"); return (Criteria) this; } public Criteria andUsernameLessThanOrEqualTo(String value) { addCriterion("username <=", value, "username"); return (Criteria) this; } public Criteria andUsernameLike(String value) { addCriterion("username like", value, "username"); return (Criteria) this; } public Criteria andUsernameNotLike(String value) { addCriterion("username not like", value, "username"); return (Criteria) this; } public Criteria andUsernameIn(List<String> values) { addCriterion("username in", values, "username"); return (Criteria) this; } public Criteria andUsernameNotIn(List<String> values) { addCriterion("username not in", values, "username"); return (Criteria) this; } public Criteria andUsernameBetween(String value1, String value2) { addCriterion("username between", value1, value2, "username"); return (Criteria) this; } public Criteria andUsernameNotBetween(String value1, String value2) { addCriterion("username not between", value1, value2, "username"); return (Criteria) this; } public Criteria andCreateTimeIsNull() { addCriterion("create_time is null"); return (Criteria) this; } public Criteria andCreateTimeIsNotNull() { addCriterion("create_time is not null"); return (Criteria) this; } public Criteria andCreateTimeEqualTo(Date value) { addCriterion("create_time =", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeNotEqualTo(Date value) { addCriterion("create_time <>", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeGreaterThan(Date value) { addCriterion("create_time >", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeGreaterThanOrEqualTo(Date value) { addCriterion("create_time >=", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeLessThan(Date value) { addCriterion("create_time <", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeLessThanOrEqualTo(Date value) { addCriterion("create_time <=", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeIn(List<Date> values) { addCriterion("create_time in", values, "createTime"); return (Criteria) this; } public Criteria andCreateTimeNotIn(List<Date> values) { addCriterion("create_time not in", values, "createTime"); return (Criteria) this; } public Criteria andCreateTimeBetween(Date value1, Date value2) { addCriterion("create_time between", value1, value2, "createTime"); return (Criteria) this; } public Criteria andCreateTimeNotBetween(Date value1, Date value2) { addCriterion("create_time not between", value1, value2, "createTime"); return (Criteria) this; } } public static class Criteria extends GeneratedCriteria { protected Criteria() { super(); } } public static class Criterion { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } } <|start_filename|>src/main/java/com/daxiang/typehandler/ByListTypeHandler.java<|end_filename|> package com.daxiang.typehandler; import com.daxiang.model.page.By; /** * Created by jiangyitao. */ public class ByListTypeHandler extends ListTypeHandler { @Override public Class getTypeClass() { return By.class; } } <|start_filename|>src/main/java/com/daxiang/service/PageService.java<|end_filename|> package com.daxiang.service; import com.daxiang.dao.PageDao; import com.daxiang.exception.ServerException; import com.daxiang.mbg.po.*; import com.daxiang.model.PagedData; import com.daxiang.model.enums.UploadDir; import com.daxiang.security.SecurityUtil; import com.github.pagehelper.PageHelper; import com.daxiang.mbg.mapper.PageMapper; import com.daxiang.model.PageRequest; import com.daxiang.model.vo.PageVo; import lombok.extern.slf4j.Slf4j; import org.apache.commons.io.FilenameUtils; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DuplicateKeyException; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.CollectionUtils; import org.springframework.util.StringUtils; import java.io.FileNotFoundException; import java.io.IOException; import java.util.*; import java.util.stream.Collectors; /** * Created by jiangyitao. */ @Slf4j @Service public class PageService { @Autowired private PageMapper pageMapper; @Autowired private PageDao pageDao; @Autowired private ActionService actionService; @Autowired private UserService userService; @Autowired private FileService fileService; @Transactional public void add(Page page) { page.setCreateTime(new Date()); page.setCreatorUid(SecurityUtil.getCurrentUserId()); String originalImgPath = page.getImgPath(); String destImgPath = null; if (!StringUtils.isEmpty(originalImgPath)) { destImgPath = UploadDir.IMG.path + "/" + FilenameUtils.getName(originalImgPath); page.setImgPath(destImgPath); } try { int insertCount = pageMapper.insertSelective(page); if (insertCount != 1) { throw new ServerException("添加失败,请稍后重试"); } } catch (DuplicateKeyException e) { throw new ServerException(page.getName() + "已存在"); } // 数据库添加成功,图片移动到IMG目录 if (!StringUtils.isEmpty(destImgPath)) { try { fileService.moveFile(originalImgPath, destImgPath); } catch (FileNotFoundException e) { log.info("file not found: {}", originalImgPath); throw new ServerException("图片不存在,该图片可能已保存至其他Page"); } catch (IOException e) { log.error("move {} -> {} err", originalImgPath, destImgPath, e); throw new ServerException(e.getMessage()); } } } public void deleteAndClearRelatedRes(Integer pageId) { Page page = pageMapper.selectByPrimaryKey(pageId); if (page == null) { throw new ServerException("page不存在"); } // 检查Page名下是否有action List<Action> actions = actionService.getActionsByPageId(pageId); if (!CollectionUtils.isEmpty(actions)) { String actionNames = actions.stream().map(Action::getName).collect(Collectors.joining("、")); throw new ServerException("actions: " + actionNames + ",已绑定该page,无法删除"); } int deleteCount = pageMapper.deleteByPrimaryKey(pageId); if (deleteCount != 1) { throw new ServerException("删除失败,请稍后重试"); } fileService.deleteQuietly(page.getImgPath()); } public void update(Page page) { try { int updateCount = pageMapper.updateByPrimaryKeyWithBLOBs(page); if (updateCount != 1) { throw new ServerException("更新失败,请稍后重试"); } } catch (DuplicateKeyException e) { throw new ServerException(page.getName() + "已存在"); } } public PagedData<PageVo> listWithoutWindowHierarchy(Page query, String orderBy, PageRequest pageRequest) { com.github.pagehelper.Page<Object> page = PageHelper.startPage(pageRequest.getPageNum(), pageRequest.getPageSize()); if (StringUtils.isEmpty(orderBy)) { orderBy = "create_time desc"; } List<PageVo> pageVos = getPageVosWithoutWindowHierarchy(query, orderBy); return new PagedData<>(pageVos, page.getTotal()); } public PageVo getPageVoById(Integer pageId) { if (pageId == null) { throw new ServerException("pageId不能为空"); } Page page = pageMapper.selectByPrimaryKey(pageId); if (page == null) { throw new ServerException("page不存在"); } List<PageVo> pageVos = convertPagesToPageVos(Arrays.asList(page)); return pageVos.get(0); } private List<PageVo> convertPagesToPageVos(List<Page> pages) { if (CollectionUtils.isEmpty(pages)) { return new ArrayList<>(); } List<Integer> creatorUids = pages.stream() .map(Page::getCreatorUid) .filter(Objects::nonNull) .distinct() .collect(Collectors.toList()); Map<Integer, User> userMap = userService.getUserMapByIds(creatorUids); List<PageVo> pageVos = pages.stream().map(page -> { PageVo pageVo = new PageVo(); BeanUtils.copyProperties(page, pageVo); if (page.getCreatorUid() != null) { User user = userMap.get(page.getCreatorUid()); if (user != null) { pageVo.setCreatorNickName(user.getNickName()); } } return pageVo; }).collect(Collectors.toList()); return pageVos; } public List<PageVo> getPageVosWithoutWindowHierarchy(Page query, String orderBy) { List<Page> pages = getPagesWithoutWindowHierarchy(query, orderBy); return convertPagesToPageVos(pages); } public List<Page> getPagesWithoutWindowHierarchy(Page query) { return getPagesWithoutWindowHierarchy(query, null); } public List<Page> getPagesWithoutWindowHierarchy(Page query, String orderBy) { PageExample example = new PageExample(); if (query != null) { PageExample.Criteria criteria = example.createCriteria(); if (query.getId() != null) { criteria.andIdEqualTo(query.getId()); } if (query.getCategoryId() != null) { criteria.andCategoryIdEqualTo(query.getCategoryId()); } if (query.getProjectId() != null) { criteria.andProjectIdEqualTo(query.getProjectId()); } } if (!StringUtils.isEmpty(orderBy)) { example.setOrderByClause(orderBy); } return pageDao.selectPagesWithoutWindowHierarchyByExample(example); } public List<Page> getPagesWithoutWindowHierarchyByProjectId(Integer projectId) { if (projectId == null) { throw new ServerException("projectId不能为空"); } Page query = new Page(); query.setProjectId(projectId); return getPagesWithoutWindowHierarchy(query); } public List<Page> getPagesWithoutWindowHierarchyByCategoryIds(List<Integer> categoryIds) { if (CollectionUtils.isEmpty(categoryIds)) { return new ArrayList<>(); } PageExample example = new PageExample(); PageExample.Criteria criteria = example.createCriteria(); criteria.andCategoryIdIn(categoryIds); return pageDao.selectPagesWithoutWindowHierarchyByExample(example); } } <|start_filename|>src/main/java/com/daxiang/service/TestTaskService.java<|end_filename|> package com.daxiang.service; import com.alibaba.fastjson.JSONObject; import com.daxiang.exception.ServerException; import com.daxiang.mbg.mapper.TestTaskMapper; import com.daxiang.mbg.po.*; import com.daxiang.model.vo.TestTaskVo; import com.daxiang.model.vo.TestTaskSummary; import com.github.pagehelper.PageHelper; import com.github.pagehelper.Page; import com.daxiang.model.PagedData; import com.daxiang.model.PageRequest; import com.daxiang.model.dto.Testcase; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Lazy; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.CollectionUtils; import org.springframework.util.StringUtils; import java.text.NumberFormat; import java.util.*; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.Stream; /** * Created by jiangyitao. */ @Service public class TestTaskService { @Autowired private TestTaskMapper testTaskMapper; @Autowired private TestPlanService testPlanService; @Autowired private DeviceTestTaskService deviceTestTaskService; @Autowired private GlobalVarService globalVarService; @Autowired private ActionService actionService; @Lazy @Autowired private ActionProcessor actionProcessor; @Autowired private ProjectService projectService; @Autowired private EnvironmentService environmentService; @Autowired private PageService pageService; @Autowired private UserService userService; @Autowired private TestSuiteService testSuiteService; @Autowired private BrowserService browserService; @Autowired private MobileService mobileService; /** * 提交测试任务 * * @return */ @Transactional public void commit(Integer testPlanId, Integer commitorUid) { if (testPlanId == null || commitorUid == null) { throw new ServerException("testPlanId or commitorUid 不能为空"); } TestPlan testPlan = testPlanService.getTestPlanById(testPlanId); if (testPlan == null) { throw new ServerException("测试计划不存在"); } // 待测试的测试用例 List<Integer> testcaseIds = testSuiteService.getTestSuitesByIds(testPlan.getTestSuites()).stream() .flatMap(testSuite -> testSuite.getTestcases().stream()) .distinct().collect(Collectors.toList()); // 过滤出已发布的用例 List<Action> testcases = actionService.getActionsByIds(testcaseIds).stream() .filter(action -> action.getState() == Action.RELEASE_STATE).collect(Collectors.toList()); if (CollectionUtils.isEmpty(testcases)) { throw new ServerException("测试集内没有已发布的测试用例"); } testcaseIds = testcases.stream().map(Action::getId).collect(Collectors.toList()); // 检查testcase依赖的testcase是否存在 for (Action testcase : testcases) { List<Integer> depends = testcase.getDepends(); if (!CollectionUtils.isEmpty(depends) && !testcaseIds.containsAll(depends)) { throw new ServerException("测试用例: " + testcase.getName() + ", 依赖的用例不在当前提测的所有用例中"); } } // 前置后置action List<Integer> beforeAndAfterActionIds = Stream.of(testPlan.getBeforeClass(), testPlan.getBeforeMethod(), testPlan.getAfterClass(), testPlan.getAfterMethod()) .filter(Objects::nonNull).distinct().collect(Collectors.toList()); Map<Integer, Action> beforeAndAfterActionMap = actionService.getActionsByIds(beforeAndAfterActionIds).stream() .collect(Collectors.toMap(Action::getId, Function.identity())); // 待处理的所有action List<Action> actions = new ArrayList<>(testcases); actions.addAll(beforeAndAfterActionMap.values()); actionProcessor.process(actions, testPlan.getEnvironmentId()); // 保存测试任务 TestTask testTask = saveTestTask(testPlan, commitorUid); List<GlobalVar> globalVars = globalVarService.getGlobalVarsByProjectIdAndEnv(testTask.getProjectId(), testPlan.getEnvironmentId()); List<com.daxiang.mbg.po.Page> pages = pageService.getPagesWithoutWindowHierarchyByProjectId(testTask.getProjectId()); Project project = projectService.getProjectById(testTask.getProjectId()); // 根据不同用例分发策略,给device分配用例 Map<String, List<Action>> deviceTestcasesMap = allocateTestcaseToDevice(testPlan.getDeviceIds(), testcases, testPlan.getRunMode()); Map<String, JSONObject> deviceMap = new HashMap<>(); Set<String> deviceIds = deviceTestcasesMap.keySet(); if (project.getPlatform() == Project.PC_WEB_PLATFORM) { // browser Map<String, Browser> browserMap = browserService.getBrowserMapByBrowserIds(deviceIds); browserMap.forEach((browserId, browser) -> deviceMap.put(browserId, (JSONObject) JSONObject.toJSON(browser))); } else { // mobile Map<String, Mobile> mobileMap = mobileService.getMobileMapByIds(deviceIds); mobileMap.forEach((mobileId, mobile) -> deviceMap.put(mobileId, (JSONObject) JSONObject.toJSON(mobile))); } // todo 批量保存 deviceTestcasesMap.forEach((deviceId, actionList) -> { DeviceTestTask deviceTestTask = new DeviceTestTask(); deviceTestTask.setProjectId(testTask.getProjectId()); deviceTestTask.setPlatform(project.getPlatform()); deviceTestTask.setCapabilities(project.getCapabilities()); deviceTestTask.setTestTaskId(testTask.getId()); deviceTestTask.setTestPlan(testPlan); deviceTestTask.setDeviceId(deviceId); deviceTestTask.setDevice(deviceMap.get(deviceId)); deviceTestTask.setGlobalVars(globalVars); deviceTestTask.setPages(pages); if (testPlan.getBeforeClass() != null) { deviceTestTask.setBeforeClass(beforeAndAfterActionMap.get(testPlan.getBeforeClass())); } if (testPlan.getBeforeMethod() != null) { deviceTestTask.setBeforeMethod(beforeAndAfterActionMap.get(testPlan.getBeforeMethod())); } if (testPlan.getAfterClass() != null) { deviceTestTask.setAfterClass(beforeAndAfterActionMap.get(testPlan.getAfterClass())); } if (testPlan.getAfterMethod() != null) { deviceTestTask.setAfterMethod(beforeAndAfterActionMap.get(testPlan.getAfterMethod())); } List<Testcase> cases = actionList.stream().map(action -> { Testcase testcase = new Testcase(); BeanUtils.copyProperties(action, testcase); return testcase; }).collect(Collectors.toList()); deviceTestTask.setTestcases(cases); deviceTestTask.setStatus(DeviceTestTask.UNSTART_STATUS); deviceTestTaskService.add(deviceTestTask); }); } /** * 给device分配测试用例 * * @param deviceIds * @param testcases * @param runMode * @return */ private Map<String, List<Action>> allocateTestcaseToDevice(List<String> deviceIds, List<Action> testcases, Integer runMode) { Map<String, List<Action>> result = new HashMap<>(); // deviceId : List<Action> if (runMode == TestPlan.RUN_MODE_COMPATIBLE) { // 兼容模式:所有device都运行同一份用例 result = deviceIds.stream().collect(Collectors.toMap(Function.identity(), v -> testcases)); } else if (runMode == TestPlan.RUN_MODE_EFFICIENCY) { // 高效模式:平均分配用例给device int i = 0; // 分配到第几个device for (Action testcase : testcases) { String deviceId = deviceIds.get(i); List<Action> actions = result.computeIfAbsent(deviceId, k -> new ArrayList<>()); actions.add(testcase); i++; // 分配完最后一个device,再从第一个device开始分配 if (i == deviceIds.size()) { i = 0; } } } return result; } private TestTask saveTestTask(TestPlan testPlan, Integer commitorUid) { TestTask testTask = new TestTask(); testTask.setProjectId(testPlan.getProjectId()); testTask.setTestPlanId(testPlan.getId()); testTask.setTestPlan(testPlan); testTask.setStatus(TestTask.UNFINISHED_STATUS); testTask.setCreatorUid(commitorUid); testTask.setCommitTime(new Date()); int insertRow = testTaskMapper.insertSelective(testTask); if (insertRow != 1) { throw new ServerException("保存TestTask失败"); } return testTask; } public PagedData<TestTaskVo> list(TestTask query, String orderBy, PageRequest pageRequest) { Page page = PageHelper.startPage(pageRequest.getPageNum(), pageRequest.getPageSize()); if (StringUtils.isEmpty(orderBy)) { orderBy = "commit_time desc"; } List<TestTaskVo> testTaskVos = getTestTaskVos(query, orderBy); return new PagedData<>(testTaskVos, page.getTotal()); } private List<TestTaskVo> convertTestTasksToTestTaskVos(List<TestTask> testTasks) { if (CollectionUtils.isEmpty(testTasks)) { return new ArrayList<>(); } List<Integer> creatorUids = testTasks.stream() .map(TestTask::getCreatorUid) .filter(Objects::nonNull) .distinct() .collect(Collectors.toList()); Map<Integer, User> userMap = userService.getUserMapByIds(creatorUids); List<TestTaskVo> testTaskVos = testTasks.stream().map(testTask -> { TestTaskVo testTaskVo = new TestTaskVo(); BeanUtils.copyProperties(testTask, testTaskVo); if (testTask.getCreatorUid() != null) { User user = userMap.get(testTask.getCreatorUid()); if (user != null) { testTaskVo.setCreatorNickName(user.getNickName()); } } return testTaskVo; }).collect(Collectors.toList()); return testTaskVos; } public List<TestTaskVo> getTestTaskVos(TestTask query, String orderBy) { List<TestTask> testTasks = getTestTasks(query, orderBy); return convertTestTasksToTestTaskVos(testTasks); } public List<TestTask> getTestTasks(TestTask query) { return getTestTasks(query, null); } public List<TestTask> getTestTasks(TestTask query, String orderBy) { TestTaskExample example = new TestTaskExample(); if (query != null) { TestTaskExample.Criteria criteria = example.createCriteria(); if (query.getId() != null) { criteria.andIdEqualTo(query.getId()); } if (query.getProjectId() != null) { criteria.andProjectIdEqualTo(query.getProjectId()); } if (query.getTestPlanId() != null) { criteria.andTestPlanIdEqualTo(query.getTestPlanId()); } if (query.getStatus() != null) { criteria.andStatusEqualTo(query.getStatus()); } } if (!StringUtils.isEmpty(orderBy)) { example.setOrderByClause(orderBy); } return testTaskMapper.selectByExampleWithBLOBs(example); } public List<TestTask> getUnFinishedTestTasks() { TestTask query = new TestTask(); query.setStatus(TestTask.UNFINISHED_STATUS); return getTestTasks(query); } public void update(TestTask testTask) { int updateCount = testTaskMapper.updateByPrimaryKeySelective(testTask); if (updateCount != 1) { throw new ServerException("更新失败"); } } public TestTaskSummary getTestTaskSummary(Integer testTaskId) { if (testTaskId == null) { throw new ServerException("testTaskId不能为空"); } TestTask testTask = testTaskMapper.selectByPrimaryKey(testTaskId); if (testTask == null) { throw new ServerException("测试任务不存在"); } Project project = projectService.getProjectById(testTask.getProjectId()); if (project == null) { throw new ServerException("项目不存在"); } TestTaskSummary summary = new TestTaskSummary(); BeanUtils.copyProperties(testTask, summary); summary.setPlatform(project.getPlatform()); summary.setProjectName(project.getName()); User user = userService.getUserById(testTask.getCreatorUid()); if (user != null) { summary.setCommitorNickName(user.getNickName()); } Integer passCaseCount = testTask.getPassCaseCount(); Integer totalCaseCount = testTask.getPassCaseCount() + testTask.getFailCaseCount() + testTask.getSkipCaseCount(); NumberFormat numberFormat = NumberFormat.getInstance(); numberFormat.setMaximumFractionDigits(2); // 精确到小数点2位 String passPercent = numberFormat.format(passCaseCount.floatValue() * 100 / totalCaseCount) + "%"; summary.setPassPercent(passPercent); if (testTask.getTestPlan() != null) { Integer envId = testTask.getTestPlan().getEnvironmentId(); String envName = environmentService.getEnvironmentNameById(envId); summary.setEnvironmentName(envName); } return summary; } @Transactional public void deleteAndClearRelatedRes(Integer testTaskId) { if (testTaskId == null) { throw new ServerException("testTaskId不能为空"); } TestTask testTask = testTaskMapper.selectByPrimaryKey(testTaskId); if (testTask == null) { throw new ServerException("testTask不存在"); } List<DeviceTestTask> deviceTestTasks = deviceTestTaskService.getDeviceTestTasksByTestTaskId(testTaskId); if (!CollectionUtils.isEmpty(deviceTestTasks)) { List<DeviceTestTask> deviceTestTasksInRunning = deviceTestTasks.stream() .filter(deviceTestTask -> deviceTestTask.getStatus() == DeviceTestTask.RUNNING_STATUS) .collect(Collectors.toList()); if (!CollectionUtils.isEmpty(deviceTestTasksInRunning)) { // 有device还在运行,不让删除testTask String deviceIdsInRunning = deviceTestTasksInRunning.stream() .map(DeviceTestTask::getDeviceId).collect(Collectors.joining("、")); throw new ServerException(deviceIdsInRunning + ",正在运行,无法删除"); } else { // 批量删除deviceTestTask List<Integer> deviceTestTaskIds = deviceTestTasks.stream().map(DeviceTestTask::getId).collect(Collectors.toList()); deviceTestTaskService.deleteBatch(deviceTestTaskIds); } } int deleteCount = testTaskMapper.deleteByPrimaryKey(testTaskId); if (deleteCount != 1) { throw new ServerException("删除失败,请稍后重试"); } if (!CollectionUtils.isEmpty(deviceTestTasks)) { deviceTestTasks.forEach(deviceTestTask -> deviceTestTaskService.clearRelatedRes(deviceTestTask)); } } } <|start_filename|>src/main/java/com/daxiang/controller/ProjectController.java<|end_filename|> package com.daxiang.controller; import com.daxiang.model.PageRequest; import com.daxiang.model.PagedData; import com.daxiang.model.Response; import com.daxiang.model.vo.ProjectVo; import com.daxiang.service.ProjectService; import com.daxiang.mbg.po.Project; import com.daxiang.validator.group.UpdateGroup; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; import java.util.List; /** * Created by jiangyitao. */ @RestController @RequestMapping("/project") @Slf4j public class ProjectController { @Autowired private ProjectService projectService; @PostMapping("/add") public Response add(@Valid @RequestBody Project project) { projectService.add(project); return Response.success("添加成功"); } @DeleteMapping("/{projectId}") public Response delete(@PathVariable Integer projectId) { projectService.delete(projectId); return Response.success("删除成功"); } @PostMapping("/update") public Response update(@Validated({UpdateGroup.class}) @RequestBody Project project) { projectService.update(project); return Response.success("更新成功"); } @PostMapping("/list") public Response list(Project query, String orderBy, PageRequest pageRequest) { if (pageRequest.needPaging()) { PagedData<ProjectVo> pagedData = projectService.list(query, orderBy, pageRequest); return Response.success(pagedData); } else { List<ProjectVo> projectVos = projectService.getProjectVos(query, orderBy); return Response.success(projectVos); } } } <|start_filename|>src/main/java/com/daxiang/utils/HttpServletUtil.java<|end_filename|> package com.daxiang.utils; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import javax.servlet.http.HttpServletRequest; /** * Created by jiangyitao. */ public class HttpServletUtil { public static HttpServletRequest getCurrentHttpServletRequest() { ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes(); return attributes.getRequest(); } /** * 获取静态资源下载的baseUrl * * @return baseUrl 如:http://192.168.8.8:8887/ */ public static StringBuilder getStaticResourceBaseUrl() { HttpServletRequest request = getCurrentHttpServletRequest(); return new StringBuilder() .append(request.getScheme()) .append("://") .append(request.getServerName()) .append(":") .append(request.getServerPort()) .append("/"); } public static String getStaticResourceUrl(String filePath) { return getStaticResourceBaseUrl().append(filePath).toString(); } } <|start_filename|>src/main/java/com/daxiang/service/RoleService.java<|end_filename|> package com.daxiang.service; import com.daxiang.mbg.mapper.RoleMapper; import com.daxiang.mbg.po.Role; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; /** * Created by jiangyitao. */ @Service public class RoleService { @Autowired private RoleMapper roleMapper; public List<Role> list() { return roleMapper.selectByExample(null); } } <|start_filename|>src/main/java/com/daxiang/mbg/po/Browser.java<|end_filename|> package com.daxiang.mbg.po; import com.fasterxml.jackson.annotation.JsonFormat; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; import java.io.Serializable; import java.util.Date; public class Browser implements Serializable { public static final int OFFLINE_STATUS = 0; public static final int USING_STATUS = 1; public static final int IDLE_STATUS = 2; /** * 浏览器id * * @mbg.generated */ @NotBlank(message = "浏览器id不能为空") private String id; /** * 类型: chrome firefox ... * * @mbg.generated */ @NotBlank(message = "浏览器type不能为空") private String type; /** * 版本号 * * @mbg.generated */ @NotBlank(message = "浏览器version不能为空") private String version; /** * 平台: 1. windows 2.linux 3.macos * * @mbg.generated */ @NotNull(message = "浏览器所在platform不能为空") private Integer platform; /** * 状态:0.离线 1.使用中 2.空闲 * * @mbg.generated */ private Integer status; /** * 浏览器所在的agent的ip * * @mbg.generated */ private String agentIp; /** * 浏览器所在的agent的端口 * * @mbg.generated */ private Integer agentPort; /** * 最近一次在线时间 * * @mbg.generated */ @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") private Date lastOnlineTime; /** * 最近一次使用人 * * @mbg.generated */ private String username; /** * 创建时间 * * @mbg.generated */ @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") private Date createTime; private static final long serialVersionUID = 1L; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public Integer getPlatform() { return platform; } public void setPlatform(Integer platform) { this.platform = platform; } public Integer getStatus() { return status; } public void setStatus(Integer status) { this.status = status; } public String getAgentIp() { return agentIp; } public void setAgentIp(String agentIp) { this.agentIp = agentIp; } public Integer getAgentPort() { return agentPort; } public void setAgentPort(Integer agentPort) { this.agentPort = agentPort; } public Date getLastOnlineTime() { return lastOnlineTime; } public void setLastOnlineTime(Date lastOnlineTime) { this.lastOnlineTime = lastOnlineTime; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", type=").append(type); sb.append(", version=").append(version); sb.append(", platform=").append(platform); sb.append(", status=").append(status); sb.append(", agentIp=").append(agentIp); sb.append(", agentPort=").append(agentPort); sb.append(", lastOnlineTime=").append(lastOnlineTime); sb.append(", username=").append(username); sb.append(", createTime=").append(createTime); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } } <|start_filename|>src/main/java/com/daxiang/init/StartupRunner.java<|end_filename|> package com.daxiang.init; import com.daxiang.service.FileService; import com.daxiang.service.TestPlanService; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; import org.springframework.stereotype.Component; /** * Created by jiangyitao. */ @Component @Slf4j public class StartupRunner implements ApplicationRunner { @Autowired private TestPlanService testPlanService; @Autowired private FileService fileService; @Override public void run(ApplicationArguments args) { fileService.mkUploadDirIfNotExists(); // 启动server时,按cron表达式执行所有开启的定时任务 testPlanService.scheduleEnabledTasks(); } } <|start_filename|>src/main/java/com/daxiang/mbg/po/DeviceTestTask.java<|end_filename|> package com.daxiang.mbg.po; import com.alibaba.fastjson.JSONObject; import com.daxiang.mbg.po.GlobalVar; import com.daxiang.mbg.po.Page; import com.daxiang.model.dto.Testcase; import com.daxiang.validator.group.UpdateGroup; import javax.validation.constraints.NotNull; import java.io.Serializable; import java.util.Date; import java.util.List; public class DeviceTestTask implements Serializable { /** 出错,无法运行 */ public static final int ERROR_STATUS = -1; /** 未开始 */ public static final int UNSTART_STATUS = 0; /** 运行中 */ public static final int RUNNING_STATUS = 1; /** 完成 */ public static final int FINISHED_STATUS = 2; @NotNull(message = "id不能为空", groups = {UpdateGroup.class}) private Integer id; /** * 项目id * * @mbg.generated */ private Integer projectId; /** * 平台 * * @mbg.generated */ private Integer platform; /** * 测试任务id * * @mbg.generated */ private Integer testTaskId; /** * deviceId * * @mbg.generated */ private String deviceId; /** * 状态:-1:无法运行 0:未开始 1:运行中 2:已完成 * * @mbg.generated */ private Integer status; /** * 开始测试时间 * * @mbg.generated */ private Date startTime; /** * 结束测试时间 * * @mbg.generated */ private Date endTime; /** * org.openqa.selenium.Capabilities * * @mbg.generated */ private String capabilities; /** * 下发任务时的testplan * * @mbg.generated */ private TestPlan testPlan; /** * 下发任务时的device * * @mbg.generated */ private JSONObject device; /** * 全局变量 * * @mbg.generated */ private java.util.List<GlobalVar> globalVars; /** * pages * * @mbg.generated */ private java.util.List<Page> pages; /** * BeforeClass * * @mbg.generated */ private Action beforeClass; /** * BeforeMethod * * @mbg.generated */ private Action beforeMethod; /** * AfterClass * * @mbg.generated */ private Action afterClass; /** * AfterMethod * * @mbg.generated */ private Action afterMethod; /** * 执行的测试用例 * * @mbg.generated */ private java.util.List<com.daxiang.model.dto.Testcase> testcases; /** * agent转换后的代码 * * @mbg.generated */ private String code; /** * status: -1, 错误信息 * * @mbg.generated */ private String errMsg; private static final long serialVersionUID = 1L; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Integer getProjectId() { return projectId; } public void setProjectId(Integer projectId) { this.projectId = projectId; } public Integer getPlatform() { return platform; } public void setPlatform(Integer platform) { this.platform = platform; } public Integer getTestTaskId() { return testTaskId; } public void setTestTaskId(Integer testTaskId) { this.testTaskId = testTaskId; } public String getDeviceId() { return deviceId; } public void setDeviceId(String deviceId) { this.deviceId = deviceId; } public Integer getStatus() { return status; } public void setStatus(Integer status) { this.status = status; } public Date getStartTime() { return startTime; } public void setStartTime(Date startTime) { this.startTime = startTime; } public Date getEndTime() { return endTime; } public void setEndTime(Date endTime) { this.endTime = endTime; } public String getCapabilities() { return capabilities; } public void setCapabilities(String capabilities) { this.capabilities = capabilities; } public TestPlan getTestPlan() { return testPlan; } public void setTestPlan(TestPlan testPlan) { this.testPlan = testPlan; } public JSONObject getDevice() { return device; } public void setDevice(JSONObject device) { this.device = device; } public java.util.List<GlobalVar> getGlobalVars() { return globalVars; } public void setGlobalVars(java.util.List<GlobalVar> globalVars) { this.globalVars = globalVars; } public java.util.List<Page> getPages() { return pages; } public void setPages(java.util.List<Page> pages) { this.pages = pages; } public Action getBeforeClass() { return beforeClass; } public void setBeforeClass(Action beforeClass) { this.beforeClass = beforeClass; } public Action getBeforeMethod() { return beforeMethod; } public void setBeforeMethod(Action beforeMethod) { this.beforeMethod = beforeMethod; } public Action getAfterClass() { return afterClass; } public void setAfterClass(Action afterClass) { this.afterClass = afterClass; } public Action getAfterMethod() { return afterMethod; } public void setAfterMethod(Action afterMethod) { this.afterMethod = afterMethod; } public java.util.List<com.daxiang.model.dto.Testcase> getTestcases() { return testcases; } public void setTestcases(java.util.List<com.daxiang.model.dto.Testcase> testcases) { this.testcases = testcases; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getErrMsg() { return errMsg; } public void setErrMsg(String errMsg) { this.errMsg = errMsg; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", projectId=").append(projectId); sb.append(", platform=").append(platform); sb.append(", testTaskId=").append(testTaskId); sb.append(", deviceId=").append(deviceId); sb.append(", status=").append(status); sb.append(", startTime=").append(startTime); sb.append(", endTime=").append(endTime); sb.append(", capabilities=").append(capabilities); sb.append(", testPlan=").append(testPlan); sb.append(", device=").append(device); sb.append(", globalVars=").append(globalVars); sb.append(", pages=").append(pages); sb.append(", beforeClass=").append(beforeClass); sb.append(", beforeMethod=").append(beforeMethod); sb.append(", afterClass=").append(afterClass); sb.append(", afterMethod=").append(afterMethod); sb.append(", testcases=").append(testcases); sb.append(", code=").append(code); sb.append(", errMsg=").append(errMsg); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } } <|start_filename|>src/main/java/com/daxiang/typehandler/JSONObjectTypeHandler.java<|end_filename|> package com.daxiang.typehandler; import com.alibaba.fastjson.JSONObject; import org.apache.ibatis.type.BaseTypeHandler; import org.apache.ibatis.type.JdbcType; import java.sql.CallableStatement; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; /** * Created by jiangyitao. */ public class JSONObjectTypeHandler extends BaseTypeHandler<JSONObject> { @Override public void setNonNullParameter(PreparedStatement preparedStatement, int i, JSONObject jsonObject, JdbcType jdbcType) throws SQLException { preparedStatement.setString(i, jsonObject.toJSONString()); } @Override public JSONObject getNullableResult(ResultSet resultSet, String s) throws SQLException { return JSONObject.parseObject(resultSet.getString(s)); } @Override public JSONObject getNullableResult(ResultSet resultSet, int i) throws SQLException { return JSONObject.parseObject(resultSet.getString(i)); } @Override public JSONObject getNullableResult(CallableStatement callableStatement, int i) throws SQLException { return JSONObject.parseObject(callableStatement.getString(i)); } } <|start_filename|>src/main/java/com/daxiang/mbg/po/TestTaskExample.java<|end_filename|> package com.daxiang.mbg.po; import java.util.ArrayList; import java.util.Date; import java.util.List; public class TestTaskExample { protected String orderByClause; protected boolean distinct; protected List<Criteria> oredCriteria; public TestTaskExample() { oredCriteria = new ArrayList<Criteria>(); } public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } public String getOrderByClause() { return orderByClause; } public void setDistinct(boolean distinct) { this.distinct = distinct; } public boolean isDistinct() { return distinct; } public List<Criteria> getOredCriteria() { return oredCriteria; } public void or(Criteria criteria) { oredCriteria.add(criteria); } public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } protected abstract static class GeneratedCriteria { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andIdIsNull() { addCriterion("id is null"); return (Criteria) this; } public Criteria andIdIsNotNull() { addCriterion("id is not null"); return (Criteria) this; } public Criteria andIdEqualTo(Integer value) { addCriterion("id =", value, "id"); return (Criteria) this; } public Criteria andIdNotEqualTo(Integer value) { addCriterion("id <>", value, "id"); return (Criteria) this; } public Criteria andIdGreaterThan(Integer value) { addCriterion("id >", value, "id"); return (Criteria) this; } public Criteria andIdGreaterThanOrEqualTo(Integer value) { addCriterion("id >=", value, "id"); return (Criteria) this; } public Criteria andIdLessThan(Integer value) { addCriterion("id <", value, "id"); return (Criteria) this; } public Criteria andIdLessThanOrEqualTo(Integer value) { addCriterion("id <=", value, "id"); return (Criteria) this; } public Criteria andIdIn(List<Integer> values) { addCriterion("id in", values, "id"); return (Criteria) this; } public Criteria andIdNotIn(List<Integer> values) { addCriterion("id not in", values, "id"); return (Criteria) this; } public Criteria andIdBetween(Integer value1, Integer value2) { addCriterion("id between", value1, value2, "id"); return (Criteria) this; } public Criteria andIdNotBetween(Integer value1, Integer value2) { addCriterion("id not between", value1, value2, "id"); return (Criteria) this; } public Criteria andProjectIdIsNull() { addCriterion("project_id is null"); return (Criteria) this; } public Criteria andProjectIdIsNotNull() { addCriterion("project_id is not null"); return (Criteria) this; } public Criteria andProjectIdEqualTo(Integer value) { addCriterion("project_id =", value, "projectId"); return (Criteria) this; } public Criteria andProjectIdNotEqualTo(Integer value) { addCriterion("project_id <>", value, "projectId"); return (Criteria) this; } public Criteria andProjectIdGreaterThan(Integer value) { addCriterion("project_id >", value, "projectId"); return (Criteria) this; } public Criteria andProjectIdGreaterThanOrEqualTo(Integer value) { addCriterion("project_id >=", value, "projectId"); return (Criteria) this; } public Criteria andProjectIdLessThan(Integer value) { addCriterion("project_id <", value, "projectId"); return (Criteria) this; } public Criteria andProjectIdLessThanOrEqualTo(Integer value) { addCriterion("project_id <=", value, "projectId"); return (Criteria) this; } public Criteria andProjectIdIn(List<Integer> values) { addCriterion("project_id in", values, "projectId"); return (Criteria) this; } public Criteria andProjectIdNotIn(List<Integer> values) { addCriterion("project_id not in", values, "projectId"); return (Criteria) this; } public Criteria andProjectIdBetween(Integer value1, Integer value2) { addCriterion("project_id between", value1, value2, "projectId"); return (Criteria) this; } public Criteria andProjectIdNotBetween(Integer value1, Integer value2) { addCriterion("project_id not between", value1, value2, "projectId"); return (Criteria) this; } public Criteria andTestPlanIdIsNull() { addCriterion("test_plan_id is null"); return (Criteria) this; } public Criteria andTestPlanIdIsNotNull() { addCriterion("test_plan_id is not null"); return (Criteria) this; } public Criteria andTestPlanIdEqualTo(Integer value) { addCriterion("test_plan_id =", value, "testPlanId"); return (Criteria) this; } public Criteria andTestPlanIdNotEqualTo(Integer value) { addCriterion("test_plan_id <>", value, "testPlanId"); return (Criteria) this; } public Criteria andTestPlanIdGreaterThan(Integer value) { addCriterion("test_plan_id >", value, "testPlanId"); return (Criteria) this; } public Criteria andTestPlanIdGreaterThanOrEqualTo(Integer value) { addCriterion("test_plan_id >=", value, "testPlanId"); return (Criteria) this; } public Criteria andTestPlanIdLessThan(Integer value) { addCriterion("test_plan_id <", value, "testPlanId"); return (Criteria) this; } public Criteria andTestPlanIdLessThanOrEqualTo(Integer value) { addCriterion("test_plan_id <=", value, "testPlanId"); return (Criteria) this; } public Criteria andTestPlanIdIn(List<Integer> values) { addCriterion("test_plan_id in", values, "testPlanId"); return (Criteria) this; } public Criteria andTestPlanIdNotIn(List<Integer> values) { addCriterion("test_plan_id not in", values, "testPlanId"); return (Criteria) this; } public Criteria andTestPlanIdBetween(Integer value1, Integer value2) { addCriterion("test_plan_id between", value1, value2, "testPlanId"); return (Criteria) this; } public Criteria andTestPlanIdNotBetween(Integer value1, Integer value2) { addCriterion("test_plan_id not between", value1, value2, "testPlanId"); return (Criteria) this; } public Criteria andStatusIsNull() { addCriterion("status is null"); return (Criteria) this; } public Criteria andStatusIsNotNull() { addCriterion("status is not null"); return (Criteria) this; } public Criteria andStatusEqualTo(Integer value) { addCriterion("status =", value, "status"); return (Criteria) this; } public Criteria andStatusNotEqualTo(Integer value) { addCriterion("status <>", value, "status"); return (Criteria) this; } public Criteria andStatusGreaterThan(Integer value) { addCriterion("status >", value, "status"); return (Criteria) this; } public Criteria andStatusGreaterThanOrEqualTo(Integer value) { addCriterion("status >=", value, "status"); return (Criteria) this; } public Criteria andStatusLessThan(Integer value) { addCriterion("status <", value, "status"); return (Criteria) this; } public Criteria andStatusLessThanOrEqualTo(Integer value) { addCriterion("status <=", value, "status"); return (Criteria) this; } public Criteria andStatusIn(List<Integer> values) { addCriterion("status in", values, "status"); return (Criteria) this; } public Criteria andStatusNotIn(List<Integer> values) { addCriterion("status not in", values, "status"); return (Criteria) this; } public Criteria andStatusBetween(Integer value1, Integer value2) { addCriterion("status between", value1, value2, "status"); return (Criteria) this; } public Criteria andStatusNotBetween(Integer value1, Integer value2) { addCriterion("status not between", value1, value2, "status"); return (Criteria) this; } public Criteria andCreatorUidIsNull() { addCriterion("creator_uid is null"); return (Criteria) this; } public Criteria andCreatorUidIsNotNull() { addCriterion("creator_uid is not null"); return (Criteria) this; } public Criteria andCreatorUidEqualTo(Integer value) { addCriterion("creator_uid =", value, "creatorUid"); return (Criteria) this; } public Criteria andCreatorUidNotEqualTo(Integer value) { addCriterion("creator_uid <>", value, "creatorUid"); return (Criteria) this; } public Criteria andCreatorUidGreaterThan(Integer value) { addCriterion("creator_uid >", value, "creatorUid"); return (Criteria) this; } public Criteria andCreatorUidGreaterThanOrEqualTo(Integer value) { addCriterion("creator_uid >=", value, "creatorUid"); return (Criteria) this; } public Criteria andCreatorUidLessThan(Integer value) { addCriterion("creator_uid <", value, "creatorUid"); return (Criteria) this; } public Criteria andCreatorUidLessThanOrEqualTo(Integer value) { addCriterion("creator_uid <=", value, "creatorUid"); return (Criteria) this; } public Criteria andCreatorUidIn(List<Integer> values) { addCriterion("creator_uid in", values, "creatorUid"); return (Criteria) this; } public Criteria andCreatorUidNotIn(List<Integer> values) { addCriterion("creator_uid not in", values, "creatorUid"); return (Criteria) this; } public Criteria andCreatorUidBetween(Integer value1, Integer value2) { addCriterion("creator_uid between", value1, value2, "creatorUid"); return (Criteria) this; } public Criteria andCreatorUidNotBetween(Integer value1, Integer value2) { addCriterion("creator_uid not between", value1, value2, "creatorUid"); return (Criteria) this; } public Criteria andPassCaseCountIsNull() { addCriterion("pass_case_count is null"); return (Criteria) this; } public Criteria andPassCaseCountIsNotNull() { addCriterion("pass_case_count is not null"); return (Criteria) this; } public Criteria andPassCaseCountEqualTo(Integer value) { addCriterion("pass_case_count =", value, "passCaseCount"); return (Criteria) this; } public Criteria andPassCaseCountNotEqualTo(Integer value) { addCriterion("pass_case_count <>", value, "passCaseCount"); return (Criteria) this; } public Criteria andPassCaseCountGreaterThan(Integer value) { addCriterion("pass_case_count >", value, "passCaseCount"); return (Criteria) this; } public Criteria andPassCaseCountGreaterThanOrEqualTo(Integer value) { addCriterion("pass_case_count >=", value, "passCaseCount"); return (Criteria) this; } public Criteria andPassCaseCountLessThan(Integer value) { addCriterion("pass_case_count <", value, "passCaseCount"); return (Criteria) this; } public Criteria andPassCaseCountLessThanOrEqualTo(Integer value) { addCriterion("pass_case_count <=", value, "passCaseCount"); return (Criteria) this; } public Criteria andPassCaseCountIn(List<Integer> values) { addCriterion("pass_case_count in", values, "passCaseCount"); return (Criteria) this; } public Criteria andPassCaseCountNotIn(List<Integer> values) { addCriterion("pass_case_count not in", values, "passCaseCount"); return (Criteria) this; } public Criteria andPassCaseCountBetween(Integer value1, Integer value2) { addCriterion("pass_case_count between", value1, value2, "passCaseCount"); return (Criteria) this; } public Criteria andPassCaseCountNotBetween(Integer value1, Integer value2) { addCriterion("pass_case_count not between", value1, value2, "passCaseCount"); return (Criteria) this; } public Criteria andFailCaseCountIsNull() { addCriterion("fail_case_count is null"); return (Criteria) this; } public Criteria andFailCaseCountIsNotNull() { addCriterion("fail_case_count is not null"); return (Criteria) this; } public Criteria andFailCaseCountEqualTo(Integer value) { addCriterion("fail_case_count =", value, "failCaseCount"); return (Criteria) this; } public Criteria andFailCaseCountNotEqualTo(Integer value) { addCriterion("fail_case_count <>", value, "failCaseCount"); return (Criteria) this; } public Criteria andFailCaseCountGreaterThan(Integer value) { addCriterion("fail_case_count >", value, "failCaseCount"); return (Criteria) this; } public Criteria andFailCaseCountGreaterThanOrEqualTo(Integer value) { addCriterion("fail_case_count >=", value, "failCaseCount"); return (Criteria) this; } public Criteria andFailCaseCountLessThan(Integer value) { addCriterion("fail_case_count <", value, "failCaseCount"); return (Criteria) this; } public Criteria andFailCaseCountLessThanOrEqualTo(Integer value) { addCriterion("fail_case_count <=", value, "failCaseCount"); return (Criteria) this; } public Criteria andFailCaseCountIn(List<Integer> values) { addCriterion("fail_case_count in", values, "failCaseCount"); return (Criteria) this; } public Criteria andFailCaseCountNotIn(List<Integer> values) { addCriterion("fail_case_count not in", values, "failCaseCount"); return (Criteria) this; } public Criteria andFailCaseCountBetween(Integer value1, Integer value2) { addCriterion("fail_case_count between", value1, value2, "failCaseCount"); return (Criteria) this; } public Criteria andFailCaseCountNotBetween(Integer value1, Integer value2) { addCriterion("fail_case_count not between", value1, value2, "failCaseCount"); return (Criteria) this; } public Criteria andSkipCaseCountIsNull() { addCriterion("skip_case_count is null"); return (Criteria) this; } public Criteria andSkipCaseCountIsNotNull() { addCriterion("skip_case_count is not null"); return (Criteria) this; } public Criteria andSkipCaseCountEqualTo(Integer value) { addCriterion("skip_case_count =", value, "skipCaseCount"); return (Criteria) this; } public Criteria andSkipCaseCountNotEqualTo(Integer value) { addCriterion("skip_case_count <>", value, "skipCaseCount"); return (Criteria) this; } public Criteria andSkipCaseCountGreaterThan(Integer value) { addCriterion("skip_case_count >", value, "skipCaseCount"); return (Criteria) this; } public Criteria andSkipCaseCountGreaterThanOrEqualTo(Integer value) { addCriterion("skip_case_count >=", value, "skipCaseCount"); return (Criteria) this; } public Criteria andSkipCaseCountLessThan(Integer value) { addCriterion("skip_case_count <", value, "skipCaseCount"); return (Criteria) this; } public Criteria andSkipCaseCountLessThanOrEqualTo(Integer value) { addCriterion("skip_case_count <=", value, "skipCaseCount"); return (Criteria) this; } public Criteria andSkipCaseCountIn(List<Integer> values) { addCriterion("skip_case_count in", values, "skipCaseCount"); return (Criteria) this; } public Criteria andSkipCaseCountNotIn(List<Integer> values) { addCriterion("skip_case_count not in", values, "skipCaseCount"); return (Criteria) this; } public Criteria andSkipCaseCountBetween(Integer value1, Integer value2) { addCriterion("skip_case_count between", value1, value2, "skipCaseCount"); return (Criteria) this; } public Criteria andSkipCaseCountNotBetween(Integer value1, Integer value2) { addCriterion("skip_case_count not between", value1, value2, "skipCaseCount"); return (Criteria) this; } public Criteria andCommitTimeIsNull() { addCriterion("commit_time is null"); return (Criteria) this; } public Criteria andCommitTimeIsNotNull() { addCriterion("commit_time is not null"); return (Criteria) this; } public Criteria andCommitTimeEqualTo(Date value) { addCriterion("commit_time =", value, "commitTime"); return (Criteria) this; } public Criteria andCommitTimeNotEqualTo(Date value) { addCriterion("commit_time <>", value, "commitTime"); return (Criteria) this; } public Criteria andCommitTimeGreaterThan(Date value) { addCriterion("commit_time >", value, "commitTime"); return (Criteria) this; } public Criteria andCommitTimeGreaterThanOrEqualTo(Date value) { addCriterion("commit_time >=", value, "commitTime"); return (Criteria) this; } public Criteria andCommitTimeLessThan(Date value) { addCriterion("commit_time <", value, "commitTime"); return (Criteria) this; } public Criteria andCommitTimeLessThanOrEqualTo(Date value) { addCriterion("commit_time <=", value, "commitTime"); return (Criteria) this; } public Criteria andCommitTimeIn(List<Date> values) { addCriterion("commit_time in", values, "commitTime"); return (Criteria) this; } public Criteria andCommitTimeNotIn(List<Date> values) { addCriterion("commit_time not in", values, "commitTime"); return (Criteria) this; } public Criteria andCommitTimeBetween(Date value1, Date value2) { addCriterion("commit_time between", value1, value2, "commitTime"); return (Criteria) this; } public Criteria andCommitTimeNotBetween(Date value1, Date value2) { addCriterion("commit_time not between", value1, value2, "commitTime"); return (Criteria) this; } public Criteria andFinishTimeIsNull() { addCriterion("finish_time is null"); return (Criteria) this; } public Criteria andFinishTimeIsNotNull() { addCriterion("finish_time is not null"); return (Criteria) this; } public Criteria andFinishTimeEqualTo(Date value) { addCriterion("finish_time =", value, "finishTime"); return (Criteria) this; } public Criteria andFinishTimeNotEqualTo(Date value) { addCriterion("finish_time <>", value, "finishTime"); return (Criteria) this; } public Criteria andFinishTimeGreaterThan(Date value) { addCriterion("finish_time >", value, "finishTime"); return (Criteria) this; } public Criteria andFinishTimeGreaterThanOrEqualTo(Date value) { addCriterion("finish_time >=", value, "finishTime"); return (Criteria) this; } public Criteria andFinishTimeLessThan(Date value) { addCriterion("finish_time <", value, "finishTime"); return (Criteria) this; } public Criteria andFinishTimeLessThanOrEqualTo(Date value) { addCriterion("finish_time <=", value, "finishTime"); return (Criteria) this; } public Criteria andFinishTimeIn(List<Date> values) { addCriterion("finish_time in", values, "finishTime"); return (Criteria) this; } public Criteria andFinishTimeNotIn(List<Date> values) { addCriterion("finish_time not in", values, "finishTime"); return (Criteria) this; } public Criteria andFinishTimeBetween(Date value1, Date value2) { addCriterion("finish_time between", value1, value2, "finishTime"); return (Criteria) this; } public Criteria andFinishTimeNotBetween(Date value1, Date value2) { addCriterion("finish_time not between", value1, value2, "finishTime"); return (Criteria) this; } } public static class Criteria extends GeneratedCriteria { protected Criteria() { super(); } } public static class Criterion { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } } <|start_filename|>src/main/java/com/daxiang/model/vo/PageVo.java<|end_filename|> package com.daxiang.model.vo; import com.daxiang.mbg.po.Page; import com.daxiang.utils.HttpServletUtil; import lombok.Data; import org.springframework.util.StringUtils; /** * Created by jiangyitao. */ @Data public class PageVo extends Page { private String creatorNickName = ""; private String imgUrl; public String getImgUrl() { if (!StringUtils.isEmpty(getImgPath())) return HttpServletUtil.getStaticResourceUrl(getImgPath()); return null; } } <|start_filename|>src/main/java/com/daxiang/mbg/po/TestPlanExample.java<|end_filename|> package com.daxiang.mbg.po; import java.util.ArrayList; import java.util.Date; import java.util.List; public class TestPlanExample { protected String orderByClause; protected boolean distinct; protected List<Criteria> oredCriteria; public TestPlanExample() { oredCriteria = new ArrayList<Criteria>(); } public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } public String getOrderByClause() { return orderByClause; } public void setDistinct(boolean distinct) { this.distinct = distinct; } public boolean isDistinct() { return distinct; } public List<Criteria> getOredCriteria() { return oredCriteria; } public void or(Criteria criteria) { oredCriteria.add(criteria); } public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } protected abstract static class GeneratedCriteria { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andIdIsNull() { addCriterion("id is null"); return (Criteria) this; } public Criteria andIdIsNotNull() { addCriterion("id is not null"); return (Criteria) this; } public Criteria andIdEqualTo(Integer value) { addCriterion("id =", value, "id"); return (Criteria) this; } public Criteria andIdNotEqualTo(Integer value) { addCriterion("id <>", value, "id"); return (Criteria) this; } public Criteria andIdGreaterThan(Integer value) { addCriterion("id >", value, "id"); return (Criteria) this; } public Criteria andIdGreaterThanOrEqualTo(Integer value) { addCriterion("id >=", value, "id"); return (Criteria) this; } public Criteria andIdLessThan(Integer value) { addCriterion("id <", value, "id"); return (Criteria) this; } public Criteria andIdLessThanOrEqualTo(Integer value) { addCriterion("id <=", value, "id"); return (Criteria) this; } public Criteria andIdIn(List<Integer> values) { addCriterion("id in", values, "id"); return (Criteria) this; } public Criteria andIdNotIn(List<Integer> values) { addCriterion("id not in", values, "id"); return (Criteria) this; } public Criteria andIdBetween(Integer value1, Integer value2) { addCriterion("id between", value1, value2, "id"); return (Criteria) this; } public Criteria andIdNotBetween(Integer value1, Integer value2) { addCriterion("id not between", value1, value2, "id"); return (Criteria) this; } public Criteria andNameIsNull() { addCriterion("name is null"); return (Criteria) this; } public Criteria andNameIsNotNull() { addCriterion("name is not null"); return (Criteria) this; } public Criteria andNameEqualTo(String value) { addCriterion("name =", value, "name"); return (Criteria) this; } public Criteria andNameNotEqualTo(String value) { addCriterion("name <>", value, "name"); return (Criteria) this; } public Criteria andNameGreaterThan(String value) { addCriterion("name >", value, "name"); return (Criteria) this; } public Criteria andNameGreaterThanOrEqualTo(String value) { addCriterion("name >=", value, "name"); return (Criteria) this; } public Criteria andNameLessThan(String value) { addCriterion("name <", value, "name"); return (Criteria) this; } public Criteria andNameLessThanOrEqualTo(String value) { addCriterion("name <=", value, "name"); return (Criteria) this; } public Criteria andNameLike(String value) { addCriterion("name like", value, "name"); return (Criteria) this; } public Criteria andNameNotLike(String value) { addCriterion("name not like", value, "name"); return (Criteria) this; } public Criteria andNameIn(List<String> values) { addCriterion("name in", values, "name"); return (Criteria) this; } public Criteria andNameNotIn(List<String> values) { addCriterion("name not in", values, "name"); return (Criteria) this; } public Criteria andNameBetween(String value1, String value2) { addCriterion("name between", value1, value2, "name"); return (Criteria) this; } public Criteria andNameNotBetween(String value1, String value2) { addCriterion("name not between", value1, value2, "name"); return (Criteria) this; } public Criteria andDescriptionIsNull() { addCriterion("description is null"); return (Criteria) this; } public Criteria andDescriptionIsNotNull() { addCriterion("description is not null"); return (Criteria) this; } public Criteria andDescriptionEqualTo(String value) { addCriterion("description =", value, "description"); return (Criteria) this; } public Criteria andDescriptionNotEqualTo(String value) { addCriterion("description <>", value, "description"); return (Criteria) this; } public Criteria andDescriptionGreaterThan(String value) { addCriterion("description >", value, "description"); return (Criteria) this; } public Criteria andDescriptionGreaterThanOrEqualTo(String value) { addCriterion("description >=", value, "description"); return (Criteria) this; } public Criteria andDescriptionLessThan(String value) { addCriterion("description <", value, "description"); return (Criteria) this; } public Criteria andDescriptionLessThanOrEqualTo(String value) { addCriterion("description <=", value, "description"); return (Criteria) this; } public Criteria andDescriptionLike(String value) { addCriterion("description like", value, "description"); return (Criteria) this; } public Criteria andDescriptionNotLike(String value) { addCriterion("description not like", value, "description"); return (Criteria) this; } public Criteria andDescriptionIn(List<String> values) { addCriterion("description in", values, "description"); return (Criteria) this; } public Criteria andDescriptionNotIn(List<String> values) { addCriterion("description not in", values, "description"); return (Criteria) this; } public Criteria andDescriptionBetween(String value1, String value2) { addCriterion("description between", value1, value2, "description"); return (Criteria) this; } public Criteria andDescriptionNotBetween(String value1, String value2) { addCriterion("description not between", value1, value2, "description"); return (Criteria) this; } public Criteria andProjectIdIsNull() { addCriterion("project_id is null"); return (Criteria) this; } public Criteria andProjectIdIsNotNull() { addCriterion("project_id is not null"); return (Criteria) this; } public Criteria andProjectIdEqualTo(Integer value) { addCriterion("project_id =", value, "projectId"); return (Criteria) this; } public Criteria andProjectIdNotEqualTo(Integer value) { addCriterion("project_id <>", value, "projectId"); return (Criteria) this; } public Criteria andProjectIdGreaterThan(Integer value) { addCriterion("project_id >", value, "projectId"); return (Criteria) this; } public Criteria andProjectIdGreaterThanOrEqualTo(Integer value) { addCriterion("project_id >=", value, "projectId"); return (Criteria) this; } public Criteria andProjectIdLessThan(Integer value) { addCriterion("project_id <", value, "projectId"); return (Criteria) this; } public Criteria andProjectIdLessThanOrEqualTo(Integer value) { addCriterion("project_id <=", value, "projectId"); return (Criteria) this; } public Criteria andProjectIdIn(List<Integer> values) { addCriterion("project_id in", values, "projectId"); return (Criteria) this; } public Criteria andProjectIdNotIn(List<Integer> values) { addCriterion("project_id not in", values, "projectId"); return (Criteria) this; } public Criteria andProjectIdBetween(Integer value1, Integer value2) { addCriterion("project_id between", value1, value2, "projectId"); return (Criteria) this; } public Criteria andProjectIdNotBetween(Integer value1, Integer value2) { addCriterion("project_id not between", value1, value2, "projectId"); return (Criteria) this; } public Criteria andEnvironmentIdIsNull() { addCriterion("environment_id is null"); return (Criteria) this; } public Criteria andEnvironmentIdIsNotNull() { addCriterion("environment_id is not null"); return (Criteria) this; } public Criteria andEnvironmentIdEqualTo(Integer value) { addCriterion("environment_id =", value, "environmentId"); return (Criteria) this; } public Criteria andEnvironmentIdNotEqualTo(Integer value) { addCriterion("environment_id <>", value, "environmentId"); return (Criteria) this; } public Criteria andEnvironmentIdGreaterThan(Integer value) { addCriterion("environment_id >", value, "environmentId"); return (Criteria) this; } public Criteria andEnvironmentIdGreaterThanOrEqualTo(Integer value) { addCriterion("environment_id >=", value, "environmentId"); return (Criteria) this; } public Criteria andEnvironmentIdLessThan(Integer value) { addCriterion("environment_id <", value, "environmentId"); return (Criteria) this; } public Criteria andEnvironmentIdLessThanOrEqualTo(Integer value) { addCriterion("environment_id <=", value, "environmentId"); return (Criteria) this; } public Criteria andEnvironmentIdIn(List<Integer> values) { addCriterion("environment_id in", values, "environmentId"); return (Criteria) this; } public Criteria andEnvironmentIdNotIn(List<Integer> values) { addCriterion("environment_id not in", values, "environmentId"); return (Criteria) this; } public Criteria andEnvironmentIdBetween(Integer value1, Integer value2) { addCriterion("environment_id between", value1, value2, "environmentId"); return (Criteria) this; } public Criteria andEnvironmentIdNotBetween(Integer value1, Integer value2) { addCriterion("environment_id not between", value1, value2, "environmentId"); return (Criteria) this; } public Criteria andBeforeClassIsNull() { addCriterion("before_class is null"); return (Criteria) this; } public Criteria andBeforeClassIsNotNull() { addCriterion("before_class is not null"); return (Criteria) this; } public Criteria andBeforeClassEqualTo(Integer value) { addCriterion("before_class =", value, "beforeClass"); return (Criteria) this; } public Criteria andBeforeClassNotEqualTo(Integer value) { addCriterion("before_class <>", value, "beforeClass"); return (Criteria) this; } public Criteria andBeforeClassGreaterThan(Integer value) { addCriterion("before_class >", value, "beforeClass"); return (Criteria) this; } public Criteria andBeforeClassGreaterThanOrEqualTo(Integer value) { addCriterion("before_class >=", value, "beforeClass"); return (Criteria) this; } public Criteria andBeforeClassLessThan(Integer value) { addCriterion("before_class <", value, "beforeClass"); return (Criteria) this; } public Criteria andBeforeClassLessThanOrEqualTo(Integer value) { addCriterion("before_class <=", value, "beforeClass"); return (Criteria) this; } public Criteria andBeforeClassIn(List<Integer> values) { addCriterion("before_class in", values, "beforeClass"); return (Criteria) this; } public Criteria andBeforeClassNotIn(List<Integer> values) { addCriterion("before_class not in", values, "beforeClass"); return (Criteria) this; } public Criteria andBeforeClassBetween(Integer value1, Integer value2) { addCriterion("before_class between", value1, value2, "beforeClass"); return (Criteria) this; } public Criteria andBeforeClassNotBetween(Integer value1, Integer value2) { addCriterion("before_class not between", value1, value2, "beforeClass"); return (Criteria) this; } public Criteria andBeforeMethodIsNull() { addCriterion("before_method is null"); return (Criteria) this; } public Criteria andBeforeMethodIsNotNull() { addCriterion("before_method is not null"); return (Criteria) this; } public Criteria andBeforeMethodEqualTo(Integer value) { addCriterion("before_method =", value, "beforeMethod"); return (Criteria) this; } public Criteria andBeforeMethodNotEqualTo(Integer value) { addCriterion("before_method <>", value, "beforeMethod"); return (Criteria) this; } public Criteria andBeforeMethodGreaterThan(Integer value) { addCriterion("before_method >", value, "beforeMethod"); return (Criteria) this; } public Criteria andBeforeMethodGreaterThanOrEqualTo(Integer value) { addCriterion("before_method >=", value, "beforeMethod"); return (Criteria) this; } public Criteria andBeforeMethodLessThan(Integer value) { addCriterion("before_method <", value, "beforeMethod"); return (Criteria) this; } public Criteria andBeforeMethodLessThanOrEqualTo(Integer value) { addCriterion("before_method <=", value, "beforeMethod"); return (Criteria) this; } public Criteria andBeforeMethodIn(List<Integer> values) { addCriterion("before_method in", values, "beforeMethod"); return (Criteria) this; } public Criteria andBeforeMethodNotIn(List<Integer> values) { addCriterion("before_method not in", values, "beforeMethod"); return (Criteria) this; } public Criteria andBeforeMethodBetween(Integer value1, Integer value2) { addCriterion("before_method between", value1, value2, "beforeMethod"); return (Criteria) this; } public Criteria andBeforeMethodNotBetween(Integer value1, Integer value2) { addCriterion("before_method not between", value1, value2, "beforeMethod"); return (Criteria) this; } public Criteria andAfterClassIsNull() { addCriterion("after_class is null"); return (Criteria) this; } public Criteria andAfterClassIsNotNull() { addCriterion("after_class is not null"); return (Criteria) this; } public Criteria andAfterClassEqualTo(Integer value) { addCriterion("after_class =", value, "afterClass"); return (Criteria) this; } public Criteria andAfterClassNotEqualTo(Integer value) { addCriterion("after_class <>", value, "afterClass"); return (Criteria) this; } public Criteria andAfterClassGreaterThan(Integer value) { addCriterion("after_class >", value, "afterClass"); return (Criteria) this; } public Criteria andAfterClassGreaterThanOrEqualTo(Integer value) { addCriterion("after_class >=", value, "afterClass"); return (Criteria) this; } public Criteria andAfterClassLessThan(Integer value) { addCriterion("after_class <", value, "afterClass"); return (Criteria) this; } public Criteria andAfterClassLessThanOrEqualTo(Integer value) { addCriterion("after_class <=", value, "afterClass"); return (Criteria) this; } public Criteria andAfterClassIn(List<Integer> values) { addCriterion("after_class in", values, "afterClass"); return (Criteria) this; } public Criteria andAfterClassNotIn(List<Integer> values) { addCriterion("after_class not in", values, "afterClass"); return (Criteria) this; } public Criteria andAfterClassBetween(Integer value1, Integer value2) { addCriterion("after_class between", value1, value2, "afterClass"); return (Criteria) this; } public Criteria andAfterClassNotBetween(Integer value1, Integer value2) { addCriterion("after_class not between", value1, value2, "afterClass"); return (Criteria) this; } public Criteria andAfterMethodIsNull() { addCriterion("after_method is null"); return (Criteria) this; } public Criteria andAfterMethodIsNotNull() { addCriterion("after_method is not null"); return (Criteria) this; } public Criteria andAfterMethodEqualTo(Integer value) { addCriterion("after_method =", value, "afterMethod"); return (Criteria) this; } public Criteria andAfterMethodNotEqualTo(Integer value) { addCriterion("after_method <>", value, "afterMethod"); return (Criteria) this; } public Criteria andAfterMethodGreaterThan(Integer value) { addCriterion("after_method >", value, "afterMethod"); return (Criteria) this; } public Criteria andAfterMethodGreaterThanOrEqualTo(Integer value) { addCriterion("after_method >=", value, "afterMethod"); return (Criteria) this; } public Criteria andAfterMethodLessThan(Integer value) { addCriterion("after_method <", value, "afterMethod"); return (Criteria) this; } public Criteria andAfterMethodLessThanOrEqualTo(Integer value) { addCriterion("after_method <=", value, "afterMethod"); return (Criteria) this; } public Criteria andAfterMethodIn(List<Integer> values) { addCriterion("after_method in", values, "afterMethod"); return (Criteria) this; } public Criteria andAfterMethodNotIn(List<Integer> values) { addCriterion("after_method not in", values, "afterMethod"); return (Criteria) this; } public Criteria andAfterMethodBetween(Integer value1, Integer value2) { addCriterion("after_method between", value1, value2, "afterMethod"); return (Criteria) this; } public Criteria andAfterMethodNotBetween(Integer value1, Integer value2) { addCriterion("after_method not between", value1, value2, "afterMethod"); return (Criteria) this; } public Criteria andRunModeIsNull() { addCriterion("run_mode is null"); return (Criteria) this; } public Criteria andRunModeIsNotNull() { addCriterion("run_mode is not null"); return (Criteria) this; } public Criteria andRunModeEqualTo(Integer value) { addCriterion("run_mode =", value, "runMode"); return (Criteria) this; } public Criteria andRunModeNotEqualTo(Integer value) { addCriterion("run_mode <>", value, "runMode"); return (Criteria) this; } public Criteria andRunModeGreaterThan(Integer value) { addCriterion("run_mode >", value, "runMode"); return (Criteria) this; } public Criteria andRunModeGreaterThanOrEqualTo(Integer value) { addCriterion("run_mode >=", value, "runMode"); return (Criteria) this; } public Criteria andRunModeLessThan(Integer value) { addCriterion("run_mode <", value, "runMode"); return (Criteria) this; } public Criteria andRunModeLessThanOrEqualTo(Integer value) { addCriterion("run_mode <=", value, "runMode"); return (Criteria) this; } public Criteria andRunModeIn(List<Integer> values) { addCriterion("run_mode in", values, "runMode"); return (Criteria) this; } public Criteria andRunModeNotIn(List<Integer> values) { addCriterion("run_mode not in", values, "runMode"); return (Criteria) this; } public Criteria andRunModeBetween(Integer value1, Integer value2) { addCriterion("run_mode between", value1, value2, "runMode"); return (Criteria) this; } public Criteria andRunModeNotBetween(Integer value1, Integer value2) { addCriterion("run_mode not between", value1, value2, "runMode"); return (Criteria) this; } public Criteria andCronExpressionIsNull() { addCriterion("cron_expression is null"); return (Criteria) this; } public Criteria andCronExpressionIsNotNull() { addCriterion("cron_expression is not null"); return (Criteria) this; } public Criteria andCronExpressionEqualTo(String value) { addCriterion("cron_expression =", value, "cronExpression"); return (Criteria) this; } public Criteria andCronExpressionNotEqualTo(String value) { addCriterion("cron_expression <>", value, "cronExpression"); return (Criteria) this; } public Criteria andCronExpressionGreaterThan(String value) { addCriterion("cron_expression >", value, "cronExpression"); return (Criteria) this; } public Criteria andCronExpressionGreaterThanOrEqualTo(String value) { addCriterion("cron_expression >=", value, "cronExpression"); return (Criteria) this; } public Criteria andCronExpressionLessThan(String value) { addCriterion("cron_expression <", value, "cronExpression"); return (Criteria) this; } public Criteria andCronExpressionLessThanOrEqualTo(String value) { addCriterion("cron_expression <=", value, "cronExpression"); return (Criteria) this; } public Criteria andCronExpressionLike(String value) { addCriterion("cron_expression like", value, "cronExpression"); return (Criteria) this; } public Criteria andCronExpressionNotLike(String value) { addCriterion("cron_expression not like", value, "cronExpression"); return (Criteria) this; } public Criteria andCronExpressionIn(List<String> values) { addCriterion("cron_expression in", values, "cronExpression"); return (Criteria) this; } public Criteria andCronExpressionNotIn(List<String> values) { addCriterion("cron_expression not in", values, "cronExpression"); return (Criteria) this; } public Criteria andCronExpressionBetween(String value1, String value2) { addCriterion("cron_expression between", value1, value2, "cronExpression"); return (Criteria) this; } public Criteria andCronExpressionNotBetween(String value1, String value2) { addCriterion("cron_expression not between", value1, value2, "cronExpression"); return (Criteria) this; } public Criteria andEnableScheduleIsNull() { addCriterion("enable_schedule is null"); return (Criteria) this; } public Criteria andEnableScheduleIsNotNull() { addCriterion("enable_schedule is not null"); return (Criteria) this; } public Criteria andEnableScheduleEqualTo(Integer value) { addCriterion("enable_schedule =", value, "enableSchedule"); return (Criteria) this; } public Criteria andEnableScheduleNotEqualTo(Integer value) { addCriterion("enable_schedule <>", value, "enableSchedule"); return (Criteria) this; } public Criteria andEnableScheduleGreaterThan(Integer value) { addCriterion("enable_schedule >", value, "enableSchedule"); return (Criteria) this; } public Criteria andEnableScheduleGreaterThanOrEqualTo(Integer value) { addCriterion("enable_schedule >=", value, "enableSchedule"); return (Criteria) this; } public Criteria andEnableScheduleLessThan(Integer value) { addCriterion("enable_schedule <", value, "enableSchedule"); return (Criteria) this; } public Criteria andEnableScheduleLessThanOrEqualTo(Integer value) { addCriterion("enable_schedule <=", value, "enableSchedule"); return (Criteria) this; } public Criteria andEnableScheduleIn(List<Integer> values) { addCriterion("enable_schedule in", values, "enableSchedule"); return (Criteria) this; } public Criteria andEnableScheduleNotIn(List<Integer> values) { addCriterion("enable_schedule not in", values, "enableSchedule"); return (Criteria) this; } public Criteria andEnableScheduleBetween(Integer value1, Integer value2) { addCriterion("enable_schedule between", value1, value2, "enableSchedule"); return (Criteria) this; } public Criteria andEnableScheduleNotBetween(Integer value1, Integer value2) { addCriterion("enable_schedule not between", value1, value2, "enableSchedule"); return (Criteria) this; } public Criteria andEnableRecordVideoIsNull() { addCriterion("enable_record_video is null"); return (Criteria) this; } public Criteria andEnableRecordVideoIsNotNull() { addCriterion("enable_record_video is not null"); return (Criteria) this; } public Criteria andEnableRecordVideoEqualTo(Integer value) { addCriterion("enable_record_video =", value, "enableRecordVideo"); return (Criteria) this; } public Criteria andEnableRecordVideoNotEqualTo(Integer value) { addCriterion("enable_record_video <>", value, "enableRecordVideo"); return (Criteria) this; } public Criteria andEnableRecordVideoGreaterThan(Integer value) { addCriterion("enable_record_video >", value, "enableRecordVideo"); return (Criteria) this; } public Criteria andEnableRecordVideoGreaterThanOrEqualTo(Integer value) { addCriterion("enable_record_video >=", value, "enableRecordVideo"); return (Criteria) this; } public Criteria andEnableRecordVideoLessThan(Integer value) { addCriterion("enable_record_video <", value, "enableRecordVideo"); return (Criteria) this; } public Criteria andEnableRecordVideoLessThanOrEqualTo(Integer value) { addCriterion("enable_record_video <=", value, "enableRecordVideo"); return (Criteria) this; } public Criteria andEnableRecordVideoIn(List<Integer> values) { addCriterion("enable_record_video in", values, "enableRecordVideo"); return (Criteria) this; } public Criteria andEnableRecordVideoNotIn(List<Integer> values) { addCriterion("enable_record_video not in", values, "enableRecordVideo"); return (Criteria) this; } public Criteria andEnableRecordVideoBetween(Integer value1, Integer value2) { addCriterion("enable_record_video between", value1, value2, "enableRecordVideo"); return (Criteria) this; } public Criteria andEnableRecordVideoNotBetween(Integer value1, Integer value2) { addCriterion("enable_record_video not between", value1, value2, "enableRecordVideo"); return (Criteria) this; } public Criteria andFailRetryCountIsNull() { addCriterion("fail_retry_count is null"); return (Criteria) this; } public Criteria andFailRetryCountIsNotNull() { addCriterion("fail_retry_count is not null"); return (Criteria) this; } public Criteria andFailRetryCountEqualTo(Integer value) { addCriterion("fail_retry_count =", value, "failRetryCount"); return (Criteria) this; } public Criteria andFailRetryCountNotEqualTo(Integer value) { addCriterion("fail_retry_count <>", value, "failRetryCount"); return (Criteria) this; } public Criteria andFailRetryCountGreaterThan(Integer value) { addCriterion("fail_retry_count >", value, "failRetryCount"); return (Criteria) this; } public Criteria andFailRetryCountGreaterThanOrEqualTo(Integer value) { addCriterion("fail_retry_count >=", value, "failRetryCount"); return (Criteria) this; } public Criteria andFailRetryCountLessThan(Integer value) { addCriterion("fail_retry_count <", value, "failRetryCount"); return (Criteria) this; } public Criteria andFailRetryCountLessThanOrEqualTo(Integer value) { addCriterion("fail_retry_count <=", value, "failRetryCount"); return (Criteria) this; } public Criteria andFailRetryCountIn(List<Integer> values) { addCriterion("fail_retry_count in", values, "failRetryCount"); return (Criteria) this; } public Criteria andFailRetryCountNotIn(List<Integer> values) { addCriterion("fail_retry_count not in", values, "failRetryCount"); return (Criteria) this; } public Criteria andFailRetryCountBetween(Integer value1, Integer value2) { addCriterion("fail_retry_count between", value1, value2, "failRetryCount"); return (Criteria) this; } public Criteria andFailRetryCountNotBetween(Integer value1, Integer value2) { addCriterion("fail_retry_count not between", value1, value2, "failRetryCount"); return (Criteria) this; } public Criteria andCreatorUidIsNull() { addCriterion("creator_uid is null"); return (Criteria) this; } public Criteria andCreatorUidIsNotNull() { addCriterion("creator_uid is not null"); return (Criteria) this; } public Criteria andCreatorUidEqualTo(Integer value) { addCriterion("creator_uid =", value, "creatorUid"); return (Criteria) this; } public Criteria andCreatorUidNotEqualTo(Integer value) { addCriterion("creator_uid <>", value, "creatorUid"); return (Criteria) this; } public Criteria andCreatorUidGreaterThan(Integer value) { addCriterion("creator_uid >", value, "creatorUid"); return (Criteria) this; } public Criteria andCreatorUidGreaterThanOrEqualTo(Integer value) { addCriterion("creator_uid >=", value, "creatorUid"); return (Criteria) this; } public Criteria andCreatorUidLessThan(Integer value) { addCriterion("creator_uid <", value, "creatorUid"); return (Criteria) this; } public Criteria andCreatorUidLessThanOrEqualTo(Integer value) { addCriterion("creator_uid <=", value, "creatorUid"); return (Criteria) this; } public Criteria andCreatorUidIn(List<Integer> values) { addCriterion("creator_uid in", values, "creatorUid"); return (Criteria) this; } public Criteria andCreatorUidNotIn(List<Integer> values) { addCriterion("creator_uid not in", values, "creatorUid"); return (Criteria) this; } public Criteria andCreatorUidBetween(Integer value1, Integer value2) { addCriterion("creator_uid between", value1, value2, "creatorUid"); return (Criteria) this; } public Criteria andCreatorUidNotBetween(Integer value1, Integer value2) { addCriterion("creator_uid not between", value1, value2, "creatorUid"); return (Criteria) this; } public Criteria andCreateTimeIsNull() { addCriterion("create_time is null"); return (Criteria) this; } public Criteria andCreateTimeIsNotNull() { addCriterion("create_time is not null"); return (Criteria) this; } public Criteria andCreateTimeEqualTo(Date value) { addCriterion("create_time =", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeNotEqualTo(Date value) { addCriterion("create_time <>", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeGreaterThan(Date value) { addCriterion("create_time >", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeGreaterThanOrEqualTo(Date value) { addCriterion("create_time >=", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeLessThan(Date value) { addCriterion("create_time <", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeLessThanOrEqualTo(Date value) { addCriterion("create_time <=", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeIn(List<Date> values) { addCriterion("create_time in", values, "createTime"); return (Criteria) this; } public Criteria andCreateTimeNotIn(List<Date> values) { addCriterion("create_time not in", values, "createTime"); return (Criteria) this; } public Criteria andCreateTimeBetween(Date value1, Date value2) { addCriterion("create_time between", value1, value2, "createTime"); return (Criteria) this; } public Criteria andCreateTimeNotBetween(Date value1, Date value2) { addCriterion("create_time not between", value1, value2, "createTime"); return (Criteria) this; } } public static class Criteria extends GeneratedCriteria { protected Criteria() { super(); } } public static class Criterion { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } } <|start_filename|>src/main/java/com/daxiang/model/Response.java<|end_filename|> package com.daxiang.model; import com.alibaba.fastjson.annotation.JSONField; import com.fasterxml.jackson.annotation.JsonIgnore; import lombok.Data; import org.springframework.util.StringUtils; /** * Created by jiangyitao. */ @Data public class Response<T> { private static final Integer SUCCESS = 1; private static final Integer FAIL = 0; private static final Integer ERROR = -1; private static final Integer UNAUTHORIZED = 401; private static final Integer ACCESSDENIED = 403; private Integer status; private String msg; private T data; private static <T> Response<T> createResponse(Integer status, String msg, T data) { Response<T> response = new Response<>(); response.setStatus(status); response.setMsg(msg); response.setData(data); return response; } @JsonIgnore @JSONField(serialize = false) public boolean isSuccess() { return SUCCESS.equals(status); } public static Response success() { return createResponse(SUCCESS, "success", null); } public static <T> Response<T> success(T data) { return createResponse(SUCCESS, "success", data); } public static Response success(String msg) { return createResponse(SUCCESS, msg, null); } public static <T> Response<T> success(String msg, T data) { return createResponse(SUCCESS, msg, data); } public static Response fail(String msg) { return createResponse(FAIL, msg, null); } public static Response error(String msg) { return createResponse(ERROR, msg, null); } public static Response unauthorized(String msg) { return createResponse(UNAUTHORIZED, StringUtils.isEmpty(msg) ? "认证失败" : msg, null); } public static Response accessDenied() { return createResponse(ACCESSDENIED, "权限不足", null); } } <|start_filename|>src/main/java/com/daxiang/typehandler/EnvironmentValueListTypeHandler.java<|end_filename|> package com.daxiang.typehandler; import com.daxiang.model.environment.EnvironmentValue; /** * Created by jiangyitao. */ public class EnvironmentValueListTypeHandler extends ListTypeHandler { @Override public Class getTypeClass() { return EnvironmentValue.class; } } <|start_filename|>src/main/java/com/daxiang/mbg/po/Project.java<|end_filename|> package com.daxiang.mbg.po; import com.daxiang.validator.annotation.JSONFormatIfHasText; import com.daxiang.validator.group.UpdateGroup; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; import java.io.Serializable; import java.util.Date; public class Project implements Serializable { public static final int ANDROID_PLATFORM = 1; public static final int IOS_PLATFORM = 2; public static final int PC_WEB_PLATFORM = 3; /** * 项目id * * @mbg.generated */ @NotNull(message = "id不能为空", groups = {UpdateGroup.class}) private Integer id; /** * 项目名 * * @mbg.generated */ @NotBlank(message = "项目名不能为空") private String name; /** * 项目描述 * * @mbg.generated */ private String description; /** * 1.andorid 2.iOS 3.pc web * * @mbg.generated */ @NotNull(message = "平台不能为空") private Integer platform; /** * 创建人id * * @mbg.generated */ private Integer creatorUid; /** * 创建时间 * * @mbg.generated */ private Date createTime; /** * org.openqa.selenium.Capabilities * * @mbg.generated */ @JSONFormatIfHasText(message = "Capabilities必须为合法的JSON格式") private String capabilities; private static final long serialVersionUID = 1L; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Integer getPlatform() { return platform; } public void setPlatform(Integer platform) { this.platform = platform; } public Integer getCreatorUid() { return creatorUid; } public void setCreatorUid(Integer creatorUid) { this.creatorUid = creatorUid; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public String getCapabilities() { return capabilities; } public void setCapabilities(String capabilities) { this.capabilities = capabilities; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", name=").append(name); sb.append(", description=").append(description); sb.append(", platform=").append(platform); sb.append(", creatorUid=").append(creatorUid); sb.append(", createTime=").append(createTime); sb.append(", capabilities=").append(capabilities); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } } <|start_filename|>src/main/java/com/daxiang/mbg/po/Driver.java<|end_filename|> package com.daxiang.mbg.po; import com.daxiang.model.dto.DriverFile; import com.daxiang.validator.group.UpdateGroup; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.NotNull; import java.io.Serializable; import java.util.Date; import java.util.List; public class Driver implements Serializable { @NotNull(message = "id不能为空", groups = {UpdateGroup.class}) private Integer id; /** * 版本号 * * @mbg.generated */ @NotBlank(message = "version不能为空") private String version; /** * 1. chromedriver * * @mbg.generated */ @NotNull(message = "type不能为空") private Integer type; /** * 创建时间 * * @mbg.generated */ private Date createTime; /** * 创建人 * * @mbg.generated */ private Integer creatorUid; /** * 各平台文件,1.windows 2.linux 3.macos * * @mbg.generated */ private java.util.List<com.daxiang.model.dto.DriverFile> files; /** * deviceIds * * @mbg.generated */ private java.util.List<String> deviceIds; private static final long serialVersionUID = 1L; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public Integer getType() { return type; } public void setType(Integer type) { this.type = type; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Integer getCreatorUid() { return creatorUid; } public void setCreatorUid(Integer creatorUid) { this.creatorUid = creatorUid; } public java.util.List<com.daxiang.model.dto.DriverFile> getFiles() { return files; } public void setFiles(java.util.List<com.daxiang.model.dto.DriverFile> files) { this.files = files; } public java.util.List<String> getDeviceIds() { return deviceIds; } public void setDeviceIds(java.util.List<String> deviceIds) { this.deviceIds = deviceIds; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", version=").append(version); sb.append(", type=").append(type); sb.append(", createTime=").append(createTime); sb.append(", creatorUid=").append(creatorUid); sb.append(", files=").append(files); sb.append(", deviceIds=").append(deviceIds); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } } <|start_filename|>src/main/java/com/daxiang/model/vo/ActionVo.java<|end_filename|> package com.daxiang.model.vo; import com.daxiang.mbg.po.Action; import lombok.Data; /** * Created by jiangyitao. */ @Data public class ActionVo extends Action { private String creatorNickName = ""; private String updatorNickName = ""; } <|start_filename|>src/main/java/com/daxiang/validator/JSONFormatIfHasTextValidator.java<|end_filename|> package com.daxiang.validator; import com.alibaba.fastjson.JSONObject; import com.daxiang.validator.annotation.JSONFormatIfHasText; import org.springframework.util.StringUtils; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; /** * Created by jiangyitao. */ public class JSONFormatIfHasTextValidator implements ConstraintValidator<JSONFormatIfHasText, String> { @Override public boolean isValid(String value, ConstraintValidatorContext context) { if (StringUtils.hasText(value)) { try { JSONObject.parseObject(value); } catch (Exception e) { return false; } } return true; } } <|start_filename|>src/main/java/com/daxiang/controller/TestPlanController.java<|end_filename|> package com.daxiang.controller; import com.daxiang.mbg.po.TestPlan; import com.daxiang.model.PageRequest; import com.daxiang.model.PagedData; import com.daxiang.model.Response; import com.daxiang.model.vo.TestPlanVo; import com.daxiang.service.TestPlanService; import com.daxiang.validator.group.UpdateGroup; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; import java.util.List; /** * Created by jiangyitao. */ @RestController @RequestMapping("/testPlan") public class TestPlanController { @Autowired private TestPlanService testPlanService; @PostMapping("/add") public Response addTestPlan(@RequestBody @Valid TestPlan testPlan) { testPlanService.add(testPlan); return Response.success("添加成功"); } @DeleteMapping("/{testPlanId}") public Response deleteTestPlan(@PathVariable Integer testPlanId) { testPlanService.delete(testPlanId); return Response.success("删除成功"); } @PostMapping("/update") public Response updateTestPlan(@RequestBody @Validated({UpdateGroup.class}) TestPlan testPlan) { testPlanService.update(testPlan); return Response.success("更新成功"); } @PostMapping("/list") public Response list(TestPlan query, String orderBy, PageRequest pageRequest) { if (pageRequest.needPaging()) { PagedData<TestPlanVo> pagedData = testPlanService.list(query, orderBy, pageRequest); return Response.success(pagedData); } else { List<TestPlanVo> testPlanVos = testPlanService.getTestPlanVos(query, orderBy); return Response.success(testPlanVos); } } } <|start_filename|>src/main/java/com/daxiang/agent/AgentStatusChangeNotifier.java<|end_filename|> package com.daxiang.agent; import com.daxiang.service.BrowserService; import com.daxiang.service.MobileService; import de.codecentric.boot.admin.server.domain.entities.Instance; import de.codecentric.boot.admin.server.domain.entities.InstanceRepository; import de.codecentric.boot.admin.server.domain.events.InstanceEvent; import de.codecentric.boot.admin.server.domain.events.InstanceStatusChangedEvent; import de.codecentric.boot.admin.server.domain.values.StatusInfo; import de.codecentric.boot.admin.server.notify.AbstractStatusChangeNotifier; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import reactor.core.publisher.Mono; import java.net.URI; import java.net.URISyntaxException; /** * Created by jiangyitao. */ @Component @Slf4j public class AgentStatusChangeNotifier extends AbstractStatusChangeNotifier { @Autowired private MobileService mobileService; @Autowired private BrowserService browserService; public AgentStatusChangeNotifier(InstanceRepository repository) { super(repository); } @Override protected Mono<Void> doNotify(InstanceEvent event, Instance instance) { return Mono.fromRunnable(() -> { if (event instanceof InstanceStatusChangedEvent) { String agentUrl = instance.getRegistration().getServiceUrl(); String status = ((InstanceStatusChangedEvent) event).getStatusInfo().getStatus(); log.info("agent: {}, status: {}", agentUrl, status); URI agentUri; try { agentUri = new URI(agentUrl); } catch (URISyntaxException e) { log.error("非法的agentUrl: {}", agentUrl, e); return; } if (!StatusInfo.STATUS_UP.equals(status)) { // agent离线,把该agent下device变为离线 mobileService.agentOffline(agentUri.getHost()); browserService.agentOffline(agentUri.getHost()); } } }); } } <|start_filename|>src/main/java/com/daxiang/validator/group/SaveActionGroup.java<|end_filename|> package com.daxiang.validator.group; import javax.validation.groups.Default; /** * Created by jiangyitao. */ public interface SaveActionGroup extends Default { } <|start_filename|>src/main/java/com/daxiang/model/dto/UserRoleDto.java<|end_filename|> package com.daxiang.model.dto; import com.daxiang.mbg.po.Role; import com.daxiang.mbg.po.UserRole; import lombok.Data; /** * Created by jiangyitao. */ @Data public class UserRoleDto extends UserRole { private Role role; } <|start_filename|>src/main/java/com/daxiang/typehandler/DriverFileListTypeHandler.java<|end_filename|> package com.daxiang.typehandler; import com.daxiang.model.dto.DriverFile; /** * Created by jiangyitao. */ public class DriverFileListTypeHandler extends ListTypeHandler { @Override public Class getTypeClass() { return DriverFile.class; } } <|start_filename|>src/main/java/com/daxiang/model/environment/EnvironmentValue.java<|end_filename|> package com.daxiang.model.environment; import com.daxiang.validator.group.GlobalVarGroup; import lombok.Data; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; /** * Created by jiangyitao. */ @Data public class EnvironmentValue { public static final int DEFAULT_ENVIRONMENT_ID = -1; @NotNull(message = "environmentId不能为空") private Integer environmentId; @NotBlank(message = "environmentValue不能为空", groups = {GlobalVarGroup.class}) private String value; } <|start_filename|>src/main/java/com/daxiang/model/vo/CategoryVo.java<|end_filename|> package com.daxiang.model.vo; import com.daxiang.mbg.po.Category; import lombok.Data; /** * Created by jiangyitao. */ @Data public class CategoryVo extends Category { private String creatorNickName = ""; } <|start_filename|>src/main/java/com/daxiang/controller/BrowserController.java<|end_filename|> package com.daxiang.controller; import com.daxiang.mbg.po.Browser; import com.daxiang.model.PageRequest; import com.daxiang.model.PagedData; import com.daxiang.model.Response; import com.daxiang.service.BrowserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; import java.util.List; /** * Created by jiangyitao. */ @RestController @RequestMapping("/browser") public class BrowserController { @Autowired private BrowserService browserService; @PostMapping("/save") public Response save(@RequestBody @Valid Browser browser) { browserService.save(browser); return Response.success("保存成功"); } @PostMapping("/list") public Response list(Browser query, String orderBy, PageRequest pageRequest) { if (pageRequest.needPaging()) { PagedData<Browser> pagedData = browserService.list(query, orderBy, pageRequest); return Response.success(pagedData); } else { List<Browser> browsers = browserService.getBrowsers(query, orderBy); return Response.success(browsers); } } @GetMapping("/{browserId}/start") public Response start(@PathVariable String browserId) { Browser browser = browserService.start(browserId); return Response.success(browser); } @GetMapping("/online") public Response getOnlineBrowsers() { List<Browser> onlineBrowsers = browserService.getOnlineBrowsers(); return Response.success(onlineBrowsers); } } <|start_filename|>src/main/java/com/daxiang/validator/NoDuplicateEnvironmentValidator.java<|end_filename|> package com.daxiang.validator; import com.daxiang.model.environment.EnvironmentValue; import com.daxiang.validator.annotation.NoDuplicateEnvironment; import org.springframework.util.CollectionUtils; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.stream.Collectors; /** * Created by jiangyitao. */ public class NoDuplicateEnvironmentValidator implements ConstraintValidator<NoDuplicateEnvironment, List<EnvironmentValue>> { @Override public boolean isValid(List<EnvironmentValue> environmentValueList, ConstraintValidatorContext context) { if (!CollectionUtils.isEmpty(environmentValueList)) { Map<Integer, Long> environmentIdCountMap = environmentValueList.stream().filter(env -> Objects.nonNull(env.getEnvironmentId())) .collect(Collectors.groupingBy(EnvironmentValue::getEnvironmentId, Collectors.counting())); for (Map.Entry<Integer, Long> environmentIdCount : environmentIdCountMap.entrySet()) { if (environmentIdCount.getValue() > 1) { return false; } } } return true; } } <|start_filename|>src/main/java/com/daxiang/model/vo/EnvironmentVo.java<|end_filename|> package com.daxiang.model.vo; import com.daxiang.mbg.po.Environment; import lombok.Data; /** * Created by jiangyitao. */ @Data public class EnvironmentVo extends Environment { private String creatorNickName = ""; } <|start_filename|>src/main/java/com/daxiang/model/PagedData.java<|end_filename|> package com.daxiang.model; import lombok.Data; import java.util.List; /** * Created by jiangyitao. */ @Data public class PagedData<T> { private long total; private List<T> data; public PagedData(List<T> data, long total) { this.data = data; this.total = total; } } <|start_filename|>src/main/java/com/daxiang/mbg/mapper/MobileMapper.java<|end_filename|> package com.daxiang.mbg.mapper; import com.daxiang.mbg.po.Mobile; import com.daxiang.mbg.po.MobileExample; import java.util.List; import org.apache.ibatis.annotations.Param; public interface MobileMapper { long countByExample(MobileExample example); int deleteByExample(MobileExample example); int deleteByPrimaryKey(String id); int insert(Mobile record); int insertSelective(Mobile record); List<Mobile> selectByExample(MobileExample example); Mobile selectByPrimaryKey(String id); int updateByExampleSelective(@Param("record") Mobile record, @Param("example") MobileExample example); int updateByExample(@Param("record") Mobile record, @Param("example") MobileExample example); int updateByPrimaryKeySelective(Mobile record); int updateByPrimaryKey(Mobile record); } <|start_filename|>src/main/java/com/daxiang/controller/TestTaskController.java<|end_filename|> package com.daxiang.controller; import com.daxiang.mbg.po.TestTask; import com.daxiang.model.PageRequest; import com.daxiang.model.PagedData; import com.daxiang.model.Response; import com.daxiang.model.vo.TestTaskSummary; import com.daxiang.model.vo.TestTaskVo; import com.daxiang.security.SecurityUtil; import com.daxiang.service.TestTaskService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List; /** * Created by jiangyitao. */ @RestController @RequestMapping("/testTask") public class TestTaskController { @Autowired private TestTaskService testTaskService; @GetMapping("/commit") public Response commit(Integer testPlanId) { testTaskService.commit(testPlanId, SecurityUtil.getCurrentUserId()); return Response.success("提交成功"); } @PostMapping("/list") public Response list(TestTask query, String orderBy, PageRequest pageRequest) { if (pageRequest.needPaging()) { PagedData<TestTaskVo> pagedData = testTaskService.list(query, orderBy, pageRequest); return Response.success(pagedData); } else { List<TestTaskVo> testTaskVos = testTaskService.getTestTaskVos(query, orderBy); return Response.success(testTaskVos); } } @GetMapping("/{testTaskId}/summary") public Response getTestTaskSummary(@PathVariable Integer testTaskId) { TestTaskSummary testTaskSummary = testTaskService.getTestTaskSummary(testTaskId); return Response.success(testTaskSummary); } @DeleteMapping("/{testTaskId}") public Response delete(@PathVariable Integer testTaskId) { testTaskService.deleteAndClearRelatedRes(testTaskId); return Response.success("删除成功"); } } <|start_filename|>src/main/java/com/daxiang/service/TestSuiteService.java<|end_filename|> package com.daxiang.service; import com.daxiang.dao.TestSuiteDao; import com.daxiang.exception.ServerException; import com.daxiang.mbg.po.*; import com.daxiang.model.PageRequest; import com.daxiang.model.PagedData; import com.daxiang.security.SecurityUtil; import com.github.pagehelper.PageHelper; import com.github.pagehelper.Page; import com.daxiang.mbg.mapper.TestSuiteMapper; import com.daxiang.model.vo.TestSuiteVo; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DuplicateKeyException; import org.springframework.stereotype.Service; import org.springframework.util.CollectionUtils; import org.springframework.util.StringUtils; import java.util.*; import java.util.stream.Collectors; /** * Created by jiangyitao. */ @Service public class TestSuiteService { @Autowired private TestSuiteDao testSuiteDao; @Autowired private TestSuiteMapper testSuiteMapper; @Autowired private TestPlanService testPlanService; @Autowired private UserService userService; public void add(TestSuite testSuite) { testSuite.setCreateTime(new Date()); testSuite.setCreatorUid(SecurityUtil.getCurrentUserId()); try { int insertCount = testSuiteMapper.insertSelective(testSuite); if (insertCount != 1) { throw new ServerException("添加失败,请稍后重试"); } } catch (DuplicateKeyException e) { throw new ServerException(testSuite.getName() + "已存在"); } } public void delete(Integer testSuiteId) { // 检查该测试集是否被testplan使用 List<TestPlan> testPlans = testPlanService.getTestPlansByTestSuiteId(testSuiteId); if (!CollectionUtils.isEmpty(testPlans)) { String testPlanNames = testPlans.stream().map(TestPlan::getName).collect(Collectors.joining("、")); throw new ServerException("测试计划: " + testPlanNames + ",正在使用,无法删除"); } int deleteCount = testSuiteMapper.deleteByPrimaryKey(testSuiteId); if (deleteCount != 1) { throw new ServerException("删除失败,请稍后重试"); } } public void update(TestSuite testSuite) { try { int updateCount = testSuiteMapper.updateByPrimaryKeySelective(testSuite); if (updateCount != 1) { throw new ServerException("更新失败,请稍后重试"); } } catch (DuplicateKeyException e) { throw new ServerException(testSuite.getName() + "已存在"); } } public PagedData<TestSuiteVo> list(TestSuite query, String orderBy, PageRequest pageRequest) { Page page = PageHelper.startPage(pageRequest.getPageNum(), pageRequest.getPageSize()); if (StringUtils.isEmpty(orderBy)) { orderBy = "create_time desc"; } List<TestSuiteVo> testSuiteVos = getTestSuiteVos(query, orderBy); return new PagedData<>(testSuiteVos, page.getTotal()); } private List<TestSuiteVo> convertTestSuitesToTestSuiteVos(List<TestSuite> testSuites) { if (CollectionUtils.isEmpty(testSuites)) { return new ArrayList<>(); } List<Integer> creatorUids = testSuites.stream() .map(TestSuite::getCreatorUid) .filter(Objects::nonNull) .distinct() .collect(Collectors.toList()); Map<Integer, User> userMap = userService.getUserMapByIds(creatorUids); List<TestSuiteVo> testSuiteVos = testSuites.stream().map(testSuite -> { TestSuiteVo testSuiteVo = new TestSuiteVo(); BeanUtils.copyProperties(testSuite, testSuiteVo); if (testSuite.getCreatorUid() != null) { User user = userMap.get(testSuite.getCreatorUid()); if (user != null) { testSuiteVo.setCreatorNickName(user.getNickName()); } } return testSuiteVo; }).collect(Collectors.toList()); return testSuiteVos; } public List<TestSuiteVo> getTestSuiteVos(TestSuite query, String orderBy) { List<TestSuite> testSuites = getTestSuites(query, orderBy); return convertTestSuitesToTestSuiteVos(testSuites); } public List<TestSuite> getTestSuites(TestSuite query, String orderBy) { TestSuiteExample example = new TestSuiteExample(); if (query != null) { TestSuiteExample.Criteria criteria = example.createCriteria(); if (query.getId() != null) { criteria.andIdEqualTo(query.getId()); } if (query.getProjectId() != null) { criteria.andProjectIdEqualTo(query.getProjectId()); } if (!StringUtils.isEmpty(query.getName())) { criteria.andNameEqualTo(query.getName()); } } if (!StringUtils.isEmpty(orderBy)) { example.setOrderByClause(orderBy); } return testSuiteMapper.selectByExampleWithBLOBs(example); } public List<TestSuite> getTestSuitesByIds(List<Integer> ids) { if (CollectionUtils.isEmpty(ids)) { return new ArrayList<>(); } TestSuiteExample example = new TestSuiteExample(); TestSuiteExample.Criteria criteria = example.createCriteria(); criteria.andIdIn(ids); return testSuiteMapper.selectByExampleWithBLOBs(example); } public List<TestSuite> getTestSuitesByActionId(Integer actionId) { return testSuiteDao.selectByActionId(actionId); } } <|start_filename|>src/main/java/com/daxiang/mbg/mapper/EnvironmentMapper.java<|end_filename|> package com.daxiang.mbg.mapper; import com.daxiang.mbg.po.Environment; import com.daxiang.mbg.po.EnvironmentExample; import java.util.List; import org.apache.ibatis.annotations.Param; public interface EnvironmentMapper { long countByExample(EnvironmentExample example); int deleteByExample(EnvironmentExample example); int deleteByPrimaryKey(Integer id); int insert(Environment record); int insertSelective(Environment record); List<Environment> selectByExample(EnvironmentExample example); Environment selectByPrimaryKey(Integer id); int updateByExampleSelective(@Param("record") Environment record, @Param("example") EnvironmentExample example); int updateByExample(@Param("record") Environment record, @Param("example") EnvironmentExample example); int updateByPrimaryKeySelective(Environment record); int updateByPrimaryKey(Environment record); } <|start_filename|>src/main/java/com/daxiang/validator/JavaIdentifierValidator.java<|end_filename|> package com.daxiang.validator; import com.daxiang.validator.annotation.JavaIdentifier; import org.springframework.util.StringUtils; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; /** * Created by jiangyitao. * 校验是否符合java标识符规范 */ public class JavaIdentifierValidator implements ConstraintValidator<JavaIdentifier, String> { @Override public boolean isValid(String value, ConstraintValidatorContext context) { return isJavaIdentifier(value); } public static boolean isJavaIdentifier(String value) { if (!StringUtils.hasLength(value)) { return false; } // 校验首字符 if (!Character.isJavaIdentifierStart(value.charAt(0))) { return false; } // 校验首字符之后的字符 for (int i = 1; i < value.length(); i++) { if (!Character.isJavaIdentifierPart(value.charAt(i))) { return false; } } return true; } } <|start_filename|>src/main/java/com/daxiang/typehandler/ElementListTypeHandler.java<|end_filename|> package com.daxiang.typehandler; import com.daxiang.model.page.Element; /** * Created by jiangyitao. */ public class ElementListTypeHandler extends ListTypeHandler { @Override public Class getTypeClass() { return Element.class; } } <|start_filename|>src/main/java/com/daxiang/model/dto/DriverFile.java<|end_filename|> package com.daxiang.model.dto; import com.alibaba.fastjson.annotation.JSONField; import com.daxiang.utils.HttpServletUtil; import lombok.Data; import org.springframework.util.StringUtils; /** * Created by jiangyitao. */ @Data public class DriverFile { /** * 1.windows 2.linux 3.macos */ private Integer platform; private String filePath; @JSONField(serialize = false) // 不会序列化的表中 private String downloadUrl; public String getDownloadUrl() { if (!StringUtils.isEmpty(filePath)) { return HttpServletUtil.getStaticResourceUrl(filePath); } return null; } } <|start_filename|>src/main/java/com/daxiang/security/WebSecurityConfig.java<|end_filename|> package com.daxiang.security; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpMethod; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; import java.util.Arrays; import java.util.HashSet; /** * Created by jiangyitao. */ @Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled = true) public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Value("${frontend}") private String frontend; @Autowired private JwtTokenFilter jwtTokenFilter; @Autowired private JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint; @Autowired private JwtAccessDeniedHandler jwtAccessDeniedHandler; @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable().cors(); http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); HttpMethod permitHttpMethod = HttpMethod.OPTIONS; String[] permitAntPatterns = new String[]{ "/", "/user/login", "/upload/**", "/" + frontend + "/**", // 以下为agent调用的接口 "/springboot-admin/**", "/action/resetBasicAction", "/upload/file/*", "/project/list", "/mobile/list", "/agentExtJar/lastUploadTimeList", "/mobile/save", "/browser/save", "/driver/downloadUrl", "/deviceTestTask/**" }; http.authorizeRequests() .antMatchers(permitHttpMethod).permitAll() .antMatchers(permitAntPatterns).permitAll() .anyRequest().authenticated(); http.exceptionHandling() .authenticationEntryPoint(jwtAuthenticationEntryPoint) .accessDeniedHandler(jwtAccessDeniedHandler); jwtTokenFilter.setShouldNotFilterHttpMethod(permitHttpMethod); jwtTokenFilter.setShouldNotFilterAntPatterns(new HashSet<>(Arrays.asList(permitAntPatterns))); http.addFilterBefore(jwtTokenFilter, UsernamePasswordAuthenticationFilter.class); } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(12); } @Override @Bean public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } } <|start_filename|>src/main/java/com/daxiang/controller/HomeController.java<|end_filename|> package com.daxiang.controller; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; /** * Created by jiangyitao. */ @Controller public class HomeController { @Value("redirect:/${frontend}/index.html") private String url; @GetMapping("/") public String index() { return url; } } <|start_filename|>src/main/java/com/daxiang/dao/AgentExtJarDao.java<|end_filename|> package com.daxiang.dao; import com.daxiang.mbg.po.AgentExtJar; import java.util.List; /** * Created by jiangyitao. */ public interface AgentExtJarDao { List<AgentExtJar> selectLastUploadTimeList(); } <|start_filename|>src/main/java/com/daxiang/typehandler/PageListTypeHandler.java<|end_filename|> package com.daxiang.typehandler; import com.daxiang.mbg.po.Page; /** * Created by jiangyitao. */ public class PageListTypeHandler extends ListTypeHandler { @Override public Class getTypeClass() { return Page.class; } } <|start_filename|>src/main/java/com/daxiang/controller/RoleController.java<|end_filename|> package com.daxiang.controller; import com.daxiang.mbg.po.Role; import com.daxiang.model.Response; import com.daxiang.service.RoleService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.List; /** * Created by jiangyitao. */ @RestController @RequestMapping("/role") public class RoleController { @Autowired private RoleService roleService; @GetMapping("/list") public Response list() { List<Role> roles = roleService.list(); return Response.success(roles); } } <|start_filename|>src/main/java/com/daxiang/mbg/po/AgentExtJarExample.java<|end_filename|> package com.daxiang.mbg.po; import java.util.ArrayList; import java.util.Date; import java.util.List; public class AgentExtJarExample { protected String orderByClause; protected boolean distinct; protected List<Criteria> oredCriteria; public AgentExtJarExample() { oredCriteria = new ArrayList<Criteria>(); } public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } public String getOrderByClause() { return orderByClause; } public void setDistinct(boolean distinct) { this.distinct = distinct; } public boolean isDistinct() { return distinct; } public List<Criteria> getOredCriteria() { return oredCriteria; } public void or(Criteria criteria) { oredCriteria.add(criteria); } public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } protected abstract static class GeneratedCriteria { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andIdIsNull() { addCriterion("id is null"); return (Criteria) this; } public Criteria andIdIsNotNull() { addCriterion("id is not null"); return (Criteria) this; } public Criteria andIdEqualTo(Integer value) { addCriterion("id =", value, "id"); return (Criteria) this; } public Criteria andIdNotEqualTo(Integer value) { addCriterion("id <>", value, "id"); return (Criteria) this; } public Criteria andIdGreaterThan(Integer value) { addCriterion("id >", value, "id"); return (Criteria) this; } public Criteria andIdGreaterThanOrEqualTo(Integer value) { addCriterion("id >=", value, "id"); return (Criteria) this; } public Criteria andIdLessThan(Integer value) { addCriterion("id <", value, "id"); return (Criteria) this; } public Criteria andIdLessThanOrEqualTo(Integer value) { addCriterion("id <=", value, "id"); return (Criteria) this; } public Criteria andIdIn(List<Integer> values) { addCriterion("id in", values, "id"); return (Criteria) this; } public Criteria andIdNotIn(List<Integer> values) { addCriterion("id not in", values, "id"); return (Criteria) this; } public Criteria andIdBetween(Integer value1, Integer value2) { addCriterion("id between", value1, value2, "id"); return (Criteria) this; } public Criteria andIdNotBetween(Integer value1, Integer value2) { addCriterion("id not between", value1, value2, "id"); return (Criteria) this; } public Criteria andNameIsNull() { addCriterion("name is null"); return (Criteria) this; } public Criteria andNameIsNotNull() { addCriterion("name is not null"); return (Criteria) this; } public Criteria andNameEqualTo(String value) { addCriterion("name =", value, "name"); return (Criteria) this; } public Criteria andNameNotEqualTo(String value) { addCriterion("name <>", value, "name"); return (Criteria) this; } public Criteria andNameGreaterThan(String value) { addCriterion("name >", value, "name"); return (Criteria) this; } public Criteria andNameGreaterThanOrEqualTo(String value) { addCriterion("name >=", value, "name"); return (Criteria) this; } public Criteria andNameLessThan(String value) { addCriterion("name <", value, "name"); return (Criteria) this; } public Criteria andNameLessThanOrEqualTo(String value) { addCriterion("name <=", value, "name"); return (Criteria) this; } public Criteria andNameLike(String value) { addCriterion("name like", value, "name"); return (Criteria) this; } public Criteria andNameNotLike(String value) { addCriterion("name not like", value, "name"); return (Criteria) this; } public Criteria andNameIn(List<String> values) { addCriterion("name in", values, "name"); return (Criteria) this; } public Criteria andNameNotIn(List<String> values) { addCriterion("name not in", values, "name"); return (Criteria) this; } public Criteria andNameBetween(String value1, String value2) { addCriterion("name between", value1, value2, "name"); return (Criteria) this; } public Criteria andNameNotBetween(String value1, String value2) { addCriterion("name not between", value1, value2, "name"); return (Criteria) this; } public Criteria andVersionIsNull() { addCriterion("version is null"); return (Criteria) this; } public Criteria andVersionIsNotNull() { addCriterion("version is not null"); return (Criteria) this; } public Criteria andVersionEqualTo(String value) { addCriterion("version =", value, "version"); return (Criteria) this; } public Criteria andVersionNotEqualTo(String value) { addCriterion("version <>", value, "version"); return (Criteria) this; } public Criteria andVersionGreaterThan(String value) { addCriterion("version >", value, "version"); return (Criteria) this; } public Criteria andVersionGreaterThanOrEqualTo(String value) { addCriterion("version >=", value, "version"); return (Criteria) this; } public Criteria andVersionLessThan(String value) { addCriterion("version <", value, "version"); return (Criteria) this; } public Criteria andVersionLessThanOrEqualTo(String value) { addCriterion("version <=", value, "version"); return (Criteria) this; } public Criteria andVersionLike(String value) { addCriterion("version like", value, "version"); return (Criteria) this; } public Criteria andVersionNotLike(String value) { addCriterion("version not like", value, "version"); return (Criteria) this; } public Criteria andVersionIn(List<String> values) { addCriterion("version in", values, "version"); return (Criteria) this; } public Criteria andVersionNotIn(List<String> values) { addCriterion("version not in", values, "version"); return (Criteria) this; } public Criteria andVersionBetween(String value1, String value2) { addCriterion("version between", value1, value2, "version"); return (Criteria) this; } public Criteria andVersionNotBetween(String value1, String value2) { addCriterion("version not between", value1, value2, "version"); return (Criteria) this; } public Criteria andMd5IsNull() { addCriterion("md5 is null"); return (Criteria) this; } public Criteria andMd5IsNotNull() { addCriterion("md5 is not null"); return (Criteria) this; } public Criteria andMd5EqualTo(String value) { addCriterion("md5 =", value, "md5"); return (Criteria) this; } public Criteria andMd5NotEqualTo(String value) { addCriterion("md5 <>", value, "md5"); return (Criteria) this; } public Criteria andMd5GreaterThan(String value) { addCriterion("md5 >", value, "md5"); return (Criteria) this; } public Criteria andMd5GreaterThanOrEqualTo(String value) { addCriterion("md5 >=", value, "md5"); return (Criteria) this; } public Criteria andMd5LessThan(String value) { addCriterion("md5 <", value, "md5"); return (Criteria) this; } public Criteria andMd5LessThanOrEqualTo(String value) { addCriterion("md5 <=", value, "md5"); return (Criteria) this; } public Criteria andMd5Like(String value) { addCriterion("md5 like", value, "md5"); return (Criteria) this; } public Criteria andMd5NotLike(String value) { addCriterion("md5 not like", value, "md5"); return (Criteria) this; } public Criteria andMd5In(List<String> values) { addCriterion("md5 in", values, "md5"); return (Criteria) this; } public Criteria andMd5NotIn(List<String> values) { addCriterion("md5 not in", values, "md5"); return (Criteria) this; } public Criteria andMd5Between(String value1, String value2) { addCriterion("md5 between", value1, value2, "md5"); return (Criteria) this; } public Criteria andMd5NotBetween(String value1, String value2) { addCriterion("md5 not between", value1, value2, "md5"); return (Criteria) this; } public Criteria andFilePathIsNull() { addCriterion("file_path is null"); return (Criteria) this; } public Criteria andFilePathIsNotNull() { addCriterion("file_path is not null"); return (Criteria) this; } public Criteria andFilePathEqualTo(String value) { addCriterion("file_path =", value, "filePath"); return (Criteria) this; } public Criteria andFilePathNotEqualTo(String value) { addCriterion("file_path <>", value, "filePath"); return (Criteria) this; } public Criteria andFilePathGreaterThan(String value) { addCriterion("file_path >", value, "filePath"); return (Criteria) this; } public Criteria andFilePathGreaterThanOrEqualTo(String value) { addCriterion("file_path >=", value, "filePath"); return (Criteria) this; } public Criteria andFilePathLessThan(String value) { addCriterion("file_path <", value, "filePath"); return (Criteria) this; } public Criteria andFilePathLessThanOrEqualTo(String value) { addCriterion("file_path <=", value, "filePath"); return (Criteria) this; } public Criteria andFilePathLike(String value) { addCriterion("file_path like", value, "filePath"); return (Criteria) this; } public Criteria andFilePathNotLike(String value) { addCriterion("file_path not like", value, "filePath"); return (Criteria) this; } public Criteria andFilePathIn(List<String> values) { addCriterion("file_path in", values, "filePath"); return (Criteria) this; } public Criteria andFilePathNotIn(List<String> values) { addCriterion("file_path not in", values, "filePath"); return (Criteria) this; } public Criteria andFilePathBetween(String value1, String value2) { addCriterion("file_path between", value1, value2, "filePath"); return (Criteria) this; } public Criteria andFilePathNotBetween(String value1, String value2) { addCriterion("file_path not between", value1, value2, "filePath"); return (Criteria) this; } public Criteria andFileSizeIsNull() { addCriterion("file_size is null"); return (Criteria) this; } public Criteria andFileSizeIsNotNull() { addCriterion("file_size is not null"); return (Criteria) this; } public Criteria andFileSizeEqualTo(Long value) { addCriterion("file_size =", value, "fileSize"); return (Criteria) this; } public Criteria andFileSizeNotEqualTo(Long value) { addCriterion("file_size <>", value, "fileSize"); return (Criteria) this; } public Criteria andFileSizeGreaterThan(Long value) { addCriterion("file_size >", value, "fileSize"); return (Criteria) this; } public Criteria andFileSizeGreaterThanOrEqualTo(Long value) { addCriterion("file_size >=", value, "fileSize"); return (Criteria) this; } public Criteria andFileSizeLessThan(Long value) { addCriterion("file_size <", value, "fileSize"); return (Criteria) this; } public Criteria andFileSizeLessThanOrEqualTo(Long value) { addCriterion("file_size <=", value, "fileSize"); return (Criteria) this; } public Criteria andFileSizeIn(List<Long> values) { addCriterion("file_size in", values, "fileSize"); return (Criteria) this; } public Criteria andFileSizeNotIn(List<Long> values) { addCriterion("file_size not in", values, "fileSize"); return (Criteria) this; } public Criteria andFileSizeBetween(Long value1, Long value2) { addCriterion("file_size between", value1, value2, "fileSize"); return (Criteria) this; } public Criteria andFileSizeNotBetween(Long value1, Long value2) { addCriterion("file_size not between", value1, value2, "fileSize"); return (Criteria) this; } public Criteria andUploadTimeIsNull() { addCriterion("upload_time is null"); return (Criteria) this; } public Criteria andUploadTimeIsNotNull() { addCriterion("upload_time is not null"); return (Criteria) this; } public Criteria andUploadTimeEqualTo(Date value) { addCriterion("upload_time =", value, "uploadTime"); return (Criteria) this; } public Criteria andUploadTimeNotEqualTo(Date value) { addCriterion("upload_time <>", value, "uploadTime"); return (Criteria) this; } public Criteria andUploadTimeGreaterThan(Date value) { addCriterion("upload_time >", value, "uploadTime"); return (Criteria) this; } public Criteria andUploadTimeGreaterThanOrEqualTo(Date value) { addCriterion("upload_time >=", value, "uploadTime"); return (Criteria) this; } public Criteria andUploadTimeLessThan(Date value) { addCriterion("upload_time <", value, "uploadTime"); return (Criteria) this; } public Criteria andUploadTimeLessThanOrEqualTo(Date value) { addCriterion("upload_time <=", value, "uploadTime"); return (Criteria) this; } public Criteria andUploadTimeIn(List<Date> values) { addCriterion("upload_time in", values, "uploadTime"); return (Criteria) this; } public Criteria andUploadTimeNotIn(List<Date> values) { addCriterion("upload_time not in", values, "uploadTime"); return (Criteria) this; } public Criteria andUploadTimeBetween(Date value1, Date value2) { addCriterion("upload_time between", value1, value2, "uploadTime"); return (Criteria) this; } public Criteria andUploadTimeNotBetween(Date value1, Date value2) { addCriterion("upload_time not between", value1, value2, "uploadTime"); return (Criteria) this; } public Criteria andUploadorUidIsNull() { addCriterion("uploador_uid is null"); return (Criteria) this; } public Criteria andUploadorUidIsNotNull() { addCriterion("uploador_uid is not null"); return (Criteria) this; } public Criteria andUploadorUidEqualTo(Integer value) { addCriterion("uploador_uid =", value, "uploadorUid"); return (Criteria) this; } public Criteria andUploadorUidNotEqualTo(Integer value) { addCriterion("uploador_uid <>", value, "uploadorUid"); return (Criteria) this; } public Criteria andUploadorUidGreaterThan(Integer value) { addCriterion("uploador_uid >", value, "uploadorUid"); return (Criteria) this; } public Criteria andUploadorUidGreaterThanOrEqualTo(Integer value) { addCriterion("uploador_uid >=", value, "uploadorUid"); return (Criteria) this; } public Criteria andUploadorUidLessThan(Integer value) { addCriterion("uploador_uid <", value, "uploadorUid"); return (Criteria) this; } public Criteria andUploadorUidLessThanOrEqualTo(Integer value) { addCriterion("uploador_uid <=", value, "uploadorUid"); return (Criteria) this; } public Criteria andUploadorUidIn(List<Integer> values) { addCriterion("uploador_uid in", values, "uploadorUid"); return (Criteria) this; } public Criteria andUploadorUidNotIn(List<Integer> values) { addCriterion("uploador_uid not in", values, "uploadorUid"); return (Criteria) this; } public Criteria andUploadorUidBetween(Integer value1, Integer value2) { addCriterion("uploador_uid between", value1, value2, "uploadorUid"); return (Criteria) this; } public Criteria andUploadorUidNotBetween(Integer value1, Integer value2) { addCriterion("uploador_uid not between", value1, value2, "uploadorUid"); return (Criteria) this; } } public static class Criteria extends GeneratedCriteria { protected Criteria() { super(); } } public static class Criterion { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } } <|start_filename|>src/main/java/com/daxiang/exception/ServerException.java<|end_filename|> package com.daxiang.exception; /** * Created by jiangyitao. */ public class ServerException extends RuntimeException { public ServerException(String msg) { super(msg); } public ServerException(Throwable cause) { super(cause); } } <|start_filename|>src/main/java/com/daxiang/dao/UserProjectDao.java<|end_filename|> package com.daxiang.dao; import com.daxiang.mbg.po.UserProject; import com.daxiang.model.dto.UserProjectDto; import org.apache.ibatis.annotations.Param; import java.util.List; /** * Created by jiangyitao. */ public interface UserProjectDao { int insertBatch(@Param("userProjects") List<UserProject> userProjects); List<UserProjectDto> selectUserProjectDtosByUserIds(@Param("userIds") List<Integer> userIds); } <|start_filename|>src/main/java/com/daxiang/service/DeviceTestTaskService.java<|end_filename|> package com.daxiang.service; import com.daxiang.exception.ServerException; import com.daxiang.mbg.mapper.DeviceTestTaskMapper; import com.daxiang.mbg.po.DeviceTestTaskExample; import com.daxiang.model.PageRequest; import com.daxiang.model.PagedData; import com.daxiang.model.action.Step; import com.daxiang.model.dto.Testcase; import com.github.pagehelper.PageHelper; import com.github.pagehelper.Page; import com.daxiang.mbg.po.DeviceTestTask; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.util.CollectionUtils; import org.springframework.util.StringUtils; import java.util.List; /** * Created by jiangyitao. */ @Slf4j @Service public class DeviceTestTaskService { @Autowired private DeviceTestTaskMapper deviceTestTaskMapper; @Autowired private FileService fileService; public void update(DeviceTestTask deviceTestTask) { int updateCount = deviceTestTaskMapper.updateByPrimaryKeySelective(deviceTestTask); if (updateCount != 1) { throw new ServerException("更新失败,请稍后重试"); } } public PagedData<DeviceTestTask> list(DeviceTestTask query, String orderBy, PageRequest pageRequest) { Page page = PageHelper.startPage(pageRequest.getPageNum(), pageRequest.getPageSize()); List<DeviceTestTask> deviceTestTasks = getDeviceTestTasks(query, orderBy); return new PagedData<>(deviceTestTasks, page.getTotal()); } public List<DeviceTestTask> getDeviceTestTasks(DeviceTestTask query) { return getDeviceTestTasks(query, null); } public List<DeviceTestTask> getDeviceTestTasks(DeviceTestTask query, String orderBy) { DeviceTestTaskExample example = new DeviceTestTaskExample(); if (query != null) { DeviceTestTaskExample.Criteria criteria = example.createCriteria(); if (query.getId() != null) { criteria.andIdEqualTo(query.getId()); } if (query.getTestTaskId() != null) { criteria.andTestTaskIdEqualTo(query.getTestTaskId()); } if (!StringUtils.isEmpty(query.getDeviceId())) { criteria.andDeviceIdEqualTo(query.getDeviceId()); } if (query.getStatus() != null) { criteria.andStatusEqualTo(query.getStatus()); } } if (!StringUtils.isEmpty(orderBy)) { example.setOrderByClause(orderBy); } return deviceTestTaskMapper.selectByExampleWithBLOBs(example); } public DeviceTestTask getFirstUnStartDeviceTestTask(String deviceId) { if (StringUtils.isEmpty(deviceId)) { throw new ServerException("deviceId不能为空"); } DeviceTestTask query = new DeviceTestTask(); query.setDeviceId(deviceId); query.setStatus(DeviceTestTask.UNSTART_STATUS); List<DeviceTestTask> deviceTestTasks = getDeviceTestTasks(query, "id asc limit 1"); return CollectionUtils.isEmpty(deviceTestTasks) ? null : deviceTestTasks.get(0); } public void updateTestcase(Integer deviceTestTaskId, Testcase sourceTestcase) { if (deviceTestTaskId == null) { throw new ServerException("deviceTestTaskId不能为空"); } DeviceTestTask deviceTestTask = deviceTestTaskMapper.selectByPrimaryKey(deviceTestTaskId); if (deviceTestTask == null) { throw new ServerException("deviceTestTask不存在"); } deviceTestTask.getTestcases().stream() .filter(testcase -> testcase.getId().equals(sourceTestcase.getId())) .findFirst() .ifPresent(testcase -> { // 更新testcase运行结果 copyTestcaseProperties(sourceTestcase, testcase); if (!CollectionUtils.isEmpty(sourceTestcase.getSteps())) { updateSteps(testcase.getSteps(), sourceTestcase.getSteps().get(0)); } else if (!CollectionUtils.isEmpty(sourceTestcase.getSetUp())) { updateSteps(testcase.getSetUp(), sourceTestcase.getSetUp().get(0)); } else if (!CollectionUtils.isEmpty(sourceTestcase.getTearDown())) { updateSteps(testcase.getTearDown(), sourceTestcase.getTearDown().get(0)); } }); int updateCount = deviceTestTaskMapper.updateByPrimaryKeySelective(deviceTestTask); if (updateCount != 1) { throw new ServerException("更新失败,请稍后重试"); } } private void updateSteps(List<Step> steps, Step sourceStep) { steps.stream() .filter(step -> step.getNumber().equals(sourceStep.getNumber())) .findFirst() .ifPresent(step -> { // 更新step运行结果 copyStepProperties(sourceStep, step); }); } private void copyStepProperties(Step sourceStep, Step targetStep) { if (sourceStep.getStartTime() != null) { targetStep.setStartTime(sourceStep.getStartTime()); } if (sourceStep.getEndTime() != null) { targetStep.setEndTime(sourceStep.getEndTime()); } } private void copyTestcaseProperties(Testcase sourceTestcase, Testcase targetTestcase) { if (sourceTestcase.getStatus() != null) { targetTestcase.setStatus(sourceTestcase.getStatus()); } if (sourceTestcase.getStartTime() != null) { targetTestcase.setStartTime(sourceTestcase.getStartTime()); } if (sourceTestcase.getEndTime() != null) { targetTestcase.setEndTime(sourceTestcase.getEndTime()); } if (!StringUtils.isEmpty(sourceTestcase.getFailInfo())) { targetTestcase.setFailInfo(sourceTestcase.getFailInfo()); } if (!StringUtils.isEmpty(sourceTestcase.getFailImgPath())) { targetTestcase.setFailImgPath(sourceTestcase.getFailImgPath()); } if (!StringUtils.isEmpty(sourceTestcase.getVideoPath())) { targetTestcase.setVideoPath(sourceTestcase.getVideoPath()); } if (!StringUtils.isEmpty(sourceTestcase.getLogPath())) { targetTestcase.setLogPath(sourceTestcase.getLogPath()); } } public void add(DeviceTestTask deviceTestTask) { int insertCount = deviceTestTaskMapper.insertSelective(deviceTestTask); if (insertCount != 1) { throw new ServerException("添加失败"); } } public List<DeviceTestTask> getDeviceTestTasksByTestTaskId(Integer testTaskId) { DeviceTestTask query = new DeviceTestTask(); query.setTestTaskId(testTaskId); return getDeviceTestTasks(query); } public List<DeviceTestTask> getDeviceTestTasksByTestTaskIds(List<Integer> testTaskIds) { DeviceTestTaskExample example = new DeviceTestTaskExample(); DeviceTestTaskExample.Criteria criteria = example.createCriteria(); criteria.andTestTaskIdIn(testTaskIds); return deviceTestTaskMapper.selectByExampleWithBLOBs(example); } public void deleteBatch(List<Integer> ids) { if (CollectionUtils.isEmpty(ids)) { return; } DeviceTestTaskExample example = new DeviceTestTaskExample(); DeviceTestTaskExample.Criteria criteria = example.createCriteria(); criteria.andIdIn(ids); int deleteCount = deviceTestTaskMapper.deleteByExample(example); if (deleteCount != ids.size()) { throw new ServerException("删除失败"); } } public void deleteAndClearRelatedRes(Integer deviceTestTaskId) { if (deviceTestTaskId == null) { throw new ServerException("deviceTestTaskId不能为空"); } DeviceTestTask deviceTestTask = deviceTestTaskMapper.selectByPrimaryKey(deviceTestTaskId); if (deviceTestTask == null) { throw new ServerException("deviceTestTask不存在"); } if (deviceTestTask.getStatus() == DeviceTestTask.RUNNING_STATUS) { throw new ServerException("deviceTestTask正在执行,无法删除"); } int deleteCount = deviceTestTaskMapper.deleteByPrimaryKey(deviceTestTaskId); if (deleteCount != 1) { throw new ServerException("删除失败,请稍后重试"); } clearRelatedRes(deviceTestTask); } public void clearRelatedRes(DeviceTestTask deviceTestTask) { List<Testcase> testcases = deviceTestTask.getTestcases(); if (!CollectionUtils.isEmpty(testcases)) { testcases.forEach(testcase -> { fileService.deleteQuietly(testcase.getFailImgPath()); fileService.deleteQuietly(testcase.getVideoPath()); fileService.deleteQuietly(testcase.getLogPath()); }); } } } <|start_filename|>src/main/java/com/daxiang/model/dto/Testcase.java<|end_filename|> package com.daxiang.model.dto; import com.alibaba.fastjson.annotation.JSONField; import com.daxiang.mbg.po.Action; import com.daxiang.utils.HttpServletUtil; import com.fasterxml.jackson.annotation.JsonFormat; import lombok.Data; import org.springframework.format.annotation.DateTimeFormat; import org.springframework.util.StringUtils; import java.util.Date; /** * Created by jiangyitao. */ @Data public class Testcase extends Action { public static final int FAIL_STATUS = 0; public static final int PASS_STATUS = 1; public static final int SKIP_STATUS = 2; @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss.SSS", timezone = "GMT+8") @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss.SSS") private Date startTime; @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss.SSS", timezone = "GMT+8") @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss.SSS") private Date endTime; /** * 失败截图 */ private String failImgPath; @JSONField(serialize = false) // 不会序列化的表中 private String failImgUrl; /** * 失败信息 */ private String failInfo; /** * 运行视频 */ private String videoPath; @JSONField(serialize = false) // 不会序列化的表中 private String videoUrl; private String logPath; @JSONField(serialize = false) // 不会序列化的表中 private String logUrl; private Integer status; public String getFailImgUrl() { if (!StringUtils.isEmpty(failImgPath)) return HttpServletUtil.getStaticResourceUrl(failImgPath); return null; } public String getVideoUrl() { if (!StringUtils.isEmpty(videoPath)) return HttpServletUtil.getStaticResourceUrl(videoPath); return null; } public String getLogUrl() { if (!StringUtils.isEmpty(logPath)) return HttpServletUtil.getStaticResourceUrl(logPath); return null; } } <|start_filename|>src/main/java/com/daxiang/model/vo/ProjectVo.java<|end_filename|> package com.daxiang.model.vo; import com.daxiang.mbg.po.Project; import lombok.Data; /** * Created by jiangyitao. */ @Data public class ProjectVo extends Project { private String creatorNickName = ""; } <|start_filename|>src/main/java/com/daxiang/model/dto/ActionTreeNode.java<|end_filename|> package com.daxiang.model.dto; import com.daxiang.mbg.po.Action; import com.fasterxml.jackson.annotation.JsonInclude; import lombok.Data; import org.springframework.beans.BeanUtils; import java.util.List; /** * Created by jiangyitao. */ @Data @JsonInclude(JsonInclude.Include.NON_NULL) public class ActionTreeNode extends Action { private List<ActionTreeNode> children; public static ActionTreeNode create(Action action) { ActionTreeNode actionTreeNode = new ActionTreeNode(); BeanUtils.copyProperties(action, actionTreeNode); return actionTreeNode; } } <|start_filename|>src/main/java/com/daxiang/model/vo/MobileVo.java<|end_filename|> package com.daxiang.model.vo; import com.daxiang.mbg.po.Mobile; import com.daxiang.utils.HttpServletUtil; import lombok.Data; import org.springframework.util.StringUtils; /** * Created by jiangyitao. */ @Data public class MobileVo extends Mobile { private String imgUrl; public String getImgUrl() { if (!StringUtils.isEmpty(getImgPath())) return HttpServletUtil.getStaticResourceUrl(getImgPath()); return null; } } <|start_filename|>src/main/java/com/daxiang/mbg/po/Category.java<|end_filename|> package com.daxiang.mbg.po; import com.daxiang.validator.group.UpdateGroup; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; import java.io.Serializable; import java.util.Date; public class Category implements Serializable { public static final int TYPE_PAGE = 1; public static final int TYPE_ACTION = 2; public static final int TYPE_GLOBAL_VAR = 3; public static final int TYPE_TESTCASE = 4; public static final int TYPE_BASE_ACTION = 5; @NotNull(message = "id不能为空", groups = {UpdateGroup.class}) private Integer id; /** * 父id * * @mbg.generated */ private Integer parentId; /** * 分类名字 * * @mbg.generated */ @NotBlank(message = "分类名不能为空") private String name; /** * 类型:1.page 2.action 3.全局变量 4.testcase(action) 5.基础action * * @mbg.generated */ @NotNull(message = "分类类型不能为空") private Integer type; /** * 所属项目的id * * @mbg.generated */ @NotNull(message = "项目Id不能为空") private Integer projectId; /** * 创建时间 * * @mbg.generated */ private Date createTime; /** * 创建人 * * @mbg.generated */ private Integer creatorUid; private static final long serialVersionUID = 1L; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Integer getParentId() { return parentId; } public void setParentId(Integer parentId) { this.parentId = parentId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getType() { return type; } public void setType(Integer type) { this.type = type; } public Integer getProjectId() { return projectId; } public void setProjectId(Integer projectId) { this.projectId = projectId; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Integer getCreatorUid() { return creatorUid; } public void setCreatorUid(Integer creatorUid) { this.creatorUid = creatorUid; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", parentId=").append(parentId); sb.append(", name=").append(name); sb.append(", type=").append(type); sb.append(", projectId=").append(projectId); sb.append(", createTime=").append(createTime); sb.append(", creatorUid=").append(creatorUid); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } } <|start_filename|>src/main/java/com/daxiang/typehandler/TestPlanTypeHandler.java<|end_filename|> package com.daxiang.typehandler; import com.alibaba.fastjson.JSONObject; import com.daxiang.mbg.po.TestPlan; import org.apache.ibatis.type.BaseTypeHandler; import org.apache.ibatis.type.JdbcType; import java.sql.CallableStatement; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; /** * Created by jiangyitao. */ public class TestPlanTypeHandler extends BaseTypeHandler<TestPlan> { @Override public void setNonNullParameter(PreparedStatement preparedStatement, int i, TestPlan testPlan, JdbcType jdbcType) throws SQLException { preparedStatement.setString(i, JSONObject.toJSONString(testPlan)); } @Override public TestPlan getNullableResult(ResultSet resultSet, String s) throws SQLException { return JSONObject.parseObject(resultSet.getString(s), TestPlan.class); } @Override public TestPlan getNullableResult(ResultSet resultSet, int i) throws SQLException { return JSONObject.parseObject(resultSet.getString(i), TestPlan.class); } @Override public TestPlan getNullableResult(CallableStatement callableStatement, int i) throws SQLException { return JSONObject.parseObject(callableStatement.getString(i), TestPlan.class); } } <|start_filename|>src/main/java/com/daxiang/model/dto/UserDto.java<|end_filename|> package com.daxiang.model.dto; import com.daxiang.mbg.po.Project; import com.daxiang.mbg.po.Role; import com.daxiang.mbg.po.User; import com.fasterxml.jackson.annotation.JsonIgnore; import lombok.Data; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.NotNull; import java.util.Collection; import java.util.List; import java.util.stream.Collectors; /** * Created by jiangyitao. */ @Data public class UserDto extends User implements UserDetails { @NotEmpty(message = "角色不能为空") private List<Role> roles; @NotNull(message = "projects不能为null") private List<Project> projects; @JsonIgnore @Override public Collection<? extends GrantedAuthority> getAuthorities() { return roles.stream() .map(role -> new SimpleGrantedAuthority(role.getName())) .collect(Collectors.toList()); } @JsonIgnore @Override public boolean isAccountNonExpired() { return true; } @JsonIgnore @Override public boolean isAccountNonLocked() { return true; } @JsonIgnore @Override public boolean isCredentialsNonExpired() { return true; } @JsonIgnore @Override public boolean isEnabled() { return getStatus() == User.ENABLE_STATUS; } } <|start_filename|>src/main/java/com/daxiang/model/vo/DriverVo.java<|end_filename|> package com.daxiang.model.vo; import com.daxiang.mbg.po.Driver; import lombok.Data; /** * Created by jiangyitao. */ @Data public class DriverVo extends Driver { private String creatorNickName = ""; } <|start_filename|>src/main/java/com/daxiang/model/vo/TestPlanVo.java<|end_filename|> package com.daxiang.model.vo; import com.daxiang.mbg.po.TestPlan; import lombok.Data; /** * Created by jiangyitao. */ @Data public class TestPlanVo extends TestPlan { private String creatorNickName = ""; } <|start_filename|>src/main/java/com/daxiang/model/vo/AgentVo.java<|end_filename|> package com.daxiang.model.vo; import com.daxiang.mbg.po.Browser; import com.daxiang.mbg.po.Mobile; import lombok.Data; import java.util.List; /** * Created by jiangyitao. */ @Data public class AgentVo { private String instanceId; private String version; private String ip; private Integer port; private String osName; private String javaVersion; private String appiumVersion; private Boolean isConfigAapt; private List<Mobile> mobiles; private List<Browser> browsers; } <|start_filename|>src/main/java/com/daxiang/service/AgentExtJarService.java<|end_filename|> package com.daxiang.service; import com.daxiang.agent.AgentClient; import com.daxiang.dao.AgentExtJarDao; import com.daxiang.exception.ServerException; import com.daxiang.mbg.mapper.AgentExtJarMapper; import com.daxiang.mbg.po.AgentExtJar; import com.daxiang.mbg.po.AgentExtJarExample; import com.daxiang.mbg.po.User; import com.daxiang.model.*; import com.daxiang.model.enums.UploadDir; import com.daxiang.model.vo.AgentExtJarVo; import com.daxiang.model.vo.AgentVo; import com.daxiang.security.SecurityUtil; import com.daxiang.utils.HttpServletUtil; import com.github.pagehelper.Page; import com.github.pagehelper.PageHelper; import lombok.extern.slf4j.Slf4j; import org.apache.commons.io.FileUtils; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DuplicateKeyException; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.CollectionUtils; import org.springframework.util.DigestUtils; import org.springframework.util.StringUtils; import org.springframework.web.multipart.MultipartFile; import java.io.IOException; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; /** * Created by jiangyitao. */ @Slf4j @Service public class AgentExtJarService { @Autowired private AgentExtJarMapper agentExtJarMapper; @Autowired private AgentExtJarDao agentExtJarDao; @Autowired private FileService fileService; @Autowired private UserService userService; @Autowired private AgentService agentService; @Autowired private AgentClient agentClient; @Transactional public void upload(MultipartFile file) { if (file == null) { throw new ServerException("file不能为空"); } String filename = file.getOriginalFilename(); if (!StringUtils.hasText(filename)) { throw new ServerException("文件名不能为空"); } // eg.spring-boot-2.1.4.RELEASE.jar Matcher matcher = Pattern.compile("(.+)-([0-9].*)\\.jar").matcher(filename); String jarName = null; String jarVersion = null; while (matcher.find()) { jarName = matcher.group(1); // spring-boot jarVersion = matcher.group(2); // 2.1.4.RELEASE } if (StringUtils.isEmpty(jarName) || StringUtils.isEmpty(jarVersion)) { throw new ServerException(filename + "格式错误,正确格式示例: commons-io-2.6.jar"); } if (fileService.exist(UploadDir.AGENT_EXT_JAR, filename)) { throw new ServerException(filename + "已存在"); } AgentExtJar agentExtJar = new AgentExtJar(); agentExtJar.setName(jarName); agentExtJar.setVersion(jarVersion); agentExtJar.setUploadorUid(SecurityUtil.getCurrentUserId()); agentExtJar.setUploadTime(new Date()); UploadFile uploadFile = fileService.upload(file, UploadDir.AGENT_EXT_JAR, false); agentExtJar.setFilePath(uploadFile.getFilePath()); agentExtJar.setFileSize(uploadFile.getFile().length()); try { String md5 = DigestUtils.md5DigestAsHex(FileUtils.readFileToByteArray(uploadFile.getFile())); agentExtJar.setMd5(md5); } catch (IOException e) { log.error("read file err, file={}", agentExtJar.getFilePath(), e); fileService.deleteQuietly(agentExtJar.getFilePath()); throw new ServerException(e.getMessage()); } int insertRow; try { insertRow = agentExtJarMapper.insertSelective(agentExtJar); } catch (Exception e) { fileService.deleteQuietly(agentExtJar.getFilePath()); if (e instanceof DuplicateKeyException) { throw new ServerException(filename + "已存在"); } throw new ServerException(e); } if (insertRow != 1) { fileService.deleteQuietly(agentExtJar.getFilePath()); throw new ServerException(filename + "添加失败,请稍后重试"); } List<AgentVo> onlineAgents = agentService.getOnlineAgentsWithoutDevices(); if (CollectionUtils.isEmpty(onlineAgents)) { return; } boolean anyAgentLoadJarSuccess = false; String jarUrl = HttpServletUtil.getStaticResourceUrl(agentExtJar.getFilePath()); // 分发jar到在线的agent for (AgentVo onlineAgent : onlineAgents) { Response response = agentClient.loadJar(onlineAgent.getIp(), onlineAgent.getPort(), jarUrl); if (response.isSuccess()) { anyAgentLoadJarSuccess = true; } else { log.warn("agent({}) load jar({}) fail, response={}", onlineAgent.getIp(), agentExtJar.getFilePath(), response); } } // 只要有1个agent加载成功,就认为这个jar是合法的 if (!anyAgentLoadJarSuccess) { fileService.deleteQuietly(agentExtJar.getFilePath()); throw new ServerException("agent加载" + filename + "失败,请检查文件是否合法"); } } public void delete(Integer id) { if (id == null) { throw new ServerException("id不能为空"); } AgentExtJar agentExtJar = agentExtJarMapper.selectByPrimaryKey(id); if (agentExtJar == null) { throw new ServerException("记录不存在"); } int deleteRow = agentExtJarMapper.deleteByPrimaryKey(id); if (deleteRow != 1) { throw new ServerException("删除失败,请稍后重试"); } fileService.deleteQuietly(agentExtJar.getFilePath()); } public PagedData<AgentExtJarVo> list(AgentExtJar query, String orderBy, PageRequest pageRequest) { Page page = PageHelper.startPage(pageRequest.getPageNum(), pageRequest.getPageSize()); if (StringUtils.isEmpty(orderBy)) { orderBy = "id desc"; } List<AgentExtJarVo> agentExtJarVos = getAgentExtJarVos(query, orderBy); return new PagedData<>(agentExtJarVos, page.getTotal()); } public List<AgentExtJarVo> getAgentExtJarVos(AgentExtJar query, String orderBy) { List<AgentExtJar> agentExtJars = getAgentExtJars(query, orderBy); return convertAgentExtJarsToAgentExtJarVos(agentExtJars); } public List<AgentExtJar> getAgentExtJars(AgentExtJar query, String orderBy) { AgentExtJarExample example = new AgentExtJarExample(); if (query != null) { AgentExtJarExample.Criteria criteria = example.createCriteria(); if (query.getId() != null) { criteria.andIdEqualTo(query.getId()); } if (!StringUtils.isEmpty(query.getMd5())) { criteria.andMd5EqualTo(query.getMd5()); } if (!StringUtils.isEmpty(query.getName())) { criteria.andNameLike("%" + query.getName() + "%"); } } if (!StringUtils.isEmpty(orderBy)) { example.setOrderByClause(orderBy); } return agentExtJarMapper.selectByExample(example); } private List<AgentExtJarVo> convertAgentExtJarsToAgentExtJarVos(List<AgentExtJar> agentExtJars) { if (CollectionUtils.isEmpty(agentExtJars)) { return new ArrayList<>(); } List<Integer> uploadorUids = agentExtJars.stream() .map(AgentExtJar::getUploadorUid) .filter(Objects::nonNull) .distinct() .collect(Collectors.toList()); Map<Integer, User> userMap = userService.getUserMapByIds(uploadorUids); List<AgentExtJarVo> agentExtJarVos = agentExtJars.stream().map(agentExtJar -> { AgentExtJarVo agentExtJarVo = new AgentExtJarVo(); BeanUtils.copyProperties(agentExtJar, agentExtJarVo); User user = userMap.get(agentExtJar.getUploadorUid()); if (user != null) { agentExtJarVo.setUploadorNickName(user.getNickName()); } return agentExtJarVo; }).collect(Collectors.toList()); return agentExtJarVos; } public List<AgentExtJarVo> getLastUploadTimeList() { List<AgentExtJar> agentExtJars = agentExtJarDao.selectLastUploadTimeList(); return agentExtJars.stream().map(agentExtJar -> { AgentExtJarVo agentExtJarVo = new AgentExtJarVo(); BeanUtils.copyProperties(agentExtJar, agentExtJarVo); return agentExtJarVo; }).collect(Collectors.toList()); } } <|start_filename|>src/main/java/com/daxiang/mbg/po/BrowserExample.java<|end_filename|> package com.daxiang.mbg.po; import java.util.ArrayList; import java.util.Date; import java.util.List; public class BrowserExample { protected String orderByClause; protected boolean distinct; protected List<Criteria> oredCriteria; public BrowserExample() { oredCriteria = new ArrayList<Criteria>(); } public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } public String getOrderByClause() { return orderByClause; } public void setDistinct(boolean distinct) { this.distinct = distinct; } public boolean isDistinct() { return distinct; } public List<Criteria> getOredCriteria() { return oredCriteria; } public void or(Criteria criteria) { oredCriteria.add(criteria); } public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } protected abstract static class GeneratedCriteria { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andIdIsNull() { addCriterion("id is null"); return (Criteria) this; } public Criteria andIdIsNotNull() { addCriterion("id is not null"); return (Criteria) this; } public Criteria andIdEqualTo(String value) { addCriterion("id =", value, "id"); return (Criteria) this; } public Criteria andIdNotEqualTo(String value) { addCriterion("id <>", value, "id"); return (Criteria) this; } public Criteria andIdGreaterThan(String value) { addCriterion("id >", value, "id"); return (Criteria) this; } public Criteria andIdGreaterThanOrEqualTo(String value) { addCriterion("id >=", value, "id"); return (Criteria) this; } public Criteria andIdLessThan(String value) { addCriterion("id <", value, "id"); return (Criteria) this; } public Criteria andIdLessThanOrEqualTo(String value) { addCriterion("id <=", value, "id"); return (Criteria) this; } public Criteria andIdLike(String value) { addCriterion("id like", value, "id"); return (Criteria) this; } public Criteria andIdNotLike(String value) { addCriterion("id not like", value, "id"); return (Criteria) this; } public Criteria andIdIn(List<String> values) { addCriterion("id in", values, "id"); return (Criteria) this; } public Criteria andIdNotIn(List<String> values) { addCriterion("id not in", values, "id"); return (Criteria) this; } public Criteria andIdBetween(String value1, String value2) { addCriterion("id between", value1, value2, "id"); return (Criteria) this; } public Criteria andIdNotBetween(String value1, String value2) { addCriterion("id not between", value1, value2, "id"); return (Criteria) this; } public Criteria andTypeIsNull() { addCriterion("type is null"); return (Criteria) this; } public Criteria andTypeIsNotNull() { addCriterion("type is not null"); return (Criteria) this; } public Criteria andTypeEqualTo(String value) { addCriterion("type =", value, "type"); return (Criteria) this; } public Criteria andTypeNotEqualTo(String value) { addCriterion("type <>", value, "type"); return (Criteria) this; } public Criteria andTypeGreaterThan(String value) { addCriterion("type >", value, "type"); return (Criteria) this; } public Criteria andTypeGreaterThanOrEqualTo(String value) { addCriterion("type >=", value, "type"); return (Criteria) this; } public Criteria andTypeLessThan(String value) { addCriterion("type <", value, "type"); return (Criteria) this; } public Criteria andTypeLessThanOrEqualTo(String value) { addCriterion("type <=", value, "type"); return (Criteria) this; } public Criteria andTypeLike(String value) { addCriterion("type like", value, "type"); return (Criteria) this; } public Criteria andTypeNotLike(String value) { addCriterion("type not like", value, "type"); return (Criteria) this; } public Criteria andTypeIn(List<String> values) { addCriterion("type in", values, "type"); return (Criteria) this; } public Criteria andTypeNotIn(List<String> values) { addCriterion("type not in", values, "type"); return (Criteria) this; } public Criteria andTypeBetween(String value1, String value2) { addCriterion("type between", value1, value2, "type"); return (Criteria) this; } public Criteria andTypeNotBetween(String value1, String value2) { addCriterion("type not between", value1, value2, "type"); return (Criteria) this; } public Criteria andVersionIsNull() { addCriterion("version is null"); return (Criteria) this; } public Criteria andVersionIsNotNull() { addCriterion("version is not null"); return (Criteria) this; } public Criteria andVersionEqualTo(String value) { addCriterion("version =", value, "version"); return (Criteria) this; } public Criteria andVersionNotEqualTo(String value) { addCriterion("version <>", value, "version"); return (Criteria) this; } public Criteria andVersionGreaterThan(String value) { addCriterion("version >", value, "version"); return (Criteria) this; } public Criteria andVersionGreaterThanOrEqualTo(String value) { addCriterion("version >=", value, "version"); return (Criteria) this; } public Criteria andVersionLessThan(String value) { addCriterion("version <", value, "version"); return (Criteria) this; } public Criteria andVersionLessThanOrEqualTo(String value) { addCriterion("version <=", value, "version"); return (Criteria) this; } public Criteria andVersionLike(String value) { addCriterion("version like", value, "version"); return (Criteria) this; } public Criteria andVersionNotLike(String value) { addCriterion("version not like", value, "version"); return (Criteria) this; } public Criteria andVersionIn(List<String> values) { addCriterion("version in", values, "version"); return (Criteria) this; } public Criteria andVersionNotIn(List<String> values) { addCriterion("version not in", values, "version"); return (Criteria) this; } public Criteria andVersionBetween(String value1, String value2) { addCriterion("version between", value1, value2, "version"); return (Criteria) this; } public Criteria andVersionNotBetween(String value1, String value2) { addCriterion("version not between", value1, value2, "version"); return (Criteria) this; } public Criteria andPlatformIsNull() { addCriterion("platform is null"); return (Criteria) this; } public Criteria andPlatformIsNotNull() { addCriterion("platform is not null"); return (Criteria) this; } public Criteria andPlatformEqualTo(Integer value) { addCriterion("platform =", value, "platform"); return (Criteria) this; } public Criteria andPlatformNotEqualTo(Integer value) { addCriterion("platform <>", value, "platform"); return (Criteria) this; } public Criteria andPlatformGreaterThan(Integer value) { addCriterion("platform >", value, "platform"); return (Criteria) this; } public Criteria andPlatformGreaterThanOrEqualTo(Integer value) { addCriterion("platform >=", value, "platform"); return (Criteria) this; } public Criteria andPlatformLessThan(Integer value) { addCriterion("platform <", value, "platform"); return (Criteria) this; } public Criteria andPlatformLessThanOrEqualTo(Integer value) { addCriterion("platform <=", value, "platform"); return (Criteria) this; } public Criteria andPlatformIn(List<Integer> values) { addCriterion("platform in", values, "platform"); return (Criteria) this; } public Criteria andPlatformNotIn(List<Integer> values) { addCriterion("platform not in", values, "platform"); return (Criteria) this; } public Criteria andPlatformBetween(Integer value1, Integer value2) { addCriterion("platform between", value1, value2, "platform"); return (Criteria) this; } public Criteria andPlatformNotBetween(Integer value1, Integer value2) { addCriterion("platform not between", value1, value2, "platform"); return (Criteria) this; } public Criteria andStatusIsNull() { addCriterion("status is null"); return (Criteria) this; } public Criteria andStatusIsNotNull() { addCriterion("status is not null"); return (Criteria) this; } public Criteria andStatusEqualTo(Integer value) { addCriterion("status =", value, "status"); return (Criteria) this; } public Criteria andStatusNotEqualTo(Integer value) { addCriterion("status <>", value, "status"); return (Criteria) this; } public Criteria andStatusGreaterThan(Integer value) { addCriterion("status >", value, "status"); return (Criteria) this; } public Criteria andStatusGreaterThanOrEqualTo(Integer value) { addCriterion("status >=", value, "status"); return (Criteria) this; } public Criteria andStatusLessThan(Integer value) { addCriterion("status <", value, "status"); return (Criteria) this; } public Criteria andStatusLessThanOrEqualTo(Integer value) { addCriterion("status <=", value, "status"); return (Criteria) this; } public Criteria andStatusIn(List<Integer> values) { addCriterion("status in", values, "status"); return (Criteria) this; } public Criteria andStatusNotIn(List<Integer> values) { addCriterion("status not in", values, "status"); return (Criteria) this; } public Criteria andStatusBetween(Integer value1, Integer value2) { addCriterion("status between", value1, value2, "status"); return (Criteria) this; } public Criteria andStatusNotBetween(Integer value1, Integer value2) { addCriterion("status not between", value1, value2, "status"); return (Criteria) this; } public Criteria andAgentIpIsNull() { addCriterion("agent_ip is null"); return (Criteria) this; } public Criteria andAgentIpIsNotNull() { addCriterion("agent_ip is not null"); return (Criteria) this; } public Criteria andAgentIpEqualTo(String value) { addCriterion("agent_ip =", value, "agentIp"); return (Criteria) this; } public Criteria andAgentIpNotEqualTo(String value) { addCriterion("agent_ip <>", value, "agentIp"); return (Criteria) this; } public Criteria andAgentIpGreaterThan(String value) { addCriterion("agent_ip >", value, "agentIp"); return (Criteria) this; } public Criteria andAgentIpGreaterThanOrEqualTo(String value) { addCriterion("agent_ip >=", value, "agentIp"); return (Criteria) this; } public Criteria andAgentIpLessThan(String value) { addCriterion("agent_ip <", value, "agentIp"); return (Criteria) this; } public Criteria andAgentIpLessThanOrEqualTo(String value) { addCriterion("agent_ip <=", value, "agentIp"); return (Criteria) this; } public Criteria andAgentIpLike(String value) { addCriterion("agent_ip like", value, "agentIp"); return (Criteria) this; } public Criteria andAgentIpNotLike(String value) { addCriterion("agent_ip not like", value, "agentIp"); return (Criteria) this; } public Criteria andAgentIpIn(List<String> values) { addCriterion("agent_ip in", values, "agentIp"); return (Criteria) this; } public Criteria andAgentIpNotIn(List<String> values) { addCriterion("agent_ip not in", values, "agentIp"); return (Criteria) this; } public Criteria andAgentIpBetween(String value1, String value2) { addCriterion("agent_ip between", value1, value2, "agentIp"); return (Criteria) this; } public Criteria andAgentIpNotBetween(String value1, String value2) { addCriterion("agent_ip not between", value1, value2, "agentIp"); return (Criteria) this; } public Criteria andAgentPortIsNull() { addCriterion("agent_port is null"); return (Criteria) this; } public Criteria andAgentPortIsNotNull() { addCriterion("agent_port is not null"); return (Criteria) this; } public Criteria andAgentPortEqualTo(Integer value) { addCriterion("agent_port =", value, "agentPort"); return (Criteria) this; } public Criteria andAgentPortNotEqualTo(Integer value) { addCriterion("agent_port <>", value, "agentPort"); return (Criteria) this; } public Criteria andAgentPortGreaterThan(Integer value) { addCriterion("agent_port >", value, "agentPort"); return (Criteria) this; } public Criteria andAgentPortGreaterThanOrEqualTo(Integer value) { addCriterion("agent_port >=", value, "agentPort"); return (Criteria) this; } public Criteria andAgentPortLessThan(Integer value) { addCriterion("agent_port <", value, "agentPort"); return (Criteria) this; } public Criteria andAgentPortLessThanOrEqualTo(Integer value) { addCriterion("agent_port <=", value, "agentPort"); return (Criteria) this; } public Criteria andAgentPortIn(List<Integer> values) { addCriterion("agent_port in", values, "agentPort"); return (Criteria) this; } public Criteria andAgentPortNotIn(List<Integer> values) { addCriterion("agent_port not in", values, "agentPort"); return (Criteria) this; } public Criteria andAgentPortBetween(Integer value1, Integer value2) { addCriterion("agent_port between", value1, value2, "agentPort"); return (Criteria) this; } public Criteria andAgentPortNotBetween(Integer value1, Integer value2) { addCriterion("agent_port not between", value1, value2, "agentPort"); return (Criteria) this; } public Criteria andLastOnlineTimeIsNull() { addCriterion("last_online_time is null"); return (Criteria) this; } public Criteria andLastOnlineTimeIsNotNull() { addCriterion("last_online_time is not null"); return (Criteria) this; } public Criteria andLastOnlineTimeEqualTo(Date value) { addCriterion("last_online_time =", value, "lastOnlineTime"); return (Criteria) this; } public Criteria andLastOnlineTimeNotEqualTo(Date value) { addCriterion("last_online_time <>", value, "lastOnlineTime"); return (Criteria) this; } public Criteria andLastOnlineTimeGreaterThan(Date value) { addCriterion("last_online_time >", value, "lastOnlineTime"); return (Criteria) this; } public Criteria andLastOnlineTimeGreaterThanOrEqualTo(Date value) { addCriterion("last_online_time >=", value, "lastOnlineTime"); return (Criteria) this; } public Criteria andLastOnlineTimeLessThan(Date value) { addCriterion("last_online_time <", value, "lastOnlineTime"); return (Criteria) this; } public Criteria andLastOnlineTimeLessThanOrEqualTo(Date value) { addCriterion("last_online_time <=", value, "lastOnlineTime"); return (Criteria) this; } public Criteria andLastOnlineTimeIn(List<Date> values) { addCriterion("last_online_time in", values, "lastOnlineTime"); return (Criteria) this; } public Criteria andLastOnlineTimeNotIn(List<Date> values) { addCriterion("last_online_time not in", values, "lastOnlineTime"); return (Criteria) this; } public Criteria andLastOnlineTimeBetween(Date value1, Date value2) { addCriterion("last_online_time between", value1, value2, "lastOnlineTime"); return (Criteria) this; } public Criteria andLastOnlineTimeNotBetween(Date value1, Date value2) { addCriterion("last_online_time not between", value1, value2, "lastOnlineTime"); return (Criteria) this; } public Criteria andUsernameIsNull() { addCriterion("username is null"); return (Criteria) this; } public Criteria andUsernameIsNotNull() { addCriterion("username is not null"); return (Criteria) this; } public Criteria andUsernameEqualTo(String value) { addCriterion("username =", value, "username"); return (Criteria) this; } public Criteria andUsernameNotEqualTo(String value) { addCriterion("username <>", value, "username"); return (Criteria) this; } public Criteria andUsernameGreaterThan(String value) { addCriterion("username >", value, "username"); return (Criteria) this; } public Criteria andUsernameGreaterThanOrEqualTo(String value) { addCriterion("username >=", value, "username"); return (Criteria) this; } public Criteria andUsernameLessThan(String value) { addCriterion("username <", value, "username"); return (Criteria) this; } public Criteria andUsernameLessThanOrEqualTo(String value) { addCriterion("username <=", value, "username"); return (Criteria) this; } public Criteria andUsernameLike(String value) { addCriterion("username like", value, "username"); return (Criteria) this; } public Criteria andUsernameNotLike(String value) { addCriterion("username not like", value, "username"); return (Criteria) this; } public Criteria andUsernameIn(List<String> values) { addCriterion("username in", values, "username"); return (Criteria) this; } public Criteria andUsernameNotIn(List<String> values) { addCriterion("username not in", values, "username"); return (Criteria) this; } public Criteria andUsernameBetween(String value1, String value2) { addCriterion("username between", value1, value2, "username"); return (Criteria) this; } public Criteria andUsernameNotBetween(String value1, String value2) { addCriterion("username not between", value1, value2, "username"); return (Criteria) this; } public Criteria andCreateTimeIsNull() { addCriterion("create_time is null"); return (Criteria) this; } public Criteria andCreateTimeIsNotNull() { addCriterion("create_time is not null"); return (Criteria) this; } public Criteria andCreateTimeEqualTo(Date value) { addCriterion("create_time =", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeNotEqualTo(Date value) { addCriterion("create_time <>", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeGreaterThan(Date value) { addCriterion("create_time >", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeGreaterThanOrEqualTo(Date value) { addCriterion("create_time >=", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeLessThan(Date value) { addCriterion("create_time <", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeLessThanOrEqualTo(Date value) { addCriterion("create_time <=", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeIn(List<Date> values) { addCriterion("create_time in", values, "createTime"); return (Criteria) this; } public Criteria andCreateTimeNotIn(List<Date> values) { addCriterion("create_time not in", values, "createTime"); return (Criteria) this; } public Criteria andCreateTimeBetween(Date value1, Date value2) { addCriterion("create_time between", value1, value2, "createTime"); return (Criteria) this; } public Criteria andCreateTimeNotBetween(Date value1, Date value2) { addCriterion("create_time not between", value1, value2, "createTime"); return (Criteria) this; } } public static class Criteria extends GeneratedCriteria { protected Criteria() { super(); } } public static class Criterion { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } } <|start_filename|>src/main/java/com/daxiang/mbg/po/AgentExtJar.java<|end_filename|> package com.daxiang.mbg.po; import java.io.Serializable; import java.util.Date; public class AgentExtJar implements Serializable { private Integer id; /** * jar name * * @mbg.generated */ private String name; /** * 版本 * * @mbg.generated */ private String version; /** * jar文件 md5 * * @mbg.generated */ private String md5; /** * 服务端保存的文件路径 * * @mbg.generated */ private String filePath; /** * 文件大小 * * @mbg.generated */ private Long fileSize; /** * 上传时间 * * @mbg.generated */ private Date uploadTime; /** * 上传人 * * @mbg.generated */ private Integer uploadorUid; private static final long serialVersionUID = 1L; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public String getMd5() { return md5; } public void setMd5(String md5) { this.md5 = md5; } public String getFilePath() { return filePath; } public void setFilePath(String filePath) { this.filePath = filePath; } public Long getFileSize() { return fileSize; } public void setFileSize(Long fileSize) { this.fileSize = fileSize; } public Date getUploadTime() { return uploadTime; } public void setUploadTime(Date uploadTime) { this.uploadTime = uploadTime; } public Integer getUploadorUid() { return uploadorUid; } public void setUploadorUid(Integer uploadorUid) { this.uploadorUid = uploadorUid; } public String getFilename() { return name + "-" + version + ".jar"; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", name=").append(name); sb.append(", version=").append(version); sb.append(", md5=").append(md5); sb.append(", filePath=").append(filePath); sb.append(", fileSize=").append(fileSize); sb.append(", uploadTime=").append(uploadTime); sb.append(", uploadorUid=").append(uploadorUid); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } } <|start_filename|>src/main/java/com/daxiang/model/page/Element.java<|end_filename|> package com.daxiang.model.page; import com.daxiang.validator.annotation.JavaIdentifier; import lombok.Data; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotEmpty; import java.util.List; /** * Created by jiangyitao. */ @Data public class Element { @JavaIdentifier(message = "element name不合法") private String name; @NotEmpty(message = "element findBy不能为空") private List<String> findBy; @NotBlank(message = "element value不能为空") private String value; private String description; } <|start_filename|>src/main/java/com/daxiang/model/vo/TestTaskSummary.java<|end_filename|> package com.daxiang.model.vo; import com.daxiang.mbg.po.TestTask; import lombok.Data; /** * Created by jiangyitao. */ @Data public class TestTaskSummary extends TestTask { private Integer platform; private String projectName; private String commitorNickName; private String passPercent; private String environmentName; } <|start_filename|>src/main/java/com/daxiang/model/vo/TestSuiteVo.java<|end_filename|> package com.daxiang.model.vo; import com.daxiang.mbg.po.TestSuite; import lombok.Data; /** * Created by jiangyitao. */ @Data public class TestSuiteVo extends TestSuite { private String creatorNickName = ""; } <|start_filename|>src/main/java/com/daxiang/service/MobileService.java<|end_filename|> package com.daxiang.service; import com.daxiang.agent.AgentClient; import com.daxiang.exception.ServerException; import com.daxiang.mbg.mapper.MobileMapper; import com.daxiang.mbg.po.Mobile; import com.daxiang.mbg.po.MobileExample; import com.daxiang.model.PageRequest; import com.daxiang.model.vo.MobileVo; import com.github.pagehelper.PageHelper; import com.github.pagehelper.Page; import com.daxiang.model.PagedData; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.util.CollectionUtils; import org.springframework.util.StringUtils; import java.util.*; import java.util.function.Function; import java.util.stream.Collectors; /** * Created by jiangyitao. */ @Service @Slf4j public class MobileService { @Autowired private MobileMapper mobileMapper; @Autowired private AgentClient agentClient; @Autowired private FileService fileService; public void save(Mobile mobile) { Mobile dbMobile = mobileMapper.selectByPrimaryKey(mobile.getId()); int saveCount; if (dbMobile == null) { // 首次接入的mobile saveCount = mobileMapper.insertSelective(mobile); } else { // 更新Mobile saveCount = mobileMapper.updateByPrimaryKeySelective(mobile); } if (saveCount != 1) { throw new ServerException("保存失败,请稍后重试"); } } public void deleteAndClearRelatedRes(String mobileId) { if (mobileId == null) { throw new ServerException("mobileId不能为空"); } Mobile mobile = mobileMapper.selectByPrimaryKey(mobileId); if (mobile == null) { throw new ServerException("mobile不存在"); } int deleteCount = mobileMapper.deleteByPrimaryKey(mobileId); if (deleteCount != 1) { throw new ServerException("删除失败,请稍后重试"); } try { agentClient.deleteMobile(mobile.getAgentIp(), mobile.getAgentPort(), mobileId); } catch (Exception ignore) { } fileService.deleteQuietly(mobile.getImgPath()); } public PagedData<MobileVo> list(Mobile query, String orderBy, PageRequest pageRequest) { Page page = PageHelper.startPage(pageRequest.getPageNum(), pageRequest.getPageSize()); if (StringUtils.isEmpty(orderBy)) { orderBy = "status desc,create_time desc"; } List<MobileVo> mobileVos = getMobileVos(query, orderBy); return new PagedData<>(mobileVos, page.getTotal()); } public List<MobileVo> getMobileVos(Mobile query, String orderBy) { List<Mobile> mobiles = getMobiles(query, orderBy); List<MobileVo> mobileVos = mobiles.stream().map(mobile -> { MobileVo mobileVo = new MobileVo(); BeanUtils.copyProperties(mobile, mobileVo); return mobileVo; }).collect(Collectors.toList()); return mobileVos; } public List<Mobile> getMobiles(Mobile query, String orderBy) { MobileExample example = new MobileExample(); if (query != null) { MobileExample.Criteria criteria = example.createCriteria(); if (!StringUtils.isEmpty(query.getId())) { criteria.andIdEqualTo(query.getId()); } if (!StringUtils.isEmpty(query.getName())) { criteria.andNameLike("%" + query.getName() + "%"); } if (query.getEmulator() != null) { criteria.andEmulatorEqualTo(query.getEmulator()); } if (!StringUtils.isEmpty(query.getSystemVersion())) { criteria.andSystemVersionEqualTo(query.getSystemVersion()); } if (!StringUtils.isEmpty(query.getAgentIp())) { criteria.andAgentIpEqualTo(query.getAgentIp()); } if (query.getAgentPort() != null) { criteria.andAgentPortEqualTo(query.getAgentPort()); } if (query.getPlatform() != null) { criteria.andPlatformEqualTo(query.getPlatform()); } if (query.getStatus() != null) { criteria.andStatusEqualTo(query.getStatus()); } } if (!StringUtils.isEmpty(orderBy)) { example.setOrderByClause(orderBy); } return mobileMapper.selectByExample(example); } public Mobile start(String mobileId) { if (StringUtils.isEmpty(mobileId)) { throw new ServerException("mobileId不能为空"); } Mobile dbMobile = mobileMapper.selectByPrimaryKey(mobileId); if (dbMobile == null) { throw new ServerException("mobile不存在"); } // 有时server被强制关闭,导致agent下mobile的状态无法同步到server // 可能会出现数据库里的mobile状态与实际不一致的情况 // 在此通过agent获取最新的mobile状态 Mobile agentMobile = null; try { agentMobile = agentClient.getMobile(dbMobile.getAgentIp(), dbMobile.getAgentPort(), dbMobile.getId()).getData(); } catch (Exception ign) { // agent可能已经关闭 } if (agentMobile == null) { if (dbMobile.getStatus() != Mobile.OFFLINE_STATUS) { // 数据库记录的不是离线,变为离线 dbMobile.setStatus(Mobile.OFFLINE_STATUS); mobileMapper.updateByPrimaryKeySelective(dbMobile); } throw new ServerException("mobile不在线"); } else { if (agentMobile.getStatus() == Mobile.IDLE_STATUS) { return agentMobile; } else { // 同步最新状态 mobileMapper.updateByPrimaryKeySelective(agentMobile); throw new ServerException("mobile未闲置"); } } } public List<Mobile> getOnlineMobiles(Integer platform) { MobileExample example = new MobileExample(); MobileExample.Criteria criteria = example.createCriteria(); criteria.andStatusNotEqualTo(Mobile.OFFLINE_STATUS); if (platform != null) { criteria.andPlatformEqualTo(platform); } return mobileMapper.selectByExample(example); } public List<Mobile> getOnlineMobilesByAgentIps(List<String> agentIps) { if (CollectionUtils.isEmpty(agentIps)) { return new ArrayList<>(); } MobileExample example = new MobileExample(); example.createCriteria() .andAgentIpIn(agentIps) .andStatusNotEqualTo(Mobile.OFFLINE_STATUS); return mobileMapper.selectByExample(example); } public void agentOffline(String agentIp) { Mobile mobile = new Mobile(); mobile.setStatus(Mobile.OFFLINE_STATUS); MobileExample example = new MobileExample(); example.createCriteria().andAgentIpEqualTo(agentIp); mobileMapper.updateByExampleSelective(mobile, example); } public List<Mobile> getMobilesByIds(Set<String> mobileIds) { if (CollectionUtils.isEmpty(mobileIds)) { return new ArrayList<>(); } MobileExample example = new MobileExample(); MobileExample.Criteria criteria = example.createCriteria(); criteria.andIdIn(new ArrayList<>(mobileIds)); return mobileMapper.selectByExample(example); } public Map<String, Mobile> getMobileMapByIds(Set<String> mobileIds) { List<Mobile> mobiles = getMobilesByIds(mobileIds); return mobiles.stream().collect(Collectors.toMap(Mobile::getId, Function.identity(), (k1, k2) -> k1)); } } <|start_filename|>src/main/java/com/daxiang/security/SecurityUtil.java<|end_filename|> package com.daxiang.security; import com.daxiang.model.dto.UserDto; import org.springframework.security.core.context.SecurityContextHolder; /** * Created by jiangyitao. */ public class SecurityUtil { public static Integer getCurrentUserId() { return getCurrentUserDto().getId(); } public static UserDto getCurrentUserDto() { return (UserDto) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); } } <|start_filename|>src/main/java/com/daxiang/dao/PageDao.java<|end_filename|> package com.daxiang.dao; import com.daxiang.mbg.po.Page; import com.daxiang.mbg.po.PageExample; import java.util.List; /** * Created by jiangyitao. */ public interface PageDao { List<Page> selectPagesWithoutWindowHierarchyByExample(PageExample example); } <|start_filename|>src/main/java/com/daxiang/mbg/mapper/UserProjectMapper.java<|end_filename|> package com.daxiang.mbg.mapper; import com.daxiang.mbg.po.UserProject; import com.daxiang.mbg.po.UserProjectExample; import java.util.List; import org.apache.ibatis.annotations.Param; public interface UserProjectMapper { long countByExample(UserProjectExample example); int deleteByExample(UserProjectExample example); int deleteByPrimaryKey(Integer id); int insert(UserProject record); int insertSelective(UserProject record); List<UserProject> selectByExample(UserProjectExample example); UserProject selectByPrimaryKey(Integer id); int updateByExampleSelective(@Param("record") UserProject record, @Param("example") UserProjectExample example); int updateByExample(@Param("record") UserProject record, @Param("example") UserProjectExample example); int updateByPrimaryKeySelective(UserProject record); int updateByPrimaryKey(UserProject record); } <|start_filename|>src/main/java/com/daxiang/dao/UserRoleDao.java<|end_filename|> package com.daxiang.dao; import com.daxiang.mbg.po.UserRole; import com.daxiang.model.dto.UserRoleDto; import org.apache.ibatis.annotations.Param; import java.util.List; /** * Created by jiangyitao. */ public interface UserRoleDao { int insertBatch(@Param("userRoles") List<UserRole> userRoles); List<UserRoleDto> selectUserRoleDtosByUserIds(@Param("userIds") List<Integer> userIds); } <|start_filename|>src/main/java/com/daxiang/security/JwtTokenFilter.java<|end_filename|> package com.daxiang.security; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpMethod; import org.springframework.security.authentication.*; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Component; import org.springframework.util.AntPathMatcher; import org.springframework.util.StringUtils; import org.springframework.web.filter.OncePerRequestFilter; import org.springframework.web.util.UrlPathHelper; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.Set; /** * Created by jiangyitao. */ @Component public class JwtTokenFilter extends OncePerRequestFilter { @Autowired private UserDetailsService userDetailsService; @Autowired private JwtAuthenticationEntryPoint authenticationEntryPoint; @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { String token = JwtTokenUtil.getTokenFromHttpRequestHeader(request); if (StringUtils.isEmpty(token)) { authenticationEntryPoint.commence(request, response, new BadCredentialsException("token不能为空")); return; } String username = JwtTokenUtil.parseUsername(token); if (username == null) { authenticationEntryPoint.commence(request, response, new BadCredentialsException("无效的token")); return; } UserDetails userDetails; try { userDetails = userDetailsService.loadUserByUsername(username); } catch (UsernameNotFoundException e) { authenticationEntryPoint.commence(request, response, e); return; } if (!userDetails.isEnabled()) { authenticationEntryPoint.commence(request, response, new DisabledException("账号已禁用")); return; } if (!userDetails.isAccountNonLocked()) { authenticationEntryPoint.commence(request, response, new LockedException("账户已锁定")); return; } if (!userDetails.isCredentialsNonExpired()) { authenticationEntryPoint.commence(request, response, new CredentialsExpiredException("凭证已过期")); return; } if (!userDetails.isAccountNonExpired()) { authenticationEntryPoint.commence(request, response, new AccountExpiredException("账号已过期")); return; } Authentication auth = new UsernamePasswordAuthenticationToken(userDetails, "", userDetails.getAuthorities()); SecurityContextHolder.getContext().setAuthentication(auth); filterChain.doFilter(request, response); } private Set<String> shouldNotFilterAntPatterns; private String shouldNotFilterHttpMethod; private AntPathMatcher antPathMatcher = new AntPathMatcher(); private UrlPathHelper urlPathHelper = new UrlPathHelper(); /** * 是否需要走doFilterInternal逻辑 */ @Override protected boolean shouldNotFilter(HttpServletRequest request) { if (shouldNotFilterHttpMethod != null && shouldNotFilterHttpMethod.equals(request.getMethod())) { return true; } if (shouldNotFilterAntPatterns != null) { return shouldNotFilterAntPatterns.stream() .anyMatch(p -> antPathMatcher.match(p, urlPathHelper.getRequestUri(request))); } return false; } public void setShouldNotFilterAntPatterns(Set<String> shouldNotFilterAntPatterns) { this.shouldNotFilterAntPatterns = shouldNotFilterAntPatterns; } public void setShouldNotFilterHttpMethod(HttpMethod shouldNotFilterHttpMethod) { this.shouldNotFilterHttpMethod = shouldNotFilterHttpMethod.toString(); } } <|start_filename|>src/main/java/com/daxiang/controller/PageController.java<|end_filename|> package com.daxiang.controller; import com.daxiang.mbg.po.Page; import com.daxiang.model.PageRequest; import com.daxiang.model.PagedData; import com.daxiang.model.Response; import com.daxiang.model.vo.PageVo; import com.daxiang.service.PageService; import com.daxiang.validator.group.UpdateGroup; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; import java.util.List; /** * Created by jiangyitao. */ @Slf4j @RestController @RequestMapping("/page") public class PageController { @Autowired private PageService pageService; @PostMapping("/add") public Response add(@Valid @RequestBody Page page) { pageService.add(page); return Response.success("添加成功", page); } @GetMapping("/{pageId}") public Response getPageVoById(@PathVariable Integer pageId) { PageVo pageVo = pageService.getPageVoById(pageId); return Response.success(pageVo); } @DeleteMapping("/{pageId}") public Response delete(@PathVariable Integer pageId) { pageService.deleteAndClearRelatedRes(pageId); return Response.success("删除成功"); } @PostMapping("/update") public Response update(@Validated({UpdateGroup.class}) @RequestBody Page page) { pageService.update(page); return Response.success("更新成功"); } @PostMapping("/list") public Response list(Page query, String orderBy, PageRequest pageRequest) { if (pageRequest.needPaging()) { PagedData<PageVo> pagedData = pageService.listWithoutWindowHierarchy(query, orderBy, pageRequest); return Response.success(pagedData); } else { List<PageVo> pageVos = pageService.getPageVosWithoutWindowHierarchy(query, orderBy); return Response.success(pageVos); } } } <|start_filename|>src/main/java/com/daxiang/model/action/LocalVar.java<|end_filename|> package com.daxiang.model.action; import com.daxiang.model.environment.EnvironmentValue; import com.daxiang.validator.annotation.JavaIdentifier; import com.daxiang.validator.annotation.NoDuplicateEnvironment; import com.fasterxml.jackson.annotation.JsonInclude; import lombok.Data; import javax.validation.Valid; import javax.validation.constraints.NotBlank; import java.util.List; /** * Created by jiangyitao. * action局部变量 */ @Data public class LocalVar { /** * 参数类型 */ @NotBlank(message = "局部变量类型不能为空") private String type; /** * 局部变量名 */ @JavaIdentifier(message = "局部变量名不合法") private String name; /** * 局部变量值 */ @Valid @NoDuplicateEnvironment(message = "局部变量环境不能重复") private List<EnvironmentValue> environmentValues; /** * 专门给agent用的 */ @JsonInclude(JsonInclude.Include.NON_NULL) private String value; /** * 变量描述 */ private String description; } <|start_filename|>src/main/java/com/daxiang/model/vo/AppVo.java<|end_filename|> package com.daxiang.model.vo; import com.daxiang.mbg.po.App; import com.daxiang.utils.HttpServletUtil; import lombok.Data; /** * Created by jiangyitao. */ @Data public class AppVo extends App { private String uploadorNickName = ""; private String downloadUrl; public String getDownloadUrl() { return HttpServletUtil.getStaticResourceUrl(getFilePath()); } } <|start_filename|>src/main/java/com/daxiang/controller/TestSuiteController.java<|end_filename|> package com.daxiang.controller; import com.daxiang.mbg.po.TestSuite; import com.daxiang.model.PageRequest; import com.daxiang.model.PagedData; import com.daxiang.model.Response; import com.daxiang.model.vo.TestSuiteVo; import com.daxiang.service.TestSuiteService; import com.daxiang.validator.group.UpdateGroup; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; import java.util.List; /** * Created by jiangyitao. */ @RestController @RequestMapping("/testSuite") public class TestSuiteController { @Autowired private TestSuiteService testSuiteService; @PostMapping("/add") public Response add(@Valid @RequestBody TestSuite testSuite) { testSuiteService.add(testSuite); return Response.success("添加成功"); } @DeleteMapping("/{testSuiteId}") public Response delete(@PathVariable Integer testSuiteId) { testSuiteService.delete(testSuiteId); return Response.success("删除成功"); } @PostMapping("/update") public Response update(@RequestBody @Validated({UpdateGroup.class}) TestSuite testSuite) { testSuiteService.update(testSuite); return Response.success("更新成功"); } @PostMapping("/list") public Response list(TestSuite query, String orderBy, PageRequest pageRequest) { if (pageRequest.needPaging()) { PagedData<TestSuiteVo> pagedData = testSuiteService.list(query, orderBy, pageRequest); return Response.success(pagedData); } else { List<TestSuiteVo> testSuiteVos = testSuiteService.getTestSuiteVos(query, orderBy); return Response.success(testSuiteVos); } } } <|start_filename|>src/main/java/com/daxiang/service/EnvironmentService.java<|end_filename|> package com.daxiang.service; import com.daxiang.exception.ServerException; import com.daxiang.mbg.mapper.EnvironmentMapper; import com.daxiang.mbg.po.*; import com.daxiang.model.PagedData; import com.daxiang.model.PageRequest; import com.daxiang.model.environment.EnvironmentValue; import com.daxiang.model.vo.EnvironmentVo; import com.daxiang.security.SecurityUtil; import com.github.pagehelper.PageHelper; import com.github.pagehelper.Page; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DuplicateKeyException; import org.springframework.stereotype.Service; import org.springframework.util.CollectionUtils; import org.springframework.util.StringUtils; import java.util.*; import java.util.stream.Collectors; /** * Created by jiangyitao. */ @Service public class EnvironmentService { @Autowired private EnvironmentMapper environmentMapper; @Autowired private ActionService actionService; @Autowired private GlobalVarService globalVarService; @Autowired private TestPlanService testPlanService; @Autowired private UserService userService; public void add(Environment environment) { environment.setCreateTime(new Date()); environment.setCreatorUid(SecurityUtil.getCurrentUserId()); try { int insertCount = environmentMapper.insertSelective(environment); if (insertCount != 1) { throw new ServerException("添加失败,请稍后重试"); } } catch (DuplicateKeyException e) { throw new ServerException(environment.getName() + "已存在"); } } public void delete(Integer environmentId) { check(environmentId); int deleteCount = environmentMapper.deleteByPrimaryKey(environmentId); if (deleteCount != 1) { throw new ServerException("删除失败,请稍后重试"); } } public void update(Environment environment) { try { int updateCount = environmentMapper.updateByPrimaryKeySelective(environment); if (updateCount != 1) { throw new ServerException("更新失败,请稍后重试"); } } catch (DuplicateKeyException e) { throw new ServerException(environment.getName() + "已存在"); } } public PagedData<EnvironmentVo> list(Environment query, String orderBy, PageRequest pageRequest) { Page page = PageHelper.startPage(pageRequest.getPageNum(), pageRequest.getPageSize()); if (StringUtils.isEmpty(orderBy)) { orderBy = "create_time desc"; } List<EnvironmentVo> environmentVos = getEnvironmentVos(query, orderBy); return new PagedData<>(environmentVos, page.getTotal()); } private List<EnvironmentVo> convertEnvironmentsToEnvironmentVos(List<Environment> environments) { if (CollectionUtils.isEmpty(environments)) { return new ArrayList<>(); } List<Integer> creatorUids = environments.stream() .map(Environment::getCreatorUid) .filter(Objects::nonNull) .distinct() .collect(Collectors.toList()); Map<Integer, User> userMap = userService.getUserMapByIds(creatorUids); List<EnvironmentVo> environmentVos = environments.stream().map(env -> { EnvironmentVo environmentVo = new EnvironmentVo(); BeanUtils.copyProperties(env, environmentVo); if (env.getCreatorUid() != null) { User user = userMap.get(env.getCreatorUid()); if (user != null) { environmentVo.setCreatorNickName(user.getNickName()); } } return environmentVo; }).collect(Collectors.toList()); return environmentVos; } public List<EnvironmentVo> getEnvironmentVos(Environment query, String orderBy) { List<Environment> environments = getEnvironments(query, orderBy); return convertEnvironmentsToEnvironmentVos(environments); } public List<Environment> getEnvironments(Environment query, String orderBy) { EnvironmentExample example = new EnvironmentExample(); if (query != null) { EnvironmentExample.Criteria criteria = example.createCriteria(); if (query.getId() != null) { criteria.andIdEqualTo(query.getId()); } if (!StringUtils.isEmpty(query.getName())) { criteria.andNameEqualTo(query.getName()); } if (query.getProjectId() != null) { criteria.andProjectIdEqualTo(query.getProjectId()); } } if (!StringUtils.isEmpty(orderBy)) { example.setOrderByClause(orderBy); } return environmentMapper.selectByExample(example); } /** * 检查env没有被action.localVar globalVar testplan使用 * * @param envId */ private void check(Integer envId) { // 检查env是否被action localVars使用 List<Action> actions = actionService.getActionsByLocalVarsEnvironmentId(envId); if (!CollectionUtils.isEmpty(actions)) { String actionNames = actions.stream().map(Action::getName).collect(Collectors.joining("、")); throw new ServerException("actions: " + actionNames + ", 正在使用此环境"); } // 检查env是否被globalVar使用 List<GlobalVar> globalVars = globalVarService.getGlobalVarsByEnvironmentId(envId); if (!CollectionUtils.isEmpty(globalVars)) { String globalVarNames = globalVars.stream().map(GlobalVar::getName).collect(Collectors.joining("、")); throw new ServerException("globalVars: " + globalVarNames + ", 正在使用此环境"); } // 检查env是否被testplan使用 List<TestPlan> testPlans = testPlanService.getTestPlansByEnvironmentId(envId); if (!CollectionUtils.isEmpty(testPlans)) { String testPlanNames = testPlans.stream().map(TestPlan::getName).collect(Collectors.joining("、")); throw new ServerException("testPlans: " + testPlanNames + ", 正在使用此环境"); } } /** * 在environmentValues中找到与envId匹配的value */ public String getValueInEnvironmentValues(List<EnvironmentValue> environmentValues, Integer envId) { String defaultValue = null; for (EnvironmentValue env : environmentValues) { Integer environmentId = env.getEnvironmentId(); if (envId.equals(environmentId)) { return env.getValue(); } else if (environmentId == EnvironmentValue.DEFAULT_ENVIRONMENT_ID) { defaultValue = env.getValue(); } } return defaultValue; } public String getEnvironmentNameById(Integer envId) { if (envId == EnvironmentValue.DEFAULT_ENVIRONMENT_ID) { return "默认"; } Environment environment = environmentMapper.selectByPrimaryKey(envId); if (environment != null) { return environment.getName(); } return ""; } } <|start_filename|>src/main/java/com/daxiang/schedule/ScheduledTaskExecutor.java<|end_filename|> package com.daxiang.schedule; import com.daxiang.model.dto.Testcase; import com.daxiang.service.FileService; import com.daxiang.service.TestTaskService; import com.daxiang.mbg.po.DeviceTestTask; import com.daxiang.mbg.po.TestTask; import com.daxiang.service.DeviceTestTaskService; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.CollectionUtils; import java.util.Comparator; import java.util.Date; import java.util.List; import java.util.Map; import java.util.stream.Collectors; /** * Created by jiangyitao. */ @Slf4j @Component public class ScheduledTaskExecutor { @Autowired private TestTaskService testTaskService; @Autowired private DeviceTestTaskService deviceTestTaskService; @Autowired private FileService fileService; /** * 统计已完成的测试任务 */ @Transactional @Scheduled(fixedRate = 10000) public void statisticsFinishedTestTask() { // 未完成的测试任务 List<TestTask> testTasks = testTaskService.getUnFinishedTestTasks(); if (CollectionUtils.isEmpty(testTasks)) { return; } List<Integer> testTaskIds = testTasks.stream().map(TestTask::getId).collect(Collectors.toList()); // todo 批量更新 deviceTestTaskService.getDeviceTestTasksByTestTaskIds(testTaskIds).stream() .collect(Collectors.groupingBy(DeviceTestTask::getTestTaskId)) // 按照testTaskId分组 .forEach((testTaskId, deviceTestTasks) -> { // 所有device都测试完成 boolean allDeviceTestFinished = deviceTestTasks.stream() .allMatch(task -> task.getStatus() == DeviceTestTask.FINISHED_STATUS); if (allDeviceTestFinished) { log.info("开始统计测试结果, testTaskId: {}", testTaskId); List<Testcase> testcases = deviceTestTasks.stream() .flatMap(task -> task.getTestcases().stream()).collect(Collectors.toList()); // 按测试用例结果分组 Map<Integer, Long> result = testcases.stream() .collect(Collectors.groupingBy(Testcase::getStatus, Collectors.counting())); TestTask testTask = new TestTask(); testTask.setId(testTaskId); testTask.setStatus(TestTask.FINISHED_STATUS); // 所有用例结束时间最晚的作为完成时间 Date maxEndTime = testcases.stream().map(Testcase::getEndTime).max(Comparator.naturalOrder()).get(); testTask.setFinishTime(maxEndTime); int passCount = result.getOrDefault(Testcase.PASS_STATUS, 0L).intValue(); testTask.setPassCaseCount(passCount); int failCount = result.getOrDefault(Testcase.FAIL_STATUS, 0L).intValue(); testTask.setFailCaseCount(failCount); int skipCount = result.getOrDefault(Testcase.SKIP_STATUS, 0L).intValue(); testTask.setSkipCaseCount(skipCount); testTaskService.update(testTask); log.info("测试结果统计完成, testTaskId: {}", testTaskId); } }); } /** * 每天0点,清理3天前的临时文件 */ @Scheduled(cron = "0 0 0 * * ?") public void clearTmpFiles() { int beforeDays = 3; log.info("开始清除{}天前的临时文件", beforeDays); int deletedTmpFilesCount = fileService.clearTmpFilesBefore(beforeDays); log.info("清理临时文件完成,共清理{}个文件", deletedTmpFilesCount); } } <|start_filename|>src/main/java/com/daxiang/mbg/po/AppExample.java<|end_filename|> package com.daxiang.mbg.po; import java.util.ArrayList; import java.util.Date; import java.util.List; public class AppExample { protected String orderByClause; protected boolean distinct; protected List<Criteria> oredCriteria; public AppExample() { oredCriteria = new ArrayList<Criteria>(); } public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } public String getOrderByClause() { return orderByClause; } public void setDistinct(boolean distinct) { this.distinct = distinct; } public boolean isDistinct() { return distinct; } public List<Criteria> getOredCriteria() { return oredCriteria; } public void or(Criteria criteria) { oredCriteria.add(criteria); } public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } protected abstract static class GeneratedCriteria { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andIdIsNull() { addCriterion("id is null"); return (Criteria) this; } public Criteria andIdIsNotNull() { addCriterion("id is not null"); return (Criteria) this; } public Criteria andIdEqualTo(Integer value) { addCriterion("id =", value, "id"); return (Criteria) this; } public Criteria andIdNotEqualTo(Integer value) { addCriterion("id <>", value, "id"); return (Criteria) this; } public Criteria andIdGreaterThan(Integer value) { addCriterion("id >", value, "id"); return (Criteria) this; } public Criteria andIdGreaterThanOrEqualTo(Integer value) { addCriterion("id >=", value, "id"); return (Criteria) this; } public Criteria andIdLessThan(Integer value) { addCriterion("id <", value, "id"); return (Criteria) this; } public Criteria andIdLessThanOrEqualTo(Integer value) { addCriterion("id <=", value, "id"); return (Criteria) this; } public Criteria andIdIn(List<Integer> values) { addCriterion("id in", values, "id"); return (Criteria) this; } public Criteria andIdNotIn(List<Integer> values) { addCriterion("id not in", values, "id"); return (Criteria) this; } public Criteria andIdBetween(Integer value1, Integer value2) { addCriterion("id between", value1, value2, "id"); return (Criteria) this; } public Criteria andIdNotBetween(Integer value1, Integer value2) { addCriterion("id not between", value1, value2, "id"); return (Criteria) this; } public Criteria andPlatformIsNull() { addCriterion("platform is null"); return (Criteria) this; } public Criteria andPlatformIsNotNull() { addCriterion("platform is not null"); return (Criteria) this; } public Criteria andPlatformEqualTo(Integer value) { addCriterion("platform =", value, "platform"); return (Criteria) this; } public Criteria andPlatformNotEqualTo(Integer value) { addCriterion("platform <>", value, "platform"); return (Criteria) this; } public Criteria andPlatformGreaterThan(Integer value) { addCriterion("platform >", value, "platform"); return (Criteria) this; } public Criteria andPlatformGreaterThanOrEqualTo(Integer value) { addCriterion("platform >=", value, "platform"); return (Criteria) this; } public Criteria andPlatformLessThan(Integer value) { addCriterion("platform <", value, "platform"); return (Criteria) this; } public Criteria andPlatformLessThanOrEqualTo(Integer value) { addCriterion("platform <=", value, "platform"); return (Criteria) this; } public Criteria andPlatformIn(List<Integer> values) { addCriterion("platform in", values, "platform"); return (Criteria) this; } public Criteria andPlatformNotIn(List<Integer> values) { addCriterion("platform not in", values, "platform"); return (Criteria) this; } public Criteria andPlatformBetween(Integer value1, Integer value2) { addCriterion("platform between", value1, value2, "platform"); return (Criteria) this; } public Criteria andPlatformNotBetween(Integer value1, Integer value2) { addCriterion("platform not between", value1, value2, "platform"); return (Criteria) this; } public Criteria andNameIsNull() { addCriterion("name is null"); return (Criteria) this; } public Criteria andNameIsNotNull() { addCriterion("name is not null"); return (Criteria) this; } public Criteria andNameEqualTo(String value) { addCriterion("name =", value, "name"); return (Criteria) this; } public Criteria andNameNotEqualTo(String value) { addCriterion("name <>", value, "name"); return (Criteria) this; } public Criteria andNameGreaterThan(String value) { addCriterion("name >", value, "name"); return (Criteria) this; } public Criteria andNameGreaterThanOrEqualTo(String value) { addCriterion("name >=", value, "name"); return (Criteria) this; } public Criteria andNameLessThan(String value) { addCriterion("name <", value, "name"); return (Criteria) this; } public Criteria andNameLessThanOrEqualTo(String value) { addCriterion("name <=", value, "name"); return (Criteria) this; } public Criteria andNameLike(String value) { addCriterion("name like", value, "name"); return (Criteria) this; } public Criteria andNameNotLike(String value) { addCriterion("name not like", value, "name"); return (Criteria) this; } public Criteria andNameIn(List<String> values) { addCriterion("name in", values, "name"); return (Criteria) this; } public Criteria andNameNotIn(List<String> values) { addCriterion("name not in", values, "name"); return (Criteria) this; } public Criteria andNameBetween(String value1, String value2) { addCriterion("name between", value1, value2, "name"); return (Criteria) this; } public Criteria andNameNotBetween(String value1, String value2) { addCriterion("name not between", value1, value2, "name"); return (Criteria) this; } public Criteria andVersionIsNull() { addCriterion("version is null"); return (Criteria) this; } public Criteria andVersionIsNotNull() { addCriterion("version is not null"); return (Criteria) this; } public Criteria andVersionEqualTo(String value) { addCriterion("version =", value, "version"); return (Criteria) this; } public Criteria andVersionNotEqualTo(String value) { addCriterion("version <>", value, "version"); return (Criteria) this; } public Criteria andVersionGreaterThan(String value) { addCriterion("version >", value, "version"); return (Criteria) this; } public Criteria andVersionGreaterThanOrEqualTo(String value) { addCriterion("version >=", value, "version"); return (Criteria) this; } public Criteria andVersionLessThan(String value) { addCriterion("version <", value, "version"); return (Criteria) this; } public Criteria andVersionLessThanOrEqualTo(String value) { addCriterion("version <=", value, "version"); return (Criteria) this; } public Criteria andVersionLike(String value) { addCriterion("version like", value, "version"); return (Criteria) this; } public Criteria andVersionNotLike(String value) { addCriterion("version not like", value, "version"); return (Criteria) this; } public Criteria andVersionIn(List<String> values) { addCriterion("version in", values, "version"); return (Criteria) this; } public Criteria andVersionNotIn(List<String> values) { addCriterion("version not in", values, "version"); return (Criteria) this; } public Criteria andVersionBetween(String value1, String value2) { addCriterion("version between", value1, value2, "version"); return (Criteria) this; } public Criteria andVersionNotBetween(String value1, String value2) { addCriterion("version not between", value1, value2, "version"); return (Criteria) this; } public Criteria andPackageNameIsNull() { addCriterion("package_name is null"); return (Criteria) this; } public Criteria andPackageNameIsNotNull() { addCriterion("package_name is not null"); return (Criteria) this; } public Criteria andPackageNameEqualTo(String value) { addCriterion("package_name =", value, "packageName"); return (Criteria) this; } public Criteria andPackageNameNotEqualTo(String value) { addCriterion("package_name <>", value, "packageName"); return (Criteria) this; } public Criteria andPackageNameGreaterThan(String value) { addCriterion("package_name >", value, "packageName"); return (Criteria) this; } public Criteria andPackageNameGreaterThanOrEqualTo(String value) { addCriterion("package_name >=", value, "packageName"); return (Criteria) this; } public Criteria andPackageNameLessThan(String value) { addCriterion("package_name <", value, "packageName"); return (Criteria) this; } public Criteria andPackageNameLessThanOrEqualTo(String value) { addCriterion("package_name <=", value, "packageName"); return (Criteria) this; } public Criteria andPackageNameLike(String value) { addCriterion("package_name like", value, "packageName"); return (Criteria) this; } public Criteria andPackageNameNotLike(String value) { addCriterion("package_name not like", value, "packageName"); return (Criteria) this; } public Criteria andPackageNameIn(List<String> values) { addCriterion("package_name in", values, "packageName"); return (Criteria) this; } public Criteria andPackageNameNotIn(List<String> values) { addCriterion("package_name not in", values, "packageName"); return (Criteria) this; } public Criteria andPackageNameBetween(String value1, String value2) { addCriterion("package_name between", value1, value2, "packageName"); return (Criteria) this; } public Criteria andPackageNameNotBetween(String value1, String value2) { addCriterion("package_name not between", value1, value2, "packageName"); return (Criteria) this; } public Criteria andLaunchActivityIsNull() { addCriterion("launch_activity is null"); return (Criteria) this; } public Criteria andLaunchActivityIsNotNull() { addCriterion("launch_activity is not null"); return (Criteria) this; } public Criteria andLaunchActivityEqualTo(String value) { addCriterion("launch_activity =", value, "launchActivity"); return (Criteria) this; } public Criteria andLaunchActivityNotEqualTo(String value) { addCriterion("launch_activity <>", value, "launchActivity"); return (Criteria) this; } public Criteria andLaunchActivityGreaterThan(String value) { addCriterion("launch_activity >", value, "launchActivity"); return (Criteria) this; } public Criteria andLaunchActivityGreaterThanOrEqualTo(String value) { addCriterion("launch_activity >=", value, "launchActivity"); return (Criteria) this; } public Criteria andLaunchActivityLessThan(String value) { addCriterion("launch_activity <", value, "launchActivity"); return (Criteria) this; } public Criteria andLaunchActivityLessThanOrEqualTo(String value) { addCriterion("launch_activity <=", value, "launchActivity"); return (Criteria) this; } public Criteria andLaunchActivityLike(String value) { addCriterion("launch_activity like", value, "launchActivity"); return (Criteria) this; } public Criteria andLaunchActivityNotLike(String value) { addCriterion("launch_activity not like", value, "launchActivity"); return (Criteria) this; } public Criteria andLaunchActivityIn(List<String> values) { addCriterion("launch_activity in", values, "launchActivity"); return (Criteria) this; } public Criteria andLaunchActivityNotIn(List<String> values) { addCriterion("launch_activity not in", values, "launchActivity"); return (Criteria) this; } public Criteria andLaunchActivityBetween(String value1, String value2) { addCriterion("launch_activity between", value1, value2, "launchActivity"); return (Criteria) this; } public Criteria andLaunchActivityNotBetween(String value1, String value2) { addCriterion("launch_activity not between", value1, value2, "launchActivity"); return (Criteria) this; } public Criteria andFilePathIsNull() { addCriterion("file_path is null"); return (Criteria) this; } public Criteria andFilePathIsNotNull() { addCriterion("file_path is not null"); return (Criteria) this; } public Criteria andFilePathEqualTo(String value) { addCriterion("file_path =", value, "filePath"); return (Criteria) this; } public Criteria andFilePathNotEqualTo(String value) { addCriterion("file_path <>", value, "filePath"); return (Criteria) this; } public Criteria andFilePathGreaterThan(String value) { addCriterion("file_path >", value, "filePath"); return (Criteria) this; } public Criteria andFilePathGreaterThanOrEqualTo(String value) { addCriterion("file_path >=", value, "filePath"); return (Criteria) this; } public Criteria andFilePathLessThan(String value) { addCriterion("file_path <", value, "filePath"); return (Criteria) this; } public Criteria andFilePathLessThanOrEqualTo(String value) { addCriterion("file_path <=", value, "filePath"); return (Criteria) this; } public Criteria andFilePathLike(String value) { addCriterion("file_path like", value, "filePath"); return (Criteria) this; } public Criteria andFilePathNotLike(String value) { addCriterion("file_path not like", value, "filePath"); return (Criteria) this; } public Criteria andFilePathIn(List<String> values) { addCriterion("file_path in", values, "filePath"); return (Criteria) this; } public Criteria andFilePathNotIn(List<String> values) { addCriterion("file_path not in", values, "filePath"); return (Criteria) this; } public Criteria andFilePathBetween(String value1, String value2) { addCriterion("file_path between", value1, value2, "filePath"); return (Criteria) this; } public Criteria andFilePathNotBetween(String value1, String value2) { addCriterion("file_path not between", value1, value2, "filePath"); return (Criteria) this; } public Criteria andUploadTimeIsNull() { addCriterion("upload_time is null"); return (Criteria) this; } public Criteria andUploadTimeIsNotNull() { addCriterion("upload_time is not null"); return (Criteria) this; } public Criteria andUploadTimeEqualTo(Date value) { addCriterion("upload_time =", value, "uploadTime"); return (Criteria) this; } public Criteria andUploadTimeNotEqualTo(Date value) { addCriterion("upload_time <>", value, "uploadTime"); return (Criteria) this; } public Criteria andUploadTimeGreaterThan(Date value) { addCriterion("upload_time >", value, "uploadTime"); return (Criteria) this; } public Criteria andUploadTimeGreaterThanOrEqualTo(Date value) { addCriterion("upload_time >=", value, "uploadTime"); return (Criteria) this; } public Criteria andUploadTimeLessThan(Date value) { addCriterion("upload_time <", value, "uploadTime"); return (Criteria) this; } public Criteria andUploadTimeLessThanOrEqualTo(Date value) { addCriterion("upload_time <=", value, "uploadTime"); return (Criteria) this; } public Criteria andUploadTimeIn(List<Date> values) { addCriterion("upload_time in", values, "uploadTime"); return (Criteria) this; } public Criteria andUploadTimeNotIn(List<Date> values) { addCriterion("upload_time not in", values, "uploadTime"); return (Criteria) this; } public Criteria andUploadTimeBetween(Date value1, Date value2) { addCriterion("upload_time between", value1, value2, "uploadTime"); return (Criteria) this; } public Criteria andUploadTimeNotBetween(Date value1, Date value2) { addCriterion("upload_time not between", value1, value2, "uploadTime"); return (Criteria) this; } public Criteria andUploadorUidIsNull() { addCriterion("uploador_uid is null"); return (Criteria) this; } public Criteria andUploadorUidIsNotNull() { addCriterion("uploador_uid is not null"); return (Criteria) this; } public Criteria andUploadorUidEqualTo(Integer value) { addCriterion("uploador_uid =", value, "uploadorUid"); return (Criteria) this; } public Criteria andUploadorUidNotEqualTo(Integer value) { addCriterion("uploador_uid <>", value, "uploadorUid"); return (Criteria) this; } public Criteria andUploadorUidGreaterThan(Integer value) { addCriterion("uploador_uid >", value, "uploadorUid"); return (Criteria) this; } public Criteria andUploadorUidGreaterThanOrEqualTo(Integer value) { addCriterion("uploador_uid >=", value, "uploadorUid"); return (Criteria) this; } public Criteria andUploadorUidLessThan(Integer value) { addCriterion("uploador_uid <", value, "uploadorUid"); return (Criteria) this; } public Criteria andUploadorUidLessThanOrEqualTo(Integer value) { addCriterion("uploador_uid <=", value, "uploadorUid"); return (Criteria) this; } public Criteria andUploadorUidIn(List<Integer> values) { addCriterion("uploador_uid in", values, "uploadorUid"); return (Criteria) this; } public Criteria andUploadorUidNotIn(List<Integer> values) { addCriterion("uploador_uid not in", values, "uploadorUid"); return (Criteria) this; } public Criteria andUploadorUidBetween(Integer value1, Integer value2) { addCriterion("uploador_uid between", value1, value2, "uploadorUid"); return (Criteria) this; } public Criteria andUploadorUidNotBetween(Integer value1, Integer value2) { addCriterion("uploador_uid not between", value1, value2, "uploadorUid"); return (Criteria) this; } public Criteria andProjectIdIsNull() { addCriterion("project_id is null"); return (Criteria) this; } public Criteria andProjectIdIsNotNull() { addCriterion("project_id is not null"); return (Criteria) this; } public Criteria andProjectIdEqualTo(Integer value) { addCriterion("project_id =", value, "projectId"); return (Criteria) this; } public Criteria andProjectIdNotEqualTo(Integer value) { addCriterion("project_id <>", value, "projectId"); return (Criteria) this; } public Criteria andProjectIdGreaterThan(Integer value) { addCriterion("project_id >", value, "projectId"); return (Criteria) this; } public Criteria andProjectIdGreaterThanOrEqualTo(Integer value) { addCriterion("project_id >=", value, "projectId"); return (Criteria) this; } public Criteria andProjectIdLessThan(Integer value) { addCriterion("project_id <", value, "projectId"); return (Criteria) this; } public Criteria andProjectIdLessThanOrEqualTo(Integer value) { addCriterion("project_id <=", value, "projectId"); return (Criteria) this; } public Criteria andProjectIdIn(List<Integer> values) { addCriterion("project_id in", values, "projectId"); return (Criteria) this; } public Criteria andProjectIdNotIn(List<Integer> values) { addCriterion("project_id not in", values, "projectId"); return (Criteria) this; } public Criteria andProjectIdBetween(Integer value1, Integer value2) { addCriterion("project_id between", value1, value2, "projectId"); return (Criteria) this; } public Criteria andProjectIdNotBetween(Integer value1, Integer value2) { addCriterion("project_id not between", value1, value2, "projectId"); return (Criteria) this; } } public static class Criteria extends GeneratedCriteria { protected Criteria() { super(); } } public static class Criterion { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } } <|start_filename|>src/main/java/com/daxiang/service/UserProjectService.java<|end_filename|> package com.daxiang.service; import com.daxiang.dao.UserProjectDao; import com.daxiang.exception.ServerException; import com.daxiang.mbg.mapper.UserProjectMapper; import com.daxiang.mbg.po.Project; import com.daxiang.mbg.po.UserProject; import com.daxiang.mbg.po.UserProjectExample; import com.daxiang.model.dto.UserProjectDto; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.util.CollectionUtils; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; /** * Created by jiangyitao. */ @Service public class UserProjectService { @Autowired private UserProjectMapper userProjectMapper; @Autowired private UserProjectDao userProjectDao; public void addBatch(List<UserProject> userProjects) { if (CollectionUtils.isEmpty(userProjects)) { return; } int insertCount = userProjectDao.insertBatch(userProjects); if (insertCount != userProjects.size()) { throw new ServerException("添加失败"); } } public void addBatch(Integer userId, List<Project> projects) { List<UserProject> userProjects = projects.stream().map(project -> { UserProject userProject = new UserProject(); userProject.setUserId(userId); userProject.setProjectId(project.getId()); return userProject; }).collect(Collectors.toList()); addBatch(userProjects); } public int deleteByUserId(Integer userId) { UserProjectExample example = new UserProjectExample(); UserProjectExample.Criteria criteria = example.createCriteria(); criteria.andUserIdEqualTo(userId); return userProjectMapper.deleteByExample(example); } public List<UserProjectDto> getUserProjectDtosByUserIds(List<Integer> userIds) { if (CollectionUtils.isEmpty(userIds)) { return new ArrayList<>(); } return userProjectDao.selectUserProjectDtosByUserIds(userIds); } } <|start_filename|>src/main/java/com/daxiang/service/GlobalVarService.java<|end_filename|> package com.daxiang.service; import com.daxiang.dao.GlobalVarDao; import com.daxiang.exception.ServerException; import com.daxiang.mbg.po.GlobalVarExample; import com.daxiang.mbg.po.User; import com.daxiang.model.PagedData; import com.daxiang.security.SecurityUtil; import com.github.pagehelper.PageHelper; import com.github.pagehelper.Page; import com.daxiang.mbg.mapper.GlobalVarMapper; import com.daxiang.mbg.po.GlobalVar; import com.daxiang.model.PageRequest; import com.daxiang.model.vo.GlobalVarVo; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DuplicateKeyException; import org.springframework.stereotype.Service; import org.springframework.util.CollectionUtils; import org.springframework.util.StringUtils; import java.util.*; import java.util.stream.Collectors; /** * Created by jiangyitao. */ @Service public class GlobalVarService { @Autowired private GlobalVarMapper globalVarMapper; @Autowired private GlobalVarDao globalVarDao; @Autowired private UserService userService; @Autowired private EnvironmentService environmentService; public void add(GlobalVar globalVar) { globalVar.setCreateTime(new Date()); globalVar.setCreatorUid(SecurityUtil.getCurrentUserId()); try { int insertCount = globalVarMapper.insertSelective(globalVar); if (insertCount != 1) { throw new ServerException("添加失败,请稍后重试"); } } catch (DuplicateKeyException e) { throw new ServerException(globalVar.getName() + "已存在"); } } public void addBatch(List<GlobalVar> globalVars) { Integer currentUserId = SecurityUtil.getCurrentUserId(); Date now = new Date(); globalVars.forEach(globalVar -> { globalVar.setCreateTime(now); globalVar.setCreatorUid(currentUserId); }); try { int insertCount = globalVarDao.insertBatch(globalVars); if (insertCount != globalVars.size()) { throw new ServerException("添加失败,请稍后重试"); } } catch (DuplicateKeyException e) { throw new ServerException("命名冲突"); } } public void delete(Integer globalVarId) { if (globalVarId == null) { throw new ServerException("globalVarId不能为空"); } // todo 检查全局变量是否被action使用 int deleteCount = globalVarMapper.deleteByPrimaryKey(globalVarId); if (deleteCount != 1) { throw new ServerException("删除失败,请稍后重试"); } } public void update(GlobalVar globalVar) { // todo 检查全局变量是否被action使用 try { int updateCount = globalVarMapper.updateByPrimaryKeyWithBLOBs(globalVar); if (updateCount != 1) { throw new ServerException("更新失败,请稍后重试"); } } catch (DuplicateKeyException e) { throw new ServerException(globalVar.getName() + "已存在"); } } public PagedData<GlobalVarVo> list(GlobalVar query, String orderBy, PageRequest pageRequest) { Page page = PageHelper.startPage(pageRequest.getPageNum(), pageRequest.getPageSize()); if (StringUtils.isEmpty(orderBy)) { orderBy = "create_time desc"; } List<GlobalVarVo> globalVarVos = getGlobalVarVos(query, orderBy); return new PagedData<>(globalVarVos, page.getTotal()); } private List<GlobalVarVo> convertGlobalVarsToGlobalVarVos(List<GlobalVar> globalVars) { if (CollectionUtils.isEmpty(globalVars)) { return new ArrayList<>(); } List<Integer> creatorUids = globalVars.stream() .map(GlobalVar::getCreatorUid) .filter(Objects::nonNull) .distinct() .collect(Collectors.toList()); Map<Integer, User> userMap = userService.getUserMapByIds(creatorUids); List<GlobalVarVo> globalVarVos = globalVars.stream().map(globalVar -> { GlobalVarVo globalVarVo = new GlobalVarVo(); BeanUtils.copyProperties(globalVar, globalVarVo); if (globalVar.getCreatorUid() != null) { User user = userMap.get(globalVar.getCreatorUid()); if (user != null) { globalVarVo.setCreatorNickName(user.getNickName()); } } return globalVarVo; }).collect(Collectors.toList()); return globalVarVos; } public List<GlobalVarVo> getGlobalVarVos(GlobalVar query, String orderBy) { List<GlobalVar> globalVars = getGlobalVars(query, orderBy); return convertGlobalVarsToGlobalVarVos(globalVars); } public List<GlobalVar> getGlobalVars(GlobalVar query) { return getGlobalVars(query, null); } public List<GlobalVar> getGlobalVars(GlobalVar query, String orderBy) { GlobalVarExample example = new GlobalVarExample(); if (query != null) { GlobalVarExample.Criteria criteria = example.createCriteria(); if (query.getId() != null) { criteria.andIdEqualTo(query.getId()); } if (query.getType() != null) { criteria.andTypeEqualTo(query.getType()); } if (query.getProjectId() != null) { criteria.andProjectIdEqualTo(query.getProjectId()); } if (query.getCategoryId() != null) { criteria.andCategoryIdEqualTo(query.getCategoryId()); } if (!StringUtils.isEmpty(query.getName())) { criteria.andNameEqualTo(query.getName()); } } if (!StringUtils.isEmpty(orderBy)) { example.setOrderByClause(orderBy); } return globalVarMapper.selectByExampleWithBLOBs(example); } public List<GlobalVar> getGlobalVarsByEnvironmentId(Integer envId) { if (envId == null) { throw new ServerException("envId不能为空"); } return globalVarDao.selectByEnvironmentId(envId); } public List<GlobalVar> getGlobalVarsByProjectIdAndEnv(Integer projectId, Integer env) { if (projectId == null || env == null) { throw new ServerException("projectId or env不能为空"); } GlobalVar query = new GlobalVar(); query.setProjectId(projectId); List<GlobalVar> globalVars = getGlobalVars(query); globalVars.forEach(globalVar -> { String value = environmentService.getValueInEnvironmentValues(globalVar.getEnvironmentValues(), env); globalVar.setValue(value); }); return globalVars; } public List<GlobalVar> getGlobalVarsByCategoryIds(List<Integer> categoryIds) { if (CollectionUtils.isEmpty(categoryIds)) { return new ArrayList<>(); } GlobalVarExample example = new GlobalVarExample(); GlobalVarExample.Criteria criteria = example.createCriteria(); criteria.andCategoryIdIn(categoryIds); return globalVarMapper.selectByExample(example); } } <|start_filename|>src/main/java/com/daxiang/validator/NoDuplicateByValidator.java<|end_filename|> package com.daxiang.validator; import com.daxiang.model.page.By; import com.daxiang.validator.annotation.NoDuplicateBy; import org.springframework.util.CollectionUtils; import org.springframework.util.StringUtils; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; import java.util.List; import java.util.Map; import java.util.stream.Collectors; /** * Created by jiangyitao. */ public class NoDuplicateByValidator implements ConstraintValidator<NoDuplicateBy, List<By>> { @Override public boolean isValid(List<By> byList, ConstraintValidatorContext context) { if (!CollectionUtils.isEmpty(byList)) { Map<String, Long> byNameCountMap = byList.stream().filter(by -> !StringUtils.isEmpty(by.getName())) .collect(Collectors.groupingBy(By::getName, Collectors.counting())); for (Map.Entry<String, Long> byNameCount : byNameCountMap.entrySet()) { if (byNameCount.getValue() > 1) { return false; } } } return true; } } <|start_filename|>src/main/java/com/daxiang/service/AppService.java<|end_filename|> package com.daxiang.service; import com.daxiang.agent.AgentClient; import com.daxiang.exception.ServerException; import com.daxiang.mbg.mapper.AppMapper; import com.daxiang.mbg.po.App; import com.daxiang.mbg.po.AppExample; import com.daxiang.mbg.po.User; import com.daxiang.model.*; import com.daxiang.model.enums.UploadDir; import com.daxiang.model.vo.AgentVo; import com.daxiang.model.vo.AppVo; import com.daxiang.security.SecurityUtil; import com.daxiang.utils.HttpServletUtil; import com.github.pagehelper.Page; import com.github.pagehelper.PageHelper; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.util.CollectionUtils; import org.springframework.util.StringUtils; import org.springframework.web.multipart.MultipartFile; import java.util.*; import java.util.stream.Collectors; /** * Created by jiangyitao. */ @Service @Slf4j public class AppService { @Autowired private AppMapper appMapper; @Autowired private AgentService agentService; @Autowired private AgentClient agentClient; @Autowired private UserService userService; @Autowired private FileService fileService; public void upload(App app, MultipartFile file) { UploadFile uploadFile = fileService.upload(file, UploadDir.APP); app.setFilePath(uploadFile.getFilePath()); app.setUploadTime(new Date()); app.setUploadorUid(SecurityUtil.getCurrentUserId()); int insertCount = appMapper.insertSelective(app); if (insertCount != 1) { throw new ServerException("上传失败"); } } public void deleteAndClearRelatedRes(Integer appId) { if (appId == null) { throw new ServerException("appId不能为空"); } App app = appMapper.selectByPrimaryKey(appId); if (app == null) { throw new ServerException("app不存在"); } int deleteCount = appMapper.deleteByPrimaryKey(appId); if (deleteCount != 1) { throw new ServerException("删除失败,请稍后再试"); } fileService.deleteQuietly(app.getFilePath()); } public void update(App app) { int updateCount = appMapper.updateByPrimaryKey(app); if (updateCount != 1) { throw new ServerException("更新失败,请稍后重试"); } } public PagedData<AppVo> list(App query, String orderBy, PageRequest pageRequest) { Page page = PageHelper.startPage(pageRequest.getPageNum(), pageRequest.getPageSize()); if (StringUtils.isEmpty(orderBy)) { orderBy = "upload_time desc"; } List<AppVo> appVos = getAppVos(query, orderBy); return new PagedData<>(appVos, page.getTotal()); } private List<AppVo> convertAppsToAppVos(List<App> apps) { if (CollectionUtils.isEmpty(apps)) { return new ArrayList<>(); } List<Integer> uploadorUids = apps.stream() .map(App::getUploadorUid) .filter(Objects::nonNull) .distinct() .collect(Collectors.toList()); Map<Integer, User> userMap = userService.getUserMapByIds(uploadorUids); List<AppVo> appVos = apps.stream().map(app -> { AppVo appVo = new AppVo(); BeanUtils.copyProperties(app, appVo); if (app.getUploadorUid() != null) { User user = userMap.get(app.getUploadorUid()); if (user != null) { appVo.setUploadorNickName(user.getNickName()); } } return appVo; }).collect(Collectors.toList()); return appVos; } public List<AppVo> getAppVos(App query, String orderBy) { List<App> apps = getApps(query, orderBy); return convertAppsToAppVos(apps); } public List<App> getApps(App query, String orderBy) { AppExample example = new AppExample(); if (query != null) { AppExample.Criteria criteria = example.createCriteria(); if (query.getId() != null) { criteria.andIdEqualTo(query.getId()); } if (query.getPlatform() != null) { criteria.andPlatformEqualTo(query.getPlatform()); } if (query.getProjectId() != null) { criteria.andProjectIdEqualTo(query.getProjectId()); } } if (!StringUtils.isEmpty(orderBy)) { example.setOrderByClause(orderBy); } return appMapper.selectByExample(example); } public void aaptDumpBadging(Integer appId) { if (appId == null) { throw new ServerException("appId不能为空"); } App app = appMapper.selectByPrimaryKey(appId); if (app == null) { throw new ServerException("app不存在"); } if (app.getPlatform() != Platform.ANDROID) { throw new ServerException("只有Android平台才能执行aapt dump"); } List<AgentVo> onlineAgents = agentService.getOnlineAgentsWithoutDevices(); if (CollectionUtils.isEmpty(onlineAgents)) { throw new ServerException("暂无在线的agent,无法执行aapt dump"); } Optional<AgentVo> agentVo = onlineAgents.stream().filter(AgentVo::getIsConfigAapt).findAny(); if (!agentVo.isPresent()) { throw new ServerException("暂无配置了aapt的agent,无法执行aapt dump"); } AgentVo agent = agentVo.get(); Response agentResponse = agentClient.aaptDumpBadging(agent.getIp(), agent.getPort(), HttpServletUtil.getStaticResourceUrl(app.getFilePath())); if (!agentResponse.isSuccess()) { throw new ServerException(agentResponse.getMsg()); } String dumpInfo = (String) agentResponse.getData(); if (StringUtils.isEmpty(dumpInfo)) { throw new ServerException("aapt dump信息为空"); } log.info("app: {}, dumpInfo: {}", app.getName(), dumpInfo); String version = org.apache.commons.lang3.StringUtils.substringBetween(dumpInfo, "versionName='", "'"); String packageName = org.apache.commons.lang3.StringUtils.substringBetween(dumpInfo, "package: name='", "'"); String launchActivity = org.apache.commons.lang3.StringUtils.substringBetween(dumpInfo, "launchable-activity: name='", "'"); app.setVersion(version); app.setPackageName(packageName); app.setLaunchActivity(launchActivity); int updateCount = appMapper.updateByPrimaryKeySelective(app); if (updateCount != 1) { throw new ServerException("更新失败,请稍后重试"); } } } <|start_filename|>src/main/java/com/daxiang/controller/AppController.java<|end_filename|> package com.daxiang.controller; import com.daxiang.mbg.po.App; import com.daxiang.model.PageRequest; import com.daxiang.model.PagedData; import com.daxiang.model.Response; import com.daxiang.model.vo.AppVo; import com.daxiang.service.AppService; import com.daxiang.validator.group.UpdateGroup; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import javax.validation.Valid; import java.util.List; /** * Created by jiangyitao. */ @RestController @RequestMapping("/app") public class AppController { @Autowired private AppService appService; @PostMapping("/upload") public Response upload(@Valid App app, MultipartFile file) { appService.upload(app, file); return Response.success("上传成功"); } @DeleteMapping("/{appId}") public Response delete(@PathVariable Integer appId) { appService.deleteAndClearRelatedRes(appId); return Response.success("删除成功"); } @PostMapping("/update") public Response update(@Validated({UpdateGroup.class}) @RequestBody App app) { appService.update(app); return Response.success("更新成功"); } @PostMapping("/list") public Response list(App query, String orderBy, PageRequest pageRequest) { if (pageRequest.needPaging()) { PagedData<AppVo> pagedData = appService.list(query, orderBy, pageRequest); return Response.success(pagedData); } else { List<AppVo> appVos = appService.getAppVos(query, orderBy); return Response.success(appVos); } } @GetMapping("/{appId}/aaptDumpBadging") public Response aaptDumpBadging(@PathVariable Integer appId) { appService.aaptDumpBadging(appId); return Response.success("获取成功"); } } <|start_filename|>src/main/java/com/daxiang/service/UserService.java<|end_filename|> package com.daxiang.service; import com.daxiang.exception.ServerException; import com.daxiang.mbg.mapper.UserMapper; import com.daxiang.mbg.po.Project; import com.daxiang.mbg.po.Role; import com.daxiang.model.PagedData; import com.daxiang.model.PageRequest; import com.daxiang.model.dto.UserDto; import com.daxiang.model.dto.UserProjectDto; import com.daxiang.model.dto.UserRoleDto; import com.daxiang.security.JwtTokenUtil; import com.daxiang.mbg.po.User; import com.daxiang.mbg.po.UserExample; import com.github.pagehelper.PageHelper; import com.github.pagehelper.Page; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DuplicateKeyException; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.AuthenticationException; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.CollectionUtils; import org.springframework.util.StringUtils; import java.util.*; import java.util.function.Function; import java.util.stream.Collectors; /** * Created by jiangyitao. */ @Service public class UserService { @Autowired private UserMapper userMapper; @Autowired private UserRoleService userRoleService; @Autowired private UserProjectService userProjectService; @Autowired private ProjectService projectService; @Autowired private AuthenticationManager authenticationManager; @Autowired private PasswordEncoder passwordEncoder; @Transactional public void add(UserDto userDto) { User user = new User(); BeanUtils.copyProperties(userDto, user); user.setPassword(passwordEncoder.encode(user.getPassword())); user.setCreateTime(new Date()); // 用户 int insertCount; try { insertCount = userMapper.insertSelective(user); } catch (DuplicateKeyException e) { throw new ServerException(user.getUsername() + "已存在"); } if (insertCount != 1) { throw new ServerException("添加用户失败,请稍后重试"); } userRoleService.addBatch(user.getId(), userDto.getRoles()); userProjectService.addBatch(user.getId(), userDto.getProjects()); } @Transactional public void delete(Integer userId) { if (userId == null) { throw new ServerException("userId不能为空"); } userRoleService.deleteByUserId(userId); userProjectService.deleteByUserId(userId); userMapper.deleteByPrimaryKey(userId); } @Transactional public void update(UserDto userDto) { User user = new User(); BeanUtils.copyProperties(userDto, user); User originalUser = userMapper.selectByPrimaryKey(user.getId()); if (originalUser == null) { throw new ServerException("用户不存在"); } if (!originalUser.getPassword().equals(user.getPassword())) { // 修改了密码,需要重新encode user.setPassword(passwordEncoder.encode(user.getPassword())); } try { int updateCount = userMapper.updateByPrimaryKeySelective(user); if (updateCount != 1) { throw new ServerException("更新用户失败,请稍后重试"); } } catch (DuplicateKeyException e) { throw new ServerException(user.getUsername() + "已存在"); } userRoleService.deleteByUserId(user.getId()); userRoleService.addBatch(user.getId(), userDto.getRoles()); userProjectService.deleteByUserId(user.getId()); userProjectService.addBatch(user.getId(), userDto.getProjects()); } public PagedData<UserDto> list(User query, String orderBy, PageRequest pageRequest) { Page page = PageHelper.startPage(pageRequest.getPageNum(), pageRequest.getPageSize()); if (StringUtils.isEmpty(orderBy)) { orderBy = "create_time desc"; } List<UserDto> userDtos = getUserDtos(query, orderBy); return new PagedData<>(userDtos, page.getTotal()); } private List<UserDto> convertUsersToUserDtos(List<User> users) { if (CollectionUtils.isEmpty(users)) { return new ArrayList<>(); } List<Integer> userIds = users.stream().map(User::getId).collect(Collectors.toList()); // 按用户id分组 Map<Integer, List<UserRoleDto>> userRoleDtosMap = userRoleService.getUserRoleDtosByUserIds(userIds).stream() .collect(Collectors.groupingBy(UserRoleDto::getUserId)); Map<Integer, List<UserProjectDto>> userProjectDtosMap = userProjectService.getUserProjectDtosByUserIds(userIds).stream() .collect(Collectors.groupingBy(UserProjectDto::getUserId)); List<UserDto> userDtos = users.stream().map(user -> { UserDto userDto = new UserDto(); BeanUtils.copyProperties(user, userDto); List<UserRoleDto> userRoleDtos = userRoleDtosMap.get(user.getId()); if (userRoleDtos == null) { userDto.setRoles(new ArrayList<>()); } else { List<Role> roles = userRoleDtos.stream().map(UserRoleDto::getRole).collect(Collectors.toList()); userDto.setRoles(roles); } List<UserProjectDto> userProjectDtos = userProjectDtosMap.get(user.getId()); if (userProjectDtos == null) { userDto.setProjects(new ArrayList<>()); } else { List<Project> projects = userProjectDtos.stream().map(UserProjectDto::getProject).collect(Collectors.toList()); userDto.setProjects(projects); } return userDto; }).collect(Collectors.toList()); return userDtos; } public String login(User user) { try { authenticationManager.authenticate( new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword())); } catch (AuthenticationException e) { throw new ServerException(e.getMessage()); } return JwtTokenUtil.createToken(user.getUsername()); } public List<UserDto> getUserDtos(User query, String orderBy) { List<User> users = getUsers(query, orderBy); return convertUsersToUserDtos(users); } public List<User> getUsers(User query, String orderBy) { UserExample example = new UserExample(); if (query != null) { UserExample.Criteria criteria = example.createCriteria(); if (query.getId() != null) { criteria.andIdEqualTo(query.getId()); } if (!StringUtils.isEmpty(query.getUsername())) { criteria.andUsernameLike("%" + query.getUsername() + "%"); } if (!StringUtils.isEmpty(query.getNickName())) { criteria.andNickNameEqualTo(query.getNickName()); } if (query.getStatus() != null) { criteria.andStatusEqualTo(query.getStatus()); } } if (!StringUtils.isEmpty(orderBy)) { example.setOrderByClause(orderBy); } return userMapper.selectByExample(example); } public User getUserByUsername(String username) { UserExample example = new UserExample(); example.createCriteria().andUsernameEqualTo(username); List<User> users = userMapper.selectByExample(example); if (!users.isEmpty()) { return users.get(0); } return null; } public UserDto getUserDtoByUsername(String username) { User user = getUserByUsername(username); if (user == null) { return null; } UserDto userDto = new UserDto(); BeanUtils.copyProperties(user, userDto); List<Integer> singleUid = Collections.singletonList(user.getId()); List<Role> roles = userRoleService.getUserRoleDtosByUserIds(singleUid).stream() .map(UserRoleDto::getRole).collect(Collectors.toList()); userDto.setRoles(roles); boolean isAdmin = roles.stream().map(Role::getName).anyMatch("admin"::equals); if (isAdmin) { userDto.setProjects(projectService.getAll()); } else { List<Project> projects = userProjectService.getUserProjectDtosByUserIds(singleUid).stream() .map(UserProjectDto::getProject).collect(Collectors.toList()); userDto.setProjects(projects); } return userDto; } public List<User> getUsersByIds(List<Integer> userIds) { if (CollectionUtils.isEmpty(userIds)) { return new ArrayList<>(); } UserExample example = new UserExample(); UserExample.Criteria criteria = example.createCriteria(); criteria.andIdIn(userIds); return userMapper.selectByExample(example); } public Map<Integer, User> getUserMapByIds(List<Integer> userIds) { List<User> users = getUsersByIds(userIds); return users.stream().collect(Collectors.toMap(User::getId, Function.identity(), (k1, k2) -> k1)); } public User getUserById(Integer userId) { return userMapper.selectByPrimaryKey(userId); } } <|start_filename|>src/main/java/com/daxiang/security/JwtTokenUtil.java<|end_filename|> package com.daxiang.security; import io.jsonwebtoken.Claims; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import javax.servlet.http.HttpServletRequest; import java.util.Date; /** * Created by jiangyitao. */ public class JwtTokenUtil { private static final String SECRET_KEY = "opendx"; private static final long TOKEN_EXPIRE_IN_MS = 30 * 24 * 60 * 60 * 1000L; // token过期时间: 30天 private static final String TOKEN_HTTP_REQUEST_HEADER = "token"; public static String createToken(String username) { Claims claims = Jwts.claims().setSubject(username); return Jwts.builder() .setClaims(claims) .setExpiration(new Date(System.currentTimeMillis() + TOKEN_EXPIRE_IN_MS)) .signWith(SignatureAlgorithm.HS256, SECRET_KEY) .compact(); } public static String parseUsername(String token) { try { // token错误,过期 都会抛出异常 return Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(token).getBody().getSubject(); } catch (Exception e) { return null; } } public static String getTokenFromHttpRequestHeader(HttpServletRequest request) { return request.getHeader(TOKEN_HTTP_REQUEST_HEADER); } } <|start_filename|>src/main/java/com/daxiang/mbg/mapper/AgentExtJarMapper.java<|end_filename|> package com.daxiang.mbg.mapper; import com.daxiang.mbg.po.AgentExtJar; import com.daxiang.mbg.po.AgentExtJarExample; import java.util.List; import org.apache.ibatis.annotations.Param; public interface AgentExtJarMapper { long countByExample(AgentExtJarExample example); int deleteByExample(AgentExtJarExample example); int deleteByPrimaryKey(Integer id); int insert(AgentExtJar record); int insertSelective(AgentExtJar record); List<AgentExtJar> selectByExample(AgentExtJarExample example); AgentExtJar selectByPrimaryKey(Integer id); int updateByExampleSelective(@Param("record") AgentExtJar record, @Param("example") AgentExtJarExample example); int updateByExample(@Param("record") AgentExtJar record, @Param("example") AgentExtJarExample example); int updateByPrimaryKeySelective(AgentExtJar record); int updateByPrimaryKey(AgentExtJar record); } <|start_filename|>src/main/java/com/daxiang/controller/AgentController.java<|end_filename|> package com.daxiang.controller; import com.daxiang.model.Response; import com.daxiang.model.vo.AgentVo; import com.daxiang.service.AgentService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.List; /** * Created by jiangyitao. */ @RestController @RequestMapping("/agent") public class AgentController { @Autowired private AgentService agentService; @GetMapping("/online") public Response getOnlineAgents() { List<AgentVo> agents = agentService.getOnlineAgents(); return Response.success(agents); } } <|start_filename|>src/main/java/com/daxiang/security/JwtAccessDeniedHandler.java<|end_filename|> package com.daxiang.security; import com.alibaba.fastjson.JSON; import com.daxiang.model.Response; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.web.access.AccessDeniedHandler; import org.springframework.stereotype.Component; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * Created by jiangyitao. */ @Component public class JwtAccessDeniedHandler implements AccessDeniedHandler { @Override public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e) throws IOException { response.setCharacterEncoding("UTF-8"); response.setContentType("application/json"); response.getWriter().println(JSON.toJSONString(Response.accessDenied())); response.getWriter().flush(); } } <|start_filename|>src/main/java/com/daxiang/controller/DeviceTestTaskController.java<|end_filename|> package com.daxiang.controller; import com.daxiang.model.PageRequest; import com.daxiang.mbg.po.DeviceTestTask; import com.daxiang.model.PagedData; import com.daxiang.model.Response; import com.daxiang.model.dto.Testcase; import com.daxiang.service.DeviceTestTaskService; import com.daxiang.validator.group.UpdateGroup; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import java.util.List; /** * Created by jiangyitao. */ @RestController @RequestMapping("/deviceTestTask") public class DeviceTestTaskController { @Autowired private DeviceTestTaskService deviceTestTaskService; @PostMapping("/update") public Response update(@RequestBody @Validated({UpdateGroup.class}) DeviceTestTask deviceTestTask) { deviceTestTaskService.update(deviceTestTask); return Response.success("更新成功"); } @PostMapping("/list") public Response list(DeviceTestTask query, String orderBy, PageRequest pageRequest) { if (pageRequest.needPaging()) { PagedData<DeviceTestTask> pagedData = deviceTestTaskService.list(query, orderBy, pageRequest); return Response.success(pagedData); } else { List<DeviceTestTask> deviceTestTasks = deviceTestTaskService.getDeviceTestTasks(query, orderBy); return Response.success(deviceTestTasks); } } @PostMapping("/{deviceTestTaskId}/updateTestcase") public Response updateTestcase(@PathVariable Integer deviceTestTaskId, @RequestBody Testcase testcase) { deviceTestTaskService.updateTestcase(deviceTestTaskId, testcase); return Response.success("更新成功"); } @GetMapping("/firstUnStart/device/{deviceId}") public Response getFirstUnStartDeviceTestTask(@PathVariable String deviceId) { DeviceTestTask deviceTestTask = deviceTestTaskService.getFirstUnStartDeviceTestTask(deviceId); return Response.success(deviceTestTask); } @DeleteMapping("/{deviceTestTaskId}") public Response delete(@PathVariable Integer deviceTestTaskId) { deviceTestTaskService.deleteAndClearRelatedRes(deviceTestTaskId); return Response.success("删除成功"); } } <|start_filename|>src/main/java/com/daxiang/service/DriverService.java<|end_filename|> package com.daxiang.service; import com.daxiang.dao.DriverDao; import com.daxiang.exception.ServerException; import com.daxiang.mbg.mapper.DriverMapper; import com.daxiang.mbg.po.Driver; import com.daxiang.mbg.po.DriverExample; import com.daxiang.mbg.po.User; import com.daxiang.model.PagedData; import com.daxiang.model.PageRequest; import com.daxiang.model.dto.DriverFile; import com.daxiang.model.vo.DriverVo; import com.daxiang.security.SecurityUtil; import com.daxiang.utils.HttpServletUtil; import com.github.pagehelper.PageHelper; import com.github.pagehelper.Page; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DuplicateKeyException; import org.springframework.stereotype.Service; import org.springframework.util.CollectionUtils; import org.springframework.util.StringUtils; import java.util.*; import java.util.stream.Collectors; /** * Created by jiangyitao. */ @Service public class DriverService { @Autowired private DriverMapper driverMapper; @Autowired private DriverDao driverDao; @Autowired private UserService userService; @Autowired private FileService fileService; public void add(Driver driver) { driver.setCreateTime(new Date()); driver.setCreatorUid(SecurityUtil.getCurrentUserId()); try { int insertCount = driverMapper.insertSelective(driver); if (insertCount != 1) { throw new ServerException("添加失败,请稍后重试"); } } catch (DuplicateKeyException e) { throw new ServerException(driver.getVersion() + "已存在"); } } public void deleteAndClearRelatedRes(Integer driverId) { if (driverId == null) { throw new ServerException("driverId不能为空"); } Driver driver = driverMapper.selectByPrimaryKey(driverId); if (driver == null) { throw new ServerException("driver不存在"); } int deleteCount = driverMapper.deleteByPrimaryKey(driverId); if (deleteCount != 1) { throw new ServerException("删除失败,请稍后重试"); } List<DriverFile> driverFiles = driver.getFiles(); if (!CollectionUtils.isEmpty(driverFiles)) { driverFiles.forEach(driverFile -> fileService.deleteQuietly(driverFile.getFilePath())); } } public void update(Driver driver) { try { int updateCount = driverMapper.updateByPrimaryKeyWithBLOBs(driver); if (updateCount != 1) { throw new ServerException("更新失败,请稍后重试"); } } catch (DuplicateKeyException e) { throw new ServerException(driver.getVersion() + "已存在"); } } public PagedData<DriverVo> list(Driver query, String orderBy, PageRequest pageRequest) { Page page = PageHelper.startPage(pageRequest.getPageNum(), pageRequest.getPageSize()); if (StringUtils.isEmpty(orderBy)) { orderBy = "create_time desc"; } List<DriverVo> driverVos = getDriverVos(query, orderBy); return new PagedData<>(driverVos, page.getTotal()); } private List<DriverVo> convertDriversToDriverVos(List<Driver> drivers) { if (CollectionUtils.isEmpty(drivers)) { return new ArrayList<>(); } List<Integer> creatorUids = drivers.stream() .map(Driver::getCreatorUid) .filter(Objects::nonNull) .distinct() .collect(Collectors.toList()); Map<Integer, User> userMap = userService.getUserMapByIds(creatorUids); List<DriverVo> driverVos = drivers.stream().map(driver -> { DriverVo driverVo = new DriverVo(); BeanUtils.copyProperties(driver, driverVo); if (driver.getCreatorUid() != null) { User user = userMap.get(driver.getCreatorUid()); if (user != null) { driverVo.setCreatorNickName(user.getNickName()); } } return driverVo; }).collect(Collectors.toList()); return driverVos; } public List<DriverVo> getDriverVos(Driver query, String orderBy) { List<Driver> drivers = getDrivers(query, orderBy); return convertDriversToDriverVos(drivers); } public List<Driver> getDrivers(Driver query, String orderBy) { DriverExample example = new DriverExample(); if (query != null) { DriverExample.Criteria criteria = example.createCriteria(); if (query.getId() != null) { criteria.andIdEqualTo(query.getId()); } if (query.getType() != null) { criteria.andTypeEqualTo(query.getType()); } if (!StringUtils.isEmpty(query.getVersion())) { criteria.andVersionEqualTo(query.getVersion()); } } if (!StringUtils.isEmpty(orderBy)) { example.setOrderByClause(orderBy); } return driverMapper.selectByExampleWithBLOBs(example); } public String getDownloadUrl(Integer type, String deviceId, Integer platform) { if (type == null || StringUtils.isEmpty(deviceId) || platform == null) { throw new ServerException("type or deviceId or platform 不能为空"); } List<Driver> drivers = driverDao.selectByTypeAndDeviceId(type, deviceId); if (!CollectionUtils.isEmpty(drivers)) { // 如果同一个device对应了多个driver,取第一个 List<DriverFile> driverFiles = drivers.get(0).getFiles(); if (!CollectionUtils.isEmpty(driverFiles)) { Optional<DriverFile> driverFile = driverFiles.stream().filter(f -> platform.equals(f.getPlatform())).findFirst(); if (driverFile.isPresent()) { String filePath = driverFile.get().getFilePath(); if (!StringUtils.isEmpty(filePath)) { return HttpServletUtil.getStaticResourceUrl(filePath); } } } } return ""; } } <|start_filename|>src/main/java/com/daxiang/service/UserRoleService.java<|end_filename|> package com.daxiang.service; import com.daxiang.dao.UserRoleDao; import com.daxiang.exception.ServerException; import com.daxiang.mbg.mapper.UserRoleMapper; import com.daxiang.mbg.po.Role; import com.daxiang.mbg.po.UserRole; import com.daxiang.mbg.po.UserRoleExample; import com.daxiang.model.dto.UserRoleDto; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.util.CollectionUtils; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; /** * Created by jiangyitao. */ @Service public class UserRoleService { @Autowired private UserRoleDao userRoleDao; @Autowired private UserRoleMapper userRoleMapper; public void addBatch(List<UserRole> userRoles) { int insertCount = userRoleDao.insertBatch(userRoles); if (insertCount != userRoles.size()) { throw new ServerException("添加失败"); } } public void addBatch(Integer userId, List<Role> roles) { List<UserRole> userRoles = roles.stream().map(role -> { UserRole userRole = new UserRole(); userRole.setUserId(userId); userRole.setRoleId(role.getId()); return userRole; }).collect(Collectors.toList()); addBatch(userRoles); } public int deleteByUserId(Integer userId) { UserRoleExample example = new UserRoleExample(); UserRoleExample.Criteria criteria = example.createCriteria(); criteria.andUserIdEqualTo(userId); return userRoleMapper.deleteByExample(example); } public List<UserRoleDto> getUserRoleDtosByUserIds(List<Integer> userIds) { if (CollectionUtils.isEmpty(userIds)) { return new ArrayList<>(); } return userRoleDao.selectUserRoleDtosByUserIds(userIds); } } <|start_filename|>src/main/java/com/daxiang/service/BrowserService.java<|end_filename|> package com.daxiang.service; import com.daxiang.agent.AgentClient; import com.daxiang.exception.ServerException; import com.daxiang.mbg.mapper.BrowserMapper; import com.daxiang.mbg.po.Browser; import com.daxiang.mbg.po.BrowserExample; import com.daxiang.model.PagedData; import com.daxiang.model.PageRequest; import com.github.pagehelper.Page; import com.github.pagehelper.PageHelper; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.util.CollectionUtils; import org.springframework.util.StringUtils; import java.util.*; import java.util.function.Function; import java.util.stream.Collectors; /** * Created by jiangyitao. */ @Service @Slf4j public class BrowserService { @Autowired private BrowserMapper browserMapper; @Autowired private AgentClient agentClient; public void save(Browser browser) { Browser dbBrowser = browserMapper.selectByPrimaryKey(browser.getId()); int saveCount; if (dbBrowser == null) { browser.setCreateTime(new Date()); saveCount = browserMapper.insertSelective(browser); } else { saveCount = browserMapper.updateByPrimaryKeySelective(browser); } if (saveCount != 1) { throw new ServerException("保存失败,请稍后重试"); } } public PagedData<Browser> list(Browser query, String orderBy, PageRequest pageRequest) { Page page = PageHelper.startPage(pageRequest.getPageNum(), pageRequest.getPageSize()); if (StringUtils.isEmpty(orderBy)) { orderBy = "status desc,create_time desc"; } List<Browser> browsers = getBrowsers(query, orderBy); return new PagedData<>(browsers, page.getTotal()); } public List<Browser> getBrowsers(Browser query, String orderBy) { BrowserExample example = new BrowserExample(); if (query != null) { BrowserExample.Criteria criteria = example.createCriteria(); if (!StringUtils.isEmpty(query.getId())) { criteria.andIdEqualTo(query.getId()); } if (!StringUtils.isEmpty(query.getType())) { criteria.andTypeEqualTo(query.getType()); } if (!StringUtils.isEmpty(query.getVersion())) { criteria.andVersionEqualTo(query.getVersion()); } if (query.getPlatform() != null) { criteria.andPlatformEqualTo(query.getPlatform()); } if (!StringUtils.isEmpty(query.getAgentIp())) { criteria.andAgentIpEqualTo(query.getAgentIp()); } if (query.getStatus() != null) { criteria.andStatusEqualTo(query.getStatus()); } } if (!StringUtils.isEmpty(orderBy)) { example.setOrderByClause(orderBy); } return browserMapper.selectByExample(example); } public Browser start(String browserId) { if (StringUtils.isEmpty(browserId)) { throw new ServerException("浏览器id不能为空"); } Browser dbBrowser = browserMapper.selectByPrimaryKey(browserId); if (dbBrowser == null) { throw new ServerException("浏览器不存在"); } // 有时server被强制关闭,导致数据库浏览器状态与实际不一致 // 在此通过agent获取最新的浏览器状态 Browser agentBrowser = null; try { agentBrowser = agentClient.getBrowser(dbBrowser.getAgentIp(), dbBrowser.getAgentPort(), dbBrowser.getId()).getData(); } catch (Exception ign) { // agent可能已经关闭 } if (agentBrowser == null) { if (dbBrowser.getStatus() != Browser.OFFLINE_STATUS) { // 数据库记录的不是离线,变为离线 dbBrowser.setStatus(Browser.OFFLINE_STATUS); browserMapper.updateByPrimaryKeySelective(dbBrowser); } throw new ServerException("浏览器不在线"); } else { if (agentBrowser.getStatus() == Browser.IDLE_STATUS) { return agentBrowser; } else { // 同步最新状态 browserMapper.updateByPrimaryKeySelective(agentBrowser); throw new ServerException("浏览器未闲置"); } } } public List<Browser> getOnlineBrowsers() { BrowserExample example = new BrowserExample(); BrowserExample.Criteria criteria = example.createCriteria(); criteria.andStatusNotEqualTo(Browser.OFFLINE_STATUS); return browserMapper.selectByExample(example); } public List<Browser> getOnlineBrowsersByAgentIps(List<String> agentIps) { if (CollectionUtils.isEmpty(agentIps)) { return new ArrayList<>(); } BrowserExample example = new BrowserExample(); example.createCriteria() .andAgentIpIn(agentIps) .andStatusNotEqualTo(Browser.OFFLINE_STATUS); return browserMapper.selectByExample(example); } public void agentOffline(String agentIp) { Browser browser = new Browser(); browser.setStatus(Browser.OFFLINE_STATUS); BrowserExample example = new BrowserExample(); example.createCriteria().andAgentIpEqualTo(agentIp); browserMapper.updateByExampleSelective(browser, example); } public List<Browser> getBrowsersByIds(Set<String> browserIds) { if (CollectionUtils.isEmpty(browserIds)) { return new ArrayList<>(); } BrowserExample example = new BrowserExample(); BrowserExample.Criteria criteria = example.createCriteria(); criteria.andIdIn(new ArrayList<>(browserIds)); return browserMapper.selectByExample(example); } public Map<String, Browser> getBrowserMapByBrowserIds(Set<String> browserIds) { List<Browser> browsers = getBrowsersByIds(browserIds); return browsers.stream().collect(Collectors.toMap(Browser::getId, Function.identity(), (k1, k2) -> k1)); } } <|start_filename|>src/main/java/com/daxiang/service/TestPlanService.java<|end_filename|> package com.daxiang.service; import com.daxiang.exception.ServerException; import com.daxiang.mbg.po.TestPlan; import com.daxiang.mbg.po.TestPlanExample; import com.daxiang.mbg.po.User; import com.daxiang.model.PagedData; import com.daxiang.model.PageRequest; import com.daxiang.dao.TestPlanDao; import com.daxiang.model.vo.TestPlanVo; import com.daxiang.security.SecurityUtil; import com.github.pagehelper.PageHelper; import com.github.pagehelper.Page; import com.daxiang.mbg.mapper.TestPlanMapper; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DuplicateKeyException; import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler; import org.springframework.scheduling.support.CronTrigger; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.CollectionUtils; import org.springframework.util.StringUtils; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ScheduledFuture; import java.util.stream.Collectors; /** * Created by jiangyitao. */ @Slf4j @Service public class TestPlanService { private static final ThreadPoolTaskScheduler TASK_SCHEDULER; private static final Map<Integer, ScheduledFuture> TEST_PLAN_SCHEDULED_FUTURE_MAP = new ConcurrentHashMap<>(); static { TASK_SCHEDULER = new ThreadPoolTaskScheduler(); TASK_SCHEDULER.initialize(); } @Autowired private TestPlanMapper testPlanMapper; @Autowired private TestPlanDao testPlanDao; @Autowired private TestTaskService testTaskService; @Autowired private UserService userService; @Transactional public void add(TestPlan testPlan) { if (testPlan.getEnableSchedule() == TestPlan.ENABLE_SCHEDULE && StringUtils.isEmpty(testPlan.getCronExpression())) { // 若开启定时任务,表达式不能为空 throw new ServerException("cron表达式不能为空"); } testPlan.setCreateTime(new Date()); testPlan.setCreatorUid(SecurityUtil.getCurrentUserId()); try { int insertCount = testPlanMapper.insertSelective(testPlan); if (insertCount != 1) { throw new ServerException("添加失败,请稍后重试"); } } catch (DuplicateKeyException e) { throw new ServerException(testPlan.getName() + "已存在"); } if (testPlan.getEnableSchedule() == TestPlan.ENABLE_SCHEDULE) { addOrUpdateScheduleTask(testPlan); } } @Transactional public void delete(Integer testPlanId) { int deleteCount = testPlanMapper.deleteByPrimaryKey(testPlanId); if (deleteCount != 1) { throw new ServerException("删除失败,请稍后重试"); } cancelScheduleTask(testPlanId); } @Transactional public void update(TestPlan testPlan) { if (testPlan.getEnableSchedule() == TestPlan.ENABLE_SCHEDULE && StringUtils.isEmpty(testPlan.getCronExpression())) { // 若开启定时任务,表达式不能为空 throw new ServerException("cron表达式不能为空"); } try { int updateCount = testPlanMapper.updateByPrimaryKeyWithBLOBs(testPlan); if (updateCount != 1) { throw new ServerException("更新失败,请稍后重试"); } } catch (DuplicateKeyException e) { throw new ServerException(testPlan.getName() + "已存在"); } if (testPlan.getEnableSchedule() == TestPlan.ENABLE_SCHEDULE) { addOrUpdateScheduleTask(testPlan); } else { cancelScheduleTask(testPlan.getId()); } } public PagedData<TestPlanVo> list(TestPlan query, String orderBy, PageRequest pageRequest) { Page page = PageHelper.startPage(pageRequest.getPageNum(), pageRequest.getPageSize()); if (StringUtils.isEmpty(orderBy)) { orderBy = "create_time desc"; } List<TestPlanVo> testPlanVos = getTestPlanVos(query, orderBy); return new PagedData<>(testPlanVos, page.getTotal()); } private List<TestPlanVo> convertTestPlansToTestPlanVos(List<TestPlan> testPlans) { if (CollectionUtils.isEmpty(testPlans)) { return new ArrayList<>(); } List<Integer> creatorUids = testPlans.stream() .map(TestPlan::getCreatorUid) .filter(Objects::nonNull) .distinct() .collect(Collectors.toList()); Map<Integer, User> userMap = userService.getUserMapByIds(creatorUids); List<TestPlanVo> testPlanVos = testPlans.stream().map(testPlan -> { TestPlanVo testPlanVo = new TestPlanVo(); BeanUtils.copyProperties(testPlan, testPlanVo); if (testPlan.getCreatorUid() != null) { User user = userMap.get(testPlan.getCreatorUid()); if (user != null) { testPlanVo.setCreatorNickName(user.getNickName()); } } return testPlanVo; }).collect(Collectors.toList()); return testPlanVos; } public List<TestPlanVo> getTestPlanVos(TestPlan query, String orderBy) { List<TestPlan> testPlans = getTestPlans(query, orderBy); return convertTestPlansToTestPlanVos(testPlans); } public List<TestPlan> getTestPlans(TestPlan query) { return getTestPlans(query, null); } public List<TestPlan> getTestPlans(TestPlan query, String orderBy) { TestPlanExample example = new TestPlanExample(); if (query != null) { TestPlanExample.Criteria criteria = example.createCriteria(); if (query.getId() != null) { criteria.andIdEqualTo(query.getId()); } if (query.getProjectId() != null) { criteria.andProjectIdEqualTo(query.getProjectId()); } if (!StringUtils.isEmpty(query.getName())) { criteria.andNameEqualTo(query.getName()); } if (query.getRunMode() != null) { criteria.andRunModeEqualTo(query.getRunMode()); } if (query.getEnableSchedule() != null) { criteria.andEnableScheduleEqualTo(query.getEnableSchedule()); } if (query.getEnvironmentId() != null) { criteria.andEnvironmentIdEqualTo(query.getEnvironmentId()); } if (query.getEnableRecordVideo() != null) { criteria.andEnableRecordVideoEqualTo(query.getEnableRecordVideo()); } } if (!StringUtils.isEmpty(orderBy)) { example.setOrderByClause(orderBy); } return testPlanMapper.selectByExampleWithBLOBs(example); } public void scheduleEnabledTasks() { TestPlan query = new TestPlan(); query.setEnableSchedule(TestPlan.ENABLE_SCHEDULE); List<TestPlan> testPlans = getTestPlans(query); testPlans.forEach(this::addOrUpdateScheduleTask); } private synchronized void addOrUpdateScheduleTask(TestPlan testPlan) { ScheduledFuture future = TEST_PLAN_SCHEDULED_FUTURE_MAP.get(testPlan.getId()); if (future != null) { // 取消上一次设置的定时任务 log.info("cancel schedule, testPlan: {}", testPlan.getName()); future.cancel(true); } log.info("add schedule, testPlan: {}", testPlan.getName()); CronTrigger cronTrigger = new CronTrigger(testPlan.getCronExpression()); future = TASK_SCHEDULER.schedule(() -> testTaskService.commit(testPlan.getId(), testPlan.getCreatorUid()), cronTrigger); TEST_PLAN_SCHEDULED_FUTURE_MAP.put(testPlan.getId(), future); } private synchronized void cancelScheduleTask(Integer testPlanId) { if (testPlanId == null) { throw new ServerException("testPlanId不能为空"); } ScheduledFuture future = TEST_PLAN_SCHEDULED_FUTURE_MAP.get(testPlanId); if (future != null) { log.info("cancel schedule, testPlanId: {}", testPlanId); future.cancel(true); TEST_PLAN_SCHEDULED_FUTURE_MAP.remove(testPlanId); } } public TestPlan getTestPlanById(Integer testPlanId) { return testPlanMapper.selectByPrimaryKey(testPlanId); } public List<TestPlan> getTestPlansByTestSuiteId(Integer testSuiteId) { if (testSuiteId == null) { throw new ServerException("testSuiteId不能为空"); } return testPlanDao.selectByTestSuiteId(testSuiteId); } public List<TestPlan> getTestPlansByActionId(Integer actionId) { return testPlanDao.selectByActionId(actionId); } public List<TestPlan> getTestPlansByEnvironmentId(Integer envId) { if (envId == null) { throw new ServerException("envId不能为空"); } TestPlan query = new TestPlan(); query.setEnvironmentId(envId); return getTestPlans(query); } } <|start_filename|>src/main/java/com/daxiang/controller/ActionController.java<|end_filename|> package com.daxiang.controller; import com.daxiang.mbg.po.Action; import com.daxiang.model.PageRequest; import com.daxiang.model.PagedData; import com.daxiang.model.Response; import com.daxiang.model.dto.ActionTreeNode; import com.daxiang.model.request.ActionDebugRequest; import com.daxiang.model.vo.ActionVo; import com.daxiang.service.ActionService; import com.daxiang.validator.group.SaveActionGroup; import com.daxiang.validator.group.UpdateGroup; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; import java.util.List; /** * Created by jiangyitao. */ @RestController @RequestMapping("/action") public class ActionController { @Autowired private ActionService actionService; @PostMapping("/add") public Response add(@RequestBody @Validated({SaveActionGroup.class}) Action action) { actionService.add(action); return Response.success("添加成功"); } @PostMapping("/resetBasicAction") public Response resetBasicAction(@RequestBody List<Action> actions) { actionService.resetBasicAction(actions); return Response.success(); } @DeleteMapping("/{actionId}") public Response delete(@PathVariable Integer actionId) { actionService.delete(actionId); return Response.success("删除成功"); } @PostMapping("/update") public Response update(@RequestBody @Validated({SaveActionGroup.class, UpdateGroup.class}) Action action) { actionService.update(action); return Response.success("更新成功"); } @PostMapping("/list") public Response list(Action query, String orderBy, PageRequest pageRequest) { if (pageRequest.needPaging()) { PagedData<ActionVo> pagedData = actionService.list(query, orderBy, pageRequest); return Response.success(pagedData); } else { List<ActionVo> actionVos = actionService.getActionVos(query, orderBy); return Response.success(actionVos); } } @GetMapping("/cascader") public Response cascader(Integer projectId, Integer platform, Integer type) { List<ActionTreeNode> tree = actionService.cascader(projectId, platform, type); return Response.success(tree); } @PostMapping("/debug") public Response debug(@Valid @RequestBody ActionDebugRequest actionDebugRequest) { return actionService.debug(actionDebugRequest); } } <|start_filename|>src/main/java/com/daxiang/dao/GlobalVarDao.java<|end_filename|> package com.daxiang.dao; import com.daxiang.mbg.po.GlobalVar; import org.apache.ibatis.annotations.Param; import java.util.List; /** * Created by jiangyitao. */ public interface GlobalVarDao { int insertBatch(@Param("globalVars") List<GlobalVar> globalVars); List<GlobalVar> selectByEnvironmentId(@Param("envId") Integer envId); } <|start_filename|>src/main/java/com/daxiang/controller/CategoryController.java<|end_filename|> package com.daxiang.controller; import com.daxiang.mbg.po.Category; import com.daxiang.model.PageRequest; import com.daxiang.model.PagedData; import com.daxiang.model.Response; import com.daxiang.model.vo.CategoryVo; import com.daxiang.service.CategoryService; import com.daxiang.utils.Tree; import com.daxiang.validator.group.UpdateGroup; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; import java.util.List; /** * Created by jiangyitao. */ @RestController @RequestMapping("/category") public class CategoryController { @Autowired private CategoryService categoryService; @PostMapping("/add") public Response add(@RequestBody @Valid Category category) { categoryService.add(category); return Response.success("添加成功"); } @DeleteMapping("/{categoryId}/type/{type}/project/{projectId}") public Response delete(@PathVariable Integer categoryId, @PathVariable Integer type, @PathVariable Integer projectId) { categoryService.delete(categoryId, type, projectId); return Response.success("删除成功"); } @PostMapping("/update") public Response update(@RequestBody @Validated({UpdateGroup.class}) Category category) { categoryService.update(category); return Response.success("更新成功"); } @PostMapping("/list") public Response list(Category query, String orderBy, PageRequest pageRequest) { if (pageRequest.needPaging()) { PagedData<CategoryVo> pagedData = categoryService.list(query, orderBy, pageRequest); return Response.success(pagedData); } else { List<CategoryVo> categoryVos = categoryService.getCategoryVos(query, orderBy); return Response.success(categoryVos); } } @GetMapping("/tree") public Response getCategoryTree(Integer projectId, Integer type) { List<Tree.TreeNode> tree = categoryService.getCategoryTreeByProjectIdAndType(projectId, type); return Response.success(tree); } } <|start_filename|>src/main/java/com/daxiang/mbg/mapper/BrowserMapper.java<|end_filename|> package com.daxiang.mbg.mapper; import com.daxiang.mbg.po.Browser; import com.daxiang.mbg.po.BrowserExample; import java.util.List; import org.apache.ibatis.annotations.Param; public interface BrowserMapper { long countByExample(BrowserExample example); int deleteByExample(BrowserExample example); int deleteByPrimaryKey(String id); int insert(Browser record); int insertSelective(Browser record); List<Browser> selectByExample(BrowserExample example); Browser selectByPrimaryKey(String id); int updateByExampleSelective(@Param("record") Browser record, @Param("example") BrowserExample example); int updateByExample(@Param("record") Browser record, @Param("example") BrowserExample example); int updateByPrimaryKeySelective(Browser record); int updateByPrimaryKey(Browser record); } <|start_filename|>src/main/java/com/daxiang/config/RestTemplateConfig.java<|end_filename|> package com.daxiang.config; import lombok.extern.slf4j.Slf4j; import org.apache.commons.io.IOUtils; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpRequest; import org.springframework.http.client.*; import org.springframework.web.client.RestTemplate; import java.io.IOException; import java.nio.charset.Charset; /** * Created by jiangyitao. */ @Configuration public class RestTemplateConfig { @Bean public RestTemplate restTemplate(ClientHttpRequestFactory factory) { RestTemplate restTemplate = new RestTemplate(new BufferingClientHttpRequestFactory(factory)); restTemplate.getInterceptors().add(new LoggingClientHttpRequestInterceptor()); return restTemplate; } @Bean public ClientHttpRequestFactory simpleClientHttpRequestFactory() { SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory(); factory.setReadTimeout(600000); factory.setConnectTimeout(600000); return factory; } @Slf4j static class LoggingClientHttpRequestInterceptor implements ClientHttpRequestInterceptor { @Override public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException { printRequest(request, body); ClientHttpResponse response = execution.execute(request, body); printResponse(response); return response; } private void printRequest(HttpRequest request, byte[] body) { log.info("[http-request][{}->{}] {}", request.getMethod(), request.getURI(), new String(body, Charset.forName("UTF-8"))); } private void printResponse(ClientHttpResponse response) throws IOException { log.info("[http-response] {}", IOUtils.toString(response.getBody(), Charset.forName("UTF-8"))); } } } <|start_filename|>src/main/java/com/daxiang/controller/UploadController.java<|end_filename|> package com.daxiang.controller; import com.daxiang.model.Response; import com.daxiang.model.UploadFile; import com.daxiang.model.enums.UploadDir; import com.daxiang.service.FileService; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; /** * Created by jiangyitao. */ @RestController @RequestMapping("/upload") @Slf4j public class UploadController { @Autowired private FileService fileService; @PostMapping("/file/{fileType}") public Response uploadFile(MultipartFile file, @PathVariable Integer fileType) { UploadFile uploadFile = fileService.upload(file, UploadDir.get(fileType)); return Response.success(uploadFile); } } <|start_filename|>src/main/java/com/daxiang/controller/DriverController.java<|end_filename|> package com.daxiang.controller; import com.daxiang.mbg.po.Driver; import com.daxiang.model.PageRequest; import com.daxiang.model.PagedData; import com.daxiang.model.Response; import com.daxiang.model.vo.DriverVo; import com.daxiang.service.DriverService; import com.daxiang.validator.group.UpdateGroup; import com.google.common.collect.ImmutableMap; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; import java.util.List; /** * Created by jiangyitao. */ @RestController @RequestMapping("/driver") public class DriverController { @Autowired private DriverService driverService; @PostMapping("/add") public Response add(@Valid @RequestBody Driver driver) { driverService.add(driver); return Response.success("添加成功"); } @DeleteMapping("/{driverId}") public Response delete(@PathVariable Integer driverId) { driverService.deleteAndClearRelatedRes(driverId); return Response.success("删除成功"); } @PostMapping("/update") public Response update(@Validated({UpdateGroup.class}) @RequestBody Driver driver) { driverService.update(driver); return Response.success("更新成功"); } @PostMapping("/list") public Response list(Driver query, String orderBy, PageRequest pageRequest) { if (pageRequest.needPaging()) { PagedData<DriverVo> pagedData = driverService.list(query, orderBy, pageRequest); return Response.success(pagedData); } else { List<DriverVo> driverVos = driverService.getDriverVos(query, orderBy); return Response.success(driverVos); } } @PostMapping("/downloadUrl") public Response getDownloadUrl(Integer type, String deviceId, Integer platform) { String url = driverService.getDownloadUrl(type, deviceId, platform); return Response.success(ImmutableMap.of("downloadUrl", url)); } } <|start_filename|>src/main/java/com/daxiang/service/FileService.java<|end_filename|> package com.daxiang.service; import com.daxiang.exception.ServerException; import com.daxiang.model.UploadFile; import com.daxiang.model.enums.UploadDir; import com.daxiang.utils.HttpServletUtil; import com.daxiang.utils.UUIDUtil; import lombok.extern.slf4j.Slf4j; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.ArrayUtils; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; import org.springframework.web.multipart.MultipartFile; import java.io.File; import java.io.IOException; import java.util.concurrent.TimeUnit; /** * Created by jiangyitao. */ @Slf4j @Service public class FileService { @Value("${static-location}/") private String staticLocation; public void deleteQuietly(String filePath) { if (StringUtils.isEmpty(filePath)) { return; } File file = new File(staticLocation + filePath); boolean deleted = FileUtils.deleteQuietly(file); if (deleted) { log.info("delete {} success", file.getAbsolutePath()); } else { log.warn("delete {} fail, the file is maybe not exists", file.getAbsolutePath()); } } public void mkUploadDirIfNotExists() { File uploadTmpDir = new File(staticLocation + UploadDir.TMP.path); if (!uploadTmpDir.exists()) { log.info("创建tmp目录 -> {}", uploadTmpDir.getAbsolutePath()); uploadTmpDir.mkdirs(); } File uploadImgDir = new File(staticLocation + UploadDir.IMG.path); if (!uploadImgDir.exists()) { log.info("创建img目录 -> {}", uploadImgDir.getAbsolutePath()); uploadImgDir.mkdirs(); } File uploadVideoDir = new File(staticLocation + UploadDir.VIDEO.path); if (!uploadVideoDir.exists()) { log.info("创建video目录 -> {}", uploadVideoDir.getAbsolutePath()); uploadVideoDir.mkdirs(); } File uploadAppDir = new File(staticLocation + UploadDir.APP.path); if (!uploadAppDir.exists()) { log.info("创建app目录 -> {}", uploadAppDir.getAbsolutePath()); uploadAppDir.mkdirs(); } File uploadDriverDir = new File(staticLocation + UploadDir.DRIVER.path); if (!uploadDriverDir.exists()) { log.info("创建driver目录 -> {}", uploadDriverDir.getAbsolutePath()); uploadDriverDir.mkdirs(); } File uploadLogDir = new File(staticLocation + UploadDir.LOG.path); if (!uploadDriverDir.exists()) { log.info("创建log目录 -> {}", uploadLogDir.getAbsolutePath()); uploadLogDir.mkdirs(); } File uploadAgentExtJarDir = new File(staticLocation + UploadDir.AGENT_EXT_JAR.path); if (!uploadAgentExtJarDir.exists()) { log.info("创建agent ext jar目录 -> {}", uploadAgentExtJarDir.getAbsolutePath()); uploadAgentExtJarDir.mkdirs(); } } public UploadFile upload(MultipartFile file, UploadDir uploadDir) { return upload(file, uploadDir, true); } public UploadFile upload(MultipartFile file, UploadDir uploadDir, boolean renameFile) { if (file == null || uploadDir == null) { throw new ServerException("file or uploadDir不能为空"); } String originalFilename = file.getOriginalFilename(); String destFilePath = renameFile ? uploadDir.path + "/" + UUIDUtil.getUUIDFilename(originalFilename) : uploadDir.path + "/" + originalFilename; File destFile = new File(staticLocation + destFilePath); try { log.info("upload {} -> {}", originalFilename, destFilePath); FileUtils.copyInputStreamToFile(file.getInputStream(), destFile); } catch (IOException e) { log.error("write {} to {} err", originalFilename, destFilePath, e); throw new ServerException(e.getMessage()); } UploadFile uploadFile = new UploadFile(); uploadFile.setFile(destFile); uploadFile.setFilePath(destFilePath); uploadFile.setDownloadUrl(HttpServletUtil.getStaticResourceUrl(destFilePath)); return uploadFile; } public void moveFile(String srcFilePath, String destFilePath) throws IOException { File src = new File(staticLocation + srcFilePath); File dest = new File(staticLocation + destFilePath); log.info("move {} -> {}", src, dest); FileUtils.moveFile(src, dest); } public int clearTmpFilesBefore(int beforeDays) { int deletedTmpFilesCount = 0; File[] files = new File(staticLocation + UploadDir.TMP.path).listFiles(); if (ArrayUtils.isEmpty(files)) { return deletedTmpFilesCount; } long currentTimeMillis = System.currentTimeMillis(); long beforeMs = TimeUnit.DAYS.toMillis(beforeDays); for (File file : files) { if (currentTimeMillis - file.lastModified() >= beforeMs) { boolean isDeleted = file.delete(); if (isDeleted) { deletedTmpFilesCount++; log.info("delete {} success", file.getAbsolutePath()); } else { log.warn("delete {} fail", file.getAbsolutePath()); } } } return deletedTmpFilesCount; } public boolean exist(UploadDir uploadDir, String filename) { return new File(staticLocation + uploadDir.path, filename).exists(); } } <|start_filename|>src/main/java/com/daxiang/service/AgentService.java<|end_filename|> package com.daxiang.service; import com.alibaba.fastjson.JSONObject; import com.daxiang.exception.ServerException; import com.daxiang.mbg.po.Browser; import com.daxiang.mbg.po.Mobile; import com.daxiang.model.vo.AgentVo; import de.codecentric.boot.admin.server.domain.entities.Instance; import de.codecentric.boot.admin.server.domain.values.Endpoint; import de.codecentric.boot.admin.server.domain.values.StatusInfo; import de.codecentric.boot.admin.server.services.InstanceRegistry; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; import java.net.URI; import java.net.URISyntaxException; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.stream.Collectors; /** * Created by jiangyitao. */ @Service @Slf4j public class AgentService { @Autowired private InstanceRegistry instanceRegistry; @Autowired private MobileService mobileService; @Autowired private BrowserService browserService; @Autowired private RestTemplate restTemplate; public List<AgentVo> getOnlineAgents() { List<AgentVo> agentVos = getOnlineAgentsWithoutDevices(); List<String> agentIps = agentVos.stream().map(AgentVo::getIp).collect(Collectors.toList()); List<Mobile> mobiles = mobileService.getOnlineMobilesByAgentIps(agentIps); Map<String, List<Mobile>> mobileMap = mobiles.stream().collect(Collectors.groupingBy(Mobile::getAgentIp)); // agentIp: List<Mobile> List<Browser> browsers = browserService.getOnlineBrowsersByAgentIps(agentIps); Map<String, List<Browser>> browserMap = browsers.stream().collect(Collectors.groupingBy(Browser::getAgentIp)); // agentIp: List<Browser> agentVos.forEach(agentVo -> { String ip = agentVo.getIp(); agentVo.setMobiles(mobileMap.get(ip)); agentVo.setBrowsers(browserMap.get(ip)); }); return agentVos; } public List<AgentVo> getOnlineAgentsWithoutDevices() { return instanceRegistry.getInstances().collectList().block().stream() .filter(agent -> StatusInfo.STATUS_UP.equals(agent.getStatusInfo().getStatus())) .map(this::createAgentVoWithoutDevices) .collect(Collectors.toList()); } private AgentVo createAgentVoWithoutDevices(Instance agent) { URI uri; try { uri = new URI(agent.getRegistration().getServiceUrl()); } catch (URISyntaxException e) { throw new ServerException(e); } AgentVo agentVo = new AgentVo(); agentVo.setInstanceId(agent.getId().getValue()); agentVo.setIp(uri.getHost()); agentVo.setPort(uri.getPort()); Optional<Endpoint> env = agent.getEndpoints().get("env"); if (env.isPresent()) { // http://agent_ip:agent_port/actuator/env JSONObject response = restTemplate.getForObject(env.get().getUrl(), JSONObject.class); Object sysProperties = response.getJSONArray("propertySources").stream() .filter(property -> "systemProperties".equals(((JSONObject) property).get("name"))) .findFirst().get(); JSONObject properties = ((JSONObject) (sysProperties)).getJSONObject("properties"); agentVo.setOsName(properties.getJSONObject("os.name").getString("value")); agentVo.setJavaVersion(properties.getJSONObject("java.version").getString("value")); agentVo.setIsConfigAapt(properties.getJSONObject("aapt").getBoolean("value")); agentVo.setVersion(properties.getJSONObject("agent.version").getString("value")); JSONObject appiumVersion = properties.getJSONObject("appium.version"); if (appiumVersion != null) { agentVo.setAppiumVersion(appiumVersion.getString("value")); } } return agentVo; } } <|start_filename|>src/main/java/com/daxiang/mbg/po/User.java<|end_filename|> package com.daxiang.mbg.po; import com.daxiang.validator.group.SaveUserGroup; import com.daxiang.validator.group.UpdateGroup; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; import java.io.Serializable; import java.util.Date; public class User implements Serializable { public static final int ENABLE_STATUS = 1; @NotNull(message = "用户id不能为空", groups = {UpdateGroup.class}) private Integer id; /** * 用户名 * * @mbg.generated */ @NotBlank(message = "用户名不能为空") private String username; /** * 用户密码 * * @mbg.generated */ @NotBlank(message = "密码不能为空") private String password; /** * 用户昵称 * * @mbg.generated */ @NotBlank(message = "昵称不能为空", groups = {SaveUserGroup.class}) private String nickName; /** * 状态,0:禁用 1:正常 * * @mbg.generated */ @NotNull(message = "账户状态不能为空", groups = {SaveUserGroup.class}) private Integer status; /** * 创建时间 * * @mbg.generated */ private Date createTime; private static final long serialVersionUID = 1L; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public void setPassword(String password) { this.password = password; } public String getPassword() { return password; } public String getNickName() { return nickName; } public void setNickName(String nickName) { this.nickName = nickName; } public Integer getStatus() { return status; } public void setStatus(Integer status) { this.status = status; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", username=").append(username); sb.append(", password=").append(password); sb.append(", nickName=").append(nickName); sb.append(", status=").append(status); sb.append(", createTime=").append(createTime); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } } <|start_filename|>src/main/java/com/daxiang/validator/HasLengthIfNotEmptyValidator.java<|end_filename|> package com.daxiang.validator; import com.daxiang.validator.annotation.HasLengthIfNotEmpty; import org.springframework.util.CollectionUtils; import org.springframework.util.StringUtils; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; import java.util.List; /** * Created by jiangyitao. */ public class HasLengthIfNotEmptyValidator implements ConstraintValidator<HasLengthIfNotEmpty, List<String>> { @Override public boolean isValid(List<String> values, ConstraintValidatorContext context) { if (!CollectionUtils.isEmpty(values)) { for (String value : values) { if (!StringUtils.hasLength(value)) { return false; } } } return true; } } <|start_filename|>src/main/java/com/daxiang/controller/EnvironmentController.java<|end_filename|> package com.daxiang.controller; import com.daxiang.mbg.po.Environment; import com.daxiang.model.PageRequest; import com.daxiang.model.PagedData; import com.daxiang.model.Response; import com.daxiang.model.vo.EnvironmentVo; import com.daxiang.service.EnvironmentService; import com.daxiang.validator.group.UpdateGroup; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; import java.util.List; /** * Created by jiangyitao. */ @RestController @RequestMapping("/environment") public class EnvironmentController { @Autowired private EnvironmentService environmentService; @PostMapping("/add") public Response add(@Valid @RequestBody Environment environment) { environmentService.add(environment); return Response.success("添加成功"); } @DeleteMapping("/{environmentId}") public Response delete(@PathVariable Integer environmentId) { environmentService.delete(environmentId); return Response.success("删除成功"); } @PostMapping("/update") public Response update(@Validated({UpdateGroup.class}) @RequestBody Environment environment) { environmentService.update(environment); return Response.success("更新成功"); } @PostMapping("/list") public Response list(Environment query, String orderBy, PageRequest pageRequest) { if (pageRequest.needPaging()) { PagedData<EnvironmentVo> pagedData = environmentService.list(query, orderBy, pageRequest); return Response.success(pagedData); } else { List<EnvironmentVo> environmentVos = environmentService.getEnvironmentVos(query, orderBy); return Response.success(environmentVos); } } } <|start_filename|>src/main/java/com/daxiang/model/dto/CategoryTreeNode.java<|end_filename|> package com.daxiang.model.dto; import com.daxiang.mbg.po.Category; import com.daxiang.utils.Tree; import com.fasterxml.jackson.annotation.JsonInclude; import lombok.Data; import org.springframework.beans.BeanUtils; import java.util.List; /** * Created by jiangyitao. */ @Data @JsonInclude(JsonInclude.Include.NON_NULL) public class CategoryTreeNode extends Category implements Tree.TreeNode { private List<Tree.TreeNode> children; public static CategoryTreeNode create(Category category) { CategoryTreeNode categoryTreeNode = new CategoryTreeNode(); BeanUtils.copyProperties(category, categoryTreeNode); return categoryTreeNode; } } <|start_filename|>src/main/java/com/daxiang/controller/ApplicationController.java<|end_filename|> package com.daxiang.controller; import com.daxiang.model.Response; import com.google.common.collect.ImmutableMap; import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * Created by jiangyitao. */ @RestController @RequestMapping("/application") public class ApplicationController { @Value("${version}") private String version; @GetMapping("/version") public Response version() { return Response.success(ImmutableMap.of("version", version)); } } <|start_filename|>src/main/java/com/daxiang/mbg/mapper/GlobalVarMapper.java<|end_filename|> package com.daxiang.mbg.mapper; import com.daxiang.mbg.po.GlobalVar; import com.daxiang.mbg.po.GlobalVarExample; import java.util.List; import org.apache.ibatis.annotations.Param; public interface GlobalVarMapper { long countByExample(GlobalVarExample example); int deleteByExample(GlobalVarExample example); int deleteByPrimaryKey(Integer id); int insert(GlobalVar record); int insertSelective(GlobalVar record); List<GlobalVar> selectByExampleWithBLOBs(GlobalVarExample example); List<GlobalVar> selectByExample(GlobalVarExample example); GlobalVar selectByPrimaryKey(Integer id); int updateByExampleSelective(@Param("record") GlobalVar record, @Param("example") GlobalVarExample example); int updateByExampleWithBLOBs(@Param("record") GlobalVar record, @Param("example") GlobalVarExample example); int updateByExample(@Param("record") GlobalVar record, @Param("example") GlobalVarExample example); int updateByPrimaryKeySelective(GlobalVar record); int updateByPrimaryKeyWithBLOBs(GlobalVar record); int updateByPrimaryKey(GlobalVar record); } <|start_filename|>src/main/java/com/daxiang/model/action/Param.java<|end_filename|> package com.daxiang.model.action; import com.daxiang.validator.annotation.JavaIdentifier; import lombok.Data; import javax.validation.constraints.NotBlank; import java.util.List; /** * Created by jiangyitao. * action参数 */ @Data public class Param { /** * 参数类型 */ @NotBlank(message = "方法参数类型不能为空") private String type; /** * 参数名 */ @JavaIdentifier(message = "方法参数名不合法") private String name; /** * 参数描述 */ private String description; /** * 可能的值,供调用方参考 */ private List<PossibleValue> possibleValues; } <|start_filename|>src/main/java/com/daxiang/model/enums/UploadDir.java<|end_filename|> package com.daxiang.model.enums; import java.util.stream.Stream; /** * Created by jiangyitao. */ public enum UploadDir { TMP(-1, "upload/tmp"), IMG(1, "upload/img"), VIDEO(2, "upload/video"), APP(3, "upload/app"), DRIVER(4, "upload/driver"), LOG(5, "upload/log"), AGENT_EXT_JAR(6, "upload/agent_ext_jar"); public int fileType; public String path; UploadDir(int fileType, String path) { this.fileType = fileType; this.path = path; } public static UploadDir get(int fileType) { return Stream.of(UploadDir.values()) .filter(uploadDir -> uploadDir.fileType == fileType) .findFirst() .orElseThrow(() -> new IllegalArgumentException("unknow fileType=" + fileType)); } } <|start_filename|>src/main/java/com/daxiang/validator/NoDuplicateElementValidator.java<|end_filename|> package com.daxiang.validator; import com.daxiang.model.page.Element; import com.daxiang.validator.annotation.NoDuplicateElement; import org.springframework.util.CollectionUtils; import org.springframework.util.StringUtils; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; import java.util.List; import java.util.Map; import java.util.stream.Collectors; /** * Created by jiangyitao. */ public class NoDuplicateElementValidator implements ConstraintValidator<NoDuplicateElement, List<Element>> { @Override public boolean isValid(List<Element> elementList, ConstraintValidatorContext context) { if (!CollectionUtils.isEmpty(elementList)) { Map<String, Long> elementNameCountMap = elementList.stream().filter(element -> !StringUtils.isEmpty(element.getName())) .collect(Collectors.groupingBy(Element::getName, Collectors.counting())); for (Map.Entry<String, Long> elementNameCount : elementNameCountMap.entrySet()) { if (elementNameCount.getValue() > 1) { return false; } } } return true; } } <|start_filename|>src/main/java/com/daxiang/service/ProjectService.java<|end_filename|> package com.daxiang.service; import com.daxiang.exception.ServerException; import com.daxiang.mbg.mapper.ProjectMapper; import com.daxiang.mbg.po.User; import com.daxiang.model.PageRequest; import com.daxiang.mbg.po.ProjectExample; import com.daxiang.security.SecurityUtil; import com.github.pagehelper.PageHelper; import com.github.pagehelper.Page; import com.daxiang.mbg.po.Project; import com.daxiang.model.PagedData; import com.daxiang.model.vo.ProjectVo; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DuplicateKeyException; import org.springframework.stereotype.Service; import org.springframework.util.CollectionUtils; import org.springframework.util.StringUtils; import java.util.*; import java.util.stream.Collectors; /** * Created by jiangyitao. */ @Service public class ProjectService { @Autowired private ProjectMapper projectMapper; @Autowired private UserService userService; public void add(Project project) { project.setCreateTime(new Date()); project.setCreatorUid(SecurityUtil.getCurrentUserId()); try { int insertCount = projectMapper.insertSelective(project); if (insertCount != 1) { throw new ServerException("添加失败,请稍后重试"); } } catch (DuplicateKeyException e) { throw new ServerException(project.getName() + "已存在"); } } public void delete(Integer projectId) { if (projectId == null) { throw new ServerException("projectId不能为空"); } int deleteCount = projectMapper.deleteByPrimaryKey(projectId); if (deleteCount != 1) { throw new ServerException("删除失败,请稍后重试"); } } public void update(Project project) { try { int updateCount = projectMapper.updateByPrimaryKeySelective(project); if (updateCount != 1) { throw new ServerException("更新失败,请稍后重试"); } } catch (DuplicateKeyException e) { throw new ServerException(project.getName() + "已存在"); } } public PagedData<ProjectVo> list(Project query, String orderBy, PageRequest pageRequest) { Page page = PageHelper.startPage(pageRequest.getPageNum(), pageRequest.getPageSize()); if (StringUtils.isEmpty(orderBy)) { orderBy = "create_time desc"; } List<ProjectVo> projectVos = getProjectVos(query, orderBy); return new PagedData<>(projectVos, page.getTotal()); } private List<ProjectVo> convertProjectsToProjectVos(List<Project> projects) { if (CollectionUtils.isEmpty(projects)) { return new ArrayList<>(); } List<Integer> creatorUids = projects.stream() .map(Project::getCreatorUid) .filter(Objects::nonNull) .distinct() .collect(Collectors.toList()); Map<Integer, User> userMap = userService.getUserMapByIds(creatorUids); List<ProjectVo> projectVos = projects.stream().map(project -> { ProjectVo projectVo = new ProjectVo(); BeanUtils.copyProperties(project, projectVo); if (project.getCreatorUid() != null) { User user = userMap.get(project.getCreatorUid()); if (user != null) { projectVo.setCreatorNickName(user.getNickName()); } } return projectVo; }).collect(Collectors.toList()); return projectVos; } public List<ProjectVo> getProjectVos(Project query, String orderBy) { List<Project> projects = getProjects(query, orderBy); return convertProjectsToProjectVos(projects); } public List<Project> getProjects(Project query, String orderBy) { ProjectExample example = new ProjectExample(); if (query != null) { ProjectExample.Criteria criteria = example.createCriteria(); if (query.getId() != null) { criteria.andIdEqualTo(query.getId()); } if (!StringUtils.isEmpty(query.getName())) { criteria.andNameEqualTo(query.getName()); } if (query.getPlatform() != null) { criteria.andPlatformEqualTo(query.getPlatform()); } } if (!StringUtils.isEmpty(orderBy)) { example.setOrderByClause(orderBy); } return projectMapper.selectByExampleWithBLOBs(example); } public Project getProjectById(Integer id) { return projectMapper.selectByPrimaryKey(id); } public List<Project> getAll() { return projectMapper.selectByExample(null); } } <|start_filename|>src/main/java/com/daxiang/model/Platform.java<|end_filename|> package com.daxiang.model; /** * Created by jiangyitao. */ public interface Platform { int ANDROID = 1; int IOS = 2; int PC_WEB = 3; } <|start_filename|>src/main/java/com/daxiang/model/dto/UserProjectDto.java<|end_filename|> package com.daxiang.model.dto; import com.daxiang.mbg.po.Project; import com.daxiang.mbg.po.UserProject; import lombok.Data; /** * Created by jiangyitao. */ @Data public class UserProjectDto extends UserProject { private Project project; } <|start_filename|>src/main/java/com/daxiang/mbg/po/Page.java<|end_filename|> package com.daxiang.mbg.po; import com.daxiang.validator.annotation.JavaIdentifier; import com.daxiang.validator.annotation.NoDuplicateBy; import com.daxiang.validator.annotation.NoDuplicateElement; import com.daxiang.validator.group.UpdateGroup; import javax.validation.Valid; import javax.validation.constraints.NotNull; import java.io.Serializable; import java.util.Date; public class Page implements Serializable { public static final int TYPE_ANDROID_NATIVE = 1; public static final int TYPE_IOS_NATIVE = 2; public static final int TYPE_WEB = 3; @NotNull(message = "id不能为空", groups = {UpdateGroup.class}) private Integer id; /** * page名 * * @mbg.generated */ @JavaIdentifier(message = "Page名不合法") private String name; /** * page所属项目 * * @mbg.generated */ @NotNull(message = "所属项目不能为空") private Integer projectId; /** * 1.android_native 2.ios_native 3.web * * @mbg.generated */ @NotNull(message = "type不能为空") private Integer type; /** * page所属分类 * * @mbg.generated */ private Integer categoryId; /** * page描述 * * @mbg.generated */ private String description; /** * 服务端保存的文件路径 * * @mbg.generated */ private String imgPath; /** * window高度 * * @mbg.generated */ private Integer windowHeight; /** * window宽度 * * @mbg.generated */ private Integer windowWidth; /** * 屏幕方向 * * @mbg.generated */ private String windowOrientation; /** * 图片所属的deviceId * * @mbg.generated */ private String deviceId; /** * 创建人id * * @mbg.generated */ private Integer creatorUid; /** * 创建时间 * * @mbg.generated */ private Date createTime; /** * 页面布局 * * @mbg.generated */ private String windowHierarchy; /** * 元素 * * @mbg.generated */ @Valid @NoDuplicateElement(message = "元素名不能重复") private java.util.List<com.daxiang.model.page.Element> elements; /** * By * * @mbg.generated */ @Valid @NoDuplicateBy(message = "By name不能重复") private java.util.List<com.daxiang.model.page.By> bys; private static final long serialVersionUID = 1L; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getProjectId() { return projectId; } public void setProjectId(Integer projectId) { this.projectId = projectId; } public Integer getType() { return type; } public void setType(Integer type) { this.type = type; } public Integer getCategoryId() { return categoryId; } public void setCategoryId(Integer categoryId) { this.categoryId = categoryId; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getImgPath() { return imgPath; } public void setImgPath(String imgPath) { this.imgPath = imgPath; } public Integer getWindowHeight() { return windowHeight; } public void setWindowHeight(Integer windowHeight) { this.windowHeight = windowHeight; } public Integer getWindowWidth() { return windowWidth; } public void setWindowWidth(Integer windowWidth) { this.windowWidth = windowWidth; } public String getWindowOrientation() { return windowOrientation; } public void setWindowOrientation(String windowOrientation) { this.windowOrientation = windowOrientation; } public String getDeviceId() { return deviceId; } public void setDeviceId(String deviceId) { this.deviceId = deviceId; } public Integer getCreatorUid() { return creatorUid; } public void setCreatorUid(Integer creatorUid) { this.creatorUid = creatorUid; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public String getWindowHierarchy() { return windowHierarchy; } public void setWindowHierarchy(String windowHierarchy) { this.windowHierarchy = windowHierarchy; } public java.util.List<com.daxiang.model.page.Element> getElements() { return elements; } public void setElements(java.util.List<com.daxiang.model.page.Element> elements) { this.elements = elements; } public java.util.List<com.daxiang.model.page.By> getBys() { return bys; } public void setBys(java.util.List<com.daxiang.model.page.By> bys) { this.bys = bys; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", name=").append(name); sb.append(", projectId=").append(projectId); sb.append(", type=").append(type); sb.append(", categoryId=").append(categoryId); sb.append(", description=").append(description); sb.append(", imgPath=").append(imgPath); sb.append(", windowHeight=").append(windowHeight); sb.append(", windowWidth=").append(windowWidth); sb.append(", windowOrientation=").append(windowOrientation); sb.append(", deviceId=").append(deviceId); sb.append(", creatorUid=").append(creatorUid); sb.append(", createTime=").append(createTime); sb.append(", windowHierarchy=").append(windowHierarchy); sb.append(", elements=").append(elements); sb.append(", bys=").append(bys); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
faxianLeo/server
<|start_filename|>IAD-Nov-2018/iad-books/src/main/java/com/example/demo/BookRepository.java<|end_filename|> package com.example.demo; import org.springframework.data.mongodb.repository.Query; import org.springframework.data.repository.CrudRepository; public interface BookRepository extends CrudRepository<Book, String> { Book findByIsbn(String isbn); SimpleBook findSimpleByIsbn(String isbn); Iterable<Book> findByAuthorFirstNameAndAuthorLastName(String fn, String ln); @Query("{'authorFirstName':'Kendall', 'authorLastName':'Crolius'}") Iterable<Book> kendallsBooks(); } <|start_filename|>IAD-Nov-2019/iad-books/src/main/java/habuma/Thing.java<|end_filename|> package habuma; public class Thing { private Thing otherThing; public void setOtherThing(Thing otherThing) { this.otherThing = otherThing; } } <|start_filename|>STL-Apr-2018/src/main/java/habuma/ProfilesStlApplication.java<|end_filename|> package habuma; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; @SpringBootApplication public class ProfilesStlApplication { public static void main(String[] args) { SpringApplication.run(ProfilesStlApplication.class, args); } @Bean public CommandLineRunner dataLoader(ProfileRepository repo, BookRepository bookRepo) { return args -> { repo.save(new Profile("habuma", "password", "<PASSWORD>", true)); repo.save(new Profile("venkat", "password", "<PASSWORD>", true)); repo.save(new Profile("nate", "password1", "<PASSWORD>", false)); bookRepo.save(new Book("1234567890", "Knitting with Dog Hair", "Kendall", "Crolius")); bookRepo.save(new Book("1928374560", "Collecting Camel Hair", "Kendall", "Jones")); bookRepo.save(new Book("9876543210", "Crafting with Cat Hair", "Tsuyana", "Smith")); }; } } <|start_filename|>SEA-Oct-2018/sea-profiles/src/main/java/habuma/ProfileController.java<|end_filename|> package habuma; import org.springframework.security.core.annotation.AuthenticationPrincipal; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import lombok.RequiredArgsConstructor; @Controller @RequestMapping("/profiles") @RequiredArgsConstructor public class ProfileController { @GetMapping("/me") public String me(@AuthenticationPrincipal Profile profile, Model model) { model.addAttribute("profile", profile); return "profile"; } } <|start_filename|>SLC-May-2019/slc-books/src/main/java/habuma/books/MyInfoContributor.java<|end_filename|> package habuma.books; import org.springframework.boot.actuate.info.InfoContributor; import org.springframework.stereotype.Component; import java.awt.Point; import org.springframework.boot.actuate.info.Info.Builder; @Component public class MyInfoContributor implements InfoContributor { @Override public void contribute(Builder builder) { Point p = new Point(100, 200); builder .withDetail("time", System.currentTimeMillis()) .withDetail("point", p); } } <|start_filename|>SLC-May-2019/slc-books/src/main/java/habuma/books/HelloController.java<|end_filename|> package habuma.books; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import io.micrometer.core.instrument.MeterRegistry; import lombok.RequiredArgsConstructor; @RestController @RequiredArgsConstructor public class HelloController { private final GreetingProps props; private final MeterRegistry registry; @GetMapping("/hello") public String hello() { registry.counter("habuma.books", "controller", "hello").increment(); return props.getMessage(); } } <|start_filename|>SpringBoot-Workshop-May-2021/books/src/main/java/books/RandomInfoContributor.java<|end_filename|> package books; import org.springframework.boot.actuate.info.InfoContributor; import org.springframework.boot.actuate.info.Info.Builder; import org.springframework.stereotype.Component; @Component public class RandomInfoContributor implements InfoContributor { @Override public void contribute(Builder builder) { builder.withDetail("randomValue", Math.random()); } } <|start_filename|>VIRTUAL-Jul-2021/spring-integration/trip-source/src/main/java/habuma/TripSender.java<|end_filename|> package habuma; import org.springframework.integration.annotation.Gateway; import org.springframework.integration.annotation.MessagingGateway; import org.springframework.scheduling.annotation.Async; @MessagingGateway public interface TripSender { @Gateway(requestChannel = "tripChannel") TripBooking sendTrip(TripBooking trip); } <|start_filename|>uberconf-2021/boot-workshop/uber-books-reactive/src/main/java/habuma/HelloController.java<|end_filename|> package habuma; import java.time.Duration; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; @RestController public class HelloController { @GetMapping("/hello") public Mono<String> hello() { return Mono.just("Hello world!"); } @GetMapping("/count") public Flux<Long> counter() { return Flux.interval(Duration.ofSeconds(1)); } } <|start_filename|>IAD-Apr-2019/spring-boot/src/main/java/habuma/books/HelloController.java<|end_filename|> package habuma.books; import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import io.micrometer.core.instrument.MeterRegistry; import lombok.RequiredArgsConstructor; @RestController @RequiredArgsConstructor public class HelloController { private final GreetingProps props; private final MeterRegistry reg; @GetMapping("/hello") public String hello() { reg.counter("demo.hello", "one", "two").increment(); return props.getMessage(); } } <|start_filename|>ArchConf-2020/event-driven-spring/rabbit-solutions-logger/src/main/java/com/example/demo/RabbitFunApplication.java<|end_filename|> package com.example.demo; import java.util.Optional; import org.springframework.amqp.core.Message; import org.springframework.amqp.rabbit.annotation.RabbitListener; import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.ApplicationRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.messaging.handler.annotation.MessageMapping; import org.springframework.messaging.handler.annotation.Payload; import lombok.extern.slf4j.Slf4j; @SpringBootApplication @Slf4j public class RabbitFunApplication { public static void main(String[] args) { SpringApplication.run(RabbitFunApplication.class, args); } @Bean public ApplicationRunner appRunner() { return args -> { while(true) { Optional<Solution> optionalEquation = receiveSolution(); optionalEquation.ifPresent(solution -> { log.info("SOLUTION: " + solution); }); } }; } @Autowired private RabbitTemplate rabbit; public Optional<Solution> receiveSolution() { Solution solution = (Solution) rabbit.receiveAndConvert("solutions", -1); return Optional.ofNullable(solution); } } <|start_filename|>BOS-Sept-2021/reactive-books/src/main/java/habuma/SecurityConfig.java<|end_filename|> package habuma; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpMethod; import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity; import org.springframework.security.config.web.server.ServerHttpSecurity; import org.springframework.security.core.userdetails.MapReactiveUserDetailsService; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.server.SecurityWebFilterChain; @Configuration @EnableWebFluxSecurity public class SecurityConfig { @Bean public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) { return http .authorizeExchange() .pathMatchers(HttpMethod.POST, "/books") .authenticated().anyExchange() .permitAll() .and().httpBasic() .and().csrf().disable() // WARNING! .build(); } @Bean public MapReactiveUserDetailsService userDetailsService(PasswordEncoder encoder) { UserDetails user = User .withUsername("habuma") .password(encoder.encode("password")) .authorities("ROLE_USER") .build(); return new MapReactiveUserDetailsService(user); } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } } <|start_filename|>MSN-Feb-2020/testing-books/src/test/java/habuma/BookControllerTests.java<|end_filename|> package habuma; import static org.mockito.Mockito.never; import static org.mockito.Mockito.only; import static org.mockito.Mockito.verify; import static org.springframework.http.MediaType.APPLICATION_JSON; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import java.nio.charset.Charset; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.core.io.Resource; import org.springframework.security.test.context.support.WithAnonymousUser; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.web.servlet.MockMvc; import org.springframework.util.StreamUtils; @WebMvcTest(controllers = BookController.class) public class BookControllerTests { @Autowired MockMvc mockMvc; @Value("classpath:/testbook.json") Resource bookResource; @MockBean BookRepository mockRepo; @Test @WithMockUser(username="admin", password="password", roles={"USER", "ADMIN"}) public void testSavesABook() throws Exception { Book bookToSave = new Book("1234567890", "Test Book", "Test Author"); Book savedBook = new Book("1234567890", "Test Book", "Test Author"); savedBook.setId(100L); Mockito.when(mockRepo.save(bookToSave)) .thenReturn(savedBook); mockMvc.perform(post("/books") .contentType(APPLICATION_JSON) .content(resourceToJsonString(bookResource))) .andExpect(status().isCreated()) .andExpect(jsonPath("id").value(100L)) .andExpect(jsonPath("isbn").value("1234567890")) .andExpect(jsonPath("title").value("Test Book")) .andExpect(jsonPath("author").value("Test Author")); verify(mockRepo,only()).save(bookToSave); } @Test @WithMockUser(username="admin", password="password", roles={"USER"}) public void testSavesABook_notadmin() throws Exception { Book bookToSave = new Book("1234567890", "Test Book", "Test Author"); Book savedBook = new Book("1234567890", "Test Book", "Test Author"); savedBook.setId(100L); Mockito.when(mockRepo.save(bookToSave)) .thenReturn(savedBook); mockMvc.perform(post("/books") .contentType(APPLICATION_JSON) .content(resourceToJsonString(bookResource))) .andExpect(status().isForbidden()); verify(mockRepo,never()).save(bookToSave); } @Test @WithAnonymousUser public void testSavesABook_notauthenticated() throws Exception { Book bookToSave = new Book("1234567890", "Test Book", "Test Author"); Book savedBook = new Book("1234567890", "Test Book", "Test Author"); savedBook.setId(100L); Mockito.when(mockRepo.save(bookToSave)) .thenReturn(savedBook); mockMvc.perform(post("/books") .contentType(APPLICATION_JSON) .content(resourceToJsonString(bookResource))) .andExpect(status().isUnauthorized()); verify(mockRepo,never()).save(bookToSave); } private String resourceToJsonString(Resource resource) throws Exception{ return StreamUtils.copyToString( resource.getInputStream(), Charset.defaultCharset()); } } <|start_filename|>IAD-Apr-2019/spring-data-rest/src/main/java/habuma/DontDeleteEventListener.java<|end_filename|> package habuma; import org.springframework.data.rest.core.event.AbstractRepositoryEventListener; import org.springframework.stereotype.Component; import lombok.extern.slf4j.Slf4j; @Slf4j @Component public class DontDeleteEventListener extends AbstractRepositoryEventListener<Book> { @Override protected void onBeforeDelete(Book book) { log.info("ABOUT TO DELETE: " + book); if (book.getAuthor().getLastName().equals("Walls")) { throw new DontDeleteCraigsBooksException(); } } @Override protected void onAfterDelete(Book book) { log.info("JUST DELETED: " + book); } } <|start_filename|>STL-Apr-2018/src/main/java/habuma/BookController.java<|end_filename|> package habuma; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import lombok.RequiredArgsConstructor; @RestController @RequestMapping("/skoob") @RequiredArgsConstructor public class BookController { private final BookRepository repo; @GetMapping public Iterable<SimpleBook> books() { return repo.findSimpleBooksByFirstName("Kendall"); } } <|start_filename|>VIRTUAL-Oct-2020/nfjs-books/src/main/java/habuma/HelloController.java<|end_filename|> package habuma; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; @Controller public class HelloController { @GetMapping("/hello") public String hello(Model model) { model.addAttribute("who", "NFJS"); return "hello-view"; } } <|start_filename|>CMH-June-2019/books-cmh/src/main/java/habuma/RandomInfoContributor.java<|end_filename|> package habuma; import org.springframework.boot.actuate.info.Info.Builder; import org.springframework.boot.actuate.info.InfoContributor; import org.springframework.stereotype.Component; @Component public class RandomInfoContributor implements InfoContributor { @Override public void contribute(Builder builder) { builder .withDetail("random-number", Math.random()) .withDetail("some-book", new Book("1234567890", "Knitting with Dog Hair", "Kendall", "Crolius")); } } <|start_filename|>MSN-Feb-2020/testing-books/src/main/java/habuma/BookController.java<|end_filename|> package habuma; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; @RestController @RequestMapping("/books") @RequiredArgsConstructor @Slf4j public class BookController { private final BookRepository bookRepo; @GetMapping public Iterable<Book> allBooks() { return bookRepo.findAll(); } @PostMapping @ResponseStatus(HttpStatus.CREATED) public Book saveABook(@RequestBody Book book) { return bookRepo.save(book); } @GetMapping(params = "author") public Iterable<Book> byAuthor(@RequestParam("author") String author) { return bookRepo.findByAuthor(author); } } <|start_filename|>VIRTUAL-Jan-2021/gateway/streamer/src/main/java/com/example/demo/StreamingController.java<|end_filename|> package com.example.demo; import java.time.Duration; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import reactor.core.publisher.Flux; @RestController public class StreamingController { @GetMapping(path="/stream", produces = MediaType.APPLICATION_NDJSON_VALUE) public Flux<CountEntry> stream(@RequestParam(name="count", defaultValue = "10") Integer count) { return Flux.interval(Duration.ofSeconds(1)) .map(l -> new CountEntry(l)) .take(count); } } <|start_filename|>ArchConf-2020/event-driven-spring/stream-equation-solver/src/main/java/com/example/demo/StreamSourceFunApplication.java<|end_filename|> package com.example.demo; import java.util.function.Function; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.messaging.Message; import org.springframework.messaging.MessageHeaders; @SpringBootApplication public class StreamSourceFunApplication { public static void main(String[] args) { SpringApplication.run(StreamSourceFunApplication.class, args); } @Bean public Function<Message<Equation>, Solution> solve(QuadraticSolver solver) { return equation -> { MessageHeaders headers = equation.getHeaders(); System.out.println("HEADERS: " + headers); return solver.solve(equation.getPayload()); }; } } <|start_filename|>SEA-Nov-2019/sea-books/src/main/java/com/example/demo/HelloWorldController.java<|end_filename|> package com.example.demo; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import lombok.RequiredArgsConstructor; @RestController @RequiredArgsConstructor public class HelloWorldController { private final GreetingProps props; @GetMapping("/hello") public String hello() { return props.getMessage(); } } <|start_filename|>STL-Apr-2018/src/main/java/habuma/SecurityConfig.java<|end_filename|> package habuma; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.crypto.password.NoOpPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; @Configuration @EnableGlobalMethodSecurity(prePostEnabled=true) public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private ProfileRepository profileRepo; @Override protected void configure(HttpSecurity http) throws Exception { http .formLogin() .loginPage("/login") .and() .authorizeRequests() .antMatchers("/login").permitAll() .antMatchers("/ui/profiles/**").access("hasRole('ROLE_USER')") .antMatchers("/**").permitAll() ; } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth .userDetailsService( username -> { return profileRepo.findByUsername(username); }); } @Bean public PasswordEncoder passwordEncoder() { return NoOpPasswordEncoder.getInstance(); } } <|start_filename|>MSN-Feb-2020/reactive-tacos/src/main/java/habuma/TacoRepository.java<|end_filename|> package habuma; import org.springframework.data.r2dbc.repository.Query; import org.springframework.data.repository.reactive.ReactiveCrudRepository; import reactor.core.publisher.Flux; public interface TacoRepository extends ReactiveCrudRepository<Taco, Long> { @Query("select id, name, wrap, filling from Taco where wrap=:wrap") Flux<Taco> findByWrap(String wrap); } <|start_filename|>VIRTUAL-Oct-2020/weather-service/src/main/java/habuma/WeatherController.java<|end_filename|> package habuma; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/weather") @ConfigurationProperties(prefix="weather") public class WeatherController { private String current; @GetMapping("/current") public String currentConditions() { return current; } @GetMapping("/slow") public String slow() throws Exception { Thread.sleep(10000); return "SLOW"; } public String getCurrent() { return current; } public void setCurrent(String current) { this.current = current; } } <|start_filename|>STL-Apr-2019/spring-boot/books/src/main/java/habuma/books/ScheduledThings.java<|end_filename|> package habuma.books; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; @Component public class ScheduledThings { @Scheduled(fixedRate=5000) public void doSomething() { System.out.println(System.currentTimeMillis()); } } <|start_filename|>ORD-Oct-2019/books-ord/src/main/java/com/example/demo/BooksController.java<|end_filename|> package com.example.demo; import java.util.Optional; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import lombok.RequiredArgsConstructor; @RestController @RequestMapping("/mvc/books") @RequiredArgsConstructor public class BooksController { private final BooksRepository repo; @GetMapping public Iterable<Book> allBooks() { return repo.findAll(); } @GetMapping("/{id}") public Optional<Book> byId(@PathVariable("id") Long id) { return repo.findById(id); } @PostMapping public Book saveBook(@RequestBody Book book) { return repo.save(book); } @GetMapping("/kendalls") public Iterable<Book> kendallsBooks() { return repo.findByAuthorFirstName("Kendall"); } @GetMapping("/kendalls/simple") public Iterable<SimplePublication> kendallsSimpleBooks() { return repo.findSimpleByAuthorFirstName("Kendall"); } } <|start_filename|>IAD-Nov-2019/iad-books/src/main/java/habuma/IadBooksApplication.java<|end_filename|> package habuma; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; @SpringBootApplication public class IadBooksApplication { public static void main(String[] args) { SpringApplication.run(IadBooksApplication.class, args); } @Bean public Thing thing() { Thing thing = new Thing(); thing.setOtherThing(otherThing()); return thing; } @Bean public Thing otherThing() { return new Thing(); } @Bean public CommandLineRunner dataLoader(BooksRepository repo, AuthorRepository aRepo) { return args -> { Author kendall = aRepo.save(new Author("Kendall", "Crolius")); Author kaori = aRepo.save(new Author("Kaori", "Tsutaya")); repo.save(new Book("0312152906", "Knitting with Dog Hair: Better a sweater from a dog you know and love than from a sheep you'll never meet", kendall)); repo.save(new Book("1594745250", "Crafting with Cat Hair", kaori)); }; } } <|start_filename|>uberconf-2021/spring-containers/hello-k8s/src/main/java/com/example/demo/HelloK8sApplication.java<|end_filename|> package com.example.demo; import org.springframework.boot.ApplicationRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.availability.AvailabilityChangeEvent; import org.springframework.boot.availability.LivenessState; import org.springframework.boot.availability.ReadinessState; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; @SpringBootApplication public class HelloK8sApplication { public static void main(String[] args) { SpringApplication.run(HelloK8sApplication.class, args); } @Bean public ApplicationRunner delayer(ApplicationContext ctx) { return args -> { AvailabilityChangeEvent.publish( ctx, ReadinessState.REFUSING_TRAFFIC); Thread.sleep(30000); AvailabilityChangeEvent.publish( ctx, ReadinessState.ACCEPTING_TRAFFIC); }; } } <|start_filename|>MSN-Feb-2020/testing-books/src/test/java/habuma/BookWebTests.java<|end_filename|> package habuma; import static org.assertj.core.api.Assertions.assertThat; import java.net.URI; import java.nio.charset.Charset; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.core.io.Resource; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.RequestEntity; import org.springframework.http.ResponseEntity; import org.springframework.util.StreamUtils; @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) public class BookWebTests { @Autowired TestRestTemplate rest; @Autowired BookRepository bookRepo; @Value("classpath:/testbook.json") Resource bookJsonResource; @Test public void saveABook() throws Exception { String bookJson = resourceToJsonString(bookJsonResource); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); headers.setBasicAuth("mickey", "password"); RequestEntity<String> requestEntity = new RequestEntity<String>( bookJson, headers, HttpMethod.POST, URI.create("/books")); ResponseEntity<Book> responseEntity = rest.exchange(requestEntity, Book.class); assertThat(responseEntity.getStatusCode()).isEqualTo(HttpStatus.CREATED); Book savedBookResponse = responseEntity.getBody(); Long savedBookId = savedBookResponse.getId(); assertThat(savedBookId).isNotNull(); Book fetchedBook = bookRepo.findById(savedBookId).get(); assertThat(fetchedBook).isNotNull(); assertThat(fetchedBook.getIsbn()).isEqualTo("1234567890"); assertThat(fetchedBook.getTitle()).isEqualTo("Test Book"); assertThat(fetchedBook.getAuthor()).isEqualTo("Test Author"); } private String resourceToJsonString(Resource resource) throws Exception{ return StreamUtils.copyToString( resource.getInputStream(), Charset.defaultCharset()); } } <|start_filename|>Boot-Workshop-Jan-2021/books/src/main/java/habuma/RandomInfoContributor.java<|end_filename|> package habuma; import org.springframework.boot.actuate.info.Info.Builder; import org.springframework.boot.actuate.info.InfoContributor; import org.springframework.stereotype.Component; @Component public class RandomInfoContributor implements InfoContributor { @Override public void contribute(Builder builder) { builder .withDetail("random-number", Math.random()) .build(); } } <|start_filename|>SLC-May-2019/slc-books/src/main/java/habuma/books/BooksRepository.java<|end_filename|> package habuma.books; import org.springframework.data.repository.CrudRepository; public interface BooksRepository extends CrudRepository<Book, Long> { } <|start_filename|>SpringBoot-Workshop-Oct-2021/nfjs-books/src/main/java/habuma/GoodbyeController.java<|end_filename|> package habuma; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class GoodbyeController { @GetMapping("/bye") public String bye() { return "Hasta la vista!!!!!!"; } } <|start_filename|>STL-Apr-2018/src/main/java/habuma/BooksUiController.java<|end_filename|> package habuma; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import lombok.RequiredArgsConstructor; @Controller @RequestMapping("/ui/books") @RequiredArgsConstructor public class BooksUiController { private final BookServiceImpl bookService; @GetMapping public String allTheBook(Model model) { model.addAttribute("books", bookService.allBooks()); return "bookList"; } } <|start_filename|>VIRTUAL-Nov-2020/nfjs-books/src/test/java/habuma/FacebookClientTest.java<|end_filename|> package habuma; import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.test.web.client.match.MockRestRequestMatchers.*; import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.autoconfigure.web.client.RestClientTest; import org.springframework.core.io.Resource; import org.springframework.http.HttpMethod; import org.springframework.http.MediaType; import org.springframework.test.web.client.MockRestServiceServer; @RestClientTest(FacebookClient.class) public class FacebookClientTest { @Autowired FacebookClient fb; @Autowired MockRestServiceServer server; @Value("classpath:/habuma/fbme.json") Resource meJson; @BeforeEach public void setup() throws Exception { this.server.expect(method(HttpMethod.GET)) .andExpect(requestTo("https://graph.facebook.com/me")) .andExpect(header("Authorization", "Bearer MOCK_TOKEN")) .andRespond(withSuccess().body(meJson).contentType(MediaType.APPLICATION_JSON)); } @Test public void testGetMe() throws Exception { FacebookProfile me = fb.getMe("MOCK_TOKEN"); assertThat(me.getId()).isEqualTo("fakeId01234"); assertThat(me.getName()).isEqualTo("Test User"); } } <|start_filename|>MSN-Feb-2020/tacotalk/src/main/java/habuma/Taco.java<|end_filename|> package habuma; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; import lombok.Data; import lombok.RequiredArgsConstructor; @Data @RequiredArgsConstructor @Document public class Taco { @Id private String id; private final String name; private final String wrap; private final String filling; } <|start_filename|>MSP-Mar-2020/tacos/src/main/resources/static/styles.css<|end_filename|> body { font-family: sans-serif; color: blue; background-color: aliceblue; } <|start_filename|>BOS-Sept-2021/nfjs-books/src/main/java/habuma/HelloController.java<|end_filename|> package habuma; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class HelloController { private final GreetingProps props; public HelloController(GreetingProps props) { this.props = props; } @GetMapping(path="/hello") public String hello() { return props.getMessage(); } } <|start_filename|>STL-Apr-2018/src/main/java/habuma/ProfileRepositoryExtras.java<|end_filename|> package habuma; public interface ProfileRepositoryExtras { void doSomethingStupid(); } <|start_filename|>BOS-Sept-2019/books-bos/src/main/java/habuma/RandomEndpoint.java<|end_filename|> package habuma; import org.springframework.boot.actuate.endpoint.annotation.Endpoint; import org.springframework.boot.actuate.endpoint.annotation.ReadOperation; import org.springframework.stereotype.Component; @Component @Endpoint(id = "random", enableByDefault = true) public class RandomEndpoint { @ReadOperation public String random() { return "RANDOM VALUE: " + Math.random(); } } <|start_filename|>uberconf-2019/voice-apps-workshop/hello-uber-conf-gactions/functions/index.js<|end_filename|> const {actionssdk} = require ('actions-on-google'); const functions = require('firebase-functions'); const app = actionssdk({debug: true}); // // Create and Deploy Your First Cloud Functions // // https://firebase.google.com/docs/functions/write-firebase-functions // // exports.helloWorld = functions.https.onRequest((request, response) => { // response.send("Hello from Firebase!"); // }); app.intent('actions.intent.MAIN', (conv) => { conv.ask('Welcome to Uber Conf. You can say hi.'); }); app.intent('com.habuma.hello.HITHERE', (conv) => { conv.close('Hi there!'); }); exports.uberConf = functions.https.onRequest(app); <|start_filename|>STL-Apr-2018/src/main/java/habuma/HelloController.java<|end_filename|> package habuma; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import lombok.RequiredArgsConstructor; @RestController @RequiredArgsConstructor public class HelloController { private final GreetingProperties props; @GetMapping("/hello") public String hello() { return "Hello " + props.getMessage(); } } <|start_filename|>ORD-Nov-2018/ord-books/src/main/java/habuma/BookRepositoryImpl.java<|end_filename|> package habuma; public class BookRepositoryImpl implements BookRepoExtras { public void doSomethingCompletelyDifferent() { System.out.println("**********************"); System.out.println("**********************"); System.out.println("**********************"); System.out.println("**********************"); System.out.println("DOING SOMETHING DIFFERENT"); System.out.println("**********************"); System.out.println("**********************"); System.out.println("**********************"); System.out.println("**********************"); } } <|start_filename|>MSP-Mar-2020/testing-books/src/test/java/habuma/tacos/BookControllerTests.java<|end_filename|> package habuma.tacos; import static org.mockito.Mockito.only; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.io.IOException; import java.nio.charset.Charset; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.core.io.Resource; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import org.springframework.util.StreamUtils; @WebMvcTest(controllers = BookController.class) public class BookControllerTests { @Autowired MockMvc mockMvc; @MockBean BookRepository mockRepo; @Value("classpath:/book.json") private Resource bookJson; @BeforeEach public void setupMocks() throws Exception { Book savedBook = new Book("1234567890", "Test Book", "Test Author"); savedBook.setId(100L); when(mockRepo.save(new Book("1234567890", "Test Book", "Test Author"))) .thenReturn(savedBook); } @Test @WithMockUser(username = "testuser", password = "password", roles = {"ADMIN", "USER"}) public void testSaveABook() throws Exception { mockMvc.perform(MockMvcRequestBuilders.post("/books") .contentType(MediaType.APPLICATION_JSON) .content(getBookJsonAsString())) .andExpect(MockMvcResultMatchers.status().isCreated()) .andExpect(MockMvcResultMatchers.jsonPath("isbn").value("1234567890")) .andExpect(MockMvcResultMatchers.jsonPath("title").value("Test Book")) .andExpect(MockMvcResultMatchers.jsonPath("author").value("Test Author")); verify(mockRepo, only()).save(new Book("1234567890", "Test Book", "Test Author")); } private String getBookJsonAsString() throws IOException { return StreamUtils.copyToString(bookJson.getInputStream(), Charset.defaultCharset()); } } <|start_filename|>STL-Apr-2018/src/main/java/habuma/ProfileRepository.java<|end_filename|> package habuma; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; import org.springframework.data.repository.query.QueryByExampleExecutor; public interface ProfileRepository extends CrudRepository<Profile, Long>, ProfileRepositoryExtras, QueryByExampleExecutor<Profile> { Iterable<Profile> findByPassword(String password); Iterable<Profile> findByPasswordAndEnabled(String pwd, boolean e); Profile findByUsername(String u); int countByPassword(String p); @Query("from Profile p where p.username='venkat'") Profile findVenkatsProfile(); } <|start_filename|>MSN-Feb-2020/tacotalk/src/main/java/habuma/TacoController.java<|end_filename|> package habuma; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; @Controller @RequestMapping("/tacos") @RequiredArgsConstructor @Slf4j public class TacoController { private final TacoRepository tacoRepo; @GetMapping public String allTacos(Model model) { model.addAttribute("tacos", tacoRepo.findAll()); return "tacolist"; } @GetMapping("/form") public String tacoForm() { return "tacoform"; } @PostMapping public String saveATaco(Taco taco) { log.info("TACO: " + taco); tacoRepo.save(taco); return "redirect:/tacos"; } } <|start_filename|>BOS-Sept-2018-2/src/main/java/habuma/BookRepositoryImpl.java<|end_filename|> package habuma; public class BookRepositoryImpl implements BookRepoExtras { @Override public void doSomethingDifferent() { System.out.println("*******************"); System.out.println("*******************"); System.out.println("*******************"); System.out.println("*******************"); System.out.println("DOING SOMETHING DIFFERENT"); System.out.println("*******************"); System.out.println("*******************"); System.out.println("*******************"); System.out.println("*******************"); } } <|start_filename|>ArchConf-2020/event-driven-spring/rabbit-equation-solver/src/main/java/com/example/demo/RabbitFunApplication.java<|end_filename|> package com.example.demo; import java.util.Optional; import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.ApplicationRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; @SpringBootApplication public class RabbitFunApplication { public static void main(String[] args) { SpringApplication.run(RabbitFunApplication.class, args); } @Bean public ApplicationRunner appRunner(QuadraticSolver solver) { return args -> { while(true) { Optional<Equation> optionalEquation = receiveEquation(); optionalEquation.ifPresent(equation -> { Solution solution = solver.solve(equation); sendSolution(solution); }); } }; } @Autowired private RabbitTemplate rabbit; public Optional<Equation> receiveEquation() { Equation equation = (Equation) rabbit.receiveAndConvert("equations", -1); return Optional.ofNullable(equation); } public void sendSolution(Solution solution) { rabbit.convertAndSend("solutions", solution); } } <|start_filename|>VIRTUAL-Jan-2021/gateway/hello-service/src/main/java/com/example/demo/HelloController.java<|end_filename|> package com.example.demo; import java.util.Iterator; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.context.request.WebRequest; @RestController public class HelloController { @GetMapping("/hello") public String hello(WebRequest request) { Iterator<String> headerNames = request.getHeaderNames(); System.out.println("REQUEST HEADERS: "); while(headerNames.hasNext()) { String headerName = headerNames.next(); System.out.println(" ----> " + headerName + " = " + request.getHeader(headerName)); } return "Hello world!"; } @GetMapping("/goodbye") public String bye() { return "Bye bye!"; } } <|start_filename|>uberconf-2019/spring-boot/uber-books/src/main/java/habuma/HelloController.java<|end_filename|> package habuma; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import io.micrometer.core.instrument.MeterRegistry; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; @Controller @RequiredArgsConstructor @Slf4j public class HelloController { private final MessageProps props; private final MeterRegistry registry; @GetMapping("/hello") public String hello(Model model) { registry.counter("uberconf", "hello", "world").increment(); log.debug("SAYING HELLO"); model.addAttribute("who", props.getWho()); return "hello-view"; } } <|start_filename|>VIRTUAL-Sept-2020/reactive-books/src/main/java/habuma/BooksController.java<|end_filename|> package habuma; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import lombok.RequiredArgsConstructor; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; @RestController @RequestMapping("/books") @RequiredArgsConstructor public class BooksController { private final BookRepository bookRepo; @GetMapping public Flux<Book> allBooks() { return bookRepo.findAll(); } @PostMapping public Mono<Book> saveABook(@RequestBody Mono<Book> book) { return book .doOnNext(b -> { bookRepo.save(b).subscribe(); }); } } <|start_filename|>uberconf-2020/rsocket-client/src/main/java/habuma/RsocketClientApplication.java<|end_filename|> package habuma; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.messaging.rsocket.RSocketRequester; @SpringBootApplication public class RsocketClientApplication { public static void main(String[] args) { SpringApplication.run(RsocketClientApplication.class, args); } @Bean public CommandLineRunner clr(RSocketRequester.Builder requesterBuilder) { return args -> { RSocketRequester requester = requesterBuilder .connectTcp("localhost", 7000) .block(); requester .route("book") .data(new Book("1234567890", "Hi there", "Bob")) .retrieveFlux(String.class) .subscribe(response -> { System.out.println(response); }); }; } } <|start_filename|>IAD-Nov-2018/iad-profiles/src/main/java/habuma/WebConfig.java<|end_filename|> package habuma; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class WebConfig implements WebMvcConfigurer { @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addRedirectViewController("/", "/profiles/me"); registry.addViewController("/login").setViewName("loginPage"); } } <|start_filename|>AUS-July-2018/src/main/java/habuma/HelloController.java<|end_filename|> package habuma; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; @RestController @RequestMapping("/hello") @RequiredArgsConstructor @Slf4j public class HelloController { private final GreetingProps props; @GetMapping public String hello() { log.debug("HELLO FROM THE HELLO CONTROLLER"); return props.getMessage(); } } <|start_filename|>BOS-Sept-2021/container-test/src/test/java/habuma/books/MyContainerTest.java<|end_filename|> package habuma.books; import static org.assertj.core.api.Assertions.assertThat; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.client.RestTemplate; import org.testcontainers.containers.GenericContainer; import org.testcontainers.containers.output.Slf4jLogConsumer; import org.testcontainers.junit.jupiter.Container; public class MyContainerTest { private static final Logger log = LoggerFactory.getLogger(MyContainerTest.class); private static final String HELLO_IMAGE = "habuma/hello-k8s"; @Container private final GenericContainer<?> topLevelContainer = new GenericContainer<>(HELLO_IMAGE) .withExposedPorts(8080) .withLogConsumer(new Slf4jLogConsumer(log)); @BeforeEach public void setup() throws Exception { topLevelContainer.start(); } @Test public void dummy() { Integer firstMappedPort = topLevelContainer.getFirstMappedPort(); RestTemplate rest = new RestTemplate(); String response = rest.getForObject( "http://localhost:{port}/hello", String.class, firstMappedPort); assertThat(response).isEqualTo("Hello!"); } } <|start_filename|>SEA-Oct-2018/sea-profiles/src/main/java/habuma/ProfileRepository.java<|end_filename|> package habuma; import org.springframework.data.repository.CrudRepository; public interface ProfileRepository extends CrudRepository<Profile, Long> { Profile findByUsername(String username); } <|start_filename|>CMH-June-2019/books-cmh/src/main/java/habuma/ColumbusEndpoint.java<|end_filename|> package habuma; import org.springframework.boot.actuate.endpoint.annotation.Endpoint; import org.springframework.boot.actuate.endpoint.annotation.ReadOperation; import org.springframework.boot.actuate.endpoint.annotation.WriteOperation; import org.springframework.stereotype.Component; @Component @Endpoint(id = "columbus", enableByDefault = true) public class ColumbusEndpoint { @ReadOperation public String read() { return "Hello, Columbus!"; } @WriteOperation public String write(String who) { return "Hello, " + who + "!"; } } <|start_filename|>uberconf-2020/uber-books/src/main/java/habuma/CustomEndpoint.java<|end_filename|> package habuma; import org.springframework.boot.actuate.endpoint.annotation.Endpoint; import org.springframework.boot.actuate.endpoint.annotation.ReadOperation; import org.springframework.stereotype.Component; import lombok.Data; @Component @Endpoint(id = "custom") public class CustomEndpoint { @ReadOperation public CustomThing customThing() { return new CustomThing("hello", System.currentTimeMillis()); } @Data public static class CustomThing { private final String message; private final Long timestamp; } } <|start_filename|>PWX-2020/google-actions/favorite-things/webhooks/ActionsOnGoogleFulfillment/index.js<|end_filename|> const { conversation, Card, Image } = require('@assistant/conversation'); const functions = require('firebase-functions'); const app = conversation(); app.handle('favoriteColorEvent', conv => { // Implement your code here console.log("LOGGING THE CONV: ", conv); const favoriteColor = conv.scene.slots.favoriteColor.value; const favoritePet = conv.scene.slots.favoritePet.value; console.log("LOGGING A FAVORITE COLOR: " + favoriteColor); conv.overwrite = true; conv.add(`A ${favoriteColor} ${favoritePet}! Imagine that!`); conv.add(new Card({ title: 'Favorite Color', subtitle: 'The world is a carousel of colors...', text: `Your favorite color is ${favoriteColor}`, image: new Image({ url: 'https://cdn4.iconfinder.com/data/icons/drawing-and-painting-tool-cartoon-style/512/al448_4-512.png', alt: 'colors' }) })); }); app.handle('WhatIsAPetIntentHandler', conv => { conv.add('A pet is a beloved animal that you treat as a close friend or a member of your family.'); }); exports.ActionsOnGoogleFulfillment = functions.https.onRequest(app); <|start_filename|>uberconf-2019/spring-boot/uber-books/src/main/java/habuma/MessageProps.java<|end_filename|> package habuma; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Configuration; import lombok.Data; @Configuration @Data @ConfigurationProperties(prefix="message") public class MessageProps { private String who; } <|start_filename|>MSP-Mar-2019/boot-demo/src/main/resources/static/styles.css<|end_filename|> body { color: yellow; background-color: red; font-family: cursive; } <|start_filename|>IAD-Apr-2019/spring-boot/src/main/java/habuma/books/BooksRepository.java<|end_filename|> package habuma.books; public interface BooksRepository { Iterable<Book> findAll(); Book save(Book b); } <|start_filename|>VIRTUAL-Jul-2021/solver-integration/logger/src/main/java/com/example/demo/Solution.java<|end_filename|> package com.example.demo; import java.io.Serializable; import lombok.ToString; @ToString public class Solution implements Serializable { private static final long serialVersionUID = 1L; private double x1; private double x2; public Solution() {} public Solution(double x1, double x2) { this.x1 = x1; this.x2 = x2; } public double getX1() { return x1; } public void setX1(double x1) { this.x1 = x1; } public double getX2() { return x2; } public void setX2(double x2) { this.x2 = x2; } public static long getSerialversionuid() { return serialVersionUID; } } <|start_filename|>uberconf-2019/spring-boot/uber-books/src/main/java/habuma/UberBooksApplication.java<|end_filename|> package habuma; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.scheduling.annotation.EnableScheduling; @SpringBootApplication @EnableScheduling public class UberBooksApplication { public static void main(String[] args) { SpringApplication.run(UberBooksApplication.class, args); } @Bean public CommandLineRunner dataLoader(BookRepository repo) { return args -> { repo.save(new Book("1234567890", "Knitting with Dog Hair", "Kendall", "Crolius")); repo.save(new Book("9876543210", "Crafting with Cat Hair", "Kaori", "Tsutaya")); repo.save(new Book("1029384857", "Spring in Action, Fifth Edition", "Craig", "Walls")); repo.save(new Book("9876543210", "Spring Boot in Action", "Craig", "Walls")); }; } } <|start_filename|>VIRTUAL-Nov-2020/nfjs-books/src/main/java/habuma/BookController.java<|end_filename|> package habuma; import java.util.Optional; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import io.micrometer.core.instrument.MeterRegistry; import lombok.RequiredArgsConstructor; @RestController @RequestMapping("/books") @RequiredArgsConstructor public class BookController { private final BookRepository repo; private final MeterRegistry meter; @GetMapping public Iterable<Book> allBooks() { meter.counter("nfjs", "requests", "books", "foo", "bar").increment(); return repo.findAll(); } @GetMapping("/{id}") public Optional<Book> bookById(@PathVariable("id") Long id) { return repo.findById(id); } @GetMapping("/isbn/{isbn}") public Book bookByIsbn(@PathVariable("isbn") String isbn) { return repo.findByIsbn(isbn); } @PostMapping public Book save(@RequestBody Book book) { return repo.save(book); } @Scheduled(fixedDelay = 5000) public void doSomethingEverySoOften() { System.out.println("PING"); } } <|start_filename|>uberconf-2019/voice-apps-workshop/starflyer-travel/lambda/custom/index.js<|end_filename|> /* eslint-disable func-names */ /* eslint-disable no-console */ const Alexa = require('ask-sdk-core'); const request = require('request'); const {DynamoDbPersistenceAdapter} = require ('ask-sdk-dynamodb-persistence-adapter'); const persistenceAdapter = new DynamoDbPersistenceAdapter( { tableName: 'RememberWhereIWent', createTable: true } ); const PERMISSIONS = ['alexa::profile:given_name:read', 'alexa::profile:email:read']; const LaunchRequestHandler = { canHandle(handlerInput) { return handlerInput.requestEnvelope.request.type === 'LaunchRequest'; }, async handle(handlerInput) { const { requestEnvelope, serviceClientFactory, responseBuilder} = handlerInput; try { const client = serviceClientFactory.getUpsServiceClient(); const email = await client.getProfileEmail(); const givenName = await client.getProfileGivenName(); console.log("GOT PROFILE DATA : ", email, givenName); } catch (error) { if (error.name === 'ServiceError' && error.statusCode == 403) { return responseBuilder .speak("Please grant me permission to access your email address and name in the Amazon Alexa app.") .withAskForPermissionsConsentCard(PERMISSIONS) .getResponse(); } throw error; } const speechText = 'Welcome to StarFlyer Travel. Where do you want to go?'; return responseBuilder .speak(speechText) .reprompt(speechText) .withSimpleCard('Hello World', speechText) .addDirective({ type: 'Alexa.Presentation.APL.RenderDocument', version: '1.0', document: require('stoplight.json'), datasources: { "welcomeData": { "welcomeText": speechText } } }) .getResponse(); }, }; const HelloWorldIntentHandler = { canHandle(handlerInput) { return handlerInput.requestEnvelope.request.type === 'IntentRequest' && handlerInput.requestEnvelope.request.intent.name === 'HelloWorldIntent'; }, handle(handlerInput) { const speechText = 'Hello traveler!'; console.log('Saying hello...'); console.log(handlerInput); return handlerInput.responseBuilder .speak(speechText) .withSimpleCard('StarFlyer Travel', speechText) .getResponse(); }, }; const ScheduleTripIntentHandler = { canHandle(handlerInput) { const request = handlerInput.requestEnvelope.request; return request.type === 'IntentRequest' && request.intent.name === 'ScheduleTripIntent' && (request.dialogState === 'COMPLETED'); }, async handle(handlerInput) { const { requestEnvelope, serviceClientFactory, responseBuilder} = handlerInput; try { const client = serviceClientFactory.getUpsServiceClient(); const email = await client.getProfileEmail(); const givenName = await client.getProfileGivenName(); console.log("GOT PROFILE DATA : ", email, givenName); const allSlots = handlerInput.requestEnvelope.request.intent.slots; // const destination = allSlots['destination'].value; const destination = allSlots['destination'] .resolutions.resolutionsPerAuthority[0].values[0].value.name; handlerInput.attributesManager.getPersistentAttributes() .then((attributes) => { if (attributes.previousDestination.destination) { console.log("I remember that your previous destination was " + attributes.previousDestination.destination); } attributes.previousDestination = { 'destination': destination }; handlerInput.attributesManager.setPersistentAttributes(attributes); handlerInput.attributesManager.savePersistentAttributes(); console.log("I'll remember that your destination is " + destination); }); const departureDate = allSlots['departureDate'].value; const returnDate = allSlots['returnDate'].value; var accessToken = handlerInput.requestEnvelope.context.System.user.accessToken; if (accessToken == undefined) { const speechText = "You must have a skill that is connected to your Google Calendar account. " + "Please use Alexa app to link your Alexa account to Google."; return responseBuilder .speak(speechText) .withLinkAccountCard() .getResponse(); } const summary = `Trip to ${destination}`; const description = `Trip to ${destination} leaving ${departureDate} and returning ${returnDate}. Pack your bags.` await addToGoogleCalendar(accessToken, summary, description, departureDate, returnDate); const speechText = `Enjoy your trip to ${destination}, ${givenName}! Thanks for using StarFlyer Travel.`; return handlerInput.responseBuilder .speak(speechText) .withSimpleCard('StarFlyer Travel', speechText) .withShouldEndSession(true) .getResponse(); } catch (error) { if (error.name === 'ServiceError' && error.statusCode == 403) { return responseBuilder .speak("Please grant me permission to access your email address and name in the Amazon Alexa app.") .withAskForPermissionsConsentCard(PERMISSIONS) .getResponse(); } throw error; } }, }; function addToGoogleCalendar(token, summary, description, departureDate, returnDate) { return new Promise((resolve, reject) => { const payload = { summary: summary, description: description, "end": { date: returnDate }, start: { date: departureDate } }; request( { method: 'POST', uri: 'https://www.googleapis.com/calendar/v3/calendars/primary/events', headers: { 'Accept': 'application/json', 'Content-type': 'application/json', 'Authorization': 'Bearer ' + token }, body: JSON.stringify(payload) }, function (err, res, body) { return resolve(JSON.parse(body)); } ); }); } const ScheduleTripIntentHandler_InProgress = { canHandle(handlerInput) { const request = handlerInput.requestEnvelope.request; return request.type === 'IntentRequest' && request.intent.name === 'ScheduleTripIntent' && (request.dialogState === 'STARTED' || request.dialogState === 'IN_PROGRESS'); }, handle(handlerInput) { const currentIntent = handlerInput.requestEnvelope.request.intent; const allSlots = currentIntent.slots; const departureString = allSlots['departureDate'].value; const returnString = allSlots['returnDate'].value; if (departureString && returnString) { const departureDate = new Date(departureString); const returnDate = new Date(returnString); if (departureDate >= returnDate) { currentIntent.slots['returnDate'].value = null; return handlerInput.responseBuilder .speak("StarFlyer Travel specializes in space travel, \ not time travel. Please specify a return date that is \ after the departure date.") .addDelegateDirective(currentIntent) .getResponse(); } } return handlerInput.responseBuilder .addDelegateDirective(currentIntent) .getResponse(); }, }; const HelpIntentHandler = { canHandle(handlerInput) { return handlerInput.requestEnvelope.request.type === 'IntentRequest' && handlerInput.requestEnvelope.request.intent.name === 'AMAZON.HelpIntent'; }, handle(handlerInput) { const speechText = 'You can say hello to me!'; return handlerInput.responseBuilder .speak(speechText) .reprompt(speechText) .withSimpleCard('Hello World', speechText) .getResponse(); }, }; const CancelAndStopIntentHandler = { canHandle(handlerInput) { return handlerInput.requestEnvelope.request.type === 'IntentRequest' && (handlerInput.requestEnvelope.request.intent.name === 'AMAZON.CancelIntent' || handlerInput.requestEnvelope.request.intent.name === 'AMAZON.StopIntent'); }, handle(handlerInput) { const speechText = 'Goodbye!'; return handlerInput.responseBuilder .speak(speechText) .withSimpleCard('Hello World', speechText) .getResponse(); }, }; const SessionEndedRequestHandler = { canHandle(handlerInput) { return handlerInput.requestEnvelope.request.type === 'SessionEndedRequest'; }, handle(handlerInput) { console.log(`Session ended with reason: ${handlerInput.requestEnvelope.request.reason}`); return handlerInput.responseBuilder.getResponse(); }, }; const ErrorHandler = { canHandle() { return true; }, handle(handlerInput, error) { console.log(`Error handled: ${error.message}`); return handlerInput.responseBuilder .speak('Sorry, I can\'t understand the command. Please say again.') .reprompt('Sorry, I can\'t understand the command. Please say again.') .getResponse(); }, }; const skillBuilder = Alexa.SkillBuilders.custom(); exports.handler = skillBuilder .addRequestHandlers( LaunchRequestHandler, HelloWorldIntentHandler, ScheduleTripIntentHandler, ScheduleTripIntentHandler_InProgress, HelpIntentHandler, CancelAndStopIntentHandler, SessionEndedRequestHandler ) .withApiClient(new Alexa.DefaultApiClient()) .withPersistenceAdapter(persistenceAdapter) .addErrorHandlers(ErrorHandler) .lambda(); <|start_filename|>uberconf-2019/spring-boot/uber-books/src/main/java/habuma/UberConfEndpoint.java<|end_filename|> package habuma; import org.springframework.boot.actuate.endpoint.annotation.Endpoint; import org.springframework.boot.actuate.endpoint.annotation.ReadOperation; import org.springframework.boot.actuate.endpoint.annotation.WriteOperation; import org.springframework.stereotype.Component; @Component @Endpoint(id="uberconf", enableByDefault = true) public class UberConfEndpoint { private Book book = new Book("1234567890", "Crafting with Cat Hair", "Kaori", "Tsutaya");; @ReadOperation public Book getABook() { return book; } @WriteOperation public Book setBook(Book book) { this.book = book; return book; } } <|start_filename|>CMH-June-2019/books-cmh/src/main/java/habuma/DataConfig.java<|end_filename|> package habuma; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.rest.core.config.RepositoryRestConfiguration; import org.springframework.data.rest.webmvc.config.RepositoryRestConfigurer; import org.springframework.data.rest.webmvc.config.RepositoryRestConfigurerAdapter; @Configuration public class DataConfig { @Bean public RepositoryRestConfigurer sdrConfig() { return new RepositoryRestConfigurer() { @Override public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) { config .withEntityLookup() .forRepository( BooksRepository.class, Book::getIsbn, BooksRepository::findByIsbn ); } }; } } <|start_filename|>MSN-Feb-2020/tacotalk/src/main/java/habuma/TacotalkApplication.java<|end_filename|> package habuma; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; @SpringBootApplication public class TacotalkApplication { public static void main(String[] args) { SpringApplication.run(TacotalkApplication.class, args); } @Bean public CommandLineRunner dataLoader(TacoRepository tacoRepo) { return args -> { tacoRepo.save(new Taco("Trailer Park", "Flour", "Fried Chicken")); tacoRepo.save(new Taco("Democrat", "Corn", "Barbacoa")); }; } } <|start_filename|>STL-Apr-2018/src/main/java/habuma/RepoEventListener.java<|end_filename|> package habuma; import org.springframework.data.rest.core.event.AbstractRepositoryEventListener; import org.springframework.stereotype.Component; @Component public class RepoEventListener extends AbstractRepositoryEventListener<Book> { @Override protected void onBeforeDelete(Book entity) { System.out.println("ABOUT TO DELETE: " + entity.getTitle()); if (entity.getTitle().toLowerCase().contains("camel")) { throw new ILikeCamelsException(); } } } <|start_filename|>SEA-Oct-2018/sea-books/src/main/java/habuma/HelloController.java<|end_filename|> package habuma; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import io.micrometer.core.instrument.MeterRegistry; @RestController public class HelloController { private MeterRegistry mr; public HelloController(MeterRegistry mr) { this.mr = mr; } @GetMapping("/hello") public String hello() { mr.counter("hello.world", "hello", "count") .increment(); return "Hello Redmond!!!!!!!!"; } } <|start_filename|>EventDrivenSpring-Workshop-Dec-2020/stream/logger/src/main/java/com/example/demo/LoggerApplication.java<|end_filename|> package com.example.demo; import java.util.function.Consumer; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import lombok.extern.slf4j.Slf4j; @SpringBootApplication @Slf4j public class LoggerApplication { public static void main(String[] args) { SpringApplication.run(LoggerApplication.class, args); } @Bean public Consumer<Solution> logSolution() { return solution -> { log.info("CLOUD STREAM LOGGER GOT A SOLUTION: " + solution); }; } } <|start_filename|>uberconf-2020/uber-books/src/main/java/habuma/RandomNumberInfoContributor.java<|end_filename|> package habuma; import org.springframework.boot.actuate.info.InfoContributor; import org.springframework.boot.actuate.info.Info.Builder; import org.springframework.stereotype.Component; @Component public class RandomNumberInfoContributor implements InfoContributor { @Override public void contribute(Builder builder) { builder .withDetail("random", Math.random()) .withDetail("timestamp", System.currentTimeMillis()); } } <|start_filename|>IAD-Apr-2019/spring-boot/src/main/java/habuma/books/JdbcBooksRepository.java<|end_filename|> package habuma.books; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Repository; import lombok.RequiredArgsConstructor; @Repository @RequiredArgsConstructor public class JdbcBooksRepository implements BooksRepository { private final JdbcTemplate jdbc; @Override public Iterable<Book> findAll() { return jdbc.query("select id, isbn, title, author from Books", (rs, rownum) -> { return new Book( rs.getLong("id"), rs.getString("isbn"), rs.getString("title"), rs.getString("author") ); }); } @Override public Book save(Book b) { jdbc.update("insert into Books (id, isbn, title, author) values (?,?,?,?)", b.getId(), b.getIsbn(), b.getTitle(), b.getAuthor() ); return b; } } <|start_filename|>MSN-Feb-2020/reactive-tacos/src/main/java/habuma/TacoController.java<|end_filename|> package habuma; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; @RestController @RequiredArgsConstructor @RequestMapping("/tacos") @Slf4j public class TacoController { private final TacoRepository repo; @GetMapping public Flux<Taco> tacos() { return repo.findAll(); } @GetMapping(params="wrap") public Flux<Taco> tacosByWrap(@RequestParam("wrap") String wrap) { return repo.findByWrap(wrap); } @PostMapping public Mono<Taco> saveTaco(@RequestBody Mono<Taco> tacoMono) { log.info("BEFORE"); Mono<Taco> response = tacoMono .doOnNext(t -> log.info("TACO: " + t)) .flatMap(taco -> { log.info("DURING"); return repo.save(taco); }) .doOnNext(t -> log.info("TACO (AFTER): " + t)) ; log.info("AFTER"); return response; } } <|start_filename|>MSP-Mar-2020/reactive-tacos/src/main/java/habuma/tacos/ReactiveTacosApplication.java<|end_filename|> package habuma.tacos; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.data.mongodb.core.CollectionOptions; import org.springframework.data.mongodb.core.MongoOperations; import lombok.extern.slf4j.Slf4j; @SpringBootApplication @Slf4j public class ReactiveTacosApplication { public static void main(String[] args) { SpringApplication.run(ReactiveTacosApplication.class, args); } @Bean public CommandLineRunner dataLoader(TacoRepository repo, MongoOperations mongoOps) { return args -> { CollectionOptions options = CollectionOptions.empty().capped().size(50); mongoOps.createCollection("taco", options); repo.save(new Taco("Democrat", "Corn Tortilla", "Barbacoa")).subscribe(System.out::println); repo.save(new Taco("Trailer Park", "Flour Tortilla", "Fried Chicken")).subscribe(System.out::println); repo.save(new Taco("Tipsy Chick", "Flour Tortilla", "Bourbon glazed chicken")).subscribe(System.out::println); }; } } <|start_filename|>K8s-Workshop-Nov-2020/hello-service/src/main/java/habuma/GreetingProps.java<|end_filename|> package habuma; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.cloud.context.config.annotation.RefreshScope; import org.springframework.stereotype.Component; @Component @ConfigurationProperties(prefix="greeting") @RefreshScope public class GreetingProps { private String message; public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } } <|start_filename|>BOS-Sept-2021/reactive-books/src/main/java/habuma/BookRepository.java<|end_filename|> package habuma; import org.springframework.data.repository.reactive.ReactiveCrudRepository; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; public interface BookRepository extends ReactiveCrudRepository<Book, String>{ Mono<Book> findByIsbn(String isbn); Flux<Book> findByAuthor(String author); } <|start_filename|>VIRTUAL-Jan-2021/event-driven/equation-emitter/src/main/java/com/example/demo/EmitterProps.java<|end_filename|> package com.example.demo; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; @Component @ConfigurationProperties(prefix="emitter") public class EmitterProps { private String queueName; public String getQueueName() { return queueName; } public void setQueueName(String queueName) { this.queueName = queueName; } } <|start_filename|>DFW-June-2019/lowercase-function/src/main/java/com/example/demo/Lowercase.java<|end_filename|> package com.example.demo; import java.util.function.Function; public class Lowercase implements Function<String, String> { @Override public String apply(String t) { return t.toLowerCase(); } } <|start_filename|>DSM-Aug-2019/boot-sessions/dsm-books/src/main/java/habuma/HelloController.java<|end_filename|> package habuma; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import io.micrometer.core.instrument.MeterRegistry; import lombok.RequiredArgsConstructor; @Controller @RequiredArgsConstructor public class HelloController { private final GreetingProps props; private final MeterRegistry registry; @GetMapping("/hello") public String hello(Model model) { registry.counter("dsm-books", "hello", props.getWho()) .increment(); model.addAttribute("who", props.getWho()); return "hello-view"; } @GetMapping("/hello/{who}") public String hello(@PathVariable("who") String who, Model model) { registry.counter("dsm-books", "hello", who) .increment(); model.addAttribute("who", who); return "hello-view"; } } <|start_filename|>uberconf-2020/uber-books/src/main/java/habuma/FacebookClient.java<|end_filename|> package habuma; import java.net.URI; import org.springframework.boot.web.client.RestTemplateBuilder; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.RequestEntity; import org.springframework.stereotype.Component; import org.springframework.web.client.RestTemplate; @Component public class FacebookClient { private RestTemplate rest; public FacebookClient(RestTemplateBuilder rtBuilder) { this.rest = rtBuilder.build(); } public String getProfile() { HttpHeaders headers = new HttpHeaders(); headers.setBearerAuth("MOCK_TOKEN"); RequestEntity<Void> requestEntity = new RequestEntity<Void>(headers, HttpMethod.GET, URI.create("https://graph.facebook.com/me")); return rest.exchange(requestEntity, String.class).getBody(); } public RestTemplate getRestTemplate() { return rest; } } <|start_filename|>MSP-Mar-2019/boot-demo/src/main/java/habuma/RandomHealthIndicator.java<|end_filename|> package habuma; import org.springframework.boot.actuate.health.Health; import org.springframework.boot.actuate.health.HealthIndicator; import org.springframework.stereotype.Component; @Component public class RandomHealthIndicator implements HealthIndicator{ @Override public Health health() { double value = Math.random(); if (value > 0.5) { return Health .up() .withDetail("value", "The value is " + value) .build(); } else if (value > 0.3) { return Health.unknown() .withDetail("value", "The value is unknown") .build(); } else if (value > 0.2) { return Health.outOfService() .withDetail("value", "The value is out of service: " + value) .withDetail("time", System.currentTimeMillis()) .build(); } return Health.down() .withDetail("reason", "The value is really low: " + value) .build(); } } <|start_filename|>MSP-Oct-2019/boot-sessions/books-msp/src/main/java/habuma/HelloController.java<|end_filename|> package habuma; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; @RestController @RequiredArgsConstructor @Slf4j public class HelloController { private final GreetingProps props; @GetMapping("/hello") public String hello() { log.debug("WARNING: SAYING HELLO"); return props.getMessage(); } } <|start_filename|>IAD-Apr-2019/spring-data-rest/src/main/java/habuma/BookRepository.java<|end_filename|> package habuma; import org.springframework.data.repository.CrudRepository; import org.springframework.data.rest.core.annotation.RepositoryRestResource; import org.springframework.data.rest.core.annotation.RestResource; @RepositoryRestResource(excerptProjection = SimpleBook.class) public interface BookRepository extends CrudRepository<Book, Long> { Book findByIsbn(String isbn); SimpleBook findSimpleByIsbn(String isbn); @Override // @RestResource(exported = false) void deleteById(Long id); @Override // @RestResource(exported = false) void delete(Book entity); } <|start_filename|>VIRTUAL-Sept-2020/nfjs-books/src/main/java/habuma/RandomInfoContributor.java<|end_filename|> package habuma; import org.springframework.boot.actuate.info.InfoContributor; import org.springframework.stereotype.Component; import org.springframework.boot.actuate.info.Info.Builder; @Component public class RandomInfoContributor implements InfoContributor { @Override public void contribute(Builder builder) { double random = Math.random(); builder .withDetail("random", random); } } <|start_filename|>VIRTUAL-Sept-2020/nfjs-books/src/main/java/habuma/MyScheduledBean.java<|end_filename|> package habuma; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; @Component public class MyScheduledBean { @Scheduled(fixedDelay = 5000) public void doSomething() { System.out.println("DOING SOMETHING"); } } <|start_filename|>uberconf-2020/rsocket-client/src/main/java/habuma/Book.java<|end_filename|> package habuma; import lombok.Data; import lombok.NoArgsConstructor; import lombok.RequiredArgsConstructor; @Data @NoArgsConstructor(force=true) @RequiredArgsConstructor public class Book { private Long id; private final String isbn; private final String title; private final String author; } <|start_filename|>IAD-Apr-2019/spring-boot/src/main/java/habuma/books/IadBooksApplication.java<|end_filename|> package habuma.books; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class IadBooksApplication { public static void main(String[] args) { System.setProperty("spring.main.lazy-initialization", "true"); System.setProperty("spring.jmx.enabled", "false"); SpringApplication.run(IadBooksApplication.class, args); } } <|start_filename|>VIRTUAL-Sept-2020/weather-service/src/main/java/habuma/WeatherController.java<|end_filename|> package habuma; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/weather") public class WeatherController { @GetMapping public String weather() { return "Cloudy and cool"; } @GetMapping("/slow") public String slow() throws Exception { Thread.sleep(10000); return "SLOW"; } } <|start_filename|>uberconf-2021/spring-data/uber-book-jpa/src/main/java/com/example/demo/BookRepository.java<|end_filename|> package com.example.demo; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; public interface BookRepository extends CrudRepository<Book, Long> { Iterable<Book> findByAuthor(String author); Iterable<SimpleBook> findSimpleByAuthor(String author); @Query("from Book b where b.author='<NAME>'") Iterable<Book> findKendallsBooks(); } <|start_filename|>CMH-June-2019/books-cmh/src/main/java/habuma/HelloController.java<|end_filename|> package habuma; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import lombok.RequiredArgsConstructor; @Controller @RequiredArgsConstructor public class HelloController { private final GreetingProps props; @GetMapping("/hello") public String hello(Model model) { model.addAttribute("where", props.getWhere()); return "hello-view"; } } <|start_filename|>CMH-June-2019/books-cmh/src/main/java/habuma/GreetingProps.java<|end_filename|> package habuma; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; import lombok.Data; @Component @Data @ConfigurationProperties(prefix = "greeting") public class GreetingProps { private String where; } <|start_filename|>VIRTUAL-Oct-2020/nfjs-reactive-books/src/test/java/habuma/ReactiveTest.java<|end_filename|> package habuma; import java.time.Duration; import org.junit.jupiter.api.Test; import reactor.core.publisher.Flux; public class ReactiveTest { // @Test public void testReactiveStuff() throws Exception { Long[] values = new Long[] {1L,2L,3L,4L,5L,6L}; Flux.fromArray(new Long[] {1L,2L,3L,4L,5L,6L,7L,8L,9L,10L}) .doOnNext(n -> System.out.println("NEXT: " + n)) .take(5) .doOnNext(n -> System.out.println("TAKE: " + n)) .map(n -> "NUMBER IS: " + n) .doOnNext(n -> System.out.println("MAPPED: " + n)) .subscribe(); Thread.sleep(10000); } } <|start_filename|>MSN-Feb-2020/testing-books/src/test/java/habuma/TestingBooksApplicationTests.java<|end_filename|> package habuma; import static org.assertj.core.api.Assertions.assertThat; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class TestingBooksApplicationTests { @Autowired Bottle bottle; @Test void contextLoads() { } @Test public void checkBottle() { Rum rum = bottle.getRum(); assertThat(rum.getBrand()).isEqualTo("Bacardi"); } } <|start_filename|>EventDrivenSpring-Workshop-Dec-2020/stream/solver/src/main/java/com/example/demo/SolverApplication.java<|end_filename|> package com.example.demo; import java.util.function.Function; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; @SpringBootApplication public class SolverApplication { private static final Logger logger = LoggerFactory.getLogger(SolverApplication.class); public static void main(String[] args) { SpringApplication.run(SolverApplication.class, args); } @Autowired QuadraticSolver solver; @Bean public Function<Equation, Solution> solve() { return equation -> { return solver.solve(equation); }; } } <|start_filename|>MSP-Oct-2019/boot-sessions/books-msp/src/main/java/habuma/BooksMspApplication.java<|end_filename|> package habuma; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; @SpringBootApplication public class BooksMspApplication { public static void main(String[] args) { SpringApplication.run(BooksMspApplication.class, args); } } <|start_filename|>EventDrivenSpring-Workshop-Aug-2021/si-trip-sink/src/main/java/habuma/SiTripSinkApplication.java<|end_filename|> package habuma; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.amqp.rabbit.connection.ConnectionFactory; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.integration.amqp.inbound.AmqpMessageSource; import org.springframework.integration.dsl.IntegrationFlow; import org.springframework.integration.dsl.IntegrationFlows; import org.springframework.integration.dsl.Pollers; @SpringBootApplication public class SiTripSinkApplication { private static final Logger log = LoggerFactory.getLogger(SiTripSinkApplication.class); public static void main(String[] args) { SpringApplication.run(SiTripSinkApplication.class, args); } @Bean public IntegrationFlow flow(ConnectionFactory cf) { return IntegrationFlows .from(new AmqpMessageSource(cf, "itineraries"), c -> c.poller(Pollers.fixedRate(1000))) .<Itinerary>handle(itinerary -> { log.info("SCHEDULING ITINERARY: " + itinerary); }) .get(); } } <|start_filename|>VIRTUAL-Nov-2020/nfjs-books/src/test/java/habuma/BookCTests.java<|end_filename|> package habuma; import static org.mockito.Mockito.only; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.springframework.http.MediaType.APPLICATION_JSON; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import java.io.IOException; import java.nio.charset.Charset; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.core.io.Resource; import org.springframework.security.test.context.support.WithAnonymousUser; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.web.servlet.MockMvc; import org.springframework.util.StreamUtils; import io.micrometer.core.instrument.MeterRegistry; @WebMvcTest(controllers=BookController.class) public class BookCTests { @Autowired MockMvc mockMvc; @MockBean BookRepository bookRepo; @MockBean MeterRegistry meterRegistry; @Value("classpath:/habuma/book.json") Resource bookJson; @Test @WithMockUser(username = "dummy", password="password", roles={"USER", "ADMIN"}) public void testSavesABook() throws Exception { Book bookToSave = new Book("1234567890", "Test Book", "Test Author"); Book savedBook = new Book("1234567890", "Test Book", "Test Author"); savedBook.setId(1L); Mockito.when(bookRepo.save(bookToSave)) .thenReturn(savedBook); mockMvc.perform(post("/books") .contentType(APPLICATION_JSON) .content(getBookJsonAsString())) .andExpect(status().isOk()) .andExpect(jsonPath("id").value(1L)) .andExpect(jsonPath("isbn").value("1234567890")) .andExpect(jsonPath("title").value("Test Book")) .andExpect(jsonPath("author").value("Test Author")); verify(bookRepo, only()).save(bookToSave); } @Test @WithMockUser(username="username", password="password", roles={"USER"}) public void testSavesABook_UnauthorizedUser() throws Exception { mockMvc.perform(post("/books") .contentType(APPLICATION_JSON) .content(getBookJsonAsString())) .andExpect(status().isForbidden()); verifyNoInteractions(bookRepo); } @Test @WithAnonymousUser public void testSavesABook_AnonymousUser() throws Exception { mockMvc.perform(post("/books") .contentType(APPLICATION_JSON) .content(getBookJsonAsString())) .andExpect(status().isUnauthorized()); verifyNoInteractions(bookRepo); } private String getBookJsonAsString() throws IOException { return StreamUtils.copyToString(bookJson.getInputStream(), Charset.defaultCharset()); } } <|start_filename|>EventDrivenSpring-Workshop-Aug-2021/scs-trip-processor/src/main/java/habuma/ScsTripProcessorApplication.java<|end_filename|> package habuma; import java.util.function.Function; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; @SpringBootApplication public class ScsTripProcessorApplication { private static final Logger log = LoggerFactory.getLogger(ScsTripProcessorApplication.class); public static void main(String[] args) { SpringApplication.run(ScsTripProcessorApplication.class, args); } @Bean public Function<TripBooking, Itinerary> processTrip() { return trip -> { log.info("PROCESSING TRIP. Payment card: " + trip.getPaymentCardNumber()); return trip.getItinerary(); }; } } <|start_filename|>ArchConf-2020/spring-gateway/archconf-gateway/src/main/java/com/example/demo/ArchconfGatewayApplication.java<|end_filename|> package com.example.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver; import org.springframework.cloud.gateway.route.RouteLocator; import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder; import org.springframework.context.annotation.Bean; import reactor.core.publisher.Mono; @SpringBootApplication public class ArchconfGatewayApplication { public static void main(String[] args) { SpringApplication.run(ArchconfGatewayApplication.class, args); } @Bean public KeyResolver userKeyResolver() { return exchange -> Mono.just("habuma"); } // @Bean // public RouteLocator customRouteLocator(RouteLocatorBuilder builder) { // return builder.routes() // .route("start", r-> // r.path("/**") // .filters(f -> f.addRequestHeader("X-ArchConf", "December 2020")) // .uri("http://localhost:8080")) // .build(); // } } <|start_filename|>IAD-Apr-2019/spring-data-rest/src/main/java/habuma/PublisherRepository.java<|end_filename|> package habuma; import org.springframework.data.repository.CrudRepository; public interface PublisherRepository extends CrudRepository<Publisher, Long> { } <|start_filename|>VIRTUAL-Jan-2021/gateway/streamer/src/main/java/com/example/demo/StreamerApplication.java<|end_filename|> package com.example.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class StreamerApplication { public static void main(String[] args) { SpringApplication.run(StreamerApplication.class, args); } } <|start_filename|>VIRTUAL-Sept-2020/reactive-books/src/main/java/habuma/HelloController.java<|end_filename|> package habuma; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import reactor.core.publisher.Mono; @RestController public class HelloController { @GetMapping("/hello") public Mono<String> hello() { //... return Mono.just("Hello Reactive World!!!!!!!!!") .map(text -> text.toUpperCase()); } @PostMapping("/echobook") public Mono<Book> addABook(@RequestBody Mono<Book> book) { return book .map(book2 -> new Book(book2.getIsbn(), book2.getTitle(), book2.getAuthor().toUpperCase())); } } <|start_filename|>MSP-Mar-2020/tacos/src/main/java/habuma/tacos/TacoController.java<|end_filename|> package habuma.tacos; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import lombok.RequiredArgsConstructor; @Controller @RequestMapping("/tacos") @RequiredArgsConstructor public class TacoController { private final TacoRepository tacoRepo; @GetMapping public String tacoList(@RequestParam(name="wrap", required=false) String wrap, Model model) { if (wrap == null) { Iterable<Taco> tacos = tacoRepo.findAll(); model.addAttribute("tacos", tacos); } else { Iterable<Taco> tacos = tacoRepo.findByWrap(wrap); model.addAttribute("tacos", tacos); } return "tacolist"; } } <|start_filename|>uberconf-2021/spring-data/uber-book-mongodb/src/main/java/com/example/demo/BookController.java<|end_filename|> package com.example.demo; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; @RestController @RequestMapping("/books") public class BookController { private final BookRepository repo; public BookController(BookRepository repo) { this.repo = repo; } @GetMapping public Flux<Book> allBooks() { return repo.findAll(); } @GetMapping(params="author") public Flux<Book> byAuthor(@RequestParam("author") String author) { return repo.findByAuthor(author); } @GetMapping("/kendalls") public Flux<Book> kendalls() { return repo.findKendallsBooks(); } @PostMapping public Mono<Book> saveABook(@RequestBody Book book) { return repo.save(book); } } <|start_filename|>VIRTUAL-Nov-2020/nfjs-books/src/test/java/habuma/BookRepositoryTests.java<|end_filename|> package habuma; import static org.assertj.core.api.Assertions.assertThat; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; @DataJpaTest public class BookRepositoryTests { @Autowired BookRepository bookRepo; private Book savedBook; @BeforeEach public void setup() { Book book = new Book("1234567890", "Test Book", "Test Author"); this.savedBook = bookRepo.save(book); } @Test public void testFindByIsbn() { Book foundBook = bookRepo.findByIsbn("1234567890"); assertThat(foundBook.getId()).isNotNull(); assertThat(foundBook.getIsbn()).isEqualTo("1234567890"); assertThat(foundBook.getTitle()).isEqualTo("Test Book"); assertThat(foundBook.getAuthor()).isEqualTo("Test Author"); } } <|start_filename|>EventDrivenSpring-Workshop-Dec-2020/integration/file-reader/src/main/java/com/example/demo/FileReaderApplication.java<|end_filename|> package com.example.demo; import java.io.File; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.amqp.core.AmqpTemplate; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.integration.amqp.dsl.Amqp; import org.springframework.integration.dsl.IntegrationFlow; import org.springframework.integration.dsl.IntegrationFlows; import org.springframework.integration.dsl.Pollers; import org.springframework.integration.dsl.Transformers; import org.springframework.integration.file.dsl.Files; @SpringBootApplication public class FileReaderApplication { private static final Logger log = LoggerFactory.getLogger(FileReaderApplication.class); public static void main(String[] args) { SpringApplication.run(FileReaderApplication.class, args); } @Bean public IntegrationFlow flow(AmqpTemplate amqpTemplate) { return IntegrationFlows .from(Files.inboundAdapter(new File("/Users/habuma/equations")) .patternFilter("*.json"), c -> c.poller(Pollers.fixedRate(1000))) .transform(Transformers.fromJson(Equation.class)) .handle(Amqp.outboundGateway(amqpTemplate).routingKey("equations")) .get(); } } <|start_filename|>VIRTUAL-Nov-2020/nfjs-books/src/main/java/habuma/FacebookClient.java<|end_filename|> package habuma; import java.net.URI; import org.springframework.boot.web.client.RestTemplateBuilder; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.RequestEntity; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import org.springframework.web.client.RestOperations; @Service public class FacebookClient { private RestOperations rest; public FacebookClient(RestTemplateBuilder rtBuilder) { this.rest = rtBuilder.build(); } public FacebookProfile getMe(String accessToken) { HttpHeaders headers = new HttpHeaders(); headers.add("Authorization", "Bearer " + accessToken); RequestEntity<String> requestEntity = new RequestEntity<>( headers, HttpMethod.GET, URI.create("https://graph.facebook.com/me")); ResponseEntity<FacebookProfile> responseEntity = rest.exchange( requestEntity, FacebookProfile.class); return responseEntity.getBody(); } } <|start_filename|>SEA-Oct-2018/sea-profiles/src/main/java/habuma/SeaProfilesApplication.java<|end_filename|> package habuma; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; @SpringBootApplication public class SeaProfilesApplication { public static void main(String[] args) { SpringApplication.run(SeaProfilesApplication.class, args); } @Bean public CommandLineRunner dataLoader(ProfileRepository repo) { return args -> { repo.save(new Profile("habuma", "password", "<PASSWORD>", "<PASSWORD>")); repo.save(new Profile("schutta", "password", "<PASSWORD>", "<PASSWORD>")); repo.save(new Profile("kousen", "password", "<PASSWORD>", <PASSWORD>")); repo.save(new Profile("sletten", "password", "<PASSWORD>", "<PASSWORD>")); repo.save(new Profile("johnson", "password", "<PASSWORD>", "<PASSWORD>")); }; } } <|start_filename|>VIRTUAL-Nov-2020/nfjs-books/src/main/java/habuma/FacebookProfile.java<|end_filename|> package habuma; import lombok.Data; @Data public class FacebookProfile { private String id; private String name; } <|start_filename|>ORD-Oct-2019/books-ord/src/main/java/com/example/demo/SdJdbcApplication.java<|end_filename|> package com.example.demo; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; @SpringBootApplication public class SdJdbcApplication { public static void main(String[] args) { SpringApplication.run(SdJdbcApplication.class, args); } @Bean public CommandLineRunner dataLoader(BooksRepository repo) { return args -> { repo.save(new Book("1234567890", "Knitting with Dog Hair", "Kendall", "Crolius")); repo.save(new Book("9876543210", "Crafting with Cat Hair", "Kaori", "Tsutaya")); repo.save(new Book("1029384756", "Spring in Action, Fifth Edition", "Craig", "Walls")); }; } } <|start_filename|>EventDrivenSpring-Workshop-Aug-2021/scs-trip-sink/src/main/java/habuma/ScsTripSinkApplication.java<|end_filename|> package habuma; import java.util.function.Consumer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; @SpringBootApplication public class ScsTripSinkApplication { private static final Logger log = LoggerFactory.getLogger(ScsTripSinkApplication.class); public static void main(String[] args) { SpringApplication.run(ScsTripSinkApplication.class, args); } @Bean public Consumer<Itinerary> scheduleItinerary() { return itinerary -> { log.info("SCHEDULING ITINERARY: " + itinerary); }; } } <|start_filename|>MSP-Mar-2020/mini-quest/content/en-GB/resources/Snippets.json<|end_filename|> { "sfx": "<audio src='$SNIPPET_S3_RESOURCES_URI/audio/$1'/>", "pic": "$SNIPPET_S3_RESOURCES_URI/images/$1" } <|start_filename|>SEA-Oct-2018/sea-profiles/src/main/java/habuma/SecurityConfig.java<|end_filename|> package habuma; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.crypto.password.NoOpPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; @Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private ProfileRepository profileRepo; @Override protected void configure(HttpSecurity http) throws Exception { http .formLogin() .loginPage("/signin") .loginProcessingUrl("/signin") .and() .logout() .and() .authorizeRequests() .antMatchers("/profiles/**").access("hasRole('ROLE_USER')") .antMatchers("/**").permitAll() ; } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService( username -> { return profileRepo.findByUsername(username); }); } @Bean public PasswordEncoder passwordEncoder() { return NoOpPasswordEncoder.getInstance(); } } <|start_filename|>STL-Apr-2018/src/main/resources/static/styles.css<|end_filename|> body { color:red; background-color: yellow; } ul { color: blue; } <|start_filename|>ORD-Nov-2018/ord-books/src/main/java/habuma/BookRepository.java<|end_filename|> package habuma; import org.springframework.data.mongodb.repository.Query; import org.springframework.data.repository.CrudRepository; import org.springframework.data.repository.query.Param; public interface BookRepository extends CrudRepository<Book, String>, BookRepoExtras { Book findByIsbn(@Param("abcd") String isbn); SimpleBook findSimpleByIsbn(String isbn); @Query("{'authorFirstName':'Kendall','authorLastName':'Crolius'}") Iterable<Book> findKendallsBooks(); } <|start_filename|>EventDrivenSpring-Workshop-Apr-2021/trip-processor/src/main/java/habuma/TripProcessorApplication.java<|end_filename|> package habuma; import org.springframework.amqp.core.Queue; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; @SpringBootApplication public class TripProcessorApplication { public static void main(String[] args) { SpringApplication.run(TripProcessorApplication.class, args); } @Bean public Queue itineraries() { return new Queue("itineraries", true, false, false); } } <|start_filename|>uberconf-2020/uber-books/src/test/java/habuma/BookRepositoryTest.java<|end_filename|> package habuma; import static org.assertj.core.api.Assertions.assertThat; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; @DataJpaTest public class BookRepositoryTest { @Autowired BookRepository bookRepo; private Book savedBook; @BeforeEach public void saveAnInitialBook() { Book book = new Book("1234567890", "Test Book", "Test Author"); this.savedBook = bookRepo.save(book); } @Test public void testSave() { // assertThat(savedBook.getId()).isEqualTo(1L); assertThat(savedBook.getIsbn()).isEqualTo("1234567890"); assertThat(savedBook.getTitle()).isEqualTo("Test Book"); assertThat(savedBook.getAuthor()).isEqualTo("Test Author"); } @Test public void findBookByIsbn() { Book foundBook = bookRepo.findByIsbn("1234567890"); assertThat(foundBook.getIsbn()).isEqualTo("1234567890"); assertThat(foundBook.getTitle()).isEqualTo("Test Book"); assertThat(foundBook.getAuthor()).isEqualTo("Test Author"); } } <|start_filename|>uberconf-2021/spring-testing/testing-spring-final/src/test/java/habuma/BookRepositoryTests.java<|end_filename|> package habuma; import static org.assertj.core.api.Assertions.assertThat; import java.util.List; import java.util.stream.Collectors; import java.util.stream.StreamSupport; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; @DataJpaTest public class BookRepositoryTests { @Autowired BookRepository repo; @Test public void testSave() { assertThat(repo.count()).isEqualTo(2); Book savedBook = repo.save(new Book("1122334455", "Test Book", "Test Author")); assertThat(savedBook.getId()).isNotNull(); assertThat(repo.count()).isEqualTo(3); } @Test public void testDelete() { assertThat(repo.count()).isEqualTo(2); repo.deleteById(1L); assertThat(repo.count()).isEqualTo(1); } @Test public void testFindByIsbn() { Book book = repo.findByIsbn("1234567890"); assertThat(book.getIsbn()).isEqualTo("1234567890"); assertThat(book.getTitle()).isEqualTo("Knitting with Dog Hair"); assertThat(book.getAuthor()).isEqualTo("<NAME>"); } @Test public void testFindByAuthor() { Iterable<Book> books = repo.findByAuthor("<NAME>"); List<Book> bookList = StreamSupport.stream(books.spliterator(), false) .collect(Collectors.toList()); assertThat(bookList.size()).isEqualTo(1); Book book = bookList.get(0); assertThat(book.getIsbn()).isEqualTo("9876543210"); assertThat(book.getTitle()).isEqualTo("Crafting with Cat Hair"); assertThat(book.getAuthor()).isEqualTo("<NAME>"); } } <|start_filename|>AUS-July-2019/spring-boot-sessions/austin-books/src/main/java/habuma/DummyEndpoint.java<|end_filename|> package habuma; import org.springframework.boot.actuate.endpoint.annotation.Endpoint; import org.springframework.boot.actuate.endpoint.annotation.ReadOperation; import org.springframework.boot.actuate.endpoint.annotation.Selector; import org.springframework.boot.actuate.endpoint.annotation.WriteOperation; import org.springframework.stereotype.Component; @Endpoint(id = "dummy", enableByDefault = true) @Component public class DummyEndpoint { private String newValue = "This is just test info."; @ReadOperation public String dummyInfo() { return newValue; } @WriteOperation(produces = "text/plain") public String changeSomething(@Selector String newValue) { this.newValue = newValue; return newValue; } } <|start_filename|>SEA-Nov-2019/sea-books/src/main/java/com/example/demo/Book.java<|end_filename|> package com.example.demo; import org.springframework.data.annotation.Id; import lombok.Data; @Data public class Book { @Id private Long id; private final String isbn; private final String title; private final String author; } <|start_filename|>MSN-Feb-2020/reactive-books/src/main/java/habuma/BookController.java<|end_filename|> package habuma; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import lombok.RequiredArgsConstructor; import reactor.core.publisher.Flux; @RestController @RequestMapping("/books") @RequiredArgsConstructor public class BookController { private final BookRepository repo; @GetMapping public Flux<Book> books() { return repo.findAll(); } @GetMapping(params="author") public Flux<Book> booksByAuthor(@RequestParam("author") String author) { return repo.findByAuthor(author); } } <|start_filename|>VIRTUAL-Jan-2021/event-driven/rabbit-equation-solver/src/main/java/com/example/demo/QuadraticSolver.java<|end_filename|> package com.example.demo; import org.springframework.stereotype.Service; @Service public class QuadraticSolver { public Solution solve(Equation equation) { double[] solutionPair = this.solve( equation.getCoefficientA(), equation.getCoefficientB(), equation.getCoefficientC()); return new Solution(solutionPair[0], solutionPair[1]); } private double[] solve(double a, double b, double c) { // divide all terms by a to normalize to a = 1 double bn = b / a; double cn = c / a; double avg = (bn/2); double u = Math.sqrt((bn*bn / 4) - cn); double x1 = -avg - u; double x2 = -avg + u; return new double[] {x1, x2}; } } <|start_filename|>SpringBoot-Workshop-Oct-2021/nfjs-books/src/main/java/habuma/HelloController.java<|end_filename|> package habuma; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; @Controller public class HelloController { public HelloController(GreetingProps props) { this.props = props; } private final GreetingProps props; @GetMapping("/hello") public String hello(Model model) { model.addAttribute("who", props.getWho()); return "helloView"; } } <|start_filename|>SpringBoot-Workshop-May-2021/books/src/main/java/books/GoodbyeController.java<|end_filename|> package books; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; @Controller public class GoodbyeController { @GetMapping("/goodbye") public String bye(Model model) { model.addAttribute("who", "World"); return "bye"; } } <|start_filename|>SLC-May-2019/slc-books/src/main/java/habuma/books/RandomHealthIndicator.java<|end_filename|> package habuma.books; import org.springframework.boot.actuate.health.Health; import org.springframework.boot.actuate.health.HealthIndicator; import org.springframework.stereotype.Component; @Component public class RandomHealthIndicator implements HealthIndicator { @Override public Health health() { double value = Math.random(); if (value > 0.5) { return Health.up() .withDetail("reason", "The value is big enough: " + value) .build(); } else if (value > 0.2) { try { throw new RuntimeException("OUCH"); } catch (RuntimeException e) { return Health.down(e).build(); } } return Health.down() .withDetail("reason", "The value is too small: " + value) .build(); } } <|start_filename|>SLC-May-2019/slc-books/src/main/resources/META-INF/additional-spring-configuration-metadata.json<|end_filename|> {"properties": [{ "name": "greeting.message", "type": "java.lang.String", "description": "The thing you want to say hi with." }]} <|start_filename|>IAD-Apr-2019/spring-data-rest/src/main/java/habuma/DontDeleteCraigsBooksException.java<|end_filename|> package habuma; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; @ResponseStatus(code = HttpStatus.METHOD_NOT_ALLOWED) public class DontDeleteCraigsBooksException extends RuntimeException { private static final long serialVersionUID = 1L; } <|start_filename|>VIRTUAL-Jul-2021/spring-integration/trip-source/src/main/java/habuma/RandomTripSource.java<|end_filename|> package habuma; import java.time.Duration; import java.time.Instant; import java.util.Date; import java.util.Random; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.amqp.core.AmqpTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.integration.amqp.dsl.Amqp; import org.springframework.integration.channel.DirectChannel; import org.springframework.integration.dsl.IntegrationFlow; import org.springframework.integration.dsl.IntegrationFlows; import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.Scheduled; import habuma.Itinerary.Destination; @SpringBootApplication @EnableScheduling public class RandomTripSource { private static Logger log = LoggerFactory.getLogger(RandomTripSource.class); private static final String[] TRAVELERS = { "Mickey", "Donald", "Goofy", "Minnie", "Daisy" }; private static final String[] CARD_NUMBERS = { "4417123456789113", "4111111111111111" }; private Random random = new Random(); public static void main(String[] args) throws Exception { SpringApplication.run(RandomTripSource.class, args); } @Autowired TripSender tripSender; @Scheduled(fixedRate = 1000) public void sendTrip() { TripBooking trip = new TripBooking(); trip.setTravelerName(pickItem(TRAVELERS)); trip.setPaymentCardNumber(pickItem(CARD_NUMBERS)); trip.setItinerary(pickItinerary()); log.info("SENDING TRIP: " + trip); TripBooking sent = tripSender.sendTrip(trip); System.out.println("SENT: " + sent); } @Bean public DirectChannel tripChannel() { return new DirectChannel(); } @Bean public IntegrationFlow tripFlow( AmqpTemplate amqpTemplate) { return IntegrationFlows.from(tripChannel()) .handle(Amqp.outboundGateway(amqpTemplate).routingKey("trips")) .get(); } // random data generators private <T> T pickItem(T[] items) { return items[random.nextInt(items.length)]; } private Itinerary pickItinerary() { Destination destination = pickItem(Destination.values()); Instant startDate = Instant.now().plus(Duration.ofDays(random.nextInt(10))); Instant returnDate = startDate.plus(Duration.ofDays(random.nextInt(10))); return new Itinerary(destination, new Date(startDate.toEpochMilli()), new Date(returnDate.toEpochMilli())); } } <|start_filename|>STL-Apr-2018/src/main/java/habuma/ProfileRepositoryImpl.java<|end_filename|> package habuma; public class ProfileRepositoryImpl implements ProfileRepositoryExtras { public void doSomethingStupid() { System.out.println("------------"); System.out.println("------------"); System.out.println("------------"); System.out.println("DOING SOMETHING STUPID"); System.out.println("------------"); System.out.println("------------"); System.out.println("------------"); } } <|start_filename|>EventDrivenSpring-Workshop-Apr-2021/trip-source/src/main/java/habuma/TripSender.java<|end_filename|> package habuma; import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class TripSender { private final RabbitTemplate rabbit; @Autowired public TripSender(RabbitTemplate rabbit) { this.rabbit = rabbit; } public void sendTrip(TripBooking trip) { rabbit.convertAndSend("trips", trip); } } <|start_filename|>IAD-Apr-2019/spring-boot/src/test/java/habuma/books/IadBooksApplicationTests.java<|end_filename|> package habuma.books; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.boot.web.server.LocalServerPort; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest public class IadBooksApplicationTests { @Test public void contextLoads() { } } <|start_filename|>AUS-July-2019/spring-boot-sessions/streaming/src/main/java/habuma/StreamingController.java<|end_filename|> package habuma; import java.time.Duration; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import reactor.core.publisher.Flux; @RestController public class StreamingController { @GetMapping(path="/stream", produces = MediaType.APPLICATION_STREAM_JSON_VALUE) public Flux<Thing> stream() { return Flux.interval(Duration.ofSeconds(1)) .map(l -> new Thing(l, System.currentTimeMillis())); } private final class Thing { Thing(long l, long t) { this.l = l; this.t = t; } private final long l; private final long t; public long getL() { return l; } public long getT() { return t; } } } <|start_filename|>ORD-Nov-2018/ord-profiles/src/main/java/habuma/SecurityConfig.java<|end_filename|> package habuma; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.crypto.password.NoOpPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import lombok.extern.slf4j.Slf4j; @Configuration @Slf4j public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private ProfileRepository userRepo; @Override protected void configure(HttpSecurity http) throws Exception { http .formLogin() .loginPage("/login") .and() .authorizeRequests() .antMatchers("/profiles/**").access("hasRole('ROLE_USER') && isAuthenticated()") .antMatchers("/**").permitAll() ; } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth .userDetailsService( username -> { log.info("LOOKING UP USER: " + username); return userRepo.findByUsername(username); }); } @Bean public PasswordEncoder passwordEncoder() { return NoOpPasswordEncoder.getInstance(); } } <|start_filename|>uberconf-2020/reactive-uber-books/src/main/java/habuma/ReactiveUberBooksApplication.java<|end_filename|> package habuma; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class ReactiveUberBooksApplication { public static void main(String[] args) { SpringApplication.run(ReactiveUberBooksApplication.class, args); } } <|start_filename|>STL-Apr-2018/src/main/java/habuma/SimpleBook.java<|end_filename|> package habuma; import org.springframework.beans.factory.annotation.Value; import org.springframework.data.rest.core.config.Projection; @Projection(name="simple", types={Book.class}) public interface SimpleBook { String getTitle(); @Value("#{target.lastName + ', ' + target.firstName}") String getAuthor(); } <|start_filename|>uberconf-2020/uber-books/src/test/java/habuma/FacebookClientTest.java<|end_filename|> package habuma; import static org.springframework.test.web.client.match.MockRestRequestMatchers.header; import static org.springframework.test.web.client.match.MockRestRequestMatchers.method; import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo; import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.autoconfigure.web.client.RestClientTest; import org.springframework.core.io.Resource; import org.springframework.http.HttpMethod; import org.springframework.http.MediaType; import org.springframework.test.web.client.MockRestServiceServer; @RestClientTest(components = FacebookClient.class) public class FacebookClientTest { // // Post session fix: Fixed by using RestTemplateBuilder in the client // @Autowired FacebookClient fb; @Autowired MockRestServiceServer server; @Value("classpath:/fbme.json") Resource meJson; @BeforeEach public void setup() throws Exception { this.server.expect(method(HttpMethod.GET)) .andExpect(requestTo("https://graph.facebook.com/me")) .andExpect(header("Authorization", "Bearer MOCK_TOKEN")) .andRespond(withSuccess().body(meJson).contentType(MediaType.APPLICATION_JSON)); } @Test public void testGetMe() throws Exception { String me = fb.getProfile(); System.out.println("ME: " + me); } } <|start_filename|>VIRTUAL-Jul-2021/spring-books/src/main/java/books/BooksController.java<|end_filename|> package books; import java.util.Optional; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import lombok.RequiredArgsConstructor; @RestController @RequestMapping("/books") @RequiredArgsConstructor public class BooksController { final BookRepository repo; @GetMapping public Iterable<Book> allBooks() { return repo.findAll(); } @GetMapping("/{id}") public Optional<Book> byId(@PathVariable("id") Long id) { return repo.findById(id); } @PostMapping public Book saveABook(@RequestBody Book book) { return repo.save(book); } } <|start_filename|>IAD-Apr-2019/spring-data-rest/src/main/java/habuma/Author.java<|end_filename|> package habuma; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import lombok.AccessLevel; import lombok.Data; import lombok.NoArgsConstructor; import lombok.RequiredArgsConstructor; @Entity @Data @RequiredArgsConstructor @NoArgsConstructor(access=AccessLevel.PRIVATE, force=true) public class Author { @Id @GeneratedValue(strategy=GenerationType.AUTO) private Long id; private final String firstName; private final String lastName; } <|start_filename|>BOS-Sept-2021/testing-spring-final/src/test/java/habuma/BookControllerMvcTests.java<|end_filename|> package habuma; import static org.mockito.Mockito.when; import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document; import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.documentationConfiguration; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; 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.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.restdocs.RestDocumentationContextProvider; import org.springframework.restdocs.RestDocumentationExtension; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; @WebMvcTest @ExtendWith(RestDocumentationExtension.class) public class BookControllerMvcTests { @Autowired MockMvc mockMvc; @MockBean BookRepository bookRepo; @Autowired private WebApplicationContext context; @BeforeEach public void setUp(RestDocumentationContextProvider restDocumentation) { this.mockMvc = MockMvcBuilders .webAppContextSetup(context) .apply(documentationConfiguration(restDocumentation)) .build(); } @Test public void testGetByIsbn() throws Exception { Book testBook = new Book("1122334455", "Test Book", "Test Author"); testBook.setId(1L); when(bookRepo.findByIsbn("1122334455")).thenReturn(testBook); mockMvc.perform(get("/books/{id}", "1122334455")) .andExpect(jsonPath("id").value(1L)).andExpect(jsonPath("isbn").value("1122334455")) .andExpect(jsonPath("title").value("Test Book")).andExpect(jsonPath("author").value("Test Author")) .andDo(document("sample")); } } <|start_filename|>IAD-Nov-2019/iad-books/src/main/java/habuma/BooksController.java<|end_filename|> package habuma; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; @RestController @RequestMapping("/mvc/books") @RequiredArgsConstructor @Slf4j public class BooksController { private final BooksRepository repo; @GetMapping public Iterable<Book> allBooks() { log.info("GETTING ALL BOOKS"); return repo.findAll(); } @GetMapping("/{isbn}") public Book bookByIsbn(@PathVariable("isbn") String isbn) { return repo.findByIsbn(isbn); } @GetMapping("/{isbn}/simple") public SimplePublication simpleByIsbn(@PathVariable("isbn") String isbn) { return repo.findSimpleByIsbn(isbn); } @PostMapping public Book saveABook(@RequestBody Book book) { return repo.save(book); } } <|start_filename|>uberconf-2021/event-driven-spring/trip-domain/src/main/java/habuma/Itinerary.java<|end_filename|> package habuma; import java.io.Serializable; import java.util.Date; public class Itinerary implements Serializable { private static final long serialVersionUID = 1L; private Destination destination; private Date startDate; private Date returnDate; public static enum Destination { MERCURY, VENUS, MARS, JUPITER, SATURN, URANUS, NEPTUNE, PLUTO } public Itinerary() {} public Itinerary(Destination destination, Date startDate, Date returnDate) { this.destination = destination; this.startDate = startDate; this.returnDate = returnDate; } @Override public String toString() { return "(destination=" + destination + ", startDate=" + startDate + ", returnDate=" + returnDate + ")"; } public Destination getDestination() { return destination; } public void setDestination(Destination destination) { this.destination = destination; } public Date getStartDate() { return startDate; } public void setStartDate(Date startDate) { this.startDate = startDate; } public Date getReturnDate() { return returnDate; } public void setReturnDate(Date returnDate) { this.returnDate = returnDate; } } <|start_filename|>ArchConf-2020/event-driven-spring/integration-equation-solver/src/main/java/com/example/demo/Equation.java<|end_filename|> package com.example.demo; import java.io.Serializable; import lombok.AllArgsConstructor; import lombok.Data; @Data @AllArgsConstructor public class Equation implements Serializable { private static final long serialVersionUID = 1L; private double coefficientA; private double coefficientB; private double coefficientC; } <|start_filename|>MSN-Feb-2020/testing-books/src/test/java/habuma/BookRepoTest.java<|end_filename|> package habuma; import static org.assertj.core.api.Assertions.assertThat; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; @DataJpaTest public class BookRepoTest { @Autowired BookRepository bookRepo; private Book savedBook; @BeforeEach public void setup() { Book book = new Book("1234567890", "Test Book", "Test Author"); this.savedBook = bookRepo.save(book); } @Test public void testSave() { assertThat(savedBook.getIsbn()).isEqualTo("1234567890"); assertThat(savedBook.getTitle()).isEqualTo("Test Book"); assertThat(savedBook.getAuthor()).isEqualTo("Test Author"); } @Test public void findByIsbn() { Book isbnBook = bookRepo.findByIsbn("1234567890"); assertThat(isbnBook.getIsbn()).isEqualTo("1234567890"); assertThat(isbnBook.getTitle()).isEqualTo("Test Book"); assertThat(isbnBook.getAuthor()).isEqualTo("Test Author"); } } <|start_filename|>IAD-Nov-2018/iad-books/src/main/java/com/example/demo/Book.java<|end_filename|> package com.example.demo; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; import lombok.AccessLevel; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.RequiredArgsConstructor; @Data @Document @NoArgsConstructor(force=true, access=AccessLevel.PRIVATE) @AllArgsConstructor public class Book { @Id private String id; private String isbn; private String title; private String authorFirstName; private String authorLastName; } <|start_filename|>MSP-Mar-2020/tacos/src/main/resources/templates/tacolist.html<|end_filename|> <html> <head> <title>Hello Tacos</title> <link rel="stylesheet" th:href="@{/styles.css}"/> </head> <body> <h2>Here are some muy delicioso tacos!</h2> <ul> <li th:each="taco : ${tacos}"> <span th:text="${taco.name}">TACO NAME</span> - <span th:text="${taco.filling}">TACO NAME</span> in a <span th:text="${taco.wrap}">TACO NAME</span> </li> </ul> </body> </html> <|start_filename|>VIRTUAL-Jul-2021/solver-integration/file-reader/src/main/java/com/example/demo/Equation.java<|end_filename|> package com.example.demo; import java.io.Serializable; import lombok.ToString; @ToString public class Equation implements Serializable { private static final long serialVersionUID = 1L; private double coefficientA; private double coefficientB; private double coefficientC; public Equation() {} public Equation( double coefficientA, double coefficientB, double coefficientC) { this.coefficientA = coefficientA; this.coefficientB = coefficientB; this.coefficientC = coefficientC; } public double getCoefficientA() { return coefficientA; } public void setCoefficientA(double coefficientA) { this.coefficientA = coefficientA; } public double getCoefficientB() { return coefficientB; } public void setCoefficientB(double coefficientB) { this.coefficientB = coefficientB; } public double getCoefficientC() { return coefficientC; } public void setCoefficientC(double coefficientC) { this.coefficientC = coefficientC; } } <|start_filename|>ArchConf-2020/event-driven-spring/mdb-equation-solver/src/main/java/com/example/demo/MdbSolverApplication.java<|end_filename|> package com.example.demo; import org.springframework.amqp.rabbit.annotation.RabbitListener; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.messaging.handler.annotation.SendTo; @SpringBootApplication public class MdbSolverApplication { public static void main(String[] args) { SpringApplication.run(MdbSolverApplication.class, args); } @Autowired QuadraticSolver solver; @RabbitListener(queues = "equations") @SendTo("solutions") public Solution handleMessage(Equation equation) { return solver.solve(equation); } } <|start_filename|>DSM-Aug-2019/boot-sessions/dsm-books/src/test/java/habuma/DemoApplicationTests.java<|end_filename|> package habuma; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.web.server.LocalServerPort; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) public class DemoApplicationTests { @LocalServerPort long port; @Test public void contextLoads() { System.out.println("PORT: " + port); } } <|start_filename|>IAD-Apr-2019/spring-data-rest/src/main/java/habuma/Publisher.java<|end_filename|> package habuma; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToOne; import lombok.AccessLevel; import lombok.Data; import lombok.NoArgsConstructor; import lombok.RequiredArgsConstructor; @Entity @Data @RequiredArgsConstructor @NoArgsConstructor(access=AccessLevel.PRIVATE, force=true) public class Publisher { @Id @GeneratedValue(strategy=GenerationType.AUTO) private Long id; private final String name; @ManyToOne(cascade=CascadeType.MERGE) private final Address address; } <|start_filename|>IAD-Apr-2019/spring-data-rest/src/main/java/habuma/Address.java<|end_filename|> package habuma; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import lombok.AccessLevel; import lombok.Data; import lombok.NoArgsConstructor; import lombok.RequiredArgsConstructor; @Entity @Data @RequiredArgsConstructor @NoArgsConstructor(access=AccessLevel.PRIVATE, force=true) public class Address { @Id @GeneratedValue(strategy=GenerationType.AUTO) private Long id; private final String street; private final String city; private final String state; private final String zipCode; } <|start_filename|>uberconf-2020/rsocket-server/src/main/java/habuma/RSocketServer.java<|end_filename|> package habuma; import java.time.Duration; import org.springframework.messaging.handler.annotation.MessageMapping; import org.springframework.stereotype.Controller; import reactor.core.publisher.Flux; @Controller public class RSocketServer { @MessageMapping("book") Flux<String> handler(Book book) { System.out.println("GOT A BOOK! : " + book); return Flux.interval(Duration.ofSeconds(1)) .map(i -> "Count : " + i); } } <|start_filename|>VIRTUAL-Jul-2021/trip-domain/src/main/java/habuma/TripBooking.java<|end_filename|> package habuma; import java.io.Serializable; import lombok.Data; @Data public class TripBooking implements Serializable { private static final long serialVersionUID = 1L; private String travelerName; private String paymentCardNumber; private Itinerary itinerary; } <|start_filename|>VIRTUAL-Jul-2021/message-driven-beans/trip-processor/src/main/java/habuma/TripProcessor.java<|end_filename|> package habuma; import java.util.concurrent.atomic.AtomicInteger; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.amqp.rabbit.annotation.RabbitListener; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.messaging.handler.annotation.SendTo; @SpringBootApplication public class TripProcessor { private static Logger log = LoggerFactory.getLogger(TripProcessor.class); public static void main(String[] args) { System.setProperty("spring.devtools.restart.enabled", "false"); SpringApplication.run(TripProcessor.class, args); } AtomicInteger total = new AtomicInteger(); @RabbitListener(queues = "trips") @SendTo("itineraries") public Itinerary handleMessage(TripBooking trip) { log.info("PROCESSING TRIP. Payment card: " + trip.getPaymentCardNumber()); return trip.getItinerary(); } } <|start_filename|>BOS-Sept-2018-2/src/main/java/habuma/BookRepository.java<|end_filename|> package habuma; import org.springframework.data.mongodb.repository.Query; import org.springframework.data.repository.CrudRepository; public interface BookRepository extends CrudRepository<Book, String>, BookRepoExtras { // from Book b where b.author=? Iterable<Book> findByAuthor(String author); Book findByIsbn(String isbn); @Query("{'author':'<NAME>'}") Iterable<Book> findKendallsBooks(); // findByIsbnAndTitleLikeOrAuthorContainsAndTitleStartingWith(fjdfjfhjkfhdjkfhkj) // Iterable<Book> findByAgeLessThan(int age); // Iterable<Book> findByCopyrightDateLessThan(Date date) // Iterable<Book> findByPublisher_Address_ZipCode(String zc); } <|start_filename|>uberconf-2021/boot-workshop/uber-books/src/main/java/habuma/Book.java<|end_filename|> package habuma; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; @Entity public class Book { @Id @GeneratedValue private Long id; private final String isbn; private final String title; private final String author; private Book() { this(null, null, null); } public Book(String isbn, String title, String author) { this.isbn = isbn; this.title = title; this.author = author; } public void setId(Long id) { this.id = id; } public Long getId() { return id; } public String getIsbn() { return isbn; } public String getTitle() { return title; } public String getAuthor() { return author; } } <|start_filename|>EventDrivenSpring-Workshop-Aug-2021/scs-trip-source/src/main/java/habuma/Itinerary.java<|end_filename|> package habuma; import java.io.Serializable; import java.util.Date; public class Itinerary implements Serializable { private static final long serialVersionUID = 1L; private Destination destination; private Date startDate; private Date endDate; public Destination getDestination() { return destination; } public void setDestination(Destination destination) { this.destination = destination; } public Date getStartDate() { return startDate; } public void setStartDate(Date startDate) { this.startDate = startDate; } public Date getEndDate() { return endDate; } public void setEndDate(Date endDate) { this.endDate = endDate; } public static enum Destination { MERCURY, VENUS, MARS, JUPITER, SATURN, URANUS, NEPTUNE, PLUTO } } <|start_filename|>MSP-Oct-2019/boot-sessions/books-msp/src/main/java/habuma/RandomHealthIndicator.java<|end_filename|> package habuma; import org.springframework.boot.actuate.health.Health; import org.springframework.boot.actuate.health.HealthIndicator; import org.springframework.stereotype.Component; @Component public class RandomHealthIndicator implements HealthIndicator { @Override public Health health() { double value = Math.random(); // increased likelihood of a healthy app to avoid frequent ups and downs in // the admin if (value > 0.1) { // healthy return Health .up() .withDetail("reason", "The value was sufficiently large: " + value) .build(); } // unhealthy return Health .down() .withDetail("reason", "The value was too small: " + value) .build(); } } <|start_filename|>IAD-Apr-2019/spring-boot/src/main/java/habuma/books/Book.java<|end_filename|> package habuma.books; import lombok.Data; import lombok.RequiredArgsConstructor; @Data @RequiredArgsConstructor public class Book { public Book(Long id, String isbn, String title, String author) { this.id = id; this.isbn = isbn; this.title = title; this.author = author; } private Long id; private final String isbn; private final String title; private final String author; } <|start_filename|>VIRTUAL-Jan-2021/gateway/gateway/src/main/java/hello/GatewayApplication.java<|end_filename|> package hello; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver; import org.springframework.cloud.gateway.route.RouteLocator; import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder; import org.springframework.context.annotation.Bean; import reactor.core.publisher.Mono; @SpringBootApplication public class GatewayApplication { public static void main(String[] args) { SpringApplication.run(GatewayApplication.class, args); } @Bean public RouteLocator customRouteLocator(RouteLocatorBuilder builder) { return builder.routes() .route("yahoo", r-> r.path("/oohay") .filters(f -> f.rewritePath(".*", "/")) .uri("https://yahoo.com")) .build(); } @Bean public KeyResolver userKeyResolver() { return exchange -> Mono.just("habuma"); } } <|start_filename|>uberconf-2021/boot-workshop/uber-books-reactive/src/main/java/habuma/BookController.java<|end_filename|> package habuma; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; @RestController @RequestMapping("/books") public class BookController { private final BookRepository repo; public BookController(BookRepository repo) { this.repo = repo; } @GetMapping public Flux<Book> allBooks() { return repo.findAll(); } @PostMapping public Mono<Book> saveBook(@RequestBody Book book) { return repo.save(book); } } <|start_filename|>SpringBoot-Workshop-Oct-2021/nfjs-books/src/main/java/habuma/GreetingProps.java<|end_filename|> package habuma; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; @Component @ConfigurationProperties(prefix="greeting") public class GreetingProps { private String who; public String getWho() { return who; } public void setWho(String who) { this.who = who; } } <|start_filename|>uberconf-2021/alexa-skills/UberTravel-slots/lambda/ScheduleTripIntentHandler.js<|end_filename|> const Alexa = require('ask-sdk-core'); exports.ScheduleTripIntentHandler = { canHandle(handlerInput) { console.log("IN CanHandle()"); return Alexa.getRequestType(handlerInput.requestEnvelope) === 'IntentRequest' && Alexa.getIntentName(handlerInput.requestEnvelope) === 'ScheduleTripIntent'; }, handle(handlerInput) { const destination = getResolvedSlotValue(handlerInput.requestEnvelope, 'destination'); const startDate = Alexa.getSlotValue(handlerInput.requestEnvelope, 'startDate'); const tripLength = Alexa.getSlotValue(handlerInput.requestEnvelope, 'tripLength'); // // TODO: Submit trip details to backend travel system. // const speakOutput = `Enjoy your trip to ${destination}!`; return handlerInput.responseBuilder .speak(speakOutput) //.reprompt('add a reprompt if you want to keep the session open for the user to respond') .getResponse(); } }; const getResolvedSlotValue = (requestEnvelope, slotName) => { const slotResolution = Alexa.getSlot(requestEnvelope, slotName) .resolutions.resolutionsPerAuthority[0]; return slotResolution.status.code === 'ER_SUCCESS_MATCH' ? slotResolution.values[0].value.name : Alexa.getSlotValue(requestEnvelope, slotName); }; <|start_filename|>IAD-Nov-2019/iad-books/src/main/java/habuma/GreetingProps.java<|end_filename|> package habuma; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; import lombok.Data; @Data @Component @ConfigurationProperties(prefix="greeting") public class GreetingProps { private String message = "Hello, world!"; private int random; } <|start_filename|>uberconf-2020/reactive-uber-books/src/test/java/habuma/ReactiveTests.java<|end_filename|> package habuma; import java.time.Duration; import org.junit.jupiter.api.Test; import reactor.core.publisher.Flux; public class ReactiveTests { @Test public void testFlux() throws Exception { Flux.interval(Duration.ofSeconds(1)) .take(5) .filter(n -> (n%2 == 0)) .map(n -> "COUNTER: " + n) .doOnNext(d -> { System.out.println(d); }) .log() .subscribe(); Thread.sleep(10000); } } <|start_filename|>VIRTUAL-Jan-2021/boot/books/src/main/java/books/HelloController.java<|end_filename|> package books; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import lombok.RequiredArgsConstructor; @Controller @RequiredArgsConstructor public class HelloController { private final GreetingProps props; @GetMapping("/hello") public String hello(Model model) { model.addAttribute("message", "THE MESSAGE IS: " + props.getMessage()); return "hello-view"; } } <|start_filename|>AUS-July-2019/spring-boot-sessions/austin-books/src/main/java/habuma/BooksRepository.java<|end_filename|> package habuma; import org.springframework.data.mongodb.repository.Query; import org.springframework.data.repository.CrudRepository; public interface BooksRepository extends CrudRepository<Book, String> { Book findByIsbn(String isbn); SimpleBook findSimpleByIsbn(String isbn); @Query("{'authorFirstName':'Kendall'}") Iterable<Book> findKendallsBooks(); } <|start_filename|>IAD-Nov-2019/iad-books/src/main/resources/META-INF/additional-spring-configuration-metadata.json<|end_filename|> {"properties": [{ "name": "greeting.message", "type": "java.lang.String", "description": "The thing you wish to say to someone when you see them." }]} <|start_filename|>EventDrivenSpring-Workshop-Apr-2021/trip-source/src/main/java/habuma/TripSourceApplication.java<|end_filename|> package habuma; import java.util.Date; import org.springframework.amqp.core.Queue; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.Scheduled; import habuma.Itinerary.Destination; @SpringBootApplication @EnableScheduling public class TripSourceApplication { public static void main(String[] args) { SpringApplication.run(TripSourceApplication.class, args); } @Bean public Queue trips() { return new Queue("trips", true, false, false); } @Autowired TripSender tripSender; @Scheduled(fixedRate=5000) public void sendTrip() { TripBooking trip = new TripBooking(); Itinerary itinerary = new Itinerary(); itinerary.setDestination(Destination.JUPITER); itinerary.setStartDate(new Date()); itinerary.setEndDate(new Date()); trip.setItinerary(itinerary); trip.setTravelerName("<NAME>"); trip.setPaymentCardNumber("4111111111111111"); tripSender.sendTrip(trip); } } <|start_filename|>EventDrivenSpring-Workshop-Dec-2020/mdbs/solver/src/main/java/com/example/demo/SolverApplication.java<|end_filename|> package com.example.demo; import java.util.Optional; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.amqp.rabbit.annotation.RabbitListener; import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.ApplicationRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.messaging.handler.annotation.SendTo; @SpringBootApplication public class SolverApplication { private static final Logger logger = LoggerFactory.getLogger(SolverApplication.class); public static void main(String[] args) { SpringApplication.run(SolverApplication.class, args); } @Autowired QuadraticSolver solver; @RabbitListener(queues = "equations") @SendTo("solutions") public Solution handleMessage(Equation equation) { return solver.solve(equation); } } <|start_filename|>Boot-Workshop-Jan-2021/books/src/main/java/habuma/RandomEndpoint.java<|end_filename|> package habuma; import org.springframework.boot.actuate.endpoint.annotation.Endpoint; import org.springframework.boot.actuate.endpoint.annotation.ReadOperation; import org.springframework.boot.actuate.endpoint.annotation.WriteOperation; import org.springframework.stereotype.Component; @Component @Endpoint(id = "random", enableByDefault = true) public class RandomEndpoint { @ReadOperation public String hello() { return "Hello from the endpoint"; } } <|start_filename|>VIRTUAL-Oct-2020/nfjs-reactive-books/src/main/java/habuma/HelloController.java<|end_filename|> package habuma; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import reactor.core.publisher.Mono; @RestController public class HelloController { @GetMapping("/hello") public Mono<String> hello() { //... return Mono.just("Hello") .map(s -> s.toUpperCase()) .map(s -> s.toLowerCase()); } } <|start_filename|>DSM-Aug-2019/boot-sessions/dsm-books/src/main/resources/META-INF/additional-spring-configuration-metadata.json<|end_filename|> {"properties": [{ "name": "greeting.who", "type": "java.lang.String", "description": "The entity you wish to greet." }]} <|start_filename|>uberconf-2021/spring-testing/testing-spring-final/src/test/java/habuma/BookControllerWebTests.java<|end_filename|> package habuma; import static org.assertj.core.api.Assertions.assertThat; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.test.web.client.TestRestTemplate; @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) public class BookControllerWebTests { @Autowired TestRestTemplate rest; @Test public void testGet() { Book[] books = rest.getForObject("/books", Book[].class); assertThat(books.length).isEqualTo(2); } @Test public void testGetByIsbn() { Book book = rest.getForObject("/books/{isbn}", Book.class, "1234567890"); assertThat(book.getId()).isEqualTo(1L); assertThat(book.getIsbn()).isEqualTo("1234567890"); assertThat(book.getTitle()).isEqualTo("Knitting with Dog Hair"); assertThat(book.getAuthor()).isEqualTo("<NAME>"); } @Test public void testSave() { Book bookToSave = new Book("1122334455", "Test Book", "Test Author"); Book savedBook = rest.postForObject("/books", bookToSave, Book.class); assertThat(savedBook).isNotNull(); assertThat(savedBook.getId()).isNotNull(); } } <|start_filename|>VIRTUAL-Nov-2020/nfjs-books/src/main/java/habuma/HelloController.java<|end_filename|> package habuma; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import io.micrometer.core.instrument.MeterRegistry; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; @Controller @RequiredArgsConstructor @Slf4j public class HelloController { private final GreetingProps props; private final MeterRegistry meter; @GetMapping("/hello") public String hello(Model model) { meter.counter("nfjs", "requests", "hello").increment(); log.debug("HELLO CONTROLLER INVOKED"); model.addAttribute("who", "You fools"); model.addAttribute("message", props.getMessage()); return "hello-view"; } } <|start_filename|>ORD-Nov-2018/ord-books/src/main/java/habuma/JdbcBookRepository.java<|end_filename|> package habuma; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Repository; import lombok.RequiredArgsConstructor; @Repository @RequiredArgsConstructor public class JdbcBookRepository implements BookRepository { private final JdbcTemplate jdbc; @Override public Iterable<Book> findAll() { return jdbc.query("select isbn, title, author from Books order by isbn", (rs, rowNum) -> { String isbn = rs.getString("isbn"); String title = rs.getString("title"); String author = rs.getString("author"); return new Book(isbn, title, author); }); } @Override public Book save(Book b) { return null; } } <|start_filename|>Boot-Workshop-Jan-2021/books/src/main/java/habuma/RandomHealthIndicator.java<|end_filename|> package habuma; import org.springframework.boot.actuate.health.Health; import org.springframework.boot.actuate.health.HealthIndicator; import org.springframework.stereotype.Component; @Component public class RandomHealthIndicator implements HealthIndicator { @Override public Health health() { double random = Math.random(); if (random > 0.5) { return Health.up() .withDetail("Reason", "The value was sufficiently large: " + random) .build(); } return Health.down() .withDetail("Reason", "The value was too small: " + random) .build(); } } <|start_filename|>EventDrivenSpring-Workshop-Dec-2020/templates/solver/src/main/java/com/example/demo/SolverApplication.java<|end_filename|> package com.example.demo; import java.util.Optional; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.ApplicationRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; @SpringBootApplication public class SolverApplication { private static final Logger logger = LoggerFactory.getLogger(SolverApplication.class); public static void main(String[] args) { SpringApplication.run(SolverApplication.class, args); } @Autowired RabbitTemplate rabbit; public Optional<Equation> receiveEquation() { Equation equation = (Equation) rabbit.receiveAndConvert("equations", -1); return Optional.of(equation); } public void sendSolution(Solution solution) { rabbit.convertAndSend("solutions", solution); } @Bean public ApplicationRunner appRunner(QuadraticSolver solver) { return args -> { while(true) { Optional<Equation> equation = receiveEquation(); equation.ifPresent(eq -> { Solution solution = solver.solve(eq); sendSolution(solution); }); } }; } } <|start_filename|>VIRTUAL-Nov-2020/nfjs-books/src/main/java/habuma/GreetingProps.java<|end_filename|> package habuma; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; import lombok.Data; @Data @ConfigurationProperties(prefix="greeting") @Component public class GreetingProps { private String message; } <|start_filename|>MSP-Mar-2019/boot-demo/src/main/java/habuma/GoodbyeController.java<|end_filename|> package habuma; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; @Controller public class GoodbyeController { @GetMapping("/bye") public String bye() { return "goodbye"; } } <|start_filename|>MSN-Feb-2020/tacotalk/src/main/java/habuma/HelloController.java<|end_filename|> package habuma; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; @Controller public class HelloController { @GetMapping(path="/hello") public String hello( @RequestParam(name="who", defaultValue="World") String who, Model model) { model.addAttribute("who", who); return "hello-view"; } } <|start_filename|>BOS-Sept-2019/books-bos/src/main/java/habuma/RandomHealthIndicator.java<|end_filename|> package habuma; import org.springframework.boot.actuate.health.Health; import org.springframework.boot.actuate.health.HealthIndicator; import org.springframework.stereotype.Component; @Component public class RandomHealthIndicator implements HealthIndicator { @Override public Health health() { double value = Math.random(); if (value > 0.5) { return Health.up() .withDetail("reason", "The value was sufficiently large: " + value) .build(); } RuntimeException exception = new RuntimeException("Crap happened!"); return Health.down(exception) .withDetail("reason", "The value was too small: " + value) .build(); } } <|start_filename|>DSM-Aug-2019/boot-sessions/dsm-books/src/main/java/habuma/GreetingProps.java<|end_filename|> package habuma; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; import lombok.Data; @Component @Data @ConfigurationProperties(prefix="greeting") public class GreetingProps { private String who; private String where = "Des Moines"; } <|start_filename|>VIRTUAL-Jul-2021/spring-integration/itinerary-scheduler/src/main/java/habuma/ItinerarySchedulerSinkApplication.java<|end_filename|> package habuma; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.amqp.core.AmqpTemplate; import org.springframework.amqp.rabbit.connection.ConnectionFactory; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.integration.amqp.inbound.AmqpMessageSource; import org.springframework.integration.dsl.IntegrationFlow; import org.springframework.integration.dsl.IntegrationFlows; import org.springframework.integration.dsl.Pollers; @SpringBootApplication public class ItinerarySchedulerSinkApplication { private static Logger log = LoggerFactory.getLogger(ItinerarySchedulerSinkApplication.class); public static void main(String[] args) { SpringApplication.run(ItinerarySchedulerSinkApplication.class, args); } @Bean public IntegrationFlow flow(ConnectionFactory connectionFactory, AmqpTemplate amqpTemplate) { return IntegrationFlows .from(new AmqpMessageSource(connectionFactory, "itineraries"), c -> c.poller(Pollers.fixedRate(1000))) .handle(itinerary -> { log.info("SCHEDULING ITINERARY: " + itinerary); }) .get(); } } <|start_filename|>MSN-Feb-2020/tacotalk/src/main/java/habuma/SecurityConfig.java<|end_filename|> package habuma; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpMethod; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; @Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .formLogin() .and() .csrf() .and() .authorizeRequests() .antMatchers("/tacos/form").hasRole("ADMIN") .antMatchers(HttpMethod.POST, "/tacos").hasRole("ADMIN") .antMatchers("/**").permitAll(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth .inMemoryAuthentication() .withUser("mickey").password(passwordEncoder().encode("password")).roles("ADMIN", "USER") .and() .withUser("donald").password(passwordEncoder().encode("password")).roles("USER"); } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } } <|start_filename|>EventDrivenSpring-Workshop-Aug-2021/si-trip-processor/src/main/java/habuma/SiTripProcessorApplication.java<|end_filename|> package habuma; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.amqp.core.AmqpTemplate; import org.springframework.amqp.rabbit.connection.ConnectionFactory; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.integration.amqp.dsl.Amqp; import org.springframework.integration.amqp.inbound.AmqpMessageSource; import org.springframework.integration.dsl.IntegrationFlow; import org.springframework.integration.dsl.IntegrationFlows; import org.springframework.integration.dsl.Pollers; @SpringBootApplication public class SiTripProcessorApplication { private static final Logger log = LoggerFactory.getLogger(SiTripProcessorApplication.class); public static void main(String[] args) { SpringApplication.run(SiTripProcessorApplication.class, args); } @Bean public IntegrationFlow flow(ConnectionFactory cf, AmqpTemplate amqpTemplate) { return IntegrationFlows .from(new AmqpMessageSource(cf, "trips"), c -> c.poller(Pollers.fixedRate(1000))) .<TripBooking, Itinerary> transform(trip -> { log.info("PROCESSING TRIP: Payment card number: " + trip.getPaymentCardNumber()); return trip.getItinerary(); }) .handle(Amqp.outboundGateway(amqpTemplate).routingKey("itineraries")) .get(); } } <|start_filename|>STL-Apr-2018/src/main/java/habuma/ProfileUiController.java<|end_filename|> package habuma; import org.springframework.security.core.annotation.AuthenticationPrincipal; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import lombok.RequiredArgsConstructor; @Controller @RequiredArgsConstructor public class ProfileUiController { @GetMapping("/ui/profiles/me") public String allProfiles(@AuthenticationPrincipal Profile profile, Model model) { model.addAttribute("profile", profile); return "profiles"; } } <|start_filename|>ORD-Nov-2018/ord-books/src/main/java/habuma/Foo.java<|end_filename|> package habuma; import org.springframework.context.annotation.Profile; import org.springframework.stereotype.Component; @Component @Profile("chicago") public class Foo { } <|start_filename|>EventDrivenSpring-Workshop-Apr-2021/trip-sink/src/main/java/habuma/TripSink.java<|end_filename|> package habuma; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.amqp.rabbit.annotation.RabbitListener; import org.springframework.stereotype.Component; @Component public class TripSink { private static Logger log = LoggerFactory.getLogger(TripSink.class); @RabbitListener(queues = "itineraries") public void logItinerary(Itinerary itinerary) { log.info("ITINERARY: " + itinerary.getDestination()); } } <|start_filename|>AUS-July-2019/spring-boot-sessions/austin-books/src/main/resources/static/styles.css<|end_filename|> body { background-color: red; color: yellow; } <|start_filename|>BOS-Sept-2019/books-bos/src/main/java/habuma/HelloController.java<|end_filename|> package habuma; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import io.micrometer.core.instrument.MeterRegistry; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; @RestController @RequiredArgsConstructor @Slf4j public class HelloController { private final GreetingProperties props; private final MeterRegistry registry; @GetMapping("/hello") public String hello() { registry.counter("boston-nfjs", "tag", "hello") .increment(); log.debug("Hello is being called"); return props.getMessage(); } } <|start_filename|>VIRTUAL-Jul-2021/spring-cloud-stream/trip-processor/src/main/java/habuma/TripProcessor.java<|end_filename|> package habuma; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Function; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; @SpringBootApplication public class TripProcessor { private static Logger log = LoggerFactory.getLogger(TripProcessor.class); public static void main(String[] args) { System.setProperty("spring.devtools.restart.enabled", "false"); SpringApplication.run(TripProcessor.class, args); } @Bean public Function<TripBooking, Itinerary> processTrip() { return trip -> { log.info("PROCESSING TRIP. Payment card: " + trip.getPaymentCardNumber()); return trip.getItinerary(); }; } } <|start_filename|>ArchConf-2020/event-driven-spring/mdb-solution-logger/src/main/java/com/example/demo/MdbSolutionLoggerApplication.java<|end_filename|> package com.example.demo; import org.springframework.amqp.rabbit.annotation.RabbitListener; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import lombok.extern.slf4j.Slf4j; @SpringBootApplication @Slf4j public class MdbSolutionLoggerApplication { public static void main(String[] args) { SpringApplication.run(MdbSolutionLoggerApplication.class, args); } @RabbitListener(queues = "solutions") public void handleMessage(Solution solution) { log.info("SOLUTION: " + solution); } } <|start_filename|>VIRTUAL-Jul-2021/spring-books/src/main/java/books/OtherConfig.java<|end_filename|> package books; import org.springframework.context.annotation.Configuration; @Configuration public class OtherConfig { } <|start_filename|>MSN-Feb-2020/tacotalk/src/main/java/habuma/TacoApiController.java<|end_filename|> package habuma; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import lombok.RequiredArgsConstructor; @RestController @RequestMapping("/api/tacos") @RequiredArgsConstructor public class TacoApiController { private final TacoRepository tacoRepo; @GetMapping public Iterable<Taco> allTacos() { return tacoRepo.findAll(); } } <|start_filename|>Spring-K8s-Workshop-Aug-2021/hello-kubernetes/src/main/java/hello/HelloController.java<|end_filename|> package hello; import org.springframework.boot.availability.AvailabilityChangeEvent; import org.springframework.boot.availability.AvailabilityState; import org.springframework.boot.availability.LivenessState; import org.springframework.context.ApplicationContext; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class HelloController { private GreetingProps props; private ApplicationContext context; public HelloController(GreetingProps props, ApplicationContext context) { this.props = props; this.context = context; } @GetMapping("/hello") public String hello() throws Exception { Thread.sleep(20000); return props.getMessage(); } @GetMapping("/break") public String breakTHings() { AvailabilityChangeEvent.publish(context, LivenessState.BROKEN); return "BROKEN"; } } <|start_filename|>uberconf-2021/spring-data/uber-book-jpa/src/main/java/com/example/demo/SimpleBook.java<|end_filename|> package com.example.demo; import org.springframework.beans.factory.annotation.Value; public interface SimpleBook { String getIsbn(); String getTitle(); @Value("#{target.author + '....' + target.isbn}") String getAuthorFullName(); } <|start_filename|>STL-Apr-2018/src/main/java/habuma/Profile.java<|end_filename|> package habuma; import java.util.Arrays; import java.util.Collection; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import lombok.AccessLevel; import lombok.Data; import lombok.NoArgsConstructor; import lombok.RequiredArgsConstructor; @Data @NoArgsConstructor(force=true, access=AccessLevel.PRIVATE) @RequiredArgsConstructor @Entity public class Profile implements UserDetails { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy=GenerationType.AUTO) private Long id; private final String username; private final String password; private final String fullName; private final Boolean enabled; @Override public Collection<? extends GrantedAuthority> getAuthorities() { String role = "ROLE_USER"; if (username.equals("venkat")) { role = "ROLE_VENKAT"; } SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(role); return Arrays.asList(simpleGrantedAuthority); } @Override public boolean isAccountNonExpired() { return true; } @Override public boolean isAccountNonLocked() { return true; } @Override public boolean isCredentialsNonExpired() { return true; } @Override public boolean isEnabled() { return true; } } <|start_filename|>VIRTUAL-Nov-2020/hello-service/src/main/java/habuma/HelloController.java<|end_filename|> package habuma; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController @ConfigurationProperties(prefix="greeting") public class HelloController { private String message; public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } @GetMapping("/hello") public String hello() throws Exception { return message; } } <|start_filename|>ArchConf-2020/event-driven-spring/integration-equation-solver/src/main/java/com/example/demo/IntegrationEquationSolverApplication.java<|end_filename|> package com.example.demo; import org.springframework.amqp.core.AmqpTemplate; import org.springframework.amqp.rabbit.connection.ConnectionFactory; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.integration.amqp.dsl.Amqp; import org.springframework.integration.amqp.inbound.AmqpMessageSource; import org.springframework.integration.dsl.IntegrationFlow; import org.springframework.integration.dsl.IntegrationFlows; import org.springframework.integration.dsl.Pollers; @SpringBootApplication public class IntegrationEquationSolverApplication { public static void main(String[] args) { SpringApplication.run(IntegrationEquationSolverApplication.class, args); } @Bean public IntegrationFlow flow( ConnectionFactory connectionFactory, AmqpTemplate amqpTemplate, QuadraticSolver solver) { return IntegrationFlows .from(new AmqpMessageSource(connectionFactory, "equations"), c->c.poller(Pollers.fixedRate(1000))) .<Equation, Solution>transform(equation -> solver.solve(equation)) .handle(Amqp.outboundGateway(amqpTemplate).routingKey("solutions")) .get(); } } <|start_filename|>ORD-Nov-2018/ord-books/src/main/java/habuma/BooksController.java<|end_filename|> package habuma; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import lombok.RequiredArgsConstructor; @RestController @RequestMapping("/legacy/books") @RequiredArgsConstructor public class BooksController { private final BookRepository repo; @GetMapping public Iterable<Book> all() { return repo.findAll(); } @GetMapping("/{isbn}") public Book byIsbn(@PathVariable("isbn") String isbn) { return repo.findByIsbn(isbn); } @GetMapping("/kendalls") public Iterable<Book> kendalls() { repo.doSomethingCompletelyDifferent(); return repo.findKendallsBooks(); } @GetMapping("/simple/{isbn}") public SimpleBook simpleBookIsbn(@PathVariable("isbn") String isbn) { return repo.findSimpleByIsbn(isbn); } } <|start_filename|>MSP-Mar-2019/boot-demo/src/main/java/habuma/HiController.java<|end_filename|> package habuma; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import io.micrometer.core.instrument.MeterRegistry; @RestController public class HiController { private GreetingProps props; private MeterRegistry meterRegistry; public HiController(GreetingProps props, MeterRegistry meterRegistry) { this.props = props; this.meterRegistry = meterRegistry; } @GetMapping("/hi") public String hi() { meterRegistry.counter("demoApp", "hi", "counter") .increment(); return props.getMessage(); } } <|start_filename|>VIRTUAL-Jul-2021/spring-integration/trip-processor/src/main/java/habuma/TripProcessor.java<|end_filename|> package habuma; import java.util.concurrent.atomic.AtomicInteger; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.amqp.core.AmqpTemplate; import org.springframework.amqp.rabbit.connection.ConnectionFactory; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.integration.amqp.dsl.Amqp; import org.springframework.integration.amqp.inbound.AmqpMessageSource; import org.springframework.integration.dsl.IntegrationFlow; import org.springframework.integration.dsl.IntegrationFlows; import org.springframework.integration.dsl.Pollers; @SpringBootApplication public class TripProcessor { private static Logger log = LoggerFactory.getLogger(TripProcessor.class); public static void main(String[] args) { SpringApplication.run(TripProcessor.class, args); } AtomicInteger total = new AtomicInteger(); @Bean public IntegrationFlow flow( ConnectionFactory cf, AmqpTemplate amqpTemplate) { return IntegrationFlows .from(new AmqpMessageSource(cf, "trips"), c -> c.poller(Pollers.fixedRate(1000))) .<TripBooking, Itinerary> transform(trip -> { log.info("PROCESSING TRIP. Payment card: " + trip.getPaymentCardNumber()); log.info("ITINERARY: " + trip.getItinerary()); return trip.getItinerary(); }) .handle(Amqp.outboundGateway(amqpTemplate).routingKey("itineraries").waitForConfirm(false)) .get(); } } <|start_filename|>IAD-Nov-2018/iad-books/src/main/java/com/example/demo/BookController.java<|end_filename|> package com.example.demo; import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import io.micrometer.core.instrument.MeterRegistry; import lombok.RequiredArgsConstructor; @RestController @RequestMapping("/myapi/books") @RequiredArgsConstructor public class BookController { private final BookRepository repo; private final GreetingProps props; private final MeterRegistry meters; @GetMapping("/hi") public String hi() { meters.counter("com.nofluffjuststuff", "A", "B").increment(); return props.getMessage(); } @GetMapping public Iterable<Book> findAll() { return repo.findAll(); } @PostMapping public Book save(@RequestBody Book book) { return repo.save(book); } @GetMapping("/{isbn}") public Book findByIsbn(@PathVariable("isbn") String isbn) { return repo.findByIsbn(isbn); } @GetMapping("/{isbn}/simple") public SimpleBook findSimpleByIsbn(@PathVariable("isbn") String isbn) { return repo.findSimpleByIsbn(isbn); } @GetMapping("/kendalls") public Iterable<Book> kendallsBooks() { return repo.kendallsBooks(); } } <|start_filename|>ArchConf-2020/spring-gateway/hello-world/src/main/java/com/example/demo/HelloController.java<|end_filename|> package com.example.demo; import java.util.Iterator; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.context.request.WebRequest; @RestController public class HelloController { @GetMapping("/hello") public String hello(WebRequest req) { logHeaders(req); return "Hello world!"; } @GetMapping("/bye") public String bye(WebRequest req) { logHeaders(req); return "Bye!"; } private void logHeaders(WebRequest req) { Iterator<String> headerNames = req.getHeaderNames(); while(headerNames.hasNext()) { String headerName = headerNames.next(); String value = req.getHeader(headerName); System.out.println(" - " + headerName + " = " + value); } } } <|start_filename|>VIRTUAL-Jan-2021/boot/books/src/main/java/books/BookRepository.java<|end_filename|> package books; import org.springframework.data.repository.CrudRepository; public interface BookRepository extends CrudRepository<Book, Long> { } <|start_filename|>Spring-K8s-Workshop-Mar-2021/spring-k8s-workshop/src/main/java/com/example/demo/LivenessReadinessController.java<|end_filename|> package com.example.demo; import org.springframework.boot.availability.AvailabilityChangeEvent; import org.springframework.boot.availability.LivenessState; import org.springframework.boot.availability.ReadinessState; import org.springframework.context.ApplicationContext; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class LivenessReadinessController { private ApplicationContext applicationContext; public LivenessReadinessController(ApplicationContext applicationContext) { this.applicationContext = applicationContext; } @PostMapping("/notready") public String notReady() { AvailabilityChangeEvent.publish( applicationContext, ReadinessState.REFUSING_TRAFFIC); return "notready"; } @PostMapping("/ready") public String ready() { AvailabilityChangeEvent.publish( applicationContext, ReadinessState.ACCEPTING_TRAFFIC); return "ready"; } @PostMapping("/alive") public String alive() { AvailabilityChangeEvent.publish( applicationContext, LivenessState.CORRECT); return "alive"; } @PostMapping("/dead") public String dead() { AvailabilityChangeEvent.publish( applicationContext, LivenessState.BROKEN); return "dead"; } } <|start_filename|>IAD-Nov-2019/iad-books/src/main/java/habuma/BooksRepository.java<|end_filename|> package habuma; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; public interface BooksRepository extends CrudRepository<Book, Long> { Book findByIsbn(String isbn); SimplePublication findSimpleByIsbn(String isbn); @Query("from Book b where b.author.firstName = 'Kendall' and b.author.lastName='Crolius'") Book findBooksByKendallCrolius(); } <|start_filename|>EventDrivenSpring-Workshop-Aug-2021/scs-trip-source/src/main/java/habuma/TripBooking.java<|end_filename|> package habuma; import java.io.Serializable; public class TripBooking implements Serializable { private static final long serialVersionUID = 1L; private String travelerName; private String paymentCardNumber; private Itinerary itinerary; public String getTravelerName() { return travelerName; } public void setTravelerName(String travelerName) { this.travelerName = travelerName; } public String getPaymentCardNumber() { return paymentCardNumber; } public void setPaymentCardNumber(String paymentCardNumber) { this.paymentCardNumber = paymentCardNumber; } public Itinerary getItinerary() { return itinerary; } public void setItinerary(Itinerary itinerary) { this.itinerary = itinerary; } } <|start_filename|>BOS-Sept-2019/books-bos/src/main/java/habuma/HiyaController.java<|end_filename|> package habuma; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; @Controller public class HiyaController { @GetMapping("/hi") public String hiya(Model model) { model.addAttribute("who", "Framingham"); return "hiya"; } } <|start_filename|>MSN-Feb-2020/msn-books/src/main/java/habuma/RandomHealthIndicator.java<|end_filename|> package habuma; import org.springframework.boot.actuate.health.Health; import org.springframework.boot.actuate.health.HealthIndicator; import org.springframework.stereotype.Component; @Component public class RandomHealthIndicator implements HealthIndicator { @Override public Health health() { double random = Math.random(); if (random > 0.5) { //healthy return Health.up() .withDetail("reason", "The value is large enough: " + random) .build(); } //unhealthy return Health.down() .withDetail("reason", "The value is too low: " + random) .build(); } } <|start_filename|>STL-Apr-2019/spring-boot/books/src/main/java/habuma/books/BooksController.java<|end_filename|> package habuma.books; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import io.micrometer.core.instrument.MeterRegistry; import lombok.RequiredArgsConstructor; @RestController @RequestMapping("/books") @RequiredArgsConstructor public class BooksController { private final BookRepository repo; private final MeterRegistry meterRegistry; @GetMapping public Iterable<Book> allBooks() { meterRegistry.counter("habuma.books", "allbooks", "requests").increment(); return repo.findAll(); } } <|start_filename|>MSP-Oct-2018/msp-books/src/main/java/habuma/BookRepository.java<|end_filename|> package habuma; public interface BookRepository { Iterable<Book> findAll(); } <|start_filename|>MSN-Feb-2020/reactive-books/src/main/java/habuma/Book.java<|end_filename|> package habuma; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; import lombok.Data; import lombok.RequiredArgsConstructor; @Document @Data @RequiredArgsConstructor public class Book { @Id private String id; private final String isbn; private final String title; private final String author; } <|start_filename|>EventDrivenSpring-Workshop-Apr-2021/trip-processor/src/main/java/habuma/TripHandler.java<|end_filename|> package habuma; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.amqp.rabbit.annotation.RabbitListener; import org.springframework.messaging.handler.annotation.SendTo; import org.springframework.stereotype.Component; @Component public class TripHandler { private static final Logger log = LoggerFactory.getLogger(TripHandler.class); @RabbitListener(queues = "trips") @SendTo("itineraries") public Itinerary processTrip(TripBooking trip) { log.info("PROCESSING TRIP: Payment card: " + trip.getPaymentCardNumber()); return trip.getItinerary(); } } <|start_filename|>uberconf-2019/spring-boot/uber-books-2/src/main/java/habuma/Book.java<|end_filename|> package habuma; import org.springframework.data.mongodb.core.mapping.Document; import lombok.Data; @Document @Data public class Book { private String id; private final String isbn; private final String title; private final String author; } <|start_filename|>SpringBoot-Workshop-Oct-2021/nfjs-books/src/main/java/habuma/BookRepository.java<|end_filename|> package habuma; import org.springframework.data.repository.reactive.ReactiveCrudRepository; import reactor.core.publisher.Flux; public interface BookRepository extends ReactiveCrudRepository<Book, String>{ Flux<Book> findByAuthor(String author); } <|start_filename|>uberconf-2021/spring-containers/hello-k8s/src/main/java/com/example/demo/HelloController.java<|end_filename|> package com.example.demo; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class HelloController { @GetMapping("/hello") public String hello() throws Exception { Thread.sleep(10000); return "Hello UberConf!"; } } <|start_filename|>AUS-July-2019/spring-boot-sessions/austin-books/src/main/java/habuma/RandomInfoContributor.java<|end_filename|> package habuma; import org.springframework.boot.actuate.info.InfoContributor; import org.springframework.stereotype.Component; import org.springframework.boot.actuate.info.Info.Builder; @Component public class RandomInfoContributor implements InfoContributor { @Override public void contribute(Builder builder) { builder .withDetail("random-number", Math.random()) .withDetail("some-book", new Book("1029384756", "Crafting with Cat Hair", "Kaori", "Tsutaya")); } } <|start_filename|>IAD-Nov-2019/iad-books/src/main/java/habuma/Book.java<|end_filename|> package habuma; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToOne; import lombok.AccessLevel; import lombok.Data; import lombok.NoArgsConstructor; import lombok.RequiredArgsConstructor; @Data @Entity @NoArgsConstructor(force=true, access=AccessLevel.PRIVATE) @RequiredArgsConstructor public class Book { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private final String isbn; private final String title; @ManyToOne private final Author author; } <|start_filename|>MSN-Feb-2020/hello-madison/test/testing.json<|end_filename|> { "handler": "../lambda/custom/index.js", "jest": { "coveragePathIgnorePatterns": [ "<rootDir>/test/.*\\.js", "<rootDir>/testflow.js", "<rootDir>/lambda/custom/util.js", "<rootDir>/lambda/custom/local-debugger.js" ] } } <|start_filename|>DSM-Aug-2019/boot-sessions/dsm-books/src/main/java/habuma/HiyaEndpoint.java<|end_filename|> package habuma; import org.springframework.boot.actuate.endpoint.annotation.Endpoint; import org.springframework.boot.actuate.endpoint.annotation.ReadOperation; import org.springframework.stereotype.Component; @Component @Endpoint(id = "hiya", enableByDefault = true) public class HiyaEndpoint { @ReadOperation public String hiya() { return "Hiya!"; } } <|start_filename|>DFW-June-2019/dfw-profiles/src/main/java/com/example/demo/HomeController.java<|end_filename|> package com.example.demo; import java.security.Principal; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; @Controller public class HomeController { @GetMapping("/home") public String home(Principal principal, Model model) { String name = principal.getName(); model.addAttribute("who", name); return "homepage"; } } <|start_filename|>BOS-Sept-2018-2/src/main/java/habuma/BooksController.java<|end_filename|> package habuma; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import lombok.RequiredArgsConstructor; @RestController @RequestMapping("/books") @RequiredArgsConstructor public class BooksController { private final BookRepository repo; @GetMapping public Iterable<Book> allBooks() { return repo.findAll(); } @GetMapping(params="author") public Iterable<Book> byAuthor(@RequestParam("author") String author) { return repo.findByAuthor(author); } @GetMapping("/kendalls") public Iterable<Book> kendallsBooks() { repo.doSomethingDifferent(); return repo.findKendallsBooks(); } @PostMapping public Book saveABook(@RequestBody Book book) { return repo.save(book); } } <|start_filename|>SpringBoot-Workshop-Oct-2021/nfjs-books/src/main/java/habuma/HowdyController.java<|end_filename|> package habuma; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import reactor.core.scheduler.Scheduler; import reactor.core.scheduler.Schedulers; @RestController public class HowdyController { @GetMapping("/howdy") public Mono<String> howdy() { return Mono.just("Howdy!") .map(in -> in.toUpperCase()); } @GetMapping("/fruits") public Flux<String> fruits() { return Flux.fromArray(new String[] {"Apple", "Orange", "Grape"}) .flatMap(in -> Mono.just(in.toLowerCase()) .subscribeOn(Schedulers.parallel())); } } <|start_filename|>ORD-Oct-2019/books-ord/src/main/java/com/example/demo/SDRConfig.java<|end_filename|> package com.example.demo; import org.springframework.context.annotation.Configuration; import org.springframework.data.rest.core.config.RepositoryRestConfiguration; import org.springframework.data.rest.webmvc.config.RepositoryRestConfigurer; @Configuration public class SDRConfig implements RepositoryRestConfigurer { @Override public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) { config .withEntityLookup() .forRepository( BooksRepository.class, Book::getIsbn, BooksRepository::findByIsbn ); } } <|start_filename|>BOS-Sept-2021/testing-spring-final/src/main/java/habuma/BookController.java<|end_filename|> package habuma; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import lombok.RequiredArgsConstructor; @RestController @RequestMapping("/books") @RequiredArgsConstructor public class BookController { private final BookRepository repo; @GetMapping public Iterable<Book> allBooks() { return repo.findAll(); } @GetMapping("/{isbn}") public Book byIsbn(@PathVariable("isbn") String isbn) { return repo.findByIsbn(isbn); } @PostMapping public Book save(@RequestBody Book book) { return repo.save(book); } } <|start_filename|>uberconf-2019/spring-boot/uber-books/src/main/java/habuma/ScheduledStuff.java<|end_filename|> package habuma; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import lombok.extern.slf4j.Slf4j; @Component @Slf4j public class ScheduledStuff { // @Scheduled(fixedDelay = 5000) public void doSomething() { log.info("DOING SOMETHING"); } } <|start_filename|>BOS-Sept-2018-2/src/main/java/habuma/HiController.java<|end_filename|> package habuma; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class HiController { @GetMapping("/") public String hi() { return "Hiya Boston!"; } } <|start_filename|>VIRTUAL-Sept-2020/nfjs-books/src/main/java/habuma/BooksController.java<|end_filename|> package habuma; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import lombok.RequiredArgsConstructor; @RestController @RequestMapping("/books") @RequiredArgsConstructor public class BooksController { private final BookRepository repo; @GetMapping Iterable<Book> findAll() { return repo.findAll(); } @PostMapping Book save(@RequestBody Book book) { return repo.save(book); } } <|start_filename|>uberconf-2019/voice-apps-workshop/starflyer-travel/test_output/report/index.html<|end_filename|> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>jest-stare!</title> <link href="css/bootstrap.min.css" rel="stylesheet" type="text/css"> <link href="css/diff2html.min.css" rel="stylesheet" type="text/css"> <link href="css/jest-stare.css" rel="stylesheet" type="text/css"> <script src="js/jquery.min.js"></script> <script src="js/holder.js"></script> <script src="js/diff2html.min.js"></script> <script src="js/bootstrap.min.js"></script> <script src="js/view.js"></script> </head> <body> <header> <!-- Fixed navbar --> <nav class="navbar navbar-expand-md navbar-dark fixed-top bg-dark"> <a class="navbar-brand" href="#">jest-stare</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarCollapse"> <ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a class="nav-link" href="#">Home <span class="sr-only">(current)</span> </a> </li> <li class="nav-item"> <a id="coverage-link" class="nav-link disabled" href="#">Coverage</a> </li> <li class="nav-item"> <div class="onoff-switch mr-sm-2 ml-sm-2"> <input type="checkbox" name="passoff-switch" class="passoff-switch-checkbox" id="lab-passoff-switch" checked> <label class="onoff-switch-label" for="lab-passoff-switch"> <span class="passoff-switch-inner"></span> <span class="passoff-switch-switch"></span> </label> </div> </li> <li class="nav-item"> <div class="onoff-switch mr-sm-2 ml-sm-2"> <input type="checkbox" name="failoff-switch" class="failoff-switch-checkbox" id="lab-failoff-switch" checked> <label class="onoff-switch-label" for="lab-failoff-switch"> <span class="failoff-switch-inner"></span> <span class="failoff-switch-switch"></span> </label> </div> </li> </ul> <!-- <form class="form-inline mt-2 mt-md-0"> <input class="form-control mr-sm-2" type="text" placeholder="Search" aria-label="Search" disabled> <button class="btn btn-outline-success my-2 my-sm-0" type="submit" disabled>Search</button> </form> --> </div> </nav> </header> <!-- Begin page content --> <main role="main" class="container"> <h1 class="mt-5"></h1> <!-- Three columns of text below the carousel --> <div class="row"> <div class="col-lg-4"> <canvas id="test-suites-canvas" width="100" height="100"></canvas> <h2>Test Suites</h2> <div class="list-group"> <p id="test-suites-results" class="list-group-item list-group-item-action">1 passed, 1 total</p> </div> </div> <!-- /.col-lg-4 --> <div class="col-lg-4"> <canvas id="tests-canvas" width="100" height="100"></canvas> <h2>Tests</h2> <div class="list-group"> <p id="tests-results" class="list-group-item list-group-item-action">3 passed, 3 total</p> </div> </div> <!-- /.col-lg-4 --> <div class="col-lg-4" id="snapshots-group"> <canvas id="snapshots-canvas" width="100" height="100"></canvas> <h2>Snapshots</h2> <div class="list-group"> <p id="snapshots-results" class="list-group-item list-group-item-action">0 passed, 0 total</p> </div> </div> <!-- /.col-lg-4 --> </div> <div id="loading-info" class="progress"> <div class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar" aria-valuenow="100" aria-valuemin="0" aria-valuemax="100" style="width: 100%"></div> </div> <div class="d-none" id="test-config">{ &quot;additionalResultsProcessors&quot;: [], &quot;resultDir&quot;: &quot;&#x2F;Users&#x2F;habuma&#x2F;starflyer-travel&#x2F;test_output&#x2F;report&#x2F;&quot;, &quot;log&quot;: false, &quot;coverageLink&quot;: &quot;..&#x2F;coverage&#x2F;lcov-report&#x2F;index.html&quot;, &quot;resultHtml&quot;: &quot;index.html&quot;, &quot;resultJson&quot;: &quot;jest-results.json&quot; }</div> <div class="d-none" id="test-results">{ &quot;numFailedTestSuites&quot;: 0, &quot;numFailedTests&quot;: 0, &quot;numPassedTestSuites&quot;: 1, &quot;numPassedTests&quot;: 3, &quot;numPendingTestSuites&quot;: 0, &quot;numPendingTests&quot;: 0, &quot;numRuntimeErrorTestSuites&quot;: 0, &quot;numTodoTests&quot;: 0, &quot;numTotalTestSuites&quot;: 1, &quot;numTotalTests&quot;: 3, &quot;openHandles&quot;: [], &quot;snapshot&quot;: { &quot;added&quot;: 0, &quot;didUpdate&quot;: false, &quot;failure&quot;: false, &quot;filesAdded&quot;: 0, &quot;filesRemoved&quot;: 0, &quot;filesUnmatched&quot;: 0, &quot;filesUpdated&quot;: 0, &quot;matched&quot;: 0, &quot;total&quot;: 0, &quot;unchecked&quot;: 0, &quot;uncheckedKeysByFile&quot;: [], &quot;unmatched&quot;: 0, &quot;updated&quot;: 0 }, &quot;startTime&quot;: 1563297317291, &quot;success&quot;: false, &quot;testResults&quot;: [ { &quot;failureMessage&quot;: null, &quot;leaks&quot;: false, &quot;memoryUsage&quot;: 0, &quot;numFailingTests&quot;: 0, &quot;numPassingTests&quot;: 3, &quot;numPendingTests&quot;: 0, &quot;skipped&quot;: false, &quot;snapshot&quot;: { &quot;added&quot;: 0, &quot;fileDeleted&quot;: false, &quot;matched&quot;: 0, &quot;unchecked&quot;: 0, &quot;uncheckedKeys&quot;: [], &quot;unmatched&quot;: 0, &quot;updated&quot;: 0 }, &quot;testFilePath&quot;: &quot;&#x2F;Users&#x2F;habuma&#x2F;starflyer-travel&#x2F;tests&#x2F;simple.test.yml&quot;, &quot;testResults&quot;: [ { &quot;ancestorTitles&quot;: [ &quot;en-US&quot;, &quot;Launch request for Star Flyer Travel&quot; ], &quot;duration&quot;: 54, &quot;failureMessages&quot;: [], &quot;location&quot;: { &quot;column&quot;: 0, &quot;line&quot;: 0 }, &quot;numPassingAsserts&quot;: 0, &quot;status&quot;: &quot;passed&quot;, &quot;title&quot;: &quot;LaunchRequest&quot; }, { &quot;ancestorTitles&quot;: [ &quot;en-US&quot;, &quot;Hello World&quot; ], &quot;duration&quot;: 2, &quot;failureMessages&quot;: [], &quot;location&quot;: { &quot;column&quot;: 0, &quot;line&quot;: 0 }, &quot;numPassingAsserts&quot;: 0, &quot;status&quot;: &quot;passed&quot;, &quot;title&quot;: &quot;Hello&quot; }, { &quot;ancestorTitles&quot;: [ &quot;en-US&quot;, &quot;Hello World&quot; ], &quot;duration&quot;: 1, &quot;failureMessages&quot;: [], &quot;location&quot;: { &quot;column&quot;: 0, &quot;line&quot;: 0 }, &quot;numPassingAsserts&quot;: 0, &quot;status&quot;: &quot;passed&quot;, &quot;title&quot;: &quot;HelloWorldIntent&quot; } ], &quot;perfStats&quot;: { &quot;end&quot;: 1563297317956, &quot;start&quot;: 1563297317339 }, &quot;numTodoTests&quot;: 0 } ], &quot;wasInterrupted&quot;: false, &quot;coverageMap&quot;: { &quot;&#x2F;Users&#x2F;habuma&#x2F;starflyer-travel&#x2F;lambda&#x2F;custom&#x2F;index.js&quot;: { &quot;path&quot;: &quot;&#x2F;Users&#x2F;habuma&#x2F;starflyer-travel&#x2F;lambda&#x2F;custom&#x2F;index.js&quot;, &quot;statementMap&quot;: { &quot;0&quot;: { &quot;start&quot;: { &quot;line&quot;: 4, &quot;column&quot;: 14 }, &quot;end&quot;: { &quot;line&quot;: 4, &quot;column&quot;: 37 } }, &quot;1&quot;: { &quot;start&quot;: { &quot;line&quot;: 6, &quot;column&quot;: 29 }, &quot;end&quot;: { &quot;line&quot;: 19, &quot;column&quot;: 1 } }, &quot;2&quot;: { &quot;start&quot;: { &quot;line&quot;: 8, &quot;column&quot;: 4 }, &quot;end&quot;: { &quot;line&quot;: 8, &quot;column&quot;: 73 } }, &quot;3&quot;: { &quot;start&quot;: { &quot;line&quot;: 11, &quot;column&quot;: 23 }, &quot;end&quot;: { &quot;line&quot;: 11, &quot;column&quot;: 78 } }, &quot;4&quot;: { &quot;start&quot;: { &quot;line&quot;: 13, &quot;column&quot;: 4 }, &quot;end&quot;: { &quot;line&quot;: 17, &quot;column&quot;: 21 } }, &quot;5&quot;: { &quot;start&quot;: { &quot;line&quot;: 21, &quot;column&quot;: 32 }, &quot;end&quot;: { &quot;line&quot;: 36, &quot;column&quot;: 1 } }, &quot;6&quot;: { &quot;start&quot;: { &quot;line&quot;: 23, &quot;column&quot;: 4 }, &quot;end&quot;: { &quot;line&quot;: 24, &quot;column&quot;: 81 } }, &quot;7&quot;: { &quot;start&quot;: { &quot;line&quot;: 27, &quot;column&quot;: 23 }, &quot;end&quot;: { &quot;line&quot;: 27, &quot;column&quot;: 40 } }, &quot;8&quot;: { &quot;start&quot;: { &quot;line&quot;: 28, &quot;column&quot;: 4 }, &quot;end&quot;: { &quot;line&quot;: 28, &quot;column&quot;: 35 } }, &quot;9&quot;: { &quot;start&quot;: { &quot;line&quot;: 29, &quot;column&quot;: 4 }, &quot;end&quot;: { &quot;line&quot;: 29, &quot;column&quot;: 30 } }, &quot;10&quot;: { &quot;start&quot;: { &quot;line&quot;: 31, &quot;column&quot;: 4 }, &quot;end&quot;: { &quot;line&quot;: 34, &quot;column&quot;: 21 } }, &quot;11&quot;: { &quot;start&quot;: { &quot;line&quot;: 38, &quot;column&quot;: 26 }, &quot;end&quot;: { &quot;line&quot;: 52, &quot;column&quot;: 1 } }, &quot;12&quot;: { &quot;start&quot;: { &quot;line&quot;: 40, &quot;column&quot;: 4 }, &quot;end&quot;: { &quot;line&quot;: 41, &quot;column&quot;: 82 } }, &quot;13&quot;: { &quot;start&quot;: { &quot;line&quot;: 44, &quot;column&quot;: 23 }, &quot;end&quot;: { &quot;line&quot;: 44, &quot;column&quot;: 49 } }, &quot;14&quot;: { &quot;start&quot;: { &quot;line&quot;: 46, &quot;column&quot;: 4 }, &quot;end&quot;: { &quot;line&quot;: 50, &quot;column&quot;: 21 } }, &quot;15&quot;: { &quot;start&quot;: { &quot;line&quot;: 54, &quot;column&quot;: 35 }, &quot;end&quot;: { &quot;line&quot;: 68, &quot;column&quot;: 1 } }, &quot;16&quot;: { &quot;start&quot;: { &quot;line&quot;: 56, &quot;column&quot;: 4 }, &quot;end&quot;: { &quot;line&quot;: 58, &quot;column&quot;: 85 } }, &quot;17&quot;: { &quot;start&quot;: { &quot;line&quot;: 61, &quot;column&quot;: 23 }, &quot;end&quot;: { &quot;line&quot;: 61, &quot;column&quot;: 33 } }, &quot;18&quot;: { &quot;start&quot;: { &quot;line&quot;: 63, &quot;column&quot;: 4 }, &quot;end&quot;: { &quot;line&quot;: 66, &quot;column&quot;: 21 } }, &quot;19&quot;: { &quot;start&quot;: { &quot;line&quot;: 70, &quot;column&quot;: 35 }, &quot;end&quot;: { &quot;line&quot;: 79, &quot;column&quot;: 1 } }, &quot;20&quot;: { &quot;start&quot;: { &quot;line&quot;: 72, &quot;column&quot;: 4 }, &quot;end&quot;: { &quot;line&quot;: 72, &quot;column&quot;: 79 } }, &quot;21&quot;: { &quot;start&quot;: { &quot;line&quot;: 75, &quot;column&quot;: 4 }, &quot;end&quot;: { &quot;line&quot;: 75, &quot;column&quot;: 93 } }, &quot;22&quot;: { &quot;start&quot;: { &quot;line&quot;: 77, &quot;column&quot;: 4 }, &quot;end&quot;: { &quot;line&quot;: 77, &quot;column&quot;: 54 } }, &quot;23&quot;: { &quot;start&quot;: { &quot;line&quot;: 81, &quot;column&quot;: 21 }, &quot;end&quot;: { &quot;line&quot;: 93, &quot;column&quot;: 1 } }, &quot;24&quot;: { &quot;start&quot;: { &quot;line&quot;: 83, &quot;column&quot;: 4 }, &quot;end&quot;: { &quot;line&quot;: 83, &quot;column&quot;: 16 } }, &quot;25&quot;: { &quot;start&quot;: { &quot;line&quot;: 86, &quot;column&quot;: 4 }, &quot;end&quot;: { &quot;line&quot;: 86, &quot;column&quot;: 51 } }, &quot;26&quot;: { &quot;start&quot;: { &quot;line&quot;: 88, &quot;column&quot;: 4 }, &quot;end&quot;: { &quot;line&quot;: 91, &quot;column&quot;: 21 } }, &quot;27&quot;: { &quot;start&quot;: { &quot;line&quot;: 95, &quot;column&quot;: 21 }, &quot;end&quot;: { &quot;line&quot;: 95, &quot;column&quot;: 49 } }, &quot;28&quot;: { &quot;start&quot;: { &quot;line&quot;: 97, &quot;column&quot;: 0 }, &quot;end&quot;: { &quot;line&quot;: 106, &quot;column&quot;: 12 } } }, &quot;fnMap&quot;: { &quot;0&quot;: { &quot;name&quot;: &quot;(anonymous_0)&quot;, &quot;decl&quot;: { &quot;start&quot;: { &quot;line&quot;: 7, &quot;column&quot;: 2 }, &quot;end&quot;: { &quot;line&quot;: 7, &quot;column&quot;: 3 } }, &quot;loc&quot;: { &quot;start&quot;: { &quot;line&quot;: 7, &quot;column&quot;: 26 }, &quot;end&quot;: { &quot;line&quot;: 9, &quot;column&quot;: 3 } }, &quot;line&quot;: 7 }, &quot;1&quot;: { &quot;name&quot;: &quot;(anonymous_1)&quot;, &quot;decl&quot;: { &quot;start&quot;: { &quot;line&quot;: 10, &quot;column&quot;: 2 }, &quot;end&quot;: { &quot;line&quot;: 10, &quot;column&quot;: 3 } }, &quot;loc&quot;: { &quot;start&quot;: { &quot;line&quot;: 10, &quot;column&quot;: 23 }, &quot;end&quot;: { &quot;line&quot;: 18, &quot;column&quot;: 3 } }, &quot;line&quot;: 10 }, &quot;2&quot;: { &quot;name&quot;: &quot;(anonymous_2)&quot;, &quot;decl&quot;: { &quot;start&quot;: { &quot;line&quot;: 22, &quot;column&quot;: 2 }, &quot;end&quot;: { &quot;line&quot;: 22, &quot;column&quot;: 3 } }, &quot;loc&quot;: { &quot;start&quot;: { &quot;line&quot;: 22, &quot;column&quot;: 26 }, &quot;end&quot;: { &quot;line&quot;: 25, &quot;column&quot;: 3 } }, &quot;line&quot;: 22 }, &quot;3&quot;: { &quot;name&quot;: &quot;(anonymous_3)&quot;, &quot;decl&quot;: { &quot;start&quot;: { &quot;line&quot;: 26, &quot;column&quot;: 2 }, &quot;end&quot;: { &quot;line&quot;: 26, &quot;column&quot;: 3 } }, &quot;loc&quot;: { &quot;start&quot;: { &quot;line&quot;: 26, &quot;column&quot;: 23 }, &quot;end&quot;: { &quot;line&quot;: 35, &quot;column&quot;: 3 } }, &quot;line&quot;: 26 }, &quot;4&quot;: { &quot;name&quot;: &quot;(anonymous_4)&quot;, &quot;decl&quot;: { &quot;start&quot;: { &quot;line&quot;: 39, &quot;column&quot;: 2 }, &quot;end&quot;: { &quot;line&quot;: 39, &quot;column&quot;: 3 } }, &quot;loc&quot;: { &quot;start&quot;: { &quot;line&quot;: 39, &quot;column&quot;: 26 }, &quot;end&quot;: { &quot;line&quot;: 42, &quot;column&quot;: 3 } }, &quot;line&quot;: 39 }, &quot;5&quot;: { &quot;name&quot;: &quot;(anonymous_5)&quot;, &quot;decl&quot;: { &quot;start&quot;: { &quot;line&quot;: 43, &quot;column&quot;: 2 }, &quot;end&quot;: { &quot;line&quot;: 43, &quot;column&quot;: 3 } }, &quot;loc&quot;: { &quot;start&quot;: { &quot;line&quot;: 43, &quot;column&quot;: 23 }, &quot;end&quot;: { &quot;line&quot;: 51, &quot;column&quot;: 3 } }, &quot;line&quot;: 43 }, &quot;6&quot;: { &quot;name&quot;: &quot;(anonymous_6)&quot;, &quot;decl&quot;: { &quot;start&quot;: { &quot;line&quot;: 55, &quot;column&quot;: 2 }, &quot;end&quot;: { &quot;line&quot;: 55, &quot;column&quot;: 3 } }, &quot;loc&quot;: { &quot;start&quot;: { &quot;line&quot;: 55, &quot;column&quot;: 26 }, &quot;end&quot;: { &quot;line&quot;: 59, &quot;column&quot;: 3 } }, &quot;line&quot;: 55 }, &quot;7&quot;: { &quot;name&quot;: &quot;(anonymous_7)&quot;, &quot;decl&quot;: { &quot;start&quot;: { &quot;line&quot;: 60, &quot;column&quot;: 2 }, &quot;end&quot;: { &quot;line&quot;: 60, &quot;column&quot;: 3 } }, &quot;loc&quot;: { &quot;start&quot;: { &quot;line&quot;: 60, &quot;column&quot;: 23 }, &quot;end&quot;: { &quot;line&quot;: 67, &quot;column&quot;: 3 } }, &quot;line&quot;: 60 }, &quot;8&quot;: { &quot;name&quot;: &quot;(anonymous_8)&quot;, &quot;decl&quot;: { &quot;start&quot;: { &quot;line&quot;: 71, &quot;column&quot;: 2 }, &quot;end&quot;: { &quot;line&quot;: 71, &quot;column&quot;: 3 } }, &quot;loc&quot;: { &quot;start&quot;: { &quot;line&quot;: 71, &quot;column&quot;: 26 }, &quot;end&quot;: { &quot;line&quot;: 73, &quot;column&quot;: 3 } }, &quot;line&quot;: 71 }, &quot;9&quot;: { &quot;name&quot;: &quot;(anonymous_9)&quot;, &quot;decl&quot;: { &quot;start&quot;: { &quot;line&quot;: 74, &quot;column&quot;: 2 }, &quot;end&quot;: { &quot;line&quot;: 74, &quot;column&quot;: 3 } }, &quot;loc&quot;: { &quot;start&quot;: { &quot;line&quot;: 74, &quot;column&quot;: 23 }, &quot;end&quot;: { &quot;line&quot;: 78, &quot;column&quot;: 3 } }, &quot;line&quot;: 74 }, &quot;10&quot;: { &quot;name&quot;: &quot;(anonymous_10)&quot;, &quot;decl&quot;: { &quot;start&quot;: { &quot;line&quot;: 82, &quot;column&quot;: 2 }, &quot;end&quot;: { &quot;line&quot;: 82, &quot;column&quot;: 3 } }, &quot;loc&quot;: { &quot;start&quot;: { &quot;line&quot;: 82, &quot;column&quot;: 14 }, &quot;end&quot;: { &quot;line&quot;: 84, &quot;column&quot;: 3 } }, &quot;line&quot;: 82 }, &quot;11&quot;: { &quot;name&quot;: &quot;(anonymous_11)&quot;, &quot;decl&quot;: { &quot;start&quot;: { &quot;line&quot;: 85, &quot;column&quot;: 2 }, &quot;end&quot;: { &quot;line&quot;: 85, &quot;column&quot;: 3 } }, &quot;loc&quot;: { &quot;start&quot;: { &quot;line&quot;: 85, &quot;column&quot;: 30 }, &quot;end&quot;: { &quot;line&quot;: 92, &quot;column&quot;: 3 } }, &quot;line&quot;: 85 } }, &quot;branchMap&quot;: { &quot;0&quot;: { &quot;loc&quot;: { &quot;start&quot;: { &quot;line&quot;: 23, &quot;column&quot;: 11 }, &quot;end&quot;: { &quot;line&quot;: 24, &quot;column&quot;: 80 } }, &quot;type&quot;: &quot;binary-expr&quot;, &quot;locations&quot;: [ { &quot;start&quot;: { &quot;line&quot;: 23, &quot;column&quot;: 11 }, &quot;end&quot;: { &quot;line&quot;: 23, &quot;column&quot;: 72 } }, { &quot;start&quot;: { &quot;line&quot;: 24, &quot;column&quot;: 9 }, &quot;end&quot;: { &quot;line&quot;: 24, &quot;column&quot;: 80 } } ], &quot;line&quot;: 23 }, &quot;1&quot;: { &quot;loc&quot;: { &quot;start&quot;: { &quot;line&quot;: 40, &quot;column&quot;: 11 }, &quot;end&quot;: { &quot;line&quot;: 41, &quot;column&quot;: 81 } }, &quot;type&quot;: &quot;binary-expr&quot;, &quot;locations&quot;: [ { &quot;start&quot;: { &quot;line&quot;: 40, &quot;column&quot;: 11 }, &quot;end&quot;: { &quot;line&quot;: 40, &quot;column&quot;: 72 } }, { &quot;start&quot;: { &quot;line&quot;: 41, &quot;column&quot;: 9 }, &quot;end&quot;: { &quot;line&quot;: 41, &quot;column&quot;: 81 } } ], &quot;line&quot;: 40 }, &quot;2&quot;: { &quot;loc&quot;: { &quot;start&quot;: { &quot;line&quot;: 56, &quot;column&quot;: 11 }, &quot;end&quot;: { &quot;line&quot;: 58, &quot;column&quot;: 84 } }, &quot;type&quot;: &quot;binary-expr&quot;, &quot;locations&quot;: [ { &quot;start&quot;: { &quot;line&quot;: 56, &quot;column&quot;: 11 }, &quot;end&quot;: { &quot;line&quot;: 56, &quot;column&quot;: 72 } }, { &quot;start&quot;: { &quot;line&quot;: 57, &quot;column&quot;: 10 }, &quot;end&quot;: { &quot;line&quot;: 57, &quot;column&quot;: 84 } }, { &quot;start&quot;: { &quot;line&quot;: 58, &quot;column&quot;: 11 }, &quot;end&quot;: { &quot;line&quot;: 58, &quot;column&quot;: 83 } } ], &quot;line&quot;: 56 } }, &quot;s&quot;: { &quot;0&quot;: 1, &quot;1&quot;: 1, &quot;2&quot;: 3, &quot;3&quot;: 1, &quot;4&quot;: 1, &quot;5&quot;: 1, &quot;6&quot;: 2, &quot;7&quot;: 2, &quot;8&quot;: 2, &quot;9&quot;: 2, &quot;10&quot;: 2, &quot;11&quot;: 1, &quot;12&quot;: 0, &quot;13&quot;: 0, &quot;14&quot;: 0, &quot;15&quot;: 1, &quot;16&quot;: 0, &quot;17&quot;: 0, &quot;18&quot;: 0, &quot;19&quot;: 1, &quot;20&quot;: 0, &quot;21&quot;: 0, &quot;22&quot;: 0, &quot;23&quot;: 1, &quot;24&quot;: 0, &quot;25&quot;: 0, &quot;26&quot;: 0, &quot;27&quot;: 1, &quot;28&quot;: 1 }, &quot;f&quot;: { &quot;0&quot;: 3, &quot;1&quot;: 1, &quot;2&quot;: 2, &quot;3&quot;: 2, &quot;4&quot;: 0, &quot;5&quot;: 0, &quot;6&quot;: 0, &quot;7&quot;: 0, &quot;8&quot;: 0, &quot;9&quot;: 0, &quot;10&quot;: 0, &quot;11&quot;: 0 }, &quot;b&quot;: { &quot;0&quot;: [ 2, 2 ], &quot;1&quot;: [ 0, 0 ], &quot;2&quot;: [ 0, 0, 0 ] }, &quot;_coverageSchema&quot;: &quot;43e27e138ebf9cfc5966b082cf9a028302ed4184&quot;, &quot;hash&quot;: &quot;10f0fa1c62aa45ebf8b01b6b9699523be107bb2b&quot; } } }</div> <div class="d-none" id="test-global-config">{ &quot;bail&quot;: 0, &quot;changedFilesWithAncestor&quot;: false, &quot;collectCoverage&quot;: true, &quot;collectCoverageFrom&quot;: [ &quot;**&#x2F;*.js&quot;, &quot;!**&#x2F;node_modules&#x2F;**&quot;, &quot;!**&#x2F;vendor&#x2F;**&quot;, &quot;!**&#x2F;test_output&#x2F;**&quot; ], &quot;coverageDirectory&quot;: &quot;&#x2F;Users&#x2F;habuma&#x2F;starflyer-travel&#x2F;test_output&#x2F;coverage&quot;, &quot;coverageReporters&quot;: [ &quot;json&quot;, &quot;text&quot;, &quot;lcov&quot;, &quot;clover&quot; ], &quot;coverageThreshold&quot;: null, &quot;errorOnDeprecated&quot;: false, &quot;expand&quot;: false, &quot;filter&quot;: null, &quot;globalSetup&quot;: null, &quot;globalTeardown&quot;: null, &quot;json&quot;: false, &quot;maxConcurrency&quot;: 5, &quot;maxWorkers&quot;: 1, &quot;noStackTrace&quot;: false, &quot;notify&quot;: false, &quot;notifyMode&quot;: &quot;failure-change&quot;, &quot;projects&quot;: null, &quot;reporters&quot;: [ [ &quot;default&quot;, {} ], [ &quot;&#x2F;usr&#x2F;local&#x2F;lib&#x2F;node_modules&#x2F;bespoken-tools&#x2F;node_modules&#x2F;jest-stare&#x2F;lib&#x2F;index.js&quot;, {} ] ], &quot;rootDir&quot;: &quot;&#x2F;Users&#x2F;habuma&#x2F;starflyer-travel&quot;, &quot;runTestsByPath&quot;: false, &quot;silent&quot;: true, &quot;skipFilter&quot;: false, &quot;testFailureExitCode&quot;: 1, &quot;testPathPattern&quot;: &quot;&quot;, &quot;testResultsProcessor&quot;: null, &quot;testSequencer&quot;: &quot;&#x2F;usr&#x2F;local&#x2F;lib&#x2F;node_modules&#x2F;bespoken-tools&#x2F;node_modules&#x2F;@jest&#x2F;test-sequencer&#x2F;build&#x2F;index.js&quot;, &quot;updateSnapshot&quot;: &quot;new&quot;, &quot;useStderr&quot;: false, &quot;verbose&quot;: true, &quot;watch&quot;: false, &quot;watchman&quot;: true }</div> </main> <hr> <footer class="footer"> <div class="container"> <span class="text-muted">&copy; jest-stare 2019</span> </div> </footer> </body> </html> <|start_filename|>uberconf-2020/uber-books/src/main/java/habuma/BooksController.java<|end_filename|> package habuma; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import lombok.RequiredArgsConstructor; @RestController @RequestMapping("/books") @RequiredArgsConstructor public class BooksController { private final BookRepository bookRepo; // private final MeterRegistry registry; @GetMapping public Iterable<Book> allBooks() { // registry.counter("uberbooks", "greeting", "allBooks").increment(); return bookRepo.findAll(); } @PostMapping public Book saveABook(@RequestBody Book book) { System.out.println("SAVING A BOOK"); return bookRepo.save(book); } } <|start_filename|>MSP-Mar-2020/reactive-tacos/src/main/java/habuma/tacos/HelloController.java<|end_filename|> package habuma.tacos; import java.time.Duration; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import lombok.Data; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; @RestController public class HelloController { @GetMapping("/hello") public Mono<String> hello() { return Mono.just("Hello"); } @PostMapping(path="/hi") public Mono<String> hi(@RequestBody Mono<Who> who) { return who .map(w -> "Hi, " + w.getName()); } @GetMapping("/counter") public Flux<Long> counter() { return Flux.interval(Duration.ofSeconds(1)); } @Data public static class Who { private String name; } } <|start_filename|>DFW-June-2019/dfw-profiles/src/main/java/com/example/demo/SecurityConfig.java<|end_filename|> package com.example.demo; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; @Configuration //@EnableGlobalMethodSecurity(prePostEnabled = true) public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .formLogin() .and() .authorizeRequests() .antMatchers("/home").access("hasRole('ROLE_ADMIN')"); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth .inMemoryAuthentication() .withUser("habuma").password(passwordEncoder().encode("password")).roles("ADMIN", "USER") .and() .withUser("venkat").password(passwordEncoder().encode("password")).roles("USER"); } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } } <|start_filename|>VIRTUAL-Oct-2020/nfjs-reactive-books/src/main/java/habuma/BookController.java<|end_filename|> package habuma; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import lombok.RequiredArgsConstructor; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; @RestController @RequestMapping("/books") @RequiredArgsConstructor public class BookController { final BookRepository repo; @GetMapping public Flux<Book> allBooks() { return repo.findAll(); } @GetMapping("/{id}") public Mono<Book> byId(@PathVariable("id") String id) { return repo.findById(id); } @PostMapping public Mono<Book> save(@RequestBody Book book) { return repo.save(book); } } <|start_filename|>VIRTUAL-Nov-2020/nfjs-books/src/test/java/habuma/BookWebTests.java<|end_filename|> package habuma; import static org.assertj.core.api.Assertions.assertThat; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.boot.web.server.LocalServerPort; @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) public class BookWebTests { @LocalServerPort int port; @Autowired TestRestTemplate rest; @Autowired BookRepository bookRepo; @BeforeEach public void setup() { bookRepo.save(new Book("1234567890", "Test Book", "Test Author")); bookRepo.save(new Book("9876543210", "Test Book 2", "Test Author 2")); } @AfterEach public void cleared() { bookRepo.deleteAll(); } @Test public void findById() { Book foundBook = rest.getForObject("/books/{id}", Book.class, 1); assertThat(foundBook.getIsbn()).isEqualTo("1234567890"); assertThat(foundBook.getTitle()).isEqualTo("Test Book"); assertThat(foundBook.getAuthor()).isEqualTo("Test Author"); Book foundBook2 = rest.getForObject("/books/{id}", Book.class, 2); assertThat(foundBook2.getIsbn()).isEqualTo("9876543210"); assertThat(foundBook2.getTitle()).isEqualTo("Test Book 2"); assertThat(foundBook2.getAuthor()).isEqualTo("Test Author 2"); } @Test public void findByIsbn() { Book foundBook = rest.getForObject("/books/isbn/{isbn}", Book.class, "1234567890"); assertThat(foundBook.getIsbn()).isEqualTo("1234567890"); assertThat(foundBook.getTitle()).isEqualTo("Test Book"); assertThat(foundBook.getAuthor()).isEqualTo("Test Author"); } } <|start_filename|>MSP-Mar-2020/tacos/src/main/java/habuma/tacos/TacoRepository.java<|end_filename|> package habuma.tacos; import org.springframework.data.repository.CrudRepository; public interface TacoRepository extends CrudRepository<Taco, Long> { Iterable<Taco> findByWrap(String wrap); } <|start_filename|>MSP-Mar-2020/testing-books/src/test/java/habuma/tacos/BookRepositoryTests.java<|end_filename|> package habuma.tacos; import static org.assertj.core.api.Assertions.assertThat; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; @DataJpaTest(showSql = true) public class BookRepositoryTests { @Autowired BookRepository repo; @BeforeEach public void saveABook() { Book savedBook = repo.save(new Book("1234567890", "Test Book", "Test Author")); assertThat(savedBook.getId()).isNotNull(); assertThat(savedBook.getIsbn()).isEqualTo("1234567890"); assertThat(savedBook.getTitle()).isEqualTo("Test Book"); assertThat(savedBook.getAuthor()).isEqualTo("Test Author"); } @Test public void fetchABook() { Book foundByIsbn = repo.findByIsbn("1234567890"); assertThat(foundByIsbn.getId()).isNotNull(); assertThat(foundByIsbn.getIsbn()).isEqualTo("1234567890"); assertThat(foundByIsbn.getTitle()).isEqualTo("Test Book"); assertThat(foundByIsbn.getAuthor()).isEqualTo("Test Author"); } } <|start_filename|>MSP-Mar-2020/tacos/src/main/java/habuma/tacos/TacoApiController.java<|end_filename|> package habuma.tacos; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import lombok.RequiredArgsConstructor; @RestController @RequestMapping("/api/tacos") @RequiredArgsConstructor public class TacoApiController { private final TacoRepository tacoRepo; @GetMapping public Iterable<Taco> tacos() { return tacoRepo.findAll(); } @PostMapping public Taco saveATaco(@RequestBody Taco taco) { return tacoRepo.save(taco); } } <|start_filename|>SEA-Nov-2019/sea-books/src/main/java/com/example/demo/BooksRepository.java<|end_filename|> package com.example.demo; import org.springframework.data.jdbc.repository.query.Query; import org.springframework.data.repository.CrudRepository; public interface BooksRepository extends CrudRepository<Book, Long> { @Query("select id, isbn, title, author from Book where isbn=:isbn") Book findByIsbn(String isbn); } <|start_filename|>VIRTUAL-Sept-2020/nfjs-books/src/main/java/habuma/HelloController.java<|end_filename|> package habuma; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import io.micrometer.core.instrument.MeterRegistry; @Controller public class HelloController { private GreetingProps props; private MeterRegistry registry; public HelloController(GreetingProps props, MeterRegistry registry) { this.props = props; this.registry = registry; } @GetMapping("/hello") public String hello(Model model) { registry.counter("nfjs-books", "hello", "count").increment(); System.out.println("HI"); model.addAttribute("message", props.getMessage()); return "hello-view"; } } <|start_filename|>VIRTUAL-Jul-2021/message-driven-beans/itinerary-scheduler/src/main/java/habuma/ItinerarySchedulerSinkApplication.java<|end_filename|> package habuma; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.amqp.rabbit.annotation.RabbitListener; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class ItinerarySchedulerSinkApplication { private static Logger log = LoggerFactory.getLogger(ItinerarySchedulerSinkApplication.class); public static void main(String[] args) { SpringApplication.run(ItinerarySchedulerSinkApplication.class, args); } @RabbitListener(queues = "itineraries") public void scheduleItinerary(Itinerary itinerary) { log.info("SCHEDULING ITINERARY: " + itinerary); } } <|start_filename|>uberconf-2020/uber-books/src/main/java/habuma/HelloController.java<|end_filename|> package habuma; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import lombok.extern.slf4j.Slf4j; @Controller @Slf4j public class HelloController { @Autowired GreetingProps props; // @Autowired // MeterRegistry registry; @GetMapping("/hello") public String hello() { log.debug("GREETING IS: " + props.getMessage()); // registry.counter("uberbooks", "greeting", "hello").increment(); return "greeting"; } } <|start_filename|>VIRTUAL-Jul-2021/solver-integration/logger/src/main/java/com/example/demo/LoggerApplication.java<|end_filename|> package com.example.demo; import org.springframework.amqp.core.AmqpTemplate; import org.springframework.amqp.rabbit.connection.ConnectionFactory; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.integration.amqp.inbound.AmqpMessageSource; import org.springframework.integration.dsl.IntegrationFlow; import org.springframework.integration.dsl.IntegrationFlows; import org.springframework.integration.dsl.Pollers; import lombok.extern.slf4j.Slf4j; @SpringBootApplication @Slf4j public class LoggerApplication { public static void main(String[] args) { SpringApplication.run(LoggerApplication.class, args); } @Bean public IntegrationFlow flow(ConnectionFactory connectionFactory, AmqpTemplate amqpTemplate) { return IntegrationFlows .from(new AmqpMessageSource(connectionFactory, "solutions"), c->c.poller(Pollers.fixedRate(1000))) .handle(message -> { log.info("INTEGRATION LOGGER GOT A SOLUTION: " + message.getPayload()); }) .get(); } } <|start_filename|>EventDrivenSpring-Workshop-Dec-2020/emitter/src/main/java/com/example/demo/EmitterController.java<|end_filename|> package com.example.demo; import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; @RestController public class EmitterController { private final RabbitTemplate rabbit; public EmitterController(RabbitTemplate rabbit) { this.rabbit = rabbit; } @PostMapping("/quad") public Equation handle(@RequestBody Equation equation) { // Change this to "equations.quadratic" for the // Spring Cloud Streams example String queueName = "equations"; rabbit.convertAndSend(queueName, equation); return equation; } } <|start_filename|>CMH-June-2019/books-cmh/src/main/java/habuma/BooksRepository.java<|end_filename|> package habuma; import org.springframework.data.repository.CrudRepository; import org.springframework.data.rest.core.annotation.RestResource; public interface BooksRepository extends CrudRepository<Book, Long> { SimpleBook findSimpleById(Long id); Book findByIsbn(String isbn); Iterable<Book> findByAuthorLastName(String a); @RestResource(exported = false) @Override void delete(Book entity); @RestResource(exported = false) @Override void deleteAll(); @RestResource(exported = false) @Override void deleteById(Long id); @RestResource(exported = false) @Override void deleteAll(Iterable<? extends Book> entities); } <|start_filename|>MSP-Mar-2020/reactive-tacos/src/main/java/habuma/tacos/TacoController.java<|end_filename|> package habuma.tacos; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import lombok.RequiredArgsConstructor; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; @RestController @RequestMapping("/tacos") @RequiredArgsConstructor public class TacoController { private final TacoRepository repo; @GetMapping public Flux<Taco> allTacos() { return repo.findAll(); } @GetMapping(path="/bywrap", params="wrap", produces="application/stream+json") public Flux<Taco> byWrap(@RequestParam("wrap") String wrap) { return repo.findByWrap(wrap) .map(taco -> { Taco responseTaco = new Taco(taco.getName().toUpperCase(), taco.getWrap(), taco.getFilling()); responseTaco.setId(taco.getId()); return responseTaco; }); } @PostMapping public Mono<Taco> saveTaco(@RequestBody Mono<Taco> tacoMono) { return tacoMono .flatMap(taco -> { return repo.save(taco); }); } } <|start_filename|>STL-Apr-2018/src/main/java/habuma/CustomBookProcessor.java<|end_filename|> package habuma; import org.springframework.hateoas.EntityLinks; import org.springframework.hateoas.Resource; import org.springframework.hateoas.ResourceProcessor; import org.springframework.stereotype.Component; import lombok.NonNull; import lombok.RequiredArgsConstructor; @Component @RequiredArgsConstructor public class CustomBookProcessor implements ResourceProcessor<Resource<Book>> { private final @NonNull EntityLinks entityLinks; @Override public Resource<Book> process(Resource<Book> resource) { Book book = resource.getContent(); if(book.getTitle().contains("Camel")) { resource.add( entityLinks .linkForSingleResource(Book.class, book.getIsbn()) .slash("BUY") .slash("NOW") .withRel("BUY_THIS_BOOK") ); } return resource; } } <|start_filename|>MSN-Feb-2020/testing-books/src/main/java/habuma/TestingBooksApplication.java<|end_filename|> package habuma; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class TestingBooksApplication { public static void main(String[] args) { SpringApplication.run(TestingBooksApplication.class, args); } } <|start_filename|>STL-Apr-2019/spring-boot/books/src/main/java/habuma/books/DemoInfoContributor.java<|end_filename|> package habuma.books; import org.springframework.boot.actuate.info.Info.Builder; import org.springframework.boot.actuate.info.InfoContributor; import org.springframework.stereotype.Component; @Component public class DemoInfoContributor implements InfoContributor { @Override public void contribute(Builder builder) { builder.withDetail("session-name", "Spring Boot Actuator") .withDetail("time", System.currentTimeMillis()); } } <|start_filename|>SpringBoot-Workshop-May-2021/books/src/main/java/books/BookRepository.java<|end_filename|> package books; import org.springframework.data.repository.CrudRepository; public interface BookRepository extends CrudRepository<Book, Long>{ Iterable<Book> findByAuthor(String author); } <|start_filename|>BOS-Sept-2019/books-bos/src/main/java/habuma/BooksController.java<|end_filename|> package habuma; import java.util.Optional; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import lombok.RequiredArgsConstructor; @RestController @RequestMapping("/books") @RequiredArgsConstructor public class BooksController { private final BooksRepository bookRepo; @GetMapping public Iterable<Book> allBooks() { return bookRepo.findAll(); } @GetMapping("/{id}") public Optional<Book> bookById(@PathVariable("id") Long id){ return bookRepo.findById(id); } @PostMapping public Book saveABook(@RequestBody Book book) { return bookRepo.save(book); } } <|start_filename|>SEA-Nov-2019/sea-books/src/main/java/com/example/demo/SeaBooksGoodApplication.java<|end_filename|> package com.example.demo; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; @SpringBootApplication public class SeaBooksGoodApplication { public static void main(String[] args) { SpringApplication.run(SeaBooksGoodApplication.class, args); } @Bean public CommandLineRunner startup() { return args -> { System.out.println("HELLO!"); }; } } <|start_filename|>MSN-Feb-2020/testing-books/src/main/java/habuma/Bottle.java<|end_filename|> package habuma; import org.springframework.stereotype.Component; import lombok.AllArgsConstructor; import lombok.Data; @Data @Component @AllArgsConstructor public class Bottle { private Rum rum; } <|start_filename|>uberconf-2020/uber-books/src/test/java/habuma/HelloWebTest.java<|end_filename|> package habuma; import static org.assertj.core.api.Assertions.assertThat; import java.net.URI; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.RequestEntity; @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) public class HelloWebTest { @Autowired TestRestTemplate rest; @Test public void saysHelloToGetRequest() { HttpHeaders headers = new HttpHeaders(); headers.setBasicAuth("habuma", "password"); RequestEntity<Void> requestEntity = new RequestEntity<Void>(headers, HttpMethod.GET, URI.create("/hellorest")); String response = rest.exchange(requestEntity, String.class).getBody(); assertThat(response).isEqualTo("Hello world!"); } // // Post-session TODO: I still need to fix this test...will look at it later. // // @Test public void saveABook() { Book bookToSave = new Book("1234567890", "Fake Book", "<NAME>"); HttpHeaders headers = new HttpHeaders(); headers.setBasicAuth("habuma", "password"); RequestEntity<Book> requestEntity = new RequestEntity<Book>(bookToSave, headers, HttpMethod.POST, URI.create("/books")); Book savedBook = rest.exchange(requestEntity, Book.class).getBody(); assertThat(savedBook.getId()).isNotNull(); } } <|start_filename|>K8s-Workshop-Nov-2020/hello-service/src/main/java/habuma/HelloController.java<|end_filename|> package habuma; import org.springframework.boot.availability.AvailabilityChangeEvent; import org.springframework.boot.availability.LivenessState; import org.springframework.context.ApplicationContext; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class HelloController { private final GreetingProps props; private ApplicationContext context; public HelloController(GreetingProps props, ApplicationContext context) { this.props = props; this.context = context; } @GetMapping("/hello") public String hello() { return props.getMessage(); } @GetMapping("/goodbye") public String bye() { AvailabilityChangeEvent.publish(context, LivenessState.BROKEN); return "Bye bye"; } } <|start_filename|>MSN-Feb-2020/testing-books/src/main/java/habuma/Rum.java<|end_filename|> package habuma; import org.springframework.stereotype.Component; @Component public class Rum { public String getBrand() { return "Bacardi"; } } <|start_filename|>ArchConf-2020/event-driven-spring/integration-equation-solver/src/main/java/com/example/demo/Solution.java<|end_filename|> package com.example.demo; import java.io.Serializable; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @AllArgsConstructor @NoArgsConstructor public class Solution implements Serializable { private static final long serialVersionUID = 1L; private double x1; private double x2; } <|start_filename|>AUS-July-2018/src/main/java/habuma/DataLoaderConfig.java<|end_filename|> package habuma; import org.springframework.boot.CommandLineRunner; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class DataLoaderConfig { @Bean public CommandLineRunner loadData(BookRepository repo) { return args -> { repo.save(new Book("1234567890", "Knitting with Dog Hair", "<NAME>")); repo.save(new Book("9876543210", "Crafting with Cat Hair", "Kaori Tsutaya")); }; } } <|start_filename|>VIRTUAL-Nov-2020/nfjs-books/src/main/java/habuma/HelloEndpoint.java<|end_filename|> package habuma; import org.springframework.boot.actuate.endpoint.annotation.Endpoint; import org.springframework.boot.actuate.endpoint.annotation.ReadOperation; import org.springframework.stereotype.Component; @Component @Endpoint(id = "hello", enableByDefault = true) public class HelloEndpoint { @ReadOperation public String hello() { return "Hello from the actuator"; } } <|start_filename|>BOS-Sept-2021/nfjs-books/src/main/java/habuma/HowdyController.java<|end_filename|> package habuma; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ResponseBody; @Controller public class HowdyController { @GetMapping("/howdy") public String howdy(Model model) { model.addAttribute("message", "How<NAME>!"); return "howdy-view"; } @GetMapping("/bye") @ResponseBody public String bye() { return "Goodbye"; } } <|start_filename|>MSP-Mar-2020/tacos/src/main/java/habuma/tacos/TacosApplication.java<|end_filename|> package habuma.tacos; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; @SpringBootApplication public class TacosApplication { public static void main(String[] args) { SpringApplication.run(TacosApplication.class, args); } @Bean public CommandLineRunner dataLoader(TacoRepository repo) { return args -> { repo.save(new Taco("Democrat", "Corn Tortilla", "Barbacoa")); repo.save(new Taco("Trailer Park", "Flour Tortilla", "Fried Chicken")); repo.save(new Taco("Tipsy Chick", "Flour Tortilla", "Bourbon glazed chicken")); }; } } <|start_filename|>MSN-Feb-2020/msn-books/src/main/java/habuma/HelloController.java<|end_filename|> package habuma; import java.util.Arrays; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import io.micrometer.core.instrument.MeterRegistry; import lombok.extern.slf4j.Slf4j; @RestController @Slf4j public class HelloController { @Autowired MeterRegistry meterRegistry; @GetMapping("/hello") public String hello() throws Exception { meterRegistry.counter("habuma", "hello", "count").increment(); // for(int i=0;i<60;i++) { // log.debug("SLEEPING: " + i); // Thread.sleep(1000L); // } return "Hello world!"; } } <|start_filename|>ORD-Nov-2018/ord-books/src/main/java/habuma/BookRepoExtras.java<|end_filename|> package habuma; public interface BookRepoExtras { void doSomethingCompletelyDifferent(); } <|start_filename|>BOS-Sept-2019/books-data-bos/src/main/java/habuma/BooksRepository.java<|end_filename|> package habuma; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; public interface BooksRepository extends CrudRepository<Book, Long>{ Book findByIsbn(String isbn); SimpleBook findSimpleByIsbn(String isbn); @Query("from Book b where b.authorFirstName='Kendall'") Iterable<Book> findKendallsBooks(); } <|start_filename|>EventDrivenSpring-Workshop-Dec-2020/templates/logger/src/main/java/com/example/demo/LoggerApplication.java<|end_filename|> package com.example.demo; import java.util.Optional; import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.ApplicationRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import lombok.extern.slf4j.Slf4j; @SpringBootApplication @Slf4j public class LoggerApplication { public static void main(String[] args) { SpringApplication.run(LoggerApplication.class, args); } @Autowired RabbitTemplate rabbit; private Optional<Solution> receiveSolution() { Solution solution = (Solution) rabbit.receiveAndConvert("solutions", -1); return Optional.of(solution); } @Bean public ApplicationRunner appRunner() { return args -> { while(true) { Optional<Solution> optionalSolution = receiveSolution(); optionalSolution.ifPresent(solution -> { log.info("LOGGER GOT A SOLUTION: " + solution); }); } }; } } <|start_filename|>EventDrivenSpring-Workshop-Apr-2021/scs-trip-source/src/main/java/habuma/ScsTripSourceApplication.java<|end_filename|> package habuma; import java.util.Date; import java.util.function.Supplier; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import habuma.Itinerary.Destination; @SpringBootApplication public class ScsTripSourceApplication { private static final Logger log = LoggerFactory.getLogger(ScsTripSourceApplication.class); public static void main(String[] args) { SpringApplication.run(ScsTripSourceApplication.class, args); } @Bean public Supplier<TripBooking> sendTrip() { return () -> { TripBooking trip = new TripBooking(); trip.setTravelerName("<NAME>"); trip.setPaymentCardNumber("4111111111111111"); Itinerary itinerary = new Itinerary(); itinerary.setDestination(Destination.MARS); itinerary.setStartDate(new Date()); itinerary.setEndDate(new Date()); trip.setItinerary(itinerary); log.info("SENDING TRIP: " + trip.getTravelerName()); return trip; }; } } <|start_filename|>VIRTUAL-Jul-2021/trip-domain/src/main/java/habuma/Itinerary.java<|end_filename|> package habuma; import java.io.Serializable; import java.util.Date; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @AllArgsConstructor @NoArgsConstructor public class Itinerary implements Serializable { private static final long serialVersionUID = 1L; private Destination destination; private Date startDate; private Date returnDate; public static enum Destination { MERCURY, VENUS, MARS, JUPITER, SATURN, URANUS, NEPTUNE, PLUTO } } <|start_filename|>IAD-Apr-2019/spring-data-rest/src/main/java/habuma/Book.java<|end_filename|> package habuma; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToOne; import com.fasterxml.jackson.annotation.JsonIgnore; import lombok.AccessLevel; import lombok.Data; import lombok.NoArgsConstructor; import lombok.RequiredArgsConstructor; @Entity @Data @RequiredArgsConstructor @NoArgsConstructor(access=AccessLevel.PRIVATE, force=true) public class Book { @Id @GeneratedValue(strategy=GenerationType.AUTO) private Long id; private final String isbn; private final String title; @ManyToOne private final Publisher publisher; @ManyToOne @JsonIgnore private final Author author; private final Integer pages; } <|start_filename|>STL-Apr-2018/src/main/java/habuma/BookServiceImpl.java<|end_filename|> package habuma; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Service; import org.springframework.web.bind.annotation.GetMapping; import lombok.RequiredArgsConstructor; @Service @RequiredArgsConstructor public class BookServiceImpl { private final BookRepository repo; @GetMapping @PreAuthorize("hasRole('ROLE_USER')") public Iterable<Book> allBooks() { return repo.findAll(); } } <|start_filename|>STL-Apr-2019/spring-boot/books/src/main/java/habuma/books/BookRepository.java<|end_filename|> package habuma.books; import org.springframework.data.repository.CrudRepository; public interface BookRepository extends CrudRepository<Book, Long> { Book findByIsbn(String isbn); } <|start_filename|>ORD-Nov-2018/ord-books/src/main/java/habuma/HiController.java<|end_filename|> package habuma; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import io.micrometer.core.instrument.MeterRegistry; import lombok.RequiredArgsConstructor; @RestController @RequiredArgsConstructor public class HiController { private final GreetingProps props; private final MeterRegistry metrics; @GetMapping("/") public String hi() { metrics.counter("greeting.message", "hello", "count").increment(); return props.getMessage(); } } <|start_filename|>ORD-Oct-2019/books-ord/src/test/java/com/example/demo/SdJdbcApplicationTests.java<|end_filename|> package com.example.demo; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.ActiveProfiles; @SpringBootTest @ActiveProfiles(profiles = "ord") class SdJdbcApplicationTests { @Autowired GreetingProps props; @Test void contextLoads() { } @Test void greetingIsSet() { Assertions.assertNotNull(props.getMessage()); Assertions.assertEquals("Hello, Chicago!", props.getMessage()); } } <|start_filename|>ArchConf-2020/event-driven-spring/equation-emitter/src/main/java/com/example/demo/QuadraticController.java<|end_filename|> package com.example.demo; import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import lombok.RequiredArgsConstructor; @RestController @RequiredArgsConstructor public class QuadraticController { private final RabbitTemplate rabbit; @PostMapping("/quad") public Equation postEquation(@RequestBody Equation equation) { rabbit.convertAndSend("equations.quadratic", equation); return equation; } } <|start_filename|>uberconf-2019/spring-boot/uber-books-2/src/main/java/habuma/BooksRepository.java<|end_filename|> package habuma; import org.springframework.data.mongodb.repository.Query; import org.springframework.data.repository.CrudRepository; public interface BooksRepository extends CrudRepository<Book, String> { Book findByIsbn(String isbn); @Query("{'author':'<NAME>'}") Iterable<Book> kendallsBooks(); void doSomething(); } <|start_filename|>IAD-Apr-2019/spring-data-rest/src/main/java/habuma/SimpleBook.java<|end_filename|> package habuma; import org.springframework.data.rest.core.config.Projection; @Projection(name = "simple", types = Book.class) public interface SimpleBook { String getIsbn(); String getTitle(); } <|start_filename|>uberconf-2021/boot-workshop/uber-books/src/main/java/habuma/BookRepository.java<|end_filename|> package habuma; import org.springframework.data.repository.CrudRepository; public interface BookRepository extends CrudRepository<Book, Long> { Iterable<Book> findByAuthor(String author); Iterable<Book> findByAuthorAndTitleLike(String author, String tl); } <|start_filename|>BOS-Sept-2018-2/src/main/java/habuma/BookRepoExtras.java<|end_filename|> package habuma; public interface BookRepoExtras { void doSomethingDifferent(); } <|start_filename|>BOS-Sept-2018-2/src/main/java/habuma/RandomHealthIndicator.java<|end_filename|> package habuma; import org.springframework.boot.actuate.health.Health; import org.springframework.boot.actuate.health.HealthIndicator; import org.springframework.stereotype.Component; @Component public class RandomHealthIndicator implements HealthIndicator { @Override public Health health() { double r = Math.random(); if (r > 0.5) { // up return Health.up() .withDetail("reason", "The number is big enough: " + r) .withDetail("other", "Hi there") .build(); } else { // down return Health.down() .withDetail("reason", "The number is too small: " + r) .build(); } } } <|start_filename|>STL-Apr-2019/spring-boot/books/src/main/java/habuma/books/GreetingProps.java<|end_filename|> package habuma.books; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; import lombok.Data; @Component @ConfigurationProperties(prefix="greeting") @Data public class GreetingProps { private String message = "Hello world"; } <|start_filename|>uberconf-2020/uber-books/src/main/java/habuma/SecurityConfig.java<|end_filename|> package habuma; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth .inMemoryAuthentication() .withUser("habuma").password(passwordEncoder().encode("password")).roles("USER", "ADMIN").and() .withUser("mickey").password(passwordEncoder().encode("password")).roles("USER"); } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } } <|start_filename|>MSP-Mar-2020/mini-quest/abcConfig.json<|end_filename|> { "prod": {}, "beta": {}, "alpha": {}, "dev": {}, "prod-en-us": {}, "beta-en-us": {}, "alpha-en-us": {}, "dev-en-us": {}, "en-us": {}, "en-gb": {}, "default": { "ask-profile-name": "default", "aws-profile-name": "default", "skill-invocation-name": "mini quest", "dynamo-db-session-table-name": "mini-quest-2-sessions", "s3-domain-name": "s3.amazonaws.com", "s3-bucket-name": "alexa-ml", "ask-skill-directory-name": "mini-quest-2", "publish-locales": [ "en-US" ], "update-string-with-source": true, "story-title": "mini quest 2", "story-id": "mini-quest-2", "abc-baked-filename": "baked_story.json", "abc-recording-script-filename": "vo_script.txt", "public-resource-folders": ["audio", "images", "vo"], "polly-config": { "enabled": false, "combineAudioTags": true, "dontUseCache": false, "engine": "standard" }, "default-narrator": { "enabled": false, "name": "Matthew", "pitch": "+10%", "rate": "112%", "volume": "1.0" }, "snippet-map-filename": "Snippets.json", "apl-templates-filename": "apl-templates.json", "custom-slottype-filename": "SlotTypes.json", "isp-config-filename": "ProductISPs.json" } } <|start_filename|>VIRTUAL-Jan-2021/gateway/streamer/src/main/java/com/example/demo/CountEntry.java<|end_filename|> package com.example.demo; public class CountEntry { private Long value; public CountEntry(Long value) { this.value = value; } public Long getValue() { return value; } public void setValue(Long value) { this.value = value; } } <|start_filename|>VIRTUAL-Jul-2021/spring-books/src/main/java/books/HelloController.java<|end_filename|> package books; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; @Controller public class HelloController { GreetingProps props; public HelloController(GreetingProps props) { this.props = props; } @GetMapping(path="/hello") public String hello(Model model) { model.addAttribute("greeting", props.getMessage()); return "hellopage"; } } <|start_filename|>VIRTUAL-Sept-2020/reactive-books/src/main/java/habuma/SecurityConfig.java<|end_filename|> package habuma; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity; import org.springframework.security.config.web.server.ServerHttpSecurity; import org.springframework.security.core.userdetails.MapReactiveUserDetailsService; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.server.SecurityWebFilterChain; @Configuration @EnableWebFluxSecurity public class SecurityConfig { @Bean public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) { return http .authorizeExchange() .pathMatchers("/books").authenticated() .anyExchange().permitAll() .and() .build(); } @Bean public MapReactiveUserDetailsService userDetailsService() { UserDetails user = User .withUsername("habuma") .password(passwordEncoder().encode("password")) .authorities("ROLE_USER") .build(); return new MapReactiveUserDetailsService(user); } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } } <|start_filename|>VIRTUAL-Sept-2020/nfjs-books/src/main/java/habuma/GoodbyeEndpoint.java<|end_filename|> package habuma; import org.springframework.boot.actuate.endpoint.annotation.Endpoint; import org.springframework.boot.actuate.endpoint.annotation.ReadOperation; import org.springframework.stereotype.Component; @Component @Endpoint(id="goodbye") public class GoodbyeEndpoint { @ReadOperation public String goodbye() { return "Goodbye and thanks for attending my session"; } } <|start_filename|>uberconf-2021/spring-data/uber-book-jdbc/src/main/java/com/example/demo/BookRepository.java<|end_filename|> package com.example.demo; import org.springframework.data.jdbc.repository.query.Query; import org.springframework.data.repository.CrudRepository; public interface BookRepository extends CrudRepository<Book, Long> { Iterable<Book> findByAuthor(String author); @Query("select id, isbn, title, author from Book where author='<NAME>'") Iterable<Book> findKendallsBooks(); } <|start_filename|>uberconf-2020/uber-books/src/test/java/habuma/HelloRestTest.java<|end_filename|> package habuma; import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document; import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.documentationConfiguration; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.http.MediaType; import org.springframework.restdocs.RestDocumentationContextProvider; import org.springframework.restdocs.RestDocumentationExtension; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.security.web.FilterChainProxy; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; @WebMvcTest(controllers = { HelloRestController.class, BooksController.class}) @ExtendWith(RestDocumentationExtension.class) public class HelloRestTest { @MockBean BookRepository bookRepo; @Autowired MockMvc mockMvc; @Autowired WebApplicationContext context; // // Post-session fixes: To fix the @WithMockUser problem, see the items below // with comments that say "fixes-mock-user" // @BeforeEach public void setup(RestDocumentationContextProvider restDocumentation) { this.mockMvc = MockMvcBuilders.webAppContextSetup(context) .apply(documentationConfiguration(restDocumentation)) .apply(springSecurity()) // fixes-mock-user .build(); } @Test @WithMockUser(username="habuma", password="password", roles= {"USER"}) public void testHello() throws Exception { mockMvc.perform(get("/hellorest")) .andExpect(content().string("Hello world!")); } @Test @WithMockUser(username="habuma", password="password", roles= {"USER"}) public void testSaveBook() throws Exception { Book bookToSave = new Book("1234567890", "Test Book", "Test Smith"); Book savedBook = new Book("1234567890", "Test Book", "Test Smith"); savedBook.setId(1L); Mockito.when(bookRepo.save(bookToSave)) .thenReturn(savedBook); mockMvc.perform(post("/books") .with(csrf()) // fixes-mock-user .contentType(MediaType.APPLICATION_JSON) .content("{\"isbn\":\"1234567890\", \"title\":\"Test Book\", \"author\":\"<NAME>\"}")) .andExpect(jsonPath("id").value(1L)) .andExpect(jsonPath("isbn").value("1234567890")) .andDo(document("books")); } } <|start_filename|>ORD-Oct-2019/books-ord/src/main/java/com/example/demo/BooksRepository.java<|end_filename|> package com.example.demo; import org.springframework.data.repository.CrudRepository; public interface BooksRepository extends CrudRepository<Book, Long> { Iterable<Book> findByAuthorFirstName(String author); Iterable<SimplePublication> findSimpleByAuthorFirstName(String author); Book findByIsbn(String isbn); } <|start_filename|>uberconf-2021/spring-data/uber-book-mongodb/src/main/java/com/example/demo/BookRepository.java<|end_filename|> package com.example.demo; import org.springframework.data.mongodb.repository.Query; import org.springframework.data.repository.reactive.ReactiveCrudRepository; import reactor.core.publisher.Flux; public interface BookRepository extends ReactiveCrudRepository<Book, String> { Flux<Book> findByAuthor(String author); @Query("{author:'<NAME>'}") Flux<Book> findKendallsBooks(); } <|start_filename|>IAD-Nov-2018/iad-books/src/main/java/com/example/demo/MyInfoContributor.java<|end_filename|> package com.example.demo; import java.util.HashMap; import java.util.Map; import org.springframework.boot.actuate.info.Info.Builder; import org.springframework.boot.actuate.info.InfoContributor; import org.springframework.stereotype.Component; @Component public class MyInfoContributor implements InfoContributor { @Override public void contribute(Builder builder) { Map<String, Object> other = new HashMap<>(); other.put("A", "B"); other.put("C", "D"); builder .withDetail("time", System.currentTimeMillis()) .withDetail("other", other) .withDetails(other) .build(); } } <|start_filename|>SEA-Oct-2018/sea-books/src/main/java/habuma/DummyInfoContributor.java<|end_filename|> package habuma; import org.springframework.boot.actuate.info.Info.Builder; import org.springframework.boot.actuate.info.InfoContributor; import org.springframework.stereotype.Component; @Component public class DummyInfoContributor implements InfoContributor { @Override public void contribute(Builder builder) { builder .withDetail("foo", "BAR") .withDetail("xyz", "123") .build(); } } <|start_filename|>STL-Apr-2019/spring-boot/books/src/main/java/habuma/books/BooksApplication.java<|end_filename|> package habuma.books; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.scheduling.annotation.EnableScheduling; @SpringBootApplication @EnableScheduling public class BooksApplication { public static void main(String[] args) { SpringApplication.run(BooksApplication.class, args); } @Bean public CommandLineRunner dataLoader(BookRepository repo) { return args -> { repo.save(new Book("1234567890", "Knitting With Dog Hair", "<NAME>")); repo.save(new Book("9876543210", "Crafting With Cat Hair", "<NAME>")); repo.save(new Book("1928373650", "Spring in Action, Fifth Edition", "<NAME>")); }; } } <|start_filename|>uberconf-2019/spring-boot/uber-books-2/src/main/java/habuma/BooksRepositoryImpl.java<|end_filename|> package habuma; public class BooksRepositoryImpl { public void doSomething() { System.out.println("DOING SOMETHING"); } } <|start_filename|>MSP-Oct-2018/msp-books/src/main/java/habuma/JdbcBookRepository.java<|end_filename|> package habuma; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Repository; import lombok.RequiredArgsConstructor; @Repository @RequiredArgsConstructor public class JdbcBookRepository implements BookRepository { private final JdbcTemplate jdbc; @Override public Iterable<Book> findAll() { return jdbc.query("select isbn, title, author from Books", (rs, rowNum) -> { return new Book(rs.getString("isbn"), rs.getString("title"), rs.getString("author")); }); } } <|start_filename|>MSP-Oct-2019/boot-sessions/books-msp/src/main/java/habuma/GoodbyeController.java<|end_filename|> package habuma; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; @Controller public class GoodbyeController { @GetMapping("/goodbye") public String goodbye() { return "bye"; } } <|start_filename|>SLC-May-2019/slc-books/src/main/java/habuma/books/BooksController.java<|end_filename|> package habuma.books; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import io.micrometer.core.instrument.MeterRegistry; import lombok.RequiredArgsConstructor; @RestController @RequestMapping("/books") @RequiredArgsConstructor public class BooksController { private final BooksRepository repo; private final MeterRegistry registry; @GetMapping public Iterable<Book> allBooks() { registry.counter("habuma.books", "controller", "books").increment(); return repo.findAll(); } @PostMapping public Book saveBook(@RequestBody Book book) { return repo.save(book); } } <|start_filename|>ArchConf-2020/event-driven-spring/stream-solutions-logger/src/main/java/com/example/demo/StreamSolutionsLoggerApplication.java<|end_filename|> package com.example.demo; import java.util.function.Consumer; import java.util.function.Function; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import lombok.extern.slf4j.Slf4j; @SpringBootApplication @Slf4j public class StreamSolutionsLoggerApplication { public static void main(String[] args) { SpringApplication.run(StreamSolutionsLoggerApplication.class, args); } @Bean public Consumer<Solution> logSolution() { return solution -> { log.info("SOLUTION: " + solution); }; } } <|start_filename|>MSP-Mar-2020/testing-books/src/test/java/habuma/tacos/BookWebTests.java<|end_filename|> package habuma.tacos; import static org.assertj.core.api.Assertions.assertThat; import java.io.IOException; import java.net.URI; import java.nio.charset.Charset; import java.util.List; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.core.io.Resource; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.RequestEntity; import org.springframework.http.ResponseEntity; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.util.StreamUtils; @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) public class BookWebTests { @Value("classpath:/book.json") private Resource bookJson; @Autowired TestRestTemplate rest; @Autowired BookRepository repo; @Test public void testPostABook() throws Exception { assertThat(repo.count()).isEqualTo(0); String bookJson = getBookJsonAsString(); HttpHeaders headers = new HttpHeaders(); headers.setBasicAuth("habuma", "password"); headers.setContentType(MediaType.APPLICATION_JSON); RequestEntity<String> requestEntity = new RequestEntity<String>( bookJson, headers, HttpMethod.POST, URI.create("/books")); ResponseEntity<Book> exchange = rest.exchange(requestEntity, Book.class); Book savedBook = exchange.getBody(); assertThat(exchange.getStatusCode()).isEqualTo(HttpStatus.CREATED); assertThat(savedBook.getId()).isNotNull(); assertThat(savedBook.getIsbn()).isEqualTo("1234567890"); assertThat(savedBook.getTitle()).isEqualTo("Test Book"); assertThat(savedBook.getAuthor()).isEqualTo("Test Author"); List<Book> books = rest.getForObject("/books", List.class); assertThat(books.size()).isEqualTo(1); assertThat(repo.count()).isEqualTo(1); } private String getBookJsonAsString() throws IOException { return StreamUtils.copyToString(bookJson.getInputStream(), Charset.defaultCharset()); } } <|start_filename|>uberconf-2019/spring-boot/uber-books/src/main/java/habuma/BookRepository.java<|end_filename|> package habuma; import org.springframework.data.repository.CrudRepository; public interface BookRepository extends CrudRepository<Book, Long> { Book findByIsbn(String isbn); SimpleBook findSimpleByIsbn(String isbn); } <|start_filename|>uberconf-2020/reactive-uber-books/src/main/java/habuma/BookRepository.java<|end_filename|> package habuma; import org.springframework.data.repository.reactive.ReactiveCrudRepository; public interface BookRepository extends ReactiveCrudRepository<Book, String> { } <|start_filename|>MSP-Mar-2020/mini-quest/content/languageStrings.json<|end_filename|> { "en-US": { "translation": { "start.narration": "Welcome to mini-quest! If you are a brave adventurer, ready to face peril and seek treasure, say \"Let's go\"!", "utterance-go": "go", "utterance-venture on": "venture on", "at castle door.narration": "You are standing on the drawbridge of a rather tiny castle. To your left and right is a moat that surrounds the castle. Behind you is the safety of home. But if you go forward, you'll enter the castle. What do you want to do?", "utterance-go left": "go left", "utterance-go right": "go right", "utterance-left": "left", "utterance-right": "right", "utterance-jump in moat": "jump in moat", "utterance-go back": "go back", "utterance-go home": "go home", "utterance-run home": "run home", "utterance-run away": "run away", "utterance-enter castle": "enter castle", "utterance-enter": "enter", "utterance-go forward": "go forward", "eaten by alligators.narration": "Although the waters of the castle moat look like a great place to swim, you quickly find that they are filled with hungry alligators. Unfortunately, you are their meal.", "run away.narration": "As you turn to run home, the drawbridge crumbles below you. You fall into the alligator-infested waters of the castle moat and die.", "castle entryway.narration": "The castle entryway is dark and dusty, but there's just enough ambient light to make out what appears to be a wooden box.", "box is locked.narration": "The box is closed and wrapped in chains. You wonder what's inside. There is a parchment note attached.", "box is open.narration": "The box appears to be open.", "box is closed.narration": "The box is closed and there are chains on the floor around it. You wonder what's inside. There is a parchment note attached.", "read note.narration": "The note is scrawled clumsily, but you can make out the words \"Say 'open sesame'\". As you read the note, it crumbles into dust on the ground.", "box locked.narration": "The box is secured by a chain and an unusual lock. The lock has no slot for a key or means of entering a combination. You wonder how it might be opened. If only there were some instructions...", "open box.narration": "With the lock and chains gone, the box opens easily. Inside, you see a brilliant gemstone. It must be worth a fortune!", "lock disappears.narration": "Upon uttering the words \"open sesame\", the lock disintegrates and the chains fall off of the box.", "take gem.narration": "As you remove the gem from the box, it glows even brighter. You find yourself\n momentarily mesmerized by its brilliance, but gather your wits and put the gem\n into your pocket.\n\n You leave the castle and return home. You immediately seek out a gemologist to\n appraise your newfound treasure. It sells at market for a handsome price,\n enabling you to live comfortably for the remainder of your days." } } } <|start_filename|>MSP-Mar-2020/reactive-tacos/src/main/java/habuma/tacos/TacoRepository.java<|end_filename|> package habuma.tacos; import org.springframework.data.mongodb.repository.Tailable; import org.springframework.data.repository.reactive.ReactiveCrudRepository; import reactor.core.publisher.Flux; public interface TacoRepository extends ReactiveCrudRepository<Taco, String> { @Tailable Flux<Taco> findByWrap(String wrap); } <|start_filename|>ORD-Nov-2018/ord-books/src/main/java/habuma/MyInfoContributor.java<|end_filename|> package habuma; import org.springframework.boot.actuate.info.Info.Builder; import org.springframework.boot.actuate.info.InfoContributor; import org.springframework.stereotype.Component; @Component public class MyInfoContributor implements InfoContributor { @Override public void contribute(Builder builder) { builder .withDetail("xyz", "12345") .build(); } } <|start_filename|>STL-Apr-2018/src/main/java/habuma/ProfController.java<|end_filename|> package habuma; import org.springframework.data.domain.Example; import org.springframework.data.domain.ExampleMatcher; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import lombok.RequiredArgsConstructor; @RestController @RequestMapping("/prof") @RequiredArgsConstructor public class ProfController { private final ProfileRepository repo; @GetMapping public Iterable<Profile> byExample() { Profile exampleProfile = new Profile("NATE", null, "<NAME>", false); Example<Profile> example = Example.of(exampleProfile, ExampleMatcher.matching() .withIgnoreCase("username", "fullName")); return repo.findAll(example); } } <|start_filename|>VIRTUAL-Jul-2021/solver-integration/solver/src/main/java/com/example/demo/SolverApplication.java<|end_filename|> package com.example.demo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.amqp.core.AmqpTemplate; import org.springframework.amqp.rabbit.annotation.RabbitListener; import org.springframework.amqp.rabbit.connection.ConnectionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.integration.amqp.dsl.Amqp; import org.springframework.integration.amqp.inbound.AmqpMessageSource; import org.springframework.integration.dsl.IntegrationFlow; import org.springframework.integration.dsl.IntegrationFlows; import org.springframework.integration.dsl.Pollers; import org.springframework.messaging.handler.annotation.SendTo; @SpringBootApplication public class SolverApplication { private static final Logger logger = LoggerFactory.getLogger(SolverApplication.class); public static void main(String[] args) { SpringApplication.run(SolverApplication.class, args); } @Autowired QuadraticSolver solver; @Bean public IntegrationFlow flow( ConnectionFactory cf, AmqpTemplate amqpTemplate) { return IntegrationFlows .from(new AmqpMessageSource(cf, "equations"), c -> c.poller(Pollers.fixedRate(1000))) .<Equation, Solution> transform(equation -> solver.solve(equation)) .handle(Amqp.outboundGateway(amqpTemplate).routingKey("solutions")) .get(); } } <|start_filename|>VIRTUAL-Jul-2021/spring-books/src/main/java/books/LegacySystemHealthIndicator.java<|end_filename|> package books; import org.springframework.boot.actuate.health.Health; import org.springframework.boot.actuate.health.HealthContributor; import org.springframework.boot.actuate.health.HealthIndicator; import org.springframework.stereotype.Component; @Component public class LegacySystemHealthIndicator implements HealthIndicator { @Override public Health health() { double random = Math.random(); if (random > 0.5) { return Health.up() .withDetail("reason", "The value is large enough: " + random) .build(); } // DOWN return Health.down() .withDetail("reason", "The value is too small: " + random) .build(); } } <|start_filename|>EventDrivenSpring-Workshop-Dec-2020/mdbs/logger/src/main/java/com/example/demo/LoggerApplication.java<|end_filename|> package com.example.demo; import java.util.Optional; import org.springframework.amqp.rabbit.annotation.RabbitListener; import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.ApplicationRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.messaging.handler.annotation.SendTo; import lombok.extern.slf4j.Slf4j; @SpringBootApplication @Slf4j public class LoggerApplication { public static void main(String[] args) { SpringApplication.run(LoggerApplication.class, args); } @RabbitListener(queues = "solutions") public void handleMessage(Solution solution) { log.info("LOGGER GOT A SOLUTION: !!! " + solution); } } <|start_filename|>BOS-Sept-2019/books-data-bos/src/main/java/habuma/BooksDataBosApplication.java<|end_filename|> package habuma; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; @SpringBootApplication public class BooksDataBosApplication { public static void main(String[] args) { SpringApplication.run(BooksDataBosApplication.class, args); } @Bean public CommandLineRunner dataLoader(BooksRepository repo) { return args -> { repo.save(new Book("1234567890", "Knitting with Dog Hair", "Kendall", "Crolius")); repo.save(new Book("9876543210", "Crafting with Cat Hair", "Kaori", "Tsutaya")); }; } } <|start_filename|>STL-Apr-2018/src/main/java/habuma/RestConfiguration.java<|end_filename|> package habuma; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.rest.core.config.RepositoryRestConfiguration; import org.springframework.data.rest.webmvc.config.RepositoryRestConfigurerAdapter; @Configuration public class RestConfiguration { @Bean public RepositoryRestConfigurerAdapter sdrCustomizer() { return new RepositoryRestConfigurerAdapter() { @Override public void configureRepositoryRestConfiguration( RepositoryRestConfiguration config) { config .withEntityLookup() .forRepository(BookRepository.class, Book::getIsbn, BookRepository::findByIsbn); } }; } } <|start_filename|>MSN-Feb-2020/tacotalk/src/main/java/habuma/TacoRepository.java<|end_filename|> package habuma; import org.springframework.data.repository.CrudRepository; public interface TacoRepository extends CrudRepository<Taco, String> { Iterable<Taco> findByWrap(String wrap); } <|start_filename|>AUS-July-2019/spring-boot-sessions/austin-books/src/main/java/habuma/Book.java<|end_filename|> package habuma; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; import lombok.Data; @Data @Document public class Book { @Id private String id; private final String isbn; private final String title; private final String authorFirstName; private final String authorLastName; } <|start_filename|>IAD-Apr-2019/spring-boot/src/main/java/habuma/books/BooksController.java<|end_filename|> package habuma.books; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import lombok.RequiredArgsConstructor; @RestController @RequestMapping("/books") @RequiredArgsConstructor public class BooksController { private final BooksRepository repo; @GetMapping public Iterable<Book> books() { return repo.findAll(); } } <|start_filename|>Boot-Workshop-Jan-2021/books/src/main/java/habuma/BooksController.java<|end_filename|> package habuma; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/books") public class BooksController { private final BookRepository repo; public BooksController(BookRepository repo) { this.repo = repo; } @GetMapping public Iterable<Book> allBooks() { return repo.findAll(); } @PostMapping public Book saveBook(@RequestBody Book book) { return repo.save(book); } } <|start_filename|>uberconf-2021/alexa-skills/UberTravel-Conversations/lambda/index.js<|end_filename|> const Alexa = require('ask-sdk-core'); const util = require('./util'); const ScheduleTripApiHandler = { canHandle(handlerInput) { return util.isApiRequest( handlerInput, 'com.ubertravel.scheduleTrip'); }, handle(handlerInput) { const destination = util.getApiArguments(handlerInput).destination; const startDate = util.getApiArguments(handlerInput).startDate; const tripLength = util.getApiArguments(handlerInput).tripLength; const reservationNumber = scheduleTrip(destination, startDate, tripLength); const response = { apiResponse: { reservationNumber: reservationNumber, destination: destination, departureDate: startDate, returnDate: tripLength } }; return response; } }; function scheduleTrip(destination, departureDate, returnDate) { console.log("HANDLING A SCHEDULE TRIP REQUEST::::: "); console.log(` - ${destination}`); console.log(` - ${departureDate}`); console.log(` - ${returnDate}`); // // TODO: Invoke travel booking API // return 12345; // <-- Fake reservation number } const LaunchRequestHandler = { canHandle(handlerInput) { return Alexa.getRequestType(handlerInput.requestEnvelope) === 'LaunchRequest'; }, handle(handlerInput) { const speakOutput = 'Welcome, you can say Hello or Help. Which would you like to try?'; return handlerInput.responseBuilder .speak(speakOutput) .reprompt(speakOutput) .getResponse(); } }; const SessionEndedRequestHandler = { canHandle(handlerInput) { return Alexa.getRequestType(handlerInput.requestEnvelope) === 'SessionEndedRequest'; }, handle(handlerInput) { // Any cleanup logic goes here. return handlerInput.responseBuilder.getResponse(); } }; // The intent reflector is used for interaction model testing and debugging. // It will simply repeat the intent the user said. You can create custom handlers // for your intents by defining them above, then also adding them to the request // handler chain below. const IntentReflectorHandler = { canHandle(handlerInput) { return Alexa.getRequestType(handlerInput.requestEnvelope) === 'IntentRequest'; }, handle(handlerInput) { const intentName = Alexa.getIntentName(handlerInput.requestEnvelope); const speakOutput = `You just triggered ${intentName}`; return handlerInput.responseBuilder .speak(speakOutput) //.reprompt('add a reprompt if you want to keep the session open for the user to respond') .getResponse(); } }; // Generic error handling to capture any syntax or routing errors. If you receive an error // stating the request handler chain is not found, you have not implemented a handler for // the intent being invoked or included it in the skill builder below. const ErrorHandler = { canHandle() { return true; }, handle(handlerInput, error) { console.log(`~~~~ Error handled: ${error.stack}`); const speakOutput = `Sorry, I had trouble doing what you asked. Please try again.`; return handlerInput.responseBuilder .speak(speakOutput) .reprompt(speakOutput) .getResponse(); } }; // The SkillBuilder acts as the entry point for your skill, routing all request and response // payloads to the handlers above. Make sure any new handlers or interceptors you've // defined are included below. The order matters - they're processed top to bottom. exports.handler = Alexa.SkillBuilders.custom() .addRequestHandlers( LaunchRequestHandler, ScheduleTripApiHandler, SessionEndedRequestHandler, IntentReflectorHandler, ) .addErrorHandlers( ErrorHandler, ) .lambda(); <|start_filename|>IAD-Nov-2018/iad-books/src/main/resources/META-INF/additional-spring-configuration-metadata.json<|end_filename|> { "properties": [ { "name": "greeting.message", "type": "java.lang.String", "description": "The greeting we wish to convey." }, { "name": "greeting.other", "type": "java.lang.String", "description": "A description for 'greeting.other'" } ]} <|start_filename|>SEA-Nov-2019/sea-books/src/main/java/com/example/demo/GreetingProps.java<|end_filename|> package com.example.demo; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; import lombok.Data; @Data @Component @ConfigurationProperties(prefix="greeting") public class GreetingProps { private String message; } <|start_filename|>IAD-Apr-2019/spring-data-rest/src/main/java/habuma/BooksController.java<|end_filename|> package habuma; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import lombok.RequiredArgsConstructor; @RestController @RequiredArgsConstructor @RequestMapping("/books") public class BooksController { private final BookRepository repo; @GetMapping public Iterable<Book> allBooks() { return repo.findAll(); } @GetMapping("/{id}") public Book byId(@PathVariable("id") Book book) { return book; } @GetMapping("/isbn/{isbn}") public SimpleBook byIsbn(@PathVariable("isbn") String isbn) { return repo.findSimpleByIsbn(isbn); } @PostMapping public Book saveABook(@RequestBody Book book) { return repo.save(book); } } <|start_filename|>VIRTUAL-Nov-2020/nfjs-books/src/test/java/habuma/BookControllerTests.java<|end_filename|> package habuma; import static org.mockito.Mockito.verifyNoInteractions; import static org.springframework.http.MediaType.APPLICATION_JSON; import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document; import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.documentationConfiguration; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import java.io.IOException; import java.nio.charset.Charset; import java.util.Optional; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.actuate.autoconfigure.metrics.export.simple.SimpleMetricsExportAutoConfiguration; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Import; import org.springframework.core.io.Resource; import org.springframework.http.MediaType; import org.springframework.restdocs.RestDocumentationContextProvider; import org.springframework.restdocs.RestDocumentationExtension; import org.springframework.security.config.annotation.SecurityConfigurer; import org.springframework.security.test.context.support.WithAnonymousUser; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.util.StreamUtils; import org.springframework.web.context.WebApplicationContext; import io.micrometer.core.instrument.MeterRegistry; import io.micrometer.core.instrument.config.MeterRegistryConfig; @WebMvcTest(controllers=BookController.class) @ExtendWith(RestDocumentationExtension.class) public class BookControllerTests { @MockBean BookRepository bookRepo; @MockBean MeterRegistry meterRegistry; @Autowired MockMvc mockMvc; @Autowired WebApplicationContext context; @Value("classpath:/habuma/book.json") Resource bookJson; @BeforeEach public void setup(RestDocumentationContextProvider restDocumentation) throws Exception { // Configure the RestDocs configuration with MockMvc. Also, configure Spring Security configuration. // Normally, Spring Security configuration is automatically configured with MockMvc, but since this // method creates a new MockMvc setup from scratch, we have to also explicitly configure Spring // Security with MockMvc. this.mockMvc = MockMvcBuilders.webAppContextSetup(context) .apply(documentationConfiguration(restDocumentation)) .apply(SecurityMockMvcConfigurers.springSecurity()) .build(); } @Test public void testGetBook() throws Exception { Book testBook = new Book("1234567890", "Test Book", "Test Author"); testBook.setId(123L); Mockito.when(bookRepo.findById(123L)).thenReturn(Optional.of(testBook)); mockMvc.perform(get("/books/{id}", 123L) .contentType(MediaType.APPLICATION_JSON)) .andExpect(jsonPath("id").value(123L)) .andExpect(jsonPath("isbn").value("1234567890")) .andExpect(jsonPath("title").value("Test Book")) .andExpect(jsonPath("author").value("Test Author")) .andExpect(status().isOk()) .andDo(document("sample")); } @Test @WithMockUser(username="username", password="password", roles={"USER"}) public void testSavesABook_UnauthorizedUser() throws Exception { mockMvc.perform(post("/books") .contentType(APPLICATION_JSON) .content(getBookJsonAsString())) .andExpect(status().isForbidden()); verifyNoInteractions(bookRepo); } private String getBookJsonAsString() throws IOException { return StreamUtils.copyToString(bookJson.getInputStream(), Charset.defaultCharset()); } } <|start_filename|>IAD-Nov-2018/iad-books/src/main/java/com/example/demo/SimpleBook.java<|end_filename|> package com.example.demo; import org.springframework.beans.factory.annotation.Value; public interface SimpleBook { String getIsbn(); String getTitle(); @Value("#{target.authorFirstName + ' :: ' + target.authorLastName}") String getAuthor(); @Value("#{T(System).currentTimeMillis()}") long getTimestamp(); } <|start_filename|>MSP-Mar-2019/boot-demo/src/main/java/habuma/MyInfoContributor.java<|end_filename|> package habuma; import org.springframework.boot.actuate.info.Info.Builder; import org.springframework.boot.actuate.info.InfoContributor; import org.springframework.stereotype.Component; @Component public class MyInfoContributor implements InfoContributor { @Override public void contribute(Builder builder) { builder .withDetail("address", "123 NorthStreet") .withDetail("random", Math.random()) .build(); } } <|start_filename|>IAD-Apr-2019/spring-data-rest/src/main/java/habuma/SpringdataFunApplication.java<|end_filename|> package habuma; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; @SpringBootApplication public class SpringdataFunApplication { public static void main(String[] args) { SpringApplication.run(SpringdataFunApplication.class, args); } @Bean public CommandLineRunner dataLoader(BookRepository bookRepo, AuthorRepository authorRepo, PublisherRepository publisherRepo, AddressRepository addressRepo) { return new CommandLineRunner() { @Override public void run(String... args) throws Exception { Address manningAddress = addressRepo.save(new Address("1233 Heartwood Drive", "Cherry Hill", "NJ", "08003")); Publisher manning = publisherRepo.save(new Publisher("Manning Publications Co.", manningAddress)); Author cwalls = authorRepo.save(new Author("Craig", "Walls")); bookRepo.save(new Book("9781617292545", "Spring Boot in Action", manning, cwalls, 264)); bookRepo.save(new Book("9781617291203", "Spring in Action. Fourth Edition", manning, cwalls, 624)); Address oreillyAddr = addressRepo.save(new Address("1005 Grevenstein Highway North", "Sebastopol", "CA", "95472")); Publisher oreilly = publisherRepo.save(new Publisher("O'Reilly Publications", oreillyAddr)); Author ken = authorRepo.save(new Author("Ken", "Kousen")); bookRepo.save(new Book("B01GQTM84E", "Gradle Recipes for Android", oreilly, ken, 168)); } }; } } <|start_filename|>VIRTUAL-Oct-2020/nfjs-reactive-books/src/main/java/habuma/CounterController.java<|end_filename|> package habuma; import java.time.Duration; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import reactor.core.publisher.Flux; @RestController public class CounterController { @GetMapping(path="/count", produces = {MediaType.APPLICATION_STREAM_JSON_VALUE}) public Flux<String> counter() { return Flux.interval(Duration.ofSeconds(1)) .map(n -> "COUNT: " + n); } } <|start_filename|>IAD-Apr-2019/spring-boot/src/main/java/habuma/books/DemoInfoContributor.java<|end_filename|> package habuma.books; import org.springframework.boot.actuate.info.Info.Builder; import org.springframework.boot.actuate.info.InfoContributor; import org.springframework.stereotype.Component; import lombok.RequiredArgsConstructor; @Component @RequiredArgsConstructor public class DemoInfoContributor implements InfoContributor { private final GreetingProps props; @Override public void contribute(Builder builder) { builder .withDetail("time", System.currentTimeMillis()) .withDetail("greeting-props", props); } } <|start_filename|>SLC-May-2019/slc-books/src/main/java/habuma/books/ThingScheduler.java<|end_filename|> package habuma.books; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; @Component public class ThingScheduler { @Scheduled(fixedRate = 5000) public void tick() { System.out.println("------>>> " + System.currentTimeMillis()); } } <|start_filename|>VIRTUAL-Sept-2020/reactive-books/src/test/java/habuma/ReactiveLearningTests.java<|end_filename|> package habuma; import org.junit.jupiter.api.Test; import reactor.core.publisher.Mono; public class ReactiveLearningTests { @Test public void testReactiveStuff() { Mono.just("Hello") .doOnNext(text -> { System.out.print("---> " + text); }) .subscribe(); } } <|start_filename|>ORD-Nov-2018/ord-books/src/main/java/habuma/SimpleBook.java<|end_filename|> package habuma; import org.springframework.beans.factory.annotation.Value; import org.springframework.data.rest.core.config.Projection; @Projection(name="simple", types=Book.class) public interface SimpleBook { String getTitle(); @Value("#{target.authorFirstName + ' ' + target.authorLastName}") String getAuthor(); }
habuma/nfjs-samples
<|start_filename|>src/Model/Mailbox.hs<|end_filename|> {-# LANGUAGE QuasiQuotes #-} module Model.Mailbox where import Data.Aeson import Data.Text import Data.Time import Data.String.Interpolate (i) import Data.Time.ISO8601 (formatISO8601Millis) newtype EmailAddress = EmailAddress Text deriving ToJSON newtype Url = Url Text deriving ToJSON data Mailbox = Mailbox { mailboxId :: Text , created :: UTCTime } receiveUrl :: Mailbox -> Url receiveUrl m = Url [i|https://api.unverified.email/receive/#{mailboxId m}|] mailboxAddress :: Mailbox -> EmailAddress mailboxAddress m = EmailAddress [i|#{mailboxId m}@unverified.email|] instance ToJSON Mailbox where toJSON m = object [ "mailbox" .= mailboxAddress m , "receive" .= receiveUrl m , "mailbox_id" .= mailboxId m , "created" .= formatISO8601Millis (created m) ] <|start_filename|>src/Action/Create.hs<|end_filename|> {-# LANGUAGE QuasiQuotes #-} module Action.Create (createMailbox) where import Control.Concurrent (threadDelay) import Data.String.Interpolate (i) import Data.Text (Text) import Data.Time.Clock import Data.UUID import Data.UUID.V4 import Model.Mailbox import qualified Prometheus import Protolude import System.Directory (createDirectoryIfMissing) import Web.Scotty (ActionM, json, liftAndCatchIO) import qualified Env createMailbox :: Prometheus.Counter -> ActionM () createMailbox metricMailboxCreations = do liftAndCatchIO (Prometheus.incCounter metricMailboxCreations) liftAndCatchIO mailbox >>= json mailbox :: IO Mailbox mailbox = dubiousDosPreventionAttempt >> Mailbox <$> getNewMailboxId <*> getCurrentTime where dubiousDosPreventionAttempt = whenM (Env.featureToggle "FEATURE_NO_DELAY") $ threadDelay 1_000_000 getNewMailboxId :: IO Text getNewMailboxId = do maildir <- Env.maildir let expectedDir = [i|#{maildir}/expected|] createDirectoryIfMissing True expectedDir mailboxId <- toText <$> nextRandom writeFile [i|#{expectedDir}/#{mailboxId}|] "" return mailboxId <|start_filename|>test/Test/Hspec/Wai/FeatureToggle.hs<|end_filename|> {-# LANGUAGE FlexibleContexts #-} module Test.Hspec.Wai.FeatureToggle where import Control.Exception (bracket_) import System.Environment (lookupEnv, setEnv, unsetEnv) import Test.Hspec (SpecWith, around_) withFeatureToggleOn :: String -> SpecWith a -> SpecWith a withFeatureToggleOn featureName = around_ (\action -> do previousVal <- lookupEnv featureName bracket_ set' (unsetTo' previousVal) action ) where set' = setEnv featureName "True" unsetTo' = \case Just v -> setEnv featureName v Nothing -> unsetEnv featureName <|start_filename|>src/Dispatcher.hs<|end_filename|> module Dispatcher ( runnableApp , testableApp ) where import Control.Concurrent import qualified Env import LoadEnv import Network.Wai (Application) import Network.Wai.Middleware.RequestLogger import Protolude import Web.Scotty (ScottyM, scotty, scottyApp, middleware) import qualified Network.Wai.Middleware.Prometheus as Prometheus import qualified Prometheus as Prometheus import qualified Prometheus.Metric.GHC as Prometheus import qualified Controller.Mailbox {-# NOINLINE metricMailboxCreations #-} metricMailboxCreations :: Prometheus.Counter metricMailboxCreations = Prometheus.unsafeRegister $ Prometheus.counter $ Prometheus.Info "api_mailbox_creations" "The number of mailboxes created via the api" app' :: ScottyM () app' = Controller.Mailbox.controller metricMailboxCreations metricsApp :: ScottyM () metricsApp = middleware (Prometheus.prometheus Prometheus.def) testableApp :: IO Application testableApp = ifM Env.debugMode (scottyApp $ middleware logStdoutDev >> app') (scottyApp app') runnableApp :: IO () runnableApp = do _ <- Prometheus.register Prometheus.ghcMetrics loadEnv port <- Env.port prometheusPort <- Env.prometheusPort _metricsThreadId <- forkIO $ scotty (fromIntegral prometheusPort) metricsApp scotty (fromIntegral port) $ middleware logStdout >> app' <|start_filename|>infra/smtpd/Dockerfile<|end_filename|> FROM alpine:3.11 RUN apk --no-cache add \ ca-certificates \ bash \ curl \ opensmtpd \ tini RUN adduser -D -H unverified && \ mkdir -p /mailbox/unverified && \ chown unverified:unverified /mailbox/unverified COPY ./smtpd.conf /etc/smtpd EXPOSE 25/tcp ENTRYPOINT ["tini", "-g", "--"] CMD ["/usr/sbin/smtpd", "-d"] <|start_filename|>test/Controller/UsageTest.hs<|end_filename|> module Controller.UsageTest where import Data.String.Interpolate (i) import Data.Text import Network.Wai (Application) import Test.Hspec import Test.Hspec.Wai import qualified Env spec :: SpecWith Application spec = describe "Controller.UsageTest" $ describe "GET /" $ do it "responds with usage" $ do apiUrl <- Env.apiURL infoPageUrl <- Env.infoPageURL smtpUrl <- Env.smtpURL get "/" `shouldRespondWith` usage apiUrl infoPageUrl smtpUrl it "has 'Content-Type: text/plain; charset=utf-8'" $ get "/" `shouldRespondWith` 200 {matchHeaders = ["Content-Type" <:> "text/plain; charset=utf-8"]} usage :: Text -> Text -> Text -> ResponseMatcher usage apiUrl infoPageUrl smtpUrl = [i| UNVERIFIED.EMAIL a tool that helps testing your emails. # Usage You can use api.unverified.email to create a mailbox, send email(s) to it from your tests, and, verify that the email(s) have all the needed content by downloading them through the api. 1. To create a mailbox, make a GET request to: https://#{apiUrl}/create The response will be a json containing all the information about a newly created mailbox. 2.a Send your emails to the mailbox address that you will find from the create step. 2.b Alternatively, you can include the mailbox_id in any other place in your email (subject, headers if you have access to them, or even in the body), and send the email to <EMAIL> to be able to receive it later through api. 2.c You could also set #{smtpUrl} as your smtp server for testing and dev environment, and send your emails to the real addresses you actually intended. unverified.email will catch all email, storing it for you to fetch via api. 3. Verify the emails in your test, by making another GET request to: https://#{apiUrl}/receive/<mailbox_id> where <mailbox_id> is the one from the creation step. The creation step actually includes the receive url, so you don't need to concatenate anything in your code. unverified.email will answer with a list of all the emails, including the To, From, and Subject fields, as well as the raw source of the email body for you to parse :) # There are few notes though: - You can create as many mailboxes as you want. The mailboxes and all the emails will be deleted 5 minutes after they are created. - The /receive endpoint will wait for emails to be delivered for at least 15 seconds, so you should not need to hit the url repeatedly. - The code is available at https://github.com/ptek/api.unverified.email *And a note of warning*: unverified.email is not yet finalised. I am certain it can be used by developers and in your pipelines, and we can iron out the small kinks together if they appear. But it is still very fresh, so just open an issue please, if something needs attention. For more details, visit #{infoPageUrl} |] <|start_filename|>src/Model/Usage.hs<|end_filename|> {-# LANGUAGE QuasiQuotes #-} module Model.Usage (plainText) where import Data.String.Interpolate (i) import Data.Text (Text) import qualified Data.Text.Lazy as TL plainText :: Text -> Text -> Text -> TL.Text plainText apiUrl infoPageUrl smtpUrl = [i| UNVERIFIED.EMAIL a tool that helps testing your emails. # Usage You can use api.unverified.email to create a mailbox, send email(s) to it from your tests, and, verify that the email(s) have all the needed content by downloading them through the api. 1. To create a mailbox, make a GET request to: https://#{apiUrl}/create The response will be a json containing all the information about a newly created mailbox. 2.a Send your emails to the mailbox address that you will find from the create step. 2.b Alternatively, you can include the mailbox_id in any other place in your email (subject, headers if you have access to them, or even in the body), and send the email to <EMAIL> to be able to receive it later through api. 2.c You could also set #{smtpUrl} as your smtp server for testing and dev environment, and send your emails to the real addresses you actually intended. unverified.email will catch all email, storing it for you to fetch via api. 3. Verify the emails in your test, by making another GET request to: https://#{apiUrl}/receive/<mailbox_id> where <mailbox_id> is the one from the creation step. The creation step actually includes the receive url, so you don't need to concatenate anything in your code. unverified.email will answer with a list of all the emails, including the To, From, and Subject fields, as well as the raw source of the email body for you to parse :) # There are few notes though: - You can create as many mailboxes as you want. The mailboxes and all the emails will be deleted 5 minutes after they are created. - The /receive endpoint will wait for emails to be delivered for at least 15 seconds, so you should not need to hit the url repeatedly. - The code is available at https://github.com/ptek/api.unverified.email *And a note of warning*: unverified.email is not yet finalised. I am certain it can be used by developers and in your pipelines, and we can iron out the small kinks together if they appear. But it is still very fresh, so just open an issue please, if something needs attention. For more details, visit #{infoPageUrl} |] <|start_filename|>src/Env.hs<|end_filename|> module Env ( port , prometheusPort , apiURL , infoPageURL , smtpURL , maildir , featureToggle , debugMode ) where import Control.Monad.Fail import Control.Monad.IO.Class (MonadIO, liftIO) import Data.Text (Text) import qualified Data.Text as T import Prelude hiding (fail) import System.Environment (lookupEnv) import Text.Read (readEither) port :: (MonadIO m, MonadFail m) => m Int port = readEnv "PORT" prometheusPort :: (MonadIO m, MonadFail m) => m Int prometheusPort = readEnv "PORT_PROMETHEUS" apiURL :: (MonadIO m, MonadFail m) => m Text apiURL = T.pack <$> readEnvString "API_URL" smtpURL :: (MonadIO m, MonadFail m) => m Text smtpURL = T.pack <$> readEnvString "SMTP_URL" infoPageURL :: (MonadIO m, MonadFail m) => m Text infoPageURL = T.pack <$> readEnvString "INFO_PAGE_URL" maildir :: (MonadIO m, MonadFail m) => m FilePath maildir = readEnvString "MAILDIR" debugMode :: (MonadIO m) => m Bool debugMode = featureToggle "DEBUG_MODE" {-# INLINEABLE featureToggle #-} featureToggle :: (MonadIO m) => String -> m Bool featureToggle toggleName = liftIO (parseDevelopmentMode <$> lookupEnv toggleName) where parseDevelopmentMode (Just "True") = True parseDevelopmentMode _otherwise = False {-# INLINEABLE readEnvString #-} readEnvString :: (MonadIO m, MonadFail m) => String -> m String readEnvString name = do result <- liftIO $ lookupEnv name case result of Nothing -> fail $ "No value set for environment variable: " <> name Just x -> return x {-# INLINEABLE readEnv #-} readEnv :: (MonadIO m, MonadFail m, Read a) => String -> m a readEnv name = do val <- readEnvString name case readEither val of Left err -> fail $ "Error parsing value from environment variable. " <> name <> " = " <> show val <> " => " <> err Right result -> return result <|start_filename|>src/Controller/Mailbox.hs<|end_filename|> module Controller.Mailbox ( controller ) where import Web.Scotty (ScottyM, get, param) import qualified Prometheus import Protolude hiding (get) import qualified Action.Create import qualified Action.Usage import qualified Action.Receive controller :: Prometheus.Counter -> ScottyM () controller metricMailboxCreations = do get "/" Action.Usage.usage get "/create" (Action.Create.createMailbox metricMailboxCreations) get "/receive/:mailboxId" (param "mailboxId" >>= Action.Receive.receiveMailbox) <|start_filename|>src/Action/Receive.hs<|end_filename|> {-# LANGUAGE QuasiQuotes #-} module Action.Receive where import Control.Retry import qualified Data.ByteString as B import Data.String.Interpolate (i) import Data.Text (Text) import qualified Data.Text as T import qualified Data.Text.Encoding as TE import qualified Data.Text.Encoding.Error as TE import Protolude import System.Directory (doesDirectoryExist, listDirectory) import Text.StringConvert (s) import Web.Scotty (ActionM, json, liftAndCatchIO) import qualified Env import Model.Email receiveMailbox :: Text -> ActionM () receiveMailbox mailboxId = liftAndCatchIO (readMailbox mailboxId) >>= json readMailbox :: Text -> IO [Email] readMailbox mailboxId = do maildir <- Env.maildir ifM (Env.featureToggle "FEATURE_NO_DELAY") (findEmails maildir mailboxId) (retry' $ findEmails maildir mailboxId) where retry' = retrying jitterRetry considerRetrying . const jitterRetry = limitRetriesByCumulativeDelay 29_250_000 (fullJitterBackoff 250_000) considerRetrying _ emails = return (null emails) findEmails :: FilePath -> Text -> IO [Email] findEmails maildir mailboxId = ifM (directoriesExist &&^ isMailboxIdExpected mailboxId) (do mailFiles <- listDirectory newMailsDir >>= mapM (maybeReadFile . ([i|#{newMailsDir}/|]++)) return . mapMaybe parseEmail $ filter (isForMailboxId mailboxId) mailFiles ) (return []) where newMailsDir = [i|#{maildir}/new|] expectedMailsDir = [i|#{maildir}/expected|] isForMailboxId = T.isInfixOf maybeReadFile path = TE.decodeUtf8With TE.lenientDecode <$> B.readFile path directoriesExist = doesDirectoryExist maildir &&^ doesDirectoryExist newMailsDir &&^ doesDirectoryExist expectedMailsDir isMailboxIdExpected mailboxId' = fmap (elem (s mailboxId')) (listDirectory expectedMailsDir) <|start_filename|>test/Controller/CreateTest.hs<|end_filename|> module Controller.CreateTest where import Lens.Micro import Lens.Micro.Aeson import Network.Wai (Application) import Protolude (whenM) import System.Directory (doesDirectoryExist, removeDirectoryRecursive) import Test.Hspec import Test.Hspec.Wai import qualified Env import Test.Hspec.Wai.FeatureToggle import Test.Hspec.Wai.ValueMatchers spec :: SpecWith Application spec = describe "Controller.CreateTest" $ before_ cleanMaildir $ withFeatureToggleOn "FEATURE_NO_DELAY" $ describe "GET /create" $ it "responds with information about a new mailbox" $ get "/create" `shouldRespondWith` jsonResponseForCreate jsonResponseForCreate :: ResponseMatcher jsonResponseForCreate = 200 { matchBody = introspectBody (\body -> [ isUUID (body ^? key "mailbox_id" . _String) , (body ^? key "mailbox" . _String) `contains` "@unverified.email" , (body ^? key "receive" . _String) `contains` "https://api.unverified.email/receive" , (body ^? key "created" . _String) `hasLength` 24 ]) } cleanMaildir :: IO () cleanMaildir = do maildir <- Env.maildir whenM (doesDirectoryExist maildir) (removeDirectoryRecursive maildir) <|start_filename|>test/Test.hs<|end_filename|> module Main (main) where import LoadEnv import Test.Hspec import Test.Hspec.Wai import Dispatcher (testableApp) import qualified Controller.CreateTest import qualified Controller.ReceiveTest import qualified Controller.UsageTest main :: IO () main = do loadEnv hspec spec spec :: Spec spec = with testableApp $ do Controller.UsageTest.spec Controller.CreateTest.spec Controller.ReceiveTest.spec <|start_filename|>app/Main.hs<|end_filename|> module Main where import Dispatcher (runnableApp) main :: IO () main = runnableApp <|start_filename|>infra/api/Dockerfile<|end_filename|> FROM frolvlad/alpine-glibc:alpine-3.11_glibc-2.30 RUN apk --no-cache add \ ca-certificates \ gmp \ tini COPY entrypoint.sh /entrypoint.sh RUN echo '* * * * * find ${MAILDIR} -type f -mmin +5 -print | xargs -I{} sh -c "rm -f {}"' >> /etc/crontabs/root ENV PORT=80 \ PORT_PROMETHEUS=8081 \ API_URL="api.unverified.email" \ SMTP_URL="smtp.unverified.email:25" \ INFO_PAGE_URL="https://github.com/ptek/api.unverified.email" \ MAILDIR="/mailbox/unverified/" COPY dist/unverified-email-api /opt/bin/unverified-email-api EXPOSE 80/tcp EXPOSE 8081/tcp ENTRYPOINT ["tini", "-g", "--", "/entrypoint.sh"] <|start_filename|>src/Model/Email.hs<|end_filename|> module Model.Email where import Data.Aeson import Data.Text (Text) import qualified Data.Text as T import GHC.Generics import Protolude data Email = Email { addressTo :: Text , addressFrom :: Text , subject :: Text , fullContent :: Text } deriving (Generic, Show) instance ToJSON Email where toEncoding = genericToEncoding (defaultOptions {fieldLabelModifier = camelTo2 '_'}) parseEmail :: Text -> Maybe Email parseEmail email = Email <$> parseTo <*> parseFrom <*> parseSubject <*> pure email where emailLines = T.lines email parseTo = T.drop 4 <$> headMay (filter ("To: " `T.isPrefixOf`) emailLines) parseFrom = T.drop 6 <$> headMay (filter ("From: " `T.isPrefixOf`) emailLines) parseSubject = T.drop 9 <$> headMay (filter ("Subject: " `T.isPrefixOf`) emailLines) <|start_filename|>test/Controller/ReceiveTest.hs<|end_filename|> module Controller.ReceiveTest where import Data.Aeson (FromJSON) import Data.String.Interpolate (i) import Data.Text (Text) import Data.Time.Clock (diffUTCTime, getCurrentTime) import GHC.Generics import Lens.Micro import Lens.Micro.Aeson import Network.Wai (Application) import Network.Wai.Test import Protolude (whenM) import System.Directory (createDirectoryIfMissing, doesDirectoryExist, removeDirectoryRecursive) import Test.Hspec (SpecWith, before_, describe, it) import Test.Hspec.Expectations.Lifted import Test.Hspec.Wai import Text.StringConvert (s) import qualified Env import Test.Hspec.Wai.FeatureToggle import Test.Hspec.Wai.ValueMatchers spec :: SpecWith Application spec = describe "Controller.ReceiveTest" $ before_ cleanMaildir $ do withFeatureToggleOn "FEATURE_NO_DELAY" $ describe "GET /receive" $ do it "responds with empty emails for unknown mailbox id" $ get "/receive/unknown-mailbox-id" `shouldRespondWith` jsonEmailsForReceive [] it "responds with an email when it arrives in the mailbox" $ do (mailboxId, mailboxAddress) <- createMailbox let testEmail = testEmailTo mailboxAddress sendEmail testEmail get [i|/receive/#{mailboxId}|] `shouldRespondWith` jsonEmailsForReceive [(mailboxAddress, plainEmail testEmail)] it "doesnt show emails for inboxes that were not created" $ do let mailboxId = "guessable-mailbox-id" :: Text sendEmail $ testEmailTo [i|#{mailbox<EMAIL>|] get [i|/receive/#{mailboxId}|] `shouldRespondWith` jsonEmailsForReceive [] describe "GET /receive" $ it "responds with a delay waiting for an email to arrive" $ do timeStart <- liftIO getCurrentTime _ <- get "/receive/unknown-mailbox-id" timeFinished <- liftIO getCurrentTime (timeFinished `diffUTCTime` timeStart) `shouldSatisfy` (> 15) (timeFinished `diffUTCTime` timeStart) `shouldSatisfy` (< 29.5) cleanMaildir :: IO () cleanMaildir = do maildir <- Env.maildir whenM (doesDirectoryExist maildir) (removeDirectoryRecursive maildir) jsonEmailsForReceive :: [(Text, Text)] -> ResponseMatcher jsonEmailsForReceive vs = 200 { matchBody = introspectBody (\body -> [ (body ^.. values . key "address_to" . _String) `equalsTo` map fst vs , (body ^.. values . key "full_content" . _String) `equalsTo` map snd vs ]) } createMailbox :: WaiSession (Text, Text) createMailbox = do mailbox :: Text <- s . simpleBody <$> get "/create" let mailboxId = mailbox ^. key "mailbox_id" . _String let mailboxAddress = mailbox ^. key "mailbox" . _String return (mailboxId, mailboxAddress) sendEmail :: TestEmail -> WaiSession () sendEmail te = do maildir <- (++ "/new") <$> Env.maildir liftIO $ do createDirectoryIfMissing True maildir writeFile [i|#{maildir}/1566204945.111.51ff45ed527f|] (s (plainEmail te)) testEmailTo :: Text -> TestEmail testEmailTo addressTo = TestEmail "<EMAIL>" addressTo "A test email" "Body of a test email" plainEmail :: TestEmail -> Text plainEmail TestEmail{..} = [i| Return-Path: #{addressFrom} Delivered-To: #{addressTo} Received: from user-PC (8ta-246-224-193.telkomadsl.co.za [172.16.31.103]) by 51ff45ed527f (OpenSMTPD) with ESMTP id 116053ef for <#{addressTo}>; Mon, 19 Aug 2019 08:55:44 +0000 (UTC) From: #{addressFrom} Subject: #{subject} To: #{addressTo} Date: Mon, 19 Aug 2019 10:55:37 +0200 X-Priority: 3 X-Library: Indy 8.0.25 #{body} |] data TestEmail = TestEmail { addressFrom :: Text , addressTo :: Text , subject :: Text , body :: Text } deriving (Eq, Show, Generic) instance FromJSON TestEmail <|start_filename|>src/Action/Usage.hs<|end_filename|> module Action.Usage (usage) where import Protolude import Web.Scotty (ActionM, text) import qualified Env import qualified Model.Usage usage :: ActionM () usage = Model.Usage.plainText <$> Env.apiURL <*> Env.infoPageURL <*> Env.smtpURL >>= text <|start_filename|>test/Test/Hspec/Wai/ValueMatchers.hs<|end_filename|> module Test.Hspec.Wai.ValueMatchers where import Data.Maybe (catMaybes, isJust) import Data.Text (Text) import qualified Data.Text as T import qualified Data.UUID as UUID import Test.Hspec.Wai import Data.String.Interpolate (i) import Text.StringConvert (s) introspectBody :: (Text -> [Maybe String]) -> MatchBody introspectBody matchers = MatchBody introspectionMatcher where introspectionMatcher _ body = introspectWith (s body) introspectWith tbody = if null (introspect tbody) then Nothing else Just (unlines (introspect tbody)) introspect tbody = catMaybes (matchers tbody) equalsTo :: (Show a, Eq a) => a -> a -> Maybe String equalsTo x y = if x == y then Nothing else Just [i|#{show x} did not equal #{show y}|] maybeEqualsTo :: (Show a, Eq a) => Maybe a -> a -> Maybe String maybeEqualsTo (Just x) y = if x == y then Nothing else Just [i|#{show x} did not equal #{show y}|] maybeEqualsTo Nothing y = Just [i|expected #{show y} not found|] contains :: Maybe Text -> Text -> Maybe String contains (Just x) y = if y `T.isInfixOf` x then Nothing else Just [i|could not find #{y} in #{x}|] contains Nothing y = Just [i|expected #{y} not found|] hasLength :: Maybe Text -> Int -> Maybe String hasLength (Just t) n = if T.length t == n then Nothing else Just [i|length of #{show t} (#{T.length t}) is different than #{n} |] hasLength Nothing n = Just [i|could not find anything with length #{n}|] listHasLength :: (Foldable t, Show (t a)) => Maybe (t a) -> Int -> Maybe String listHasLength (Just t) n = if length t == n then Nothing else Just [i|length of #{show t} (#{length t}) is different than #{n} |] listHasLength Nothing n = Just [i|could not find anything with length #{n}|] isUUID :: Maybe Text -> Maybe String isUUID (Just t) = if isJust (UUID.fromText t) then Nothing else Just [i|#{t} is not a valid uuid|] isUUID Nothing = Just "could not find the expected UUID"
ptek/api.unverified.email
<|start_filename|>wnba_teams.json<|end_filename|> { "teams": [ {"tid": 0, "cid": 0, "did": 0, "region": "Atlanta", "name": "Dream", "abbrev": "ATL", "pop": 4.3, "imgURL": "https://upload.wikimedia.org/wikipedia/en/thumb/5/54/Atlanta_Dream_logo.svg/320px-Atlanta_Dream_logo.svg.png" }, {"tid": 1, "cid": 0, "did": 0, "region": "Connecticut", "name": "Sun", "abbrev": "CON", "pop": 4.4, "imgURL": "https://upload.wikimedia.org/wikipedia/en/thumb/0/09/Connecticut_Sun_logo.svg/261px-Connecticut_Sun_logo.svg.png"}, {"tid": 2, "cid": 0, "did": 0, "region": "Chicago", "name": "Sky", "abbrev": "CHI", "pop": 8.8, "imgURL": "https://upload.wikimedia.org/wikipedia/en/thumb/f/fc/Chicago_Sky_logo.svg/209px-Chicago_Sky_logo.svg.png"}, {"tid": 3, "cid": 0, "did": 0, "region": "Indiana", "name": "Fever", "abbrev": "IND", "pop": 1.6, "imgURL": "https://upload.wikimedia.org/wikipedia/en/thumb/5/54/Indiana_Fever_logo.svg/253px-Indiana_Fever_logo.svg.png"}, {"tid": 4, "cid": 1, "did": 1, "region": "Dallas", "name": "Wings", "abbrev": "DAL", "pop": 4.7, "imgURL": "https://upload.wikimedia.org/wikipedia/en/thumb/9/95/Dallas_Wings_logo.svg/320px-Dallas_Wings_logo.svg.png"}, {"tid": 5, "cid": 1, "did": 1, "region": "Las Vegas", "name": "Aces", "abbrev": "LVA", "pop": 1.7,"imgURL":"https://upload.wikimedia.org/wikipedia/en/thumb/f/fb/Las_Vegas_Aces_logo.svg/171px-Las_Vegas_Aces_logo.svg.png" }, {"tid": 6, "cid": 1, "did": 1, "region": "Los Angeles", "name": "Sparks", "abbrev": "LAS", "pop": 12.3,"imgURL":"https://upload.wikimedia.org/wikipedia/en/thumb/9/9f/Los_Angeles_Sparks_logo.svg/330px-Los_Angeles_Sparks_logo.svg.png" }, {"tid": 7, "cid": 1, "did": 1, "region": "Minnesota", "name": "Lynx", "abbrev": "MIN", "pop": 2.6,"imgURL":"https://upload.wikimedia.org/wikipedia/en/thumb/7/75/Minnesota_Lynx_logo.svg/330px-Minnesota_Lynx_logo.svg.png" }, {"tid": 8, "cid": 0, "did": 0, "region": "New York", "name": "Liberty", "abbrev": "NYL", "pop": 18.7,"imgURL":"https://upload.wikimedia.org/wikipedia/en/thumb/a/a1/New_York_Liberty_logo.svg/330px-New_York_Liberty_logo.svg.png" }, {"tid": 9, "cid": 1, "did": 1, "region": "Phoenix", "name": "Mercury", "abbrev": "PHO", "pop": 3.4,"imgURL":"https://upload.wikimedia.org/wikipedia/en/thumb/a/a6/Phoenix_Mercury_logo.svg/330px-Phoenix_Mercury_logo.svg.png" }, {"tid": 10, "cid": 1, "did": 1, "region": "Seattle", "name": "Storm", "abbrev": "SEA", "pop": 3.0,"imgURL":"https://upload.wikimedia.org/wikipedia/en/thumb/a/ac/Seattle_Storm_logo.svg/330px-Seattle_Storm_logo.svg.png" }, {"tid": 11, "cid": 0, "did": 0, "region": "Washington", "name": "Mystics", "abbrev": "WAS", "pop": 4.2,"imgURL":"https://upload.wikimedia.org/wikipedia/en/thumb/7/79/Washington_Mystics_logo.svg/330px-Washington_Mystics_logo.svg.png" } ] }
firebrettbrown/bbgm
<|start_filename|>src/SecureOTA.cpp<|end_filename|> /* Copyright (c) 2014-present PlatformIO <<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. **/ #include <WiFiClientSecure.h> #include <Update.h> #include <BintrayClient.h> #include "SecureOTA.h" const BintrayClient bintray(BINTRAY_USER, BINTRAY_REPO, BINTRAY_PACKAGE); // Connection port (HTTPS) const int port = 443; // Connection timeout const uint32_t RESPONSE_TIMEOUT_MS = 5000; // Variables to validate firmware content volatile int contentLength = 0; volatile bool isValidContentType = false; void checkFirmwareUpdates() { // Fetch the latest firmware version const String latest = bintray.getLatestVersion(); if (latest.length() == 0) { Serial.println("Could not load info about the latest firmware, so nothing to update. Continue ..."); return; } else if (atoi(latest.c_str()) <= VERSION) { //Serial.println("The current firmware is up to date. Continue ..."); return; } Serial.println("There is a new version of firmware available: v." + latest); processOTAUpdate(latest); } // A helper function to extract header value from header inline String getHeaderValue(String header, String headerName) { return header.substring(strlen(headerName.c_str())); } /** * OTA update processing */ void processOTAUpdate(const String &version) { String firmwarePath = bintray.getBinaryPath(version); if (!firmwarePath.endsWith(".bin")) { Serial.println("Unsupported binary format. OTA update cannot be performed!"); return; } String currentHost = bintray.getStorageHost(); String prevHost = currentHost; WiFiClientSecure client; client.setCACert(bintray.getCertificate(currentHost)); if (!client.connect(currentHost.c_str(), port)) { Serial.println("Cannot connect to " + currentHost); return; } bool redirect = true; while (redirect) { if (currentHost != prevHost) { client.stop(); client.setCACert(bintray.getCertificate(currentHost)); if (!client.connect(currentHost.c_str(), port)) { Serial.println("Redirect detected! Cannot connect to " + currentHost + " for some reason!"); return; } } //Serial.println("Requesting: " + firmwarePath); client.print(String("GET ") + firmwarePath + " HTTP/1.1\r\n"); client.print(String("Host: ") + currentHost + "\r\n"); client.print("Cache-Control: no-cache\r\n"); client.print("Connection: close\r\n\r\n"); unsigned long timeout = millis(); while (client.available() == 0) { if (millis() - timeout > RESPONSE_TIMEOUT_MS) { Serial.println("Client Timeout !"); client.stop(); return; } } while (client.available()) { String line = client.readStringUntil('\n'); // Check if the line is end of headers by removing space symbol line.trim(); // if the the line is empty, this is the end of the headers if (!line.length()) { break; // proceed to OTA update } // Check allowed HTTP responses if (line.startsWith("HTTP/1.1")) { if (line.indexOf("200") > 0) { //Serial.println("Got 200 status code from server. Proceeding to firmware flashing"); redirect = false; } else if (line.indexOf("302") > 0) { //Serial.println("Got 302 status code from server. Redirecting to the new address"); redirect = true; } else { //Serial.println("Could not get a valid firmware url"); //Unexptected HTTP response. Retry or skip update? redirect = false; } } // Extracting new redirect location if (line.startsWith("Location: ")) { String newUrl = getHeaderValue(line, "Location: "); //Serial.println("Got new url: " + newUrl); newUrl.remove(0, newUrl.indexOf("//") + 2); currentHost = newUrl.substring(0, newUrl.indexOf('/')); newUrl.remove(newUrl.indexOf(currentHost), currentHost.length()); firmwarePath = newUrl; //Serial.println("firmwarePath: " + firmwarePath); continue; } // Checking headers if (line.startsWith("Content-Length: ")) { contentLength = atoi((getHeaderValue(line, "Content-Length: ")).c_str()); Serial.println("Got " + String(contentLength) + " bytes from server"); } if (line.startsWith("Content-Type: ")) { String contentType = getHeaderValue(line, "Content-Type: "); //Serial.println("Got " + contentType + " payload."); if (contentType == "application/octet-stream") { isValidContentType = true; } } } } // check whether we have everything for OTA update if (contentLength && isValidContentType) { if (Update.begin(contentLength)) { Serial.println("Starting Over-The-Air update. This may take some time to complete ..."); size_t written = Update.writeStream(client); if (written == contentLength) { Serial.println("Written : " + String(written) + " successfully"); } else { Serial.println("Written only : " + String(written) + "/" + String(contentLength) + ". Retry?"); // Retry?? } if (Update.end()) { if (Update.isFinished()) { Serial.println("OTA update has successfully completed. Rebooting ..."); ESP.restart(); } else { Serial.println("Something went wrong! OTA update hasn't been finished properly."); } } else { Serial.println("An error Occurred. Error #: " + String(Update.getError())); } } else { Serial.println("There isn't enough space to start OTA update"); client.flush(); } } else { Serial.println("There was no valid content in the response from the OTA server!"); client.flush(); } } <|start_filename|>test/test_bintray_client.cpp<|end_filename|> #include <Arduino.h> #include <unity.h> #include <BintrayClient.h> #include <WiFi.h> const BintrayClient bintray(BINTRAY_USER, BINTRAY_REPO, BINTRAY_PACKAGE); // void setUp(void) { // } // void tearDown(void) { // // clean stuff up here // } void test_wifi_connection(void) { const int RESPONSE_TIMEOUT_MS = 5000; unsigned long timeout = millis(); WiFi.begin(WIFI_SSID, WIFI_PASS); while (WiFi.status() != WL_CONNECTED) { if (millis() - timeout > RESPONSE_TIMEOUT_MS) { TEST_FAIL_MESSAGE("WiFi connection timeout. Please check your settings!"); } delay(500); } TEST_ASSERT_TRUE(WiFi.isConnected()); } void test_bintray_client_credentials(void) { TEST_ASSERT_EQUAL_STRING(BINTRAY_USER, bintray.getUser().c_str()); TEST_ASSERT_EQUAL_STRING(BINTRAY_REPO, bintray.getRepository().c_str()); TEST_ASSERT_EQUAL_STRING(BINTRAY_PACKAGE, bintray.getPackage().c_str()); } void test_bintray_latest_version_is_not_empty(void) { const String version = bintray.getLatestVersion(); TEST_ASSERT_TRUE(version.length() > 0); TEST_ASSERT_TRUE(atoi(version.c_str()) != 0); } void test_bintray_binary_path_is_valid(void) { const String binaryPath = bintray.getBinaryPath(bintray.getLatestVersion()); TEST_ASSERT_TRUE(binaryPath.length() > 0); TEST_ASSERT_TRUE(binaryPath.endsWith(".bin")); TEST_ASSERT_TRUE(binaryPath.indexOf(BINTRAY_USER) > 0); } void setup() { delay(2000); UNITY_BEGIN(); RUN_TEST(test_bintray_client_credentials); RUN_TEST(test_wifi_connection); RUN_TEST(test_bintray_latest_version_is_not_empty); RUN_TEST(test_bintray_binary_path_is_valid); UNITY_END(); } void loop() {}
bpapesh/testTravis
<|start_filename|>src/index.js<|end_filename|> var CoCreateOverlayScroll = (function() { var _base; var SCROLLBAR_WIDTH = getScrollbarWidth(); var CLASSNAMES = { element: 'co_overlay-scroll', verticalScrollbar: 'co_scrollbar _vertical', horizontalScrollbar: 'co_scrollbar _horizontal', thumb: 'thumb', view: 'co_overlay-viewport', disable: 'co_scrollbar-disable-selection', prevented: 'co_prevented', resizeTrigger: 'co_resize-trigger', }; function getScrollbarWidth() { var e = document.createElement('div'), sw; e.style.position = 'absolute'; e.style.top = '-9999px'; e.style.width = '100px'; e.style.height = '100px'; e.style.overflow = 'scroll'; e.style.msOverflowStyle = 'scrollbar'; document.body.appendChild(e); sw = (e.offsetWidth - e.clientWidth); document.body.removeChild(e); return sw; } function isSubstr (str, sub) { if(str.indexOf(sub) > -1) return true; return false; } function addClass(el, classNames) { if (el.classList) { return classNames.forEach(function(cl) { el.classList.add(cl); }); } el.className += ' ' + classNames.join(' '); } function removeClass(el, classNames) { if (el.classList) { return classNames.forEach(function(cl) { el.classList.remove(cl); }); } el.className = el.className.replace(new RegExp('(^|\\b)' + classNames.join('|') + '(\\b|$)', 'gi'), ' '); } function innerDomElement ( target, selector, isInnerWrap = false) { var innerEle = target.querySelector(selector); if(!innerEle) { innerEle = document.createElement('div'); if(isInnerWrap){ while(target.childNodes.length > 0) { innerEle.appendChild(target.childNodes[0]); } } target.appendChild(innerEle); } return innerEle; } function isIE() { var agent = navigator.userAgent.toLowerCase(); return agent.indexOf("msie") !== -1 || agent.indexOf("trident") !== -1 || agent.indexOf(" edge/") !== -1; } function ScrollInstance(el) { var _instance = { element : el, options : { visible: 'show', hScroll: { behavior: 'scroll', pos: 'bottom' }, vScroll: { behavior: 'scroll', pos: 'right' } }, forceGemini : false, onResize : null, minThumbSize : 20, _cache : {events: {}}, _cursorDown : false, _prevPageX : 0, _prevPageY : 0, _document : null, _viewElement : null, _scrollbarVerticalElement : null, _thumbVerticalElement : null, _scrollbarHorizontalElement : null, _scrollbarHorizontalElement : null } _instance.initDomOptions = function() { var scrollTypes = this.element.dataset.overlayScroll_type; if(typeof scrollTypes !== 'undefined'){ scrollTypes = scrollTypes.toLowerCase(); this.options.hScroll.behavior = isSubstr(scrollTypes, 'scrollx') ? "scroll" : "_disabled"; this.options.vScroll.behavior = isSubstr(scrollTypes, 'scrolly') ? "scroll" : "_disabled"; } var scrollPos = this.element.dataset.overlayScroll_pos; if(typeof scrollPos !== 'undefined'){ scrollPos = scrollPos.toLowerCase(); this.options.hScroll.pos = isSubstr(scrollPos, 'top') ? 'top' : 'bottom'; this.options.vScroll.pos = isSubstr(scrollPos, 'left') ? 'left' : 'right'; } var scrollVisible = this.element.dataset.overlayScroll_visible; var visibles = ['show', 'hide', 'auto']; if(typeof scrollVisible !== 'undefined'){ scrollVisible = scrollVisible.toLowerCase(); this.options.visible = visibles.indexOf(scrollVisible) > -1 ? scrollVisible : 'show'; } console.log(this.options); } _instance.create = function() { this.initDomOptions(); if ( !SCROLLBAR_WIDTH ) { addClass(this.element, [CLASSNAMES.prevented]); if (this.onResize) { this._viewElement = innerDomElement(this.element, ':scope > .' + CLASSNAMES.view, true); addClass(this._viewElement, [CLASSNAMES.view]); this._createResizeTrigger(); } } else { var targetClassNames = [] if(this.options.visible !== 'show') targetClassNames.push('scroll-' + this.options.visible); if(this.options.hScroll.behavior !== 'scroll') targetClassNames.push('horizontal' + this.options.hScroll.behavior); if(this.options.vScroll.behavior !== 'scroll') targetClassNames.push('vertical' + this.options.vScroll.behavior); addClass(this.element, targetClassNames); this._document = document; this._viewElement = innerDomElement(this.element, ':scope > .' + CLASSNAMES.view, true); addClass(this._viewElement, [CLASSNAMES.view]); this._scrollbarHorizontalElement = innerDomElement(this.element, ':scope > .' + CLASSNAMES.horizontalScrollbar.split(' ').join('.')); this._thumbHorizontalElement = innerDomElement(this._scrollbarHorizontalElement, ':scope > .' + CLASSNAMES.thumb); var hScrollClassNames = CLASSNAMES.horizontalScrollbar.split(/\s/); hScrollClassNames.push(this.options.hScroll.pos); addClass(this._scrollbarHorizontalElement, hScrollClassNames); addClass(this._thumbHorizontalElement, [CLASSNAMES.thumb]); this._scrollbarVerticalElement = innerDomElement(this.element, ':scope > .' + CLASSNAMES.verticalScrollbar.split(' ').join('.')); this._thumbVerticalElement = innerDomElement(this._scrollbarVerticalElement, ':scope > .' + CLASSNAMES.thumb); var vScrollClassNames = CLASSNAMES.verticalScrollbar.split(/\s/); vScrollClassNames.push(this.options.vScroll.pos); addClass(this._scrollbarVerticalElement, vScrollClassNames); addClass(this._thumbVerticalElement, [CLASSNAMES.thumb]); } this._createResizeTrigger(); return this._bindEvents().update(); }; _instance._createResizeTrigger = function() { var obj = document.createElement('object'); addClass(obj, [CLASSNAMES.resizeTrigger]); obj.type = 'text/html'; obj.setAttribute('tabindex', '-1'); var resizeHandler = this._resizeHandler.bind(this); obj.onload = function () { var win = obj.contentDocument.defaultView; win.addEventListener('resize', resizeHandler); }; if (!isIE()) obj.data = 'about:blank'; this.element.appendChild(obj); if (isIE()) obj.data = 'about:blank'; this._resizeTriggerElement = obj; }; _instance.update = function() { if (!SCROLLBAR_WIDTH) return this; this._viewElement.style.width = ((this.element.offsetWidth + SCROLLBAR_WIDTH).toString() + 'px'); this._viewElement.style.height = ((this.element.offsetHeight + SCROLLBAR_WIDTH).toString() + 'px'); this._naturalThumbSizeX = this._scrollbarHorizontalElement.clientWidth / this._viewElement.scrollWidth * this._scrollbarHorizontalElement.clientWidth; this._naturalThumbSizeY = this._scrollbarVerticalElement.clientHeight / this._viewElement.scrollHeight * this._scrollbarVerticalElement.clientHeight; this._scrollTopMax = this._viewElement.scrollHeight - this._viewElement.clientHeight; this._scrollLeftMax = this._viewElement.scrollWidth - this._viewElement.clientWidth; if (this._naturalThumbSizeY < this.minThumbSize) { this._thumbVerticalElement.style.height = this.minThumbSize + 'px'; } else if (this._scrollTopMax) { this._thumbVerticalElement.style.height = this._naturalThumbSizeY + 'px'; } else { this._thumbVerticalElement.style.height = '0px'; } if (this._naturalThumbSizeX < this.minThumbSize) { this._thumbHorizontalElement.style.width = this.minThumbSize + 'px'; } else if (this._scrollLeftMax) { this._thumbHorizontalElement.style.width = this._naturalThumbSizeX + 'px'; } else { this._thumbHorizontalElement.style.width = '0px'; } this._thumbSizeY = this._thumbVerticalElement.clientHeight; this._thumbSizeX = this._thumbHorizontalElement.clientWidth; this._trackTopMax = this._scrollbarVerticalElement.clientHeight - this._thumbSizeY; this._trackLeftMax = this._scrollbarHorizontalElement.clientWidth - this._thumbSizeX; this._scrollHandler(); return this; }; _instance.destroy = function() { if (this._resizeTriggerElement) { this.element.removeChild(this._resizeTriggerElement); this._resizeTriggerElement = null; } if (!SCROLLBAR_WIDTH) return this; this._unbinEvents(); removeClass(this.element, [CLASSNAMES.element, 'scroll-' + this.options.visible]); this.element.removeChild(this._scrollbarVerticalElement); this.element.removeChild(this._scrollbarHorizontalElement); while(this._viewElement.childNodes.length > 0) { this.element.appendChild(this._viewElement.childNodes[0]); } this.element.removeChild(this._viewElement); this._document = null; return null; }; _instance._bindEvents = function() { this._cache.events.scrollHandler = this._scrollHandler.bind(this); this._cache.events.clickVerticalTrackHandler = this._clickVerticalTrackHandler.bind(this); this._cache.events.clickHorizontalTrackHandler = this._clickHorizontalTrackHandler.bind(this); this._cache.events.clickVerticalThumbHandler = this._clickVerticalThumbHandler.bind(this); this._cache.events.clickHorizontalThumbHandler = this._clickHorizontalThumbHandler.bind(this); this._cache.events.mouseUpDocumentHandler = this._mouseUpDocumentHandler.bind(this); this._cache.events.mouseMoveDocumentHandler = this._mouseMoveDocumentHandler.bind(this); this._viewElement.addEventListener('scroll', this._cache.events.scrollHandler); this._scrollbarVerticalElement.addEventListener('mousedown', this._cache.events.clickVerticalTrackHandler); this._scrollbarHorizontalElement.addEventListener('mousedown', this._cache.events.clickHorizontalTrackHandler); this._thumbVerticalElement.addEventListener('mousedown', this._cache.events.clickVerticalThumbHandler); this._thumbHorizontalElement.addEventListener('mousedown', this._cache.events.clickHorizontalThumbHandler); this._document.addEventListener('mouseup', this._cache.events.mouseUpDocumentHandler); return this; }; _instance._unbinEvents = function() { this._viewElement.removeEventListener('scroll', this._cache.events.scrollHandler); this._scrollbarVerticalElement.removeEventListener('mousedown', this._cache.events.clickVerticalTrackHandler); this._scrollbarHorizontalElement.removeEventListener('mousedown', this._cache.events.clickHorizontalTrackHandler); this._thumbVerticalElement.removeEventListener('mousedown', this._cache.events.clickVerticalThumbHandler); this._thumbHorizontalElement.removeEventListener('mousedown', this._cache.events.clickHorizontalThumbHandler); this._document.removeEventListener('mouseup', this._cache.events.mouseUpDocumentHandler); this._document.removeEventListener('mousemove', this._cache.events.mouseMoveDocumentHandler); return this; }; _instance._scrollHandler = function() { var x = (this._viewElement.scrollLeft * this._trackLeftMax / this._scrollLeftMax) || 0; var y = (this._viewElement.scrollTop * this._trackTopMax / this._scrollTopMax) || 0; this._thumbHorizontalElement.style.msTransform = 'translateX(' + x + 'px)'; this._thumbHorizontalElement.style.webkitTransform = 'translate3d(' + x + 'px, 0, 0)'; this._thumbHorizontalElement.style.transform = 'translate3d(' + x + 'px, 0, 0)'; if(this.options.vScroll.behavior == 'scroll'){ this._thumbVerticalElement.style.msTransform = 'translateY(' + y + 'px)'; this._thumbVerticalElement.style.webkitTransform = 'translate3d(0, ' + y + 'px, 0)'; this._thumbVerticalElement.style.transform = 'translate3d(0, ' + y + 'px, 0)'; } }; _instance._resizeHandler = function() { this.update(); if (this.onResize) { this.onResize(); } }; _instance._clickVerticalTrackHandler = function(e) { if(e.target !== e.currentTarget) { return; } var offset = e.offsetY - this._naturalThumbSizeY * .5 , thumbPositionPercentage = offset * 100 / this._scrollbarVerticalElement.clientHeight; this._viewElement.scrollTop = thumbPositionPercentage * this._viewElement.scrollHeight / 100; }; _instance._clickHorizontalTrackHandler = function(e) { if(e.target !== e.currentTarget) { return; } var offset = e.offsetX - this._naturalThumbSizeX * .5 , thumbPositionPercentage = offset * 100 / this._scrollbarHorizontalElement.clientWidth; this._viewElement.scrollLeft = thumbPositionPercentage * this._viewElement.scrollWidth / 100; }; _instance._clickVerticalThumbHandler = function(e) { this._startDrag(e); this._prevPageY = this._thumbSizeY - e.offsetY; }; _instance._clickHorizontalThumbHandler = function(e) { this._startDrag(e); this._prevPageX = this._thumbSizeX - e.offsetX; }; _instance._startDrag = function(e) { this._cursorDown = true; addClass(document.body, [CLASSNAMES.disable]); this._document.addEventListener('mousemove', this._cache.events.mouseMoveDocumentHandler); this._document.onselectstart = function() {return false;}; }; _instance._mouseUpDocumentHandler = function() { this._cursorDown = false; this._prevPageX = this._prevPageY = 0; removeClass(document.body, [CLASSNAMES.disable]); this._document.removeEventListener('mousemove', this._cache.events.mouseMoveDocumentHandler); this._document.onselectstart = null; }; _instance._mouseMoveDocumentHandler = function(e) { if (this._cursorDown === false) {return;} var offset, thumbClickPosition; if (this._prevPageY) { offset = e.clientY - this._scrollbarVerticalElement.getBoundingClientRect().top; thumbClickPosition = this._thumbSizeY - this._prevPageY; this._viewElement.scrollTop = this._scrollTopMax * (offset - thumbClickPosition) / this._trackTopMax; return void 0; } if (this._prevPageX) { offset = e.clientX - this._scrollbarHorizontalElement.getBoundingClientRect().left; thumbClickPosition = this._thumbSizeX - this._prevPageX; this._viewElement.scrollLeft = this._scrollLeftMax * (offset - thumbClickPosition) / this._trackLeftMax; } }; _instance.create(); return _instance; } _base = { _objects: [], init: function() { var scrollEles = document.querySelectorAll('.co_overlay-scroll'); for(var i = 0; i < scrollEles.length; i++){ this.createObj(scrollEles[i]); } }, checkExistObj: function(el) { for(var i = 0; i < this._objects.length; i++){ if(el.isSameNode(this._objects[i].el)) return true; } return false; }, createObj: function(el) { if(this.checkExistObj(el)) return; this._objects.push(new ScrollInstance(el)); } }; return _base; })(); window.onload = function(){ CoCreateOverlayScroll.init(); } export default CoCreateOverlayScroll; <|start_filename|>overlay-scroll-archive/CoCreate-overlay-scroll.js<|end_filename|> // CoCreate OverlayScrollbar var CoCreateOverlayScroll = (function() { var _base; var _globals; var VENDOR = (function () { var jsCache = {}; var cssCache = {}; var cssPrefixes = ['-webkit-', '-moz-', '-o-', '-ms-']; var jsPrefixes = ['WebKit', 'Moz', 'O', 'MS']; function firstLetterToUpper(str) { return str.charAt(0).toUpperCase() + str.slice(1); } return { _cssPrefixes: cssPrefixes, _jsPrefixes: jsPrefixes, _cssProperty: function (name) { var result = cssCache[name]; if (cssCache.hasOwnProperty(name)) return result; var uppercasedName = firstLetterToUpper(name); var elmStyle = document.createElement('div').style; var resultPossibilities; var i = 0; var v; var currVendorWithoutDashes; for (; i < cssPrefixes.length; i++) { currVendorWithoutDashes = cssPrefixes[i].replace(/-/g, ''); resultPossibilities = [ name, cssPrefixes[i] + name, currVendorWithoutDashes + uppercasedName, firstLetterToUpper(currVendorWithoutDashes) + uppercasedName ]; for (v = 0; v < resultPossibilities.length; v++) { if (elmStyle[resultPossibilities[v]] !== undefined) { result = resultPossibilities[v]; break; } } } cssCache[name] = result; return result; }, _jsAPI: function (name, isInterface, fallback) { var i = 0; var result = jsCache[name]; if (!jsCache.hasOwnProperty(name)) { result = window[name]; for (; i < jsPrefixes.length; i++) result = result || window[(isInterface ? jsPrefixes[i] : jsPrefixes[i].toLowerCase()) + firstLetterToUpper(name)]; jsCache[name] = result; } return result || fallback; } } })(); var COMPAT = (function () { function windowSize(x) { return x ? window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth : window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight; } function bind(func, thisObj) { if (typeof func != 'function') { throw "Can't bind function!"; } var aArgs = Array['prototype'].slice.call(arguments, 2); var fNOP = function () { }; var fBound = function () { return func.apply(this instanceof fNOP ? this : thisObj, aArgs.concat(Array['prototype'].slice.call(arguments))); }; if (func['prototype']) fNOP['prototype'] = func['prototype']; fBound['prototype'] = new fNOP(); return fBound; } return { wW: bind(windowSize, 0, true), wH: bind(windowSize, 0), rAF: bind(VENDOR._jsAPI, 0, 'requestAnimationFrame', false, function (func) { return window.setTimeout(func, 1000 / 60); }), stpP: function (event) { if (event.stopPropagation) event.stopPropagation(); else event.cancelBubble = true; }, prvD: function (event) { if (event.preventDefault && event.cancelable) event.preventDefault(); else event.returnValue = false; }, page: function (event) { event = event.originalEvent || event; var strPage = 'page'; var strClient = 'client'; var strX = 'X'; var strY = 'Y'; var target = event.target || event.srcElement || document; var eventDoc = target.ownerDocument || document; var doc = eventDoc.documentElement; var body = eventDoc.body; if (event.touches !== undefined) { var touch = event.touches[0]; return { x: touch[strPage + strX], y: touch[strPage + strY] } } if (!event[strPage + strX] && event[strClient + strX] && event[strClient + strX] != null) { return { x: event[strClient + strX] + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0), y: event[strClient + strY] + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc && doc.clientTop || body && body.clientTop || 0) } } return { x: event[strPage + strX], y: event[strPage + strY] }; }, mBtn: function (event) { var button = event.button; if (!event.which && button !== undefined) return (button & 1 ? 1 : (button & 2 ? 3 : (button & 4 ? 2 : 0))); else return event.which; }, inA: function (item, arr) { for (var i = 0; i < arr.length; i++) try { if (arr[i] === item) return i; } catch (e) { } return -1; }, isA: function (arr) { var def = Array.isArray; return def ? def(arr) : this.type(arr) == 'array'; }, type: function (obj) { if (obj === undefined) return obj + ''; if (obj === null) return obj + ''; return Object.prototype.toString.call(obj).replace(/^\[object (.+)\]$/, '$1').toLowerCase(); }, bind: bind } })(); var Utils = (function () { var _rnothtmlwhite = (/[^\x20\t\r\n\f]+/g); var _type = COMPAT.type; var _cssNumber = { animationIterationCount: true, columnCount: true, fillOpacity: true, flexGrow: true, flexShrink: true, fontWeight: true, lineHeight: true, opacity: true, order: true, orphans: true, widows: true, zIndex: true, zoom: true }; function extend() { var src, copyIsArray, copy, name, options, clone, target = arguments[0] || {}, i = 1, length = arguments.length, deep = false; if (_type(target) == 'boolean') { deep = target; target = arguments[1] || {}; i = 2; } if (_type(target) != 'object' && !_type(target) == 'function') { target = {}; } if (length === i) { target = FakejQuery; --i; } for (; i < length; i++) { if ((options = arguments[i]) != null) { for (name in options) { src = target[name]; copy = options[name]; if (target === copy) continue; if (deep && copy && (isPlainObject(copy) || (copyIsArray = COMPAT.isA(copy)))) { if (copyIsArray) { copyIsArray = false; clone = src && COMPAT.isA(src) ? src : []; } else { clone = src && isPlainObject(src) ? src : {}; } target[name] = extend(deep, clone, copy); } else if (copy !== undefined) { target[name] = copy; } } } } return target; }; function inArray(item, arr, fromIndex) { for (var i = fromIndex || 0; i < arr.length; i++) if (arr[i] === item) return i; return -1; } function isSubstr(str, sub) { if(str.indexOf(sub) > -1) return true; return false; } function isFunction(obj) { return _type(obj) == 'function'; }; function isEmptyObject(obj) { for (var name in obj) if(obj.hasOwnProperty(name)) return false; return true; }; function isPlainObject(obj) { if (!obj || _type(obj) != 'object') return false; var key; var proto = 'prototype'; var hasOwnProperty = Object[proto].hasOwnProperty; var hasOwnConstructor = hasOwnProperty.call(obj, 'constructor'); var hasIsPrototypeOf = obj.constructor && obj.constructor[proto] && hasOwnProperty.call(obj.constructor[proto], 'isPrototypeOf'); if (obj.constructor && !hasOwnConstructor && !hasIsPrototypeOf) return false; for (key in obj) { /**/ } return _type(key) == 'undefined' || hasOwnProperty.call(obj, key); }; function each(obj, callback) { var i = 0; if (isArrayLike(obj)) { for (; i < obj.length; i++) { if (callback.call(obj[i], i, obj[i]) === false) break; } } else { for (i in obj) { if (callback.call(obj[i], i, obj[i]) === false) break; } } return obj; }; function isArrayLike(obj) { var length = !!obj && 'length' in obj && obj.length; var t = _type(obj); return isFunction(t) ? false : (t == 'array' || length === 0 || _type(length) == 'number' && length > 0 && (length - 1) in obj); } function stripAndCollapse(value) { var tokens = value.match(_rnothtmlwhite) || []; return tokens.join(' '); } function matches(elem, selector) { var nodeList = (elem.parentNode || document).querySelectorAll(selector) || []; var i = nodeList.length; while (i--) if (nodeList[i] == elem) return true; return false; } function insertAdjacentElement(el, strategy, child) { if (COMPAT.isA(child)) { for (var i = 0; i < child.length; i++) insertAdjacentElement(el, strategy, child[i]); } else if (_type(child) == 'string') el.insertAdjacentHTML(strategy, child); else el.insertAdjacentElement(strategy, child.nodeType ? child : child[0]); } function setCSSVal(el, prop, val) { try { if (el.style[prop] !== undefined) el.style[prop] = parseCSSVal(prop, val); } catch (e) { } } function parseCSSVal(prop, val) { if (!_cssNumber[prop.toLowerCase()] && _type(val) == 'number') val += 'px'; return val; } function elementIsVisible(el) { return !!(el.offsetWidth || el.offsetHeight || el.getClientRects().length); } function FakejQuery(selector) { if (arguments.length === 0) return this; var base = new FakejQuery(); var elements = selector; var i = 0; var elms; var el; if (_type(selector) == 'string') { elements = []; if (selector.charAt(0) === '<') { el = document.createElement('div'); el.innerHTML = selector; elms = el.children; } else elms = document.querySelectorAll(selector); for (; i < elms.length; i++) elements.push(elms[i]); } if (elements) { if (_type(elements) != 'string' && (!isArrayLike(elements) || elements === window || elements === elements.self)) elements = [elements]; for (i = 0; i < elements.length; i++) base[i] = elements[i]; base.length = elements.length; } return base; }; FakejQuery.prototype = { on: function (eventName, handler) { eventName = (eventName || '').match(_rnothtmlwhite) || ['']; var eventNameLength = eventName.length; var i = 0; var el; return this.each(function () { el = this; try { if (el.addEventListener) { for (; i < eventNameLength; i++) el.addEventListener(eventName[i], handler); } else if (el.detachEvent) { for (; i < eventNameLength; i++) el.attachEvent('on' + eventName[i], handler); } } catch (e) { } }); }, off: function (eventName, handler) { eventName = (eventName || '').match(_rnothtmlwhite) || ['']; var eventNameLength = eventName.length; var i = 0; var el; return this.each(function () { el = this; try { if (el.removeEventListener) { for (; i < eventNameLength; i++) el.removeEventListener(eventName[i], handler); } else if (el.detachEvent) { for (; i < eventNameLength; i++) el.detachEvent('on' + eventName[i], handler); } } catch (e) { } }); }, one: function (eventName, handler) { eventName = (eventName || '').match(_rnothtmlwhite) || ['']; return this.each(function () { var el = FakejQuery(this); FakejQuery.each(eventName, function (i, oneEventName) { var oneHandler = function (e) { handler.call(this, e); el.off(oneEventName, oneHandler); }; el.on(oneEventName, oneHandler); }); }); }, trigger: function (eventName) { var el; var event; return this.each(function () { el = this; if (document.createEvent) { event = document.createEvent('HTMLEvents'); event.initEvent(eventName, true, false); el.dispatchEvent(event); } else el.fireEvent('on' + eventName); }); }, append: function (child) { return this.each(function () { insertAdjacentElement(this, 'beforeend', child); }); }, prepend: function (child) { return this.each(function () { insertAdjacentElement(this, 'afterbegin', child); }); }, before: function (child) { return this.each(function () { insertAdjacentElement(this, 'beforebegin', child); }); }, after: function (child) { return this.each(function () { insertAdjacentElement(this, 'afterend', child); }); }, remove: function () { return this.each(function () { var el = this; var parentNode = el.parentNode; if (parentNode != null) parentNode.removeChild(el); }); }, unwrap: function () { var parents = []; var i; var el; var parent; this.each(function () { parent = this.parentNode; if (inArray(parent, parents) === - 1) parents.push(parent); }); for (i = 0; i < parents.length; i++) { el = parents[i]; parent = el.parentNode; while (el.firstChild) parent.insertBefore(el.firstChild, el); parent.removeChild(el); } return this; }, wrapAll: function (wrapperHTML) { var i; var nodes = this; var wrapper = FakejQuery(wrapperHTML)[0]; var deepest = wrapper; var parent = nodes[0].parentNode; var previousSibling = nodes[0].previousSibling; while (deepest.childNodes.length > 0) deepest = deepest.childNodes[0]; for (i = 0; nodes.length - i; deepest.firstChild === nodes[0] && i++) deepest.appendChild(nodes[i]); var nextSibling = previousSibling ? previousSibling.nextSibling : parent.firstChild; parent.insertBefore(wrapper, nextSibling); return this; }, wrapInner: function (wrapperHTML) { return this.each(function () { var el = FakejQuery(this); var contents = el.contents(); if (contents.length) contents.wrapAll(wrapperHTML); else el.append(wrapperHTML); }); }, wrap: function (wrapperHTML) { return this.each(function () { FakejQuery(this).wrapAll(wrapperHTML); }); }, css: function (styles, val) { var el; var key; var cptStyle; var getCptStyle = window.getComputedStyle; if (_type(styles) == 'string') { if (val === undefined) { el = this[0]; cptStyle = getCptStyle ? getCptStyle(el, null) : el.currentStyle[styles]; return getCptStyle ? cptStyle != null ? cptStyle.getPropertyValue(styles) : el.style[styles] : cptStyle; } else { return this.each(function () { setCSSVal(this, styles, val); }); } } else { return this.each(function () { for (key in styles) setCSSVal(this, key, styles[key]); }); } }, hasClass: function (className) { var elem, i = 0; var classNamePrepared = ' ' + className + ' '; var classList; while ((elem = this[i++])) { classList = elem.classList; if (classList && classList.contains(className)) return true; else if (elem.nodeType === 1 && (' ' + stripAndCollapse(elem.className + '') + ' ').indexOf(classNamePrepared) > -1) return true; } return false; }, addClass: function (className) { var classes; var elem; var cur; var curValue; var clazz; var finalValue; var supportClassList; var elmClassList; var i = 0; var v = 0; if (className) { classes = className.match(_rnothtmlwhite) || []; while ((elem = this[i++])) { elmClassList = elem.classList; if (supportClassList === undefined) supportClassList = elmClassList !== undefined; if (supportClassList) { while ((clazz = classes[v++])) elmClassList.add(clazz); } else { curValue = elem.className + ''; cur = elem.nodeType === 1 && (' ' + stripAndCollapse(curValue) + ' '); if (cur) { while ((clazz = classes[v++])) if (cur.indexOf(' ' + clazz + ' ') < 0) cur += clazz + ' '; finalValue = stripAndCollapse(cur); if (curValue !== finalValue) elem.className = finalValue; } } } } return this; }, removeClass: function (className) { var classes; var elem; var cur; var curValue; var clazz; var finalValue; var supportClassList; var elmClassList; var i = 0; var v = 0; if (className) { classes = className.match(_rnothtmlwhite) || []; while ((elem = this[i++])) { elmClassList = elem.classList; if (supportClassList === undefined) supportClassList = elmClassList !== undefined; if (supportClassList) { while ((clazz = classes[v++])) elmClassList.remove(clazz); } else { curValue = elem.className + ''; cur = elem.nodeType === 1 && (' ' + stripAndCollapse(curValue) + ' '); if (cur) { while ((clazz = classes[v++])) while (cur.indexOf(' ' + clazz + ' ') > -1) cur = cur.replace(' ' + clazz + ' ', ' '); finalValue = stripAndCollapse(cur); if (curValue !== finalValue) elem.className = finalValue; } } } } return this; }, hide: function () { return this.each(function () { this.style.display = 'none'; }); }, show: function () { return this.each(function () { this.style.display = 'block'; }); }, attr: function (attrName, value) { var i = 0; var el; while (el = this[i++]) { if (value === undefined) return el.getAttribute(attrName); el.setAttribute(attrName, value); } return this; }, removeAttr: function (attrName) { return this.each(function () { this.removeAttribute(attrName); }); }, offset: function () { var el = this[0]; var rect = el.getBoundingClientRect(); var scrollLeft = window.pageXOffset || document.documentElement['scrollLeft']; var scrollTop = window.pageYOffset || document.documentElement['scrollTop']; return { top: rect.top + scrollTop, left: rect.left + scrollLeft }; }, position: function () { var el = this[0]; return { top: el.offsetTop, left: el.offsetLeft }; }, scrollLeft: function (value) { var i = 0; var el; while (el = this[i++]) { if (value === undefined) return el['scrollLeft']; el['scrollLeft'] = value; } return this; }, scrollTop: function (value) { var i = 0; var el; while (el = this[i++]) { if (value === undefined) return el['scrollTop']; el['scrollTop'] = value; } return this; }, val: function (value) { var el = this[0]; if (!value) return el.value; el.value = value; return this; }, first: function () { return this.eq(0); }, last: function () { return this.eq(-1); }, eq: function (index) { return FakejQuery(this[index >= 0 ? index : this.length + index]); }, find: function (selector) { var children = []; var i; this.each(function () { var el = this; var ch = el.querySelectorAll(selector); for (i = 0; i < ch.length; i++) children.push(ch[i]); }); return FakejQuery(children); }, children: function (selector) { var children = []; var el; var ch; var i; this.each(function () { ch = this.children; for (i = 0; i < ch.length; i++) { el = ch[i]; if (selector) { if ((el.matches && el.matches(selector)) || matches(el, selector)) children.push(el); } else children.push(el); } }); return FakejQuery(children); }, parent: function (selector) { var parents = []; var parent; this.each(function () { parent = this.parentNode; if (selector ? FakejQuery(parent).is(selector) : true) parents.push(parent); }); return FakejQuery(parents); }, is: function (selector) { var el; var i; for (i = 0; i < this.length; i++) { el = this[i]; if (selector === ':visible') return elementIsVisible(el); if (selector === ':hidden') return !elementIsVisible(el); if ((el.matches && el.matches(selector)) || matches(el, selector)) return true; } return false; }, contents: function () { var contents = []; var childs; var i; this.each(function () { childs = this.childNodes; for (i = 0; i < childs.length; i++) contents.push(childs[i]); }); return FakejQuery(contents); }, each: function (callback) { return each(this, callback); }, }; extend(FakejQuery, { extend: extend, inArray: inArray, isSubstr: isSubstr, isEmptyObject: isEmptyObject, isPlainObject: isPlainObject, each: each }); return FakejQuery; })(); var _baseDefaultOptions = (function () { var type = COMPAT.type; var possibleTypes = ['boolean', 'number', 'string', 'array', 'object', 'function', 'null']; var ut = [['img'], ['string', 'array', 'null']]; var vv = 'v-h:visible-hidden v-s:visible-scroll s:scroll h:hidden'; var hv = 'v:visible h:hidden a:auto'; var sv = 'n:never s:scroll l:leave m:move'; var optionsDefaults = { className: ['co_theme-light', ['null', 'string']], autoUpdateInterval: [33, 'number'], updateOnLoad: ut, overflowBehavior: { x: ['scroll', vv], y: ['scroll', vv] }, scrollPos: { x: ['bottom', 'bottom top'], y: ['right', 'right left'] }, scrollbars: { visibility: ['visible', hv], autoHide: ['never', sv], autoHideDelay: [800, 'number'], dragScrolling: [true, 'boolean'], clickScrolling: [true, 'boolean'] }, }; var convert = function (template) { var recursive = function (obj) { var key; var val; var valType; for (key in obj) { if (!obj.hasOwnProperty(key)) continue; val = obj[key]; valType = type(val); if (valType == 'array') obj[key] = val[template ? 1 : 0]; else if (valType == 'object') obj[key] = recursive(val); } return obj; }; return recursive(Utils.extend(true, {}, optionsDefaults)); }; return { _defaults: convert(), _template: convert(true), _validate: function (obj, template, diffObj) { var validatedOptions = {}; var validatedOptionsPrepared = {}; var objectCopy = Utils.extend(true, {}, obj); var inArray = Utils.inArray; var isEmptyObj = Utils.isEmptyObject; var checkObjectProps = function (data, template, diffData, validatedOptions, validatedOptionsPrepared, prevPropName) { for (var prop in template) { if (template.hasOwnProperty(prop) && data.hasOwnProperty(prop)) { var isValid = false; var isDiff = false; var templateValue = template[prop]; var templateValueType = type(templateValue); var templateIsComplex = templateValueType == 'object'; var templateTypes = !COMPAT.isA(templateValue) ? [templateValue] : templateValue; var dataDiffValue = diffData[prop]; var dataValue = data[prop]; var dataValueType = type(dataValue); var propPrefix = prevPropName ? prevPropName + '.' : ''; var restrictSVS; var restrictSVPS; var isRestrictedValue; var mainPossibility; var currType; var i; var v; var j; dataDiffValue = dataDiffValue === undefined ? {} : dataDiffValue; if (templateIsComplex && dataValueType == 'object') { validatedOptions[prop] = {}; validatedOptionsPrepared[prop] = {}; checkObjectProps(dataValue, templateValue, dataDiffValue, validatedOptions[prop], validatedOptionsPrepared[prop], propPrefix + prop); Utils.each([data, validatedOptions, validatedOptionsPrepared], function (index, value) { if (isEmptyObj(value[prop])) { delete value[prop]; } }); } else if (!templateIsComplex) { for (i = 0; i < templateTypes.length; i++) { currType = templateTypes[i]; templateValueType = type(currType); isRestrictedValue = templateValueType == 'string' && inArray(currType, possibleTypes) === -1; if (isRestrictedValue) { restrictSVS = currType.split(' '); for (v = 0; v < restrictSVS.length; v++) { restrictSVPS = restrictSVS[v].split(':'); mainPossibility = restrictSVPS[0]; for (j = 0; j < restrictSVPS.length; j++) { if (dataValue === restrictSVPS[j]) { isValid = true; break; } } if (isValid) break; } } else { if (dataValueType === currType) { isValid = true; break; } } } if (isValid) { isDiff = dataValue !== dataDiffValue; if (isDiff) validatedOptions[prop] = dataValue; if (isRestrictedValue ? inArray(dataDiffValue, restrictSVPS) < 0 : isDiff) validatedOptionsPrepared[prop] = isRestrictedValue ? mainPossibility : dataValue; } delete data[prop]; } } } }; checkObjectProps(objectCopy, template, diffObj || {}, validatedOptions, validatedOptionsPrepared); return { _default: validatedOptions, _prepared: validatedOptionsPrepared }; } } }()); function scrollGlobals() { var _base = this; var msie = (function () { var ua = window.navigator.userAgent; var msie = ua.indexOf('MSIE '); var trident = ua.indexOf('Trident/'); var edge = ua.indexOf('Edge/'); var rv = ua.indexOf('rv:'); var result; if (msie > 0) result = parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10); else if (trident > 0) result = parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10); else if (edge > 0) result = parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10); return result; })(); Utils.extend(_base, { msie: msie, autoUpdateLoop: false, autoUpdateRecommended: false, overlayScrollbarDummySize: { x: 30, y: 30 }, supportPassiveEvents: (function () { var supportsPassive = false; try { window.addEventListener('test', null, Object.defineProperty({}, 'passive', { get: function () { supportsPassive = true; } })); } catch (e) { } return supportsPassive; })(), }); } function scrollInstance(el) { var _base = { element: el, options: {} }; var type = COMPAT.type; var each = Utils.each; var _frameworkProto = Utils.prototype; if (!isHTMLElement(el)) return; var _msieVersion; var _supportPassiveEvents; var _initialized; var _isBody; var _documentMixed; var _domExists; var _isBorderBox; var _sleeping; var _contentBorderSize = {}; var _scrollHorizontalInfo = {}; var _scrollVerticalInfo = {}; var _viewportSize = {}; var _strMinusHidden = '-hidden'; var _strMarginMinus = 'margin-'; var _sPadMins = 'padding-'; var _sBordMins = 'border-'; var _strMinMinus = 'min-'; var _strMaxMinus = 'max-'; var _strSync = 'sync'; var _strScroll = 'scroll'; var _strHundredPercent = '100%'; var _strScrollbar = 'scrollbar'; var _strMinusHorizontal = '-horizontal'; var _strMinusVertical = '-vertical'; var _strMouseTouchDownEvent = 'mousedown touchstart'; var _strMouseTouchUpEvent = 'mouseup touchend touchcancel'; var _strMouseTouchMoveEvent = 'mousemove touchmove'; var _strMouseEnter = 'mouseenter'; var _strMouseLeave = 'mouseleave'; var _strKeyDownEvent = 'keydown'; var _strKeyUpEvent = 'keyup'; var _strSelectStartEvent = 'selectstart'; var _cassNamesPrefix = 'co_'; var _classNameHTMLElement = _cassNamesPrefix + 'html'; var _classNameHostElement = _cassNamesPrefix + 'host'; var _classNameHostElementForeign = _classNameHostElement + '-foreign'; var _cHH = _classNameHostElement + '-' + _strScrollbar + _strMinusHorizontal + _strMinusHidden; var _cVH = _classNameHostElement + '-' + _strScrollbar + _strMinusVertical + _strMinusHidden; var _classNameHostTransition = _classNameHostElement + '-transition'; var _classNameHostScrolling = _classNameHostElement + '-scrolling'; var _classNameViewportElement = _cassNamesPrefix + 'viewport'; var _classNameContentElement = _cassNamesPrefix + 'content'; var _classNameScrollbar = _cassNamesPrefix + _strScrollbar; var _classNameScrollbarTrack = _classNameScrollbar + '-track'; var _classNameScrollbarTrackOff = _classNameScrollbarTrack + '-off'; var _classNameScrollbarHandle = _classNameScrollbar + '-handle'; var _classNameScrollbarHandleOff = _classNameScrollbarHandle + '-off'; var _classNameScrollbarUnusable = _classNameScrollbar + '-unusable'; var _classNameScrollbarAutoHidden = _classNameScrollbar + '-' + 'auto' + _strMinusHidden; var _classNameScrollbarHorizontal = _classNameScrollbar + _strMinusHorizontal; var _classNameScrollbarVertical = _classNameScrollbar + _strMinusVertical; var _classNameDragging = _cassNamesPrefix + 'dragging'; var _classNameThemeNone = _cassNamesPrefix + 'theme-none'; var _classNamesDynamicDestroy = [ _classNameScrollbarTrackOff, _classNameScrollbarHandleOff, _classNameScrollbarUnusable, _classNameScrollbarAutoHidden, _classNameDragging].join(' '); var _currentOptions; var _currentPreparedOptions; var _lastUpdateTime; var _swallowedUpdateHints = {}; var _swallowedUpdateTimeout; var _swallowUpdateLag = 42; var _updateOnLoadEventName = 'load'; var _updateOnLoadElms = []; var _wE; var _docE; var _htmlElement; var _bodyElement; var _tE; var _hostElement; var _viewportElement; var _contentElement; var _contentArrangeElement; var _sHE; var _sHTE; var _sHHE; var _sVE; var _sVTE; var _sVHE; var _wENative; var _docENative; var _hostElementNative; var _viewportElementNative; var _contentElementNative; var _hostSizeCache; var _contentScrollSizeCache; var _hasOverflowCache; var _hideOverflowCache; var _cssBoxSizingCache; var _cssPaddingCache; var _cssBorderCache; var _cssMarginCache; var _cssDirectionCache; var _overflowBehaviorCache; var _overflowAmountCache; var _esDCache; var _sVCache; var _scrollbarsAutoHideCache; var _scrollbarsClickScrollingCache; var _scrollbarsDragScrollingCache; var _classNameCache; var _oldClassName; var _bodyMinSizeCache; var _destroyEvents = []; var _scrollbarsAutoHideTimeoutId; var _scrollbarsAutoHideMoveTimeoutId; var _scrollbarsAutoHideDelay; var _scrollbarsAutoHideNever; var _scrollbarsAutoHideScroll; var _scrollbarsAutoHideMove; var _scrollbarsAutoHideLeave; var _scrollbarsHandleHovered; var _scrollbarsHandlesDefineScrollPos; function initOptions() { var options = {}; var scrollTypes = el.dataset.overlayScroll_type; if(typeof scrollTypes !== 'undefined'){ scrollTypes = scrollTypes.toLowerCase(); options.overflowBehavior = { x: Utils.isSubstr(scrollTypes, 'scrollx') ? "scroll" : "hidden", y: Utils.isSubstr(scrollTypes, 'scrolly') ? "scroll" : "hidden", } } var scrollPos = el.dataset.overlayScroll_pos; if(typeof scrollPos !== 'undefined'){ scrollPos = scrollPos.toLowerCase(); options.scrollPos = { x: Utils.isSubstr(scrollPos, 'top') ? 'top' : 'bottom', y: Utils.isSubstr(scrollPos, 'left') ? 'left' : 'right' } } var scrollVisible = el.dataset.overlayScroll_visible; if(typeof scrollVisible !== 'undefined'){ scrollVisible = scrollVisible.toLowerCase(); options.scrollbars = { visibility: scrollVisible == 'hide' ? 'hidden' : 'visible', autoHide: scrollVisible == 'auto' ? 'leave' : 'never', autoHideDelay : 100, }; } var validatedOpts = _baseDefaultOptions._validate(extendDeep({}, _baseDefaultOptions._defaults, options), _baseDefaultOptions._template, _currentOptions); _currentOptions = extendDeep({}, _currentOptions, validatedOpts._default); _currentPreparedOptions = extendDeep({}, _currentPreparedOptions, validatedOpts._prepared); } //==== Event Listener ====// function setupResponsiveEventListener(element, eventNames, listener, remove, passiveOrOptions) { var collected = COMPAT.isA(eventNames) && COMPAT.isA(listener); var method = remove ? 'removeEventListener' : 'addEventListener'; var onOff = remove ? 'off' : 'on'; var events = collected ? false : eventNames.split(' ') var i = 0; var passiveOrOptionsIsObj = Utils.isPlainObject(passiveOrOptions); var passive = _supportPassiveEvents && (passiveOrOptionsIsObj ? (passiveOrOptions._passive || false) : passiveOrOptions); var capture = passiveOrOptionsIsObj && (passiveOrOptions._capture || false); var useNative = capture || passive; var nativeParam = passive ? { passive: passive, capture: capture, } : capture; if (collected) { for (; i < eventNames.length; i++) setupResponsiveEventListener(element, eventNames[i], listener[i], remove, passiveOrOptions); } else { for (; i < events.length; i++) { if(useNative) { element[0][method](events[i], listener, nativeParam); } else { element[onOff](events[i], listener); } } } } function addDestroyEventListener(element, eventNames, listener, passive) { setupResponsiveEventListener(element, eventNames, listener, false, passive); _destroyEvents.push(COMPAT.bind(setupResponsiveEventListener, 0, element, eventNames, listener, true, passive)); } function hostOnMouseEnter() { if (_scrollbarsAutoHideLeave) refreshScrollbarsAutoHide(true); } function hostOnMouseLeave() { if (_scrollbarsAutoHideLeave && !_bodyElement.hasClass(_classNameDragging)) refreshScrollbarsAutoHide(false); } function hostOnMouseMove() { if (_scrollbarsAutoHideMove) { refreshScrollbarsAutoHide(true); clearTimeout(_scrollbarsAutoHideMoveTimeoutId); _scrollbarsAutoHideMoveTimeoutId = setTimeout(function () { if (_scrollbarsAutoHideMove) refreshScrollbarsAutoHide(false); }, 100); } } function documentOnSelectStart(event) { COMPAT.prvD(event); return false; } function updateOnLoadCallback(event) { var elm = Utils(event.target); eachUpdateOnLoad(function (i, updateOnLoadSelector) { if (elm.is(updateOnLoadSelector)) update({ _contentSizeChanged: true }); }); } function setupHostMouseTouchEvents(destroy) { if (!destroy) setupHostMouseTouchEvents(true); setupResponsiveEventListener(_hostElement, _strMouseTouchMoveEvent.split(' ')[0], hostOnMouseMove, (!_scrollbarsAutoHideMove || destroy), true); setupResponsiveEventListener(_hostElement, [_strMouseEnter, _strMouseLeave], [hostOnMouseEnter, hostOnMouseLeave], (!_scrollbarsAutoHideLeave || destroy), true); if (!_initialized && !destroy) _hostElement.one('mouseover', hostOnMouseEnter); } //==== Update Detection ====// function bodyMinSizeChanged() { var bodyMinSize = {}; if (_isBody && _contentArrangeElement) { bodyMinSize.w = parseToZeroOrNumber(_contentArrangeElement.css(_strMinMinus + 'width')); bodyMinSize.h = parseToZeroOrNumber(_contentArrangeElement.css(_strMinMinus + 'height')); bodyMinSize.c = checkCache(bodyMinSize, _bodyMinSizeCache); bodyMinSize.f = true; //flag for "measured at least once" } _bodyMinSizeCache = bodyMinSize; return !!bodyMinSize.c; } function updateAutoContentSizeChanged() { if (_sleeping) return false; var contentMeasureElement = getContentMeasureElement(); var setCSS = false; var css = {}; var float; var bodyMinSizeC; var changed; var contentElementScrollSize; if (setCSS) { float = _contentElement.css('float'); css['float'] = 'left'; css['width'] = 'auto'; _contentElement.css(css); } contentElementScrollSize = { w: contentMeasureElement.scrollWidth, h: contentMeasureElement.scrollHeight }; if (setCSS) { css['float'] = float; css['width'] = _strHundredPercent; _contentElement.css(css); } bodyMinSizeC = bodyMinSizeChanged(); changed = checkCache(contentElementScrollSize, _esDCache); _esDCache = contentElementScrollSize; return changed || bodyMinSizeC; } //==== Update ====// function update(updateHints) { clearTimeout(_swallowedUpdateTimeout); updateHints = updateHints || {}; _swallowedUpdateHints._hostSizeChanged |= updateHints._hostSizeChanged; _swallowedUpdateHints._contentSizeChanged |= updateHints._contentSizeChanged; _swallowedUpdateHints._force |= updateHints._force; var now = Date.now && Date.now() || new Date().getTime(); var hostSizeChanged = !!_swallowedUpdateHints._hostSizeChanged; var contentSizeChanged = !!_swallowedUpdateHints._contentSizeChanged; var force = !!_swallowedUpdateHints._force; var changedOptions = updateHints._changedOptions; var swallow = _swallowUpdateLag > 0 && _initialized && !force && !changedOptions && (now - _lastUpdateTime) < _swallowUpdateLag ; var displayIsHidden; if (swallow) _swallowedUpdateTimeout = setTimeout(update, _swallowUpdateLag); if (swallow || (_sleeping && !changedOptions) || (_initialized && !force && (displayIsHidden = _hostElement.is(':hidden'))) || _hostElement.css('display') === 'inline') return; _lastUpdateTime = now; _swallowedUpdateHints = {}; changedOptions = changedOptions || {}; var checkCacheAutoForce = function () { return checkCache.apply(this, [].slice.call(arguments).concat([force])); }; var currScroll = { x: _viewportElement['scrollLeft'](), y: _viewportElement['scrollTop']() }; var currentPreparedOptionsScrollbars = _currentPreparedOptions.scrollbars; var scrollbarsVisibility = currentPreparedOptionsScrollbars.visibility; var scrollbarsVisibilityChanged = checkCacheAutoForce(scrollbarsVisibility, _sVCache); var scrollbarsAutoHide = currentPreparedOptionsScrollbars.autoHide; var scrollbarsAutoHideChanged = checkCacheAutoForce(scrollbarsAutoHide, _scrollbarsAutoHideCache); var scrollbarsClickScrolling = currentPreparedOptionsScrollbars.clickScrolling; var scrollbarsClickScrollingChanged = checkCacheAutoForce(scrollbarsClickScrolling, _scrollbarsClickScrollingCache); var scrollbarsDragScrolling = currentPreparedOptionsScrollbars.dragScrolling; var scrollbarsDragScrollingChanged = checkCacheAutoForce(scrollbarsDragScrolling, _scrollbarsDragScrollingCache); var className = _currentPreparedOptions.className; var classNameChanged = checkCacheAutoForce(className, _classNameCache); var overflowBehavior = _currentPreparedOptions.overflowBehavior; var overflowBehaviorChanged = checkCacheAutoForce(overflowBehavior, _overflowBehaviorCache, force); _scrollbarsAutoHideNever = scrollbarsAutoHide === 'n'; _scrollbarsAutoHideScroll = scrollbarsAutoHide === 's'; _scrollbarsAutoHideMove = scrollbarsAutoHide === 'm'; _scrollbarsAutoHideLeave = scrollbarsAutoHide === 'l'; _scrollbarsAutoHideDelay = currentPreparedOptionsScrollbars.autoHideDelay; _oldClassName = _classNameCache; _sVCache = scrollbarsVisibility; _scrollbarsAutoHideCache = scrollbarsAutoHide; _scrollbarsClickScrollingCache = scrollbarsClickScrolling; _scrollbarsDragScrollingCache = scrollbarsDragScrolling; _classNameCache = className; _overflowBehaviorCache = extendDeep({}, overflowBehavior); _hasOverflowCache = _hasOverflowCache || { x: false, y: false }; if (classNameChanged) { removeClass(_hostElement, _oldClassName + ' ' + _classNameThemeNone); addClass(_hostElement, className !== undefined && className !== null && className.length > 0 ? className : _classNameThemeNone); } displayIsHidden = displayIsHidden === undefined ? _hostElement.is(':hidden') : displayIsHidden; var cssDirection = _hostElement.css('direction'); var cssDirectionChanged = checkCacheAutoForce(cssDirection, _cssDirectionCache); var boxSizing = _hostElement.css('box-sizing'); var boxSizingChanged = checkCacheAutoForce(boxSizing, _cssBoxSizingCache); var padding = getTopRightBottomLeftHost(_sPadMins); _isBorderBox = (boxSizing === 'border-box'); var updateBorderX = !_isBorderBox; var updateBorderY = !_isBorderBox; var border = getTopRightBottomLeftHost(_sBordMins, '-' + 'width', !updateBorderX, !updateBorderY) var margin = getTopRightBottomLeftHost(_strMarginMinus); var contentElementCSS = {}; var getHostSize = function () { return { w: _hostElementNative.clientWidth, h: _hostElementNative.clientHeight }; }; var getViewportSize = function () { return { w: _viewportElementNative.offsetWidth + Math.max(0, _contentElementNative.clientWidth - _contentElementNative.scrollWidth), h: _viewportElementNative.offsetHeight + Math.max(0, _contentElementNative.clientHeight - _contentElementNative.scrollHeight) }; }; padding.c = checkCacheAutoForce(padding, _cssPaddingCache); _borderX = border.l + border.r; _borderY = border.t + border.b; border.c = checkCacheAutoForce(border, _cssBorderCache); _marginX = margin.l + margin.r; _marginY = margin.t + margin.b; margin.c = checkCacheAutoForce(margin, _cssMarginCache); _cssDirectionCache = cssDirection; _cssBoxSizingCache = boxSizing; _cssPaddingCache = padding; _cssBorderCache = border; _cssMarginCache = margin; if (padding.c || cssDirectionChanged || boxSizingChanged ) { var paddingValues = [padding.t, padding.r, padding.b, padding.l]; setTopRightBottomLeft(contentElementCSS, _sPadMins, paddingValues); } _viewportSize = getViewportSize(); _contentElement.css(contentElementCSS); contentElementCSS = {}; if (hostSizeChanged || contentSizeChanged || cssDirectionChanged || boxSizingChanged || overflowBehaviorChanged || scrollbarsVisibilityChanged || scrollbarsAutoHideChanged || scrollbarsDragScrollingChanged || scrollbarsClickScrollingChanged) { var strOverflow = 'overflow'; var strOverflowX = strOverflow + '-x'; var strOverflowY = strOverflow + '-y'; var viewportElementResetCSS = {}; setTopRightBottomLeft(viewportElementResetCSS, ''); var contentMeasureElement = getContentMeasureElement(); _viewportElement.css(viewportElementResetCSS); _viewportSize = getViewportSize(); var hostSize = getHostSize(); _contentElement.css(contentElementCSS); contentElementCSS = {}; var contentScrollSize = { w: contentMeasureElement.scrollWidth, h: contentMeasureElement.scrollHeight, }; contentScrollSize.c = contentSizeChanged = checkCacheAutoForce(contentScrollSize, _contentScrollSizeCache); _contentScrollSizeCache = contentScrollSize; _viewportSize = getViewportSize(); hostSize = getHostSize(); hostSizeChanged = checkCacheAutoForce(hostSize, _hostSizeCache); _hostSizeCache = hostSize; var previousOverflowAmount = _overflowAmountCache; var overflowBehaviorIsVS = {}; var overflowBehaviorIsVH = {}; var overflowBehaviorIsS = {}; var overflowAmount = {}; var hasOverflow = {}; var hideOverflow = {}; var canScroll = {}; var viewportRect = _viewportElementNative.getBoundingClientRect(); var setOverflowVariables = function (horizontal) { var scrollbarVars = getScrollbarVars(horizontal); var scrollbarVarsInverted = getScrollbarVars(!horizontal); var xyI = scrollbarVarsInverted._x_y; var xy = scrollbarVars._x_y; var wh = scrollbarVars._w_h; var widthHeight = scrollbarVars._width_height; var scrollMax = _strScroll + scrollbarVars._Left_Top + 'Max'; var fractionalOverflowAmount = viewportRect[widthHeight] ? Math.abs(viewportRect[widthHeight] - _viewportSize[wh]) : 0; var checkFractionalOverflowAmount = previousOverflowAmount && previousOverflowAmount[xy] > 0 && _viewportElementNative[scrollMax] === 0; overflowBehaviorIsVS[xy] = overflowBehavior[xy] === 'v-s'; overflowBehaviorIsVH[xy] = overflowBehavior[xy] === 'v-h'; overflowBehaviorIsS[xy] = overflowBehavior[xy] === 's'; overflowAmount[xy] = Math.max(0, Math.round((contentScrollSize[wh] - _viewportSize[wh]) * 100) / 100); overflowAmount[xy] *= (checkFractionalOverflowAmount && fractionalOverflowAmount > 0 && fractionalOverflowAmount < 1) ? 0 : 1; hasOverflow[xy] = overflowAmount[xy] > 0; hideOverflow[xy] = overflowBehaviorIsVS[xy] || overflowBehaviorIsVH[xy] ? (hasOverflow[xyI] && !overflowBehaviorIsVS[xyI] && !overflowBehaviorIsVH[xyI]) : hasOverflow[xy]; hideOverflow[xy + 's'] = hideOverflow[xy] ? (overflowBehaviorIsS[xy] || overflowBehaviorIsVS[xy]) : false; canScroll[xy] = hasOverflow[xy] && hideOverflow[xy + 's']; }; setOverflowVariables(true); setOverflowVariables(false); overflowAmount.c = checkCacheAutoForce(overflowAmount, _overflowAmountCache); _overflowAmountCache = overflowAmount; hasOverflow.c = checkCacheAutoForce(hasOverflow, _hasOverflowCache); _hasOverflowCache = hasOverflow; hideOverflow.c = checkCacheAutoForce(hideOverflow, _hideOverflowCache); _hideOverflowCache = hideOverflow; var v_EC = {}; var setViewportCSS; if (hostSizeChanged || hasOverflow.c || hideOverflow.c || contentScrollSize.c || overflowBehaviorChanged || boxSizingChanged || cssDirectionChanged ) { v_EC['left'] = ''; setViewportCSS = function (horizontal) { var scrollbarVars = getScrollbarVars(horizontal); var scrollbarVarsInverted = getScrollbarVars(!horizontal); var xy = scrollbarVars._x_y; var XY = scrollbarVars._X_Y; var strDirection = horizontal ? 'bottom' : 'right'; var reset = function () { v_EC[strDirection] = ''; _contentBorderSize[scrollbarVarsInverted._w_h] = 0; }; if (hasOverflow[xy] && hideOverflow[xy + 's']) { v_EC[strOverflow + XY] = _strScroll; v_EC[strDirection] = ''; _contentBorderSize[scrollbarVarsInverted._w_h] = 0; } else { v_EC[strOverflow + XY] = ''; reset(); } }; setViewportCSS(true); setViewportCSS(false); v_EC[_sPadMins + 'top'] = v_EC[_strMarginMinus + 'top'] = v_EC[_sPadMins + 'left'] = v_EC[_strMarginMinus + 'left'] = ''; v_EC[_sPadMins + 'right'] = v_EC[_strMarginMinus + 'right'] = ''; if ((hasOverflow.x && hideOverflow.x) || (hasOverflow.y && hideOverflow.y)) { } else { if (overflowBehaviorIsVH.x || overflowBehaviorIsVS.x || overflowBehaviorIsVH.y || overflowBehaviorIsVS.y) { v_EC[strOverflowX] = v_EC[strOverflowY] = 'visible'; } } _viewportElement.css(v_EC); v_EC = {}; if ((hasOverflow.c || boxSizingChanged )) { var elementStyle = _contentElementNative.style; var dump; elementStyle.webkitTransform = 'scale(1)'; elementStyle.display = 'run-in'; dump = _contentElementNative.offsetHeight; elementStyle.display = ''; //|| dump; //use dump to prevent it from deletion if minify elementStyle.webkitTransform = ''; } } contentElementCSS = {}; if (cssDirectionChanged ) contentElementCSS['left'] = ''; _contentElement.css(contentElementCSS); _viewportElement['scrollLeft'](currScroll.x)['scrollTop'](currScroll.y); var scrollbarsVisibilityVisible = scrollbarsVisibility === 'v'; var scrollbarsVisibilityHidden = scrollbarsVisibility === 'h'; var scrollbarsVisibilityAuto = scrollbarsVisibility === 'a'; var refreshScrollbarsVisibility = function (showX, showY) { showY = showY === undefined ? showX : showY; refreshScrollbarAppearance(true, showX, canScroll.x) refreshScrollbarAppearance(false, showY, canScroll.y) }; if (scrollbarsVisibilityChanged || overflowBehaviorChanged || hideOverflow.c || hasOverflow.c ) { if (scrollbarsVisibilityAuto) { refreshScrollbarsVisibility(canScroll.x, canScroll.y); } else if (scrollbarsVisibilityVisible) { refreshScrollbarsVisibility(true); } else if (scrollbarsVisibilityHidden) { refreshScrollbarsVisibility(false); } } if (scrollbarsAutoHideChanged ) { setupHostMouseTouchEvents(!_scrollbarsAutoHideLeave && !_scrollbarsAutoHideMove); refreshScrollbarsAutoHide(_scrollbarsAutoHideNever, !_scrollbarsAutoHideNever); } if (hostSizeChanged || overflowAmount.c || boxSizingChanged || cssDirectionChanged) { refreshScrollbarHandleLength(true); refreshScrollbarHandleOffset(true); refreshScrollbarHandleLength(false); refreshScrollbarHandleOffset(false); } if (scrollbarsClickScrollingChanged) refreshScrollbarsInteractive(true, scrollbarsClickScrolling); if (scrollbarsDragScrollingChanged) refreshScrollbarsInteractive(false, scrollbarsDragScrolling); } if (_isBody && _bodyMinSizeCache && (_hasOverflowCache.c || _bodyMinSizeCache.c)) { if (!_bodyMinSizeCache.f) bodyMinSizeChanged(); _bodyMinSizeCache.c = false; } if (_initialized && changedOptions.updateOnLoad) { updateElementsOnLoad(); } } function updateElementsOnLoad() { eachUpdateOnLoad(function (i, updateOnLoadSelector) { _contentElement.find(updateOnLoadSelector).each(function (i, el) { if (COMPAT.inA(el, _updateOnLoadElms) < 0) { _updateOnLoadElms.push(el); Utils(el) .off(_updateOnLoadEventName, updateOnLoadCallback) .on(_updateOnLoadEventName, updateOnLoadCallback); } }); }); } //==== Structure ====// function setupStructureDOM() { _hostElement = _hostElement || _tE; _contentElement = _contentElement || selectOrGenerateDivByClass(_classNameContentElement); _viewportElement = _viewportElement || selectOrGenerateDivByClass(_classNameViewportElement); if (_domExists) addClass(_hostElement, _classNameHostElementForeign); if (!_domExists) { addClass(_tE, _classNameHostElement); _hostElement.wrapInner(_contentElement) .wrapInner(_viewportElement); _contentElement = findFirst(_hostElement, '.' + _classNameContentElement); _viewportElement = findFirst(_hostElement, '.' + _classNameViewportElement); } if (_isBody) addClass(_htmlElement, _classNameHTMLElement); _hostElementNative = _hostElement[0]; _viewportElementNative = _viewportElement[0]; _contentElementNative = _contentElement[0]; } function setupStructureEvents() { var scrollStopTimeoutId; var scrollStopDelay = 175; function viewportOnScroll(event) { if (!_sleeping) { if (scrollStopTimeoutId !== undefined) clearTimeout(scrollStopTimeoutId); else { if (_scrollbarsAutoHideScroll || _scrollbarsAutoHideMove) refreshScrollbarsAutoHide(true); addClass(_hostElement, _classNameHostScrolling); } if (!_scrollbarsHandlesDefineScrollPos) { refreshScrollbarHandleOffset(true); refreshScrollbarHandleOffset(false); } scrollStopTimeoutId = setTimeout(function () { clearTimeout(scrollStopTimeoutId); scrollStopTimeoutId = undefined; if (_scrollbarsAutoHideScroll || _scrollbarsAutoHideMove) refreshScrollbarsAutoHide(false); removeClass(_hostElement, _classNameHostScrolling); }, scrollStopDelay); } } addDestroyEventListener(_viewportElement, _strScroll, viewportOnScroll, true); } //==== Scrollbars ====// function setupScrollbarsDOM(destroy) { var selectOrGenerateScrollbarDOM = function (isHorizontal) { var posClassName = 'position-' + (isHorizontal ? _currentPreparedOptions.scrollPos.x : _currentPreparedOptions.scrollPos.y); var scrollbarClassName = isHorizontal ? _classNameScrollbarHorizontal : _classNameScrollbarVertical; var scrollbar = selectOrGenerateDivByClass(_classNameScrollbar + ' ' + scrollbarClassName + ' ' + posClassName, true); var track = selectOrGenerateDivByClass(_classNameScrollbarTrack, scrollbar); var handle = selectOrGenerateDivByClass(_classNameScrollbarHandle, scrollbar); if (!_domExists && !destroy) { scrollbar.append(track); track.append(handle); } return { _scrollbar: scrollbar, _track: track, _handle: handle }; }; function resetScrollbarDOM(isHorizontal) { var scrollbarVars = getScrollbarVars(isHorizontal); var scrollbar = scrollbarVars._scrollbar; var track = scrollbarVars._track; var handle = scrollbarVars._handle; if (_domExists && _initialized) { each([scrollbar, track, handle], function (i, elm) { removeClass(elm.removeAttr('style'), _classNamesDynamicDestroy); }); } else { remove(scrollbar || selectOrGenerateScrollbarDOM(isHorizontal)._scrollbar); } } var horizontalElements; var verticalElements; if (!destroy) { horizontalElements = selectOrGenerateScrollbarDOM(true); verticalElements = selectOrGenerateScrollbarDOM(); _sHE = horizontalElements._scrollbar; _sHTE = horizontalElements._track; _sHHE = horizontalElements._handle; _sVE = verticalElements._scrollbar; _sVTE = verticalElements._track; _sVHE = verticalElements._handle; if (!_domExists) { _viewportElement.after(_sVE); _viewportElement.after(_sHE); } } else { resetScrollbarDOM(true); resetScrollbarDOM(); } } function setupScrollbarEvents(isHorizontal) { var scrollbarVars = getScrollbarVars(isHorizontal); var scrollbarVarsInfo = scrollbarVars._info; var insideIFrame = _wENative.top !== _wENative; var xy = scrollbarVars._x_y; var XY = scrollbarVars._X_Y; var scroll = _strScroll + scrollbarVars._Left_Top; var trackTimeout; var mouseDownScroll; var mouseDownOffset; function getPointerPosition(event) { return _msieVersion && insideIFrame ? event['screen' + XY] : COMPAT.page(event)[xy]; } function getPreparedScrollbarsOption(name) { return _currentPreparedOptions.scrollbars[name]; } function onMouseTouchDownContinue(event) { var originalEvent = event.originalEvent || event; var isTouchEvent = originalEvent.touches !== undefined; return _sleeping || !_scrollbarsDragScrollingCache || COMPAT.mBtn(event) === 1 || isTouchEvent; } function documentDragMove(event) { if (onMouseTouchDownContinue(event)) { var trackLength = scrollbarVarsInfo._trackLength; var handleLength = scrollbarVarsInfo._handleLength; var scrollRange = scrollbarVarsInfo._maxScroll; var scrollRaw = (getPointerPosition(event) - mouseDownOffset); var scrollDeltaPercent = scrollRaw / (trackLength - handleLength); var scrollDelta = (scrollRange * scrollDeltaPercent); scrollDelta = isFinite(scrollDelta) ? scrollDelta : 0; _viewportElement[scroll](Math.round(mouseDownScroll + scrollDelta)); if (_scrollbarsHandlesDefineScrollPos) refreshScrollbarHandleOffset(isHorizontal, mouseDownScroll + scrollDelta); if (!_supportPassiveEvents) COMPAT.prvD(event); } else documentMouseTouchUp(event); } function documentMouseTouchUp(event) { event = event || event.originalEvent; setupResponsiveEventListener(_docE, [_strMouseTouchMoveEvent, _strMouseTouchUpEvent, _strKeyDownEvent, _strKeyUpEvent, _strSelectStartEvent], [documentDragMove, documentMouseTouchUp, documentOnSelectStart], true); COMPAT.rAF()(function() { setupResponsiveEventListener(_docE, 'click', COMPAT.stpP(event), true, { _capture: true }); }); if (_scrollbarsHandlesDefineScrollPos) refreshScrollbarHandleOffset(isHorizontal, true); _scrollbarsHandlesDefineScrollPos = false; removeClass(_bodyElement, _classNameDragging); removeClass(scrollbarVars._handle, 'active'); removeClass(scrollbarVars._track, 'active'); removeClass(scrollbarVars._scrollbar, 'active'); mouseDownScroll = undefined; mouseDownOffset = undefined; if (trackTimeout !== undefined) { _base.scrollStop(); clearTimeout(trackTimeout); trackTimeout = undefined; } if (event) { var rect = _hostElementNative.getBoundingClientRect(); var mouseInsideHost = event.clientX >= rect.left && event.clientX <= rect.right && event.clientY >= rect.top && event.clientY <= rect.bottom; if (!mouseInsideHost) hostOnMouseLeave(); if (_scrollbarsAutoHideScroll || _scrollbarsAutoHideMove) refreshScrollbarsAutoHide(false); } } function onHandleMouseTouchDown(event) { if (onMouseTouchDownContinue(event)) onHandleMouseTouchDownAction(event); } function onHandleMouseTouchDownAction(event) { mouseDownScroll = _viewportElement[scroll](); mouseDownScroll = isNaN(mouseDownScroll) || mouseDownScroll < 0 ? 0 : mouseDownScroll; mouseDownOffset = getPointerPosition(event); _scrollbarsHandlesDefineScrollPos = !getPreparedScrollbarsOption('snapHandle'); addClass(_bodyElement, _classNameDragging); addClass(scrollbarVars._handle, 'active'); addClass(scrollbarVars._scrollbar, 'active'); setupResponsiveEventListener(_docE, [_strMouseTouchMoveEvent, _strMouseTouchUpEvent, _strSelectStartEvent], [documentDragMove, documentMouseTouchUp, documentOnSelectStart]); COMPAT.rAF()(function() { setupResponsiveEventListener(_docE, 'click', COMPAT.stpP(event), false, { _capture: true }); }); if (_msieVersion || !_documentMixed) COMPAT.prvD(event); COMPAT.stpP(event); } function onTrackMouseTouchDown(event) { if (onMouseTouchDownContinue(event)) { var trackOffset = scrollbarVars._track.offset()[scrollbarVars._left_top]; var scrollAction = function () { var mouseOffset = (mouseDownOffset - trackOffset); var trackLength = scrollbarVarsInfo._trackLength; var handleLength = scrollbarVarsInfo._handleLength; var scrollRange = scrollbarVarsInfo._maxScroll; var instantScrollPosition = scrollRange * ((mouseOffset - (handleLength / 2)) / (trackLength - handleLength)); instantScrollPosition = isFinite(instantScrollPosition) ? instantScrollPosition : 0; _viewportElement[scroll](instantScrollPosition); refreshScrollbarHandleOffset(isHorizontal, instantScrollPosition); }; mouseDownOffset = COMPAT.page(event)[xy]; _scrollbarsHandlesDefineScrollPos = !getPreparedScrollbarsOption('snapHandle'); addClass(_bodyElement, _classNameDragging); addClass(scrollbarVars._track, 'active'); addClass(scrollbarVars._scrollbar, 'active'); setupResponsiveEventListener(_docE, [_strMouseTouchUpEvent, _strKeyDownEvent, _strKeyUpEvent, _strSelectStartEvent], [documentMouseTouchUp, documentOnSelectStart]); scrollAction(); COMPAT.prvD(event); COMPAT.stpP(event); } } function onTrackMouseTouchEnter(event) { _scrollbarsHandleHovered = true; if (_scrollbarsAutoHideScroll || _scrollbarsAutoHideMove) refreshScrollbarsAutoHide(true); } function onTrackMouseTouchLeave(event) { _scrollbarsHandleHovered = false; if (_scrollbarsAutoHideScroll || _scrollbarsAutoHideMove) refreshScrollbarsAutoHide(false); } function onScrollbarMouseTouchDown(event) { COMPAT.stpP(event); } addDestroyEventListener(scrollbarVars._handle, _strMouseTouchDownEvent, onHandleMouseTouchDown); addDestroyEventListener(scrollbarVars._track, [_strMouseTouchDownEvent, _strMouseEnter, _strMouseLeave], [onTrackMouseTouchDown, onTrackMouseTouchEnter, onTrackMouseTouchLeave]); addDestroyEventListener(scrollbarVars._scrollbar, _strMouseTouchDownEvent, onScrollbarMouseTouchDown); } function refreshScrollbarAppearance(isHorizontal, shallBeVisible, canScroll) { var scrollbarHiddenClassName = isHorizontal ? _cHH : _cVH; var scrollbarElement = isHorizontal ? _sHE : _sVE; addRemoveClass(_hostElement, scrollbarHiddenClassName, !shallBeVisible); addRemoveClass(scrollbarElement, _classNameScrollbarUnusable, !canScroll); } function refreshScrollbarsAutoHide(shallBeVisible, delayfree) { clearTimeout(_scrollbarsAutoHideTimeoutId); if (shallBeVisible) { removeClass(_sHE, _classNameScrollbarAutoHidden); removeClass(_sVE, _classNameScrollbarAutoHidden); } else { var anyActive; var hide = function () { if (!_scrollbarsHandleHovered) { anyActive = _sHHE.hasClass('active') || _sVHE.hasClass('active'); if (!anyActive && (_scrollbarsAutoHideScroll || _scrollbarsAutoHideMove || _scrollbarsAutoHideLeave)) addClass(_sHE, _classNameScrollbarAutoHidden); if (!anyActive && (_scrollbarsAutoHideScroll || _scrollbarsAutoHideMove || _scrollbarsAutoHideLeave)) addClass(_sVE, _classNameScrollbarAutoHidden); } }; if (_scrollbarsAutoHideDelay > 0 && delayfree !== true) _scrollbarsAutoHideTimeoutId = setTimeout(hide, _scrollbarsAutoHideDelay); else hide(); } } function refreshScrollbarHandleLength(isHorizontal) { var handleCSS = {}; var scrollbarVars = getScrollbarVars(isHorizontal); var scrollbarVarsInfo = scrollbarVars._info; var digit = 1000000; var handleRatio = Math.min(1, _viewportSize[scrollbarVars._w_h] / _contentScrollSizeCache[scrollbarVars._w_h]); handleCSS[scrollbarVars._width_height] = (Math.floor(handleRatio * 100 * digit) / digit) + '%'; //the last * digit / digit is for flooring to the 4th digit scrollbarVars._handle.css(handleCSS); scrollbarVarsInfo._handleLength = scrollbarVars._handle[0]['offset' + scrollbarVars._Width_Height]; scrollbarVarsInfo._handleLengthRatio = handleRatio; } function refreshScrollbarHandleOffset(isHorizontal, scrollOrTransition) { var transition = type(scrollOrTransition) == 'boolean'; var scrollbarVars = getScrollbarVars(isHorizontal); var scrollbarVarsInfo = scrollbarVars._info; var nativeScroll = isHorizontal ? _viewportElement['scrollLeft']() : _viewportElement['scrollTop'](); var currentScroll = scrollOrTransition === undefined || transition ? nativeScroll : scrollOrTransition; var handleLength = scrollbarVarsInfo._handleLength; var trackLength = scrollbarVars._track[0]['offset' + scrollbarVars._Width_Height]; var handleTrackDiff = trackLength - handleLength; var handleCSS = {}; var maxScroll = (_viewportElementNative[_strScroll + scrollbarVars._Width_Height] - _viewportElementNative['client' + scrollbarVars._Width_Height]); var getScrollRatio = function (base) { return isNaN(base / maxScroll) ? 0 : Math.max(0, Math.min(1, base / maxScroll)); }; var getHandleOffset = function (scrollRatio) { var offset = handleTrackDiff * scrollRatio; offset = isNaN(offset) ? 0 : offset; offset = Math.max(0, offset); return offset; }; var scrollRatio = getScrollRatio(nativeScroll); var unsnappedScrollRatio = getScrollRatio(currentScroll); var handleOffset = getHandleOffset(unsnappedScrollRatio); var snappedHandleOffset = getHandleOffset(scrollRatio); scrollbarVarsInfo._maxScroll = maxScroll; scrollbarVarsInfo._currentScroll = nativeScroll; scrollbarVarsInfo._currentScrollRatio = scrollRatio; handleCSS[scrollbarVars._left_top] = handleOffset; scrollbarVars._handle.css(handleCSS); scrollbarVarsInfo._handleOffset = handleOffset; scrollbarVarsInfo._snappedHandleOffset = snappedHandleOffset; scrollbarVarsInfo._trackLength = trackLength; } function refreshScrollbarsInteractive(isTrack, value) { var action = value ? 'removeClass' : 'addClass'; var element1 = isTrack ? _sHTE : _sHHE; var element2 = isTrack ? _sVTE : _sVHE; var className = isTrack ? _classNameScrollbarTrackOff : _classNameScrollbarHandleOff; element1[action](className); element2[action](className); } function getScrollbarVars(isHorizontal) { return { _width_height: isHorizontal ? 'width' : 'height', _Width_Height: isHorizontal ? 'Width' : 'Height', _left_top: isHorizontal ? 'left' : 'top', _Left_Top: isHorizontal ? 'Left' : 'Top', _x_y: isHorizontal ? 'x' : 'y', _X_Y: isHorizontal ? 'X' : 'Y', _w_h: isHorizontal ? 'w' : 'h', _l_t: isHorizontal ? 'l' : 't', _track: isHorizontal ? _sHTE : _sVTE, _handle: isHorizontal ? _sHHE : _sVHE, _scrollbar: isHorizontal ? _sHE : _sVE, _info: isHorizontal ? _scrollHorizontalInfo : _scrollVerticalInfo }; } //==== Utils ====// function setTopRightBottomLeft(targetCSSObject, prefix, values) { prefix = prefix || ''; values = values || ['', '', '', '']; targetCSSObject[prefix + 'top'] = values[0]; targetCSSObject[prefix + 'right'] = values[1]; targetCSSObject[prefix + 'bottom'] = values[2]; targetCSSObject[prefix + 'left'] = values[3]; } function getTopRightBottomLeftHost(prefix, suffix, zeroX, zeroY) { suffix = suffix || ''; prefix = prefix || ''; return { t: zeroY ? 0 : parseToZeroOrNumber(_hostElement.css(prefix + 'top' + suffix)), r: zeroX ? 0 : parseToZeroOrNumber(_hostElement.css(prefix + 'right' + suffix)), b: zeroY ? 0 : parseToZeroOrNumber(_hostElement.css(prefix + 'bottom' + suffix)), l: zeroX ? 0 : parseToZeroOrNumber(_hostElement.css(prefix + 'left' + suffix)) }; } function isHTMLElement(o) { var strOwnerDocument = 'ownerDocument'; var strHTMLElement = 'HTMLElement'; var wnd = o && o[strOwnerDocument] ? (o[strOwnerDocument].parentWindow || window) : window; return ( typeof wnd[strHTMLElement] == 'object' ? o instanceof wnd[strHTMLElement] : //DOM2 o && typeof o == 'object' && o !== null && o.nodeType === 1 && typeof o.nodeName == 'string' ); } function parseToZeroOrNumber(value, toFloat) { var num = toFloat ? parseFloat(value) : parseInt(value, 10); return isNaN(num) ? 0 : num; } function getContentMeasureElement() { return _contentElementNative; } function generateDiv(classesOrAttrs, content) { return '<div ' + (classesOrAttrs ? type(classesOrAttrs) == 'string' ? 'class="' + classesOrAttrs + '"' : (function () { var key; var attrs = ''; if (Utils.isPlainObject(classesOrAttrs)) { for (key in classesOrAttrs) attrs += (key === 'c' ? 'class' : key) + '="' + classesOrAttrs[key] + '" '; } return attrs; })() : '') + '>' + (content || '') + '</div>'; } function selectOrGenerateDivByClass(className, selectParentOrOnlyChildren) { var onlyChildren = type(selectParentOrOnlyChildren) == 'boolean'; var selectParent = onlyChildren ? _hostElement : (selectParentOrOnlyChildren || _hostElement); return (_domExists && !selectParent.length) ? null : _domExists ? selectParent[onlyChildren ? 'children' : 'find']('.' + className.replace(/\s/g, '.')).eq(0) : Utils(generateDiv(className)) } function eachUpdateOnLoad(action) { var updateOnLoad = _currentPreparedOptions.updateOnLoad; updateOnLoad = type(updateOnLoad) == 'string' ? updateOnLoad.split(' ') : updateOnLoad; if (COMPAT.isA(updateOnLoad)) { each(updateOnLoad, action); } } //==== Utils Cache ====// function checkCache(current, cache, force) { if (force) return force; if (type(current) == 'object' && type(cache) == 'object') { for (var prop in current) { if (prop !== 'c') { if (current.hasOwnProperty(prop) && cache.hasOwnProperty(prop)) { if (checkCache(current[prop], cache[prop])) return true; } else { return true; } } } } else { return current !== cache; } return false; } //==== Shortcuts ====// function extendDeep() { return Utils.extend.apply(this, [true].concat([].slice.call(arguments))); } function addClass(el, classes) { return _frameworkProto.addClass.call(el, classes); } function removeClass(el, classes) { return _frameworkProto.removeClass.call(el, classes); } function addRemoveClass(el, classes, doAdd) { return doAdd ? addClass(el, classes) : removeClass(el, classes); } function remove(el) { return _frameworkProto.remove.call(el); } function findFirst(el, selector) { return _frameworkProto.find.call(el, selector).eq(0); } //==== API ====// _base.update = function (force) { var contentSizeC; var isString = type(force) == 'string'; var doUpdateAuto; var mutHost; var mutContent; if (isString) { if (force === 'auto') { contentSizeC = updateAutoContentSizeChanged(); doUpdateAuto = contentSizeC; if (doUpdateAuto) { update({ _contentSizeChanged: contentSizeC, _changedOptions: _initialized ? undefined : _currentPreparedOptions }); } } else if (force === _strSync) { mutHost = _base.update('auto'); } else if (force === 'zoom') { update({ _hostSizeChanged: true, _contentSizeChanged: true }); } } else { force = _sleeping || force; _sleeping = false; if (!_base.update(_strSync) || force) update({ _force: force }); } updateElementsOnLoad(); return doUpdateAuto || mutHost || mutContent; }; function construct(targetElement) { initOptions(); _msieVersion = _globals.msie; _autoUpdateRecommended = _globals.autoUpdateRecommended; _supportPassiveEvents = _globals.supportPassiveEvents; _docE = Utils(targetElement.ownerDocument); _docENative = _docE[0]; _wE = Utils(_docENative.defaultView || _docENative.parentWindow); _wENative = _wE[0]; _htmlElement = findFirst(_docE, 'html'); _bodyElement = findFirst(_htmlElement, 'body'); _tE = Utils(targetElement); _isBody = _tE.is('body'); _documentMixed = _docENative !== document; _domExists = _tE.hasClass(_classNameHostElement); var initBodyScroll; var bodyMouseTouchDownListener; if (_isBody) { initBodyScroll = {}; initBodyScroll.l = Math.max(_tE['scrollLeft'](), _htmlElement['scrollLeft'](), _wE['scrollLeft']()); initBodyScroll.t = Math.max(_tE['scrollTop'](), _htmlElement['scrollTop'](), _wE['scrollTop']()); bodyMouseTouchDownListener = function () { _viewportElement.removeAttr('tabindex'); setupResponsiveEventListener(_viewportElement, _strMouseTouchDownEvent, bodyMouseTouchDownListener, true, true); } } setupStructureDOM(); setupScrollbarsDOM(); setupStructureEvents(); setupScrollbarEvents(true); setupScrollbarEvents(false); if (_isBody) { _viewportElement['scrollLeft'](initBodyScroll.l)['scrollTop'](initBodyScroll.t); if (document.activeElement == targetElement && _viewportElementNative.focus) { _viewportElement.attr('tabindex', '-1'); _viewportElementNative.focus(); setupResponsiveEventListener(_viewportElement, _strMouseTouchDownEvent, bodyMouseTouchDownListener, false, true); } } _base.update('auto'); _initialized = true; addClass(_hostElement, _classNameHostTransition); return _base; } construct(el); return { element: el, options: _currentOptions }; } _base = { _objects: [], init: function() { if (!_globals) _globals = new scrollGlobals(); var scrollEles = document.querySelectorAll('.co_overlay-scroll'); for(var i = 0; i < scrollEles.length; i++){ this.createObj(scrollEles[i]); } }, checkExistObj: function(el) { for(var i = 0; i < this._objects.length; i++){ if(el.isSameNode(this._objects[i].el)) return true; } return false; }, createObj: function(el) { if(this.checkExistObj(el)) return; this._objects.push(new scrollInstance(el)); } }; return _base; })(); CoCreateOverlayScroll.init(); export default CoCreateOverlayScroll; <|start_filename|>overlay-scroll-archive/CoCreate-overlay-scroll.css<|end_filename|> html.co_html, html.co_html > .co_host { display: block; overflow: hidden; box-sizing: border-box; height: 100% !important; width: 100% !important; min-width: 100% !important; min-height: 100% !important; margin: 0 !important; position: absolute !important; } html.co_html > .co_host > .co_wrapper { position: absolute; } body.co_dragging, body.co_dragging * { cursor: default; } .co_host, .co_host-textarea { position: relative; overflow: visible !important; -webkit-box-orient: vertical; -webkit-box-direction: normal; -ms-flex-direction: column; flex-direction: column; -ms-flex-wrap: nowrap; flex-wrap: nowrap; -webkit-box-pack: start; -ms-flex-pack: start; justify-content: flex-start; -ms-flex-line-pack: start; align-content: flex-start; -webkit-box-align: start; -ms-flex-align: start; -ms-grid-row-align: flex-start; align-items: flex-start; } .co_host-flexbox { overflow: hidden !important; display: -webkit-box; display: -ms-flexbox; display: flex; } .co_host-flexbox > .co_size-auto-observer { height: inherit !important; } .co_host-flexbox > .co_content-glue { -webkit-box-flex: 1; -ms-flex-positive: 1; flex-grow: 1; -ms-flex-negative: 0; flex-shrink: 0; } .co_host-flexbox > .co_size-auto-observer, .co_host-flexbox > .co_content-glue { min-height: 0; min-width: 0; -webkit-box-flex: 0; -ms-flex-positive: 0; flex-grow: 0; -ms-flex-negative: 1; flex-shrink: 1; -ms-flex-preferred-size: auto; flex-basis: auto; } #os-dummy-scrollbar-size { position: fixed; opacity: 0; -ms-filter: 'progid:DXImageTransform.Microsoft.Alpha(Opacity=0)'; visibility: hidden; overflow: scroll; height: 500px; width: 500px; } #os-dummy-scrollbar-size > div { width: 200%; height: 200%; margin: 10px 0; } /* fix restricted measuring */ #os-dummy-scrollbar-size:before, #os-dummy-scrollbar-size:after, .co_content:before, .co_content:after { content: ''; display: table; width: 0.01px; height: 0.01px; line-height: 0; font-size: 0; flex-grow: 0; flex-shrink: 0; visibility: hidden; } #os-dummy-scrollbar-size, .co_viewport { -ms-overflow-style: scrollbar !important; } .co_overlay-scroll #os-dummy-scrollbar-size, .co_overlay-scroll .co_viewport { scrollbar-width: none !important; } .co_overlay-scroll #os-dummy-scrollbar-size::-webkit-scrollbar, .co_overlay-scroll .co_viewport::-webkit-scrollbar, .co_overlay-scroll #os-dummy-scrollbar-size::-webkit-scrollbar-corner, .co_overlay-scroll .co_viewport::-webkit-scrollbar-corner { display: none !important; width: 0px !important; height: 0px !important; visibility: hidden !important; background: transparent !important; } .co_content-glue { box-sizing: inherit; max-height: 100%; max-width: 100%; width: 100%; pointer-events: none; } .co_wrapper { box-sizing: inherit; direction: inherit; position: absolute; overflow: visible; padding: 0; margin: 0; left: 0; top: 0; bottom: 0; right: 0; width: auto !important; height: auto !important; } .co_host-overflow > .co_wrapper { overflow: hidden; } .co_viewport { direction: inherit !important; box-sizing: inherit !important; resize: none !important; outline: none !important; position: absolute; overflow: hidden; top: 0; left: 0; bottom: 0; right: 0; padding: 0; margin: 0; -webkit-overflow-scrolling: touch; } .co_content-arrange { position: absolute; z-index: -1; min-height: 1px; min-width: 1px; pointer-events: none; } .co_content { direction: inherit; box-sizing: border-box !important; position: relative; display: block; height: 100%; width: 100%; height: 100%; width: 100%; visibility: visible; } .co_content > .co_textarea { box-sizing: border-box !important; direction: inherit !important; background: transparent !important; outline: 0px none transparent !important; overflow: hidden !important; position: absolute !important; display: block !important; top: 0 !important; left: 0 !important; margin: 0 !important; border-radius: 0px !important; float: none !important; -webkit-filter: none !important; filter: none !important; border: none !important; resize: none !important; -webkit-transform: none !important; transform: none !important; max-width: none !important; max-height: none !important; box-shadow: none !important; -webkit-perspective: none !important; perspective: none !important; opacity: 1 !important; z-index: 1 !important; clip: auto !important; vertical-align: baseline !important; padding: 0px; } .co_content > .co_textarea-cover { z-index: -1; pointer-events: none; } .co_content > .co_textarea[wrap='off'] { white-space: pre !important; margin: 0px !important; } .co_text-inherit { font-family: inherit; font-size: inherit; font-weight: inherit; font-style: inherit; font-variant: inherit; text-transform: inherit; text-decoration: inherit; text-indent: inherit; text-align: inherit; text-shadow: inherit; text-overflow: inherit; letter-spacing: inherit; word-spacing: inherit; line-height: inherit; unicode-bidi: inherit; direction: inherit; color: inherit; cursor: text; } .co_resize-observer, .co_resize-observer-host { box-sizing: inherit; display: block; visibility: hidden; position: absolute; top: 0; left: 0; height: 100%; width: 100%; overflow: hidden; pointer-events: none; z-index: -1; } .co_resize-observer-host { padding: inherit; border: inherit; border-color: transparent; border-style: solid; box-sizing: border-box; } .co_resize-observer-host.observed { display: flex; flex-direction: column; justify-content: flex-start; align-items: flex-start; } .co_resize-observer-host > .co_resize-observer, .co_resize-observer-host.observed > .co_resize-observer { height: 200%; width: 200%; padding: inherit; border: inherit; margin: 0; display: block; box-sizing: content-box; } .co_resize-observer-host.observed > .co_resize-observer, .co_resize-observer-host.observed > .co_resize-observer:before { display: flex; position: relative; flex-grow: 1; flex-shrink: 0; flex-basis: auto; box-sizing: border-box; } .co_resize-observer-host.observed > .co_resize-observer:before { content: ''; box-sizing: content-box; padding: inherit; border: inherit; margin: 0; } .co_size-auto-observer { box-sizing: inherit !important; height: 100%; width: inherit; max-width: 1px; position: relative; float: left; max-height: 1px; overflow: hidden; z-index: -1; padding: 0; margin: 0; pointer-events: none; -webkit-box-flex: inherit; -ms-flex-positive: inherit; flex-grow: inherit; -ms-flex-negative: 0; flex-shrink: 0; -ms-flex-preferred-size: 0; flex-basis: 0; } .co_size-auto-observer > .co_resize-observer { width: 1000%; height: 1000%; min-height: 1px; min-width: 1px; } .co_resize-observer-item { position: absolute; top: 0; right: 0; bottom: 0; left: 0; overflow: hidden; z-index: -1; opacity: 0; direction: ltr !important; -webkit-box-flex: 0 !important; -ms-flex: none !important; flex: none !important; } .co_resize-observer-item-final { position: absolute; left: 0; top: 0; -webkit-transition: none !important; transition: none !important; -webkit-box-flex: 0 !important; -ms-flex: none !important; flex: none !important; } .co_resize-observer { -webkit-animation-duration: 0.001s; animation-duration: 0.001s; -webkit-animation-name: os-resize-observer-dummy-animation; animation-name: os-resize-observer-dummy-animation; } object.co_resize-observer { box-sizing: border-box !important; } @-webkit-keyframes os-resize-observer-dummy-animation { from { z-index: 0; } to { z-index: -1; } } @keyframes os-resize-observer-dummy-animation { from { z-index: 0; } to { z-index: -1; } } /* CUSTOM SCROLLBARS AND CORNER CORE: */ .co_host-transition > .co_scrollbar, .co_host-transition > .co_scrollbar-corner { -webkit-transition: opacity 0.3s, visibility 0.3s, top 0.3s, right 0.3s, bottom 0.3s, left 0.3s; transition: opacity 0.3s, visibility 0.3s, top 0.3s, right 0.3s, bottom 0.3s, left 0.3s; } html.co_html > .co_host > .co_scrollbar { position: absolute; z-index: 999999; } .co_scrollbar, .co_scrollbar-corner { position: absolute; opacity: 1; -ms-filter: 'progid:DXImageTransform.Microsoft.Alpha(Opacity=100)'; z-index: 1; } .co_scrollbar-corner { bottom: 0; right: 0; } .co_scrollbar { pointer-events: none; } .co_scrollbar-track { pointer-events: auto; position: relative; height: 100%; width: 100%; padding: 0 !important; border: none !important; } .co_scrollbar-handle { pointer-events: auto; position: absolute; width: 100%; height: 100%; } .co_scrollbar-handle-off, .co_scrollbar-track-off { pointer-events: none; } .co_scrollbar.co_scrollbar-unusable, .co_scrollbar.co_scrollbar-unusable * { pointer-events: none !important; } .co_scrollbar.co_scrollbar-unusable .co_scrollbar-handle { opacity: 0 !important; } .co_scrollbar-horizontal.position-top { top: 0; left: 0; } .co_scrollbar-horizontal.position-bottom { bottom: 0; left: 0; } .co_scrollbar-vertical.position-left { top: 0; left: 0; } .co_scrollbar-vertical.position-right { top: 0; right: 0; } .co_scrollbar-auto-hidden, .co_wrapper + .co_scrollbar-corner, .co_host-resize-disabled.co_host-scrollbar-horizontal-hidden > .co_scrollbar-corner, .co_host-scrollbar-horizontal-hidden > .co_scrollbar-horizontal, .co_host-resize-disabled.co_host-scrollbar-vertical-hidden > .co_scrollbar-corner, .co_host-scrollbar-vertical-hidden > .co_scrollbar-vertical, .co_scrollbar-horizontal.co_scrollbar-auto-hidden + .co_scrollbar-vertical + .co_scrollbar-corner, .co_scrollbar-horizontal + .co_scrollbar-vertical.co_scrollbar-auto-hidden + .co_scrollbar-corner, .co_scrollbar-horizontal.co_scrollbar-auto-hidden + .co_scrollbar-vertical.co_scrollbar-auto-hidden + .co_scrollbar-corner { opacity: 0; visibility: hidden; pointer-events: none; } .co_scrollbar-corner-resize-both { cursor: nwse-resize; } .co_scrollbar-corner-resize-horizontal { cursor: ew-resize; } .co_scrollbar-corner-resize-vertical { cursor: ns-resize; } .co_dragging .co_scrollbar-corner.co_scrollbar-corner-resize { cursor: default; } .co_host-resize-disabled.co_host-scrollbar-horizontal-hidden > .co_scrollbar-vertical { top: 0; bottom: 0; } .co_host-resize-disabled.co_host-scrollbar-vertical-hidden > .co_scrollbar-horizontal{ right: 0; left: 0; } .co_scrollbar:hover, .co_scrollbar-corner.co_scrollbar-corner-resize { opacity: 1 !important; visibility: visible !important; } .co_overlay-scroll { overflow: hidden !important; } .co_overlay-scroll > .co_scrollbar-horizontal { left: 10px; right: 10px; height: 10px; } .co_overlay-scroll > .co_scrollbar-vertical { top: 10px; bottom: 10px; width: 10px; } .co_overlay-scroll > .co_scrollbar-corner { height: 10px; width: 10px; } .co_overlay-scroll > .co_scrollbar-corner { background-color: transparent; } .co_overlay-scroll > .co_scrollbar { padding: 2px; box-sizing: border-box; background: transparent; } .co_overlay-scroll > .co_scrollbar.co_scrollbar-unusable { background: transparent; } .co_overlay-scroll > .co_scrollbar > .co_scrollbar-track { background: transparent; } .co_overlay-scroll > .co_scrollbar-horizontal > .co_scrollbar-track > .co_scrollbar-handle { min-width: 30px; } .co_overlay-scroll > .co_scrollbar-vertical > .co_scrollbar-track > .co_scrollbar-handle { min-height: 30px; } .co_overlay-scroll.co_host-transition > .co_scrollbar > .co_scrollbar-track > .co_scrollbar-handle { -webkit-transition: background-color 0.3s; transition: background-color 0.3s; } .co_overlay-scroll > .co_scrollbar > .co_scrollbar-track > .co_scrollbar-handle, .co_overlay-scroll > .co_scrollbar > .co_scrollbar-track { border-radius: 10px; } .co_overlay-scroll > .co_scrollbar > .co_scrollbar-track > .co_scrollbar-handle { background: rgba(190, 190, 190, .8); } .co_overlay-scroll > .co_scrollbar:hover > .co_scrollbar-track > .co_scrollbar-handle { background: rgba(150, 150, 150, .8); } .co_overlay-scroll > .co_scrollbar > .co_scrollbar-track > .co_scrollbar-handle.active { background: rgba(170, 170, 170, .8); } .co_overlay-scroll.dark-mode > .co_scrollbar > .co_scrollbar-track > .co_scrollbar-handle { background: rgba(0, 0, 0, 0.4); } .co_overlay-scroll.dark-mode > .co_scrollbar:hover > .co_scrollbar-track > .co_scrollbar-handle { background: rgba(0, 0, 0, .55); } .co_overlay-scroll.dark-mode > .co_scrollbar > .co_scrollbar-track > .co_scrollbar-handle.active { background: rgba(0, 0, 0, .7); } .co_overlay-scroll > .co_scrollbar-horizontal .co_scrollbar-handle:before, .co_overlay-scroll > .co_scrollbar-vertical .co_scrollbar-handle:before { content: ''; position: absolute; left: 0; right: 0; top: 0; bottom: 0; display: block; } .co_overlay-scroll.co_host-scrollbar-horizontal-hidden > .co_scrollbar-horizontal .co_scrollbar-handle:before, .co_overlay-scroll.co_host-scrollbar-vertical-hidden > .co_scrollbar-vertical .co_scrollbar-handle:before { display: none; } .co_overlay-scroll > .co_scrollbar-horizontal .co_scrollbar-handle:before { top: -6px; bottom: -2px; } .co_overlay-scroll > .co_scrollbar-vertical .co_scrollbar-handle:before { left: -6px; right: -2px; } <|start_filename|>src/index.css<|end_filename|> .co_scrollbar-disable-selection { -webkit-touch-callout: none; -webkit-user-select: none; -khtml-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; } .co_prevented { -webkit-overflow-scrolling: touch; } .co_prevented > .co_scrollbar { display: none; } .co_overlay-scroll { position: relative; overflow: hidden!important; width: 100%; height: 100%; } .co_scrollbar { position: absolute; right: 2px; bottom: 2px; z-index: 1; border-radius: 3px; } .co_scrollbar._vertical { width: 6px; top: 2px; } .co_scrollbar._vertical.left { left: 2px; } .co_scrollbar._horizontal { height: 6px; left: 2px; } .co_scrollbar._horizontal.top { top: 2px } .co_scrollbar .thumb { position: relative; display: block; width: 0; height: 0; cursor: pointer; border-radius: inherit; background-color: rgba(150,150,150,.5); transform: translate3d(0,0,0); } .co_scrollbar .thumb:hover, .co_scrollbar .thumb:active { background-color: rgba(150,150,150,.6); } .co_scrollbar._vertical .thumb { width: 100%; } .co_scrollbar._horizontal .thumb { height: 100%; } .co_overlay-scroll .co_overlay-viewport { width: 100%; height: 100%; overflow: scroll; transform: translate3d(0,0,0); -webkit-overflow-scrolling: touch; } .co_overlay-scroll.dark-mode .co_scrollbar .thumb { background-color: rgba(0,0,0,.5); } .co_overlay-scroll.dark-mode .co_scrollbar .thumb:hover, .co_overlay-scroll.dark-mode .co_scrollbar .thumb:active { background-color: rgba(0,0,0,.7); } .co_overlay-scroll.scroll-hide .co_scrollbar, .co_overlay-scroll.vertical_disabled .co_scrollbar._vertical, .co_overlay-scroll.horizontal_disabled .co_scrollbar._horizontal{ display: none; } .co_overlay-scroll.vertical_disabled .co_overlay-viewport { overflow-y: hidden; } .co_overlay-scroll.horizontal_disabled .co_overlay-viewport { overflow-x: hidden; } .co_overlay-scroll.scroll-auto .co_scrollbar { opacity: 0; transition: opacity 120ms ease-out; } .co_overlay-scroll.scroll-auto:hover > .co_scrollbar, .co_overlay-scroll.scroll-auto:active > .co_scrollbar, .co_overlay-scroll.scroll-auto:focus > .co_scrollbar { opacity: 1; transition: opacity 340ms ease-out; } .co_resize-trigger { position: absolute; display: block; top: 0; left: 0; height: 100%; width: 100%; overflow: hidden; pointer-events: none; z-index: -1; opacity: 0; }
CoCreate-app/CoCreate-overlay-scroll
<|start_filename|>editor/portal.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* portal.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ddehtyar <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/02/20 12:11:58 by ddehtyar #+# #+# */ /* Updated: 2019/02/20 12:11:59 by ddehtyar ### ########.fr */ /* */ /* ************************************************************************** */ #include "doom_nuken.h" void make_portal_sector2(t_doom *den, t_wals *first_element, t_wals *first_element_new) { t_sector_list *lmp; t_sector_list *sector_in; t_wals *next_sector_start; sector_in = NULL; add_new_sector(den); lmp = den->sectors; den->i = -1; while (lmp->next) { if (++den->i == den->find_tmp->sec) sector_in = lmp; lmp = lmp->next; } next_sector_start = first_element; change_way2(den, first_element->next, &first_element); first_element->next = 0; while (next_sector_start->next) { first_element_new->next_sector = lmp; next_sector_start->next->next_sector = sector_in; first_element_new = first_element_new->next; next_sector_start = next_sector_start->next; } next_sector_start->blouk = 1; } void portal_sector_new(t_doom *den, t_wals *rmp, t_wals *lmp) { while (lmp && lmp->inside == den->find_tmp->inside) { rmp->next = (t_wals *)malloc(sizeof(t_wals)); rmp->next->x = lmp->x; rmp->next->y = lmp->y; rmp->next->x1 = lmp->x1; rmp->next->y1 = lmp->y1; rmp->next->sec = den->sec; rmp->next->p = 0; rmp->next->glass = -1; rmp->next->blouk = 0; rmp->next->inside = 0; rmp->next->tex = 1; rmp->next->nextsector_wall = lmp; lmp->nextsector_wall = rmp->next; rmp->next->next = NULL; den->walls += 1; lmp = lmp->next; rmp = rmp->next; } } void make_portal_sector(t_doom *den, t_col *vec) { t_wals *rmp; t_wals *lmp; t_wals *first_element; t_wals *first_element_new; lmp = NULL; rmp = den->tmp; while (rmp->next) { if ((rmp->sec != den->find_tmp->sec && rmp->next->sec == den->find_tmp->sec && rmp->next->inside == den->find_tmp->inside) || (rmp->sec == den->find_tmp->sec && rmp->inside != den->find_tmp->inside && rmp->next->inside == den->find_tmp->inside)) lmp = rmp->next; rmp = rmp->next; } first_element = rmp; first_element_new = lmp; portal_sector_new(den, rmp, lmp); den->sec += 1; den->secbak += 1; make_portal_sector2(den, first_element, first_element_new); retry_write(den, vec); } int check_make_portal(t_doom *den) { if (((den->find_tmp_one->x1 == den->find_tmp_two->x) && (den->find_tmp_one->x == den->find_tmp_two->x1) && (den->find_tmp_one->y == den->find_tmp_two->y1) && (den->find_tmp_one->y1 == den->find_tmp_two->y)) || ((den->find_tmp_one->x1 == den->find_tmp_two->x1) && (den->find_tmp_one->x == den->find_tmp_two->x) && (den->find_tmp_one->y == den->find_tmp_two->y) && (den->find_tmp_one->y1 == den->find_tmp_two->y1))) return (1); return (0); } void portal_sector(t_doom *den) { t_wals *rmp; if (check_make_portal(den) == 1) { rmp = den->tmp; while (rmp) { if (rmp == den->find_tmp_one) { rmp->next_sector = get_sector_id(den, den->find_tmp_two->sec); rmp->nextsector_wall = den->find_tmp_two; } if (rmp == den->find_tmp_two) { rmp->next_sector = get_sector_id(den, den->find_tmp_one->sec); rmp->nextsector_wall = den->find_tmp_one; den->color = 0xFF0000; ft_line(den, &den->rec); break ; } rmp = rmp->next; } den->color = 0xFFFFFF; SDL_UpdateWindowSurface(den->window); } } <|start_filename|>3d/SRC/draw_hud.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* draw_hud.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbolilyi <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/02/28 16:24:31 by dbolilyi #+# #+# */ /* Updated: 2019/02/28 16:29:48 by dbolilyi ### ########.fr */ /* */ /* ************************************************************************** */ #include "../guardians.h" void draw_crosshair(t_sdl *iw) { int i; int j; int to; j = WINDOW_W / 2; i = WINDOW_H / 2 - 4; to = WINDOW_H / 2 - 15; while (--i > to) set_pixel2(iw->sur, j, i, 0x00FF00); i = WINDOW_H / 2 + 4; to = WINDOW_H / 2 + 15; while (++i < to) set_pixel2(iw->sur, j, i, 0x00FF00); i = WINDOW_H / 2; j = WINDOW_W / 2 + 4; to = WINDOW_W / 2 + 15; while (++j < to) set_pixel2(iw->sur, j, i, 0x00FF00); j = WINDOW_W / 2 - 4; to = WINDOW_W / 2 - 15; while (--j > to) set_pixel2(iw->sur, j, i, 0x00FF00); } void draw_text_number(t_sdl *iw, t_draw_info *d, const char *s, int numb) { d->s2 = ft_itoa(numb); d->s3 = ft_strjoin(s, d->s2); free(d->s2); d->stext = TTF_RenderText_Solid(iw->arial_font, d->s3, d->col); free(d->s3); SDL_BlitSurface(d->stext, NULL, iw->sur, &d->rect); SDL_FreeSurface(d->stext); } void draw_text(t_sdl *iw, const char *s, int x, int y) { SDL_Color col; SDL_Rect rect; SDL_Surface *stext; col.a = 0; col.r = 0; col.g = 255; col.b = 0; rect.x = x; rect.y = y; rect.h = 100; rect.w = 100; stext = TTF_RenderText_Solid(iw->arial_font, s, col); SDL_BlitSurface(stext, NULL, iw->sur, &rect); SDL_FreeSurface(stext); } void draw_text_blue(t_sdl *iw, const char *s, int x, int y) { SDL_Color col; SDL_Rect rect; SDL_Surface *stext; col.a = 0; col.r = 0; col.g = 0; col.b = 170; rect.x = x; rect.y = y; rect.h = 100; rect.w = 100; stext = TTF_RenderText_Solid(iw->arial_font, s, col); SDL_BlitSurface(stext, NULL, iw->sur, &rect); SDL_FreeSurface(stext); } void draw_some_info2(t_sdl *iw) { char *s; if (iw->v.f_button_mode == 1) { draw_text(iw, "Select Sectors to control light by pressing F", 50, 150); draw_text(iw, "Press G to exit this mode", 50, 175); } else if (iw->v.f_button_mode == 2) { draw_text(iw, "Select Sector to be animated by pressing F", 50, 150); draw_text(iw, "Press G to exit this mode", 50, 175); } else if (iw->v.f_button_mode == 3) { draw_text(iw, "Select walls to be animated by pressing F", 50, 150); draw_text(iw, "Press G to exit this mode", 50, 175); if (iw->v.wall_anim != 0) { draw_text(iw, "Selected walls: ", 50, 200); draw_text(iw, (s = ft_itoa(iw->v.wall_anim->count_walls)), 250, 200); free(s); } } } <|start_filename|>3d/SRC/add_delete_picture.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* add_delete_picture.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbolilyi <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/02/28 14:56:20 by dbolilyi #+# #+# */ /* Updated: 2019/02/28 14:57:48 by dbolilyi ### ########.fr */ /* */ /* ************************************************************************** */ #include "../guardians.h" void add_picture(t_sdl *iw, t_wall *wall) { t_picture *tmp; if (iw->v.submenu_mode != 0 || iw->v.f_button_mode != 0) return ; tmp = (t_picture *)malloc(sizeof(t_picture)); tmp->left_plus = 0; tmp->zu = get_ceil_z(iw, wall->x, wall->y); tmp->tw = 500; tmp->t = iw->v.tex_to_fill; tmp->next = wall->p; wall->p = tmp; if (iw->v.tex_to_fill == 17 || iw->v.tex_to_fill == 18) { iw->v.f_button_mode = 1; iw->v.f_button_pointer = (void *)tmp; } else if (iw->v.tex_to_fill == 19) { iw->v.submenu_mode = 4; draw_submenu(iw); iw->v.f_button_pointer = (void *)tmp; } calculate_picture(iw, wall, tmp); } void delete_wall_animation1(t_sdl *iw, t_wall_animation *tmp2) { do_wall_animation_step_dx(iw, tmp2, -tmp2->curr_dx); do_wall_animation_step_dy(iw, tmp2, -tmp2->curr_dy); iw->wall_animations = iw->wall_animations->next; free(tmp2); } void delete_wall_animation(t_sdl *iw, t_picture *pic) { t_wall_animation *tmp; t_wall_animation *tmp2; if (iw->wall_animations == 0) return ; if (iw->wall_animations->trigger == pic) { delete_wall_animation1(iw, iw->wall_animations); return ; } tmp = iw->wall_animations; while (tmp->next) { if (tmp->next->trigger == pic) { tmp2 = tmp->next; do_wall_animation_step_dx(iw, tmp2, -tmp2->curr_dx); do_wall_animation_step_dy(iw, tmp2, -tmp2->curr_dy); tmp->next = tmp->next->next; free(tmp2); return ; } tmp = tmp->next; } } void delete_light_and_animations(t_sdl *iw, t_picture *pic) { int sec; t_sector_animation a; t_sector_animation *tmp; t_sector_animation *tmp2; sec = -1; while (++sec < iw->v.sc) if (iw->sectors[sec].light == pic) iw->sectors[sec].light = 0; a.next = iw->sector_animations; tmp = &a; while (tmp->next) { if (tmp->next->trigger == pic) { tmp2 = tmp->next; tmp->next = tmp->next->next; do_sector_animation_step(iw, tmp2, -tmp2->curr_dy); free(tmp2); } else tmp = tmp->next; } iw->sector_animations = a.next; delete_wall_animation(iw, pic); } void delete_picture(t_wall *wall, t_picture *pic, t_sdl *iw) { t_picture *tmp; if (iw->v.submenu_mode != 0 || iw->v.f_button_mode != 0) return ; delete_light_and_animations(iw, pic); if (pic == wall->p) { wall->p = wall->p->next; free(pic); } else { tmp = wall->p; while (tmp->next != 0) { if (tmp->next == pic) break ; tmp = tmp->next; } if (tmp->next != 0) { tmp->next = tmp->next->next; free(pic); } } } <|start_filename|>libft/ft_itoa_base.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_itoa_base.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ddehtyar <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/03/31 18:18:08 by ddehtyar #+# #+# */ /* Updated: 2018/04/01 17:08:40 by ddehtyar ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" static char *ft_base(int b, long int qwe, int base) { long int a; int i; int iter; char *let; char *c; let = "0123456789ABCDEF"; a = 1; i = 1; iter = 0; while (qwe / a != 0 && (i++ >= 0)) a = a * base; a = a / base; c = (char*)malloc(i + b); if (b == 1) c[0] = '-'; while (iter < i - 1) { c[iter + b] = let[(qwe / a) % base]; a = a / base; iter++; } c[iter + b] = '\0'; return (c); } char *ft_itoa_base(int value, int base) { char *c; long int qwe; int b; qwe = value; b = 0; if (base > 16 && base < 2) return (0); if (qwe == 0) { c = (char*)malloc(2); c[0] = '0'; c[1] = '\0'; return (c); } if (base != 10 && qwe < 0) qwe = -qwe; if (base == 10 && qwe < 0) { b = 1; qwe = -qwe; } c = ft_base(b, qwe, base); return (c); } <|start_filename|>3d/SRC4/draw_glass_kernel.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* draw_glass_kernel.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbolilyi <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/05 14:37:38 by dbolilyi #+# #+# */ /* Updated: 2019/03/05 14:37:39 by dbolilyi ### ########.fr */ /* */ /* ************************************************************************** */ #include "../guardians.h" void draw_glass_tex_kernel2(t_sdl *iw, t_save_wall *left, t_save_wall *right, t_draw_wall_floor_ceil_tex_kernel *d) { if (iw->sectors[iw->d.cs].light == 0 || iw->sectors[iw->d.cs].light->t != 18) d->cint[6] = 1; else d->cint[6] = 0; d->cint[1] = iw->t[left->wall->glass]->w; d->cint[2] = iw->t[left->wall->glass]->h; d->lv.x = (float)(left->p.x - iw->p.x); d->lv.y = (float)(left->p.y - iw->p.y); d->rv.x = (float)(right->p.x - iw->p.x); d->rv.y = (float)(right->p.y - iw->p.y); d->ang = acosf((d->lv.x * d->rv.x + d->lv.y * d->rv.y) / (sqrtf(d->lv.x * d->lv.x + d->lv.y * d->lv.y) * sqrtf(d->rv.x * d->rv.x + d->rv.y * d->rv.y))); d->cfloat[0] = d->ang / (float)(right->x - left->x + 1); d->rv.x = (float)(-right->p.x + left->p.x); d->rv.y = (float)(-right->p.y + left->p.y); d->cfloat[2] = G180 - acosf((d->lv.x * d->rv.x + d->lv.y * d->rv.y) / (sqrtf(d->lv.x * d->lv.x + d->lv.y * d->lv.y) * sqrtf(d->rv.x * d->rv.x + d->rv.y * d->rv.y))); d->cfloat[1] = sqrtf(powf(iw->p.x - left->p.x, 2.0f) + powf(iw->p.y - left->p.y, 2.0f)); d->len_lr = sqrtf(powf(left->p.x - right->p.x, 2.0f) + powf(left->p.y - right->p.y, 2.0f)); d->cint[0] = iw->d.cs; } void draw_glass_tex_kernel3(t_sdl *iw, t_save_wall *left, t_save_wall *right, t_draw_wall_floor_ceil_tex_kernel *d) { d->cint[7] = iw->t[left->wall->glass]->bpp; d->cint[8] = iw->t[left->wall->glass]->pitch; d->cint[3] = get_ceil_z(iw, iw->walls[left->wall->nextsector_wall].next->x, iw->walls[left->wall->nextsector_wall].next->y); d->cint[4] = get_floor_z(iw, iw->walls[left->wall->nextsector_wall].next->x, iw->walls[left->wall->nextsector_wall].next->y); if (left->zu < d->cint[3]) { d->cfloat[5] = (right->zu - left->zu) / d->len_lr; d->cint[3] = left->zu; } else { d->cint[5] = get_ceil_z(iw, iw->walls[left->wall->nextsector_wall].x, iw->walls[left->wall->nextsector_wall].y); d->cfloat[5] = (d->cint[5] - d->cint[3]) / d->len_lr; } } void draw_glass_tex_kernel4(t_sdl *iw, t_save_wall *left, t_save_wall *right, t_draw_wall_floor_ceil_tex_kernel *d) { if (left->zd > d->cint[4]) { d->cfloat[6] = (right->zd - left->zd) / d->len_lr; d->cint[4] = left->zd; } else { d->cint[5] = get_floor_z(iw, iw->walls[left->wall->nextsector_wall].x, iw->walls[left->wall->nextsector_wall].y); d->cfloat[6] = (d->cint[5] - d->cint[4]) / d->len_lr; } iw->d.cs = d->cint[0]; d->cint[0] = left->x; d->cint[5] = WINDOW_W; d->cfloat[3] = left->olen; d->cfloat[4] = iw->tsz[left->wall->glass]; iw->k.ret = clEnqueueWriteBuffer(iw->k.command_queue, iw->k.m_wallTop, CL_TRUE, 0, (right->x - left->x + 1) * sizeof(int), iw->d.save_top_betw, 0, NULL, NULL); iw->k.ret = clEnqueueWriteBuffer(iw->k.command_queue, iw->k.m_wallBot, CL_TRUE, 0, (right->x - left->x + 1) * sizeof(int), iw->d.save_bot_betw, 0, NULL, NULL); iw->k.ret = clEnqueueWriteBuffer(iw->k.command_queue, iw->k.m_cint, CL_TRUE, 0, 9 * sizeof(int), d->cint, 0, NULL, NULL); } void draw_glass_tex_kernel(t_sdl *iw, t_save_wall *left, t_save_wall *right, int len) { t_draw_wall_floor_ceil_tex_kernel d; draw_glass_tex_kernel2(iw, left, right, &d); iw->d.cs = left->wall->nextsector; draw_glass_tex_kernel3(iw, left, right, &d); draw_glass_tex_kernel4(iw, left, right, &d); iw->k.ret = clEnqueueWriteBuffer(iw->k.command_queue, iw->k.m_cfloat, CL_TRUE, 0, 7 * sizeof(float), d.cfloat, 0, NULL, NULL); iw->k.ret = clSetKernelArg(iw->k.kernel5, 3, sizeof(cl_mem), (void *)&iw->k.m_t[left->wall->glass]); d.global_item_size = len; d.local_item_size = 1; iw->k.ret = clEnqueueNDRangeKernel(iw->k.command_queue, iw->k.kernel5, 1, NULL, &d.global_item_size, &d.local_item_size, 0, NULL, NULL); clFlush(iw->k.command_queue); clFinish(iw->k.command_queue); } <|start_filename|>editor/delete.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* delete.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ddehtyar <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/02/06 12:16:30 by ddehtyar #+# #+# */ /* Updated: 2019/02/06 12:16:31 by ddehtyar ### ########.fr */ /* */ /* ************************************************************************** */ #include "doom_nuken.h" int go_delete_help(int sec, t_wals *rmp, t_doom *den, int k) { if (rmp->next && rmp->next->sec != sec) { if (k == 1) den->tmp->next = rmp->next; if (k == 0) den->tmp = rmp->next; return (den->i); } if (k == 0 && rmp->next == NULL) { den->tmp = NULL; return (den->i); } if (rmp->next == NULL) { den->tmp->next = NULL; return (den->i); } return (0); } int go_delete(int sec, t_wals *rmp, t_doom *den, int k) { t_wals *cmp; t_wals *nmp; int m; nmp = NULL; den->i = 0; while (rmp) { if (rmp->next_sector != 0) go_delete_one(rmp, nmp); cmp = rmp; den->i += 1; if ((m = go_delete_help(sec, rmp, den, k)) != 0) { free(cmp); return (den->i); } rmp = rmp->next; free(cmp); } return (0); } void delete_sector_one(t_doom *den, int sec) { t_wals *first; den->i = go_delete(sec, den->tmp, den, 0); first = den->tmp; while (den->tmp) { den->tmp->sec -= 1; den->tmp = den->tmp->next; } den->tmp = first; } void delete_sector_two(t_doom *den, int sec) { den->i = go_delete(sec, den->tmp->next, den, 1); while (den->tmp->next) { den->tmp->next->sec -= 1; den->tmp = den->tmp->next; } } void delete_sector(t_doom *den) { t_wals *first; int sec; int nw; den->i = 0; sec = den->find_tmp->sec; first = den->tmp; nw = 0; while (den->tmp) { if (den->tmp->sec == sec) { delete_sector_one(den, sec); break ; } else if (den->tmp->next && den->tmp->next->sec == sec) { delete_sector_two(den, sec); den->tmp = first; break ; } nw++; den->tmp = den->tmp->next; } delete_sector2(den, sec, nw); } <|start_filename|>editor/button.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* button.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ddehtyar <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/01 15:40:41 by ddehtyar #+# #+# */ /* Updated: 2019/03/01 15:40:42 by ddehtyar ### ########.fr */ /* */ /* ************************************************************************** */ #include "doom_nuken.h" void pres_button_two(int x, int y, t_doom *den) { if (x >= 1840 && x < 1890 && y >= 680 && y < 730) den->button_change = 6; else if (x >= 1760 && x < 1810 && y >= 440 && y < 597) den->button_change = 8; else if (x >= 1815 && x < 1865 && y >= 440 && y < 597) den->button_change = 9; else if (x >= 1875 && x < 1925 && y >= 443 && y < 600) den->button_change = 10; else if (x >= 1940 && x < 1990 && y >= 443 && y < 600) den->button_change = 11; } void pres_button(int x, int y, t_doom *den, t_col *vec) { if (den->sec > 0 && den->blouk == 1) { if (x >= 1760 && x < 1810 && y >= 510 && y < 567) den->button_change = 1; else if (x >= 1820 && x < 1870 && y >= 510 && y < 567) den->button_change = 2; else if (x >= 1880 && x < 1930 && y >= 510 && y < 567) den->button_change = 3; else if (x >= 1940 && x < 1990 && y >= 510 && y < 567) den->button_change = 4; else if (x >= 1840 && x < 1890 && y >= 300 && y < 357) den->button_change = 5; else if (x >= 1840 && x < 1900 && y >= 680 && y < 737) den->button_change = 6; else if (x >= 1760 && x < 2010 && y >= 300 && y < 730) pres_button_two(x, y, den); else den->button_change = 0; } if (x >= 1770 && x < 1830 && y >= 300 && y < 357) den->button_change = 7; movie_button(den, vec); } int check_picture_wall(t_doom *den, t_wals *tmp) { while (tmp) { if (tmp == den->find_tmp) { if (tmp->p != NULL) return (1); else return (0); } tmp = tmp->next; } return (0); } int check_picture(t_doom *den) { t_wals *tmp; tmp = den->tmp; if (den->change != 3) { if (check_picture_wall(den, tmp) == 1) return (1); } else { if (tmp->sec != den->find_tmp->sec) { while (tmp->next && tmp->next->sec != den->find_tmp->sec) tmp = tmp->next; tmp = tmp->next; } while (tmp && tmp->sec == den->find_tmp->sec) { if (tmp->p != NULL) return (1); tmp = tmp->next; } } return (0); } void blouk_delete(t_doom *den) { char *cmp; SDL_Color color_text; clean_string(den); color_text.r = 255; color_text.g = 0; color_text.b = 0; cmp = "please delete picture in wall\n"; den->TTF_TextSolid = TTF_RenderText_Blended_Wrapped(den->font, cmp, color_text, 200); den->rect.x = 1770; den->rect.y = 380; den->rect.h = 50; den->rect.w = 30; SDL_BlitSurface(den->TTF_TextSolid, NULL, den->bmp, &den->rect); SDL_FreeSurface(den->TTF_TextSolid); SDL_UpdateWindowSurface(den->window); } <|start_filename|>3d/SRC4/draw_inclined_wall_floor_ceil_kernel.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* draw_inclined_wall_floor_ceil_kernel.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbolilyi <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/05 14:38:05 by dbolilyi #+# #+# */ /* Updated: 2019/03/05 14:38:06 by dbolilyi ### ########.fr */ /* */ /* ************************************************************************** */ #include "../guardians.h" void draw_inclined_wall_floor_ceil_tex_kernel2(t_sdl *iw, t_draw_wall_floor_ceil_tex_kernel *d) { d->cint[22] = iw->d.screen_right; d->cint[23] = iw->sectors[iw->d.cs].cl.t; if (iw->sectors[iw->d.cs].fr.n == 0) { d->cint[11] = 0; d->cint[12] = 0; d->cint[13] = -1; d->cint[14] = iw->sectors[iw->d.cs].fr.z; } else { d->cint[11] = iw->sectors[iw->d.cs].fr.n->a; d->cint[12] = iw->sectors[iw->d.cs].fr.n->b; d->cint[13] = iw->sectors[iw->d.cs].fr.n->c; d->cint[14] = iw->sectors[iw->d.cs].fr.n->d; } } void draw_inclined_wall_floor_ceil_tex_kernel3(t_sdl *iw, t_save_wall *left, t_save_wall *right, t_draw_wall_floor_ceil_tex_kernel *d) { if (iw->sectors[iw->d.cs].cl.n == 0) { d->cint[15] = 0; d->cint[16] = 0; d->cint[17] = -1; d->cint[18] = iw->sectors[iw->d.cs].cl.z; } else { d->cint[15] = iw->sectors[iw->d.cs].cl.n->a; d->cint[16] = iw->sectors[iw->d.cs].cl.n->b; d->cint[17] = iw->sectors[iw->d.cs].cl.n->c; d->cint[18] = iw->sectors[iw->d.cs].cl.n->d; } d->cint[19] = left->zu; d->cint[20] = left->zd; d->cfloat[5] = iw->d.screen.a; d->cfloat[6] = iw->d.screen.b; d->cfloat[7] = iw->d.screen.c; d->cfloat[8] = iw->d.screen_len; d->cfloat[13] = left->olen; d->lv.x = (float)(left->p.x - iw->p.x); d->lv.y = (float)(left->p.y - iw->p.y); d->rv.x = (float)(right->p.x - iw->p.x); d->rv.y = (float)(right->p.y - iw->p.y); } void draw_inclined_wall_floor_ceil_tex_kernel4(t_sdl *iw, t_save_wall *left, t_save_wall *right, t_draw_wall_floor_ceil_tex_kernel *d) { d->ang = acosf((d->lv.x * d->rv.x + d->lv.y * d->rv.y) / (sqrtf(d->lv.x * d->lv.x + d->lv.y * d->lv.y) * sqrtf(d->rv.x * d->rv.x + d->rv.y * d->rv.y))); d->cfloat[0] = d->ang / (float)(right->x - left->x + 1); d->ang = 0.0f; d->rv.x = (float)(-right->p.x + left->p.x); d->rv.y = (float)(-right->p.y + left->p.y); d->cfloat[2] = G180 - acosf((d->lv.x * d->rv.x + d->lv.y * d->rv.y) / (sqrtf(d->lv.x * d->lv.x + d->lv.y * d->lv.y) * sqrtf(d->rv.x * d->rv.x + d->rv.y * d->rv.y))); d->cfloat[1] = sqrtf(powf(iw->p.x - left->p.x, 2.0f) + powf(iw->p.y - left->p.y, 2.0f)); d->len_lr = sqrtf(powf(left->p.x - right->p.x, 2.0f) + powf(left->p.y - right->p.y, 2.0f)); d->cfloat[15] = (right->zu - left->zu) / d->len_lr; d->cfloat[16] = (right->zd - left->zd) / d->len_lr; d->cfloat[3] = (float)(right->p.x - left->p.x) / d->len_lr; d->cfloat[4] = (float)(right->p.y - left->p.y) / d->len_lr; d->zu = get_ceil_z(iw, iw->p.x, iw->p.y); d->zd = get_floor_z(iw, iw->p.x, iw->p.y); d->cfloat[9] = (float)(d->zu - d->zd) / (float)(iw->p.z - d->zd); d->cfloat[10] = (float)(d->zu - d->zd) / (float)(d->zu - iw->p.z); d->cfloat[11] = (float)iw->p.x / 1000.0f; d->cfloat[12] = (float)iw->p.y / 1000.0f; } void draw_inclined_wall_floor_ceil_tex_kernel5(t_sdl *iw, t_save_wall *left, t_save_wall *right, t_draw_wall_floor_ceil_tex_kernel *d) { iw->k.ret = clEnqueueWriteBuffer(iw->k.command_queue, iw->k.m_wallTop, CL_TRUE, 0, (right->x - left->x + 1) * sizeof(int), iw->d.wallTop, 0, NULL, NULL); iw->k.ret = clEnqueueWriteBuffer(iw->k.command_queue, iw->k.m_wallBot, CL_TRUE, 0, (right->x - left->x + 1) * sizeof(int), iw->d.wallBot, 0, NULL, NULL); iw->k.ret = clEnqueueWriteBuffer(iw->k.command_queue, iw->k.m_cint, CL_TRUE, 0, 25 * sizeof(int), d->cint, 0, NULL, NULL); iw->k.ret = clEnqueueWriteBuffer(iw->k.command_queue, iw->k.m_cfloat, CL_TRUE, 0, 17 * sizeof(float), d->cfloat, 0, NULL, NULL); if (left->wall->t >= 0) iw->k.ret = clSetKernelArg(iw->k.kernel0, 3, sizeof(cl_mem), (void *)&iw->k.m_t[left->wall->t]); else iw->k.ret = clSetKernelArg(iw->k.kernel0, 3, sizeof(cl_mem), (void *)&iw->k.m_t[0]); iw->k.ret = clSetKernelArg(iw->k.kernel0, 4, sizeof(cl_mem), (void *)&iw->k.m_t[iw->sectors[iw->d.cs].fr.t]); if (iw->sectors[iw->d.cs].cl.t >= 0) iw->k.ret = clSetKernelArg(iw->k.kernel0, 5, sizeof(cl_mem), (void *)&iw->k.m_t[iw->sectors[iw->d.cs].cl.t]); else iw->k.ret = clSetKernelArg(iw->k.kernel0, 5, sizeof(cl_mem), (void *)&iw->k.m_t[iw->sectors[iw->d.cs].fr.t]); } void draw_inclined_wall_floor_ceil_tex_kernel(t_sdl *iw, t_save_wall *left, t_save_wall *right, int len) { t_draw_wall_floor_ceil_tex_kernel d; draw_inclined_wall_floor_ceil_tex_kernel1(iw, left, &d); d.cint[21] = iw->d.screen_left; draw_inclined_wall_floor_ceil_tex_kernel2(iw, &d); draw_inclined_wall_floor_ceil_tex_kernel3(iw, left, right, &d); draw_inclined_wall_floor_ceil_tex_kernel4(iw, left, right, &d); draw_inclined_wall_floor_ceil_tex_kernel5(iw, left, right, &d); d.global_item_size = len; d.local_item_size = 1; iw->k.ret = clEnqueueNDRangeKernel(iw->k.command_queue, iw->k.kernel0, 1, NULL, &d.global_item_size, &d.local_item_size, 0, NULL, NULL); iw->k.ret = clFlush(iw->k.command_queue); iw->k.ret = clFinish(iw->k.command_queue); } <|start_filename|>editor/save.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* save.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: elopukh <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/05 15:21:11 by elopukh #+# #+# */ /* Updated: 2019/03/05 15:21:13 by elopukh ### ########.fr */ /* */ /* ************************************************************************** */ #define _CRT_SECURE_NO_WARNINGS #include "doom_nuken.h" void set_nextsectors(t_doom *den) { t_wals *w; w = den->tmp; while (w) { if (w->next_sector != 0) { w->next_sector_numb = w->next_sector->id; w->nextsector_wall_numb = w->nextsector_wall->id; } else { w->next_sector_numb = -1; w->nextsector_wall_numb = -1; } w = w->next; } } void save_map_music(t_doom *den) { int i; i = -1; while (++i < MUSIC_COUNT) { write(den->fd, &(den->iw.sounds.music_pack_size[i]), sizeof(size_t)); write(den->fd, den->iw.sounds.music_pack[i], den->iw.sounds.music_pack_size[i]); } } void save_map_env(t_doom *den) { int i; i = -1; while (++i < ENV_COUNT) { write(den->fd, den->iw.sounds.env[i], sizeof(Mix_Chunk)); write(den->fd, den->iw.sounds.env[i]->abuf, den->iw.sounds.env[i]->alen); } } void save_map_file1(t_doom *den, int zero) { write(den->fd, "This is map created for doom-nukem " "by dbolilyi & ddehtyar & kkostrub & elopukh", 78); set_walls_sectors_ids(den); set_nextsectors(den); save_map_walls_pictures(den); write(den->fd, &zero, sizeof(int)); save_map_sec(den); write(den->fd, &zero, sizeof(int)); save_map_sprites(den); write(den->fd, &zero, sizeof(int)); save_map_sector_animations(den); write(den->fd, &zero, sizeof(int)); save_map_wall_animations(den); write(den->fd, &zero, sizeof(int)); save_map_checkpoints(den); write(den->fd, &zero, sizeof(int)); den->iw.l.start_x = den->player.x * MAP_SCALE; den->iw.l.start_y = den->player.y * MAP_SCALE; den->iw.l.start_rot = den->player.introt; den->iw.l.win_sector = den->finish; write(den->fd, &den->iw.l, sizeof(t_level)); write(den->fd, &zero, sizeof(int)); save_map_textures(den, zero); } void save_map_file(t_doom *den) { int zero; den->fd = open(den->fname, WRITE_MAP); if (den->fd < 0) return ; zero = 0; save_map_file1(den, zero); write(den->fd, &zero, sizeof(int)); save_map_music(den); write(den->fd, &zero, sizeof(int)); save_map_env(den); write(den->fd, &zero, sizeof(int)); write(den->fd, &den->iw.k.source_size, sizeof(size_t)); write(den->fd, den->iw.k.source_str, den->iw.k.source_size); write(den->fd, &zero, sizeof(int)); write(den->fd, &den->iw.font_pack_size, sizeof(size_t)); write(den->fd, den->iw.font_pack, den->iw.font_pack_size); write(den->fd, &zero, sizeof(int)); close(den->fd); } <|start_filename|>3d/SRC3/draw.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* draw.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbolilyi <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/05 13:02:00 by dbolilyi #+# #+# */ /* Updated: 2019/03/05 13:02:00 by dbolilyi ### ########.fr */ /* */ /* ************************************************************************** */ #include "../guardians.h" void draw_start(t_sdl *iw) { t_save_wall *left; t_save_wall *right; t_save_wall_pairs *tmp; if (iw->d.vw == 0) return ; left = iw->d.vw; while (left != 0) { if ((right = find_next_vis_wall(iw, left)) != 0 && left->x < right->x) if (!(right->x < iw->d.screen_left || left->x > iw->d.screen_right)) add_pair(iw, left, right); left = left->next; } new_sort_pairs(iw); calculate_sprites_once(iw); tmp = iw->d.vwp; while (tmp != 0) { get_sprites_top_bottom(iw, tmp); draw_left_right(iw, tmp->left, tmp->right); tmp = tmp->next; } save_walls(iw); free_pairs(iw); } void draw4(t_sdl *iw) { if (iw->v.kernel) draw_sprites_kernel(iw); else draw_sprites(iw); if (iw->v.game_mode && !iw->v.kernel) draw_gun(iw); else if (iw->v.game_mode) draw_gun_kernel(iw); if (iw->v.kernel) iw->k.ret = clEnqueueReadBuffer(iw->k.command_queue, iw->k.m_sur, CL_TRUE, 0, WINDOW_W * WINDOW_H * sizeof(int), iw->sur->pixels, 0, NULL, NULL); if (iw->v.wall_anim != 0) draw_selected_walls_to_be_animated(iw); iw->d.vw = *(iw->vw_save); *(iw->vw_save) = 0; free_walls(iw); iw->p.z += iw->v.crouch; } void draw3(t_sdl *iw) { t_visited_sector *tmp; iw->d.prev_sector = -1; iw->d.prev_sector_wall = 0; iw->sectors[iw->d.cs].visited = 1; tmp = (t_visited_sector *)malloc(sizeof(t_visited_sector)); tmp->sec = iw->d.cs; tmp->next = iw->visited_sectors; iw->visited_sectors = tmp; draw_start(iw); iw->visited_sectors = iw->visited_sectors->next; free(tmp); if (!check_look_picture(iw)) *(iw->v.look_picture) = 0; if (!iw->v.kernel) draw_skybox(iw); else draw_skybox_kernel(iw); sort_sprites(iw); draw4(iw); } void draw2(t_sdl *iw) { get_direction(iw); get_screen_line(iw); get_left_right_lines_points(iw); iw->d.vw = 0; iw->d.vwp = 0; iw->d.screen_left = 0; iw->d.screen_right = WINDOW_W - 1; get_visible_walls(iw); get_left_right_visible_walls(iw); if (iw->v.kernel) { clEnqueueWriteBuffer(iw->k.command_queue, iw->k.m_top, CL_TRUE, 0, (WINDOW_W + 1) * sizeof(int), iw->d.top, 0, NULL, NULL); clEnqueueWriteBuffer(iw->k.command_queue, iw->k.m_bottom, CL_TRUE, 0, (WINDOW_W + 1) * sizeof(int), iw->d.bottom, 0, NULL, NULL); } if (iw->v.mouse_mode == 1) { iw->v.look_portal = 0; *(iw->v.look_wall) = 0; *(iw->v.look_sector) = 0; *(iw->v.look_picture) = 0; iw->v.look_sprite = 0; } draw3(iw); } void draw(t_sdl *iw) { t_sprite *tmp1; int j; j = 0; tmp1 = *iw->sprite; while (tmp1 != 0) { tmp1->draweble = 0; j = 0; while (j < WINDOW_W) { tmp1->top[j] = -1; j++; } tmp1 = tmp1->next; } j = -1; while (++j < iw->v.sc) iw->sectors[j].visited = 0; set_top_bottom(iw); if ((iw->d.cs = get_sector(iw)) == -1) return ; iw->p.z -= iw->v.crouch; iw->v.ls = iw->d.cs; draw2(iw); } <|start_filename|>editor/info_display.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* info_display.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ddehtyar <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/02/28 17:05:35 by ddehtyar #+# #+# */ /* Updated: 2019/02/28 17:05:36 by ddehtyar ### ########.fr */ /* */ /* ************************************************************************** */ #include "doom_nuken.h" void info_display_three(t_doom *den, char *infor, SDL_Color color_text) { den->rect.x = 1920; den->rect.y = 94; den->TTF_TextSolid = TTF_RenderText_Blended_Wrapped(den->font, den->blouk == 1 ? "YES" : "NO", color_text, 200); SDL_BlitSurface(den->TTF_TextSolid, NULL, den->bmp, &den->rect); SDL_FreeSurface(den->TTF_TextSolid); if (den->change == 1 || den->change == 2) change_wall(den, color_text); free(infor); board_display(den); SDL_UpdateWindowSurface(den->window); } void info_display_two(t_doom *den, char *infor, SDL_Color color_text) { SDL_BlitSurface(den->TTF_TextSolid, NULL, den->bmp, &den->rect); SDL_FreeSurface(den->TTF_TextSolid); free(infor); den->rect.x = 1860; den->rect.y = 37; infor = ft_itoa(den->walls + 1); den->TTF_TextSolid = TTF_RenderText_Blended_Wrapped(den->font, infor, color_text, 200); SDL_BlitSurface(den->TTF_TextSolid, NULL, den->bmp, &den->rect); SDL_FreeSurface(den->TTF_TextSolid); free(infor); den->rect.x = 1860; den->rect.y = 67; sum_sprite(den); infor = ft_itoa(den->sprites); den->TTF_TextSolid = TTF_RenderText_Blended_Wrapped(den->font, infor, color_text, 200); SDL_BlitSurface(den->TTF_TextSolid, NULL, den->bmp, &den->rect); SDL_FreeSurface(den->TTF_TextSolid); info_display_three(den, infor, color_text); } void info_display(t_doom *den) { char *cmp; char *infor; SDL_Color color_text; color_text.r = 255; color_text.g = 255; color_text.b = 255; den->rect.x = 1770; den->rect.y = 10; den->rect.h = 50; den->rect.w = 30; cmp = "sectors:\nwalls:\nsprites:\nclosed sector:\ndedicated wall\n" "start_x:\nstar_y:\nfifnish_x:\nfinish_y:\nsector: "; den->TTF_TextSolid = TTF_RenderText_Blended_Wrapped(den->font, cmp, color_text, 200); SDL_BlitSurface(den->TTF_TextSolid, NULL, den->bmp, &den->rect); SDL_FreeSurface(den->TTF_TextSolid); den->rect.x = 1860; den->rect.y = 10; infor = ft_itoa(den->sec); den->TTF_TextSolid = TTF_RenderText_Blended_Wrapped(den->font, infor, color_text, 200); info_display_two(den, infor, color_text); } void change_wall_two(t_doom *den, SDL_Color ct, char *in) { den->rect.y = 204; in = ft_itoa(den->find_tmp->x1); den->TTF_TextSolid = TTF_RenderText_Blended_Wrapped(den->font, in, ct, 200); SDL_BlitSurface(den->TTF_TextSolid, NULL, den->bmp, &den->rect); SDL_FreeSurface(den->TTF_TextSolid); free(in); den->rect.y = 231; in = ft_itoa(den->find_tmp->y1); den->TTF_TextSolid = TTF_RenderText_Blended_Wrapped(den->font, in, ct, 200); SDL_BlitSurface(den->TTF_TextSolid, NULL, den->bmp, &den->rect); SDL_FreeSurface(den->TTF_TextSolid); free(in); den->rect.y = 258; in = ft_itoa(den->find_tmp->sec); den->TTF_TextSolid = TTF_RenderText_Blended_Wrapped(den->font, in, ct, 200); SDL_BlitSurface(den->TTF_TextSolid, NULL, den->bmp, &den->rect); SDL_FreeSurface(den->TTF_TextSolid); free(in); } void change_wall(t_doom *den, SDL_Color ct) { char *in; den->rect.x = 1880; den->rect.y = 150; den->rect.h = 50; den->rect.w = 30; in = ft_itoa(den->find_tmp->x); den->TTF_TextSolid = TTF_RenderText_Blended_Wrapped(den->font, in, ct, 200); SDL_BlitSurface(den->TTF_TextSolid, NULL, den->bmp, &den->rect); SDL_FreeSurface(den->TTF_TextSolid); free(in); den->rect.y = 177; in = ft_itoa(den->find_tmp->y); den->TTF_TextSolid = TTF_RenderText_Blended_Wrapped(den->font, in, ct, 200); SDL_BlitSurface(den->TTF_TextSolid, NULL, den->bmp, &den->rect); SDL_FreeSurface(den->TTF_TextSolid); free(in); change_wall_two(den, ct, in); } <|start_filename|>3d/SRC/mouse_left_up4.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* mouse_left_up4.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbolilyi <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/05 15:28:35 by dbolilyi #+# #+# */ /* Updated: 2019/03/05 15:28:36 by dbolilyi ### ########.fr */ /* */ /* ************************************************************************** */ #include "../guardians.h" void mouse_buttonleft_up1_4(int x, t_sdl *iw) { if (iw->v.submenu_mode == 1 && x > WINDOW_W - 450) { if (x < WINDOW_W - 430) { iw->v.sector_anim->type = 1; iw->v.submenu_mode = 2; draw_submenu(iw); } else if (x < WINDOW_W - 395) { iw->v.sector_anim->type = 2; iw->v.submenu_mode = 2; draw_submenu(iw); } else if (x < WINDOW_W - 355) { iw->v.sector_anim->type = 0; iw->v.submenu_mode = 2; draw_submenu(iw); } else if (x > WINDOW_W - 335 && x < WINDOW_W - 280) exit_editing_sector_animation(iw); } else mouse_buttonleft_up1_5(x, iw); } void mouse_buttonleft_up1_3(int x, int y, t_sdl *iw) { if (x < 230) { if (iw->v.changing_fc) { free((*(iw->v.look_sector))->cl.n); (*(iw->v.look_sector))->cl.n = 0; } else { free((*(iw->v.look_sector))->fr.n); (*(iw->v.look_sector))->fr.n = 0; } } else if (x > 332 && x < 430) { if (y < WINDOW_H + 135) draw_decor_tex_to_select(iw); else if (y < WINDOW_H + 170) draw_pickup_tex_to_select(iw); else draw_enemies_tex_to_select(iw); } else mouse_buttonleft_up1_4(x, iw); } void mouse_buttonleft_up1_2(int x, int y, t_sdl *iw) { if (x < 210) { if (y < WINDOW_H + 150) { if (iw->v.changing_fc) rotate_fc(&(*(iw->v.look_sector))->cl, 1, 1); else rotate_fc(&(*(iw->v.look_sector))->fr, 1, 1); } else { if (iw->v.changing_fc) rotate_fc(&(*(iw->v.look_sector))->cl, 1, -1); else rotate_fc(&(*(iw->v.look_sector))->fr, 1, -1); } } else mouse_buttonleft_up1_3(x, y, iw); } void mouse_buttonleft_up1_1(int y, t_sdl *iw) { if (y < WINDOW_H + 150) { if (iw->v.changing_fc) (*(iw->v.look_sector))->cl.z += 100; else if ((*(iw->v.look_sector))->cl.z - (*(iw->v.look_sector))->fr.z > 200) (*(iw->v.look_sector))->fr.z += 100; } else if (!iw->v.changing_fc) (*(iw->v.look_sector))->fr.z -= 100; else if ((*(iw->v.look_sector))->cl.z - (*(iw->v.look_sector))->fr.z > 200) (*(iw->v.look_sector))->cl.z -= 100; if (iw->v.changing_fc && (*(iw->v.look_sector))->cl.n != 0) (*(iw->v.look_sector))->cl.n->d = (*(iw->v.look_sector))-> cl.n->a * (*(iw->v.look_sector))->cl.x - (*(iw->v.look_sector))->cl.n->b * (*(iw->v.look_sector))->cl.y - (*(iw->v.look_sector))->cl.n->c * (*(iw->v.look_sector))->cl.z; else if (!iw->v.changing_fc && (*(iw->v.look_sector))->fr.n != 0) (*(iw->v.look_sector))->fr.n->d = (*(iw->v.look_sector))-> fr.n->a * (*(iw->v.look_sector))->fr.x - (*(iw->v.look_sector))->fr.n->b * (*(iw->v.look_sector))->fr.y - (*(iw->v.look_sector))->fr.n->c * (*(iw->v.look_sector))->fr.z; } void mouse_buttonleft_up1(int x, int y, t_sdl *iw) { if (x < 40) { iw->v.changing_fc = ((iw->v.changing_fc) ? 0 : 1); SDL_FillRect(iw->sur, &iw->v.chang_fc_rect, 0x000000); if (iw->v.changing_fc) draw_text(iw, "C", 15, WINDOW_H + 135); else draw_text(iw, "F", 15, WINDOW_H + 135); } else if (x < 70) mouse_buttonleft_up1_1(y, iw); else if (x < 140) { if (y < WINDOW_H + 150) rotate_fc(((iw->v.changing_fc) ? &(*(iw->v.look_sector))->cl : &(*(iw->v.look_sector))->fr), 0, 1); else if (iw->v.changing_fc) rotate_fc(&(*(iw->v.look_sector))->cl, 0, -1); else rotate_fc(&(*(iw->v.look_sector))->fr, 0, -1); } else mouse_buttonleft_up1_2(x, y, iw); } <|start_filename|>libft/Makefile<|end_filename|> # **************************************************************************** # # # # ::: :::::::: # # Makefile :+: :+: :+: # # +:+ +:+ +:+ # # By: dbolilyi <<EMAIL>> +#+ +:+ +#+ # # +#+#+#+#+#+ +#+ # # Created: 2018/03/27 18:40:56 by dbolilyi #+# #+# # # Updated: 2018/05/08 10:55:21 by dbolilyi ### ########.fr # # # # **************************************************************************** # NAME = libft.a HEADER = libft.h SRC = \ ft_atoi.c \ ft_bzero.c \ ft_isalnum.c \ ft_isalpha.c \ ft_isascii.c \ ft_isdigit.c \ ft_isprint.c \ ft_itoa.c \ ft_memalloc.c \ ft_memccpy.c \ ft_memchr.c \ ft_memcmp.c \ ft_memcpy.c \ ft_memdel.c \ ft_memmove.c \ ft_memset.c \ ft_putchar.c \ ft_putchar_fd.c \ ft_putendl.c \ ft_putendl_fd.c \ ft_putnbr.c \ ft_putnbr_fd.c \ ft_putstr.c \ ft_putstr_fd.c \ ft_strcat.c \ ft_strchr.c \ ft_strclr.c \ ft_strcmp.c \ ft_strcpy.c \ ft_strdel.c \ ft_strdup.c \ ft_strequ.c \ ft_striter.c \ ft_striteri.c \ ft_strjoin.c \ ft_strlcat.c \ ft_strlen.c \ ft_strmap.c \ ft_strmapi.c \ ft_strncat.c \ ft_strncmp.c \ ft_strncpy.c \ ft_strnequ.c \ ft_strnew.c \ ft_strnstr.c \ ft_strrchr.c \ ft_strsplit.c \ ft_strstr.c \ ft_strsub.c \ ft_strtrim.c \ ft_tolower.c \ ft_toupper.c \ ft_lstadd.c \ ft_lstdel.c \ ft_lstdelone.c \ ft_lstiter.c \ ft_lstnew.c \ ft_lstmap.c \ ft_strrev.c \ ft_lstadd_end.c \ ft_lstfree.c \ ft_lst_getn.c \ ft_lst_size.c \ get_next_line.c OBJ = \ ft_atoi.o \ ft_bzero.o \ ft_isalnum.o \ ft_isalpha.o \ ft_isascii.o \ ft_isdigit.o \ ft_isprint.o \ ft_itoa.o \ ft_memalloc.o \ ft_memccpy.o \ ft_memchr.o \ ft_memcmp.o \ ft_memcpy.o \ ft_memdel.o \ ft_memmove.o \ ft_memset.o \ ft_putchar.o \ ft_putchar_fd.o \ ft_putendl.o \ ft_putendl_fd.o \ ft_putnbr.o \ ft_putnbr_fd.o \ ft_putstr.o \ ft_putstr_fd.o \ ft_strcat.o \ ft_strchr.o \ ft_strclr.o \ ft_strcmp.o \ ft_strcpy.o \ ft_strdel.o \ ft_strdup.o \ ft_strequ.o \ ft_striter.o \ ft_striteri.o \ ft_strjoin.o \ ft_strlcat.o \ ft_strlen.o \ ft_strmap.o \ ft_strmapi.o \ ft_strncat.o \ ft_strncmp.o \ ft_strncpy.o \ ft_strnequ.o \ ft_strnew.o \ ft_strnstr.o \ ft_strrchr.o \ ft_strsplit.o \ ft_strstr.o \ ft_strsub.o \ ft_strtrim.o \ ft_tolower.o \ ft_toupper.o \ ft_lstadd.o \ ft_lstdel.o \ ft_lstdelone.o \ ft_lstiter.o \ ft_lstnew.o \ ft_lstmap.o \ ft_strrev.o \ ft_lstadd_end.o \ ft_lstfree.o \ ft_lst_getn.o \ ft_lst_size.o \ get_next_line.o FL = -Wall -Wextra -Werror all: $(NAME) $(NAME): @gcc -c $(FL) $(SRC) @ar rc $(NAME) $(OBJ) @ranlib $(NAME) @echo "\033[92mDONE\033[0m" clean: @/bin/rm -f $(OBJ) fclean: clean @/bin/rm -f $(NAME) re: fclean \ all <|start_filename|>editor/save5.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* save5.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: elopukh <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/05 15:46:05 by elopukh #+# #+# */ /* Updated: 2019/03/05 15:46:06 by elopukh ### ########.fr */ /* */ /* ************************************************************************** */ #include "doom_nuken.h" void write_textures2(t_doom *den, int zero) { int i; i = -1; while (++i < WEAPONS_TEXTURES_COUNT) { write(den->fd, den->iw.t_weap[i], sizeof(t_packaging_texture)); write(den->fd, den->iw.t_weap[i]->pixels, den->iw.t_weap[i]->pitch * den->iw.t_weap[i]->h); } write(den->fd, &zero, sizeof(int)); } void write_textures1(t_doom *den, int zero) { int i; i = -1; while (++i < PICK_UP_TEXTURES_COUNT) { write(den->fd, den->iw.t_pickup[i], sizeof(t_packaging_texture)); write(den->fd, den->iw.t_pickup[i]->pixels, den->iw.t_pickup[i]->pitch * den->iw.t_pickup[i]->h); } write(den->fd, &zero, sizeof(int)); i = -1; while (++i < ENEMIES_TEXTURES_COUNT) { write(den->fd, den->iw.t_enemies[i], sizeof(t_packaging_texture)); write(den->fd, den->iw.t_enemies[i]->pixels, den->iw.t_enemies[i]->pitch * den->iw.t_enemies[i]->h); } write(den->fd, &zero, sizeof(int)); write_textures2(den, zero); } void many_write(t_doom *den, int zero) { write(den->fd, den->iw.hud.enot, sizeof(t_packaging_texture)); write(den->fd, den->iw.hud.enot->pixels, den->iw.hud.enot->pitch * den->iw.hud.enot->h); write(den->fd, &zero, sizeof(int)); write(den->fd, den->iw.hud.miss, sizeof(t_packaging_texture)); write(den->fd, den->iw.hud.miss->pixels, den->iw.hud.miss->pitch * den->iw.hud.miss->h); write(den->fd, &zero, sizeof(int)); write(den->fd, den->iw.hud.saved, sizeof(t_packaging_texture)); write(den->fd, den->iw.hud.saved->pixels, den->iw.hud.saved->pitch * den->iw.hud.saved->h); write(den->fd, &zero, sizeof(int)); write(den->fd, den->iw.hud.dead, sizeof(t_packaging_texture)); write(den->fd, den->iw.hud.dead->pixels, den->iw.hud.dead->pitch * den->iw.hud.dead->h); write(den->fd, &zero, sizeof(int)); write(den->fd, den->iw.hud.win, sizeof(t_packaging_texture)); write(den->fd, den->iw.hud.win->pixels, den->iw.hud.win->pitch * den->iw.hud.win->h); write(den->fd, &zero, sizeof(int)); } void save_map_textures(t_doom *den, int zero) { int i; write_textures(den, zero); write_textures1(den, zero); many_write(den, zero); i = -1; while (++i < 3) { write(den->fd, den->iw.bag.button[i], sizeof(t_packaging_texture)); write(den->fd, den->iw.bag.button[i]->pixels, den->iw.bag.button[i]->pitch * den->iw.bag.button[i]->h); } write(den->fd, &zero, sizeof(int)); write(den->fd, den->iw.map.player, sizeof(t_packaging_texture)); write(den->fd, den->iw.map.player->pixels, den->iw.map.player->pitch * den->iw.map.player->h); write(den->fd, &zero, sizeof(int)); i = -1; while (++i < 6) { write(den->fd, den->iw.menu.icons[i], sizeof(t_packaging_texture)); write(den->fd, den->iw.menu.icons[i]->pixels, den->iw.menu.icons[i]->pitch * den->iw.menu.icons[i]->h); } write(den->fd, &zero, sizeof(int)); } void set_walls_sectors_ids(t_doom *den) { t_sector_list *sec; int id; t_wals *w; sec = den->sectors; id = 0; while (sec) { sec->id = id++; sec = sec->next; } w = den->tmp; id = 0; while (w) { w->id = id++; w = w->next; } } <|start_filename|>3d/SRC2/loop2.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* loop2.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbolilyi <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/05 16:42:02 by dbolilyi #+# #+# */ /* Updated: 2019/03/05 16:42:03 by dbolilyi ### ########.fr */ /* */ /* ************************************************************************** */ #include "../guardians.h" void loop1(t_sdl *iw) { if (iw->guns.status != 0) guns_loop(iw); if (iw->guns.status == 2 && clock() - iw->guns.prev_update_time > CLKS_P_S / 8) reload_gun(iw); guns_movements(iw); if (iw->v.game_mode) check_checkpoints(iw); if (iw->v.jetpack != 1 && clock() - iw->v.jetpack > JETPACK_TIME) { iw->v.jetpack = 1; iw->v.fly_mode = 0; iw->v.fall = 1; iw->v.fly_down = 1; iw->v.fly_up = 1; } if (iw->v.rot_right != 1) { iw->p.rot += (ROTATION_SPEED_PER_HALF_SEC * USELESS3 / (float)CLKS_P_S * 2.0f) * G1; while (iw->p.rot >= G360) iw->p.rot -= G360; iw->p.introt = (int)(iw->p.rot / G1); iw->v.rot_right = clock(); } } void loop2(t_sdl *iw) { if (iw->v.rot_left != 1) { iw->p.rot -= (ROTATION_SPEED_PER_HALF_SEC * USELESS2 / (float)CLKS_P_S * 2.0f) * G1; while (iw->p.rot < 0.0f) iw->p.rot += G360; iw->p.introt = (int)(iw->p.rot / G1); iw->v.rot_left = clock(); } if (iw->v.rot_up != 1 && iw->p.rotup < 2 * WINDOW_H) { iw->p.rotup += 2 * WINDOW_H * (clock() - iw->v.rot_up) / CLKS_P_S; iw->v.rot_up = clock(); } if (iw->v.rot_down != 1 && iw->p.rotup > -2 * WINDOW_H) { iw->p.rotup -= 2 * WINDOW_H * (clock() - iw->v.rot_down) / CLKS_P_S; iw->v.rot_down = clock(); } death(iw); if (iw->v.game_mode && iw->d.cs == iw->l.win_sector) { image_loop(iw, iw->hud.win); exit_x(iw); } } <|start_filename|>editor/doom_nuken.h<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* doom_Nuken.h :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ddehtyar <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/08/27 16:41:41 by ddehtyar #+# #+# */ /* Updated: 2018/08/27 16:41:42 by ddehtyar ### ########.fr */ /* */ /* ************************************************************************** */ #ifndef _DOOM_NUKEN_H # define _DOOM_NUKEN_H # define _CRT_SECURE_NO_WARNINGS # include <stdlib.h> # include <math.h> # include <time.h> # include "../3d/guardians.h" # ifdef __linux__ # include <SDL2/SDL.h> # include <SDL2/SDL_ttf.h> # else # include <SDL.h> # include <SDL_ttf.h> # endif # define WIDTH 2000 # define HEIGHT 1100 # define START 50 # define LIM -1000000 # define XSKAPE (START + den->skape) + den->startx # define YSKAPE (START + den->skape) + den->starty # define SKAPE (START + den->skape); typedef struct s_insect { long int x1; long int y1; long int x2; long int y2; unsigned long int wallcrossed; } t_insect; typedef struct s_rotate { double hwd; double hhd; double hws; double hhs; double a; double b; double r; int y; int x; int i; int j; } t_rotate; typedef struct s_cord { int x; int y; int bool_cor; int inside; } t_cord; typedef struct s_sector_list { // Sector Floor t_sector_fc fr; // Sector Ceil t_sector_fc cl; struct s_sector_list *next; int id; t_picture *light; int light_wall_numb; int light_numb; } t_sector_list; typedef struct s_wals { int x; int y; int x1; int y1; int sec; int blouk; int inside; //внутри сектора int tex; struct s_sector_list *next_sector; struct s_wals *nextsector_wall; struct s_wals *next; int id; int glass; t_picture *p; int next_sector_numb; int nextsector_wall_numb; } t_wals; typedef struct s_getmap { int w; int s; int i; int cw; int inside; int inside_start; t_sector_list *sl; t_wals *tmp; } t_getmap; typedef struct s_sort { t_line2d l; t_intpoint2d v1; t_intpoint2d v2; float sector_dir; } t_sort; typedef struct s_doom { t_sector_list *sectors; int border; int skape; int retskape; int startx; int starty; int color; int b_color; int button; int change; int walls; int sprites; int incede; t_sort *sort; t_sprite *sprite; t_wals *tmp; int sec; int secbak; int blouk; int i; int secbaktmp; int noblouk; int blouk3d; // переменная для блокировки int xsec; int ysec; int finish; // int select; // int button_change; int quit; t_col rec; t_col rec_two; t_wals *find_tmp; t_wals *find_tmp_one; t_wals *find_tmp_two; t_sprite *find_sprite; SDL_Window *window; SDL_Surface *bmp; SDL_Surface *icon[13]; TTF_Font *font; SDL_Color color_text; SDL_Surface *TTF_TextSolid; SDL_Rect rect; t_cord xy; t_player player; SDL_Cursor *cursor; int blockwall; double angle; // 3DDDDDD t_sdl iw; int fd; char *fname; } t_doom; void ft_line_y(t_doom *den, t_brz *tip, int x1, int y1); void ft_line_x(t_doom *den, t_brz *tip, int x1, int y1); void ft_line(t_doom *den, t_col *vec); void pixel_width(t_doom *den, int x, int y, int colort); void pixel_bigwidth(t_doom *den, int x, int y, int colort); Uint32 get_pixel2(SDL_Surface *sur, const int x, const int y); void coordinate_network(int x, int y, t_doom *den, t_col *vec); void set_pixel(SDL_Surface *bmp, int x, int y, Uint32 pixel); void load_image(t_doom *den); void free_surface(t_doom *den); void map_redactor_mane2(t_doom *den); void map_redactor_mane(t_doom *den, t_col *vec); void clean_find_vec(t_doom *den); void map_network (t_doom *den); void findstart(t_doom *den); void board_display_three(t_doom *den); void board_display_two(t_doom *den); void board_display(t_doom *den); void clean_display(t_doom *den); void blouk_wall(t_doom *den, t_wals *tmp, t_col *vec); void save_list(t_doom *den, t_col *vec); void save_map(int x, t_doom *den, t_col *vec); void save_map_help(t_doom *den, t_col *vec); void save_list_help(t_doom *den, t_col *vec); void save_map_help_two(t_doom *den, t_col *vec); void ft_lstaddmap(t_wals **start, t_wals *new); void ft_lstnewmap(t_wals **new, int x, int y, t_doom *den); void ft_lstnewmap_sec(t_wals **new, int x, int y, t_doom *den); void ft_save_parm(t_wals **tmp, int x, int y, t_doom *den); void ft_lstnewmap_sec_help(t_doom *den); float isleft_or_right(t_wals *list); void sort_sector(t_doom *den); void add_sector_dir(t_wals *tmp, t_wals *last, t_sort *sort); void sort_list_incide(t_doom *den); void check_data_sector(t_doom *den); void write_map_help(t_doom *den, t_col *vec); void write_map(t_doom *den, t_col *vec); void write_list_help(t_doom *den, t_wals *tmp, t_wals *rmp, t_wals *nmp); void write_list(t_doom *den, t_wals *tmp); void move_sector(t_doom *den, int y, int x); void find_wals(int x, int y, t_doom *den); void look_find_sector_two(t_doom *den); void clear_find(t_doom *den); void find_wals_help(t_doom *den); int point_into_segments(int x, int y, t_doom *den); void sector_in_sector_two(t_doom *den, t_wals *cmp, t_wals *lmp); void sector_in_sector(t_doom *den); void sort_walls_inside(t_doom *den); int inside_sect(t_doom *den, t_wals **tmp, int sec); void sort_walls_inside_help(t_doom *den, int *walls, int i, t_wals *rmp); int go_delete(int sec, t_wals *rmp, t_doom *den, int k); int go_delete_help(int sec, t_wals *rmp, t_doom *den, int k); void delete_sector_one(t_doom *den, int sec); void delete_sector_two(t_doom *den, int sec); void delete_sector(t_doom *den); void delete_pointer(t_doom *den, void* ptr); void delete_sector_memory(t_doom *den); void delete_sector_memory_one(t_doom *den, t_sector_list *first); void delete_sector_memory_two(t_doom *den, t_sector_list *first); void delete_wall(t_doom *den, t_col *vec); void delete_sprite(t_doom *den, t_sprite *s); void check_finish_sprite(t_doom *den); void see_sprite(t_doom *den); void find_sprite(t_doom *den, int x, int y); void add_sprite(t_doom *den); void make_portal_sector2(t_doom *den, t_wals *first_element, t_wals *first_element_new); void portal_sector_new(t_doom *den, t_wals *rmp, t_wals *lmp); void make_portal_sector(t_doom *den, t_col *vec); int check_make_portal(t_doom *den); void portal_sector(t_doom *den); void blouk_player(t_doom *den); void player(t_doom *den); void rotate_image(t_doom *den); void change_way(t_doom *den, int i, t_col *vec); void rotate_image_help(t_doom *den, t_rotate *rot); void add_new_sector(t_doom *den); void sort_help(int i, t_wals *rmp, t_wals *tmp, int *walls); void sort_walls_sec(t_wals *tmp); t_sector_list *get_sector_id(t_doom *den, int id); void change_way2(t_doom *den, t_wals *first_element, t_wals **first_element2); void in_all_sect(t_doom *den); int in_all_help(t_doom *den, t_wals *lmp, int sec); void blonk_on_now(t_doom *den); void clean_string(t_doom *den); void back_startwall(t_doom *den, t_col *vec); void change_rec(t_doom *den, t_col *rec, t_wals *tmp); void next_wall_change(t_doom *den, t_wals *tmp, t_wals *rmp); void next_wall (t_doom *den); void back_wall_check(t_doom *den, t_wals *rmp, t_wals *lmp); void back_wall(t_doom *den, t_col *vec); void check_sprite(t_doom *den); void sum_sprite(t_doom *den); void sprite(t_doom *den); void retry_write(t_doom *den, t_col *vec); void clear_texture(t_doom *den, t_col *vec); void drow_find(t_doom *den); void all_sector(t_doom *den, t_wals *tmp); void blouk_write(t_doom *den); void clean_vec(t_col *vec); void info_display(t_doom *den); void info_display_two(t_doom *den, char *infor, SDL_Color color_text); void info_display_three(t_doom *den, char *infor, SDL_Color color_text); void change_wall_two(t_doom *den, SDL_Color color_text, char *infor); void change_wall(t_doom *den, SDL_Color color_text); void pres_button_two(int x, int y, t_doom *den); void pres_button(int x, int y, t_doom *den, t_col *vec); int check_picture_wall(t_doom *den, t_wals *tmp); int check_picture(t_doom *den); void blouk_delete(t_doom *den); void movie_button_five(t_doom *den, t_col *vec); void movie_button_four(t_doom *den, t_col *vec); void movie_button_three(t_doom *den); void movie_button_two(t_doom *den, t_col *vec); void movie_button(t_doom *den, t_col *vec); void mouse_button_down_sdl(t_doom *den, t_col *vec, SDL_Event e); void mouse_button_down_up_sdl(t_doom *den, t_col *vec, SDL_Event e); void key_down_sdl(t_doom *den, t_col *vec, const Uint8 *state); void ft_sdl_init(t_doom *den); void mouse_button_down(t_doom *den, t_col *vec, int x, int y); void ft_sdl_init_star(t_doom *den, t_col *vec); void key_down_but(t_doom *den, t_col *vec, const Uint8 *state); void mousewheel(t_doom *den, t_col *vec, int y); void mouse_button_down_select(t_doom *den, t_col *vec, SDL_Event e); void move_scan_sector(t_doom *den, const Uint8 *state); void move_scan_sprite(t_doom *den, const Uint8 *state); void move_scancode(t_doom *den, t_col *vec, const Uint8 *state); void mouse_button_rotate(t_doom *den, t_col *vec, int x, int y); void mouse_button_sprite(t_doom *den, t_col *vec, int x, int y); int count_walls(t_wals *tmp, t_getmap *gm, t_sdl *iw, t_doom *den); void get_map_one(t_sdl *iw, t_getmap *gm); void get_map_two(t_sdl *iw, t_getmap *gm); void get_map_three(t_sdl *iw, t_getmap *gm); void get_map(t_sdl *iw, t_doom *den); int main_edit(t_doom *den); int get_3d_def_edit(t_doom *den); void main3d_edit_free(t_doom *den); void main3d_edit(t_doom *den); void give_date(t_doom *den, t_sdl *iw); void unget_map_help(t_sdl *iw, t_wals *tmp, t_sector_list *sl); void unget_map(t_sdl *iw, t_doom *den, t_wals *tmp); int main_new(t_doom *den); void get_3d_def_new_init(t_doom *den); int get_3d_def_new(t_doom *den); void get_font_file(t_doom *den); int usage(void); int check_new(t_doom *den, char *fname); int check_load(t_doom *den, char *fname); int main_edit(t_doom *den); int get_3d_def_edit(t_doom *den); void main3d_edit_free(t_doom *den); void main3d_edit(t_doom *den); int get_3d_def_game(t_doom *den); void main3d_game(t_doom *den); void main3d_game_help(t_doom *den); int main_game(t_doom *den); void go_delete_one(t_wals *rmp, t_wals *nmp); int main_help(t_doom *den, char **argv); int main_help_two(t_doom *den, char **argv); int main_help_one(t_doom *den, char **argv); int load_map(t_doom *den); int load4_game(t_doom *den); void save_map_sec(t_doom *den); int count_pictures(t_picture *pic); void save_map_walls_pictures(t_doom *den); void save_map_sprites(t_doom *den); void save_reverse_map_wall_animations(t_doom *den, t_wall_animation *tmp); void save_map_sector_animations(t_doom *den); void save_map_wall_animations(t_doom *den); void save_map_checkpoints(t_doom *den); void write_textures(t_doom *den, int zero); void set_walls_sectors_ids(t_doom *den); void save_map_textures(t_doom *den, int zero); int read_check(int fd, void *dst, size_t max_inp); int load_map_sector_animations(t_doom *den); int load_map_wall_animations(t_doom *den); int load_map_checkpoints(t_doom *den); int load_map_level(t_doom *den); int load_map_sec(t_doom *den); int load_map_textures(t_doom *den); int connect_map_sectors(t_doom *den); void save_map_file(t_doom *den); void delete_sector2(t_doom *den, int sec, int nw); void check_deleting_wall_animations(t_doom *den, int nw); void save_map_info(t_doom *den); #endif <|start_filename|>editor/delete2.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* delete2.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbolilyi <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/11 12:57:25 by dbolilyi #+# #+# */ /* Updated: 2019/03/11 12:57:40 by dbolilyi ### ########.fr */ /* */ /* ************************************************************************** */ #include "doom_nuken.h" void check_deleting_sector_animations3(t_wall_animation *wa, int nw, int *f, int cw) { t_wall_animation *tmp; int i; i = -1; while (++i < wa->next->count_walls) { if (wa->next->walls[i] >= nw && wa->next->walls[i] < nw + cw) { tmp = wa->next; wa->next = wa->next->next; free(tmp); *f = 0; break ; } else if (wa->next->walls[i] >= nw + cw) wa->next->walls[i] -= cw; } } void check_deleting_sector_animations2(t_doom *den, int cw, int nw) { t_wall_animation wa_start; t_wall_animation *wa; int f; wa_start.next = den->iw.wall_animations; wa = &wa_start; while (wa->next) { f = 1; check_deleting_sector_animations3(wa, nw, &f, cw); if (f) wa = wa->next; } den->iw.wall_animations = wa_start.next; } void check_deleting_sector_animations(t_doom *den, int sec, int cw, int nw) { t_sector_animation sa_start; t_sector_animation *sa; t_sector_animation *tmp; sa_start.next = den->iw.sector_animations; sa = &sa_start; while (sa->next) if (sa->next->sector == sec) { tmp = sa->next; sa->next = sa->next->next; free(tmp); } else { if (sa->next->sector > sec) sa->next->sector -= 1; sa = sa->next; } den->iw.sector_animations = sa_start.next; check_deleting_sector_animations2(den, cw, nw); } void delete_sector2(t_doom *den, int sec, int nw) { check_deleting_sector_animations(den, sec, den->i, nw); den->walls = den->walls - den->i; den->sec -= 1; den->secbak -= 1; den->incede = 0; } <|start_filename|>3d/SRC/inside_sector.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* inside_sector.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbolilyi <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/02/28 17:07:12 by dbolilyi #+# #+# */ /* Updated: 2019/02/28 17:07:35 by dbolilyi ### ########.fr */ /* */ /* ************************************************************************** */ #include "../guardians.h" int in_sec_xy(t_sdl *iw, int sector, int x, int y) { t_in_sec d; int i; d.wallCrossed = 0; i = iw->sectors[sector].sw - 1; while (++i < iw->sectors[sector].sw + iw->sectors[sector].nw) { d.y1 = iw->walls[i].y - y; d.y2 = iw->walls[i].next->y - y; if ((d.y1 ^ d.y2) < 0) { d.x1 = iw->walls[i].x - x; d.x2 = iw->walls[i].next->x - x; if ((d.x1 ^ d.x2) >= 0) d.wallCrossed ^= d.x1; else d.wallCrossed ^= (d.x1 * d.y2 - d.x2 * d.y1) ^ d.y2; } } return (d.wallCrossed >> 31); } int in_sec(int sector, t_sdl *iw) { t_in_sec d; int i; d.wallCrossed = 0; i = iw->sectors[sector].sw - 1; while (++i < iw->sectors[sector].sw + iw->sectors[sector].nw) { d.y1 = iw->walls[i].y - iw->p.y; d.y2 = iw->walls[i].next->y - iw->p.y; if ((d.y1 ^ d.y2) < 0) { d.x1 = iw->walls[i].x - iw->p.x; d.x2 = iw->walls[i].next->x - iw->p.x; if ((d.x1 ^ d.x2) >= 0) d.wallCrossed ^= d.x1; else d.wallCrossed ^= (d.x1 * d.y2 - d.x2 * d.y1) ^ d.y2; } } return (d.wallCrossed >> 31); } int get_sector(t_sdl *iw) { int sec; sec = iw->v.ls - 1; while (++sec < iw->v.sc) if (in_sec(sec, iw) != 0) return (sec); sec = -1; while (++sec < iw->v.ls) if (in_sec(sec, iw) != 0) return (sec); return (-1); } <|start_filename|>3d/SRC3/draw_left_right.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* draw_left_right.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbolilyi <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/05 13:03:20 by dbolilyi #+# #+# */ /* Updated: 2019/03/05 13:03:21 by dbolilyi ### ########.fr */ /* */ /* ************************************************************************** */ #include "../guardians.h" void draw_all(t_sdl *iw, t_save_wall *left, t_save_wall *right, int len) { if (left->wall->nextsector == -1) { if (left->wall->p != 0) { ft_memcpy(iw->d.top_save, iw->d.top, USELESS4); ft_memcpy(iw->d.bottom_save, iw->d.bottom, USELESS4); } if (iw->sectors[iw->d.cs].fr.n == 0 && iw->sectors[iw->d.cs].cl.n == 0) draw_wall_floor_ceil_tex(iw, left, right, len); else draw_inclined_wall_floor_ceil_tex(iw, left, right, len); if (left->wall->p != 0) draw_pictures(iw, left); } else { if (iw->sectors[iw->d.cs].fr.n == 0 && iw->sectors[iw->d.cs].cl.n == 0) draw_floor_ceil_tex(iw, left, right, len); else draw_inclined_floor_ceil_tex(iw, left, right, len); draw_next_sector(iw, left, right); } } void draw_all_kernel(t_sdl *iw, t_save_wall *left, t_save_wall *right, int len) { if (left->wall->nextsector == -1) { if (left->wall->p != 0) { clEnqueueCopyBuffer(iw->k.command_queue, iw->k.m_top, iw->k.m_save_top2, 0, 0, USELESS4, 0, NULL, NULL); clEnqueueCopyBuffer(iw->k.command_queue, iw->k.m_bottom, iw->k.m_save_bottom2, 0, 0, USELESS4, 0, NULL, NULL); } if (iw->sectors[iw->d.cs].fr.n == 0 && iw->sectors[iw->d.cs].cl.n == 0) draw_wall_floor_ceil_tex_kernel(iw, left, right, len); else draw_inclined_wall_floor_ceil_tex_kernel(iw, left, right, len); if (left->wall->p != 0) draw_pictures_kernel(iw, left); } else draw_next_sector_kernel(iw, left, right, len); } void draw_left_right2(t_sdl *iw, t_save_wall *left, t_save_wall *right) { if (*(iw->v.look_wall) == 0 && iw->v.mouse_mode == 1 && left->x < WINDOW_W / 2 && right->x > WINDOW_W / 2 && iw->d.screen_left < WINDOW_W / 2 && iw->d.screen_right > WINDOW_W / 2) { if (left->wall->nextsector != -1 && iw->v.look_portal == 0) iw->v.look_portal = left->wall; if (left->wall->nextsector == -1) { *(iw->v.look_wall) = left->wall; *(iw->v.look_sector) = &iw->sectors[iw->d.cs]; } else if (left->wall->nextsector == iw->d.prev_sector) { *(iw->v.look_wall) = left->wall; *(iw->v.look_sector) = &iw->sectors[iw->d.cs]; } } if (iw->v.kernel) draw_all_kernel(iw, left, right, right->x - left->x + 1); else draw_all(iw, left, right, right->x - left->x + 1); } void draw_left_right(t_sdl *iw, t_save_wall *left, t_save_wall *right) { t_draw_line l; if (left->x >= right->x) return ; iw->d.wallTop = (int *)malloc((right->x - left->x + 1) * sizeof(int)); iw->d.wallBot = (int *)malloc((right->x - left->x + 1) * sizeof(int)); if (!iw->d.wallTop || !iw->d.wallBot) return ; l.x0 = left->x; l.x1 = right->x; l.y0 = WINDOW_H * (iw->p.z + (int)left->plen / 2 - left->zd) / (int)left->plen + iw->p.rotup; l.y1 = WINDOW_H * (iw->p.z + (int)right->plen / 2 - right->zd) / (int)right->plen + iw->p.rotup; brez_line(iw->d.wallBot, l); l.y0 = WINDOW_H * (iw->p.z + (int)left->plen / 2 - left->zu) / (int)left->plen + iw->p.rotup; l.y1 = WINDOW_H * (iw->p.z + (int)right->plen / 2 - right->zu) / (int)right->plen + iw->p.rotup; brez_line(iw->d.wallTop, l); draw_left_right2(iw, left, right); free(iw->d.wallBot); free(iw->d.wallTop); } <|start_filename|>3d/SRC4/draw_inclined_floor_ceil_betw_kernel.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* draw_inclined_floor_ceil_betw_kernel.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbolilyi <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/05 14:37:53 by dbolilyi #+# #+# */ /* Updated: 2019/03/05 14:37:58 by dbolilyi ### ########.fr */ /* */ /* ************************************************************************** */ #include "../guardians.h" void draw_inclined_floor_ceil_betw_tex_kernel2(t_sdl *iw, t_draw_wall_floor_ceil_tex_kernel *d) { d->cint[23] = iw->sectors[iw->d.cs].cl.t; d->cint[24] = iw->p.rotup; if (iw->sectors[iw->d.cs].fr.n == 0) { d->cint[11] = 0; d->cint[12] = 0; d->cint[13] = -1; d->cint[14] = iw->sectors[iw->d.cs].fr.z; } else { d->cint[11] = iw->sectors[iw->d.cs].fr.n->a; d->cint[12] = iw->sectors[iw->d.cs].fr.n->b; d->cint[13] = iw->sectors[iw->d.cs].fr.n->c; d->cint[14] = iw->sectors[iw->d.cs].fr.n->d; } } void draw_inclined_floor_ceil_betw_tex_kernel3(t_sdl *iw, t_save_wall *left, t_draw_wall_floor_ceil_tex_kernel *d) { if (iw->sectors[iw->d.cs].cl.n == 0) { d->cint[15] = 0; d->cint[16] = 0; d->cint[17] = -1; d->cint[18] = iw->sectors[iw->d.cs].cl.z; } else { d->cint[15] = iw->sectors[iw->d.cs].cl.n->a; d->cint[16] = iw->sectors[iw->d.cs].cl.n->b; d->cint[17] = iw->sectors[iw->d.cs].cl.n->c; d->cint[18] = iw->sectors[iw->d.cs].cl.n->d; } d->cint[19] = left->zu; d->cint[20] = left->zd; d->cfloat[5] = iw->d.screen.a; d->cfloat[6] = iw->d.screen.b; d->cfloat[7] = iw->d.screen.c; d->cfloat[8] = iw->d.screen_len; d->cfloat[13] = left->olen; d->cfloat[14] = iw->tsz[left->wall->t]; d->cfloat[17] = iw->p.rot; d->cfloat[18] = iw->v.angle; d->lv.x = (float)(left->p.x - iw->p.x); } void draw_inclined_floor_ceil_betw_tex_kernel4(t_sdl *iw, t_save_wall *left, t_save_wall *right, t_draw_wall_floor_ceil_tex_kernel *d) { d->lv.y = (float)(left->p.y - iw->p.y); d->rv.x = (float)(right->p.x - iw->p.x); d->rv.y = (float)(right->p.y - iw->p.y); d->ang = acosf((d->lv.x * d->rv.x + d->lv.y * d->rv.y) / (sqrtf(d->lv.x * d->lv.x + d->lv.y * d->lv.y) * sqrtf(d->rv.x * d->rv.x + d->rv.y * d->rv.y))); d->cfloat[0] = d->ang / (float)(right->x - left->x + 1); d->ang = 0.0f; d->rv.x = (float)(-right->p.x + left->p.x); d->rv.y = (float)(-right->p.y + left->p.y); d->cfloat[2] = G180 - acosf((d->lv.x * d->rv.x + d->lv.y * d->rv.y) / (sqrtf(d->lv.x * d->lv.x + d->lv.y * d->lv.y) * sqrtf(d->rv.x * d->rv.x + d->rv.y * d->rv.y))); d->cfloat[1] = sqrtf(powf(iw->p.x - left->p.x, 2.0f) + powf(iw->p.y - left->p.y, 2.0f)); d->len_lr = sqrtf(powf(left->p.x - right->p.x, 2.0f) + powf(left->p.y - right->p.y, 2.0f)); d->cfloat[15] = (right->zu - left->zu) / d->len_lr; d->cfloat[16] = (right->zd - left->zd) / d->len_lr; d->cfloat[3] = (float)(right->p.x - left->p.x) / d->len_lr; d->cfloat[4] = (float)(right->p.y - left->p.y) / d->len_lr; d->zu = get_ceil_z(iw, iw->p.x, iw->p.y); d->zd = get_floor_z(iw, iw->p.x, iw->p.y); d->cfloat[9] = (float)(d->zu - d->zd) / (float)(iw->p.z - d->zd); d->cfloat[10] = (float)(d->zu - d->zd) / (float)(d->zu - iw->p.z); } void draw_inclined_floor_ceil_betw_tex_kernel5(t_sdl *iw, t_save_wall *left, t_save_wall *right, t_draw_wall_floor_ceil_tex_kernel *d) { d->cfloat[11] = (float)iw->p.x / 1000.0f; d->cfloat[12] = (float)iw->p.y / 1000.0f; iw->k.ret = clEnqueueWriteBuffer(iw->k.command_queue, iw->k.m_wallTop, CL_TRUE, 0, (right->x - left->x + 1) * sizeof(int), iw->d.wallTop, 0, NULL, NULL); iw->k.ret = clEnqueueWriteBuffer(iw->k.command_queue, iw->k.m_wallBot, CL_TRUE, 0, (right->x - left->x + 1) * sizeof(int), iw->d.wallBot, 0, NULL, NULL); iw->k.ret = clEnqueueWriteBuffer(iw->k.command_queue, iw->k.m_cint, CL_TRUE, 0, 26 * sizeof(int), d->cint, 0, NULL, NULL); iw->k.ret = clEnqueueWriteBuffer(iw->k.command_queue, iw->k.m_cfloat, CL_TRUE, 0, 19 * sizeof(float), d->cfloat, 0, NULL, NULL); iw->k.ret = clEnqueueWriteBuffer(iw->k.command_queue, iw->k.m_top_betw, CL_TRUE, 0, (right->x - left->x + 1) * sizeof(int), iw->d.save_top_betw, 0, NULL, NULL); iw->k.ret = clEnqueueWriteBuffer(iw->k.command_queue, iw->k.m_bot_betw, CL_TRUE, 0, (right->x - left->x + 1) * sizeof(int), iw->d.save_bot_betw, 0, NULL, NULL); iw->k.ret = clSetKernelArg(iw->k.kernel2, 3, sizeof(cl_mem), (void *)&iw->k.m_t[left->wall->t]); iw->k.ret = clSetKernelArg(iw->k.kernel2, 4, sizeof(cl_mem), (void *)&iw->k.m_t[iw->sectors[iw->d.cs].fr.t]); } void draw_inclined_floor_ceil_betw_tex_kernel(t_sdl *iw, t_save_wall *left, t_save_wall *right, int len) { t_draw_wall_floor_ceil_tex_kernel d; draw_inclined_floor_ceil_betw_tex_kernel1(iw, left, &d); d.cint[22] = iw->d.screen_right; draw_inclined_floor_ceil_betw_tex_kernel2(iw, &d); draw_inclined_floor_ceil_betw_tex_kernel3(iw, left, &d); draw_inclined_floor_ceil_betw_tex_kernel4(iw, left, right, &d); draw_inclined_floor_ceil_betw_tex_kernel5(iw, left, right, &d); if (iw->sectors[iw->d.cs].cl.t >= 0) iw->k.ret = clSetKernelArg(iw->k.kernel2, 5, sizeof(cl_mem), (void *)&iw->k.m_t[iw->sectors[iw->d.cs].cl.t]); else iw->k.ret = clSetKernelArg(iw->k.kernel2, 5, sizeof(cl_mem), (void *)&iw->k.m_t[iw->l.skybox]); d.global_item_size = len; d.local_item_size = 1; iw->k.ret = clEnqueueNDRangeKernel(iw->k.command_queue, iw->k.kernel2, 1, NULL, &d.global_item_size, &d.local_item_size, 0, NULL, NULL); iw->k.ret = clFlush(iw->k.command_queue); iw->k.ret = clFinish(iw->k.command_queue); } <|start_filename|>3d/SRC3/get_floor_ceil_z.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* get_floor_ceil_z.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbolilyi <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/05 13:04:28 by dbolilyi #+# #+# */ /* Updated: 2019/03/05 13:04:29 by dbolilyi ### ########.fr */ /* */ /* ************************************************************************** */ #include "../guardians.h" int get_floor_z(t_sdl *iw, int x, int y) { if (iw->sectors[iw->d.cs].fr.n == 0) return (iw->sectors[iw->d.cs].fr.z); else return ((iw->sectors[iw->d.cs].fr.n->a * x + iw->sectors[iw->d.cs].fr.n->b * y + iw->sectors[iw->d.cs].fr.n->d) / (-iw->sectors[iw->d.cs].fr.n->c)); } int get_ceil_z(t_sdl *iw, int x, int y) { if (iw->sectors[iw->d.cs].cl.n == 0) return (iw->sectors[iw->d.cs].cl.z); else return ((iw->sectors[iw->d.cs].cl.n->a * x + iw->sectors[iw->d.cs].cl. n->b * y + iw->sectors[iw->d.cs].cl.n->d) / (-iw->sectors[iw->d.cs].cl.n->c)); } int get_floor_z_sec(t_sdl *iw, int x, int y, int sector) { if (iw->sectors[sector].fr.n == 0) return (iw->sectors[sector].fr.z); else return ((iw->sectors[sector].fr.n->a * x + iw->sectors[sector].fr.n->b * y + iw->sectors[sector].fr.n->d) / (-iw->sectors[sector].fr.n->c)); } int get_ceil_z_sec(t_sdl *iw, int x, int y, int sector) { if (iw->sectors[sector].cl.n == 0) return (iw->sectors[sector].cl.z); else return ((iw->sectors[sector].cl.n->a * x + iw->sectors[sector].cl.n->b * y + iw->sectors[sector].cl.n->d) / (-iw->sectors[sector].cl.n->c)); } void rotate_fc(t_sector_fc *fc, int xy, int pl) { if (fc->n == 0) { fc->n = (t_vector *)malloc(sizeof(t_vector)); fc->n->c = INCLINED_FC_Z; fc->n->a = 0; fc->n->b = 0; } if (xy && ((pl > 0 && fc->n->b < MAX_INCLINED_FC_XY) || (pl < 0 && fc->n->b > -MAX_INCLINED_FC_XY))) fc->n->b += pl; else if (!xy && ((pl > 0 && fc->n->a < MAX_INCLINED_FC_XY) || (pl < 0 && fc->n->a > -MAX_INCLINED_FC_XY))) fc->n->a += pl; if (fc->n->a == 0 && fc->n->b == 0) { free(fc->n); fc->n = 0; } else fc->n->d = -fc->n->a * fc->x - fc->n->b * fc->y - fc->n->c * fc->z; } <|start_filename|>3d/SRC/backpack2.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* backpack2.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbolilyi <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/05 15:18:07 by dbolilyi #+# #+# */ /* Updated: 2019/03/05 15:18:14 by dbolilyi ### ########.fr */ /* */ /* ************************************************************************** */ #include "../guardians.h" void draw_butttons(t_sdl *iw, SDL_Rect *rect) { rect->w = ((((WINDOW_W - (WINDOW_W / 4.5)) - (WINDOW_W - (WINDOW_W / 2.5))) / 3) < ((WINDOW_H - (WINDOW_H / 5)) - (WINDOW_H - (WINDOW_H / 2.5)))) ? (((WINDOW_W - (WINDOW_W / 4.5)) - (WINDOW_W - (WINDOW_W / 2.5))) / 3) : ((WINDOW_H - (WINDOW_H / 5)) - (WINDOW_H - (WINDOW_H / 2.5))); rect->h = rect->w; rect->x = (WINDOW_W - (WINDOW_W / 2.5)); rect->y = (WINDOW_H - (WINDOW_H / 2.6)); ft_scaled_blit(iw->bag.button[2], iw->sur, rect); if (iw->bag.click_x >= rect->x && iw->bag.click_x <= rect->x + rect->w && iw->bag.click_y >= rect->y && iw->bag.click_y <= rect->y + rect->h && iw->v.mouse_mode == 0) use_item(iw); rect->x = WINDOW_W - (WINDOW_W / 2.5) + rect->w * 2; ft_scaled_blit(iw->bag.button[1], iw->sur, rect); if (iw->bag.click_x >= rect->x && iw->bag.click_x <= rect->x + rect->w && iw->bag.click_y >= rect->y && iw->bag.click_y <= rect->y + rect->h && iw->v.mouse_mode == 0) drop_item(iw); } void draw_selected_item(t_packaging_texture *tex, SDL_Surface *winsur, SDL_Rect *rect, t_sdl *iw) { int i; int j; int color; i = -1; rect->w = (WINDOW_W - (WINDOW_W / 4.5)) - (WINDOW_W - (WINDOW_W / 2.5)); rect->h = (WINDOW_H - (WINDOW_H / 4.5)) - (WINDOW_H / 2.5); while (++i < (WINDOW_W - (WINDOW_W / 4.5)) - (WINDOW_W - (WINDOW_W / 2.5)) - 1) { j = -1; while (++j < (WINDOW_H - (WINDOW_H / 4.5)) - (WINDOW_H / 2.5) - 1) { color = get_pixel(tex, tex->w * i / rect->w, tex->h * j / rect->h); if (color != 0xff00e3 && color != 0x010000) set_pixel2(winsur, WINDOW_W - (WINDOW_W / 2.5) + i, rect->y + j, color); } } draw_butttons(iw, rect); } int draw_item(t_sdl *iw, SDL_Rect *rect, int i) { if (rect->x + iw->bag.indent + rect->w > WINDOW_W - (WINDOW_W / 2.5)) { rect->y += rect->h + iw->bag.indent; rect->x = (WINDOW_W / 4.5); if (rect->y + rect->h >= WINDOW_H - (WINDOW_H / 4.5)) return (0); } ft_scaled_blit(iw->t_pickup[iw->bag.item_in_bag1[i]->t_numb], iw->sur, rect); if (iw->bag.click_x >= rect->x && iw->bag.click_x <= rect->x + rect->w && iw->bag.click_y >= rect->y && iw->bag.click_y <= rect->y + rect->h && iw->v.mouse_mode == 0) { iw->bag.selected_item = iw->bag.item_in_bag1[i]; draw_frame(iw, iw->sur, rect); } rect->x += rect->w + iw->bag.indent; return (1); } void draw_items(t_sdl *iw) { int i; int w_transparency; SDL_Rect rect; w_transparency = (WINDOW_W - (WINDOW_W / 2.5)) - (WINDOW_W / 4.5); rect.w = w_transparency * 0.15; rect.h = w_transparency * 0.15; iw->bag.num_item_in_line = w_transparency / rect.w - 1; iw->bag.indent = (w_transparency - (iw->bag.num_item_in_line * rect.w)) / iw->bag.num_item_in_line; (iw->bag.indent < 1) ? iw->bag.indent++ : 0; rect.x = (WINDOW_W / 4.5); rect.y = (WINDOW_H / 4.5); i = -1; while (++i < iw->bag.count_items && rect.x <= WINDOW_W - (WINDOW_W / 2.5)) if (draw_item(iw, &rect, i) == 0) break ; rect.y = (WINDOW_H / 4.5); if (iw->bag.selected_item != 0) draw_selected_item(iw->t_pickup[iw->bag.selected_item->t_numb], iw->sur, &rect, iw); } <|start_filename|>3d/SRC/using_cards.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* using_cards.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbolilyi <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/01 17:49:22 by dbolilyi #+# #+# */ /* Updated: 2019/03/01 17:49:48 by dbolilyi ### ########.fr */ /* */ /* ************************************************************************** */ #include "../guardians.h" int get_picture_dist(t_sdl *iw, t_picture *pic) { return ((int)sqrtf(powf((pic->x0 + pic->x1) / 2 - iw->p.x, 2.0f) + powf((pic->y0 + pic->y1) / 2 - iw->p.y, 2.0f) + powf((pic->zu + pic->zd) / 2 - iw->p.z, 2.0f))); } t_sprite *get_card_from_bag(t_sdl *iw, int t_numb) { int i; i = -1; while (++i < iw->bag.count_items) if (iw->bag.item_in_bag1[i]->t_numb == t_numb) return (iw->bag.item_in_bag1[i]); return (0); } void button_f_up_cards2(t_sdl *iw, t_sprite *tmp) { int i; i = 1; if (iw->v.f_button_mode == 0 && *(iw->v.look_picture) != 0 && (*iw->v.look_picture)->t == 23 && get_picture_dist(iw, *(iw->v.look_picture)) < BUTTON_PRESS_DIST && (tmp = get_card_from_bag(iw, 7)) != 0) i = 0; else if (iw->v.f_button_mode == 0 && *(iw->v.look_picture) != 0 && (*iw->v.look_picture)->t == 24 && get_picture_dist(iw, *(iw->v.look_picture)) < BUTTON_PRESS_DIST && (tmp = get_card_from_bag(iw, 8)) != 0) i = 0; if (i) return ; (*iw->v.look_picture)->t = 21; iw->bag.selected_item = tmp; use_item_delete(iw); change_sector_animation_status(iw, *(iw->v.look_picture)); change_wall_animation_status(iw, *(iw->v.look_picture)); delete_used_sprite(iw, tmp); Mix_PlayChannel(1, iw->sounds.env[2], 0); } void button_f_up_cards(t_sdl *iw) { t_sprite *tmp; if (iw->v.f_button_mode == 0 && *(iw->v.look_picture) != 0 && (*iw->v.look_picture)->t == 22 && get_picture_dist(iw, *(iw->v.look_picture)) < BUTTON_PRESS_DIST && (tmp = get_card_from_bag(iw, 9)) != 0) { (*iw->v.look_picture)->t = 21; iw->bag.selected_item = tmp; use_item_delete(iw); change_sector_animation_status(iw, *(iw->v.look_picture)); change_wall_animation_status(iw, *(iw->v.look_picture)); delete_used_sprite(iw, tmp); Mix_PlayChannel(1, iw->sounds.env[2], 0); } else button_f_up_cards2(iw, 0); } <|start_filename|>3d/SRC4/draw_skybox_kernel.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* draw_skybox_kernel.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbolilyi <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/05 14:38:19 by dbolilyi #+# #+# */ /* Updated: 2019/03/05 14:38:20 by dbolilyi ### ########.fr */ /* */ /* ************************************************************************** */ #include "../guardians.h" void draw_skybox_kernel2(t_sdl *iw, int *cint, float *cfloat) { cint[0] = WINDOW_H; cint[1] = WINDOW_W; cint[2] = iw->t[iw->l.skybox]->w; cint[3] = iw->t[iw->l.skybox]->h; cint[4] = iw->d.screen_left; cfloat[2] = iw->p.rot; cfloat[3] = iw->v.angle; cfloat[0] = ((-iw->p.rotup + 2 * WINDOW_H) * (iw->t[iw->l.skybox]->h)) / (4 * WINDOW_H); cfloat[1] = (float)iw->t[iw->l.skybox]->h / (float)(4 * WINDOW_H); } void draw_skybox_kernel(t_sdl *iw) { int cint[5]; float cfloat[4]; size_t global_item_size; size_t local_item_size; draw_skybox_kernel2(iw, cint, cfloat); iw->k.ret = clEnqueueWriteBuffer(iw->k.command_queue, iw->k.m_cint, CL_TRUE, 0, 5 * sizeof(int), cint, 0, NULL, NULL); iw->k.ret = clEnqueueWriteBuffer(iw->k.command_queue, iw->k.m_cfloat, CL_TRUE, 0, 4 * sizeof(float), cfloat, 0, NULL, NULL); iw->k.ret = clSetKernelArg(iw->k.kernel4, 3, sizeof(cl_mem), (void *)&iw->k.m_t[iw->l.skybox]); global_item_size = iw->d.screen_right - iw->d.screen_left; local_item_size = 1; iw->k.ret = clEnqueueNDRangeKernel(iw->k.command_queue, iw->k.kernel4, 1, NULL, &global_item_size, &local_item_size, 0, NULL, NULL); iw->k.ret = clFlush(iw->k.command_queue); iw->k.ret = clFinish(iw->k.command_queue); } <|start_filename|>editor/load_connect.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* connect.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: kkostrub <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/05 17:11:12 by kkostrub #+# #+# */ /* Updated: 2019/03/05 17:11:21 by kkostrub ### ########.fr */ /* */ /* ************************************************************************** */ #include "doom_nuken.h" int connect_sector(t_doom *den, t_wals *wall) { t_sector_list *tmp; tmp = den->sectors; while (tmp) { if (tmp->id == wall->next_sector_numb) { wall->next_sector = tmp; return (1); } tmp = tmp->next; } return (0); } int connect_wall(t_doom *den, t_wals *wall) { t_wals *tmp; tmp = den->tmp; while (tmp) { if (tmp->id == wall->nextsector_wall_numb) { wall->nextsector_wall = tmp; return (1); } tmp = tmp->next; } return (0); } int connect_map_sectors(t_doom *den) { t_wals *tmp; tmp = den->tmp; while (tmp) { if (tmp->next_sector_numb != -1) { if (!connect_sector(den, tmp) || !connect_wall(den, tmp)) return (0); } tmp = tmp->next; } return (1); } <|start_filename|>editor/map_redactor.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* map_redactor.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ddehtyar <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/01/29 15:26:50 by ddehtyar #+# #+# */ /* Updated: 2019/01/29 15:26:52 by ddehtyar ### ########.fr */ /* */ /* ************************************************************************** */ #include "doom_nuken.h" void map_redactor_mane(t_doom *den, t_col *vec) { den->skape = 0; den->retskape = den->skape; den->startx = 0; den->starty = 0; den->blouk = 0; den->change = 0; den->button_change = 0; den->find_tmp_one = 0; den->select = 0; den->blockwall = 0; den->incede = 0; den->angle = 0; den->noblouk = 0; den->sort = 0; den->find_tmp = 0; den->find_tmp_one = 0; den->find_tmp_two = 0; den->find_sprite = 0; clean_vec(vec); clean_find_vec(den); info_display(den); } void map_redactor_mane2(t_doom *den) { den->sec = 0; den->secbak = -1; den->walls = -1; den->sprites = 0; den->player.x = -10000; den->player.y = -10000; den->player.introt = 1; den->finish = -1; den->sprite = 0; den->tmp = 0; den->sectors = 0; den->secbaktmp = 0; } void clean_find_vec(t_doom *den) { den->change = 0; den->rec.x1 = 0; den->rec.y1 = 0; den->rec.x2 = 0; den->rec.y2 = 0; den->rec.sect = 0; den->rec_two.x1 = 0; den->rec_two.y1 = 0; den->rec_two.x2 = 0; den->rec_two.y2 = 0; den->rec_two.sect = 0; } void map_network(t_doom *den) { int y; int x; y = 0; while (y < HEIGHT) { x = 0; while (x < (WIDTH - 220)) { pixel_width(den, x, y, 0xB3B3B3); x += (START + den->skape); } y += (START + den->skape); } den->border = x - (START + den->skape); } void findstart(t_doom *den) { den->startx = den->startx / (den->retskape + START) * (den->skape + START); den->starty = den->starty / (den->retskape + START) * (den->skape + START); den->retskape = den->skape; } <|start_filename|>3d/SRC/mouse_left_up3.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* mouse_left_up3.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbolilyi <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/05 15:28:29 by dbolilyi #+# #+# */ /* Updated: 2019/03/05 15:28:30 by dbolilyi ### ########.fr */ /* */ /* ************************************************************************** */ #include "../guardians.h" void mouse_buttonleft_up1_8(int x, t_sdl *iw) { if (iw->v.submenu_mode == 5 && x > WINDOW_W - 450) { if (x < WINDOW_W - 380) { iw->v.wall_anim->moving_type = 0; iw->v.submenu_mode = 6; draw_submenu(iw); } else if (x < WINDOW_W - 305) { iw->v.wall_anim->moving_type = 1; iw->v.submenu_mode = 6; draw_submenu(iw); } else if (x < WINDOW_W - 225) { iw->v.wall_anim->moving_type = 2; iw->v.submenu_mode = 6; draw_submenu(iw); } else if (x < WINDOW_W - 165) exit_editing_wall_animation(iw); } else mouse_buttonleft_up1_9(x, iw); } void mouse_buttonleft_up1_7(int x, t_sdl *iw) { if (iw->v.submenu_mode == 4 && x > WINDOW_W - 450) { if (x < WINDOW_W - 375) { iw->v.f_button_mode = 2; iw->v.submenu_mode = 0; draw_submenu(iw); } else if (x < WINDOW_W - 300) { iw->v.f_button_mode = 3; iw->v.submenu_mode = 0; draw_submenu(iw); } else if (x < WINDOW_W - 240) { iw->v.submenu_mode = 0; iw->v.f_button_pointer = 0; draw_submenu(iw); } } else mouse_buttonleft_up1_8(x, iw); } void mouse_buttonleft_up1_6_1(int x, t_sdl *iw) { if (x < WINDOW_W - 245) { do_sector_animation_step(iw, iw->v.sector_anim, -iw->v.sector_anim->dy); iw->v.sector_anim->next = iw->sector_animations; iw->v.submenu_mode = 0; draw_submenu(iw); iw->v.sector_anim->prev_clock = clock(); iw->sector_animations = iw->v.sector_anim; iw->v.sector_anim = 0; } else if (x < WINDOW_W - 200) exit_editing_sector_animation(iw); } void mouse_buttonleft_up1_6(int x, t_sdl *iw) { if (iw->v.submenu_mode == 3 && x > WINDOW_W - 340) { if (x < WINDOW_W - 320) { iw->v.sector_anim->speed += ((iw->v.sector_anim->speed < 9) ? 1 : 0); draw_submenu(iw); } else if (x < WINDOW_W - 295) { iw->v.sector_anim->speed -= ((iw->v.sector_anim->speed > 1) ? 1 : 0); draw_submenu(iw); } else mouse_buttonleft_up1_6_1(x, iw); } else mouse_buttonleft_up1_7(x, iw); } void mouse_buttonleft_up1_5(int x, t_sdl *iw) { if (iw->v.submenu_mode == 2 && x > WINDOW_W - 450) { if (x < WINDOW_W - 390) { do_sector_animation_step(iw, iw->v.sector_anim, 100); iw->v.sector_anim->dy += 100; } else if (x < WINDOW_W - 330) { do_sector_animation_step(iw, iw->v.sector_anim, -100); iw->v.sector_anim->dy -= 100; } else if (x < WINDOW_W - 280) { iw->v.submenu_mode = 3; draw_submenu(iw); } else if (x < WINDOW_W - 220) exit_editing_sector_animation(iw); } else mouse_buttonleft_up1_6(x, iw); } <|start_filename|>3d/SRC/mouse_left_up.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* mouse_left_up.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbolilyi <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/01 14:15:41 by dbolilyi #+# #+# */ /* Updated: 2019/03/01 14:21:25 by dbolilyi ### ########.fr */ /* */ /* ************************************************************************** */ #include "../guardians.h" void mouse_buttonleft_up2(int x, t_sdl *iw, int i) { if (iw->v.sprites_select_mode == 0) { i = x / 100 + iw->v.scroll_decor_sprites; if (i < DECOR_TEXTURES_COUNT) { iw->v.selected_sprite_type = 0; iw->v.selected_sprite = i; } } else if (iw->v.sprites_select_mode == 1) { i = x / 100 + iw->v.scroll_pickup_sprites; if (i < PICK_UP_TEXTURES_COUNT) { iw->v.selected_sprite_type = 1; iw->v.selected_sprite = i; } } else if (iw->v.sprites_select_mode == 2) { if (!((i = x / 100) < COUNT_ENEMIES)) return ; iw->v.selected_sprite_type = 2; iw->v.selected_sprite = i; } } void mouse_buttonleft_up3_1(t_sdl *iw) { iw->v.look_sprite->type = 2; iw->v.look_sprite->e.enemy_numb = iw->v.selected_sprite; iw->v.look_sprite->e.status = 0; if (iw->v.selected_sprite == 0) { iw->v.look_sprite->e.health = ENEMY_HEALTH0; iw->v.look_sprite->t_numb = 0; iw->v.look_sprite->t = iw->t_enemies[0]; iw->v.look_sprite->t_kernel = &iw->k.m_t_enemies[0]; } else if (iw->v.selected_sprite == 1) { iw->v.look_sprite->e.health = ENEMY_HEALTH1; iw->v.look_sprite->t_numb = 8; iw->v.look_sprite->t = iw->t_enemies[8]; iw->v.look_sprite->t_kernel = &iw->k.m_t_enemies[8]; } else if (iw->v.selected_sprite == 2) { iw->v.look_sprite->e.health = ENEMY_HEALTH2; iw->v.look_sprite->t_numb = 20; iw->v.look_sprite->t = iw->t_enemies[20]; iw->v.look_sprite->t_kernel = &iw->k.m_t_enemies[20]; } } void mouse_buttonleft_up3(t_sdl *iw) { if (iw->v.selected_sprite_type == 0) { iw->v.look_sprite->type = 0; iw->v.look_sprite->t_numb = iw->v.selected_sprite; iw->v.look_sprite->t = iw->t_decor[iw->v.selected_sprite]; iw->v.look_sprite->t_kernel = &iw->k.m_t_decor[iw->v.selected_sprite]; if (iw->v.selected_sprite == 1) add_checkpoint(iw, iw->v.look_sprite); } else if (iw->v.selected_sprite_type == 1) { iw->v.look_sprite->type = 1; iw->v.look_sprite->t_numb = iw->v.selected_sprite; iw->v.look_sprite->t = iw->t_pickup[iw->v.selected_sprite]; iw->v.look_sprite->t_kernel = &iw->k.m_t_pickup[iw->v.selected_sprite]; } else if (iw->v.selected_sprite_type == 2) mouse_buttonleft_up3_1(iw); } void mouse_buttonleft_up4(t_sdl *iw) { if (iw->v.mouse_mode == 1 && *(iw->v.look_picture) != 0 && *(iw->v.look_wall) != 0 && !iw->v.game_mode) { (*(iw->v.look_picture))->t = iw->v.tex_to_fill; calculate_picture(iw, *(iw->v.look_wall), *(iw->v.look_picture)); } else if (iw->v.mouse_mode == 1 && *(iw->v.look_wall) != 0 && !iw->v.game_mode) { if (iw->v.look_portal == 0 || iw->v.look_portal->glass < 0) (*(iw->v.look_wall))->t = iw->v.tex_to_fill; else iw->v.look_portal->glass = -1; } } void mouse_buttonleft_up(int x, int y, t_sdl *iw) { int i; iw->v.left_mouse_pressed = 0; if (y > WINDOW_H && y < WINDOW_H + 100 && iw->v.mouse_mode == 0) { i = x / 100 + iw->v.scroll_first_tex; if (i < TEXTURES_COUNT) iw->v.tex_to_fill = i; } else if (y > WINDOW_H + 100 && y < WINDOW_H + 200 && iw->v.mouse_mode == 0 && *(iw->v.look_wall) != 0) mouse_buttonleft_up1(x, y, iw); else if (y > WINDOW_H + 200 && y < WINDOW_H + 300 && iw->v.mouse_mode == 0) mouse_buttonleft_up2(x, iw, 0); else if (iw->v.sprite_editing && iw->v.mouse_mode == 1 && iw->v.look_sprite != 0) mouse_buttonleft_up3(iw); else mouse_buttonleft_up4(iw); } <|start_filename|>editor/game_mode.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* game_mode.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ddehtyar <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/05 15:29:13 by ddehtyar #+# #+# */ /* Updated: 2019/03/05 15:29:14 by ddehtyar ### ########.fr */ /* */ /* ************************************************************************** */ #include "doom_nuken.h" int get_3d_def_game(t_doom *den) { den->iw.v.game_mode = 1; den->iw.v.kernel = 1; den->iw.v.look_wall = (t_wall **)malloc(sizeof(t_wall *)); den->iw.v.look_sector = (t_sector **)malloc(sizeof(t_sector *)); den->iw.v.look_picture = (t_picture **)malloc(sizeof(t_picture *)); den->iw.sprite = (t_sprite **)malloc(sizeof(t_sprite *)); den->iw.vw_save = (t_save_wall **)malloc(sizeof(t_save_wall *)); den->iw.arial_font = TTF_OpenFontRW(SDL_RWFromConstMem(den->iw.font_pack, den->iw.font_pack_size), 0, 24); if (den->iw.arial_font == 0) { write(1, "Error loading file\n", 20); return (0); } den->font = den->iw.arial_font; load_kernel(&den->iw.k, &den->iw); get_kernel_mem(&den->iw); get_kernels(&den->iw); get_guns(&den->iw); get_sounds_game(&den->iw); return (1); } void main3d_game_help(t_doom *den) { circle(&den->iw.hud, FOOTX, FOOTY); get_map(&den->iw, den); set_sprites_z(&den->iw); get_sectors_ways(&den->iw); create_map(&den->iw); Mix_PlayMusic(den->iw.sounds.music[4], -1); image_loop(&den->iw, den->iw.t[den->iw.l.story]); menu_loop(&den->iw); Mix_HaltMusic(); draw(&den->iw); } void main3d_game(t_doom *den) { give_date(den, &den->iw); get_def_new(&den->iw); den->iw.win = SDL_CreateWindow("Guardians of the Galaxy", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, WINDOW_W, WINDOW_H, SDL_WINDOW_SHOWN); SDL_SetRelativeMouseMode(den->iw.v.mouse_mode); den->iw.sur = SDL_GetWindowSurface(den->iw.win); main3d_game_help(den); SDL_UpdateWindowSurface(den->iw.win); main_loop(&den->iw); SDL_SetRelativeMouseMode(0); SDL_FreeSurface(den->iw.sur); SDL_DestroyWindow(den->iw.win); if (den->iw.v.sector_anim != 0) free(den->iw.v.sector_anim); if (den->iw.v.wall_anim != 0) free(den->iw.v.wall_anim); undo_animations(&den->iw); unget_map(&den->iw, den, den->tmp); free(den->iw.walls); free(den->iw.sectors); free_sector_ways(&den->iw); } int main_game(t_doom *den) { SDL_Init(SDL_INIT_EVERYTHING); TTF_Init(); Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 2048); if (!get_3d_def_game(den)) return (0); main3d_game(den); return (0); } <|start_filename|>3d/SRC/player_moving2.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* player_moving2.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbolilyi <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/05 15:25:16 by dbolilyi #+# #+# */ /* Updated: 2019/03/05 15:25:19 by dbolilyi ### ########.fr */ /* */ /* ************************************************************************** */ #include "../guardians.h" int is_wall_portal2(t_sdl *iw, int dx, int dy, int wall) { t_line2d mv; int side1; int side2; mv.a = (float)dy; mv.b = (float)(-dx); mv.c = -mv.a * (float)iw->p.x - mv.b * (float)iw->p.y; if (mv.a * (float)iw->walls[wall].x + mv.b * (float)iw->walls[wall].y + mv.c > 0) side1 = 1; else side1 = -1; if (mv.a * (float)iw->walls[wall].next->x + mv.b * (float)iw->walls[wall].next->y + mv.c > 0) side2 = 1; else side2 = -1; if (side1 * side2 < 0) return (1); return (0); } t_wall *is_wall_portal(t_sdl *iw, int dx, int dy) { int wall; int side1; int side2; if (iw->d.cs < 0) return (0); wall = iw->sectors[iw->d.cs].sw - 1; while (++wall < iw->sectors[iw->d.cs].sw + iw->sectors[iw->d.cs].nw) { if (iw->walls[wall].nextsector == -1) continue; if (iw->walls[wall].l.a * (float)iw->p.x + iw->walls[wall].l.b * (float)iw->p.y + iw->walls[wall].l.c > 0) side1 = 1; else side1 = -1; side2 = ((iw->walls[wall].l.a * (float)(iw->p.x + dx) + iw->walls[wall].l.b * (float)(iw->p.y + dy) + iw->walls[wall].l.c > 0) ? 1 : -1); if (side1 * side2 < 0 && is_wall_portal2(iw, dx, dy, wall)) return (&iw->walls[wall]); } return (0); } void move_collisions2(t_sdl *iw, int dx, int dy, int tmp) { int dd; int i; if (in_sec_xy(iw, iw->d.cs, iw->p.x, iw->p.y + dy * tmp) && in_sec_xy(iw, iw->d.cs, iw->p.x, iw->p.y + dy)) { dd = dx / 20 * 2; dx = 0; i = -1; while (++i < 10 && in_sec_xy(iw, iw->d.cs, iw->p.x + dx * tmp, iw->p.y + dy * tmp) && in_sec_xy(iw, iw->d.cs, iw->p.x + dx, iw->p.y + dy)) dx += dd; iw->p.x += dx - dd; iw->p.y += dy; } } void move_collisions(t_sdl *iw, int dx, int dy, int tmp) { int dd; int i; if (in_sec_xy(iw, iw->d.cs, iw->p.x + dx * tmp, iw->p.y) && in_sec_xy(iw, iw->d.cs, iw->p.x + dx, iw->p.y)) { dd = dy / 20 * 2; dy = 0; i = -1; while (++i < 10 && in_sec_xy(iw, iw->d.cs, iw->p.x + dx * tmp, iw->p.y + dy * tmp) && in_sec_xy(iw, iw->d.cs, iw->p.x + dx, iw->p.y + dy)) dy += dd; iw->p.x += dx; iw->p.y += dy - dd; } else move_collisions2(iw, dx, dy, tmp); } int check_moving_in_portal_z(t_sdl *iw, int dx, int dy, t_wall *sw) { int nx; int ny; int savecs; int nszu; int nszd; nx = iw->p.x + dx + iw->walls[sw->nextsector_wall].x - sw->next->x; ny = iw->p.y + dy + iw->walls[sw->nextsector_wall].y - sw->next->y; savecs = iw->d.cs; iw->d.cs = sw->nextsector; nszu = get_ceil_z(iw, nx, ny); nszd = get_floor_z(iw, nx, ny); iw->d.cs = savecs; if (nszu - nszd >= PLAYER_HEIGHT + PLAYER_HEAD_SIZE && (nszd < iw->p.z || nszd - iw->p.z + PLAYER_HEIGHT < MAX_CLIMB_HEIGHT) && in_sec_xy(iw, sw->nextsector, nx, ny)) return (1); return (0); } <|start_filename|>3d/SRC3/bresenham_save.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* bresenham_save.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbolilyi <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/05 13:01:47 by dbolilyi #+# #+# */ /* Updated: 2019/03/05 13:01:48 by dbolilyi ### ########.fr */ /* */ /* ************************************************************************** */ #include "../guardians.h" void put_wall_pixel(t_brez *b, int x, int y) { if (x != b->prev_x) { *(b->wall_y++) = y; b->prev_x = x; } } void print_brez(t_brez *b, int d, int d1, int d2) { int i; if (b->k <= 0) b->dx = b->dy; i = 0; while (++i <= b->dx) { if (d > 0) { d += d2; b->y += b->sy; } else d += d1; if (b->k > 0) put_wall_pixel(b, b->x, b->y); else put_wall_pixel(b, b->y, b->x); b->x += b->sx; } } void brez_line(int *wall_y, t_draw_line line) { t_brez b; *(wall_y++) = line.y0; b.prev_x = line.x0; b.wall_y = wall_y; b.sx = (line.x1 >= line.x0) ? (1) : (-1); b.sy = (line.y1 >= line.y0) ? (1) : (-1); b.dx = (line.x1 > line.x0) ? (line.x1 - line.x0) : (line.x0 - line.x1); b.dy = (line.y1 > line.y0) ? (line.y1 - line.y0) : (line.y0 - line.y1); if (abs(line.y1 - line.y0) < abs(line.x1 - line.x0)) { b.x = line.x0 + b.sx; b.y = line.y0; b.k = 1; print_brez(&b, (b.dy * 2) - b.dx, b.dy * 2, (b.dy - b.dx) * 2); } else { b.x = line.y0 + b.sy; b.y = line.x0; b.sy = (line.x1 >= line.x0) ? (1) : (-1); b.sx = (line.y1 >= line.y0) ? (1) : (-1); b.k = 0; print_brez(&b, (b.dx * 2) - b.dy, b.dx * 2, (b.dx - b.dy) * 2); } } <|start_filename|>3d/SRC3/draw_floor_ceil.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* draw_floor_ceil.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbolilyi <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/05 13:02:39 by dbolilyi #+# #+# */ /* Updated: 2019/03/05 13:02:40 by dbolilyi ### ########.fr */ /* */ /* ************************************************************************** */ #include "../guardians.h" void draw_floor_ceil_tex3(t_sdl *iw, t_save_wall *left, t_draw_wall_floor_ceil_tex *d) { d->left_len = sinf(d->ang) * d->lenpl / sinf(d->sing - d->ang); d->r.x = (float)left->p.x + d->rv.x * d->left_len; d->r.y = (float)left->p.y + d->rv.y * d->left_len; d->frcoef = get_ceil_z(iw, d->r.x, d->r.y) - get_floor_z(iw, d->r.x, d->r.y); d->wall_dist = (float)WINDOW_H / (fabsf(iw->d.screen.a * d->r.x + iw->d.screen.b * d->r.y + iw->d.screen.c) / iw->d.screen_len) * d->frcoef; d->r.x /= 1000.0f; d->r.y /= 1000.0f; } void draw_floor_ceil_tex4(t_sdl *iw, t_save_wall *left, t_draw_wall_floor_ceil_tex *d) { if (iw->d.wallBot[d->j] < iw->d.top[left->x + d->j]) d->i = iw->d.top[left->x + d->j] - 1; else d->i = iw->d.wallBot[d->j] - 1; d->k = (float)(iw->d.wallBot[d->j] - iw->d.wallTop[d->j]) + d->frpl * (float)(d->i + 1 - iw->d.wallBot[d->j]); while (++d->i < iw->d.bottom[left->x + d->j]) { d->weight = d->wall_dist / d->k; d->k += d->frpl; d->floor.x = d->weight * d->r.x + (1.0f - d->weight) * d->px; d->floor.y = d->weight * d->r.y + (1.0f - d->weight) * d->py; set_pixel2(iw->sur, left->x + d->j, d->i, get_light_color(get_pixel(iw->t[iw->sectors[iw->d.cs].fr.t], ((d->floor.x < 0) ? (((int)(d->floor.x * (float)iw->t[iw->sectors [iw->d.cs].fr.t]->w) % iw->t[iw->sectors[iw->d.cs].fr.t]->w) + iw->t[iw->sectors[iw->d.cs].fr.t]->w - 1) : ((int)(d->floor.x * (float)iw->t[iw->sectors[iw->d.cs].fr.t]->w) % iw->t[iw-> sectors[iw->d.cs].fr.t]->w)), ((d->floor.y < 0) ? (((int)(d->floor.y * (float)iw->t[iw->sectors[iw->d.cs].fr.t]->h) % iw->t[iw-> sectors[iw->d.cs].fr.t]->h) + iw->t[iw->sectors[iw->d.cs].fr.t]->h - 1) : ((int)(d->floor.y * (float)iw->t[iw->sectors[iw->d.cs].fr.t]->h) % iw->t[iw->sectors[iw->d.cs].fr.t]->h))), iw->sectors[iw->d.cs].light)); } } void draw_floor_ceil_tex5_1(t_sdl *iw, t_save_wall *left, t_draw_wall_floor_ceil_tex *d) { if (iw->d.wallTop[d->j] < iw->d.bottom[left->x + d->j]) d->i = iw->d.wallTop[d->j] + 1; else d->i = iw->d.bottom[left->x + d->j] + 1; d->k = (float)(iw->d.wallBot[d->j] - iw->d.wallTop[d->j]) + d->clpl * (float)(iw->d.wallTop[d->j] - d->i + 1); while (--d->i >= iw->d.top[left->x + d->j]) { d->weight = d->wall_dist / d->k; d->k += d->clpl; d->floor.x = d->weight * d->r.x + (1.0f - d->weight) * d->px; d->floor.y = d->weight * d->r.y + (1.0f - d->weight) * d->py; set_pixel2(iw->sur, left->x + d->j, d->i, get_light_color(get_pixel(iw->t[iw->sectors[iw->d.cs].cl.t], ((d->floor.x < 0) ? (((int)(d->floor.x * (float) iw->t[iw->sectors[iw->d.cs].cl.t]->w) % iw->t[iw->sectors [iw->d.cs].cl.t]->w) + iw->t[iw->sectors[iw->d.cs].cl.t]->w - 1) : ((int)(d->floor.x * (float)iw->t[iw->sectors[iw->d.cs].cl.t]->w) % iw->t[iw->sectors[iw->d.cs].cl.t]->w)), ((d->floor.y < 0) ? (((int) (d->floor.y * (float)iw->t[iw->sectors[iw->d.cs].cl.t]->h) % iw->t[iw-> sectors[iw->d.cs].cl.t]->h) + iw->t[iw->sectors[iw->d.cs].cl.t]->h - 1) : ((int)(d->floor.y * (float)iw->t[iw->sectors[iw->d.cs].cl.t]->h) % iw->t[iw->sectors[iw->d.cs].cl.t]->h))), iw->sectors[iw->d.cs].light)); } } void draw_floor_ceil_tex5(t_sdl *iw, t_save_wall *left, t_draw_wall_floor_ceil_tex *d) { if (!(iw->d.wallTop[d->j] > iw->d.top[left->x + d->j])) return ; if (iw->sectors[iw->d.cs].cl.t >= 0) { draw_floor_ceil_tex5_1(iw, left, d); iw->d.top[left->x + d->j] = iw->d.wallTop[d->j]; } else { d->sky_y = -iw->p.rotup + 2 * WINDOW_H; d->sky_y = (d->sky_y * (iw->t[iw->l.skybox]->h)) / (4 * WINDOW_H); d->i = iw->d.top[left->x + d->j] - 1; d->sky_y += d->dy * iw->d.top[left->x + d->j]; if (d->sky_x > iw->t[iw->l.skybox]->w) d->sky_x = d->sky_x - iw->t[iw->l.skybox]->w; while (++d->i < iw->d.wallTop[d->j] && d->i < iw->d.bottom[left->x + d->j]) { set_pixel2(iw->sur, d->j + left->x, d->i, get_pixel(iw->t[iw->l.skybox], (int)d->sky_x, (int)d->sky_y)); d->sky_y += d->dy; } } } void draw_floor_ceil_tex(t_sdl *iw, t_save_wall *left, t_save_wall *right, int len) { t_draw_wall_floor_ceil_tex d; draw_floor_ceil_tex1(iw, left, right, &d); draw_floor_ceil_tex2(iw, left, &d); d.j = -1; while (++d.j < len) { if (iw->d.top[left->x + d.j] >= iw->d.bottom[left->x + d.j]) { d.ang += d.dang; if (iw->sectors[iw->d.cs].cl.t < 0) d.sky_x += d.dx; continue; } draw_floor_ceil_tex3(iw, left, &d); if (iw->d.wallBot[d.j] < iw->d.bottom[left->x + d.j]) { draw_floor_ceil_tex4(iw, left, &d); iw->d.bottom[left->x + d.j] = iw->d.wallBot[d.j]; } draw_floor_ceil_tex5(iw, left, &d); if (iw->sectors[iw->d.cs].cl.t < 0) d.sky_x += d.dx; d.ang += d.dang; } } <|start_filename|>editor/sector_in_sector.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* sector_in_sector.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ddehtyar <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/02/05 17:37:10 by ddehtyar #+# #+# */ /* Updated: 2019/02/05 17:37:11 by ddehtyar ### ########.fr */ /* */ /* ************************************************************************** */ #include "doom_nuken.h" void sector_in_sector_two(t_doom *den, t_wals *cmp, t_wals *lmp) { while (den->tmp->next) { if (den->tmp->sec == den->xy.bool_cor && den->tmp->next->sec != den->xy.bool_cor) { den->tmp->next = lmp->next; while (den->tmp->next) den->tmp = den->tmp->next; den->tmp->next = cmp; while (den->tmp) { if (den->tmp->next == lmp->next) den->tmp->next = NULL; den->tmp = den->tmp->next; } return ; } den->tmp = den->tmp->next; } } void sector_in_sector(t_doom *den) { t_wals *rmp; t_wals *cmp; t_wals *lmp; cmp = NULL; rmp = den->tmp; if (den->sec > 2) { while (den->tmp->next) { if (den->tmp->next->sec == den->xy.bool_cor && den->tmp->next->next->sec != den->xy.bool_cor) cmp = den->tmp->next->next; if (den->tmp->next->sec == den->sec - 1) { lmp = den->tmp; den->tmp = rmp; sector_in_sector_two(den, cmp, lmp); break ; } den->tmp = den->tmp->next; } } den->tmp = rmp; } void sort_walls_inside_help(t_doom *den, int *walls, int i, t_wals *rmp) { while (rmp && rmp->inside == 1) { walls[i] = rmp->x; walls[i + 1] = rmp->y; walls[i + 2] = rmp->x1; walls[i + 3] = rmp->y1; i += 4; rmp = rmp->next; } --i; while (den->tmp && den->tmp->inside == 1) { den->tmp->y = walls[i]; den->tmp->x = walls[i - 1]; den->tmp->y1 = walls[i - 2]; den->tmp->x1 = walls[i - 3]; i -= 4; den->tmp = den->tmp->next; } free(walls); } void sort_walls_inside(t_doom *den) { t_wals *rmp; int i; int *walls; i = 0; rmp = den->tmp; while (rmp && rmp->inside == 1) { i++; rmp = rmp->next; } rmp = den->tmp; walls = (int *)malloc(sizeof(int) * (i * 4)); i = 0; sort_walls_inside_help(den, walls, i, rmp); } int inside_sect(t_doom *den, t_wals **tmp, int sec) { t_insect in; in.wallcrossed = 0; while (*tmp) { den->xy.inside = (*tmp)->inside; if ((*tmp)->sec != sec) break ; in.y1 = (*tmp)->y - den->xy.y; in.y2 = (*tmp)->y1 - den->xy.y; if ((in.y1 ^ in.y2) < 0) { in.x1 = (*tmp)->x - den->xy.x; in.x2 = (*tmp)->x1 - den->xy.x; if ((in.x1 ^ in.x2) >= 0) in.wallcrossed ^= in.x1; else in.wallcrossed ^= (in.x1 * in.y2 - in.x2 * in.y1) ^ in.y2; } if ((*tmp)->next == NULL || ((*tmp)->next->sec != sec)) break ; if ((*tmp)->next != NULL) (*tmp) = (*tmp)->next; } return (in.wallcrossed >> 31); } <|start_filename|>editor/write_list.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* write_list.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ddehtyar <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/02/05 16:16:05 by ddehtyar #+# #+# */ /* Updated: 2019/02/05 16:16:05 by ddehtyar ### ########.fr */ /* */ /* ************************************************************************** */ #include "doom_nuken.h" void write_map_help(t_doom *den, t_col *vec) { vec->x1 = (den->tmp->x * XSKAPE); vec->y1 = (den->tmp->y * YSKAPE); vec->x2 = (den->tmp->x1 * XSKAPE); vec->y2 = (den->tmp->y1 * YSKAPE); if (vec->x1 < den->border && vec->x1 >= 0) pixel_bigwidth(den, vec->x1, vec->y1, 0x00FF00); if (vec->x2 < den->border && vec->x2 >= 0) pixel_bigwidth(den, vec->x2, vec->y2, 0x00FF00); if (den->tmp->next_sector && den->tmp->nextsector_wall) den->color = 0xFF0000; if (den->tmp->sec == den->finish) den->color = 0xFFFF00; ft_line(den, vec); if (den->tmp->blouk == 1) { vec->x1 = -1000000; vec->y1 = -1000000; vec->x2 = -1000000; vec->y2 = -1000000; } den->color = 0xFFFFFF; } void write_map(t_doom *den, t_col *vec) { t_wals *rmp; rmp = den->tmp; if (den->tmp) { while (den->tmp) { if (den->retskape != den->skape) findstart(den); write_map_help(den, vec); den->tmp = den->tmp->next; } den->button = 0; if (den->player.x != -10000 && den->player.y != -10000) rotate_image(den); if (den->sprite) see_sprite(den); } den->tmp = rmp; } void write_list_help(t_doom *den, t_wals *tmp, t_wals *rmp, t_wals *nmp) { tmp->next->next->x = tmp->next->x; tmp->next->next->y = tmp->next->y; tmp->next->next->sec = tmp->next->sec; tmp->next = tmp->next->next; delete_pointer(den, rmp); if (rmp->next_sector != 0) { nmp = rmp->nextsector_wall; nmp->next_sector = 0; nmp->nextsector_wall = 0; rmp->next_sector = 0; rmp->nextsector_wall = 0; } } void write_list(t_doom *den, t_wals *tmp) { t_wals *rmp; t_wals *nmp; int nw; nmp = NULL; SDL_FillRect(den->bmp, NULL, 0x000000); rmp = tmp; if (den->retskape != den->skape) findstart(den); if (!tmp) return ; nw = 0; if (tmp != den->find_tmp) while (tmp->next && tmp->next != den->find_tmp) { nw++; tmp = tmp->next; } rmp = tmp->next; if (!(tmp->next->next && tmp->next->next->sec == tmp->next->sec)) return ; check_deleting_wall_animations(den, nw); write_list_help(den, tmp, rmp, nmp); free(rmp); den->walls -= 1; } void move_sector(t_doom *den, int y, int x) { t_wals *rmp; rmp = den->tmp; while (den->tmp) { if (den->tmp->sec == den->find_tmp->sec) { den->tmp->x += x; den->tmp->x1 += x; den->tmp->y += y; den->tmp->y1 += y; } else if (den->tmp->sec && den->tmp->sec > den->find_tmp->sec) break ; den->tmp = den->tmp->next; } den->tmp = rmp; } <|start_filename|>3d/SRC2/main_loops.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* main_loops.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbolilyi <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/05 12:07:33 by dbolilyi #+# #+# */ /* Updated: 2019/03/05 12:07:34 by dbolilyi ### ########.fr */ /* */ /* ************************************************************************** */ #include "../guardians.h" void menu_loop(t_sdl *iw) { SDL_Event e; int quit; game_start_menu(iw); quit = 0; while (!quit) while (SDL_PollEvent(&e) != 0) if (e.type == SDL_KEYDOWN) { if (e.key.keysym.scancode == 81) { iw->menu.count += ((iw->menu.count < 3) ? 1 : -2); game_start_menu(iw); } else if (e.key.keysym.scancode == 82) { iw->menu.count -= ((iw->menu.count > 1) ? 1 : -2); game_start_menu(iw); } else if (e.key.keysym.scancode == 40) quit = 1; else if (e.key.keysym.scancode == 41) exit_x(iw); } } void image_loop(t_sdl *iw, t_packaging_texture *tex) { SDL_Event e; int quit; SDL_Rect rect; rect.w = WINDOW_W; rect.h = WINDOW_H; rect.x = 0; rect.y = 0; ft_scaled_blit2(tex, iw->sur, &rect); SDL_UpdateWindowSurface(iw->win); quit = 0; while (!quit) while (SDL_PollEvent(&e) != 0) if (e.type == SDL_KEYDOWN) { if (e.key.keysym.scancode == 41) exit_x(iw); else if (e.key.keysym.scancode == 40) quit = 1; } } void main_loop2(t_sdl *iw, SDL_Event *e) { if (e->type == SDL_MOUSEMOTION) { mouse_move(e->motion.xrel, e->motion.yrel, iw); iw->v.mouse_x = e->motion.x; iw->v.mouse_y = e->motion.y; } else if (e->type == SDL_MOUSEBUTTONUP && e->button.button == SDL_BUTTON_LEFT) { mouse_buttonleft_up(e->button.x, e->button.y, iw); iw->bag.click_x = e->button.x; iw->bag.click_y = e->button.y; } else if (e->type == SDL_MOUSEBUTTONDOWN && e->button.button == SDL_BUTTON_LEFT && iw->v.game_mode) iw->v.left_mouse_pressed = 1; else if (e->type == SDL_MOUSEBUTTONUP && e->button.button == SDL_BUTTON_RIGHT) mouse_buttonright_up(iw); else if (e->type == SDL_MOUSEWHEEL && e->wheel.y != 0) mouse_wheel(e, iw); } void main_loop(t_sdl *iw) { SDL_Event e; iw->quit = 0; while (!iw->quit) { while (SDL_PollEvent(&e) != 0) if (e.type == SDL_QUIT) iw->quit = 1; else if (e.type == SDL_KEYDOWN) { key_down_repeat(e.key.keysym.scancode, iw); if (e.key.repeat == 0) key_down(e.key.keysym.scancode, iw); } else if (e.type == SDL_KEYUP) key_up(e.key.keysym.scancode, iw); else main_loop2(iw, &e); loop(iw); } } void game_start_menu1(t_sdl *iw, SDL_Rect *player, SDL_Rect *zast, SDL_Rect *diff) { player->x = 0; player->y = 0; player->w = WINDOW_W; player->h = WINDOW_H; zast->x = WINDOW_W / 10; zast->y = WINDOW_H / 8; zast->w = WINDOW_W / 4; zast->h = WINDOW_H / 8; diff->w = WINDOW_W / 6; diff->h = WINDOW_H / 10; diff->x = zast->x + (zast->w - diff->w) / 2; diff->y = zast->y + (zast->h - diff->h) / 2; ft_scaled_blit(iw->menu.icons[0], iw->sur, player); } <|start_filename|>editor/draw_pixels.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* draw_pixels.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ddehtyar <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/01/29 14:20:46 by ddehtyar #+# #+# */ /* Updated: 2019/01/29 14:20:48 by ddehtyar ### ########.fr */ /* */ /* ************************************************************************** */ #include "doom_nuken.h" Uint32 get_pixel2(SDL_Surface *sur, const int x, const int y) { uint8_t *v; int bpp; if (x < 0 || x >= sur->w || y < 0 || y >= sur->h) return (0); bpp = sur->format->BytesPerPixel; v = (uint8_t *)sur->pixels + y * sur->pitch + x * bpp; return (v[0] | v[1] << 8 | v[2] << 16); } void coordinate_network(int x, int y, t_doom *den, t_col *vec) { int all_skape; float findx; float findy; all_skape = START + den->skape; findx = ((float)x / all_skape + 0.5); vec->xmod = (int)findx * all_skape; findy = ((float)y / all_skape + 0.5); vec->ymod = (int)findy * all_skape; } void set_pixel(SDL_Surface *bmp, int x, int y, Uint32 pixel) { Uint32 *target_pixel; target_pixel = NULL; if (x < WIDTH && x >= 0 && y < HEIGHT && y >= 0) { target_pixel = (char *)bmp->pixels + y * bmp->pitch + x * sizeof(int); *target_pixel = pixel; } } void load_image(t_doom *den) { den->icon[0] = SDL_LoadBMP("icon/delete.bmp"); den->icon[1] = SDL_LoadBMP("icon/next_wall.bmp"); den->icon[2] = SDL_LoadBMP("icon/all_walls.bmp"); den->icon[3] = SDL_LoadBMP("icon/start.bmp"); den->icon[4] = SDL_LoadBMP("icon/5.bmp"); den->icon[5] = SDL_LoadBMP("icon/save.bmp"); den->icon[6] = SDL_LoadBMP("icon/bakc.bmp"); den->icon[7] = SDL_LoadBMP("icon/player.bmp"); den->icon[8] = SDL_LoadBMP("icon/all_sector.bmp"); den->icon[9] = SDL_LoadBMP("icon/way.bmp"); den->icon[10] = SDL_LoadBMP("icon/sprite.bmp"); den->icon[11] = SDL_LoadBMP("icon/finish.bmp"); den->icon[12] = SDL_LoadBMP("icon/sprite_find.bmp"); den->i = -1; while (++den->i < 13) { if (den->icon[den->i] == 0) { write(1, "Error, check your files which need to be exist\n", 47); exit(0); } } } void free_surface(t_doom *den) { int i; i = -1; while (++i < 12) SDL_FreeSurface(den->icon[i]); } <|start_filename|>editor/sprite_two.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* sprite_two.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ddehtyar <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/02/28 16:26:54 by ddehtyar #+# #+# */ /* Updated: 2019/02/28 16:26:55 by ddehtyar ### ########.fr */ /* */ /* ************************************************************************** */ #include "doom_nuken.h" void check_sprite(t_doom *den) { t_sprite *tmp; t_sprite *tmp2; tmp = den->sprite; while (tmp) { den->xy.x = tmp->x; den->xy.y = tmp->y; in_all_sect(den); tmp->num_sec = den->xy.bool_cor; tmp2 = tmp; tmp = tmp->next; if (den->xy.bool_cor == -1) delete_sprite(den, tmp2); } } void sum_sprite(t_doom *den) { t_sprite *tmp; tmp = den->sprite; den->sprites = 0; if (den->sprite) { while (tmp) { den->sprites += 1; tmp = tmp->next; } } } void sprite(t_doom *den) { den->cursor = SDL_CreateColorCursor(den->icon[10], 0, 0); SDL_SetCursor(den->cursor); den->blockwall = 2; } void retry_write(t_doom *den, t_col *vec) { clean_find_vec(den); clear_texture(den, vec); map_network(den); info_display(den); blonk_on_now(den); } void clear_texture(t_doom *den, t_col *vec) { SDL_FillRect(den->bmp, NULL, 0x000000); vec->x1 = LIM; vec->y1 = LIM; vec->x2 = LIM; vec->y2 = LIM; vec->xmod = 0; vec->ymod = 0; write_map(den, vec); } <|start_filename|>editor/check_option.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* check_option.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ddehtyar <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/02/20 16:17:30 by ddehtyar #+# #+# */ /* Updated: 2019/02/20 16:17:31 by ddehtyar ### ########.fr */ /* */ /* ************************************************************************** */ #include "doom_nuken.h" int in_all_help(t_doom *den, t_wals *lmp, int sec) { den->tmp = lmp; den->xy.x += 1; if (inside_sect(den, &den->tmp, sec) != 0) { den->tmp = lmp; den->xy.y -= 1; if (inside_sect(den, &den->tmp, sec) != 0) { den->xy.x -= 1; den->xy.bool_cor = sec; return (1); } else den->xy.x -= 1; } else { den->xy.x -= 1; den->xy.y -= 1; } return (0); } void in_all_sect(t_doom *den) { t_wals *rmp; t_wals *lmp; rmp = den->tmp; den->i = -1; while (++den->i < den->sec) { lmp = den->tmp; if (inside_sect(den, &den->tmp, den->i) != 0) { den->tmp = lmp; den->xy.y += 1; if (inside_sect(den, &den->tmp, den->i) != 0) { if (in_all_help(den, lmp, den->i) == 1) break ; } else den->xy.y -= 1; } den->xy.bool_cor = -1; if (den->tmp->next != NULL) den->tmp = den->tmp->next; } den->tmp = rmp; } void blonk_on_now(t_doom *den) { t_wals *wals; wals = den->tmp; if (!den->tmp) { den->blouk = 1; return ; } while (wals->next) wals = wals->next; if (wals->blouk == 1) den->blouk = 1; } void clean_string(t_doom *den) { int i; int j; j = 380; while (++j < 420) { i = den->border; while (++i < WIDTH) set_pixel(den->bmp, i, j, 0); } } void back_startwall(t_doom *den, t_col *vec) { clean_vec(vec); den->xsec = -1000000; den->ysec = -1000000; clear_texture(den, vec); map_network(den); info_display(den); den->button = 1; den->blouk = 1; } <|start_filename|>3d/SRC2/loop.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* loop.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbolilyi <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/05 12:07:23 by dbolilyi #+# #+# */ /* Updated: 2019/03/05 12:11:18 by dbolilyi ### ########.fr */ /* */ /* ************************************************************************** */ #include "../guardians.h" void loop3(t_sdl *iw, clock_t t, float jsz) { if (iw->v.right != 1) move(iw, 90, &iw->v.right); if (iw->v.fall != 1 && !iw->v.fly_mode) { t = clock(); iw->p.z -= (int)(iw->l.accel * ((double)(t - iw->v.fall) / (double)CLKS_P_S) * 50.0f); } else if (iw->v.jump_time != 1) { jsz = (float)(clock() - iw->v.jump_time) / (float)CLKS_P_S * (float)JUMP_HEIGHT * iw->l.accel / 10.0f; if ((int)jsz >= iw->v.jump) { iw->p.z += iw->v.jump; iw->v.jump_time = 1; } else { iw->p.z += (int)jsz; iw->v.jump -= (int)jsz; } } } void loop4(t_sdl *iw) { if (iw->v.fly_up != 1) { iw->p.z += (int)(FLY_SPEED * USELESS1 / (float)CLKS_P_S); iw->v.fly_up = clock(); } if (iw->v.fly_down != 1) { iw->p.z -= (int)(FLY_SPEED * (float)(clock() - iw->v.fly_down) / (float)CLKS_P_S); iw->v.fly_down = clock(); } if (iw->sectors[iw->d.cs].cl.t >= 0 && iw->p.z + PLAYER_HEAD_SIZE - iw->v.crouch > iw->v.plrzu && iw->v.fly_mode != 2) iw->v.fall_z = (iw->p.z = iw->v.plrzu - PLAYER_HEAD_SIZE + iw->v.crouch); else if (iw->p.z - iw->v.plrzd < PLAYER_HEIGHT && iw->v.fly_mode != 2) { iw->p.z = iw->v.plrzd + PLAYER_HEIGHT; iw->v.fall = 1; if (iw->v.fall_z - iw->p.z >= FALLING_DIE_SIZE && iw->v.game_mode) iw->p.health = 0; } } void loop6(t_sdl *iw) { if (iw->v.fly_mode == 2) { if (iw->v.front != 1) move(iw, 0, &iw->v.front); if (iw->v.back != 1) move(iw, 180, &iw->v.back); if (iw->v.left != 1) move(iw, 270, &iw->v.left); if (iw->v.right != 1) move(iw, 90, &iw->v.right); } else iw->v.fall = 1; } void loop5(t_sdl *iw) { if (iw->d.cs >= 0) { iw->v.plrzu = get_ceil_z(iw, iw->p.x, iw->p.y); iw->v.plrzd = get_floor_z(iw, iw->p.x, iw->p.y); if (iw->v.crouch != 0 && iw->v.crouch_pressed == 0 && iw->v.plrzu - iw->v.plrzd >= PLAYER_HEIGHT + PLAYER_HEAD_SIZE) iw->v.crouch = 0; if (iw->v.front != 1) move(iw, 0, &iw->v.front); if (iw->v.back != 1) move(iw, 180, &iw->v.back); if (iw->v.left != 1) move(iw, 270, &iw->v.left); loop3(iw, 0, 0.0f); if (iw->v.fall == 1 && iw->v.jump_time == 1 && (iw->p.z - iw->v.plrzd) > PLAYER_HEIGHT && !iw->v.fly_mode) { iw->v.fall = clock(); iw->v.fall_z = iw->p.z; } loop4(iw); } else loop6(iw); } void loop(t_sdl *iw) { if ((double)(clock() - iw->loop_update_time) < (double)CLKS_P_S / (double)MAX_FPS) return ; sound_loop(iw); environment_loop(iw); if (iw->v.left_mouse_pressed && iw->v.mouse_mode == 1) attack(iw); loop1(iw); loop2(iw); loop5(iw); do_sector_animations(iw); do_wall_animations(iw); if (iw->v.fly_mode != 2) check_walls_collisions(iw); if (iw->v.game_mode) check_enemies(iw); update(iw); iw->v.fps = (int)((float)CLKS_P_S / (float)(clock() - iw->loop_update_time)); iw->loop_update_time = clock(); } <|start_filename|>3d/SRC3/set_defaults_guns.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* set_defaults_guns.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbolilyi <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/05 13:05:56 by dbolilyi #+# #+# */ /* Updated: 2019/03/05 13:05:57 by dbolilyi ### ########.fr */ /* */ /* ************************************************************************** */ #include "../guardians.h" void get_guns_center(t_sdl *iw, int i, int scale) { scale /= 2; iw->guns.t_rect[i].w = iw->t_weap[i]->w * WINDOW_W / scale; iw->guns.t_rect[i].h = iw->guns.t_rect[i].w * iw->t_weap[i]->h / iw->t_weap[i]->w; iw->guns.t_rect[i].x = (WINDOW_W - iw->guns.t_rect[i].w) / 2; iw->guns.t_rect[i].y = (WINDOW_H - iw->guns.t_rect[i].h) / 2; } void get_guns_center_down(t_sdl *iw, int i, int scale) { scale /= 2; iw->guns.t_rect[i].w = iw->t_weap[i]->w * WINDOW_W / scale; iw->guns.t_rect[i].h = iw->guns.t_rect[i].w * iw->t_weap[i]->h / iw->t_weap[i]->w; iw->guns.t_rect[i].x = (WINDOW_W - iw->guns.t_rect[i].w) / 2; iw->guns.t_rect[i].y = WINDOW_H - iw->guns.t_rect[i].h; } void get_guns3(t_sdl *iw) { iw->guns.t_rect[7].x += iw->guns.t_rect[7].w * 3 / 5; get_guns_center_down(iw, 8, 2500); iw->guns.t_rect[8].x += iw->guns.t_rect[8].w * 3 / 5; get_guns_center_down(iw, 9, 2500); iw->guns.t_rect[9].x += iw->guns.t_rect[9].w * 3 / 5; get_guns_center_down(iw, 10, 1500); get_guns_center_down(iw, 11, 1500); get_guns_center_down(iw, 12, 1500); get_guns_center_down(iw, 13, 1500); get_guns_center_down(iw, 14, 1500); get_guns_center_down(iw, 15, 1500); get_guns_center_down(iw, 16, 1500); iw->guns.prev_update_time = clock(); } void get_guns2(t_sdl *iw) { get_guns_center(iw, 3, 1700); iw->guns.t_rect[3].x += WINDOW_W / 9; iw->guns.t_rect[3].y -= WINDOW_H / 3; get_guns_center(iw, 4, 2200); iw->guns.t_rect[4].x += WINDOW_W / 8; iw->guns.t_rect[4].y -= WINDOW_H / 3; get_guns_center(iw, 5, 2200); iw->guns.t_rect[5].x += WINDOW_W / 7; iw->guns.t_rect[5].y -= WINDOW_H / 5; get_guns_center(iw, 6, 2200); iw->guns.t_rect[6].x += WINDOW_W / 6; iw->guns.t_rect[6].y += WINDOW_H / 10; get_guns_center_down(iw, 7, 2500); get_guns3(iw); } void get_guns(t_sdl *iw) { iw->guns.t = 17; iw->guns.max_bullets[0] = 1; iw->guns.max_bullets[1] = 4; iw->guns.max_bullets[2] = 10; iw->guns.max_bullets_in_stock[0] = 0; iw->guns.max_bullets_in_stock[1] = 40; iw->guns.max_bullets_in_stock[2] = 100; iw->guns.bullets[0] = 1; iw->guns.bullets[1] = 0; iw->guns.bullets[2] = 0; iw->guns.bullets_in_stock[0] = 0; iw->guns.bullets_in_stock[1] = 0; iw->guns.bullets_in_stock[2] = 0; iw->guns.gun_in_hands = 0; iw->guns.status = 0; get_guns_center_down(iw, 17, 2000); get_guns_center_down(iw, 18, 2000); get_guns_center_down(iw, 0, 3000); iw->guns.t_rect[0].x += iw->guns.t_rect[0].w / 3 * 2; get_guns_center_down(iw, 1, 3000); iw->guns.t_rect[1].x += iw->guns.t_rect[1].w * 4 / 5; get_guns_center(iw, 2, 1700); iw->guns.t_rect[2].x += WINDOW_W / 10; iw->guns.t_rect[2].y -= WINDOW_H / 5; get_guns2(iw); } <|start_filename|>editor/sector.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* sector.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ddehtyar <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/02/20 15:12:57 by ddehtyar #+# #+# */ /* Updated: 2019/02/20 15:12:58 by ddehtyar ### ########.fr */ /* */ /* ************************************************************************** */ #include "doom_nuken.h" void add_new_sector(t_doom *den) { t_sector_list *nsec; t_sector_list *tmp; nsec = (t_sector_list *)malloc(sizeof(t_sector_list)); nsec->next = 0; nsec->fr.z = 0; nsec->fr.n = 0; nsec->fr.t = 1; nsec->cl.z = 2000; nsec->cl.n = 0; nsec->cl.t = 3; nsec->light = 0; if (den->sectors == 0) den->sectors = nsec; else { tmp = den->sectors; while (tmp->next != 0) tmp = tmp->next; tmp->next = nsec; } } void change_way2(t_doom *den, t_wals *first_element, t_wals **first_element2) { int tmp; if (first_element != 0) change_way2(den, first_element->next, first_element2); else return ; tmp = first_element->x; first_element->x = first_element->x1; first_element->x1 = tmp; tmp = first_element->y; first_element->y = first_element->y1; first_element->y1 = tmp; (*first_element2)->next = first_element; (*first_element2) = (*first_element2)->next; } void sort_help(int i, t_wals *rmp, t_wals *tmp, int *walls) { while (rmp) { walls[i] = rmp->x; walls[i + 1] = rmp->y; walls[i + 2] = rmp->x1; walls[i + 3] = rmp->y1; i += 4; rmp = rmp->next; } --i; while (tmp) { tmp->y = walls[i]; tmp->x = walls[i - 1]; tmp->y1 = walls[i - 2]; tmp->x1 = walls[i - 3]; i -= 4; tmp = tmp->next; } } void sort_walls_sec(t_wals *tmp) { t_wals *rmp; int i; int *walls; i = 0; rmp = tmp; while (rmp) { i++; rmp = rmp->next; } rmp = tmp; walls = (int *)malloc(sizeof(int) * (i * 4)); i = 0; sort_help(i, rmp, tmp, walls); free(walls); } t_sector_list *get_sector_id(t_doom *den, int id) { t_sector_list *tmp; int i; tmp = den->sectors; i = -1; while (++i < id) tmp = tmp->next; return (tmp); } <|start_filename|>3d/SRC3/draw_between_sectors_bot_tex.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* draw_between_sectors_bot_tex.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbolilyi <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/05 13:02:09 by dbolilyi #+# #+# */ /* Updated: 2019/03/05 13:02:10 by dbolilyi ### ########.fr */ /* */ /* ************************************************************************** */ #include "../guardians.h" void draw_between_sectors_bot_tex1(t_sdl *iw, t_save_wall *left, t_save_wall *right, t_draw_wall_tex *d) { d->lv.x = (float)(left->p.x - iw->p.x); d->lv.y = (float)(left->p.y - iw->p.y); d->rv.x = (float)(right->p.x - iw->p.x); d->rv.y = (float)(right->p.y - iw->p.y); d->ang = acosf((d->lv.x * d->rv.x + d->lv.y * d->rv.y) / (sqrtf(d->lv.x * d->lv.x + d->lv.y * d->lv.y) * sqrtf(d->rv.x * d->rv.x + d->rv.y * d->rv.y))); d->dang = d->ang / (float)(right->x - left->x); d->ang = 0.0f; d->rv.x = (float)(-right->p.x + left->p.x); d->rv.y = (float)(-right->p.y + left->p.y); d->sing = G180 - acosf((d->lv.x * d->rv.x + d->lv.y * d->rv.y) / (sqrtf(d->lv.x * d->lv.x + d->lv.y * d->lv.y) * sqrtf(d->rv.x * d->rv.x + d->rv.y * d->rv.y))); d->lenpl = sqrtf(powf(iw->p.x - left->p.x, 2.0f) + powf(iw->p.y - left->p.y, 2.0f)); d->len_lr = sqrtf(powf(left->p.x - right->p.x, 2.0f) + powf(left->p.y - right->p.y, 2.0f)); d->zudiff = (right->zu - left->zu) / d->len_lr; d->zddiff = (right->zd - left->zd) / d->len_lr; d->left_len = 0.0f; d->tx = left->olen * (float)iw->t[left->wall->t]->w * iw->tsz[left->wall->t] / 1000.0f; while (d->tx >= (float)iw->t[left->wall->t]->w) d->tx -= (float)iw->t[left->wall->t]->w; } void draw_between_sectors_bot_tex2_1(t_sdl *iw, t_save_wall *left, int *tmp, t_draw_wall_tex *d) { iw->d.bottom[left->x + d->j] = tmp[d->j]; d->ang += d->dang; d->left_len = sinf(d->ang) * d->lenpl / sinf(d->sing - d->ang); d->tx = (left->olen + d->left_len) * (float)iw->t[left->wall->t]->w * iw->tsz[left->wall->t] / 1000.0f; while (d->tx > (float)iw->t[left->wall->t]->w) d->tx -= (float)iw->t[left->wall->t]->w; } void draw_between_sectors_bot_tex2(t_sdl *iw, t_save_wall *left, int *tmp, t_draw_wall_tex *d) { int i; d->ty = d->ty * (float)iw->t[left->wall->t]->h / 1000.0f; d->dty = ((d->zu - d->zd) * (float)iw->t[left->wall->t]->h / 1000.0f) / (float)(iw->d.wallBot[d->j] - iw->d.wallTop[d->j]) * iw->tsz[left->wall->t]; while (d->ty > (float)iw->t[left->wall->t]->h) d->ty -= (float)iw->t[left->wall->t]->h; if (tmp[d->j] > iw->d.top[d->j + left->x]) i = tmp[d->j] - 1; else { i = iw->d.top[d->j + left->x]; d->ty += d->dty * (float)(iw->d.top[d->j + left->x] - tmp[d->j]); } while (++i < iw->d.bottom[left->x + d->j]) { set_pixel2(iw->sur, left->x + d->j, i, get_light_color(get_pixel(iw->t[left->wall->t], (int)d->tx, (int)d->ty), iw->sectors[iw->visited_sectors->sec].light)); d->ty += d->dty; while (d->ty >= (float)iw->t[left->wall->t]->h) d->ty -= (float)iw->t[left->wall->t]->h; } draw_between_sectors_bot_tex2_1(iw, left, tmp, d); } void draw_between_sectors_bot_tex(t_sdl *iw, t_save_wall *left, t_save_wall *right, int *tmp) { t_draw_wall_tex d; if (left->wall->t < 0) return ; draw_between_sectors_bot_tex1(iw, left, right, &d); d.j = -1; while (++d.j < right->x - left->x) { if (iw->d.top[left->x + d.j] >= iw->d.bottom[left->x + d.j] || iw->d.bottom[left->x + d.j] <= tmp[d.j]) { d.ang += d.dang; continue; } d.zu = (float)left->zu + d.left_len * d.zudiff; d.zd = (float)left->zd + d.left_len * d.zddiff; if (iw->d.wallTop[d.j] < tmp[d.j]) d.ty = d.zu + iw->tsz[left->wall->t] * (d.zu - d.zd) * (float)(tmp[d.j] - iw->d.wallTop[d.j]) / (float)(iw->d.wallBot[d.j] - iw->d.wallTop[d.j]); else d.ty = d.zu; draw_between_sectors_bot_tex2(iw, left, tmp, &d); } } <|start_filename|>3d/SRC3/sound_loops.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* sound_loops.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbolilyi <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/05 13:06:16 by dbolilyi #+# #+# */ /* Updated: 2019/03/05 13:06:17 by dbolilyi ### ########.fr */ /* */ /* ************************************************************************** */ #include "../guardians.h" void sound_loop(t_sdl *iw) { if (!Mix_PlayingMusic()) { Mix_PlayMusic(iw->sounds.music[iw->v.next_music], 0); iw->v.next_music++; if (iw->v.next_music >= MUSIC_COUNT) iw->v.next_music = 0; } } void environment_loop(t_sdl *iw) { if (iw->v.fly_mode == 0 && iw->v.fall == 1 && (iw->v.front != 1 || iw->v.back != 1 || iw->v.left != 1 || iw->v.right != 1)) { if (!Mix_Playing(0)) Mix_PlayChannel(0, iw->sounds.env[0], -1); } else if (iw->v.fly_mode == 0 && Mix_Playing(0)) Mix_HaltChannel(0); if (iw->v.fly_mode && !Mix_Playing(0)) Mix_PlayChannel(0, iw->sounds.env[18], -1); } <|start_filename|>3d/SRC/wall_animations.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* wall_animations.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbolilyi <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/01 18:01:21 by dbolilyi #+# #+# */ /* Updated: 2019/03/01 18:04:53 by dbolilyi ### ########.fr */ /* */ /* ************************************************************************** */ #include "../guardians.h" void add_wall_to_wall_animation2(t_sdl *iw, int add_wall) { int i; t_wall_animation *tmp; tmp = iw->v.wall_anim; i = -1; while (++i < tmp->count_walls) if (add_wall == tmp->walls[i]) return ; tmp->walls[tmp->count_walls] = add_wall; tmp->count_walls++; if (tmp->count_walls == COUNT_WALLS_TO_ANIM) { iw->v.f_button_mode = 0; iw->v.f_button_pointer = 0; iw->v.submenu_mode = 5; draw_submenu(iw); } } void add_wall_to_wall_animation(t_sdl *iw) { t_wall_animation *tmp; int add_wall; add_wall = get_wall_by_pointer(iw, *(iw->v.look_sector), *(iw->v.look_wall)); if (iw->walls[add_wall].nextsector != -1 || iw->walls[add_wall].next->nextsector != -1 || iw->walls[add_wall].next->next->nextsector != -1) return ; if (iw->v.wall_anim == 0) { tmp = (t_wall_animation *)malloc(sizeof(t_wall_animation)); tmp->dx = 0; tmp->dy = 0; tmp->curr_dx = 0; tmp->curr_dy = 0; tmp->speed = 1; tmp->status = 0; tmp->count_walls = 1; tmp->walls[0] = add_wall; tmp->trigger = (t_picture *)iw->v.f_button_pointer; iw->v.wall_anim = tmp; } else add_wall_to_wall_animation2(iw, add_wall); } void calculate_pictures_list(t_sdl *iw, t_wall *wall, t_picture *p) { while (p) { calculate_picture(iw, wall, p); p = p->next; } } void do_wall_animation_step_dx(t_sdl *iw, t_wall_animation *a, int dx) { iw->i = -1; while (++iw->i < a->count_walls) { if (a->moving_type == 1 && iw->walls[a->walls[iw->i]].next ->next->y > iw->walls[a->walls[iw->i]].next->y) { iw->walls[a->walls[iw->i]].next->x -= dx; iw->walls[a->walls[iw->i]].next->next->x -= dx; } else { iw->walls[a->walls[iw->i]].next->x += dx; iw->walls[a->walls[iw->i]].next->next->x += dx; } get_wall_line2(&iw->walls[a->walls[iw->i]]); get_wall_line2(iw->walls[a->walls[iw->i]].next); get_wall_line2(iw->walls[a->walls[iw->i]].next->next); calculate_pictures_list(iw, &iw->walls[a->walls[iw->i]], iw->walls[a->walls[iw->i]].p); calculate_pictures_list(iw, iw->walls[a->walls[iw->i]].next, iw->walls[a->walls[iw->i]].next->p); calculate_pictures_list(iw, iw->walls[a->walls[iw->i]].next-> next, iw->walls[a->walls[iw->i]].next->next->p); } } void do_wall_animation_step_dy(t_sdl *iw, t_wall_animation *a, int dy) { iw->i = -1; while (++iw->i < a->count_walls) { if (a->moving_type == 2 && iw->walls[a->walls[iw->i]].next ->next->x > iw->walls[a->walls[iw->i]].next->x) { iw->walls[a->walls[iw->i]].next->y -= dy; iw->walls[a->walls[iw->i]].next->next->y -= dy; } else { iw->walls[a->walls[iw->i]].next->y += dy; iw->walls[a->walls[iw->i]].next->next->y += dy; } get_wall_line2(&iw->walls[a->walls[iw->i]]); get_wall_line2(iw->walls[a->walls[iw->i]].next); get_wall_line2(iw->walls[a->walls[iw->i]].next->next); calculate_pictures_list(iw, &iw->walls[a->walls[iw->i]], iw->walls[a->walls[iw->i]].p); calculate_pictures_list(iw, iw->walls[a->walls[iw->i]].next, iw->walls[a->walls[iw->i]].next->p); calculate_pictures_list(iw, iw->walls[a->walls[iw->i]].next-> next, iw->walls[a->walls[iw->i]].next->next->p); } } <|start_filename|>editor/draw_line.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* draw_line.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ddehtyar <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/01/29 13:31:53 by ddehtyar #+# #+# */ /* Updated: 2019/01/29 13:31:55 by ddehtyar ### ########.fr */ /* */ /* ************************************************************************** */ #include "doom_nuken.h" void ft_line(t_doom *den, t_col *vec) { t_brz tip; int x2; int x1; int y2; int y1; x1 = vec->x1; x2 = vec->x2; y1 = vec->y1; y2 = vec->y2; tip.color = den->color; tip.dx = (x2 - x1 >= 0 ? 1 : -1); tip.dy = (y2 - y1 >= 0 ? 1 : -1); tip.lengthx = abs(x2 - x1); tip.lengthy = abs(y2 - y1); tip.length = (tip.lengthx > tip.lengthy ? tip.lengthx : tip.lengthy); if (tip.length == 0 && x1 < den->border && y2 < HEIGHT && x1 >= 0 && y2 >= 0 && x2 <= den->border) set_pixel(den->bmp, x1, y2, tip.color); if (tip.lengthy <= tip.lengthx) ft_line_x(den, &tip, x1, y1); else ft_line_y(den, &tip, x1, y1); } void ft_line_x(t_doom *den, t_brz *tip, int x1, int y1) { tip->x = x1; tip->y = y1; tip->d = -tip->lengthx; tip->length++; while (tip->length--) { if (tip->x < den->border && tip->y < HEIGHT && tip->x >= 0 && tip->y >= 0) set_pixel(den->bmp, tip->x, tip->y, tip->color); tip->x += tip->dx; tip->d += 2 * tip->lengthy; if (tip->d > 0) { tip->d -= 2 * tip->lengthx; tip->y += tip->dy; } } } void ft_line_y(t_doom *den, t_brz *tip, int x1, int y1) { tip->x = x1; tip->y = y1; tip->d = -tip->lengthy; tip->length++; while (tip->length--) { if (tip->x < den->border && tip->y < HEIGHT && tip->x >= 0 && tip->y >= 0) set_pixel(den->bmp, tip->x, tip->y, tip->color); tip->y += tip->dy; tip->d += 2 * tip->lengthx; if (tip->d > 0) { tip->d -= 2 * tip->lengthy; tip->x += tip->dx; } } } void pixel_width(t_doom *den, int x, int y, int colort) { set_pixel(den->bmp, x, y, colort); set_pixel(den->bmp, x + 1, y, colort); set_pixel(den->bmp, x, y + 1, colort); } void pixel_bigwidth(t_doom *den, int x, int y, int colort) { pixel_width(den, x, y, colort); pixel_width(den, x - 1, y, colort); pixel_width(den, x + 1, y, colort); pixel_width(den, x, y + 1, colort); pixel_width(den, x, y - 1, colort); } <|start_filename|>3d/SRC2/enemies_main_functions2.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* enemies_main_functions2.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbolilyi <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/05 16:46:39 by dbolilyi #+# #+# */ /* Updated: 2019/03/05 16:46:40 by dbolilyi ### ########.fr */ /* */ /* ************************************************************************** */ #include "../guardians.h" int esp_check_walls(t_sdl *iw, t_enemy_sees_player *esp) { int wall; wall = iw->sectors[esp->curr_sector].sw - 1; while (++wall < iw->sectors[esp->curr_sector].sw + iw->sectors[esp->curr_sector].nw) { if (iw->walls[wall].nextsector != -1) continue; esp->k1 = iw->walls[wall].l.a * (float)esp->px + iw->walls[wall].l.b * (float)esp->py + iw->walls[wall].l.c; esp->k2 = iw->walls[wall].l.a * (float)esp->ex + iw->walls[wall].l.b * (float)esp->ey + iw->walls[wall].l.c; if ((esp->k1 > 0.0f && esp->k2 < 0.0f) || (esp->k1 < 0.0f && esp->k2 > 0.0f)) { esp->k1 = esp->a * (float)iw->walls[wall].x + esp->b * (float)iw->walls[wall].y + esp->c; esp->k2 = esp->a * (float)iw->walls[wall].next->x + esp->b * (float)iw->walls[wall].next->y + esp->c; if ((esp->k1 > 0.0f && esp->k2 < 0.0f) || (esp->k1 < 0.0f && esp->k2 > 0.0f)) return (0); } } return (1); } int esp_check_portal(t_sdl *iw, t_enemy_sees_player *esp, int portal) { if (iw->walls[portal].glass >= 0 || iw->walls[iw->walls[portal].nextsector_wall].glass >= 0) return (0); esp->k1 = iw->walls[portal].l.a * (float)esp->px + iw->walls[portal].l.b * (float)esp->py + iw->walls[portal].l.c; esp->k2 = iw->walls[portal].l.a * (float)esp->ex + iw->walls[portal].l.b * (float)esp->ey + iw->walls[portal].l.c; if ((esp->k1 > 0.0f && esp->k2 < 0.0f) || (esp->k1 < 0.0f && esp->k2 > 0.0f)) { esp->k1 = esp->a * (float)iw->walls[portal].x + esp->b * (float)iw->walls[portal].y + esp->c; esp->k2 = esp->a * (float)iw->walls[portal].next->x + esp->b * (float)iw->walls[portal].next->y + esp->c; if ((esp->k1 > 0.0f && esp->k2 < 0.0f) || (esp->k1 < 0.0f && esp->k2 > 0.0f)) return (1); } return (0); } void esp_get_new_player_coordinates(t_sdl *iw, t_sector_way *way, t_enemy_sees_player *esp, t_sprite *s) { esp->px = iw->p.x; esp->py = iw->p.y; esp->ex = s->x; esp->ey = s->y; esp->curr_sector = s->num_sec; while (way) { esp->px -= iw->walls[iw->walls[way->portal].nextsector_wall].x - iw->walls[way->portal].next->x; esp->py -= iw->walls[iw->walls[way->portal].nextsector_wall].y - iw->walls[way->portal].next->y; way = way->next; } } int enemy_sees_player2_1(t_sdl *iw, t_sprite *s, t_sector_way *way, t_enemy_sees_player *esp) { if (!way) { esp->a = (float)(esp->py - esp->ey); esp->b = (float)(esp->ex - esp->px); esp->c = (float)(esp->px * esp->ey - esp->ex * esp->py); if (esp_check_walls(iw, esp)) { s->e.vis_esp = *esp; return ((int)sqrtf(powf(esp->px - esp->ex, 2.0f) + powf(esp->py - esp->ey, 2.0f))); } } return (-1); } int enemy_sees_player2(t_sdl *iw, t_sprite *s, t_sector_way *way, t_enemy_sees_player *esp) { while (way) { esp->a = (float)(esp->py - esp->ey); esp->b = (float)(esp->ex - esp->px); esp->c = (float)(esp->px * esp->ey - esp->ex * esp->py); if (!esp_check_walls(iw, esp) || !esp_check_portal(iw, esp, way->portal)) break ; esp->px += iw->walls[iw->walls[way->portal].nextsector_wall].x - iw->walls[way->portal].next->x; esp->py += iw->walls[iw->walls[way->portal].nextsector_wall].y - iw->walls[way->portal].next->y; esp->ex += iw->walls[iw->walls[way->portal].nextsector_wall].x - iw->walls[way->portal].next->x; esp->ey += iw->walls[iw->walls[way->portal].nextsector_wall].y - iw->walls[way->portal].next->y; esp->curr_sector = iw->walls[way->portal].nextsector; way = way->next; } return (enemy_sees_player2_1(iw, s, way, esp)); } <|start_filename|>Makefile<|end_filename|> # **************************************************************************** # # # # ::: :::::::: # # Makefile :+: :+: :+: # # +:+ +:+ +:+ # # By: dbolilyi <<EMAIL>> +#+ +:+ +#+ # # +#+#+#+#+#+ +#+ # # Created: 2018/06/16 16:42:45 by dbolilyi #+# #+# # # Updated: 2018/09/23 13:17:55 by dbolilyi ### ########.fr # # # # **************************************************************************** # NAME = doom-nukem SRC = 3d/SRC/minimap.c \ 3d/SRC/input_validation.c \ 3d/SRC/inside_sector.c \ 3d/SRC/set_get_pixels.c \ 3d/SRC/add_delete_picture.c \ 3d/SRC/add_delete_picture2.c \ 3d/SRC/draw_hud.c \ 3d/SRC/draw_hud2.c \ 3d/SRC/draw_hud3.c \ 3d/SRC/draw_hud4.c \ 3d/SRC/get_by_pointer.c \ 3d/SRC/sector_animations.c \ 3d/SRC/wall_animations.c \ 3d/SRC/wall_animations2.c \ 3d/SRC/hud_game.c \ 3d/SRC/hud_game2.c \ 3d/SRC/backpack.c \ 3d/SRC/backpack2.c \ 3d/SRC/backpack3.c \ 3d/SRC/checkpoints.c \ 3d/SRC/using_cards.c \ 3d/SRC/button_f_up.c \ 3d/SRC/key_up_hook.c \ 3d/SRC/key_down_hook.c \ 3d/SRC/mouse_move_right_wheel.c \ 3d/SRC/mouse_left_up.c \ 3d/SRC/mouse_left_up2.c \ 3d/SRC/mouse_left_up3.c \ 3d/SRC/mouse_left_up4.c \ 3d/SRC/player_moving.c \ 3d/SRC/player_moving2.c \ editor/save.c \ editor/save1.c \ editor/save2.c \ editor/save3.c \ editor/save4.c \ editor/save5.c \ editor/load_animation.c \ editor/load_connect.c \ editor/load_game.c \ editor/load_map_sec.c \ editor/load_map_tex.c \ editor/load_map.c \ 3d/SRC2/check_collisions.c \ 3d/SRC2/do_animations.c \ 3d/SRC2/do_animations2.c \ 3d/SRC2/enemies_main_functions.c \ 3d/SRC2/enemies_main_functions2.c \ 3d/SRC2/enemies_main_functions3.c \ 3d/SRC2/enemy_intelligence0.c \ 3d/SRC2/enemy_intelligence1.c \ 3d/SRC2/enemy_intelligence2.c \ 3d/SRC2/enemy_intelligence2_2.c \ 3d/SRC2/guns_mechanic.c \ 3d/SRC2/guns_mechanic2.c \ 3d/SRC2/loop.c \ 3d/SRC2/loop2.c \ 3d/SRC2/main_loops.c \ 3d/SRC2/main_loops2.c \ 3d/SRC2/read_from_files.c \ 3d/SRC2/read_from_files2.c \ 3d/SRC3/bresenham_save.c \ 3d/SRC3/checkpoints_game.c \ 3d/SRC3/draw.c \ 3d/SRC3/draw_between_sectors_bot_tex.c \ 3d/SRC3/draw_between_sectors_top_tex.c \ 3d/SRC3/draw_floor_ceil.c \ 3d/SRC3/draw_floor_ceil2.c \ 3d/SRC3/draw_get_between_sectors_walls.c \ 3d/SRC3/draw_get_between_sectors_walls2.c \ 3d/SRC3/draw_glass.c \ 3d/SRC3/draw_gun.c \ 3d/SRC3/draw_inclined_floor_ceil.c \ 3d/SRC3/draw_inclined_floor_ceil2.c \ 3d/SRC3/draw_inclined_wall_floor_ceil.c \ 3d/SRC3/draw_inclined_wall_floor_ceil2.c \ 3d/SRC3/draw_left_right.c \ 3d/SRC3/draw_pictures.c \ 3d/SRC3/draw_skybox.c \ 3d/SRC3/draw_sprites.c \ 3d/SRC3/draw_subfunctions.c \ 3d/SRC3/draw_wall_floor_ceil.c \ 3d/SRC3/draw_wall_floor_ceil2.c \ 3d/SRC3/free_ways_exit_x.c \ 3d/SRC3/ft_funcs.c \ 3d/SRC3/get_floor_ceil_z.c \ 3d/SRC3/get_kernel_mem.c \ 3d/SRC3/get_left_right_visible_walls.c \ 3d/SRC3/get_left_right_visible_walls2.c \ 3d/SRC3/get_packaging_tex_from_sur.c \ 3d/SRC3/get_sector_ways.c \ 3d/SRC3/get_sector_ways2.c \ 3d/SRC3/get_start_draw_vectors_lines.c \ 3d/SRC3/get_visible_walls.c \ 3d/SRC3/map_wall_equations.c \ 3d/SRC3/next_sector.c \ 3d/SRC3/next_sector2.c \ 3d/SRC3/set_defaults.c \ 3d/SRC3/set_defaults_guns.c \ 3d/SRC3/set_defaults_sprites.c \ 3d/SRC3/sound_loops.c \ 3d/SRC3/sprites_calculation.c \ 3d/SRC3/sprites_calculation2.c \ 3d/SRC3/undo_animations.c \ 3d/SRC3/update_window.c \ 3d/SRC3/wall_pairs_sort.c \ 3d/SRC4/draw_floor_ceil_betw_kernel.c \ 3d/SRC4/draw_glass_kernel.c \ 3d/SRC4/draw_gun_kernel.c \ 3d/SRC4/draw_inclined_floor_ceil_betw_kernel.c \ 3d/SRC4/draw_inclined_floor_ceil_betw_kernel2.c \ 3d/SRC4/draw_inclined_wall_floor_ceil_kernel.c \ 3d/SRC4/draw_inclined_wall_floor_ceil_kernel2.c \ 3d/SRC4/draw_pictures_kernel.c \ 3d/SRC4/draw_skybox_kernel.c \ 3d/SRC4/draw_sprites_kernel.c \ 3d/SRC4/draw_wall_floor_ceil_kernel.c \ 3d/SRC4/setup_opencl.c \ 3d/SRC4/setup_opencl2.c \ editor/main.c \ editor/save_list.c \ editor/display.c \ editor/draw_pixels.c \ editor/draw_line.c \ editor/map_redactor.c \ editor/save_new_list.c \ editor/write_list.c \ editor/find_walls.c \ editor/sector_in_sector.c \ editor/delete.c \ editor/sort_sector.c \ editor/sprite.c \ editor/delete_memory.c \ editor/portal.c \ editor/player.c \ editor/sector.c \ editor/check_option.c \ editor/walls.c \ editor/sprite_two.c \ editor/find_allsector.c \ editor/info_display.c \ editor/button.c \ editor/button_move.c \ editor/init_sdl.c \ editor/mouse_button.c \ editor/get_map.c \ editor/edit.c \ editor/unget.c \ editor/new_game.c \ editor/chech_new_load.c \ editor/game_mode.c \ editor/move_scan.c \ editor/delete2.c \ editor/write_list2.c OBJ = $(SRC:.c=.o) INC = -I./frameworks/SDL2.framework/Headers\ -I./frameworks/SDL2_ttf.framework/Headers\ -I./frameworks/SDL2_mixer.framework/Versions/A/Headers ERRFL = -Wall -Wextra -g # -Werror FL = -F./frameworks \ -rpath ./frameworks \ -framework SDL2 -framework SDL2_ttf -framework SDL2_mixer -framework OpenCL all: $(NAME) $(OBJ): %.o: %.c @echo "\033[93mCompiling \033[0m$@" @cc $(ERRFL) -c -o $@ $< $(INC) $(NAME): $(OBJ) @echo "\033[93mCompiling libft\033[0m" @make -C ./libft @echo "\033[93mCompiling $(NAME)\033[0m" @gcc $(ERRFL) $(FL) -o $@ $(OBJ) -L libft/ ./libft/libft.a @echo "\033[92mDONE\033[0m" clean: @echo "\033[91mDeleting libft objects\033[0m" @make -C libft/ clean @echo "\033[91mDeleting $(NAME) objects\033[0m" @rm -f $(OBJ) fclean: clean @echo "\033[91mDeleting libft.a\033[0m" @make -C libft/ fclean @echo "\033[91mDeleting $(NAME)\033[0m" @rm -f $(NAME) re: fclean \ all .PHONY: all clean fclean re .NOTPARALLEL: all clean fclean re <|start_filename|>editor/chech_new_load.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* chech_new_load.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ddehtyar <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/05 15:18:47 by ddehtyar #+# #+# */ /* Updated: 2019/03/05 15:18:48 by ddehtyar ### ########.fr */ /* */ /* ************************************************************************** */ #include "doom_nuken.h" void get_font_file(t_doom *den) { void *tmp; int fd; SDL_RWops *rw; den->iw.arial_font = 0; fd = open("fonts/ARIAL.TTF", READ_MAP); if (fd < 0) return ; tmp = malloc(70000); den->iw.font_pack_size = read(fd, tmp, 70000); close(fd); den->iw.font_pack = malloc(den->iw.font_pack_size); ft_memcpy(den->iw.font_pack, tmp, den->iw.font_pack_size); free(tmp); rw = SDL_RWFromConstMem(den->iw.font_pack, den->iw.font_pack_size); den->iw.arial_font = TTF_OpenFontRW(rw, 0, 24); den->font = den->iw.arial_font; } int usage(void) { write(1, "usage: doom-nukem new|edit|game map_name\n", 41); return (0); } int check_new(t_doom *den, char *fname) { den->fd = open(fname, O_WRONLY); if (den->fd >= 0) { close(den->fd); return (0); } den->fd = open(fname, O_DIRECTORY); if (den->fd >= 0) { close(den->fd); return (0); } den->fd = open(fname, O_WRONLY | O_CREAT | S_IRUSR | S_IWUSR); if (den->fd < 0) return (0); close(den->fd); den->fname = ft_strdup(fname); return (1); } int check_load(t_doom *den, char *fname) { den->fd = open(fname, O_DIRECTORY); if (den->fd >= 0) { close(den->fd); return (0); } den->fd = open(fname, O_RDWR); if (den->fd < 0) return (0); close(den->fd); den->fname = ft_strdup(fname); return (1); } <|start_filename|>3d/SRC/key_down_hook.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* key_down_hook.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbolilyi <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/02/28 17:13:30 by dbolilyi #+# #+# */ /* Updated: 2019/02/28 17:17:08 by dbolilyi ### ########.fr */ /* */ /* ************************************************************************** */ #include "../guardians.h" void key_down4(int code, t_sdl *iw) { if (code == 224 && iw->v.fly_mode == 0) { iw->v.crouch = CROUCH_SIZE; iw->v.crouch_pressed = 1; iw->v.sprint = 1; } } void key_down3(int code, t_sdl *iw) { if (code == 224 && iw->v.fly_mode) iw->v.fly_down = clock(); else if (code == 21 && iw->v.game_mode && iw->guns.status == 0 && iw->guns.bullets[iw->guns.gun_in_hands] < iw->guns.max_bullets[iw->guns.gun_in_hands]) iw->guns.status = 2; else if (code == 43 && iw->v.game_mode) { SDL_SetRelativeMouseMode(iw->bag.bag); iw->v.mouse_mode = iw->bag.bag; iw->bag.bag = ((iw->bag.bag == 1) ? 0 : 1); } else if (code == 9 && iw->v.game_mode) add_item(iw); else if (code == 8 && iw->v.game_mode && iw->bag.selected_item != 0) use_item(iw); else if (code == 20 && iw->v.game_mode) drop_item(iw); else if (code == 57 && iw->v.have_clocks) iw->map.back = ((iw->map.back == 1) ? 0 : 1); else if (code == 225 && iw->v.crouch == 0) iw->v.sprint = 2; else key_down4(code, iw); } void key_down2(int code, t_sdl *iw) { if (code == 18) iw->v.kernel = ((iw->v.kernel == 1) ? 0 : 1); else if (code == 43 && !iw->v.game_mode) { iw->v.mouse_mode = ((iw->v.mouse_mode == 1) ? 0 : 1); SDL_SetRelativeMouseMode(iw->v.mouse_mode); } else if (code == 55 && *(iw->v.look_sector) != 0 && iw->v.mouse_mode == 1 && !iw->v.game_mode) (*(iw->v.look_sector))->cl.t = iw->v.tex_to_fill; else if (code == 56 && *(iw->v.look_sector) != 0 && iw->v.mouse_mode == 1 && !iw->v.game_mode) (*(iw->v.look_sector))->fr.t = iw->v.tex_to_fill; else if (code == 54 && *(iw->v.look_sector) != 0 && iw->v.mouse_mode == 1 && !iw->v.game_mode) (*(iw->v.look_sector))->cl.t = -1; else if (code == 16 && iw->v.mouse_mode == 1 && *(iw->v.look_wall) != 0 && (*iw->v.look_wall)->nextsector == -1 && !iw->v.game_mode) (*(iw->v.look_wall))->t = -1; else if (code == 48 && iw->v.mouse_mode == 1) iw->v.sprite_editing = 1; else if (code == 44 && iw->v.fly_mode) iw->v.fly_up = clock(); else key_down3(code, iw); } void key_down(int code, t_sdl *iw) { if (code == 79) iw->v.rot_right = clock(); else if (code == 80) iw->v.rot_left = clock(); else if (code == 26) iw->v.front = clock(); else if (code == 22) iw->v.back = clock(); else if (code == 4) iw->v.left = clock(); else if (code == 7) iw->v.right = clock(); else if (code == 82) iw->v.rot_up = clock(); else if (code == 81) iw->v.rot_down = clock(); else if (code == 47 && *(iw->v.look_picture) != 0 && *(iw->v.look_wall) != 0 && !iw->v.game_mode) { iw->v.picture_changing = *(iw->v.look_picture); iw->v.wall_picture_changing = *(iw->v.look_wall); } else key_down2(code, iw); } void key_down_repeat(int code, t_sdl *iw) { if (code == 44 && iw->v.jump_time == 1 && iw->v.fall == 1 && !iw->v.fly_mode) { iw->v.jump_time = clock(); iw->v.jump = JUMP_HEIGHT; Mix_PlayChannel(0, iw->sounds.env[1], 0); } else if (code == 87 && !iw->v.game_mode && iw->l.accel < 9.9f) iw->l.accel += 0.1f; else if (code == 86 && !iw->v.game_mode && iw->l.accel > 0.2f) iw->l.accel -= 0.1f; } <|start_filename|>editor/save_new_list.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* save_new_list.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ddehtyar <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/02/04 15:43:27 by ddehtyar #+# #+# */ /* Updated: 2019/02/04 15:43:28 by ddehtyar ### ########.fr */ /* */ /* ************************************************************************** */ #include "doom_nuken.h" void ft_lstaddmap(t_wals **start, t_wals *new) { t_wals *tmp; if (*start == 0) *start = new; else { tmp = *start; while (tmp->next != 0) tmp = tmp->next; tmp->next = new; } } void ft_lstnewmap(t_wals **new, int x, int y, t_doom *den) { t_wals *tmp; if (*new == NULL) { tmp = (t_wals *)malloc(sizeof(t_wals)); tmp->x = (x - den->startx) / (START + den->skape); tmp->y = (y - den->starty) / (START + den->skape); tmp->next = NULL; *new = tmp; } else { tmp = *new; while (tmp->next) tmp = tmp->next; tmp->next = (t_wals *)malloc(sizeof(t_wals)); tmp->next->x = (x - den->startx) / (START + den->skape); tmp->next->y = (y - den->starty) / (START + den->skape); tmp->next->next = NULL; } } void ft_save_parm(t_wals **tmp, int x, int y, t_doom *den) { (*tmp)->x1 = (x - den->startx) / (START + den->skape); (*tmp)->y1 = (y - den->starty) / (START + den->skape); (*tmp)->tex = 0; (*tmp)->next_sector = NULL; (*tmp)->nextsector_wall = NULL; (*tmp)->blouk = den->blouk; (*tmp)->inside = den->incede; (*tmp)->glass = -1; (*tmp)->p = 0; } void ft_lstnewmap_sec_help(t_doom *den) { if (den->blouk == 1) { if (den->incede == 0) { add_new_sector(den); sort_sector(den); } else if (den->incede == 1) { sort_list_incide(den); sector_in_sector(den); check_data_sector(den); den->incede = 0; } } } void ft_lstnewmap_sec(t_wals **new, int x, int y, t_doom *den) { t_wals *tmp; tmp = *new; if (tmp->next == NULL) { ft_save_parm(&tmp, x, y, den); tmp->sec = den->sec; *new = tmp; } else { tmp = *new; while (tmp->next) tmp = tmp->next; ft_save_parm(&tmp, x, y, den); tmp->sec = den->secbaktmp; ft_lstnewmap_sec_help(den); } } <|start_filename|>editor/load_map.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* load_map.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: kkostrub <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/05 15:48:06 by kkostrub #+# #+# */ /* Updated: 2019/03/05 17:32:25 by kkostrub ### ########.fr */ /* */ /* ************************************************************************** */ #define ONE (WINDOW_W * 2 + 2) #include "doom_nuken.h" int load_map_sprites(t_doom *den) { t_sprite *tmp; int i; den->sprite = 0; if (!read_check(den->fd, &den->sprites, sizeof(int))) return (0); i = -1; while (++i < den->sprites) { tmp = (t_sprite *)malloc(sizeof(t_sprite)); if (!read_check(den->fd, tmp, sizeof(t_sprite) - sizeof(int) * ONE)) { free(tmp); return (0); } tmp->fall_time = 1; tmp->e.previous_picture_change = 1; tmp->e.prev_update_time = 1; tmp->next = den->sprite; den->sprite = tmp; } return (1); } int load_map_walls_pictures_1(t_doom *den, t_wals *tmp) { t_picture *pic; int count_pic; int j; if (!read_check(den->fd, &count_pic, sizeof(int))) return (0); j = -1; while (++j < count_pic) { pic = (t_picture *)malloc(sizeof(t_picture)); if (!read_check(den->fd, pic, sizeof(t_picture))) { free(pic); return (0); } pic->next = tmp->p; tmp->p = pic; } return (1); } int load_map_walls_pictures(t_doom *den) { t_wals *tmp; int i; den->tmp = 0; if (!read_check(den->fd, &den->walls, sizeof(int))) return (0); i = -1; while (++i < den->walls) { tmp = (t_wals *)malloc(sizeof(t_wals)); if (!read_check(den->fd, tmp, sizeof(t_wals))) { free(tmp); return (0); } tmp->p = 0; if (!load_map_walls_pictures_1(den, tmp)) return (0); tmp->next = den->tmp; den->tmp = tmp; } den->walls -= 1; return (1); } int load_map_1(t_doom *den, int zero) { if (!read_check(den->fd, &zero, sizeof(int)) || zero != 0) return (0); if (!load_map_sector_animations(den)) return (0); if (!read_check(den->fd, &zero, sizeof(int)) || zero != 0) return (0); if (!load_map_wall_animations(den)) return (0); if (!read_check(den->fd, &zero, sizeof(int)) || zero != 0) return (0); if (!load_map_checkpoints(den)) return (0); if (!read_check(den->fd, &zero, sizeof(int)) || zero != 0) return (0); if (!load_map_level(den)) return (0); if (!read_check(den->fd, &zero, sizeof(int)) || zero != 0) return (0); return (1); } int load_map(t_doom *den) { int zero; char author[79]; zero = 0; author[78] = '\0'; if (!read_check(den->fd, author, 78)) return (0); if (ft_strcmp(author, "This is map created for doom-nukem by" " dbolilyi & ddehtyar & kkostrub & elopukh") != 0) return (0); if (!load_map_walls_pictures(den)) return (0); if (!read_check(den->fd, &zero, sizeof(int)) || zero != 0) return (0); if (!load_map_sec(den)) return (0); if (!connect_map_sectors(den)) return (0); if (!read_check(den->fd, &zero, sizeof(int)) || zero != 0) return (0); if (!load_map_sprites(den)) return (0); if (!load_map_1(den, zero)) return (0); return (1); } <|start_filename|>3d/SRC/mouse_move_right_wheel.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* mouse_move_right_wheel.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbolilyi <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/01 15:02:07 by dbolilyi #+# #+# */ /* Updated: 2019/03/01 15:08:20 by dbolilyi ### ########.fr */ /* */ /* ************************************************************************** */ #include "../guardians.h" void mouse_move1(int xrel, int yrel, t_sdl *iw, int len) { iw->v.picture_changing->left_plus += xrel; if (iw->v.picture_changing->left_plus < 0) iw->v.picture_changing->left_plus = 0; else if (iw->v.picture_changing->left_plus + iw->v.picture_changing->tw > (len = (int)sqrtf(powf(iw->v.wall_picture_changing->next->x - iw->v.wall_picture_changing->x, 2.0f) + powf(iw->v.wall_picture_changing->next->y - iw->v.wall_picture_changing->y, 2.0f)))) iw->v.picture_changing->left_plus = len - iw->v.picture_changing->tw; iw->v.picture_changing->zu -= yrel; calculate_picture(iw, iw->v.wall_picture_changing, iw->v.picture_changing); } void mouse_move(int xrel, int yrel, t_sdl *iw) { if (iw->v.mouse_mode == 0) return ; if (iw->v.picture_changing == 0) { iw->p.rot += MOUSE_SENSIVITY * (float)xrel; if (iw->p.rot < 0.0f) iw->p.rot += G360; else if (iw->p.rot >= G360) iw->p.rot -= G360; iw->p.introt = (int)(iw->p.rot / G1); iw->p.rotup -= MOUSE_UP_DOWN_SENSIVITY * yrel; if (iw->p.rotup > 2 * WINDOW_H) iw->p.rotup = 2 * WINDOW_H; else if (iw->p.rotup < -2 * WINDOW_H) iw->p.rotup = -2 * WINDOW_H; } else mouse_move1(xrel, yrel, iw, 0); } void mouse_buttonright_up(t_sdl *iw) { if (iw->v.game_mode) return ; if (iw->v.look_sprite != 0 && iw->v.look_sprite->type == 2 && iw->v.sprite_editing && iw->v.look_sprite->e.status == 0) { iw->v.look_sprite->e.status = 1; iw->v.look_sprite->t_numb++; iw->v.look_sprite->t = iw->t_enemies[iw->v.look_sprite->t_numb]; iw->v.look_sprite->t_kernel = &iw->k.m_t_enemies[iw->v.look_sprite->t_numb]; } else if (iw->v.mouse_mode == 1 && iw->v.picture_changing == 0 && *(iw->v.look_picture) != 0 && *(iw->v.look_wall) != 0) delete_picture(*(iw->v.look_wall), *(iw->v.look_picture), iw); else if (iw->v.mouse_mode == 1 && iw->v.look_portal != 0) iw->v.look_portal->glass = iw->v.tex_to_fill; } void mouse_wheel1(SDL_Event *e, t_sdl *iw) { if (iw->v.mouse_mode == 1 && iw->v.picture_changing != 0) { if (e->wheel.y < 0 && iw->v.picture_changing->tw - 30 > 50) iw->v.picture_changing->tw -= 30; else if (e->wheel.y > 0) iw->v.picture_changing->tw += 30; calculate_picture(iw, iw->v.wall_picture_changing, iw->v.picture_changing); } else if (iw->v.mouse_mode == 1 && iw->v.sprite_editing && !iw->v.game_mode && iw->v.look_sprite != 0) { if (e->wheel.y < 0) iw->v.look_sprite->scale *= 1.1f; else if (iw->v.look_sprite->scale > 0.2f) iw->v.look_sprite->scale /= 1.1f; } } void mouse_wheel(SDL_Event *e, t_sdl *iw) { if (iw->v.mouse_y > WINDOW_H && iw->v.mouse_y < WINDOW_H + 100 && iw->v.mouse_mode == 0) { iw->v.scroll_first_tex -= e->wheel.y; if (iw->v.scroll_first_tex < 0) iw->v.scroll_first_tex = 0; if (iw->v.scroll_first_tex >= TEXTURES_COUNT) iw->v.scroll_first_tex = TEXTURES_COUNT - 1; SDL_FillRect(iw->sur, &iw->v.scroll_tex_rect, 0x000000); draw_tex_to_select(iw); } else if (iw->v.mouse_y > WINDOW_H + 200 && iw->v.mouse_y < WINDOW_H + 300 && iw->v.mouse_mode == 0 && iw->v.sprites_select_mode == 1) { iw->v.scroll_pickup_sprites -= e->wheel.y; if (iw->v.scroll_pickup_sprites < 0) iw->v.scroll_pickup_sprites = 0; if (iw->v.scroll_pickup_sprites >= PICK_UP_TEXTURES_COUNT) iw->v.scroll_pickup_sprites = PICK_UP_TEXTURES_COUNT - 1; draw_pickup_tex_to_select(iw); } else mouse_wheel1(e, iw); } <|start_filename|>3d/SRC2/enemies_main_functions.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* enemies_main_functions.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbolilyi <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/05 12:05:36 by dbolilyi #+# #+# */ /* Updated: 2019/03/05 12:05:37 by dbolilyi ### ########.fr */ /* */ /* ************************************************************************** */ #include "../guardians.h" void check_enemies_in_sector(t_sdl *iw, t_sprite *e) { t_sprite *tmp; tmp = *iw->sprite; while (tmp) { if (tmp->num_sec == e->num_sec && tmp->e.status == 1) tmp->e.status = 0; tmp = tmp->next; } } int move_enemy(t_sdl *iw, t_sprite *s) { t_point2d vect_norm; t_intpoint2d vect; float len; clock_t t; vect_norm.x = s->e.vis_esp.px - s->e.vis_esp.ex; vect_norm.y = s->e.vis_esp.py - s->e.vis_esp.ey; len = sqrtf(powf(vect_norm.x, 2.0f) + powf(vect_norm.y, 2.0f)); vect_norm.x /= len; vect_norm.y /= len; t = clock(); vect.x = vect_norm.x * (float)(t - s->e.prev_update_time) / (float)CLKS_P_S * 1000.0f; vect.y = vect_norm.y * (float)(t - s->e.prev_update_time) / (float)CLKS_P_S * 1000.0f; if (in_sec_xy(iw, s->num_sec, s->x + vect.x, s->y + vect.y)) { s->x += vect.x; s->y += vect.y; return (1); } return (move_enemy_in_portal(iw, s, &vect)); } void sprite_physics(t_sdl *iw, t_sprite *s) { int tmp; if (s->fall_time != 1 && (s->e.enemy_numb != 0 || s->e.status >= 4)) s->z -= (int)(iw->l.accel * ((float)(clock() - s->fall_time) / (float)CLKS_P_S) * 50.0f); tmp = get_ceil_z_sec(iw, s->x, s->y, s->num_sec); if (s->z + SPRITE_HEIGHT > tmp) s->z = tmp - SPRITE_HEIGHT; tmp = get_floor_z_sec(iw, s->x, s->y, s->num_sec); if (s->z < tmp) { s->z = tmp; s->fall_time = 1; } else s->fall_time = clock() - CLKS_P_S / 10; } void check_enemies(t_sdl *iw) { t_sprite *tmp; tmp = *iw->sprite; while (tmp) { if (tmp->type == 2) { if (tmp->e.enemy_numb == 0) enemy_intelligence0(iw, tmp); else if (tmp->e.enemy_numb == 1) enemy_intelligence1(iw, tmp); else if (tmp->e.enemy_numb == 2) enemy_intelligence2(iw, tmp, 0); tmp->e.prev_update_time = clock(); } tmp = tmp->next; } } int esp_check_return(t_sdl *iw, t_sprite *s, int ret) { if (ret < 0) return (-1); if (abs(iw->p.z - s->z) < ENEMY_SEES_PLAYER_MAX_Z_DIFF || (s->draweble && s->x_s >= 0 && s->x_s < WINDOW_W && s->sy > s->top[s->x_s] && s->sy < s->bottom[s->x_s])) return (ret); return (-1); } <|start_filename|>3d/SRC3/draw_floor_ceil2.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* draw_floor_ceil2.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbolilyi <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/05 16:56:04 by dbolilyi #+# #+# */ /* Updated: 2019/03/05 16:56:05 by dbolilyi ### ########.fr */ /* */ /* ************************************************************************** */ #include "../guardians.h" void draw_floor_ceil_tex1(t_sdl *iw, t_save_wall *left, t_save_wall *right, t_draw_wall_floor_ceil_tex *d) { d->lv.x = (float)(left->p.x - iw->p.x); d->lv.y = (float)(left->p.y - iw->p.y); d->rv.x = (float)(right->p.x - iw->p.x); d->rv.y = (float)(right->p.y - iw->p.y); d->ang = acosf((d->lv.x * d->rv.x + d->lv.y * d->rv.y) / (sqrtf(d->lv.x * d->lv.x + d->lv.y * d->lv.y) * sqrtf(d->rv.x * d->rv.x + d->rv.y * d->rv.y))); d->dang = d->ang / (float)(right->x - left->x + 1); d->ang = 0.0f; d->rv.x = (float)(-right->p.x + left->p.x); d->rv.y = (float)(-right->p.y + left->p.y); d->sing = G180 - acosf((d->lv.x * d->rv.x + d->lv.y * d->rv.y) / (sqrtf(d-> lv.x * d->lv.x + d->lv.y * d->lv.y) * sqrtf(d->rv.x * d->rv.x + d->rv.y * d->rv.y))); d->lenpl = sqrtf(powf(iw->p.x - left->p.x, 2.0f) + powf(iw->p.y - left->p.y, 2.0f)); d->len_lr = sqrtf(powf(left->p.x - right->p.x, 2.0f) + powf(left->p.y - right->p.y, 2.0f)); d->rv.x = (float)(right->p.x - left->p.x) / d->len_lr; d->rv.y = (float)(right->p.y - left->p.y) / d->len_lr; d->zu = get_ceil_z(iw, iw->p.x, iw->p.y); d->zd = get_floor_z(iw, iw->p.x, iw->p.y); d->frpl = (float)(d->zu - d->zd) / (float)(iw->p.z - d->zd); d->clpl = (float)(d->zu - d->zd) / (float)(d->zu - iw->p.z); d->px = (float)iw->p.x / 1000.0f; } void draw_floor_ceil_tex2(t_sdl *iw, t_save_wall *left, t_draw_wall_floor_ceil_tex *d) { d->py = (float)iw->p.y / 1000.0f; if (iw->sectors[iw->d.cs].cl.t < 0) { d->rot = (iw->p.rot - iw->v.angle) + (float)left->x / (float)WINDOW_W * iw->v.angle * 2.0f; if (d->rot < 0.0f) d->rot += G360; else if (d->rot > G360) d->rot -= G360; d->sky_x = d->rot * ((float)iw->t[iw->l.skybox]->w) / G360; d->dx = (float)iw->t[iw->l.skybox]->w / (G360 / (iw->v.angle * 2) * WINDOW_W); d->dy = (float)iw->t[iw->l.skybox]->h / (float)(4 * WINDOW_H); } } <|start_filename|>3d/SRC3/update_window.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* update_window.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbolilyi <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/05 13:06:34 by dbolilyi #+# #+# */ /* Updated: 2019/03/05 13:06:35 by dbolilyi ### ########.fr */ /* */ /* ************************************************************************** */ #include "../guardians.h" void update2(t_sdl *iw) { if (iw->hud.saved_time != 1) { if (clock() - iw->hud.saved_time < HUD_SAVED_TIME) draw_save(iw); else iw->hud.saved_time = 1; } if (iw->bag.bag == 1 || iw->map.back == 1) transparency(iw); if (iw->bag.bag == 1) draw_items(iw); if (iw->map.back == 1) draw_minimap(iw); if (iw->v.game_mode) draw_icon_bag(iw); draw_selected_tex(iw); draw_selected_sprite(iw); SDL_UpdateWindowSurface(iw->win); } void update(t_sdl *iw) { SDL_FillRect(iw->sur, &iw->winrect, 0x000000); draw(iw); draw_some_info(iw); if (iw->v.game_mode) { make_health(&iw->hud, iw); draw_checkpoint_text(iw); } if (iw->bag.bag != 1 && iw->map.back != 1) draw_crosshair(iw); if (iw->hud.miss_time != 1) { if (clock() - iw->hud.miss_time < HUD_MISS_TIME) draw_miss(iw); else iw->hud.miss_time = 1; } update2(iw); } <|start_filename|>3d/struct.h<|end_filename|> #ifndef __STRUCT_H # define __STRUCT_H # include "defines.h" typedef struct s_packaging_texture { void *pixels; int w; int h; int pitch; int bpp; } t_packaging_texture; typedef struct s_line2d { // Ax + By + C = 0. This is A float a; // Ax + By + C = 0. This is B float b; // Ax + By + C = 0. This is C float c; } t_line2d; typedef struct s_picture { //left shift in units int left_plus; // //top shift in units // int top_plus; // Z Coordinate of top of the picture int zu; //picture width int tw; //texture int t; int zd; int x0; int x1; int y0; int y1; struct s_picture *next; } t_picture; typedef struct s_wall { int x; int y; // Wall line t_line2d l; // Texture number int t; // Index of the next sector int nextsector; // Index of the same wall in the next sector int nextsector_wall; // Glass texture (-1 if just a portal) int glass; // Pictures above the main texture t_picture *p; struct s_wall *next; } t_wall; typedef struct s_vector { // Ax + By + Cz + D = 0 this is A int a; // Ax + By + Cz + D = 0 this is B int b; // Ax + By + Cz + D = 0 this is C int c; // Ax + By + Cz + D = 0 this is D int d; } t_vector; typedef struct s_sector_fc { // X coordinate of floor|ceil int x; // Y coordinate of floor|ceil int y; // Z coordinate of floor|ceil int z; // Normal vector (null if no slope) t_vector *n; // Texture int t; } t_sector_fc; typedef struct s_sector { // Start Wall int sw; // Number Walls int nw; // Sector Floor t_sector_fc fr; // Sector Ceil t_sector_fc cl; // Visited on draw or not int visited; //Light trigger t_picture *light; } t_sector; //typedef struct s_anim_portal_rotate //{ // int start_wall; // int angle; // // 0 - in standart, 1 - rotated // int anim_status; // // -1 - static, else - begin time // int time; // //struct s_anim_portal_rotate *next; //} t_anim_portal_rotate; typedef struct s_player { int x; int y; int z; float rot; int introt; int rotup; int health; } t_player; typedef struct s_point2d { float x; float y; } t_point2d; typedef struct s_intpoint2d { int x; int y; } t_intpoint2d; typedef struct s_draw_line { int x0; int y0; int x1; int y1; } t_draw_line; typedef struct s_draw_wall_tex { float tx; float ty; float dty; float sing; float ang; float dang; float lenpl; t_point2d lv; t_point2d rv; float zudiff; float zddiff; float zu; float zd; float left_len; float len_lr; int j; } t_draw_wall_tex; typedef struct s_draw_wall_tex_kernel { /*float tx; float ty; float dty;*/ t_point2d lv; t_point2d rv; /*float zu; float zd; float left_len;*/ float len_lr; } t_draw_wall_tex_kernel; typedef struct s_draw_floor_tex { float sing; float ang; float dang; float lenpl; t_point2d lv; t_point2d rv; float zu; float zd; float left_len; float len_lr; float wall_dist; float weight; float k; float pl; t_point2d floor; t_point2d r; float coef; float px; float py; } t_draw_floor_tex; typedef struct s_draw_wall_floor_ceil_tex { float sing; float ang; float dang; float lenpl; t_point2d lv; t_point2d rv; float zu; float zd; float left_len; float len_lr; float wall_dist; float weight; float k; float frpl; float clpl; t_point2d floor; t_point2d r; int frcoef; int clcoef; float px; float py; float zudiff; float zddiff; float tx; float ty; float dty; float rot; float dx; float dy; float sky_x; float sky_y; int i; int j; float ty_tsz; } t_draw_wall_floor_ceil_tex; typedef struct s_draw_wall_floor_ceil_tex_kernel { float ang; t_point2d lv; t_point2d rv; float len_lr; int zu; int zd; int cint[26]; float cfloat[19]; size_t global_item_size; size_t local_item_size; } t_draw_wall_floor_ceil_tex_kernel; typedef struct s_draw_floor_tex_kernel { float ang; t_point2d lv; t_point2d rv; float zu; float zd; float len_lr; } t_draw_floor_tex_kernel; typedef struct s_draw_skybox { float rot; float dx; float dy; float sky_x; float sky_y; } t_draw_skybox; typedef struct s_draw_glass { float sing; float ang; float dang; float lenpl; t_point2d lv; t_point2d rv; float zu; float zd; float left_len; float len_lr; float zudiff; float zddiff; float tx; float ty; float dty; int pixel; int nleft_zu; int nright_zu; int nleft_zd; int nright_zd; int i; int j; float ty_tsz; } t_draw_glass; typedef struct s_draw_picture { float lang; float rang; float plen; int rx0; int rx1; int ry0_up; int ry0_down; int ry1_up; int ry1_down; float dy_down; float dy_up; float down; float up; float dx; float pic_x; float pic_y; float dy_plus; int pixel; int i; int j; int cint[9]; float cfloat[6]; size_t global_item_size; size_t local_item_size; } t_draw_picture; typedef struct s_save_wall { int x; float len; float plen; float olen; t_intpoint2d p; t_wall *wall; int zu; int zd; struct s_save_wall *next; } t_save_wall; typedef struct s_save_wall_pairs { t_save_wall *left; t_save_wall *right; struct s_save_wall_pairs *next; } t_save_wall_pairs; typedef struct s_draw_info { char *s; char *s2; char *s3; SDL_Surface *stext; SDL_Color col; SDL_Rect rect; } t_draw_info; // typedef struct s_save_wall_pairs_closest // { // t_save_wall_pairs *tmp; // // 0 - left, 1 - right // int lr; // } t_save_wall_pairs_closest; typedef struct s_visited_sector { int sec; struct s_visited_sector *next; } t_visited_sector; typedef struct s_enemy_sees_player { int px; int py; int ex; int ey; int curr_sector; float k1; float k2; float a; float b; float c; } t_enemy_sees_player; typedef struct s_enemy { int enemy_numb; int health; // 0 - passive turned on player, // 1 - passive turned away player, // 2 - haunting player // 3 - attack start // 4.. other custom modes int status; // time of previous loop update long long int prev_update_time; int start_x; int start_y; t_enemy_sees_player vis_esp; long long int previous_picture_change; } t_enemy; typedef struct s_sprite { int x; int t_numb; t_packaging_texture *t; cl_mem *t_kernel; int y; int z; long long int fall_time; int x_s; float plen; float pplen; //float dist; int spritewidth; int spriteheight; int sy; int sx; int ey; int ex; int i; int num_sec; float scale; struct s_sprite *next; int draweble; // 0 - decor, 1 - pickup, 2 - enemy int type; t_enemy e; // int index; int taken; int top[WINDOW_W + 1]; int bottom[WINDOW_W + 1]; } t_sprite; typedef struct s_sector_animation { // 0 - FC, 1 - F, 2 - C int type; // The value to which to change int dy; // Current changed Z int curr_dy; // Change value for a some clocks int speed; // Previous change time long long int prev_clock; // Sector to be animated int sector; // 0 - not animated, 1 - animated int status; t_picture *trigger; int trig_wall_numb; int trig_pic_numb; struct s_sector_animation *next; } t_sector_animation; //typedef struct s_animated_walls //{ // t_wall *wall; // struct s_animated_walls *next; //} t_animated_walls; typedef struct s_wall_animation { // 0 - Same, 1 - Inverse by X, 2 - Inverse by Y int moving_type; // 0 - DX->DY, 1 - DY->DX int priority; // The value to which to change X int dx; // The value to which to change Y int dy; // Current changed X int curr_dx; // Current changed Y int curr_dy; // Change value for a some clocks int speed; // 0 - not animated, 1 - animated int status; // Previous change time long long int prev_clock; // Count wall to be animated int count_walls; // ->next Walls to be animated int walls[COUNT_WALLS_TO_ANIM]; //t_animated_walls *walls; t_picture *trigger; int trig_wall_numb; int trig_pic_numb; struct s_wall_animation *next; } t_wall_animation; ////////////////////////////////////////////////////////////////////////////// typedef struct s_col { int x1; int y1; int x2; int y2; int xmod; int ymod; int sect; } t_col; typedef struct s_xy { int x; int y; } t_xy; typedef struct s_brz { int dx; int dy; int lengthx; int lengthy; int length; int x; int y; int d; int color; } t_brz; typedef struct s_hud { SDL_Surface *enot_sur; t_packaging_texture *enot; SDL_Surface *miss_sur; t_packaging_texture *miss; clock_t miss_time; SDL_Surface *saved_sur; t_packaging_texture *saved; clock_t saved_time; SDL_Rect rect; // int color; int shell; int i; t_xy mas[300]; t_xy mas2[300]; int rad; int koord; SDL_Surface *dead_sur; t_packaging_texture *dead; SDL_Surface *win_sur; t_packaging_texture *win; } t_hud; typedef struct s_keyb_inp { char s[INPUT_STRING_LEN + 1]; int s_len; t_sprite *sprite; //starting from 0 int sprite_numb; struct s_keyb_inp *next; } t_keyb_inp; ///////////////////////////////////////////////// typedef struct s_draw { int top[WINDOW_W + 1]; int bottom[WINDOW_W + 1]; int top_save[WINDOW_W + 1]; int bottom_save[WINDOW_W + 1]; t_intpoint2d view_dir; t_line2d screen; float screen_len; t_line2d left_line; t_line2d right_line; t_point2d left_point; t_point2d right_point; // Current Sector int cs; // Visible Walls t_save_wall *vw; // Left Right Walls to Draw t_save_wall_pairs *vwp; int *wallTop; int *wallBot; int prev_sector; t_wall *prev_sector_wall; int screen_left; int screen_right; int *save_bot_betw; int *save_top_betw; } t_draw; typedef struct s_kernel { char *source_str; size_t source_size; cl_context context; cl_device_id device_id; cl_uint ret_num_devices; cl_uint ret_num_platforms; cl_platform_id *platforms; cl_int ret; cl_command_queue command_queue; cl_program program; //cl_kernel kernel; cl_mem m_sur; cl_mem m_t[TEXTURES_COUNT]; cl_mem m_top; cl_mem m_bottom; cl_mem m_wallTop; cl_mem m_wallBot; cl_mem m_cint; cl_mem m_cfloat; cl_mem m_top_betw; cl_mem m_bot_betw; cl_mem m_save_top; cl_mem m_save_bottom; cl_mem m_save_top2; cl_mem m_save_bottom2; cl_mem m_save_top3; cl_mem m_save_bottom3; cl_mem m_t_decor[DECOR_TEXTURES_COUNT]; cl_mem m_t_enemies[ENEMIES_TEXTURES_COUNT]; cl_mem m_t_pickup[PICK_UP_TEXTURES_COUNT]; cl_mem m_t_weap[WEAPONS_TEXTURES_COUNT]; // draw_inclined_wall_floor_ceil_tex_kernel cl_kernel kernel0; // draw_wall_floor_ceil_tex_kernel cl_kernel kernel1; // draw_inclined_floor_ceil_betw_walls_tex_kernel cl_kernel kernel2; // draw_floor_ceil_betw_walls_tex_kernel cl_kernel kernel3; // draw_skybox_kernel cl_kernel kernel4; // draw_glass_tex_kernel cl_kernel kernel5; // draw_picture_kernel cl_kernel kernel6; // draw_sprite_kernel cl_kernel kernel7; // draw_gun_kernel cl_kernel kernel8; } t_kernel; typedef struct s_variables { // Sectors Count int sc; // Last Sector int ls; // FOV angle / 2 float angle; // 1 - kernel-ON int kernel; // move clock_t front; clock_t back; clock_t left; clock_t right; // rotate clock_t rot_left; clock_t rot_right; clock_t rot_up; clock_t rot_down; clock_t fall; clock_t jump_time; int plrzu; int plrzd; int jump; int fps; int tex_to_fill; int scroll_first_tex; int mouse_mode; int mouse_x; int mouse_y; SDL_Rect scroll_tex_rect; t_wall **look_wall; t_wall *look_portal; t_sector **look_sector; t_picture **look_picture; t_sprite *look_sprite; // 0 - floor, 1 - ceil int changing_fc; SDL_Rect chang_fc_rect; //int count_portal_rot_anim; // 0 - Walls texture editing, 1 - Pictures editing // int edit_mode; t_picture *picture_changing; t_wall *wall_picture_changing; int f_button_mode; void *f_button_pointer; int submenu_mode; t_sector_animation *sector_anim; t_wall_animation *wall_anim; int game_mode; // 0 - decor, 1 - pickup, 2 - enemies int sprites_select_mode; int scroll_decor_sprites; int scroll_pickup_sprites; int selected_sprite_type; int selected_sprite; int sprite_editing; int fly_mode; clock_t fly_up; clock_t fly_down; int weapon_change_x; int weapon_change_xdir; int weapon_change_y; int weapon_change_y_hide; int weapon_change_ydir; int left_mouse_pressed; char *on_screen_text; clock_t on_screen_text_time; int have_clocks; clock_t jetpack; t_sprite *last_checkpoint; t_keyb_inp *last_to_write; int next_music; int sprint; int crouch; int crouch_pressed; int fall_z; } t_variables; typedef struct s_level { // Skybox texture number int skybox; // acceleration (meters per second^2) float accel; // Start story texture number int story; int start_x; int start_y; int start_rot; // Level end sector int win_sector; } t_level; // typedef struct s_visited_portal // { // t_wall *wall; // struct s_visited_portal *next; // } t_visited_portal; typedef struct s_sector_way { int portal; struct s_sector_way *next; } t_sector_way; typedef struct s_sector_ways { t_sector_way *way_start; int way_len; struct s_sector_ways *next; } t_sector_ways; typedef struct s_get_sectors_ways { int from; int to; int current; t_sector_ways *ways; } t_get_sectors_ways; //typedef struct s_draw_gun //{ // SDL_Surface *(t)[]; //} t_draw_gun; typedef struct s_guns { // 0 - texture numb int t; // 0 - hands, 1 - pistol, 2 - rifle int gun_in_hands; // 0 - in_hand, 1 - shooting, // 2 - reload, 3 - changing int status; int bullets[WEAPONS_COUNT]; int max_bullets[WEAPONS_COUNT]; int bullets_in_stock[WEAPONS_COUNT]; int max_bullets_in_stock[WEAPONS_COUNT]; SDL_Rect t_rect[WEAPONS_TEXTURES_COUNT]; clock_t prev_update_time; } t_guns; typedef struct s_bag { int bag; t_packaging_texture *(button)[3]; SDL_Surface *(button_sur)[3]; //int item_in_bag[20]; t_sprite *item_in_bag1[20]; int count_items; t_sprite *selected_item; int num_item_in_line; int indent; int click_x; int click_y; } t_bag; typedef struct s_map { int back; int mid_x; int mid_y; int min_x; int max_x; int min_y; int max_y; SDL_Rect pl_rect; SDL_Surface *player_sur; t_packaging_texture *player; } t_map; typedef struct s_menu { int count; SDL_Surface *icons_sur[6]; t_packaging_texture *icons[6]; } t_menu; typedef struct s_sound { Mix_Music *music[MUSIC_COUNT]; void *music_pack[MUSIC_COUNT]; size_t music_pack_size[MUSIC_COUNT]; SDL_RWops *music_rw[MUSIC_COUNT]; //x - xxxxx - chanel //0 - steps - 0 //1 - jump - 0 //2 - door opening - 1 //3 - pickup - 2 //4 - drop - 2 //5 - rifle shot - 3 //6 - pistol shot - 3 //7 - pistol reload - 3 //8 - rifle reload - 3 //9 - oof - 4 //10 - oof2 - 4 //11 - enemy2_attack - 7 //12 - red_button - 2 //13 - enemy0_attack - 5 //14 - enemy1_attack - 6 //15 - save - 2 //16 - light_on_off - 2 //17 - use item - 2 //18 - fly - 0 //19 - enemy2_dying //20 - enemy0_dying //21 - enemy1_dying /*void *env_pack[ENV_COUNT]; size_t env_pack_size[ENV_COUNT]; SDL_RWops *env_rw[ENV_COUNT];*/ Mix_Chunk *env[ENV_COUNT]; } t_sound; typedef struct s_sdl { SDL_Window *win; SDL_Surface *sur; SDL_Rect winrect; char quit; t_wall *walls; t_sector *sectors; // Player t_player p; t_variables v; t_level l; t_draw d; // textures SDL_Surface *(t_sur)[TEXTURES_COUNT]; t_packaging_texture *(t)[TEXTURES_COUNT]; // textures compression float tsz[TEXTURES_COUNT]; t_kernel k; int loop_update_time; void *font_pack; size_t font_pack_size; TTF_Font *arial_font; // t_visited_portal *visited_portals; t_visited_sector *visited_sectors; // Sprites t_sprite **sprite; // Sprite textures //SDL_Surface *(st)[SPRITES_TEXTURES_COUNT]; SDL_Surface *(t_decor_sur)[DECOR_TEXTURES_COUNT]; t_packaging_texture *(t_decor)[DECOR_TEXTURES_COUNT]; SDL_Surface *(t_enemies_sur)[ENEMIES_TEXTURES_COUNT]; t_packaging_texture *(t_enemies)[ENEMIES_TEXTURES_COUNT]; SDL_Surface *(t_pickup_sur)[PICK_UP_TEXTURES_COUNT]; t_packaging_texture *(t_pickup)[PICK_UP_TEXTURES_COUNT]; SDL_Surface *(t_weap_sur)[WEAPONS_TEXTURES_COUNT]; t_packaging_texture *(t_weap)[WEAPONS_TEXTURES_COUNT]; t_sector_animation *sector_animations; t_wall_animation *wall_animations; t_save_wall **vw_save; t_sector_ways ***ways; t_keyb_inp *checkpoints; t_hud hud; t_guns guns; t_bag bag; t_map map; t_menu menu; t_sound sounds; int i; } t_sdl; typedef struct s_brez { int x; int y; int dx; int dy; int sx; int sy; int k; int *wall_y; int prev_x; struct s_sdl *iw; int color; } t_brez; typedef struct s_input_loop { int quit; t_keyb_inp *ki; char *alphabet; int shift; } t_input_loop; typedef struct s_draw_circle { int xc; int yc; } t_draw_circle; typedef struct s_in_sec { long int x1; long int y1; long int x2; long int y2; unsigned long int wallCrossed; } t_in_sec; typedef struct s_move { float ang; int dx; int dy; float speed; t_wall *sw; int tmp; } t_move; typedef struct s_check_collisions { int wall; int len; float nx; float ny; float tmp; } t_check_collisions; typedef struct s_draw_gun { int i; int j; int to_i; int start_j; int to_j; int pixel; SDL_Rect changed_rect; } t_draw_gun; typedef struct s_draw_sprite { int i; int j; int stripe; int y; float koef; int texX; int texY; int colour; } t_draw_sprite; typedef struct s_free_sector_ways { int i; int j; t_sector_ways *tmp; t_sector_way *tmp2; t_sector_ways *tmp_f; t_sector_way *tmp2_f; } t_free_sector_ways; #endif <|start_filename|>3d/SRC/key_up_hook.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* key_up_hook.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbolilyi <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/02/28 17:54:06 by dbolilyi #+# #+# */ /* Updated: 2019/02/28 17:55:05 by dbolilyi ### ########.fr */ /* */ /* ************************************************************************** */ #include "../guardians.h" void key_up4(int code, t_sdl *iw) { if (code == 30 && iw->guns.status == 0 && iw->guns.gun_in_hands != 1 && iw->guns.bullets[1] > 0) { iw->guns.status = 3; iw->guns.gun_in_hands = 1; iw->hud.shell = 100 * iw->guns.bullets[1] / iw->guns.max_bullets[1]; } else if (code == 85 && !iw->v.game_mode) iw->l.skybox = iw->v.tex_to_fill; else if (code == 84 && !iw->v.game_mode) iw->l.story = iw->v.tex_to_fill; else if (code == 225) iw->v.sprint = 1; else if (code == 224) iw->v.crouch_pressed = 0; } void key_up3(int code, t_sdl *iw) { if (code == 44 && iw->v.fly_mode) iw->v.fly_up = 1; else if (code == 224 && iw->v.fly_mode) iw->v.fly_down = 1; else if (code == 6 && *iw->v.look_wall != 0 && (*iw->v.look_wall)->t >= 0 && (*iw->v.look_wall)->t < TEXTURES_COUNT) iw->v.tex_to_fill = (*iw->v.look_wall)->t; else if (code == 32 && iw->guns.status == 0 && iw->guns.gun_in_hands != 0) { iw->guns.status = 3; iw->guns.gun_in_hands = 0; iw->hud.shell = 100 * iw->guns.bullets[0] / iw->guns.max_bullets[0]; } else if (code == 31 && iw->guns.status == 0 && iw->guns.gun_in_hands != 2 && iw->guns.bullets[2] > 0) { iw->guns.status = 3; iw->guns.gun_in_hands = 2; iw->hud.shell = 100 * iw->guns.bullets[2] / iw->guns.max_bullets[2]; } else key_up4(code, iw); } void key_up2(int code, t_sdl *iw) { if (code == 9) button_f_up(iw); else if (code == 10) { if (iw->v.f_button_mode == 3 && iw->v.wall_anim != 0) { iw->v.submenu_mode = 5; draw_submenu(iw); } iw->v.f_button_mode = 0; iw->v.f_button_pointer = 0; } else if (code == 48) iw->v.sprite_editing = 0; else if (code == 25 && !iw->v.game_mode) { iw->v.fly_mode = ((iw->v.fly_mode == 2) ? 0 : iw->v.fly_mode + 1); Mix_HaltChannel(0); iw->v.fall = 1; iw->v.fly_down = 1; iw->v.fly_up = 1; } else key_up3(code, iw); } void key_up(int code, t_sdl *iw) { if (code == 41) iw->quit = 1; else if (code == 79) iw->v.rot_right = 1; else if (code == 80) iw->v.rot_left = 1; else if (code == 26) iw->v.front = 1; else if (code == 22) iw->v.back = 1; else if (code == 4) iw->v.left = 1; else if (code == 7) iw->v.right = 1; else if (code == 82) iw->v.rot_up = 1; else if (code == 81) iw->v.rot_down = 1; else if (code == 47) iw->v.picture_changing = 0; else if (code == 19 && iw->v.mouse_mode == 1 && *(iw->v.look_wall) != 0 && !iw->v.game_mode) add_picture(iw, *(iw->v.look_wall)); else key_up2(code, iw); } <|start_filename|>3d/SRC/sector_animations.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* sector_animations.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbolilyi <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/01 17:29:52 by dbolilyi #+# #+# */ /* Updated: 2019/03/01 17:30:53 by dbolilyi ### ########.fr */ /* */ /* ************************************************************************** */ #include "../guardians.h" void add_sector_animation(t_sdl *iw) { t_sector_animation *tmp; tmp = (t_sector_animation *)malloc(sizeof(t_sector_animation)); tmp->trigger = (t_picture *)iw->v.f_button_pointer; tmp->sector = get_sector_by_pointer(iw, *(iw->v.look_sector)); tmp->speed = 1; tmp->dy = 0; tmp->status = 0; tmp->curr_dy = 0; iw->v.sector_anim = tmp; } void do_sector_animation_step1(t_sdl *iw, t_sector_animation *a, int dz) { int w; t_picture *p; if (a->type == 0) { iw->sectors[a->sector].fr.z += dz; iw->sectors[a->sector].cl.z += dz; w = iw->sectors[a->sector].sw - 1; while (++w < iw->sectors[a->sector].sw + iw->sectors[a->sector].nw) { p = iw->walls[w].p; while (p) { p->zu += dz; p->zd += dz; p = p->next; } } } else if (a->type == 1) iw->sectors[a->sector].fr.z += dz; else if (a->type == 2) iw->sectors[a->sector].cl.z += dz; } void do_sector_animation_step(t_sdl *iw, t_sector_animation *a, int dz) { int i; do_sector_animation_step1(iw, a, dz); i = a->sector; if (iw->sectors[i].fr.n != 0) iw->sectors[i].fr.n->d = -iw->sectors[i].fr.n->a * iw->sectors[i].fr.x - iw->sectors[i].fr.n->b * iw->sectors[i].fr.y - iw->sectors[i].fr.n->c * iw->sectors[i].fr.z; if (iw->sectors[i].cl.n != 0) iw->sectors[i].cl.n->d = -iw->sectors[i].cl.n->a * iw->sectors[i].cl.x - iw->sectors[i].cl.n->b * iw->sectors[i].cl.y - iw->sectors[i].cl.n->c * iw->sectors[i].cl.z; } void exit_editing_sector_animation(t_sdl *iw) { if (iw->v.submenu_mode == 2 || iw->v.submenu_mode == 3) do_sector_animation_step(iw, iw->v.sector_anim, -iw->v.sector_anim->dy); free(iw->v.sector_anim); iw->v.sector_anim = 0; iw->v.submenu_mode = 0; draw_submenu(iw); } void change_sector_animation_status(t_sdl *iw, t_picture *p) { t_sector_animation *tmp; tmp = iw->sector_animations; while (tmp) { if (tmp->trigger == p) { tmp->status = ((tmp->status == 0) ? 1 : 0); return ; } tmp = tmp->next; } } <|start_filename|>editor/save4.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* save4.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: elopukh <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/05 15:44:11 by elopukh #+# #+# */ /* Updated: 2019/03/05 15:44:12 by elopukh ### ########.fr */ /* */ /* ************************************************************************** */ #include "doom_nuken.h" void save_map_wall_animations(t_doom *den) { t_wall_animation *tmp; int count; count = 0; tmp = den->iw.wall_animations; while (tmp) { count++; tmp = tmp->next; } write(den->fd, &count, sizeof(int)); if (den->iw.wall_animations) save_reverse_map_wall_animations(den, den->iw.wall_animations); } void set_checkpoints_sprite_numb(t_doom *den, t_keyb_inp *tmp) { t_sprite *spr; int numb; numb = 0; spr = den->sprite; while (spr) { if (spr == tmp->sprite) { tmp->sprite_numb = numb; return ; } spr = spr->next; numb++; } } void save_reverse_map_checkpoints(t_doom *den, t_keyb_inp *tmp) { if (tmp->next != 0) save_reverse_map_checkpoints(den, tmp->next); set_checkpoints_sprite_numb(den, tmp); write(den->fd, tmp, sizeof(t_keyb_inp)); } void save_map_checkpoints(t_doom *den) { t_keyb_inp *tmp; int count; count = 0; tmp = den->iw.checkpoints; while (tmp) { count++; tmp = tmp->next; } write(den->fd, &count, sizeof(int)); if (den->iw.checkpoints) save_reverse_map_checkpoints(den, den->iw.checkpoints); } void write_textures(t_doom *den, int zero) { int i; i = -1; while (++i < TEXTURES_COUNT) { write(den->fd, den->iw.t[i], sizeof(t_packaging_texture)); write(den->fd, den->iw.t[i]->pixels, den->iw.t[i]->pitch * den->iw.t[i]->h); } write(den->fd, (void *)den->iw.tsz, sizeof(float) * TEXTURES_COUNT); write(den->fd, &zero, sizeof(int)); i = -1; while (++i < DECOR_TEXTURES_COUNT) { write(den->fd, den->iw.t_decor[i], sizeof(t_packaging_texture)); write(den->fd, den->iw.t_decor[i]->pixels, den->iw.t_decor[i]->pitch * den->iw.t_decor[i]->h); } write(den->fd, &zero, sizeof(int)); } <|start_filename|>editor/load_game.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* load_game.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: kkostrub <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/05 15:48:11 by kkostrub #+# #+# */ /* Updated: 2019/03/05 17:19:56 by kkostrub ### ########.fr */ /* */ /* ************************************************************************** */ #include "doom_nuken.h" int load_map_level(t_doom *den) { if (!read_check(den->fd, &den->iw.l, sizeof(t_level))) return (0); den->player.x = den->iw.l.start_x / MAP_SCALE; den->player.y = den->iw.l.start_y / MAP_SCALE; den->player.introt = den->iw.l.start_rot; den->finish = den->iw.l.win_sector; return (1); } int load_map_music(t_doom *den) { int i; i = -1; while (++i < MUSIC_COUNT) { if (!read_check(den->fd, &(den->iw.sounds.music_pack_size[i]), sizeof(size_t))) return (0); den->iw.sounds.music_pack[i] = malloc(den->iw.sounds.music_pack_size[i]); if (!read_check(den->fd, den->iw.sounds.music_pack[i], den->iw.sounds.music_pack_size[i])) return (0); } return (1); } int load_map_env(t_doom *den) { int i; i = -1; while (++i < ENV_COUNT) { den->iw.sounds.env[i] = (Mix_Chunk *)malloc(sizeof(Mix_Chunk)); if (!read_check(den->fd, den->iw.sounds.env[i], sizeof(Mix_Chunk))) return (0); den->iw.sounds.env[i]->abuf = malloc(den->iw.sounds.env[i]->alen); if (!read_check(den->fd, den->iw.sounds.env[i]->abuf, den->iw.sounds.env[i]->alen)) return (0); } return (1); } int load4_game_1(t_doom *den, int i) { den->iw.k.source_str = malloc(den->iw.k.source_size); if (!read_check(den->fd, den->iw.k.source_str, den->iw.k.source_size)) return (0); if (!read_check(den->fd, &i, sizeof(int)) || i != 0) return (0); if (!read_check(den->fd, &den->iw.font_pack_size, sizeof(size_t))) return (0); den->iw.font_pack = malloc(den->iw.font_pack_size); if (!read_check(den->fd, den->iw.font_pack, den->iw.font_pack_size)) return (0); if (!read_check(den->fd, &i, sizeof(int)) || i != 0) return (0); return (1); } int load4_game(t_doom *den) { int i; if (!load_map_textures(den)) return (0); if (!read_check(den->fd, &i, sizeof(int)) || i != 0) return (0); if (!load_map_music(den)) return (0); if (!read_check(den->fd, &i, sizeof(int)) || i != 0) return (0); if (!load_map_env(den)) return (0); if (!read_check(den->fd, &i, sizeof(int)) || i != 0) return (0); if (!read_check(den->fd, &den->iw.k.source_size, sizeof(size_t))) return (0); if (!load4_game_1(den, i)) return (0); return (1); } <|start_filename|>3d/SRC4/draw_pictures_kernel.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* draw_pictures_kernel.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbolilyi <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/05 14:38:13 by dbolilyi #+# #+# */ /* Updated: 2019/03/05 14:38:14 by dbolilyi ### ########.fr */ /* */ /* ************************************************************************** */ #include "../guardians.h" int draw_picture_kernel2(t_sdl *iw, t_picture *pic, t_draw_picture *d) { if (iw->sectors[iw->d.cs].light == 0 || iw->sectors[iw->d.cs].light->t != 18) d->cint[8] = 1; else d->cint[8] = 0; d->cint[1] = iw->t[pic->t]->h; d->cint[4] = iw->t[pic->t]->w; d->cint[5] = WINDOW_W; d->cint[6] = iw->t[pic->t]->bpp; d->cint[7] = iw->t[pic->t]->pitch; d->lang = get_vectors_angle(iw->d.left_point.x - (float)iw->p.x, iw->d.left_point.y - (float)iw->p.y, (float)(pic->x0 - iw->p.x), (float)(pic->y0 - iw->p.y)); d->rang = get_vectors_angle(iw->d.right_point.x - (float)iw->p.x, iw->d.right_point.y - (float)iw->p.y, (float)(pic->x0 - iw->p.x), (float)(pic->y0 - iw->p.y)); if (d->rang < iw->v.angle * 2) d->rx0 = (int)(d->lang * (float)WINDOW_W / (2.0f * iw->v.angle)); else return (0); d->lang = get_vectors_angle(iw->d.left_point.x - (float)iw->p.x, iw->d.left_point.y - (float)iw->p.y, (float)(pic->x1 - iw->p.x), (float)(pic->y1 - iw->p.y)); return (1); } int draw_picture_kernel3(t_sdl *iw, t_picture *pic, t_draw_picture *d) { if (d->rang < iw->v.angle * 2) d->rx1 = (int)(d->lang * (float)WINDOW_W / (2.0f * iw->v.angle)); else d->rx1 = -(int)(d->lang * (float)WINDOW_W / (2.0f * iw->v.angle)); if (d->rx1 >= WINDOW_W) return (0); d->plen = fabsf(iw->d.screen.a * (float)pic->x0 + iw->d.screen.b * (float)pic->y0 + iw->d.screen.c) / sqrtf(iw->d.screen.a * iw->d.screen.a + iw->d.screen.b * iw->d.screen.b); d->ry0_up = WINDOW_H * (iw->p.z + (int)d->plen / 2 - pic->zu) / (int)(d->plen + 1) + iw->p.rotup; d->ry0_down = WINDOW_H * (iw->p.z + (int)d->plen / 2 - pic->zd) / (int)(d->plen + 1) + iw->p.rotup; d->plen = fabsf(iw->d.screen.a * (float)pic->x1 + iw->d.screen.b * (float)pic->y1 + iw->d.screen.c) / sqrtf( iw->d.screen.a * iw->d.screen.a + iw->d.screen.b * iw->d.screen.b); d->cint[3] = WINDOW_H * (iw->p.z + (int)d->plen / 2 - pic->zu) / (int)(d->plen + 1) + iw->p.rotup; d->cint[2] = WINDOW_H * (iw->p.z + (int)d->plen / 2 - pic->zd) / (int)(d->plen + 1) + iw->p.rotup; d->cfloat[0] = 0.0f; d->down = d->ry0_down - d->cint[2]; d->up = d->ry0_up - d->cint[3]; d->dx = d->rx0 - d->rx1; return (1); } void draw_picture_kernel4(t_sdl *iw, t_picture *pic, t_draw_picture *d) { d->cfloat[2] = d->down / d->dx; d->cfloat[3] = d->down / d->dx; d->cfloat[4] = d->up / d->dx; d->cfloat[5] = d->up / d->dx; d->cfloat[1] = (float)iw->t[pic->t]->w / d->dx; if (d->cint[0] < 0) { d->cfloat[0] += d->cfloat[1] * (float)abs(d->cint[0]); d->cfloat[2] += d->cfloat[3] * (float)abs(d->cint[0]); d->cfloat[4] += d->cfloat[5] * (float)abs(d->cint[0]); d->cint[0] = 0; } iw->k.ret = clEnqueueWriteBuffer(iw->k.command_queue, iw->k.m_cint, CL_TRUE, 0, 9 * sizeof(int), d->cint, 0, NULL, NULL); iw->k.ret = clEnqueueWriteBuffer(iw->k.command_queue, iw->k.m_cfloat, CL_TRUE, 0, 6 * sizeof(float), d->cfloat, 0, NULL, NULL); iw->k.ret = clSetKernelArg(iw->k.kernel6, 3, sizeof(cl_mem), (void *)&iw->k.m_t[pic->t]); } int draw_picture_kernel(t_sdl *iw, t_picture *pic) { t_draw_picture d; if (!draw_picture_kernel2(iw, pic, &d)) return (0); d.rang = get_vectors_angle(iw->d.right_point.x - (float)iw->p.x, iw->d.right_point.y - (float)iw->p.y, (float)(pic->x1 - iw->p.x), (float)(pic->y1 - iw->p.y)); if (!draw_picture_kernel3(iw, pic, &d)) return (0); d.cint[0] = d.rx1; draw_picture_kernel4(iw, pic, &d); if (d.rx0 < WINDOW_W) d.global_item_size = d.rx0 - d.cint[0]; else d.global_item_size = WINDOW_W - d.cint[0]; d.local_item_size = 1; if (d.global_item_size <= WINDOW_W) iw->k.ret = clEnqueueNDRangeKernel(iw->k.command_queue, iw->k.kernel6, 1, NULL, &d.global_item_size, &d.local_item_size, 0, NULL, NULL); clFlush(iw->k.command_queue); clFinish(iw->k.command_queue); if (d.rx1 <= WINDOW_W / 2 && d.rx0 >= WINDOW_W / 2) return (1); return (0); } void draw_pictures_kernel(t_sdl *iw, t_save_wall *left) { t_picture *pic; pic = left->wall->p; while (pic != 0) { if (draw_picture_kernel(iw, pic) && *(iw->v.look_picture) == 0) *(iw->v.look_picture) = pic; pic = pic->next; } } <|start_filename|>3d/SRC3/draw_pictures.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* draw_pictures.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbolilyi <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/05 13:03:27 by dbolilyi #+# #+# */ /* Updated: 2019/03/05 13:03:28 by dbolilyi ### ########.fr */ /* */ /* ************************************************************************** */ #include "../guardians.h" void draw_picture2(t_sdl *iw, t_picture *pic, t_draw_picture *d) { d->lang = get_vectors_angle(iw->d.left_point.x - (float)iw->p.x, iw->d.left_point.y - (float)iw->p.y, (float)(pic->x0 - iw->p.x), (float)(pic->y0 - iw->p.y)); d->rang = get_vectors_angle(iw->d.right_point.x - (float)iw->p.x, iw->d.right_point.y - (float)iw->p.y, (float)(pic->x0 - iw->p.x), (float)(pic->y0 - iw->p.y)); if (d->rang < iw->v.angle * 2) d->rx0 = (int)(d->lang * (float)WINDOW_W / (2.0f * iw->v.angle)); else d->rx0 = -(int)(d->lang * (float)WINDOW_W / (2.0f * iw->v.angle)); d->lang = get_vectors_angle(iw->d.left_point.x - (float)iw->p.x, iw->d.left_point.y - (float)iw->p.y, (float)(pic->x1 - iw->p.x), (float)(pic->y1 - iw->p.y)); d->rang = get_vectors_angle(iw->d.right_point.x - (float)iw->p.x, iw->d.right_point.y - (float)iw->p.y, (float)(pic->x1 - iw->p.x), (float)(pic->y1 - iw->p.y)); if (d->rang < iw->v.angle * 2) d->rx1 = (int)(d->lang * (float)WINDOW_W / (2.0f * iw->v.angle)); else d->rx1 = -(int)(d->lang * (float)WINDOW_W / (2.0f * iw->v.angle)); d->plen = fabsf(iw->d.screen.a * (float)pic->x0 + iw->d.screen.b * (float)pic->y0 + iw->d.screen.c) / sqrtf( iw->d.screen.a * iw->d.screen.a + iw->d.screen.b * iw->d.screen.b); d->ry0_up = WINDOW_H * (iw->p.z + (int)d->plen / 2 - pic->zu) / (int)(d->plen + 1) + iw->p.rotup; } void draw_picture3(t_sdl *iw, t_picture *pic, t_draw_picture *d) { d->ry0_down = WINDOW_H * (iw->p.z + (int)d->plen / 2 - pic->zd) / (int)(d->plen + 1) + iw->p.rotup; d->plen = fabsf(iw->d.screen.a * (float)pic->x1 + iw->d.screen.b * (float)pic->y1 + iw->d.screen.c) / sqrtf( iw->d.screen.a * iw->d.screen.a + iw->d.screen.b * iw->d.screen.b); d->ry1_up = WINDOW_H * (iw->p.z + (int)d->plen / 2 - pic->zu) / (int)(d->plen + 1) + iw->p.rotup; d->ry1_down = WINDOW_H * (iw->p.z + (int)d->plen / 2 - pic->zd) / (int)(d->plen + 1) + iw->p.rotup; d->pic_x = 0; d->down = d->ry0_down - d->ry1_down; d->up = d->ry0_up - d->ry1_up; d->dx = d->rx0 - d->rx1; d->dy_down = d->down / d->dx; d->dy_up = d->up / d->dx; d->i = d->rx1; if (d->i < 0) { d->pic_x += iw->t[pic->t]->w * abs(d->i) / d->dx; d->dy_down += (float)(d->down / d->dx * abs(d->i)); d->dy_up += (float)(d->up / d->dx * abs(d->i)); d->i = 0; } } void draw_picture4(t_sdl *iw, t_picture *pic, t_draw_picture *d) { d->dy_plus = iw->t[pic->t]->h / ((d->ry1_down + (float)d->dy_down) - (d->ry1_up + (float)d->dy_up)); d->j = d->ry1_up + (float)d->dy_up; if (d->j >= iw->d.top_save[d->i]) d->pic_y = 0; else { d->pic_y = d->dy_plus * (iw->d.top_save[d->i] - d->j); d->j = iw->d.top_save[d->i]; } while (d->j++ < d->ry1_down + (float)d->dy_down && d->j < iw->d.bottom_save[d->i]) { d->pixel = get_pixel(iw->t[pic->t], (int)d->pic_x, (int)d->pic_y); if (d->pixel != 0x010000) set_pixel2(iw->sur, d->i, d->j, get_light_color(d->pixel, iw->sectors[iw->d.cs].light)); d->pic_y += d->dy_plus; } d->pic_x += iw->t[pic->t]->w / d->dx; d->dy_down += (float)(d->down / d->dx); d->dy_up += (float)(d->up / d->dx); } int draw_picture(t_sdl *iw, t_picture *pic) { t_draw_picture d; draw_picture2(iw, pic, &d); draw_picture3(iw, pic, &d); while (d.i++ <= d.rx0 && d.i <= WINDOW_W) { if (iw->d.top_save[d.i] >= iw->d.bottom_save[d.i]) d.pic_x += iw->t[pic->t]->w / d.dx; else draw_picture4(iw, pic, &d); } if (d.rx1 <= WINDOW_W / 2 && d.rx0 >= WINDOW_W / 2) return (1); return (0); } void draw_pictures(t_sdl *iw, t_save_wall *left) { t_picture *pic; pic = left->wall->p; while (pic != 0) { if (draw_picture(iw, pic) && *(iw->v.look_picture) == 0) *(iw->v.look_picture) = pic; pic = pic->next; } } <|start_filename|>3d/SRC3/next_sector2.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* next_sector2.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbolilyi <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/05 17:15:03 by dbolilyi #+# #+# */ /* Updated: 2019/03/05 17:15:04 by dbolilyi ### ########.fr */ /* */ /* ************************************************************************** */ #include "../guardians.h" void draw_next_sector3(t_sdl *iw, t_save_wall *left, t_save_wall *right, t_sdl *iw2) { if (left->wall->glass >= 0) { if (iw->sectors[iw2->d.cs].cl.t < 0) draw_skybox(iw2); sort_sprites(iw); draw_glass_sprites(iw2); change_saved_top_bot_between_lines(iw, right->x - left->x + 1); draw_glass_tex(iw, left, right, right->x - left->x + 1); } free(iw->d.save_bot_betw); free(iw->d.save_top_betw); fill_portal(iw, left, right, iw2); } void draw_next_sector2(t_sdl *iw, t_save_wall *left, t_save_wall *right, t_sdl *iw2) { t_visited_sector *tmp; get_direction(iw2); get_screen_line(iw2); get_left_right_lines_points(iw2); iw2->d.vw = 0; iw2->d.vwp = 0; iw2->d.screen_left = left->x; iw2->d.screen_right = right->x; fill_tb_by_slsr(iw2); get_visible_walls(iw2); get_left_right_visible_walls(iw2); iw2->d.prev_sector = iw->d.cs; iw2->d.prev_sector_wall = left->wall; iw->sectors[iw2->d.cs].visited = 1; tmp = (t_visited_sector *)malloc(sizeof(t_visited_sector)); tmp->sec = iw2->d.cs; tmp->next = iw2->visited_sectors; iw2->visited_sectors = tmp; draw_start(iw2); iw2->visited_sectors = iw2->visited_sectors->next; free(tmp); draw_next_sector3(iw, left, right, iw2); } void draw_next_sector(t_sdl *iw, t_save_wall *left, t_save_wall *right) { t_sdl iw2; int i; iw2 = *iw; fill_top_skybox(&iw2, left, right->x - left->x + 1); iw2.p.x += iw->walls[left->wall->nextsector_wall].x - left->wall->next->x; iw2.p.y += iw->walls[left->wall->nextsector_wall].y - left->wall->next->y; iw2.d.cs = left->wall->nextsector; iw->d.save_bot_betw = get_between_sectors_walls( &iw2, left, right, &iw->d.save_top_betw); draw_between_sectors_walls(&iw2, left, right); i = left->x - 1; while (++i < right->x) { iw->d.top[i] = iw2.d.top[i]; iw->d.bottom[i] = iw2.d.bottom[i]; } if (sector_visited(iw, iw2.d.cs)) { free(iw->d.save_bot_betw); free(iw->d.save_top_betw); return ; } draw_next_sector2(iw, left, right, &iw2); } void draw_next_sector_kernel4(t_sdl *iw, t_save_wall *left, t_save_wall *right, t_sdl *iw2) { if (left->wall->glass >= 0) { if (iw->sectors[iw2->d.cs].cl.t < 0) draw_skybox_kernel(iw2); sort_sprites(iw); draw_glass_sprites_kernel(iw2); change_saved_top_bot_between_lines(iw, right->x - left->x + 1); draw_glass_tex_kernel(iw, left, right, right->x - left->x + 1); } free(iw->d.save_bot_betw); free(iw->d.save_top_betw); } <|start_filename|>3d/SRC3/get_sector_ways.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* get_sector_ways.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbolilyi <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/05 13:05:02 by dbolilyi #+# #+# */ /* Updated: 2019/03/05 13:05:03 by dbolilyi ### ########.fr */ /* */ /* ************************************************************************** */ #include "../guardians.h" void add_portal_in_way2(t_sector_ways *tmp, int portal) { t_sector_way *nw; t_sector_way *w; tmp->way_len++; nw = (t_sector_way *)malloc(sizeof(t_sector_way)); nw->portal = portal; nw->next = 0; if (tmp->way_start == 0) tmp->way_start = nw; else { w = tmp->way_start; while (w->next) w = w->next; w->next = nw; } } t_sector_ways *add_portal_in_way(t_sector_ways *current_way, int portal) { t_sector_ways *tmp; t_sector_way *way; tmp = (t_sector_ways *)malloc(sizeof(t_sector_ways)); tmp->way_start = 0; tmp->way_len = 0; if (current_way == 0) { tmp->way_len = 1; tmp->way_start = (t_sector_way *)malloc(sizeof(t_sector_way)); tmp->way_start->next = 0; tmp->way_start->portal = portal; return (tmp); } way = current_way->way_start; while (way) { add_portal_in_way2(tmp, way->portal); way = way->next; } add_portal_in_way2(tmp, portal); return (tmp); } void go_in_sector_way(t_sdl *iw, t_get_sectors_ways *g, t_sector_ways *current_way) { int wall; int save; if (g->current == g->to) { current_way->next = g->ways; g->ways = current_way; return ; } wall = iw->sectors[g->current].sw - 1; if (current_way == 0 || current_way->way_len < MAX_PORTALS_IN_SECTOR_WAY) while (++wall < iw->sectors[g->current].sw + iw->sectors[g->current].nw) { if (iw->walls[wall].nextsector == -1 || sector_in_way(iw, current_way, iw->walls[wall].nextsector) || iw->walls[wall].nextsector == g->from) continue; save = g->current; g->current = iw->walls[wall].nextsector; go_in_sector_way(iw, g, add_portal_in_way(current_way, wall)); g->current = save; } free_way(&current_way); } void get_sectors_ways2(t_sdl *iw) { t_get_sectors_ways g; g.from = -1; while (++g.from < iw->v.sc) { g.to = -1; while (++g.to < iw->v.sc) { if (g.from == g.to) continue; g.ways = 0; g.current = g.from; go_in_sector_way(iw, &g, 0); iw->ways[g.from][g.to] = g.ways; } } } void get_sectors_ways(t_sdl *iw) { int i; int j; iw->ways = (t_sector_ways ***)malloc(iw->v.sc * sizeof(t_sector_ways **)); i = -1; while (++i < iw->v.sc) { iw->ways[i] = (t_sector_ways **)malloc( iw->v.sc * sizeof(t_sector_ways *)); j = -1; while (++j < iw->v.sc) iw->ways[i][j] = 0; } get_sectors_ways2(iw); } <|start_filename|>3d/defines.h<|end_filename|> #ifndef __DEFINES_H # define __DEFINES_H # define WINDOW_W 2000 # define WINDOW_H 1100 # define MAX_SOURCE_SIZE 0x100000 # define TEXTURES_COUNT 48 # define DECOR_TEXTURES_COUNT 8 # define ENEMIES_TEXTURES_COUNT 30 # define PICK_UP_TEXTURES_COUNT 11 # define WEAPONS_TEXTURES_COUNT 19 # define COUNT_ENEMIES 3 # define G1 0.01745329f # define G90 1.5707963f # define G180 3.1415926f # define G360 6.2831852f # define MOVING_SPEED_PER_HALF_SEC 1000.0f # define ROTATION_SPEED_PER_HALF_SEC 80.0f # define MOUSE_SENSIVITY 0.002f # define MOUSE_UP_DOWN_SENSIVITY 2 # define PLAYER_HEIGHT 400 # define PLAYER_HEAD_SIZE 200 # define MAX_CLIMB_HEIGHT 300 # define JUMP_HEIGHT 1000 //# define PL_COL_SZ 10 # define COLLISION_SIZE 400 # define COLLISION_SIZE2 200 # define BUTTON_PRESS_DIST 1000 # define MENU_COLOR 0x00FF00 # define INCLINED_FC_Z 30 # define MAX_INCLINED_FC_XY 15 # define ANIMATION_TIME_SEC 1 # define COUNT_WALLS_TO_ANIM 10 # define FLY_SPEED 2000.0f # define FOOTX WINDOW_W - 150 # define FOOTY 120 # define SPRITE_HEIGHT 400 # define WEAPONS_COUNT 3 # define WEAPONS_MOVING_CHANGE_VALUE WINDOW_W / 20 # define INPUT_STRING_LEN 32 # define INPUT_LINE_LEN 200 # define USELESS1 (float)(clock() - iw->v.fly_up) # define USELESS2 (float)(clock() - iw->v.rot_left) # define USELESS3 (float)(clock() - iw->v.rot_right) # define USELESS4 WINDOW_W * sizeof(int) #ifdef __APPLE__ # define WRITE_MAP O_WRONLY | O_TRUNC # define READ_MAP O_RDONLY # define MAX_FPS 250 # define CLKS_P_S (CLOCKS_PER_SEC * 2) #elif __linux__ # define WRITE_MAP O_WRONLY | O_TRUNC # define READ_MAP O_RDONLY # define MAX_FPS 45 # define CLKS_P_S (CLOCKS_PER_SEC / 3) #else # define WRITE_MAP O_WRONLY | _O_BINARY | O_TRUNC # define READ_MAP O_RDONLY | _O_BINARY # define MAX_FPS 500 # define CLKS_P_S CLOCKS_PER_SEC #endif # define HUD_MISS_TIME CLKS_P_S / 2 # define HUD_SAVED_TIME CLKS_P_S # define ENEMY_HEALTH0 10 # define ENEMY_DAMAGE0 8 # define ENEMY_HEALTH1 20 # define ENEMY_DAMAGE1 25 # define ENEMY_HEALTH2 12 # define ENEMY_DAMAGE2 5 # define JETPACK_TIME CLKS_P_S * 10 # define CHECKPOINT_DIST 2000 # define MAP_SCALE 250 # define MUSIC_COUNT 5 # define ENV_COUNT 22 # define MAX_MUSIC_SIZE 10000000 # define CROUCH_SIZE 200 # define FALLING_DIE_SIZE 2000 # define ENEMY_SEES_PLAYER_MAX_Z_DIFF 1000 # define ENEMY_MAX_CLIMB_HEIGHT 600 # define MAX_PORTALS_IN_SECTOR_WAY 5 #endif <|start_filename|>3d/SRC3/sprites_calculation.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* sprites_calculation.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbolilyi <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/05 13:06:22 by dbolilyi #+# #+# */ /* Updated: 2019/03/05 13:06:23 by dbolilyi ### ########.fr */ /* */ /* ************************************************************************** */ #include "../guardians.h" void get_sprites_top_bottom1(t_sdl *iw, t_save_wall_pairs *tmp, t_sprite *tmp1) { int j; int jend; if ((tmp1->sx >= tmp->left->x && tmp1->sx <= tmp->right->x) || (tmp1->ex >= tmp->left->x && tmp1->ex <= tmp->right->x) || (tmp1->sx <= tmp->left->x && tmp1->ex >= tmp->right->x)) if (find_point(tmp, tmp1) == 1) { j = ft_max(tmp1->sx, ft_max(tmp->left->x, iw->d.screen_left)) - 1; jend = ft_min(tmp1->ex, ft_min(tmp->right->x, iw->d.screen_right)); while (++j <= jend) if (tmp1->top[j] == -1) { tmp1->top[j] = iw->d.top[j]; tmp1->bottom[j] = iw->d.bottom[j]; } } } void get_sprites_top_bottom(t_sdl *iw, t_save_wall_pairs *tmp) { t_sprite *tmp1; if (iw->v.kernel) { clEnqueueReadBuffer(iw->k.command_queue, iw->k.m_top, CL_TRUE, 0, (WINDOW_W + 1) * sizeof(int), iw->d.top, 0, NULL, NULL); clEnqueueReadBuffer(iw->k.command_queue, iw->k.m_bottom, CL_TRUE, 0, (WINDOW_W + 1) * sizeof(int), iw->d.bottom, 0, NULL, NULL); } tmp1 = *iw->sprite; while (tmp1 != 0) { if (!iw->sectors[tmp1->num_sec].visited || !tmp1->draweble || iw->d.cs != tmp1->num_sec) { tmp1 = tmp1->next; continue; } get_sprites_top_bottom1(iw, tmp, tmp1); tmp1 = tmp1->next; } } void switch_nexts_sprites(t_sprite *s1, t_sprite *s2) { t_sprite *tmp; t_sprite *tmp2; if (!s1 || !s2) return ; if (s2->next == s1) { s2->next = s2->next->next; s1->next = s1->next->next; s2->next->next = s1; } else { tmp = s1->next->next; s1->next->next = s2->next->next; tmp2 = s2->next; s2->next = s1->next; s1->next = tmp2; tmp2->next = tmp; } } void sort_sprites2(t_sdl *iw, t_sprite *tmp1) { t_sprite *max; t_sprite *tmp2; max = 0; tmp2 = tmp1->next; while (tmp2->next != 0) { if (iw->sectors[tmp2->next->num_sec].visited && tmp2->next->draweble) if (tmp2->next->plen > tmp1->next->plen && (max == 0 || max->next->plen < tmp2->next->plen)) max = tmp2; tmp2 = tmp2->next; } switch_nexts_sprites(max, tmp1); } void sort_sprites(t_sdl *iw) { t_sprite head; t_sprite *tmp1; if (!*iw->sprite) return ; head.next = *iw->sprite; tmp1 = &head; while (tmp1->next->next != 0) { if (!iw->sectors[tmp1->next->num_sec].visited || !tmp1->next->draweble) { tmp1 = tmp1->next; continue; } sort_sprites2(iw, tmp1); tmp1 = tmp1->next; } *iw->sprite = head.next; } <|start_filename|>3d/SRC/hud_game2.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* hud_game2.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbolilyi <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/05 15:14:46 by dbolilyi #+# #+# */ /* Updated: 2019/03/05 15:14:56 by dbolilyi ### ########.fr */ /* */ /* ************************************************************************** */ #include "../guardians.h" void draw_miss(t_sdl *iw) { SDL_Rect rect; rect.w = WINDOW_W / 10; rect.h = rect.w * iw->hud.miss->h / iw->hud.miss->w; rect.x = WINDOW_W / 2 - rect.w / 2; rect.y = WINDOW_H / 3 - WINDOW_H / 10 * (clock() - iw->hud.miss_time) / CLKS_P_S; ft_scaled_blit(iw->hud.miss, iw->sur, &rect); } void draw_save(t_sdl *iw) { SDL_Rect rect; rect.w = WINDOW_W / 4; rect.h = rect.w * iw->hud.saved->h / iw->hud.saved->w; rect.x = WINDOW_W / 2 - rect.w / 2; rect.y = 20 + WINDOW_H / 20 * (clock() - iw->hud.saved_time) / CLKS_P_S; ft_scaled_blit(iw->hud.saved, iw->sur, &rect); } <|start_filename|>3d/SRC/add_delete_picture2.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* add_delete_picture2.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbolilyi <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/05 15:13:02 by dbolilyi #+# #+# */ /* Updated: 2019/03/05 15:13:03 by dbolilyi ### ########.fr */ /* */ /* ************************************************************************** */ #include "../guardians.h" void calculate_picture2(t_wall *wall, t_picture *pic) { if (wall->y == wall->next->y) { pic->y1 = wall->y; pic->y0 = wall->y; if (wall->x > wall->next->x) { pic->x1 = wall->x - pic->left_plus; pic->x0 = pic->x1 - pic->tw; } else { pic->x1 = wall->x + pic->left_plus; pic->x0 = pic->x1 + pic->tw; } } else calculate_not_squared_wall_picture(wall, pic); } void calculate_picture(t_sdl *iw, t_wall *wall, t_picture *pic) { if (wall->x == wall->next->x) { pic->x1 = wall->x; pic->x0 = wall->x; if (wall->y > wall->next->y) { pic->y1 = wall->y - pic->left_plus; pic->y0 = pic->y1 - pic->tw; } else { pic->y1 = wall->y + pic->left_plus; pic->y0 = pic->y1 + pic->tw; } } else calculate_picture2(wall, pic); pic->zd = pic->zu - pic->tw * iw->t[pic->t]->h * 120 / iw->t[pic->t]->w / 100; } void calculate_not_squared_wall_picture(t_wall *wall, t_picture *pic) { float alpha; alpha = get_vectors_angle(wall->next->x - wall->x, wall->next->y - wall->y, ((wall->next->x > wall->x) ? 10 : -10), 0); pic->x1 = (float)wall->x + (float)pic->left_plus * cosf(alpha) * ((wall->next->x > wall->x) ? 1.0f : -1.0f); pic->y1 = (float)wall->y + (float)pic->left_plus * sinf(alpha) * ((wall->next->y > wall->y) ? 1.0f : -1.0f); pic->x0 = (float)wall->x + (float)(pic->left_plus + pic->tw) * cosf(alpha) * ((wall->next->x > wall->x) ? 1.0f : -1.0f); pic->y0 = (float)wall->y + (float)(pic->left_plus + pic->tw) * sinf(alpha) * ((wall->next->y > wall->y) ? 1.0f : -1.0f); } <|start_filename|>editor/load_map_sec.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* load_map_sec.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: kkostrub <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/05 15:47:57 by kkostrub #+# #+# */ /* Updated: 2019/03/05 17:33:54 by kkostrub ### ########.fr */ /* */ /* ************************************************************************** */ #include "doom_nuken.h" int load_map_checkpoints_1(t_doom *den, t_keyb_inp *tmp) { t_sprite *spr; int j; if (!read_check(den->fd, tmp, sizeof(t_keyb_inp))) { free(tmp); return (0); } j = -1; spr = den->sprite; while (spr && ++j < tmp->sprite_numb) spr = spr->next; if (!spr) { free(tmp); return (0); } tmp->sprite = spr; return (1); } int load_map_checkpoints(t_doom *den) { int i; int count; t_keyb_inp *tmp; den->iw.checkpoints = 0; if (!read_check(den->fd, &count, sizeof(int))) return (0); i = -1; while (++i < count) { tmp = (t_keyb_inp *)malloc(sizeof(t_keyb_inp)); if (!load_map_checkpoints_1(den, tmp)) return (0); tmp->next = den->iw.checkpoints; den->iw.checkpoints = tmp; } return (1); } int load_map_sec_1(t_doom *den, t_sector_list *tmp) { if (!read_check(den->fd, tmp, sizeof(t_sector_list))) { free(tmp); return (0); } if (tmp->fr.n != 0) { tmp->fr.n = (t_vector *)malloc(sizeof(t_vector)); if (!read_check(den->fd, tmp->fr.n, sizeof(t_vector))) { free(tmp); return (0); } } if (tmp->cl.n != 0) { tmp->cl.n = (t_vector *)malloc(sizeof(t_vector)); if (!read_check(den->fd, tmp->cl.n, sizeof(t_vector))) { free(tmp); return (0); } } return (1); } int load_map_sec_2(t_doom *den, t_sector_list *tmp) { int j; t_wals *rmp; t_picture *pic; rmp = den->tmp; j = -1; while (rmp && ++j < tmp->light_wall_numb) rmp = rmp->next; if (!rmp) { free(tmp); return (0); } pic = rmp->p; j = -1; while (pic && ++j < tmp->light_numb) pic = pic->next; if (!pic) { free(tmp); return (0); } tmp->light = pic; return (1); } int load_map_sec(t_doom *den) { t_sector_list *tmp; int i; den->sectors = 0; if (!read_check(den->fd, &den->sec, sizeof(int))) return (0); i = -1; while (++i < den->sec) { tmp = (t_sector_list *)malloc(sizeof(t_sector_list)); if (!load_map_sec_1(den, tmp)) return (0); if (tmp->light != 0) if (!load_map_sec_2(den, tmp)) return (0); tmp->next = den->sectors; den->sectors = tmp; } den->secbak = den->sec; den->secbaktmp = den->sec; return (1); } <|start_filename|>3d/SRC/player_moving.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* player_moving.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbolilyi <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/01 16:00:55 by dbolilyi #+# #+# */ /* Updated: 2019/03/01 16:04:37 by dbolilyi ### ########.fr */ /* */ /* ************************************************************************** */ #include "../guardians.h" void move_in_portal(t_sdl *iw, t_move *d) { int nx; int ny; int savecs; int nszu; int nszd; nx = iw->p.x + d->dx + iw->walls[d->sw->nextsector_wall].x - d->sw->next->x; ny = iw->p.y + d->dy + iw->walls[d->sw->nextsector_wall].y - d->sw->next->y; savecs = iw->d.cs; iw->d.cs = d->sw->nextsector; nszu = get_ceil_z(iw, nx, ny); nszd = get_floor_z(iw, nx, ny); iw->d.cs = savecs; if (nszu - nszd >= PLAYER_HEIGHT + PLAYER_HEAD_SIZE - iw->v.crouch && (nszd <= iw->p.z || nszd - iw->p.z + PLAYER_HEIGHT < MAX_CLIMB_HEIGHT) && (nszu >= iw->p.z + PLAYER_HEAD_SIZE - iw->v.crouch) && in_sec_xy(iw, d->sw->nextsector, nx, ny)) { iw->p.x = nx; iw->p.y = ny; iw->d.cs = d->sw->nextsector; } else move_collisions(iw, d->dx, d->dy, d->tmp); } void move3(t_sdl *iw, t_move *d) { if (in_sec_xy(iw, iw->d.cs, iw->p.x + d->dx, iw->p.y + d->dy)) { if (in_sec_xy(iw, iw->d.cs, iw->p.x + d->dx * d->tmp, iw->p.y + d->dy * d->tmp) || ((d->sw = is_wall_portal(iw, d->dx * d->tmp, d->dy * d->tmp)) != 0 && d->sw->glass < 0)) { iw->p.x += d->dx + ((d->dx < 0) ? 1 : -1); iw->p.y += d->dy + ((d->dy < 0) ? 1 : -1); } else move_collisions(iw, d->dx, d->dy, d->tmp); } else if ((d->sw = is_wall_portal(iw, d->dx, d->dy)) == 0 || d->sw->glass >= 0) move_collisions(iw, d->dx, d->dy, d->tmp); else move_in_portal(iw, d); } void move2(t_sdl *iw, t_move *d) { if (iw->v.fly_mode == 2) { if ((d->sw = is_wall_portal(iw, d->dx, d->dy)) == 0) { iw->p.x += d->dx; iw->p.y += d->dy; } else { iw->p.x += d->dx + iw->walls[d->sw->nextsector_wall].x - d->sw->next->x; iw->p.y += d->dy + iw->walls[d->sw->nextsector_wall].y - d->sw->next->y; } return ; } d->tmp = COLLISION_SIZE / (int)(sqrtf(powf((float)d->dx, 2.0f) + powf((float)d->dy, 2.0f)) + 1.0f); move3(iw, d); } void move1(t_move *d) { if (d->ang < 90) { d->dx = (int)(d->speed * cosf(d->ang)) * 2; d->dy = (int)(-d->speed * sinf(d->ang)) * 2; } else if (d->ang < 180) { d->dx = (int)(-d->speed * cosf(G180 - d->ang)) * 2; d->dy = (int)(-d->speed * sinf(G180 - d->ang)) * 2; } else if (d->ang < 270) { d->dx = (int)(d->speed * cosf(d->ang) - G180) * 2; d->dy = (int)(-d->speed * sinf(d->ang) - G180) * 2; } else { d->dx = (int)(d->speed * cosf(G360 - d->ang)) * 2; d->dy = (int)(d->speed * sinf(G360 - d->ang)) * 2; } } void move(t_sdl *iw, int pl, clock_t *time) { t_move d; d.ang = (iw->p.rot + (float)pl * G1); while (d.ang >= G360) d.ang -= G360; d.speed = (float)iw->v.sprint * MOVING_SPEED_PER_HALF_SEC * ((float)(clock() - *time) / (float)CLKS_P_S); *time = clock(); move1(&d); move2(iw, &d); } <|start_filename|>libft/ft_itoa.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_itoa.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbolilyi <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/03/27 15:04:43 by dbolilyi #+# #+# */ /* Updated: 2018/04/01 20:58:14 by dbolilyi ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" static char *check2_ft_itoa(int n) { char *s; if (n == -2147483648) { s = (char *)malloc(12 * sizeof(char)); s = ft_strcpy(s, "-2147483648"); return (s); } if (n == 0) { s = (char *)malloc(2 * sizeof(char)); s[0] = '0'; s[1] = '\0'; return (s); } return (0); } static char *check_ft_itoa(int *n, int *len, char *min, long int *k) { char *s; s = check2_ft_itoa(*n); if (s != 0) return (s); if (*n < 0) { *len = 2; *n = -1 * (*n); *min = 1; } else *len = 1; *k = 1; while ((*n / *k) != 0) { *k *= 10; (*len)++; } return (0); } static void assign_ft_itoa(char *s, int len, int n, long int k) { while (len-- > 0) { *(s++) = (n / k) + 48; n -= (n / k) * k; k /= 10; } *s = '\0'; } char *ft_itoa(int n) { char *s; char *tmp; int len; char min; long int k; min = 0; s = check_ft_itoa(&n, &len, &min, &k); if (s != 0) return (s); s = (char *)malloc((len--) * sizeof(char)); if (s == 0) return (0); tmp = s; if (min == 1) { *s = '-'; tmp = s; len--; s++; } k /= 10; assign_ft_itoa(s, len, n, k); return (tmp); } <|start_filename|>3d/SRC/draw_hud2.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* draw_hud2.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbolilyi <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/05 15:21:09 by dbolilyi #+# #+# */ /* Updated: 2019/03/05 15:21:11 by dbolilyi ### ########.fr */ /* */ /* ************************************************************************** */ #include "../guardians.h" void draw_selected_sprite(t_sdl *iw) { SDL_Rect rect; if (iw->v.game_mode) return ; rect.x = WINDOW_W - 110; rect.y = 130; rect.w = 100; rect.h = 100; if (iw->v.selected_sprite_type == 0) ft_scaled_blit(iw->t_decor[iw->v.selected_sprite], iw->sur, &rect); else if (iw->v.selected_sprite_type == 1) ft_scaled_blit(iw->t_pickup[iw->v.selected_sprite], iw->sur, &rect); else if (iw->v.selected_sprite_type == 2) { if (iw->v.selected_sprite == 0) ft_scaled_blit(iw->t_enemies[0], iw->sur, &rect); else if (iw->v.selected_sprite == 1) ft_scaled_blit(iw->t_enemies[8], iw->sur, &rect); else if (iw->v.selected_sprite == 2) ft_scaled_blit(iw->t_enemies[20], iw->sur, &rect); } } void draw_submenu4(t_sdl *iw) { char *s; if (iw->v.submenu_mode == 8) { draw_text(iw, "Set DY of walls animation:", WINDOW_W - 500, WINDOW_H + 110); draw_text(iw, "+100 -100 OK Exit", WINDOW_W - 450, WINDOW_H + 135); } else if (iw->v.submenu_mode == 9) { draw_text(iw, "Set speed of walls animation:", WINDOW_W - 500, WINDOW_H + 110); draw_text(iw, "Speed:", WINDOW_W - 450, WINDOW_H + 135); draw_text(iw, (s = ft_itoa(iw->v.wall_anim->speed)), WINDOW_W - 370, WINDOW_H + 135); free(s); draw_text(iw, "+ - OK Exit", WINDOW_W - 340, WINDOW_H + 135); } } void draw_submenu3(t_sdl *iw) { if (iw->v.submenu_mode == 5) { draw_text(iw, "Select walls moving type:", WINDOW_W - 500, WINDOW_H + 110); draw_text(iw, "Same Inv_X Inv_Y Exit", WINDOW_W - 450, WINDOW_H + 135); } else if (iw->v.submenu_mode == 7) { draw_text(iw, "Set DX of walls animation:", WINDOW_W - 500, WINDOW_H + 110); draw_text(iw, "+100 -100 OK Exit", WINDOW_W - 450, WINDOW_H + 135); } else draw_submenu4(iw); } void draw_submenu2(t_sdl *iw) { char *s; if (iw->v.submenu_mode == 3) { draw_text(iw, "Set speed of sector animation:", WINDOW_W - 500, WINDOW_H + 110); draw_text(iw, "Speed:", WINDOW_W - 450, WINDOW_H + 135); draw_text(iw, (s = ft_itoa(iw->v.sector_anim->speed)), WINDOW_W - 370, WINDOW_H + 135); free(s); draw_text(iw, "+ - OK Exit", WINDOW_W - 340, WINDOW_H + 135); } else if (iw->v.submenu_mode == 4) { draw_text(iw, "Choose animation:", WINDOW_W - 500, WINDOW_H + 110); draw_text(iw, "Sector Walls Exit", WINDOW_W - 450, WINDOW_H + 135); } else if (iw->v.submenu_mode == 6) { draw_text(iw, "Select walls moving priority:", WINDOW_W - 500, WINDOW_H + 110); draw_text(iw, "DXDY DYDX Exit", WINDOW_W - 450, WINDOW_H + 135); } else draw_submenu3(iw); } void draw_submenu(t_sdl *iw) { SDL_Rect rect; rect.x = WINDOW_W - 500; rect.y = WINDOW_H + 100; rect.w = 500; rect.h = 100; SDL_FillRect(iw->sur, &rect, 0x000000); if (iw->v.submenu_mode == 1) { draw_text(iw, "Choose type of sector animation:", WINDOW_W - 500, WINDOW_H + 110); draw_text(iw, "F C FC Exit", WINDOW_W - 450, WINDOW_H + 135); } else if (iw->v.submenu_mode == 2) { draw_text(iw, "Set DZ of sector animation:", WINDOW_W - 500, WINDOW_H + 110); draw_text(iw, "+100 -100 OK Exit", WINDOW_W - 450, WINDOW_H + 135); } else draw_submenu2(iw); } <|start_filename|>3d/SRC4/setup_opencl2.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* setup_opencl2.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbolilyi <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/05 17:24:31 by dbolilyi #+# #+# */ /* Updated: 2019/03/05 17:24:32 by dbolilyi ### ########.fr */ /* */ /* ************************************************************************** */ #include "../guardians.h" void get_kernels2(t_sdl *iw) { iw->k.kernel0 = clCreateKernel(iw->k.program, "draw_inclined_wall_floor_ceil_tex_kernel", &iw->k.ret); iw->k.ret = clSetKernelArg(iw->k.kernel0, 0, sizeof(cl_mem), (void *)&iw->k.m_top); iw->k.ret = clSetKernelArg(iw->k.kernel0, 1, sizeof(cl_mem), (void *)&iw->k.m_bottom); iw->k.ret = clSetKernelArg(iw->k.kernel0, 2, sizeof(cl_mem), (void *)&iw->k.m_sur); iw->k.ret = clSetKernelArg(iw->k.kernel0, 6, sizeof(cl_mem), (void *)&iw->k.m_wallTop); iw->k.ret = clSetKernelArg(iw->k.kernel0, 7, sizeof(cl_mem), (void *)&iw->k.m_wallBot); iw->k.ret = clSetKernelArg(iw->k.kernel0, 8, sizeof(cl_mem), (void *)&iw->k.m_cint); iw->k.ret = clSetKernelArg(iw->k.kernel0, 9, sizeof(cl_mem), (void *)&iw->k.m_cfloat); iw->k.kernel1 = clCreateKernel(iw->k.program, "draw_wall_floor_ceil_tex_kernel", &iw->k.ret); iw->k.ret = clSetKernelArg(iw->k.kernel1, 0, sizeof(cl_mem), (void *)&iw->k.m_top); iw->k.ret = clSetKernelArg(iw->k.kernel1, 1, sizeof(cl_mem), (void *)&iw->k.m_bottom); iw->k.ret = clSetKernelArg(iw->k.kernel1, 2, sizeof(cl_mem), (void *)&iw->k.m_sur); } void get_kernels3(t_sdl *iw) { iw->k.ret = clSetKernelArg(iw->k.kernel1, 6, sizeof(cl_mem), (void *)&iw->k.m_wallTop); iw->k.ret = clSetKernelArg(iw->k.kernel1, 7, sizeof(cl_mem), (void *)&iw->k.m_wallBot); iw->k.ret = clSetKernelArg(iw->k.kernel1, 8, sizeof(cl_mem), (void *)&iw->k.m_cint); iw->k.ret = clSetKernelArg(iw->k.kernel1, 9, sizeof(cl_mem), (void *)&iw->k.m_cfloat); iw->k.kernel2 = clCreateKernel(iw->k.program, "draw_inclined_floor_ceil_betw_walls_tex_kernel", &iw->k.ret); iw->k.ret = clSetKernelArg(iw->k.kernel2, 0, sizeof(cl_mem), (void *)&iw->k.m_top); iw->k.ret = clSetKernelArg(iw->k.kernel2, 1, sizeof(cl_mem), (void *)&iw->k.m_bottom); iw->k.ret = clSetKernelArg(iw->k.kernel2, 2, sizeof(cl_mem), (void *)&iw->k.m_sur); iw->k.ret = clSetKernelArg(iw->k.kernel2, 6, sizeof(cl_mem), (void *)&iw->k.m_wallTop); iw->k.ret = clSetKernelArg(iw->k.kernel2, 7, sizeof(cl_mem), (void *)&iw->k.m_wallBot); iw->k.ret = clSetKernelArg(iw->k.kernel2, 8, sizeof(cl_mem), (void *)&iw->k.m_cint); iw->k.ret = clSetKernelArg(iw->k.kernel2, 9, sizeof(cl_mem), (void *)&iw->k.m_cfloat); } void get_kernels4(t_sdl *iw) { iw->k.ret = clSetKernelArg(iw->k.kernel2, 10, sizeof(cl_mem), (void *)&iw->k.m_top_betw); iw->k.ret = clSetKernelArg(iw->k.kernel2, 11, sizeof(cl_mem), (void *)&iw->k.m_bot_betw); iw->k.kernel3 = clCreateKernel(iw->k.program, "draw_floor_ceil_betw_walls_tex_kernel", &iw->k.ret); clSetKernelArg(iw->k.kernel3, 0, sizeof(cl_mem), (void *)&iw->k.m_top); clSetKernelArg(iw->k.kernel3, 1, sizeof(cl_mem), (void *)&iw->k.m_bottom); clSetKernelArg(iw->k.kernel3, 2, sizeof(cl_mem), (void *)&iw->k.m_sur); clSetKernelArg(iw->k.kernel3, 6, sizeof(cl_mem), (void *)&iw->k.m_wallTop); clSetKernelArg(iw->k.kernel3, 7, sizeof(cl_mem), (void *)&iw->k.m_wallBot); clSetKernelArg(iw->k.kernel3, 8, sizeof(cl_mem), (void *)&iw->k.m_cint); clSetKernelArg(iw->k.kernel3, 9, sizeof(cl_mem), (void *)&iw->k.m_cfloat); clSetKernelArg(iw->k.kernel3, 10, sizeof(cl_mem), (void *)&iw->k.m_top_betw); clSetKernelArg(iw->k.kernel3, 11, sizeof(cl_mem), (void *)&iw->k.m_bot_betw); } <|start_filename|>editor/write_list2.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* write_list2.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbolilyi <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/11 13:01:56 by dbolilyi #+# #+# */ /* Updated: 2019/03/11 13:02:08 by dbolilyi ### ########.fr */ /* */ /* ************************************************************************** */ #include "doom_nuken.h" void check_deleting_wall_animations2(t_wall_animation *wa, int nw, int *f) { t_wall_animation *tmp; int i; i = -1; while (++i < wa->next->count_walls) { if (wa->next->walls[i] == nw) { tmp = wa->next; wa->next = wa->next->next; free(tmp); *f = 0; break ; } else if (wa->next->walls[i] > nw) wa->next->walls[i] -= 1; } } void check_deleting_wall_animations(t_doom *den, int nw) { t_wall_animation wa_start; t_wall_animation *wa; int f; wa_start.next = den->iw.wall_animations; wa = &wa_start; while (wa->next) { f = 1; check_deleting_wall_animations2(wa, nw, &f); if (f) wa = wa->next; } den->iw.wall_animations = wa_start.next; } <|start_filename|>3d/SRC3/set_defaults.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* set_defaults.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbolilyi <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/05 13:05:45 by dbolilyi #+# #+# */ /* Updated: 2019/03/05 13:05:46 by dbolilyi ### ########.fr */ /* */ /* ************************************************************************** */ #include "../guardians.h" void get_birth_def2(t_sdl *iw) { iw->v.fall = clock(); iw->v.jump_time = 1; iw->v.jump = 0; iw->v.fly_mode = 0; iw->v.fly_down = 1; iw->v.fly_up = 1; iw->p.health = 100; iw->v.jetpack = 1; iw->v.sprint = 1; iw->v.left_mouse_pressed = 0; iw->v.crouch = 0; iw->v.crouch_pressed = 0; iw->v.fall_z = iw->p.z; } void get_birth_def(t_sdl *iw) { iw->p.x = iw->l.start_x; iw->p.y = iw->l.start_y; iw->p.z = -1000000; iw->p.introt = iw->l.start_rot; iw->p.rot = (float)iw->p.introt * G1; iw->p.rotup = 0; iw->v.front = 1; iw->v.back = 1; iw->v.left = 1; iw->v.right = 1; iw->v.rot_left = 1; iw->v.rot_right = 1; iw->v.rot_up = 1; iw->v.rot_down = 1; get_birth_def2(iw); } void get_def_new3(t_sdl *iw) { int i; iw->map.back = 0; iw->map.pl_rect.x = WINDOW_W / 2 - WINDOW_W / 100; iw->map.pl_rect.y = WINDOW_H / 2 + WINDOW_H / 34; iw->map.pl_rect.w = 20; iw->map.pl_rect.h = 20; iw->menu.count = 1; iw->hud.miss_time = 1; iw->v.have_clocks = 0; iw->v.last_checkpoint = 0; iw->hud.saved_time = 1; iw->v.last_to_write = 0; iw->v.next_music = 0; Mix_VolumeMusic(15); i = -1; while (++i < ENV_COUNT) Mix_Volume(i, 60); Mix_Volume(4, 15); Mix_Volume(0, 120); Mix_VolumeChunk(iw->sounds.env[0], 64); Mix_VolumeChunk(iw->sounds.env[1], 64); get_birth_def(iw); } void get_def_new2(t_sdl *iw) { iw->v.chang_fc_rect.y = WINDOW_H + 100; iw->v.picture_changing = 0; iw->visited_sectors = 0; iw->v.f_button_mode = 0; iw->v.submenu_mode = 0; iw->v.sector_anim = 0; iw->v.wall_anim = 0; *(iw->vw_save) = 0; iw->v.sprites_select_mode = 0; iw->v.scroll_decor_sprites = 0; iw->v.scroll_pickup_sprites = 0; iw->v.selected_sprite_type = 0; iw->v.selected_sprite = 0; iw->v.sprite_editing = 0; iw->hud.rad = 100; iw->hud.shell = 100; iw->v.weapon_change_x = 0; iw->v.weapon_change_y = 20; iw->v.weapon_change_xdir = 1; iw->v.weapon_change_ydir = 1; iw->v.weapon_change_y_hide = 0; iw->bag.bag = 0; iw->bag.count_items = 0; iw->bag.selected_item = 0; get_def_new3(iw); } void get_def_new(t_sdl *iw) { iw->v.ls = 0; iw->v.angle = (float)WINDOW_W / (float)WINDOW_H * 22.0f * G1; iw->loop_update_time = clock(); iw->v.fps = 0; iw->winrect.x = 0; iw->winrect.y = 0; iw->winrect.w = WINDOW_W; iw->winrect.h = WINDOW_H; iw->v.tex_to_fill = 0; iw->v.scroll_first_tex = 0; iw->v.mouse_mode = 1; iw->v.scroll_tex_rect.h = 100; iw->v.scroll_tex_rect.w = WINDOW_W; iw->v.scroll_tex_rect.x = 0; iw->v.scroll_tex_rect.y = WINDOW_H; *(iw->v.look_wall) = 0; *(iw->v.look_sector) = 0; *(iw->v.look_picture) = 0; iw->v.look_sprite = 0; iw->v.look_portal = 0; iw->v.changing_fc = 0; iw->v.chang_fc_rect.h = 100; iw->v.chang_fc_rect.w = 40; iw->v.chang_fc_rect.x = 0; get_def_new2(iw); } <|start_filename|>3d/SRC/hud_game.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* hud_game.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbolilyi <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/02/28 16:46:03 by dbolilyi #+# #+# */ /* Updated: 2019/02/28 16:48:25 by dbolilyi ### ########.fr */ /* */ /* ************************************************************************** */ #include "../guardians.h" void drawcircle(t_hud *den, t_draw_circle *c, int x, int y) { den->koord += 4; den->mas[den->i].x = c->xc - y; den->mas[den->i].y = c->yc - x; den->mas[150 - den->i].x = c->xc - x; den->mas[150 - den->i].y = c->yc - y; den->mas[den->i + 151].x = c->xc + x; den->mas[den->i + 151].y = c->yc - y; den->mas[300 - den->i].x = c->xc + y; den->mas[300 - den->i].y = c->yc - x; den->mas2[den->i].x = c->xc - y; den->mas2[den->i].y = c->yc + x; den->mas2[150 - den->i].x = c->xc - x; den->mas2[150 - den->i].y = c->yc + y; den->mas2[den->i + 150].x = c->xc + x; den->mas2[den->i + 150].y = c->yc + y; den->mas2[300 - den->i].x = c->xc + y; den->mas2[300 - den->i].y = c->yc + x; den->i += 1; } t_draw_circle circle2(t_hud *den, int xc, int yc) { t_draw_circle c; c.xc = xc; c.yc = yc; den->koord = 0; den->i = 0; den->rect.x = FOOTX - den->rad + 20; den->rect.y = FOOTY - den->rad + 2; den->rect.h = den->rad * 2 - 5; den->rect.w = den->rad * 2 - 5; return (c); } void circle(t_hud *den, int xc, int yc) { int r; int x; int y; int d; t_draw_circle c; c = circle2(den, xc, yc); r = den->rad; x = 0; y = r; d = 3 - 2 * r; drawcircle(den, &c, x, y); while (y >= x) { x++; if (d > 0) { y--; d = d + 4 * (x - y) + 10; } else d = d + 4 * x + 6; drawcircle(den, &c, x, y); } } void ft_line2(t_sdl *iw, int x, int y, int color) { int i; i = x - 1; while (++i < x + 30) set_pixel2(iw->sur, i, y, color); } void make_health(t_hud *den, t_sdl *iw) { int i; char *s; i = -1; while (++i < (3 * iw->p.health)) ft_line2(iw, den->mas[i].x, den->mas[i].y, 0xAA0000); i = -1; while (++i < (3 * den->shell)) ft_line2(iw, den->mas2[i].x, den->mas2[i].y, 0x0000AA); ft_scaled_blit(den->enot, iw->sur, &den->rect); draw_text_blue(iw, "/", WINDOW_W - 50, 185); if (iw->guns.bullets_in_stock[iw->guns.gun_in_hands] > 0) { draw_text_blue(iw, (s = ft_itoa(iw->guns.bullets_in_stock[ iw->guns.gun_in_hands])), WINDOW_W - 40, 185); free(s); } } <|start_filename|>editor/mouse_button.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* mouse_button.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ddehtyar <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/04 16:02:06 by ddehtyar #+# #+# */ /* Updated: 2019/03/04 16:02:07 by ddehtyar ### ########.fr */ /* */ /* ************************************************************************** */ #include "doom_nuken.h" void mouse_button_down(t_doom *den, t_col *vec, int x, int y) { if (den->sec > 0 && den->blouk == 1) { den->xy.x = (((float)x - den->startx) / (START + den->skape) + 0.5); den->xy.y = (((float)y - den->starty) / (START + den->skape) + 0.5); in_all_sect(den); if (den->xy.bool_cor != -1) den->incede = 1; } coordinate_network(x, y, den, vec); save_map(x, den, vec); clean_display(den); info_display(den); } void ft_sdl_init_star(t_doom *den, t_col *vec) { den->quit = 0; den->button = 0; den->window = SDL_CreateWindow("doom_nuken", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, WIDTH, HEIGHT, 0); den->bmp = SDL_GetWindowSurface(den->window); load_image(den); SDL_FillRect(den->bmp, NULL, 0x000000); map_redactor_mane(den, vec); map_network(den); info_display(den); clear_texture(den, vec); map_network(den); if (den->sec > 0) blonk_on_now(den); info_display(den); } void key_down_but(t_doom *den, t_col *vec, const Uint8 *state) { if ((state[SDL_SCANCODE_UP]) || (state[SDL_SCANCODE_DOWN]) || (state[SDL_SCANCODE_LEFT]) || (state[SDL_SCANCODE_RIGHT])) move_scancode(den, vec, state); else if (state[SDL_SCANCODE_LSHIFT]) { den->button_change = 3; movie_button(den, vec); } if (state[SDL_SCANCODE_TAB]) { den->select = den->select == 1 ? 0 : 1; if (den->select == 0) { den->change = 0; retry_write(den, vec); } } } void mousewheel(t_doom *den, t_col *vec, int y) { if (y > 0) den->skape += 10; if (y < 0) { if (START + den->skape > 10) den->skape -= 10; } den->change = 0; clear_texture(den, vec); map_network(den); if (den->sec > 0) blonk_on_now(den); info_display(den); } void mouse_button_down_select(t_doom *den, t_col *vec, SDL_Event e) { if (den->change == 3) { retry_write(den, vec); den->change = 0; } if ((e.button.x < den->player.x * XSKAPE + 10 && e.button.x > den->player.x * XSKAPE - 10) && (e.button.y < den->player.y * YSKAPE + 10 && e.button.y > den->player.y * YSKAPE - 10)) change_way(den, 1, vec); else find_wals(e.button.x, e.button.y, den); find_sprite(den, e.button.x, e.button.y); clean_display(den); info_display(den); } <|start_filename|>editor/save2.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* save2.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: elopukh <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/05 15:39:33 by elopukh #+# #+# */ /* Updated: 2019/03/05 15:39:34 by elopukh ### ########.fr */ /* */ /* ************************************************************************** */ #define SUM WINDOW_W * 2 + 2 #include "doom_nuken.h" void save_reverse_map_pictures(t_doom *den, t_picture *pic) { if (pic->next != 0) save_reverse_map_pictures(den, pic->next); write(den->fd, pic, sizeof(t_picture)); } void save_reverse_map_walls_pictures(t_doom *den, t_wals *tmp) { int i; if (tmp->next != 0) save_reverse_map_walls_pictures(den, tmp->next); write(den->fd, tmp, sizeof(t_wals)); i = count_pictures(tmp->p); write(den->fd, &i, sizeof(int)); if (tmp->p) save_reverse_map_pictures(den, tmp->p); } void save_map_walls_pictures(t_doom *den) { int i; i = den->walls + 1; write(den->fd, &i, sizeof(int)); if (den->tmp) save_reverse_map_walls_pictures(den, den->tmp); } void save_reverse_map_sprites(t_doom *den, t_sprite *spr) { if (spr->next != 0) save_reverse_map_sprites(den, spr->next); write(den->fd, spr, sizeof(t_sprite) - sizeof(int) * (SUM)); } void save_map_sprites(t_doom *den) { write(den->fd, &den->sprites, sizeof(int)); if (den->sprite) save_reverse_map_sprites(den, den->sprite); } <|start_filename|>3d/SRC2/enemy_intelligence0.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* enemy_intelligence0.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbolilyi <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/05 12:05:15 by dbolilyi #+# #+# */ /* Updated: 2019/03/05 12:08:06 by dbolilyi ### ########.fr */ /* */ /* ************************************************************************** */ #include "../guardians.h" void enemy_intelligence0_s0(t_sdl *iw, t_sprite *s) { int i; if (clock() - s->e.previous_picture_change > CLKS_P_S / 3) { s->e.previous_picture_change = clock(); if (s->t_numb == 0) s->t_numb = 2; else s->t_numb = 0; s->t = iw->t_enemies[s->t_numb]; s->t_kernel = &iw->k.m_t_enemies[s->t_numb]; } if ((i = enemy_sees_player(iw, s)) != -1) { if ((i < 10000 || s->e.health < ENEMY_HEALTH0) && i > 800) move_enemy(iw, s); else if (i <= 800) s->e.status = 3; } else if (s->e.vis_esp.curr_sector != -1) { if ((i = (int)sqrtf(powf(s->x - s->e.vis_esp.px, 2.0f) + powf(s->y - s->e.vis_esp.py, 2.0f))) > 10) move_enemy(iw, s); } } void enemy_intelligence0_s3(t_sdl *iw, t_sprite *s) { s->e.previous_picture_change = clock(); if (s->t_numb != 3 && s->t_numb != 4) s->t_numb = 3; else if (s->t_numb == 3) { s->t_numb = 4; iw->p.health -= ENEMY_DAMAGE0 * iw->menu.count; if (!Mix_Playing(5)) Mix_PlayChannel(5, iw->sounds.env[13], 0); if (!Mix_Playing(4)) Mix_PlayChannel(4, iw->sounds.env[9], 0); } else { s->t_numb = 0; s->e.status = 0; } s->t = iw->t_enemies[s->t_numb]; s->t_kernel = &iw->k.m_t_enemies[s->t_numb]; } void enemy_intelligence0_2(t_sdl *iw, t_sprite *s) { int i; if (s->e.status == 4 && clock() - s->e.previous_picture_change > CLKS_P_S / 5) { s->e.previous_picture_change = clock(); if (s->t_numb < 5) s->t_numb = 5; else if (s->t_numb < 7) s->t_numb++; else s->e.status = 5; s->t = iw->t_enemies[s->t_numb]; s->t_kernel = &iw->k.m_t_enemies[s->t_numb]; } else if (s->e.status == 1) if (s->e.health < 10 || ((i = enemy_sees_player(iw, s)) != -1 && i < 1000)) { check_enemies_in_sector(iw, s); s->e.status = 0; s->t_numb = 0; s->t = iw->t_enemies[s->t_numb]; s->t_kernel = &iw->k.m_t_enemies[s->t_numb]; } } void enemy_intelligence0(t_sdl *iw, t_sprite *s) { if (s->e.status == 0) enemy_intelligence0_s0(iw, s); else if (s->e.status == 3 && clock() - s->e.previous_picture_change > CLKS_P_S / 5) enemy_intelligence0_s3(iw, s); else enemy_intelligence0_2(iw, s); sprite_physics(iw, s); if (s->e.health < 0 && s->e.status < 4) { Mix_PlayChannel(5, iw->sounds.env[20], 0); s->e.status = 4; } } <|start_filename|>editor/save1.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* save1.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: elopukh <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/05 15:35:34 by elopukh #+# #+# */ /* Updated: 2019/03/05 15:35:35 by elopukh ### ########.fr */ /* */ /* ************************************************************************** */ #include "doom_nuken.h" int func1(t_sector_list *sec, t_picture *pic, int num_wall, int num_pic) { if (pic == sec->light) { sec->light_wall_numb = num_wall; sec->light_numb = num_pic; return (1); } return (0); } void set_sector_wall_light_numbs(t_doom *den, t_sector_list *sec) { t_wals *tmp; t_picture *pic; int num_wall; int num_pic; if (sec->light == 0) return ; tmp = den->tmp; num_wall = 0; while (tmp) { pic = tmp->p; num_pic = 0; while (pic) { if (func1(sec, pic, num_wall, num_pic) == 1) return ; pic = pic->next; num_pic++; } tmp = tmp->next; num_wall++; } } void save_reverse_map_sec(t_doom *den, t_sector_list *tmp) { if (tmp->next != 0) save_reverse_map_sec(den, tmp->next); set_sector_wall_light_numbs(den, tmp); write(den->fd, tmp, sizeof(t_sector_list)); if (tmp->fr.n != 0) write(den->fd, tmp->fr.n, sizeof(t_vector)); if (tmp->cl.n != 0) write(den->fd, tmp->cl.n, sizeof(t_vector)); } void save_map_sec(t_doom *den) { int i; i = den->sec; write(den->fd, &i, sizeof(int)); if (den->sectors) save_reverse_map_sec(den, den->sectors); } int count_pictures(t_picture *pic) { int i; i = 0; while (pic) { i++; pic = pic->next; } return (i); } <|start_filename|>3d/SRC3/get_start_draw_vectors_lines.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* get_start_draw_vectors_lines.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbolilyi <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/05 13:05:09 by dbolilyi #+# #+# */ /* Updated: 2019/03/05 13:05:10 by dbolilyi ### ########.fr */ /* */ /* ************************************************************************** */ #include "../guardians.h" void get_direction(t_sdl *iw) { if (iw->p.rot > G90 && iw->p.rot < G90 * 3) iw->d.view_dir.x = -1; else iw->d.view_dir.x = 1; if (iw->p.rot < G180) iw->d.view_dir.y = -1; else iw->d.view_dir.y = 1; } void get_screen_line(t_sdl *iw) { float na; na = iw->p.rot + G90; if (na > G360) na -= G360; na = get_k_angle(na); iw->d.screen.a = tanf(na); iw->d.screen.b = -1.0f; iw->d.screen.c = (float)iw->p.y - iw->d.screen.a * (float)iw->p.x; iw->d.screen_len = sqrtf(iw->d.screen.a * iw->d.screen.a + iw->d.screen.b * iw->d.screen.b); } void get_left_right_lines_points2(t_sdl *iw) { float na; float nk; na = iw->p.rot + iw->v.angle; if (na > G360) na -= G360; nk = get_k_angle(na); iw->d.right_line.a = tanf(nk); iw->d.right_line.b = -1.0f; iw->d.right_line.c = (float)iw->p.y - iw->d.right_line.a * (float)iw->p.x; if (na < 180.0f * G1) iw->d.right_point.y = (float)iw->p.y - 1.0f; else iw->d.right_point.y = (float)iw->p.y + 1.0f; iw->d.right_point.x = (iw->d.right_line.b * iw->d.right_point.y + iw->d.right_line.c) / (-iw->d.right_line.a); } void get_left_right_lines_points(t_sdl *iw) { float na; float nk; na = iw->p.rot - iw->v.angle; if (na < 0.0f) na += G360; nk = get_k_angle(na); iw->d.left_line.a = tanf(nk); iw->d.left_line.b = -1.0f; iw->d.left_line.c = (float)iw->p.y - iw->d.left_line.a * (float)iw->p.x; if (na < 180.0f * G1) iw->d.left_point.y = (float)iw->p.y - 1.0f; else iw->d.left_point.y = (float)iw->p.y + 1.0f; iw->d.left_point.x = (iw->d.left_line.b * iw->d.left_point.y + iw->d.left_line.c) / (-iw->d.left_line.a); get_left_right_lines_points2(iw); } float get_k_angle(float rot) { if (rot < G180) return (G180 - rot); else return (G360 - rot); } <|start_filename|>editor/save_list.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* save_list.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ddehtyar <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/02/04 13:02:37 by ddehtyar #+# #+# */ /* Updated: 2019/02/04 13:02:38 by ddehtyar ### ########.fr */ /* */ /* ************************************************************************** */ #include "doom_nuken.h" void save_list_help(t_doom *den, t_col *vec) { if (den->button == 1) { ft_lstnewmap(&den->tmp, vec->x1, vec->y1, den); ft_lstnewmap_sec(&den->tmp, vec->x2, vec->y2, den); } else { ft_lstnewmap(&den->tmp, vec->x2, vec->y2, den); ft_lstnewmap_sec(&den->tmp, vec->x1, vec->y1, den); } } void save_list(t_doom *den, t_col *vec) { save_list_help(den, vec); if (den->sec != den->secbak) { if (den->secbak == -1) { den->xsec = den->tmp->x; den->ysec = den->tmp->y; } den->secbak += 1; if (den->sec > 0) clean_vec(vec); } } void save_map_help_two(t_doom *den, t_col *vec) { if (vec->x1 > LIM && vec->x2 > LIM && vec->y1 > LIM && vec->y2 > LIM) { if ((vec->xmod - den->startx) / (START + den->skape) == den->xsec && (vec->ymod - den->starty) / (START + den->skape) == den->ysec) den->sec += 1; ft_line(den, vec); den->walls += 1; if (den->sec != den->secbak && den->secbak >= 0) { den->blouk = 1; save_list(den, vec); den->button = 0; } else save_list(den, vec); } } void save_map_help(t_doom *den, t_col *vec) { if ((den->blouk == 1 && den->secbak > -1) || (den->xsec == LIM && den->ysec == LIM && den->sec > 0)) { if (den->button == 1) { den->xsec = (vec->x2 - den->startx) / (START + den->skape); den->ysec = (vec->y2 - den->starty) / (START + den->skape); } else if (den->button == 0) { den->xsec = (vec->x1 - den->startx) / (START + den->skape); den->ysec = (vec->y1 - den->starty) / (START + den->skape); } den->secbaktmp = den->sec; den->blouk = 0; } save_map_help_two(den, vec); } void save_map(int x, t_doom *den, t_col *vec) { if (den->button == 0 && x < den->border && (vec->xmod != vec->x2 || vec->ymod != vec->y2)) { vec->x1 = vec->xmod; vec->y1 = vec->ymod; pixel_bigwidth(den, vec->x1, vec->y1, 0x00FF00); } else if (den->button == 1 && x < den->border && (vec->xmod != vec->x1 || vec->ymod != vec->y1)) { vec->x2 = vec->xmod; vec->y2 = vec->ymod; pixel_bigwidth(den, vec->x2, vec->y2, 0x00FF00); } else if ((vec->xmod == vec->x1 && vec->ymod == vec->y1) || (vec->xmod == vec->x2 && vec->ymod == vec->y2)) den->button = den->button == 1 ? 0 : 1; save_map_help(den, vec); } <|start_filename|>editor/load_map_tex.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* load_map_tex.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: kkostrub <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/05 15:48:08 by kkostrub #+# #+# */ /* Updated: 2019/03/05 17:03:23 by kkostrub ### ########.fr */ /* */ /* ************************************************************************** */ #include "doom_nuken.h" int read_check(int fd, void *dst, size_t max_inp) { size_t i; if ((i = read(fd, dst, max_inp)) != max_inp) return (0); return (1); } int load_map_texture(int fd, t_packaging_texture **t, int count) { int i; i = -1; while (++i < count) { t[i] = (t_packaging_texture *)malloc(sizeof(t_packaging_texture)); if (!read_check(fd, t[i], sizeof(t_packaging_texture))) return (0); t[i]->pixels = malloc(t[i]->pitch * t[i]->h); if (!read_check(fd, t[i]->pixels, t[i]->pitch * t[i]->h)) return (0); } return (1); } int load_map_textures2(t_doom *den, int i) { if (!read_check(den->fd, &i, sizeof(int)) || i != 0) return (0); if (!load_map_texture(den->fd, &den->iw.hud.dead, 1)) return (0); if (!read_check(den->fd, &i, sizeof(int)) || i != 0) return (0); if (!load_map_texture(den->fd, &den->iw.hud.win, 1)) return (0); if (!read_check(den->fd, &i, sizeof(int)) || i != 0) return (0); if (!load_map_texture(den->fd, den->iw.bag.button, 3)) return (0); if (!read_check(den->fd, &i, sizeof(int)) || i != 0) return (0); if (!load_map_texture(den->fd, &den->iw.map.player, 1)) return (0); if (!read_check(den->fd, &i, sizeof(int)) || i != 0) return (0); if (!load_map_texture(den->fd, den->iw.menu.icons, 6)) return (0); if (!read_check(den->fd, &i, sizeof(int)) || i != 0) return (0); return (1); } int load_map_textures1(t_doom *den, int i) { if (!read_check(den->fd, &i, sizeof(int)) || i != 0) return (0); if (!load_map_texture(den->fd, (t_packaging_texture **)den->iw.t_enemies, ENEMIES_TEXTURES_COUNT)) return (0); if (!read_check(den->fd, &i, sizeof(int)) || i != 0) return (0); if (!load_map_texture(den->fd, (t_packaging_texture **)den->iw.t_weap, WEAPONS_TEXTURES_COUNT)) return (0); if (!read_check(den->fd, &i, sizeof(int)) || i != 0) return (0); if (!load_map_texture(den->fd, &den->iw.hud.enot, 1)) return (0); if (!read_check(den->fd, &i, sizeof(int)) || i != 0) return (0); if (!load_map_texture(den->fd, &den->iw.hud.miss, 1)) return (0); if (!read_check(den->fd, &i, sizeof(int)) || i != 0) return (0); if (!load_map_texture(den->fd, &den->iw.hud.saved, 1)) return (0); if (!load_map_textures2(den, i)) return (0); return (1); } int load_map_textures(t_doom *den) { int i; if (!load_map_texture(den->fd, (t_packaging_texture **)den->iw.t, TEXTURES_COUNT)) return (0); if (!read_check(den->fd, (void *)den->iw.tsz, sizeof(float) * TEXTURES_COUNT)) return (0); if (!read_check(den->fd, &i, sizeof(int)) || i != 0) return (0); if (!load_map_texture(den->fd, (t_packaging_texture **)den->iw.t_decor, DECOR_TEXTURES_COUNT)) return (0); if (!read_check(den->fd, &i, sizeof(int)) || i != 0) return (0); if (!load_map_texture(den->fd, (t_packaging_texture **)den->iw.t_pickup, PICK_UP_TEXTURES_COUNT)) return (0); if (!load_map_textures1(den, i)) return (0); return (1); } <|start_filename|>3d/SRC3/draw_get_between_sectors_walls.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* draw_get_between_sectors_walls.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbolilyi <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/05 13:02:46 by dbolilyi #+# #+# */ /* Updated: 2019/03/05 13:02:47 by dbolilyi ### ########.fr */ /* */ /* ************************************************************************** */ #include "../guardians.h" void get_between_sectors_walls2(t_sdl *iw, t_save_wall *left, t_save_wall *right, int **top) { int lz; int rz; t_draw_line l; l.x0 = left->x; l.x1 = right->x; lz = get_ceil_z(iw, left->p.x + iw->walls[left->wall->nextsector_wall].x - left->wall->next->x, left->p.y + iw->walls [left->wall->nextsector_wall].y - left->wall->next->y); rz = get_ceil_z(iw, right->p.x + iw->walls[left->wall->nextsector_wall].x - left->wall->next->x, right->p.y + iw->walls [left->wall->nextsector_wall].y - left->wall->next->y); l.y0 = WINDOW_H * (iw->p.z + (int)left->plen / 2 - lz) / (int)left->plen + iw->p.rotup; l.y1 = WINDOW_H * (iw->p.z + (int)right->plen / 2 - rz) / (int)right->plen + iw->p.rotup; brez_line(*top, l); } int *get_between_sectors_walls(t_sdl *iw, t_save_wall *left, t_save_wall *right, int **top) { t_draw_line l; int lz; int rz; int *bottom; bottom = (int *)malloc((right->x - left->x + 1) * sizeof(int)); *top = (int *)malloc((right->x - left->x + 1) * sizeof(int)); l.x0 = left->x; l.x1 = right->x; lz = get_floor_z(iw, left->p.x + iw->walls[left->wall->nextsector_wall].x - left->wall->next->x, left->p.y + iw->walls [left->wall->nextsector_wall].y - left->wall->next->y); rz = get_floor_z(iw, right->p.x + iw->walls[left->wall->nextsector_wall].x - left->wall->next->x, right->p.y + iw->walls [left->wall->nextsector_wall].y - left->wall->next->y); l.y0 = WINDOW_H * (iw->p.z + (int)left->plen / 2 - lz) / (int)left->plen + iw->p.rotup; l.y1 = WINDOW_H * (iw->p.z + (int)right->plen / 2 - rz) / (int)right->plen + iw->p.rotup; brez_line(bottom, l); get_between_sectors_walls2(iw, left, right, top); return (bottom); } void fill_portal(t_sdl *iw, t_save_wall *left, t_save_wall *right, t_sdl *iw2) { int j; j = left->x - 1; while (++j < right->x) { if (iw2->d.top[j] > iw->d.top[j]) iw->d.top[j] = iw2->d.top[j]; if (iw2->d.bottom[j] < iw->d.bottom[j]) iw->d.bottom[j] = iw2->d.bottom[j]; } } void fill_top_skybox(t_sdl *iw2, t_save_wall *left, int len) { int i; i = -1; while (++i < len) if (iw2->d.wallTop[i] > iw2->d.top[left->x + i]) iw2->d.top[left->x + i] = iw2->d.wallTop[i]; } void fill_tb_by_slsr(t_sdl *iw) { int i; i = -1; while (++i < iw->d.screen_left) iw->d.top[i] = iw->d.bottom[i]; i = iw->d.screen_right - 1; while (++i <= WINDOW_W) iw->d.top[i] = iw->d.bottom[i]; } <|start_filename|>3d/SRC2/read_from_files2.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* read_from_files2.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbolilyi <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/05 16:48:36 by dbolilyi #+# #+# */ /* Updated: 2019/03/05 16:48:37 by dbolilyi ### ########.fr */ /* */ /* ************************************************************************** */ #include "../guardians.h" void read_textures3(t_sdl *iw) { iw->t_sur[24] = SDL_LoadBMP("textures/24.bmp"); iw->tsz[24] = 1.0f; iw->bag.button_sur[0] = SDL_LoadBMP("interface_textures/backpack/frame.bmp"); iw->bag.button_sur[1] = SDL_LoadBMP("interface_textures/backpack/del.bmp"); iw->bag.button_sur[2] = SDL_LoadBMP("interface_textures/backpack/ok.bmp"); iw->menu.icons_sur[0] = SDL_LoadBMP("interface_textures/menu/0.bmp"); iw->menu.icons_sur[1] = SDL_LoadBMP("interface_textures/menu/1.bmp"); iw->menu.icons_sur[2] = SDL_LoadBMP("interface_textures/menu/2.bmp"); iw->menu.icons_sur[3] = SDL_LoadBMP("interface_textures/menu/3.bmp"); iw->menu.icons_sur[4] = SDL_LoadBMP("interface_textures/menu/4.bmp"); iw->menu.icons_sur[5] = SDL_LoadBMP("interface_textures/menu/5.bmp"); iw->map.player_sur = SDL_LoadBMP("interface_textures/map/player.bmp"); iw->hud.enot_sur = SDL_LoadBMP("interface_textures/HUD/enot.bmp"); iw->hud.miss_sur = SDL_LoadBMP("interface_textures/HUD/miss.bmp"); iw->hud.dead_sur = SDL_LoadBMP("interface_textures/HUD/groot_lose.bmp"); iw->hud.win_sur = SDL_LoadBMP("interface_textures/HUD/groot_win.bmp"); iw->hud.saved_sur = SDL_LoadBMP("interface_textures/HUD/saved.bmp"); } void read_textures2_1(t_sdl *iw) { iw->t_sur[25] = SDL_LoadBMP("textures/25.bmp"); iw->tsz[25] = 2.5f; iw->t_sur[26] = SDL_LoadBMP("textures/26.bmp"); iw->tsz[26] = 1.0f; iw->t_sur[27] = SDL_LoadBMP("textures/27.bmp"); iw->tsz[27] = 1.0f; iw->t_sur[28] = SDL_LoadBMP("textures/28.bmp"); iw->tsz[28] = 1.0f; iw->t_sur[29] = SDL_LoadBMP("textures/29.bmp"); iw->tsz[29] = 1.0f; iw->t_sur[30] = SDL_LoadBMP("textures/30.bmp"); iw->tsz[30] = 1.0f; iw->t_sur[31] = SDL_LoadBMP("textures/31.bmp"); iw->tsz[31] = 1.0f; iw->t_sur[32] = SDL_LoadBMP("textures/32.bmp"); iw->tsz[32] = 1.0f; iw->t_sur[33] = SDL_LoadBMP("textures/33.bmp"); iw->tsz[33] = 1.0f; iw->t_sur[34] = SDL_LoadBMP("textures/34.bmp"); iw->tsz[34] = 1.0f; iw->t_sur[35] = SDL_LoadBMP("textures/35.bmp"); iw->tsz[35] = 2.5f; iw->t_sur[36] = SDL_LoadBMP("textures/36.bmp"); iw->tsz[36] = 2.5f; iw->t_sur[37] = SDL_LoadBMP("textures/37.bmp"); iw->tsz[37] = 1.0f; iw->t_sur[38] = SDL_LoadBMP("textures/38.bmp"); iw->tsz[38] = 5.0f; iw->t_sur[39] = SDL_LoadBMP("textures/39.bmp"); iw->tsz[39] = 1.0f; iw->t_sur[40] = SDL_LoadBMP("textures/40.bmp"); iw->tsz[40] = 1.0f; iw->t_sur[41] = SDL_LoadBMP("textures/41.bmp"); iw->tsz[41] = 0.666666f; iw->t_sur[42] = SDL_LoadBMP("textures/42.bmp"); iw->tsz[42] = 1.0f; iw->t_sur[43] = SDL_LoadBMP("textures/43.bmp"); iw->tsz[43] = 1.0f; iw->t_sur[44] = SDL_LoadBMP("textures/44.bmp"); iw->tsz[44] = 1.0f; iw->t_sur[45] = SDL_LoadBMP("textures/45.bmp"); iw->tsz[45] = 2.0f; iw->t_sur[46] = SDL_LoadBMP("textures/46.bmp"); iw->tsz[46] = 2.0f; iw->t_sur[47] = SDL_LoadBMP("textures/47.bmp"); iw->tsz[47] = 1.0f; } void read_textures2(t_sdl *iw) { iw->t_sur[12] = SDL_LoadBMP("textures/12.bmp"); iw->tsz[12] = 1.0f; iw->t_sur[13] = SDL_LoadBMP("textures/13.bmp"); iw->tsz[13] = 1.0f; iw->t_sur[14] = SDL_LoadBMP("textures/14.bmp"); iw->tsz[14] = 1.0f; iw->t_sur[15] = SDL_LoadBMP("textures/15.bmp"); iw->tsz[15] = 1.0f; iw->t_sur[16] = SDL_LoadBMP("textures/16.bmp"); iw->tsz[16] = 1.0f; iw->t_sur[17] = SDL_LoadBMP("textures/17.bmp"); iw->tsz[17] = 1.0f; iw->t_sur[18] = SDL_LoadBMP("textures/18.bmp"); iw->tsz[18] = 1.0f; iw->t_sur[19] = SDL_LoadBMP("textures/19.bmp"); iw->tsz[19] = 1.0f; iw->t_sur[20] = SDL_LoadBMP("textures/20.bmp"); iw->tsz[20] = 1.0f; iw->t_sur[21] = SDL_LoadBMP("textures/21.bmp"); iw->tsz[21] = 1.0f; iw->t_sur[22] = SDL_LoadBMP("textures/22.bmp"); iw->tsz[22] = 1.0f; iw->t_sur[23] = SDL_LoadBMP("textures/23.bmp"); iw->tsz[23] = 1.0f; read_textures2_1(iw); read_textures3(iw); } void read_textures(t_sdl *iw) { iw->t_sur[0] = SDL_LoadBMP("textures/0.bmp"); iw->tsz[0] = 1.0f; iw->t_sur[1] = SDL_LoadBMP("textures/1.bmp"); iw->tsz[1] = 1.0f; iw->t_sur[2] = SDL_LoadBMP("textures/2.bmp"); iw->tsz[2] = 1.0f; iw->t_sur[3] = SDL_LoadBMP("textures/3.bmp"); iw->tsz[3] = 1.0f; iw->t_sur[4] = SDL_LoadBMP("textures/4.bmp"); iw->tsz[4] = 1.0f; iw->t_sur[5] = SDL_LoadBMP("textures/5.bmp"); iw->tsz[5] = 1.0f; iw->t_sur[6] = SDL_LoadBMP("textures/6.bmp"); iw->tsz[6] = 1.0f; iw->t_sur[7] = SDL_LoadBMP("textures/7.bmp"); iw->tsz[7] = 1.0f; iw->t_sur[8] = SDL_LoadBMP("textures/8.bmp"); iw->tsz[8] = 1.0f; iw->t_sur[9] = SDL_LoadBMP("textures/9.bmp"); iw->tsz[9] = 1.0f; iw->t_sur[10] = SDL_LoadBMP("textures/10.bmp"); iw->tsz[10] = 1.0f; iw->t_sur[11] = SDL_LoadBMP("textures/11.bmp"); iw->tsz[11] = 1.0f; read_textures2(iw); } void read_sprites_textures2(t_sdl *iw) { iw->t_enemies_sur[16] = SDL_LoadBMP("sprites/enemies/16.bmp"); iw->t_enemies_sur[17] = SDL_LoadBMP("sprites/enemies/17.bmp"); iw->t_enemies_sur[18] = SDL_LoadBMP("sprites/enemies/18.bmp"); iw->t_enemies_sur[19] = SDL_LoadBMP("sprites/enemies/19.bmp"); iw->t_enemies_sur[20] = SDL_LoadBMP("sprites/enemies/20.bmp"); iw->t_enemies_sur[21] = SDL_LoadBMP("sprites/enemies/21.bmp"); iw->t_enemies_sur[22] = SDL_LoadBMP("sprites/enemies/22.bmp"); iw->t_enemies_sur[23] = SDL_LoadBMP("sprites/enemies/23.bmp"); iw->t_enemies_sur[24] = SDL_LoadBMP("sprites/enemies/24.bmp"); iw->t_enemies_sur[25] = SDL_LoadBMP("sprites/enemies/25.bmp"); iw->t_enemies_sur[26] = SDL_LoadBMP("sprites/enemies/26.bmp"); iw->t_enemies_sur[27] = SDL_LoadBMP("sprites/enemies/27.bmp"); iw->t_enemies_sur[28] = SDL_LoadBMP("sprites/enemies/28.bmp"); iw->t_enemies_sur[29] = SDL_LoadBMP("sprites/enemies/29.bmp"); iw->t_pickup_sur[0] = SDL_LoadBMP("sprites/to_pick_up/0.bmp"); iw->t_pickup_sur[1] = SDL_LoadBMP("sprites/to_pick_up/1.bmp"); iw->t_pickup_sur[2] = SDL_LoadBMP("sprites/to_pick_up/2.bmp"); iw->t_pickup_sur[3] = SDL_LoadBMP("sprites/to_pick_up/3.bmp"); iw->t_pickup_sur[4] = SDL_LoadBMP("sprites/to_pick_up/4.bmp"); iw->t_pickup_sur[5] = SDL_LoadBMP("sprites/to_pick_up/5.bmp"); iw->t_pickup_sur[6] = SDL_LoadBMP("sprites/to_pick_up/6.bmp"); iw->t_pickup_sur[7] = SDL_LoadBMP("sprites/to_pick_up/7.bmp"); iw->t_pickup_sur[8] = SDL_LoadBMP("sprites/to_pick_up/8.bmp"); iw->t_pickup_sur[9] = SDL_LoadBMP("sprites/to_pick_up/9.bmp"); iw->t_pickup_sur[10] = SDL_LoadBMP("sprites/to_pick_up/10.bmp"); } void read_sprites_textures(t_sdl *iw) { iw->t_decor_sur[0] = SDL_LoadBMP("sprites/decorations/0.bmp"); iw->t_decor_sur[1] = SDL_LoadBMP("sprites/decorations/1.bmp"); iw->t_decor_sur[2] = SDL_LoadBMP("sprites/decorations/2.bmp"); iw->t_decor_sur[3] = SDL_LoadBMP("sprites/decorations/3.bmp"); iw->t_decor_sur[4] = SDL_LoadBMP("sprites/decorations/4.bmp"); iw->t_decor_sur[5] = SDL_LoadBMP("sprites/decorations/5.bmp"); iw->t_decor_sur[6] = SDL_LoadBMP("sprites/decorations/6.bmp"); iw->t_decor_sur[7] = SDL_LoadBMP("sprites/decorations/7.bmp"); iw->t_enemies_sur[0] = SDL_LoadBMP("sprites/enemies/0.bmp"); iw->t_enemies_sur[1] = SDL_LoadBMP("sprites/enemies/1.bmp"); iw->t_enemies_sur[2] = SDL_LoadBMP("sprites/enemies/2.bmp"); iw->t_enemies_sur[3] = SDL_LoadBMP("sprites/enemies/3.bmp"); iw->t_enemies_sur[4] = SDL_LoadBMP("sprites/enemies/4.bmp"); iw->t_enemies_sur[5] = SDL_LoadBMP("sprites/enemies/5.bmp"); iw->t_enemies_sur[6] = SDL_LoadBMP("sprites/enemies/6.bmp"); iw->t_enemies_sur[7] = SDL_LoadBMP("sprites/enemies/7.bmp"); iw->t_enemies_sur[8] = SDL_LoadBMP("sprites/enemies/8.bmp"); iw->t_enemies_sur[9] = SDL_LoadBMP("sprites/enemies/9.bmp"); iw->t_enemies_sur[10] = SDL_LoadBMP("sprites/enemies/10.bmp"); iw->t_enemies_sur[11] = SDL_LoadBMP("sprites/enemies/11.bmp"); iw->t_enemies_sur[12] = SDL_LoadBMP("sprites/enemies/12.bmp"); iw->t_enemies_sur[13] = SDL_LoadBMP("sprites/enemies/13.bmp"); iw->t_enemies_sur[14] = SDL_LoadBMP("sprites/enemies/14.bmp"); iw->t_enemies_sur[15] = SDL_LoadBMP("sprites/enemies/15.bmp"); read_sprites_textures2(iw); } <|start_filename|>3d/SRC/button_f_up.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* button_f_up.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbolilyi <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/02/28 15:28:11 by dbolilyi #+# #+# */ /* Updated: 2019/02/28 15:29:47 by dbolilyi ### ########.fr */ /* */ /* ************************************************************************** */ #include "../guardians.h" void button_f_up2(t_sdl *iw) { if (iw->v.f_button_mode == 0 && *(iw->v.look_picture) != 0 && (*(iw->v.look_picture))->t == 18 && get_picture_dist(iw, *(iw->v.look_picture)) < BUTTON_PRESS_DIST) { Mix_PlayChannel(2, iw->sounds.env[16], 0); (*(iw->v.look_picture))->t = 17; } else if (iw->v.f_button_mode == 0 && *(iw->v.look_picture) != 0 && ((*(iw->v.look_picture))->t == 19 || (*(iw->v.look_picture))->t == 20) && get_picture_dist(iw, *(iw->v.look_picture)) < BUTTON_PRESS_DIST) { (*(iw->v.look_picture))->t = (((*(iw->v.look_picture))->t == 19) ? 20 : 19); change_sector_animation_status(iw, *(iw->v.look_picture)); change_wall_animation_status(iw, *(iw->v.look_picture)); Mix_PlayChannel(2, iw->sounds.env[12], 0); } else button_f_up_cards(iw); } void button_f_up(t_sdl *iw) { if (iw->v.f_button_mode == 1 && *(iw->v.look_sector) != 0) (*(iw->v.look_sector))->light = (t_picture *)iw->v.f_button_pointer; else if (iw->v.f_button_mode == 2 && *(iw->v.look_sector) != 0) { iw->v.submenu_mode = 1; add_sector_animation(iw); iw->v.f_button_mode = 0; iw->v.f_button_pointer = 0; draw_submenu(iw); } else if (iw->v.f_button_mode == 3 && *(iw->v.look_wall) != 0) add_wall_to_wall_animation(iw); else if (iw->v.f_button_mode == 0 && *(iw->v.look_picture) != 0 && (*(iw->v.look_picture))->t == 17 && get_picture_dist(iw, *(iw->v.look_picture)) < BUTTON_PRESS_DIST) { Mix_PlayChannel(2, iw->sounds.env[16], 0); (*(iw->v.look_picture))->t = 18; } else button_f_up2(iw); } <|start_filename|>editor/get_map.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* get_map.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ddehtyar <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/05 12:10:25 by ddehtyar #+# #+# */ /* Updated: 2019/03/05 12:10:26 by ddehtyar ### ########.fr */ /* */ /* ************************************************************************** */ #include "doom_nuken.h" int count_walls(t_wals *tmp, t_getmap *gm, t_sdl *iw, t_doom *den) { int len; iw->v.sc = den->sec; iw->v.ls = 0; len = 0; gm->sl = den->sectors; gm->i = -1; while (tmp != 0) { tmp->id = len; len++; tmp = tmp->next; } return (len); } void get_map_one(t_sdl *iw, t_getmap *gm) { gm->sl->id = gm->i; iw->sectors[gm->i].nw = 0; iw->sectors[gm->i].fr.n = gm->sl->fr.n; iw->sectors[gm->i].fr.z = gm->sl->fr.z; iw->sectors[gm->i].fr.t = gm->sl->fr.t; iw->sectors[gm->i].cl.n = gm->sl->cl.n; iw->sectors[gm->i].cl.z = gm->sl->cl.z; iw->sectors[gm->i].cl.t = gm->sl->cl.t; iw->sectors[gm->i].light = gm->sl->light; } void get_map_two(t_sdl *iw, t_getmap *gm) { if (gm->tmp->next_sector) { iw->walls[gm->w].nextsector = gm->tmp->next_sector->id; iw->walls[gm->w].nextsector_wall = gm->tmp->nextsector_wall->id; } else { iw->walls[gm->w].nextsector = -1; iw->walls[gm->w].nextsector_wall = -1; } if (gm->inside != gm->tmp->inside) { iw->walls[gm->w - 1].next = &iw->walls[gm->inside_start]; gm->inside_start = gm->w; gm->inside++; } else if (gm->w != iw->sectors[gm->s].sw) iw->walls[gm->w - 1].next = &iw->walls[gm->w]; else { iw->sectors[gm->s].fr.x = iw->walls[gm->w].x; iw->sectors[gm->s].fr.y = iw->walls[gm->w].y; iw->sectors[gm->s].cl.x = iw->walls[gm->w].x; iw->sectors[gm->s].cl.y = iw->walls[gm->w].y; } } void get_map_three(t_sdl *iw, t_getmap *gm) { if (gm->tmp->sec != gm->s) { iw->walls[gm->w - 1].next = &iw->walls[gm->inside_start]; gm->s++; iw->sectors[gm->s].sw = gm->w; gm->inside = 0; gm->inside_start = gm->w; } iw->sectors[gm->s].nw++; iw->walls[gm->w].x = gm->tmp->x * MAP_SCALE; iw->walls[gm->w].y = -gm->tmp->y * MAP_SCALE; iw->walls[gm->w].t = gm->tmp->tex; iw->walls[gm->w].glass = gm->tmp->glass; iw->walls[gm->w].p = gm->tmp->p; } void get_map(t_sdl *iw, t_doom *den) { t_getmap gm; gm.cw = count_walls(den->tmp, &gm, iw, den); iw->sectors = (t_sector *)malloc(iw->v.sc * sizeof(t_sector)); while (++gm.i < iw->v.sc) { get_map_one(iw, &gm); gm.sl = gm.sl->next; } iw->walls = (t_wall *)malloc(gm.cw * sizeof(t_wall)); gm.s = 0; iw->sectors[0].sw = 0; gm.w = 0; gm.inside = 0; gm.inside_start = 0; gm.tmp = den->tmp; while (gm.tmp != 0) { get_map_three(iw, &gm); get_map_two(iw, &gm); gm.w++; gm.tmp = gm.tmp->next; } iw->walls[gm.w - 1].next = &iw->walls[gm.inside_start]; *den->iw.sprite = den->sprite; } <|start_filename|>3d/SRC2/main_loops2.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* main_loops2.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbolilyi <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/05 16:44:37 by dbolilyi #+# #+# */ /* Updated: 2019/03/05 16:44:38 by dbolilyi ### ########.fr */ /* */ /* ************************************************************************** */ #include "../guardians.h" void game_start_menu(t_sdl *iw) { SDL_Rect player; SDL_Rect zast; SDL_Rect diff; game_start_menu1(iw, &player, &zast, &diff); if (iw->menu.count == 1) ft_scaled_blit(iw->menu.icons[2], iw->sur, &zast); else ft_scaled_blit(iw->menu.icons[1], iw->sur, &zast); ft_scaled_blit(iw->menu.icons[3], iw->sur, &diff); zast.y += zast.h + WINDOW_H / 10; diff.y = zast.y + (zast.h - diff.h) / 2; if (iw->menu.count == 2) ft_scaled_blit(iw->menu.icons[2], iw->sur, &zast); else ft_scaled_blit(iw->menu.icons[1], iw->sur, &zast); ft_scaled_blit(iw->menu.icons[4], iw->sur, &diff); zast.y += zast.h + WINDOW_H / 10; diff.y = zast.y + (zast.h - diff.h) / 2; if (iw->menu.count == 3) ft_scaled_blit(iw->menu.icons[2], iw->sur, &zast); else ft_scaled_blit(iw->menu.icons[1], iw->sur, &zast); ft_scaled_blit(iw->menu.icons[5], iw->sur, &diff); SDL_UpdateWindowSurface(iw->win); } <|start_filename|>3d/SRC3/checkpoints_game.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* checkpoints_game.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbolilyi <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/05 13:01:53 by dbolilyi #+# #+# */ /* Updated: 2019/03/05 13:01:54 by dbolilyi ### ########.fr */ /* */ /* ************************************************************************** */ #include "../guardians.h" void death(t_sdl *iw) { if (iw->v.game_mode && (iw->d.cs < 0 || iw->p.health < 1)) { image_loop(iw, iw->hud.dead); get_birth_def(iw); } } void set_checkpoint(t_sdl *iw, t_sprite *s) { t_keyb_inp *tmp; Mix_PlayChannel(2, iw->sounds.env[15], 0); tmp = iw->checkpoints; while (tmp) { if (tmp->sprite == s) break ; tmp = tmp->next; } if (!tmp) return ; iw->l.start_x = s->x; iw->l.start_y = s->y; iw->v.last_checkpoint = s; iw->v.last_to_write = tmp; iw->hud.saved_time = clock(); } void check_checkpoints(t_sdl *iw) { t_sprite *tmp; tmp = *iw->sprite; while (tmp) { if (tmp->type == 0 && tmp->t_numb == 1 && tmp->draweble && tmp->plen < CHECKPOINT_DIST) { if (tmp != iw->v.last_checkpoint) set_checkpoint(iw, tmp); return ; } tmp = tmp->next; } } <|start_filename|>3d/SRC/input_validation.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* input_validation.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbolilyi <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/02/28 17:04:41 by dbolilyi #+# #+# */ /* Updated: 2019/02/28 17:05:07 by dbolilyi ### ########.fr */ /* */ /* ************************************************************************** */ #include "../guardians.h" int check_textures2(t_sdl *iw) { int i; if (iw->hud.enot_sur == 0) return (0); if (iw->hud.miss_sur == 0) return (0); if (iw->hud.dead_sur == 0) return (0); if (iw->hud.win_sur == 0) return (0); i = -1; while (++i < 3) if (iw->bag.button_sur[i] == 0) return (0); if (iw->map.player_sur == 0) return (0); i = -1; while (++i < 6) if (iw->menu.icons_sur[i] == 0) return (0); return (1); } int check_textures(t_sdl *iw) { int i; i = -1; while (++i < TEXTURES_COUNT) if (iw->t_sur[i] == 0) return (0); i = -1; while (++i < DECOR_TEXTURES_COUNT) if (iw->t_decor_sur[i] == 0) return (0); i = -1; while (++i < PICK_UP_TEXTURES_COUNT) if (iw->t_pickup_sur[i] == 0) return (0); i = -1; while (++i < ENEMIES_TEXTURES_COUNT) if (iw->t_enemies_sur[i] == 0) return (0); i = -1; while (++i < WEAPONS_TEXTURES_COUNT) if (iw->t_weap_sur[i] == 0) return (0); return (check_textures2(iw)); } int check_sound(t_sdl *iw) { int i; i = -1; while (++i < MUSIC_COUNT) if (iw->sounds.music[i] == 0) return (0); i = -1; while (++i < ENV_COUNT) if (iw->sounds.env[i] == 0) return (0); return (1); } int check_all_validation(t_sdl *iw) { if (!check_textures(iw)) return (0); if (!check_sound(iw)) return (0); if (iw->k.ret != 0) return (-1); if (iw->arial_font == 0) return (0); return (1); } <|start_filename|>editor/main.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* main.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ddehtyar <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/08/26 15:54:12 by ddehtyar #+# #+# */ /* Updated: 2018/08/26 15:54:14 by ddehtyar ### ########.fr */ /* */ /* ************************************************************************** */ #include "doom_nuken.h" #include <stdio.h> void go_delete_one(t_wals *rmp, t_wals *nmp) { nmp = rmp->nextsector_wall; nmp->next_sector = 0; nmp->nextsector_wall = 0; rmp->next_sector = 0; rmp->nextsector_wall = 0; } int main_help(t_doom *den, char **argv) { if (!check_load(den, argv[2])) { write(1, "Error loading file\n", 19); return (0); } den->fd = open(den->fname, READ_MAP); if (!load_map(den)) { write(1, "Error loading file\n", 20); close(den->fd); return (0); } close(den->fd); main_edit(den); return (1); } int main_help_two(t_doom *den, char **argv) { if (!check_load(den, argv[2])) { write(1, "Error loading file\n", 19); return (0); } den->fd = open(den->fname, READ_MAP); if (!load_map(den) || !load4_game(den)) { write(1, "Error loading file\n", 20); close(den->fd); return (0); } close(den->fd); main_game(den); return (1); } int main_help_one(t_doom *den, char **argv) { if (!check_new(den, argv[2])) { write(1, "Error creating file\n", 20); return (0); } map_redactor_mane2(den); main_new(den); return (1); } int main(int argc, char **argv) { t_doom den; if (argc != 3) return (usage()); if (ft_strcmp(argv[1], "new") == 0) { if (main_help_one(&den, argv) == 0) return (0); } else if (ft_strcmp(argv[1], "edit") == 0) { if (main_help(&den, argv) == 0) return (0); } else if (ft_strcmp(argv[1], "game") == 0) { if (main_help_two(&den, argv) == 0) return (0); } else return (usage()); return (0); } <|start_filename|>3d/SRC2/read_from_files.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* read_from_files.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbolilyi <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/05 12:07:38 by dbolilyi #+# #+# */ /* Updated: 2019/03/05 12:07:39 by dbolilyi ### ########.fr */ /* */ /* ************************************************************************** */ #include "../guardians.h" void read_weapons_textures(t_sdl *iw) { iw->t_weap_sur[0] = SDL_LoadBMP("weapons/0.bmp"); iw->t_weap_sur[1] = SDL_LoadBMP("weapons/1.bmp"); iw->t_weap_sur[2] = SDL_LoadBMP("weapons/2.bmp"); iw->t_weap_sur[3] = SDL_LoadBMP("weapons/3.bmp"); iw->t_weap_sur[4] = SDL_LoadBMP("weapons/4.bmp"); iw->t_weap_sur[5] = SDL_LoadBMP("weapons/5.bmp"); iw->t_weap_sur[6] = SDL_LoadBMP("weapons/6.bmp"); iw->t_weap_sur[7] = SDL_LoadBMP("weapons/7.bmp"); iw->t_weap_sur[8] = SDL_LoadBMP("weapons/8.bmp"); iw->t_weap_sur[9] = SDL_LoadBMP("weapons/9.bmp"); iw->t_weap_sur[10] = SDL_LoadBMP("weapons/10.bmp"); iw->t_weap_sur[11] = SDL_LoadBMP("weapons/11.bmp"); iw->t_weap_sur[12] = SDL_LoadBMP("weapons/12.bmp"); iw->t_weap_sur[13] = SDL_LoadBMP("weapons/13.bmp"); iw->t_weap_sur[14] = SDL_LoadBMP("weapons/14.bmp"); iw->t_weap_sur[15] = SDL_LoadBMP("weapons/15.bmp"); iw->t_weap_sur[16] = SDL_LoadBMP("weapons/16.bmp"); iw->t_weap_sur[17] = SDL_LoadBMP("weapons/17.bmp"); iw->t_weap_sur[18] = SDL_LoadBMP("weapons/18.bmp"); } void get_sounds_game(t_sdl *iw) { int i; i = -1; while (++i < MUSIC_COUNT) { iw->sounds.music_rw[i] = SDL_RWFromConstMem(iw->sounds.music_pack[i], iw->sounds.music_pack_size[i]); iw->sounds.music[i] = Mix_LoadMUS_RW(iw->sounds.music_rw[i], 0); } } void get_music(t_sdl *iw, int i, const char *file) { void *tmp; int fd; fd = open(file, READ_MAP); if (fd < 0) { iw->sounds.music[i] = 0; return ; } tmp = malloc(MAX_MUSIC_SIZE); iw->sounds.music_pack_size[i] = read(fd, tmp, MAX_MUSIC_SIZE); close(fd); iw->sounds.music_pack[i] = malloc(iw->sounds.music_pack_size[i]); ft_memcpy(iw->sounds.music_pack[i], tmp, iw->sounds.music_pack_size[i]); free(tmp); iw->sounds.music_rw[i] = SDL_RWFromConstMem(iw->sounds.music_pack[i], iw->sounds.music_pack_size[i]); iw->sounds.music[i] = Mix_LoadMUS_RW(iw->sounds.music_rw[i], 0); } void get_sounds2(t_sdl *iw) { iw->sounds.env[0] = Mix_LoadWAV("sound/environment/0.wav"); iw->sounds.env[1] = Mix_LoadWAV("sound/environment/1.wav"); iw->sounds.env[2] = Mix_LoadWAV("sound/environment/2.wav"); iw->sounds.env[3] = Mix_LoadWAV("sound/environment/3.wav"); iw->sounds.env[4] = Mix_LoadWAV("sound/environment/4.wav"); iw->sounds.env[5] = Mix_LoadWAV("sound/environment/5.wav"); iw->sounds.env[6] = Mix_LoadWAV("sound/environment/6.wav"); iw->sounds.env[7] = Mix_LoadWAV("sound/environment/7.wav"); iw->sounds.env[8] = Mix_LoadWAV("sound/environment/8.wav"); iw->sounds.env[9] = Mix_LoadWAV("sound/environment/9.wav"); iw->sounds.env[10] = Mix_LoadWAV("sound/environment/10.wav"); iw->sounds.env[11] = Mix_LoadWAV("sound/environment/11.wav"); iw->sounds.env[12] = Mix_LoadWAV("sound/environment/12.wav"); iw->sounds.env[13] = Mix_LoadWAV("sound/environment/13.wav"); iw->sounds.env[14] = Mix_LoadWAV("sound/environment/14.wav"); iw->sounds.env[15] = Mix_LoadWAV("sound/environment/15.wav"); iw->sounds.env[16] = Mix_LoadWAV("sound/environment/16.wav"); iw->sounds.env[17] = Mix_LoadWAV("sound/environment/17.wav"); iw->sounds.env[18] = Mix_LoadWAV("sound/environment/18.wav"); iw->sounds.env[19] = Mix_LoadWAV("sound/environment/19.wav"); iw->sounds.env[20] = Mix_LoadWAV("sound/environment/20.wav"); iw->sounds.env[21] = Mix_LoadWAV("sound/environment/21.wav"); } void get_sounds(t_sdl *iw) { get_music(iw, 0, "sound/background/0.mp3"); get_music(iw, 1, "sound/background/1.mp3"); get_music(iw, 2, "sound/background/2.mp3"); get_music(iw, 3, "sound/background/3.mp3"); get_music(iw, 4, "sound/background/4.mp3"); get_sounds2(iw); } <|start_filename|>3d/SRC3/free_ways_exit_x.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* free_ways_exit_x.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbolilyi <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/05 13:04:14 by dbolilyi #+# #+# */ /* Updated: 2019/03/05 13:04:15 by dbolilyi ### ########.fr */ /* */ /* ************************************************************************** */ #include "../guardians.h" void free_sector_ways2(t_free_sector_ways *d) { d->tmp2 = d->tmp->way_start; while (d->tmp2) { d->tmp2_f = d->tmp2; d->tmp2 = d->tmp2->next; free(d->tmp2_f); } d->tmp_f = d->tmp; d->tmp = d->tmp->next; free(d->tmp_f); } void free_sector_ways(t_sdl *iw) { t_free_sector_ways d; d.i = -1; while (++d.i < iw->v.sc) { d.j = -1; while (++d.j < iw->v.sc) { d.tmp = iw->ways[d.i][d.j]; while (d.tmp) free_sector_ways2(&d); } free(iw->ways[d.i]); } free(iw->ways); } void exit_x(t_sdl *iw) { SDL_FreeSurface(iw->sur); SDL_DestroyWindow(iw->win); TTF_Quit(); SDL_Quit(); system("leaks doom-nukem"); exit(0); } <|start_filename|>editor/edit.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* edit.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ddehtyar <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/05 14:27:18 by ddehtyar #+# #+# */ /* Updated: 2019/03/05 14:27:19 by ddehtyar ### ########.fr */ /* */ /* ************************************************************************** */ #include "doom_nuken.h" int main_edit(t_doom *den) { int ret; SDL_Init(SDL_INIT_EVERYTHING); TTF_Init(); Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 2048); ret = get_3d_def_edit(den); if (ret == 0) { write(1, "Error, check your files which need to be exist\n", 47); return (0); } else if (ret == -1) { write(1, "OpenCL initialization error\n", 28); den->iw.v.kernel = 0; } den->color = 0xFFFFFF; den->b_color = 0x505050; ft_sdl_init(den); return (0); } int get_3d_def_edit(t_doom *den) { int ret; den->iw.v.game_mode = 0; den->iw.v.kernel = 1; den->iw.v.look_wall = (t_wall **)malloc(sizeof(t_wall *)); den->iw.v.look_sector = (t_sector **)malloc(sizeof(t_sector *)); den->iw.v.look_picture = (t_picture **)malloc(sizeof(t_picture *)); den->iw.sprite = (t_sprite **)malloc(sizeof(t_sprite *)); den->iw.vw_save = (t_save_wall **)malloc(sizeof(t_save_wall *)); get_font_file(den); load_kernel(&den->iw.k, &den->iw); read_textures(&den->iw); read_sprites_textures(&den->iw); read_weapons_textures(&den->iw); get_sounds(&den->iw); if ((ret = check_all_validation(&den->iw)) == 0) return (0); get_packaging_textures(&den->iw); get_kernel_mem(&den->iw); get_kernels(&den->iw); get_guns(&den->iw); return (ret); } void main3d_edit_free(t_doom *den) { if (den->iw.v.sector_anim != 0) free(den->iw.v.sector_anim); if (den->iw.v.wall_anim != 0) free(den->iw.v.wall_anim); undo_animations(&den->iw); unget_map(&den->iw, den, den->tmp); free(den->iw.walls); free(den->iw.sectors); free_sector_ways(&den->iw); } void main3d_edit(t_doom *den) { give_date(den, &den->iw); get_def_new(&den->iw); den->iw.win = SDL_CreateWindow("Guardians of the Galaxy", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, WINDOW_W, WINDOW_H + 300, SDL_WINDOW_SHOWN); SDL_SetRelativeMouseMode(den->iw.v.mouse_mode); den->iw.sur = SDL_GetWindowSurface(den->iw.win); circle(&den->iw.hud, FOOTX, FOOTY); draw_tex_to_select(&den->iw); draw_decor_tex_to_select(&den->iw); draw_menu(&den->iw); get_map(&den->iw, den); set_sprites_z(&den->iw); get_sectors_ways(&den->iw); create_map(&den->iw); draw(&den->iw); SDL_UpdateWindowSurface(den->iw.win); main_loop(&den->iw); SDL_SetRelativeMouseMode(0); SDL_FreeSurface(den->iw.sur); SDL_DestroyWindow(den->iw.win); main3d_edit_free(den); Mix_HaltMusic(); } <|start_filename|>libft/ft_lstnew.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_lstnew.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbolilyi <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/04/02 18:35:17 by dbolilyi #+# #+# */ /* Updated: 2018/04/06 16:30:50 by dbolilyi ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" t_list *ft_lstnew(void const *content, size_t content_size) { t_list *tmp; tmp = (t_list *)malloc(sizeof(t_list)); if (tmp == 0) return (0); tmp->content_size = 0; if (content == 0) tmp->content = 0; else { tmp->content = (void *)malloc(content_size); if (tmp->content == 0) return (0); ft_memcpy(tmp->content, content, content_size); tmp->content_size = content_size; } tmp->next = 0; return (tmp); } <|start_filename|>3d/SRC3/map_wall_equations.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* map_wall_equations.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbolilyi <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/05 13:05:22 by dbolilyi #+# #+# */ /* Updated: 2019/03/05 13:05:23 by dbolilyi ### ########.fr */ /* */ /* ************************************************************************** */ #include "../guardians.h" void get_wall_line(t_sdl *iw, int wall) { iw->walls[wall].l.a = (float)(iw->walls[wall].next->y - iw->walls[wall].y); iw->walls[wall].l.b = (float)(iw->walls[wall].x - iw->walls[wall].next->x); iw->walls[wall].l.c = (float)(iw->walls[wall].next->x * iw->walls[wall].y - iw->walls[wall].x * iw->walls[wall].next->y); } void get_wall_line2(t_wall *wall) { wall->l.a = (float)(wall->next->y - wall->y); wall->l.b = (float)(wall->x - wall->next->x); wall->l.c = (float)(wall->next->x * wall->y - wall->x * wall->next->y); } void create_map(t_sdl *iw) { int i; int j; i = -1; while (++i < iw->v.sc) { if (iw->sectors[i].fr.n != 0) iw->sectors[i].fr.n->d = -iw->sectors[i].fr.n->a * iw->sectors[i].fr.x - iw->sectors[i].fr.n->b * iw->sectors[i].fr.y - iw->sectors[i].fr.n->c * iw->sectors[i].fr.z; if (iw->sectors[i].cl.n != 0) iw->sectors[i].cl.n->d = -iw->sectors[i].cl.n->a * iw->sectors[i].cl.x - iw->sectors[i].cl.n->b * iw->sectors[i].cl.y - iw->sectors[i].cl.n->c * iw->sectors[i].cl.z; j = iw->sectors[i].sw - 1; while (++j < iw->sectors[i].sw + iw->sectors[i].nw) get_wall_line(iw, j); } } <|start_filename|>3d/SRC3/get_visible_walls.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* get_visible_walls.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbolilyi <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/05 13:05:15 by dbolilyi #+# #+# */ /* Updated: 2019/03/05 13:05:16 by dbolilyi ### ########.fr */ /* */ /* ************************************************************************** */ #include "../guardians.h" float get_vectors_angle(float x1, float y1, float x2, float y2) { float k; k = (x1 * x2 + y1 * y2) / (sqrtf(x1 * x1 + y1 * y1) * sqrtf(x2 * x2 + y2 * y2)); if (k > 1.0f) return (acos(1.0f)); else if (k < -1.0f) return (acos(-1.0f)); return (acosf(k)); } void get_visible_walls2(t_sdl *iw, int wall, float lang) { t_save_wall *w; w = (t_save_wall *)malloc(sizeof(t_save_wall)); w->x = (int)(lang * (float)WINDOW_W / (2.0f * iw->v.angle)); w->len = sqrtf(powf((float)(iw->p.x - iw->walls[wall].x), 2.0f) + powf((float)(iw->p.y - iw->walls[wall].y), 2.0f)); w->plen = fabsf(iw->d.screen.a * (float)iw->walls[wall].x + iw->d.screen.b * (float)iw->walls[wall].y + iw->d.screen.c) / sqrtf( iw->d.screen.a * iw->d.screen.a + iw->d.screen.b * iw->d.screen.b); if ((int)w->plen == 0) w->plen = 1.0f; w->olen = 0.0f; w->p.x = iw->walls[wall].x; w->p.y = iw->walls[wall].y; w->wall = &iw->walls[wall]; w->zu = get_ceil_z(iw, iw->walls[wall].x, iw->walls[wall].y); w->zd = get_floor_z(iw, iw->walls[wall].x, iw->walls[wall].y); w->next = 0; add_wall(iw, w); } void get_visible_walls(t_sdl *iw) { int wall; float lang; float rang; wall = iw->sectors[iw->d.cs].sw; while (wall < iw->sectors[iw->d.cs].sw + iw->sectors[iw->d.cs].nw) { lang = get_vectors_angle(iw->d.left_point.x - (float)iw->p.x, iw->d.left_point.y - (float)iw->p.y, (float)( iw->walls[wall].x - iw->p.x), (float)(iw->walls[wall].y - iw->p.y)); rang = get_vectors_angle(iw->d.right_point.x - (float)iw->p.x, iw->d.right_point.y - (float)iw->p.y, (float)( iw->walls[wall].x - iw->p.x), (float)(iw->walls[wall].y - iw->p.y)); if ((lang <= 2 * iw->v.angle && rang <= 2 * iw->v.angle) || lang == 0.0f || rang == 0.0f) get_visible_walls2(iw, wall, lang); wall++; } } void add_wall(t_sdl *iw, t_save_wall *tmp) { t_save_wall *tmp2; if (iw->d.vw == 0 || iw->d.vw->x > tmp->x) { tmp->next = iw->d.vw; iw->d.vw = tmp; } else { tmp2 = iw->d.vw; while (tmp2->next != 0 && tmp2->next->x < tmp->x) tmp2 = tmp2->next; if (tmp2->next != 0) tmp->next = tmp2->next; tmp2->next = tmp; } } <|start_filename|>3d/SRC3/undo_animations.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* undo_animations.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbolilyi <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/05 13:06:28 by dbolilyi #+# #+# */ /* Updated: 2019/03/05 13:06:28 by dbolilyi ### ########.fr */ /* */ /* ************************************************************************** */ #include "../guardians.h" void undo_wall_animation2(t_sdl *iw, t_picture *pic) { t_wall_animation *tmp; t_wall_animation *tmp2; tmp = iw->wall_animations; while (tmp->next) { if (tmp->next->trigger == pic) { tmp2 = tmp->next; do_wall_animation_step_dx(iw, tmp2, -tmp2->curr_dx); do_wall_animation_step_dy(iw, tmp2, -tmp2->curr_dy); tmp2->status = 0; tmp2->curr_dx = 0; tmp2->curr_dy = 0; return ; } tmp = tmp->next; } } void undo_wall_animation(t_sdl *iw, t_picture *pic) { t_wall_animation *tmp2; t_wall_animation *start; if (iw->wall_animations == 0) return ; start = iw->wall_animations; if (iw->wall_animations->trigger == pic) { tmp2 = iw->wall_animations; do_wall_animation_step_dx(iw, tmp2, -tmp2->curr_dx); do_wall_animation_step_dy(iw, tmp2, -tmp2->curr_dy); tmp2->status = 0; tmp2->curr_dx = 0; tmp2->curr_dy = 0; } else undo_wall_animation2(iw, pic); iw->wall_animations = start; } void undo_animations2(t_sdl *iw, t_picture *pic) { t_sector_animation a; t_sector_animation *tmp; t_sector_animation *tmp2; a.next = iw->sector_animations; tmp = &a; while (tmp->next) { if (tmp->next->trigger == pic) { tmp2 = tmp->next; do_sector_animation_step(iw, tmp2, -tmp2->curr_dy); tmp2->curr_dy = 0; tmp2->status = 0; } tmp = tmp->next; } undo_wall_animation(iw, pic); } void undo_animations(t_sdl *iw) { int sec; int w; t_picture *tmp; sec = -1; while (++sec < iw->v.sc) { w = iw->sectors[sec].sw - 1; while (++w < iw->sectors[sec].sw + iw->sectors[sec].nw) { tmp = iw->walls[w].p; while (tmp) { undo_animations2(iw, tmp); tmp = tmp->next; } } } } <|start_filename|>3d/SRC3/get_left_right_visible_walls2.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* get_left_right_visible_walls2.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbolilyi <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/05 17:11:03 by dbolilyi #+# #+# */ /* Updated: 2019/03/05 17:11:04 by dbolilyi ### ########.fr */ /* */ /* ************************************************************************** */ #include "../guardians.h" void get_all_intersection_line(t_sdl *iw, t_line2d *nl, int right) { int wall; t_intpoint2d p; wall = iw->sectors[iw->d.cs].sw - 1; while (++wall < iw->sectors[iw->d.cs].sw + iw->sectors[iw->d.cs].nw) if (if_not_in_vw(iw, ((right == 0) ? &iw->walls[wall] : iw->walls[wall].next)) && visible_wall(iw, wall) && cross_two_lines(nl, &iw->walls[wall].l, &p) && point_in_front_and_on_wall(iw, &p, wall)) add_lr_wall(iw, &p, ((right == 0) ? &iw->walls[wall] : iw->walls[wall].next), right * WINDOW_W); } void get_left_right_visible_walls(t_sdl *iw) { get_all_intersection_line(iw, &iw->d.left_line, 0); get_all_intersection_line(iw, &iw->d.right_line, 1); } <|start_filename|>3d/SRC4/setup_opencl.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* setup_opencl.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbolilyi <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/05 14:38:40 by dbolilyi #+# #+# */ /* Updated: 2019/03/05 14:38:41 by dbolilyi ### ########.fr */ /* */ /* ************************************************************************** */ #include "../guardians.h" void get_kernels5(t_sdl *iw) { iw->k.kernel4 = clCreateKernel(iw->k.program, "draw_skybox_kernel", &iw->k.ret); iw->k.ret = clSetKernelArg(iw->k.kernel4, 0, sizeof(cl_mem), (void *)&iw->k.m_top); iw->k.ret = clSetKernelArg(iw->k.kernel4, 1, sizeof(cl_mem), (void *)&iw->k.m_bottom); iw->k.ret = clSetKernelArg(iw->k.kernel4, 2, sizeof(cl_mem), (void *)&iw->k.m_sur); iw->k.ret = clSetKernelArg(iw->k.kernel4, 4, sizeof(cl_mem), (void *)&iw->k.m_cint); iw->k.ret = clSetKernelArg(iw->k.kernel4, 5, sizeof(cl_mem), (void *)&iw->k.m_cfloat); iw->k.kernel5 = clCreateKernel(iw->k.program, "draw_glass_tex_kernel", &iw->k.ret); iw->k.ret = clSetKernelArg(iw->k.kernel5, 0, sizeof(cl_mem), (void *)&iw->k.m_save_top); iw->k.ret = clSetKernelArg(iw->k.kernel5, 1, sizeof(cl_mem), (void *)&iw->k.m_save_bottom); iw->k.ret = clSetKernelArg(iw->k.kernel5, 2, sizeof(cl_mem), (void *)&iw->k.m_sur); iw->k.ret = clSetKernelArg(iw->k.kernel5, 4, sizeof(cl_mem), (void *)&iw->k.m_wallTop); iw->k.ret = clSetKernelArg(iw->k.kernel5, 5, sizeof(cl_mem), (void *)&iw->k.m_wallBot); } void get_kernels6(t_sdl *iw) { iw->k.ret = clSetKernelArg(iw->k.kernel5, 6, sizeof(cl_mem), (void *)&iw->k.m_cint); iw->k.ret = clSetKernelArg(iw->k.kernel5, 7, sizeof(cl_mem), (void *)&iw->k.m_cfloat); iw->k.kernel6 = clCreateKernel(iw->k.program, "draw_picture_kernel", &iw->k.ret); iw->k.ret = clSetKernelArg(iw->k.kernel6, 0, sizeof(cl_mem), (void *)&iw->k.m_save_top2); iw->k.ret = clSetKernelArg(iw->k.kernel6, 1, sizeof(cl_mem), (void *)&iw->k.m_save_bottom2); iw->k.ret = clSetKernelArg(iw->k.kernel6, 2, sizeof(cl_mem), (void *)&iw->k.m_sur); iw->k.ret = clSetKernelArg(iw->k.kernel6, 4, sizeof(cl_mem), (void *)&iw->k.m_cint); iw->k.ret = clSetKernelArg(iw->k.kernel6, 5, sizeof(cl_mem), (void *)&iw->k.m_cfloat); iw->k.kernel7 = clCreateKernel(iw->k.program, "draw_sprite_kernel", &iw->k.ret); iw->k.ret = clSetKernelArg(iw->k.kernel7, 0, sizeof(cl_mem), (void *)&iw->k.m_save_top3); iw->k.ret = clSetKernelArg(iw->k.kernel7, 1, sizeof(cl_mem), (void *)&iw->k.m_save_bottom3); iw->k.ret = clSetKernelArg(iw->k.kernel7, 2, sizeof(cl_mem), (void *)&iw->k.m_sur); } void get_kernels(t_sdl *iw) { get_kernels2(iw); get_kernels3(iw); get_kernels4(iw); get_kernels5(iw); get_kernels6(iw); iw->k.ret = clSetKernelArg(iw->k.kernel7, 4, sizeof(cl_mem), (void *)&iw->k.m_cint); iw->k.kernel8 = clCreateKernel(iw->k.program, "draw_gun_kernel", &iw->k.ret); iw->k.ret = clSetKernelArg(iw->k.kernel8, 0, sizeof(cl_mem), (void *)&iw->k.m_sur); iw->k.ret = clSetKernelArg(iw->k.kernel8, 2, sizeof(cl_mem), (void *)&iw->k.m_cint); } void load_kernel2(t_kernel *k) { k->platforms = (cl_platform_id*)malloc(k->ret_num_platforms * sizeof(cl_platform_id)); k->ret = clGetPlatformIDs(k->ret_num_platforms, k->platforms, NULL); k->ret = clGetDeviceIDs(k->platforms[0], CL_DEVICE_TYPE_ALL, 1, &k->device_id, &k->ret_num_devices); k->context = clCreateContext(NULL, 1, &k->device_id, NULL, NULL, &k->ret); k->command_queue = clCreateCommandQueue(k->context, k->device_id, 0, &k->ret); k->program = clCreateProgramWithSource(k->context, 1, (const char **)&k->source_str, (const size_t *)&k->source_size, &k->ret); k->ret = clBuildProgram(k->program, 1, &k->device_id, NULL, NULL, NULL); } void load_kernel(t_kernel *k, t_sdl *iw) { int fd; if (iw->v.game_mode == 0) { k->ret = 1; fd = open("3d/kernel.cl", O_RDONLY); if (fd < 0) return ; k->source_str = (char *)malloc(MAX_SOURCE_SIZE); k->source_size = read(fd, k->source_str, MAX_SOURCE_SIZE); close(fd); } k->device_id = 0; k->platforms = 0; k->ret = clGetPlatformIDs(0, NULL, &k->ret_num_platforms); if (k->ret_num_platforms <= 0) { k->ret = 1; return ; } load_kernel2(k); } <|start_filename|>3d/SRC3/get_sector_ways2.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* get_sector_ways2.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbolilyi <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/05 17:12:14 by dbolilyi #+# #+# */ /* Updated: 2019/03/05 17:12:15 by dbolilyi ### ########.fr */ /* */ /* ************************************************************************** */ #include "../guardians.h" void free_way(t_sector_ways **way) { t_sector_way *tmp; t_sector_way *tmp2; if (*way == 0) return ; tmp = (*way)->way_start; while (tmp) { tmp2 = tmp; tmp = tmp->next; free(tmp2); } free(*way); *way = 0; } int sector_in_way(t_sdl *iw, t_sector_ways *way, int sector) { t_sector_way *tmp; if (way == 0) return (0); tmp = way->way_start; while (tmp) { if (iw->walls[tmp->portal].nextsector == sector) return (1); tmp = tmp->next; } return (0); } <|start_filename|>3d/SRC3/draw_sprites.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* draw_sprites.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbolilyi <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/05 13:03:43 by dbolilyi #+# #+# */ /* Updated: 2019/03/05 13:03:44 by dbolilyi ### ########.fr */ /* */ /* ************************************************************************** */ #include "../guardians.h" void draw_sprite2(t_sdl *iw, t_sprite *sprite, t_draw_sprite *d) { sprite->spriteheight = 2 * sprite->spritewidth * sprite->t->h / sprite->t->w; if (abs(sprite->z - iw->p.z) > 1500) sprite->spriteheight = (float)sprite->spriteheight * 1.0f / (float)(abs(sprite->z - iw->p.z) / 1500.0f); sprite->ey = WINDOW_H * (iw->p.z + (int)sprite->pplen / 2 - sprite->z) / (int)sprite->pplen + iw->p.rotup; sprite->sy = sprite->ey - sprite->spriteheight; d->i = 0; d->stripe = sprite->sx - 1; if (d->stripe < -1) { d->i -= d->stripe + 1; d->stripe = -1; } } void draw_sprite3(t_sdl *iw, t_sprite *sprite, t_draw_sprite *d) { d->y = sprite->sy - 1; if (d->y < -1) { d->j -= d->y + 1; d->y = -1; } while (++d->y < sprite->ey && d->y < WINDOW_H) { if (sprite->sy < WINDOW_H && sprite->bottom[d->stripe] > d->y && sprite->top[d->stripe] < d->y) { d->koef = (float)sprite->spriteheight / sprite->t->h; d->texY = (int)(d->j / d->koef); d->colour = get_pixel(sprite->t, d->texX, d->texY); if (d->colour != 0x010000) set_pixel2(iw->sur, d->stripe, d->y, get_light_color(d->colour, iw->sectors[sprite->num_sec].light)); } d->j++; } } void draw_sprite(t_sdl *iw, t_sprite *sprite) { t_draw_sprite d; draw_sprite2(iw, sprite, &d); while (++d.stripe < sprite->ex && d.stripe < WINDOW_W) { d.j = 0; d.koef = (float)sprite->spritewidth * 2.0f / (float)sprite->t->w; d.texX = (int)fabsf((float)d.i / d.koef); if ((sprite->top[d.stripe] < sprite->bottom[d.stripe]) && sprite->top[d.stripe] != -1) draw_sprite3(iw, sprite, &d); d.i++; } } void draw_sprites(t_sdl *iw) { t_sprite *tmp1; tmp1 = *iw->sprite; while (tmp1 != 0) { if (iw->sectors[tmp1->num_sec].visited && tmp1->draweble && tmp1->taken == 0) { if (tmp1->top[WINDOW_W / 2] != -1 && tmp1->sx < WINDOW_W / 2 && tmp1->ex > WINDOW_W / 2 && tmp1->top[WINDOW_W / 2] < WINDOW_H / 2 && tmp1->bottom[WINDOW_W / 2] > WINDOW_H / 2 && tmp1->sy < WINDOW_H / 2 && tmp1->ey > WINDOW_H / 2) iw->v.look_sprite = tmp1; draw_sprite(iw, tmp1); } tmp1 = tmp1->next; } } <|start_filename|>3d/SRC3/next_sector.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* next_sector.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbolilyi <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/05 13:05:34 by dbolilyi #+# #+# */ /* Updated: 2019/03/05 13:05:35 by dbolilyi ### ########.fr */ /* */ /* ************************************************************************** */ #include "../guardians.h" void draw_next_sector_kernel3(t_sdl *iw, t_save_wall *left, t_save_wall *right, t_sdl *iw2) { t_visited_sector *tmp; iw2->d.prev_sector_wall = left->wall; if (left->wall->glass >= 0) { clEnqueueCopyBuffer(iw->k.command_queue, iw->k.m_top, iw->k.m_save_top, 0, 0, USELESS4, 0, NULL, NULL); clEnqueueCopyBuffer(iw->k.command_queue, iw->k.m_bottom, iw->k.m_save_bottom, 0, 0, USELESS4, 0, NULL, NULL); } iw->sectors[iw2->d.cs].visited = 1; tmp = (t_visited_sector *)malloc(sizeof(t_visited_sector)); tmp->sec = iw2->d.cs; tmp->next = iw2->visited_sectors; iw2->visited_sectors = tmp; draw_start(iw2); iw2->visited_sectors = iw2->visited_sectors->next; free(tmp); draw_next_sector_kernel4(iw, left, right, iw2); } void draw_next_sector_kernel2(t_sdl *iw, t_save_wall *left, t_save_wall *right, t_sdl *iw2) { if ((iw->d.wallBot[0] < 0 && iw->d.wallBot[right->x - left->x] < 0) || (iw->d.wallTop[0] >= WINDOW_H && iw->d.wallTop[right->x - left->x] >= WINDOW_H) || sector_visited(iw, iw2->d.cs)) { free(iw->d.save_bot_betw); free(iw->d.save_top_betw); return ; } get_direction(iw2); get_screen_line(iw2); get_left_right_lines_points(iw2); iw2->d.vw = 0; iw2->d.vwp = 0; if (left->x > iw2->d.screen_left) iw2->d.screen_left = left->x; if (right->x < iw2->d.screen_right) iw2->d.screen_right = right->x; fill_tb_by_slsr(iw2); get_visible_walls(iw2); get_left_right_visible_walls(iw2); iw2->d.prev_sector = iw->d.cs; draw_next_sector_kernel3(iw, left, right, iw2); } void draw_next_sector_kernel(t_sdl *iw, t_save_wall *left, t_save_wall *right, int len) { t_sdl iw2; iw2 = *iw; iw2.p.x += iw->walls[left->wall->nextsector_wall].x - left->wall->next->x; iw2.p.y += iw->walls[left->wall->nextsector_wall].y - left->wall->next->y; iw2.d.cs = left->wall->nextsector; iw->d.save_bot_betw = get_between_sectors_walls( &iw2, left, right, &iw->d.save_top_betw); if (*(iw->v.look_wall) == 0 && iw->v.mouse_mode == 1 && left->x < WINDOW_W / 2 && right->x > WINDOW_W / 2 && (iw->d.save_top_betw[WINDOW_W / 2 - left->x] > WINDOW_H / 2 || iw->d.save_bot_betw[WINDOW_W / 2 - left->x] < WINDOW_H / 2)) { *(iw->v.look_wall) = left->wall; *(iw->v.look_sector) = &iw->sectors[iw->d.cs]; } if (iw->sectors[iw->d.cs].fr.n == 0 && iw->sectors[iw->d.cs].cl.n == 0) draw_floor_ceil_betw_tex_kernel(iw, left, right, len); else draw_inclined_floor_ceil_betw_tex_kernel(iw, left, right, len); draw_next_sector_kernel2(iw, left, right, &iw2); } void change_saved_top_bot_between_lines(t_sdl *iw, int len) { int j; if (iw->d.wallTop[0] > iw->d.save_top_betw[0]) { j = -1; while (++j < len) iw->d.save_top_betw[j] = iw->d.wallTop[j]; } if (iw->d.wallBot[0] < iw->d.save_bot_betw[0]) { j = -1; while (++j < len) iw->d.save_bot_betw[j] = iw->d.wallBot[j]; } } int sector_visited(t_sdl *iw, int sec) { t_visited_sector *s; s = iw->visited_sectors; while (s) { if (sec == s->sec) return (1); s = s->next; } return (0); } <|start_filename|>3d/SRC2/enemy_intelligence2_2.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* enemy_intelligence2_2.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbolilyi <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/05 16:45:36 by dbolilyi #+# #+# */ /* Updated: 2019/03/05 16:45:37 by dbolilyi ### ########.fr */ /* */ /* ************************************************************************** */ #include "../guardians.h" void enemy_intelligence2_s0(t_sdl *iw, t_sprite *s, int i) { if (clock() - s->e.previous_picture_change > CLKS_P_S / 3) { s->e.previous_picture_change = clock(); if (s->t_numb == 20) s->t_numb = 20; else s->t_numb = 20; s->t = iw->t_enemies[s->t_numb]; s->t_kernel = &iw->k.m_t_enemies[s->t_numb]; } if ((i = enemy_sees_player(iw, s)) != -1) { if ((i < 10000 || s->e.health < ENEMY_HEALTH2) && i > 4000) s->e.status = 2; else if (i <= 4000) s->e.status = 3; } } <|start_filename|>3d/SRC3/draw_gun.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* draw_gun.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbolilyi <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/05 13:03:01 by dbolilyi #+# #+# */ /* Updated: 2019/03/05 13:03:02 by dbolilyi ### ########.fr */ /* */ /* ************************************************************************** */ #include "../guardians.h" void draw_gun2(t_sdl *iw, t_draw_gun *d) { d->changed_rect = iw->guns.t_rect[iw->guns.t]; d->changed_rect.x += iw->v.weapon_change_x; d->changed_rect.y += iw->v.weapon_change_y + iw->v.weapon_change_y_hide; d->to_i = d->changed_rect.y + d->changed_rect.h; if (d->to_i > WINDOW_H) d->to_i = WINDOW_H; if (d->changed_rect.y < 0) d->i = -1; else d->i = d->changed_rect.y - 1; if (d->changed_rect.x < 0) d->start_j = -1; else d->start_j = d->changed_rect.x - 1; d->to_j = d->changed_rect.w + d->changed_rect.x; if (d->to_j > WINDOW_W) d->to_j = WINDOW_W; } void draw_gun(t_sdl *iw) { t_draw_gun d; draw_gun2(iw, &d); while (++d.i < d.to_i) { d.j = d.start_j; while (++d.j < d.to_j) { d.pixel = get_pixel(iw->t_weap[iw->guns.t], (d.j - d.changed_rect.x) * iw->t_weap[iw->guns.t]->w / d.changed_rect.w, (d.i - d.changed_rect.y) * iw->t_weap[iw->guns.t]->h / d.changed_rect.h); if (d.pixel != 0x010000) set_pixel2(iw->sur, d.j, d.i, get_light_color(d.pixel, iw->sectors[iw->d.cs].light)); } } } <|start_filename|>3d/SRC2/enemy_intelligence2.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* enemy_intelligence2.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbolilyi <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/05 12:07:07 by dbolilyi #+# #+# */ /* Updated: 2019/03/05 12:07:08 by dbolilyi ### ########.fr */ /* */ /* ************************************************************************** */ #include "../guardians.h" void enemy_intelligence2_s2_2(t_sdl *iw, t_sprite *s, int i) { if ((i = enemy_sees_player(iw, s)) != -1) { if (i > 4000) move_enemy(iw, s); else s->e.status = 3; } else if (s->e.vis_esp.curr_sector != -1) { if ((i = (int)sqrtf(powf(s->x - s->e.vis_esp.px, 2.0f) + powf(s->y - s->e.vis_esp.py, 2.0f))) > 10) move_enemy(iw, s); else { s->t_numb = 20; s->e.status = 0; } } } void enemy_intelligence2_s2(t_sdl *iw, t_sprite *s) { if (clock() - s->e.previous_picture_change > CLKS_P_S / 7) { s->e.previous_picture_change = clock(); if (s->t_numb == 20 || s->t_numb == 25) s->t_numb = 22; else if (s->t_numb == 24) s->t_numb = 22; else s->t_numb++; s->t = iw->t_enemies[s->t_numb]; s->t_kernel = &iw->k.m_t_enemies[s->t_numb]; } enemy_intelligence2_s2_2(iw, s, 0); } void enemy_intelligence2_s3(t_sdl *iw, t_sprite *s, int i) { s->e.previous_picture_change = clock(); if (s->t_numb != 25) { s->t_numb = 25; iw->p.health -= ENEMY_DAMAGE2 * iw->menu.count; if (!Mix_Playing(4)) Mix_PlayChannel(4, iw->sounds.env[9], 0); if (!Mix_Playing(7)) Mix_PlayChannel(7, iw->sounds.env[11], 0); } else if (s->t_numb == 25) s->t_numb = 20; s->t = iw->t_enemies[s->t_numb]; s->t_kernel = &iw->k.m_t_enemies[s->t_numb]; if ((i = enemy_sees_player(iw, s)) == -1) s->e.status = 2; } void enemy_intelligence2_s4(t_sdl *iw, t_sprite *s) { s->e.previous_picture_change = clock(); if (s->t_numb < 26) s->t_numb = 26; else if (s->t_numb == 26) s->t_numb = 27; else if (s->t_numb == 27) s->t_numb = 28; else if (s->t_numb == 28) s->t_numb = 29; else if (s->t_numb == 29) s->e.status = 5; s->t = iw->t_enemies[s->t_numb]; s->t_kernel = &iw->k.m_t_enemies[s->t_numb]; } void enemy_intelligence2(t_sdl *iw, t_sprite *s, int i) { if (s->e.status == 0) enemy_intelligence2_s0(iw, s, 0); else if (s->e.status == 1) { if ((s->e.health < ENEMY_HEALTH2) || ((i = enemy_sees_player(iw, s)) != -1 && i <= 2000)) { check_enemies_in_sector(iw, s); s->e.status = 0; s->t_numb = 20; } } else if (s->e.status == 2) enemy_intelligence2_s2(iw, s); else if (s->e.status == 3 && clock() - s->e.previous_picture_change > CLKS_P_S / 5) enemy_intelligence2_s3(iw, s, 0); else if (s->e.status == 4 && clock() - s->e.previous_picture_change > CLKS_P_S / 7) enemy_intelligence2_s4(iw, s); sprite_physics(iw, s); if (!(s->e.health <= 0 && s->e.status < 4)) return ; Mix_PlayChannel(7, iw->sounds.env[19], 0); s->e.status = 4; } <|start_filename|>editor/unget.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* unget.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ddehtyar <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/05 14:45:55 by ddehtyar #+# #+# */ /* Updated: 2019/03/05 14:45:56 by ddehtyar ### ########.fr */ /* */ /* ************************************************************************** */ #include "doom_nuken.h" void give_date(t_doom *den, t_sdl *iw) { t_sprite *tmp; if (den->player.x && den->player.y) { iw->l.start_x = den->player.x * MAP_SCALE; if (iw->l.start_x % 2 == 0) iw->l.start_x += 1; iw->l.start_y = -den->player.y * MAP_SCALE; if (iw->l.start_y % 2 == 0) iw->l.start_y += 1; } iw->l.start_rot = den->player.introt; iw->l.win_sector = den->finish; tmp = den->sprite; while (tmp) { tmp->x *= MAP_SCALE; tmp->y *= -MAP_SCALE; tmp = tmp->next; } } void unget_map_help(t_sdl *iw, t_wals *tmp, t_sector_list *sl) { int i; int j; i = -1; while (++i < iw->v.sc) { sl->fr.z = iw->sectors[i].fr.z; sl->fr.n = iw->sectors[i].fr.n; sl->fr.t = iw->sectors[i].fr.t; sl->cl.z = iw->sectors[i].cl.z; sl->cl.n = iw->sectors[i].cl.n; sl->cl.t = iw->sectors[i].cl.t; sl->light = iw->sectors[i].light; j = iw->sectors[i].sw - 1; while (++j < iw->sectors[i].sw + iw->sectors[i].nw) { tmp->tex = iw->walls[j].t; tmp->glass = iw->walls[j].glass; tmp->p = iw->walls[j].p; tmp = tmp->next; } sl = sl->next; } } void unget_map(t_sdl *iw, t_doom *den, t_wals *tmp) { t_sector_list *sl; t_sprite *tmp2; sl = den->sectors; unget_map_help(iw, tmp, sl); den->sprite = *den->iw.sprite; tmp2 = den->sprite; while (tmp2) { tmp2->x /= MAP_SCALE; tmp2->y /= -MAP_SCALE; tmp2 = tmp2->next; } } <|start_filename|>3d/SRC3/ft_funcs.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_funcs.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbolilyi <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/05 13:04:21 by dbolilyi #+# #+# */ /* Updated: 2019/03/05 13:04:22 by dbolilyi ### ########.fr */ /* */ /* ************************************************************************** */ #include "../guardians.h" int ft_min(int p1, int p2) { if (p1 < p2) return (p1); return (p2); } int ft_max(int p1, int p2) { if (p1 >= p2) return (p1); return (p2); } void ft_scaled_blit(t_packaging_texture *tex, SDL_Surface *winsur, SDL_Rect *rect) { int i; int j; int p; i = -1; while (++i < rect->h) { j = -1; while (++j < rect->w) { p = get_pixel(tex, tex->w * j / rect->w, tex->h * i / rect->h); if (p != 0x010000) set_pixel2(winsur, rect->x + j, rect->y + i, p); } } } void ft_scaled_blit2(t_packaging_texture *tex, SDL_Surface *winsur, SDL_Rect *rect) { int i; int j; i = -1; while (++i < rect->h) { j = -1; while (++j < rect->w) set_pixel2(winsur, rect->x + j, rect->y + i, get_pixel(tex, tex->w * j / rect->w, tex->h * i / rect->h)); } } <|start_filename|>3d/SRC/backpack.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* backpack.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbolilyi <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/02/28 15:04:24 by dbolilyi #+# #+# */ /* Updated: 2019/02/28 15:17:56 by dbolilyi ### ########.fr */ /* */ /* ************************************************************************** */ #include "../guardians.h" void draw_icon_bag(t_sdl *iw) { SDL_Rect rect; rect.x = WINDOW_W / 120; rect.y = WINDOW_H - WINDOW_W / 12; rect.w = WINDOW_W / 14; rect.h = WINDOW_W / 14; if (iw->bag.selected_item != 0) ft_scaled_blit(iw->t_pickup[iw->bag.selected_item->t_numb], iw->sur, &rect); else ft_scaled_blit(iw->t_weap[17], iw->sur, &rect); rect.x = 0; rect.y = WINDOW_H - WINDOW_W / 11; rect.w = WINDOW_W / 11; rect.h = WINDOW_W / 11; ft_scaled_blit(iw->bag.button[0], iw->sur, &rect); } void draw_frame(t_sdl *iw, SDL_Surface *winsur, SDL_Rect *rect) { int i; int j; int color; i = -1; while (++i < rect->w) { j = -1; while (++j < rect->h) { color = get_pixel(iw->bag.button[0], iw->bag.button[0]->w * i / rect->w, iw->bag.button[0]->h * j / rect->h); if (color != 0x010000) set_pixel2(winsur, rect->x + i, rect->y + j, color); } } } void check_drop_clock(t_sdl *iw) { if (iw->bag.selected_item->t_numb == 6) { iw->v.have_clocks = 0; iw->map.back = 0; } } void drop_item(t_sdl *iw) { int i; int flag; flag = 0; if (iw->bag.selected_item == 0) return ; Mix_PlayChannel(2, iw->sounds.env[4], 0); check_drop_clock(iw); i = 0; while (i < iw->bag.count_items) { if (iw->bag.selected_item == iw->bag.item_in_bag1[i]) flag = 1; if (flag == 1) iw->bag.item_in_bag1[i] = iw->bag.item_in_bag1[i + 1]; i++; } iw->bag.count_items--; iw->bag.selected_item->x = iw->p.x; iw->bag.selected_item->y = iw->p.y; iw->bag.selected_item->z = get_floor_z(iw, iw->p.x, iw->p.y); iw->bag.selected_item->num_sec = iw->d.cs; iw->bag.selected_item->taken = 0; iw->bag.selected_item = 0; } void delete_used_sprite(t_sdl *iw, t_sprite *s) { t_sprite head; t_sprite *tmp; t_sprite *tmp2; head.next = *iw->sprite; tmp = &head; while (tmp->next) { if (tmp->next == s) { tmp2 = tmp->next; tmp->next = tmp->next->next; free(tmp2); break ; } tmp = tmp->next; } *iw->sprite = head.next; } <|start_filename|>3d/SRC2/guns_mechanic2.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* guns_mechanic2.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbolilyi <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/05 16:43:27 by dbolilyi #+# #+# */ /* Updated: 2019/03/05 16:43:28 by dbolilyi ### ########.fr */ /* */ /* ************************************************************************** */ #include "../guardians.h" void reload_gun(t_sdl *iw) { if (iw->guns.gun_in_hands == 0) { iw->guns.bullets[iw->guns.gun_in_hands] = iw->guns.max_bullets[iw->guns.gun_in_hands]; iw->hud.shell = 100; iw->guns.status = 0; } else if (iw->guns.gun_in_hands == 1) reload_gun1(iw); else if (iw->guns.gun_in_hands == 2) reload_gun2(iw); iw->guns.prev_update_time = clock(); } void guns_loop2(t_sdl *iw) { if (iw->guns.t == 8) { damaging_enemy(iw, 2, 10000); Mix_PlayChannel(3, iw->sounds.env[5], 0); iw->guns.t = 9; } else { if (!iw->v.left_mouse_pressed || iw->guns.bullets[iw->guns.gun_in_hands] <= 0) { iw->guns.status = 0; iw->guns.t = 7; } else { iw->guns.t = 8; iw->guns.bullets[iw->guns.gun_in_hands]--; iw->hud.shell = 100 * iw->guns.bullets[iw->guns.gun_in_hands] / iw->guns.max_bullets[iw->guns.gun_in_hands]; } if (iw->guns.bullets[iw->guns.gun_in_hands] <= 0) iw->guns.status = 2; } iw->guns.prev_update_time = clock(); } void guns_loop(t_sdl *iw) { if (iw->guns.status == 1 && iw->guns.gun_in_hands == 0 && clock() - iw->guns.prev_update_time > CLKS_P_S / 15) { iw->guns.status = 0; iw->guns.t = 17; if (iw->guns.bullets[iw->guns.gun_in_hands] <= 0) iw->guns.status = 2; iw->guns.prev_update_time = clock(); } else if (iw->guns.status == 1 && iw->guns.gun_in_hands == 1 && clock() - iw->guns.prev_update_time > CLKS_P_S / 5) { iw->guns.status = 0; iw->guns.t = 0; if (iw->guns.bullets[iw->guns.gun_in_hands] <= 0) iw->guns.status = 2; iw->guns.prev_update_time = clock(); } else if (iw->guns.status == 1 && iw->guns.gun_in_hands == 2 && clock() - iw->guns.prev_update_time > CLKS_P_S / 10) guns_loop2(iw); } void guns_movements2(t_sdl *iw, int t) { if (iw->v.fps != 0) t = 150 / iw->v.fps; else t = 10; iw->v.weapon_change_x += iw->v.sprint * ((iw->v.weapon_change_xdir > 0) ? t : -t); if (abs(iw->v.weapon_change_x) > WEAPONS_MOVING_CHANGE_VALUE) { iw->v.weapon_change_xdir *= -1; iw->v.weapon_change_x = ((iw->v.weapon_change_x > 0) ? WEAPONS_MOVING_CHANGE_VALUE : -WEAPONS_MOVING_CHANGE_VALUE); } iw->v.weapon_change_y += iw->v.sprint * ((iw->v.weapon_change_ydir > 0) ? t : -t); if (iw->v.weapon_change_y > WEAPONS_MOVING_CHANGE_VALUE || iw->v.weapon_change_y < 10) iw->v.weapon_change_ydir *= -1; if (iw->v.weapon_change_y > WEAPONS_MOVING_CHANGE_VALUE) iw->v.weapon_change_y = WEAPONS_MOVING_CHANGE_VALUE; if (iw->v.weapon_change_y < 10) iw->v.weapon_change_y = 10; } void guns_movements(t_sdl *iw) { if (iw->v.game_mode && (iw->v.front != 1 || iw->v.back != 1 || iw->v.left != 1 || iw->v.right != 1)) guns_movements2(iw, 0); if (iw->guns.status == 3) { iw->v.weapon_change_y_hide += 500 / iw->v.fps; if (iw->v.weapon_change_y_hide >= iw->guns.t_rect[iw->guns.t].h) { if (iw->guns.gun_in_hands == 0) iw->guns.t = 17; else if (iw->guns.gun_in_hands == 1) iw->guns.t = 0; else if (iw->guns.gun_in_hands == 2) iw->guns.t = 7; iw->guns.status = 0; } } else if (iw->v.weapon_change_y_hide > 0) { iw->v.weapon_change_y_hide -= 1000 / iw->v.fps; if (iw->v.weapon_change_y_hide < 0) iw->v.weapon_change_y_hide = 0; } } <|start_filename|>libft/ft_strsplit.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_strsplit.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbolilyi <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/03/27 15:11:30 by dbolilyi #+# #+# */ /* Updated: 2018/06/17 17:56:16 by dbolilyi ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" static unsigned int ft_count_splitwords(char const *s, char c) { unsigned int i; if (*s == '\0') return (-2); i = 0; while (*s != '\0') { while (*s == c) s++; if (*s != '\0') { while ((*s != c) && (*s != '\0')) s++; i++; } } return (i); } static char **ft_mem_splitwords(char const *s, char c) { char **spl; unsigned int size; char **tmp; spl = (char **)malloc((ft_count_splitwords(s, c) + 1) * sizeof(char *)); if (spl == 0) return (0); tmp = spl; while (*s != '\0') { while ((*s == c) && (*s != '\0')) s++; size = 0; if (*s != '\0') { while ((*s != c) && (*s != '\0')) { s++; size++; } (*spl++) = (char *)malloc((size + 1) * sizeof(char)); } } return (tmp); } char **ft_strsplit(char const *s, char c) { char **spl; char **tmp; unsigned int i; if ((s == 0) || ((spl = ft_mem_splitwords(s, c)) == 0)) return (0); tmp = spl; while (*s != '\0') { while ((*s == c) && (*s != '\0')) s++; if (*s != '\0') { i = 0; while ((*s != c) && (*s != '\0')) spl[0][i++] = *(s++); (spl++)[0][i] = '\0'; if (*s == '\0') *spl = 0; } else *(spl++) = 0; } return (tmp); } <|start_filename|>3d/SRC4/draw_inclined_wall_floor_ceil_kernel2.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* draw_inclined_wall_floor_ceil_kernel2.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbolilyi <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/05 17:23:42 by dbolilyi #+# #+# */ /* Updated: 2019/03/05 17:23:43 by dbolilyi ### ########.fr */ /* */ /* ************************************************************************** */ #include "../guardians.h" void draw_inclined_wall_floor_ceil_tex_kernel1(t_sdl *iw, t_save_wall *left, t_draw_wall_floor_ceil_tex_kernel *d) { if (iw->sectors[iw->d.cs].light == 0 || iw->sectors[iw->d.cs].light->t != 18) d->cint[24] = 1; else d->cint[24] = 0; if (left->wall->t >= 0) { d->cint[0] = iw->t[left->wall->t]->w; d->cint[1] = iw->t[left->wall->t]->h; d->cfloat[14] = iw->tsz[left->wall->t]; } else d->cint[0] = -1; d->cint[2] = iw->t[iw->sectors[iw->d.cs].fr.t]->w; d->cint[3] = iw->t[iw->sectors[iw->d.cs].fr.t]->h; if (iw->sectors[iw->d.cs].cl.t >= 0) { d->cint[4] = iw->t[iw->sectors[iw->d.cs].cl.t]->w; d->cint[5] = iw->t[iw->sectors[iw->d.cs].cl.t]->h; } d->cint[6] = WINDOW_W; d->cint[7] = WINDOW_H; d->cint[8] = left->x; d->cint[9] = left->p.x; d->cint[10] = left->p.y; } <|start_filename|>editor/move_scan.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* move_scan.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ddehtyar <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/04 16:01:43 by ddehtyar #+# #+# */ /* Updated: 2019/03/04 16:01:44 by ddehtyar ### ########.fr */ /* */ /* ************************************************************************** */ #include "doom_nuken.h" void move_scan_sector(t_doom *den, const Uint8 *state) { if (state[SDL_SCANCODE_UP]) den->find_sprite->y -= 1; else if (state[SDL_SCANCODE_DOWN]) den->find_sprite->y += 1; else if (state[SDL_SCANCODE_LEFT]) den->find_sprite->x -= 1; else if (state[SDL_SCANCODE_RIGHT]) den->find_sprite->x += 1; } void move_scan_sprite(t_doom *den, const Uint8 *state) { if (state[SDL_SCANCODE_UP]) den->starty -= (den->skape + START); else if (state[SDL_SCANCODE_DOWN]) den->starty += (den->skape + START); else if (state[SDL_SCANCODE_LEFT]) den->startx -= (den->skape + START); else if (state[SDL_SCANCODE_RIGHT]) den->startx += (den->skape + START); clean_find_vec(den); } void move_scancode(t_doom *den, t_col *vec, const Uint8 *state) { if (den->change == 4) move_scan_sector(den, state); else if (den->change == 3 && den->select == 1) { if (state[SDL_SCANCODE_UP]) move_sector(den, -1, 0); else if (state[SDL_SCANCODE_DOWN]) move_sector(den, 1, 0); else if (state[SDL_SCANCODE_LEFT]) move_sector(den, 0, -1); else if (state[SDL_SCANCODE_RIGHT]) move_sector(den, 0, 1); } else move_scan_sprite(den, state); clear_texture(den, vec); map_network(den); if (den->sec > 0) blonk_on_now(den); info_display(den); } void mouse_button_rotate(t_doom *den, t_col *vec, int x, int y) { den->xy.x = (x - den->startx) / SKAPE; den->xy.y = (y - den->starty) / SKAPE; in_all_sect(den); if (den->xy.bool_cor != -1) { den->player.x = den->xy.x; den->player.y = den->xy.y; rotate_image(den); den->xy.bool_cor = -1; } retry_write(den, vec); den->blockwall = 0; den->button = den->button == 1 ? 0 : 1; SDL_FreeCursor(den->cursor); } void mouse_button_sprite(t_doom *den, t_col *vec, int x, int y) { den->xy.x = (x - den->startx) / SKAPE; den->xy.y = (y - den->starty) / SKAPE; in_all_sect(den); if (den->xy.bool_cor != -1) { add_sprite(den); den->xy.bool_cor = -1; } retry_write(den, vec); den->blockwall = 0; den->button = den->button == 1 ? 0 : 1; SDL_FreeCursor(den->cursor); } <|start_filename|>editor/new_game.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* new_game.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ddehtyar <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/05 15:04:48 by ddehtyar #+# #+# */ /* Updated: 2019/03/05 15:04:49 by ddehtyar ### ########.fr */ /* */ /* ************************************************************************** */ #include "doom_nuken.h" int main_new(t_doom *den) { int ret; SDL_Init(SDL_INIT_EVERYTHING); TTF_Init(); Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 2048); ret = get_3d_def_new(den); if (ret == 0) { write(1, "Error, check your files which need to be exist\n", 47); return (0); } else if (ret == -1) { write(1, "OpenCL initialization error\n", 28); den->iw.v.kernel = 0; } den->color = 0xFFFFFF; den->b_color = 0x505050; ft_sdl_init(den); return (0); } void get_3d_def_new_init(t_doom *den) { den->iw.v.game_mode = 0; den->iw.v.kernel = 1; den->iw.l.accel = 9.81f; den->iw.l.skybox = 13; den->iw.l.story = 9; } int get_3d_def_new(t_doom *den) { int ret; get_3d_def_new_init(den); den->iw.v.look_wall = (t_wall **)malloc(sizeof(t_wall *)); den->iw.v.look_sector = (t_sector **)malloc(sizeof(t_sector *)); den->iw.v.look_picture = (t_picture **)malloc(sizeof(t_picture *)); den->iw.sprite = (t_sprite **)malloc(sizeof(t_sprite *)); den->iw.vw_save = (t_save_wall **)malloc(sizeof(t_save_wall *)); den->iw.checkpoints = 0; den->iw.sector_animations = 0; den->iw.wall_animations = 0; get_font_file(den); load_kernel(&den->iw.k, &den->iw); read_textures(&den->iw); read_sprites_textures(&den->iw); read_weapons_textures(&den->iw); get_sounds(&den->iw); if ((ret = check_all_validation(&den->iw)) == 0) return (0); get_packaging_textures(&den->iw); get_kernel_mem(&den->iw); get_kernels(&den->iw); get_guns(&den->iw); return (ret); } void save_map_info(t_doom *den) { char *cmp; SDL_Color color_text; clean_string(den); color_text.g = 255; color_text.r = 0; color_text.b = 0; cmp = "map SAVED\n"; den->TTF_TextSolid = TTF_RenderText_Blended_Wrapped(den->font, cmp, color_text, 200); den->rect.x = 1770; den->rect.y = 380; den->rect.h = 50; den->rect.w = 30; SDL_BlitSurface(den->TTF_TextSolid, NULL, den->bmp, &den->rect); SDL_FreeSurface(den->TTF_TextSolid); SDL_UpdateWindowSurface(den->window); } <|start_filename|>3d/SRC2/enemies_main_functions3.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* enemies_main_functions3.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbolilyi <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/05 16:46:42 by dbolilyi #+# #+# */ /* Updated: 2019/03/05 16:46:43 by dbolilyi ### ########.fr */ /* */ /* ************************************************************************** */ #include "../guardians.h" int enemy_sees_player3(t_sdl *iw, t_sprite *s, t_enemy_sees_player *esp) { esp->a = (float)(esp->py - esp->ey); esp->b = (float)(esp->ex - esp->px); esp->c = (float)(esp->px * esp->ey - esp->ex * esp->py); if (!esp_check_walls(iw, esp)) return (-1); s->e.vis_esp = *esp; return ((int)sqrtf(powf(esp->px - esp->ex, 2.0f) + powf(esp->py - esp->ey, 2.0f))); } int enemy_sees_player(t_sdl *iw, t_sprite *s) { t_enemy_sees_player esp; t_sector_ways *ways; t_sector_way *way; int ret; esp.px = iw->p.x; esp.py = iw->p.y; esp.ex = s->x; esp.ey = s->y; esp.curr_sector = s->num_sec; if (iw->d.cs == s->num_sec) return (esp_check_return(iw, s, enemy_sees_player3(iw, s, &esp))); ways = iw->ways[s->num_sec][iw->d.cs]; while (ways) { way = ways->way_start; esp_get_new_player_coordinates(iw, way, &esp, s); if ((ret = enemy_sees_player2(iw, s, way, &esp)) != -1) return (esp_check_return(iw, s, ret)); ways = ways->next; } return (-1); } int move_enemy_in_portal2_1(t_sdl *iw, t_sprite *s, t_intpoint2d *vect, int wall) { int nx; int ny; nx = s->x + vect->x + iw->walls[iw->walls[wall].nextsector_wall].x - iw->walls[wall].next->x; ny = s->y + vect->y + iw->walls[iw->walls[wall].nextsector_wall].y - iw->walls[wall].next->y; if (get_ceil_z_sec(iw, nx, ny, iw->walls[wall].nextsector) - get_floor_z_sec(iw, nx, ny, iw->walls[wall].nextsector) < SPRITE_HEIGHT || get_floor_z_sec(iw, nx, ny, iw->walls[wall].nextsector) - s->z > ENEMY_MAX_CLIMB_HEIGHT || get_ceil_z_sec(iw, nx, ny, iw->walls[wall].nextsector) < s->z + SPRITE_HEIGHT) return (0); s->x = nx; s->y = ny; s->num_sec = iw->walls[wall].nextsector; s->e.vis_esp.ex += iw->walls[iw->walls[wall].nextsector_wall].x - iw->walls[wall].next->x; s->e.vis_esp.ey += iw->walls[iw->walls[wall].nextsector_wall].y - iw->walls[wall].next->y; s->e.vis_esp.px += iw->walls[iw->walls[wall].nextsector_wall].x - iw->walls[wall].next->x; s->e.vis_esp.py += iw->walls[iw->walls[wall].nextsector_wall].y - iw->walls[wall].next->y; return (1); } int move_enemy_in_portal2(t_sdl *iw, t_sprite *s, t_intpoint2d *vect, int wall) { float k1; float k2; s->e.vis_esp.a = (float)vect->y; s->e.vis_esp.b = (float)(-vect->x); s->e.vis_esp.c = (float)((s->x + vect->x) * s->y - s->x * (s->y + vect->y)); k1 = s->e.vis_esp.a * iw->walls[wall].x + s->e.vis_esp.b * iw->walls[wall].y + s->e.vis_esp.c; k2 = s->e.vis_esp.a * iw->walls[wall].next->x + s->e.vis_esp.b * iw->walls[wall].next->y + s->e.vis_esp.c; if ((!((k1 < 0.0f && k2 > 0.0f) || (k1 > 0.0f && k2 < 0.0f))) || (!move_enemy_in_portal2_1(iw, s, vect, wall))) return (0); return (1); } int move_enemy_in_portal(t_sdl *iw, t_sprite *s, t_intpoint2d *vect) { int wall; float k1; float k2; wall = iw->sectors[s->num_sec].sw - 1; while (++wall < iw->sectors[s->num_sec].sw + iw->sectors[s->num_sec].nw) { if (iw->walls[wall].nextsector == -1 || iw->walls[wall].glass != -1) continue; k1 = iw->walls[wall].l.a * s->x + iw->walls[wall].l.b * s->y + iw->walls[wall].l.c; k2 = iw->walls[wall].l.a * (s->x + vect->x) + iw->walls[wall].l.b * (s->y + vect->y) + iw->walls[wall].l.c; if (((k1 < 0.0f && k2 > 0.0f) || (k1 > 0.0f && k2 < 0.0f)) && move_enemy_in_portal2(iw, s, vect, wall)) return (1); } return (0); } <|start_filename|>editor/walls.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* walls.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ddehtyar <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/02/20 17:38:17 by ddehtyar #+# #+# */ /* Updated: 2019/02/20 17:38:18 by ddehtyar ### ########.fr */ /* */ /* ************************************************************************** */ #include "doom_nuken.h" void change_rec(t_doom *den, t_col *rec, t_wals *tmp) { rec->x1 = tmp->x * XSKAPE; rec->y1 = tmp->y * YSKAPE; rec->x2 = tmp->x1 * XSKAPE; rec->y2 = tmp->y1 * YSKAPE; } void next_wall_change(t_doom *den, t_wals *tmp, t_wals *rmp) { den->color = 0xFFFFFF; if (rmp->nextsector_wall) den->color = 0xFF0000; ft_line(den, &den->rec); den->rec.x1 = tmp->x * XSKAPE; den->rec.y1 = tmp->y * YSKAPE; den->rec.x2 = tmp->x1 * XSKAPE; den->rec.y2 = tmp->y1 * YSKAPE; den->color = 0x00FF00; ft_line(den, &den->rec); } void next_wall(t_doom *den) { t_wals *tmp; tmp = den->tmp; if (den->find_tmp->next && den->find_tmp->next->sec == den->rec.sect) { next_wall_change(den, den->find_tmp->next, den->find_tmp); den->find_tmp = den->find_tmp->next; den->find_tmp_one = den->find_tmp; } else { while (tmp) { if (tmp->sec == den->rec.sect) { den->find_tmp = tmp; den->find_tmp_one = den->find_tmp; next_wall_change(den, den->find_tmp, den->find_tmp); break ; } tmp = tmp->next; } } look_find_sector_two(den); den->color = 0xFFFFFF; } void back_wall_check(t_doom *den, t_wals *rmp, t_wals *lmp) { while (den->tmp->next->next != 0) den->tmp = den->tmp->next; if (den->tmp->blouk != 1) { rmp = den->tmp->next; den->tmp->next = NULL; free(rmp); den->walls -= 1; } else if (den->tmp->sec != den->tmp->next->sec) { rmp = den->tmp->next; den->tmp->next = NULL; free(rmp); den->blouk = 1; den->walls -= 1; } den->tmp = lmp; } void back_wall(t_doom *den, t_col *vec) { t_wals *rmp; t_wals *lmp; lmp = den->tmp; rmp = den->tmp; if (den->tmp) { if (den->tmp->next != 0) back_wall_check(den, rmp, lmp); else if (den->tmp->next == 0) { rmp = den->tmp; free(rmp); den->tmp = NULL; den->blouk = 1; den->walls -= 1; } } retry_write(den, vec); } <|start_filename|>3d/SRC3/draw_wall_floor_ceil2.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* draw_wall_floor_ceil2.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbolilyi <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/05 17:13:21 by dbolilyi #+# #+# */ /* Updated: 2019/03/05 17:13:22 by dbolilyi ### ########.fr */ /* */ /* ************************************************************************** */ #include "../guardians.h" void draw_wall_floor_ceil_tex1(t_sdl *iw, t_save_wall *left, t_save_wall *right, t_draw_wall_floor_ceil_tex *d) { d->lv.x = (float)(left->p.x - iw->p.x); d->lv.y = (float)(left->p.y - iw->p.y); d->rv.x = (float)(right->p.x - iw->p.x); d->rv.y = (float)(right->p.y - iw->p.y); d->ang = acosf((d->lv.x * d->rv.x + d->lv.y * d->rv.y) / (sqrtf(d->lv.x * d->lv.x + d->lv.y * d->lv.y) * sqrtf(d->rv.x * d->rv.x + d->rv.y * d->rv.y))); d->dang = d->ang / (float)(right->x - left->x + 1); d->ang = 0.0f; d->rv.x = (float)(-right->p.x + left->p.x); d->rv.y = (float)(-right->p.y + left->p.y); d->sing = G180 - acosf((d->lv.x * d->rv.x + d->lv.y * d->rv.y) / (sqrtf(d->lv.x * d->lv.x + d->lv.y * d->lv.y) * sqrtf(d->rv.x * d->rv.x + d->rv.y * d->rv.y))); d->lenpl = sqrtf(powf(iw->p.x - left->p.x, 2.0f) + powf(iw->p.y - left->p.y, 2.0f)); d->len_lr = sqrtf(powf(left->p.x - right->p.x, 2.0f) + powf(left->p.y - right->p.y, 2.0f)); d->rv.x = (float)(right->p.x - left->p.x) / d->len_lr; d->rv.y = (float)(right->p.y - left->p.y) / d->len_lr; d->zu = get_ceil_z(iw, 0, 0); d->zd = get_floor_z(iw, 0, 0); d->frpl = (float)(d->zu - d->zd) / (float)(iw->p.z - d->zd); d->clpl = (float)(d->zu - d->zd) / (float)(d->zu - iw->p.z); d->px = (float)iw->p.x / 1000.0f; } void draw_wall_floor_ceil_tex2(t_sdl *iw, t_save_wall *left, t_draw_wall_floor_ceil_tex *d) { d->left_len = sinf(d->ang) * d->lenpl / sinf(d->sing - d->ang); d->r.x = (float)left->p.x + d->rv.x * d->left_len; d->r.y = (float)left->p.y + d->rv.y * d->left_len; d->wall_dist = (float)WINDOW_H / (fabsf(iw->d.screen.a * d->r.x + iw->d.screen.b * d->r.y + iw->d.screen.c) / iw->d.screen_len) * d->frcoef; d->r.x /= 1000.0f; d->r.y /= 1000.0f; } <|start_filename|>3d/SRC3/draw_wall_floor_ceil.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* draw_wall_floor_ceil.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbolilyi <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/05 13:03:56 by dbolilyi #+# #+# */ /* Updated: 2019/03/05 13:03:57 by dbolilyi ### ########.fr */ /* */ /* ************************************************************************** */ #include "../guardians.h" void draw_wall_floor_ceil_tex3(t_sdl *iw, t_save_wall *left, t_draw_wall_floor_ceil_tex *d) { if (iw->d.wallBot[d->j] < iw->d.top[left->x + d->j]) d->i = iw->d.top[left->x + d->j] - 1; else d->i = iw->d.wallBot[d->j] - 1; d->k = (float)(iw->d.wallBot[d->j] - iw->d.wallTop[d->j]) + d->frpl * (float)(d->i + 1 - iw->d.wallBot[d->j]); while (++d->i < iw->d.bottom[left->x + d->j]) { d->weight = d->wall_dist / d->k; d->k += d->frpl; d->floor.x = d->weight * d->r.x + (1.0f - d->weight) * d->px; d->floor.y = d->weight * d->r.y + (1.0f - d->weight) * d->py; set_pixel2(iw->sur, left->x + d->j, d->i, get_light_color(get_pixel(iw->t[iw->sectors[iw->d.cs].fr.t], ((d->floor.x < 0) ? (((int)(d->floor.x * (float)iw->t[iw->sectors[iw->d.cs]. fr.t]->w) % iw->t[iw->sectors[iw->d.cs].fr.t]->w) + iw->t[iw->sectors[iw-> d.cs].fr.t]->w - 1) : ((int)(d->floor.x * (float)iw->t[iw->sectors[iw->d. cs].fr.t]->w) % iw->t[iw->sectors[iw->d.cs].fr.t]->w)), ((d->floor.y < 0) ? (((int)(d->floor.y * (float)iw->t[iw->sectors[iw->d.cs].fr.t]->h) % iw->t [iw->sectors[iw->d.cs].fr.t]->h) + iw->t[iw->sectors[iw->d.cs].fr.t]->h - 1) : ((int)(d->floor.y * (float)iw->t[iw->sectors[iw->d.cs].fr.t]->h) % iw->t[iw->sectors[iw->d.cs].fr.t]->h))), iw->sectors[iw->d.cs].light)); } iw->d.bottom[left->x + d->j] = iw->d.wallBot[d->j]; } void draw_wall_floor_ceil_tex4(t_sdl *iw, t_save_wall *left, t_draw_wall_floor_ceil_tex *d) { if (iw->d.wallTop[d->j] < iw->d.bottom[left->x + d->j]) d->i = iw->d.wallTop[d->j] + 1; else d->i = iw->d.bottom[left->x + d->j] + 1; d->k = (float)(iw->d.wallBot[d->j] - iw->d.wallTop[d->j]) + d->clpl * (float)(iw->d.wallTop[d->j] - d->i + 1); while (--d->i >= iw->d.top[left->x + d->j]) { d->weight = d->wall_dist / d->k; d->k += d->clpl; d->floor.x = d->weight * d->r.x + (1.0f - d->weight) * d->px; d->floor.y = d->weight * d->r.y + (1.0f - d->weight) * d->py; set_pixel2(iw->sur, left->x + d->j, d->i, get_light_color(get_pixel(iw->t[iw->sectors[iw->d.cs].cl.t], ((d->floor.x < 0) ? (((int)(d->floor.x * (float)iw->t[iw->sectors[iw->d.cs]. cl.t]->w) % iw->t[iw->sectors[iw->d.cs].cl.t]->w) + iw->t[iw->sectors[iw-> d.cs].cl.t]->w - 1) : ((int)(d->floor.x * (float)iw->t[iw->sectors[iw->d. cs].cl.t]->w) % iw->t[iw->sectors[iw->d.cs].cl.t]->w)), ((d->floor.y < 0) ? (((int)(d->floor.y * (float)iw->t[iw->sectors[iw->d.cs].cl.t]->h) % iw->t [iw->sectors[iw->d.cs].cl.t]->h) + iw->t[iw->sectors[iw->d.cs].cl.t]->h - 1) : ((int)(d->floor.y * (float)iw->t[iw->sectors[iw->d.cs].cl.t]->h) % iw-> t[iw->sectors[iw->d.cs].cl.t]->h))), iw->sectors[iw->d.cs].light)); } iw->d.top[left->x + d->j] = iw->d.wallTop[d->j]; } void draw_wall_floor_ceil_tex5_1(t_sdl *iw, t_save_wall *left, t_draw_wall_floor_ceil_tex *d) { while (++d->i < iw->d.bottom[left->x + d->j]) { set_pixel2(iw->sur, left->x + d->j, d->i, get_light_color(get_pixel(iw->t[left->wall->t], (int)d->tx % iw->t[left->wall->t]->w, (int)d->ty % iw->t[left->wall->t]->h), iw->sectors[iw->d.cs].light)); d->ty += d->dty; } if (iw->d.wallTop[d->j] < iw->d.top[d->j + left->x] && iw->d.top[left->x + d->j] < iw->d.bottom[left->x + d->j]) iw->d.bottom[left->x + d->j] = iw->d.top[left->x + d->j] - 1; else if (iw->d.wallTop[d->j] >= iw->d.top[d->j + left->x] && iw->d.wallTop[d->j] < iw->d.bottom[left->x + d->j]) iw->d.bottom[left->x + d->j] = iw->d.wallTop[d->j] - 1; } void draw_wall_floor_ceil_tex5(t_sdl *iw, t_save_wall *left, t_draw_wall_floor_ceil_tex *d) { d->ty_tsz = iw->tsz[left->wall->t] * (float)iw->t[left->wall->t]->w / (float)iw->t[left->wall->t]->h; d->tx = (left->olen + d->left_len) * (float)iw->t[left->wall->t]->w * iw->tsz[left->wall->t] / 1000.0f; if (iw->d.wallTop[d->j] < iw->d.top[d->j + left->x]) d->ty = d->zu + d->ty_tsz * (d->zu - d->zd) * (float)(iw->d.top[d->j + left->x] - iw->d.wallTop[d->j]) / (float)(iw->d.wallBot[d->j] - iw->d.wallTop[d->j]); else d->ty = d->zu; d->ty = d->ty * (float)iw->t[left->wall->t]->h / 1000.0f; d->dty = ((d->zu - d->zd) * (float)iw->t[left->wall->t]->h / 1000.0f) / ( float)(iw->d.wallBot[d->j] - iw->d.wallTop[d->j]) * d->ty_tsz; if (iw->d.wallTop[d->j] < iw->d.top[d->j + left->x]) d->i = iw->d.top[left->x + d->j] - 1; else d->i = iw->d.wallTop[d->j] - 1; draw_wall_floor_ceil_tex5_1(iw, left, d); } void draw_wall_floor_ceil_tex(t_sdl *iw, t_save_wall *left, t_save_wall *right, int len) { t_draw_wall_floor_ceil_tex d; draw_wall_floor_ceil_tex1(iw, left, right, &d); d.py = (float)iw->p.y / 1000.0f; d.frcoef = d.zu - d.zd; d.j = -1; while (++d.j < len) { if (iw->d.top[left->x + d.j] >= iw->d.bottom[left->x + d.j]) { d.ang += d.dang; continue; } draw_wall_floor_ceil_tex2(iw, left, &d); if (iw->d.wallBot[d.j] < iw->d.bottom[left->x + d.j]) draw_wall_floor_ceil_tex3(iw, left, &d); if (iw->d.wallTop[d.j] > iw->d.top[left->x + d.j] && iw->sectors[iw->d.cs].cl.t >= 0) draw_wall_floor_ceil_tex4(iw, left, &d); if (left->wall->t >= 0) draw_wall_floor_ceil_tex5(iw, left, &d); d.ang += d.dang; } } <|start_filename|>editor/save3.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* save3.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: elopukh <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/05 15:42:18 by elopukh #+# #+# */ /* Updated: 2019/03/05 15:42:18 by elopukh ### ########.fr */ /* */ /* ************************************************************************** */ #include "doom_nuken.h" void set_sector_anim_wall_trig_numbs(t_doom *den, t_sector_animation *sec) { t_wals *tmp; t_picture *pic; int num_wall; int num_pic; tmp = den->tmp; num_wall = 0; while (tmp) { pic = tmp->p; num_pic = 0; while (pic) { if (pic == sec->trigger) { sec->trig_wall_numb = num_wall; sec->trig_pic_numb = num_pic; return ; } pic = pic->next; num_pic++; } tmp = tmp->next; num_wall++; } } void save_reverse_map_sector_animations(t_doom *den, t_sector_animation *tmp) { if (tmp->next != 0) save_reverse_map_sector_animations(den, tmp->next); set_sector_anim_wall_trig_numbs(den, tmp); write(den->fd, tmp, sizeof(t_sector_animation)); } void save_map_sector_animations(t_doom *den) { t_sector_animation *tmp; int count; count = 0; tmp = den->iw.sector_animations; while (tmp) { count++; tmp = tmp->next; } write(den->fd, &count, sizeof(int)); if (den->iw.sector_animations) save_reverse_map_sector_animations(den, den->iw.sector_animations); } void set_wall_anim_wall_trig_numbs(t_doom *den, t_wall_animation *sec) { t_wals *tmp; t_picture *pic; int num_wall; int num_pic; tmp = den->tmp; num_wall = 0; while (tmp) { pic = tmp->p; num_pic = 0; while (pic) { if (pic == sec->trigger) { sec->trig_wall_numb = num_wall; sec->trig_pic_numb = num_pic; return ; } pic = pic->next; num_pic++; } tmp = tmp->next; num_wall++; } } void save_reverse_map_wall_animations(t_doom *den, t_wall_animation *tmp) { if (tmp->next != 0) save_reverse_map_wall_animations(den, tmp->next); set_wall_anim_wall_trig_numbs(den, tmp); write(den->fd, tmp, sizeof(t_wall_animation)); } <|start_filename|>editor/sort_sector.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* sort_sector.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ddehtyar <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/02/04 18:34:08 by ddehtyar #+# #+# */ /* Updated: 2019/02/04 18:34:09 by ddehtyar ### ########.fr */ /* */ /* ************************************************************************** */ #include "doom_nuken.h" void sort_sector(t_doom *den) { t_wals *tmp; tmp = den->tmp; if (tmp->sec == den->sec - 1) { if (isleft_or_right(tmp) < 0) sort_walls_sec(tmp); } else { while (tmp) { if (tmp->sec == den->sec - 1) { if (isleft_or_right(tmp) < 0) { sort_walls_sec(tmp); break ; } else break ; } tmp = tmp->next; } } } void add_sector_dir(t_wals *tmp, t_wals *last, t_sort *sort) { float ang; sort->l.a = (float)sort->v1.y; sort->l.b = (float)(-sort->v1.x); sort->l.c = -sort->l.a * (float)tmp->x - sort->l.b * (float)tmp->y; ang = G180 - acosf((sort->v1.x * sort->v2.x + sort->v1.y * sort->v2.y) / sqrtf(sort->v1.x * sort->v1.x + sort->v1.y * sort->v1.y) / sqrtf(sort->v2.x * sort->v2.x + sort->v2.y * sort->v2.y)); if (sort->l.a * (float)last->x + sort->l.b * (float)last->y + sort->l.c > 0) sort->sector_dir += ang; else sort->sector_dir -= ang; } float isleft_or_right(t_wals *list) { t_wals *tmp; t_sort sort; sort.sector_dir = 0.0f; tmp = list; while (tmp->next->next) { sort.v1.x = tmp->x - tmp->next->x; sort.v1.y = tmp->y - tmp->next->y; sort.v2.x = tmp->next->next->x - tmp->next->x; sort.v2.y = tmp->next->next->y - tmp->next->y; add_sector_dir(tmp, tmp->next->next, &sort); tmp = tmp->next; } sort.v1.x = tmp->x - tmp->next->x; sort.v1.y = tmp->y - tmp->next->y; sort.v2.x = list->x - tmp->next->x; sort.v2.y = list->y - tmp->next->y; add_sector_dir(tmp, list, &sort); sort.v1.x = tmp->next->x - list->x; sort.v1.y = tmp->next->y - list->y; sort.v2.x = list->next->x - list->x; sort.v2.y = list->next->y - list->y; add_sector_dir(tmp->next, list->next, &sort); return (sort.sector_dir); } void sort_list_incide(t_doom *den) { t_wals *rmp; rmp = den->tmp; while (den->tmp->next) { if (den->tmp->inside == 1 && den->tmp->sec == den->sec - 1) { if (isleft_or_right(den->tmp) > 0) { sort_walls_inside(den); break ; } } den->tmp = den->tmp->next; } den->tmp = rmp; } void check_data_sector(t_doom *den) { t_wals *rmp; rmp = den->tmp; while (den->tmp) { if (den->tmp->sec == den->sec - 1) { den->tmp->inside += den->xy.inside; den->tmp->sec = den->xy.bool_cor; } den->tmp = den->tmp->next; } den->tmp = rmp; den->sec -= 1; den->secbak -= 1; } <|start_filename|>3d/SRC3/draw_inclined_wall_floor_ceil.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* draw_inclined_wall_floor_ceil.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbolilyi <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/05 13:03:14 by dbolilyi #+# #+# */ /* Updated: 2019/03/05 13:03:15 by dbolilyi ### ########.fr */ /* */ /* ************************************************************************** */ #include "../guardians.h" void draw_inclined_wall_floor_ceil_tex2(t_sdl *iw, t_save_wall *left, t_draw_wall_floor_ceil_tex *d) { d->left_len = sinf(d->ang) * d->lenpl / sinf(d->sing - d->ang); d->r.x = (float)left->p.x + d->rv.x * d->left_len; d->r.y = (float)left->p.y + d->rv.y * d->left_len; d->frcoef = get_ceil_z(iw, d->r.x, d->r.y) - get_floor_z(iw, d->r.x, d->r.y); d->clcoef = d->frcoef; d->wall_dist = (float)WINDOW_H / (fabsf(iw->d.screen.a * d->r.x + iw->d.screen.b * d->r.y + iw->d.screen.c) / iw->d.screen_len); d->r.x /= 1000.0f; d->r.y /= 1000.0f; if (iw->d.wallBot[d->j] < iw->d.bottom[left->x + d->j]) { if (iw->d.wallBot[d->j] < iw->d.top[left->x + d->j]) d->i = iw->d.top[left->x + d->j] - 1; else d->i = iw->d.wallBot[d->j] - 1; draw_inclined_wall_floor_ceil_tex3(iw, left, d); } } void draw_inclined_wall_floor_ceil_tex4(t_sdl *iw, t_save_wall *left, t_draw_wall_floor_ceil_tex *d) { d->k = (float)(iw->d.wallBot[d->j] - iw->d.wallTop[d->j]) + d->clpl * (float)(iw->d.wallTop[d->j] - d->i + 1); while (--d->i >= iw->d.top[left->x + d->j]) { d->weight = d->wall_dist * d->clcoef / d->k; d->k += d->clpl; d->floor.x = d->weight * d->r.x + (1.0f - d->weight) * d->px; d->floor.y = d->weight * d->r.y + (1.0f - d->weight) * d->py; d->clcoef = (get_ceil_z(iw, d->floor.x * 1000.0f, d->floor.y * 1000.0f) - get_floor_z(iw, d->floor.x * 1000.0f, d->floor.y * 1000.0f) + d->clcoef) / 2.0f; set_pixel2(iw->sur, left->x + d->j, d->i, get_light_color(get_pixel(iw->t[iw->sectors[iw->d.cs].cl.t], ((d->floor.x < 0) ? (((int)(d->floor.x * (float)iw->t[iw->sectors[iw->d.cs]. cl.t]->w) % iw->t[iw->sectors[iw->d.cs].cl.t]->w) + iw->t[iw->sectors[iw-> d.cs].cl.t]->w - 1) : ((int)(d->floor.x * (float)iw->t[iw->sectors[iw->d.cs ].cl.t]->w) % iw->t[iw->sectors[iw->d.cs].cl.t]->w)), ((d->floor.y < 0) ? (((int)(d->floor.y * (float)iw->t[iw->sectors[iw->d.cs].cl.t]->h) % iw->t [iw->sectors[iw->d.cs].cl.t]->h) + iw->t[iw->sectors[iw->d.cs].cl.t]->h - 1) : ((int)(d->floor.y * (float)iw->t[iw->sectors[iw->d.cs].cl.t]->h) % iw->t[iw->sectors[iw->d.cs].cl.t]->h))), iw->sectors[iw->d.cs].light)); } iw->d.top[left->x + d->j] = iw->d.wallTop[d->j]; } void draw_inclined_wall_floor_ceil_tex5(t_sdl *iw, t_save_wall *left, t_draw_wall_floor_ceil_tex *d) { d->zu = (float)left->zu + d->left_len * d->zudiff; d->zd = (float)left->zd + d->left_len * d->zddiff; if (iw->d.wallTop[d->j] < iw->d.top[d->j + left->x]) d->ty = d->zu + d->ty_tsz * (d->zu - d->zd) * (float)(iw->d.top[d->j + left->x] - iw->d.wallTop[d->j]) / (float)(iw->d.wallBot[d->j] - iw->d.wallTop[d->j]); else d->ty = d->zu; d->ty = d->ty * (float)iw->t[left->wall->t]->h / 1000.0f; d->dty = ((d->zu - d->zd) * (float)iw->t[left->wall->t]->h / 1000.0f) / (float)(iw->d.wallBot[d->j] - iw->d.wallTop[d->j]) * d->ty_tsz; if (iw->d.wallTop[d->j] < iw->d.top[d->j + left->x]) d->i = iw->d.top[left->x + d->j] - 1; else d->i = iw->d.wallTop[d->j] - 1; while (++d->i < iw->d.bottom[left->x + d->j]) { set_pixel2(iw->sur, left->x + d->j, d->i, get_light_color(get_pixel(iw->t[left->wall->t], (int)d->tx % iw->t[left->wall->t]->w, (int)d->ty % iw->t[left->wall->t]->h), iw->sectors[iw->d.cs].light)); d->ty += d->dty; } } void draw_inclined_wall_floor_ceil_tex6(t_sdl *iw, t_save_wall *left, t_draw_wall_floor_ceil_tex *d) { if (iw->d.wallTop[d->j] > iw->d.top[left->x + d->j] && iw->sectors[iw->d.cs].cl.t >= 0) { if (iw->d.wallTop[d->j] < iw->d.bottom[left->x + d->j]) d->i = iw->d.wallTop[d->j] + 1; else d->i = iw->d.bottom[left->x + d->j] + 1; draw_inclined_wall_floor_ceil_tex4(iw, left, d); } if (left->wall->t >= 0) { d->ty_tsz = iw->tsz[left->wall->t] * (float)iw->t[left->wall->t]->w / (float)iw->t[left->wall->t]->h; d->tx = (left->olen + d->left_len) * (float)iw->t[left->wall->t]->w * iw->tsz[left->wall->t] / 1000.0f; draw_inclined_wall_floor_ceil_tex5(iw, left, d); if (iw->d.wallTop[d->j] < iw->d.top[d->j + left->x] && iw->d.top[left->x + d->j] < iw->d.bottom[left->x + d->j]) iw->d.bottom[left->x + d->j] = iw->d.top[left->x + d->j] - 1; else if (iw->d.wallTop[d->j] >= iw->d.top[d->j + left->x] && iw->d.wallTop[d->j] < iw->d.bottom[left->x + d->j]) iw->d.bottom[left->x + d->j] = iw->d.wallTop[d->j] - 1; } } void draw_inclined_wall_floor_ceil_tex(t_sdl *iw, t_save_wall *left, t_save_wall *right, int len) { t_draw_wall_floor_ceil_tex d; draw_inclined_wall_floor_ceil_tex1(iw, left, right, &d); d.clpl = (float)(d.zu - d.zd) / (float)(d.zu - iw->p.z); d.px = (float)iw->p.x / 1000.0f; d.py = (float)iw->p.y / 1000.0f; d.j = -1; while (++d.j < len) { if (iw->d.top[left->x + d.j] >= iw->d.bottom[left->x + d.j]) { d.ang += d.dang; continue; } draw_inclined_wall_floor_ceil_tex2(iw, left, &d); draw_inclined_wall_floor_ceil_tex6(iw, left, &d); d.ang += d.dang; } } <|start_filename|>3d/SRC/wall_animations2.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* wall_animations2.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbolilyi <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/05 15:26:33 by dbolilyi #+# #+# */ /* Updated: 2019/03/05 15:26:35 by dbolilyi ### ########.fr */ /* */ /* ************************************************************************** */ #include "../guardians.h" void draw_selected_walls_to_be_animated(t_sdl *iw) { t_save_wall *tmp; int i; int y; tmp = *(iw->vw_save); while (tmp) { i = -1; while (++i < iw->v.wall_anim->count_walls) if (iw->walls[iw->v.wall_anim->walls[i]].next == tmp->wall || iw->walls[iw->v.wall_anim->walls[i]].next->next == tmp->wall) { y = 0; while (++y < WINDOW_H) set_pixel2(iw->sur, tmp->x, y, 0xFF0000); break ; } tmp = tmp->next; } } void exit_editing_wall_animation(t_sdl *iw) { if (iw->v.submenu_mode >= 7) { do_wall_animation_step_dx(iw, iw->v.wall_anim, -iw->v.wall_anim->dx); do_wall_animation_step_dy(iw, iw->v.wall_anim, -iw->v.wall_anim->dy); } free(iw->v.wall_anim); iw->v.wall_anim = 0; iw->v.submenu_mode = 0; draw_submenu(iw); } void change_wall_animation_status(t_sdl *iw, t_picture *p) { t_wall_animation *tmp; tmp = iw->wall_animations; while (tmp) { if (tmp->trigger == p) { tmp->status = ((tmp->status == 0) ? 1 : 0); return ; } tmp = tmp->next; } } <|start_filename|>editor/init_sdl.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* init_sdl.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ddehtyar <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/04 11:40:51 by ddehtyar #+# #+# */ /* Updated: 2019/03/04 11:40:53 by ddehtyar ### ########.fr */ /* */ /* ************************************************************************** */ #include "doom_nuken.h" void mouse_button_down_sdl(t_doom *den, t_col *vec, SDL_Event e) { if (e.button.button == SDL_BUTTON_LEFT && den->select == 0) { if (den->blockwall == 1) mouse_button_rotate(den, vec, e.button.x, e.button.y); else if (den->blockwall == 2) mouse_button_sprite(den, vec, e.button.x, e.button.y); else if (e.button.x <= den->border) mouse_button_down(den, vec, e.button.x, e.button.y); } else if (e.button.button == SDL_BUTTON_LEFT && den->select == 1 && e.button.x <= den->border) blouk_write(den); if (e.button.button == SDL_BUTTON_RIGHT && den->select == 1 && den->blouk == 1) mouse_button_down_select(den, vec, e); } void mouse_button_down_up_sdl(t_doom *den, t_col *vec, SDL_Event e) { if (e.button.button == SDL_BUTTON_LEFT && e.button.x <= den->border && den->blockwall == 0 && den->select == 0) den->button = den->button == 1 ? 0 : 1; if (e.button.x > den->border) pres_button(e.button.x, e.button.y, den, vec); } void key_down_sdl(t_doom *den, t_col *vec, const Uint8 *state) { if (state[SDL_SCANCODE_ESCAPE]) den->quit = 1; else key_down_but(den, vec, state); } void ft_sdl_init(t_doom *den) { SDL_Event e; const Uint8 *state; t_col vec; ft_sdl_init_star(den, &vec); state = SDL_GetKeyboardState(NULL); while (!den->quit) { while (SDL_PollEvent(&e)) { if (e.type == SDL_QUIT) den->quit = 1; if (e.type == SDL_KEYDOWN) key_down_sdl(den, &vec, state); else if (e.type == SDL_MOUSEBUTTONDOWN) mouse_button_down_sdl(den, &vec, e); else if (e.type == SDL_MOUSEBUTTONUP) mouse_button_down_up_sdl(den, &vec, e); else if (e.type == SDL_MOUSEWHEEL) mousewheel(den, &vec, e.wheel.y); } } SDL_DestroyWindow(den->window); free_surface(den); SDL_Quit(); } <|start_filename|>editor/load_animation.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* animation.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: kkostrub <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/05 15:48:03 by kkostrub #+# #+# */ /* Updated: 2019/03/05 17:34:01 by kkostrub ### ########.fr */ /* */ /* ************************************************************************** */ #include "doom_nuken.h" int load_map_sector_animations_1(t_doom *den, t_sector_animation *tmp, t_picture *pic) { t_wals *w; int j; j = -1; w = den->tmp; while (w && ++j < tmp->trig_wall_numb) w = w->next; if (!w) { free(tmp); return (0); } pic = w->p; j = -1; while (pic && ++j < tmp->trig_pic_numb) pic = pic->next; if (!pic) { free(tmp); return (0); } tmp->trigger = pic; tmp->prev_clock = clock(); tmp->next = den->iw.sector_animations; return (1); } int load_map_sector_animations(t_doom *den) { int count_anim; int i; t_sector_animation *tmp; t_picture *pic; pic = 0; den->iw.sector_animations = 0; if (!read_check(den->fd, &count_anim, sizeof(int))) return (0); i = -1; while (++i < count_anim) { tmp = (t_sector_animation *)malloc(sizeof(t_sector_animation)); if (!read_check(den->fd, tmp, sizeof(t_sector_animation))) { free(tmp); return (0); } if (!load_map_sector_animations_1(den, tmp, pic)) return (0); den->iw.sector_animations = tmp; } return (1); } int load_map_wall_animations_1(t_doom *den, t_wall_animation *tmp) { t_wals *w; t_picture *pic; int j; j = -1; w = den->tmp; while (w && ++j < tmp->trig_wall_numb) w = w->next; if (!w) { free(tmp); return (0); } pic = w->p; j = -1; while (pic && ++j < tmp->trig_pic_numb) pic = pic->next; if (!pic) { free(tmp); return (0); } tmp->trigger = pic; tmp->prev_clock = 0; return (1); } int load_map_wall_animations(t_doom *den) { int count_anim; int i; t_wall_animation *tmp; den->iw.wall_animations = 0; if (!read_check(den->fd, &count_anim, sizeof(int))) return (0); i = -1; while (++i < count_anim) { tmp = (t_wall_animation *)malloc(sizeof(t_wall_animation)); if (!read_check(den->fd, tmp, sizeof(t_wall_animation))) { free(tmp); return (0); } if (!load_map_wall_animations_1(den, tmp)) return (0); tmp->next = den->iw.wall_animations; den->iw.wall_animations = tmp; } return (1); } <|start_filename|>3d/SRC3/draw_skybox.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* draw_skybox.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbolilyi <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/05 13:03:36 by dbolilyi #+# #+# */ /* Updated: 2019/03/05 13:03:37 by dbolilyi ### ########.fr */ /* */ /* ************************************************************************** */ #include "../guardians.h" void draw_skybox2(t_sdl *iw, t_draw_skybox *d) { d->rot = iw->p.rot - iw->v.angle; if (d->rot < 0.0f) d->rot += G360; d->dx = (float)iw->t[iw->l.skybox]->w / (G360 / (iw->v.angle * 2) * WINDOW_W); d->sky_x = d->rot * ((float)iw->t[iw->l.skybox]->w) / G360 + d->dx * (float)iw->d.screen_left; d->dy = (float)iw->t[iw->l.skybox]->h / (float)(4 * WINDOW_H); } void draw_skybox(t_sdl *iw) { int j; int i; t_draw_skybox d; draw_skybox2(iw, &d); j = iw->d.screen_left - 1; while (++j < iw->d.screen_right) { d.sky_y = -iw->p.rotup + 2 * WINDOW_H; d.sky_y = (d.sky_y * (iw->t[iw->l.skybox]->h)) / (4 * WINDOW_H); d.sky_y += d.dy * iw->d.top[j]; i = iw->d.top[j] - 1; while (++i <= iw->d.bottom[j] && i < WINDOW_H) { set_pixel2(iw->sur, j, i, get_pixel(iw->t[iw->l.skybox], (int)d.sky_x, (int)d.sky_y)); d.sky_y += d.dy; } d.sky_x += d.dx; if (d.sky_x >= iw->t[iw->l.skybox]->w) d.sky_x = d.sky_x - iw->t[iw->l.skybox]->w; iw->d.bottom[j] = iw->d.top[j]; } } <|start_filename|>3d/SRC2/check_collisions.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* check_collisions.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbolilyi <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/05 12:02:47 by dbolilyi #+# #+# */ /* Updated: 2019/03/05 12:04:56 by dbolilyi ### ########.fr */ /* */ /* ************************************************************************** */ #include "../guardians.h" int check_walls_collisions_on_line_segment(t_sdl *iw, int wall, int len) { float len_pifagor; float len_p_p; len_p_p = powf(iw->walls[wall].x - iw->walls[wall].next->x, 2.0f) + powf(iw->walls[wall].y - iw->walls[wall].next->y, 2.0f); len_pifagor = powf(iw->p.x - iw->walls[wall].x, 2.0f) + powf(iw->p.y - iw->walls[wall].y, 2.0f) - powf(len, 2.0f); if (len_pifagor > len_p_p) return (0); len_pifagor = powf(iw->p.x - iw->walls[wall].next->x, 2.0f) + powf(iw->p.y - iw->walls[wall].next->y, 2.0f) - powf(len, 2.0f); if (len_pifagor > len_p_p) return (0); return (1); } void check_walls_collisions2(t_sdl *iw, t_check_collisions *d) { d->nx = iw->walls[d->wall].l.a; d->ny = iw->walls[d->wall].l.b; if ((iw->walls[d->wall].next->x > iw->walls[d->wall].x && d->ny > 0.0f) || (iw->walls[d->wall].next->x < iw->walls[d->wall].x && d->ny < 0.0f)) { d->nx = -d->nx; d->ny = -d->ny; } d->tmp = sqrtf(powf(d->nx, 2.0f) + powf(d->ny, 2.0f)); d->nx *= (float)(COLLISION_SIZE2 - d->len) / d->tmp; d->ny *= (float)(COLLISION_SIZE2 - d->len) / d->tmp; if (in_sec_xy(iw, iw->d.cs, iw->p.x + (int)d->nx, iw->p.y + (int)d->ny)) { iw->p.x += (int)d->nx; iw->p.y += (int)d->ny; } } void check_walls_collisions(t_sdl *iw) { t_check_collisions d; if (iw->d.cs < 0) return ; d.wall = iw->sectors[iw->d.cs].sw - 1; while (++d.wall < iw->sectors[iw->d.cs].sw + iw->sectors[iw->d.cs].nw) { if ((iw->walls[d.wall].nextsector == -1 || iw->walls[d.wall].glass != -1) && (iw->walls[d.wall].x != iw->walls[d.wall].next->x || iw->walls[d.wall].y != iw->walls[d.wall].next->y)) { d.len = (int)(fabsf(iw->walls[d.wall].l.a * iw->p.x + iw->walls[d.wall].l.b * iw->p.y + iw->walls[d.wall].l.c) / sqrtf( powf(iw->walls[d.wall].l.a, 2.0f) + powf(iw->walls[d.wall].l.b, 2.0f))); if (d.len < COLLISION_SIZE2 && check_walls_collisions_on_line_segment(iw, d.wall, d.len)) check_walls_collisions2(iw, &d); } } } <|start_filename|>3d/SRC/backpack3.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* backpack3.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbolilyi <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/05 15:18:17 by dbolilyi #+# #+# */ /* Updated: 2019/03/05 15:18:17 by dbolilyi ### ########.fr */ /* */ /* ************************************************************************** */ #include "../guardians.h" void use_item_delete(t_sdl *iw) { int i; int flag; Mix_PlayChannel(2, iw->sounds.env[17], 0); flag = 0; i = 0; while (i < iw->bag.count_items) { if (iw->bag.selected_item == iw->bag.item_in_bag1[i]) flag = 1; if (flag == 1) iw->bag.item_in_bag1[i] = iw->bag.item_in_bag1[i + 1]; i++; } iw->bag.count_items--; delete_used_sprite(iw, iw->bag.selected_item); iw->bag.selected_item = 0; } void use_item2(t_sdl *iw) { if (iw->bag.selected_item->t_numb == 5) { iw->guns.bullets[1] = iw->guns.max_bullets[1]; iw->guns.bullets_in_stock[1] = iw->guns.max_bullets_in_stock[1]; use_item_delete(iw); } else if (iw->bag.selected_item->t_numb == 10) { iw->v.fly_mode = 1; Mix_HaltChannel(0); iw->v.fall = 1; iw->v.fly_down = 1; iw->v.fly_up = 1; iw->v.jetpack = clock(); use_item_delete(iw); } } void use_item(t_sdl *iw) { if (iw->bag.selected_item == 0) return ; if (iw->bag.selected_item->t_numb == 2) { iw->p.health = 100; use_item_delete(iw); } else if (iw->bag.selected_item->t_numb == 3) { iw->p.health += 50; if (iw->p.health > 100) iw->p.health = 100; use_item_delete(iw); } else if (iw->bag.selected_item->t_numb == 4) { iw->guns.bullets[2] = iw->guns.max_bullets[2]; iw->guns.bullets_in_stock[2] = iw->guns.max_bullets_in_stock[2]; use_item_delete(iw); } else use_item2(iw); } void add_item2(t_sdl *iw) { if (iw->v.look_sprite->t_numb == 0) { iw->guns.bullets[2] = iw->guns.max_bullets[2]; iw->guns.bullets_in_stock[2] = iw->guns.max_bullets_in_stock[2]; if (iw->guns.status == 0) { iw->guns.gun_in_hands = 2; iw->guns.status = 3; } delete_used_sprite(iw, iw->v.look_sprite); } else { if (iw->v.look_sprite->t_numb == 6) iw->v.have_clocks = 1; iw->bag.item_in_bag1[iw->bag.count_items] = iw->v.look_sprite; iw->bag.count_items++; iw->v.look_sprite->taken = 1; } } void add_item(t_sdl *iw) { if (!(iw->v.look_sprite != 0 && iw->v.look_sprite->type == 1 && iw->v.look_sprite->taken == 0 && iw->v.look_sprite->plen < BUTTON_PRESS_DIST)) return ; Mix_PlayChannel(2, iw->sounds.env[3], 0); if (iw->v.look_sprite->t_numb == 1) { iw->guns.bullets[1] = iw->guns.max_bullets[1]; iw->guns.bullets_in_stock[1] = iw->guns.max_bullets_in_stock[1]; if (iw->guns.status == 0) { iw->guns.gun_in_hands = 1; iw->guns.status = 3; iw->hud.shell = 100; } delete_used_sprite(iw, iw->v.look_sprite); } else add_item2(iw); } <|start_filename|>editor/find_allsector.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* find_allsector.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ddehtyar <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/02/28 16:36:09 by ddehtyar #+# #+# */ /* Updated: 2019/02/28 16:36:10 by ddehtyar ### ########.fr */ /* */ /* ************************************************************************** */ #include "doom_nuken.h" void drow_find(t_doom *den) { if (den->change == 1) { den->find_tmp = den->find_tmp_one; ft_line(den, &den->rec_two); SDL_UpdateWindowSurface(den->window); den->color = 0x00FF00; ft_line(den, &den->rec); den->change = 2; SDL_UpdateWindowSurface(den->window); } else if (den->change == 2) { den->find_tmp = den->find_tmp_two; ft_line(den, &den->rec); SDL_UpdateWindowSurface(den->window); den->color = 0x00FF00; ft_line(den, &den->rec_two); den->change = 1; SDL_UpdateWindowSurface(den->window); } den->color = 0xFFFFFF; clean_display(den); info_display(den); } void all_sector(t_doom *den, t_wals *tmp) { if (den->find_tmp->sec != tmp->sec || (den->find_tmp->sec == tmp->sec && den->find_tmp->inside != tmp->inside)) { while (tmp) { if (den->find_tmp->sec == tmp->sec && den->find_tmp->inside == tmp->inside) break ; tmp = tmp->next; } } while (tmp) { if (tmp->sec != den->find_tmp->sec || (tmp->sec == den->find_tmp->sec && tmp->inside != den->find_tmp->inside)) break ; den->color = 0x00FF00; den->rec.x1 = tmp->x * XSKAPE; den->rec.y1 = tmp->y * YSKAPE; den->rec.x2 = tmp->x1 * XSKAPE; den->rec.y2 = tmp->y1 * YSKAPE; ft_line(den, &den->rec); tmp = tmp->next; } SDL_UpdateWindowSurface(den->window); } void blouk_write(t_doom *den) { char *cmp; SDL_Color ct; den->rect.x = 1770; den->rect.y = 380; den->rect.h = 50; den->rect.w = 30; clean_string(den); ct.r = 255; ct.g = 0; ct.b = 0; cmp = "card edit mode lock, press \"TAB\"\n"; den->TTF_TextSolid = TTF_RenderText_Blended_Wrapped(den->font, cmp, ct, 200); SDL_BlitSurface(den->TTF_TextSolid, NULL, den->bmp, &den->rect); SDL_FreeSurface(den->TTF_TextSolid); SDL_UpdateWindowSurface(den->window); } void clean_vec(t_col *vec) { vec->x1 = LIM; vec->y1 = LIM; vec->x2 = LIM; vec->y2 = LIM; } <|start_filename|>3d/SRC/draw_hud3.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* draw_hud3.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbolilyi <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/05 15:21:15 by dbolilyi #+# #+# */ /* Updated: 2019/03/05 15:21:17 by dbolilyi ### ########.fr */ /* */ /* ************************************************************************** */ #include "../guardians.h" void clear_sprites_tex_to_select(t_sdl *iw) { SDL_Rect rect; rect.x = 0; rect.y = WINDOW_H + 200; rect.w = WINDOW_W; rect.h = 100; SDL_FillRect(iw->sur, &rect, 0x000000); } void draw_decor_tex_to_select(t_sdl *iw) { int i; SDL_Rect rect; if (iw->v.game_mode) return ; clear_sprites_tex_to_select(iw); iw->v.sprites_select_mode = 0; rect.x = 0; rect.y = WINDOW_H + 200; rect.w = 100; rect.h = 100; i = iw->v.scroll_decor_sprites - 1; while (++i < DECOR_TEXTURES_COUNT && rect.x < WINDOW_W) { ft_scaled_blit(iw->t_decor[i], iw->sur, &rect); rect.x += 100; } } void draw_pickup_tex_to_select(t_sdl *iw) { int i; SDL_Rect rect; if (iw->v.game_mode) return ; clear_sprites_tex_to_select(iw); iw->v.sprites_select_mode = 1; rect.x = 0; rect.y = WINDOW_H + 200; rect.w = 100; rect.h = 100; i = iw->v.scroll_pickup_sprites - 1; while (++i < PICK_UP_TEXTURES_COUNT && rect.x < WINDOW_W) { ft_scaled_blit(iw->t_pickup[i], iw->sur, &rect); rect.x += 100; } } void draw_enemies_tex_to_select(t_sdl *iw) { SDL_Rect rect; if (iw->v.game_mode) return ; clear_sprites_tex_to_select(iw); iw->v.sprites_select_mode = 2; rect.x = 0; rect.y = WINDOW_H + 200; rect.w = 100; rect.h = 100; ft_scaled_blit(iw->t_enemies[0], iw->sur, &rect); rect.x += 100; ft_scaled_blit(iw->t_enemies[8], iw->sur, &rect); rect.x += 100; ft_scaled_blit(iw->t_enemies[20], iw->sur, &rect); } void draw_selected_tex(t_sdl *iw) { SDL_Rect rect; if (iw->v.game_mode) return ; rect.x = WINDOW_W - 110; rect.y = 10; rect.w = 100; rect.h = 100; ft_scaled_blit(iw->t[iw->v.tex_to_fill], iw->sur, &rect); } <|start_filename|>editor/find_walls.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* find_walls.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ddehtyar <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/02/05 16:47:58 by ddehtyar #+# #+# */ /* Updated: 2019/02/05 16:47:59 by ddehtyar ### ########.fr */ /* */ /* ************************************************************************** */ #include "doom_nuken.h" void find_wals_help(t_doom *den) { if (den->rec.x1 == 0 && den->rec.x2 == 0) { den->rec.x1 = den->tmp->x * XSKAPE; den->rec.y1 = den->tmp->y * YSKAPE; den->rec.x2 = den->tmp->x1 * XSKAPE; den->rec.y2 = den->tmp->y1 * YSKAPE; den->rec.sect = den->tmp->sec; den->find_tmp_one = den->tmp; den->change = 1; } else if (den->rec_two.x1 == 0 && den->rec_two.x2 == 0) { den->rec_two.x1 = den->tmp->x * XSKAPE; den->rec_two.y1 = den->tmp->y * YSKAPE; den->rec_two.x2 = den->tmp->x1 * XSKAPE; den->rec_two.y2 = den->tmp->y1 * YSKAPE; den->rec_two.sect = den->tmp->sec; den->find_tmp_two = den->tmp; } drow_find(den); } void find_wals(int x, int y, t_doom *den) { t_wals *rmp; int i; i = 0; rmp = den->tmp; if (den->change == 0) { while (den->tmp) { i = point_into_segments(x, y, den); if (i >= -3000 && i <= 3000) find_wals_help(den); den->tmp = den->tmp->next; } den->tmp = rmp; } else { ft_line(den, &den->rec); ft_line(den, &den->rec_two); SDL_UpdateWindowSurface(den->window); clear_find(den); } } void look_find_sector_two(t_doom *den) { t_wals *rmp; rmp = den->tmp; while (rmp) { if (rmp != den->find_tmp && ((rmp->x == den->find_tmp->x1 && rmp->y == den->find_tmp->y1 && rmp->x1 == den->find_tmp->x && rmp->y1 == den->find_tmp->y) || (rmp->x == den->find_tmp->x && rmp->y == den->find_tmp->y && rmp->x1 == den->find_tmp->x1 && rmp->y1 == den->find_tmp->y1))) { den->find_tmp_two = rmp; change_rec(den, &den->rec_two, den->find_tmp_two); break ; } else { den->find_tmp_two = NULL; } rmp = rmp->next; } } void clear_find(t_doom *den) { den->rec.x1 = 0; den->rec.y1 = 0; den->rec.x2 = 0; den->rec.y2 = 0; den->rec.sect = 0; den->find_tmp_one = 0; den->change = 0; den->rec_two.x1 = 0; den->rec_two.y1 = 0; den->rec_two.x2 = 0; den->rec_two.y2 = 0; den->rec_two.sect = 0; den->find_tmp_two = 0; } int point_into_segments(int x, int y, t_doom *den) { int x1; int y1; int x2; int y2; int skap; skap = 10; if (den->skape < 0) skap = 3; x1 = den->tmp->x * XSKAPE; y1 = den->tmp->y * YSKAPE; x2 = den->tmp->x1 * XSKAPE; y2 = den->tmp->y1 * YSKAPE; if ((x1 - skap > x && x < x2 + skap) || (x2 - skap < x && x > x1 + skap)) return (3001); if ((y1 - skap > y && y < y2 + skap) || (y2 - skap < y && y > y1 + skap)) return (3001); return (((x - x1) * (y2 - y1)) - (y - y1) * (x2 - x1)); } <|start_filename|>3d/SRC/minimap.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* minimap.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbolilyi <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/02/28 17:58:34 by dbolilyi #+# #+# */ /* Updated: 2019/03/01 13:53:11 by dbolilyi ### ########.fr */ /* */ /* ************************************************************************** */ #include "../guardians.h" void transparency(t_sdl *iw) { int i; int j; int pix; i = WINDOW_W / 5 - 10; while (i++ <= WINDOW_W - (WINDOW_W / 5) + 9) { j = WINDOW_H / 5 - 10; while (j++ <= WINDOW_H - (WINDOW_H / 5) + 9) if ((i >= WINDOW_W / 5 - 10 && i <= WINDOW_W / 5) || (j >= WINDOW_H / 5 - 10 && j <= WINDOW_H / 5) || (i <= WINDOW_W - (WINDOW_W / 5) + 10 && i >= WINDOW_W - (WINDOW_W / 5)) || (j <= WINDOW_H - (WINDOW_H / 5) + 10 && j >= WINDOW_H - (WINDOW_H / 5))) set_pixel2(iw->sur, i, j, 0x999999); else { pix = get_pixel_surface(iw->sur, i, j); set_pixel2(iw->sur, i, j, (((int)((float)(pix >> 16) * 0.3)) << 16) + (((int)((float)((pix >> 8) - (pix >> 16 << 8)) * 0.3)) << 8) + (int)((float)(pix - (pix >> 8 << 8)) * 0.3)); } } } void print_brez_m(t_brez *b, int d, int d1, int d2) { int i; if (b->k <= 0) b->dx = b->dy; i = 0; while (++i <= b->dx) { if (d > 0) { d += d2; b->y += b->sy; } else d += d1; if (b->k > 0) { if ((b->x > WINDOW_W / 5 && b->x < (WINDOW_W - WINDOW_W / 5)) && (b->y > WINDOW_H / 5 && b->y < (WINDOW_H - WINDOW_H / 5))) set_pixel2(b->iw->sur, b->x, b->y, b->color); } else if ((b->x > WINDOW_H / 5 && b->x < (WINDOW_H - WINDOW_H / 5)) && (b->y > WINDOW_W / 5 && b->y < (WINDOW_W - WINDOW_W / 5))) set_pixel2(b->iw->sur, b->y, b->x, b->color); b->x += b->sx; } } void bresen(t_sdl *iw, t_draw_line line, int color) { t_brez b; b.iw = iw; b.color = color; b.sx = (line.x1 >= line.x0) ? (1) : (-1); b.sy = (line.y1 >= line.y0) ? (1) : (-1); b.dx = (line.x1 > line.x0) ? (line.x1 - line.x0) : (line.x0 - line.x1); b.dy = (line.y1 > line.y0) ? (line.y1 - line.y0) : (line.y0 - line.y1); if (abs(line.y1 - line.y0) < abs(line.x1 - line.x0)) { b.x = line.x0 + b.sx; b.y = line.y0; b.k = 1; print_brez_m(&b, (b.dy * 2) - b.dx, b.dy * 2, (b.dy - b.dx) * 2); } else { b.x = line.y0 + b.sy; b.y = line.x0; b.sy = (line.x1 >= line.x0) ? (1) : (-1); b.sx = (line.y1 >= line.y0) ? (1) : (-1); b.k = 0; print_brez_m(&b, (b.dx * 2) - b.dy, b.dx * 2, (b.dx - b.dy) * 2); } } void draw_minimap(t_sdl *iw) { int sec; int w; int k; t_draw_line line; k = 16000 / WINDOW_W; sec = -1; while (++sec < iw->v.sc) { w = iw->sectors[sec].sw - 1; while (++w < iw->sectors[sec].sw + iw->sectors[sec].nw) if (iw->walls[w].nextsector == -1) { line.x0 = -iw->walls[w].x / k + iw->p.x / k + 8100 / k; line.x0 = WINDOW_W / 2 + ((line.x0 > WINDOW_W / 2) ? -abs( line.x0 - WINDOW_W / 2) : abs(line.x0 - WINDOW_W / 2)); line.x1 = -iw->walls[w].next->x / k + iw->p.x / k + 8100 / k; line.x1 = WINDOW_W / 2 + ((line.x1 > WINDOW_W / 2) ? -abs( line.x1 - WINDOW_W / 2) : abs(line.x1 - WINDOW_W / 2)); line.y0 = -iw->walls[w].y / k + iw->p.y / k + 4750 / k; line.y1 = -iw->walls[w].next->y / k + iw->p.y / k + 4750 / k; bresen(iw, line, 0xFF0000); } } ft_scaled_blit(iw->map.player, iw->sur, &iw->map.pl_rect); } <|start_filename|>editor/display.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* display.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ddehtyar <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/01/30 15:43:24 by ddehtyar #+# #+# */ /* Updated: 2019/01/30 15:43:26 by ddehtyar ### ########.fr */ /* */ /* ************************************************************************** */ #include "doom_nuken.h" void board_display_three(t_doom *den) { den->rect.x = 1815; den->rect.y = 440; SDL_BlitSurface(den->icon[8], NULL, den->bmp, &den->rect); den->rect.x = 1875; den->rect.y = 443; SDL_BlitSurface(den->icon[10], NULL, den->bmp, &den->rect); den->rect.x = 1935; den->rect.y = 443; SDL_BlitSurface(den->icon[11], NULL, den->bmp, &den->rect); } void board_display_two(t_doom *den) { den->rect.x = 1830; den->rect.y = 300; SDL_BlitSurface(den->icon[4], NULL, den->bmp, &den->rect); den->rect.x = 1840; den->rect.y = 680; SDL_BlitSurface(den->icon[5], NULL, den->bmp, &den->rect); den->rect.x = 1770; den->rect.y = 300; SDL_BlitSurface(den->icon[6], NULL, den->bmp, &den->rect); den->rect.x = 1755; den->rect.y = 440; SDL_BlitSurface(den->icon[7], NULL, den->bmp, &den->rect); board_display_three(den); } void board_display(t_doom *den) { den->rect.x = 1755; den->rect.y = 510; den->rect.h = 20; den->rect.w = 20; SDL_BlitSurface(den->icon[0], NULL, den->bmp, &den->rect); den->rect.x = 1815; den->rect.y = 510; SDL_BlitSurface(den->icon[1], NULL, den->bmp, &den->rect); den->rect.x = 1875; den->rect.y = 510; SDL_BlitSurface(den->icon[2], NULL, den->bmp, &den->rect); den->rect.x = 1935; den->rect.y = 510; SDL_BlitSurface(den->icon[3], NULL, den->bmp, &den->rect); board_display_two(den); } void clean_display(t_doom *den) { int i; int j; j = -1; while (++j < HEIGHT / 2) { i = den->border; while (++i < WIDTH) set_pixel(den->bmp, i, j, 0); } } void blouk_wall(t_doom *den, t_wals *tmp, t_col *vec) { t_wals *rmp; int i; vec = NULL; rmp = tmp; i = -1; while (++i <= den->sec) { while (tmp->next) { if (tmp->sec != i) break ; tmp = tmp->next; } } tmp = rmp; } <|start_filename|>3d/SRC4/draw_inclined_floor_ceil_betw_kernel2.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* draw_inclined_floor_ceil_betw_kernel2.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbolilyi <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/05 17:22:49 by dbolilyi #+# #+# */ /* Updated: 2019/03/05 17:22:51 by dbolilyi ### ########.fr */ /* */ /* ************************************************************************** */ #include "../guardians.h" void draw_inclined_floor_ceil_betw_tex_kernel1(t_sdl *iw, t_save_wall *left, t_draw_wall_floor_ceil_tex_kernel *d) { if (iw->sectors[iw->d.cs].light == 0 || iw->sectors[iw->d.cs].light->t != 18) d->cint[25] = 1; else d->cint[25] = 0; d->cint[0] = iw->t[left->wall->t]->w; d->cint[1] = iw->t[left->wall->t]->h; d->cint[2] = iw->t[iw->sectors[iw->d.cs].fr.t]->w; d->cint[3] = iw->t[iw->sectors[iw->d.cs].fr.t]->h; if (iw->sectors[iw->d.cs].cl.t >= 0) { d->cint[4] = iw->t[iw->sectors[iw->d.cs].cl.t]->w; d->cint[5] = iw->t[iw->sectors[iw->d.cs].cl.t]->h; } else { d->cint[4] = iw->t[iw->l.skybox]->w; d->cint[5] = iw->t[iw->l.skybox]->h; } d->cint[6] = WINDOW_W; d->cint[7] = WINDOW_H; d->cint[8] = left->x; d->cint[9] = left->p.x; d->cint[10] = left->p.y; d->cint[21] = iw->d.screen_left; } <|start_filename|>3d/guardians.h<|end_filename|> #ifndef __GUARDIANS_H # define __GUARDIANS_H # define _CRT_SECURE_NO_WARNINGS //# include "SDL2/SDL2.framework/Headers/SDL.h" #ifdef __linux__ # include <SDL2/SDL.h> # include <SDL2/SDL_ttf.h> # include <SDL2/SDL_mixer.h> #else # include <SDL.h> # include <SDL_ttf.h> # include <SDL_mixer.h> #endif #ifdef __APPLE__ # include <OpenCL/cl.h> # include <unistd.h> #elif __linux__ # include <CL/cl.h> # include <unistd.h> #else # include <CL/cl.h> # include <io.h> # define open _open # define close _close # define read _read # define write _write # define HAVE_STRUCT_TIMESPEC # include <sys/stat.h> # define S_IRUSR _S_IREAD # define S_IWUSR _S_IWRITE #endif # include "../libft/libft.h" # include <fcntl.h> # include <math.h> # include <time.h> # include "struct.h" void set_pixel2(SDL_Surface *surface, int x, int y, Uint32 pixel); int get_light_color(int color, t_picture *light); Uint32 get_pixel(t_packaging_texture *sur, const int x, const int y); Uint32 get_pixel_surface(SDL_Surface *sur, const int x, const int y); int in_sec_xy(t_sdl *iw, int sector, int x, int y); int in_sec(int sector, t_sdl *iw); void exit_x(t_sdl *iw); void draw_crosshair(t_sdl *iw); int get_sector_by_pointer(t_sdl *iw, t_sector *sec); int get_wall_by_pointer(t_sdl *iw, t_sector *sec, t_wall *w); void add_sector_animation(t_sdl *iw); void do_sector_animation_step(t_sdl *iw, t_sector_animation *a, int dz); void draw_selected_walls_to_be_animated(t_sdl *iw); void add_wall_to_wall_animation2(t_sdl *iw, int add_wall); void add_wall_to_wall_animation(t_sdl *iw); void calculate_pictures_list(t_sdl *iw, t_wall *wall, t_picture *p); void do_wall_animation_step_dx(t_sdl *iw, t_wall_animation *a, int dx); void do_wall_animation_step_dy(t_sdl *iw, t_wall_animation *a, int dy); void exit_editing_sector_animation(t_sdl *iw); void exit_editing_wall_animation(t_sdl *iw); void add_picture(t_sdl *iw, t_wall *wall); void delete_wall_animation(t_sdl *iw, t_picture *pic); void delete_light_and_animations(t_sdl *iw, t_picture *pic); void delete_picture(t_wall *wall, t_picture *pic, t_sdl *iw); void draw_text_number(t_sdl *iw, t_draw_info *d, const char *s, int numb); void draw_text(t_sdl *iw, const char *s, int x, int y); void draw_text_blue(t_sdl *iw, const char *s, int x, int y); void draw_some_info(t_sdl *iw); void draw_menu_sphere(t_sdl *iw, int a, const char *t); void draw_up_down_menu_arrows(t_sdl *iw, int x); void draw_menu(t_sdl *iw); void ft_scaled_blit(t_packaging_texture *tex, SDL_Surface *winsur, SDL_Rect *rect); void ft_scaled_blit2(t_packaging_texture *tex, SDL_Surface *winsur, SDL_Rect *rect); void draw_tex_to_select(t_sdl *iw); void clear_sprites_tex_to_select(t_sdl *iw); void draw_decor_tex_to_select(t_sdl *iw); void draw_pickup_tex_to_select(t_sdl *iw); void draw_enemies_tex_to_select(t_sdl *iw); void draw_selected_tex(t_sdl *iw); void draw_selected_sprite(t_sdl *iw); void draw_submenu(t_sdl *iw); void change_sector_animation_status(t_sdl *iw, t_picture *p); void change_wall_animation_status(t_sdl *iw, t_picture *p); void drawcircle(t_hud *den, t_draw_circle *c, int x, int y); void circle(t_hud *den, int xc, int yc); void ft_line2(t_sdl *iw, int x, int y, int color); void make_health(t_hud *den, t_sdl *iw); void draw_gun(t_sdl *iw); void draw_icon_bag(t_sdl *iw); void draw_frame(t_sdl *iw, SDL_Surface *winsur, SDL_Rect *rect); void drop_item(t_sdl *iw); void delete_used_sprite(t_sdl *iw, t_sprite *s); void use_item_delete(t_sdl *iw); void use_item(t_sdl *iw); void add_item(t_sdl *iw); //void draw_button(t_sdl *iw, SDL_Rect *rect, t_packaging_texture *texture); void draw_butttons(t_sdl *iw, SDL_Rect *rect); void draw_selected_item(t_packaging_texture *tex, SDL_Surface *winsur, SDL_Rect *rect, t_sdl *iw); void draw_items(t_sdl *iw); void transparency(t_sdl *iw); void draw_input_on_screen(t_sdl *iw, t_keyb_inp *ki); t_keyb_inp *input_loop(t_sdl *iw); void add_checkpoint(t_sdl *iw, t_sprite *s); void draw_checkpoint_text(t_sdl *iw); void update(t_sdl *iw); int get_picture_dist(t_sdl *iw, t_picture *pic); t_sprite *get_card_from_bag(t_sdl *iw, int t_numb); void button_f_up_cards(t_sdl *iw); void button_f_up(t_sdl *iw); void key_up(int code, t_sdl *iw); void key_down(int code, t_sdl *iw); void key_down_repeat(int code, t_sdl *iw); void mouse_move(int xrel, int yrel, t_sdl *iw); void rotate_fc(t_sector_fc *fc, int xy, int pl); void mouse_buttonleft_up(int x, int y, t_sdl *iw); void mouse_buttonright_up(t_sdl *iw); void mouse_wheel(SDL_Event *e, t_sdl *iw); t_wall *is_wall_portal(t_sdl *iw, int dx, int dy); void move_collisions(t_sdl *iw, int dx, int dy, int tmp); int check_moving_in_portal_z(t_sdl *iw, int dx, int dy, t_wall *sw); void move_in_portal(t_sdl *iw, t_move *d); void move(t_sdl *iw, int pl, clock_t *time); void get_wall_line2(t_wall *wall); void do_sector_animations(t_sdl *iw); void do_wall_animations(t_sdl *iw); int check_walls_collisions_on_line_segment(t_sdl *iw, int wall, int len); void check_walls_collisions(t_sdl *iw); int esp_check_walls(t_sdl *iw, t_enemy_sees_player *esp); int esp_check_portal(t_sdl *iw, t_enemy_sees_player *esp, int portal); void esp_get_new_player_coordinates(t_sdl *iw, t_sector_way *way, t_enemy_sees_player *esp, t_sprite *s); int enemy_sees_player(t_sdl *iw, t_sprite *s); int move_enemy_in_portal(t_sdl *iw, t_sprite *s, t_intpoint2d *vect); int move_enemy(t_sdl *iw, t_sprite *s); void sprite_physics(t_sdl *iw, t_sprite *s); void enemy_intelligence0(t_sdl *iw, t_sprite *s); void enemy_intelligence1(t_sdl *iw, t_sprite *s); void enemy_intelligence2(t_sdl *iw, t_sprite *s, int i); void check_enemies(t_sdl *iw); void draw_miss(t_sdl *iw); void draw_save(t_sdl *iw); void damaging_enemy(t_sdl *iw, int damage, int max_distance); void attack(t_sdl *iw); void reload_gun(t_sdl *iw); void guns_loop(t_sdl *iw); void guns_movements(t_sdl *iw); void death(t_sdl *iw); void set_checkpoint(t_sdl *iw, t_sprite *s); void check_checkpoints(t_sdl *iw); void sound_loop(t_sdl *iw); void environment_loop(t_sdl *iw); void loop(t_sdl *iw); void main_loop(t_sdl *iw); void get_wall_line(t_sdl *iw, int wall); void create_map(t_sdl *iw); int get_sector(t_sdl *iw); void set_top_bottom(t_sdl *iw); float get_k_angle(float rot); void get_left_right_lines_points(t_sdl *iw); void get_screen_line(t_sdl *iw); void get_direction(t_sdl *iw); void free_walls(t_sdl *iw); void free_pairs(t_sdl *iw); void add_wall(t_sdl *iw, t_save_wall *tmp); int get_floor_z(t_sdl *iw, int x, int y); int get_ceil_z(t_sdl *iw, int x, int y); int get_floor_z_sec(t_sdl *iw, int x, int y, int sector); int get_ceil_z_sec(t_sdl *iw, int x, int y, int sector); float get_vectors_angle(float x1, float y1, float x2, float y2); void get_visible_walls2(t_sdl *iw, int wall, float lang); void get_visible_walls(t_sdl *iw); int cross_two_lines(t_line2d *l1, t_line2d *l2, t_intpoint2d *p); int ft_min(int p1, int p2); int ft_max(int p1, int p2); int point_in_front_and_on_wall(t_sdl *iw, t_intpoint2d *p, int wall); int visible_wall(t_sdl *iw, int wall); int if_not_in_vw(t_sdl *iw, t_wall *wall); void add_lr_wall(t_sdl *iw, t_intpoint2d *p, t_wall *wall, int x); void get_all_intersection_line(t_sdl *iw, t_line2d *nl, int right); void get_left_right_visible_walls(t_sdl *iw); t_save_wall *find_next_vis_wall(t_sdl *iw, t_save_wall *left); void put_wall_pixel(t_brez *b, int x, int y); void print_brez(t_brez *b, int d, int d1, int d2); void brez_line(int *wall_y, t_draw_line line); void draw_between_sectors_bot_tex(t_sdl *iw, t_save_wall *left, t_save_wall *right, int *tmp); void draw_between_sectors_top_tex(t_sdl *iw, t_save_wall *left, t_save_wall *right, int *tmp); void draw_floor_ceil_tex(t_sdl *iw, t_save_wall *left, t_save_wall *right, int len); void draw_inclined_floor_ceil_tex(t_sdl *iw, t_save_wall *left, t_save_wall *right, int len); void draw_wall_floor_ceil_tex(t_sdl *iw, t_save_wall *left, t_save_wall *right, int len); void draw_inclined_wall_floor_ceil_tex(t_sdl *iw, t_save_wall *left, t_save_wall *right, int len); void draw_between_sectors_walls(t_sdl *iw, t_save_wall *left, t_save_wall *right); int *get_between_sectors_walls(t_sdl *iw, t_save_wall *left, t_save_wall *right, int **top); void fill_portal(t_sdl *iw, t_save_wall *left, t_save_wall *right, t_sdl *iw2); void fill_top_skybox(t_sdl *iw2, t_save_wall *left, int len); void fill_bot_by_wallTop(t_sdl *iw, t_save_wall *left, int len); void fill_tb_by_slsr(t_sdl *iw); void change_saved_top_bot_between_lines(t_sdl *iw, int len); void draw_glass_tex(t_sdl *iw, t_save_wall *left, t_save_wall *right, int len); int sector_visited(t_sdl *iw, int sec); void draw_glass_sprites(t_sdl *iw); void draw_next_sector(t_sdl *iw, t_save_wall *left, t_save_wall *right); void draw_next_sector_kernel(t_sdl *iw, t_save_wall *left, t_save_wall *right, int len); int draw_picture(t_sdl *iw, t_picture *pic); void draw_pictures(t_sdl *iw, t_save_wall *left); void draw_all(t_sdl *iw, t_save_wall *left, t_save_wall *right, int len); void draw_all_kernel(t_sdl *iw, t_save_wall *left, t_save_wall *right, int len); void draw_left_right(t_sdl *iw, t_save_wall *left, t_save_wall *right); void add_pair(t_sdl *iw, t_save_wall *left, t_save_wall *right); t_save_wall_pairs *get_closest_between_pair(t_save_wall_pairs *pair); int check_look_picture(t_sdl *iw); void new_sort_pairs(t_sdl *iw); void draw_skybox(t_sdl *iw); void draw_sprite(t_sdl *iw, t_sprite *sprite); void draw_sprites(t_sdl *iw); int find_point(t_save_wall_pairs *tmp, t_sprite *tmp1); void calculate_sprites_once(t_sdl *iw); void get_sprites_top_bottom(t_sdl *iw, t_save_wall_pairs *tmp); void switch_nexts_sprites(t_sprite *s1, t_sprite *s2); void sort_sprites(t_sdl *iw); void save_walls(t_sdl *iw); void draw_start(t_sdl *iw); void draw(t_sdl *iw); void read_textures(t_sdl *iw); void read_sprites_textures(t_sdl *iw); void read_weapons_textures(t_sdl *iw); void get_birth_def(t_sdl *iw); void get_def_new(t_sdl *iw); void get_kernel_mem(t_sdl *iw); void calculate_not_squared_wall_picture(t_wall *wall, t_picture *pic); void calculate_picture(t_sdl *iw, t_wall *wall, t_picture *pic); void add_picture1(t_sdl *iw); void free_way(t_sector_ways **way); int sector_in_way(t_sdl *iw, t_sector_ways *way, int sector); void add_portal_in_way2(t_sector_ways *tmp, int portal); t_sector_ways *add_portal_in_way(t_sector_ways *current_way, int portal); void go_in_sector_way(t_sdl *iw, t_get_sectors_ways *g, t_sector_ways *current_way); void get_sectors_ways2(t_sdl *iw); void get_sectors_ways(t_sdl *iw); void get_packaging_texture(t_packaging_texture **pack, SDL_Surface *sur); void get_packaging_textures(t_sdl *iw); void get_sprite_texture(t_sdl *iw, t_sprite *s); void set_sprites_z(t_sdl *iw); void get_guns_center(t_sdl *iw, int i, int scale); void get_guns_center_down(t_sdl *iw, int i, int scale); void get_guns(t_sdl *iw); void game_start_menu(t_sdl *iw); void menu_loop(t_sdl *iw); void image_loop(t_sdl *iw, t_packaging_texture *tex); void free_sector_ways(t_sdl *iw); void undo_wall_animation(t_sdl *iw, t_picture *pic); void undo_animations2(t_sdl *iw, t_picture *pic); void undo_animations(t_sdl *iw); void get_music(t_sdl *iw, int i, const char *file); void get_sounds_game(t_sdl *iw); void get_sounds(t_sdl *iw); void get_kernels(t_sdl *iw); void load_kernel(t_kernel *k, t_sdl *iw); void draw_inclined_wall_floor_ceil_tex_kernel(t_sdl *iw, t_save_wall *left, t_save_wall *right, int len); void draw_wall_floor_ceil_tex_kernel(t_sdl *iw, t_save_wall *left, t_save_wall *right, int len); void draw_inclined_floor_ceil_betw_tex_kernel(t_sdl *iw, t_save_wall *left, t_save_wall *right, int len); void draw_floor_ceil_betw_tex_kernel(t_sdl *iw, t_save_wall *left, t_save_wall *right, int len); void draw_skybox_kernel(t_sdl *iw); void draw_glass_tex_kernel(t_sdl *iw, t_save_wall *left, t_save_wall *right, int len); int draw_picture_kernel(t_sdl *iw, t_picture *pic); void draw_pictures_kernel(t_sdl *iw, t_save_wall *left); void draw_pictures_kernel(t_sdl *iw, t_save_wall *left); void draw_sprites_kernel(t_sdl *iw); void draw_glass_sprites_kernel(t_sdl *iw); void draw_gun_kernel(t_sdl *iw); int check_all_validation(t_sdl *iw); void draw_minimap(t_sdl *iw); void draw_some_info2(t_sdl *iw); void mouse_buttonleft_up1(int x, int y, t_sdl *iw); void mouse_buttonleft_up1_9(int x, t_sdl *iw); void mouse_buttonleft_up1_5(int x, t_sdl *iw); int enemy_sees_player2(t_sdl *iw, t_sprite *s, t_sector_way *way, t_enemy_sees_player *esp); void enemy_intelligence2_s0(t_sdl *iw, t_sprite *s, int i); void reload_gun1(t_sdl *iw); void reload_gun2(t_sdl *iw); void loop1(t_sdl *iw); void loop2(t_sdl *iw); void game_start_menu1(t_sdl *iw, SDL_Rect *player, SDL_Rect *zast, SDL_Rect *diff); void draw_floor_ceil_tex1(t_sdl *iw, t_save_wall *left, t_save_wall *right, t_draw_wall_floor_ceil_tex *d); void draw_floor_ceil_tex2(t_sdl *iw, t_save_wall *left, t_draw_wall_floor_ceil_tex *d); void draw_inclined_floor_ceil_tex1(t_sdl *iw, t_save_wall *left, t_save_wall *right, t_draw_wall_floor_ceil_tex *d); void draw_inclined_floor_ceil_tex2(t_sdl *iw, t_save_wall *left, t_draw_wall_floor_ceil_tex *d); void draw_inclined_floor_ceil_tex3(t_sdl *iw, t_save_wall *left, t_draw_wall_floor_ceil_tex *d); void draw_inclined_floor_ceil_tex4(t_sdl *iw, t_save_wall *left, t_draw_wall_floor_ceil_tex *d); void draw_inclined_wall_floor_ceil_tex1(t_sdl *iw, t_save_wall *left, t_save_wall *right, t_draw_wall_floor_ceil_tex *d); void draw_inclined_wall_floor_ceil_tex3(t_sdl *iw, t_save_wall *left, t_draw_wall_floor_ceil_tex *d); void draw_wall_floor_ceil_tex1(t_sdl *iw, t_save_wall *left, t_save_wall *right, t_draw_wall_floor_ceil_tex *d); void draw_wall_floor_ceil_tex2(t_sdl *iw, t_save_wall *left, t_draw_wall_floor_ceil_tex *d); void draw_next_sector_kernel4(t_sdl *iw, t_save_wall *left, t_save_wall *right, t_sdl *iw2); void draw_inclined_floor_ceil_betw_tex_kernel1(t_sdl *iw, t_save_wall *left, t_draw_wall_floor_ceil_tex_kernel *d); void draw_inclined_wall_floor_ceil_tex_kernel1(t_sdl *iw, t_save_wall *left, t_draw_wall_floor_ceil_tex_kernel *d); void get_kernels2(t_sdl *iw); void get_kernels3(t_sdl *iw); void get_kernels4(t_sdl *iw); void check_enemies_in_sector(t_sdl *iw, t_sprite *e); int esp_check_return(t_sdl *iw, t_sprite *s, int ret); #endif <|start_filename|>3d/SRC4/draw_sprites_kernel.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* draw_sprites_kernel.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbolilyi <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/05 14:38:26 by dbolilyi #+# #+# */ /* Updated: 2019/03/05 14:38:27 by dbolilyi ### ########.fr */ /* */ /* ************************************************************************** */ #include "../guardians.h" void draw_sprite_kernel1(t_sdl *iw, t_sprite *sprite, int *cint) { sprite->spriteheight = 2 * sprite->spritewidth * sprite->t->h / sprite->t->w; if (abs(sprite->z - iw->p.z) > 1500) sprite->spriteheight = (float)sprite->spriteheight * 1.0f / ((float)abs(sprite->z - iw->p.z) / 1500.0f); sprite->ey = WINDOW_H * (iw->p.z + (int)sprite->pplen / 2 - sprite->z) / (int)sprite->pplen + iw->p.rotup; sprite->sy = sprite->ey - sprite->spriteheight; if (iw->sectors[sprite->num_sec].light == 0 || iw->sectors[sprite->num_sec].light->t != 18) cint[12] = 1; else cint[12] = 0; cint[0] = sprite->sx; cint[1] = sprite->spritewidth; cint[2] = sprite->t->w; cint[3] = sprite->sy; cint[4] = sprite->ey; cint[5] = WINDOW_H; cint[6] = sprite->spriteheight; cint[7] = sprite->t->h; cint[8] = WINDOW_W; cint[9] = sprite->t->bpp; cint[10] = sprite->t->pitch; } void draw_sprite_kernel(t_sdl *iw, t_sprite *sprite) { int cint[13]; size_t global_item_size; size_t local_item_size; draw_sprite_kernel1(iw, sprite, cint); if (sprite->sx < 0) cint[11] = -sprite->sx; else cint[11] = 0; iw->k.ret = clEnqueueWriteBuffer(iw->k.command_queue, iw->k.m_cint, CL_TRUE, 0, 13 * sizeof(int), cint, 0, NULL, NULL); iw->k.ret = clEnqueueWriteBuffer(iw->k.command_queue, iw->k.m_save_top3, CL_TRUE, 0, (WINDOW_W + 1) * sizeof(int), sprite->top, 0, NULL, NULL); iw->k.ret = clEnqueueWriteBuffer(iw->k.command_queue, iw->k.m_save_bottom3, CL_TRUE, 0, (WINDOW_W + 1) * sizeof(int), sprite->bottom, 0, NULL, NULL); iw->k.ret = clSetKernelArg(iw->k.kernel7, 3, sizeof(cl_mem), (void *)sprite->t_kernel); global_item_size = ft_min(WINDOW_W, sprite->ex) - ft_max(0, sprite->sx); local_item_size = 1; iw->k.ret = clEnqueueNDRangeKernel(iw->k.command_queue, iw->k.kernel7, 1, NULL, &global_item_size, &local_item_size, 0, NULL, NULL); clFlush(iw->k.command_queue); clFinish(iw->k.command_queue); } void draw_sprites_kernel(t_sdl *iw) { t_sprite *tmp1; tmp1 = *iw->sprite; while (tmp1 != 0) { if (iw->sectors[tmp1->num_sec].visited && tmp1->draweble && tmp1->taken == 0) { if (tmp1->top[WINDOW_W / 2] != -1 && tmp1->sx < WINDOW_W / 2 && tmp1->ex > WINDOW_W / 2 && tmp1->top[WINDOW_W / 2] < WINDOW_H / 2 && tmp1->bottom[WINDOW_W / 2] > WINDOW_H / 2 && tmp1->sy < WINDOW_H / 2 && tmp1->ey > WINDOW_H / 2) iw->v.look_sprite = tmp1; draw_sprite_kernel(iw, tmp1); } tmp1 = tmp1->next; } } void draw_glass_sprites_kernel(t_sdl *iw) { t_sprite *tmp1; tmp1 = *iw->sprite; while (tmp1 != 0) { if (tmp1->num_sec == iw->d.cs && tmp1->draweble) { draw_sprite_kernel(iw, tmp1); tmp1->draweble = 0; } tmp1 = tmp1->next; } } <|start_filename|>3d/SRC4/draw_floor_ceil_betw_kernel.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* draw_floor_ceil_betw_kernel.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbolilyi <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/05 14:37:31 by dbolilyi #+# #+# */ /* Updated: 2019/03/05 14:37:32 by dbolilyi ### ########.fr */ /* */ /* ************************************************************************** */ #include "../guardians.h" void draw_floor_ceil_betw_tex_kernel2(t_sdl *iw, t_save_wall *left, t_draw_wall_floor_ceil_tex_kernel *d) { if (iw->sectors[iw->d.cs].light == 0 || iw->sectors[iw->d.cs].light->t != 18) d->cint[16] = 1; else d->cint[16] = 0; d->cint[0] = iw->t[left->wall->t]->w; d->cint[1] = iw->t[left->wall->t]->h; d->cint[2] = iw->t[iw->sectors[iw->d.cs].fr.t]->w; d->cint[3] = iw->t[iw->sectors[iw->d.cs].fr.t]->h; if (iw->sectors[iw->d.cs].cl.t >= 0) { d->cint[4] = iw->t[iw->sectors[iw->d.cs].cl.t]->w; d->cint[5] = iw->t[iw->sectors[iw->d.cs].cl.t]->h; } else { d->cint[4] = iw->t[iw->l.skybox]->w; d->cint[5] = iw->t[iw->l.skybox]->h; } d->cint[6] = WINDOW_W; d->cint[7] = WINDOW_H; d->cint[8] = left->x; d->cint[9] = left->p.x; d->cint[10] = left->p.y; d->cint[12] = iw->d.screen_left; } void draw_floor_ceil_betw_tex_kernel3(t_sdl *iw, t_save_wall *left, t_save_wall *right, t_draw_wall_floor_ceil_tex_kernel *d) { d->cint[14] = iw->sectors[iw->d.cs].cl.t; d->cint[15] = iw->p.rotup; d->cfloat[5] = iw->d.screen.a; d->cfloat[6] = iw->d.screen.b; d->cfloat[7] = iw->d.screen.c; d->cfloat[8] = iw->d.screen_len; d->cfloat[13] = left->olen; d->cfloat[14] = iw->tsz[left->wall->t]; d->cfloat[17] = iw->p.rot; d->cfloat[18] = iw->v.angle; d->lv.x = (float)(left->p.x - iw->p.x); d->lv.y = (float)(left->p.y - iw->p.y); d->rv.x = (float)(right->p.x - iw->p.x); d->rv.y = (float)(right->p.y - iw->p.y); d->ang = acosf((d->lv.x * d->rv.x + d->lv.y * d->rv.y) / (sqrtf(d->lv.x * d->lv.x + d->lv.y * d->lv.y) * sqrtf(d->rv.x * d->rv.x + d->rv.y * d->rv.y))); d->cfloat[0] = d->ang / (float)(right->x - left->x + 1); d->ang = 0.0f; d->rv.x = (float)(-right->p.x + left->p.x); d->rv.y = (float)(-right->p.y + left->p.y); d->cfloat[2] = G180 - acosf((d->lv.x * d->rv.x + d->lv.y * d->rv.y) / (sqrtf(d->lv.x * d->lv.x + d->lv.y * d->lv.y) * sqrtf(d->rv.x * d->rv.x + d->rv.y * d->rv.y))); } void draw_floor_ceil_betw_tex_kernel4(t_sdl *iw, t_save_wall *left, t_save_wall *right, t_draw_wall_floor_ceil_tex_kernel *d) { d->cfloat[1] = sqrtf(powf(iw->p.x - left->p.x, 2.0f) + powf(iw->p.y - left->p.y, 2.0f)); d->len_lr = sqrtf(powf(left->p.x - right->p.x, 2.0f) + powf(left->p.y - right->p.y, 2.0f)); d->cfloat[3] = (float)(right->p.x - left->p.x) / d->len_lr; d->cfloat[4] = (float)(right->p.y - left->p.y) / d->len_lr; d->cfloat[15] = get_ceil_z(iw, iw->p.x, iw->p.y); d->cfloat[16] = get_floor_z(iw, iw->p.x, iw->p.y); d->cint[11] = (int)(d->cfloat[15] - d->cfloat[16]); d->cfloat[9] = (float)d->cint[11] / ((float)iw->p.z - d->cfloat[16]); d->cfloat[10] = (float)d->cint[11] / (d->cfloat[15] - (float)iw->p.z); d->cfloat[11] = (float)iw->p.x / 1000.0f; d->cfloat[12] = (float)iw->p.y / 1000.0f; clEnqueueWriteBuffer(iw->k.command_queue, iw->k.m_wallTop, CL_TRUE, 0, (right->x - left->x + 1) * sizeof(int), iw->d.wallTop, 0, NULL, NULL); clEnqueueWriteBuffer(iw->k.command_queue, iw->k.m_wallBot, CL_TRUE, 0, (right->x - left->x + 1) * sizeof(int), iw->d.wallBot, 0, NULL, NULL); clEnqueueWriteBuffer(iw->k.command_queue, iw->k.m_cint, CL_TRUE, 0, 17 * sizeof(int), d->cint, 0, NULL, NULL); clEnqueueWriteBuffer(iw->k.command_queue, iw->k.m_cfloat, CL_TRUE, 0, 19 * sizeof(float), d->cfloat, 0, NULL, NULL); clEnqueueWriteBuffer(iw->k.command_queue, iw->k.m_top_betw, CL_TRUE, 0, (right->x - left->x + 1) * sizeof(int), iw->d.save_top_betw, 0, NULL, NULL); } void draw_floor_ceil_betw_tex_kernel(t_sdl *iw, t_save_wall *left, t_save_wall *right, int len) { t_draw_wall_floor_ceil_tex_kernel d; draw_floor_ceil_betw_tex_kernel2(iw, left, &d); d.cint[13] = iw->d.screen_right; draw_floor_ceil_betw_tex_kernel3(iw, left, right, &d); draw_floor_ceil_betw_tex_kernel4(iw, left, right, &d); clEnqueueWriteBuffer(iw->k.command_queue, iw->k.m_bot_betw, CL_TRUE, 0, (right->x - left->x + 1) * sizeof(int), iw->d.save_bot_betw, 0, NULL, NULL); clSetKernelArg(iw->k.kernel3, 3, sizeof(cl_mem), (void *)&iw->k.m_t[left->wall->t]); clSetKernelArg(iw->k.kernel3, 4, sizeof(cl_mem), (void *)&iw->k.m_t[iw->sectors[iw->d.cs].fr.t]); if (iw->sectors[iw->d.cs].cl.t >= 0) clSetKernelArg(iw->k.kernel3, 5, sizeof(cl_mem), (void *)&iw->k.m_t[iw->sectors[iw->d.cs].cl.t]); else clSetKernelArg(iw->k.kernel3, 5, sizeof(cl_mem), (void *)&iw->k.m_t[iw->l.skybox]); d.global_item_size = len; d.local_item_size = 1; iw->k.ret = clEnqueueNDRangeKernel(iw->k.command_queue, iw->k.kernel3, 1, NULL, &d.global_item_size, &d.local_item_size, 0, NULL, NULL); clFlush(iw->k.command_queue); clFinish(iw->k.command_queue); } <|start_filename|>3d/SRC/draw_hud4.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* draw_hud4.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbolilyi <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/05 15:22:31 by dbolilyi #+# #+# */ /* Updated: 2019/03/05 15:22:33 by dbolilyi ### ########.fr */ /* */ /* ************************************************************************** */ #include "../guardians.h" void draw_some_info(t_sdl *iw) { t_draw_info d; if (iw->v.game_mode) return ; d.col.r = 0; d.col.g = 255; d.col.b = 0; d.col.a = 0; d.rect.x = 0; d.rect.y = 0; d.rect.w = 200; d.rect.h = 100; draw_text_number(iw, &d, "FPS: ", iw->v.fps); d.rect.y = 25; draw_text_number(iw, &d, "Sector: ", iw->d.cs); d.rect.y = 50; draw_text_number(iw, &d, "Fly mode: ", iw->v.fly_mode); d.rect.y = 100; draw_text_number(iw, &d, "Story texture: ", iw->l.story); d.rect.y = 75; draw_text_number(iw, &d, "Lunar gravity: ", (int)(iw->l.accel)); d.rect.x = 165; draw_text_number(iw, &d, ".", (int)(iw->l.accel * 100.0f) % 100); draw_some_info2(iw); } void draw_menu_sphere(t_sdl *iw, int a, const char *t) { float sq; int i; int b; int r; b = WINDOW_H + 150; r = 25; i = a - r; while (++i < a + r) { sq = sqrtf(-powf(a, 2.0f) + 2.0f * (float)(a * i) + powf(r, 2.0f) - powf(i, 2.0f)); set_pixel2(iw->sur, i, (int)((float)b - sq) - 20, MENU_COLOR); set_pixel2(iw->sur, i, (int)(sq + (float)b) + 20, MENU_COLOR); } i = -1; while (++i < r / 3) { set_pixel2(iw->sur, a + r + i - 2, b - 20 - i, MENU_COLOR); set_pixel2(iw->sur, a + r - i - 2, b - 20 - i, MENU_COLOR); set_pixel2(iw->sur, a - r + i + 2, b + 20 + i, MENU_COLOR); set_pixel2(iw->sur, a - r - i + 2, b + 20 + i, MENU_COLOR); } draw_text(iw, t, a - 6, WINDOW_H + 135); } void draw_up_down_menu_arrows(t_sdl *iw, int x) { int i; i = WINDOW_H + 140; while (--i > WINDOW_H + 110) set_pixel2(iw->sur, x, i, MENU_COLOR); i = WINDOW_H + 160; while (++i < WINDOW_H + 190) set_pixel2(iw->sur, x, i, MENU_COLOR); i = -1; while (++i < 10) { set_pixel2(iw->sur, x + i, WINDOW_H + 110 + i, MENU_COLOR); set_pixel2(iw->sur, x - i, WINDOW_H + 110 + i, MENU_COLOR); set_pixel2(iw->sur, x + i, WINDOW_H + 190 - i, MENU_COLOR); set_pixel2(iw->sur, x - i, WINDOW_H + 190 - i, MENU_COLOR); } } void draw_menu(t_sdl *iw) { if (iw->v.game_mode) return ; draw_menu_sphere(iw, 100, "X"); draw_menu_sphere(iw, 170, "Y"); draw_up_down_menu_arrows(iw, 50); if (iw->v.changing_fc) draw_text(iw, "C", 15, WINDOW_H + 135); else draw_text(iw, "F", 15, WINDOW_H + 135); draw_text(iw, "R", 210, WINDOW_H + 135); draw_text(iw, "Sprites:", 250, WINDOW_H + 135); draw_text(iw, "Decor.", 335, WINDOW_H + 105); draw_text(iw, "Pickup", 335, WINDOW_H + 135); draw_text(iw, "Enemies", 335, WINDOW_H + 165); } void draw_tex_to_select(t_sdl *iw) { int i; SDL_Rect rect; if (iw->v.game_mode) return ; rect.x = 0; rect.y = WINDOW_H; rect.w = 100; rect.h = 100; i = iw->v.scroll_first_tex - 1; while (++i < TEXTURES_COUNT && rect.x < WINDOW_W) { ft_scaled_blit(iw->t[i], iw->sur, &rect); rect.x += 100; } } <|start_filename|>3d/SRC3/set_defaults_sprites.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* set_defaults_sprites.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbolilyi <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/05 13:06:05 by dbolilyi #+# #+# */ /* Updated: 2019/03/05 13:06:06 by dbolilyi ### ########.fr */ /* */ /* ************************************************************************** */ #include "../guardians.h" void get_sprite_texture(t_sdl *iw, t_sprite *s) { if (s->type == 0) { s->t = iw->t_decor[s->t_numb]; s->t_kernel = &iw->k.m_t_decor[s->t_numb]; } else if (s->type == 1) { s->t = iw->t_pickup[s->t_numb]; s->t_kernel = &iw->k.m_t_pickup[s->t_numb]; } else if (s->type == 2) { s->t = iw->t_enemies[s->t_numb]; s->t_kernel = &iw->k.m_t_enemies[s->t_numb]; } } void set_sprites_z(t_sdl *iw) { t_sprite *s; s = *(iw->sprite); while (s) { get_sprite_texture(iw, s); s->z = get_floor_z_sec(iw, s->x, s->y, s->num_sec); s = s->next; } } <|start_filename|>3d/SRC/set_get_pixels.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* set_get_pixels.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbolilyi <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/01 17:46:23 by dbolilyi #+# #+# */ /* Updated: 2019/03/01 17:47:58 by dbolilyi ### ########.fr */ /* */ /* ************************************************************************** */ #include "../guardians.h" void set_pixel2(SDL_Surface *surface, int x, int y, Uint32 pixel) { Uint8 *target_pixel; if (x >= 0 && x < surface->w && y >= 0 && y < surface->h) { target_pixel = (Uint8 *)surface->pixels + y * surface->pitch + x * 4; *(Uint32 *)target_pixel = pixel; } } int get_light_color(int color, t_picture *light) { if (light == 0 || light->t != 18) return (color); return ((((int)((float)(color >> 16) * 0.2f)) << 16) + (((int)((float)((color >> 8) - (color >> 16 << 8)) * 0.2f)) << 8) + (int)((float)(color - (color >> 8 << 8)) * 0.2f)); } Uint32 get_pixel(t_packaging_texture *sur, const int x, const int y) { uint8_t *v; int bpp; if (x < 0 || x >= sur->w || y < 0 || y >= sur->h) return (0); bpp = sur->bpp; v = (uint8_t *)sur->pixels + y * sur->pitch + x * bpp; return (v[0] | v[1] << 8 | v[2] << 16); } Uint32 get_pixel_surface(SDL_Surface *sur, const int x, const int y) { uint8_t *v; int bpp; if (x < 0 || x >= sur->w || y < 0 || y >= sur->h) return (0); bpp = sur->format->BytesPerPixel; v = (uint8_t *)sur->pixels + y * sur->pitch + x * bpp; return (v[0] | v[1] << 8 | v[2] << 16); } <|start_filename|>3d/SRC3/get_packaging_tex_from_sur.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* get_packaging_tex_from_sur.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbolilyi <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/05 13:04:51 by dbolilyi #+# #+# */ /* Updated: 2019/03/05 13:04:52 by dbolilyi ### ########.fr */ /* */ /* ************************************************************************** */ #include "../guardians.h" void get_packaging_texture(t_packaging_texture **pack, SDL_Surface *sur) { *pack = (t_packaging_texture *)malloc(sizeof(t_packaging_texture)); (*pack)->w = sur->w; (*pack)->h = sur->h; (*pack)->pitch = sur->pitch; (*pack)->bpp = sur->format->BytesPerPixel; (*pack)->pixels = malloc(sur->pitch * sur->h); ft_memcpy((*pack)->pixels, sur->pixels, sur->pitch * sur->h); SDL_FreeSurface(sur); } void get_packaging_textures2(t_sdl *iw) { int i; get_packaging_texture(&iw->bag.button[0], iw->bag.button_sur[0]); get_packaging_texture(&iw->bag.button[1], iw->bag.button_sur[1]); get_packaging_texture(&iw->bag.button[2], iw->bag.button_sur[2]); i = -1; while (++i < 6) get_packaging_texture(&iw->menu.icons[i], iw->menu.icons_sur[i]); get_packaging_texture(&iw->map.player, iw->map.player_sur); } void get_packaging_textures(t_sdl *iw) { int i; get_packaging_texture(&iw->hud.enot, iw->hud.enot_sur); get_packaging_texture(&iw->hud.miss, iw->hud.miss_sur); get_packaging_texture(&iw->hud.win, iw->hud.win_sur); get_packaging_texture(&iw->hud.dead, iw->hud.dead_sur); get_packaging_texture(&iw->hud.saved, iw->hud.saved_sur); i = -1; while (++i < TEXTURES_COUNT) get_packaging_texture(&iw->t[i], iw->t_sur[i]); i = -1; while (++i < DECOR_TEXTURES_COUNT) get_packaging_texture(&iw->t_decor[i], iw->t_decor_sur[i]); i = -1; while (++i < ENEMIES_TEXTURES_COUNT) get_packaging_texture(&iw->t_enemies[i], iw->t_enemies_sur[i]); i = -1; while (++i < PICK_UP_TEXTURES_COUNT) get_packaging_texture(&iw->t_pickup[i], iw->t_pickup_sur[i]); i = -1; while (++i < WEAPONS_TEXTURES_COUNT) get_packaging_texture(&iw->t_weap[i], iw->t_weap_sur[i]); get_packaging_textures2(iw); } <|start_filename|>3d/SRC2/enemy_intelligence1.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* enemy_intelligence1.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbolilyi <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/05 12:07:02 by dbolilyi #+# #+# */ /* Updated: 2019/03/05 12:08:36 by dbolilyi ### ########.fr */ /* */ /* ************************************************************************** */ #include "../guardians.h" void enemy_intelligence1_s2_1(t_sdl *iw, t_sprite *s, int i) { if ((i = enemy_sees_player(iw, s)) != -1) { if (i > 2000) move_enemy(iw, s); else s->e.status = 3; } else if (s->e.vis_esp.curr_sector != -1) { i = (int)sqrtf(powf(s->x - s->e.vis_esp.px, 2.0f) + powf(s->y - s->e.vis_esp.py, 2.0f)); if (i > 10) move_enemy(iw, s); else { s->t_numb = 8; s->e.status = 0; } } } void enemy_intelligence1_s2(t_sdl *iw, t_sprite *s) { if (clock() - s->e.previous_picture_change > CLKS_P_S / 3) { s->e.previous_picture_change = clock(); if (s->t_numb <= 8 || s->t_numb >= 12) s->t_numb = 10; else s->t_numb++; s->t = iw->t_enemies[s->t_numb]; s->t_kernel = &iw->k.m_t_enemies[s->t_numb]; } enemy_intelligence1_s2_1(iw, s, 0); } void enemy_intelligence1_s3(t_sdl *iw, t_sprite *s) { s->e.previous_picture_change = clock(); if (s->t_numb < 13) { s->t_numb = 13; iw->p.health -= ENEMY_DAMAGE1 * iw->menu.count; if (!Mix_Playing(6)) Mix_PlayChannel(6, iw->sounds.env[14], 0); if (!Mix_Playing(4)) Mix_PlayChannel(4, iw->sounds.env[10], 0); } else if (s->t_numb == 13) s->t_numb = 14; else { s->e.status = 0; s->t_numb = 8; } s->t = iw->t_enemies[s->t_numb]; s->t_kernel = &iw->k.m_t_enemies[s->t_numb]; } void enemy_intelligence1_2(t_sdl *iw, t_sprite *s, int i) { if (s->e.status == 4 && clock() - s->e.previous_picture_change > CLKS_P_S / 4) { s->e.previous_picture_change = clock(); if (s->t_numb < 15) s->t_numb = 15; else if (s->t_numb < 19) s->t_numb++; else s->e.status = 5; s->t = iw->t_enemies[s->t_numb]; s->t_kernel = &iw->k.m_t_enemies[s->t_numb]; } else if (s->e.status == 1) if ((i = enemy_sees_player(iw, s)) != -1 && (i < 1000 || s->e.health < ENEMY_HEALTH1)) { check_enemies_in_sector(iw, s); s->e.status = 0; } } void enemy_intelligence1(t_sdl *iw, t_sprite *s) { int i; if (s->e.status == 0) { if ((i = enemy_sees_player(iw, s)) != -1 && (i < 4000 || s->e.health < ENEMY_HEALTH1)) s->e.status = 2; } else if (s->e.status == 2) enemy_intelligence1_s2(iw, s); else if (s->e.status == 3 && clock() - s->e.previous_picture_change > CLKS_P_S / 2) enemy_intelligence1_s3(iw, s); else enemy_intelligence1_2(iw, s, 0); if (s->e.health <= 0 && s->e.status < 4) { Mix_PlayChannel(6, iw->sounds.env[21], 0); s->e.status = 4; } sprite_physics(iw, s); } <|start_filename|>3d/SRC3/draw_get_between_sectors_walls2.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* draw_get_between_sectors_walls2.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbolilyi <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/05 16:54:49 by dbolilyi #+# #+# */ /* Updated: 2019/03/05 16:54:51 by dbolilyi ### ########.fr */ /* */ /* ************************************************************************** */ #include "../guardians.h" void draw_between_sectors_walls2(t_sdl *iw, t_save_wall *left, t_save_wall *right, int *tmp) { t_draw_line l; int lz; int rz; l.x0 = left->x; l.x1 = right->x; lz = get_ceil_z(iw, left->p.x + iw->walls[left->wall->nextsector_wall].x - left->wall->next->x, left->p.y + iw->walls [left->wall->nextsector_wall].y - left->wall->next->y); rz = get_ceil_z(iw, right->p.x + iw->walls[left->wall->nextsector_wall].x - left->wall->next->x, right->p.y + iw->walls [left->wall->nextsector_wall].y - left->wall->next->y); l.y0 = WINDOW_H * (iw->p.z + (int)left->plen / 2 - lz) / (int)left->plen + iw->p.rotup; l.y1 = WINDOW_H * (iw->p.z + (int)right->plen / 2 - rz) / (int)right->plen + iw->p.rotup; brez_line(tmp, l); if (*(iw->v.look_wall) == 0 && iw->v.mouse_mode == 1 && left->x < WINDOW_W / 2 && right->x > WINDOW_W / 2 && tmp[WINDOW_W / 2 - left->x] > WINDOW_H / 2) { *(iw->v.look_wall) = left->wall; *(iw->v.look_sector) = &iw->sectors[iw->d.cs]; } draw_between_sectors_top_tex(iw, left, right, tmp); } void draw_between_sectors_walls3(t_sdl *iw, t_save_wall *left, t_save_wall *right, int *tmp) { if (*(iw->v.look_wall) == 0 && iw->v.mouse_mode == 1 && left->x < WINDOW_W / 2 && right->x > WINDOW_W / 2 && tmp[WINDOW_W / 2 - left->x] < WINDOW_H / 2) { *(iw->v.look_wall) = left->wall; *(iw->v.look_sector) = &iw->sectors[iw->d.cs]; } } void draw_between_sectors_walls(t_sdl *iw, t_save_wall *left, t_save_wall *right) { t_draw_line l; int lz; int rz; int *tmp; tmp = (int *)malloc((right->x - left->x + 1) * sizeof(int)); l.x0 = left->x; l.x1 = right->x; lz = get_floor_z(iw, left->p.x + iw->walls[left->wall->nextsector_wall].x - left->wall->next->x, left->p.y + iw->walls [left->wall->nextsector_wall].y - left->wall->next->y); rz = get_floor_z(iw, right->p.x + iw->walls[left->wall->nextsector_wall].x - left->wall->next->x, right->p.y + iw->walls [left->wall->nextsector_wall].y - left->wall->next->y); l.y0 = WINDOW_H * (iw->p.z + (int)left->plen / 2 - lz) / (int)left->plen + iw->p.rotup; l.y1 = WINDOW_H * (iw->p.z + (int)right->plen / 2 - rz) / (int)right->plen + iw->p.rotup; brez_line(tmp, l); draw_between_sectors_walls3(iw, left, right, tmp); draw_between_sectors_bot_tex(iw, left, right, tmp); draw_between_sectors_walls2(iw, left, right, tmp); free(tmp); } <|start_filename|>3d/SRC3/get_left_right_visible_walls.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* get_left_right_visible_walls.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbolilyi <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/05 13:04:44 by dbolilyi #+# #+# */ /* Updated: 2019/03/05 13:04:45 by dbolilyi ### ########.fr */ /* */ /* ************************************************************************** */ #include "../guardians.h" int if_not_in_vw(t_sdl *iw, t_wall *wall) { t_save_wall *tmp; tmp = iw->d.vw; while (tmp != 0) { if (tmp->wall == wall) return (0); tmp = tmp->next; } return (1); } void add_lr_wall(t_sdl *iw, t_intpoint2d *p, t_wall *wall, int x) { t_save_wall *tmp; tmp = (t_save_wall *)malloc(sizeof(t_save_wall)); tmp->x = x; tmp->wall = wall; tmp->len = sqrtf(powf((float)(iw->p.x - p->x), 2.0f) + powf((float)(iw->p.y - p->y), 2.0f)); tmp->plen = fabsf(iw->d.screen.a * (float)p->x + iw->d.screen.b * (float)p->y + iw->d.screen.c) / sqrtf( iw->d.screen.a * iw->d.screen.a + iw->d.screen.b * iw->d.screen.b); if ((int)tmp->plen == 0) tmp->plen = 1.0f; tmp->olen = sqrtf(powf(p->x - wall->x, 2.0f) + powf(p->y - wall->y, 2.0f)); tmp->p = *p; tmp->zd = get_floor_z(iw, p->x, p->y); tmp->zu = get_ceil_z(iw, p->x, p->y); tmp->next = 0; add_wall(iw, tmp); } int visible_wall(t_sdl *iw, int wall) { if ((iw->p.x - iw->walls[wall].x) * (iw->walls[wall].next->y - iw->walls[wall].y) - (iw->p.y - iw->walls[wall].y) * (iw->walls[wall].next->x - iw->walls[wall].x) >= 0) return (1); return (0); } int point_in_front_and_on_wall(t_sdl *iw, t_intpoint2d *p, int wall) { float side; side = iw->d.screen.a * p->x + iw->d.screen.b * p->y + iw->d.screen.c; if (side * iw->d.view_dir.y < 0) if ((p->x >= ft_min(iw->walls[wall].x, iw->walls[wall].next->x) && p->x <= ft_max(iw->walls[wall].x, iw->walls[wall].next->x)) && (p->y >= ft_min(iw->walls[wall].y, iw->walls[wall].next->y) && p->y <= ft_max(iw->walls[wall].y, iw->walls[wall].next->y))) return (1); return (0); } int cross_two_lines(t_line2d *l1, t_line2d *l2, t_intpoint2d *p) { t_line2d *tmp; float py; if (l1->a == l2->a && l1->b == l2->b) return (0); if (l1->a == 0 && l2->a != 0) { tmp = l1; l1 = l2; l2 = tmp; } else if (l1->a == 0) return (0); py = (l2->a * l1->c - l1->a * l2->c) / (l1->a * l2->b - l2->a * l1->b); p->y = (int)roundf(py); if (l2->b == 0 && l2->a != 0) p->x = (int)roundf((l2->b * py + l2->c) / (-l2->a)); else p->x = (int)roundf((l1->b * py + l1->c) / (-l1->a)); return (1); } <|start_filename|>3d/SRC3/draw_subfunctions.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* draw_subfunctions.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbolilyi <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/05 13:03:48 by dbolilyi #+# #+# */ /* Updated: 2019/03/05 13:03:49 by dbolilyi ### ########.fr */ /* */ /* ************************************************************************** */ #include "../guardians.h" t_save_wall *find_next_vis_wall(t_sdl *iw, t_save_wall *left) { t_save_wall *right; right = iw->d.vw; while (right != 0) { if (right->wall == left->wall->next) break ; right = right->next; } return (right); } void set_top_bottom(t_sdl *iw) { int i; i = -1; while (++i <= WINDOW_W) { iw->d.top[i] = 0; iw->d.bottom[i] = WINDOW_H; } } void free_walls(t_sdl *iw) { t_save_wall *tmp; t_save_wall *tmp2; tmp = iw->d.vw; while (tmp != 0) { tmp2 = tmp; tmp = tmp->next; free(tmp2); } iw->d.vw = 0; } int check_look_picture(t_sdl *iw) { t_picture *pic; if (*(iw->v.look_wall) == 0 || *(iw->v.look_picture) == 0) return (0); pic = (*(iw->v.look_wall))->p; while (pic) { if (pic == *(iw->v.look_picture)) return (1); pic = pic->next; } return (0); } void save_walls(t_sdl *iw) { t_save_wall *tmp; if (!iw->d.vw) return ; tmp = iw->d.vw; while (tmp->next) tmp = tmp->next; tmp->next = *(iw->vw_save); *(iw->vw_save) = iw->d.vw; iw->d.vw = 0; } <|start_filename|>3d/SRC3/draw_inclined_floor_ceil2.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* draw_inclined_floor_ceil2.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbolilyi <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/05 17:09:39 by dbolilyi #+# #+# */ /* Updated: 2019/03/05 17:09:40 by dbolilyi ### ########.fr */ /* */ /* ************************************************************************** */ #include "../guardians.h" void draw_inclined_floor_ceil_tex1(t_sdl *iw, t_save_wall *left, t_save_wall *right, t_draw_wall_floor_ceil_tex *d) { d->lv.x = (float)(left->p.x - iw->p.x); d->lv.y = (float)(left->p.y - iw->p.y); d->rv.x = (float)(right->p.x - iw->p.x); d->rv.y = (float)(right->p.y - iw->p.y); d->ang = acosf((d->lv.x * d->rv.x + d->lv.y * d->rv.y) / (sqrtf(d->lv.x * d->lv.x + d->lv.y * d->lv.y) * sqrtf(d->rv.x * d->rv.x + d->rv.y * d->rv.y))); d->dang = d->ang / (float)(right->x - left->x + 1); d->ang = 0.0f; d->rv.x = (float)(-right->p.x + left->p.x); d->rv.y = (float)(-right->p.y + left->p.y); d->sing = G180 - acosf((d->lv.x * d->rv.x + d->lv.y * d->rv.y) / (sqrtf(d->lv.x * d->lv.x + d->lv.y * d->lv.y) * sqrtf(d->rv.x * d->rv.x + d->rv.y * d->rv.y))); d->lenpl = sqrtf(powf(iw->p.x - left->p.x, 2.0f) + powf(iw->p.y - left->p.y, 2.0f)); d->len_lr = sqrtf(powf(left->p.x - right->p.x, 2.0f) + powf(left->p.y - right->p.y, 2.0f)); d->rv.x = (float)(right->p.x - left->p.x) / d->len_lr; d->rv.y = (float)(right->p.y - left->p.y) / d->len_lr; d->zu = get_ceil_z(iw, iw->p.x, iw->p.y); } void draw_inclined_floor_ceil_tex2(t_sdl *iw, t_save_wall *left, t_draw_wall_floor_ceil_tex *d) { d->zd = get_floor_z(iw, iw->p.x, iw->p.y); d->frpl = (float)(d->zu - d->zd) / (float)(iw->p.z - d->zd); d->clpl = (float)(d->zu - d->zd) / (float)(d->zu - iw->p.z); d->px = (float)iw->p.x / 1000.0f; d->py = (float)iw->p.y / 1000.0f; if (iw->sectors[iw->d.cs].cl.t < 0) { d->rot = (iw->p.rot - iw->v.angle) + (float)left->x / (float)WINDOW_W * iw->v.angle * 2.0f; if (d->rot < 0.0f) d->rot += G360; else if (d->rot > G360) d->rot -= G360; d->sky_x = d->rot * ((float)iw->t[iw->l.skybox]->w) / G360; d->dx = (float)iw->t[iw->l.skybox]->w / (G360 / (iw->v.angle * 2) * WINDOW_W); d->dy = (float)iw->t[iw->l.skybox]->h / (float)(4 * WINDOW_H); } } void draw_inclined_floor_ceil_tex3(t_sdl *iw, t_save_wall *left, t_draw_wall_floor_ceil_tex *d) { d->left_len = sinf(d->ang) * d->lenpl / sinf(d->sing - d->ang); d->r.x = (float)left->p.x + d->rv.x * d->left_len; d->r.y = (float)left->p.y + d->rv.y * d->left_len; d->frcoef = get_ceil_z(iw, d->r.x, d->r.y) - get_floor_z(iw, d->r.x, d->r.y); d->clcoef = d->frcoef; d->wall_dist = (float)WINDOW_H / (fabsf(iw->d.screen.a * d->r.x + iw->d.screen.b * d->r.y + iw->d.screen.c) / iw->d.screen_len); d->r.x /= 1000.0f; d->r.y /= 1000.0f; } void draw_inclined_floor_ceil_tex4(t_sdl *iw, t_save_wall *left, t_draw_wall_floor_ceil_tex *d) { d->k = (float)(iw->d.wallBot[d->j] - iw->d.wallTop[d->j]) + d->frpl * (float)(d->i + 1 - iw->d.wallBot[d->j]); while (++d->i < iw->d.bottom[left->x + d->j]) { d->weight = d->wall_dist * d->frcoef / d->k; d->k += d->frpl; d->floor.x = d->weight * d->r.x + (1.0f - d->weight) * d->px; d->floor.y = d->weight * d->r.y + (1.0f - d->weight) * d->py; d->frcoef = (get_ceil_z(iw, d->floor.x * 1000.0f, d->floor.y * 1000.0f) - get_floor_z(iw, d->floor.x * 1000.0f, d->floor.y * 1000.0f) + d->frcoef) / 2.0f; set_pixel2(iw->sur, left->x + d->j, d->i, get_light_color(get_pixel(iw->t[iw->sectors[iw->d.cs].fr.t], ((d->floor.x < 0) ? (((int)(d->floor.x * (float)iw->t[iw->sectors[iw->d.cs]. fr.t]->w) % iw->t[iw->sectors[iw->d.cs].fr.t]->w) + iw->t[iw->sectors[iw-> d.cs].fr.t]->w - 1) : ((int)(d->floor.x * (float)iw->t[iw->sectors[iw->d. cs].fr.t]->w) % iw->t[iw->sectors[iw->d.cs].fr.t]->w)), ((d->floor.y < 0) ? (((int)(d->floor.y * (float)iw->t[iw->sectors[iw->d.cs].fr.t]->h) % iw->t[ iw->sectors[iw->d.cs].fr.t]->h) + iw->t[iw->sectors[iw->d.cs].fr.t]->h - 1) : ((int)(d->floor.y * (float)iw->t[iw->sectors[iw->d.cs].fr.t]->h) % iw->t[iw->sectors[iw->d.cs].fr.t]->h))), iw->sectors[iw->d.cs].light)); } iw->d.bottom[left->x + d->j] = iw->d.wallBot[d->j]; } <|start_filename|>libft/get_next_line.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* get_next_line.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbolilyi <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/05/01 12:56:19 by dbolilyi #+# #+# */ /* Updated: 2018/06/17 14:33:42 by dbolilyi ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" #include <fcntl.h> static char *add_prev(t_line *lst, const int fd, char **line) { char *tmp1; char *tmp2; while (lst != 0) { if (lst->fd == fd) break ; lst = lst->next; } if ((lst == 0) || (lst->content == 0)) return (0); tmp1 = ft_strchr(lst->content, '\n'); if (tmp1 != 0) *tmp1 = '\0'; tmp2 = *line; *line = ft_strjoin(*line, lst->content); free(tmp2); tmp2 = lst->content; if (tmp1 != 0) lst->content = ft_strdup(tmp1 + 1); else lst->content = 0; free(tmp2); return (tmp1); } static t_line *ft_new_lst_add(t_line **lst, const int fd) { t_line *new; t_line *tmp; new = (t_line *)malloc(sizeof(t_line)); new->fd = fd; new->next = 0; if (*lst == 0) *lst = new; else { tmp = *lst; while (tmp->next != 0) tmp = tmp->next; tmp->next = new; } return (new); } static void save_end(t_line **lst, const int fd, char *end) { t_line *ltmp; ltmp = *lst; while (ltmp != 0) { if (ltmp->fd == fd) break ; ltmp = ltmp->next; } if (ltmp == 0) ltmp = ft_new_lst_add(lst, fd); ltmp->content = (char *)malloc(BUFF_SIZE); ft_strcpy(ltmp->content, end); } static char read_next(t_line **lst, const int fd, char **line) { char buf[BUFF_SIZE + 1]; char *tmp1; char *tmp2; int rd; rd = read(fd, buf, BUFF_SIZE); while (rd > 0) { buf[rd] = '\0'; tmp1 = ft_strchr(buf, '\n'); if (tmp1 != 0) *tmp1 = '\0'; tmp2 = *line; *line = ft_strjoin(*line, buf); free(tmp2); if (tmp1 != 0) { save_end(lst, fd, tmp1 + 1); return (1); } rd = read(fd, buf, BUFF_SIZE); } if ((*line != 0) && (**line != '\0')) return (1); return (0); } int get_next_line(const int fd, char **line) { static t_line *lst = 0; char c; if ((line == 0) || (fd < 0) || (read(fd, &c, 0) < 0)) return (-1); *line = 0; if (add_prev(lst, fd, line) != 0) return (1); return (read_next(&lst, fd, line)); } <|start_filename|>editor/delete_memory.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* delete_memory.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ddehtyar <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/02/19 18:51:14 by ddehtyar #+# #+# */ /* Updated: 2019/02/19 18:51:15 by ddehtyar ### ########.fr */ /* */ /* ************************************************************************** */ #include "doom_nuken.h" void delete_pointer(t_doom *den, void *ptr) { t_wals *rmp; rmp = den->tmp; while (rmp->next) { if (rmp->next_sector == ptr) rmp->next_sector = NULL; if (rmp->nextsector_wall == ptr) rmp->nextsector_wall = NULL; rmp = rmp->next; } } void delete_sector_memory_one(t_doom *den, t_sector_list *first) { t_sector_list *sect; if (first->next != NULL) { sect = first; delete_pointer(den, sect); den->sectors = den->sectors->next; free(sect); return ; } else if (first->next == NULL) { free(first); den->sectors = NULL; } } void delete_sector_memory_two(t_doom *den, t_sector_list *first) { t_sector_list *sect; if (first->next->next != NULL) { sect = first->next; delete_pointer(den, sect); first->next = first->next->next; free(sect); return ; } else if (first->next->next == NULL) { sect = first->next; free(sect); first->next = NULL; return ; } } void delete_sector_memory(t_doom *den) { t_sector_list *first; int i; i = -1; first = den->sectors; while (first) { if (++i == 0 && den->find_tmp->sec == i) { delete_sector_memory_one(den, first); return ; } else if (first->next && i + 1 == den->find_tmp->sec) { delete_sector_memory_two(den, first); return ; } first = first->next; } } void delete_wall(t_doom *den, t_col *vec) { if (den->change == 4) { delete_sprite(den, den->find_sprite); den->change = 0; } else if (den->change == 3) { check_finish_sprite(den); delete_sector_memory(den); delete_sector(den); den->change = 0; } else { den->button = 0; write_list(den, den->tmp); clean_vec(vec); } clean_find_vec(den); clear_texture(den, vec); map_network(den); info_display(den); } <|start_filename|>editor/button_move.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* button_move.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ddehtyar <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/04 11:36:17 by ddehtyar #+# #+# */ /* Updated: 2019/03/04 11:36:18 by ddehtyar ### ########.fr */ /* */ /* ************************************************************************** */ #include "doom_nuken.h" void movie_button_five(t_doom *den, t_col *vec) { if (den->button_change == 9 && (den->change == 1 || den->change == 2)) { all_sector(den, den->tmp); den->button_change = 0; den->color = 0xFFFFFF; den->change = 3; } else if (den->button_change == 10) { sprite(den); den->change = 0; den->button_change = 0; } else if (den->button_change == 11 && den->change == 3) { den->finish = den->find_tmp->sec; den->change = 0; den->button_change = 0; retry_write(den, vec); } } void movie_button_four(t_doom *den, t_col *vec) { if (den->button_change == 7) { if (den->blouk != 1 && den->walls > -1 && ((vec->x1 != -1000000 && vec->y1 != -1000000) && (vec->x2 != -1000000 && vec->y2 != -1000000))) back_wall(den, vec); else if (vec->x1 == -1000000 && vec->y1 == -1000000 && vec->x2 != -1000000 && vec->y2 != -1000000) back_startwall(den, vec); den->button_change = 0; } else if (den->button_change == 8) { player(den); den->button_change = 0; den->change = 0; } } void movie_button_three(t_doom *den) { if (den->button_change == 4) { if (den->sprite) check_sprite(den); den->xy.x = den->player.x; den->xy.y = den->player.y; in_all_sect(den); if (den->xy.bool_cor == -1) { den->player.x = -10000; den->player.y = -10000; } if (den->player.x == -10000 && den->player.y == -10000) blouk_player(den); else main3d_edit(den); den->button_change = 0; } else if (den->button_change == 5 && (den->change == 1 || den->change == 2)) { if (den->find_tmp_one && den->find_tmp_two) drow_find(den); den->button_change = 0; } } void movie_button_two(t_doom *den, t_col *vec) { if (den->button_change == 3 && ((den->change == 1 || den->change == 2) || den->change == 3)) { if (den->find_tmp_one != 0 && den->find_tmp_two != 0 && den->find_tmp->inside == 0 && den->find_tmp_one->inside == 0 && den->find_tmp_two->inside == 0) { portal_sector(den); clear_find(den); den->change = 0; den->button_change = 0; } else if (den->change == 3 && den->find_tmp->inside != 0) { make_portal_sector(den, vec); den->change = 0; den->button_change = 0; } } else if (den->button_change == 6) { save_map_file(den); save_map_info(den); den->button_change = 0; } } void movie_button(t_doom *den, t_col *vec) { if (den->button_change == 1 && (den->change != 0)) { if (check_picture(den) == 0 || den->change == 4) { delete_wall(den, vec); den->button_change = 0; } else blouk_delete(den); } else if (den->button_change == 2 && (den->change == 1 || den->change == 2)) { next_wall(den); den->button_change = 0; clean_display(den); info_display(den); SDL_UpdateWindowSurface(den->window); } else { movie_button_two(den, vec); movie_button_three(den); movie_button_four(den, vec); movie_button_five(den, vec); } } <|start_filename|>3d/SRC2/do_animations2.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* do_animations2.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbolilyi <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/05 16:36:15 by dbolilyi #+# #+# */ /* Updated: 2019/03/05 16:36:16 by dbolilyi ### ########.fr */ /* */ /* ************************************************************************** */ #include "../guardians.h" void do_sector_animations(t_sdl *iw) { t_sector_animation *tmp; tmp = iw->sector_animations; while (tmp) { if (clock() - tmp->prev_clock > CLKS_P_S / 50) { if (tmp->status == 1 && abs(tmp->curr_dy) < abs(tmp->dy)) { do_sector_animation_step(iw, tmp, ((tmp->dy > 0) ? tmp->speed : -tmp->speed) * 10); tmp->curr_dy += ((tmp->dy > 0) ? tmp->speed : -tmp->speed) * 10; } else if (tmp->status == 0 && tmp->curr_dy != 0) { do_sector_animation_step(iw, tmp, ((tmp->dy < 0) ? tmp->speed : -tmp->speed) * 10); tmp->curr_dy += ((tmp->dy < 0) ? tmp->speed : -tmp->speed) * 10; } tmp->prev_clock = clock(); } tmp = tmp->next; } } <|start_filename|>3d/SRC3/draw_glass.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* draw_glass.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbolilyi <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/05 13:02:52 by dbolilyi #+# #+# */ /* Updated: 2019/03/05 13:02:53 by dbolilyi ### ########.fr */ /* */ /* ************************************************************************** */ #include "../guardians.h" void draw_glass_tex1(t_sdl *iw, t_save_wall *left, t_save_wall *right, t_draw_glass *d) { d->lv.x = (float)(left->p.x - iw->p.x); d->lv.y = (float)(left->p.y - iw->p.y); d->rv.x = (float)(right->p.x - iw->p.x); d->rv.y = (float)(right->p.y - iw->p.y); d->ang = acosf((d->lv.x * d->rv.x + d->lv.y * d->rv.y) / (sqrtf(d->lv.x * d->lv.x + d->lv.y * d->lv.y) * sqrtf(d->rv.x * d->rv.x + d->rv.y * d->rv.y))); d->dang = d->ang / (float)(right->x - left->x + 1); d->ang = 0.0f; d->rv.x = (float)(-right->p.x + left->p.x); d->rv.y = (float)(-right->p.y + left->p.y); d->sing = G180 - acosf((d->lv.x * d->rv.x + d->lv.y * d->rv.y) / (sqrtf(d->lv.x * d->lv.x + d->lv.y * d->lv.y) * sqrtf(d->rv.x * d->rv.x + d->rv.y * d->rv.y))); d->lenpl = sqrtf(powf(iw->p.x - left->p.x, 2.0f) + powf(iw->p.y - left->p.y, 2.0f)); d->len_lr = sqrtf(powf(left->p.x - right->p.x, 2.0f) + powf(left->p.y - right->p.y, 2.0f)); } void draw_glass_tex2(t_sdl *iw, t_save_wall *left, t_save_wall *right, t_draw_glass *d) { d->nleft_zd = get_floor_z(iw, iw->walls[left->wall->nextsector_wall]. next->x, iw->walls[left->wall->nextsector_wall].next->y); if (left->zu < d->nleft_zu) { d->zudiff = (right->zu - left->zu) / d->len_lr; d->nleft_zu = left->zu; } else { d->nright_zu = get_ceil_z(iw, iw->walls[left->wall->nextsector_wall].x, iw->walls[left->wall->nextsector_wall].y); d->zudiff = (d->nright_zu - d->nleft_zu) / d->len_lr; } if (left->zd > d->nleft_zd) { d->zddiff = (right->zd - left->zd) / d->len_lr; d->nleft_zd = left->zd; } else { d->nright_zd = get_floor_z(iw, iw->walls[left->wall->nextsector_wall].x, iw->walls[left->wall->nextsector_wall].y); d->zddiff = (d->nright_zd - d->nleft_zd) / d->len_lr; } } void draw_glass_tex3(t_sdl *iw, t_save_wall *left, t_draw_glass *d) { d->zd = (float)d->nleft_zd + d->left_len * d->zddiff; d->dty = ((d->zu - d->zd) * (float)iw->t[left->wall->glass]->h / 1000.0f) / (float)(iw->d.save_bot_betw[d->j] - iw->d.save_top_betw[d->j]) * d->ty_tsz; d->ty = 0.0f; if (iw->d.save_top_betw[d->j] < iw->d.top[left->x + d->j]) { d->ty += (float)(iw->d.top[left->x + d->j] - iw->d.save_top_betw[d->j]) * d->dty; d->i = iw->d.top[left->x + d->j] - 1; } else d->i = iw->d.save_top_betw[d->j] - 1; while (++d->i < iw->d.save_bot_betw[d->j] && d->i < iw->d.bottom[d->j + left->x]) { d->pixel = get_pixel(iw->t[left->wall->glass], (int)d->tx % iw->t[left->wall->glass]->w, (int)d->ty % iw->t[left->wall->glass]->h); if (d->pixel != 0x010000) set_pixel2(iw->sur, left->x + d->j, d->i, get_light_color(d->pixel, iw->sectors[iw->d.cs].light)); d->ty += d->dty; } d->ang += d->dang; } void draw_glass_tex(t_sdl *iw, t_save_wall *left, t_save_wall *right, int len) { t_draw_glass d; draw_glass_tex1(iw, left, right, &d); d.i = iw->d.cs; iw->d.cs = left->wall->nextsector; d.nleft_zu = get_ceil_z(iw, iw->walls[left->wall->nextsector_wall].next->x, iw->walls[left->wall->nextsector_wall].next->y); draw_glass_tex2(iw, left, right, &d); iw->d.cs = d.i; d.j = -1; while (++d.j < len) { if (iw->d.top[left->x + d.j] >= iw->d.bottom[left->x + d.j]) { d.ang += d.dang; continue; } d.left_len = sinf(d.ang) * d.lenpl / sinf(d.sing - d.ang); d.tx = (left->olen + d.left_len) * (float)iw->t[left->wall->glass]->w * iw->tsz[left->wall->glass] / 1000.0f; d.zu = (float)d.nleft_zu + d.left_len * d.zudiff; d.ty_tsz = iw->tsz[left->wall->glass] * (float)iw->t[left-> wall->glass]->w / (float)iw->t[left->wall->glass]->h; draw_glass_tex3(iw, left, &d); } } void draw_glass_sprites(t_sdl *iw) { t_sprite *tmp1; tmp1 = *iw->sprite; while (tmp1 != 0) { if (tmp1->num_sec == iw->d.cs && tmp1->draweble) { draw_sprite(iw, tmp1); tmp1->draweble = 0; } tmp1 = tmp1->next; } } <|start_filename|>3d/SRC4/draw_gun_kernel.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* draw_gun_kernel.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbolilyi <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/05 14:37:44 by dbolilyi #+# #+# */ /* Updated: 2019/03/05 14:37:46 by dbolilyi ### ########.fr */ /* */ /* ************************************************************************** */ #include "../guardians.h" void draw_gun_kernel2(t_sdl *iw, int *cint, int *to_i) { cint[3] = iw->guns.t_rect[iw->guns.t].x + iw->v.weapon_change_x; cint[4] = iw->guns.t_rect[iw->guns.t].y + iw->v.weapon_change_y + iw->v.weapon_change_y_hide; if (cint[4] < 0) cint[0] = 0; else cint[0] = cint[4]; if (cint[3] < 0) cint[1] = -1; else cint[1] = cint[3] - 1; cint[5] = iw->guns.t_rect[iw->guns.t].w; cint[6] = iw->guns.t_rect[iw->guns.t].h; cint[2] = cint[5] + cint[3]; if (cint[2] > WINDOW_W) cint[2] = WINDOW_W; cint[7] = iw->t_weap[iw->guns.t]->w; cint[8] = iw->t_weap[iw->guns.t]->h; cint[9] = iw->t_weap[iw->guns.t]->bpp; cint[10] = iw->t_weap[iw->guns.t]->pitch; cint[12] = WINDOW_W; *to_i = cint[4] + cint[6]; } void draw_gun_kernel(t_sdl *iw) { int cint[13]; int to_i; size_t global_item_size; size_t local_item_size; draw_gun_kernel2(iw, cint, &to_i); if (iw->sectors[iw->d.cs].light == 0 || iw->sectors[iw->d.cs].light->t != 18) cint[11] = 1; else cint[11] = 0; if (to_i > WINDOW_H) to_i = WINDOW_H; if (to_i <= cint[0]) return ; iw->k.ret = clEnqueueWriteBuffer(iw->k.command_queue, iw->k.m_cint, CL_TRUE, 0, 13 * sizeof(int), cint, 0, NULL, NULL); iw->k.ret = clSetKernelArg(iw->k.kernel8, 1, sizeof(cl_mem), (void *)&iw->k.m_t_weap[iw->guns.t]); global_item_size = to_i - cint[0]; local_item_size = 1; iw->k.ret = clEnqueueNDRangeKernel(iw->k.command_queue, iw->k.kernel8, 1, NULL, &global_item_size, &local_item_size, 0, NULL, NULL); clFlush(iw->k.command_queue); clFinish(iw->k.command_queue); } <|start_filename|>3d/SRC2/guns_mechanic.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* guns_mechanic.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbolilyi <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/05 12:07:13 by dbolilyi #+# #+# */ /* Updated: 2019/03/05 12:07:16 by dbolilyi ### ########.fr */ /* */ /* ************************************************************************** */ #include "../guardians.h" void damaging_enemy(t_sdl *iw, int damage, int max_distance) { if (iw->v.look_portal != 0 && (iw->v.look_portal->glass == 16 || iw->v.look_portal->glass == 17 || iw->v.look_portal->glass == 46) && iw->guns.gun_in_hands != 0) { iw->v.look_portal->glass = -1; iw->walls[iw->v.look_portal->nextsector_wall].glass = -1; } if (iw->v.look_sprite == 0 || iw->v.look_sprite->type != 2 || iw->v.look_sprite->e.status >= 4) return ; if (iw->v.look_sprite->plen < max_distance) iw->v.look_sprite->e.health -= damage; else iw->hud.miss_time = clock(); } void attack2(t_sdl *iw) { if (iw->guns.gun_in_hands == 1 && iw->guns.status == 0 && clock() - iw->guns.prev_update_time > CLKS_P_S / 15) { damaging_enemy(iw, 3, 5000); Mix_PlayChannel(3, iw->sounds.env[6], 0); iw->guns.status = 1; iw->guns.t = 1; iw->guns.prev_update_time = clock(); iw->guns.bullets[1] -= 1; iw->hud.shell = 100 * iw->guns.bullets[1] / iw->guns.max_bullets[1]; } else if (iw->guns.gun_in_hands == 2 && iw->guns.status == 0 && clock() - iw->guns.prev_update_time > CLKS_P_S / 5) { iw->guns.status = 1; iw->guns.t = 8; iw->guns.prev_update_time = clock(); iw->guns.bullets[2] -= 1; iw->hud.shell = 100 * iw->guns.bullets[2] / iw->guns.max_bullets[2]; } } void attack(t_sdl *iw) { if (iw->guns.gun_in_hands == 0 && iw->guns.status == 0 && clock() - iw->guns.prev_update_time > CLKS_P_S / 15) { damaging_enemy(iw, 3, 1000); iw->guns.status = 1; iw->guns.t = 18; iw->guns.prev_update_time = clock(); iw->guns.bullets[0] -= 1; iw->hud.shell = 100 * iw->guns.bullets[0] / iw->guns.max_bullets[0]; } else attack2(iw); } void reload_gun1(t_sdl *iw) { if (iw->guns.bullets_in_stock[1] < iw->guns.max_bullets[1]) { iw->guns.gun_in_hands = 0; iw->guns.status = 3; } else if (iw->guns.t == 0) { Mix_PlayChannel(3, iw->sounds.env[7], 0); iw->guns.t = 2; } else if (iw->guns.t < 6) iw->guns.t++; else { iw->guns.bullets_in_stock[1] -= iw->guns.max_bullets[1] - iw->guns.bullets[1]; iw->guns.bullets[iw->guns.gun_in_hands] = iw->guns.max_bullets[iw->guns.gun_in_hands]; iw->hud.shell = 100; iw->guns.status = 0; iw->guns.t = 0; iw->v.weapon_change_y_hide = iw->guns.t_rect[iw->guns.t].h / 2; } } void reload_gun2(t_sdl *iw) { if (iw->guns.bullets_in_stock[2] < iw->guns.max_bullets[2]) { iw->guns.gun_in_hands = 0; iw->guns.status = 3; } else if (iw->guns.t == 7 || iw->guns.t == 8 || iw->guns.t == 9) { Mix_PlayChannel(3, iw->sounds.env[8], 0); iw->guns.t = 10; } else if (iw->guns.t < 16) iw->guns.t++; else { iw->guns.bullets_in_stock[2] -= iw->guns.max_bullets[2] - iw->guns.bullets[2]; iw->guns.bullets[iw->guns.gun_in_hands] = iw->guns.max_bullets[iw->guns.gun_in_hands]; iw->hud.shell = 100; iw->guns.status = 0; iw->guns.t = 7; iw->v.weapon_change_y_hide = iw->guns.t_rect[iw->guns.t].h / 2; } } <|start_filename|>3d/SRC3/sprites_calculation2.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* sprites_calculation2.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbolilyi <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/05 17:16:09 by dbolilyi #+# #+# */ /* Updated: 2019/03/05 17:16:10 by dbolilyi ### ########.fr */ /* */ /* ************************************************************************** */ #include "../guardians.h" int find_point(t_save_wall_pairs *tmp, t_sprite *tmp1) { int i; int ax; int ay; int bx; int by; ax = tmp->right->p.x - tmp->left->p.x; ay = tmp->right->p.y - tmp->left->p.y; bx = tmp1->x - tmp->left->p.x; by = tmp1->y - tmp->left->p.y; i = ax * by - ay * bx; if (i > 0) return (0); else return (1); } void calculate_sprites_once2(t_sdl *iw, t_sprite *tmp1) { float lang; float rang; lang = get_vectors_angle(iw->d.left_point.x - (float)iw->p.x, iw->d.left_point.y - (float)iw->p.y, (float)(tmp1->x - iw->p.x), (float)(tmp1->y - iw->p.y)); rang = get_vectors_angle(iw->d.right_point.x - (float)iw->p.x, iw->d.right_point.y - (float)iw->p.y, (float)(tmp1->x - iw->p.x), (float)(tmp1->y - iw->p.y)); tmp1->x_s = (int)(lang * (float)WINDOW_W / (2.0f * iw->v.angle)); if (rang > 2.0f * iw->v.angle) tmp1->x_s = -tmp1->x_s; tmp1->plen = sqrtf(powf((float)(iw->p.x - tmp1->x), 2.0f) + powf((float)(iw->p.y - tmp1->y), 2.0f)) + 1.0f; tmp1->pplen = fabsf(iw->d.screen.a * (float)tmp1->x + iw->d.screen.b * (float)tmp1->y + iw->d.screen.c) / sqrtf(iw->d.screen.a * iw->d.screen.a + iw->d.screen.b * iw->d.screen.b) + 1.0f; if (tmp1->pplen / tmp1->plen >= 0.5f) tmp1->spritewidth = (int)(fabsf((float)(WINDOW_W * tmp1->t->w) / tmp1->pplen) * tmp1->scale); else tmp1->spritewidth = (int)(fabsf((float)(WINDOW_W * tmp1->t->w) / tmp1->plen) * tmp1->scale); tmp1->sx = tmp1->x_s - tmp1->spritewidth; } void calculate_sprites_once(t_sdl *iw) { t_sprite *tmp1; tmp1 = *iw->sprite; while (tmp1 != 0) { if (!iw->sectors[tmp1->num_sec].visited || tmp1->draweble == 1) { tmp1 = tmp1->next; continue; } calculate_sprites_once2(iw, tmp1); tmp1->ex = tmp1->x_s + tmp1->spritewidth; if (!(tmp1->sx > iw->d.screen_right || tmp1->ex < iw->d.screen_left)) tmp1->draweble = 1; tmp1 = tmp1->next; } } <|start_filename|>editor/player.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* player.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ddehtyar <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/02/20 13:34:53 by ddehtyar #+# #+# */ /* Updated: 2019/02/20 13:34:54 by ddehtyar ### ########.fr */ /* */ /* ************************************************************************** */ #include "doom_nuken.h" void blouk_player(t_doom *den) { char *cmp; SDL_Color color_text; clean_string(den); color_text.r = 255; color_text.g = 0; color_text.b = 0; cmp = "please put a player\n"; den->TTF_TextSolid = TTF_RenderText_Blended_Wrapped(den->font, cmp, color_text, 200); den->rect.x = 1770; den->rect.y = 380; den->rect.h = 50; den->rect.w = 30; SDL_BlitSurface(den->TTF_TextSolid, NULL, den->bmp, &den->rect); SDL_FreeSurface(den->TTF_TextSolid); SDL_UpdateWindowSurface(den->window); } void player(t_doom *den) { den->cursor = SDL_CreateColorCursor(den->icon[7], 0, 0); SDL_SetCursor(den->cursor); den->blockwall = 1; } void rotate_image_help(t_doom *den, t_rotate *rot) { rot->hwd = den->player.x * XSKAPE; rot->hhd = den->player.y * YSKAPE; rot->hws = den->icon[9]->w / 2; rot->hhs = den->icon[9]->h / 2; rot->a = den->angle / 180.0 * M_PI; rot->r = sqrt(rot->hws * rot->hws + rot->hhs * rot->hhs); rot->b = atan2(1.0 * rot->hhs, rot->hws); rot->x = -1 - rot->hwd; } void rotate_image(t_doom *den) { t_rotate rot; rotate_image_help(den, &rot); if (den->player.x * XSKAPE < den->border && den->player.y * YSKAPE < WIDTH && den->player.x * XSKAPE > 0 && den->player.y * YSKAPE > 0) { while (++rot.x < rot.hwd) { rot.y = -1 - rot.hhd; while (++rot.y < rot.hhd) { rot.i = rot.x * cos(rot.a) - rot.y * sin(rot.a) + rot.r * cos(rot.b); rot.j = rot.x * sin(rot.a) + rot.y * cos(rot.a) + rot.r * sin(rot.b); if (rot.i < den->icon[9]->w && rot.i >= 0 && rot.j < den->icon[9]->h && rot.j >= 0) set_pixel(den->bmp, rot.x + rot.hwd, rot.y + rot.hhd, get_pixel2(den->icon[9], rot.i, rot.j)); } } } } void change_way(t_doom *den, int i, t_col *vec) { if (i == 1) { den->angle -= 10; if (den->angle < 0) den->angle = 360; den->player.introt += 10; if (den->player.introt > 359) den->player.introt = 0; } retry_write(den, vec); } <|start_filename|>3d/SRC/checkpoints.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* checkpoints.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbolilyi <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/02/28 15:37:25 by dbolilyi #+# #+# */ /* Updated: 2019/02/28 15:41:39 by dbolilyi ### ########.fr */ /* */ /* ************************************************************************** */ #include "../guardians.h" void draw_input_on_screen(t_sdl *iw, t_keyb_inp *ki) { int i; int to_i; int start_j; int to_j; int j; set_pixel2(iw->sur, 0, 0, 0xAAAAAA); i = WINDOW_W / 2 - INPUT_LINE_LEN - 1; to_i = WINDOW_W / 2 + INPUT_LINE_LEN; start_j = WINDOW_H / 2 - 16 - 1; to_j = WINDOW_H / 2 + 16; while (++i < to_i) { j = start_j; while (++j < to_j) set_pixel2(iw->sur, i, j, 0xCCCCCC); } ki->s[ki->s_len] = '\0'; draw_text_blue(iw, ki->s, WINDOW_W / 2 - INPUT_LINE_LEN + 12, WINDOW_H / 2 - 14); SDL_UpdateWindowSurface(iw->win); } void input_loop_keydown(t_sdl *iw, t_input_loop *d, SDL_Event *e) { if (e->key.keysym.scancode == 41) exit_x(iw); else if (e->key.keysym.scancode >= 4 && e->key.keysym.scancode <= 29 && d->ki->s_len < INPUT_STRING_LEN) { if (d->shift == 0) d->ki->s[d->ki->s_len++] = d->alphabet[e->key.keysym.scancode - 4]; else d->ki->s[d->ki->s_len++] = ft_toupper( d->alphabet[e->key.keysym.scancode - 4]); draw_input_on_screen(iw, d->ki); } else if (e->key.keysym.scancode == 44) { d->ki->s[d->ki->s_len++] = ' '; draw_input_on_screen(iw, d->ki); } else if (e->key.keysym.scancode == 42) { d->ki->s_len -= ((d->ki->s_len > 0) ? 1 : 0); draw_input_on_screen(iw, d->ki); } } t_keyb_inp *input_loop(t_sdl *iw) { t_input_loop d; SDL_Event e; d.shift = 0; d.alphabet = ft_strdup("abcdefghijklmnopqrstuvwxyz"); d.ki = (t_keyb_inp *)malloc(sizeof(t_keyb_inp)); d.ki->s_len = 0; draw_input_on_screen(iw, d.ki); d.quit = 0; while (!d.quit) while (SDL_PollEvent(&e) != 0) if (e.type == SDL_KEYDOWN) { if (e.key.keysym.scancode == 225) d.shift = 1; else if (e.key.keysym.scancode == 40) d.quit = 1; else input_loop_keydown(iw, &d, &e); } else if (e.type == SDL_KEYUP && e.key.keysym.scancode == 225) d.shift = 0; free(d.alphabet); return (d.ki); } void add_checkpoint(t_sdl *iw, t_sprite *s) { t_keyb_inp *ki; ki = input_loop(iw); ki->sprite = s; ki->next = iw->checkpoints; iw->checkpoints = ki; } void draw_checkpoint_text(t_sdl *iw) { SDL_Rect rect; SDL_Surface *stext; SDL_Color col; if (!iw->v.last_to_write) return ; rect.x = WINDOW_W - 400; rect.y = 230; col.a = 0; col.r = 0; col.g = 255; col.b = 255; rect.w = 0; rect.h = 0; iw->v.last_to_write->s[iw->v.last_to_write->s_len] = '\0'; stext = TTF_RenderText_Solid(iw->arial_font, iw->v.last_to_write->s, col); SDL_BlitSurface(stext, NULL, iw->sur, &rect); SDL_FreeSurface(stext); } <|start_filename|>3d/SRC3/draw_inclined_wall_floor_ceil2.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* draw_inclined_wall_floor_ceil2.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbolilyi <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/05 17:08:28 by dbolilyi #+# #+# */ /* Updated: 2019/03/05 17:08:29 by dbolilyi ### ########.fr */ /* */ /* ************************************************************************** */ #include "../guardians.h" void draw_inclined_wall_floor_ceil_tex1(t_sdl *iw, t_save_wall *left, t_save_wall *right, t_draw_wall_floor_ceil_tex *d) { d->lv.x = (float)(left->p.x - iw->p.x); d->lv.y = (float)(left->p.y - iw->p.y); d->rv.x = (float)(right->p.x - iw->p.x); d->rv.y = (float)(right->p.y - iw->p.y); d->ang = acosf((d->lv.x * d->rv.x + d->lv.y * d->rv.y) / (sqrtf(d->lv.x * d->lv.x + d->lv.y * d->lv.y) * sqrtf(d->rv.x * d->rv.x + d->rv.y * d->rv.y))); d->dang = d->ang / (float)(right->x - left->x + 1); d->ang = 0.0f; d->rv.x = (float)(-right->p.x + left->p.x); d->rv.y = (float)(-right->p.y + left->p.y); d->sing = G180 - acosf((d->lv.x * d->rv.x + d->lv.y * d->rv.y) / (sqrtf(d->lv.x * d->lv.x + d->lv.y * d->lv.y) * sqrtf(d->rv.x * d->rv.x + d->rv.y * d->rv.y))); d->lenpl = sqrtf(powf(iw->p.x - left->p.x, 2.0f) + powf(iw->p.y - left->p.y, 2.0f)); d->len_lr = sqrtf(powf(left->p.x - right->p.x, 2.0f) + powf(left->p.y - right->p.y, 2.0f)); d->zudiff = (right->zu - left->zu) / d->len_lr; d->zddiff = (right->zd - left->zd) / d->len_lr; d->rv.x = (float)(right->p.x - left->p.x) / d->len_lr; d->rv.y = (float)(right->p.y - left->p.y) / d->len_lr; d->zu = get_ceil_z(iw, iw->p.x, iw->p.y); d->zd = get_floor_z(iw, iw->p.x, iw->p.y); d->frpl = (float)(d->zu - d->zd) / (float)(iw->p.z - d->zd); } void draw_inclined_wall_floor_ceil_tex3(t_sdl *iw, t_save_wall *left, t_draw_wall_floor_ceil_tex *d) { d->k = (float)(iw->d.wallBot[d->j] - iw->d.wallTop[d->j]) + d->frpl * (float)(d->i + 1 - iw->d.wallBot[d->j]); while (++d->i < iw->d.bottom[left->x + d->j]) { d->weight = d->wall_dist * d->frcoef / d->k; d->k += d->frpl; d->floor.x = d->weight * d->r.x + (1.0f - d->weight) * d->px; d->floor.y = d->weight * d->r.y + (1.0f - d->weight) * d->py; d->frcoef = (get_ceil_z(iw, d->floor.x * 1000.0f, d->floor.y * 1000.0f) - get_floor_z(iw, d->floor.x * 1000.0f, d->floor.y * 1000.0f) + d->frcoef) / 2.0f; set_pixel2(iw->sur, left->x + d->j, d->i, get_light_color(get_pixel(iw->t[iw->sectors[iw->d.cs].fr.t], ((d->floor.x < 0) ? (((int)(d->floor.x * (float)iw->t[iw->sectors[iw->d.cs]. fr.t]->w) % iw->t[iw->sectors[iw->d.cs].fr.t]->w) + iw->t[iw->sectors[iw-> d.cs].fr.t]->w - 1) : ((int)(d->floor.x * (float)iw->t[iw->sectors[iw->d. cs].fr.t]->w) % iw->t[iw->sectors[iw->d.cs].fr.t]->w)), ((d->floor.y < 0) ? (((int)(d->floor.y * (float)iw->t[iw->sectors[iw->d.cs].fr.t]->h) % iw-> t[iw->sectors[iw->d.cs].fr.t]->h) + iw->t[iw->sectors[iw->d.cs].fr.t]->h - 1) : ((int)(d->floor.y * (float)iw->t[iw->sectors[iw->d.cs].fr.t]->h) % iw->t[iw->sectors[iw->d.cs].fr.t]->h))), iw->sectors[iw->d.cs].light)); } iw->d.bottom[left->x + d->j] = iw->d.wallBot[d->j]; } <|start_filename|>3d/SRC/mouse_left_up2.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* mouse_left_up2.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbolilyi <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/05 15:28:24 by dbolilyi #+# #+# */ /* Updated: 2019/03/05 15:28:25 by dbolilyi ### ########.fr */ /* */ /* ************************************************************************** */ #include "../guardians.h" void mouse_buttonleft_up1_12_1(int x, t_sdl *iw) { if (x < WINDOW_W - 245) { do_wall_animation_step_dx(iw, iw->v.wall_anim, -iw->v.wall_anim->dx); do_wall_animation_step_dy(iw, iw->v.wall_anim, -iw->v.wall_anim->dy); iw->v.wall_anim->next = iw->wall_animations; iw->v.submenu_mode = 0; draw_submenu(iw); iw->v.wall_anim->prev_clock = clock(); iw->wall_animations = iw->v.wall_anim; iw->v.wall_anim = 0; } else if (x < WINDOW_W - 200) exit_editing_wall_animation(iw); } void mouse_buttonleft_up1_12(int x, t_sdl *iw) { if (x < WINDOW_W - 320) { iw->v.wall_anim->speed += ((iw->v.wall_anim->speed < 9) ? 1 : 0); draw_submenu(iw); } else if (x < WINDOW_W - 295) { iw->v.wall_anim->speed -= ((iw->v.wall_anim->speed > 1) ? 1 : 0); draw_submenu(iw); } else mouse_buttonleft_up1_12_1(x, iw); } void mouse_buttonleft_up1_11(int x, t_sdl *iw) { if (iw->v.submenu_mode == 8 && x > WINDOW_W - 450) { if (x < WINDOW_W - 390) { iw->v.wall_anim->dy += 100; do_wall_animation_step_dy(iw, iw->v.wall_anim, 100); } else if (x < WINDOW_W - 330) { iw->v.wall_anim->dy -= 100; do_wall_animation_step_dy(iw, iw->v.wall_anim, -100); } else if (x < WINDOW_W - 280) { iw->v.submenu_mode = 9; draw_submenu(iw); } else if (x < WINDOW_W - 220) exit_editing_wall_animation(iw); } else if (iw->v.submenu_mode == 9 && x > WINDOW_W - 340) mouse_buttonleft_up1_12(x, iw); } void mouse_buttonleft_up1_10(int x, t_sdl *iw) { if (iw->v.submenu_mode == 7 && x > WINDOW_W - 450) { if (x < WINDOW_W - 390) { iw->v.wall_anim->dx += 100; do_wall_animation_step_dx(iw, iw->v.wall_anim, 100); } else if (x < WINDOW_W - 330) { iw->v.wall_anim->dx -= 100; do_wall_animation_step_dx(iw, iw->v.wall_anim, -100); } else if (x < WINDOW_W - 280) { iw->v.submenu_mode = 8; draw_submenu(iw); } else if (x < WINDOW_W - 220) exit_editing_wall_animation(iw); } else mouse_buttonleft_up1_11(x, iw); } void mouse_buttonleft_up1_9(int x, t_sdl *iw) { if (iw->v.submenu_mode == 6 && x > WINDOW_W - 450) { if (x < WINDOW_W - 380) { iw->v.wall_anim->priority = 0; iw->v.submenu_mode = 7; draw_submenu(iw); } else if (x < WINDOW_W - 300) { iw->v.wall_anim->priority = 1; iw->v.submenu_mode = 7; draw_submenu(iw); } else if (x < WINDOW_W - 225) exit_editing_wall_animation(iw); } else mouse_buttonleft_up1_10(x, iw); } <|start_filename|>3d/SRC3/draw_inclined_floor_ceil.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* draw_inclined_floor_ceil.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbolilyi <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/05 13:03:10 by dbolilyi #+# #+# */ /* Updated: 2019/03/05 13:03:11 by dbolilyi ### ########.fr */ /* */ /* ************************************************************************** */ #include "../guardians.h" void draw_inclined_floor_ceil_tex5_1(t_sdl *iw, t_save_wall *left, t_draw_wall_floor_ceil_tex *d) { d->k = (float)(iw->d.wallBot[d->j] - iw->d.wallTop[d->j]) + d->clpl * (float)(iw->d.wallTop[d->j] - d->i + 1); while (--d->i >= iw->d.top[left->x + d->j]) { d->weight = d->wall_dist * d->clcoef / d->k; d->k += d->clpl; d->floor.x = d->weight * d->r.x + (1.0f - d->weight) * d->px; d->floor.y = d->weight * d->r.y + (1.0f - d->weight) * d->py; d->clcoef = (get_ceil_z(iw, d->floor.x * 1000.0f, d->floor.y * 1000.0f) - get_floor_z(iw, d->floor.x * 1000.0f, d->floor.y * 1000.0f) + d->clcoef) / 2.0f; set_pixel2(iw->sur, left->x + d->j, d->i, get_light_color(get_pixel(iw->t[iw->sectors[iw->d.cs].cl.t], ((d->floor.x < 0) ? (((int)(d->floor.x * (float)iw->t[iw->sectors[iw->d.cs] .cl.t]->w) % iw->t[iw->sectors[iw->d.cs].cl.t]->w) + iw->t[iw->sectors[iw-> d.cs].cl.t]->w - 1) : ((int)(d->floor.x * (float)iw->t[iw->sectors[iw->d. cs].cl.t]->w) % iw->t[iw->sectors[iw->d.cs].cl.t]->w)), ((d->floor.y < 0) ? (((int)(d->floor.y * (float)iw->t[iw->sectors[iw->d.cs].cl.t]->h) % iw-> t[iw->sectors[iw->d.cs].cl.t]->h) + iw->t[iw->sectors[iw->d.cs].cl.t]->h - 1) : ((int)(d->floor.y * (float)iw->t[iw->sectors[iw->d.cs].cl.t]->h) % iw->t[iw->sectors[iw->d.cs].cl.t]->h))), iw->sectors[iw->d.cs].light)); } iw->d.top[left->x + d->j] = iw->d.wallTop[d->j]; } void draw_inclined_floor_ceil_tex5_2(t_sdl *iw, t_save_wall *left, t_draw_wall_floor_ceil_tex *d) { if (iw->d.wallTop[d->j] < iw->d.bottom[left->x + d->j]) d->i = iw->d.wallTop[d->j] + 1; else d->i = iw->d.bottom[left->x + d->j] + 1; } void draw_inclined_floor_ceil_tex5(t_sdl *iw, t_save_wall *left, t_draw_wall_floor_ceil_tex *d) { if (!(iw->d.wallTop[d->j] > iw->d.top[left->x + d->j])) return ; if (iw->sectors[iw->d.cs].cl.t >= 0) { draw_inclined_floor_ceil_tex5_2(iw, left, d); draw_inclined_floor_ceil_tex5_1(iw, left, d); } else { d->sky_y = -iw->p.rotup + 2 * WINDOW_H; d->sky_y = (d->sky_y * (iw->t[iw->l.skybox]->h)) / (4 * WINDOW_H); d->i = iw->d.top[left->x + d->j] - 1; d->sky_y += d->dy * iw->d.top[left->x + d->j]; if (d->sky_x > iw->t[iw->l.skybox]->w) d->sky_x = d->sky_x - iw->t[iw->l.skybox]->w; while (++d->i < iw->d.wallTop[d->j] && d->i < iw->d.bottom[left->x + d->j]) { set_pixel2(iw->sur, d->j + left->x, d->i, get_pixel(iw->t[iw->l.skybox], (int)d->sky_x, (int)d->sky_y)); d->sky_y += d->dy; } } } void draw_inclined_floor_ceil_tex6(t_sdl *iw, t_save_wall *left, t_draw_wall_floor_ceil_tex *d) { draw_inclined_floor_ceil_tex5(iw, left, d); if (iw->sectors[iw->d.cs].cl.t < 0) d->sky_x += d->dx; d->ang += d->dang; } void draw_inclined_floor_ceil_tex(t_sdl *iw, t_save_wall *left, t_save_wall *right, int len) { t_draw_wall_floor_ceil_tex d; draw_inclined_floor_ceil_tex1(iw, left, right, &d); draw_inclined_floor_ceil_tex2(iw, left, &d); d.j = -1; while (++d.j < len) { if (iw->d.top[left->x + d.j] >= iw->d.bottom[left->x + d.j]) { d.ang += d.dang; if (iw->sectors[iw->d.cs].cl.t < 0) d.sky_x += d.dx; continue; } draw_inclined_floor_ceil_tex3(iw, left, &d); if (iw->d.wallBot[d.j] < iw->d.bottom[left->x + d.j]) { if (iw->d.wallBot[d.j] < iw->d.top[left->x + d.j]) d.i = iw->d.top[left->x + d.j] - 1; else d.i = iw->d.wallBot[d.j] - 1; draw_inclined_floor_ceil_tex4(iw, left, &d); } draw_inclined_floor_ceil_tex6(iw, left, &d); } } <|start_filename|>3d/SRC3/get_kernel_mem.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* get_kernel_mem.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbolilyi <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/05 13:04:35 by dbolilyi #+# #+# */ /* Updated: 2019/03/05 13:04:35 by dbolilyi ### ########.fr */ /* */ /* ************************************************************************** */ #include "../guardians.h" void get_kernel_mem4(t_sdl *iw) { iw->k.m_cfloat = clCreateBuffer(iw->k.context, CL_MEM_READ_ONLY, 19 * sizeof(float), NULL, &iw->k.ret); iw->k.m_top_betw = clCreateBuffer(iw->k.context, CL_MEM_READ_ONLY, (WINDOW_W + 1) * sizeof(int), NULL, &iw->k.ret); iw->k.m_bot_betw = clCreateBuffer(iw->k.context, CL_MEM_READ_ONLY, (WINDOW_W + 1) * sizeof(int), NULL, &iw->k.ret); iw->k.m_save_top = clCreateBuffer(iw->k.context, CL_MEM_READ_WRITE, (WINDOW_W + 1) * sizeof(int), NULL, &iw->k.ret); iw->k.m_save_bottom = clCreateBuffer(iw->k.context, CL_MEM_READ_WRITE, (WINDOW_W + 1) * sizeof(int), NULL, &iw->k.ret); iw->k.m_save_top2 = clCreateBuffer(iw->k.context, CL_MEM_READ_WRITE, (WINDOW_W + 1) * sizeof(int), NULL, &iw->k.ret); iw->k.m_save_bottom2 = clCreateBuffer(iw->k.context, CL_MEM_READ_WRITE, (WINDOW_W + 1) * sizeof(int), NULL, &iw->k.ret); iw->k.m_save_top3 = clCreateBuffer(iw->k.context, CL_MEM_READ_WRITE, (WINDOW_W + 1) * sizeof(int), NULL, &iw->k.ret); iw->k.m_save_bottom3 = clCreateBuffer(iw->k.context, CL_MEM_READ_WRITE, (WINDOW_W + 1) * sizeof(int), NULL, &iw->k.ret); } void get_kernel_mem3(t_sdl *iw) { int i; i = -1; while (++i < WEAPONS_TEXTURES_COUNT) { iw->k.m_t_weap[i] = clCreateBuffer(iw->k.context, CL_MEM_READ_ONLY, iw->t_weap[i]->pitch * iw->t_weap[i]->h, NULL, &iw->k.ret); clEnqueueWriteBuffer(iw->k.command_queue, iw->k.m_t_weap[i], CL_TRUE, 0, iw->t_weap[i]->pitch * iw->t_weap[i]->h, iw->t_weap[i]->pixels, 0, NULL, NULL); } iw->k.m_top = clCreateBuffer(iw->k.context, CL_MEM_READ_WRITE, (WINDOW_W + 1) * sizeof(int), NULL, &iw->k.ret); iw->k.m_bottom = clCreateBuffer(iw->k.context, CL_MEM_READ_WRITE, (WINDOW_W + 1) * sizeof(int), NULL, &iw->k.ret); iw->k.m_sur = clCreateBuffer(iw->k.context, CL_MEM_WRITE_ONLY, (WINDOW_W + 1) * (WINDOW_H + 1) * sizeof(int), NULL, &iw->k.ret); iw->k.m_wallTop = clCreateBuffer(iw->k.context, CL_MEM_READ_ONLY, (WINDOW_W + 1) * sizeof(int), NULL, &iw->k.ret); iw->k.m_wallBot = clCreateBuffer(iw->k.context, CL_MEM_READ_ONLY, (WINDOW_W + 1) * sizeof(int), NULL, &iw->k.ret); iw->k.m_cint = clCreateBuffer(iw->k.context, CL_MEM_READ_ONLY, 26 * sizeof(int), NULL, &iw->k.ret); get_kernel_mem4(iw); } void get_kernel_mem2(t_sdl *iw) { int i; i = -1; while (++i < ENEMIES_TEXTURES_COUNT) { iw->k.m_t_enemies[i] = clCreateBuffer(iw->k.context, CL_MEM_READ_ONLY, iw->t_enemies[i]->pitch * iw->t_enemies[i]->h, NULL, &iw->k.ret); clEnqueueWriteBuffer(iw->k.command_queue, iw->k.m_t_enemies[i], CL_TRUE, 0, iw->t_enemies[i]->pitch * iw->t_enemies[i]->h, iw->t_enemies[i]->pixels, 0, NULL, NULL); } i = -1; while (++i < PICK_UP_TEXTURES_COUNT) { iw->k.m_t_pickup[i] = clCreateBuffer(iw->k.context, CL_MEM_READ_ONLY, iw->t_pickup[i]->pitch * iw->t_pickup[i]->h, NULL, &iw->k.ret); clEnqueueWriteBuffer(iw->k.command_queue, iw->k.m_t_pickup[i], CL_TRUE, 0, iw->t_pickup[i]->pitch * iw->t_pickup[i]->h, iw->t_pickup[i]->pixels, 0, NULL, NULL); } get_kernel_mem3(iw); } void get_kernel_mem(t_sdl *iw) { int i; i = -1; while (++i < TEXTURES_COUNT) { iw->k.m_t[i] = clCreateBuffer(iw->k.context, CL_MEM_READ_ONLY, iw->t[i]->pitch * iw->t[i]->h, NULL, &iw->k.ret); clEnqueueWriteBuffer(iw->k.command_queue, iw->k.m_t[i], CL_TRUE, 0, iw->t[i]->pitch * iw->t[i]->h, iw->t[i]->pixels, 0, NULL, NULL); } i = -1; while (++i < DECOR_TEXTURES_COUNT) { iw->k.m_t_decor[i] = clCreateBuffer(iw->k.context, CL_MEM_READ_ONLY, iw->t_decor[i]->pitch * iw->t_decor[i]->h, NULL, &iw->k.ret); clEnqueueWriteBuffer(iw->k.command_queue, iw->k.m_t_decor[i], CL_TRUE, 0, iw->t_decor[i]->pitch * iw->t_decor[i]->h, iw->t_decor[i]->pixels, 0, NULL, NULL); } get_kernel_mem2(iw); } <|start_filename|>3d/SRC3/wall_pairs_sort.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* wall_pairs_sort.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbolilyi <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/05 13:06:40 by dbolilyi #+# #+# */ /* Updated: 2019/03/05 13:06:42 by dbolilyi ### ########.fr */ /* */ /* ************************************************************************** */ #include "../guardians.h" void new_sort_pairs(t_sdl *iw) { t_save_wall_pairs start; t_save_wall_pairs *tmp; t_save_wall_pairs *tmp2; t_save_wall_pairs *after; int i; start.next = iw->d.vwp; tmp = &start; i = 0; while (tmp->next != 0) { i++; if (i > 1000) break ; if ((after = get_closest_between_pair(tmp->next)) != 0) { tmp2 = tmp->next; tmp->next = tmp->next->next; tmp2->next = after->next; after->next = tmp2; } else tmp = tmp->next; } iw->d.vwp = start.next; } void add_pair(t_sdl *iw, t_save_wall *left, t_save_wall *right) { t_save_wall_pairs *tmp; t_save_wall_pairs *tmp2; tmp = (t_save_wall_pairs *)malloc(sizeof(t_save_wall_pairs)); tmp->left = left; tmp->right = right; tmp->next = 0; if (iw->d.vwp == 0) iw->d.vwp = tmp; else { tmp2 = iw->d.vwp; while (tmp2->next != 0) tmp2 = tmp2->next; tmp2->next = tmp; } } t_save_wall_pairs *get_closest_between_pair(t_save_wall_pairs *pair) { t_save_wall_pairs *save; t_save_wall_pairs *tmp; save = 0; tmp = pair->next; while (tmp != 0) { if (tmp != pair) if ((tmp->left->x >= pair->left->x && tmp->left->x < pair->right->x && ((pair->left->wall->x - pair->right->wall->x) * (tmp->left->p.y - pair->right->wall->y) - (pair->left->wall->y - pair->right->wall->y) * (tmp->left->p.x - pair->right->wall->x) > 0)) || (tmp->right->x > pair->left->x && tmp->right->x <= pair->right->x && ((pair->left->wall->x - pair->right->wall->x) * (tmp->right->p.y - pair->right->wall->y) - (pair->left->wall->y - pair->right->wall->y) * (tmp->right->p.x - pair->right->wall->x) > 0))) save = tmp; tmp = tmp->next; } return (save); } void free_pairs(t_sdl *iw) { t_save_wall_pairs *tmp; t_save_wall_pairs *tmp2; tmp = iw->d.vwp; while (tmp != 0) { tmp2 = tmp; tmp = tmp->next; free(tmp2); } iw->d.vwp = 0; } <|start_filename|>editor/sprite.c<|end_filename|> /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* sprite.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ddehtyar <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/02/19 18:59:04 by ddehtyar #+# #+# */ /* Updated: 2019/02/19 18:59:05 by ddehtyar ### ########.fr */ /* */ /* ************************************************************************** */ #include "doom_nuken.h" void delete_sprite(t_doom *den, t_sprite *s) { t_sprite head; t_sprite *tmp; t_sprite *tmp2; head.next = den->sprite; tmp = &head; while (tmp->next) { if (tmp->next == s) { tmp2 = tmp->next; tmp->next = tmp->next->next; free(tmp2); break ; } tmp = tmp->next; } den->sprite = head.next; } void check_finish_sprite(t_doom *den) { t_sprite *tmp; t_sprite *tmp_next; tmp = den->sprite; if (den->find_tmp->sec < den->finish) den->finish -= 1; if (den->find_tmp->sec == den->finish) den->finish = -1; while (tmp) { tmp_next = tmp->next; if (den->find_tmp->sec == tmp->num_sec) delete_sprite(den, tmp); tmp = tmp_next; } tmp = den->sprite; while (tmp) { if (den->find_tmp->sec < tmp->num_sec) tmp->num_sec -= 1; tmp = tmp->next; } } void see_sprite(t_doom *den) { t_sprite *tmp; tmp = den->sprite; while (tmp) { if (tmp->x * XSKAPE < den->border && tmp->x * XSKAPE >= 0) { den->rect.x = (tmp->x * XSKAPE - (den->icon[10]->w / 2)); den->rect.y = (tmp->y * YSKAPE - (den->icon[10]->h / 2)); den->rect.h = 20; den->rect.w = 20; } SDL_BlitSurface(den->icon[10], NULL, den->bmp, &den->rect); tmp = tmp->next; } } void find_sprite(t_doom *den, int x, int y) { t_sprite *tmp; tmp = den->sprite; while (tmp) { if ((x < tmp->x * XSKAPE + 10 && x > tmp->x * XSKAPE - 10) && (y < tmp->y * YSKAPE + 10 && y > tmp->y * YSKAPE - 10)) { den->rect.x = tmp->x * XSKAPE - (den->icon[12]->w / 2); den->rect.y = tmp->y * YSKAPE - (den->icon[12]->h / 2); den->rect.h = 20; den->rect.w = 20; SDL_BlitSurface(den->icon[12], NULL, den->bmp, &den->rect); den->find_sprite = tmp; den->change = 4; break ; } tmp = tmp->next; } } void add_sprite(t_doom *den) { t_sprite *tmp; tmp = (t_sprite *)malloc(sizeof(t_sprite)); tmp->x = den->xy.x; tmp->y = den->xy.y; tmp->num_sec = den->xy.bool_cor; tmp->t_numb = 0; tmp->type = 0; tmp->scale = 1.0f; tmp->e.vis_esp.curr_sector = -1; tmp->e.previous_picture_change = 1; tmp->e.prev_update_time = 1; tmp->fall_time = 1; tmp->taken = 0; tmp->next = den->sprite; den->sprite = tmp; }
LlimaV10/doom-nukem_v2
<|start_filename|>app/src/main/java/com/dualcores/swagpoint/MainActivity.java<|end_filename|> package com.dualcores.swagpoint; import android.graphics.Color; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar); setSupportActionBar(toolbar); toolbar.setTitle(R.string.title); toolbar.setTitleTextColor(Color.WHITE); } }
AppSecAI-TEST/SwagPoints
<|start_filename|>Source/MapboxDataSource/Private/MapboxDataSource.cpp<|end_filename|> #include "MapboxDataSource.h" #include "Modules/ModuleManager.h" #include "IImageWrapper.h" #include "IImageWrapperModule.h" #include "Interfaces/IHttpResponse.h" #include "HttpModule.h" #include "ImageUtils.h" #include "GDALHelpers.h" #include "LandscapeConstraints.h" namespace { float long2tilexf(double lon, int z) { return (lon + 180.0) / 360.0 * (1 << z); } float lat2tileyf(double lat, int z) { double latrad = lat * PI/180.0; return (1.0 - asinh(tan(latrad)) / PI) / 2.0 * (1 << z); } int long2tilex(double lon, int z) { return (int)(floor(long2tilexf(lon, z))); } int lat2tiley(double lat, int z) { return (int)(floor(lat2tileyf(lat, z))); } double tilex2long(int x, int z) { return x / (double)(1 << z) * 360.0 - 180; } double tiley2lat(int y, int z) { double n = PI - 2.0 * PI * y / (double)(1 << z); return 180.0 / PI * atan(0.5 * (exp(n) - exp(-n))); } } const FString UMapboxDataSource::ProjectionWKT = GDALHelpers::WktFromEPSG(3857); void UMapboxDataSource::RetrieveData(FGISDataSourceDelegate InOnSuccess, FGISDataSourceDelegate InOnFailure) { this->OnSuccess = InOnSuccess; this->OnFailure = InOnFailure; this->RequestSectionRGBHeight(this->reqUpperLat, this->reqLeftLon, this->reqLowerLat, this->reqRightLon, this->reqZoom); } bool UMapboxDataSource::ValidateRequest(FString& OutError) { const int minZoom = 0; const int maxZoom = 15; const float minLat = -85.0511f; const float maxLat = 85.0511f; const float minLon = -180.0f; const float maxLon = 180.0f; if (this->reqZoom < minZoom || this->reqZoom > maxZoom) { OutError = FString::Printf(TEXT("Zoom out of valid Range (%d-%d)"), minZoom, maxZoom); return false; } if (this->reqUpperLat < this->reqLowerLat) { OutError = FString(TEXT("Upper Latitude value is lower than Lower Latitude value")); return false; } if (this->reqRightLon < this->reqLeftLon) { OutError = FString(TEXT("Right Longitude value is lower than Left Longitude value")); return false; } if (this->reqUpperLat > maxLat || this->reqLowerLat < minLat) { OutError = FString::Printf(TEXT("Upper or Lower Latitude value out of range (%f-%f)"), minLat, maxLat); return false; } if (this->reqRightLon > maxLon || this->reqLeftLon < minLon) { OutError = FString::Printf(TEXT("Upper or Lower Latitude value out of range (%f-%f)"), minLon, maxLon); return false; } return true; } void UMapboxDataSource::RequestSectionRGBHeight(float upperLat, float leftLon, float lowerLat, float rightLon, int zoom) { this->hasReqFailed = false; // Check that request values are valid FString ValidationError; if (!this->ValidateRequest(ValidationError)) { this->OnFailure.Broadcast(ValidationError, FGISData()); return; } const int dimx = 256; const int dimy = 256; // Find tile indice bounds for given coordinates and zoom float minxf = long2tilexf(leftLon, zoom); float minyf = lat2tileyf(upperLat, zoom); float maxxf = long2tilexf(rightLon, zoom); float maxyf = lat2tileyf(lowerLat, zoom); ////////// Make requests produce square results for now ///////////// minxf = (int)(floor(minxf)); minyf = (int)(floor(minyf)); maxxf = (int)(floor(maxxf)); maxyf = (int)(floor(maxyf)); // Expand either x or y dimension to produce square result bool isXLarger = (maxxf - minxf) >= (maxyf - minyf); float largerSize = isXLarger ? (maxxf - minxf) : (maxyf - minyf); float& smallerMin = isXLarger ? minyf : minxf; float& smallerMax = isXLarger ? maxyf : maxxf; while (largerSize > (smallerMax - smallerMin)) { if (((int)(smallerMax - smallerMin)) % 2) { smallerMin--; } else { smallerMax++; } } ////////// Make requests produce square results for now ///////////// int minx = (int)(floor(minxf)); int miny = (int)(floor(minyf)); int maxx = (int)(floor(maxxf)); int maxy = (int)(floor(maxyf)); // /v4/{tileset_id}/{zoom}/{x}/{y}{@2x}.{format} // https://api.mapbox.com/v4/mapbox.terrain-rgb/{z}/{x}/{y}.pngraw?access_token=YOUR_MAPBOX_ACCESS_TOKEN // https://api.mapbox.com/v4/mapbox.satellite/1/0/[email protected]?access_token=YOUR_MAPBOX_ACCESS_TOKEN // Set up parts of RGB and Height requests FString BaseURL = TEXT("https://api.mapbox.com/v4/"); FString TextureTilesetId = TEXT("mapbox.satellite"); FString TextureFormat = TEXT(".jpg90"); FString HeightTilesetId = TEXT("mapbox.terrain-rgb"); FString HeightFormat = TEXT(".pngraw"); FString ApiKey = this->reqAPIKey; // Set some useful variables for use by individual requests UMapboxDataSource* RequestTask = this; RequestTask->OffsetX = minx; RequestTask->OffsetY = miny; RequestTask->MaxX = maxx - minx + 1; RequestTask->MaxY = maxy - miny + 1; RequestTask->DimX = dimx * RequestTask->MaxX; RequestTask->DimY = dimy * RequestTask->MaxY; RequestTask->TileDimX = dimx; RequestTask->TileDimY = dimy; RequestTask->Zoom = zoom; // For properly cropped results: // RequestTask->MinU = (minxf - ((float)minx)) / ((float)RequestTask->MaxX); // RequestTask->MaxU = (maxxf - ((float)maxx)) / ((float)RequestTask->MaxX); // RequestTask->MinV = (minyf - ((float)miny)) / ((float)RequestTask->MaxY); // RequestTask->MaxV = (maxyf - ((float)maxy)) / ((float)RequestTask->MaxY); // (We are currently producing square results) // Used for cropping, we aren't cropping the results at the moment so just set UV bounds to (0-1) RequestTask->MinU = 0.0f; RequestTask->MaxU = 1.0f; RequestTask->MinV = 0.0f; RequestTask->MaxV = 1.0f; // RequestTask->NumXHeightPixels = abs(maxxf - minxf) * dimx; // RequestTask->NumYHeightPixels = abs(maxyf - minyf) * dimy; // Set size of output arrays for RGB and height data RequestTask->NumXHeightPixels = RequestTask->DimX; RequestTask->NumYHeightPixels = RequestTask->DimY; // check that number of tiles is smaller than max texture size if (RequestTask->NumXHeightPixels > LandscapeConstraints::MaxRasterSizeX() || RequestTask->NumYHeightPixels > LandscapeConstraints::MaxRasterSizeY()) { FString ErrString = FString::Printf(TEXT("%d x %d tile dims too large please reduce to 64 x 64 by lowering zoom level or reducing area"), (maxx - minx), (maxy - miny)); this->OnFailure.Broadcast(ErrString, FGISData()); return; } RequestTask->RGBData = TArray<FColor>(); RequestTask->RGBData.AddDefaulted(RequestTask->NumXHeightPixels * RequestTask->NumYHeightPixels); RequestTask->HeightData = TArray<float>(); RequestTask->HeightData.AddDefaulted(RequestTask->NumXHeightPixels * RequestTask->NumYHeightPixels); // Iterate over range of tile indices and create RGB and height data requests for each for (int x = minx; x <= maxx; x++) { for (int y = miny; y <= maxy; y++) { FString TextureRequestURL = FString::Printf(TEXT("%s%s/%d/%d/%d%s?access_token=%s"), *BaseURL, *TextureTilesetId, zoom, x, y, *TextureFormat, *ApiKey); FMapboxRequestData TextureReqData = { EMapboxRequestDataType::RGB, x, y }; RequestTask->Start(TextureRequestURL, TextureReqData); FString HeightRequestURL = FString::Printf(TEXT("%s%s/%d/%d/%d%s?access_token=%s"), *BaseURL, *HeightTilesetId, zoom, x, y, *HeightFormat, *ApiKey); FMapboxRequestData HeightReqData = { EMapboxRequestDataType::HEIGHT, x, y }; RequestTask->Start(HeightRequestURL, HeightReqData); } } } void UMapboxDataSource::Start(FString URL, FMapboxRequestData data) { // Create the Http request and add to pending request list TSharedRef<IHttpRequest> HttpRequest = FHttpModule::Get().CreateRequest(); UE_LOG(LogTemp, Log, TEXT("Sent Request: %s"), *URL); HttpRequest->OnProcessRequestComplete().BindUObject(this, &UMapboxDataSource::HandleMapboxRequest, data); HttpRequest->SetURL(URL); HttpRequest->SetVerb(TEXT("GET")); HttpRequest->ProcessRequest(); this->TotalRequests++; } void UMapboxDataSource::HandleMapboxRequest(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FMapboxRequestData data) { RemoveFromRoot(); // Check if the HTTP requests succeeded, enter failure state if any request fails if ( bSucceeded && HttpResponse.IsValid() && HttpResponse->GetContentLength() > 0 ) { IImageWrapperModule& ImageWrapperModule = FModuleManager::LoadModuleChecked<IImageWrapperModule>(FName("ImageWrapper")); TSharedPtr<IImageWrapper> ImageWrappers[3] = { ImageWrapperModule.CreateImageWrapper(EImageFormat::PNG), ImageWrapperModule.CreateImageWrapper(EImageFormat::JPEG), ImageWrapperModule.CreateImageWrapper(EImageFormat::BMP), }; // Iterate of image wrappers until one is valid for the received data for ( auto ImageWrapper : ImageWrappers ) { if ( ImageWrapper.IsValid() && ImageWrapper->SetCompressed(HttpResponse->GetContent().GetData(), HttpResponse->GetContentLength()) ) { // Determine which tile index we are dealing with int TileXIdx = data.RelX - this->OffsetX; int TileYIdx = data.RelY - this->OffsetY; switch (data.DataType) { case EMapboxRequestDataType::RGB: { // Get image data TArray64<uint8> RawData; const ERGBFormat InFormat = ERGBFormat::BGRA; ImageWrapper->GetRaw(InFormat, 8, RawData); // Set up offsets used to calculate correct source and destination indices for cropping int YHeightOffsetMin = this->DimY * this->MinV; int XHeightOffsetMin = this->DimX * this->MinU; int YHeightOffsetMax = ((int)(this->DimY * this->MaxV)) % this->TileDimY; int XHeightOffsetMax = ((int)(this->DimX * this->MaxU)) % this->TileDimX; int TilePixelOffsetX = -XHeightOffsetMin + TileXIdx * this->TileDimX; int TilePixelOffsetY = -YHeightOffsetMin + TileYIdx * this->TileDimY; // Iterate over y indices of source image that we want to read from (ignoring cropped indices) for (int y = TileYIdx ? 0 : YHeightOffsetMin; y < ((TileYIdx + 1 == this->MaxY && YHeightOffsetMax) ? YHeightOffsetMax : this->TileDimY); y++) { // Set y location to start writing to in destination array auto DestPtrIdx = ((int64)(y + TilePixelOffsetY)) * this->NumXHeightPixels + TilePixelOffsetX; FColor* DestPtr = &((FColor*)this->RGBData.GetData())[DestPtrIdx]; // Set y location to start reading from in source image auto SrcPtrIdx = ((int64)(y)) * this->TileDimX + (TileXIdx ? 0 : XHeightOffsetMin); const FColor* SrcPtr = &((FColor*)(RawData.GetData()))[SrcPtrIdx]; // Check that we don't aren't reading out of bounds data from source data if (SrcPtrIdx >= (256 * 256)) { UE_LOG(LogTemp, Error, TEXT("Accessing Height data out of bounds")) } // Check that we don't aren't writing to out of bounds indices in the destination array if (DestPtrIdx >= (this->NumXHeightPixels * this->NumYHeightPixels)) { UE_LOG(LogTemp, Error, TEXT("Writing Height data to out of bounds address")) } // Iterate over x indices of source image that we want to read from (ignoring cropped indices) for (int x = TileXIdx ? 0 : XHeightOffsetMin; x < ((TileXIdx + 1 == this->MaxX && XHeightOffsetMax) ? XHeightOffsetMax : this->TileDimX); x++) { *DestPtr++ = FColor(SrcPtr->R, SrcPtr->G, SrcPtr->B, SrcPtr->A); SrcPtr++; } } break; } case EMapboxRequestDataType::HEIGHT: { // Get image data TArray64<uint8> RawData; const ERGBFormat InFormat = ERGBFormat::BGRA; ImageWrapper->GetRaw(InFormat, 8, RawData); // Set up offsets used to calculate correct source and destination indices for cropping int YHeightOffsetMin = this->DimY * this->MinV; int XHeightOffsetMin = this->DimX * this->MinU; int YHeightOffsetMax = ((int)(this->DimY * this->MaxV)) % this->TileDimY; int XHeightOffsetMax = ((int)(this->DimX * this->MaxU)) % this->TileDimX; int TilePixelOffsetX = -XHeightOffsetMin + TileXIdx * this->TileDimX; int TilePixelOffsetY = -YHeightOffsetMin + TileYIdx * this->TileDimY; // Iterate over y indices of source image that we want to read from (ignoring cropped indices) for (int y = TileYIdx ? 0 : YHeightOffsetMin; y < ((TileYIdx + 1 == this->MaxY && YHeightOffsetMax) ? YHeightOffsetMax : this->TileDimY); y++) { // Set y location to start writing to in destination array auto DestPtrIdx = ((int64)(y + TilePixelOffsetY)) * this->NumXHeightPixels + TilePixelOffsetX; float* DestPtr = &((float*)this->HeightData.GetData())[DestPtrIdx]; // Set y location to start reading from in source image auto SrcPtrIdx = ((int64)(y)) * this->TileDimX + (TileXIdx ? 0 : XHeightOffsetMin); const FColor* SrcPtr = &((FColor*)(RawData.GetData()))[SrcPtrIdx]; // Check that we are not reading out of bounds data from src data if (SrcPtrIdx >= (256 * 256)) { UE_LOG(LogTemp, Error, TEXT("Accessing Height data out of bounds")) } // Check that we are not writing to out of bounds indices in the destination array if (DestPtrIdx >= (this->NumXHeightPixels * this->NumYHeightPixels)) { UE_LOG(LogTemp, Error, TEXT("Writing Height data to out of bounds address")) } // Iterate over x indices of source image that we want to read from (ignoring cropped indices) for (int x = TileXIdx ? 0 : XHeightOffsetMin; x < ((TileXIdx + 1 == this->MaxX && XHeightOffsetMax) ? XHeightOffsetMax : this->TileDimX); x++) { *DestPtr++ = -10000.0f + ((SrcPtr->R * 256 * 256 + SrcPtr->G * 256 + SrcPtr->B) * 0.1f); SrcPtr++; } } break; } default: { break; } } this->CompletedRequests++; UE_LOG(LogTemp, Log, TEXT("Completed Request, total resolved: %d"), this->CompletedRequests); // All requests complete, collate results and broadcast to success delegate if (this->CompletedRequests >= this->TotalRequests || this->bIgnoreMissingTiles) { UE_LOG(LogTemp, Log, TEXT("MAPBOX REQUEST COMPLETE")); FGISData OutData; OutData.HeightBuffer = this->HeightData; OutData.HeightBufferX = this->NumXHeightPixels; OutData.HeightBufferY = this->NumYHeightPixels; OutData.ColorBuffer = TArray<uint8>((uint8*)this->RGBData.GetData(), this->RGBData.Num() * sizeof(FColor)); OutData.ColorBufferX = this->NumXHeightPixels; OutData.ColorBufferY = this->NumYHeightPixels; OutData.ProjectionWKT = UMapboxDataSource::ProjectionWKT; OutData.CornerType = ECornerCoordinateType::LatLon; OutData.UpperLeft = FVector2D(tiley2lat(this->OffsetY, this->Zoom), tilex2long(this->OffsetX, this->Zoom)); OutData.LowerRight = FVector2D(tiley2lat(this->OffsetY+this->MaxY, this->Zoom), tilex2long(this->OffsetX+this->MaxX, this->Zoom)); OutData.PixelFormat = EPixelFormat::PF_B8G8R8A8; this->OnSuccess.Broadcast(FString(), OutData); } return; } } } if (!this->hasReqFailed) { this->hasReqFailed = true; FString FailString = bSucceeded ? FString(TEXT("One or more requests failed: Unable to process image")) : FString(TEXT("One or more requests failed: Web request failed")); this->OnFailure.Broadcast(FailString, FGISData()); } }
TensorWorks/LandscapeGen
<|start_filename|>test/Example/test/revise.jl<|end_filename|> # julia -i -q --project=. revise.jl example using Revise, Jive using Example trigger = function (path) printstyled("changed ", color=:cyan) println(path) revise() runtests(@__DIR__, skip=["revise.jl"]) end watch(trigger, @__DIR__, sources=[pathof(Example)]) trigger("") Base.JLOptions().isinteractive==0 && wait() <|start_filename|>test/test/skip_testsets.jl<|end_filename|> module test_skip_testsets module TestTools export @testset import Test: @testset using Test: Test, AbstractTestSet, DefaultTestSet, Error, Random, testset_forloop, get_testset_depth, get_testset, push_testset, pop_testset, finish, record, _check_testset if VERSION >= v"1.3.0-DEV.565" default_rng = Random.default_rng else GLOBAL_RNG = Random.GLOBAL_RNG end skip_testsets = [] # code from https://github.com/JuliaLang/julia/blob/master/stdlib/Test/src/Test.jl#L1065 macro testset(args...) isempty(args) && error("No arguments to @testset") tests = args[end] # Determine if a single block or for-loop style if !isa(tests,Expr) || (tests.head !== :for && tests.head !== :block) error("Expected begin/end block or for loop as argument to @testset") end if tests.head === :for ex = testset_forloop(args, tests, __source__) else if VERSION >= v"1.8.0-DEV.809" testset_beginend_call = Test.testset_beginend_call else testset_beginend_call = Test.testset_beginend end ex = testset_beginend_call(args, tests, __source__) end desc = first(args) !(desc in skip_testsets) && return ex end end # module TestTools using Test using .TestTools push!(TestTools.skip_testsets, "testset2") @testset "testset1" begin @test true end @testset "testset2" begin @test true end @testset "testset3" begin @test true end end # module test_skip_testsets
wookay/Jive.jl
<|start_filename|>app/src/main/java/com/tim/tsms/transpondsms/model/SenderModel.java<|end_filename|> package com.tim.tsms.transpondsms.model; import com.tim.tsms.transpondsms.R; public class SenderModel { private Long id; private String name; public static final int STATUS_ON = 1; public static final int STATUS_OFF = 0; private int status; public static final int TYPE_DINGDING = 0; public static final int TYPE_EMAIL = 1; public static final int TYPE_MESSAGE = 2; public static final int TYPE_WEB_NOTIFY = 3; public static final int TYPE_QYWX_GROUP_ROBOT = 4; private int type; private String jsonSetting; private long time; public SenderModel() { } public SenderModel(String name, int status, int type, String jsonSetting) { this.name = name; this.status = status == STATUS_ON ? STATUS_ON : STATUS_OFF; this.type = type; this.jsonSetting = jsonSetting; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getStatus() { return status; } public void setStatus(int status) { this.status = status == STATUS_ON ? STATUS_ON : STATUS_OFF; } public int getType() { return type; } public void setType(int type) { this.type = type; } public String getJsonSetting() { return jsonSetting; } public void setJsonSetting(String jsonSetting) { this.jsonSetting = jsonSetting; } public int getImageId() { switch (type) { case (TYPE_DINGDING): return R.mipmap.dingding; case (TYPE_EMAIL): return R.drawable.ic_baseline_email_24; case (TYPE_QYWX_GROUP_ROBOT): return R.mipmap.qywx; default: return R.mipmap.ic_launcher_round; } } public static int getImageId(int type) { switch (type) { case (TYPE_DINGDING): return R.mipmap.dingding; case (TYPE_EMAIL): return R.drawable.ic_baseline_email_24; case (TYPE_QYWX_GROUP_ROBOT): return R.mipmap.qywx; default: return R.mipmap.ic_launcher_round; } } public void setTime(long time) { this.time = time; } public long getTime() { return time; } @Override public String toString() { return "SenderModel{" + "id=" + id + ", name='" + name + '\'' + ", status=" + status + ", type=" + type + ", jsonSetting='" + jsonSetting + '\'' + ", time=" + time + '}'; } } <|start_filename|>app/src/main/java/com/tim/tsms/transpondsms/utils/SettingUtil.java<|end_filename|> package com.tim.tsms.transpondsms.utils; import android.content.Context; import android.content.SharedPreferences; import android.preference.PreferenceManager; import android.util.Log; public class SettingUtil { private static String TAG = "SettingUtil"; static Boolean hasInit=false; private static SharedPreferences sp_setting=null; private static Context context=null; public static void init(Context context1){ synchronized (hasInit){ if(hasInit)return; hasInit=true; context = context1; Log.d(TAG,"init "); sp_setting = PreferenceManager.getDefaultSharedPreferences(context1); } } public static void switchAddExtra(Boolean switchAddExtra){ Log.d(TAG,"switchAddExtra :"+switchAddExtra); sp_setting.edit() .putBoolean(Define.SP_MSG_KEY_SWITCH_ADD_EXTRA,switchAddExtra) .apply(); } public static boolean getSwitchAddExtra(){ return sp_setting.getBoolean(Define.SP_MSG_KEY_SWITCH_ADD_EXTRA,false); } public static void setAddExtraDeviceMark(String addExtraDeviceMark){ Log.d(TAG,"addExtraDeviceMark :"+addExtraDeviceMark); sp_setting.edit() .putString(Define.SP_MSG_KEY_STRING_ADD_EXTRA_DEVICE_MARK,addExtraDeviceMark) .apply(); } public static String getAddExtraDeviceMark(){ return sp_setting.getString(Define.SP_MSG_KEY_STRING_ADD_EXTRA_DEVICE_MARK,"公司红色白皮手机"); } public static void setAddExtraSim1(String sim1){ Log.d(TAG,"sim1 :"+sim1); sp_setting.edit() .putString(Define.SP_MSG_KEY_STRING_ADD_EXTRA_SIM1,sim1) .apply(); } public static String getAddExtraSim1(){ return sp_setting.getString(Define.SP_MSG_KEY_STRING_ADD_EXTRA_SIM1,"人事小姐姐卡"); } public static void setAddExtraSim2(String sim2){ Log.d(TAG,"sim2 :"+sim2); sp_setting.edit() .putString(Define.SP_MSG_KEY_STRING_ADD_EXTRA_SIM2,sim2) .apply(); } public static String getAddExtraSim2(){ return sp_setting.getString(Define.SP_MSG_KEY_STRING_ADD_EXTRA_SIM2,"客服手机卡18888888888"); } public static boolean option_withreboot(){ return sp_setting.getBoolean("option_withreboot",false); } public static boolean using_dingding(){ return sp_setting.getBoolean("option_dingding_on",false); } public static String get_using_dingding_token(){ return sp_setting.getString("option_dingding_token",""); } public static String get_using_dingding_secret(){ return sp_setting.getString("option_dingding_secret",""); } public static boolean using_email(){ return sp_setting.getBoolean("option_email_on",false); } public static void set_send_util_email(String host,String port,String from_add,String psw,String to_add){ Log.d(TAG,"set_send_util_email host:"+host+"port"+port+"from_add"+from_add+"psw"+psw+"to_add"+to_add); //验证 if(host.equals("")||port.equals("")||from_add.equals("")||psw.equals("")||to_add.equals("")){ return; } sp_setting.edit() .putString(Define.SP_MSG_SEND_UTIL_EMAIL_HOST_KEY,host) .putString(Define.SP_MSG_SEND_UTIL_EMAIL_PORT_KEY,port) .putString(Define.SP_MSG_SEND_UTIL_EMAIL_FROMADD_KEY,from_add) .putString(Define.SP_MSG_SEND_UTIL_EMAIL_PSW_KEY,psw) .putString(Define.SP_MSG_SEND_UTIL_EMAIL_TOADD_KEY,to_add) .apply(); } public static String get_send_util_email(String key){ Log.d(TAG,"get_send_util_email key"+key); String defaultstt =""; if(key.equals(Define.SP_MSG_SEND_UTIL_EMAIL_HOST_KEY)) defaultstt = "smtp服务器"; if(key.equals(Define.SP_MSG_SEND_UTIL_EMAIL_PORT_KEY)) defaultstt = "端口"; if(key.equals(Define.SP_MSG_SEND_UTIL_EMAIL_FROMADD_KEY)) defaultstt = "发送邮箱"; if(key.equals(Define.SP_MSG_SEND_UTIL_EMAIL_PSW_KEY)) defaultstt = "密码"; if(key.equals(Define.SP_MSG_SEND_UTIL_EMAIL_TOADD_KEY)) defaultstt = "接收邮箱"; return sp_setting.getString(key,defaultstt); } public static boolean saveMsgHistory(){ return sp_setting.getBoolean("option_save_history_on",false); } } <|start_filename|>app/src/main/java/com/tim/tsms/transpondsms/utils/sender/SenderMailMsg.java<|end_filename|> package com.tim.tsms.transpondsms.utils.sender; import android.os.Bundle; import android.os.Handler; import android.util.Log; import java.util.Date; import java.util.Properties; import javax.mail.Address; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import static com.tim.tsms.transpondsms.SenderActivity.NOTIFY; public class SenderMailMsg { private static String TAG = "SenderMailMsg"; //qq // private static final String HOST = "smtp.qq.com"; // private static final String PORT = "587"; // private static final String FROM_ADD = "<EMAIL>"; //发送方邮箱 // private static final String FROM_PSW = "lfrlpganzjrwbeci";//发送方邮箱授权码 // //163 // private static final String HOST = "smtp.163.com"; // private static final String PORT = "465"; //nossl 25或者ssl465 994 // private static final String FROM_ADD = "<EMAIL>"; // private static final String FROM_PSW = "xx"; public static void sendEmail(final Handler handError, final String host, final String port, final boolean ssl, final String fromemail, final String pwd, final String toAdd, final String title, final String content) { Log.d(TAG, "sendEmail: host:" + host + " port:" + port + " ssl:" + ssl + " fromemail:" + fromemail + " pwd:" + pwd + " toAdd:" + toAdd); new Thread(new Runnable() { @Override public void run() { try { final MailSenderInfo mailInfo = new MailSenderInfo(); mailInfo.setMailServerHost(host); mailInfo.setMailServerPort(port); mailInfo.setValidate(true); mailInfo.setUserName(fromemail); //你的邮箱地址 mailInfo.setPassword(<PASSWORD>);//您的邮箱密码 mailInfo.setFromAddress(fromemail);//和上面username的邮箱地址一致 mailInfo.setToAddress(toAdd); mailInfo.setSubject(title); mailInfo.setContent(content); mailInfo.setSsl(ssl); //这个类主要来发送邮件 // 判断是否需要身份认证 MyAuthenticator authenticator = null; Properties pro = mailInfo.getProperties(); if (mailInfo.isValidate()) { // 如果需要身份认证,则创建一个密码验证器 authenticator = new MyAuthenticator(mailInfo.getUserName(), mailInfo.getPassword()); } // 根据邮件会话属性和密码验证器构造一个发送邮件的session Session sendMailSession = Session.getDefaultInstance(pro, authenticator); try { // 根据session创建一个邮件消息 final Message mailMessage = new MimeMessage(sendMailSession); // 创建邮件发送者地址 Address from = new InternetAddress(mailInfo.getFromAddress()); // 设置邮件消息的发送者 mailMessage.setFrom(from); // 创建邮件的接收者地址,并设置到邮件消息中 Address to = new InternetAddress(mailInfo.getToAddress()); mailMessage.setRecipient(Message.RecipientType.TO, to); // 设置邮件消息的主题 mailMessage.setSubject(mailInfo.getSubject()); // 设置邮件消息发送的时间 mailMessage.setSentDate(new Date()); // 设置邮件消息的主要内容 String mailContent = mailInfo.getContent(); mailMessage.setText(mailContent); // 发送邮件 Transport.send(mailMessage); } catch (MessagingException ex) { ex.printStackTrace(); Log.e(TAG, "error" + ex.getMessage()); if (handError != null) { android.os.Message msg = new android.os.Message(); msg.what = NOTIFY; Bundle bundle = new Bundle(); bundle.putString("DATA", ex.getMessage()); msg.setData(bundle); handError.sendMessage(msg); } } if (handError != null) { android.os.Message msg = new android.os.Message(); msg.what = NOTIFY; Bundle bundle = new Bundle(); bundle.putString("DATA", "发送成功"); msg.setData(bundle); handError.sendMessage(msg); } Log.e(TAG, "sendEmail success");//sms.sendHtmlMail(mailInfo);//发送html格式 } catch (Exception e) { Log.e(TAG, e.getMessage(), e); if (handError != null) { android.os.Message msg = new android.os.Message(); msg.what = NOTIFY; Bundle bundle = new Bundle(); bundle.putString("DATA", e.getMessage()); msg.setData(bundle); handError.sendMessage(msg); } } } }).start(); } } /** * public void sendFileMail(View view) { * <p> * File file = new File(Environment.getExternalStorageDirectory()+File.separator+"test.txt"); * OutputStream os = null; * try { * os = new FileOutputStream(file); * String str = "hello world"; * byte[] data = str.getBytes(); * os.write(data); * } catch (FileNotFoundException e) { * e.printStackTrace(); * } catch (IOException e) { * e.printStackTrace(); * }finally{ * try { * if (os != null)os.close(); * } catch (IOException e) { * } * } * SenderMailMsg.send(file,editText.getText().toString()); * } */ <|start_filename|>app/src/main/java/com/tim/tsms/transpondsms/SenderActivity.java<|end_filename|> package com.tim.tsms.transpondsms; import android.content.DialogInterface; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.Switch; import android.widget.Toast; import com.alibaba.fastjson.JSON; import com.tim.tsms.transpondsms.adapter.SenderAdapter; import com.tim.tsms.transpondsms.model.SenderModel; import com.tim.tsms.transpondsms.model.vo.DingDingSettingVo; import com.tim.tsms.transpondsms.model.vo.EmailSettingVo; import com.tim.tsms.transpondsms.model.vo.QYWXGroupRobotSettingVo; import com.tim.tsms.transpondsms.model.vo.WebNotifySettingVo; import com.tim.tsms.transpondsms.utils.sender.SenderDingdingMsg; import com.tim.tsms.transpondsms.utils.sender.SenderMailMsg; import com.tim.tsms.transpondsms.utils.sender.SenderQyWxGroupRobotMsg; import com.tim.tsms.transpondsms.utils.sender.SenderUtil; import com.tim.tsms.transpondsms.utils.sender.SenderWebNotifyMsg; import com.umeng.analytics.MobclickAgent; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import static com.tim.tsms.transpondsms.model.SenderModel.STATUS_ON; import static com.tim.tsms.transpondsms.model.SenderModel.TYPE_DINGDING; import static com.tim.tsms.transpondsms.model.SenderModel.TYPE_EMAIL; import static com.tim.tsms.transpondsms.model.SenderModel.TYPE_QYWX_GROUP_ROBOT; import static com.tim.tsms.transpondsms.model.SenderModel.TYPE_WEB_NOTIFY; public class SenderActivity extends AppCompatActivity { private String TAG = "SenderActivity"; // 用于存储数据 private List<SenderModel> senderModels = new ArrayList<>(); private SenderAdapter adapter; public static final int NOTIFY = 0x9731993; //消息处理者,创建一个Handler的子类对象,目的是重写Handler的处理消息的方法(handleMessage()) private Handler handler = new Handler(){ @Override public void handleMessage(Message msg) { switch (msg.what){ case NOTIFY: Toast.makeText(SenderActivity.this, msg.getData().getString("DATA"), Toast.LENGTH_LONG).show(); break; } } }; @Override protected void onCreate(Bundle savedInstanceState) { Log.d(TAG, "oncreate"); super.onCreate(savedInstanceState); setContentView(R.layout.activity_sender); SenderUtil.init(SenderActivity.this); // 先拿到数据并放在适配器上 initSenders(); //初始化数据 adapter = new SenderAdapter(SenderActivity.this, R.layout.sender_item, senderModels); // 将适配器上的数据传递给listView ListView listView = findViewById(R.id.list_view_sender); listView.setAdapter(adapter); // 为ListView注册一个监听器,当用户点击了ListView中的任何一个子项时,就会回调onItemClick()方法 // 在这个方法中可以通过position参数判断出用户点击的是那一个子项 listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { SenderModel senderModel = senderModels.get(position); Log.d(TAG, "onItemClick: "+senderModel); switch (senderModel.getType()){ case TYPE_DINGDING: setDingDing(senderModel); break; case TYPE_EMAIL: setEmail(senderModel); break; case TYPE_WEB_NOTIFY: setWebNotify(senderModel); break; case TYPE_QYWX_GROUP_ROBOT: setQYWXGroupRobot(senderModel); break; default: Toast.makeText(SenderActivity.this,"异常的发送方类型!删除",Toast.LENGTH_LONG).show(); break; } } }); listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) { //定义AlertDialog.Builder对象,当长按列表项的时候弹出确认删除对话框 AlertDialog.Builder builder = new AlertDialog.Builder(SenderActivity.this); builder.setMessage("确定删除?"); builder.setTitle("提示"); //添加AlertDialog.Builder对象的setPositiveButton()方法 builder.setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { SenderUtil.delSender(senderModels.get(position).getId()); initSenders(); adapter.del(senderModels); Toast.makeText(getBaseContext(), "删除列表项", Toast.LENGTH_SHORT).show(); } }); //添加AlertDialog.Builder对象的setNegativeButton()方法 builder.setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }); builder.create().show(); return true; } }); } // 初始化数据 private void initSenders() { senderModels = SenderUtil.getSender(null, null); ; } public void addSender(View view) { AlertDialog.Builder builder = new AlertDialog.Builder(SenderActivity.this); builder.setTitle("选择发送方类型"); builder.setItems(R.array.add_sender_menu, new DialogInterface.OnClickListener() {//添加列表 @Override public void onClick(DialogInterface dialogInterface, int which) { switch (which) { case TYPE_DINGDING: setDingDing(null); break; case TYPE_EMAIL: setEmail(null); break; case TYPE_WEB_NOTIFY: setWebNotify(null); break; case TYPE_QYWX_GROUP_ROBOT: setQYWXGroupRobot(null); break; default: Toast.makeText(SenderActivity.this, "暂不支持这种转发!", Toast.LENGTH_LONG).show(); break; } } }); builder.show(); Log.d(TAG, "setDingDing show" + senderModels.size()); } private void setDingDing(final SenderModel senderModel) { DingDingSettingVo dingDingSettingVo = null; //try phrase json setting if (senderModel != null) { String jsonSettingStr = senderModel.getJsonSetting(); if (jsonSettingStr != null) { dingDingSettingVo = JSON.parseObject(jsonSettingStr, DingDingSettingVo.class); } } final AlertDialog.Builder alertDialog71 = new AlertDialog.Builder(SenderActivity.this); View view1 = View.inflate(SenderActivity.this, R.layout.activity_alter_dialog_setview_dingding, null); final EditText editTextDingdingName = view1.findViewById(R.id.editTextDingdingName); if (senderModel != null) editTextDingdingName.setText(senderModel.getName()); final EditText editTextDingdingToken = view1.findViewById(R.id.editTextDingdingToken); if (dingDingSettingVo != null) editTextDingdingToken.setText(dingDingSettingVo.getToken()); final EditText editTextDingdingSecret = view1.findViewById(R.id.editTextDingdingSecret); if (dingDingSettingVo != null) editTextDingdingSecret.setText(dingDingSettingVo.getSecret()); final EditText editTextDingdingAtMobiles = view1.findViewById(R.id.editTextDingdingAtMobiles); if (dingDingSettingVo != null && dingDingSettingVo.getAtMobils()!=null) editTextDingdingAtMobiles.setText(dingDingSettingVo.getAtMobils()); final Switch switchDingdingAtAll = view1.findViewById(R.id.switchDingdingAtAll); if (dingDingSettingVo != null && dingDingSettingVo.getAtAll()!=null) switchDingdingAtAll.setChecked(dingDingSettingVo.getAtAll()); Button buttondingdingok = view1.findViewById(R.id.buttondingdingok); Button buttondingdingdel = view1.findViewById(R.id.buttondingdingdel); Button buttondingdingtest = view1.findViewById(R.id.buttondingdingtest); alertDialog71 .setTitle(R.string.setdingdingtitle) .setIcon(R.mipmap.dingding) .setView(view1) .create(); final AlertDialog show = alertDialog71.show(); buttondingdingok.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (senderModel == null) { SenderModel newSenderModel = new SenderModel(); newSenderModel.setName(editTextDingdingName.getText().toString()); newSenderModel.setType(TYPE_DINGDING); newSenderModel.setStatus(STATUS_ON); DingDingSettingVo dingDingSettingVonew = new DingDingSettingVo( editTextDingdingToken.getText().toString(), editTextDingdingSecret.getText().toString(), editTextDingdingAtMobiles.getText().toString(), switchDingdingAtAll.isChecked()); newSenderModel.setJsonSetting(JSON.toJSONString(dingDingSettingVonew)); SenderUtil.addSender(newSenderModel); initSenders(); adapter.add(senderModels); // adapter.add(newSenderModel); } else { senderModel.setName(editTextDingdingName.getText().toString()); senderModel.setType(TYPE_DINGDING); senderModel.setStatus(STATUS_ON); DingDingSettingVo dingDingSettingVonew = new DingDingSettingVo( editTextDingdingToken.getText().toString(), editTextDingdingSecret.getText().toString(), editTextDingdingAtMobiles.getText().toString(), switchDingdingAtAll.isChecked()); senderModel.setJsonSetting(JSON.toJSONString(dingDingSettingVonew)); SenderUtil.updateSender(senderModel); initSenders(); adapter.update(senderModels); // adapter.update(senderModel,position); } show.dismiss(); } }); buttondingdingdel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (senderModel != null) { SenderUtil.delSender(senderModel.getId()); initSenders(); adapter.del(senderModels); // adapter.del(position); } show.dismiss(); } }); buttondingdingtest.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String token = editTextDingdingToken.getText().toString(); String secret = editTextDingdingSecret.getText().toString(); String atMobiles = editTextDingdingAtMobiles.getText().toString(); Boolean atAll = switchDingdingAtAll.isChecked(); if (token != null && !token.isEmpty()) { try { SenderDingdingMsg.sendMsg(handler, token, secret,atMobiles,atAll, "test@" + (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()))); } catch (Exception e) { Toast.makeText(SenderActivity.this, "发送失败:" + e.getMessage(), Toast.LENGTH_LONG).show(); e.printStackTrace(); } } else { Toast.makeText(SenderActivity.this, "token 不能为空", Toast.LENGTH_LONG).show(); } } }); } private void setEmail(final SenderModel senderModel) { EmailSettingVo emailSettingVo = null; //try phrase json setting if (senderModel != null) { String jsonSettingStr = senderModel.getJsonSetting(); if (jsonSettingStr != null) { emailSettingVo = JSON.parseObject(jsonSettingStr, EmailSettingVo.class); } } final AlertDialog.Builder alertDialog71 = new AlertDialog.Builder(SenderActivity.this); View view1 = View.inflate(SenderActivity.this, R.layout.activity_alter_dialog_setview_email, null); final EditText editTextEmailName = view1.findViewById(R.id.editTextEmailName); if (senderModel != null) editTextEmailName.setText(senderModel.getName()); final EditText editTextEmailHost = view1.findViewById(R.id.editTextEmailHost); if (emailSettingVo != null) editTextEmailHost.setText(emailSettingVo.getHost()); final EditText editTextEmailPort = view1.findViewById(R.id.editTextEmailPort); if (emailSettingVo != null) editTextEmailPort.setText(emailSettingVo.getPort()); final Switch switchEmailSSl = view1.findViewById(R.id.switchEmailSSl); if (emailSettingVo != null) switchEmailSSl.setChecked(emailSettingVo.getSsl()); final EditText editTextEmailFromAdd = view1.findViewById(R.id.editTextEmailFromAdd); if (emailSettingVo != null) editTextEmailFromAdd.setText(emailSettingVo.getFromEmail()); final EditText editTextEmailPsw = view1.findViewById(R.id.editTextEmailPsw); if (emailSettingVo != null) editTextEmailPsw.setText(emailSettingVo.getPwd()); final EditText editTextEmailToAdd = view1.findViewById(R.id.editTextEmailToAdd); if (emailSettingVo != null) editTextEmailToAdd.setText(emailSettingVo.getToEmail()); Button buttonemailok = view1.findViewById(R.id.buttonemailok); Button buttonemaildel = view1.findViewById(R.id.buttonemaildel); Button buttonemailtest = view1.findViewById(R.id.buttonemailtest); alertDialog71 .setTitle(R.string.setemailtitle) .setIcon(R.drawable.ic_baseline_email_24) .setView(view1) .create(); final AlertDialog show = alertDialog71.show(); buttonemailok.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (senderModel == null) { SenderModel newSenderModel = new SenderModel(); newSenderModel.setName(editTextEmailName.getText().toString()); newSenderModel.setType(TYPE_EMAIL); newSenderModel.setStatus(STATUS_ON); EmailSettingVo emailSettingVonew = new EmailSettingVo( editTextEmailHost.getText().toString(), editTextEmailPort.getText().toString(), switchEmailSSl.isChecked(), editTextEmailFromAdd.getText().toString(), editTextEmailPsw.getText().toString(), editTextEmailToAdd.getText().toString() ); newSenderModel.setJsonSetting(JSON.toJSONString(emailSettingVonew)); SenderUtil.addSender(newSenderModel); initSenders(); adapter.add(senderModels); } else { senderModel.setName(editTextEmailName.getText().toString()); senderModel.setType(TYPE_EMAIL); senderModel.setStatus(STATUS_ON); EmailSettingVo emailSettingVonew = new EmailSettingVo( editTextEmailHost.getText().toString(), editTextEmailPort.getText().toString(), switchEmailSSl.isChecked(), editTextEmailFromAdd.getText().toString(), editTextEmailPsw.getText().toString(), editTextEmailToAdd.getText().toString() ); senderModel.setJsonSetting(JSON.toJSONString(emailSettingVonew)); SenderUtil.updateSender(senderModel); initSenders(); adapter.update(senderModels); } show.dismiss(); } }); buttonemaildel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (senderModel != null) { SenderUtil.delSender(senderModel.getId()); initSenders(); adapter.del(senderModels); } show.dismiss(); } }); buttonemailtest.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String host = editTextEmailHost.getText().toString(); String port = editTextEmailPort.getText().toString(); Boolean ssl = switchEmailSSl.isChecked(); String fromemail = editTextEmailFromAdd.getText().toString(); String pwd = editTextEmailPsw.getText().toString(); String toemail = editTextEmailToAdd.getText().toString(); if (!host.isEmpty() && !port.isEmpty() && !fromemail.isEmpty() && !pwd.isEmpty() && !toemail.isEmpty()) { try { SenderMailMsg.sendEmail(handler,host,port,ssl,fromemail,pwd,toemail,"TranspondSms test", "test@" + (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()))); } catch (Exception e) { Toast.makeText(SenderActivity.this, "发送失败:" + e.getMessage(), Toast.LENGTH_LONG).show(); e.printStackTrace(); } } else { Toast.makeText(SenderActivity.this, "token 不能为空", Toast.LENGTH_LONG).show(); } } }); } private void setWebNotify(final SenderModel senderModel) { WebNotifySettingVo webNotifySettingVo = null; //try phrase json setting if (senderModel != null) { String jsonSettingStr = senderModel.getJsonSetting(); if (jsonSettingStr != null) { webNotifySettingVo = JSON.parseObject(jsonSettingStr, WebNotifySettingVo.class); } } final AlertDialog.Builder alertDialog71 = new AlertDialog.Builder(SenderActivity.this); View view1 = View.inflate(SenderActivity.this, R.layout.activity_alter_dialog_setview_webnotify, null); final EditText editTextWebNotifyName = view1.findViewById(R.id.editTextWebNotifyName); if (senderModel != null) editTextWebNotifyName.setText(senderModel.getName()); final EditText editTextWebNotifyToken = view1.findViewById(R.id.editTextWebNotifyToken); if (webNotifySettingVo != null) editTextWebNotifyToken.setText(webNotifySettingVo.getToken()); final EditText editTextWebNotifySecret = view1.findViewById(R.id.editTextWebNotifySecret); if (webNotifySettingVo != null) editTextWebNotifySecret.setText(webNotifySettingVo.getSecret()); Button buttonbebnotifyok = view1.findViewById(R.id.buttonbebnotifyok); Button buttonbebnotifydel = view1.findViewById(R.id.buttonbebnotifydel); Button buttonbebnotifytest = view1.findViewById(R.id.buttonbebnotifytest); alertDialog71 .setTitle(R.string.setwebnotifytitle) .setIcon(R.mipmap.ic_launcher) .setView(view1) .create(); final AlertDialog show = alertDialog71.show(); buttonbebnotifyok.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (senderModel == null) { SenderModel newSenderModel = new SenderModel(); newSenderModel.setName(editTextWebNotifyName.getText().toString()); newSenderModel.setType(TYPE_WEB_NOTIFY); newSenderModel.setStatus(STATUS_ON); WebNotifySettingVo webNotifySettingVoNew = new WebNotifySettingVo( editTextWebNotifyToken.getText().toString(), editTextWebNotifySecret.getText().toString() ); newSenderModel.setJsonSetting(JSON.toJSONString(webNotifySettingVoNew)); SenderUtil.addSender(newSenderModel); initSenders(); adapter.add(senderModels); } else { senderModel.setName(editTextWebNotifyName.getText().toString()); senderModel.setType(TYPE_WEB_NOTIFY); senderModel.setStatus(STATUS_ON); WebNotifySettingVo webNotifySettingVoNew = new WebNotifySettingVo( editTextWebNotifyToken.getText().toString(), editTextWebNotifySecret.getText().toString() ); senderModel.setJsonSetting(JSON.toJSONString(webNotifySettingVoNew)); SenderUtil.updateSender(senderModel); initSenders(); adapter.update(senderModels); } show.dismiss(); } }); buttonbebnotifydel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (senderModel != null) { SenderUtil.delSender(senderModel.getId()); initSenders(); adapter.del(senderModels); } show.dismiss(); } }); buttonbebnotifytest.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String token = editTextWebNotifyToken.getText().toString(); String secret = editTextWebNotifySecret.getText().toString(); if (!token.isEmpty()) { try { SenderWebNotifyMsg.sendMsg(handler,token,secret,"TranspondSms test", "test@" + (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()))); } catch (Exception e) { Toast.makeText(SenderActivity.this, "发送失败:" + e.getMessage(), Toast.LENGTH_LONG).show(); e.printStackTrace(); } } else { Toast.makeText(SenderActivity.this, "token 不能为空", Toast.LENGTH_LONG).show(); } } }); } private void setQYWXGroupRobot(final SenderModel senderModel) { QYWXGroupRobotSettingVo qywxGroupRobotSettingVo = null; //try phrase json setting if (senderModel != null) { String jsonSettingStr = senderModel.getJsonSetting(); if (jsonSettingStr != null) { qywxGroupRobotSettingVo = JSON.parseObject(jsonSettingStr, QYWXGroupRobotSettingVo.class); } } final AlertDialog.Builder alertDialog71 = new AlertDialog.Builder(SenderActivity.this); View view1 = View.inflate(SenderActivity.this, R.layout.activity_alter_dialog_setview_qywxgrouprobot, null); final EditText editTextQYWXGroupRobotName = view1.findViewById(R.id.editTextQYWXGroupRobotName); if (senderModel != null) editTextQYWXGroupRobotName.setText(senderModel.getName()); final EditText editTextQYWXGroupRobotWebHook = view1.findViewById(R.id.editTextQYWXGroupRobotWebHook); if (qywxGroupRobotSettingVo != null) editTextQYWXGroupRobotWebHook.setText(qywxGroupRobotSettingVo.getWebHook()); Button buttonQyWxGroupRobotOk = view1.findViewById(R.id.buttonQyWxGroupRobotOk); Button buttonQyWxGroupRobotDel = view1.findViewById(R.id.buttonQyWxGroupRobotDel); Button buttonQyWxGroupRobotTest = view1.findViewById(R.id.buttonQyWxGroupRobotTest); alertDialog71 .setTitle(R.string.setqywxgrouprobottitle) .setIcon(R.mipmap.ic_launcher) .setView(view1) .create(); final AlertDialog show = alertDialog71.show(); buttonQyWxGroupRobotOk.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (senderModel == null) { SenderModel newSenderModel = new SenderModel(); newSenderModel.setName(editTextQYWXGroupRobotName.getText().toString()); newSenderModel.setType(TYPE_QYWX_GROUP_ROBOT); newSenderModel.setStatus(STATUS_ON); QYWXGroupRobotSettingVo qywxGroupRobotSettingVoNew = new QYWXGroupRobotSettingVo( editTextQYWXGroupRobotWebHook.getText().toString() ); newSenderModel.setJsonSetting(JSON.toJSONString(qywxGroupRobotSettingVoNew)); SenderUtil.addSender(newSenderModel); initSenders(); adapter.add(senderModels); } else { senderModel.setName(editTextQYWXGroupRobotName.getText().toString()); senderModel.setType(TYPE_QYWX_GROUP_ROBOT); senderModel.setStatus(STATUS_ON); QYWXGroupRobotSettingVo qywxGroupRobotSettingVoNew = new QYWXGroupRobotSettingVo( editTextQYWXGroupRobotWebHook.getText().toString() ); senderModel.setJsonSetting(JSON.toJSONString(qywxGroupRobotSettingVoNew)); SenderUtil.updateSender(senderModel); initSenders(); adapter.update(senderModels); } show.dismiss(); } }); buttonQyWxGroupRobotDel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (senderModel != null) { SenderUtil.delSender(senderModel.getId()); initSenders(); adapter.del(senderModels); } show.dismiss(); } }); buttonQyWxGroupRobotTest.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String webHook = editTextQYWXGroupRobotWebHook.getText().toString(); if (!webHook.isEmpty()) { try { SenderQyWxGroupRobotMsg.sendMsg(handler,webHook,"TranspondSms test", "test@" + (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()))); } catch (Exception e) { Toast.makeText(SenderActivity.this, "发送失败:" + e.getMessage(), Toast.LENGTH_LONG).show(); e.printStackTrace(); } } else { Toast.makeText(SenderActivity.this, "webHook 不能为空", Toast.LENGTH_LONG).show(); } } }); } @Override protected void onDestroy() { Log.d(TAG, "onDestroy"); super.onDestroy(); } @Override protected void onResume() { super.onResume(); MobclickAgent.onResume(this); } @Override protected void onPause() { super.onPause(); MobclickAgent.onPause(this); } } <|start_filename|>app/src/main/java/com/tim/tsms/transpondsms/SettingActivity.java<|end_filename|> package com.tim.tsms.transpondsms; import android.content.DialogInterface; import android.os.Bundle; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.View; import android.widget.CompoundButton; import android.widget.EditText; import android.widget.Switch; import android.widget.Toast; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.tim.tsms.transpondsms.model.vo.FeedBackResult; import com.tim.tsms.transpondsms.utils.HttpI; import com.tim.tsms.transpondsms.utils.HttpUtil; import com.tim.tsms.transpondsms.utils.SettingUtil; import com.tim.tsms.transpondsms.utils.UpdateAppHttpUtil; import com.tim.tsms.transpondsms.utils.aUtil; import com.vector.update_app.UpdateAppManager; import com.vector.update_app.UpdateCallback; import com.vector.update_app.listener.ExceptionHandler; import java.util.HashMap; import java.util.Map; public class SettingActivity extends AppCompatActivity { private String TAG = "SettingActivity"; @Override public void onCreate(Bundle savedInstanceState) { Log.d(TAG,"oncreate"); super.onCreate(savedInstanceState); setContentView(R.layout.activity_setting); Switch switch_add_extra = (Switch)findViewById(R.id.switch_add_extra); switchAddExtra(switch_add_extra); EditText et_add_extra_device_mark = (EditText)findViewById(R.id.et_add_extra_device_mark); editAddExtraDeviceMark(et_add_extra_device_mark); EditText et_add_extra_sim1 = (EditText)findViewById(R.id.et_add_extra_sim1); editAddExtraSim1(et_add_extra_sim1); EditText et_add_extra_sim2 = (EditText)findViewById(R.id.et_add_extra_sim2); editAddExtraSim2(et_add_extra_sim2); } //设置转发附加信息 private void switchAddExtra(Switch switch_add_extra){ switch_add_extra.setChecked(SettingUtil.getSwitchAddExtra()); switch_add_extra.setOnCheckedChangeListener(new Switch.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { SettingUtil.switchAddExtra(isChecked); Log.d(TAG,"onCheckedChanged:"+isChecked); } }); } //设置转发附加信息devicemark private void editAddExtraDeviceMark(final EditText et_add_extra_device_mark){ et_add_extra_device_mark.setText(SettingUtil.getAddExtraDeviceMark()); et_add_extra_device_mark.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { SettingUtil.setAddExtraDeviceMark(et_add_extra_device_mark.getText().toString()); } }); } //设置转发附加信息devicemark private void editAddExtraSim1(final EditText et_add_extra_sim1){ et_add_extra_sim1.setText(SettingUtil.getAddExtraSim1()); et_add_extra_sim1.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { SettingUtil.setAddExtraSim1(et_add_extra_sim1.getText().toString()); } }); } //设置转发附加信息devicemark private void editAddExtraSim2(final EditText et_add_extra_sim2){ et_add_extra_sim2.setText(SettingUtil.getAddExtraSim2()); et_add_extra_sim2.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { SettingUtil.setAddExtraSim2(et_add_extra_sim2.getText().toString()); } }); } } <|start_filename|>app/src/main/java/com/tim/tsms/transpondsms/utils/InitUtil.java<|end_filename|> package com.tim.tsms.transpondsms.utils; import android.content.Context; import android.util.Log; public class InitUtil { private static String TAG = "InitUtil"; private static Context context=null; static Boolean hasInit=false; public static void init(Context context1){ Log.d(TAG,"TMSG init"); synchronized (hasInit){ if(hasInit)return; hasInit=true; context = context1; Log.d(TAG,"init context"); SettingUtil.init(context); } } } <|start_filename|>app/src/main/java/com/tim/tsms/transpondsms/model/vo/SmsVo.java<|end_filename|> package com.tim.tsms.transpondsms.model.vo; import java.io.Serializable; import java.text.SimpleDateFormat; import java.util.Date; public class SmsVo implements Serializable{ String mobile; String content; Date date; SmsExtraVo smsExtraVo; public SmsVo() { } public SmsVo(String mobile, String content, Date date, SmsExtraVo smsExtraVo) { this.mobile = mobile; this.content = content; this.date = date; this.smsExtraVo = smsExtraVo; } public String getMobile() { return mobile; } public void setMobile(String mobile) { this.mobile = mobile; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public SmsExtraVo getSmsExtraVo() { return smsExtraVo; } public void setSmsExtraVo(SmsExtraVo smsExtraVo) { this.smsExtraVo = smsExtraVo; } public String getSmsVoForSend(){ String extraStr=""; if(smsExtraVo!=null){ if(smsExtraVo.getDeviceMark()!=null && !smsExtraVo.getDeviceMark().isEmpty()){ extraStr+="来自 "+smsExtraVo.getDeviceMark()+" "; } if(smsExtraVo.getSimDesc()!=null && !smsExtraVo.getSimDesc().isEmpty()){ extraStr+="卡: "+smsExtraVo.getSimDesc()+ " \n"; } } return mobile + "\n" + content + "\n" + extraStr + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date); } @Override public String toString() { return "SmsVo{" + "mobile='" + mobile + '\'' + ", content='" + content + '\'' + ", smsExtraVo=" + smsExtraVo + ", date=" + date + '}'; } } <|start_filename|>app/src/main/java/com/tim/tsms/transpondsms/utils/sender/SendUtil.java<|end_filename|> package com.tim.tsms.transpondsms.utils.sender; import android.content.Context; import android.os.Handler; import android.util.Log; import com.alibaba.fastjson.JSON; import com.tim.tsms.transpondsms.model.LogModel; import com.tim.tsms.transpondsms.model.RuleModel; import com.tim.tsms.transpondsms.model.SenderModel; import com.tim.tsms.transpondsms.model.vo.DingDingSettingVo; import com.tim.tsms.transpondsms.model.vo.EmailSettingVo; import com.tim.tsms.transpondsms.model.vo.QYWXGroupRobotSettingVo; import com.tim.tsms.transpondsms.model.vo.SmsVo; import com.tim.tsms.transpondsms.model.vo.WebNotifySettingVo; import com.tim.tsms.transpondsms.utils.LogUtil; import com.tim.tsms.transpondsms.utils.RuleUtil; import com.tim.tsms.transpondsms.utils.SettingUtil; import java.util.List; import static com.tim.tsms.transpondsms.model.SenderModel.TYPE_DINGDING; import static com.tim.tsms.transpondsms.model.SenderModel.TYPE_EMAIL; import static com.tim.tsms.transpondsms.model.SenderModel.TYPE_QYWX_GROUP_ROBOT; import static com.tim.tsms.transpondsms.model.SenderModel.TYPE_WEB_NOTIFY; public class SendUtil { private static String TAG = "SendUtil"; public static void send_msg(String msg){ if(SettingUtil.using_dingding()){ try { SenderDingdingMsg.sendMsg(msg); }catch (Exception e){ Log.d(TAG,"发送出错:"+e.getMessage()); } } if(SettingUtil.using_email()){ // SenderMailMsg.send(SettingUtil.get_send_util_email(Define.SP_MSG_SEND_UTIL_EMAIL_TOADD_KEY),"转发",msg); } } public static void send_msg_list(Context context,List<SmsVo> smsVoList){ Log.i(TAG, "send_msg_list size: "+smsVoList.size()); for (SmsVo smsVo:smsVoList){ SendUtil.send_msg(context,smsVo); } } public static void send_msg(Context context,SmsVo smsVo){ Log.i(TAG, "send_msg smsVo:"+smsVo); RuleUtil.init(context); LogUtil.init(context); List<RuleModel> rulelist = RuleUtil.getRule(null,null); if(!rulelist.isEmpty()){ SenderUtil.init(context); for (RuleModel ruleModel:rulelist ) { //规则匹配发现需要发送 try{ if(ruleModel.checkMsg(smsVo)){ List<SenderModel> senderModels = SenderUtil.getSender(ruleModel.getSenderId(),null); for (SenderModel senderModel:senderModels ) { LogUtil.addLog(new LogModel(smsVo.getMobile(),smsVo.getContent(),senderModel.getId(),JSON.toJSONString(smsVo.getSmsExtraVo()))); SendUtil.senderSendMsgNoHandError(smsVo,senderModel); } } }catch (Exception e){ Log.e(TAG, "send_msg: fail checkMsg:",e); } } } } public static void sendMsgByRuleModelSenderId(final Handler handError, RuleModel ruleModel,SmsVo smsVo, Long senderId) throws Exception { if(senderId==null){ throw new Exception("先新建并选择发送方"); } if(!ruleModel.checkMsg(smsVo)){ throw new Exception("短信未匹配中规则"); } List<SenderModel> senderModels = SenderUtil.getSender(senderId,null); if(senderModels.isEmpty()){ throw new Exception("未找到发送方"); } for (SenderModel senderModel:senderModels ) { //test //LogUtil.addLog(new LogModel(smsVo.getMobile(),smsVo.getContent(),senderModel.getId(),JSON.toJSONString(smsVo.getSmsExtraVo()))); SendUtil.senderSendMsg(handError,smsVo,senderModel); } } public static void senderSendMsgNoHandError(SmsVo smsVo,SenderModel senderModel) { SendUtil.senderSendMsg(null,smsVo,senderModel); } public static void senderSendMsg(Handler handError,SmsVo smsVo, SenderModel senderModel) { Log.i(TAG, "senderSendMsg smsVo:"+smsVo+"senderModel:"+senderModel); switch (senderModel.getType()){ case TYPE_DINGDING: //try phrase json setting if (senderModel.getJsonSetting() != null) { DingDingSettingVo dingDingSettingVo = JSON.parseObject(senderModel.getJsonSetting(), DingDingSettingVo.class); if(dingDingSettingVo!=null){ try { SenderDingdingMsg.sendMsg(handError, dingDingSettingVo.getToken(), dingDingSettingVo.getSecret(),dingDingSettingVo.getAtMobils(),dingDingSettingVo.getAtAll(), smsVo.getSmsVoForSend()); }catch (Exception e){ Log.e(TAG, "senderSendMsg: dingding error "+e.getMessage() ); } } } break; case TYPE_EMAIL: //try phrase json setting if (senderModel.getJsonSetting() != null) { EmailSettingVo emailSettingVo = JSON.parseObject(senderModel.getJsonSetting(), EmailSettingVo.class); if(emailSettingVo!=null){ try { SenderMailMsg.sendEmail(handError, emailSettingVo.getHost(),emailSettingVo.getPort(),emailSettingVo.getSsl(),emailSettingVo.getFromEmail(), emailSettingVo.getPwd(),emailSettingVo.getToEmail(),smsVo.getMobile(),smsVo.getSmsVoForSend()); }catch (Exception e){ Log.e(TAG, "senderSendMsg: SenderMailMsg error "+e.getMessage() ); } } } break; case TYPE_WEB_NOTIFY: //try phrase json setting if (senderModel.getJsonSetting() != null) { WebNotifySettingVo webNotifySettingVo = JSON.parseObject(senderModel.getJsonSetting(), WebNotifySettingVo.class); if(webNotifySettingVo!=null){ try { SenderWebNotifyMsg.sendMsg(handError,webNotifySettingVo.getToken(),webNotifySettingVo.getSecret(),smsVo.getMobile(),smsVo.getSmsVoForSend()); }catch (Exception e){ Log.e(TAG, "senderSendMsg: SenderWebNotifyMsg error "+e.getMessage() ); } } } break; case TYPE_QYWX_GROUP_ROBOT: //try phrase json setting if (senderModel.getJsonSetting() != null) { QYWXGroupRobotSettingVo qywxGroupRobotSettingVo = JSON.parseObject(senderModel.getJsonSetting(), QYWXGroupRobotSettingVo.class); if(qywxGroupRobotSettingVo!=null){ try { SenderQyWxGroupRobotMsg.sendMsg(handError,qywxGroupRobotSettingVo.getWebHook(),smsVo.getMobile(),smsVo.getSmsVoForSend()); }catch (Exception e){ Log.e(TAG, "senderSendMsg: SenderQyWxGroupRobotMsg error "+e.getMessage() ); } } } break; default: break; } } } <|start_filename|>app/src/main/java/com/tim/tsms/transpondsms/FrontService.java<|end_filename|> package com.tim.tsms.transpondsms; import android.app.Notification; import android.app.NotificationChannel; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.content.Intent; import android.os.IBinder; import android.support.annotation.Nullable; import android.util.Log; public class FrontService extends Service { private static final String TAG = "FrontService"; private static final String CHANNEL_ONE_ID = "com.tim.tsms.transpondsms"; private static final String CHANNEL_ONE_NAME = "com.tim.tsms.transpondsmsName"; @Override public void onCreate() { super.onCreate(); Log.i(TAG,"onCreate"); Notification.Builder builder = new Notification.Builder(this); builder.setSmallIcon(R.mipmap.ic_launchert); builder.setContentTitle("转"); builder.setContentText("转发信息"); Intent intent = new Intent(this, MainActivity.class); PendingIntent pendingIntent = PendingIntent.getActivity (this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); builder.setContentIntent(pendingIntent); if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) { //修改安卓8.1以上系统报错 NotificationChannel notificationChannel = new NotificationChannel(CHANNEL_ONE_ID, CHANNEL_ONE_NAME, NotificationManager.IMPORTANCE_MIN); notificationChannel.enableLights(false);//如果使用中的设备支持通知灯,则说明此通知通道是否应显示灯 notificationChannel.setShowBadge(false);//是否显示角标 notificationChannel.setLockscreenVisibility(Notification.VISIBILITY_SECRET); NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); manager.createNotificationChannel(notificationChannel); builder.setChannelId(CHANNEL_ONE_ID); } Notification notification = builder.build(); startForeground(1, notification); } @Nullable @Override public IBinder onBind(Intent intent) { return null; } @Override public int onStartCommand(Intent intent, int flags, int startId) { Log.i(TAG,"flags: "+flags+" startId: "+startId); return START_STICKY; } } <|start_filename|>app/src/main/java/com/tim/tsms/transpondsms/utils/SimUtil.java<|end_filename|> package com.tim.tsms.transpondsms.utils; import android.os.Bundle; import android.util.Log; public class SimUtil { private static String TAG = "SimUtil"; //获取卡槽ID public static int getSimId(Bundle bundle) { int whichSIM = -1; if(bundle==null){ return whichSIM; } if (bundle.containsKey("subscription")) { whichSIM = bundle.getInt("subscription"); } if (whichSIM >= 0 && whichSIM < 5) { /*In some device Subscription id is return as subscriber id*/ //TODO:不确定能不能直接返回 Log.d(TAG,"whichSIM >= 0 && whichSIM < 5:"+whichSIM); }else{ if (bundle.containsKey("simId")) { whichSIM = bundle.getInt("simId"); } else if (bundle.containsKey("com.android.phone.extra.slot")) { whichSIM = bundle.getInt("com.android.phone.extra.slot"); } else { String keyName = ""; for (String key : bundle.keySet()) { if (key.contains("sim")) keyName = key; } if (bundle.containsKey(keyName)) { whichSIM = bundle.getInt(keyName); } } } return whichSIM+1; } } <|start_filename|>app/src/main/java/com/tim/tsms/transpondsms/AboutActivity.java<|end_filename|> package com.tim.tsms.transpondsms; import android.content.ComponentName; import android.content.DialogInterface; import android.content.pm.PackageManager; import android.os.Bundle; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.CompoundButton; import android.widget.EditText; import android.widget.Switch; import android.widget.TextView; import android.widget.Toast; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.tim.tsms.transpondsms.BroadCastReceiver.RebootBroadcastReceiver; import com.tim.tsms.transpondsms.model.vo.FeedBackResult; import com.tim.tsms.transpondsms.utils.HttpI; import com.tim.tsms.transpondsms.utils.HttpUtil; import com.tim.tsms.transpondsms.utils.UpdateAppHttpUtil; import com.tim.tsms.transpondsms.utils.aUtil; import com.vector.update_app.UpdateAppManager; import com.vector.update_app.UpdateCallback; import com.vector.update_app.listener.ExceptionHandler; import java.util.HashMap; import java.util.Map; public class AboutActivity extends AppCompatActivity { private String TAG = "AboutActivity"; @Override public void onCreate(Bundle savedInstanceState) { Log.d(TAG,"oncreate"); super.onCreate(savedInstanceState); setContentView(R.layout.activity_about); Log.d(TAG, "onCreate: "+RebootBroadcastReceiver.class.getName()); Switch check_with_reboot = (Switch)findViewById(R.id.switch_with_reboot); checkWithReboot(check_with_reboot); TextView version_now = (TextView)findViewById(R.id.version_now); Button check_version_now = (Button)findViewById(R.id.check_version_now); try { version_now.setText(aUtil.getVersionName(AboutActivity.this)); } catch (Exception e) { e.printStackTrace(); } check_version_now.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { checkNewVersion(); } }); } //检查重启广播接受器状态并设置 private void checkWithReboot(Switch withrebootSwitch){ //获取组件 final ComponentName cm = new ComponentName(this.getPackageName(), RebootBroadcastReceiver.class.getName()); final PackageManager pm = getPackageManager(); int state = pm.getComponentEnabledSetting(cm); if (state != PackageManager.COMPONENT_ENABLED_STATE_DISABLED && state != PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER) { withrebootSwitch.setChecked(true); }else{ withrebootSwitch.setChecked(false); } withrebootSwitch.setOnCheckedChangeListener(new Switch.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { int newState = (Boolean)isChecked ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED : PackageManager.COMPONENT_ENABLED_STATE_DISABLED; pm.setComponentEnabledSetting(cm, newState,PackageManager.DONT_KILL_APP); Log.d(TAG,"onCheckedChanged:"+isChecked); } }); } private void checkNewVersion(){ String geturl = "http://api.allmything.com/api/version/hasnew?versioncode="; try { geturl+= aUtil.getVersionCode(AboutActivity.this); Log.i("SettingActivity",geturl); new UpdateAppManager .Builder() //当前Activity .setActivity(AboutActivity.this) //更新地址 .setUpdateUrl(geturl) //全局异常捕获 .handleException(new ExceptionHandler() { @Override public void onException(Exception e) { Log.e(TAG, "onException: ",e ); Toast.makeText(AboutActivity.this, "更新失败:"+e.getMessage(), Toast.LENGTH_SHORT).show(); } }) //实现httpManager接口的对象 .setHttpManager(new UpdateAppHttpUtil()) .build() .checkNewApp(new UpdateCallback(){ /** * 没有新版本 */ protected void noNewApp(String error) { Toast.makeText(AboutActivity.this, "没有新版本", Toast.LENGTH_SHORT).show(); } }); // .update(); } catch (Exception e) { e.printStackTrace(); } } public void feedbackcommit(View view) { final AlertDialog.Builder builder = new AlertDialog.Builder(AboutActivity.this); View view1 = View.inflate(AboutActivity.this, R.layout.dialog_feedback, null); final EditText feedback_et_email = view1.findViewById(R.id.feedback_et_email); final EditText feedback_et_text = view1.findViewById(R.id.feedback_et_text); builder .setTitle(R.string.feedback_input_text) .setView(view1) .create(); builder.setPositiveButton("提交反馈",new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { try { Map<String,String> feedBackData=new HashMap<>(); feedBackData.put("email",feedback_et_email.getText().toString()); feedBackData.put("text",feedback_et_text.getText().toString()); new HttpUtil().asyncPost("https://api.sl.willanddo.com/api/tsms/feedBack", feedBackData, new HttpI.Callback() { @Override public void onResponse(String result) { Log.i(TAG, "onResponse: "+result); if(result!=null){ FeedBackResult feedBackResult= JSON.parseObject(result, FeedBackResult.class); Log.i(TAG, "feedBackResult: "+feedBackResult); if(feedBackResult!=null){ JSONObject feedBackResultObject= JSON.parseObject(result); Toast.makeText(AboutActivity.this,feedBackResultObject.getString("message"),Toast.LENGTH_LONG).show(); }else { Toast.makeText(AboutActivity.this,"感谢您的反馈,我们将尽快处理!",Toast.LENGTH_LONG).show(); } }else { Toast.makeText(AboutActivity.this,"感谢您的反馈,我们将尽快处理!",Toast.LENGTH_LONG).show(); } } @Override public void onError(String error) { Log.i(TAG, "onError: "+error); Toast.makeText(AboutActivity.this,error,Toast.LENGTH_LONG).show(); } }); }catch (Exception e){ Toast.makeText(AboutActivity.this,e.getMessage(),Toast.LENGTH_LONG).show(); Log.d(TAG,"feedback e: "+e.getMessage()); } } }).show(); } } <|start_filename|>app/src/main/java/com/tim/tsms/transpondsms/utils/sender/SendHistory.java<|end_filename|> package com.tim.tsms.transpondsms.utils.sender; import android.content.ContentValues; import android.content.Context; import android.content.SharedPreferences; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.provider.BaseColumns; import android.util.Log; import com.tim.tsms.transpondsms.model.LogModel; import com.tim.tsms.transpondsms.model.LogTable; import com.tim.tsms.transpondsms.utils.DbHelper; import com.tim.tsms.transpondsms.utils.Define; import com.tim.tsms.transpondsms.utils.SettingUtil; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; public class SendHistory { static String TAG = "SendHistory"; static Boolean hasInit=false; static Context context; static DbHelper dbHelper; static SQLiteDatabase db; public static void init(Context context1) { synchronized (hasInit){ if(hasInit)return; hasInit=true; context = context1; dbHelper = new DbHelper(context); db = dbHelper.getReadableDatabase(); } } public static void addHistory(String msg) { //不保存转发消息 if (!SettingUtil.saveMsgHistory()) return; //保存 SharedPreferences sp = context.getSharedPreferences(Define.SP_MSG, Context.MODE_PRIVATE); Set<String> msg_set_default = new HashSet<>(); Set<String> msg_set; msg_set = sp.getStringSet(Define.SP_MSG_SET_KEY, msg_set_default); Log.d(TAG, "msg_set:" + msg_set.toString()); Log.d(TAG, "msg_set:" + Integer.toString(msg_set.size())); msg_set.add(msg); sp.edit().putStringSet(Define.SP_MSG_SET_KEY, msg_set).apply(); } public static String getHistory() { SharedPreferences sp = context.getSharedPreferences(Define.SP_MSG, Context.MODE_PRIVATE); Set<String> msg_set = new HashSet<>(); msg_set = sp.getStringSet(Define.SP_MSG_SET_KEY, msg_set); Log.d(TAG, "msg_set.toString()" + msg_set.toString()); String getMsg = ""; for (String str : msg_set) { getMsg += str + "\n"; } return getMsg; } public static long addHistoryDb(LogModel logModel) { //不保存转发消息 if (!SettingUtil.saveMsgHistory()) return 0; // Gets the data repository in write mode SQLiteDatabase db = dbHelper.getWritableDatabase(); // Create a new map of values, where column names are the keys ContentValues values = new ContentValues(); values.put(LogTable.LogEntry.COLUMN_NAME_FROM, logModel.getFrom()); values.put(LogTable.LogEntry.COLUMN_NAME_CONTENT, logModel.getContent()); values.put(LogTable.LogEntry.COLUMN_NAME_TIME, logModel.getTime()); // Insert the new row, returning the primary key value of the new row return db.insert(LogTable.LogEntry.TABLE_NAME, null, values); } public static int delHistoryDb(Long id,String key) { // Define 'where' part of query. String selection = " 1 "; // Specify arguments in placeholder order. List<String> selectionArgList = new ArrayList<>(); if(id!=null){ // Define 'where' part of query. selection +=" and " + LogTable.LogEntry._ID + " = ? "; // Specify arguments in placeholder order. selectionArgList.add(String.valueOf(id)); } if(key!=null){ // Define 'where' part of query. selection =" and (" + LogTable.LogEntry.COLUMN_NAME_FROM + " LIKE ? or "+ LogTable.LogEntry.COLUMN_NAME_CONTENT + " LIKE ? ) "; // Specify arguments in placeholder order. selectionArgList.add(key); selectionArgList.add(key); } String[] selectionArgs = selectionArgList.toArray(new String[selectionArgList.size()]); // Issue SQL statement. return db.delete(LogTable.LogEntry.TABLE_NAME, selection, selectionArgs); } public static String getHistoryDb(Long id,String key) { // Define a projection that specifies which columns from the database // you will actually use after this query. String[] projection = { BaseColumns._ID, LogTable.LogEntry.COLUMN_NAME_FROM, LogTable.LogEntry.COLUMN_NAME_CONTENT, LogTable.LogEntry.COLUMN_NAME_TIME }; // Define 'where' part of query. String selection = " 1 "; // Specify arguments in placeholder order. List<String> selectionArgList = new ArrayList<>(); if(id!=null){ // Define 'where' part of query. selection +=" and " + LogTable.LogEntry._ID + " = ? "; // Specify arguments in placeholder order. selectionArgList.add(String.valueOf(id)); } if(key!=null){ // Define 'where' part of query. selection =" and (" + LogTable.LogEntry.COLUMN_NAME_FROM + " LIKE ? or "+ LogTable.LogEntry.COLUMN_NAME_CONTENT + " LIKE ? ) "; // Specify arguments in placeholder order. selectionArgList.add(key); selectionArgList.add(key); } String[] selectionArgs = selectionArgList.toArray(new String[selectionArgList.size()]); // How you want the results sorted in the resulting Cursor String sortOrder = LogTable.LogEntry._ID + " DESC"; Cursor cursor = db.query( LogTable.LogEntry.TABLE_NAME, // The table to query projection, // The array of columns to return (pass null to get all) selection, // The columns for the WHERE clause selectionArgs, // The values for the WHERE clause null, // don't group the rows null, // don't filter by row groups sortOrder // The sort order ); List<Long> tLogs = new ArrayList<>(); while(cursor.moveToNext()) { long itemId = cursor.getLong( cursor.getColumnIndexOrThrow(LogTable.LogEntry._ID)); tLogs.add(itemId); } cursor.close(); SharedPreferences sp = context.getSharedPreferences(Define.SP_MSG, Context.MODE_PRIVATE); Set<String> msg_set = new HashSet<>(); msg_set = sp.getStringSet(Define.SP_MSG_SET_KEY, msg_set); Log.d(TAG, "msg_set.toString()" + msg_set.toString()); String getMsg = ""; for (String str : msg_set) { getMsg += str + "\n"; } return getMsg; } } <|start_filename|>app/release/output.json<|end_filename|> [{"outputType":{"type":"APK"},"apkInfo":{"type":"MAIN","splits":[],"versionCode":363,"versionName":"3.6.3","enabled":true,"outputFile":"TSMS_release_20210309_3.6.3.apk","fullName":"release","baseName":"release"},"path":"TSMS_release_20210309_3.6.3.apk","properties":{}}] <|start_filename|>app/src/main/java/com/tim/tsms/transpondsms/utils/sender/SenderWebNotifyMsg.java<|end_filename|> package com.tim.tsms.transpondsms.utils.sender; import android.os.Bundle; import android.os.Handler; import android.util.Base64; import android.util.Log; import java.io.IOException; import java.net.URLEncoder; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import okhttp3.Call; import okhttp3.Callback; import okhttp3.MediaType; import okhttp3.MultipartBody; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; import static com.tim.tsms.transpondsms.SenderActivity.NOTIFY; public class SenderWebNotifyMsg { static String TAG = "SenderWebNotifyMsg"; public static void sendMsg(final Handler handError, String token, String secret, String from, String content) throws Exception { Log.i(TAG, "sendMsg token:"+token+" from:"+from+" content:"+content); if (token == null || token.isEmpty()) { return; } OkHttpClient client = new OkHttpClient().newBuilder() .build(); MediaType mediaType = MediaType.parse("text/plain"); MultipartBody.Builder builder= new MultipartBody.Builder().setType(MultipartBody.FORM) .addFormDataPart("from",from) .addFormDataPart("content",content); if (secret != null && !secret.isEmpty()) { Long timestamp = System.currentTimeMillis(); String stringToSign = timestamp + "\n" + secret; Mac mac = Mac.getInstance("HmacSHA256"); mac.init(new SecretKeySpec(secret.getBytes("UTF-8"), "HmacSHA256")); byte[] signData = mac.doFinal(stringToSign.getBytes("UTF-8")); String sign = URLEncoder.encode(new String(Base64.encode(signData, Base64.NO_WRAP)), "UTF-8"); Log.i(TAG, "sign:" + sign); builder.addFormDataPart("timestamp",String.valueOf(timestamp)); builder.addFormDataPart("sign",sign); } RequestBody body = builder.build(); Request request = new Request.Builder() .url(token) .method("POST", body) .build(); // Response response = client.newCall(request).execute(); Call call = client.newCall(request); call.enqueue(new Callback() { @Override public void onFailure(Call call, final IOException e) { Log.d(TAG, "onFailure:" + e.getMessage()); if(handError != null){ android.os.Message msg = new android.os.Message(); msg.what = NOTIFY; Bundle bundle = new Bundle(); bundle.putString("DATA","发送失败:" + e.getMessage()); msg.setData(bundle); handError.sendMessage(msg); } } @Override public void onResponse(Call call, Response response) throws IOException { final String responseStr = response.body().string(); Log.d(TAG, "Code:" + String.valueOf(response.code()) + responseStr); if(handError != null){ android.os.Message msg = new android.os.Message(); msg.what = NOTIFY; Bundle bundle = new Bundle(); bundle.putString("DATA","发送状态:" + responseStr); msg.setData(bundle); handError.sendMessage(msg); Log.d(TAG, "Coxxyyde:" + String.valueOf(response.code()) + responseStr); } } }); } } <|start_filename|>app/src/main/java/com/tim/tsms/transpondsms/utils/sender/SenderDingdingMsg.java<|end_filename|> package com.tim.tsms.transpondsms.utils.sender; import android.os.Bundle; import android.os.Handler; import android.text.TextUtils; import android.util.Log; import java.io.IOException; import java.net.URLEncoder; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import android.util.Base64; import com.alibaba.fastjson.JSON; import com.tim.tsms.transpondsms.utils.SettingUtil; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import okhttp3.Call; import okhttp3.Callback; import okhttp3.MediaType; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; import static com.tim.tsms.transpondsms.SenderActivity.NOTIFY; public class SenderDingdingMsg { static String TAG = "SenderDingdingMsg"; public static void sendMsg(String msg) throws Exception { String webhook_token = SettingUtil.get_using_dingding_token(); String webhook_secret = SettingUtil.get_using_dingding_secret(); if (webhook_token.equals("")) { return; } if (!webhook_secret.equals("")) { Long timestamp = System.currentTimeMillis(); String stringToSign = timestamp + "\n" + webhook_secret; Mac mac = Mac.getInstance("HmacSHA256"); mac.init(new SecretKeySpec(webhook_secret.getBytes("UTF-8"), "HmacSHA256")); byte[] signData = mac.doFinal(stringToSign.getBytes("UTF-8")); String sign = URLEncoder.encode(new String(Base64.encode(signData, Base64.NO_WRAP)), "UTF-8"); webhook_token += "&timestamp=" + timestamp + "&sign=" + sign; Log.i(TAG, "webhook_token:" + webhook_token); } final String msgf = msg; String textMsg = "{ \"msgtype\": \"text\", \"text\": {\"content\": \"" + msg + "\"}}"; OkHttpClient client = new OkHttpClient(); RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), textMsg); final Request request = new Request.Builder() .url(webhook_token) .addHeader("Content-Type", "application/json; charset=utf-8") .post(requestBody) .build(); Call call = client.newCall(request); call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { Log.d(TAG, "onFailure:" + e.getMessage()); SendHistory.addHistory("钉钉转发:" + msgf + "onFailure:" + e.getMessage()); } @Override public void onResponse(Call call, Response response) throws IOException { final String responseStr = response.body().string(); Log.d(TAG, "Code:" + String.valueOf(response.code()) + responseStr); SendHistory.addHistory("钉钉转发:" + msgf + "Code:" + String.valueOf(response.code()) + responseStr); } }); } public static void sendMsg(final Handler handError, String token, String secret,String atMobiles,Boolean atAll, String msg) throws Exception { Log.i(TAG, "sendMsg token:"+token+" secret:"+secret+" atMobiles:"+atMobiles+" atAll:"+atAll+" msg:"+msg); if (token == null || token.isEmpty()) { return; } if (secret != null && !secret.isEmpty()) { Long timestamp = System.currentTimeMillis(); String stringToSign = timestamp + "\n" + secret; Mac mac = Mac.getInstance("HmacSHA256"); mac.init(new SecretKeySpec(secret.getBytes("UTF-8"), "HmacSHA256")); byte[] signData = mac.doFinal(stringToSign.getBytes("UTF-8")); String sign = URLEncoder.encode(new String(Base64.encode(signData, Base64.NO_WRAP)), "UTF-8"); token += "&timestamp=" + timestamp + "&sign=" + sign; Log.i(TAG, "webhook_token:" + token); } Map textMsgMap =new HashMap(); textMsgMap.put("msgtype","text"); Map textText=new HashMap(); textText.put("content",msg); textMsgMap.put("text",textText); if(atMobiles != null || atAll !=null){ Map AtMap=new HashMap(); if(atMobiles!=null){ String[] atMobilesArray = atMobiles.split(","); List<String> atMobilesList=new ArrayList<>(); for (String atMobile:atMobilesArray ) { if(TextUtils.isDigitsOnly(atMobile)){ atMobilesList.add(atMobile); } } if(!atMobilesList.isEmpty()){ AtMap.put("atMobiles",atMobilesList); } } AtMap.put("isAtAll",false); if(atAll !=null){ AtMap.put("isAtAll",atAll); } textMsgMap.put("at",AtMap); } String textMsg = JSON.toJSONString(textMsgMap); Log.i(TAG, "textMsg:" + textMsg); OkHttpClient client = new OkHttpClient(); RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), textMsg); final Request request = new Request.Builder() .url(token) .addHeader("Content-Type", "application/json; charset=utf-8") .post(requestBody) .build(); Call call = client.newCall(request); call.enqueue(new Callback() { @Override public void onFailure(Call call, final IOException e) { Log.d(TAG, "onFailure:" + e.getMessage()); if(handError != null){ android.os.Message msg = new android.os.Message(); msg.what = NOTIFY; Bundle bundle = new Bundle(); bundle.putString("DATA","发送失败:" + e.getMessage()); msg.setData(bundle); handError.sendMessage(msg); } } @Override public void onResponse(Call call, Response response) throws IOException { final String responseStr = response.body().string(); Log.d(TAG, "Code:" + String.valueOf(response.code()) + responseStr); if(handError != null){ android.os.Message msg = new android.os.Message(); msg.what = NOTIFY; Bundle bundle = new Bundle(); bundle.putString("DATA","发送状态:" + responseStr); msg.setData(bundle); handError.sendMessage(msg); Log.d(TAG, "Coxxyyde:" + String.valueOf(response.code()) + responseStr); } } }); } } <|start_filename|>app/src/main/java/com/tim/tsms/transpondsms/adapter/RuleAdapter.java<|end_filename|> package com.tim.tsms.transpondsms.adapter; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; import com.tim.tsms.transpondsms.R; import com.tim.tsms.transpondsms.model.RuleModel; import com.tim.tsms.transpondsms.model.SenderModel; import com.tim.tsms.transpondsms.utils.sender.SenderUtil; import java.util.List; public class RuleAdapter extends ArrayAdapter<RuleModel> { private int resourceId; private List<RuleModel> list; // 适配器的构造函数,把要适配的数据传入这里 public RuleAdapter(Context context, int textViewResourceId, List<RuleModel> objects){ super(context,textViewResourceId,objects); resourceId=textViewResourceId; list=objects; } @Override public int getCount() { return list.size(); } @Override public RuleModel getItem(int position) { return list.get(position); } @Override public long getItemId(int position) { RuleModel item =list.get(position); if(item==null){ return 0; } return item.getId(); } // convertView 参数用于将之前加载好的布局进行缓存 @Override public View getView(int position, View convertView, ViewGroup parent){ RuleModel ruleModel=getItem(position); //获取当前项的TLog实例 // 加个判断,以免ListView每次滚动时都要重新加载布局,以提高运行效率 View view; ViewHolder viewHolder; if (convertView==null){ // 避免ListView每次滚动时都要重新加载布局,以提高运行效率 view=LayoutInflater.from(getContext()).inflate(resourceId,parent,false); // 避免每次调用getView()时都要重新获取控件实例 viewHolder=new ViewHolder(); viewHolder.ruleMatch =view.findViewById(R.id.rule_match); viewHolder.ruleSender =view.findViewById(R.id.rule_sender); // 将ViewHolder存储在View中(即将控件的实例存储在其中) view.setTag(viewHolder); } else{ view=convertView; viewHolder=(ViewHolder) view.getTag(); } // 获取控件实例,并调用set...方法使其显示出来 if(ruleModel!=null){ List<SenderModel> senderModel = SenderUtil.getSender(ruleModel.getSenderId(),null); viewHolder.ruleMatch.setText(ruleModel.getRuleMatch()); if(!senderModel.isEmpty()){ viewHolder.ruleSender.setText(senderModel.get(0).getName()); }else{ viewHolder.ruleSender.setText(""); } } return view; } // 定义一个内部类,用于对控件的实例进行缓存 class ViewHolder{ TextView ruleMatch; TextView ruleSender; } public void add(List<RuleModel> ruleModels){ if(list!=null){ list=ruleModels; notifyDataSetChanged(); } } public void del(List<RuleModel> ruleModels){ if(list!=null){ list=ruleModels; notifyDataSetChanged(); } } public void update(List<RuleModel> ruleModels){ if(list!=null){ list=ruleModels; notifyDataSetChanged(); } } } <|start_filename|>app/src/main/java/com/tim/tsms/transpondsms/adapter/SenderAdapter.java<|end_filename|> package com.tim.tsms.transpondsms.adapter; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; import com.tim.tsms.transpondsms.R; import com.tim.tsms.transpondsms.model.SenderModel; import java.util.List; public class SenderAdapter extends ArrayAdapter<SenderModel> { private int resourceId; private List<SenderModel> list; // 适配器的构造函数,把要适配的数据传入这里 public SenderAdapter(Context context, int textViewResourceId, List<SenderModel> objects){ super(context,textViewResourceId,objects); resourceId=textViewResourceId; list=objects; } @Override public int getCount() { return list.size(); } @Override public SenderModel getItem(int position) { return list.get(position); } @Override public long getItemId(int position) { SenderModel item =list.get(position); if(item==null){ return 0; } return item.getId(); } // convertView 参数用于将之前加载好的布局进行缓存 @Override public View getView(int position, View convertView, ViewGroup parent){ SenderModel senderModel=getItem(position); //获取当前项的TLog实例 // 加个判断,以免ListView每次滚动时都要重新加载布局,以提高运行效率 View view; ViewHolder viewHolder; if (convertView==null){ // 避免ListView每次滚动时都要重新加载布局,以提高运行效率 view=LayoutInflater.from(getContext()).inflate(resourceId,parent,false); // 避免每次调用getView()时都要重新获取控件实例 viewHolder=new ViewHolder(); viewHolder.senderImage =view.findViewById(R.id.sender_image); viewHolder.senderName =view.findViewById(R.id.sender_name); // 将ViewHolder存储在View中(即将控件的实例存储在其中) view.setTag(viewHolder); } else{ view=convertView; viewHolder=(ViewHolder) view.getTag(); } // 获取控件实例,并调用set...方法使其显示出来 if(senderModel!=null){ viewHolder.senderImage.setImageResource(senderModel.getImageId()); viewHolder.senderName.setText(senderModel.getName()); } return view; } // 定义一个内部类,用于对控件的实例进行缓存 class ViewHolder{ ImageView senderImage; TextView senderName; } public void add(SenderModel senderModel){ if(list!=null){ list.add(senderModel); notifyDataSetChanged(); } } public void del(int position){ if(list!=null){ list.remove(position); notifyDataSetChanged(); } } public void update(SenderModel senderModel,int position){ if(list!=null){ list.set(position,senderModel); notifyDataSetChanged(); } } public void add(List<SenderModel> senderModels){ if(list!=null){ list=senderModels; notifyDataSetChanged(); } } public void del(List<SenderModel> senderModels){ if(list!=null){ list=senderModels; notifyDataSetChanged(); } } public void update(List<SenderModel> senderModels){ if(list!=null){ list=senderModels; notifyDataSetChanged(); } } } <|start_filename|>app/src/main/java/com/tim/tsms/transpondsms/model/vo/SmsExtraVo.java<|end_filename|> package com.tim.tsms.transpondsms.model.vo; import java.io.Serializable; public class SmsExtraVo implements Serializable{ Integer simId; String simDesc; String deviceMark; public SmsExtraVo() { } public SmsExtraVo(Integer simId, String simDesc, String deviceMark) { this.simId = simId; this.simDesc = simDesc; this.deviceMark = deviceMark; } public Integer getSimId() { return simId; } public void setSimId(Integer simId) { this.simId = simId; } public String getSimDesc() { return simDesc; } public void setSimDesc(String simDesc) { this.simDesc = simDesc; } public String getDeviceMark() { return deviceMark; } public void setDeviceMark(String deviceMark) { this.deviceMark = deviceMark; } @Override public String toString() { return "SmsExtraVo{" + "simId=" + simId + ", simDesc='" + simDesc + '\'' + ", deviceMark='" + deviceMark + '\'' + '}'; } } <|start_filename|>app/src/main/java/com/tim/tsms/transpondsms/utils/RuleLine.java<|end_filename|> package com.tim.tsms.transpondsms.utils; import android.util.Log; import com.tim.tsms.transpondsms.model.vo.SmsVo; import java.util.ArrayList; import java.util.List; class RuleLine{ static String TAG = "RuleLine"; static Boolean STARTLOG = true; //开头有几个空格 int headSpaceNum=0; RuleLine beforeRuleLine; RuleLine nextRuleLine; RuleLine parentRuleLine; RuleLine childRuleLine; //and or String conjunction; public static List<String> CONJUNCTION_LIST=new ArrayList<String>(); public static final String CONJUNCTION_AND="并且"; public static final String CONJUNCTION_OR="或者"; static { CONJUNCTION_LIST.add("and"); CONJUNCTION_LIST.add("or"); CONJUNCTION_LIST.add("并且"); CONJUNCTION_LIST.add("或者"); } //手机号 短信内容 String field; public static List<String> FILED_LIST=new ArrayList<String>(); public static final String FILED_PHONE_NUM="手机号"; public static final String FILED_MSG_CONTENT="短信内容"; static { FILED_LIST.add("手机号"); FILED_LIST.add("短信内容"); } // 是否 String sure; public static List<String> SURE_LIST=new ArrayList<String>(); public static final String SURE_YES="是"; public static final String SURE_NOT="不是"; static { SURE_LIST.add("是"); SURE_LIST.add("不是"); } String check; public static List<String> CHECK_LIST=new ArrayList<String>(); public static final String CHECK_EQUALS="相等"; public static final String CHECK_CONTAIN="包含"; public static final String CHECK_START_WITH="开头"; public static final String CHECK_END_WITH="结尾"; static { CHECK_LIST.add("相等"); CHECK_LIST.add("包含"); CHECK_LIST.add("开头"); CHECK_LIST.add("结尾"); } String value; //字段分支 public boolean checkMsg(SmsVo msg){ //检查这一行和上一行合并的结果是否命中 boolean mixChecked=false; //先检查规则是否命中 switch (this.field){ case FILED_PHONE_NUM: mixChecked= checkValue(msg.getMobile()); break; case FILED_MSG_CONTENT: mixChecked= checkValue(msg.getContent()); break; default: break; } //整合肯定词 switch (this.sure){ case SURE_YES: mixChecked= mixChecked; break; case SURE_NOT: mixChecked= !mixChecked; break; default: mixChecked=false; break; } logg("rule:"+this+" checkMsg:"+msg+" checked:"+mixChecked); return mixChecked; } //内容分支 public boolean checkValue(String msgValue){ boolean checked=false; switch (this.check){ case CHECK_EQUALS: checked=this.value.equals(msgValue); break; case CHECK_CONTAIN: if(msgValue!=null){ checked=msgValue.contains(this.value); } break; case CHECK_START_WITH: if(msgValue!=null){ checked=msgValue.startsWith(this.value); } break; case CHECK_END_WITH: if(msgValue!=null){ checked=msgValue.endsWith(this.value); } break; default: break; } logg("checkValue "+msgValue+" "+this.check+" "+this.value+" checked:"+checked); return checked; } public RuleLine(String line,int linenum,RuleLine beforeRuleLine) throws Exception { logg("----------"+linenum+"-----------------"); logg(line); //规则检验: //并且 是 手机号 相等 10086 //[并且, 是, 手机号, 相等, 10086] // 并且 是 内容 包含 asfas //[, , 并且, 是, 内容, 包含, asfas] //处理头空格数用来确认跟上一行节点的相对位置:是同级还是子级 //处理4个字段,之后的全部当做value //标记3个阶段 boolean isCountHeading=false; boolean isDealMiddel=false; boolean isDealValue=false; //用于保存4个中间体: 并且, 是, 内容, 包含 List<String> middleList=new ArrayList<>(4); //保存每个中间体字符串 StringBuilder buildMiddleWord= new StringBuilder(); StringBuilder valueBuilder= new StringBuilder(); for(int i=0;i<line.length();i++) { String w= String.valueOf(line.charAt(i)); logg("walk over:"+w); //控制阶段 //开始处理头 if(i==0){ if(" ".equals(w)){ logg("start to isCountHeading:"); isCountHeading=true; }else{ //直接进入处理中间体阶段 isCountHeading=false; isDealMiddel=true; logg("start to isDealMiddel:"); } } //正在数空格头,但是遇到非空格,阶段变更:由处理空头阶段 变为 处理 中间体阶段 if(isCountHeading && (!" ".equals(w))){ logg("isCountHeading to isDealMiddel:"); isCountHeading=false; isDealMiddel=true; } //正在处理中间体,中间体数量够了,阶段变更:由处理中间体 变为 处理 value if(isDealMiddel && middleList.size()==4){ logg("isDealMiddel done middleList:"+middleList); logg("isDealMiddel to isDealValue:"); isDealMiddel=false; isDealValue=true; } logg("isCountHeading:"+isCountHeading); logg("isDealMiddel:"+isDealMiddel); logg("isDealValue:"+isDealValue); if(isCountHeading){ if(" ".equals(w)){ logg("headSpaceNum++:"+headSpaceNum); headSpaceNum++; } } if(isDealMiddel){ //遇到空格 if(" ".equals(w)){ if(buildMiddleWord.length() == 0){ throw new Exception(linenum+"行:语法错误不允许出现连续空格!"); }else{ //生成了一个中间体 middleList.add(buildMiddleWord.toString()); logg("get Middle++:"+buildMiddleWord.toString()); buildMiddleWord = new StringBuilder(); } }else{ //把w拼接到中间体上 buildMiddleWord.append(w); logg("buildMiddleWord length:"+buildMiddleWord.length()+"buildMiddleWord:"+buildMiddleWord.toString()); } } if(isDealValue){ //把余下的所有字符都拼接给value valueBuilder.append(w); } } logg("isDealValue done valueBuilder:"+valueBuilder.toString()); if(middleList.size()!=4){ throw new Exception(linenum+"行配置错误:每行必须有4段组成,例如: 并且 手机号 是 相等 "); } //规则对齐 if(beforeRuleLine!=null){ logg("beforeRuleLine :"+beforeRuleLine); logg("thisRuleLine :"+this); //同级别 if(headSpaceNum==beforeRuleLine.headSpaceNum){ logg("同级别"); this.beforeRuleLine=beforeRuleLine; beforeRuleLine.nextRuleLine=this; } //子级 if(headSpaceNum-1==beforeRuleLine.headSpaceNum){ logg("子级"); this.parentRuleLine=beforeRuleLine; beforeRuleLine.childRuleLine=this; } //查找父级别 if(headSpaceNum<beforeRuleLine.headSpaceNum){ //匹配到最近一个同级 RuleLine fBeforeRuleLine=beforeRuleLine.getBeforeRuleLine(); if (fBeforeRuleLine==null){ fBeforeRuleLine=beforeRuleLine.getParentRuleLine(); } while (fBeforeRuleLine!=null){ logg("fBeforeRuleLine"+fBeforeRuleLine); //查找到同级别 if(headSpaceNum==fBeforeRuleLine.headSpaceNum){ logg("父级别"); this.beforeRuleLine=fBeforeRuleLine; fBeforeRuleLine.nextRuleLine=this; break; }else{ //向上查找 RuleLine testfBeforeRuleLine=fBeforeRuleLine.getBeforeRuleLine(); if (testfBeforeRuleLine==null){ testfBeforeRuleLine=fBeforeRuleLine.getParentRuleLine(); } fBeforeRuleLine=testfBeforeRuleLine; } } } }else{ logg("根级别"); } this.conjunction=middleList.get(0); this.sure=middleList.get(1); this.field=middleList.get(2); this.check=middleList.get(3); this.value=valueBuilder.toString(); if(!CONJUNCTION_LIST.contains(this.conjunction)){ throw new Exception(linenum+"行配置错误:连接词只支持:"+CONJUNCTION_LIST+" 但提供了"+this.conjunction); } if(!FILED_LIST.contains(this.field)){ throw new Exception(linenum+"行配置错误:字段只支持:"+FILED_LIST+" 但提供了"+this.field); } if(!SURE_LIST.contains(this.sure)){ throw new Exception(linenum+"行配置错误 "+this.sure+" 确认词只支持:"+SURE_LIST+" 但提供了"+this.sure); } if(!CHECK_LIST.contains(this.check)){ throw new Exception(linenum+"行配置错误:比较词只支持:"+CHECK_LIST+" 但提供了"+this.check); } logg("----------"+linenum+"=="+this); } public static void startLog(boolean startLog){ STARTLOG=startLog; } public static void logg(String msg){ if(STARTLOG){ Log.i(TAG, msg); } } @Override public String toString() { return "RuleLine{" + "headSpaceNum='" + headSpaceNum + '\'' + "conjunction='" + conjunction + '\'' + ", field='" + field + '\'' + ", sure='" + sure + '\'' + ", check='" + check + '\'' + ", value='" + value + '\'' + '}'; } public int getHeadSpaceNum() { return headSpaceNum; } public void setHeadSpaceNum(int headSpaceNum) { this.headSpaceNum = headSpaceNum; } public RuleLine getBeforeRuleLine() { return beforeRuleLine; } public void setBeforeRuleLine(RuleLine beforeRuleLine) { this.beforeRuleLine = beforeRuleLine; } public RuleLine getNextRuleLine() { return nextRuleLine; } public void setNextRuleLine(RuleLine nextRuleLine) { this.nextRuleLine = nextRuleLine; } public RuleLine getParentRuleLine() { return parentRuleLine; } public void setParentRuleLine(RuleLine parentRuleLine) { this.parentRuleLine = parentRuleLine; } public RuleLine getChildRuleLine() { return childRuleLine; } public void setChildRuleLine(RuleLine childRuleLine) { this.childRuleLine = childRuleLine; } public String getConjunction() { return conjunction; } public void setConjunction(String conjunction) { this.conjunction = conjunction; } public String getField() { return field; } public void setField(String field) { this.field = field; } public String getSure() { return sure; } public void setSure(String sure) { this.sure = sure; } public String getCheck() { return check; } public void setCheck(String check) { this.check = check; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } } <|start_filename|>app/src/main/java/com/tim/tsms/transpondsms/utils/aUtil.java<|end_filename|> package com.tim.tsms.transpondsms.utils; import android.content.Context; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.os.Environment; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.Properties; public class aUtil { private static String TAG = "aUtil"; private static Context context=null; /** * 判断是否为MIUI系统,参考http://blog.csdn.net/xx326664162/article/details/52438706 * * @return */ public static boolean isMIUI() { try { String KEY_MIUI_VERSION_CODE = "ro.miui.ui.version.code"; String KEY_MIUI_VERSION_NAME = "ro.miui.ui.version.name"; String KEY_MIUI_INTERNAL_STORAGE = "ro.miui.internal.storage"; Properties prop = new Properties(); prop.load(new FileInputStream(new File(Environment.getRootDirectory(), "build.prop"))); return prop.getProperty(KEY_MIUI_VERSION_CODE, null) != null || prop.getProperty(KEY_MIUI_VERSION_NAME, null) != null || prop.getProperty(KEY_MIUI_INTERNAL_STORAGE, null) != null; } catch (final IOException e) { return false; } } public static String getVersionName(Context context) throws Exception { // 获取packagemanager的实例 PackageManager packageManager = context.getPackageManager(); // getPackageName()是你当前类的包名,0代表是获取版本信息 PackageInfo packInfo = packageManager.getPackageInfo(context.getPackageName(),0); String version = packInfo.versionName; return version; } public static Integer getVersionCode(Context context) throws Exception { // 获取packagemanager的实例 PackageManager packageManager = context.getPackageManager(); // getPackageName()是你当前类的包名,0代表是获取版本信息 PackageInfo packInfo = packageManager.getPackageInfo(context.getPackageName(),0); Integer versionCode = packInfo.versionCode; return versionCode; } } <|start_filename|>app/src/main/java/com/tim/tsms/transpondsms/model/vo/FeedBackResult.java<|end_filename|> package com.tim.tsms.transpondsms.model.vo; import java.io.Serializable; public class FeedBackResult implements Serializable { Integer code; String message; Object result; public FeedBackResult(){ } public String getMessage() { return message; } public boolean isSuccess(){ return 1==code; } @Override public String toString() { return "FeedBackResult{" + "code=" + code + ", message='" + message + '\'' + ", result=" + result + '}'; } } <|start_filename|>app/src/main/java/com/tim/tsms/transpondsms/BroadCastReceiver/MessageBroadcastReceiver.java<|end_filename|> package com.tim.tsms.transpondsms.BroadCastReceiver; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; import android.widget.Toast; public class MessageBroadcastReceiver extends BroadcastReceiver { private String TAG = "MessageBroadcastReceiver"; public static String EXTRA_DATA = "data"; public static String ACTION_DINGDING = "com.tim.tsms.transpondsms.action_dingding"; @Override public void onReceive(Context arg0, Intent intent) { Log.d(TAG,"onReceive intent "+intent.getAction()); String action = intent.getAction(); if(action.equals(ACTION_DINGDING)){ String sendStatus = intent.getStringExtra(EXTRA_DATA); Toast.makeText(arg0,"dingding sendStatus: "+sendStatus,Toast.LENGTH_LONG).show(); } } } <|start_filename|>app/src/main/java/com/tim/tsms/transpondsms/model/vo/LogVo.java<|end_filename|> package com.tim.tsms.transpondsms.model.vo; public class LogVo { private String from; private String content; private String rule; private int senderImageId; private String time; private String jsonExtra; public LogVo(String from, String content, String time, String rule,int senderImageId,String jsonExtra) { this.from = from; this.content = content; this.time = time; this.rule = rule; this.senderImageId = senderImageId; this.jsonExtra = jsonExtra; } public LogVo() { } public String getFrom() { return from; } public void setFrom(String from) { this.from = from; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getRule() { return rule; } public void setRule(String rule) { this.rule = rule; } public String getTime() { return time; } public int getSenderImageId() { return senderImageId; } public String getJsonExtra() { return jsonExtra; } public void setJsonExtra(String jsonExtra) { this.jsonExtra = jsonExtra; } public void setSenderImageId(int senderImageId) { this.senderImageId = senderImageId; } @Override public String toString() { return "LogVo{" + "from='" + from + '\'' + ", content='" + content + '\'' + ", rule='" + rule + '\'' + ", senderImageId=" + senderImageId + ", time='" + time + '\'' + ", jsonExtra='" + jsonExtra + '\'' + '}'; } } <|start_filename|>app/src/main/java/com/tim/tsms/transpondsms/model/vo/DingDingSettingVo.java<|end_filename|> package com.tim.tsms.transpondsms.model.vo; import java.io.Serializable; public class DingDingSettingVo implements Serializable { private String token; private String secret; private String atMobils; private Boolean atAll; public DingDingSettingVo() { } public DingDingSettingVo(String token, String secret, String atMobils, Boolean atAll) { this.token = token; this.secret = secret; this.atMobils = atMobils; this.atAll = atAll; } public String getToken() { return token; } public void setToken(String token) { this.token = token; } public String getSecret() { return secret; } public void setSecret(String secret) { this.secret = secret; } public String getAtMobils() { return atMobils; } public void setAtMobils(String atMobils) { this.atMobils = atMobils; } public Boolean getAtAll() { return atAll; } public void setAtAll(Boolean atAll) { this.atAll = atAll; } } <|start_filename|>app/src/main/java/com/tim/tsms/transpondsms/RuleActivity.java<|end_filename|> package com.tim.tsms.transpondsms; import android.content.DialogInterface; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.TextView; import android.widget.Toast; import com.tim.tsms.transpondsms.adapter.RuleAdapter; import com.tim.tsms.transpondsms.model.RuleModel; import com.tim.tsms.transpondsms.model.SenderModel; import com.tim.tsms.transpondsms.model.vo.SmsExtraVo; import com.tim.tsms.transpondsms.model.vo.SmsVo; import com.tim.tsms.transpondsms.utils.RuleUtil; import com.tim.tsms.transpondsms.utils.sender.SendUtil; import com.tim.tsms.transpondsms.utils.sender.SenderUtil; import com.umeng.analytics.MobclickAgent; import java.util.ArrayList; import java.util.Date; import java.util.List; import static com.tim.tsms.transpondsms.SenderActivity.NOTIFY; public class RuleActivity extends AppCompatActivity { private String TAG = "RuleActivity"; // 用于存储数据 private List<RuleModel> ruleModels = new ArrayList<>(); private RuleAdapter adapter; private Long selectSenderId=0l; private String selectSenderName=""; //消息处理者,创建一个Handler的子类对象,目的是重写Handler的处理消息的方法(handleMessage()) private Handler handler = new Handler(){ @Override public void handleMessage(Message msg) { switch (msg.what){ case NOTIFY: Toast.makeText(RuleActivity.this, msg.getData().getString("DATA"), Toast.LENGTH_LONG).show(); break; } } }; @Override protected void onCreate(Bundle savedInstanceState) { Log.d(TAG, "oncreate"); super.onCreate(savedInstanceState); setContentView(R.layout.activity_rule); RuleUtil.init(RuleActivity.this); SenderUtil.init(RuleActivity.this); // 先拿到数据并放在适配器上 initRules(); //初始化数据 adapter = new RuleAdapter(RuleActivity.this, R.layout.rule_item, ruleModels); // 将适配器上的数据传递给listView ListView listView = findViewById(R.id.list_view_rule); listView.setAdapter(adapter); // 为ListView注册一个监听器,当用户点击了ListView中的任何一个子项时,就会回调onItemClick()方法 // 在这个方法中可以通过position参数判断出用户点击的是那一个子项 listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { RuleModel ruleModel = ruleModels.get(position); Log.d(TAG, "onItemClick: "+ruleModel); setRule(ruleModel); } }); listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) { //定义AlertDialog.Builder对象,当长按列表项的时候弹出确认删除对话框 AlertDialog.Builder builder = new AlertDialog.Builder(RuleActivity.this); builder.setMessage("确定删除?"); builder.setTitle("提示"); //添加AlertDialog.Builder对象的setPositiveButton()方法 builder.setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { RuleUtil.delRule(ruleModels.get(position).getId()); initRules(); adapter.del(ruleModels); Toast.makeText(getBaseContext(), "删除列表项", Toast.LENGTH_SHORT).show(); } }); //添加AlertDialog.Builder对象的setNegativeButton()方法 builder.setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }); builder.create().show(); return true; } }); } // 初始化数据 private void initRules() { ruleModels = RuleUtil.getRule(null, null); } public void addRule(View view) { setRule(null); } private void setRule(final RuleModel ruleModel) { final AlertDialog.Builder alertDialog71 = new AlertDialog.Builder(RuleActivity.this); final View view1 = View.inflate(RuleActivity.this, R.layout.activity_alter_dialog_setview_rule, null); final RadioGroup radioGroupRuleFiled = (RadioGroup) view1.findViewById(R.id.radioGroupRuleFiled); if(ruleModel!=null)radioGroupRuleFiled.check(ruleModel.getRuleFiledCheckId()); final RadioGroup radioGroupRuleCheck = (RadioGroup) view1.findViewById(R.id.radioGroupRuleCheck); if(ruleModel!=null)radioGroupRuleCheck.check(ruleModel.getRuleCheckCheckId()); final TextView tv_mu_rule_tips = (TextView) view1.findViewById(R.id.tv_mu_rule_tips); final TextView ruleSenderTv = (TextView) view1.findViewById(R.id.ruleSenderTv); if(ruleModel!=null && ruleModel.getSenderId()!=null){ List<SenderModel> getSeners = SenderUtil.getSender(ruleModel.getSenderId(),null); if(!getSeners.isEmpty()){ ruleSenderTv.setText(getSeners.get(0).getName()); ruleSenderTv.setTag(getSeners.get(0).getId()); } } final Button btSetRuleSender = (Button) view1.findViewById(R.id.btSetRuleSender); btSetRuleSender.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Toast.makeText(RuleActivity.this,"selectSender",Toast.LENGTH_LONG).show(); selectSender(ruleSenderTv); } }); final EditText editTextRuleValue = view1.findViewById(R.id.editTextRuleValue); if (ruleModel != null) editTextRuleValue.setText(ruleModel.getValue()); //当更新选择的字段的时候,更新之下各个选项的状态 refreshSelectRadioGroupRuleFiled(radioGroupRuleFiled, radioGroupRuleCheck, editTextRuleValue,tv_mu_rule_tips); Button buttonruleok = view1.findViewById(R.id.buttonruleok); Button buttonruledel = view1.findViewById(R.id.buttonruledel); Button buttonruletest = view1.findViewById(R.id.buttonruletest); alertDialog71 .setTitle(R.string.setrule) .setView(view1) .create(); final AlertDialog show = alertDialog71.show(); buttonruleok.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Object senderId = ruleSenderTv.getTag(); if (ruleModel == null) { RuleModel newRuleModel = new RuleModel(); newRuleModel.setFiled(RuleModel.getRuleFiledFromCheckId(radioGroupRuleFiled.getCheckedRadioButtonId())); newRuleModel.setCheck(RuleModel.getRuleCheckFromCheckId(radioGroupRuleCheck.getCheckedRadioButtonId())); newRuleModel.setValue(editTextRuleValue.getText().toString()); if(senderId!=null){ newRuleModel.setSenderId(Long.valueOf(senderId.toString())); } RuleUtil.addRule(newRuleModel); initRules(); adapter.add(ruleModels); } else { ruleModel.setFiled(RuleModel.getRuleFiledFromCheckId(radioGroupRuleFiled.getCheckedRadioButtonId())); ruleModel.setCheck(RuleModel.getRuleCheckFromCheckId(radioGroupRuleCheck.getCheckedRadioButtonId())); ruleModel.setValue(editTextRuleValue.getText().toString()); if(senderId!=null){ ruleModel.setSenderId(Long.valueOf(senderId.toString())); } RuleUtil.updateRule(ruleModel); initRules(); adapter.update(ruleModels); } show.dismiss(); } }); buttonruledel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (ruleModel != null) { RuleUtil.delRule(ruleModel.getId()); initRules(); adapter.del(ruleModels); } show.dismiss(); } }); buttonruletest.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Object senderId = ruleSenderTv.getTag(); if(senderId==null){ Toast.makeText(RuleActivity.this,"请先创建选择发送方",Toast.LENGTH_LONG).show(); }else{ if (ruleModel == null) { RuleModel newRuleModel = new RuleModel(); newRuleModel.setFiled(RuleModel.getRuleFiledFromCheckId(radioGroupRuleFiled.getCheckedRadioButtonId())); newRuleModel.setCheck(RuleModel.getRuleCheckFromCheckId(radioGroupRuleCheck.getCheckedRadioButtonId())); newRuleModel.setValue(editTextRuleValue.getText().toString()); newRuleModel.setSenderId(Long.valueOf(senderId.toString())); testRule(newRuleModel,Long.valueOf(senderId.toString())); } else { ruleModel.setFiled(RuleModel.getRuleFiledFromCheckId(radioGroupRuleFiled.getCheckedRadioButtonId())); ruleModel.setCheck(RuleModel.getRuleCheckFromCheckId(radioGroupRuleCheck.getCheckedRadioButtonId())); ruleModel.setValue(editTextRuleValue.getText().toString()); ruleModel.setSenderId(Long.valueOf(senderId.toString())); testRule(ruleModel,Long.valueOf(senderId.toString())); } } } }); } //当更新选择的字段的时候,更新之下各个选项的状态 // 如果设置了转发全部,禁用选择模式和匹配值输入 // 如果设置了多重规则,选择模式置为是 private void refreshSelectRadioGroupRuleFiled(RadioGroup radioGroupRuleFiled, final RadioGroup radioGroupRuleCheck, final EditText editTextRuleValue, final TextView tv_mu_rule_tips){ refreshSelectRadioGroupRuleFiledAction(radioGroupRuleFiled.getCheckedRadioButtonId(),radioGroupRuleCheck,editTextRuleValue,tv_mu_rule_tips); radioGroupRuleFiled.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { refreshSelectRadioGroupRuleFiledAction(checkedId,radioGroupRuleCheck,editTextRuleValue,tv_mu_rule_tips); } }); } private void refreshSelectRadioGroupRuleFiledAction(int checkedRuleFiledId, final RadioGroup radioGroupRuleCheck, final EditText editTextRuleValue, final TextView tv_mu_rule_tips){ tv_mu_rule_tips.setVisibility(View.GONE); switch (checkedRuleFiledId){ case R.id.btnTranspondAll: for(int i = 0; i < radioGroupRuleCheck.getChildCount(); i++){ ((RadioButton)radioGroupRuleCheck.getChildAt(i)).setEnabled(false); } editTextRuleValue.setEnabled(false); break; case R.id.btnMultiMatch: for(int i = 0; i < radioGroupRuleCheck.getChildCount(); i++){ ((RadioButton)radioGroupRuleCheck.getChildAt(i)).setEnabled(false); } editTextRuleValue.setEnabled(true); tv_mu_rule_tips.setVisibility(View.VISIBLE); break; default: for(int i = 0; i < radioGroupRuleCheck.getChildCount(); i++){ ((RadioButton)radioGroupRuleCheck.getChildAt(i)).setEnabled(true); } editTextRuleValue.setEnabled(true); break; } } public void selectSender(final TextView showTv) { final List<SenderModel> senderModels = SenderUtil.getSender(null,null); if(senderModels.isEmpty()){ Toast.makeText(RuleActivity.this, "请先去设置发送方页面添加", Toast.LENGTH_SHORT).show(); return; } final CharSequence[] senderNames= new CharSequence[senderModels.size()]; for (int i=0;i<senderModels.size();i++){ senderNames[i]=senderModels.get(i).getName(); } AlertDialog.Builder builder = new AlertDialog.Builder(RuleActivity.this); builder.setTitle("选择发送方"); builder.setItems(senderNames, new DialogInterface.OnClickListener() {//添加列表 @Override public void onClick(DialogInterface dialogInterface, int which) { Toast.makeText(RuleActivity.this, senderNames[which], Toast.LENGTH_LONG).show(); showTv.setText(senderNames[which]); showTv.setTag(senderModels.get(which).getId()); } }); builder.show(); } public void testRule(final RuleModel ruleModel, final Long senderId) { final View view = View.inflate(RuleActivity.this, R.layout.activity_alter_dialog_setview_rule_test, null); final EditText editTextTestPhone = (EditText) view.findViewById(R.id.editTextTestPhone); final EditText editTextTestMsgContent = (EditText)view.findViewById(R.id.editTextTestMsgContent); Button buttonruletest = view.findViewById(R.id.buttonruletest); AlertDialog.Builder ad1 = new AlertDialog.Builder(RuleActivity.this); ad1.setTitle("测试规则"); ad1.setIcon(android.R.drawable.ic_dialog_info); ad1.setView(view); buttonruletest.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Log.i("editTextTestPhone", editTextTestPhone.getText().toString()); Log.i("editTextTestMsgContent", editTextTestMsgContent.getText().toString()); try{ SmsVo testSmsVo=new SmsVo(editTextTestPhone.getText().toString(),editTextTestMsgContent.getText().toString(),new Date(),new SmsExtraVo(1,"卡哇伊","红色白皮手机")); SendUtil.sendMsgByRuleModelSenderId(handler,ruleModel,testSmsVo,senderId); }catch (Exception e){ Toast.makeText(RuleActivity.this,e.getMessage(),Toast.LENGTH_LONG).show(); } } }); ad1.show();// 显示对话框 } @Override protected void onDestroy() { Log.d(TAG, "onDestroy"); super.onDestroy(); } @Override protected void onResume() { super.onResume(); MobclickAgent.onResume(this); } @Override protected void onPause() { super.onPause(); MobclickAgent.onPause(this); } } <|start_filename|>app/src/main/java/com/tim/tsms/transpondsms/model/RuleModel.java<|end_filename|> package com.tim.tsms.transpondsms.model; import android.util.Log; import com.tim.tsms.transpondsms.R; import com.tim.tsms.transpondsms.model.vo.SmsVo; import com.tim.tsms.transpondsms.utils.RuleLineUtils; import java.util.HashMap; import java.util.Map; public class RuleModel { private String TAG = "RuleModel"; private Long id; public static final String FILED_TRANSPOND_ALL="transpond_all"; public static final String FILED_PHONE_NUM="phone_num"; public static final String FILED_MSG_CONTENT="msg_content"; public static final String FILED_MULTI_MATCH="multi_match"; public static final Map<String,String> FILED_MAP=new HashMap<String, String>(); static{ FILED_MAP.put("transpond_all", "转发全部"); FILED_MAP.put("phone_num", "手机号"); FILED_MAP.put("msg_content", "内容"); FILED_MAP.put("multi_match", "多重匹配"); } private String filed; public static final String CHECK_IS="is"; public static final String CHECK_CONTAIN="contain"; public static final String CHECK_START_WITH="startwith"; public static final String CHECK_END_WITH="endwith"; public static final String CHECK_NOT_IS="notis"; public static final Map<String,String> CHECK_MAP=new HashMap<String, String>(); static{ CHECK_MAP.put("is", "是"); CHECK_MAP.put("contain", "包含"); CHECK_MAP.put("startwith", "开头是"); CHECK_MAP.put("endwith", "结尾是"); CHECK_MAP.put("notis", "不是"); } private String check; private String value; private Long senderId; private Long time; //字段分支 public boolean checkMsg(SmsVo msg) throws Exception { //检查这一行和上一行合并的结果是否命中 boolean mixChecked=false; if(msg!=null){ //先检查规则是否命中 switch (this.filed){ case FILED_TRANSPOND_ALL: mixChecked= true; break; case FILED_PHONE_NUM: mixChecked= checkValue(msg.getMobile()); break; case FILED_MSG_CONTENT: mixChecked= checkValue(msg.getContent()); break; case FILED_MULTI_MATCH: mixChecked= RuleLineUtils.checkRuleLines(msg,this.value); break; default: break; } } Log.i(TAG, "rule:"+this+" checkMsg:"+msg+" checked:"+mixChecked); return mixChecked; } //内容分支 public boolean checkValue(String msgValue){ boolean checked=false; if(this.value!=null){ switch (this.check){ case CHECK_IS: checked=this.value.equals(msgValue); break; case CHECK_CONTAIN: if(msgValue!=null){ checked=msgValue.contains(this.value); } break; case CHECK_START_WITH: if(msgValue!=null){ checked=msgValue.startsWith(this.value); } break; case CHECK_END_WITH: if(msgValue!=null){ checked=msgValue.endsWith(this.value); } break; default: break; } } Log.i(TAG, "checkValue "+msgValue+" "+this.check+" "+this.value+" checked:"+checked); return checked; } public String getRuleMatch() { switch (filed){ case FILED_TRANSPOND_ALL: return "全部转发到 "; default: return "当 "+FILED_MAP.get(filed)+" "+CHECK_MAP.get(check)+" "+value+" 转发到 "; } } public static String getRuleMatch(String filed,String check,String value) { switch (filed){ case FILED_TRANSPOND_ALL: return "全部转发到 "; default: return "当 "+FILED_MAP.get(filed)+" "+CHECK_MAP.get(check)+" "+value; } } public Long getRuleSenderId() { return senderId; } public int getRuleFiledCheckId(){ switch (filed){ case FILED_MSG_CONTENT: return R.id.btnContent; case FILED_PHONE_NUM: return R.id.btnPhone; case FILED_MULTI_MATCH: return R.id.btnMultiMatch; default: return R.id.btnTranspondAll; } } public static String getRuleFiledFromCheckId(int id){ switch (id){ case R.id.btnContent: return FILED_MSG_CONTENT; case R.id.btnPhone: return FILED_PHONE_NUM; case R.id.btnMultiMatch: return FILED_MULTI_MATCH; default: return FILED_TRANSPOND_ALL; } } public int getRuleCheckCheckId(){ switch (check){ case CHECK_CONTAIN: return R.id.btnContain; case CHECK_START_WITH: return R.id.btnStartWith; case CHECK_END_WITH: return R.id.btnEndWith; case CHECK_NOT_IS: return R.id.btnNotIs; default: return R.id.btnIs; } } public static String getRuleCheckFromCheckId(int id){ switch (id){ case R.id.btnContain: return CHECK_CONTAIN; case R.id.btnStartWith: return CHECK_START_WITH; case R.id.btnEndWith: return CHECK_END_WITH; case R.id.btnNotIs: return CHECK_NOT_IS; default: return CHECK_IS; } } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getSenderId() { return senderId; } public void setSenderId(Long senderId) { this.senderId = senderId; } public Long getTime() { return time; } public void setTime(Long time) { this.time = time; } public String getFiled() { return filed; } public void setFiled(String filed) { this.filed = filed; } public String getCheck() { return check; } public void setCheck(String check) { this.check = check; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } @Override public String toString() { return "RuleModel{" + "id=" + id + ", filed='" + filed + '\'' + ", check='" + check + '\'' + ", value='" + value + '\'' + ", senderId=" + senderId + ", time=" + time + '}'; } }
wangvic21/TranspondSms
<|start_filename|>android_databinding_plugin/src/com/heaven7/plugin/action/AndroidDatabindConfigAction.java<|end_filename|> package com.heaven7.plugin.action; import com.heaven7.plugin.ui.AndroidDatabindingDialog; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.actionSystem.LangDataKeys; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; /** * Created by heaven7 on 2015/12/24. */ public class AndroidDatabindConfigAction extends AnAction { @Override public void update(AnActionEvent e) { super.update(e); VirtualFile dir = e.getData(LangDataKeys.VIRTUAL_FILE); if (dir != null && dir.isDirectory()) { String text = dir.getName(); e.getPresentation().setVisible("res".equals(text)); } } @Override public void actionPerformed(AnActionEvent e) { final VirtualFile dir = e.getData(LangDataKeys.VIRTUAL_FILE); if (dir == null) { return; } Project project = e.getProject(); AndroidDatabindingDialog dialog = new AndroidDatabindingDialog(project, dir); dialog.show(); } } <|start_filename|>android_databinding_plugin/src/com/heaven7/plugin/util/Util.java<|end_filename|> package com.heaven7.plugin.util; import java.io.PrintWriter; import java.io.StringWriter; /** * Created by heaven7 on 2015/12/24. */ public class Util { public static String toString(Throwable t) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); t.printStackTrace(pw); Throwable cause = t.getCause(); while (cause != null) { cause.printStackTrace(pw); cause = cause.getCause(); } pw.flush(); String data = sw.toString(); pw.close(); return data; } } <|start_filename|>android_databinding_plugin/src/com/heaven7/plugin/ui/AndroidDatabindingDialog.java<|end_filename|> package com.heaven7.plugin.ui; import com.heaven7.plugin.util.Util; import com.intellij.openapi.application.Application; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.DialogWrapper; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.vfs.VirtualFile; import org.jetbrains.annotations.Nullable; import org.w3c.dom.Document; import org.w3c.dom.Element; import javax.swing.*; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import java.io.PrintWriter; import java.io.StringWriter; /** * Created by heaven7 on 2015/12/24. */ public class AndroidDatabindingDialog extends DialogWrapper { private static final String INDENT_SPACE = "{http://xml.apache.org/xslt}indent-amount"; private static final String sXmlns = "http://schemas.android.com/heaven7/android-databinding/1"; private static final String sXmlInstance = "http://www.w3.org/2001/XMLSchema-instance"; private static final String sVersion = "1.0"; private JPanel panel1; private JTextField db_TextField; private final VirtualFile mDir; private final Project mProject; public AndroidDatabindingDialog(@Nullable Project project, VirtualFile dir) { super(project); this.mDir = dir; this.mProject = project; setTitle("Android-databinding config"); setResizable(false); init(); } @Override public void show() { try { super.show(); } catch (Exception e) { e.printStackTrace(); } } @Nullable @Override protected JComponent createCenterPanel() { return panel1; } @Override protected void doOKAction() { Application app = ApplicationManager.getApplication(); app.runWriteAction(new Runnable() { @Override public void run() { try { createDatabindingFile(); } catch (Exception e) { e.printStackTrace(); } } }); super.doOKAction(); } /** return true when error */ private boolean createDatabindingFile() { try{ String f = db_TextField.getText(); final String filename = (f.endsWith(".xml") ? f : f + ".xml").trim(); VirtualFile child = mDir.findChild("raw"); if (child == null) { child = mDir.createChildDirectory(null, "raw"); } VirtualFile newXmlFile = child.findChild(filename); if (newXmlFile != null && newXmlFile.exists()) { showMessageDialog("create failed!", "caused by the file is existed!"); return true; } newXmlFile = child.createChildData(null, filename); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.newDocument(); Element root = doc.createElement("DataBinding"); root.setAttribute("xmlns",sXmlns); // root.setAttribute("xmlns:xsi",sXmlInstance); root.setAttribute("version",sVersion); doc.appendChild(root); Element dataEle = doc.createElement("data"); //<variable name="user" classname="com.heaven7.databinding.demo.bean.User$df" type="bean" /> Element variable = doc.createElement("variable"); variable.setAttribute("name","user"); variable.setAttribute("classname","com.heaven7.databinding.demo.xxx$User"); variable.setAttribute("type","bean"); // <import classname="com.heaven7.databinding" alias="ddd"/> Element importEle = doc.createElement("import"); importEle.setAttribute("classname","android.view.View"); importEle.setAttribute("alias","View"); dataEle.appendChild(variable); dataEle.appendChild(importEle); root.appendChild(dataEle); PrintWriter out = new PrintWriter(newXmlFile.getOutputStream(null)); StringWriter writer = new StringWriter(); TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(INDENT_SPACE, "4"); transformer.transform(new DOMSource(doc), new StreamResult(writer)); out.println(writer.getBuffer().toString()); out.close(); }catch (Exception e){ showMessageDialog("Exception occoured", "detail : " + Util.toString(e)); return true; } return false; } private void showMessageDialog(String title, String message) { Messages.showMessageDialog( mProject, message, title, Messages.getErrorIcon()); } }
LightSun/android-databinding-plugin
<|start_filename|>locales/en-US/27-twitter.json<|end_filename|> { "twitter": { "label": { "twitter-id": "Twitter ID", "search": "Search", "for": "for", "user": "User", "dmslabel": "DMs", "followers": "followed by", "tweetslabel": "tweets", "eventslabel": "events", "create": "Create your own application at", "copy-consumer": "From the 'Keys and tokens' section, copy the Consumer API keys", "consumer_key": "API key", "consumer_secret": "API secret key", "copy-accessToken": "Create a new 'Access token & access token secret' and copy them", "access_key": "Access token", "access_secret": "Access token secret", "enter-id": "Set your Twitter ID" }, "placeholder": { "for": "comma-separated words, @ids, #tags", "user": "comma-separated @twitter handles" }, "search": { "public": "all public tweets", "follow": "all tweets from people I follow", "user": "the tweets of specific users", "direct": "your direct messages", "events": "your twitter events" }, "tip": "Tip: Use commas without spaces between multiple search terms. Comma = OR, Space = AND.<br/>The Twitter API WILL NOT deliver 100% of all tweets.<br/>Tweets of who you follow will include their retweets and favourites.<br/><br/>Leave <b>for</b> blank to set using msg.payload.", "status": { "using-geo": "Using geo location: __location__", "tweeting": "tweeting", "failed": "failed" }, "warn": { "nousers": "User option selected but no users specified", "waiting": "Waiting for search term" }, "errors": { "ratelimit": "rate limit hit", "limitrate": "limiting rate", "streamerror": "stream error: __error__ (__rc__)", "unexpectedend": "stream ended unexpectedly", "invalidtag": "invalid tag property", "missingcredentials": "missing twitter credentials", "truncated": "truncated tweet greater than 280 characters", "sendfail": "send tweet failed: __error__", "nopayload": "no payload to tweet" } } } <|start_filename|>locales/de/27-twitter.json<|end_filename|> { "twitter": { "label": { "twitter-id": "Twitter-ID", "search": "Suche", "for": "nach", "user": "Benutzer", "dmslabel": "DMs", "followers": "Verfolgt von", "tweetslabel": "Tweets", "eventslabel": "Ereignisse", "create": "Eigene Applikation erstellen auf Seite", "copy-consumer": "Consumer API keys vom 'Keys und Tokens' Abschnitt hierher kopieren", "consumer_key": "API key", "consumer_secret": "API secret key", "copy-accessToken": "Neue 'Access token & access token secret' erzeugen und hierher kopieren", "access_key": "Access token", "access_secret": "Access token secret", "enter-id": "Setze Deine Twitter-ID" }, "placeholder": { "for": "Komma-getrennte Wörter, @ids, #tags", "user": "Komma-getrennte @twitter handles" }, "search": { "public": "alle öffentlichen Tweets", "follow": "alle Tweets von Usern, denen ich folge", "user": "Tweets bestimmter User", "direct": "meine direkten Nachrichten", "events": "meine Twitter-Ereignisse" }, "tip": "Tipp: Nur Kommas ohne Leerzeichen zwischen mehreren Suchbegriffen verwenden. Komma = ODER, Leerzeichen = UND.<br/>Die Twitter-API wird nicht 100% aller Tweets liefern.<br/>Tweets von gefolgten Usern enthalten ihre Retweets und Favoriten.<br/>Das <b>nach</b>-Feld leer lassen, um es durch msg.payload setzen zu können.", "status": { "using-geo": "Benutze Geo-Lokation: __location__", "tweeting": "Tweeting", "failed": "Fehlgeschlagen" }, "warn": { "nousers": "User-Option ausgewählt, aber keine User angegeben", "waiting": "Warte auf Suchbegriff" }, "errors": { "ratelimit": "Ratenlimit erfolgt", "limitrate": "Begrenze Rate", "streamerror": "Stream-Fehler: __error__ (__rc__)", "unexpectedend": "Stream unerwartet beendet", "invalidtag": "Ungültige Tag-Eigenschaft", "missingcredentials": "Fehlende Twitter-Berechtigungen", "truncated": "Tweet abgeschnitten nach mehr als 280 Zeichen", "sendfail": "Tweet-Senden fehlgeschlagen: __error__", "nopayload": "Keine Nutzdaten (Payload) zu tweeten" } } }
mayahq/maya-red-twitter
<|start_filename|>SharpGen/CppModel/CppCallable.cs<|end_filename|> using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; namespace SharpGen.CppModel; public abstract class CppCallable : CppContainer { protected virtual CallingConvention DefaultCallingConvention => CppCallingConvention.CDecl; public CppReturnValue ReturnValue { get; set; } private CallingConvention? callingConvention; public CallingConvention CallingConvention { get => callingConvention ?? DefaultCallingConvention; set => callingConvention = value; } public IEnumerable<CppParameter> Parameters => Iterate<CppParameter>(); protected internal override IEnumerable<CppElement> AllItems => Iterate<CppElement>().Append(ReturnValue); public override string ToString() { var builder = new StringBuilder(); builder.Append(ReturnValue); builder.Append(' '); if (Parent is CppInterface) { builder.Append(Parent.Name); builder.Append("::"); } builder.Append(Name); builder.Append('('); uint i = 0; foreach (var cppParameter in Parameters) { if (i != 0) { builder.Append(", "); } builder.Append(cppParameter); i++; } builder.Append(')'); return builder.ToString(); } public string ToShortString() { var builder = new StringBuilder(); if (Parent is CppInterface) { builder.Append(Parent.Name); builder.Append("::"); } builder.Append(Name); return builder.ToString(); } protected CppCallable(string name) : base(name) { } } <|start_filename|>SharpGen.Runtime/RawBool.cs<|end_filename|> // Copyright (c) 2010-2014 SharpDX - <NAME> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Runtime.InteropServices; namespace SharpGen.Runtime; /// <summary> /// A boolean value stored on 4 bytes (instead of 1 in .NET). /// </summary> [StructLayout(LayoutKind.Sequential, Size = 4)] public readonly struct RawBool : IEquatable<RawBool> { private readonly int boolValue; public RawBool(bool boolValue) => this.boolValue = boolValue ? 1 : 0; public RawBool(int boolValue) => this.boolValue = boolValue; public RawBool(uint boolValue) => this.boolValue = (int) boolValue; public override bool Equals(object obj) => obj switch { null => false, bool b => Equals(new RawBool(b)), RawBool rawBool => Equals(rawBool), int b => Equals(new RawBool(b)), uint b => Equals(new RawBool(b)), byte b => Equals(new RawBool(b)), sbyte b => Equals(new RawBool(b)), short b => Equals(new RawBool(b)), ushort b => Equals(new RawBool(b)), long b => Equals(new RawBool((int) b)), ulong b => Equals(new RawBool((uint) b)), _ => false }; public bool Equals(RawBool other) => (boolValue != 0) == (other.boolValue != 0); public override int GetHashCode() => boolValue; public static bool operator ==(RawBool left, RawBool right) => left.Equals(right); public static bool operator !=(RawBool left, RawBool right) => !left.Equals(right); public static implicit operator bool(RawBool booleanValue) => booleanValue.boolValue != 0; public static implicit operator RawBool(bool boolValue) => new(boolValue); public static explicit operator int(RawBool booleanValue) => booleanValue.boolValue; public static explicit operator RawBool(int boolValue) => new(boolValue); public static explicit operator uint(RawBool booleanValue) => (uint) booleanValue.boolValue; public static explicit operator RawBool(uint boolValue) => new(boolValue); public override string ToString() => (boolValue != 0).ToString(); } <|start_filename|>SharpGen/Config/SdkRule.cs<|end_filename|> using System; using System.Xml.Serialization; namespace SharpGen.Config; public enum SdkLib { StdLib = 1, WindowsSdk } public static class SdkLibExtensions { public static string Name(this SdkLib lib) => lib switch { SdkLib.StdLib => "standard library", SdkLib.WindowsSdk => "Windows SDK", _ => lib.ToString() }; } public class SdkRule { public SdkRule() { } public SdkRule(SdkLib name, string version) { Name = name; Version = version; } [XmlIgnore] public SdkLib? Name { get; private set; } [XmlAttribute("name")] public string _Name_ { get => Name.ToString(); set { if (Enum.TryParse(value, out SdkLib name)) Name = name; else Name = null; } } public bool ShouldSerialize_Name_() => Name is { } name && Enum.IsDefined(typeof(SdkLib), name); [XmlAttribute("version")] public string Version { get; set; } [XmlAttribute("components")] public string Components { get; set; } } <|start_filename|>SharpGen/Generator/StatementPlatformSingleCodeGeneratorBase.cs<|end_filename|> using System.Collections.Generic; using Microsoft.CodeAnalysis.CSharp.Syntax; using SharpGen.Model; namespace SharpGen.Generator; internal abstract class StatementPlatformSingleCodeGeneratorBase<T> : StatementCodeGeneratorBase<T>, IPlatformSingleCodeGenerator<T, StatementSyntax> where T : CsBase { protected StatementPlatformSingleCodeGeneratorBase(Ioc ioc) : base(ioc) { } public abstract IEnumerable<PlatformDetectionType> GetPlatforms(T csElement); public abstract StatementSyntax GenerateCode(T csElement, PlatformDetectionType platform); } <|start_filename|>SharpGen/Generator/FieldCodeGenerator.cs<|end_filename|> using System.Collections.Generic; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using SharpGen.Model; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; namespace SharpGen.Generator; internal sealed partial class FieldCodeGenerator : MemberMultiCodeGeneratorBase<CsField> { private readonly bool explicitLayout; public FieldCodeGenerator(Ioc ioc, bool explicitLayout) : base(ioc) { this.explicitLayout = explicitLayout; } public override IEnumerable<MemberDeclarationSyntax> GenerateCode(CsField csElement) { if (csElement.IsBoolToInt && !csElement.IsArray) { yield return GenerateBackingField(csElement, csElement.MarshalType); yield return GenerateProperty( csElement, PredefinedType(Token(SyntaxKind.BoolKeyword)), GeneratorHelpers.GenerateIntToBoolConversion, (_, value) => GeneratorHelpers.CastExpression( ParseTypeName(csElement.MarshalType.QualifiedName), GeneratorHelpers.GenerateBoolToIntConversion(value) ) ); } else if (csElement.IsArray && !csElement.IsString) { var elementType = ParseTypeName(csElement.PublicType.QualifiedName); yield return GenerateBackingField(csElement, csElement.PublicType, isArray: true); yield return GenerateProperty( csElement, ArrayType(elementType, SingletonList(ArrayRankSpecifier())), value => AssignmentExpression( SyntaxKind.CoalesceAssignmentExpression, value, ObjectCreationExpression( ArrayType( elementType, SingletonList( ArrayRankSpecifier( SingletonSeparatedList<ExpressionSyntax>( LiteralExpression( SyntaxKind.NumericLiteralExpression, Literal(csElement.ArrayDimensionValue) ) ) ) ) ) ) ), null ); } else if (csElement.IsBitField) { PropertyValueGetTransform getterTransform; PropertyValueSetTransform setterTransform; TypeSyntax propertyType; if (csElement.IsBoolBitField) { getterTransform = GeneratorHelpers.GenerateIntToBoolConversion; setterTransform = (_, value) => GeneratorHelpers.GenerateBoolToIntConversion(value); propertyType = PredefinedType(Token(SyntaxKind.BoolKeyword)); } else { getterTransform = valueExpression => GeneratorHelpers.CastExpression( ParseTypeName(csElement.PublicType.QualifiedName), valueExpression ); setterTransform = null; propertyType = ParseTypeName(csElement.PublicType.QualifiedName); } yield return GenerateBackingField(csElement, csElement.PublicType); var bitMask = LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(csElement.BitMask)); var bitOffset = LiteralExpression( SyntaxKind.NumericLiteralExpression, Literal(csElement.BitOffset) ); yield return GenerateProperty( csElement, propertyType, Compose( getterTransform, value => BinaryExpression( SyntaxKind.BitwiseAndExpression, GeneratorHelpers.WrapInParentheses( BinaryExpression(SyntaxKind.RightShiftExpression, value, bitOffset) ), bitMask ) ), Compose( (oldValue, value) => GeneratorHelpers.CastExpression( ParseTypeName(csElement.PublicType.QualifiedName), BinaryExpression( SyntaxKind.BitwiseOrExpression, GeneratorHelpers.WrapInParentheses( BinaryExpression( SyntaxKind.BitwiseAndExpression, oldValue, PrefixUnaryExpression( SyntaxKind.BitwiseNotExpression, GeneratorHelpers.WrapInParentheses( BinaryExpression(SyntaxKind.LeftShiftExpression, bitMask, bitOffset) ) ) ) ), GeneratorHelpers.WrapInParentheses( BinaryExpression( SyntaxKind.LeftShiftExpression, GeneratorHelpers.WrapInParentheses( BinaryExpression(SyntaxKind.BitwiseAndExpression, value, bitMask) ), bitOffset ) ) ) ), setterTransform ) ); } else { yield return GenerateBackingField( csElement, csElement.PublicType, propertyBacking: false, document: true ); } } private MemberDeclarationSyntax GenerateBackingField(CsField field, CsTypeBase backingType, bool isArray = false, bool propertyBacking = true, bool document = false) { var elementType = ParseTypeName(backingType.QualifiedName); var fieldDecl = FieldDeclaration( VariableDeclaration( isArray ? ArrayType(elementType, SingletonList(ArrayRankSpecifier())) : elementType, SingletonSeparatedList( VariableDeclarator(propertyBacking ? field.IntermediateMarshalName : field.Name) ) ) ) .WithModifiers( propertyBacking ? TokenList(Token(SyntaxKind.InternalKeyword)) : field.VisibilityTokenList ); if (explicitLayout) fieldDecl = AddFieldOffsetAttribute(fieldDecl, field.Offset); return document ? AddDocumentationTrivia(fieldDecl, field) : fieldDecl; } } <|start_filename|>SharpGenTools.Sdk/Extensibility/ExtensionFileReference.cs<|end_filename|> // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable enable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Reflection; using System.Reflection.Metadata; using System.Reflection.PortableExecutable; using System.Runtime.CompilerServices; using System.Threading; using Microsoft.CodeAnalysis; using SharpGen.Doc; using SharpGenTools.Sdk.Internal; using SharpGenTools.Sdk.Internal.Roslyn; namespace SharpGenTools.Sdk.Extensibility; /// <summary> /// Represents analyzers stored in an analyzer assembly file. /// </summary> /// <remarks> /// Analyzer are read from the file, owned by the reference, and doesn't change /// since the reference is accessed until the reference object is garbage collected. /// </remarks> internal sealed class ExtensionFileReference : ExtensionReference, IEquatable<ExtensionReference> { private const string DotDelimiterString = "."; private static readonly string DocProviderNamespace = typeof(IDocProvider).Namespace!; private const string DocProviderName = nameof(IDocProvider); private delegate bool ExtensionPredicate(ModuleMetadata module, InterfaceImplementation interfaceImpl); public override string FullPath { get; } private readonly Extensions<IDocProvider> _docProviders; private string? _lazyDisplay; private object? _lazyIdentity; private Assembly? _lazyAssembly; public event EventHandler<ExtensionLoadFailureEventArgs>? AnalyzerLoadFailed; /// <summary> /// Creates an ExtensionFileReference with the given <paramref name="fullPath"/> and <paramref name="assemblyLoader"/>. /// </summary> /// <param name="fullPath">Full path of the analyzer assembly.</param> /// <param name="assemblyLoader">Loader for obtaining the <see cref="Assembly"/> from the <paramref name="fullPath"/></param> public ExtensionFileReference(string fullPath, ExtensibilityAssemblyLoader assemblyLoader) { Utilities.RequireAbsolutePath(fullPath, nameof(fullPath)); FullPath = fullPath; AssemblyLoader = assemblyLoader ?? throw new ArgumentNullException(nameof(assemblyLoader)); _docProviders = new Extensions<IDocProvider>(this, IsDocProviderPredicate); // Note this analyzer full path as a dependency location, so that the analyzer loader // can correctly load analyzer dependencies. assemblyLoader.AddDependencyLocation(fullPath); } public ExtensibilityAssemblyLoader AssemblyLoader { get; } public override bool Equals(object? obj) => Equals(obj as ExtensionFileReference); public bool Equals(ExtensionFileReference? other) { if (ReferenceEquals(this, other)) return true; return other != null && ReferenceEquals(AssemblyLoader, other.AssemblyLoader) && FullPath == other.FullPath; } // legacy, for backwards compat: public bool Equals(ExtensionReference? other) { if (ReferenceEquals(this, other)) return true; return other switch { null => false, ExtensionFileReference fileReference => Equals(fileReference), _ => FullPath == other.FullPath }; } public override int GetHashCode() => HashCode.Combine(RuntimeHelpers.GetHashCode(AssemblyLoader), FullPath.GetHashCode()); public override ImmutableArray<IDocProvider> GetDocumentationProviders() { return _docProviders.GetExtensionsForAllLanguages(); } public override string Display { get { if (_lazyDisplay == null) { InitializeDisplayAndId(); } return _lazyDisplay; } } public override object Id { get { if (_lazyIdentity == null) { InitializeDisplayAndId(); } return _lazyIdentity; } } [MemberNotNull(nameof(_lazyIdentity), nameof(_lazyDisplay))] private void InitializeDisplayAndId() { try { // AssemblyName.GetAssemblyName(path) is not available on CoreCLR. // Use our metadata reader to do the equivalent thing. using var reader = new PEReader(Utilities.OpenRead(FullPath)); var metadataReader = reader.GetMetadataReader(); var assemblyIdentity = ReadAssemblyIdentityOrThrow(metadataReader); _lazyDisplay = assemblyIdentity.Name; _lazyIdentity = assemblyIdentity; } catch { _lazyDisplay = FileNameUtilities.GetFileName(FullPath, false); _lazyIdentity = _lazyDisplay; } } /// <exception cref="BadImageFormatException">An exception from metadata reader.</exception> private static AssemblyIdentity ReadAssemblyIdentityOrThrow(MetadataReader reader) { var assemblyDef = reader.GetAssemblyDefinition(); return CreateAssemblyIdentityOrThrow(reader, assemblyDef.Version, assemblyDef.Flags, assemblyDef.PublicKey, assemblyDef.Name, assemblyDef.Culture, false); } /// <exception cref="BadImageFormatException">An exception from metadata reader.</exception> private static AssemblyIdentity CreateAssemblyIdentityOrThrow( MetadataReader reader, Version version, AssemblyFlags flags, BlobHandle publicKey, StringHandle name, StringHandle culture, bool isReference) { string nameStr = reader.GetString(name); var cultureName = culture.IsNil ? null : reader.GetString(culture); var publicKeyOrToken = reader.GetBlobContent(publicKey); bool hasPublicKey; if (isReference) { hasPublicKey = (flags & AssemblyFlags.PublicKey) != 0; } else { // Assembly definitions never contain a public key token, they only can have a full key or nothing, // so the flag AssemblyFlags.PublicKey does not make sense for them and is ignored. // See Ecma-335, Partition II Metadata, 22.2 "Assembly : 0x20". // This also corresponds to the behavior of the native C# compiler and sn.exe tool. hasPublicKey = !publicKeyOrToken.IsEmpty; } if (publicKeyOrToken.IsEmpty) { publicKeyOrToken = default; } return new AssemblyIdentity( nameStr, version, cultureName, publicKeyOrToken, hasPublicKey, (flags & AssemblyFlags.Retargetable) != 0, (AssemblyContentType) ((int) (flags & AssemblyFlags.ContentTypeMask) >> 9)); } /// <summary> /// Adds the <see cref="ImmutableArray{T}"/> of <see cref="IDocProvider"/> defined in this assembly reference. /// </summary> internal void AddDocumentationProviders(ImmutableArray<IDocProvider>.Builder builder) { _docProviders.AddExtensions(builder); } private static ExtensionLoadFailureEventArgs CreateExtensionLoadFailedArgs(Exception e, string? typeNameOpt = null) { // unwrap: e = e as TargetInvocationException ?? e; // remove all line breaks from the exception message string message = e.Message.Replace("\r", string.Empty).Replace("\n", string.Empty); var errorCode = typeNameOpt != null ? ExtensionLoadFailureEventArgs.FailureErrorCode.UnableToCreateExtension : ExtensionLoadFailureEventArgs.FailureErrorCode.UnableToLoadExtension; return new ExtensionLoadFailureEventArgs(errorCode, message, e, typeNameOpt); } /// <summary> /// Opens the analyzer dll with the metadata reader and builds a map of language -> analyzer type names. /// </summary> /// <exception cref="BadImageFormatException">The PE image format is invalid.</exception> /// <exception cref="IOException">IO error reading the metadata.</exception> private static ImmutableHashSet<string> GetAnalyzerTypeNameMap(string fullPath, ExtensionPredicate extensionPredicate) { using var assembly = AssemblyMetadata.CreateFromFile(fullPath); // This is longer than strictly necessary to avoid thrashing the GC with string allocations // in the call to GetFullyQualifiedTypeNames. Specifically, this checks for the presence of // supported languages prior to creating the type names. return (from module in assembly.GetModules() from typeDefHandle in module.GetMetadataReader().TypeDefinitions let typeDef = module.GetMetadataReader().GetTypeDefinition(typeDefHandle) where GetSupportedLanguages(typeDef, module, extensionPredicate) select GetFullyQualifiedTypeName(typeDef, module)).ToImmutableHashSet(); } private static bool GetSupportedLanguages(TypeDefinition typeDef, ModuleMetadata module, ExtensionPredicate extensionPredicate) => typeDef.GetInterfaceImplementations() .Select(x => module.GetMetadataReader().GetInterfaceImplementation(x)) .Any(customAttrHandle => extensionPredicate(module, customAttrHandle)); private static bool IsDocProviderPredicate(ModuleMetadata module, InterfaceImplementation interfaceImpl) { if (!GetTypeNamespaceAndName(module.GetMetadataReader(), interfaceImpl.Interface, out var namespaceHandle, out var nameHandle)) return false; var comparer = module.GetMetadataReader().StringComparer; return comparer.Equals(nameHandle, DocProviderName) && comparer.Equals(namespaceHandle, DocProviderNamespace); } /// <summary> /// Given a token for a type, return the type's name and namespace. Only works for top level types. /// namespaceHandle will be NamespaceDefinitionHandle for defs and StringHandle for refs. /// </summary> /// <returns>True if the function successfully returns the name and namespace.</returns> private static bool GetTypeNamespaceAndName(MetadataReader metadataReader, EntityHandle typeDefOrRef, out StringHandle namespaceHandle, out StringHandle nameHandle) { nameHandle = default; namespaceHandle = default; try { return typeDefOrRef.Kind switch { HandleKind.TypeReference => GetTypeRefNamespaceAndName( (TypeReferenceHandle) typeDefOrRef, ref namespaceHandle, ref nameHandle ), HandleKind.TypeDefinition => GetTypeDefNamespaceAndName( (TypeDefinitionHandle) typeDefOrRef, ref namespaceHandle, ref nameHandle ), _ => false }; } catch (BadImageFormatException) { return false; } bool GetTypeDefNamespaceAndName(TypeDefinitionHandle typeDefHandle, ref StringHandle namespaceHandle, ref StringHandle nameHandle) { var def = metadataReader.GetTypeDefinition(typeDefHandle); if (IsNested(def.Attributes)) { // TODO - Support nested types. return false; } nameHandle = def.Name; namespaceHandle = def.Namespace; return true; static bool IsNested(TypeAttributes flags) => (flags & TypeAttributes.NestedFamANDAssem) != 0; } bool GetTypeRefNamespaceAndName(TypeReferenceHandle typeRefHandle, ref StringHandle namespaceHandle, ref StringHandle nameHandle) { var typeRefRow = metadataReader.GetTypeReference(typeRefHandle); var handleType = typeRefRow.ResolutionScope.Kind; if (handleType == HandleKind.TypeReference || handleType == HandleKind.TypeDefinition) { // TODO - Support nested types. return false; } nameHandle = typeRefRow.Name; namespaceHandle = typeRefRow.Namespace; return true; } } private static string GetFullyQualifiedTypeName(TypeDefinition typeDef, ModuleMetadata module) { var declaringType = typeDef.GetDeclaringType(); // Non nested type - simply get the full name if (declaringType.IsNil) return GetFullNameOrThrow(module, typeDef.Namespace, typeDef.Name); var declaringTypeDef = module.GetMetadataReader().GetTypeDefinition(declaringType); return GetFullyQualifiedTypeName(declaringTypeDef, module) + "+" + module.GetMetadataReader().GetString(typeDef.Name); } /// <exception cref="BadImageFormatException">An exception from metadata reader.</exception> private static string GetFullNameOrThrow(ModuleMetadata module, StringHandle namespaceHandle, StringHandle nameHandle) { var attributeTypeName = module.GetMetadataReader().GetString(nameHandle); var attributeTypeNamespaceName = module.GetMetadataReader().GetString(namespaceHandle); return BuildQualifiedName(attributeTypeNamespaceName, attributeTypeName); static string BuildQualifiedName(string qualifier, string name) { Debug.Assert(name != null); return string.IsNullOrEmpty(qualifier) ? name! : string.Concat(qualifier, DotDelimiterString, name); } } private sealed class Extensions<TExtension> where TExtension : class { private readonly ExtensionFileReference _reference; private readonly ExtensionPredicate _extensionPredicate; private ImmutableArray<TExtension> _lazyAllExtensions; private ImmutableHashSet<string>? _lazyExtensionTypeNameMap; internal Extensions(ExtensionFileReference reference, ExtensionPredicate extensionPredicate) { _reference = reference; _extensionPredicate = extensionPredicate; _lazyAllExtensions = default; } internal ImmutableArray<TExtension> GetExtensionsForAllLanguages() { if (_lazyAllExtensions.IsDefault) { ImmutableInterlocked.InterlockedInitialize(ref _lazyAllExtensions, CreateExtensionsForAllLanguages(this)); } return _lazyAllExtensions; } private static ImmutableArray<TExtension> CreateExtensionsForAllLanguages(Extensions<TExtension> extensions) { // Get all analyzers in the assembly. var builder = ImmutableArray.CreateBuilder<TExtension>(); extensions.AddExtensions(builder); return builder.ToImmutable(); } internal ImmutableHashSet<string> GetExtensionTypeNameMap() { if (_lazyExtensionTypeNameMap == null) { var analyzerTypeNameMap = GetAnalyzerTypeNameMap(_reference.FullPath, _extensionPredicate); Interlocked.CompareExchange(ref _lazyExtensionTypeNameMap, analyzerTypeNameMap, null); } return _lazyExtensionTypeNameMap; } internal void AddExtensions(ImmutableArray<TExtension>.Builder builder) { ImmutableHashSet<string> analyzerTypeNameMap; Assembly analyzerAssembly; try { analyzerTypeNameMap = GetExtensionTypeNameMap(); if (analyzerTypeNameMap.Count == 0) { return; } analyzerAssembly = _reference.GetAssembly(); } catch (Exception e) { _reference.AnalyzerLoadFailed?.Invoke(_reference, CreateExtensionLoadFailedArgs(e)); return; } var initialCount = builder.Count; var reportedError = false; GetAnalyzersForTypeNames(analyzerAssembly, analyzerTypeNameMap, builder, ref reportedError); // If there were types implementing TExtension but couldn't be cast to TExtension, generate a diagnostic. // If we've reported errors already while trying to instantiate types, don't complain. if (builder.Count == initialCount && !reportedError) { _reference.AnalyzerLoadFailed?.Invoke( _reference, new ExtensionLoadFailureEventArgs( ExtensionLoadFailureEventArgs.FailureErrorCode.InternalExtensionEntryPointCastError, "Internal extensibility error: extension entry point cannot be casted to a target extension type" ) ); } } private void GetAnalyzersForTypeNames(Assembly analyzerAssembly, IEnumerable<string> analyzerTypeNames, ImmutableArray<TExtension>.Builder builder, ref bool reportedError) { // Given the type names, get the actual System.Type and try to create an instance of the type through reflection. foreach (var typeName in analyzerTypeNames) { Type? type; try { type = analyzerAssembly.GetType(typeName, true, false); } catch (Exception e) { _reference.AnalyzerLoadFailed?.Invoke(_reference, CreateExtensionLoadFailedArgs(e, typeName)); reportedError = true; continue; } Debug.Assert(type != null); TExtension? analyzer; try { analyzer = Activator.CreateInstance(type) as TExtension; } catch (Exception e) { _reference.AnalyzerLoadFailed?.Invoke(_reference, CreateExtensionLoadFailedArgs(e, typeName)); reportedError = true; continue; } if (analyzer != null) { builder.Add(analyzer); } } } } public Assembly GetAssembly() { if (_lazyAssembly == null) { _lazyAssembly = AssemblyLoader.LoadFromPath(FullPath); } return _lazyAssembly; } } <|start_filename|>SharpGen/Doc/IDocProvider.cs<|end_filename|> // Copyright (c) 2010-2014 SharpDX - <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. #nullable enable using System.Threading.Tasks; namespace SharpGen.Doc; /// <summary> /// An <see cref="IDocProvider"/> implementation is responsible to provide documentation to the Parser /// in order to feed each C++ element with an associated documentation. /// This is optional. /// A client of Parser API could provide a documentation provider /// in an external assembly. /// </summary> public interface IDocProvider { /// <summary> /// Finds the documentation for a particular C++ item. /// </summary> /// <param name="fullName"> /// The full name. /// For top level elements (like struct, interfaces, enums, functions), it's the name of the element itself. /// For nested elements (like interface methods), the name is of the following format: "IMyInterface::MyMethod". /// </param> /// <param name="context">Environment for documenting, used to create items and subitems</param> /// <returns>Non-null documentation item container created by <see cref="IDocumentationContext"/></returns> Task<IFindDocumentationResult> FindDocumentationAsync(string fullName, IDocumentationContext context); /// <summary> /// If true, any exception thrown, or any error logged by this provider will cause the build to fail. /// </summary> /// <remarks> /// For providers that rely on unstable factors (networking), it is recommended to set this to <c>false</c>. /// However, the default choice should be <c>true</c>. /// </remarks> bool TreatFailuresAsErrors { get; } /// <summary> /// Name of the documentation provider to be presented to user when needed. /// </summary> /// <remarks> /// Short version. Without words like "documentation provider" or "extension". /// </remarks> string UserFriendlyName { get; } } <|start_filename|>SharpGen/BuiltinType.cs<|end_filename|> namespace SharpGen; public enum BuiltinType { Marshal, Math, Unsafe, Span, GCHandle, Delegate, FlagsAttribute, GC, IntPtr, UIntPtr, GuidAttribute, StructLayoutAttribute, PlatformNotSupportedException, UnmanagedFunctionPointerAttribute, UnmanagedCallersOnlyAttribute, Guid, } <|start_filename|>SharpGen.Runtime/CallbackBase.ReflectionImpl.cs<|end_filename|> #nullable enable using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; namespace SharpGen.Runtime; public abstract unsafe partial class CallbackBase { protected virtual Guid[] BuildGuidList() => GetTypeInfo().Guids; private GCHandle CreateShadow(TypeInfo type) { var shadow = (CppObjectShadow) Activator.CreateInstance(type.AsType()); // Initialize the shadow with the callback shadow.Initialize(ThisHandle); return GCHandle.Alloc(shadow, GCHandleType.Normal); } protected virtual void InitializeCallableWrappers(IDictionary<Guid, IntPtr> ccw) { // Associate all shadows with their interfaces. var typeInfo = GetTypeInfo(); var interfaces = typeInfo.Vtbls; if (interfaces.Length == 0) return; // Lazy solution: a single shadow for the whole hierarchy. // There are limitations to this approach in multi-inheritance scenarios, // when there are multiple shadows inheriting one, and they are in separate vtbl trees. // Then ToShadow methods. var shadowTypes = typeInfo.Shadows; var shadowHandle = shadowTypes.Length switch { 0 => ThisHandle, 1 => CreateShadow(shadowTypes[0]), _ => CreateMultiInheritanceShadow(shadowTypes.Select(CreateShadow).ToArray()) }; foreach (var item in interfaces) { Debug.Assert(VtblAttribute.Has(item.Type)); var success = TypeDataStorage.GetTargetVtbl(item.Type, out var vtbl); Debug.Assert(success); var wrapper = CreateCallableWrapper(vtbl, shadowHandle); ccw[item.Type.GUID] = wrapper; // Associate also inherited interface to this shadow foreach (var inheritInterface in item.ImplementedInterfaces) { var guid = inheritInterface.GUID; // If we have the same GUID as an already added interface, // then there's already an accurate shadow for it, so we have nothing to do. if (ccw.ContainsKey(guid)) continue; // Use same CCW as derived ccw[guid] = wrapper; } } } } <|start_filename|>SharpGenTools.Sdk/Documentation/DocumentationProviderFailedException.cs<|end_filename|> using System; using System.Runtime.Serialization; namespace SharpGenTools.Sdk.Documentation; internal sealed class DocumentationProviderFailedException : Exception { public DocumentationProviderFailedException() { } public DocumentationProviderFailedException(string message) : base(message) { } public DocumentationProviderFailedException(string message, Exception innerException) : base(message, innerException) { } public DocumentationProviderFailedException(SerializationInfo info, StreamingContext context) : base(info, context) { } } <|start_filename|>SharpGen/Doc/IDocMutableItem.cs<|end_filename|> namespace SharpGen.Doc; public interface IDocMutableItem { bool IsDirty { get; set; } } <|start_filename|>SharpGen.Runtime/COM/WinRTObject.cs<|end_filename|> using System; using System.Runtime.InteropServices; using SharpGen.Runtime.Win32; namespace SharpGen.Runtime; /// <unmanaged>IInspectable</unmanaged> /// <unmanaged-short>IInspectable</unmanaged-short> [Guid("AF86E2E0-B12D-4c6a-9C5A-D7AA65101E90")] public class WinRTObject : ComObject, IInspectable { public WinRTObject(IntPtr nativePtr): base(nativePtr) { } public static explicit operator WinRTObject(IntPtr nativePtr) => nativePtr == IntPtr.Zero ? null : new WinRTObject(nativePtr); /// <unmanaged>HRESULT IInspectable::GetTrustLevel([Out] TrustLevel* trustLevel)</unmanaged> /// <unmanaged-short>IInspectable::GetTrustLevel</unmanaged-short> private TrustLevel TrustLevel { get => GetTrustLevel(); } /// <unmanaged>HRESULT IInspectable::GetIids([Out] ULONG* iidCount, [Out, Buffer, Optional] GUID** iids)</unmanaged> /// <unmanaged-short>IInspectable::GetIids</unmanaged-short> private unsafe void GetIids(out uint iidCount, out IntPtr iids) { Result __result__; fixed (void* iids_ = &iids) fixed (void* iidCount_ = &iidCount) __result__ = ((delegate* unmanaged[Stdcall]<IntPtr, void*, void*, int> )this[3U])(NativePointer, iidCount_, iids_); __result__.CheckError(); } /// <unmanaged>HRESULT IInspectable::GetRuntimeClassName([Out] HSTRING* className)</unmanaged> /// <unmanaged-short>IInspectable::GetRuntimeClassName</unmanaged-short> private unsafe IntPtr GetRuntimeClassName() { IntPtr className; Result __result__; __result__ = ((delegate* unmanaged[Stdcall]<IntPtr, void*, int> )this[4U])(NativePointer, &className); __result__.CheckError(); return className; } /// <unmanaged>HRESULT IInspectable::GetTrustLevel([Out] TrustLevel* trustLevel)</unmanaged> /// <unmanaged-short>IInspectable::GetTrustLevel</unmanaged-short> private unsafe TrustLevel GetTrustLevel() { TrustLevel trustLevel; Result __result__; __result__ = ((delegate* unmanaged[Stdcall]<IntPtr, void*, int> )this[5U])(NativePointer, &trustLevel); __result__.CheckError(); return trustLevel; } public Guid[] Iids { get { GetIids(out var count, out var iids); var iid = new Guid[count]; MemoryHelpers.Read<Guid>(iids, iid, (int) count); Marshal.FreeCoTaskMem(iids); return iid; } } public string RuntimeClassName { get { var nativeStringPtr = GetRuntimeClassName(); using WinRTString nativeString = new(nativeStringPtr); return nativeString.Value; } } } <|start_filename|>SharpGen.UnitTests/XUnitLogger.cs<|end_filename|> using System; using System.Collections.Generic; using SharpGen.Logging; using Xunit; using Xunit.Abstractions; namespace SharpGen.UnitTests; internal sealed class XUnitLogger : ILogger { private readonly ITestOutputHelper output; public XUnitLogger(ITestOutputHelper output) { this.output = output; } public List<XUnitLogEvent> MessageLog { get; } = new List<XUnitLogEvent>(); public void Exit(string reason, int exitCode) { Assert.False(true, "SharpGen failed to run"); // Fail the test } public void Log(LogLevel logLevel, LogLocation logLocation, string context, string code, string message, Exception exception, params object[] parameters) { var lineMessage = LogUtilities.FormatMessage(logLevel, logLocation, context, message, exception, parameters); MessageLog.Add(new XUnitLogEvent(code, lineMessage, exception, logLevel)); output.WriteLine(lineMessage); if (exception != null) output.WriteLine(exception.ToString()); } } <|start_filename|>SharpGen/Generator/StatementSingleCodeGeneratorBase.cs<|end_filename|> using Microsoft.CodeAnalysis.CSharp.Syntax; using SharpGen.Model; namespace SharpGen.Generator; internal abstract class StatementSingleCodeGeneratorBase<T> : StatementCodeGeneratorBase<T>, ISingleCodeGenerator<T, StatementSyntax> where T : CsBase { protected StatementSingleCodeGeneratorBase(Ioc ioc) : base(ioc) { } public abstract StatementSyntax GenerateCode(T csElement); } <|start_filename|>SharpGen/Generator/DefaultGenerators.cs<|end_filename|> using SharpGen.Model; namespace SharpGen.Generator; public sealed class DefaultGenerators : IGeneratorRegistry { public DefaultGenerators(Ioc ioc) { ExpressionConstant = new ExpressionConstantCodeGenerator(ioc); GuidConstant = new GuidConstantCodeGenerator(ioc); ResultConstant = new ResultConstantCodeGenerator(ioc); ResultRegistration = new ResultRegistrationCodeGenerator(ioc); Property = new PropertyCodeGenerator(ioc); Enum = new EnumCodeGenerator(ioc); ExplicitOffsetField = new FieldCodeGenerator(ioc, true); AutoLayoutField = new FieldCodeGenerator(ioc, false); Struct = new StructCodeGenerator(ioc); NativeStruct = new NativeStructCodeGenerator(ioc); NativeInvocation = new NativeInvocationCodeGenerator(ioc); Callable = new CallableCodeGenerator(ioc); Method = new MethodCodeGenerator(ioc); Function = new FunctionCodeGenerator(ioc); FunctionImport = new FunctionImportCodeGenerator(ioc); Interface = new InterfaceCodeGenerator(ioc); Group = new GroupCodeGenerator(ioc); ShadowCallable = new ShadowCallbackGenerator(ioc); ReverseCallableProlog = new ReverseCallablePrologCodeGenerator(ioc); Vtbl = new VtblGenerator(ioc); Marshalling = new MarshallingRegistry(ioc); Config = ioc.GeneratorConfig; } public IMemberCodeGenerator<CsExpressionConstant> ExpressionConstant { get; } public IMemberCodeGenerator<CsGuidConstant> GuidConstant { get; } public IMemberCodeGenerator<CsResultConstant> ResultConstant { get; } public IStatementCodeGenerator<CsResultConstant> ResultRegistration { get; } public IMemberCodeGenerator<CsProperty> Property { get; } public IMemberCodeGenerator<CsEnum> Enum { get; } public IMemberCodeGenerator<CsStruct> NativeStruct { get; } public IMemberCodeGenerator<CsField> ExplicitOffsetField { get; } public IMemberCodeGenerator<CsField> AutoLayoutField { get; } public IMemberCodeGenerator<CsStruct> Struct { get; } public IStatementCodeGenerator<CsCallable> NativeInvocation { get; } public IMemberCodeGenerator<CsCallable> Callable { get; } public IMemberCodeGenerator<CsMethod> Method { get; } public IMemberCodeGenerator<CsFunction> Function { get; } public IMemberCodeGenerator<CsFunction> FunctionImport { get; } public IMemberCodeGenerator<CsInterface> Interface { get; } public IMemberCodeGenerator<CsInterface> Vtbl { get; } public IMemberCodeGenerator<CsCallable> ShadowCallable { get; } public IStatementCodeGenerator<CsCallable> ReverseCallableProlog { get; } public IMemberCodeGenerator<CsGroup> Group { get; } public MarshallingRegistry Marshalling { get; } public GeneratorConfig Config { get; } } <|start_filename|>SharpGen/Generator/StatementPlatformMultiCodeGeneratorBase.cs<|end_filename|> using System.Collections.Generic; using Microsoft.CodeAnalysis.CSharp.Syntax; using SharpGen.Model; namespace SharpGen.Generator; internal abstract class StatementPlatformMultiCodeGeneratorBase<T> : StatementCodeGeneratorBase<T>, IPlatformMultiCodeGenerator<T, StatementSyntax> where T : CsBase { protected StatementPlatformMultiCodeGeneratorBase(Ioc ioc) : base(ioc) { } public abstract IEnumerable<PlatformDetectionType> GetPlatforms(T csElement); public abstract IEnumerable<StatementSyntax> GenerateCode(T csElement, PlatformDetectionType platform); } <|start_filename|>SharpGen/VisualStudioSetup/InstanceState.cs<|end_filename|> using System; namespace SharpGen.VisualStudioSetup; [Flags] public enum InstanceState : uint { None = 0, Local = 1, Registered = 2, NoRebootRequired = 4, NoErrors = 8, Complete = unchecked((uint)-1), } <|start_filename|>SharpGen/Config/StringMarshalType.cs<|end_filename|> using System.Xml.Serialization; namespace SharpGen.Config; public enum StringMarshalType : byte { [XmlEnum("hglobal")] GlobalHeap, [XmlEnum("com")] ComTaskAllocator, [XmlEnum("bstr")] BinaryString, [XmlEnum("hstring")] WindowsRuntimeString, } <|start_filename|>SharpGen/Transform/TransformManager.cs<|end_filename|> // Copyright (c) 2010-2014 SharpDX - <NAME> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Collections.Generic; using System.IO; using System.Linq; using SharpGen.Config; using SharpGen.CppModel; using SharpGen.Logging; using SharpGen.Model; namespace SharpGen.Transform; /// <summary> /// This class is responsible for generating the C# model from C++ model. /// </summary> public sealed class TransformManager { private IDocumentationLinker DocLinker => ioc.DocumentationLinker; private TypeRegistry TypeRegistry => ioc.TypeRegistry; private Logger Logger => ioc.Logger; private NamespaceRegistry NamespaceRegistry { get; } private readonly HashSet<string> includesToProcess = new(StringComparer.InvariantCultureIgnoreCase); private readonly ConstantManager constantManager; private readonly GroupRegistry groupRegistry = new(); private readonly Ioc ioc; /// <summary> /// Initializes a new instance of the <see cref="TransformManager"/> class. /// </summary> public TransformManager(NamingRulesManager namingRules, ConstantManager constantManager, Ioc ioc) { NamingRules = namingRules; this.constantManager = constantManager; this.ioc = ioc ?? throw new ArgumentNullException(nameof(ioc)); NamespaceRegistry = new NamespaceRegistry(ioc); MarshalledElementFactory marshalledElementFactory = new(ioc); InteropSignatureTransform interopSignatureTransform = new(ioc); EnumTransform = new EnumTransform(namingRules, NamespaceRegistry, ioc); StructTransform = new StructTransform(namingRules, NamespaceRegistry, marshalledElementFactory, ioc); FunctionTransform = new MethodTransform(namingRules, groupRegistry, marshalledElementFactory, interopSignatureTransform, ioc); InterfaceTransform = new InterfaceTransform(namingRules, FunctionTransform, FunctionTransform, NamespaceRegistry, interopSignatureTransform, ioc); } /// <summary> /// Gets the naming rules manager. /// </summary> /// <value>The naming rules manager.</value> private NamingRulesManager NamingRules { get; } /// <summary> /// Gets or sets the enum transformer. /// </summary> /// <value>The enum transformer.</value> private EnumTransform EnumTransform { get; } /// <summary> /// Gets or sets the struct transformer. /// </summary> /// <value>The struct transformer.</value> private StructTransform StructTransform { get; } /// <summary> /// Gets or sets the method transformer. /// </summary> /// <value>The method transformer.</value> private MethodTransform FunctionTransform { get; } /// <summary> /// Gets or sets the interface transformer. /// </summary> /// <value>The interface transformer.</value> private InterfaceTransform InterfaceTransform { get; } /// <summary> /// Initializes this instance with the specified C++ module and config. /// </summary> /// <returns>The module to transform after mapping rules have been applied.</returns> private CppModule MapModule(CppModule cppModule, IReadOnlyCollection<ConfigFile> configFiles) { var numberOfConfigFilesToParse = configFiles.Count; var indexFile = 0; // Process each config file foreach (var configFile in configFiles) { Logger.Progress( 30 + (indexFile * 30) / numberOfConfigFilesToParse, "Processing mapping rules [{0}]", configFile.Id ); ProcessCppModuleWithConfig(cppModule, configFile); indexFile++; } // Strip out includes we aren't processing from transformation var moduleToTransform = new CppModule(cppModule.Name); moduleToTransform.AddRange( cppModule.Includes .Where(cppInclude => includesToProcess.Contains(cppInclude.Name)) ); return moduleToTransform; } /// <summary> /// Adds the include to process. /// </summary> /// <param name="includeId">The include id.</param> private void AddIncludeToProcess(string includeId) { includesToProcess.Add(includeId); } /// <summary> /// Process the specified config file. /// </summary> /// <param name="file">The file.</param> private void ProcessCppModuleWithConfig(CppModule cppModule, ConfigFile file) { Logger.PushLocation(file.AbsoluteFilePath); try { Logger.Message($"Process rules for config [{file.Id}] namespace [{file.Namespace}]"); var elementFinder = new CppElementFinder(cppModule); if (file.Namespace != null) { AttachIncludes(file); ProcessExtensions(elementFinder, file); } ProcessMappings(elementFinder, file); } finally { Logger.PopLocation(); } } private void UpdateNamingRules(ConfigFile file) { foreach (var namingRule in file.Naming) { if (namingRule is NamingRuleShort) NamingRules.AddShortNameRule(namingRule.Name, namingRule.Value); } } private void RegisterBindings(ConfigFile file) { foreach (var bindingRule in file.Bindings) { TypeRegistry.BindType( bindingRule.From, TypeRegistry.ImportType(bindingRule.To), string.IsNullOrEmpty(bindingRule.Marshal) ? null : TypeRegistry.ImportType(bindingRule.Marshal), bindingRule.Source ?? file.Id, bindingRule.Override ?? false ); } } private void ProcessDefines(ConfigFile file) { foreach (var defineRule in file.Extension.OfType<DefineExtensionRule>()) { CsTypeBase defineType; if (defineRule.Enum != null) { var underlyingType = string.IsNullOrWhiteSpace(defineRule.UnderlyingType) ? null : TypeRegistry.ImportPrimitiveType(defineRule.UnderlyingType); if (defineRule.SizeOf is {} size && underlyingType == null) { underlyingType = size switch { 1 => TypeRegistry.UInt8, 2 => TypeRegistry.Int16, 4 => TypeRegistry.Int32, 8 => TypeRegistry.Int64, _ => null }; } defineType = new CsEnum(null, defineRule.Enum, underlyingType); } else if (defineRule.Struct != null) { var newStruct = new CsStruct(null, defineRule.Struct); defineType = newStruct; if (defineRule.HasCustomMarshal is { } hasCustomMarshal) newStruct.HasMarshalType = hasCustomMarshal; if (defineRule.IsStaticMarshal is { } isStaticMarshal) newStruct.IsStaticMarshal = isStaticMarshal; if (defineRule.HasCustomNew is { } hasCustomNew) newStruct.HasCustomNew = hasCustomNew; if (defineRule.SizeOf is { } size) newStruct.StructSize = checked((uint) size); if (defineRule.Align is { } align) newStruct.Align = align; if (defineRule.IsNativePrimitive is { } isNativePrimitive) newStruct.IsNativePrimitive = isNativePrimitive; } else if (defineRule.Interface != null) { CsInterface iface = new(null, defineRule.Interface); if (defineRule.IsCallbackInterface is { } isCallbackInterface) iface.IsCallback = isCallbackInterface; if (defineRule.ShadowName is { } shadowName) iface.ShadowName = shadowName; if (defineRule.VtblName is { } vtblName) iface.VtblName = vtblName; if (defineRule.NativeImplementation != null) { iface.NativeImplementation = new CsInterface(null, defineRule.NativeImplementation) { IsDualCallback = true }; iface.IsCallback = true; iface.IsDualCallback = true; TypeRegistry.DefineType(iface.NativeImplementation); } defineType = iface; } else { Logger.Error(LoggingCodes.MissingElementInRule, "Invalid rule [{0}]. Requires one of enum, struct, or interface", defineRule); continue; } // Define this type TypeRegistry.DefineType(defineType); } } private void ProcessExtensions(CppElementFinder elementFinder, ConfigFile file) { // Register defined Types from <extension> tag foreach (var extensionRule in file.Extension) { switch (extensionRule) { case CreateExtensionRule { NewClass: { } newClass } createRule: { var functionGroup = CreateCsGroup(file.Namespace, newClass); if (createRule is { Visibility: { } visibility }) functionGroup.Visibility = visibility; break; } case CreateExtensionRule createRule: Logger.Error(LoggingCodes.MissingElementInRule, "Invalid rule [{0}]. Requires class", createRule); break; case ConstantRule constantRule: HandleConstantRule(elementFinder, constantRule, file.Namespace); break; case ContextRule contextRule: HandleContextRule(elementFinder, file, contextRule); break; } } } private void AttachIncludes(ConfigFile file) { // Add all includes file foreach (var includeRule in file.Includes) { var includeRuleId = includeRule.Id; if (includeRule.Attach.HasValue && includeRule.Attach.Value) { AddIncludeToProcess(includeRuleId); NamespaceRegistry.MapIncludeToNamespace(includeRuleId, includeRule.Namespace ?? file.Namespace); } else { // include will be processed if (includeRule.AttachTypes.Count > 0) AddIncludeToProcess(includeRuleId); foreach (var attachType in includeRule.AttachTypes) NamespaceRegistry.AttachTypeToNamespace($"^{attachType}$", includeRule.Namespace ?? file.Namespace); } } // Add extensions if any if (file.Extension.Count > 0) { var fileExtensionId = file.ExtensionId; AddIncludeToProcess(fileExtensionId); NamespaceRegistry.MapIncludeToNamespace(fileExtensionId, file.Namespace); } } private void ProcessMappings(CppElementFinder elementFinder, ConfigFile file) { // Perform all mappings from <mappings> tag foreach (var configRule in file.Mappings) { var ruleUsed = false; switch (configRule) { case MappingRule {Enum: { }} mappingRule: ruleUsed = elementFinder.ExecuteRule<CppEnum>(mappingRule.Enum, mappingRule); break; case MappingRule {EnumItem: { }} mappingRule: ruleUsed = elementFinder.ExecuteRule<CppEnumItem>(mappingRule.EnumItem, mappingRule); break; case MappingRule {Struct: { }} mappingRule: ruleUsed = elementFinder.ExecuteRule<CppStruct>(mappingRule.Struct, mappingRule); break; case MappingRule {Field: { }} mappingRule: ruleUsed = elementFinder.ExecuteRule<CppField>(mappingRule.Field, mappingRule); break; case MappingRule {Interface: { }} mappingRule: ruleUsed = elementFinder.ExecuteRule<CppInterface>(mappingRule.Interface, mappingRule); break; case MappingRule {Function: { }} mappingRule: ruleUsed = elementFinder.ExecuteRule<CppFunction>(mappingRule.Function, mappingRule); break; case MappingRule {Method: { }} mappingRule: ruleUsed = elementFinder.ExecuteRule<CppMethod>(mappingRule.Method, mappingRule); break; case MappingRule {Parameter: { }} mappingRule: ruleUsed = elementFinder.ExecuteRule<CppParameter>(mappingRule.Parameter, mappingRule); break; case MappingRule {Element: { }} mappingRule: ruleUsed = elementFinder.ExecuteRule<CppElement>(mappingRule.Element, mappingRule); break; case MappingRule {DocItem: { }} mappingRule: DocLinker.AddOrUpdateDocLink(mappingRule.DocItem, mappingRule.MappingNameFinal); ruleUsed = true; break; case RemoveRule {Enum: { }} removeRule: ruleUsed = RemoveElements<CppEnum>(elementFinder, removeRule.Enum); break; case RemoveRule {EnumItem: { }} removeRule: ruleUsed = RemoveElements<CppEnumItem>(elementFinder, removeRule.EnumItem); break; case RemoveRule {Struct: { }} removeRule: ruleUsed = RemoveElements<CppStruct>(elementFinder, removeRule.Struct); break; case RemoveRule {Field: { }} removeRule: ruleUsed = RemoveElements<CppField>(elementFinder, removeRule.Field); break; case RemoveRule {Interface: { }} removeRule: ruleUsed = RemoveElements<CppInterface>(elementFinder, removeRule.Interface); break; case RemoveRule {Function: { }} removeRule: ruleUsed = RemoveElements<CppFunction>(elementFinder, removeRule.Function); break; case RemoveRule {Method: { }} removeRule: ruleUsed = RemoveElements<CppMethod>(elementFinder, removeRule.Method); break; case RemoveRule {Parameter: { }} removeRule: ruleUsed = RemoveElements<CppParameter>(elementFinder, removeRule.Parameter); break; case RemoveRule {Element: { }} removeRule: ruleUsed = RemoveElements<CppElement>(elementFinder, removeRule.Element); break; case ContextRule contextRule: HandleContextRule(elementFinder, file, contextRule); ruleUsed = true; break; case MoveRule moveRule: { if (moveRule.Struct != null) StructTransform.MoveStructToInner(moveRule.Struct, moveRule.To); else if (moveRule.Method != null) InterfaceTransform.MoveMethodsToInnerInterface(moveRule.Method, moveRule.To, moveRule.Property, moveRule.Base); ruleUsed = true; break; } } if (!ruleUsed) { Logger.Warning(LoggingCodes.UnusedMappingRule, "Mapping rule [{0}] did not match any elements.", configRule); } } } private static bool RemoveElements<T>(CppElementFinder finder, string regex) where T : CppElement { var matchedAny = false; foreach (var item in finder.Find<T>(regex).ToList()) { matchedAny = true; item.RemoveFromParent(); } return matchedAny; } /// <summary> /// Handles the context rule. /// </summary> /// <param name="file">The file.</param> /// <param name="contextRule">The context rule.</param> /// <param name="moduleMapper">The C++ Module we are handling the context rule for.</param> private void HandleContextRule(CppElementFinder moduleMapper, ConfigFile file, ContextRule contextRule) { if (contextRule is ClearContextRule) moduleMapper.ClearCurrentContexts(); else { var contextIds = new List<string>(); if (!string.IsNullOrEmpty(contextRule.ContextSetId)) { var contextSet = file.FindContextSetById(contextRule.ContextSetId); if (contextSet != null) contextIds.AddRange(contextSet.Contexts); } contextIds.AddRange(contextRule.Ids); moduleMapper.AddContexts(contextIds); } } private void Init(IReadOnlyCollection<ConfigFile> configFiles) { // We have to do these steps first, otherwise we'll get undefined types for types we've mapped, which breaks the mapping. foreach (var configFile in configFiles) { Logger.RunInContext( configFile.AbsoluteFilePath, () => { // Update Naming Rules UpdateNamingRules(configFile); ProcessDefines(configFile); }); } foreach (var configFile in configFiles) { Logger.RunInContext( configFile.AbsoluteFilePath, () => { RegisterBindings(configFile); }); } } /// <summary> /// Maps all C++ types to C# /// </summary> /// <param name="cppModule">The C++ module to parse.</param> /// <param name="configFile">The config file to use to transform the C++ module into C# assemblies.</param> public (CsAssembly assembly, IEnumerable<DefineExtensionRule> consumerExtensions) Transform(CppModule cppModule, ConfigFile configFile) { Init(configFile.ConfigFilesLoaded); var moduleToTransform = MapModule(cppModule, configFile.ConfigFilesLoaded); var selectedCSharpType = new List<CsBase>(); // Prepare transform by defining/registering all types to process selectedCSharpType.AddRange(PrepareTransform(moduleToTransform, EnumTransform)); selectedCSharpType.AddRange(PrepareTransform(moduleToTransform, StructTransform)); selectedCSharpType.AddRange(PrepareTransform(moduleToTransform, InterfaceTransform)); selectedCSharpType.AddRange(PrepareTransform<CppFunction, CsFunction>(moduleToTransform, FunctionTransform)); // Transform all types Logger.Progress(65, "Transforming enums..."); ProcessTransform(EnumTransform, selectedCSharpType.OfType<CsEnum>()); Logger.Progress(70, "Transforming structs..."); ProcessTransform(StructTransform, selectedCSharpType.OfType<CsStruct>()); Logger.Progress(75, "Transforming interfaces..."); ProcessTransform(InterfaceTransform, selectedCSharpType.OfType<CsInterface>()); Logger.Progress(80, "Transforming functions..."); ProcessTransform(FunctionTransform, selectedCSharpType.OfType<CsFunction>()); CsAssembly asm = new(); foreach (var ns in NamespaceRegistry.Namespaces) { foreach (var group in ns.Classes) { constantManager.AttachConstants(group); } asm.Add(ns); } return (asm, configFile.ConfigFilesLoaded.SelectMany(file => file.Extension.OfType<DefineExtensionRule>())); } /// <summary> /// Prepares a transformer from C++ to C# model. /// </summary> /// <typeparam name="TCppElement">The C++ type of data to process</typeparam> /// <param name="transform">The transform.</param> /// <param name="typeToProcess">The type to process.</param> private IEnumerable<TCsElement> PrepareTransform<TCppElement, TCsElement>(CppModule cppModule, ITransformPreparer<TCppElement, TCsElement> transform) where TCppElement : CppElement where TCsElement : CsBase { var csElements = new List<TCsElement>(); // Predefine all structs, typedefs and interfaces foreach (var cppInclude in cppModule.Includes) { foreach (var cppItem in cppInclude.Iterate<TCppElement>()) { Logger.RunInContext( cppItem.ToString(), () => { // If already mapped, it means that there is already a predefined mapping if (TypeRegistry.FindBoundType(cppItem.Name) == null) { var csElement = transform.Prepare(cppItem); if (csElement != null) csElements.Add(csElement); } }); } } return csElements; } /// <summary> /// Processes a transformer from C++ to C# model. /// </summary> /// <typeparam name="T">The C++ type of data to process</typeparam> /// <param name="transform">The transform.</param> /// <param name="typeToProcess">The type to process.</param> private void ProcessTransform<T>(ITransformer<T> transform, IEnumerable<T> typeToProcess) where T : CsBase { foreach (var csItem in typeToProcess) { Logger.RunInContext( csItem.CppElement.ToString(), () => { transform.Process(csItem); constantManager.AttachConstants(csItem); }); } } /// <summary> /// Creates the C# class container used to group together loose elements (i.e. functions, constants). /// </summary> /// <param name="namespaceName">Name of the namespace.</param> /// <param name="className">Name of the class.</param> /// /// <returns>The C# class container</returns> private CsGroup CreateCsGroup(string namespaceName, string className) { if (className == null) throw new ArgumentNullException(nameof(className)); if (className.Contains(".")) { namespaceName = Path.GetFileNameWithoutExtension(className); className = Path.GetExtension(className).Trim('.'); } var csNameSpace = NamespaceRegistry.GetOrCreateNamespace(namespaceName); foreach (var cSharpFunctionGroup in csNameSpace.Classes) { if (cSharpFunctionGroup.Name == className) return cSharpFunctionGroup; } CsGroup group = new(className); csNameSpace.Add(group); groupRegistry.RegisterGroup(namespaceName + "." + className, group); return group; } /// <summary> /// Handles the constant rule. /// </summary> /// <param name="constantRule">The constant rule.</param> private void HandleConstantRule(CppElementFinder elementFinder, ConstantRule constantRule, string nameSpace) => constantManager.AddConstantFromMacroToCSharpType( elementFinder, constantRule.Macro ?? constantRule.Guid, constantRule.ClassName, constantRule.Type, constantRule.Name, constantRule.Value, constantRule.Visibility, nameSpace, constantRule.IsResultDescriptor ?? false ); public (IEnumerable<BindRule> bindings, IEnumerable<DefineExtensionRule> defines) GenerateTypeBindingsForConsumers() { return TypeRegistry.GetTypeBindings(); } } <|start_filename|>SharpGenTools.Sdk/SharpGenTask.InputsCache.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using SharpGenTools.Sdk.Internal; namespace SharpGenTools.Sdk; public sealed partial class SharpGenTask { private const string InputsCacheMarkerFiles = "# Files"; private const string InputsCacheMarkerEnvironmentVariables = "# Environment variables"; private readonly List<string> inputsCacheListFiles = new(); private readonly List<string> inputsCacheListEnvironmentVariables = new(); private readonly HashSet<string> inputsCacheSetFiles = new(); private readonly HashSet<string> inputsCacheSetEnvironmentVariables = new(); private readonly List<string> inputsCacheMetadataFiles = new(); private readonly List<string> inputsCacheMetadataEnvironmentVariables = new(); private bool inputsCacheImmutable; private static readonly Func<string, string> ComputeInputsCacheFileMetadataFunc = ComputeInputsCacheFileMetadata; private static readonly Func<string, string> ComputeInputsCacheEnvironmentVariableMetadataFunc = ComputeInputsCacheEnvironmentVariableMetadata; private void GenerateInputsCache() { inputsCacheImmutable = true; using CacheFile cacheFile = new(new FileInfo(InputsCache)); { using var writer = cacheFile.StreamWriter; writer.WriteLine(InputsCacheMarkerFiles); for (int i = 0, count = inputsCacheListFiles.Count; i < count; i++) { writer.Write(inputsCacheMetadataFiles[i]); writer.Write(' '); writer.WriteLine(inputsCacheListFiles[i]); } writer.WriteLine(InputsCacheMarkerEnvironmentVariables); for (int i = 0, count = inputsCacheListEnvironmentVariables.Count; i < count; i++) { writer.Write(inputsCacheListEnvironmentVariables[i]); writer.Write(' '); writer.WriteLine(inputsCacheMetadataEnvironmentVariables[i]); } } SharpGenLogger.Message( cacheFile.State switch { CacheFile.CacheState.Hit => "Input file cache is already up-to-date.", CacheFile.CacheState.Miss => "Input file cache is out-of-date.", CacheFile.CacheState.Absent => "Input file cache doesn't exist.", _ => throw new ArgumentOutOfRangeException() } ); if (cacheFile.IsWriteNeeded) cacheFile.Write(); } private static string ComputeInputsCacheFileMetadata(string path) { FileInfo file = new(path); Debug.Assert(file.Exists); return $"{file.CreationTimeUtc.Ticks} {file.LastWriteTimeUtc.Ticks} {file.Length}"; } private static string ComputeInputsCacheEnvironmentVariableMetadata(string name) => Environment.GetEnvironmentVariable(name) is { } value ? $"true {value}" : "false"; private void AddInputsCacheItem(string item, List<string> itemList, HashSet<string> itemSet, List<string> metadataList, Func<string, string> metadataFunc) { Debug.Assert(!inputsCacheImmutable); if (string.IsNullOrWhiteSpace(item)) return; var metadata = metadataFunc(item); if (itemSet.Add(item)) { itemList.Add(item); metadataList.Add(metadata); } else { bool Predicate(string x) => string.Equals(x, item); var index = itemList.FindIndex(Predicate); Debug.Assert(index != -1); Debug.Assert(metadataList[index] == metadata); } } private void AddInputsCacheFile(string path) => AddInputsCacheItem( Utilities.FixFilePath(path, Utilities.EmptyFilePathBehavior.Ignore), inputsCacheListFiles, inputsCacheSetFiles, inputsCacheMetadataFiles, ComputeInputsCacheFileMetadataFunc ); private void AddInputsCacheEnvironmentVariable(string name) => AddInputsCacheItem( name, inputsCacheListEnvironmentVariables, inputsCacheSetEnvironmentVariables, inputsCacheMetadataEnvironmentVariables, ComputeInputsCacheEnvironmentVariableMetadataFunc ); private void AddInputsCacheFiles(IEnumerable<string> paths) { foreach (var path in paths) AddInputsCacheFile(path); } private bool IsInputsCacheValid() { if (!File.Exists(InputsCache)) return false; bool files = false, env = false; foreach (var line in File.ReadLines(InputsCache, DefaultEncoding)) { if (string.IsNullOrWhiteSpace(line)) continue; if (string.Equals(line, InputsCacheMarkerFiles)) { files = true; env = false; } else if (string.Equals(line, InputsCacheMarkerEnvironmentVariables)) { files = false; env = true; } else if (files) { var items = line.Split(SpaceSeparator, 4); long creation = long.Parse(items[0]), modified = long.Parse(items[1]), size = long.Parse(items[2]); FileInfo file = new(items[3]); if (!file.Exists) return false; if (file.Length != size) return false; if (file.CreationTimeUtc.Ticks != creation) return false; if (file.LastWriteTimeUtc.Ticks != modified) return false; } else if (env) { var items = line.Split(SpaceSeparator, 3); if (!bool.TryParse(items[1], out var nonNull)) return false; var value = Environment.GetEnvironmentVariable(items[0]); if (value is not null != nonNull) return false; if (nonNull && value != items[2]) return false; } else { // Unsupported block, either some future SharpGen version wrote this file, // or the file data is simply corrupt. Either way, invalidate the cache. return false; } } return true; } } <|start_filename|>SharpGen/VisualStudioSetup/ISetupConfiguration2.cs<|end_filename|>  using System.Runtime.InteropServices; namespace SharpGen.VisualStudioSetup; [Guid("26AAB78C-4A60-49D6-AF3B-3C35BC93365D")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [ComImport] public interface ISetupConfiguration2 : ISetupConfiguration { [return: MarshalAs(UnmanagedType.Interface)] new IEnumSetupInstances EnumInstances(); [return: MarshalAs(UnmanagedType.Interface)] new ISetupInstance GetInstanceForCurrentProcess(); [return: MarshalAs(UnmanagedType.Interface)] new ISetupInstance GetInstanceForPath([MarshalAs(UnmanagedType.LPWStr), In] string path); [return: MarshalAs(UnmanagedType.Interface)] IEnumSetupInstances EnumAllInstances(); } <|start_filename|>SdkTests/Interface/PropertyTests.cs<|end_filename|> using System; using System.Collections.Generic; using System.Text; using Xunit; namespace Interface; public class PropertyTests { [Fact] public void IsMethodGeneratesIsProperty() { using (var value = Functions.CreatePropertyTest(true, 0, 0)) { Assert.True(value.IsTrue); } } [Fact] public void IsMethodWithOutParamGeneratesIsProperty() { using (var value = Functions.CreatePropertyTest(true, 0, 0)) { Assert.True(value.IsTrueOutProp); } } [Fact] public void GetSetMethodsGenerateProperty() { using (var value = Functions.CreatePropertyTest(false, 10, 0)) { Assert.Equal(10, value.Value); value.Value = 15; Assert.Equal(15, value.Value); } } [Fact] public void GetSetMethodsWithOutParamGenerateProperty() { using (var value = Functions.CreatePropertyTest(false, 0, 10)) { Assert.Equal(10, value.Value2); value.Value2 = 15; Assert.Equal(15, value.Value2); } } [Fact] public void PersistentPropertyCachesFirstValue() { using (var value = Functions.CreatePropertyTest(false, 10, 0)) { Assert.Equal(10, value.ValuePersistent); value.Value = 15; Assert.Equal(10, value.ValuePersistent); } } [Fact] public void PersistentPropertyWithInterfaceCachesValue() { using (var value = Functions.CreatePropertyTest(false, 0, 0)) { Assert.Equal(value.NativePointer, value.SelfPersistent.NativePointer); } } } <|start_filename|>SharpGen.Runtime/DisposeEventHandler.cs<|end_filename|> namespace SharpGen.Runtime; public delegate void DisposeEventHandler(DisposeBase sender, bool disposing); <|start_filename|>SharpGen/Generator/Marshallers/StructSizeRelationMarshaller.cs<|end_filename|> using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using SharpGen.Model; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; namespace SharpGen.Generator.Marshallers; internal sealed class StructSizeRelationMarshaller : MarshallerBase, IRelationMarshaller { public StatementSyntax GenerateManagedToNative(CsMarshalBase publicElement, CsMarshalBase relatedElement) => ExpressionStatement( AssignmentExpression( SyntaxKind.SimpleAssignmentExpression, GetMarshalStorageLocation(relatedElement), SizeOfExpression(IdentifierName("__Native")) ) ); public StructSizeRelationMarshaller(Ioc ioc) : base(ioc) { } } <|start_filename|>SharpGen/GlobalNamespaceProvider.cs<|end_filename|> // Copyright (c) 2010-2014 SharpDX - <NAME> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Collections.Generic; using System.Runtime.CompilerServices; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace SharpGen; /// <summary> /// Global namespace provider. /// </summary> public class GlobalNamespaceProvider { private readonly Dictionary<WellKnownName, string> wellKnownOverrides = new(); private readonly Dictionary<WellKnownName, NameSyntax> wellKnownOverrideCache = new(); private readonly Dictionary<WellKnownName, NameSyntax> wellKnownDefaults = new(); private readonly Dictionary<BuiltinType, NameSyntax> builtInDefaults = new() { [BuiltinType.Marshal] = SyntaxFactory.ParseName("System.Runtime.InteropServices.Marshal"), [BuiltinType.Math] = SyntaxFactory.ParseName("System.Math"), [BuiltinType.Unsafe] = SyntaxFactory.ParseName("System.Runtime.CompilerServices.Unsafe"), [BuiltinType.Span] = SyntaxFactory.ParseName("System.Span"), [BuiltinType.GCHandle] = SyntaxFactory.ParseName("System.Runtime.InteropServices.GCHandle"), [BuiltinType.Delegate] = SyntaxFactory.ParseName("System.Delegate"), [BuiltinType.FlagsAttribute] = SyntaxFactory.ParseName("System.FlagsAttribute"), [BuiltinType.GC] = SyntaxFactory.ParseName("System.GC"), [BuiltinType.IntPtr] = SyntaxFactory.ParseName("System.IntPtr"), [BuiltinType.UIntPtr] = SyntaxFactory.ParseName("System.UIntPtr"), [BuiltinType.GuidAttribute] = SyntaxFactory.ParseName("System.Runtime.InteropServices.GuidAttribute"), [BuiltinType.StructLayoutAttribute] = SyntaxFactory.ParseName("System.Runtime.InteropServices.StructLayoutAttribute"), [BuiltinType.PlatformNotSupportedException] = SyntaxFactory.ParseName("System.PlatformNotSupportedException"), [BuiltinType.UnmanagedFunctionPointerAttribute] = SyntaxFactory.ParseName("System.Runtime.InteropServices.UnmanagedFunctionPointerAttribute"), [BuiltinType.UnmanagedCallersOnlyAttribute] = SyntaxFactory.ParseName("System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute"), [BuiltinType.Guid] = SyntaxFactory.ParseName("System.Guid"), // TODO: use these! }; private readonly Dictionary<BuiltinType, string> builtInOverrides = new(); private readonly Dictionary<BuiltinType, NameSyntax> builtInOverrideCache = new(); public string GetTypeName(WellKnownName name) => wellKnownOverrides.TryGetValue(name, out var overridenName) ? overridenName : WellKnownDefaultName(name); [MethodImpl(MethodImplOptions.AggressiveInlining)] private static string WellKnownDefaultName(WellKnownName name) => name switch { WellKnownName.WinRTString => "SharpGen.Runtime.Win32.WinRTString", _ => "SharpGen.Runtime." + name }; public NameSyntax GetTypeNameSyntax(WellKnownName name) { if (wellKnownOverrideCache.TryGetValue(name, out var cache)) return cache; NameSyntax value; if (wellKnownOverrides.TryGetValue(name, out var overrideName)) { value = SyntaxFactory.ParseName(overrideName); wellKnownOverrideCache.Add(name, value); return value; } if (wellKnownDefaults.TryGetValue(name, out var defaultName)) return defaultName; value = SyntaxFactory.ParseName(WellKnownDefaultName(name)); wellKnownDefaults.Add(name, value); return value; } public NameSyntax GetTypeNameSyntax(BuiltinType type) { if (builtInOverrideCache.TryGetValue(type, out var cache)) return cache; if (builtInOverrides.TryGetValue(type, out var overrideName)) { var value = SyntaxFactory.ParseName(overrideName); builtInOverrideCache.Add(type, value); return value; } return builtInDefaults[type]; } public NameSyntax GetGenericTypeNameSyntax(BuiltinType type, TypeArgumentListSyntax typeArgumentList) { if (type != BuiltinType.Span) throw new ArgumentOutOfRangeException(nameof(type)); return SyntaxFactory.QualifiedName( SyntaxFactory.IdentifierName("System"), SyntaxFactory.GenericName(SyntaxFactory.Identifier("Span")).WithTypeArgumentList(typeArgumentList) ); } public void OverrideName(WellKnownName wellKnownName, string name) => wellKnownOverrides[wellKnownName] = name; public void OverrideName(BuiltinType builtInName, string name) => builtInOverrides[builtInName] = name; } <|start_filename|>SharpGen.UnitTests/Runtime/TestTypeRegistry.cs<|end_filename|> using System.Runtime.CompilerServices; using SharpGen.Runtime; namespace SharpGen.UnitTests.Runtime; internal static class TestTypeRegistry { [ModuleInitializer] internal static void Initialize() { TypeDataStorage.Storage<ICallback>.SourceVtbl = CallbackVtbl.Vtbl; TypeDataStorage.Storage<ICallback2>.SourceVtbl = Callback2Vtbl.Vtbl; TypeDataRegistrationHelper helper = new(); { helper.Add<ICallback>(); helper.Register<ICallback>(); } { helper.Add<ICallback>(); helper.Add<ICallback2>(); helper.Register<ICallback2>(); } } } <|start_filename|>SharpGen.Runtime/BooleanHelpers.IntToBool.Span.cs<|end_filename|> using System; using System.Runtime.InteropServices; namespace SharpGen.Runtime; public static partial class BooleanHelpers { /// <summary> /// Converts integer array to bool array. /// </summary> /// <param name="src">A pointer to the array of integers.</param> /// <param name="array">The target bool array to fill.</param> public static void ConvertToBoolArray(Span<byte> src, Span<bool> array) => src.CopyTo(MemoryMarshal.AsBytes(array)); /// <summary> /// Converts integer array to bool array. /// </summary> /// <param name="src">A pointer to the array of integers.</param> /// <param name="array">The target bool array to fill.</param> public static void ConvertToBoolArray(Span<short> src, Span<bool> array) { var arrayLength = array.Length; for (var i = 0; i < arrayLength; i++) array[i] = src[i] != 0; } /// <summary> /// Converts integer array to bool array. /// </summary> /// <param name="src">A pointer to the array of integers.</param> /// <param name="array">The target bool array to fill.</param> public static void ConvertToBoolArray(Span<int> src, Span<bool> array) { var arrayLength = array.Length; for (var i = 0; i < arrayLength; i++) array[i] = src[i] != 0; } /// <summary> /// Converts integer array to bool array. /// </summary> /// <param name="src">A pointer to the array of integers.</param> /// <param name="array">The target bool array to fill.</param> public static void ConvertToBoolArray(Span<long> src, Span<bool> array) { var arrayLength = array.Length; for (var i = 0; i < arrayLength; i++) array[i] = src[i] != 0; } /// <summary> /// Converts integer array to bool array. /// </summary> /// <param name="src">A pointer to the array of integers.</param> /// <param name="array">The target bool array to fill.</param> public static void ConvertToBoolArray(Span<sbyte> src, Span<bool> array) => MemoryMarshal.AsBytes(src).CopyTo(MemoryMarshal.AsBytes(array)); /// <summary> /// Converts integer array to bool array. /// </summary> /// <param name="src">A pointer to the array of integers.</param> /// <param name="array">The target bool array to fill.</param> public static void ConvertToBoolArray(Span<ushort> src, Span<bool> array) { var arrayLength = array.Length; for (var i = 0; i < arrayLength; i++) array[i] = src[i] != 0; } /// <summary> /// Converts integer array to bool array. /// </summary> /// <param name="src">A pointer to the array of integers.</param> /// <param name="array">The target bool array to fill.</param> public static void ConvertToBoolArray(Span<uint> src, Span<bool> array) { var arrayLength = array.Length; for (var i = 0; i < arrayLength; i++) array[i] = src[i] != 0; } /// <summary> /// Converts integer array to bool array. /// </summary> /// <param name="src">A pointer to the array of integers.</param> /// <param name="array">The target bool array to fill.</param> public static void ConvertToBoolArray(Span<ulong> src, Span<bool> array) { var arrayLength = array.Length; for (var i = 0; i < arrayLength; i++) array[i] = src[i] != 0; } } <|start_filename|>SharpGen/Generator/Marshallers/LengthRelationMarshaller.cs<|end_filename|> using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using SharpGen.Model; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; namespace SharpGen.Generator.Marshallers; internal sealed class LengthRelationMarshaller : MarshallerBase, IRelationMarshaller { public StatementSyntax GenerateManagedToNative(CsMarshalBase publicElement, CsMarshalBase relatedElement) { var lengthExpression = GeneratorHelpers.LengthExpression(IdentifierName(publicElement.Name)); return ExpressionStatement( AssignmentExpression( SyntaxKind.SimpleAssignmentExpression, IdentifierName(relatedElement.Name), GenerateNullCheckIfNeeded( publicElement, relatedElement is CsMarshalCallableBase lengthStorage ? GeneratorHelpers.CastExpression( ReverseCallablePrologCodeGenerator.GetPublicType(lengthStorage), lengthExpression ) : lengthExpression, DefaultLiteral ) ) ); } public static StatementSyntax GenerateNativeToManaged(CsMarshalBase publicElement, CsMarshalBase relatedElement) => ExpressionStatement( AssignmentExpression( SyntaxKind.SimpleAssignmentExpression, IdentifierName(publicElement.Name), ObjectCreationExpression( ArrayType( ParseTypeName(publicElement.PublicType.QualifiedName), SingletonList( ArrayRankSpecifier( SingletonSeparatedList<ExpressionSyntax>(IdentifierName(relatedElement.Name)) ) ) ) ) ) ); public LengthRelationMarshaller(Ioc ioc) : base(ioc) { } } <|start_filename|>SharpGen.Runtime/CppObject.cs<|end_filename|> // Copyright (c) 2010-2014 SharpDX - <NAME> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.ComponentModel; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Threading; using SharpGen.Runtime.Diagnostics; namespace SharpGen.Runtime; /// <summary> /// Root class for all native interop objects. /// </summary> public class CppObject : DisposeBase, ICallbackable, IEquatable<CppObject> { /// <summary> /// The native pointer /// </summary> [DebuggerBrowsable(DebuggerBrowsableState.Never)] private IntPtr _nativePointer; private static readonly ConditionalWeakTable<CppObject, object> TagTable = new(); /// <summary> /// Gets or sets a custom user tag object to associate with this instance. /// </summary> /// <value>The tag object.</value> [EditorBrowsable(EditorBrowsableState.Advanced)] public object Tag { get => TagTable.TryGetValue(this, out var tag) ? tag : null; set => TagTable.Add(this, value); } /// <summary> /// Default constructor. /// </summary> /// <param name = "pointer">Pointer to C++ object</param> public CppObject(IntPtr pointer) { _nativePointer = pointer; if (ObjectTrackerReadOnlyConfiguration.IsEnabled) ObjectTracker.Track(this, pointer); } /// <summary> /// Default constructor. /// </summary> /// <param name = "pointer">Pointer to C++ object</param> public unsafe CppObject(UIntPtr pointer) : this(new IntPtr(pointer.ToPointer())) { } /// <summary> /// Initializes a new instance of the <see cref="CppObject"/> class. /// </summary> protected CppObject() { } /// <summary> /// Get a pointer to the underlying Cpp Object /// </summary> public IntPtr NativePointer { [MethodImpl(Utilities.MethodAggressiveOptimization)] get => _nativePointer; set { var oldNativePointer = Interlocked.Exchange(ref _nativePointer, value); if (oldNativePointer == value) return; if (ObjectTrackerReadOnlyConfiguration.IsEnabled) ObjectTracker.MigrateNativePointer(this, oldNativePointer, value); NativePointerUpdated(oldNativePointer); } } public override string ToString() => Utilities.FormatPointer(NativePointer); public static explicit operator IntPtr(CppObject cppObject) => cppObject?.NativePointer ?? IntPtr.Zero; /// <summary> /// Method called when the <see cref="NativePointer"/> is updated. /// </summary> protected virtual void NativePointerUpdated(IntPtr oldNativePointer) { } protected unsafe void* this[int index] { [MethodImpl(Utilities.MethodAggressiveOptimization)] #if DEBUG get { Debug.Assert(!IsDisposed); return (*(void***) _nativePointer)[index]; } #else get => (*(void***) _nativePointer)[index]; #endif } protected unsafe void* this[uint index] { [MethodImpl(Utilities.MethodAggressiveOptimization)] #if DEBUG get { Debug.Assert(!IsDisposed); return (*(void***) _nativePointer)[index]; } #else get => (*(void***) _nativePointer)[index]; #endif } protected unsafe void* this[nint index] { [MethodImpl(Utilities.MethodAggressiveOptimization)] #if DEBUG get { Debug.Assert(!IsDisposed); return (*(void***) _nativePointer)[index]; } #else get => (*(void***) _nativePointer)[index]; #endif } protected unsafe void* this[nuint index] { [MethodImpl(Utilities.MethodAggressiveOptimization)] #if DEBUG get { Debug.Assert(!IsDisposed); return (*(void***) _nativePointer)[index]; } #else get => (*(void***) _nativePointer)[index]; #endif } [DebuggerBrowsable(DebuggerBrowsableState.Never)] protected override bool IsDisposed => NativePointer == IntPtr.Zero; protected sealed override void Dispose(bool disposing) { var nativePointer = NativePointer; DisposeCore(nativePointer, disposing); if (ObjectTrackerReadOnlyConfiguration.IsEnabled) ObjectTracker.Untrack(this, nativePointer); // Set pointer to null (using protected members in order to avoid callbacks). #if DEBUG var oldNativePointer = Interlocked.Exchange(ref _nativePointer, IntPtr.Zero); Debug.Assert(oldNativePointer == nativePointer); #else Interlocked.Exchange(ref _nativePointer, IntPtr.Zero); #endif NativePointerUpdated(nativePointer); } /// <summary> /// Releases unmanaged and - optionally - managed resources /// </summary> /// <param name="nativePointer"><see cref="NativePointer"/></param> /// <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 DisposeCore(IntPtr nativePointer, bool disposing) { } public bool Equals(CppObject other) { if (ReferenceEquals(null, other)) return false; return ReferenceEquals(this, other) || _nativePointer.Equals(other._nativePointer); } public override bool Equals(object obj) => ReferenceEquals(this, obj) || obj is CppObject other && _nativePointer.Equals(other._nativePointer); public override int GetHashCode() => _nativePointer.GetHashCode(); public static bool operator ==(CppObject left, CppObject right) => Equals(left, right); public static bool operator !=(CppObject left, CppObject right) => !Equals(left, right); } <|start_filename|>SharpGen.Runtime/Diagnostics/ObjectTracker.cs<|end_filename|> // Copyright (c) 2010-2014 SharpDX - <NAME> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Collections.Generic; using System.Threading; namespace SharpGen.Runtime.Diagnostics; using ObjectReferenceDictionary = Dictionary<IntPtr, List<WeakReference<CppObject>>>; /// <summary> /// Track all allocated objects. /// </summary> public static class ObjectTracker { private static ObjectReferenceDictionary _processGlobalObjectReferences; private static readonly ThreadLocal<ObjectReferenceDictionary> ThreadStaticObjectReferences = new(static () => new ObjectReferenceDictionary(), false); /// <summary> /// Occurs when a CppObject is tracked. /// </summary> public static event Action<CppObject> Tracked; /// <summary> /// Occurs when a CppObject is untracked. /// </summary> public static event Action<CppObject> UnTracked; private static ObjectReferenceDictionary ObjectReferences => ObjectTrackerReadOnlyConfiguration.IsObjectTrackingThreadStatic ? ThreadStaticObjectReferences.Value : _processGlobalObjectReferences ??= new(); /// <summary> /// Tracks the specified native object. /// </summary> /// <param name="cppObject">The native object.</param> public static void Track(CppObject cppObject) { if (cppObject is null) return; var nativePointer = cppObject.NativePointer; Track(cppObject, nativePointer); } internal static void Track(CppObject cppObject, IntPtr nativePointer) { if (nativePointer == IntPtr.Zero) return; var objectReferences = ObjectReferences; lock (objectReferences) TrackImpl(cppObject, nativePointer, objectReferences); // Fire an event. Tracked?.Invoke(cppObject); } private static void TrackImpl(CppObject cppObject, IntPtr nativePointer, ObjectReferenceDictionary objectReferences) { if (!objectReferences.TryGetValue(nativePointer, out var referenceList)) { referenceList = new List<WeakReference<CppObject>>(); objectReferences.Add(nativePointer, referenceList); } referenceList.Add(new WeakReference<CppObject>(cppObject)); } /// <summary> /// Untracks the specified native object. /// </summary> /// <param name="cppObject">The native object.</param> public static void UnTrack(CppObject cppObject) { if (cppObject is null) return; var nativePointer = cppObject.NativePointer; Untrack(cppObject, nativePointer); } internal static void Untrack(CppObject cppObject, IntPtr nativePointer) { if (nativePointer == IntPtr.Zero) return; var objectReferences = ObjectReferences; bool foundTracked; lock (objectReferences) { foundTracked = UntrackImpl(cppObject, nativePointer, objectReferences); } if (foundTracked) { // Fire an event UnTracked?.Invoke(cppObject); } } private static bool UntrackImpl(CppObject cppObject, IntPtr nativePointer, ObjectReferenceDictionary objectReferences) { var foundTracked = objectReferences.TryGetValue(nativePointer, out var referenceList); if (!foundTracked) return false; // Object is tracked, remove from reference list for (var i = referenceList.Count - 1; i >= 0; --i) { if (!referenceList[i].TryGetTarget(out var target) || ReferenceEquals(target, cppObject)) referenceList.RemoveAt(i); } // Remove empty list if (referenceList.Count == 0) objectReferences.Remove(nativePointer); return true; } internal static void MigrateNativePointer(CppObject cppObject, IntPtr oldNativePointer, IntPtr newNativePointer) { if (cppObject is null) return; var hasOldNativePointer = oldNativePointer != IntPtr.Zero; var hasNewNativePointer = newNativePointer != IntPtr.Zero; if (!hasOldNativePointer && !hasNewNativePointer) return; var objectReferences = ObjectReferences; lock (objectReferences) { if (hasOldNativePointer) UntrackImpl(cppObject, oldNativePointer, objectReferences); if (hasNewNativePointer) TrackImpl(cppObject, newNativePointer, objectReferences); } } /// <summary> /// Reports all COM object that are active and not yet disposed. /// </summary> private static List<WeakReference<CppObject>> FindActiveObjects() { List<WeakReference<CppObject>> activeObjects; var objectReferences = ObjectReferences; lock (objectReferences) { activeObjects = new(objectReferences.Count); foreach (var referenceList in objectReferences.Values) { foreach (var objectReference in referenceList) { if (objectReference.TryGetTarget(out _)) activeObjects.Add(objectReference); } } } return activeObjects; } } <|start_filename|>SharpGen/Generator/MemberPlatformMultiCodeGeneratorBase.cs<|end_filename|> using System.Collections.Generic; using Microsoft.CodeAnalysis.CSharp.Syntax; using SharpGen.Model; namespace SharpGen.Generator; internal abstract class MemberPlatformMultiCodeGeneratorBase<T> : MemberCodeGeneratorBase<T>, IPlatformMultiCodeGenerator<T, MemberDeclarationSyntax> where T : CsBase { protected MemberPlatformMultiCodeGeneratorBase(Ioc ioc) : base(ioc) { } public abstract IEnumerable<PlatformDetectionType> GetPlatforms(T csElement); public abstract IEnumerable<MemberDeclarationSyntax> GenerateCode(T csElement, PlatformDetectionType platform); } <|start_filename|>SharpGen/Parser/SdkResolver.cs<|end_filename|> #nullable enable using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices; using SharpGen.Config; using SharpGen.Logging; using SharpGen.VisualStudioSetup; namespace SharpGen.Parser; public sealed class SdkResolver { private static readonly string[] WindowsSdkIncludes = { "shared", "um", "ucrt", "winrt" }; private static readonly char[] ComponentSeparator = { ';' }; public SdkResolver(Logger logger) { Logger = logger; } private Logger Logger { get; } public IEnumerable<IncludeDirRule> ResolveIncludeDirsForSdk(SdkRule sdkRule) { if (sdkRule.Components is { } components && sdkRule.Name != SdkLib.WindowsSdk) Logger.Warning(null, $"Unexpected `{sdkRule._Name_}` SDK components specified: `{components}`."); switch (sdkRule.Name) { case SdkLib.StdLib: return ResolveStdLib(sdkRule.Version); case SdkLib.WindowsSdk: return ResolveWindowsSdk(sdkRule.Version, sdkRule.Components); default: Logger.Error(LoggingCodes.UnknownSdk, "Unknown SDK specified in an SDK rule."); return Enumerable.Empty<IncludeDirRule>(); } } private IEnumerable<IncludeDirRule> ResolveStdLib(string? version) { if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { foreach (var vsInstallDir in GetVSInstallPath()) { string actualVersion; if (version is not null) { actualVersion = version; } else { var defaultVersion = Path.Combine( vsInstallDir, "VC", "Auxiliary", "Build", "Microsoft.VCToolsVersion.default.txt" ); if (!File.Exists(defaultVersion)) continue; actualVersion = File.ReadAllText(defaultVersion); } var path = Path.Combine( vsInstallDir, "VC", "Tools", "MSVC", actualVersion.Trim(), "include" ); if (!Directory.Exists(path)) continue; yield return new IncludeDirRule(path); yield break; } } else { if (version is not null) { var path = Path.Combine("/usr", "include", "c++", version); if (Directory.Exists(path)) yield return new IncludeDirRule(path); } else { DirectoryInfo cpp = new(Path.Combine("/usr", "include", "c++")); if (!cpp.Exists) yield break; // TODO: pick latest if not specified var path = cpp.EnumerateDirectories().FirstOrDefault()?.FullName; if (path is not null) yield return new IncludeDirRule(path); } } } private IReadOnlyCollection<string?> GetVSInstallPath() { var vsPathOverride = Environment.GetEnvironmentVariable("SHARPGEN_VS_OVERRIDE"); if (!string.IsNullOrEmpty(vsPathOverride)) { return new[] {vsPathOverride}; } List<string?> paths = new(); try { var query = new SetupConfiguration(); var enumInstances = query.EnumInstances(); int fetched; var instances = new ISetupInstance[1]; do { enumInstances.Next(1, instances, out fetched); if (fetched <= 0) continue; var instance2 = (ISetupInstance2) instances[0]; var state = instance2.GetState(); if ((state & InstanceState.Registered) != InstanceState.Registered) continue; if (instance2.GetPackages().Any(Predicate)) paths.Add(instance2.GetInstallationPath()); } while (fetched > 0); static bool Predicate(ISetupPackageReference pkg) => pkg.GetId() == "Microsoft.VisualStudio.Component.VC.Tools.x86.x64"; } catch (Exception e) { Logger.LogRawMessage( LogLevel.Warning, LoggingCodes.VisualStudioDiscoveryError, "Visual Studio installation discovery has thrown an exception", e ); } if (paths.Count == 0) Logger.Fatal("Unable to find a Visual Studio installation that has the Visual C++ Toolchain installed."); return paths; } private IEnumerable<IncludeDirRule> ResolveWindowsSdk(string version, string? components) { var componentList = components is not null ? components.Split(ComponentSeparator, StringSplitOptions.RemoveEmptyEntries) .Select(static x => x.Trim()) .ToArray() : WindowsSdkIncludes; if (Environment.GetEnvironmentVariable("SHARPGEN_SDK_OVERRIDE") is { Length: > 0 } sdkPathOverride) { foreach (var include in componentList) yield return new IncludeDirRule(Path.Combine(sdkPathOverride, "Include", version, include)); } const string prefix = @"=HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows Kits\Installed Roots\KitsRoot10;Include\"; foreach (var include in componentList) yield return new IncludeDirRule(prefix + version + '\\' + include); } } <|start_filename|>SharpGen/Generator/GuidConstantRoslynGenerator.cs<|end_filename|> using System; using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; namespace SharpGen.Generator; internal static class GuidConstantRoslynGenerator { public static SyntaxToken[] GuidToTokens(Guid guid) { var extractedGuid = Unsafe.As<Guid, GuidExtractor>(ref guid); return new[] { Literal(extractedGuid.a), Literal(extractedGuid.b), Literal(extractedGuid.c), Literal(extractedGuid.d), Literal(extractedGuid.e), Literal(extractedGuid.f), Literal(extractedGuid.g), Literal(extractedGuid.h), Literal(extractedGuid.i), Literal(extractedGuid.j), Literal(extractedGuid.k) }; } private static SyntaxToken Literal(int value) => SyntaxFactory.Literal("0x" + value.ToString("X8"), value); private static SyntaxToken Literal(byte value) => SyntaxFactory.Literal("0x" + value.ToString("X2"), value); private static SyntaxToken Literal(short value) => SyntaxFactory.Literal("0x" + value.ToString("X4"), value); [SuppressMessage("ReSharper", "InconsistentNaming")] private readonly struct GuidExtractor { #pragma warning disable 649 public readonly int a; public readonly short b; public readonly short c; public readonly byte d; public readonly byte e; public readonly byte f; public readonly byte g; public readonly byte h; public readonly byte i; public readonly byte j; public readonly byte k; #pragma warning restore 649 } } <|start_filename|>SharpGen.Generator/SharpGenModuleGenerator.GenerateUtilities.cs<|end_filename|> using System.Collections.Generic; using System.Text; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; namespace SharpGen.Generator; public sealed partial class SharpGenModuleGenerator { private static readonly NameSyntax ConditionalAttribute = ParseName("System.Diagnostics.Conditional"); private static readonly NameSyntax AttributeUsage = ParseName("System.AttributeUsage"); private static readonly NameSyntax AttributeTargets = ParseName("System.AttributeTargets"); private static readonly NameSyntax Attribute = ParseName("System.Attribute"); private static readonly AttributeSyntax DebugConditionalAttribute = SyntaxFactory.Attribute( ConditionalAttribute, AttributeArgumentList( SingletonSeparatedList( AttributeArgument( LiteralExpression(SyntaxKind.StringLiteralExpression, Literal("SHARPGEN_ATTRIBUTE_DEBUG")) ) ) ) ); private static readonly AttributeSyntax MethodAttributeUsage = SyntaxFactory.Attribute( AttributeUsage, AttributeArgumentList( SeparatedList<AttributeArgumentSyntax>( new SyntaxNodeOrToken[] { AttributeArgument( MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, AttributeTargets, IdentifierName("Method") ) ), Token(SyntaxKind.CommaToken), AttributeArgument(LiteralExpression(SyntaxKind.FalseLiteralExpression)) .WithNameEquals(NameEquals(IdentifierName("Inherited"))) } ) ) ); private static void GenerateUtilities(GeneratorExecutionContext context) { List<MemberDeclarationSyntax> attributes = new(1); var moduleInitType = context.Compilation.GetTypeByMetadataName(ModuleInitializerAttributeName); if (moduleInitType is not { IsReferenceType: true, IsGenericType: false } || !context.Compilation.IsSymbolAccessibleWithin(moduleInitType, context.Compilation.Assembly)) attributes.Add(ModuleInitializerAttribute); if (attributes.Count == 0) return; context.AddSource( "SourceGeneratorUtilities.g.cs", SourceText.From(GenerateCompilationUnit(attributes).ToString(), Encoding.UTF8) ); } private static NamespaceDeclarationSyntax ModuleInitializerAttribute => NamespaceDeclaration( QualifiedName( QualifiedName(IdentifierName("System"), IdentifierName("Runtime")), IdentifierName("CompilerServices") ) ) .AddMembers( ClassDeclaration("ModuleInitializerAttribute") .AddAttributeLists( AttributeList(SingletonSeparatedList(MethodAttributeUsage)), AttributeList(SingletonSeparatedList(DebugConditionalAttribute)) ) .AddModifiers(Token(SyntaxKind.InternalKeyword), Token(SyntaxKind.SealedKeyword)) .AddBaseListTypes(SimpleBaseType(Attribute)) .AddMembers( ConstructorDeclaration(Identifier("ModuleInitializerAttribute")) .WithModifiers(TokenList(Token(SyntaxKind.PublicKeyword))) .WithBody(Block()) ) ); } <|start_filename|>SharpGen.Runtime/Result.cs<|end_filename|> // Copyright (c) 2010-2014 SharpGen.Runtime - <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. #nullable enable using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace SharpGen.Runtime; /// <summary> /// Result structure. /// </summary> [StructLayout(LayoutKind.Sequential)] [SuppressMessage("ReSharper", "ConvertToAutoProperty")] public readonly partial struct Result : IComparable, IComparable<Result>, IEquatable<Result>, IFormattable { // .NET Native has issues with <...> in property backing fields in structs private readonly int _code; /// <summary> /// Gets the HRESULT error code. /// </summary> /// <value>The HRESULT error code.</value> public int Code => _code; /// <param name="code">The HRESULT error code.</param> public Result(int code) => _code = code; /// <param name="code">The HRESULT error code.</param> public Result(uint code) => _code = unchecked((int) code); /// <param name="code">The HRESULT error code.</param> public Result(long code) => _code = unchecked((int) code); /// <param name="code">The HRESULT error code.</param> public Result(ulong code) => _code = unchecked((int) code); /// <summary> /// Gets a value indicating whether this <see cref="Result"/> is success. /// </summary> /// <value><c>true</c> if success; otherwise, <c>false</c>.</value> public bool Success => Code >= 0; /// <summary> /// Gets a value indicating whether this <see cref="Result"/> is failure. /// </summary> /// <value><c>true</c> if failure; otherwise, <c>false</c>.</value> public bool Failure => Code < 0; public static bool operator ==(Result left, Result right) => left.Code == right.Code; public static bool operator !=(Result left, Result right) => left.Code != right.Code; public static bool operator <(Result left, Result right) => left.CompareTo(right) < 0; public static bool operator >(Result left, Result right) => left.CompareTo(right) > 0; public static bool operator <=(Result left, Result right) => left.CompareTo(right) <= 0; public static bool operator >=(Result left, Result right) => left.CompareTo(right) >= 0; public static explicit operator sbyte(Result value) => unchecked((sbyte)value.Code); public static explicit operator short(Result value) => unchecked((short)value.Code); public static explicit operator long(Result value) => value.Code; public static explicit operator int(Result value) => value.Code; public static explicit operator nint(Result value) => value.Code; public static explicit operator byte(Result value) => unchecked((byte)value.Code); public static explicit operator ushort(Result value) => unchecked((ushort)value.Code); public static explicit operator uint(Result value) => unchecked((uint)value.Code); public static explicit operator ulong(Result value) => unchecked((ulong)value.Code); public static explicit operator nuint(Result value) => (nuint)value.Code; public static explicit operator Result(sbyte value) => new(value); public static explicit operator Result(short value) => new(value); public static implicit operator Result(int value) => new(value); public static explicit operator Result(long value) => new((int)value); public static explicit operator Result(nint value) => new((int)value); public static explicit operator Result(byte value) => new(value); public static explicit operator Result(ushort value) => new(value); public static implicit operator Result(uint value) => new(value); public static explicit operator Result(ulong value) => new((int)value); public static explicit operator Result(nuint value) => new((int)value); public bool Equals(Result other) => Code == other.Code; public override bool Equals(object? obj) => obj is Result res && Equals(res); public override int GetHashCode() => Code; public override string ToString() => Code.ToString("X8"); public string ToString(string format, IFormatProvider formatProvider) => Code.ToString(format, formatProvider); public int CompareTo(Result other) => Code.CompareTo(other.Code); public int CompareTo(object? obj) { if (ReferenceEquals(null, obj)) return 1; return obj is Result other ? CompareTo(other) : throw new ArgumentException($"Object must be of type {nameof(Result)}"); } [DoesNotReturn] private void ThrowFailureException() => throw new SharpGenException(this); /// <summary> /// Checks the error. /// </summary> public void CheckError() { if (Failure) ThrowFailureException(); } /// <summary> /// Checks the error. /// </summary> public void CheckError(Result allowedFail) { var code = Code; if (code < 0 && code != allowedFail.Code) ThrowFailureException(); } /// <summary> /// Checks the error. /// </summary> public void CheckError(Result allowedFail1, Result allowedFail2) { var code = Code; if (code >= 0) return; if (code != allowedFail1.Code && code != allowedFail2.Code) ThrowFailureException(); } /// <summary> /// Checks the error. /// </summary> public void CheckError(params Result[] allowedFails) { var code = Code; if (code < 0 && !allowedFails.Contains(code)) ThrowFailureException(); } /// <summary> /// Checks the error. /// </summary> public void CheckError(IEnumerable<Result> allowedFails) { var code = Code; if (code < 0 && !allowedFails.Contains(code)) ThrowFailureException(); } /// <summary> /// Gets a <see cref="Result"/> from an <see cref="Exception"/>. /// </summary> /// <param name="ex">The exception</param> /// <returns>The associated result code</returns> public static Result GetResultFromException(Exception ex) => new(ex.HResult); public string Module => ResultDescriptor.Find(Code).Module; public string NativeApiCode => ResultDescriptor.Find(Code).NativeApiCode; public string ApiCode => ResultDescriptor.Find(Code).ApiCode; public string Description => ResultDescriptor.Find(Code).Description; [MethodImpl(Utilities.MethodAggressiveOptimization)] public static void Register(Result result, string? module = null, string? nativeApiCode = null, string? apiCode = null, string? description = null) => ResultDescriptor.Register(result.Code, module, nativeApiCode, apiCode, description); [MethodImpl(Utilities.MethodAggressiveOptimization)] public static void Register(int result, string? module = null, string? nativeApiCode = null, string? apiCode = null, string? description = null) => ResultDescriptor.Register(result, module, nativeApiCode, apiCode, description); [MethodImpl(Utilities.MethodAggressiveOptimization)] public static void Register(uint result, string? module = null, string? nativeApiCode = null, string? apiCode = null, string? description = null) => ResultDescriptor.Register(result, module, nativeApiCode, apiCode, description); [MethodImpl(Utilities.MethodAggressiveOptimization)] public static void Register(long result, string? module = null, string? nativeApiCode = null, string? apiCode = null, string? description = null) => ResultDescriptor.Register(unchecked((int) result), module, nativeApiCode, apiCode, description); [MethodImpl(Utilities.MethodAggressiveOptimization)] public static void Register(ulong result, string? module = null, string? nativeApiCode = null, string? apiCode = null, string? description = null) => ResultDescriptor.Register(unchecked((int) result), module, nativeApiCode, apiCode, description); } <|start_filename|>SharpGen.Generator/SharpGenModuleGenerator.GenerateModule.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; namespace SharpGen.Generator; public sealed partial class SharpGenModuleGenerator { private static void GenerateModule(GeneratorExecutionContext context) { var walker = (SemanticTreeWalker) context.SyntaxContextReceiver!; List<GuidJob> guidJobs = new(); List<VtblJob> vtblJobs = new(); void HandleGuid(ITypeSymbol symbol, Guid parsedGuid) => guidJobs.Add(new GuidJob(symbol, parsedGuid, Utilities.GetGuidParameters(parsedGuid))); void HandleVtbl(ITypeSymbol symbol, ITypeSymbol vtblTypeSymbol) { bool TypePredicate(INamedTypeSymbol x) => x.AllInterfaces.Any(y => y.ToDisplayString() == CallbackableInterfaceName); Debug.Assert(!vtblJobs.Any(x => SymbolEqualityComparer.Default.Equals(x.InterfaceType, symbol))); vtblJobs.Add( new VtblJob(symbol, vtblTypeSymbol) { CallbackInterfaces = symbol.AllInterfaces.Where(TypePredicate).Reverse().ToArray() } ); } if (context.CancellationToken.IsCancellationRequested) return; foreach (var symbol in walker.QueuedJobs) { if (symbol.GetGuidAttribute() is { } guidAttribute) HandleGuid(symbol, guidAttribute); if (context.CancellationToken.IsCancellationRequested) return; if (symbol.GetVtblAttribute() is { } vtblAttribute) HandleVtbl(symbol, vtblAttribute); } if (context.CancellationToken.IsCancellationRequested) return; StatementSyntaxList body = new(); StatementSyntax GuidTransform(GuidJob job) => context.Compilation.IsSymbolAccessibleWithin(job.Type, context.Compilation.Assembly) ? ExpressionStatement( AssignmentExpression( SyntaxKind.SimpleAssignmentExpression, StorageField(ParseName(job.Type.ToDisplayString()), IdentifierName("Guid")), ObjectCreationExpression(ParseTypeName("System.Guid"), job.GuidSyntax, default) ) ) : Block() .WithLeadingTrivia( Comment( $"// Type {job.Type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat)} is inaccessible, but has GUID {job.Guid}" ) ); body.AddRange(guidJobs, GuidTransform); if (context.CancellationToken.IsCancellationRequested) return; if (vtblJobs.Count > 0) { body.AddRange( vtblJobs, job => ExpressionStatement( AssignmentExpression( SyntaxKind.SimpleAssignmentExpression, StorageField(ParseName(job.InterfaceType.ToDisplayString()), IdentifierName("SourceVtbl")), MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, ParseTypeName(job.VtblType.ToDisplayString()), IdentifierName("Vtbl") ) ) ) ); body.Add( LocalDeclarationStatement( VariableDeclaration( ParseName("SharpGen.Runtime.TypeDataRegistrationHelper"), SingletonSeparatedList( VariableDeclarator(Identifier("helper")) .WithInitializer(EqualsValueClause(ImplicitObjectCreationExpression())) ) ) ) ); if (context.CancellationToken.IsCancellationRequested) return; var helper = IdentifierName("helper"); var add = Identifier("Add"); foreach (var vtblJob in vtblJobs) { ExpressionStatementSyntax AddVtbl(ITypeSymbol typeSymbol) { var name = typeSymbol.ToDisplayString(); var localVtbl = vtblJobs.ExclusiveOrDefault( x => SymbolEqualityComparer.Default.Equals(x.InterfaceType, typeSymbol) )?.VtblType; if (localVtbl is null && context.Compilation.GetTypeByMetadataName(name).GetVtblAttribute() is { } vtblTypeSymbol && context.Compilation.IsSymbolAccessibleWithin(vtblTypeSymbol, context.Compilation.Assembly)) localVtbl = vtblTypeSymbol; return ExpressionStatement( InvocationExpression( MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, helper, localVtbl is not null ? IdentifierName(add) : GenericName( add, TypeArgumentList(SingletonSeparatedList(ParseTypeName(name))) ) ), ArgumentList( localVtbl is not null ? SingletonSeparatedList( Argument( MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, ParseTypeName(localVtbl.ToDisplayString()), IdentifierName("Vtbl") ) ) ) : default ) ) ); } body.AddRange(vtblJob.CallbackInterfaces.Append(vtblJob.InterfaceType), AddVtbl); if (context.CancellationToken.IsCancellationRequested) return; body.Add( ExpressionStatement( InvocationExpression( MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, helper, GenericName( Identifier("Register"), TypeArgumentList( SingletonSeparatedList(ParseTypeName(vtblJob.InterfaceType.ToDisplayString())) ) ) ) ) ) ); } } if (body.Count == 0) return; if (context.CancellationToken.IsCancellationRequested) return; var staticModifier = TokenList(Token(SyntaxKind.InternalKeyword), Token(SyntaxKind.StaticKeyword)); var clazz = ClassDeclaration("SharpGenModuleInitializer") .WithModifiers(staticModifier) .AddModifiers(Token(SyntaxKind.UnsafeKeyword)) .WithMembers( SingletonList<MemberDeclarationSyntax>( MethodDeclaration(PredefinedType(Token(SyntaxKind.VoidKeyword)), "Initialize") .WithModifiers(staticModifier) .AddAttributeLists(ModuleInitializerAttributeList) .WithBody(body.ToBlock()) ) ); context.AddSource( "SharpGen.Module.g.cs", SourceText.From(GenerateCompilationUnit(clazz).ToString(), Encoding.UTF8) ); } private sealed record GuidJob(ITypeSymbol Type, Guid Guid, ArgumentListSyntax GuidSyntax) { public readonly ITypeSymbol Type = Type ?? throw new ArgumentNullException(nameof(Type)); public readonly ArgumentListSyntax GuidSyntax = GuidSyntax ?? throw new ArgumentNullException(nameof(GuidSyntax)); } private sealed class VtblJob { public readonly ITypeSymbol InterfaceType; public readonly ITypeSymbol VtblType; public INamedTypeSymbol[] CallbackInterfaces { get; init; } public VtblJob(ITypeSymbol interfaceType, ITypeSymbol vtblType) { InterfaceType = interfaceType ?? throw new ArgumentNullException(nameof(interfaceType)); VtblType = vtblType ?? throw new ArgumentNullException(nameof(vtblType)); } } private static ExpressionSyntax StorageField(TypeSyntax typeName, SimpleNameSyntax name) => MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, TypeDataStorage, GenericName(Identifier("Storage"), TypeArgumentList(SingletonSeparatedList(typeName))) ), name ); } <|start_filename|>SharpGen.Runtime/InterfaceArray.cs<|end_filename|> // Copyright (c) 2010-2014 SharpDX - <NAME> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; namespace SharpGen.Runtime; /// <summary> /// A fast method to pass array of <see cref="CppObject"/>-derived objects to SharpGen methods. /// </summary> /// <typeparam name="T">Type of the <see cref="CppObject"/></typeparam> [DebuggerTypeProxy(typeof(InterfaceArray<>.InterfaceArrayDebugView))] [DebuggerDisplay("Count={" + nameof(Length) + "}")] [SuppressMessage("ReSharper", "ConvertToAutoProperty")] public unsafe struct InterfaceArray<T> : IReadOnlyList<T>, IEnlightenedDisposable, IDisposable where T : CppObject { // .NET Native has issues with <...> in property backing fields in structs private T[] _values; private void* _nativePointer; public InterfaceArray(params T[] array) { if (array != null) { var length = unchecked((uint) array.Length); if (length != 0) { _values = new T[length]; _nativePointer = MemoryHelpers.AllocateMemory(length * (uint)IntPtr.Size); for (var i = 0; i < length; i++) this[i] = array[i]; } else { _nativePointer = default; _values = null; } } else { _nativePointer = default; _values = null; } } public InterfaceArray(int size) : this((uint) size) { } public InterfaceArray(uint size) { if (size > 0) { _values = new T[size]; _nativePointer = MemoryHelpers.AllocateMemory(size * (uint)IntPtr.Size); } else { _nativePointer = default; _values = null; } } public InterfaceArray(void* pointer, nuint size) { if (size > 0) { _nativePointer = pointer; _values = new T[size]; var ptr = (IntPtr*) pointer; for (nuint i = 0; i < size; i++) _values[i] = MarshallingHelpers.FromPointer<T>(ptr[i]); } else { _nativePointer = default; _values = null; } } /// <summary> /// Gets the pointer to the native array associated to this instance. /// </summary> public void* NativePointer { readonly get => _nativePointer; private set => _nativePointer = value; } public readonly int Length => _values?.Length ?? 0; private readonly bool IsDisposed => NativePointer == default; public void CheckAndDispose(bool disposing) { if (IsDisposed) return; _values = null; MemoryHelpers.FreeMemory(NativePointer); NativePointer = default; } public void Dispose() => CheckAndDispose(true); public readonly T this[int i] { get => _values[i]; set { _values[i] = value; ((IntPtr*) NativePointer)[i] = value?.NativePointer ?? IntPtr.Zero; } } public readonly T this[uint i] { get => _values[i]; set { _values[i] = value; ((IntPtr*) NativePointer)[i] = value?.NativePointer ?? IntPtr.Zero; } } public readonly T this[nint i] { get => _values[i]; set { _values[i] = value; ((IntPtr*) NativePointer)[i] = value?.NativePointer ?? IntPtr.Zero; } } public readonly T this[nuint i] { get => _values[i]; set { _values[i] = value; ((IntPtr*) NativePointer)[i] = value?.NativePointer ?? IntPtr.Zero; } } readonly IEnumerator IEnumerable.GetEnumerator() => _values != null ? _values.GetEnumerator() : EmptyEnumerator.Instance; public readonly IEnumerator<T> GetEnumerator() => _values != null ? new ArrayEnumerator(_values.GetEnumerator()) : EmptyEnumerator.Instance; private readonly struct ArrayEnumerator : IEnumerator<T> { private readonly IEnumerator enumerator; public ArrayEnumerator(IEnumerator enumerator) => this.enumerator = enumerator; public void Dispose() { } public bool MoveNext() => enumerator.MoveNext(); public void Reset() => enumerator.Reset(); public T Current => (T)enumerator.Current; object IEnumerator.Current => Current; } private readonly struct EmptyEnumerator : IEnumerator<T> { public static readonly IEnumerator<T> Instance = default(EmptyEnumerator); public void Dispose() { } public bool MoveNext() => false; public void Reset() { } public T Current => throw new InvalidOperationException(); object IEnumerator.Current => Current; } private sealed class InterfaceArrayDebugView { public InterfaceArrayDebugView(InterfaceArray<T> array) => Items = array._values; [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public T[] Items { get; } } readonly int IReadOnlyCollection<T>.Count => Length; } <|start_filename|>SharpGen/Config/Visibility.cs<|end_filename|> // Copyright (c) 2010-2014 SharpDX - <NAME> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Xml.Serialization; namespace SharpGen.Config; [Flags] public enum Visibility : uint { [XmlEnum("public")] Public = 0x01, [XmlEnum("internal")] Internal = 0x02, [XmlEnum("protected")] Protected = 0x04, [XmlEnum("sharpgen-group")] SharpGenGroup = 0x08, [XmlEnum("private")] Private = 0x10, [XmlEnum("override")] Override = 0x20, [XmlEnum("abstract")] Abstract = 0x40, [XmlEnum("static")] Static = 0x80, [XmlEnum("const")] Const = 0x100, [XmlEnum("virtual")] Virtual = 0x200, [XmlEnum("readonly")] Readonly = 0x400, [XmlEnum("sealed")] Sealed = 0x800, [XmlEnum("protected-internal")] ProtectedInternal = 0x1000, [XmlEnum("private-protected")] PrivateProtected = 0x2000, } <|start_filename|>SharpGen.Runtime/CallbackBase.Reflection.cs<|end_filename|> #nullable enable using System; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace SharpGen.Runtime; public abstract partial class CallbackBase { private readonly struct ImmediateShadowInterfaceInfo { public readonly TypeInfo Type; public readonly List<TypeInfo> ImplementedInterfaces; public ImmediateShadowInterfaceInfo(TypeInfo type) { Type = type; ImplementedInterfaces = new(6); foreach (var implementedInterface in type.ImplementedInterfaces) { var interfaceInfo = implementedInterface.GetTypeInfo(); // If there is no Vtbl attribute then this isn't a native interface. if (!VtblAttribute.Has(interfaceInfo)) continue; ImplementedInterfaces.Add(interfaceInfo); } } } // Cache reflection on interface inheritance private class CallbackTypeInfo { private readonly TypeInfo type; private ImmediateShadowInterfaceInfo[]? _vtbls; private TypeInfo[]? _shadows; private Guid[]? _guids; public CallbackTypeInfo(Type type) : this(type.GetTypeInfo()) { } private CallbackTypeInfo(TypeInfo type) { this.type = type ?? throw new ArgumentNullException(nameof(type)); } /// <summary> /// Gets a list of implemented interfaces that aren't inherited by any other <c>[Vtbl]</c> interfaces. /// </summary> /// <returns>The interface list.</returns> public ImmediateShadowInterfaceInfo[] Vtbls { get { lock (this) if (_vtbls is { } vtbls) return vtbls; var list = BuildVtblList(); lock (this) _vtbls = list; return list; } } public TypeInfo[] Shadows { get { lock (this) if (_shadows is { } shadows) return shadows; var list = BuildShadowList(); lock (this) _shadows = list; return list; } } public Guid[] Guids { get { lock (this) if (_guids is { } guids) return guids; var list = BuildGuidList(); lock (this) _guids = list; return list; } } private ImmediateShadowInterfaceInfo[] BuildVtblList() { HashSet<TypeInfo> removeQueue = new(); List<ImmediateShadowInterfaceInfo> result = new(); foreach (var implementedInterface in type.ImplementedInterfaces) { var item = implementedInterface.GetTypeInfo(); // Only process interfaces that have vtbl if (!VtblAttribute.Has(item)) continue; ImmediateShadowInterfaceInfo interfaceInfo = new(item); result.Add(interfaceInfo); // Keep only final interfaces and not intermediate. foreach (var @interface in interfaceInfo.ImplementedInterfaces) removeQueue.Add(@interface); } result.RemoveAll(item => removeQueue.Contains(item.Type)); return result.ToArray(); } private Guid[] BuildGuidList() { List<Guid> guids = new(); // Associate all shadows with their interfaces. foreach (var item in Vtbls) { var itemType = item.Type; if (!ExcludeFromTypeListAttribute.Has(itemType)) guids.Add(itemType.GUID); // Associate also inherited interface to this shadow foreach (var inheritInterface in item.ImplementedInterfaces) { if (!ExcludeFromTypeListAttribute.Has(inheritInterface)) guids.Add(inheritInterface.GUID); } } #if NETCOREAPP2_0_OR_GREATER || NETSTANDARD2_1 || NET472 HashSet<Guid> guidSet = new(guids.Count); #else HashSet<Guid> guidSet = new(); #endif return guids.Where(guid => guidSet.Add(guid)).ToArray(); } private TypeInfo[] BuildShadowList() { List<TypeInfo> shadows = new(), result; foreach (var implementedInterface in type.ImplementedInterfaces) { var attribute = ShadowAttribute.Get(implementedInterface); // Only process interfaces that have Shadow attribute if (attribute is null) continue; shadows.Add(attribute.Type.GetTypeInfo()); } var count = shadows.Count; result = new List<TypeInfo>(count); // Retain only shadows which have no other subtypes (none of the other shadows are children) for (var i = 0; i < count; i++) { var item = shadows[i]; var any = false; for (var j = 0; j < count; j++) { if (i == j) continue; if (item.IsAssignableFrom(shadows[j])) { any = true; break; } } if (!any) result.Add(item); } return result.ToArray(); } } } <|start_filename|>SharpGen.Runtime/VtblAttribute.cs<|end_filename|> using System; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; namespace SharpGen.Runtime; /// <summary> /// Vtbl attribute is used to associate a C++ callable managed interface to its virtual method table static type. /// </summary> [AttributeUsage(AttributeTargets.Interface)] public sealed class VtblAttribute : Attribute { /// <summary> /// Type of the associated virtual method table /// </summary> public Type Type { get; } /// <summary> /// Initializes a new instance of <see cref="VtblAttribute"/> class. /// </summary> /// <param name="holder">Type of the associated virtual method table</param> public VtblAttribute(Type holder) { Type = holder ?? throw new ArgumentNullException(nameof(holder)); Debug.Assert(Type.GetTypeInfo() is { IsClass: true, IsAbstract: true, IsSealed: true }); } [MethodImpl(Utilities.MethodAggressiveOptimization)] internal static VtblAttribute Get(Type type) => Get(type.GetTypeInfo()); [MethodImpl(Utilities.MethodAggressiveOptimization)] internal static VtblAttribute Get(TypeInfo type) => type.GetCustomAttribute<VtblAttribute>(); internal static bool Has(Type type) => Get(type.GetTypeInfo()) != null; internal static bool Has(TypeInfo type) => Get(type) != null; } <|start_filename|>SharpGen/VisualStudioSetup/SetupConfigurationClass.cs<|end_filename|>  using System.Runtime.InteropServices; namespace SharpGen.VisualStudioSetup; [Guid("177F0C4A-1CD3-4DE7-A32C-71DBBB9FA36D")] [ClassInterface(ClassInterfaceType.None)] [ComImport] public class SetupConfigurationClass { } <|start_filename|>SharpGen.Runtime/MarshallingHelpers.cs<|end_filename|> using System; using System.Runtime.CompilerServices; namespace SharpGen.Runtime; public static partial class MarshallingHelpers { /// <summary> /// Instantiate a CppObject from a native pointer. /// </summary> /// <typeparam name="T">The CppObject class that will be returned</typeparam> /// <param name="cppObjectPtr">The native pointer to a C++ object.</param> /// <returns>An instance of T bound to the native pointer</returns> public static T FromPointer<T>(IntPtr cppObjectPtr) where T : CppObject => cppObjectPtr == IntPtr.Zero ? null : (T) Activator.CreateInstance(typeof(T), cppObjectPtr); /// <summary> /// Instantiate a CppObject from a native pointer. /// </summary> /// <typeparam name="T">The CppObject class that will be returned</typeparam> /// <param name="cppObjectPtr">The native pointer to a C++ object.</param> /// <returns>An instance of T bound to the native pointer</returns> public static T FromPointer<T>(UIntPtr cppObjectPtr) where T : CppObject => cppObjectPtr == UIntPtr.Zero ? null : (T) Activator.CreateInstance(typeof(T), cppObjectPtr); [MethodImpl(Utilities.MethodAggressiveOptimization)] public static uint AddRef<TCallback>(TCallback callback) where TCallback : ICallbackable => callback switch { null => throw new NullReferenceException(), ComObject cpp => cpp.AddRef(), CallbackBase managed => managed.AddRef(), }; [MethodImpl(Utilities.MethodAggressiveOptimization)] public static uint Release<TCallback>(TCallback callback) where TCallback : ICallbackable => callback switch { null => throw new NullReferenceException(), ComObject cpp => cpp.Release(), CallbackBase managed => managed.Release(), }; /// <summary> /// Return the unmanaged C++ pointer from a <see cref="SharpGen.Runtime.ICallbackable"/> instance. /// </summary> /// <typeparam name="TCallback">The type of the callback.</typeparam> /// <param name="callback">The callback.</param> /// <returns>A pointer to the unmanaged C++ object of the callback</returns> public static IntPtr ToCallbackPtr<TCallback>(ICallbackable callback) where TCallback : ICallbackable => callback switch { null => IntPtr.Zero, CppObject cpp => cpp.NativePointer, CallbackBase managed => managed.Find<TCallback>() }; /// <summary> /// Return the unmanaged C++ pointer from a <see cref="SharpGen.Runtime.CppObject"/> instance. /// </summary> /// <typeparam name="TCallback">The type of the callback.</typeparam> /// <param name="obj">The object.</param> /// <returns>A pointer to the unmanaged C++ object of the callback</returns> /// <remarks>This method is meant as a fast-path for codegen to use to reduce the number of casts.</remarks> [MethodImpl(Utilities.MethodAggressiveOptimization)] public static IntPtr ToCallbackPtr<TCallback>(CppObject obj) where TCallback : ICallbackable => obj?.NativePointer ?? IntPtr.Zero; /// <summary> /// Return the unmanaged C++ pointer from a <see cref="SharpGen.Runtime.CppObject"/> instance. /// </summary> /// <param name="obj">The object.</param> /// <returns>A pointer to the unmanaged C++ object of the callback</returns> /// <remarks>This method is meant as a fast-path for codegen to use to reduce the number of casts.</remarks> [MethodImpl(Utilities.MethodAggressiveOptimization)] public static IntPtr ToCallbackPtr(CppObject obj) => obj?.NativePointer ?? IntPtr.Zero; } <|start_filename|>SharpGen/Generator/RoslynGenerator.cs<|end_filename|> using System; using System.Collections.Generic; using System.IO; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using SharpGen.Model; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; namespace SharpGen.Generator; public sealed class RoslynGenerator { private static readonly SyntaxTokenList ModuleInitModifiers = TokenList(Token(SyntaxKind.InternalKeyword), Token(SyntaxKind.StaticKeyword)); private const string AutoGeneratedCommentText = "// <auto-generated/>\n"; private static readonly AttributeListSyntax ModuleInitializerAttributeList = AttributeList( SingletonSeparatedList(Attribute(ParseName("System.Runtime.CompilerServices.ModuleInitializerAttribute"))) ); public SyntaxTree Run(CsAssembly csAssembly, Ioc ioc) { var logger = ioc.Logger; var generators = ioc.Generators; logger.Message("Generating Roslyn syntax tree..."); var resultConstants = csAssembly.Namespaces .SelectMany(x => x.EnumerateDescendants<CsResultConstant>(withAdditionalItems: false)) .ToArray(); var moduleInitializer = resultConstants.Length > 0 ? new[] { ClassDeclaration("ModuleDataInitializer") .WithModifiers(ModuleInitModifiers) .AddMembers(GenerateResultDescriptor(resultConstants, ioc)) } : Enumerable.Empty<MemberDeclarationSyntax>(); MemberDeclarationSyntax NamespaceSelector(CsNamespace ns) { MemberSyntaxList list = new(ioc); list.AddRange(ns.Enums.OrderBy(element => element.Name), generators.Enum); list.AddRange(ns.Structs.OrderBy(element => element.Name), generators.Struct); list.AddRange(ns.Classes.OrderBy(element => element.Name), generators.Group); list.AddRange(ns.Interfaces.OrderBy(element => element.Name), generators.Interface); return NamespaceDeclaration(ParseName(ns.Name), default, default, List(list)) .WithLeadingTrivia(Comment(AutoGeneratedCommentText)); } return CSharpSyntaxTree.Create( RoslynSyntaxNormalizer.Normalize( CompilationUnit( default, default, default, List(csAssembly.Namespaces.Select(NamespaceSelector)).AddRange(moduleInitializer) ), " ", "\r\n", true ) ); } private MethodDeclarationSyntax GenerateResultDescriptor(CsResultConstant[] descriptors, Ioc ioc) { StatementSyntaxList list = new(ioc); list.AddRange(descriptors, ioc.Generators.ResultRegistration); return MethodDeclaration(PredefinedType(Token(SyntaxKind.VoidKeyword)), "RegisterResultCodes") .WithModifiers(ModuleInitModifiers) .AddAttributeLists(ModuleInitializerAttributeList) .WithBody(list.ToBlock()); } } <|start_filename|>SharpGen/Config/Preprocessor.cs<|end_filename|> // Copyright (c) 2010-2014 SharpDX - <NAME> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.IO; using System.Linq; using System.Xml; using System.Xml.Linq; namespace SharpGen.Config; /// <summary> /// A simple XML preprocessor. /// </summary> internal static class Preprocessor { /// <summary> /// Preprocesses the XML document given the reader instance. /// </summary> public static void Preprocess(XmlReader xmlReader, Stream outputStream, params string[] macros) { var doc = XDocument.Load(xmlReader); XNamespace ns = ConfigFile.XmlNamespace; var list = doc.Descendants(ns + "ifndef").ToList(); // Work on deepest first list.Reverse(); foreach (var ifndef in list) { var attr = ifndef.Attribute("name"); if (attr != null && macros.Contains(attr.Value)) { ifndef.Remove(); } else { foreach (var element in ifndef.Elements()) { ifndef.AddBeforeSelf(element); } ifndef.Remove(); } } list.Clear(); list.AddRange(doc.Descendants(ns + "ifdef")); // Work on deepest first list.Reverse(); foreach (var ifdef in list) { var attr = ifdef.Attribute("name"); if (attr != null && !string.IsNullOrWhiteSpace(attr.Value)) { var values = attr.Value.Split(new[] { "|" }, StringSplitOptions.RemoveEmptyEntries); if (values.Any(macros.Contains)) { foreach (var element in ifdef.Elements()) { ifdef.AddBeforeSelf(element); } } } ifdef.Remove(); } doc.Save(outputStream); } } <|start_filename|>SharpGen.Runtime/COM/IInspectableWithTrustLevel.cs<|end_filename|> namespace SharpGen.Runtime; public interface IInspectableWithTrustLevel { TrustLevel TrustLevel { get; } } <|start_filename|>SharpGen.UnitTests/Platform/IncludeDirectoryResolverTests.cs<|end_filename|> using System.Linq; using System.Runtime.InteropServices; using SharpGen.Config; using SharpGen.Logging; using SharpGen.Platform; using Xunit; using Xunit.Abstractions; namespace SharpGen.UnitTests.Platform; public class IncludeDirectoryResolverTests : TestBase { private readonly IncludeDirectoryResolver resolver; public IncludeDirectoryResolverTests(ITestOutputHelper outputHelper) : base(outputHelper) { resolver = new IncludeDirectoryResolver(Ioc); } [SkippableFact] public void CanResolveRegistryPath() { Skip.IfNot(RuntimeInformation.IsOSPlatform(OSPlatform.Windows), "Registry paths can only be resolved on Windows"); resolver.AddDirectories(new IncludeDirRule(@"=HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows Kits\Installed Roots\KitsRoot10")); Assert.Equal($@"-isystem""C:\Program Files (x86)\Windows Kits\10""", resolver.IncludeArguments.First()); } [SkippableFact] public void CanResolveRegistryPathWithSubPath() { Skip.IfNot(RuntimeInformation.IsOSPlatform(OSPlatform.Windows), "Registry paths can only be resolved on Windows"); resolver.AddDirectories(new IncludeDirRule(@"=HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows Kits\Installed Roots\KitsRoot10;SubFolder")); Assert.Equal($@"-isystem""C:\Program Files (x86)\Windows Kits\10\SubFolder""", resolver.IncludeArguments.First()); } [SkippableFact] public void RegistryPathsFailToResolveOffWindows() { Skip.If(RuntimeInformation.IsOSPlatform(OSPlatform.Windows)); resolver.AddDirectories(new IncludeDirRule(@"=HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows Kits\Installed Roots\KitsRoot10;SubFolder")); using (LoggerMessageCountEnvironment(1, LogLevel.Error)) using (LoggerMessageCountEnvironment(0, ~LogLevel.Error)) using (LoggerCodeRequiredEnvironment(LoggingCodes.RegistryKeyNotFound)) { resolver.IncludeArguments.ToArray(); } } } <|start_filename|>SharpGen/Transform/MethodOverloadBuilder.cs<|end_filename|> using System; using SharpGen.Config; using SharpGen.Model; namespace SharpGen.Transform; internal sealed class MethodOverloadBuilder { private readonly Ioc ioc; public MethodOverloadBuilder(Ioc ioc) { this.ioc = ioc ?? throw new ArgumentNullException(nameof(ioc)); } private GlobalNamespaceProvider GlobalNamespace => ioc.GlobalNamespace; public CsMethod CreateInterfaceArrayOverload(CsMethod original) { // Create a new method and transforms all array of CppObject to InterfaceArray<CppObject> var newMethod = (CsMethod)original.Clone(); foreach (var csParameter in newMethod.PublicParameters) { if (!csParameter.IsInInterfaceArrayLike) continue; csParameter.PublicType = new CsInterfaceArray( (CsInterface) csParameter.PublicType, GlobalNamespace.GetTypeName(WellKnownName.InterfaceArray) ); csParameter.MarshalType = TypeRegistry.IntPtr; } return newMethod; } public CsMethod CreateRawPtrOverload(CsMethod original) { // Create private method with raw pointers for arrays, with all arrays as pure IntPtr // In order to be able to generate method taking single element var rawMethod = (CsMethod)original.Clone(); rawMethod.Visibility = Visibility.Private; foreach (var csSubParameter in rawMethod.PublicParameters) { if (csSubParameter.IsArray || csSubParameter.IsInterface || csSubParameter.HasPointer) { csSubParameter.PublicType = csSubParameter.MarshalType = TypeRegistry.IntPtr; csSubParameter.IsArray = false; csSubParameter.Attribute = CsParameterAttribute.In; } } return rawMethod; } } <|start_filename|>SharpGen/Generator/GeneratorHelpers.cs<|end_filename|> using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using SharpGen.Model; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; namespace SharpGen.Generator; public static class GeneratorHelpers { private static readonly PlatformDetectionType[] Platforms = (PlatformDetectionType[])Enum.GetValues(typeof(PlatformDetectionType)); private static readonly PlatformDetectionType[] PlatformsNoAny = Platforms.Where(x => x != PlatformDetectionType.Any).ToArray(); private static readonly int PlatformsNoAnyStringLength = PlatformsNoAny.Select(x => x.ToString().Length).Max() + 2; private static ThrowStatementSyntax ThrowException(TypeSyntax exception, string message) => ThrowStatement( ObjectCreationExpression( exception, ArgumentList( message == null ? default : SingletonSeparatedList( Argument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(message))) ) ), null ) ); private static readonly ThrowStatementSyntax ThrowPlatformNotSupportedStatement = ThrowException( ParseTypeName("System.PlatformNotSupportedException"), null ); internal static readonly LiteralExpressionSyntax ZeroLiteral = LiteralExpression( SyntaxKind.NumericLiteralExpression, Literal(0) ); internal static readonly IdentifierNameSyntax VarIdentifierName = IdentifierName( Identifier(SyntaxTriviaList.Empty, SyntaxKind.VarKeyword, "var", "var", SyntaxTriviaList.Empty) ); public static ExpressionSyntax WrapInParentheses(ExpressionSyntax expression) => expression is TypeSyntax or ParenthesizedExpressionSyntax or LiteralExpressionSyntax or InvocationExpressionSyntax or MemberAccessExpressionSyntax or ElementAccessExpressionSyntax or MemberBindingExpressionSyntax or ThisExpressionSyntax or BaseExpressionSyntax ? expression : ParenthesizedExpression(expression); public static ExpressionSyntax LengthExpression(ExpressionSyntax expression) => MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, WrapInParentheses(expression), IdentifierName("Length") ); public static ExpressionSyntax OptionalLengthExpression(ExpressionSyntax expression) => BinaryExpression( SyntaxKind.CoalesceExpression, ConditionalAccessExpression( WrapInParentheses(expression), MemberBindingExpression(IdentifierName("Length")) ), ZeroLiteral ); public static ExpressionSyntax CastExpression(TypeSyntax type, ExpressionSyntax expression) { var wrappedExpression = WrapInParentheses(expression); return expression is CastExpressionSyntax {Type: { } castType} && castType.IsEquivalentTo(type) ? wrappedExpression : SyntaxFactory.CastExpression(type, wrappedExpression); } public static ExpressionSyntax GenerateBoolToIntConversion(ExpressionSyntax valueExpression) => ConditionalExpression( WrapInParentheses(valueExpression), LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(1)), ZeroLiteral ); public static BinaryExpressionSyntax GenerateIntToBoolConversion(ExpressionSyntax valueExpression) => BinaryExpression( SyntaxKind.NotEqualsExpression, ZeroLiteral, valueExpression ); public static TypeSyntax IntPtrType { get; } = ParseTypeName("System.IntPtr"); public static TypeSyntax UIntPtrType { get; } = ParseTypeName("System.UIntPtr"); public static MemberAccessExpressionSyntax IntPtrZero { get; } = MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, IntPtrType, IdentifierName(nameof(IntPtr.Zero)) ); public static TypeSyntax VoidPtrType { get; } = PointerType(PredefinedType(Token(SyntaxKind.VoidKeyword))); public static string GetPlatformSpecificSuffix(PlatformDetectionType platform) { if (platform == PlatformDetectionType.Any) return "_"; StringBuilder str = new("_", PlatformsNoAnyStringLength); foreach (var flag in PlatformsNoAny) { if ((platform & flag) != flag) continue; str.Append(flag); str.Append('_'); } return str.ToString(); } public static StatementSyntax GetPlatformSpecificStatements(GlobalNamespaceProvider globalNamespace, GeneratorConfig config, IEnumerable<PlatformDetectionType> types, Func<PlatformDetectionType, StatementSyntax> syntaxBuilder) { List<IfStatementSyntax> ifStatements = new(); var allPlatformBitmap = config.Platforms; foreach (var platform in types) { var platformStatement = syntaxBuilder(platform); if ((platform & allPlatformBitmap) == allPlatformBitmap) return platformStatement; ExpressionSyntax condition = null; foreach (var flag in PlatformsNoAny) { if ((platform & flag) != flag) continue; var newCondition = PlatformCondition(globalNamespace, flag); condition = condition is null ? newCondition : BinaryExpression(SyntaxKind.LogicalAndExpression, condition, newCondition); } ifStatements.Add( condition is null ? (IfStatementSyntax) platformStatement : IfStatement(condition, platformStatement) ); } IfStatementSyntax platformDetectionIfStatement = null; for (var i = ifStatements.Count - 1; i >= 0; i--) { platformDetectionIfStatement = ifStatements[i].WithElse( platformDetectionIfStatement is null ? ElseClause(ThrowPlatformNotSupportedStatement) : ElseClause(platformDetectionIfStatement) ); } return platformDetectionIfStatement; } public static ExpressionSyntax PlatformCondition(GlobalNamespaceProvider globalNamespace, PlatformDetectionType flag) => MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, globalNamespace.GetTypeNameSyntax(WellKnownName.PlatformDetection), IdentifierName("Is" + flag) ); public static T WithLeadingIfDirective<T>(this T node, ExpressionSyntax condition) where T : SyntaxNode => node.WithLeadingTrivia( node.GetLeadingTrivia().Insert(0, Trivia(IfDirectiveTrivia(condition, true, true, true))) ); public static T WithTrailingEndIfDirective<T>(this T node) where T : SyntaxNode => node.WithTrailingTrivia(node.GetTrailingTrivia().Add(Trivia(EndIfDirectiveTrivia(true)))); public static T WithTrailingElseDirective<T>(this T node) where T : SyntaxNode => node.WithTrailingTrivia(node.GetTrailingTrivia().Add(Trivia(ElseDirectiveTrivia(true, true)))); public static LocalDeclarationStatementSyntax VarDeclaration(SyntaxToken name, ExpressionSyntax value) => LocalDeclarationStatement( VariableDeclaration( VarIdentifierName, SingletonSeparatedList(VariableDeclarator(name, default, EqualsValueClause(value))) ) ); public static Func<CsMethod, int> GetOffsetGetter(PlatformDetectionType platform) { return platform switch { PlatformDetectionType.Windows => WindowsOffsetGetter, PlatformDetectionType.ItaniumSystemV => ItaniumSystemVOffsetGetter, _ => throw new ArgumentOutOfRangeException(nameof(platform), platform, null) }; static int WindowsOffsetGetter(CsMethod x) => x.WindowsOffset; static int ItaniumSystemVOffsetGetter(CsMethod x) => x.Offset; } public delegate ExpressionSyntax ExpressionTransform<in T>(T expression) where T : ExpressionSyntax; private static ExpressionSyntax IdentityExpressionTransformImpl<T>(T expression) where T : ExpressionSyntax => expression; public static ExpressionSyntax PlatformSpecificExpression<T>(GlobalNamespaceProvider globalNamespace, PlatformDetectionType platform, Func<bool> anyPredicate, Func<T> windowsExpression, Func<T> nonWindowsExpression, ExpressionTransform<T> conditionalWrapper = null) where T : ExpressionSyntax { if ((platform & PlatformDetectionType.Any) == PlatformDetectionType.Any && anyPredicate()) { conditionalWrapper ??= IdentityExpressionTransformImpl; return ConditionalExpression( PlatformCondition(globalNamespace, PlatformDetectionType.Windows), conditionalWrapper(windowsExpression()), conditionalWrapper(nonWindowsExpression()) ); } // Use the Windows offset for the default offset in the vtable when the Windows platform is requested for compat reasons. return (platform & PlatformDetectionType.Windows) != 0 ? windowsExpression() : nonWindowsExpression(); } public static readonly IdentifierNameSyntax PreprocessorNameSyntax = IdentifierName("NET5_0_OR_GREATER"); public static readonly PrefixUnaryExpressionSyntax NotPreprocessorNameSyntax = PrefixUnaryExpression(SyntaxKind.LogicalNotExpression, PreprocessorNameSyntax); } <|start_filename|>SharpGen/Config/ConfigExtensions.cs<|end_filename|> using System.Collections.Generic; using System.Linq; using SharpGen.CppModel; using SharpGen.Logging; namespace SharpGen.Config; public static class ConfigExtensions { public static CppModule CreateSkeletonModule(this ConfigFile config) { var module = new CppModule(config.Id); foreach (var includeRule in config.ConfigFilesLoaded.SelectMany(cfg => cfg.Includes)) { var cppInclude = module.FindInclude(includeRule.Id); if (cppInclude != null) continue; module.Add(new CppInclude(includeRule.Id)); } return module; } public static void ExpandDynamicVariables(this ConfigFile config, Logger logger, CppModule module) { // Load all defines and store them in the config file to allow dynamic variable substitution foreach (var cppInclude in module.Includes) { foreach (var cppDefine in cppInclude.Macros) { config.DynamicVariables[cppDefine.Name] = cppDefine.Value; } } // Expand all variables with all dynamic variables config.ExpandVariables(true, logger); } public static void GetFilesWithIncludesAndExtensionHeaders(this ConfigFile configRoot, out HashSet<ConfigFile> filesWithIncludes, out HashSet<ConfigFile> filesWithExtensionHeaders) { filesWithExtensionHeaders = new HashSet<ConfigFile>(ConfigFile.IdComparer); filesWithIncludes = new HashSet<ConfigFile>(ConfigFile.IdComparer); // Check if the file has any includes related config foreach (var configFile in configRoot.ConfigFilesLoaded) { // Build prolog var includesAnyFiles = configFile.IncludeProlog.Count > 0 || configFile.Includes.Count > 0 || configFile.References.Count > 0; if (configFile.Extension.Any(rule => rule.GeneratesExtensionHeader())) { filesWithExtensionHeaders.Add(configFile); includesAnyFiles = true; } // If this config file has any include rules if (includesAnyFiles) filesWithIncludes.Add(configFile); } } /// <summary> /// Checks if this rule is creating headers extension. /// </summary> /// <param name="rule">The rule to check.</param> /// <returns>true if the rule is creating an header extension.</returns> public static bool GeneratesExtensionHeader(this ExtensionBaseRule rule) { return rule is CreateCppExtensionRule createCpp && !string.IsNullOrEmpty(createCpp.Macro) || rule is ConstantRule constant && !string.IsNullOrEmpty(constant.Macro); } } <|start_filename|>SharpGen/Generator/Marshallers/WrapperMarshallerBase.cs<|end_filename|> using System; using System.Collections.Generic; using Microsoft.CodeAnalysis.CSharp.Syntax; using SharpGen.Model; namespace SharpGen.Generator.Marshallers; internal abstract class WrapperMarshallerBase : MarshallerBase, IMarshaller { private readonly IMarshaller implementation; protected WrapperMarshallerBase(Ioc ioc, IMarshaller implementation) : base(ioc) { this.implementation = implementation ?? throw new ArgumentNullException(nameof(implementation)); } public virtual IEnumerable<StatementSyntax> GenerateManagedToNativeProlog(CsMarshalCallableBase csElement) => implementation.GenerateManagedToNativeProlog(csElement); public virtual IEnumerable<StatementSyntax> GenerateNativeToManagedExtendedProlog(CsMarshalCallableBase csElement) => implementation.GenerateNativeToManagedExtendedProlog(csElement); public virtual StatementSyntax GenerateManagedToNative(CsMarshalBase csElement, bool singleStackFrame) => implementation.GenerateManagedToNative(csElement, singleStackFrame); public virtual StatementSyntax GenerateNativeToManaged(CsMarshalBase csElement, bool singleStackFrame) => implementation.GenerateNativeToManaged(csElement, singleStackFrame); public virtual ArgumentSyntax GenerateNativeArgument(CsMarshalCallableBase csElement) => implementation.GenerateNativeArgument(csElement); public virtual ArgumentSyntax GenerateManagedArgument(CsParameter csElement) => implementation.GenerateManagedArgument(csElement); public virtual ParameterSyntax GenerateManagedParameter(CsParameter csElement) => implementation.GenerateManagedParameter(csElement); public virtual StatementSyntax GenerateNativeCleanup(CsMarshalBase csElement, bool singleStackFrame) => implementation.GenerateNativeCleanup(csElement, singleStackFrame); public virtual FixedStatementSyntax GeneratePin(CsParameter csElement) => implementation.GeneratePin(csElement); public virtual bool CanMarshal(CsMarshalBase csElement) => implementation.CanMarshal(csElement); public virtual bool GeneratesMarshalVariable(CsMarshalCallableBase csElement) => implementation.GeneratesMarshalVariable(csElement); public virtual TypeSyntax GetMarshalTypeSyntax(CsMarshalBase csElement) => implementation.GetMarshalTypeSyntax(csElement); } <|start_filename|>SharpGen/Generator/Marshallers/ArrayOfInterfaceMarshaller.cs<|end_filename|> using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using SharpGen.Model; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; namespace SharpGen.Generator.Marshallers; internal sealed class ArrayOfInterfaceMarshaller : ArrayMarshallerBase { public override bool CanMarshal(CsMarshalBase csElement) => csElement.IsArray && csElement.IsInterface; public override StatementSyntax GenerateManagedToNative(CsMarshalBase csElement, bool singleStackFrame) => LoopThroughArrayParameter( csElement, (publicElement, marshalElement) => MarshalInterfaceInstanceToNative(csElement, publicElement, marshalElement) ); public override StatementSyntax GenerateNativeCleanup(CsMarshalBase csElement, bool singleStackFrame) => GenerateGCKeepAlive(csElement); public override StatementSyntax GenerateNativeToManaged(CsMarshalBase csElement, bool singleStackFrame) => csElement switch { CsParameter {IsFast: true, IsOut: true} => GenerateNullCheckIfNeeded( csElement, ExpressionStatement( InvocationExpression( MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, GlobalNamespace.GetTypeNameSyntax(WellKnownName.MarshallingHelpers), GenericName(Identifier("ConvertToInterfaceArrayFast")) .WithTypeArgumentList( TypeArgumentList( SingletonSeparatedList<TypeSyntax>( IdentifierName(csElement.PublicType.QualifiedName) ) ) ) ), ArgumentList( SeparatedList(new[] { // ReadOnlySpan<IntPtr> pointers, Span<TCallback> interfaces Argument(GetMarshalStorageLocation(csElement)), Argument(IdentifierName(csElement.Name)) } ) ) ) ) ), _ => LoopThroughArrayParameter( csElement, (publicElement, marshalElement) => MarshalInterfaceInstanceFromNative(csElement, publicElement, marshalElement) ) }; protected override TypeSyntax GetMarshalElementTypeSyntax(CsMarshalBase csElement) => IntPtrType; public ArrayOfInterfaceMarshaller(Ioc ioc) : base(ioc) { } } <|start_filename|>SharpGen.Runtime/COM/ComObject.cs<|end_filename|> // Copyright (c) 2010-2014 SharpDX - <NAME> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Reflection; using System.Runtime.InteropServices; using System.Runtime.Versioning; using SharpGen.Runtime.Diagnostics; namespace SharpGen.Runtime; /// <unmanaged>IUnknown</unmanaged> /// <unmanaged-short>IUnknown</unmanaged-short> [Guid("00000000-0000-0000-C000-000000000046")] public class ComObject : CppObject, IUnknown { public ComObject(IntPtr nativePtr): base(nativePtr) { } public static explicit operator ComObject(IntPtr nativePtr) => nativePtr == IntPtr.Zero ? null : new ComObject(nativePtr); /// <unmanaged>HRESULT IUnknown::QueryInterface([In] const GUID&amp; riid, [Out] void** ppvObject)</unmanaged> /// <unmanaged-short>IUnknown::QueryInterface</unmanaged-short> public unsafe Result QueryInterface(Guid riid, out IntPtr ppvObject) { Result __result__; fixed (void* ppvObject_ = &ppvObject) __result__ = ((delegate* unmanaged[Stdcall]<IntPtr, void*, void*, int> )this[0U])(NativePointer, &riid, ppvObject_); return __result__; } /// <unmanaged>ULONG IUnknown::AddRef()</unmanaged> /// <unmanaged-short>IUnknown::AddRef</unmanaged-short> public unsafe uint AddRef() { uint __result__; __result__ = ((delegate* unmanaged[Stdcall]<IntPtr, uint> )this[1U])(NativePointer); return __result__; } /// <unmanaged>ULONG IUnknown::Release()</unmanaged> /// <unmanaged-short>IUnknown::Release</unmanaged-short> public unsafe uint Release() { uint __result__; __result__ = ((delegate* unmanaged[Stdcall]<IntPtr, uint> )this[2U])(NativePointer); return __result__; } /// <summary> /// Initializes a new instance of the <see cref="ComObject"/> class from a IUnknown object. /// </summary> /// <param name="iunknownObject">Reference to a IUnknown object</param> #if NET5_0_OR_GREATER [SupportedOSPlatform("windows")] #endif public ComObject(object iunknownObject) : base(Marshal.GetIUnknownForObject(iunknownObject)) { } /// <summary> /// Initializes a new instance of the <see cref="ComObject"/> class. /// </summary> protected ComObject() { } /// <summary> /// Query instance for a particular COM GUID/interface support. /// </summary> /// <param name = "guid">GUID query interface</param> /// <msdn-id>ms682521</msdn-id> /// <unmanaged>IUnknown::QueryInterface</unmanaged> /// <unmanaged-short>IUnknown::QueryInterface</unmanaged-short> public virtual IntPtr QueryInterfaceOrNull(Guid guid) { QueryInterface(guid, out var pointer); return pointer; } ///<summary> /// Query this instance for a particular COM interface support. ///</summary> ///<typeparam name="T">The type of the COM interface to query</typeparam> ///<returns>An instance of the queried interface</returns> /// <exception cref="SharpGenException">If this object doesn't support the interface</exception> /// <msdn-id>ms682521</msdn-id> /// <unmanaged>IUnknown::QueryInterface</unmanaged> /// <unmanaged-short>IUnknown::QueryInterface</unmanaged-short> public virtual T QueryInterface<T>() where T : ComObject { QueryInterface(typeof(T).GetTypeInfo().GUID, out var parentPtr).CheckError(); return MarshallingHelpers.FromPointer<T>(parentPtr); } /// <summary> /// Queries a managed object for a particular COM interface support (This method is a shortcut to <see cref="QueryInterface"/>) /// </summary> ///<typeparam name="T">The type of the COM interface to query</typeparam> /// <param name="comObject">The managed COM object.</param> ///<returns>An instance of the queried interface</returns> /// <msdn-id>ms682521</msdn-id> /// <unmanaged>IUnknown::QueryInterface</unmanaged> /// <unmanaged-short>IUnknown::QueryInterface</unmanaged-short> #if NET5_0_OR_GREATER [SupportedOSPlatform("windows")] #endif public static T As<T>(object comObject) where T : ComObject => As<T>(Marshal.GetIUnknownForObject(comObject)); /// <summary> /// Queries a managed object for a particular COM interface support (This method is a shortcut to <see cref="QueryInterface"/>) /// </summary> ///<typeparam name="T">The type of the COM interface to query</typeparam> /// <param name="iunknownPtr">The managed COM object.</param> ///<returns>An instance of the queried interface</returns> /// <msdn-id>ms682521</msdn-id> /// <unmanaged>IUnknown::QueryInterface</unmanaged> /// <unmanaged-short>IUnknown::QueryInterface</unmanaged-short> public static T As<T>(IntPtr iunknownPtr) where T : ComObject { using var tempObject = new ComObject(iunknownPtr); return tempObject.QueryInterface<T>(); } /// <summary> /// Queries a managed object for a particular COM interface support. /// </summary> ///<typeparam name="T">The type of the COM interface to query</typeparam> /// <param name="comObject">The managed COM object.</param> ///<returns>An instance of the queried interface</returns> /// <msdn-id>ms682521</msdn-id> /// <unmanaged>IUnknown::QueryInterface</unmanaged> /// <unmanaged-short>IUnknown::QueryInterface</unmanaged-short> #if NET5_0_OR_GREATER [SupportedOSPlatform("windows")] #endif public static T QueryInterface<T>(object comObject) where T : ComObject => As<T>(Marshal.GetIUnknownForObject(comObject)); /// <summary> /// Queries a managed object for a particular COM interface support. /// </summary> ///<typeparam name="T">The type of the COM interface to query</typeparam> /// <param name="comPointer">A pointer to a COM object.</param> ///<returns>An instance of the queried interface</returns> /// <msdn-id>ms682521</msdn-id> /// <unmanaged>IUnknown::QueryInterface</unmanaged> /// <unmanaged-short>IUnknown::QueryInterface</unmanaged-short> public static T QueryInterfaceOrNull<T>(IntPtr comPointer) where T : ComObject { using var tempObject = new ComObject(comPointer); return tempObject.QueryInterfaceOrNull<T>(); } ///<summary> /// Query Interface for a particular interface support. ///</summary> ///<returns>An instance of the queried interface or null if it is not supported</returns> ///<returns></returns> /// <msdn-id>ms682521</msdn-id> /// <unmanaged>IUnknown::QueryInterface</unmanaged> /// <unmanaged-short>IUnknown::QueryInterface</unmanaged-short> public virtual T QueryInterfaceOrNull<T>() where T : ComObject => MarshallingHelpers.FromPointer<T>(QueryInterfaceOrNull(typeof(T).GetTypeInfo().GUID)); ///<summary> /// Query Interface for a particular interface support and attach to the given instance. ///</summary> ///<typeparam name="T"></typeparam> ///<returns></returns> protected void QueryInterfaceFrom<T>(T fromObject) where T : ComObject => NativePointer = fromObject.QueryInterfaceOrNull(GetType().GetTypeInfo().GUID); protected override void DisposeCore(IntPtr nativePointer, bool disposing) { // Release the object if (disposing || ObjectTrackerReadOnlyConfiguration.IsReleaseOnFinalizerEnabled) Release(); } } <|start_filename|>SharpGen.Platform/Documentation/DocItem.cs<|end_filename|> using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.Linq; using SharpGen.Doc; namespace SharpGen.Platform.Documentation; internal sealed class DocItem : IDocItem { private readonly ObservableCollection<IDocSubItem> items = new(); private readonly ObservableSet<string> names = new(StringComparer.InvariantCultureIgnoreCase); private readonly ObservableSet<string> seeAlso = new(StringComparer.InvariantCultureIgnoreCase); private bool isDirty; private string remarks; private string @return; private string shortId; private string summary; public DocItem() { names.CollectionChanged += OnCollectionChanged; items.CollectionChanged += OnCollectionChanged; seeAlso.CollectionChanged += OnCollectionChanged; } public string ShortId { get => shortId; set { if (shortId == value) return; shortId = value; IsDirty = true; } } public IList<string> Names => names; public string Summary { get => summary; set { if (summary == value) return; summary = value; IsDirty = true; } } public string Remarks { get => remarks; set { if (remarks == value) return; remarks = value; IsDirty = true; } } public string Return { get => @return; set { if (@return == value) return; @return = value; IsDirty = true; } } public IList<IDocSubItem> Items => items; public IList<string> SeeAlso => seeAlso; public bool IsDirty { get => isDirty ? isDirty : isDirty = items.Any(DirtyPredicate); set => isDirty = value; } private void OnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { IsDirty = true; } private static bool DirtyPredicate(IDocSubItem x) => x.IsDirty; } <|start_filename|>SharpGen.UnitTests/LoggerAssertHandler.cs<|end_filename|> namespace SharpGen.UnitTests; public delegate void LoggerAssertHandler(XUnitLogEvent[] events); <|start_filename|>SharpGen/Generator/Marshallers/ArrayMarshallerBase.cs<|end_filename|> using System.Collections.Generic; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using SharpGen.Model; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; namespace SharpGen.Generator.Marshallers; internal abstract class ArrayMarshallerBase : MarshallerBase, IMarshaller { public ArgumentSyntax GenerateManagedArgument(CsParameter csElement) => Argument(IdentifierName(csElement.Name)); public ParameterSyntax GenerateManagedParameter(CsParameter csElement) => GenerateManagedArrayParameter(csElement); public abstract StatementSyntax GenerateNativeCleanup(CsMarshalBase csElement, bool singleStackFrame); public IEnumerable<StatementSyntax> GenerateManagedToNativeProlog(CsMarshalCallableBase csElement) { var identifier = GetMarshalStorageLocationIdentifier(csElement); var elementType = GetMarshalElementTypeSyntax(csElement); var spanTypeName = GlobalNamespace.GetGenericTypeNameSyntax( BuiltinType.Span, TypeArgumentList(SingletonSeparatedList(elementType)) ); ArrayTypeSyntax GetArrayType(ExpressionSyntax length) => ArrayType( elementType, SingletonList(ArrayRankSpecifier(SingletonSeparatedList(length))) ); yield return LocalDeclarationStatement( VariableDeclaration( spanTypeName, SingletonSeparatedList( VariableDeclarator( identifier, default, EqualsValueClause(StackAllocArrayCreationExpression(GetArrayType(ZeroLiteral))) ) ) ) ); var variable = IdentifierName(identifier); var length = GeneratorHelpers.LengthExpression(IdentifierName(csElement.Name)); var arrayType = GetArrayType(LengthIdentifierName); yield return GenerateNullCheckIfNeeded( csElement, Block( LocalDeclarationStatement( VariableDeclaration( TypeInt32, SingletonSeparatedList( VariableDeclarator(LengthIdentifier, default, EqualsValueClause(length)) ) ) ), ExpressionStatement( AssignmentExpression( SyntaxKind.SimpleAssignmentExpression, variable, ConditionalExpression( BinaryExpression( SyntaxKind.LessThanExpression, BinaryExpression( SyntaxKind.MultiplyExpression, GeneratorHelpers.CastExpression(TypeUInt32, LengthIdentifierName), SizeOf(elementType) ), LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(1024u)) ), StackAllocArrayCreationExpression(arrayType), ObjectCreationExpression(arrayType) ) ) ) ) ); } public IEnumerable<StatementSyntax> GenerateNativeToManagedExtendedProlog(CsMarshalCallableBase csElement) { yield return GenerateArrayNativeToManagedExtendedProlog(csElement); } public abstract StatementSyntax GenerateManagedToNative(CsMarshalBase csElement, bool singleStackFrame); public abstract StatementSyntax GenerateNativeToManaged(CsMarshalBase csElement, bool singleStackFrame); public ArgumentSyntax GenerateNativeArgument(CsMarshalCallableBase csElement) => Argument(IdentifierName(csElement.IntermediateMarshalName)); public FixedStatementSyntax GeneratePin(CsParameter csElement) => FixedStatement( VariableDeclaration( VoidPtrType, SingletonSeparatedList( VariableDeclarator( Identifier(csElement.IntermediateMarshalName), null, EqualsValueClause(GetMarshalStorageLocation(csElement)) ) ) ), EmptyStatement() ); public abstract bool CanMarshal(CsMarshalBase csElement); public bool GeneratesMarshalVariable(CsMarshalCallableBase csElement) => true; protected abstract TypeSyntax GetMarshalElementTypeSyntax(CsMarshalBase csElement); public TypeSyntax GetMarshalTypeSyntax(CsMarshalBase csElement) => PointerType(GetMarshalElementTypeSyntax(csElement)); protected ArrayMarshallerBase(Ioc ioc) : base(ioc) { } } <|start_filename|>SharpGen/Model/InteropType.cs<|end_filename|> // Copyright (c) 2010-2014 SharpDX - <NAME> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; namespace SharpGen.Model; /// <summary> /// Type used for template /// </summary> public sealed class InteropType : IEquatable<InteropType> { public InteropType(string typeName) { if (string.IsNullOrEmpty(typeName)) throw new ArgumentException("Value cannot be null or empty.", nameof(typeName)); TypeName = typeName; } public static implicit operator InteropType(CsFundamentalType type) => new(type.Name); public static implicit operator InteropType(string input) => new(input); public string TypeName { get; } public bool Equals(InteropType other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return TypeName == other.TypeName; } public override bool Equals(object obj) => ReferenceEquals(this, obj) || obj is InteropType other && Equals(other); public override int GetHashCode() => TypeName != null ? TypeName.GetHashCode() : 0; public static bool operator ==(InteropType left, InteropType right) => Equals(left, right); public static bool operator !=(InteropType left, InteropType right) => !Equals(left, right); } <|start_filename|>SharpGenTools.Sdk/CodeGenFailedException.cs<|end_filename|> using System; namespace SharpGenTools.Sdk; internal sealed class CodeGenFailedException : Exception { public CodeGenFailedException() { } public CodeGenFailedException(string message) : base(message) { } } <|start_filename|>SharpGen/Generator/Marshallers/IMarshaller.cs<|end_filename|> using System.Collections.Generic; using Microsoft.CodeAnalysis.CSharp.Syntax; using SharpGen.Model; namespace SharpGen.Generator.Marshallers; public interface IMarshaller { IEnumerable<StatementSyntax> GenerateManagedToNativeProlog(CsMarshalCallableBase csElement); IEnumerable<StatementSyntax> GenerateNativeToManagedExtendedProlog(CsMarshalCallableBase csElement); StatementSyntax GenerateManagedToNative(CsMarshalBase csElement, bool singleStackFrame); StatementSyntax GenerateNativeToManaged(CsMarshalBase csElement, bool singleStackFrame); ArgumentSyntax GenerateNativeArgument(CsMarshalCallableBase csElement); ArgumentSyntax GenerateManagedArgument(CsParameter csElement); ParameterSyntax GenerateManagedParameter(CsParameter csElement); StatementSyntax GenerateNativeCleanup(CsMarshalBase csElement, bool singleStackFrame); FixedStatementSyntax GeneratePin(CsParameter csElement); bool CanMarshal(CsMarshalBase csElement); bool GeneratesMarshalVariable(CsMarshalCallableBase csElement); TypeSyntax GetMarshalTypeSyntax(CsMarshalBase csElement); } <|start_filename|>SharpGen.Runtime/PlatformDetection.AppContainer.cs<|end_filename|> using System; using System.ComponentModel; using System.Runtime.InteropServices; using System.Security; namespace SharpGen.Runtime; public static partial class PlatformDetection { private const int ERROR_NO_TOKEN = unchecked((int) 0x800703F0); private static SafeAccessTokenHandle GetCurrentToken(out int hr) { hr = 0; var success = OpenThreadToken(out var safeTokenHandle); if (!success) hr = Marshal.GetHRForLastWin32Error(); if (!success && hr == ERROR_NO_TOKEN) // No impersonation safeTokenHandle = GetCurrentProcessToken(out hr); return safeTokenHandle; } [DllImport(Advapi32, SetLastError = true)] private static extern bool OpenThreadToken(IntPtr threadHandle, TokenAccessLevels dwDesiredAccess, bool bOpenAsSelf, out SafeAccessTokenHandle phThreadToken); [DllImport(Kernel32)] private static extern IntPtr GetCurrentThread(); private static bool OpenThreadToken(out SafeAccessTokenHandle tokenHandle) => OpenThreadToken(GetCurrentThread(), TokenAccessLevels.Query, true, out tokenHandle) || OpenThreadToken(GetCurrentThread(), TokenAccessLevels.Query, false, out tokenHandle); [DllImport(Advapi32, SetLastError = true)] private static extern bool OpenProcessToken(IntPtr processToken, TokenAccessLevels desiredAccess, out SafeAccessTokenHandle tokenHandle); [DllImport(Kernel32)] private static extern IntPtr GetCurrentProcess(); [DllImport(Kernel32, SetLastError = true)] private static extern bool CloseHandle(IntPtr handle); private static SafeAccessTokenHandle GetCurrentProcessToken(out int hr) { hr = 0; if (!OpenProcessToken(GetCurrentProcess(), TokenAccessLevels.Query, out var safeTokenHandle)) hr = Marshal.GetHRForLastWin32Error(); return safeTokenHandle; } [DllImport(Advapi32, CharSet = CharSet.Unicode, SetLastError = true)] private static extern bool GetTokenInformation(SafeAccessTokenHandle tokenHandle, TOKEN_INFORMATION_CLASS tokenInformationClass, IntPtr tokenInformation, uint tokenInformationLength, out uint returnLength); private static unsafe bool HasAppContainerToken() { var dwIsAppContainerPtr = stackalloc int[1]; using var safeTokenHandle = GetCurrentToken(out var hr); if (safeTokenHandle == null || safeTokenHandle.IsInvalid) { throw new SecurityException(new Win32Exception(hr).Message); } if (!GetTokenInformation(safeTokenHandle, TOKEN_INFORMATION_CLASS.TokenIsAppContainer, new IntPtr(dwIsAppContainerPtr), sizeof(int), out _)) { hr = Marshal.GetHRForLastWin32Error(); throw new Win32Exception(new Win32Exception(hr).Message); } return *dwIsAppContainerPtr != 0; } [Flags] private enum TokenAccessLevels { Query = 0x00000008 } private sealed class SafeAccessTokenHandle : SafeHandle { private SafeAccessTokenHandle() : base(IntPtr.Zero, true) { } // 0 is an Invalid Handle public SafeAccessTokenHandle(IntPtr handle) : base(handle, true) { } public override bool IsInvalid => handle == IntPtr.Zero || handle == new IntPtr(-1); protected override bool ReleaseHandle() => CloseHandle(handle); } private enum TOKEN_INFORMATION_CLASS : uint { TokenUser = 1, TokenGroups, TokenPrivileges, TokenOwner, TokenPrimaryGroup, TokenDefaultDacl, TokenSource, TokenType, TokenImpersonationLevel, TokenStatistics, TokenRestrictedSids, TokenSessionId, TokenGroupsAndPrivileges, TokenSessionReference, TokenSandBoxInert, TokenAuditPolicy, TokenOrigin, TokenElevationType, TokenLinkedToken, TokenElevation, TokenHasRestrictions, TokenAccessInformation, TokenVirtualizationAllowed, TokenVirtualizationEnabled, TokenIntegrityLevel, TokenUIAccess, TokenMandatoryPolicy, TokenLogonSid, TokenIsAppContainer, TokenCapabilities, TokenAppContainerSid, TokenAppContainerNumber, TokenUserClaimAttributes, TokenDeviceClaimAttributes, TokenRestrictedUserClaimAttributes, TokenRestrictedDeviceClaimAttributes, TokenDeviceGroups, TokenRestrictedDeviceGroups, TokenSecurityAttributes, TokenIsRestricted, MaxTokenInfoClass } } <|start_filename|>SharpGen/Parser/MacroManager.cs<|end_filename|> // Copyright (c) 2010-2014 SharpDX - <NAME> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Collections.Generic; using System.IO; using System.Text.RegularExpressions; using SharpGen.CppModel; namespace SharpGen.Parser; /// <summary> /// This class is responsible to get all macros defined from a C++ header file. /// </summary> public sealed class MacroManager { private static readonly Regex MatchIncludeLine = new(@"^\s*#\s+\d+\s+""([^""]+)""", RegexOptions.Compiled); private static readonly Regex MatchDefine = new(@"^\s*#define\s+([a-zA-Z_][\w_]*)\s+(.*)", RegexOptions.Compiled); private readonly ICastXmlRunner _gccxml; private Dictionary<string, string> _currentMacros; private readonly Dictionary<string, Dictionary<string, string>> _mapIncludeToMacros = new(StringComparer.InvariantCultureIgnoreCase); private readonly HashSet<string> _includedFiles = new(StringComparer.InvariantCultureIgnoreCase); /// <summary> /// Initializes a new instance of the <see cref="MacroManager"/> class. /// </summary> /// <param name="gccxml">The GccXml parser.</param> public MacroManager(ICastXmlRunner gccxml) { _gccxml = gccxml; } public IEnumerable<string> IncludedFiles => _includedFiles; /// <summary> /// Parses the specified C++ header file and fills the <see cref="CppModule"/> with defined macros. /// </summary> /// <param name="file">The C++ header file to parse.</param> /// <param name="group">The CppModule object to fill with macro definitions.</param> public void Parse(string file, CppModule group) { _gccxml.Preprocess(file, ParseLine); foreach (var includeName in _mapIncludeToMacros.Keys) { var includeId = Path.GetFileNameWithoutExtension(includeName); var include = group.FindInclude(includeId); if (include == null) { include = new CppInclude(includeId); group.Add(include); } foreach (var macroDefinition in _mapIncludeToMacros[includeName]) include.Add(new CppDefine(macroDefinition.Key, macroDefinition.Value)); } } /// <summary> /// Parses a macro definition line. /// </summary> private void ParseLine(string line) { // Collect the sort command output. if (!String.IsNullOrEmpty(line)) { Match result = MatchIncludeLine.Match(line); if (result.Success) { if (result.Groups[1].Value.StartsWith("<")) _currentMacros = null; else { _includedFiles.Add(result.Groups[1].Value.Replace(@"\\", @"\")); var currentFile = Path.GetFileName(result.Groups[1].Value); if (!_mapIncludeToMacros.TryGetValue(currentFile, out _currentMacros)) { _currentMacros = new Dictionary<string,string>(); _mapIncludeToMacros.Add(currentFile, _currentMacros); } } } else if (_currentMacros != null) { result = MatchDefine.Match(line); if (result.Success) { string value = result.Groups[2].Value.TrimEnd(); if (!string.IsNullOrEmpty(value)) { _currentMacros.Remove(result.Groups[1].Value); _currentMacros.Add(result.Groups[1].Value, value); } } } } } } <|start_filename|>SharpGen.Runtime/CppObjectMultiShadow.cs<|end_filename|> #nullable enable using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; namespace SharpGen.Runtime; internal sealed class CppObjectMultiShadow { private readonly GCHandle[] _shadows; public CppObjectMultiShadow(GCHandle[] shadows) { _shadows = shadows ?? throw new ArgumentNullException(nameof(shadows)); #if DEBUG foreach (var handle in _shadows) { Debug.Assert(handle.IsAllocated); Debug.Assert(handle.Target is CppObjectShadow or CppObjectMultiShadow); } #endif } public T? ToShadow<T>() where T : CppObjectShadow { foreach (var handle in _shadows) { switch (handle.Target) { case T shadow: return shadow; case CppObjectMultiShadow multiShadow when multiShadow.ToShadow<T>() is { } shadow: return shadow; } } return null; } public bool ToCallback<T>([NotNullWhen(true)] out T? value) where T : ICallbackable { foreach (var handle in _shadows) { switch (handle.Target) { case CppObjectShadow shadow: value = shadow.ToCallback<T>(); return true; case CppObjectMultiShadow multiShadow when multiShadow.ToShadow<CppObjectShadow>() is { } shadow: value = shadow.ToCallback<T>(); return true; } } value = default; return false; } internal void AddShadowsToSet(HashSet<CppObjectShadow> shadows) { foreach (var handle in _shadows) { if (!handle.IsAllocated) continue; switch (handle.Target) { case CppObjectShadow shadow: shadows.Add(shadow); break; case CppObjectMultiShadow multiShadow: multiShadow.AddShadowsToSet(shadows); break; } } } } <|start_filename|>SharpGenTools.Sdk/Extensibility/ExtensionReference.cs<|end_filename|> // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable enable using System.Collections.Immutable; using SharpGen.Doc; namespace SharpGenTools.Sdk.Extensibility; /// <summary> /// Represents an extension assembly reference that contains documentation providers. /// </summary> /// <remarks> /// Represents a logical location of the extension reference, not the content of the reference. /// The content might change in time. A snapshot is taken when the SDK queries the reference for its extensibility points. /// </remarks> public abstract class ExtensionReference { protected ExtensionReference() { } /// <summary> /// Full path describing the location of the extension reference, or null if the reference has no location. /// </summary> public abstract string? FullPath { get; } /// <summary> /// Path or name used in error messages to identity the reference. /// </summary> /// <remarks> /// Should not be null. /// </remarks> public virtual string Display => string.Empty; /// <summary> /// A unique identifier for this extension reference. /// </summary> /// <remarks> /// Should not be null. /// Note that this and <see cref="FullPath"/> serve different purposes. An extension reference may not /// have a path, but it always has an ID. Further, two extension references with different paths may /// represent two copies of the same analyzer, in which case the IDs should also be the same. /// </remarks> public abstract object Id { get; } /// <summary> /// Gets all the documentation providers defined in this assembly reference. /// </summary> public abstract ImmutableArray<IDocProvider> GetDocumentationProviders(); } <|start_filename|>SharpGen/Generator/Marshallers/IRelationMarshaller.cs<|end_filename|> using Microsoft.CodeAnalysis.CSharp.Syntax; using SharpGen.Model; namespace SharpGen.Generator.Marshallers; public interface IRelationMarshaller { StatementSyntax GenerateManagedToNative(CsMarshalBase publicElement, CsMarshalBase relatedElement); } <|start_filename|>SharpGenTools.Sdk/Extensibility/UnresolvedExtensionReference.cs<|end_filename|> // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable enable using System; using System.Collections.Immutable; using SharpGen.Doc; namespace SharpGenTools.Sdk.Extensibility; /// <summary> /// Represents an extension reference that can't be resolved. /// </summary> /// <remarks> /// For error reporting only, can't be used to reference an extension assembly. /// </remarks> public sealed class UnresolvedExtensionReference : ExtensionReference { public UnresolvedExtensionReference(string unresolvedPath) { FullPath = unresolvedPath ?? throw new ArgumentNullException(nameof(unresolvedPath)); } public override string Display => "Unresolved: " + FullPath; public override string FullPath { get; } public override object Id => FullPath; public override ImmutableArray<IDocProvider> GetDocumentationProviders() => ImmutableArray<IDocProvider>.Empty; } <|start_filename|>SharpGenTools.Sdk/Documentation/DocumentationLogger.cs<|end_filename|> using System; using SharpGen.Logging; namespace SharpGenTools.Sdk.Documentation; internal sealed class DocumentationLogger : LoggerBase { private readonly LoggerBase loggerBaseImplementation; public DocumentationLogger(LoggerBase loggerBaseImplementation) { this.loggerBaseImplementation = loggerBaseImplementation; } public LogLevel MaxLevel { get; set; } = LogLevel.Fatal; public override ILogger LoggerOutput => loggerBaseImplementation.LoggerOutput; public override bool HasErrors => loggerBaseImplementation.HasErrors; public override IProgressReport ProgressReport => loggerBaseImplementation.ProgressReport; public override void PushContext(string context) => loggerBaseImplementation.PushContext(context); public override void PushLocation(string fileName, int line = 1, int column = 1) => loggerBaseImplementation.PushLocation(fileName, line, column); public override void PopLocation() => loggerBaseImplementation.PopLocation(); public override void PushContext(string context, params object[] parameters) => loggerBaseImplementation.PushContext(context, parameters); public override void PopContext() => loggerBaseImplementation.PopContext(); public override void Progress(int level, string message, params object[] parameters) => loggerBaseImplementation.Progress(level, message, parameters); public override void Exit(string reason, params object[] parameters) => throw new DocumentationProviderFailedException(reason ?? string.Empty); public override void LogRawMessage(LogLevel type, string code, string message, Exception exception, params object[] parameters) { if (type > MaxLevel) type = MaxLevel; loggerBaseImplementation.LogRawMessage(type, code, message, exception, parameters); } } <|start_filename|>SharpGen.UnitTests/ConstantManagerTests.cs<|end_filename|> using System; using System.Linq; using SharpGen.CppModel; using SharpGen.Model; using SharpGen.Transform; using Xunit; using Xunit.Abstractions; namespace SharpGen.UnitTests; public class ConstantManagerTests : TestBase { private readonly ConstantManager constantManager; public ConstantManagerTests(ITestOutputHelper outputHelper) : base(outputHelper) { constantManager = new ConstantManager(new NamingRulesManager(), Ioc); } [Fact] public void CanAddConstantFromCppConstant() { var value = "1"; var macro = new CppConstant("Macro", "int", value); var csTypeName = "MyClass"; var constantName = "Constant"; constantManager.AddConstantFromMacroToCSharpType(new CppElementFinder(macro), "Macro", csTypeName, "int", constantName, "$1", null, "namespace", false); var csStructure = new CsStruct(null, csTypeName); constantManager.AttachConstants(csStructure); Assert.Single(csStructure.Items); var variable = (CsExpressionConstant)csStructure.Items.First(); Assert.Equal(value, variable.Value); Assert.Equal(constantName, variable.Name); } [Fact] public void CanAddConstantFromGuid() { var guid = Guid.NewGuid(); var macro = new CppGuid("Macro", guid); var csTypeName = "MyClass"; var constantName = "Constant"; constantManager.AddConstantFromMacroToCSharpType(new CppElementFinder(macro), "Macro", csTypeName, "System.Guid", constantName, "$1", null, "namespace", false); var csStructure = new CsStruct(null, csTypeName); constantManager.AttachConstants(csStructure); Assert.Single(csStructure.Items); var variable = (CsGuidConstant)csStructure.Items.First(); Assert.Equal(guid, variable.Value); Assert.Equal(constantName, variable.Name); } [Fact] public void CanAddConstantFromGuidAndFallback() { var guid = Guid.NewGuid(); var macro = new CppGuid("Macro", guid); var csTypeName = "MyClass"; var constantName = "Constant"; constantManager.AddConstantFromMacroToCSharpType(new CppElementFinder(macro), "Macro", csTypeName, "int", constantName, "$1", null, "namespace", false); var csStructure = new CsStruct(null, csTypeName); constantManager.AttachConstants(csStructure); Assert.Single(csStructure.Items); var variable = (CsExpressionConstant)csStructure.Items.First(); Assert.Equal(guid.ToString(), variable.Value); Assert.Equal(constantName, variable.Name); } } <|start_filename|>SharpGenTools.Sdk/SharpGenTask.PropertyCache.cs<|end_filename|> #nullable enable using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Runtime.CompilerServices; using System.Security.Cryptography; using System.Text; using System.Threading; using Microsoft.Build.Framework; using SharpGenTools.Sdk.Internal; namespace SharpGenTools.Sdk; public sealed partial class SharpGenTask { private const int CacheFormatSignature = ('S' << 0) | ('G' << 8) | ('P' << 16) | ('C' << 24); private const int CacheFormatVersion = 1; private static HashAlgorithm CreateSettingsHash() => SHA256.Create(); private bool GeneratePropertyCache() { List<string> parts = new(4) { "SharpGen" }; if (!string.Equals(PlatformName, "AnyCPU", StringComparison.InvariantCultureIgnoreCase)) parts.Add(PlatformName); if (!string.IsNullOrWhiteSpace(RuntimeIdentifier)) parts.Add(RuntimeIdentifier); CacheFile cacheFile = new(); try { { using var writer = cacheFile.StreamWriter; HashSettings(writer); } var currentHash = Base64UrlEncode(cacheFile.ComputeHash(CreateSettingsHash())); parts.Add(currentHash); var profileName = string.Join("-", parts); workerLock = new Mutex(false, @"Global\" + profileName); var cacheInvalid = false; try { while (!(workerLockAcquired = workerLock.WaitOne(TimeSpan.FromSeconds(5))) && !AbortExecution) { SharpGenLogger.Message($"Waiting for the worker to finish job {profileName}…"); } } catch (AbandonedMutexException) { SharpGenLogger.Message($"The worker failed to complete job {profileName}."); workerLockAcquired = true; cacheInvalid = true; } ProfilePath = Path.Combine(IntermediateOutputDirectory, profileName); if (!workerLockAcquired) { SharpGenLogger.Message($"Aborting the wait for job {profileName} to complete."); Debug.Assert(AbortExecution); return true; } cacheFile.File = new FileInfo(PropertyCache); Utilities.RequireAbsolutePath(PropertyCache, nameof(PropertyCache)); if (File.Exists(DirtyMarkerFile)) { SharpGenLogger.Message("Dirty marker exists, requesting full regeneration."); cacheInvalid = true; } else if (!cacheInvalid) { cacheInvalid = cacheFile.IsWriteNeeded; SharpGenLogger.Message( cacheFile.State switch { CacheFile.CacheState.Hit => "Properties match cached value.", CacheFile.CacheState.Miss => "Properties mismatch, writing a new property cache file.", CacheFile.CacheState.Absent => "Properties cache doesn't exist.", _ => throw new ArgumentOutOfRangeException() } ); } if (cacheFile.IsWriteNeeded) cacheFile.Write(); return cacheInvalid; } finally { cacheFile.Dispose(); } } private void HashSettings(StreamWriter writer) { writer.Write(CacheFormatSignature.ToString("X8")); writer.Write('.'); writer.Write(CacheFormatVersion); writer.WriteLine(); WriteStringArray(CastXmlArguments); WriteString(CastXmlExecutable); WriteStringArray(ConfigFiles); WriteString(ConsumerBindMappingConfigId); WriteBool(DocumentationFailuresAsErrors); WriteStringArray(ExtensionAssemblies); WriteStringArray(ExternalDocumentation); WriteTaskItems(GlobalNamespaceOverrides); WriteStringArray(Macros); WriteString(IntermediateOutputDirectory); WriteString(PlatformName); WriteString(RuntimeIdentifier); WriteStringArray(Platforms); WriteStringArray(SilenceMissingDocumentationErrorIdentifierPatterns); void WriteString(string? s, [CallerArgumentExpression("s")] string? name = null) { writer.Write(name); writer.Write(": "); writer.WriteLine(s ?? "<null>"); } void WriteBool(bool v, [CallerArgumentExpression("v")] string? name = null) { writer.Write(name); writer.Write(": "); writer.WriteLine(v); } void WriteStringArray(IReadOnlyList<string>? items, [CallerArgumentExpression("items")] string? name = null) { writer.Write(name); writer.Write(":"); if (items is null) { writer.WriteLine(" <null>"); return; } writer.WriteLine(); for (int i = 0, length = items.Count; i < length; i++) { writer.Write("* "); writer.WriteLine(items[i]); } } void WriteTaskItem(ITaskItem? item, [CallerArgumentExpression("item")] string? name = null) { writer.Write(name); writer.Write(": "); if (item is null) { writer.WriteLine("<null>"); return; } writer.WriteLine(item.ItemSpec); foreach (DictionaryEntry entry in item.CloneCustomMetadata()) { writer.Write(name); writer.Write("["); writer.Write(entry.Key.ToString() ?? "<null>"); writer.Write("]: "); writer.WriteLine(entry.Value?.ToString() ?? "<null>"); } } void WriteTaskItems(IReadOnlyList<ITaskItem?>? items, [CallerArgumentExpression("items")] string? name = null) { writer.Write(name); writer.Write(":"); if (items is null) { writer.WriteLine(" <null>"); return; } writer.WriteLine(); for (int i = 0, length = items.Count; i < length; i++) { WriteTaskItem(items[i], $"{name}[{i}]"); } } } private static string Base64UrlEncode(byte[] input) { if (input == null) throw new ArgumentNullException(nameof(input)); // Special-case empty input var count = input.Length; if (count == 0) return string.Empty; var numWholeOrPartialInputBlocks = checked(count + 2) / 3; var buffer = new char[checked(numWholeOrPartialInputBlocks * 4)]; var numBase64Chars = Base64UrlEncode(input, buffer, count); return new string(buffer, 0, numBase64Chars); } private static int Base64UrlEncode(byte[] input, char[] output, int count) { // Use base64url encoding with no padding characters. See RFC 4648, Sec. 5. // Start with default Base64 encoding. var numBase64Chars = Convert.ToBase64CharArray(input, 0, count, output, 0); // Fix up '+' -> '-' and '/' -> '_'. Drop padding characters. for (var i = 0; i < numBase64Chars; i++) { switch (output[i]) { case '+': output[i] = '-'; break; case '/': output[i] = '_'; break; case '=': // We've reached a padding character; truncate the remainder. return i; } } return numBase64Chars; } } <|start_filename|>SharpGen/Transform/ITransformer.cs<|end_filename|> using SharpGen.Model; namespace SharpGen.Transform; public interface ITransformer<TCsElement> where TCsElement: CsBase { void Process(TCsElement csElement); } <|start_filename|>SharpGen/Transform/IInteropSignatureTransform.cs<|end_filename|> #nullable enable using System.Collections.Generic; using SharpGen.Model; namespace SharpGen.Transform; public interface IInteropSignatureTransform { IDictionary<PlatformDetectionType, InteropMethodSignature> GetInteropSignatures(CsCallable callable); } <|start_filename|>SharpGen.Generator/Utilities.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Runtime.CompilerServices; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; namespace SharpGen.Generator; public static class Utilities { private static AttributeData? TypeToAttribute(INamespaceOrTypeSymbol? typeSymbol, string name) { if (typeSymbol is null) return null; var attributes = typeSymbol.GetAttributes() .Where(x => x.AttributeClass?.ToDisplayString() == name) .ToArray(); return attributes.Length == 0 ? null : attributes.ExclusiveOrDefault(); } public static ITypeSymbol? GetVtblAttribute(this INamespaceOrTypeSymbol? typeSymbol) { if (TypeToAttribute(typeSymbol, "SharpGen.Runtime.VtblAttribute") is not { ConstructorArguments: var args }) return null; if (args.Single() is { Kind: TypedConstantKind.Type, Value: ITypeSymbol { IsValueType: false, IsReferenceType: true, IsStatic: true, IsTupleType: false, IsNativeIntegerType: false, IsAnonymousType: false } vtblType } ) return vtblType; throw new Exception(); } public static Guid? GetGuidAttribute(this INamespaceOrTypeSymbol? typeSymbol) { if (TypeToAttribute(typeSymbol, "System.Runtime.InteropServices.GuidAttribute") is not { ConstructorArguments: var args }) return null; if (args.Single() is { Kind: TypedConstantKind.Primitive, Value: string { Length: > 0 } guidString } ) return Guid.Parse(guidString); throw new Exception(); } public static TSource? ExclusiveOrDefault<TSource>(this IEnumerable<TSource>? source) where TSource : class { if (source == null) return default; if (source is IList<TSource> list) { if (list.Count == 1) return list[0]; } else { using var e = source.GetEnumerator(); if (!e.MoveNext()) return default; var result = e.Current; if (!e.MoveNext()) return result; } return default; } public static TSource? ExclusiveOrDefault<TSource>(this IEnumerable<TSource>? source, Func<TSource, bool> predicate) where TSource : class { if (source == null) return default; if (predicate == null) throw new ArgumentNullException(nameof(predicate)); using var e = source.GetEnumerator(); while (e.MoveNext()) { var result = e.Current; if (predicate(result)) { while (e.MoveNext()) if (predicate(e.Current)) return default; return result; } } return default; } [SuppressMessage("ReSharper", "InconsistentNaming")] private readonly struct GuidExtractor { #pragma warning disable 649 public readonly int a; public readonly short b; public readonly short c; public readonly byte d; public readonly byte e; public readonly byte f; public readonly byte g; public readonly byte h; public readonly byte i; public readonly byte j; public readonly byte k; #pragma warning restore 649 } public static ArgumentListSyntax GetGuidParameters(Guid parsedGuid) { var extractedGuid = Unsafe.As<Guid, GuidExtractor>(ref parsedGuid); return ArgumentList( SeparatedList( new[] { Literal4(extractedGuid.a), Literal2(extractedGuid.b), Literal2(extractedGuid.c), Literal1(extractedGuid.d), Literal1(extractedGuid.e), Literal1(extractedGuid.f), Literal1(extractedGuid.g), Literal1(extractedGuid.h), Literal1(extractedGuid.i), Literal1(extractedGuid.j), Literal1(extractedGuid.k) } ) ); static ArgumentSyntax LiteralArgument(SyntaxToken x) => Argument(LiteralExpression(SyntaxKind.NumericLiteralExpression, x)); static ArgumentSyntax Literal1(byte value) => LiteralArgument(Literal("0x" + value.ToString("X2"), value)); static ArgumentSyntax Literal2(short value) => LiteralArgument(Literal("0x" + value.ToString("X4"), value)); static ArgumentSyntax Literal4(int value) => LiteralArgument(Literal("0x" + value.ToString("X8"), value)); } } <|start_filename|>SharpGen.Runtime/ResultDescriptor.cs<|end_filename|> // Copyright (c) 2010-2014 SharpDX - <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. #nullable enable using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Text; namespace SharpGen.Runtime; /// <summary> /// Descriptor used to provide detailed message for a particular <see cref="Result"/>. /// </summary> [SuppressMessage("ReSharper", "ConvertToAutoProperty")] internal readonly struct ResultDescriptor : IEquatable<ResultDescriptor> { private static readonly ConcurrentDictionary<int, ResultDescriptor> Descriptors = new(); // .NET Native has issues with <...> in property backing fields in structs private readonly Result _result; private readonly string? _module; private readonly string? _nativeApiCode; private readonly string? _apiCode; private readonly string? _description; private const string UnknownText = "Unknown"; static ResultDescriptor() { const string generalModule = "General"; Register(Result.Abort, generalModule, "E_ABORT", "Operation aborted"); Register(Result.AccessDenied, generalModule, "E_ACCESSDENIED", "General access denied error"); Register(Result.Fail, generalModule, "E_FAIL", "Unspecified error"); Register(Result.Handle, generalModule, "E_HANDLE", "Invalid handle"); Register(Result.InvalidArg, generalModule, "E_INVALIDARG", "Invalid arguments"); Register(Result.NoInterface, generalModule, "E_NOINTERFACE", "No such interface supported"); Register(Result.NotImplemented, generalModule, "E_NOTIMPL", "Not implemented"); Register(Result.OutOfMemory, generalModule, "E_OUTOFMEMORY", "Out of memory"); Register(Result.InvalidPointer, generalModule, "E_POINTER", "Invalid pointer"); Register(Result.UnexpectedFailure, generalModule, "E_UNEXPECTED", "Catastrophic failure"); Register(Result.WaitAbandoned, generalModule, "WAIT_ABANDONED", "WaitAbandoned"); Register(Result.WaitTimeout, generalModule, "WAIT_TIMEOUT", "WaitTimeout"); Register(Result.Pending, generalModule, "E_PENDING", "Pending"); Register(Result.InsufficientBuffer, generalModule, "E_NOT_SUFFICIENT_BUFFER", "Insufficient buffer"); } /// <summary> /// Initializes a new instance of the <see cref="ResultDescriptor"/> class. /// </summary> /// <param name="code">The HRESULT error code.</param> /// <param name="module">The module (ex: SharpDX.Direct2D1).</param> /// <param name="apiCode">The API code (ex: D2D1_ERR_...).</param> /// <param name="description">The description of the result code if any.</param> private ResultDescriptor(Result code, string? module = null, string? nativeApiCode = null, string? apiCode = null, string? description = null) { _result = code; _module = module; _nativeApiCode = nativeApiCode; _apiCode = apiCode; _description = description ?? GetDescriptionFromResultCode(code.Code); } public Result Result => _result; private int Code => Result.Code; public string Module => _module ?? UnknownText; public string NativeApiCode => _nativeApiCode ?? UnknownText; public string ApiCode => _apiCode ?? UnknownText; public string Description => _description ?? UnknownText; /// <inheritdoc/> public override string ToString() { List<FormattableString> items = new(4) { $"HRESULT: [0x{Result.Code:X}]" }; if (_module is {Length: >0} module) items.Add($"Module: [{module}]"); var nativeApiCode = _nativeApiCode; var apiCode = _apiCode; var hasApiCode = apiCode is { Length: >0 }; switch (nativeApiCode is { Length: >0 }) { case true when hasApiCode: items.Add($"ApiCode: [{nativeApiCode}/{apiCode}]"); break; case true: items.Add($"ApiCode: [{nativeApiCode}]"); break; case false when hasApiCode: items.Add($"ApiCode: [{apiCode}]"); break; case false: break; } if (_description is {Length: >0} description) items.Add($"Message: [{description}]"); StringBuilder builder = new(256); foreach (var item in items) { if (builder.Length != 0) builder.Append(", "); builder.AppendFormat(item.Format, item.GetArguments()); } return builder.ToString(); } public bool Equals(ResultDescriptor other) => Result.Equals(other.Result); public override bool Equals(object? obj) => obj is ResultDescriptor other && Result.Equals(other.Result); public override int GetHashCode() => Result.GetHashCode(); public static bool operator ==(ResultDescriptor left, ResultDescriptor right) => left.Equals(right); public static bool operator !=(ResultDescriptor left, ResultDescriptor right) => !left.Equals(right); public static implicit operator Result(ResultDescriptor result) => result.Result; public static explicit operator int(ResultDescriptor result) => result.Result.Code; public static explicit operator uint(ResultDescriptor result) => unchecked((uint)result.Result.Code); [MethodImpl(Utilities.MethodAggressiveOptimization)] public static ResultDescriptor Find(Result result) => Find(result.Code); [MethodImpl(Utilities.MethodAggressiveOptimization)] public static ResultDescriptor Find(int result) => Descriptors.GetOrAdd(result, static result => new(result)); [MethodImpl(Utilities.MethodAggressiveOptimization)] public static void Register(Result result, string? module = null, string? nativeApiCode = null, string? apiCode = null, string? description = null) => Register(result.Code, module, nativeApiCode, apiCode, description); [MethodImpl(Utilities.MethodAggressiveOptimization)] public static void Register(int result, string? module = null, string? nativeApiCode = null, string? apiCode = null, string? description = null) => Descriptors[result] = new(result, module, nativeApiCode, apiCode, description); private static string? GetDescriptionFromResultCode(int resultCode) { if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { const int FORMAT_MESSAGE_ALLOCATE_BUFFER = 0x00000100; const int FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200; const int FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000; const int flags = FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS; var buffer = IntPtr.Zero; if (FormatMessage(flags, IntPtr.Zero, resultCode, 0, ref buffer, 0, IntPtr.Zero) == 0) return null; var description = Marshal.PtrToStringUni(buffer); Marshal.FreeHGlobal(buffer); return description?.Length > 0 ? description : null; } return null; } [DllImport("kernel32.dll", EntryPoint = "FormatMessageW", CharSet = CharSet.Unicode, SetLastError = true, BestFitMapping = true, ExactSpelling = true)] private static extern uint FormatMessage(int dwFlags, IntPtr lpSource, int dwMessageId, int dwLanguageId, ref IntPtr lpBuffer, int nSize, IntPtr arguments); } <|start_filename|>SharpGen/Generator/ISingleCodeGenerator.cs<|end_filename|> using Microsoft.CodeAnalysis; using SharpGen.Model; namespace SharpGen.Generator; public interface ISingleCodeGenerator<in TCsElement, out TSyntax> where TCsElement : CsBase where TSyntax : SyntaxNode { TSyntax GenerateCode(TCsElement csElement); } <|start_filename|>SharpGen.Runtime/CallbackBase.ReflectionCache.cs<|end_filename|> #nullable enable using System; using System.Collections.Generic; namespace SharpGen.Runtime; public abstract partial class CallbackBase { private static readonly Dictionary<Type, CallbackTypeInfo> TypeReflectionCache = new(); private CallbackTypeInfo GetTypeInfo() { CallbackTypeInfo info; var type = GetType(); var cache = TypeReflectionCache; lock (cache) if (cache.TryGetValue(type, out info)) return info; info = new CallbackTypeInfo(type); lock (cache) cache[type] = info; return info; } } <|start_filename|>SharpGen/Generator/EnumCodeGenerator.cs<|end_filename|> using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using SharpGen.Logging; using SharpGen.Model; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; namespace SharpGen.Generator; internal sealed class EnumCodeGenerator : MemberSingleCodeGeneratorBase<CsEnum> { private static readonly SyntaxList<AttributeListSyntax> FlagAttributeList = SingletonList( AttributeList(SingletonSeparatedList(Attribute(ParseName("System.FlagsAttribute")))) ); public override MemberDeclarationSyntax GenerateCode(CsEnum csElement) { var enumDecl = EnumDeclaration(csElement.Name); var underlyingType = ParseTypeName(csElement.UnderlyingType.Name); enumDecl = enumDecl .WithModifiers(csElement.VisibilityTokenList) .WithBaseList(BaseList(SingletonSeparatedList<BaseTypeSyntax>(SimpleBaseType(underlyingType)))) .AddMembers( csElement.EnumItems .Select(item => { var itemDecl = EnumMemberDeclaration(item.Name); if (!string.IsNullOrEmpty(item.Value)) { itemDecl = itemDecl.WithEqualsValue( EqualsValueClause( CheckedExpression( SyntaxKind.UncheckedExpression, CastExpression( underlyingType, LiteralExpression( SyntaxKind.NumericLiteralExpression, GetValueLiteral(item.Value, csElement.Name, item.Name) ))))); } return AddDocumentationTrivia(itemDecl, item); }) .ToArray() ); if (csElement.IsFlag) enumDecl = enumDecl.WithAttributeLists(FlagAttributeList); return AddDocumentationTrivia(enumDecl, csElement); } private SyntaxToken GetValueLiteral(string value, string enumName, string enumItemName) { // [...] integer types in rank order, signed given preference over unsigned. if (int.TryParse(value, out var valueInt)) return Literal(valueInt); if (uint.TryParse(value, out var valueUInt)) return Literal(valueUInt); if (long.TryParse(value, out var valueLong)) return Literal(valueLong); if (ulong.TryParse(value, out var valueULong)) return Literal(valueULong); Logger.Error( LoggingCodes.EnumItemLiteralOutOfRange, "Enum [{0}] value [{1}]=[{2}] is out of range of any valid numeric type on .NET platform", enumName, enumItemName, value ); return default; } public EnumCodeGenerator(Ioc ioc) : base(ioc) { } } <|start_filename|>SharpGenTools.Sdk/SharpGenTask.cs<|end_filename|> #nullable enable using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Xml; using Microsoft.Build.Framework; using Microsoft.Build.Utilities; using Microsoft.CodeAnalysis.CSharp; using SharpGen; using SharpGen.Config; using SharpGen.CppModel; using SharpGen.Generator; using SharpGen.Logging; using SharpGen.Model; using SharpGen.Parser; using SharpGen.Platform; using SharpGen.Platform.Documentation; using SharpGen.Transform; using SharpGenTools.Sdk.Documentation; using SharpGenTools.Sdk.Extensibility; using SharpGenTools.Sdk.Internal; using Logger = SharpGen.Logging.Logger; using SdkResolver = SharpGen.Parser.SdkResolver; namespace SharpGenTools.Sdk; public sealed partial class SharpGenTask : Task, ICancelableTask { // Default encoding used by MSBuild ReadLinesFromFile task internal static readonly Encoding DefaultEncoding = new UTF8Encoding(false, true); private static readonly char[] SpaceSeparator = { ' ' }; private readonly IocServiceContainer serviceContainer = new(); private readonly Ioc ioc = new(); private string? profilePath; private volatile bool isCancellationRequested; private Mutex? workerLock; private bool workerLockAcquired, regenerationStarted; // ReSharper disable MemberCanBePrivate.Global, UnusedAutoPropertyAccessor.Global [Required] public string[]? CastXmlArguments { get; set; } [Required] public string? CastXmlExecutable { get; set; } [Required] public string[]? ConfigFiles { get; set; } [Required] public string? ConsumerBindMappingConfigId { get; set; } [Required] public bool DebugWaitForDebuggerAttach { get; set; } [Required] public bool DocumentationFailuresAsErrors { get; set; } [Required] public string[]? ExtensionAssemblies { get; set; } [Required] public string[]? ExternalDocumentation { get; set; } [Required] public ITaskItem[]? GlobalNamespaceOverrides { get; set; } [Required] public string[]? Macros { get; set; } [Required] public string? IntermediateOutputDirectory { get; set; } public string? PlatformName { get; set; } [Required] public string[]? Platforms { get; set; } [Output] public string ProfilePath { get => profilePath ?? throw new InvalidOperationException("Profile not set"); set { if (profilePath is not null) throw new InvalidOperationException("Profile cannot be set twice"); profilePath = Utilities.EnsureTrailingSlash(value ?? throw new InvalidOperationException("Profile cannot be null")); } } public string? RuntimeIdentifier { get; set; } [Required] public string[]? SilenceMissingDocumentationErrorIdentifierPatterns { get; set; } // ReSharper restore UnusedAutoPropertyAccessor.Global, MemberCanBePrivate.Global private string GeneratedCodeFile => GetProfileChild("SharpGen.Bindings.g.cs"); private string InputsCache => GetProfileChild("InputsCache.txt"); private string PropertyCache => GetProfileChild("PropertyCache.txt"); private string DocumentationCache => GetProfileChild("DocumentationCache.json"); private string DirtyMarkerFile => GetProfileChild("dirty"); private string PackagePropsFile => GetProfileChild("Package.props"); private string ConsumerBindMappingConfig => GetProfileChild( (ConsumerBindMappingConfigId ?? throw new InvalidOperationException(nameof(ConsumerBindMappingConfigId))) + ".BindMapping.xml" ); private string GetProfileChild(string childName) => Path.Combine(ProfilePath, childName); private Logger SharpGenLogger { get; set; } [Conditional("DEBUG")] private void WaitForDebuggerAttach() { if (!Debugger.IsAttached) { SharpGenLogger.Warning(null, $"{GetType().Name} is waiting for attach: {Process.GetCurrentProcess().Id}"); Thread.Yield(); } while (!Debugger.IsAttached && !isCancellationRequested) Thread.Sleep(TimeSpan.FromSeconds(1)); } public void Cancel() => isCancellationRequested = true; private static string[] PreprocessPathListProperty(string[] items) => items.Distinct(StringComparer.OrdinalIgnoreCase) .OrderBy(static x => x, StringComparer.OrdinalIgnoreCase) .ToArray(); public override bool Execute() { BindingRedirectResolution.Enable(); SharpGenLogger = new Logger(new MSBuildSharpGenLogger(Log)); #if DEBUG if (DebugWaitForDebuggerAttach) WaitForDebuggerAttach(); #endif var success = false; try { ConfigFiles = PreprocessPathListProperty(ConfigFiles); ExtensionAssemblies = PreprocessPathListProperty(ExtensionAssemblies); ExternalDocumentation = PreprocessPathListProperty(ExternalDocumentation); if (GeneratePropertyCache()) { return success = ExecuteImpl(); } else { if (AbortExecution) return success = false; if (IsInputsCacheValid()) return success = true; return success = ExecuteImpl(); } } catch (CodeGenFailedException ex) { SharpGenLogger.Fatal("Internal SharpGen exception", ex); return success = false; } finally { Debug.Assert(workerLock != null, nameof(workerLock) + " != null"); try { GeneratePackagesProps(); } catch (Exception e) { SharpGenLogger.LogRawMessage( LogLevel.Warning, null, "Internal SharpGen exception while generating NuGet package properties file", e ); } if (regenerationStarted) { try { GenerateInputsCache(); } catch (Exception e) { SharpGenLogger.LogRawMessage( LogLevel.Warning, null, "Internal SharpGen exception while generating input file cache", e ); } } if (success && !AbortExecution && File.Exists(DirtyMarkerFile)) File.Delete(DirtyMarkerFile); if (workerLockAcquired) workerLock.ReleaseMutex(); workerLock.Dispose(); workerLock = null; } } private bool AbortExecution => SharpGenLogger.HasErrors || isCancellationRequested; private bool ExecuteImpl() { File.WriteAllBytes(DirtyMarkerFile, Array.Empty<byte>()); regenerationStarted = true; if (AbortExecution) return false; serviceContainer.AddService(SharpGenLogger); serviceContainer.AddService<IDocumentationLinker, DocumentationLinker>(); serviceContainer.AddService<GlobalNamespaceProvider>(); serviceContainer.AddService(new TypeRegistry(ioc)); ioc.ConfigureServices(serviceContainer); ExtensibilityDriver.Instance.LoadExtensions(SharpGenLogger, ExtensionAssemblies); AddInputsCacheFiles(ExtensionAssemblies); ConfigFile config = new() { Files = ConfigFiles.ToList(), Id = "SharpGen-MSBuild" }; LoadConfig(config); config.GetFilesWithIncludesAndExtensionHeaders( out var configsWithHeaders, out var configsWithExtensionHeaders ); AddInputsCacheFiles(config.ConfigFilesLoaded.Select(x => x.AbsoluteFilePath)); CppHeaderGenerator cppHeaderGenerator = new(ProfilePath, ioc); var cppHeaderGenerationResult = cppHeaderGenerator.GenerateCppHeaders(config, configsWithHeaders, configsWithExtensionHeaders); if (AbortExecution) return false; IncludeDirectoryResolver resolver = new(ioc); resolver.Configure(config); AddInputsCacheFile(CastXmlExecutable); CastXmlRunner castXml = new(resolver, CastXmlExecutable, CastXmlArguments, ioc) { OutputPath = ProfilePath }; var module = config.CreateSkeletonModule(); MacroManager macroManager = new(castXml); macroManager.Parse(Path.Combine(ProfilePath, config.HeaderFileName), module); AddInputsCacheFiles(macroManager.IncludedFiles); new CppExtensionHeaderGenerator().GenerateExtensionHeaders( config, ProfilePath, module, configsWithExtensionHeaders, cppHeaderGenerationResult.UpdatedConfigs ); AddInputsCacheFiles(configsWithExtensionHeaders.Select(x => Path.Combine(ProfilePath, x.ExtensionFileName))); if (AbortExecution) return false; // Run the parser var parser = new CppParser(config, ioc) { OutputPath = ProfilePath }; if (AbortExecution) return false; CppModule group; using (var xmlReader = castXml.Process(parser.RootConfigHeaderFileName)) { // Run the C++ parser group = parser.Run(module, xmlReader); } if (AbortExecution) return false; config.ExpandDynamicVariables(SharpGenLogger, group); var docLinker = ioc.DocumentationLinker; var globalNamespace = ioc.GlobalNamespace; NamingRulesManager namingRules = new(); foreach (var nameOverride in GlobalNamespaceOverrides) { var wellKnownName = nameOverride.ItemSpec; var overridenName = nameOverride.GetMetadata("Override"); if (string.IsNullOrEmpty(overridenName)) continue; if (Enum.TryParse(wellKnownName, out WellKnownName name)) { globalNamespace.OverrideName(name, overridenName); } else { SharpGenLogger.Warning( LoggingCodes.InvalidGlobalNamespaceOverride, "Invalid override of \"{0}\": unknown class name, ignoring the override.", wellKnownName ); } } serviceContainer.AddService( new GeneratorConfig { Platforms = ConfigPlatforms } ); // Run the main mapping process TransformManager transformer = new( namingRules, new ConstantManager(namingRules, ioc), ioc ); var (solution, defines) = transformer.Transform(group, config); var consumerConfig = new ConfigFile { Id = ConsumerBindMappingConfigId, IncludeProlog = {cppHeaderGenerationResult.Prologue}, Extension = new List<ExtensionBaseRule>(defines) }; var (bindings, generatedDefines) = transformer.GenerateTypeBindingsForConsumers(); consumerConfig.Bindings.AddRange(bindings); consumerConfig.Extension.AddRange(generatedDefines); consumerConfig.Mappings.AddRange( docLinker.GetAllDocLinks().Select( link => new MappingRule { DocItem = link.cppName, MappingNameFinal = link.cSharpName } ) ); GenerateConfigForConsumers(consumerConfig); if (AbortExecution) return false; var documentationCacheItemSpec = DocumentationCache; Utilities.RequireAbsolutePath(documentationCacheItemSpec, nameof(DocumentationCache)); var cache = File.Exists(documentationCacheItemSpec) ? DocItemCache.Read(documentationCacheItemSpec) : new DocItemCache(); DocumentationLogger docLogger = new(SharpGenLogger) {MaxLevel = LogLevel.Warning}; var docContext = new Lazy<DocumentationContext>(() => new DocumentationContext(docLogger)); ExtensibilityDriver.Instance.DocumentModule(SharpGenLogger, cache, solution, docContext).Wait(); if (docContext.IsValueCreated) { Regex[] silencePatterns = null; var docLogLevelDefault = DocumentationFailuresAsErrors ? LogLevel.Error : LogLevel.Warning; foreach (var queryFailure in docContext.Value.Failures) { if (silencePatterns == null) { silencePatterns = new Regex[SilenceMissingDocumentationErrorIdentifierPatterns.Length]; for (var i = 0; i < silencePatterns.Length; i++) silencePatterns[i] = new Regex( SilenceMissingDocumentationErrorIdentifierPatterns[i], RegexOptions.CultureInvariant ); } if (silencePatterns.Length != 0) { bool SilencePredicate(Regex x) => x.Match(queryFailure.Query).Success; if (silencePatterns.Any(SilencePredicate)) continue; } var providerName = queryFailure.FailedProviderName ?? "<null>"; var docLogLevel = queryFailure.TreatProviderFailuresAsErrors ? docLogLevelDefault : docLogLevelDefault > LogLevel.Warning ? LogLevel.Warning : docLogLevelDefault; switch (queryFailure.Exceptions) { case { Count: > 1 } exceptions: { var exceptionsCount = exceptions.Count; for (var index = 0; index < exceptionsCount; index++) { var exception = exceptions[index]; SharpGenLogger.LogRawMessage( docLogLevel, LoggingCodes.DocumentationProviderInternalError, "Documentation provider [{0}] query for \"{1}\" failed ({2}/{3}).", exception, providerName, queryFailure.Query, index + 1, exceptionsCount ); } break; } case { Count: 1 } exceptions: SharpGenLogger.LogRawMessage( docLogLevel, LoggingCodes.DocumentationProviderInternalError, "Documentation provider [{0}] query for \"{1}\" failed.", exceptions[0], providerName, queryFailure.Query ); break; default: SharpGenLogger.LogRawMessage( docLogLevel, LoggingCodes.DocumentationProviderInternalError, "Documentation provider [{0}] query for \"{1}\" failed.", null, providerName, queryFailure.Query ); break; } } } cache.WriteIfDirty(documentationCacheItemSpec); if (AbortExecution) return false; var documentationFiles = new Dictionary<string, XmlDocument>(); AddInputsCacheFiles(ExternalDocumentation); foreach (var file in ExternalDocumentation) { using var stream = File.OpenRead(file); var xml = new XmlDocument(); xml.Load(stream); documentationFiles.Add(file, xml); } if (AbortExecution) return false; serviceContainer.AddService(new ExternalDocCommentsReader(documentationFiles)); serviceContainer.AddService<IGeneratorRegistry>(new DefaultGenerators(ioc)); RoslynGenerator generator = new(); using var codeStream = File.Open(GeneratedCodeFile, FileMode.Create, FileAccess.Write); using var codeWriter = new StreamWriter(codeStream, DefaultEncoding); generator.Run(solution, ioc).GetCompilationUnitRoot().WriteTo(codeWriter); return !SharpGenLogger.HasErrors; } private PlatformDetectionType ConfigPlatforms { get { PlatformDetectionType platformMask = 0; foreach (var platform in Platforms) { if (!Enum.TryParse<PlatformDetectionType>(platform, out var parsedPlatform)) { SharpGenLogger.Warning( LoggingCodes.InvalidPlatformDetectionType, "The platform type {0} is an unknown platform to SharpGenTools. Falling back to Any platform detection.", platform ); platformMask = PlatformDetectionType.Any; } else { platformMask |= parsedPlatform; } } return platformMask == 0 ? PlatformDetectionType.Any : platformMask; } } private void GenerateConfigForConsumers(ConfigFile consumerConfig) { using var consumerBindMapping = File.Create(ConsumerBindMappingConfig); consumerConfig.Write(consumerBindMapping); } private void LoadConfig(ConfigFile config) { config.Load(null, Macros, SharpGenLogger); AddInputsCacheEnvironmentVariable("SHARPGEN_VS_OVERRIDE"); AddInputsCacheEnvironmentVariable("SHARPGEN_SDK_OVERRIDE"); SdkResolver sdkResolver = new(SharpGenLogger); SharpGenLogger.Message("Resolving SDKs..."); foreach (var cfg in config.ConfigFilesLoaded) { SharpGenLogger.Message("Resolving SDK for Config {0}", cfg); foreach (var sdk in cfg.Sdks) { SharpGenLogger.Message("Resolving {0}: Version {1}", sdk.Name, sdk.Version); foreach (var directory in sdkResolver.ResolveIncludeDirsForSdk(sdk)) { SharpGenLogger.Message("Resolved include directory {0}", directory); cfg.IncludeDirs.Add(directory); } } } } private void GeneratePackagesProps() { using CacheFile cacheFile = new(new FileInfo(PackagePropsFile)); { using var writer = cacheFile.StreamWriter; writer.WriteLine(@"<Project>"); writer.WriteLine(@" <ItemGroup>"); writer.WriteLine( $@" <SharpGenConsumerMapping Include=""$([MSBuild]::NormalizePath('$(MSBuildThisFileDirectory)', '..', 'build', '{ConsumerBindMappingConfigId}.BindMapping.xml'))""/>" ); writer.WriteLine(@" </ItemGroup>"); writer.WriteLine(@"</Project>"); } SharpGenLogger.Message( cacheFile.State switch { CacheFile.CacheState.Hit => "NuGet package properties file is already up-to-date.", CacheFile.CacheState.Miss => "NuGet package properties file is out-of-date.", CacheFile.CacheState.Absent => "NuGet package properties file doesn't exist.", _ => throw new ArgumentOutOfRangeException() } ); if (cacheFile.IsWriteNeeded) cacheFile.Write(); } } <|start_filename|>SharpGen/Model/CsFundamentalType.cs<|end_filename|> using System; using System.Reflection; using System.Runtime.InteropServices; using SharpGen.Transform; namespace SharpGen.Model; public sealed class CsFundamentalType : CsTypeBase { private static readonly Type VoidType = typeof(void); internal CsFundamentalType(Type type, PrimitiveTypeIdentity identity, string name) : this(type, name) { PrimitiveTypeIdentity = identity; } internal CsFundamentalType(Type type, string name) : base(null, name) { var typeInfo = type.GetTypeInfo(); IsPrimitive = typeInfo.IsPrimitive; IsValueType = typeInfo.IsValueType || IsPrimitive; IsString = type == typeof(string); IsIntPtr = type == typeof(IntPtr) || type == typeof(UIntPtr); if (IsIntPtr) { IsUntypedPointer = true; } else if (typeInfo.IsPointer) { var reducedToPointer = ReducePointers(type, typeInfo); IsUntypedPointer = reducedToPointer == VoidType; IsTypedPointer = !IsUntypedPointer; } IsIntegerType = type == typeof(int) || type == typeof(short) || type == typeof(byte) || type == typeof(long) || type == typeof(uint) || type == typeof(ushort) || type == typeof(sbyte) || type == typeof(ulong); IsFloatingPointType = type == typeof(float) || type == typeof(double); IsGuid = type == typeof(Guid); // We need to ensure that we always return 8 (64-bit) even when running the generator on x64. Size = IsPointerSize ? 8 : SizeOf(type); AlignmentCore = IsPointerSize ? null : GetAlignment(type) ?? base.AlignmentCore; } internal readonly PrimitiveTypeIdentity? PrimitiveTypeIdentity; public override uint Size { get; } protected override uint? AlignmentCore { get; } public override bool IsBlittable => IsIntegerType || IsPointer || IsFloatingPointType || IsGuid || PrimitiveTypeIdentity is { Type: PrimitiveTypeCode.Void }; public bool IsValueType { get; } public bool IsPrimitive { get; } public bool IsIntPtr { get; } public bool IsPointer => IsTypedPointer || IsUntypedPointer; public bool IsUntypedPointer { get; } public bool IsTypedPointer { get; } public bool IsString { get; } public bool IsIntegerType { get; } public bool IsFloatingPointType { get; } public bool IsPointerSize => IsPointer || IsString; public bool IsGuid { get; } private static uint SizeOf(Type type) { try { if (type.IsEnum) type = Enum.GetUnderlyingType(type); return checked((uint) Marshal.SizeOf(type)); } catch (Exception) { return 0; } } /// <summary> /// Calculates the natural alignment of a type or null if it is a pointer alignment /// </summary> private static uint? GetAlignment(Type type) { if (type == typeof(long) || type == typeof(ulong) || type == typeof(double)) return 8; if (type == typeof(int) || type == typeof(uint) || type == typeof(float)) return 4; if (type == typeof(short) || type == typeof(ushort) || type == typeof(char)) return 2; if (type == typeof(byte) || type == typeof(sbyte)) return 1; return null; } private static Type ReducePointers(Type type, TypeInfo typeInfo) { while (true) { if (!typeInfo.IsPointer) return type; type = typeInfo.GetElementType(); typeInfo = type.GetTypeInfo(); } } } <|start_filename|>SharpGenTools.Sdk/Documentation/FindDocumentationResultSuccess.cs<|end_filename|> using System; using SharpGen.Doc; namespace SharpGenTools.Sdk.Documentation; internal sealed class FindDocumentationResultSuccess : IFindDocumentationResult { public FindDocumentationResultSuccess(IDocItem item) => Item = item ?? throw new ArgumentNullException(nameof(item)); public bool Success => true; public IDocItem Item { get; } } <|start_filename|>SharpGen/Generator/IGeneratorRegistry.cs<|end_filename|> using SharpGen.Model; namespace SharpGen.Generator; public interface IGeneratorRegistry { IMemberCodeGenerator<CsExpressionConstant> ExpressionConstant { get; } IMemberCodeGenerator<CsGuidConstant> GuidConstant { get; } IMemberCodeGenerator<CsResultConstant> ResultConstant { get; } IStatementCodeGenerator<CsResultConstant> ResultRegistration { get; } IMemberCodeGenerator<CsProperty> Property { get; } IMemberCodeGenerator<CsEnum> Enum { get; } IMemberCodeGenerator<CsStruct> NativeStruct { get; } IMemberCodeGenerator<CsField> ExplicitOffsetField { get; } IMemberCodeGenerator<CsField> AutoLayoutField { get; } IMemberCodeGenerator<CsStruct> Struct { get; } IStatementCodeGenerator<CsCallable> NativeInvocation { get; } IMemberCodeGenerator<CsCallable> Callable { get; } IMemberCodeGenerator<CsMethod> Method { get; } IMemberCodeGenerator<CsFunction> Function { get; } IMemberCodeGenerator<CsFunction> FunctionImport { get; } IMemberCodeGenerator<CsInterface> Interface { get; } IMemberCodeGenerator<CsInterface> Vtbl { get; } IMemberCodeGenerator<CsCallable> ShadowCallable { get; } IStatementCodeGenerator<CsCallable> ReverseCallableProlog { get; } IMemberCodeGenerator<CsGroup> Group { get; } MarshallingRegistry Marshalling { get; } GeneratorConfig Config { get; } } <|start_filename|>SharpGen/Model/CsElementExtensions.cs<|end_filename|> namespace SharpGen.Model; public static class CsElementExtensions { public static CsInterface GetNativeImplementationOrThis(this CsInterface iface) => iface.NativeImplementation ?? iface; public static string GetNativeImplementationQualifiedName(this CsTypeBase type) => type is CsInterface iface ? iface.GetNativeImplementationOrThis().QualifiedName : type.QualifiedName; } <|start_filename|>SharpGen/Transform/TypeRegistry.Primitives.cs<|end_filename|> using System; using System.Collections.Generic; using SharpGen.Model; namespace SharpGen.Transform; public partial class TypeRegistry { public static readonly CsFundamentalType Void = new( typeof(void), new PrimitiveTypeIdentity(PrimitiveTypeCode.Void), "void" ); public static readonly CsFundamentalType VoidPtr = new( typeof(void*), new PrimitiveTypeIdentity(PrimitiveTypeCode.Void, 1), "void*" ); public static readonly CsFundamentalType Int32 = new( typeof(int), new PrimitiveTypeIdentity(PrimitiveTypeCode.Int32), "int" ); public static readonly CsFundamentalType Int16 = new( typeof(short), new PrimitiveTypeIdentity(PrimitiveTypeCode.Int16), "short" ); public static readonly CsFundamentalType Float = new( typeof(float), new PrimitiveTypeIdentity(PrimitiveTypeCode.Float), "float" ); public static readonly CsFundamentalType Double = new( typeof(double), new PrimitiveTypeIdentity(PrimitiveTypeCode.Double), "double" ); public static readonly CsFundamentalType Int64 = new( typeof(long), new PrimitiveTypeIdentity(PrimitiveTypeCode.Int64), "long" ); public static readonly CsFundamentalType UInt32 = new( typeof(uint), new PrimitiveTypeIdentity(PrimitiveTypeCode.UInt32), "uint" ); public static readonly CsFundamentalType UInt64 = new( typeof(ulong), new PrimitiveTypeIdentity(PrimitiveTypeCode.UInt64), "ulong" ); public static readonly CsFundamentalType UInt16 = new( typeof(ushort), new PrimitiveTypeIdentity(PrimitiveTypeCode.UInt16), "ushort" ); public static readonly CsFundamentalType UInt8 = new( typeof(byte), new PrimitiveTypeIdentity(PrimitiveTypeCode.UInt8), "byte" ); public static readonly CsFundamentalType Int8 = new( typeof(sbyte), new PrimitiveTypeIdentity(PrimitiveTypeCode.Int8), "sbyte" ); public static readonly CsFundamentalType Boolean = new( typeof(bool), new PrimitiveTypeIdentity(PrimitiveTypeCode.Boolean), "bool" ); public static readonly CsFundamentalType Char = new( typeof(char), new PrimitiveTypeIdentity(PrimitiveTypeCode.Char), "char" ); public static readonly CsFundamentalType Decimal = new( typeof(decimal), new PrimitiveTypeIdentity(PrimitiveTypeCode.Decimal), "decimal" ); public static readonly CsFundamentalType String = new( typeof(string), new PrimitiveTypeIdentity(PrimitiveTypeCode.String), "string" ); public static readonly CsFundamentalType IntPtr = new( typeof(IntPtr), new PrimitiveTypeIdentity(PrimitiveTypeCode.IntPtr), "System.IntPtr" ); public static readonly CsFundamentalType UIntPtr = new( typeof(UIntPtr), new PrimitiveTypeIdentity(PrimitiveTypeCode.UIntPtr), "System.UIntPtr" ); private static readonly Dictionary<PrimitiveTypeIdentity, CsFundamentalType> PrimitiveTypeEntriesByIdentity = new() { // ReSharper disable PossibleInvalidOperationException [Void.PrimitiveTypeIdentity.Value] = Void, [VoidPtr.PrimitiveTypeIdentity.Value] = VoidPtr, [Int32.PrimitiveTypeIdentity.Value] = Int32, [Int16.PrimitiveTypeIdentity.Value] = Int16, [Float.PrimitiveTypeIdentity.Value] = Float, [Double.PrimitiveTypeIdentity.Value] = Double, [Int64.PrimitiveTypeIdentity.Value] = Int64, [UInt32.PrimitiveTypeIdentity.Value] = UInt32, [UInt64.PrimitiveTypeIdentity.Value] = UInt64, [UInt16.PrimitiveTypeIdentity.Value] = UInt16, [UInt8.PrimitiveTypeIdentity.Value] = UInt8, [Int8.PrimitiveTypeIdentity.Value] = Int8, [Boolean.PrimitiveTypeIdentity.Value] = Boolean, [Char.PrimitiveTypeIdentity.Value] = Char, [Decimal.PrimitiveTypeIdentity.Value] = Decimal, [String.PrimitiveTypeIdentity.Value] = String, [IntPtr.PrimitiveTypeIdentity.Value] = IntPtr, [UIntPtr.PrimitiveTypeIdentity.Value] = UIntPtr, // ReSharper restore PossibleInvalidOperationException }; private static readonly Dictionary<string, CsFundamentalType> PrimitiveTypeEntriesByName = new() { ["void"] = Void, ["void*"] = VoidPtr, ["int"] = Int32, ["short"] = Int16, ["float"] = Float, ["double"] = Double, ["long"] = Int64, ["uint"] = UInt32, ["ulong"] = UInt64, ["ushort"] = UInt16, ["byte"] = UInt8, ["sbyte"] = Int8, ["bool"] = Boolean, ["char"] = Char, ["decimal"] = Decimal, ["string"] = String, ["IntPtr"] = IntPtr, ["UIntPtr"] = UIntPtr, ["System.IntPtr"] = IntPtr, ["System.UIntPtr"] = UIntPtr, ["nint"] = IntPtr, ["nuint"] = UIntPtr, }; private static readonly Dictionary<PrimitiveTypeCode, Type> PrimitiveRuntimeTypesByCode = new() { [PrimitiveTypeCode.Void] = typeof(void), [PrimitiveTypeCode.Int32] = typeof(int), [PrimitiveTypeCode.Int16] = typeof(short), [PrimitiveTypeCode.Float] = typeof(float), [PrimitiveTypeCode.Double] = typeof(double), [PrimitiveTypeCode.Int64] = typeof(long), [PrimitiveTypeCode.UInt32] = typeof(uint), [PrimitiveTypeCode.UInt64] = typeof(ulong), [PrimitiveTypeCode.UInt16] = typeof(ushort), [PrimitiveTypeCode.UInt8] = typeof(byte), [PrimitiveTypeCode.Int8] = typeof(sbyte), [PrimitiveTypeCode.Boolean] = typeof(bool), [PrimitiveTypeCode.Char] = typeof(char), [PrimitiveTypeCode.Decimal] = typeof(decimal), [PrimitiveTypeCode.String] = typeof(string), [PrimitiveTypeCode.IntPtr] = typeof(IntPtr), [PrimitiveTypeCode.UIntPtr] = typeof(UIntPtr), }; } <|start_filename|>SharpGen.UnitTests/Runtime/VtblTests.cs<|end_filename|> using System; using System.Runtime.InteropServices; using SharpGen.Runtime; using Xunit; namespace SharpGen.UnitTests.Runtime; public class VtblTests { [Fact] public void CanRoundTripCallThroughNativeVtblToManagedObject() { using var callback = new CallbackImpl(); var callbackPtr = MarshallingHelpers.ToCallbackPtr<ICallback>(callback); Assert.NotEqual(IntPtr.Zero, callbackPtr); var methodPtr = Marshal.ReadIntPtr(Marshal.ReadIntPtr(callbackPtr)); var delegateObject = Marshal.GetDelegateForFunctionPointer<CallbackVtbl.IncrementDelegate>(methodPtr); Assert.Equal(3, delegateObject(callbackPtr, 2)); } } <|start_filename|>SharpGen/Generator/Marshallers/PointerSizeMarshaller.cs<|end_filename|> using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Syntax; using SharpGen.Model; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; namespace SharpGen.Generator.Marshallers; internal sealed class PointerSizeMarshaller : ValueTypeMarshallerBase { protected override bool CanMarshal(CsMarshalCallableBase csElement) => (csElement.PublicType.IsWellKnownType(GlobalNamespace, WellKnownName.PointerSize) || csElement.PublicType is CsFundamentalType {IsPointer: true}) && csElement is CsParameter {IsIn: true} or CsReturnValue; public override IEnumerable<StatementSyntax> GenerateManagedToNativeProlog(CsMarshalCallableBase csElement) => Enumerable.Empty<StatementSyntax>(); public override ArgumentSyntax GenerateNativeArgument(CsMarshalCallableBase csElement) => Argument( CastExpression(VoidPtrType, IdentifierName(csElement.Name)) ); public override FixedStatementSyntax GeneratePin(CsParameter csElement) => null; protected override CsTypeBase GetMarshalType(CsMarshalBase csElement) => csElement.MarshalType; public PointerSizeMarshaller(Ioc ioc) : base(ioc) { } } <|start_filename|>SharpGen.Generator/SharpGenModuleGenerator.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Syntax; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; namespace SharpGen.Generator; [Generator] public sealed partial class SharpGenModuleGenerator : ISourceGenerator { private const string CallbackableInterfaceName = "SharpGen.Runtime.ICallbackable"; private const string ModuleInitializerAttributeName = "System.Runtime.CompilerServices.ModuleInitializerAttribute"; private static readonly AttributeListSyntax ModuleInitializerAttributeList = AttributeList( SingletonSeparatedList(Attribute(ParseName(ModuleInitializerAttributeName))) ); private static readonly NameSyntax TypeDataStorage = ParseName("SharpGen.Runtime.TypeDataStorage"); public void Initialize(GeneratorInitializationContext context) { context.RegisterForSyntaxNotifications(static () => new SemanticTreeWalker()); } public void Execute(GeneratorExecutionContext context) { var configOptions = context.AnalyzerConfigOptions.GlobalOptions; var waitForDebuggerAttach = false; #pragma warning disable CA1806 if (configOptions.TryGetValue("build_property.SharpGenWaitForRoslynDebuggerAttach", out var value)) bool.TryParse(value, out waitForDebuggerAttach); #pragma warning restore CA1806 if (waitForDebuggerAttach) while (!Debugger.IsAttached && !context.CancellationToken.IsCancellationRequested) Thread.Sleep(TimeSpan.FromSeconds(1)); if (context.CancellationToken.IsCancellationRequested) return; GenerateUtilities(context); if (context.CancellationToken.IsCancellationRequested) return; GenerateModule(context); } private static CompilationUnitSyntax GenerateCompilationUnit( params MemberDeclarationSyntax[] namespaceDeclarations ) => GenerateCompilationUnit((IEnumerable<MemberDeclarationSyntax>) namespaceDeclarations); private static CompilationUnitSyntax GenerateCompilationUnit( IEnumerable<MemberDeclarationSyntax> namespaceDeclarations ) => CompilationUnit(default, default, default, List(namespaceDeclarations)) .NormalizeWhitespace(elasticTrivia: true); private sealed class SemanticTreeWalker : ISyntaxContextReceiver { public readonly HashSet<ITypeSymbol> QueuedJobs = new(SymbolEqualityComparer.Default); public void OnVisitSyntaxNode(GeneratorSyntaxContext context) { var syntaxNode = context.Node; if (syntaxNode.Language != LanguageNames.CSharp) return; if (syntaxNode is InterfaceDeclarationSyntax or ClassDeclarationSyntax) { switch (context.SemanticModel.GetDeclaredSymbol(syntaxNode)) { case ITypeSymbol symbol: QueuedJobs.Add(symbol); break; default: throw new ArgumentOutOfRangeException(); } } } } } <|start_filename|>SharpGen/Generator/Marshallers/FieldMarshallerBase.cs<|end_filename|> using System; using System.Collections.Generic; using Microsoft.CodeAnalysis.CSharp.Syntax; using SharpGen.Model; namespace SharpGen.Generator.Marshallers; internal abstract class FieldMarshallerBase : MarshallerBase, IMarshaller { public bool CanMarshal(CsMarshalBase csElement) => csElement is CsField field && CanMarshal(field); protected abstract bool CanMarshal(CsField csField); public bool GeneratesMarshalVariable(CsMarshalCallableBase csElement) => throw new NotSupportedException(); public TypeSyntax GetMarshalTypeSyntax(CsMarshalBase csElement) => throw new NotSupportedException(); public FixedStatementSyntax GeneratePin(CsParameter csElement) => throw new NotSupportedException(); public IEnumerable<StatementSyntax> GenerateManagedToNativeProlog(CsMarshalCallableBase csElement) => throw new NotSupportedException(); public IEnumerable<StatementSyntax> GenerateNativeToManagedExtendedProlog(CsMarshalCallableBase csElement) => throw new NotSupportedException(); public StatementSyntax GenerateManagedToNative(CsMarshalBase csElement, bool singleStackFrame) => GenerateManagedToNative((CsField) csElement, singleStackFrame); public StatementSyntax GenerateNativeToManaged(CsMarshalBase csElement, bool singleStackFrame) => GenerateNativeToManaged((CsField) csElement, singleStackFrame); protected abstract StatementSyntax GenerateManagedToNative(CsField csField, bool singleStackFrame); protected abstract StatementSyntax GenerateNativeToManaged(CsField csField, bool singleStackFrame); public ArgumentSyntax GenerateNativeArgument(CsMarshalCallableBase csElement) => throw new NotSupportedException(); public ArgumentSyntax GenerateManagedArgument(CsParameter csElement) => throw new NotSupportedException(); public ParameterSyntax GenerateManagedParameter(CsParameter csElement) => throw new NotSupportedException(); public StatementSyntax GenerateNativeCleanup(CsMarshalBase csElement, bool singleStackFrame) => AllowNativeCleanup ? null : throw new NotSupportedException(); protected abstract bool AllowNativeCleanup { get; } protected FieldMarshallerBase(Ioc ioc) : base(ioc) { } } <|start_filename|>SharpGen.Runtime/CppObjectCallableWrapper.cs<|end_filename|> #nullable enable using System; using System.Runtime.InteropServices; namespace SharpGen.Runtime; internal unsafe ref struct CppObjectCallableWrapper { internal static readonly int Size = IntPtr.Size * 2; // ReSharper disable once NotAccessedField.Local private void* _vtbl; private IntPtr _shadow; public readonly GCHandle Shadow => GCHandle.FromIntPtr(_shadow); public static IntPtr Create(void* vtbl, GCHandle callback) { // Allocate ptr to vtbl + ptr to callback together var nativePointer = Marshal.AllocHGlobal(Size); ref var native = ref *(CppObjectCallableWrapper*) nativePointer; native._vtbl = vtbl; native._shadow = GCHandle.ToIntPtr(callback); return nativePointer; } public static void Free(IntPtr pointer, bool disposing) { // Free the callback if (((CppObjectCallableWrapper*) pointer)->Shadow is { IsAllocated: true, Target: CppObjectShadow shadow } handle) { // Callback is a CppObjectShadow subtype. Dispose it if needed. MemoryHelpers.Dispose(shadow, disposing); // Free GCHandle if it points to a shadow, not the CallbackBase. Why? // Same GCHandle is reused in multiple CCWs to lower the handle table pressure. handle.Free(); } // Free instance Marshal.FreeHGlobal(pointer); } } <|start_filename|>SharpGen/VisualStudioSetup/ISetupPropertyStore.cs<|end_filename|> using System.Runtime.InteropServices; #pragma warning disable 0618 namespace SharpGen.VisualStudioSetup; [Guid("c601c175-a3be-44bc-91f6-4568d230fc83")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [ComImport] public interface ISetupPropertyStore { [return: MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_BSTR)] string[] GetNames(); object GetValue([MarshalAs(UnmanagedType.LPWStr), In] string pwszName); } <|start_filename|>SharpGen.UnitTests/Runtime/ICallback.cs<|end_filename|> using System; using System.Runtime.InteropServices; using SharpGen.Runtime; namespace SharpGen.UnitTests.Runtime; [Vtbl(typeof(CallbackVtbl))] interface ICallback : ICallbackable { int Increment(int param); } class CallbackImpl : CallbackBase, ICallback { public int Increment(int param) => param + 1; } public static class CallbackVtbl { private static readonly IncrementDelegate Increment = IncrementImpl; public static readonly IntPtr[] Vtbl = { Marshal.GetFunctionPointerForDelegate(Increment) }; [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate int IncrementDelegate(IntPtr thisObj, int param); private static int IncrementImpl(IntPtr thisObj, int param) => CppObjectShadow.ToCallback<ICallback>(thisObj).Increment(param); } [Vtbl(typeof(Callback2Vtbl))] interface ICallback2: ICallback { int Decrement(int param); } public static class Callback2Vtbl { private static readonly DecrementDelegate Decrement = DecrementImpl; public static IntPtr[] Vtbl { get; } = { Marshal.GetFunctionPointerForDelegate(Decrement) }; [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate int DecrementDelegate(IntPtr thisObj, int param); private static int DecrementImpl(IntPtr thisObj, int param) => CppObjectShadow.ToCallback<ICallback>(thisObj).Increment(param); } class Callback2Impl : CallbackImpl, ICallback, ICallback2 { public int Decrement(int param) => param - 1; } <|start_filename|>SharpGen/Model/CsResultConstant.cs<|end_filename|> using SharpGen.Config; using SharpGen.CppModel; namespace SharpGen.Model; public sealed class CsResultConstant : CsConstantBase { public CsResultConstant(CppElement cppElement, string name, string value, string module) : base(cppElement, name) { Value = value; Module = module; } protected override Visibility DefaultVisibility => Visibility.Public | Visibility.Static | Visibility.Readonly; public string Module { get; } public string Value { get; } protected override string DefaultDescription => $"Result {Name}"; } <|start_filename|>SharpGen/Model/MarshallableRelation.cs<|end_filename|> using Microsoft.CodeAnalysis.CSharp.Syntax; namespace SharpGen.Model; public abstract class MarshallableRelation { } public sealed class StructSizeRelation : MarshallableRelation { public override string ToString() { return "Size of enclosing structure"; } } public sealed class LengthRelation : MarshallableRelation { public string Identifier { get; set; } public override string ToString() { return $"Length of '{Identifier}'"; } } public sealed class ConstantValueRelation : MarshallableRelation { public ExpressionSyntax Value { get; set; } public override string ToString() { return $"Constant Value '{Value}'"; } } <|start_filename|>SharpGen/Transform/NamingRulesManager.HungarianNotation.cs<|end_filename|> using System; using System.Collections.Generic; using System.Linq; using SharpGen.CppModel; namespace SharpGen.Transform; public sealed partial class NamingRulesManager { private readonly List<HungarianNotationPrefix> _hungarianNotation = new() { new HungarianNotationPrefix("pp", HungarianOutPrefixSelector, "Out", "Ref", "Pointer", "Array"), new HungarianNotationPrefix("p", HungarianRefPrefixSelector, "Ref", "Pointer", "Array", "Out"), new HungarianNotationPrefix("lp", HungarianRefPrefixSelector, "Ref", "Pointer", "Array", "Out"), new HungarianNotationPrefix("pv", HungarianRefPrefixSelector, "Ref", "Pointer", "Array", "Out"), new HungarianNotationPrefix("b", HungarianIntegerPrefixSelector), new HungarianNotationPrefix("u", HungarianIntegerPrefixSelector), new HungarianNotationPrefix("n", HungarianIntegerPrefixSelector, string.Empty, "Count", "Int"), new HungarianNotationPrefix("i", HungarianIntegerPrefixSelector, string.Empty, "Index", "Int"), new HungarianNotationPrefix("ul", HungarianIntegerPrefixSelector), new HungarianNotationPrefix("us", HungarianIntegerPrefixSelector), new HungarianNotationPrefix("l", HungarianIntegerPrefixSelector), new HungarianNotationPrefix("w", HungarianIntegerPrefixSelector), new HungarianNotationPrefix("dw", HungarianIntegerPrefixSelector), new HungarianNotationPrefix("qw", HungarianIntegerPrefixSelector), new HungarianNotationPrefix("fn", HungarianFunctionPrefixSelector, "Function", "Delegate"), new HungarianNotationPrefix("pfn", HungarianFunctionPrefixSelector, "Function", "Delegate"), new HungarianNotationPrefix("lpfn", HungarianFunctionPrefixSelector, "Function", "Delegate"), new HungarianNotationPrefix("f", HungarianIntegerPrefixSelector, "Flag", "Enable", "Float"), new HungarianNotationPrefix("cb", HungarianIntegerPrefixSelector, "ByteCount", "Size", "Length"), new HungarianNotationPrefix("h", HungarianFunctionPrefixSelector, "Handle"), new HungarianNotationPrefix("str", HungarianStringPrefixSelector, "String", "Text"), new HungarianNotationPrefix("bstr", HungarianStringPrefixSelector, "String", "Text"), new HungarianNotationPrefix("pbstr", HungarianStringPrefixSelector, "String", "Text"), new HungarianNotationPrefix("wsz", HungarianStringPrefixSelector, "String", "Text"), new HungarianNotationPrefix("pstr", HungarianStringPrefixSelector, "String", "Text"), new HungarianNotationPrefix("pwsz", HungarianStringPrefixSelector, "String", "Text"), new HungarianNotationPrefix("wcs", HungarianStringPrefixSelector, "String", "Text"), new HungarianNotationPrefix("pwcs", HungarianStringPrefixSelector, "String", "Text"), }; private static int HungarianOutPrefixSelector(CppMarshallable x) => x is CppParameter {HasPointer: true} ? 0 : -1; private static int HungarianRefPrefixSelector(CppMarshallable x) => x switch { CppParameter {HasPointer: true} => 0, CppField {HasPointer: true, IsArray: false, ArrayDimension: null or {Length: 0}} => 1, CppField {IsArray: true} => 2, _ => -1 }; private static int HungarianIntegerPrefixSelector(CppMarshallable x) => x is {HasPointer: false, IsArray: false, ArrayDimension: null or {Length: 0}} ? 0 : -1; private static int HungarianFunctionPrefixSelector(CppMarshallable x) => x is {IsArray: false, ArrayDimension: null or {Length: 0}} ? 0 : -1; private static int HungarianStringPrefixSelector(CppMarshallable x) => x is {HasPointer: true} ? 0 : -1; private sealed class HungarianNotationPrefix { public HungarianNotationPrefix(string prefix, Func<CppMarshallable, int> selector, params string[] suffixVariants) { Prefix = prefix ?? throw new ArgumentNullException(nameof(prefix)); Selector = selector ?? throw new ArgumentNullException(nameof(selector)); SuffixVariants = suffixVariants; LowerSuffixVariants = suffixVariants.Select(x => x.ToLowerInvariant()).ToArray(); } private string Prefix { get; } private Func<CppMarshallable, int> Selector { get; } private string[] SuffixVariants { get; } private string[] LowerSuffixVariants { get; } public bool Apply(CppMarshallable marshallable, string name, string originalName, string originalNameLower, out string[] variants) { variants = null; if (originalName.Length <= Prefix.Length + 1) return false; if (!originalName.StartsWith(Prefix)) return false; if (!char.IsUpper(originalName[Prefix.Length])) return false; var index = Selector(marshallable); if (index < 0) return false; var content = name.Substring(Prefix.Length); var contentLower = content.ToLowerInvariant(); string SuffixWith(string suffix) => content + suffix; bool SuffixPredicate(string x) => !contentLower.Contains(x) && !originalNameLower.Contains(x); IEnumerable<string> preferredSuffixedVariants, secondarySuffixedVariants; switch (SuffixVariants.Length) { case > 0 when index >= SuffixVariants.Length: return false; case > 0: preferredSuffixedVariants = new[] { SuffixVariants[index] } .Where(SuffixPredicate).Select(SuffixWith); secondarySuffixedVariants = SuffixVariants.Take(index) .Concat(SuffixVariants.Skip(index + 1)) .Where(SuffixPredicate) .Select(SuffixWith); break; default: preferredSuffixedVariants = secondarySuffixedVariants = Enumerable.Empty<string>(); break; } variants = new[] { content }.Concat(preferredSuffixedVariants).Concat(secondarySuffixedVariants) .ToArray(); return true; } } } <|start_filename|>SharpGen/Transform/MarshalledElementFactory.cs<|end_filename|> using System; using System.Diagnostics; using System.Linq; using SharpGen.Config; using SharpGen.CppModel; using SharpGen.Logging; using SharpGen.Model; namespace SharpGen.Transform; public sealed class MarshalledElementFactory { private readonly Ioc ioc; private Logger Logger => ioc.Logger; private GlobalNamespaceProvider GlobalNamespace => ioc.GlobalNamespace; private TypeRegistry TypeRegistry => ioc.TypeRegistry; public MarshalledElementFactory(Ioc ioc) { this.ioc = ioc ?? throw new ArgumentNullException(nameof(ioc)); } public event Action<CsStruct> RequestStructProcessing; private void CreateCore(CsMarshalBase csMarshallable) { var marshallable = (CppMarshallable) csMarshallable.CppElement; CsTypeBase publicType = null; CsTypeBase marshalType = null; var mappingRule = marshallable.Rule; var publicTypeName = mappingRule is {MappingType: { } mapType} ? mapType : marshallable.TypeName; // If CppType is an array, try first to get the binding for this array if (csMarshallable.IsArray) { publicType = TypeRegistry.FindBoundType(publicTypeName + "[" + marshallable.ArrayDimension + "]"); if (publicType != null) csMarshallable.IsArray = false; } if (publicType == null) { void AssignStringTypes(CsFundamentalType charType) { publicType = csMarshallable.HasPointer || csMarshallable.IsArray ? TypeRegistry.String : charType; marshalType = csMarshallable.IsArray ? charType : null; } switch (publicTypeName) { case "char": AssignStringTypes(TypeRegistry.UInt8); break; case "wchar_t": csMarshallable.IsWideChar = true; AssignStringTypes(TypeRegistry.Char); break; default: // Try to get a declared type if (!TypeRegistry.FindBoundType(publicTypeName, out var boundType)) { Logger.Fatal("Unknown type found [{0}]", publicTypeName); return; } publicType = boundType.CSharpType; // By default, use the underlying native type as the marshal type // if it differs from the public type. marshalType = TypeRegistry.FindBoundType(marshallable.TypeName); if (publicType == marshalType) marshalType = null; // Otherwise, get the registered marshal type if one exists marshalType ??= boundType.MarshalType; break; } } switch (publicType) { case CsStruct csStruct: { if (!csStruct.IsFullyMapped) // If a structure was not already parsed, then parse it before going further RequestStructProcessing?.Invoke(csStruct); if (!csStruct.IsFullyMapped) // No one tried to map the struct so we can't continue. Logger.Fatal( $"No struct processor processed {csStruct.QualifiedName}. Cannot continue processing" ); if (csStruct.HasMarshalType && !csMarshallable.HasPointer) // If referenced structure has a specialized marshalling, then use the structure's built-in marshalling marshalType = publicType; break; } case CsEnum: // enums don't need a marshal type. They can always marshal as their underlying type. marshalType = null; break; } if (publicType.IsWellKnownType(GlobalNamespace, WellKnownName.PointerSize)) marshalType = PointerType(mappingRule); // Present void* elements as IntPtr. Marshal strings as IntPtr if (marshallable.HasPointer) { if (publicType == TypeRegistry.Void) publicType = marshalType = PointerType(mappingRule); else if (publicType == TypeRegistry.String) marshalType = TypeRegistry.IntPtr; } csMarshallable.PublicType = publicType; csMarshallable.MarshalType = marshalType; csMarshallable.Relations = RelationParser.ParseRelation(mappingRule.Relation, Logger); } private static CsFundamentalType PointerType(MappingRule mappingRule) => mappingRule.KeepPointers != true ? TypeRegistry.IntPtr : TypeRegistry.VoidPtr; public CsReturnValue Create(CppReturnValue cppReturnValue) { CsReturnValue retVal = new(ioc, cppReturnValue); CreateCore(retVal); MakeGeneralPointersBeIntPtr(retVal); if (retVal.PublicType is CsInterface {IsCallback: true} iface) { retVal.PublicType = iface.GetNativeImplementationOrThis(); } return retVal; } public CsField Create(CppField cppField, string name) { CsField field = new(ioc, cppField, name); CreateCore(field); MakeGeneralPointersBeIntPtr(field); return field; } private static void MakeGeneralPointersBeIntPtr(CsMarshalBase csMarshallable) { if (!csMarshallable.HasPointer) return; if (csMarshallable is CsReturnValue {PublicType: CsStruct} && !csMarshallable.IsArray) return; csMarshallable.MarshalType = TypeRegistry.IntPtr; if (csMarshallable.IsString || csMarshallable.IsInterface) return; csMarshallable.PublicType = TypeRegistry.IntPtr; } public CsParameter Create(CppParameter cppParameter, string name) { CsParameter param = new(ioc, cppParameter, name); CreateCore(param); if (cppParameter.IsAttributeRuleRedundant) Logger.Message("Parameter [{0}] has redundant attribute rule specification", cppParameter.FullName); static bool HasFlag(ParamAttribute value, ParamAttribute flag) => (value & flag) == flag; // -------------------------------------------------------------------------------- // Pointer - Handle special cases // -------------------------------------------------------------------------------- if (param.HasPointer) { var paramRule = cppParameter.Rule; var numIndirections = cppParameter.Pointer.Count(static p => p is '*' or '&'); bool isBuffer, isIn, isInOut, isOut; { var cppAttribute = cppParameter.Attribute; // Force Interface** to be ParamAttribute.Out if (param.PublicType is CsInterface && cppAttribute == ParamAttribute.In && numIndirections == 2) cppAttribute = ParamAttribute.Out; isBuffer = HasFlag(cppAttribute, ParamAttribute.Buffer); isIn = HasFlag(cppAttribute, ParamAttribute.In); isInOut = HasFlag(cppAttribute, ParamAttribute.InOut); isOut = HasFlag(cppAttribute, ParamAttribute.Out); } // Either In, InOut or Out is set Debug.Assert((isIn ? 1 : 0) + (isInOut ? 1 : 0) + (isOut ? 1 : 0) == 1); // -------------------------------------------------------------------------------- // Handling Parameter Interface // -------------------------------------------------------------------------------- if (param.PublicType is CsInterface) { // Simplify logic by assuming interface instance pointer is the interface itself. --numIndirections; if (isOut) param.Attribute = CsParameterAttribute.Out; } else if (isIn) { var publicType = param.PublicType; param.Attribute = publicType is CsFundamentalType {IsPointerSize: true} || publicType.IsWellKnownType(GlobalNamespace, WellKnownName.FunctionCallback) ? CsParameterAttribute.In : CsParameterAttribute.RefIn; } else if (isInOut) { if (param.IsOptional) { param.SetPublicResetMarshalType(PointerType(paramRule)); param.Attribute = CsParameterAttribute.In; } else { param.Attribute = CsParameterAttribute.Ref; } } else if (isOut) { param.Attribute = CsParameterAttribute.Out; } switch (param.PublicType) { // Handle void* with Buffer attribute case CsFundamentalType {IsUntypedPointer: true} when isBuffer: param.Attribute = CsParameterAttribute.In; param.IsArray = false; break; // Handle strings with Out attribute case CsFundamentalType {IsString: true} when isOut: param.Attribute = CsParameterAttribute.In; param.IsArray = false; param.SetPublicResetMarshalType(TypeRegistry.IntPtr); break; // There's no way to know how to deallocate native-allocated memory correctly // since we don't know what allocator the native memory uses, // so we treat any extra pointer indirections as IntPtr case not CsFundamentalType {IsUntypedPointer: true} when numIndirections > 1: param.IsArray = false; param.SetPublicResetMarshalType(TypeRegistry.IntPtr); break; } } if (param.Relations.OfType<StructSizeRelation>().Any()) Logger.Error( LoggingCodes.InvalidRelation, $"Parameter [{cppParameter}] marked with a struct-size relationship" ); return param; } } <|start_filename|>SharpGen.Platform/Documentation/DocConverterUtilities.cs<|end_filename|> using System.Collections.Generic; using System.Text.Json; using System.Text.Json.Serialization; namespace SharpGen.Platform.Documentation; internal static class DocConverterUtilities { public static T ReadProperty<T>(ref Utf8JsonReader reader, string expectedPropertyName, JsonSerializerOptions options) { if (!reader.Read()) throw new JsonException(); if (reader.TokenType != JsonTokenType.PropertyName) throw new JsonException(); var propertyName = reader.GetString(); if (!reader.Read()) throw new JsonException(); if (propertyName != expectedPropertyName) throw new JsonException(); return JsonSerializer.Deserialize<T>(ref reader, options); } public static void WriteProperty<T>(Utf8JsonWriter writer, JsonSerializerOptions options, ref JsonConverter<T> converter, string name, T value) { converter ??= (JsonConverter<T>) options.GetConverter(typeof(T)); writer.WritePropertyName(name); converter.Write(writer, value, options); } public static void AssignList<T>(IList<T> storage, IEnumerable<T> source) { storage.Clear(); foreach (var subItem in source) storage.Add(subItem); } } <|start_filename|>SharpGen/VisualStudioSetup/IEnumSetupInstances.cs<|end_filename|>  using System.Runtime.InteropServices; namespace SharpGen.VisualStudioSetup; [Guid("6380BCFF-41D3-4B2E-8B2E-BF8A6810C848")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [ComImport] public interface IEnumSetupInstances { void Next([MarshalAs(UnmanagedType.U4), In] int celt, [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.Interface), Out] ISetupInstance[] rgelt, [MarshalAs(UnmanagedType.U4)] out int pceltFetched); void Skip([MarshalAs(UnmanagedType.U4), In] int celt); void Reset(); [return: MarshalAs(UnmanagedType.Interface)] IEnumSetupInstances Clone(); } <|start_filename|>SharpGen/Model/CsMarshalCallableBase.cs<|end_filename|> using SharpGen.CppModel; namespace SharpGen.Model; public abstract class CsMarshalCallableBase : CsMarshalBase { public abstract bool UsedAsReturn { get; } public abstract bool IsOut { get; } public abstract bool IsFixed { get; } public abstract bool IsLocalManagedReference { get; } public abstract bool PassedByNativeReference { get; } protected CsMarshalCallableBase(Ioc ioc, CppMarshallable cppElement, string name) : base(ioc, cppElement, name) { } } <|start_filename|>SharpGen.UnitTests/RelationParserTests.cs<|end_filename|> using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using SharpGen.Logging; using SharpGen.Model; using SharpGen.Transform; using Xunit; using Xunit.Abstractions; namespace SharpGen.UnitTests; public class RelationParserTests : TestBase { public RelationParserTests(ITestOutputHelper outputHelper) : base(outputHelper) { } [Fact] public void ParseFailsOnMissingInput() { using (LoggerEmptyEnvironment()) { Assert.Null(RelationParser.ParseRelation(null, Logger)); } using (LoggerEmptyEnvironment()) { Assert.Null(RelationParser.ParseRelation("", Logger)); } using (LoggerEmptyEnvironment()) { Assert.Null(RelationParser.ParseRelation(" ", Logger)); } } [Fact] public void ParseFailsOnUnexpectedInput() { using (LoggerMessageCountEnvironment(2, LogLevel.Error)) using (LoggerMessageCountEnvironment(0, ~LogLevel.Error)) using (LoggerCodeRequiredEnvironment(LoggingCodes.InvalidRelation)) { Assert.Null(RelationParser.ParseRelation("Samaritan", Logger)); } using (LoggerMessageCountEnvironment(2, LogLevel.Error)) using (LoggerMessageCountEnvironment(0, ~LogLevel.Error)) using (LoggerCodeRequiredEnvironment(LoggingCodes.InvalidRelation)) { Assert.Null(RelationParser.ParseRelation("struct(", Logger)); } using (LoggerMessageCountEnvironment(2, LogLevel.Error)) using (LoggerMessageCountEnvironment(0, ~LogLevel.Error)) using (LoggerCodeRequiredEnvironment(LoggingCodes.InvalidRelation)) { Assert.Null(RelationParser.ParseRelation("struct()", Logger)); } using (LoggerMessageCountEnvironment(2, LogLevel.Error)) using (LoggerMessageCountEnvironment(0, ~LogLevel.Error)) using (LoggerCodeRequiredEnvironment(LoggingCodes.InvalidRelation)) { Assert.Null(RelationParser.ParseRelation("struct-size(42)", Logger)); } using (LoggerMessageCountEnvironment(2, LogLevel.Error)) using (LoggerMessageCountEnvironment(0, ~LogLevel.Error)) { Assert.Null(RelationParser.ParseRelation("length()", Logger)); } using (LoggerMessageCountEnvironment(2, LogLevel.Error)) using (LoggerMessageCountEnvironment(0, ~LogLevel.Error)) using (LoggerCodeRequiredEnvironment(LoggingCodes.InvalidRelation)) { Assert.Null(RelationParser.ParseRelation("Math.Max(42)", Logger)); } } [Fact] public void ParseMixedRelations() { using (LoggerEmptyEnvironment()) { const string const1 = "int.MaxValue"; const string const2 = "Math.Max( int.MinValue,Math.Pow(10, 3) ) "; var relations = RelationParser.ParseRelation($"length(initialValue), const({const1}), const({const2})", Logger); Assert.NotNull(relations); Assert.Equal(3, relations.Count); Assert.IsType<LengthRelation>(relations[0]); Assert.Equal("initialValue", ((LengthRelation) relations[0]).Identifier); Assert.IsType<ConstantValueRelation>(relations[1]); Assert.IsType<MemberAccessExpressionSyntax>(((ConstantValueRelation) relations[1]).Value); Assert.Equal(const1, ((ConstantValueRelation) relations[1]).Value.ToFullString()); Assert.IsType<ConstantValueRelation>(relations[2]); Assert.IsType<InvocationExpressionSyntax>(((ConstantValueRelation) relations[2]).Value); Assert.Equal(const2, ((ConstantValueRelation) relations[2]).Value.ToFullString()); } } [Fact] public void ParseMultipleLengths() { using (LoggerEmptyEnvironment()) { var relations = RelationParser.ParseRelation("length(initialValue),length(initialVelocity)", Logger); Assert.NotNull(relations); Assert.Equal(2, relations.Count); Assert.All(relations, relation => Assert.IsType<LengthRelation>(relation)); Assert.Equal("initialValue", ((LengthRelation) relations[0]).Identifier); Assert.Equal("initialVelocity", ((LengthRelation) relations[1]).Identifier); } using (LoggerEmptyEnvironment()) { var relations = RelationParser.ParseRelation(" length ( initialValue ) , length ( initialVelocity ) ", Logger); Assert.NotNull(relations); Assert.Equal(2, relations.Count); Assert.All(relations, relation => Assert.IsType<LengthRelation>(relation)); Assert.Equal("initialValue", ((LengthRelation) relations[0]).Identifier); Assert.Equal("initialVelocity", ((LengthRelation) relations[1]).Identifier); } } [Fact] public void ParsePreservesContents() { using (LoggerEmptyEnvironment()) { const string value = "Math.Max( int.MinValue, Math.Pow(10, 3) )"; var relations = RelationParser.ParseRelation($"const ( {value} )", Logger); Assert.NotNull(relations); Assert.Single(relations); Assert.IsType<ConstantValueRelation>(relations[0]); Assert.IsType<InvocationExpressionSyntax>(((ConstantValueRelation) relations[0]).Value); Assert.Equal(value, ((ConstantValueRelation) relations[0]).Value.ToString()); } using (LoggerEmptyEnvironment()) { const string value = "Math.Max( int.MinValue, Math.Pow (10, 3) )"; var relations = RelationParser.ParseRelation($"const ( {value})", Logger); Assert.NotNull(relations); Assert.Single(relations); Assert.IsType<ConstantValueRelation>(relations[0]); Assert.IsType<InvocationExpressionSyntax>(((ConstantValueRelation) relations[0]).Value); Assert.Equal(value, ((ConstantValueRelation) relations[0]).Value.ToString()); } using (LoggerEmptyEnvironment()) { const string value = "\"Real Control is surgical. Invisible.\""; var relations = RelationParser.ParseRelation($"const ({value})", Logger); Assert.NotNull(relations); Assert.Single(relations); Assert.IsType<ConstantValueRelation>(relations[0]); Assert.IsType<LiteralExpressionSyntax>(((ConstantValueRelation) relations[0]).Value); Assert.Equal(value, ((ConstantValueRelation) relations[0]).Value.ToString()); } using (LoggerEmptyEnvironment()) { const string value = "\"Real Control is surgical (invisible ).\""; var relations = RelationParser.ParseRelation($"const ({value})", Logger); Assert.NotNull(relations); Assert.Single(relations); Assert.IsType<ConstantValueRelation>(relations[0]); Assert.IsType<LiteralExpressionSyntax>(((ConstantValueRelation) relations[0]).Value); Assert.Equal(value, ((ConstantValueRelation) relations[0]).Value.ToString()); } using (LoggerEmptyEnvironment()) { const string value = "\"Real Control is surgical ( invisible .\""; var relations = RelationParser.ParseRelation($"const ({value})", Logger); Assert.NotNull(relations); Assert.Single(relations); Assert.IsType<ConstantValueRelation>(relations[0]); Assert.IsType<LiteralExpressionSyntax>(((ConstantValueRelation) relations[0]).Value); Assert.Equal(value, ((ConstantValueRelation) relations[0]).Value.ToString()); } using (LoggerEmptyEnvironment()) { const string value = "\"Real Control is surgical. Invisible)).\""; var relations = RelationParser.ParseRelation($"const ({value})", Logger); Assert.NotNull(relations); Assert.Single(relations); Assert.IsType<ConstantValueRelation>(relations[0]); Assert.IsType<LiteralExpressionSyntax>(((ConstantValueRelation) relations[0]).Value); Assert.Equal(value, ((ConstantValueRelation) relations[0]).Value.ToString()); } using (LoggerEmptyEnvironment()) { const string value = "DEBUG"; var relations = RelationParser.ParseRelation($"const({value})", Logger); Assert.NotNull(relations); Assert.Single(relations); Assert.IsType<ConstantValueRelation>(relations[0]); Assert.IsType<IdentifierNameSyntax>(((ConstantValueRelation) relations[0]).Value); Assert.Equal(value, ((ConstantValueRelation) relations[0]).Value.ToString()); } using (LoggerEmptyEnvironment()) { const string value = "((( ())) )"; var relations = RelationParser.ParseRelation($"const ({value} )", Logger); Assert.NotNull(relations); Assert.Single(relations); Assert.IsType<ConstantValueRelation>(relations[0]); Assert.IsType<ParenthesizedExpressionSyntax>(((ConstantValueRelation) relations[0]).Value); Assert.Equal(value, ((ConstantValueRelation) relations[0]).Value.ToString()); } } [Fact] public void ParseSimpleConstantValue() { using (LoggerEmptyEnvironment()) { var relations = RelationParser.ParseRelation("Const(null)", Logger); Assert.NotNull(relations); Assert.Single(relations); Assert.IsType<ConstantValueRelation>(relations[0]); Assert.IsType<LiteralExpressionSyntax>(((ConstantValueRelation) relations[0]).Value); Assert.Equal(SyntaxKind.NullLiteralExpression, ((LiteralExpressionSyntax)((ConstantValueRelation) relations[0]).Value).Kind()); } using (LoggerEmptyEnvironment()) { var relations = RelationParser.ParseRelation("Const(default)", Logger); Assert.NotNull(relations); Assert.Single(relations); Assert.IsType<ConstantValueRelation>(relations[0]); Assert.IsType<LiteralExpressionSyntax>(((ConstantValueRelation) relations[0]).Value); Assert.Equal(SyntaxKind.DefaultLiteralExpression, ((LiteralExpressionSyntax)((ConstantValueRelation) relations[0]).Value).Kind()); } using (LoggerEmptyEnvironment()) { var relations = RelationParser.ParseRelation("const(0)", Logger); Assert.NotNull(relations); Assert.Single(relations); Assert.IsType<ConstantValueRelation>(relations[0]); Assert.IsType<LiteralExpressionSyntax>(((ConstantValueRelation) relations[0]).Value); Assert.Equal("0", ((ConstantValueRelation) relations[0]).Value.ToFullString()); } } [Fact] public void ParseSimpleLength() { using (LoggerEmptyEnvironment()) { var relations = RelationParser.ParseRelation("length(42)", Logger); Assert.NotNull(relations); Assert.Single(relations); Assert.IsType<LengthRelation>(relations[0]); Assert.Equal("42", ((LengthRelation) relations[0]).Identifier); } using (LoggerEmptyEnvironment()) { var relations = RelationParser.ParseRelation("Length(42)", Logger); Assert.NotNull(relations); Assert.Single(relations); Assert.IsType<LengthRelation>(relations[0]); Assert.Equal("42", ((LengthRelation) relations[0]).Identifier); } using (LoggerEmptyEnvironment()) { var relations = RelationParser.ParseRelation("length(-abc/123)", Logger); Assert.NotNull(relations); Assert.Single(relations); Assert.IsType<LengthRelation>(relations[0]); Assert.Equal("-abc/123", ((LengthRelation) relations[0]).Identifier); } } [Fact] public void ParseSimpleStructSize() { using (LoggerEmptyEnvironment()) { var relations = RelationParser.ParseRelation("StructSize()", Logger); Assert.NotNull(relations); Assert.Single(relations); Assert.IsType<StructSizeRelation>(relations[0]); } using (LoggerEmptyEnvironment()) { var relations = RelationParser.ParseRelation("struct-size()", Logger); Assert.NotNull(relations); Assert.Single(relations); Assert.IsType<StructSizeRelation>(relations[0]); } using (LoggerEmptyEnvironment()) { var relations = RelationParser.ParseRelation("struct-size( )", Logger); Assert.NotNull(relations); Assert.Single(relations); Assert.IsType<StructSizeRelation>(relations[0]); } } [Fact] public void ParseWarnsOnExtraReplacedSubstrings() { using (LoggerMessageCountEnvironment(1, LogLevel.Warning)) using (LoggerMessageCountEnvironment(0, ~LogLevel.Warning)) { var relations = RelationParser.ParseRelation("const(\"struct-size\")", Logger); Assert.NotNull(relations); Assert.Single(relations); Assert.IsType<ConstantValueRelation>(relations[0]); Assert.IsType<LiteralExpressionSyntax>(((ConstantValueRelation) relations[0]).Value); Assert.Equal($"\"{nameof(StructSizeRelation)}\"", ((ConstantValueRelation) relations[0]).Value.ToFullString()); } using (LoggerMessageCountEnvironment(2, LogLevel.Warning)) using (LoggerMessageCountEnvironment(0, ~LogLevel.Warning)) { var relations = RelationParser.ParseRelation("struct-size(), const(\"struct-size\"), const(\"const(42)\")", Logger); Assert.NotNull(relations); Assert.Equal(3, relations.Count); Assert.IsType<StructSizeRelation>(relations[0]); Assert.IsType<ConstantValueRelation>(relations[1]); Assert.IsType<LiteralExpressionSyntax>(((ConstantValueRelation) relations[1]).Value); Assert.Equal($"\"{nameof(StructSizeRelation)}\"", ((ConstantValueRelation) relations[1]).Value.ToFullString()); Assert.IsType<ConstantValueRelation>(relations[2]); Assert.IsType<LiteralExpressionSyntax>(((ConstantValueRelation) relations[2]).Value); Assert.Equal($"\"{nameof(ConstantValueRelation)}(42)\"", ((ConstantValueRelation) relations[2]).Value.ToFullString()); } } } <|start_filename|>SharpGen.UnitTests/ModelTestExtensions.cs<|end_filename|> using System.Collections.Generic; using System.Linq; using SharpGen.CppModel; using SharpGen.Model; namespace SharpGen.UnitTests; internal static class ModelTestExtensions { public static T FindFirst<T>(this CppElement element, string path) where T : CppElement => element.Find<T>(path).FirstOrDefault(); public static IEnumerable<T> Find<T>(this CppElement element, string path) where T : CppElement => new CppElementFinder(element).Find<T>(path); public static CsBase[] EnumerateDescendants(this CsBase element, bool withAdditionalItems = true) => ModelUtilities.EnumerateDescendants(element, withAdditionalItems).ToArray(); public static T[] EnumerateDescendants<T>(this CsBase element, bool withAdditionalItems = true) where T : CsBase => ModelUtilities.EnumerateDescendants<T>(element, withAdditionalItems).ToArray(); } <|start_filename|>SharpGen/Model/CsMarshalBase.cs<|end_filename|> // Copyright (c) 2010-2014 SharpDX - <NAME> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Collections.Generic; using System.Collections.Immutable; using SharpGen.Config; using SharpGen.CppModel; using SharpGen.Generator.Marshallers; using SharpGen.Transform; namespace SharpGen.Model; public abstract class CsMarshalBase : CsBase { #nullable enable private IReadOnlyList<MarshallableRelation>? relations; private CsTypeBase? marshalType; private CsTypeBase publicType; /// <summary> /// Public type used for element. /// </summary> public CsTypeBase PublicType { get => publicType; set => publicType = value ?? throw new ArgumentException("Public type cannot be null"); } /// <summary> /// Internal type used for marshalling to native. /// </summary> public CsTypeBase MarshalType { get => marshalType ?? PublicType; set => marshalType = value; } public void SetPublicResetMarshalType(CsTypeBase type) { PublicType = type; marshalType = null; } public virtual bool HasPointer { get; } public ArraySpecification? ArraySpecification { get; private set; } public bool IsWideChar { get; set; } public virtual bool IsArray { get => ArraySpecification.HasValue; set { switch (value) { case true when ArraySpecification.HasValue: return; case true: ArraySpecification = new ArraySpecification(); return; case false: ArraySpecification = null; break; } } } public int ArrayDimensionValue => ArraySpecification is {Dimension: { } value} ? checked((int) value) : 0; public uint ArrayDimensionValueUnsigned => ArraySpecification is {Dimension: { } value} ? value : 0; public IReadOnlyList<MarshallableRelation> Relations { get => relations ?? ImmutableList<MarshallableRelation>.Empty; set => relations = value; } public bool IsBoolToInt => MarshalType is CsFundamentalType {IsIntegerType: true} && PublicType == TypeRegistry.Boolean; public uint Size => MarshalType.Size * (ArraySpecification is {Dimension: { } value} ? Math.Max(value, 1) : 1); public bool IsValueType => PublicType is CsStruct {GenerateAsClass: false} or CsEnum or CsFundamentalType {IsValueType: true}; public bool IsInterface => PublicType is CsInterface; public bool IsStructClass => PublicType is CsStruct {GenerateAsClass: true}; public bool IsPrimitive => PublicType is CsFundamentalType {IsPrimitive: true} or CsEnum; public bool IsString => PublicType is CsFundamentalType {IsString: true}; public bool HasNativeValueType => PublicType is CsStruct {HasMarshalType: true}; public bool IsStaticMarshal => PublicType is CsStruct {IsStaticMarshal: true}; public bool IsInterfaceArray => PublicType is CsInterfaceArray; /// <remarks> /// Used in 2 cases: /// <list type="number"> /// <item> /// <description>Backing field in structs for non-trivial cases</description> /// </item> /// <item> /// <description>Pinned Span element pointer from <see cref="ArrayMarshallerBase"/></description> /// </item> /// </list> /// </remarks> public string IntermediateMarshalName => Name[0] == '@' ? $"_{Name.Substring(1)}" : $"_{Name}"; public bool MappedToDifferentPublicType => MarshalType != PublicType && !IsBoolToInt && !(MarshalType is CsFundamentalType {IsPointer: true} && HasPointer) && !(IsInterface && HasPointer); public StringMarshalType StringMarshal { get; } = StringMarshalType.GlobalHeap; #nullable restore protected CsMarshalBase(Ioc ioc, CppElement cppElement, string name) : base(cppElement, name) { if (cppElement is CppMarshallable cppMarshallable) { HasPointer = cppMarshallable.HasPointer; ArraySpecification = ParseArrayDimensionValue(cppMarshallable.IsArray, cppMarshallable.ArrayDimension); } if (cppElement is { Rule: { StringMarshal: { } stringMarshal } }) StringMarshal = stringMarshal; ArraySpecification? ParseArrayDimensionValue(bool isArray, string arrayDimension) { if (!isArray || string.IsNullOrEmpty(arrayDimension)) return null; if (arrayDimension.Contains(",")) { ioc.Logger.Warning(null, "SharpGen might not handle multidimensional arrays properly."); } // TODO: handle multidimensional arrays return uint.TryParse(arrayDimension, out var arrayDimensionValue) && arrayDimensionValue >= 1 ? new ArraySpecification(arrayDimensionValue) : null; } } public override IEnumerable<CsBase> AdditionalItems => AppendNonNull( base.AdditionalItems, PublicType, MarshalType ); } <|start_filename|>SharpGen.Runtime/TypeDataStorage.cs<|end_filename|> // #define FORCE_REFLECTION_ONLY #nullable enable using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; namespace SharpGen.Runtime; public static unsafe class TypeDataStorage { private static readonly ConcurrentDictionary<Guid, IntPtr> vtblByGuid = new(); static TypeDataStorage() { Storage<IUnknown>.Guid = new Guid(0x00000000, 0x0000, 0x0000, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46); Storage<IInspectable>.Guid = new Guid(0xAF86E2E0, 0xB12D, 0x4C6A, 0x9C, 0x5A, 0xD7, 0xAA, 0x65, 0x10, 0x1E, 0x90); Storage<IUnknown>.SourceVtbl = ComObjectVtbl.Vtbl; Storage<IInspectable>.SourceVtbl = InspectableVtbl.Vtbl; TypeDataRegistrationHelper helper = new(); { helper.Add(ComObjectVtbl.Vtbl); helper.Register<IUnknown>(); } { helper.Add(ComObjectVtbl.Vtbl); helper.Add(InspectableVtbl.Vtbl); helper.Register<IInspectable>(); } } [MethodImpl(Utilities.MethodAggressiveOptimization)] internal static Guid GetGuid<T>() where T : ICallbackable { #if !FORCE_REFLECTION_ONLY ref var guid = ref Storage<T>.Guid; if (guid != default) return guid; #if NETSTANDARD1_3 return guid = typeof(T).GetTypeInfo().GUID; #else return guid = typeof(T).GUID; #endif #else #if NETSTANDARD1_3 return typeof(T).GetTypeInfo().GUID; #else return typeof(T).GUID; #endif #endif } internal static void Register<T>(void* vtbl) where T : ICallbackable { #if !FORCE_REFLECTION_ONLY Register(GetGuid<T>(), vtbl); #endif } internal static void Register(Guid guid, void* vtbl) => vtblByGuid[guid] = new IntPtr(vtbl); internal static IntPtr[] GetSourceVtbl<T>() where T : ICallbackable { #if !FORCE_REFLECTION_ONLY if (Storage<T>.SourceVtbl is { } storedVtbl) return storedVtbl; #endif return GetSourceVtblFromReflection(typeof(T)); } private static IntPtr[] GetSourceVtblFromReflection(Type type) { const string vtbl = "Vtbl"; var vtblAttribute = VtblAttribute.Get(type); Debug.Assert(vtblAttribute is not null, $"Type {type.FullName} has no Vtbl attribute"); var vtblType = vtblAttribute.Type; #if NETSTANDARD1_3 static bool Predicate(MemberInfo x) => x.Name == vtbl; if (vtblType.GetRuntimeFields().FirstOrDefault(Predicate)?.GetValue(null) is IntPtr[] vtblFieldValue) { return vtblFieldValue; } if (vtblType.GetRuntimeProperties().FirstOrDefault(Predicate)?.GetValue(null) is IntPtr[] vtblPropertyValue) { return vtblPropertyValue; } #else const BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy | BindingFlags.Static; if (vtblType.GetField(vtbl, flags)?.GetValue(null) is IntPtr[] vtblFieldValue) { return vtblFieldValue; } if (vtblType.GetProperty(vtbl, flags)?.GetValue(null) is IntPtr[] vtblPropertyValue) { return vtblPropertyValue; } #endif Debug.Fail($"Type {type.FullName} has no Vtbl field or property"); return null; } internal static bool GetTargetVtbl(TypeInfo type, out void* pointer) { #if !FORCE_REFLECTION_ONLY if (vtblByGuid.TryGetValue(type.GUID, out var ptr)) { pointer = ptr.ToPointer(); return true; } #endif if (GetSourceVtblFromReflection(type.AsType()) is { } sourceVtbl) { pointer = RegisterFromReflection(type, sourceVtbl).ToPointer(); return true; } pointer = default; return false; } private static IntPtr RegisterFromReflection(TypeInfo type, IntPtr[] sourceVtbl) { var callbackable = typeof(ICallbackable).GetTypeInfo(); TypeDataRegistrationHelper helper = new(); List<RegisterInheritanceItem> items = new(); foreach (var iface in type.ImplementedInterfaces) { var typeInfo = iface.GetTypeInfo(); if (callbackable == typeInfo || !callbackable.IsAssignableFrom(typeInfo)) continue; var iSourceVtbl = GetSourceVtblFromReflection(iface); if (iSourceVtbl is null) throw new Exception($"Failed to reflect Vtbl out of an {nameof(ICallbackable)} interface '{iface.FullName}'."); items.Add(new RegisterInheritanceItem(typeInfo, typeInfo.ImplementedInterfaces.Count(), iSourceVtbl)); } // TODO: properly sort items by inheritance // TODO: verify single inheritance items.Sort(static (x, y) => Comparer<int>.Default.Compare(x.InterfaceCount, y.InterfaceCount)); foreach (var (_, _, iSourceVtbl) in items) helper.Add(iSourceVtbl); helper.Add(sourceVtbl); return helper.Register(type); } private record struct RegisterInheritanceItem(TypeInfo Type, int InterfaceCount, IntPtr[] SourceVtbl); [SuppressMessage("ReSharper", "StaticMemberInGenericType")] [SuppressMessage("Usage", "CA2211:Non-constant fields should not be visible")] public static class Storage<T> where T : ICallbackable { public static Guid Guid; public static IntPtr[] SourceVtbl; } } <|start_filename|>SharpGen.Runtime/MarshallingHelpers.FastToInterfaceArray.cs<|end_filename|> using System; namespace SharpGen.Runtime; public static partial class MarshallingHelpers { /// <summary> /// Converts an array of native object pointers to a <see cref="CppObject"/> array. /// </summary> public static void ConvertToInterfaceArrayFast<TCallback>(ReadOnlySpan<IntPtr> pointers, Span<TCallback> interfaces) where TCallback : CppObject { var arrayLength = pointers.Length; for (var i = 0; i < arrayLength; ++i) interfaces[i].NativePointer = pointers[i]; } /// <summary> /// Converts an array of native object pointers to a <see cref="CppObject"/> array. /// </summary> public static void ConvertToInterfaceArrayFast<TCallback>(Span<IntPtr> pointers, Span<TCallback> interfaces) where TCallback : CppObject { var arrayLength = pointers.Length; for (var i = 0; i < arrayLength; ++i) interfaces[i].NativePointer = pointers[i]; } /// <summary> /// Converts an array of native object pointers to a <see cref="CppObject"/> array. /// </summary> public static void ConvertToInterfaceArrayFast<TCallback>(Span<IntPtr> pointers, TCallback[] interfaces) where TCallback : CppObject { var arrayLength = pointers.Length; for (var i = 0; i < arrayLength; ++i) interfaces[i].NativePointer = pointers[i]; } /// <summary> /// Converts an array of native object pointers to a <see cref="CppObject"/> array. /// </summary> public static void ConvertToInterfaceArrayFast<TCallback>(Span<IntPtr> pointers, CppObject[] interfaces) where TCallback : CppObject { var arrayLength = pointers.Length; for (var i = 0; i < arrayLength; ++i) interfaces[i].NativePointer = pointers[i]; } /// <summary> /// Converts an array of native object pointers to a <see cref="CppObject"/> array. /// </summary> public static void ConvertToInterfaceArrayFast(Span<IntPtr> pointers, CppObject[] interfaces) { var arrayLength = pointers.Length; for (var i = 0; i < arrayLength; ++i) interfaces[i].NativePointer = pointers[i]; } } <|start_filename|>SharpGen/Model/PlatformDetectionType.cs<|end_filename|> using System; namespace SharpGen.Model; [Flags] public enum PlatformDetectionType { Windows = 1 << 0, ItaniumSystemV = 1 << 1, Any = Windows | ItaniumSystemV } <|start_filename|>SharpGen/Generator/GuidConstantCodeGenerator.cs<|end_filename|> using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using SharpGen.Model; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; namespace SharpGen.Generator; internal sealed class GuidConstantCodeGenerator : MemberSingleCodeGeneratorBase<CsGuidConstant> { public GuidConstantCodeGenerator(Ioc ioc) : base(ioc) { } public override MemberDeclarationSyntax GenerateCode(CsGuidConstant csElement) { static ArgumentSyntax ArgumentSelector(SyntaxToken x) => Argument(LiteralExpression(SyntaxKind.NumericLiteralExpression, x)); var guidArguments = GuidConstantRoslynGenerator.GuidToTokens(csElement.Value) .Select(ArgumentSelector) .ToArray(); return AddDocumentationTrivia( FieldDeclaration( VariableDeclaration( GlobalNamespace.GetTypeNameSyntax(BuiltinType.Guid), SingletonSeparatedList( VariableDeclarator(Identifier(csElement.Name)) .WithInitializer( EqualsValueClause( ImplicitObjectCreationExpression() .AddArgumentListArguments(guidArguments) )) ) ) ) .WithModifiers(csElement.VisibilityTokenList), csElement ); } } <|start_filename|>SharpGen/Generator/IMemberCodeGenerator.cs<|end_filename|> using SharpGen.Model; namespace SharpGen.Generator; public interface IMemberCodeGenerator<in T> where T : CsBase { } <|start_filename|>SharpGen/Generator/ShadowCallbackGenerator.cs<|end_filename|> using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using SharpGen.Generator.Marshallers; using SharpGen.Model; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; namespace SharpGen.Generator; internal sealed class ShadowCallbackGenerator : MemberPlatformMultiCodeGeneratorBase<CsCallable> { private static readonly NameSyntax UnmanagedFunctionPointerAttributeName = ParseName("System.Runtime.InteropServices.UnmanagedFunctionPointerAttribute"); private static readonly NameSyntax UnmanagedCallersOnlyAttributeName = ParseName("System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute"); private static readonly NameSyntax CompilerServicesNamespace = ParseName("System.Runtime.CompilerServices"); public override IEnumerable<PlatformDetectionType> GetPlatforms(CsCallable csElement) => csElement.InteropSignatures.Keys; public override IEnumerable<MemberDeclarationSyntax> GenerateCode(CsCallable csElement, PlatformDetectionType platform) { var sig = csElement.InteropSignatures[platform]; var delegateDecl = GenerateDelegateDeclaration(csElement, platform, sig); if (csElement is CsMethod { IsFunctionPointerInVtbl: true }) delegateDecl = delegateDecl.WithLeadingIfDirective(GeneratorHelpers.NotPreprocessorNameSyntax) .WithTrailingElseDirective(); yield return delegateDecl; yield return GenerateShadowCallback(csElement, platform, sig); } private static DelegateDeclarationSyntax GenerateDelegateDeclaration(CsCallable csElement, PlatformDetectionType platform, InteropMethodSignature sig) => DelegateDeclaration(sig.ReturnTypeSyntax, VtblGenerator.GetMethodDelegateName(csElement, platform)) .AddAttributeLists( AttributeList( SingletonSeparatedList( Attribute(UnmanagedFunctionPointerAttributeName) .AddArgumentListArguments( AttributeArgument( ModelUtilities.GetManagedCallingConventionExpression(sig.CallingConvention)))))) .WithParameterList(GetNativeParameterList(csElement, sig)) .WithModifiers(TokenList(Token(SyntaxKind.PrivateKeyword))); private static ParameterListSyntax GetNativeParameterList(CsCallable csElement, InteropMethodSignature sig) => ParameterList( (csElement is CsMethod ? SingletonSeparatedList(Parameter(Identifier("thisObject")).WithType(GeneratorHelpers.IntPtrType)) : default) .AddRange( sig.ParameterTypes .Select(type => Parameter(Identifier(type.Name)).WithType(type.InteropTypeSyntax)) ) ); private static CatchClauseSyntax GenerateCatchClause(SyntaxToken exceptionVariableIdentifier, params StatementSyntax[] statements) { StatementSyntaxList statementList = new() { ExpressionStatement( ConditionalAccessExpression( ParenthesizedExpression( BinaryExpression( SyntaxKind.AsExpression, IdentifierName(@"@this"), IdentifierName("SharpGen.Runtime.IExceptionCallback") ) ), InvocationExpression( MemberBindingExpression(IdentifierName("RaiseException")), ArgumentList( SingletonSeparatedList( Argument(IdentifierName(exceptionVariableIdentifier)) ) ) ) ) ) }; statementList.AddRange(statements); return CatchClause() .WithDeclaration( CatchDeclaration(ParseTypeName("System.Exception"), exceptionVariableIdentifier) ) .WithBlock(statementList.ToBlock()); } private StatementSyntax GenerateShadowCallbackStatement(CsCallable csElement) => GeneratorHelpers.VarDeclaration( Identifier("@this"), InvocationExpression( MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, GlobalNamespace.GetTypeNameSyntax(WellKnownName.CppObjectShadow), GenericName( Identifier("ToCallback"), TypeArgumentList( SingletonSeparatedList<TypeSyntax>(IdentifierName(csElement.Parent.Name)) ) ) ), ArgumentList(SingletonSeparatedList(Argument(IdentifierName("thisObject")))) ) ); private MethodDeclarationSyntax GenerateShadowCallback(CsCallable csElement, PlatformDetectionType platform, InteropMethodSignature sig) { var interopReturnType = sig.ReturnTypeSyntax; var methodDeclaration = MethodDeclaration( interopReturnType, VtblGenerator.GetMethodImplName(csElement, platform) ) .WithModifiers( TokenList( Token(SyntaxKind.PrivateKeyword), Token(SyntaxKind.StaticKeyword), Token(SyntaxKind.UnsafeKeyword) ) ) .WithParameterList(GetNativeParameterList(csElement, sig)) .WithAttributeLists( csElement is CsMethod { IsFunctionPointerInVtbl: true } ? SingletonList( AttributeList( SingletonSeparatedList( Attribute( UnmanagedCallersOnlyAttributeName, AttributeArgumentList( SingletonSeparatedList( AttributeArgument(FnPtrCallConvs(sig.CallingConvention)) .WithNameEquals(NameEquals("CallConvs")) ) ) ) ) ).WithTrailingEndIfDirective() ) : default ); if (csElement is CsMethod { ManagedPartial: true }) { return methodDeclaration .AddModifiers(Token(SyntaxKind.PartialKeyword)) .WithSemicolonToken(Token(SyntaxKind.SemicolonToken)); } var statements = NewStatementList; statements.Add(csElement, platform, Generators.ReverseCallableProlog); statements.AddRange( csElement.ReturnValue, static(marshaller, item) => marshaller.GenerateNativeToManagedExtendedProlog(item) ); statements.AddRange( csElement.Parameters, static(marshaller, item) => marshaller.GenerateNativeToManagedExtendedProlog(item) ); statements.AddRange( csElement.InRefInRefParameters, static(marshaller, item) => marshaller.GenerateNativeToManaged(item, false) ); var managedArguments = csElement.PublicParameters .Select(param => GetMarshaller(param).GenerateManagedArgument(param)) .ToList(); ExpressionSyntax callableName = csElement is CsFunction ? IdentifierName(csElement.Name) : MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, IdentifierName("@this"), IdentifierName(csElement.Name) ); var invocation = InvocationExpression(callableName, ArgumentList(SeparatedList(managedArguments))); var returnValueNeedsMarshalling = GetMarshaller(csElement.ReturnValue).GeneratesMarshalVariable(csElement.ReturnValue); if (!csElement.HasReturnStatement) { statements.Add(ExpressionStatement(invocation)); } else { var publicReturnValue = csElement.ActualReturnValue; statements.Add( ExpressionStatement( AssignmentExpression( SyntaxKind.SimpleAssignmentExpression, IdentifierName(publicReturnValue.Name), invocation ) ) ); if (returnValueNeedsMarshalling && publicReturnValue is CsReturnValue) statements.Add( publicReturnValue, static(marshaller, item) => marshaller.GenerateManagedToNative(item, false) ); } statements.AddRange( csElement.LocalManagedReferenceParameters, static(marshaller, item) => marshaller.GenerateManagedToNative(item, false) ); var isForcedReturnBufferSig = sig.ForcedReturnBufferSig; var nativeReturnLocation = returnValueNeedsMarshalling ? MarshallerBase.GetMarshalStorageLocation(csElement.ReturnValue) : IdentifierName(csElement.ReturnValue.Name); if (csElement.HasReturnTypeValue && !csElement.HasReturnTypeParameter && (returnValueNeedsMarshalling || isForcedReturnBufferSig || !ReverseCallablePrologCodeGenerator.GetPublicType(csElement.ReturnValue).IsEquivalentTo(interopReturnType))) nativeReturnLocation = GeneratorHelpers.CastExpression(interopReturnType, nativeReturnLocation); if (csElement.HasReturnTypeValue) statements.Add( ReturnStatement( isForcedReturnBufferSig ? IdentifierName("returnSlot") : nativeReturnLocation ) ); var exceptionVariableIdentifier = Identifier("__exception__"); StatementSyntax[] catchClauseStatements = null; if (csElement.IsReturnTypeResult) { catchClauseStatements = new StatementSyntax[] { ReturnStatement( MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, InvocationExpression( MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, GlobalNamespace.GetTypeNameSyntax(WellKnownName.Result), IdentifierName("GetResultFromException") ), ArgumentList( SingletonSeparatedList(Argument(IdentifierName(exceptionVariableIdentifier))) ) ), IdentifierName("Code") ) ) }; if (csElement.IsReturnTypeHidden && !csElement.ForceReturnType) { statements.Add(ReturnStatement( MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, GlobalNamespace.GetTypeNameSyntax(WellKnownName.Result), IdentifierName("Ok")), IdentifierName("Code")))); } } else if (csElement.HasReturnType) { catchClauseStatements = new StatementSyntax[] { ReturnStatement( isForcedReturnBufferSig ? IdentifierName("returnSlot") : DefaultLiteral ) }; } var fullBody = NewStatementList; if (csElement is CsMethod) fullBody.Add(GenerateShadowCallbackStatement(csElement)); fullBody.Add( TryStatement() .WithBlock(statements.ToBlock()) .WithCatches( SingletonList( GenerateCatchClause(exceptionVariableIdentifier, catchClauseStatements) ) ) ); return methodDeclaration.WithBody(fullBody.ToBlock()); static ExpressionSyntax FnPtrCallConvs(CallingConvention callingConvention) => ImplicitArrayCreationExpression( InitializerExpression( SyntaxKind.ArrayInitializerExpression, SingletonSeparatedList<ExpressionSyntax>( TypeOfExpression( QualifiedName( CompilerServicesNamespace, IdentifierName("CallConv" + callingConvention.ToCallConvShortName()) ) ) ) ) ); } public ShadowCallbackGenerator(Ioc ioc) : base(ioc) { } } <|start_filename|>SharpGen/Generator/SyntaxListBase.cs<|end_filename|> #nullable enable using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; #if !SHARPGEN_ROSLYN using SharpGen.Generator.Marshallers; using SharpGen.Model; #endif namespace SharpGen.Generator; public abstract class SyntaxListBase<TValue, TSelf> : IReadOnlyList<TValue>, ICollection<TValue>, ICollection where TValue : CSharpSyntaxNode where TSelf : SyntaxListBase<TValue, TSelf> { private readonly List<TValue> listImplementation = new(8); #if !SHARPGEN_ROSLYN protected readonly Ioc? ioc; private MarshallingRegistry Registry => ioc?.Generators.Marshalling ?? throw new Exception($"{nameof(MarshallingRegistry)} is required"); protected GlobalNamespaceProvider GlobalNamespace => ioc?.GlobalNamespace ?? throw new Exception($"{nameof(GlobalNamespaceProvider)} is required"); protected GeneratorConfig Config => ioc?.Generators.Config ?? throw new Exception($"{nameof(GeneratorConfig)} is required"); protected SyntaxListBase(Ioc? ioc = null, IEnumerable<TValue?>? collection = null) { this.ioc = ioc; AddRange(collection); } #endif protected abstract TSelf New { get; } protected TSelf From<T>(IEnumerable<T>? collection) where T : class { TSelf list = New; list.AddRange(collection); return list; } public void Add(TValue? item) { if (item == null) return; listImplementation.Add(item); } public void AddRange(IEnumerable<TValue?>? collection) { if (collection == null) return; listImplementation.AddRange(collection.Where(x => x != null)!); } public void Add<T>(T? item) where T : class => Add(Coerce(item)); protected abstract TValue? Coerce<T>(T? value) where T : class; public void AddRange<T>(IEnumerable<T?>? collection) where T : class { if (collection == null) return; AddRange(collection.Select(Coerce)); } #if !SHARPGEN_ROSLYN protected abstract IEnumerable<TValue?> GetPlatformSpecificValue<TResult>( IEnumerable<PlatformDetectionType> types, Func<PlatformDetectionType, TResult> syntaxBuilder ) where TResult : class; protected abstract IEnumerable<TValue?> GetPlatformSpecificValue<TResult>( IEnumerable<PlatformDetectionType> types, Func<PlatformDetectionType, IEnumerable<TResult>> syntaxBuilder ) where TResult : class; protected bool TryAddGeneric<T, TSyntax, TGenerator>(T source, TGenerator generator) where T : CsBase where TSyntax : SyntaxNode { switch (generator) { case ISingleCodeGenerator<T, TSyntax> codeGenerator: Add(codeGenerator.GenerateCode(source)); return true; case IMultiCodeGenerator<T, TSyntax> codeGenerator: AddRange(codeGenerator.GenerateCode(source)); return true; default: return false; } } protected bool TryAddGeneric<T, TSyntax, TGenerator>(IEnumerable<T> source, TGenerator generator) where T : CsBase where TSyntax : SyntaxNode { switch (generator) { case ISingleCodeGenerator<T, TSyntax> codeGenerator: AddRange(source, x => codeGenerator.GenerateCode(x)); return true; case IMultiCodeGenerator<T, TSyntax> codeGenerator: AddRange(source, x => codeGenerator.GenerateCode(x)); return true; default: return false; } } protected bool TryAddPlatform<T, TSyntax, TGenerator>(T source, TGenerator generator) where T : CsBase where TSyntax : SyntaxNode { switch (generator) { case IPlatformSingleCodeGenerator<T, TSyntax> codeGenerator: AddRange( GetPlatformSpecificValue( codeGenerator.GetPlatforms(source), platform => codeGenerator.GenerateCode(source, platform) ) ); return true; case IPlatformMultiCodeGenerator<T, TSyntax> codeGenerator: AddRange( GetPlatformSpecificValue( codeGenerator.GetPlatforms(source), platform => codeGenerator.GenerateCode(source, platform) ) ); return true; default: return false; } } protected bool TryAddPlatform<T, TSyntax, TGenerator>(IEnumerable<T> source, TGenerator generator) where T : CsBase where TSyntax : SyntaxNode { switch (generator) { case IPlatformSingleCodeGenerator<T, TSyntax> codeGenerator: AddRange( source, x => GetPlatformSpecificValue( codeGenerator.GetPlatforms(x), platform => codeGenerator.GenerateCode(x, platform) ) ); return true; case IPlatformMultiCodeGenerator<T, TSyntax> codeGenerator: AddRange( source, x => GetPlatformSpecificValue( codeGenerator.GetPlatforms(x), platform => codeGenerator.GenerateCode(x, platform) ) ); return true; default: return false; } } protected bool TryAddPlatformFixed<T, TSyntax, TGenerator>(T source, PlatformDetectionType platform, TGenerator generator) where T : CsBase where TSyntax : SyntaxNode { switch (generator) { case IPlatformSingleCodeGenerator<T, TSyntax> codeGenerator: Add(codeGenerator.GenerateCode(source, platform)); return true; case IPlatformMultiCodeGenerator<T, TSyntax> codeGenerator: AddRange(codeGenerator.GenerateCode(source, platform)); return true; default: return false; } } protected bool TryAddPlatformFixed<T, TSyntax, TGenerator>(IEnumerable<T> source, PlatformDetectionType platform, TGenerator generator) where T : CsBase where TSyntax : SyntaxNode { switch (generator) { case IPlatformSingleCodeGenerator<T, TSyntax> codeGenerator: AddRange(source, x => codeGenerator.GenerateCode(x, platform)); return true; case IPlatformMultiCodeGenerator<T, TSyntax> codeGenerator: AddRange(source, x => codeGenerator.GenerateCode(x, platform)); return true; default: return false; } } protected bool TryAdd<T, TSyntax, TGenerator>(T source, TGenerator generator) where T : CsBase where TSyntax : SyntaxNode => TryAddGeneric<T, TSyntax, TGenerator>(source, generator) || TryAddPlatform<T, TSyntax, TGenerator>(source, generator); [SuppressMessage("ReSharper", "PossibleMultipleEnumeration")] protected bool TryAdd<T, TSyntax, TGenerator>(IEnumerable<T> source, TGenerator generator) where T : CsBase where TSyntax : SyntaxNode => TryAddGeneric<T, TSyntax, TGenerator>(source, generator) || TryAddPlatform<T, TSyntax, TGenerator>(source, generator); public void AddRange<T, TResult>(T source, Func<IMarshaller, T, IEnumerable<TResult>> transform) where T : CsMarshalBase where TResult : class => AddRange(transform(Registry.GetMarshaller(source), source)); public void AddRange<T, TResult>(IEnumerable<T> source, Func<IMarshaller, T, IEnumerable<TResult>> transform) where T : CsMarshalBase where TResult : class => AddRange(source.SelectMany(x => transform(Registry.GetMarshaller(x), x))); public void Add<T, TResult>(T source, Func<IMarshaller, T, TResult> transform) where T : CsMarshalBase where TResult : class => Add(transform(Registry.GetMarshaller(source), source)); public void AddRange<T, TResult>(IEnumerable<T> source, Func<IMarshaller, T, TResult> transform) where T : CsMarshalBase where TResult : class => AddRange(source.Select(x => transform(Registry.GetMarshaller(x), x))); #endif public void Add<T, TResult>(T source, Func<T, TResult> transform) where TResult : class => Add(transform(source)); public void AddRange<T, TResult>(IEnumerable<T> source, Func<T, TResult> transform) where TResult : class => AddRange(source.Select(transform)); public void AddRange<T, TResult>(IEnumerable<T> source, Func<T, IEnumerable<TResult>> transform) where TResult : class => AddRange(source.SelectMany(transform)); public IEnumerator<TValue> GetEnumerator() => listImplementation.GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => listImplementation.GetEnumerator(); public void Clear() => listImplementation.Clear(); public bool Contains(TValue item) => listImplementation.Contains(item); public void CopyTo(TValue[] array, int arrayIndex) => listImplementation.CopyTo(array, arrayIndex); public void CopyTo(Array array, int index) => ((ICollection) listImplementation).CopyTo(array, index); public bool Remove(TValue item) => listImplementation.Remove(item); public int Count => listImplementation.Count; public bool IsSynchronized => false; public object SyncRoot => listImplementation; public bool IsReadOnly => false; public int IndexOf(TValue item) => listImplementation.IndexOf(item); public void RemoveAt(int index) => listImplementation.RemoveAt(index); public TValue this[int index] { get => listImplementation[index]; set => listImplementation[index] = value; } } <|start_filename|>SharpGen.Runtime/COM/ComObjectVtbl.cs<|end_filename|> // Copyright (c) 2010-2014 SharpDX - <NAME> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace SharpGen.Runtime; public static unsafe class ComObjectVtbl { #if NET5_0_OR_GREATER public static readonly IntPtr[] Vtbl = { (IntPtr) (delegate* unmanaged[Stdcall]<IntPtr, Guid*, void*, int>) (&QueryInterfaceImpl), (IntPtr) (delegate* unmanaged[Stdcall]<IntPtr, uint>) (&AddRefImpl), (IntPtr) (delegate* unmanaged[Stdcall]<IntPtr, uint>) (&ReleaseImpl) }; #else private static readonly QueryInterfaceDelegate QueryInterfaceDelegateCache = QueryInterfaceImpl; private static readonly AddRefDelegate AddRefDelegateCache = AddRefImpl; private static readonly ReleaseDelegate ReleaseDelegateCache = ReleaseImpl; public static readonly IntPtr[] Vtbl = { Marshal.GetFunctionPointerForDelegate(QueryInterfaceDelegateCache), Marshal.GetFunctionPointerForDelegate(AddRefDelegateCache), Marshal.GetFunctionPointerForDelegate(ReleaseDelegateCache) }; #endif #if !NET5_0_OR_GREATER [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int QueryInterfaceDelegate(IntPtr thisObject, Guid* guid, void* output); #else [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })] #endif private static int QueryInterfaceImpl(IntPtr thisObject, Guid* guid, void* output) { var callback = CppObjectShadow.ToCallback<CallbackBase>(thisObject); #if DEBUG try { #endif ref var ppvObject = ref Unsafe.AsRef<IntPtr>(output); var result = callback.Find(*guid); ppvObject = result; if (result == IntPtr.Zero) return Result.NoInterface.Code; MarshallingHelpers.AddRef(callback); return Result.Ok.Code; #if DEBUG } catch (Exception exception) { (callback as IExceptionCallback)?.RaiseException(exception); return Result.GetResultFromException(exception).Code; } #endif } #if !NET5_0_OR_GREATER [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate uint AddRefDelegate(IntPtr thisObject); #else [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })] #endif private static uint AddRefImpl(IntPtr thisObject) => MarshallingHelpers.AddRef(CppObjectShadow.ToCallback<IUnknown>(thisObject)); #if !NET5_0_OR_GREATER [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate uint ReleaseDelegate(IntPtr thisObject); #else [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })] #endif private static uint ReleaseImpl(IntPtr thisObject) => MarshallingHelpers.Release(CppObjectShadow.ToCallback<IUnknown>(thisObject)); } <|start_filename|>SharpGenTools.Sdk/Documentation/FindDocumentationResultFailure.cs<|end_filename|> using System; using SharpGen.Doc; namespace SharpGenTools.Sdk.Documentation; internal sealed class FindDocumentationResultFailure : IFindDocumentationResult { public FindDocumentationResultFailure(TimeSpan retryDelay) => RetryDelay = retryDelay; public bool Success => false; public TimeSpan RetryDelay { get; } } <|start_filename|>SharpGenTools.Sdk/Internal/CacheFile.cs<|end_filename|> #nullable enable using System; using System.Diagnostics; using System.IO; using System.Security.Cryptography; namespace SharpGenTools.Sdk.Internal; public ref struct CacheFile { public enum CacheState { Hit, Miss, Absent } private bool? _isWriteNeeded = null; private CacheState _state = CacheState.Absent; private bool _hasWritten = false; private StreamWriter? _writer = null; private FileInfo? _file = null; public CacheFile() { Stream = new MemoryStream(); } public CacheFile(FileInfo file) : this() { File = file; } public FileInfo File { get => _file ?? throw new InvalidOperationException(); set { _file = value ?? throw new ArgumentNullException(nameof(value)); Utilities.RequireAbsolutePath(value.FullName, nameof(value)); } } private MemoryStream Stream { get; } public bool IsWriteNeeded { get { return _isWriteNeeded ??= ComputeIsWriteNeeded(); } } public CacheState State { get { _isWriteNeeded ??= ComputeIsWriteNeeded(); return _state; } } private bool ComputeIsWriteNeeded() { Debug.Assert(_isWriteNeeded is null); Debug.Assert(_writer is not null); Debug.Assert(!_hasWritten); _writer.Dispose(); File.Refresh(); if (!File.Exists) { _state = CacheState.Absent; return true; } ReadOnlySpan<byte> cachedHash = System.IO.File.ReadAllBytes(File.FullName); Stream.Position = 0; var success = Stream.TryGetBuffer(out var buffer); Debug.Assert(success); if (buffer.AsSpan().SequenceEqual(cachedHash)) { _state = CacheState.Hit; return false; } _state = CacheState.Miss; return true; } public StreamWriter StreamWriter => _writer is null ? _writer = new StreamWriter(Stream, SharpGenTask.DefaultEncoding, 1024, true) : throw new InvalidOperationException(); public void Write() { Debug.Assert(_isWriteNeeded == true); Debug.Assert(!_hasWritten); Stream.Position = 0; if (File.DirectoryName is { } directory) Directory.CreateDirectory(directory); using var file = File.Open(FileMode.Create, FileAccess.Write); Stream.CopyTo(file); _hasWritten = true; } public byte[] ComputeHash(HashAlgorithm hash) { Debug.Assert(_writer is not null); _writer.Dispose(); Stream.Position = 0; return hash.ComputeHash(Stream); } public void Dispose() { if (_writer is { } writer) writer.Dispose(); Stream.Dispose(); } } <|start_filename|>SharpGen/Generator/IPlatformCodeGenerator.cs<|end_filename|> using System.Collections.Generic; using SharpGen.Model; namespace SharpGen.Generator; public interface IPlatformCodeGenerator<in TCsElement> where TCsElement : CsBase { IEnumerable<PlatformDetectionType> GetPlatforms(TCsElement csElement); } <|start_filename|>SharpGen.UnitTests/Runtime/CppObjectTests.cs<|end_filename|> using System; using SharpGen.Runtime; using Xunit; namespace SharpGen.UnitTests.Runtime; public class CppObjectTests { [Fact] public void GetCallbackPtrReturnsPointerToShadow() { using var callback = new CallbackImpl(); Assert.NotEqual(IntPtr.Zero, MarshallingHelpers.ToCallbackPtr<ICallback>(callback)); } [Fact] public void GetCallbackPtrForClassWithMultipleInheritenceShouldReturnPointer() { using var callback = new Callback2Impl(); Assert.NotEqual(IntPtr.Zero, MarshallingHelpers.ToCallbackPtr<ICallback>(callback)); Assert.NotEqual(IntPtr.Zero, MarshallingHelpers.ToCallbackPtr<ICallback2>(callback)); } } <|start_filename|>SharpGen.Runtime/CallbackBase.cs<|end_filename|> // Copyright (c) 2010-2014 SharpDX - <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. #nullable enable using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Threading; namespace SharpGen.Runtime; /// <summary> /// Base class for all callback objects written in managed code. /// It is the container used to keep track of all native (e.g. COM) callbacks for a single managed object. /// All managed callbacks must inherit from this class. /// </summary> public abstract unsafe partial class CallbackBase : DisposeBase, ICallbackable { private Dictionary<Guid, IntPtr>? _ccw; private IntPtr _guidPtr; private IntPtr[]? _guids; #if NET5_0_OR_GREATER private uint _refCount = 1; #else private int _refCount = 1; #endif private bool _isDisposed; private GCHandle _thisHandle; protected sealed override bool IsDisposed => _isDisposed; /// <inheritdoc /> protected sealed override void Dispose(bool disposing) { DisposeCore(disposing); if (disposing) { Release(); } else { // Dispose native resources DisposeCallableWrappers(false); } // Good idea would be to get rid of the _isDisposed field and use refCount <= 0 condition instead. // That's a dangerous change not to be made lightly. _isDisposed = true; } /// <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 DisposeCore(bool disposing) { } public uint AddRef() { #if NET5_0_OR_GREATER return Interlocked.Increment(ref _refCount); #else return (uint)Interlocked.Increment(ref _refCount); #endif } public uint Release() { #if NET5_0_OR_GREATER var newRefCount = Interlocked.Decrement(ref _refCount); #else var newRefCount = Interlocked.Decrement(ref _refCount); #endif if (newRefCount == 0) { // Dispose native resources DisposeCallableWrappers(true); } return (uint) newRefCount; } public override string ToString() => $"{GetType().Name}[{RuntimeHelpers.GetHashCode(this):X}:{Volatile.Read(ref _refCount)}]"; public ReadOnlySpan<IntPtr> Guids { get { if (_guids is { } guids) return guids; var guidList = BuildGuidList(); var guidCount = guidList.Length; var guidPtr = Marshal.AllocHGlobal(sizeof(Guid) * guidCount); var pGuid = (Guid*) guidPtr; guids = new IntPtr[guidCount]; for (var i = 0; i < guidCount; i++) { pGuid[i] = guidList[i]; guids[i] = new IntPtr(pGuid + i); } // This property is not thread-safe, but can easily be fixed if need arises. _guidPtr = guidPtr; _guids = guids; return guids; } } public IntPtr Find(Guid guidType) { if (_ccw is not { } guidToShadow) { guidToShadow = _ccw = new(4); Debug.Assert(!_thisHandle.IsAllocated); InitializeCallableWrappers(_ccw); } return guidToShadow.TryGetValue(guidType, out var shadow) ? shadow : IntPtr.Zero; } public IntPtr Find<TCallback>() where TCallback : ICallbackable => Find(TypeDataStorage.GetGuid<TCallback>()); protected GCHandle ThisHandle => _thisHandle switch { { IsAllocated: true } handle => handle, _ => _thisHandle = GCHandle.Alloc(this, GCHandleType.WeakTrackResurrection) }; protected static IntPtr CreateCallableWrapper(void* vtbl, GCHandle callback) { Debug.Assert(vtbl != (void*) 0); Debug.Assert(callback.IsAllocated); return CppObjectCallableWrapper.Create(vtbl, callback); } protected static GCHandle CreateMultiInheritanceShadow(params GCHandle[] shadows) { if (shadows == null) throw new ArgumentNullException(nameof(shadows)); return shadows.Length switch { 0 => throw new ArgumentException( "Multi-inheritance shadow cannot be constructed for empty shadow collection.", nameof(shadows) ), 1 => throw new ArgumentException( "Multi-inheritance shadow cannot be constructed for a single shadow.", nameof(shadows) ), _ => GCHandle.Alloc(new CppObjectMultiShadow(shadows), GCHandleType.Normal) }; } private void DisposeCallableWrappers(bool disposing) { if (Interlocked.Exchange(ref _ccw, null) is { Values: { } shadows }) { #if NETCOREAPP2_0_OR_GREATER || NETSTANDARD2_1 || NET472 HashSet<IntPtr> freed = new(shadows.Count); #else HashSet<IntPtr> freed = new(); #endif foreach (var comObjectCallbackNative in shadows) if (freed.Add(comObjectCallbackNative)) CppObjectCallableWrapper.Free(comObjectCallbackNative, disposing); } if (Interlocked.Exchange(ref _guidPtr, default) is var pointer) Marshal.FreeHGlobal(pointer); if (_thisHandle.IsAllocated) _thisHandle.Free(); } internal IReadOnlyCollection<CppObjectShadow> Shadows { get { Debug.Assert(_ccw is not null); HashSet<CppObjectShadow> shadows = new(ReferenceEqualityComparer.Instance); foreach (CppObjectCallableWrapper* ccw in _ccw.Values) { var handle = ccw->Shadow; if (!handle.IsAllocated) continue; switch (handle.Target) { case CppObjectShadow shadow: shadows.Add(shadow); break; case CppObjectMultiShadow multiShadow: multiShadow.AddShadowsToSet(shadows); break; } } #if NET45 return shadows.ToArray(); #else return shadows; #endif } } } <|start_filename|>SharpGen.UnitTests/RoslynGeneratorTests.cs<|end_filename|> using System; using System.Collections.Generic; using System.Xml; using Microsoft.CodeAnalysis.CSharp; using SharpGen.Generator; using SharpGen.Model; using SharpGen.Transform; using Xunit; using Xunit.Abstractions; namespace SharpGen.UnitTests; public class RoslynGeneratorTests : TestBase { public RoslynGeneratorTests(ITestOutputHelper outputHelper) : base(outputHelper) { } [Fact] public void IncludeXmlDocIsNotMangled() { CsAssembly assembly = new(); CsNamespace @namespace = new("Test"); @namespace.Add( new CsStruct(null, "PAIR") { CppElementName = "PAIR" } ); assembly.Add(@namespace); XmlDocument docs = new(); docs.LoadXml(@"<comments><comment id=""PAIR"">Test</comment></comments>"); AddIocServices(CreateExternalDocCommentsReader(docs)); Assert.Collection( GenerateLines(assembly), x => Assert.Equal(@"// <auto-generated/>", x), x => Assert.Equal(@"namespace Test", x), x => Assert.Equal(@"{", x), x => Assert.Equal(@"/// <include file=""doc.xml"" path=""/comments/comment[@id='PAIR']/*"" />", x), x => Assert.Equal(@"/// <unmanaged>PAIR</unmanaged>", x), x => Assert.Equal(@"/// <unmanaged-short>PAIR</unmanaged-short>", x), x => Assert.Equal(@"[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential, Pack = 0, CharSet = System.Runtime.InteropServices.CharSet.Unicode)]", x), x => Assert.Equal(@"public partial struct PAIR", x), x => Assert.Equal(@"{", x), x => Assert.Equal(@"}", x), x => Assert.Equal(@"}", x) ); } private static Action<IocServiceContainer> CreateExternalDocCommentsReader(XmlDocument docs) { return container => container.AddService(new ExternalDocCommentsReader(new Dictionary<string, XmlDocument> { ["doc.xml"] = docs })); } private Action<IocServiceContainer> CreateDefaultGenerators() { return container => container.AddService<IGeneratorRegistry>(new DefaultGenerators(Ioc)); } private string[] GenerateLines(CsAssembly assembly) { AddIocServices(CreateDefaultGenerators()); var root = new RoslynGenerator().Run(assembly, Ioc).GetCompilationUnitRoot(); return root.ToFullString() .Split('\n', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); } } <|start_filename|>SharpGen/Generator/MarshallingRegistry.cs<|end_filename|> using System; using System.Collections.Generic; using System.Linq; using SharpGen.Generator.Marshallers; using SharpGen.Logging; using SharpGen.Model; namespace SharpGen.Generator; public sealed class MarshallingRegistry { private readonly Ioc ioc; public MarshallingRegistry(Ioc ioc) { this.ioc = ioc ?? throw new ArgumentNullException(nameof(ioc)); ValueTypeMarshaller valueTypeMarshaller = new(ioc); Marshallers = new List<IMarshaller> { new InterfaceArrayMarshaller(ioc), new ArrayOfInterfaceMarshaller(ioc), new BoolToIntArrayMarshaller(ioc), new BoolToIntMarshaller(ioc), new InterfaceMarshaller(ioc), new PointerSizeMarshaller(ioc), new StringMarshaller(ioc), new RemappedTypeMarshaller(ioc), new StructWithNativeTypeMarshaller(ioc), new StructWithNativeTypeArrayMarshaller(ioc), new NullableInstanceMarshaller(ioc), new BitfieldMarshaller(ioc), new ValueTypeArrayMarshaller(ioc), new FallbackFieldMarshaller(ioc), valueTypeMarshaller }; RefWrappingMarshallers = Marshallers.Select(x => new RefWrapperMarshaller(ioc, x)).ToArray(); EnumWrappingMarshaller = new EnumParameterWrapperMarshaller(ioc, valueTypeMarshaller); RelationMarshallers = new Dictionary<Type, IRelationMarshaller> { [typeof(StructSizeRelation)] = new StructSizeRelationMarshaller(ioc), [typeof(LengthRelation)] = new LengthRelationMarshaller(ioc), [typeof(ConstantValueRelation)] = new ConstantValueRelationMarshaller(ioc) }; } private IReadOnlyList<IMarshaller> Marshallers { get; } private IReadOnlyList<WrapperMarshallerBase> RefWrappingMarshallers { get; } private WrapperMarshallerBase EnumWrappingMarshaller { get; } private IReadOnlyDictionary<Type, IRelationMarshaller> RelationMarshallers { get; } public IMarshaller GetMarshaller(CsMarshalBase csElement) { var marshaller = GetMarshallers(csElement).FirstOrDefault(m => m.CanMarshal(csElement)); if (marshaller != null) return marshaller; if (csElement.PublicType is CsUndefinedType || csElement.MarshalType is CsUndefinedType) { var logger = ioc.Logger; logger.Error( LoggingCodes.CannotMarshalUnknownType, $"The element '{csElement}' has an unknown type and cannot be marshalled accurately. Maybe you used a <bind> directive and didn't use a <define> to define the type for SharpGen?" ); logger.Exit("Unable to generate code with unknown marshal type."); return null; } throw new InvalidOperationException($"No marshaller found for {csElement}"); } private IEnumerable<IMarshaller> GetMarshallers(CsMarshalBase csElement) { if (RefWrapperMarshaller.IsApplicable(csElement)) return RefWrappingMarshallers; if (EnumParameterWrapperMarshaller.IsApplicable(csElement)) return Marshallers.Prepend(EnumWrappingMarshaller); return Marshallers; } public IRelationMarshaller GetRelationMarshaller(MarshallableRelation relation) { return RelationMarshallers[relation.GetType()]; } } <|start_filename|>SharpGen/Generator/IStatementCodeGenerator.cs<|end_filename|> using SharpGen.Model; namespace SharpGen.Generator; public interface IStatementCodeGenerator<in T> where T : CsBase { } <|start_filename|>SharpGen/IocServiceContainer.cs<|end_filename|> using System; using System.ComponentModel.Design; namespace SharpGen; public sealed class IocServiceContainer : ServiceContainer { public IocServiceContainer() { } public IocServiceContainer(IServiceProvider parentProvider) : base(parentProvider) { } public void AddService<T>(T serviceInstance) where T : class { if (serviceInstance == null) throw new ArgumentNullException(nameof(serviceInstance)); AddService(typeof(T), serviceInstance); } public void AddService<T>() where T : class, new() { AddService(typeof(T), new T()); } public void AddService<TI, TImpl>() where TI : class where TImpl : class, new() { AddService(typeof(TI), new TImpl()); } } <|start_filename|>SdkTests/Struct/RelationTests.cs<|end_filename|> using System; using Xunit; namespace Struct; public class RelationTests { [Fact] public unsafe void StructSize() { var str = default(StructSizeRelation); var native = default(StructSizeRelation.__Native); str.__MarshalTo(ref native); Assert.Equal(sizeof(StructSizeRelation.__Native), native.Size); } [Fact] public void Constant() { var str = default(ReservedRelation); var native = default(ReservedRelation.__Native); str.__MarshalTo(ref native); Assert.Equal(42, native.Reserved); } } <|start_filename|>SdkTests/Functions/ParameterMarshallingTests.cs<|end_filename|> using System; using System.Runtime.InteropServices; using SharpGen.Runtime; using Xunit; namespace Functions; public class ParameterMarshallingTests { [Fact] public void InterfaceOutArrays() { int num = 3; Interface[] results = new Interface[num]; NativeFunctions.GetInterfaces(num, results); foreach (var result in results) { result.Method(); } } [Fact] public void InterfaceOutArraysOptional() { int num = 3; NativeFunctions.GetInterfacesOptional(num, null); } [Fact] public void OutIntArray() { int num = 3; int[] results = new int[num]; NativeFunctions.GetIntArray(num, results); for (int i = 0; i < num; i++) { Assert.Equal(i, results[i]); } } [Fact] public void StringMarshalling() { Assert.Equal('W', NativeFunctions.GetFirstCharacter("Wide-char test")); Assert.Equal((byte)'A', NativeFunctions.GetFirstAnsiCharacter("Ansi-char test")); } [Fact] public void StructMarshalling() { var defaultMarshalling = new StructWithMarshal(); defaultMarshalling.I[1] = 6; var staticMarshalling = new StructWithStaticMarshal(); staticMarshalling.I[1] = 10; NativeFunctions.StructMarshalling(defaultMarshalling, staticMarshalling, out var defaultOut, out var staticOut); Assert.Equal(defaultMarshalling.I[1], defaultOut.I[1]); Assert.Equal(staticMarshalling.I[1], staticOut.I[1]); } [Fact] public void StructArray() { var defaultMarshalling = new[] { new StructWithMarshal() }; var staticMarshalling = new[] { new StructWithStaticMarshal() }; defaultMarshalling[0].I[1] = 10; staticMarshalling[0].I[1] = 30; var defaultMarshallingOut = new[] { new StructWithMarshal() }; var staticMarshallingOut = new[] { new StructWithStaticMarshal() }; NativeFunctions.StructArrayMarshalling( defaultMarshalling, staticMarshalling , defaultMarshallingOut, staticMarshallingOut ); Assert.Equal(defaultMarshalling[0].I[1], defaultMarshallingOut[0].I[1]); Assert.Equal(staticMarshalling[0].I[1], staticMarshallingOut[0].I[1]); } [Fact] public void FastOut() { var iface = new Interface(IntPtr.Zero); NativeFunctions.FastOutTest(iface); Assert.NotEqual(IntPtr.Zero, iface.NativePointer); } [Fact] public void Enum() { Assert.Equal(1, (int)NativeFunctions.PassThroughEnum(MyEnum.TestValue)); } [Fact] public void EnumOut() { var value = NativeFunctions.EnumOut(); Assert.Equal(MyEnum.TestValue, value); } [Fact] public void RefParameterTest() { int i = 1; NativeFunctions.Increment(ref i); Assert.Equal(2, i); } [Fact] public void NullableParameterTest() { Assert.Equal(2, NativeFunctions.Add(2, null)); Assert.Equal(2, NativeFunctions.Add(1, 1)); } [Fact] public void BoolToIntTest() { Assert.True(NativeFunctions.BoolToIntTest(true)); Assert.False(NativeFunctions.BoolToIntTest(false)); } [Fact] public void BoolArrayTest() { var inArray = new bool[2]; inArray[1] = true; var outArray = new bool[2]; NativeFunctions.BoolArrayTest(inArray, outArray, 2); Assert.False(outArray[0]); Assert.True(outArray[1]); } [Fact] public void StringReturnTest() { Assert.Equal("Functions", NativeFunctions.GetName()); } [Fact] public void StructRefParameter() { var csStruct = new StructWithMarshal(); NativeFunctions.SetAllElements(ref csStruct); Assert.Equal(10, csStruct.I[0]); Assert.Equal(10, csStruct.I[1]); Assert.Equal(10, csStruct.I[2]); } [Fact] public void NullableStructParameter() { Assert.Equal(0, NativeFunctions.FirstElementOrZero(null)); var csStruct = new StructWithMarshal(); csStruct.I[0] = 4; Assert.Equal(csStruct.I[0], NativeFunctions.FirstElementOrZero(csStruct)); } [Fact] public void OptionalArrayOfStruct() { var elements = new [] { new SimpleStruct{ I = 1 } }; Assert.Equal(1, NativeFunctions.Sum(1, elements)); Assert.Equal(0, NativeFunctions.Sum(0, null)); } [Fact] public void ParamsArray() { Assert.Equal(10, NativeFunctions.Product(1, new SimpleStruct{ I = 10 })); } [Fact] public void ForcePassByValueParameter() { var value = new LargeStruct(); value.I[0] = 10; value.I[1] = 20; value.I[2] = 30; Assert.Equal(60, NativeFunctions.SumValues(value)); } [Fact] public void PointerSize() { var value = new PointerSize(20); Assert.Equal(new PointerSize(20), NativeFunctions.PassThroughPointerSize(value)); } [Fact] public void OptionalStructArrayOut() { NativeFunctions.StructArrayOut(new StructWithMarshal(), null); } [Fact] public void ArrayOfStructAsClass() { var test = new [] { new StructAsClass {I = 1}, new StructAsClass {I = 2}}; Assert.Equal(3, NativeFunctions.SumInner(test, 2)); } [Fact] public void WrappedStructAsClass() { Assert.Equal(1, NativeFunctions.GetWrapper().Wrapped.I); } [Fact] public unsafe void OptionalInOutStructPointer() { var test = new SimpleStruct { I = 5 }; void* addr = &test; NativeFunctions.AddOne((IntPtr)addr); Assert.Equal(6, test.I); } [Fact] public void EnumArrayTest() { var test = new [] { MyEnum.TestValue, MyEnum.TestValue }; Assert.Equal(MyEnum.TestValue, NativeFunctions.FirstEnumElement(test)); } [Fact] public unsafe void PreserveVoidPointer1() { var ptr = Marshal.AllocHGlobal(4); Marshal.WriteInt32(ptr, 42); Assert.True(NativeFunctions.PreserveVoidPointer1None(ptr)); Assert.True(NativeFunctions.PreserveVoidPointer1False(ptr)); Assert.True(NativeFunctions.PreserveVoidPointer1True((void*) ptr)); Marshal.FreeHGlobal(ptr); } [Fact] public unsafe void PreserveVoidPointer2() { Assert.True(NativeFunctions.PreserveVoidPointer2None((IntPtr) 42)); Assert.True(NativeFunctions.PreserveVoidPointer2False((IntPtr) 42)); Assert.True(NativeFunctions.PreserveVoidPointer2True((void*) 42)); } } <|start_filename|>SharpGenTools.Sdk/Internal/Roslyn/Debug.cs<|end_filename|> // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable enable using System.Diagnostics; using System.Diagnostics.CodeAnalysis; namespace SharpGenTools.Sdk.Internal.Roslyn; internal static class RoslynDebug { /// <inheritdoc cref="Debug.Assert(bool)"/> [Conditional("DEBUG")] public static void Assert([DoesNotReturnIf(false)] bool b) => Debug.Assert(b); /// <inheritdoc cref="Debug.Assert(bool, string)"/> [Conditional("DEBUG")] public static void Assert([DoesNotReturnIf(false)] bool b, string message) => Debug.Assert(b, message); [Conditional("DEBUG")] public static void AssertNotNull<T>([NotNull] T value) { Assert(value is object, "Unexpected null reference"); } } <|start_filename|>SharpGen/Model/CsParameter.cs<|end_filename|> // Copyright (c) 2010-2014 SharpDX - <NAME> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using SharpGen.Config; using SharpGen.CppModel; namespace SharpGen.Model; public sealed class CsParameter : CsMarshalCallableBase { private bool isOptional, usedAsReturn; private const int SizeOfLimit = 16; public CsParameterAttribute Attribute { get; set; } = CsParameterAttribute.In; public string DefaultValue { get; } private bool ForcePassByValue { get; } public bool HasParams { get; } public bool IsFast { get; } public override bool IsArray { get => base.IsArray && !IsString; set => base.IsArray = value; } public override bool HasPointer => base.HasPointer || ArraySpecification.HasValue; public override bool IsFixed { get { if (IsRef || IsRefIn) return !(PassedByNullableInstance || RefInPassedByValue); if (IsOut && !IsBoolToInt) return true; if (IsArray && !IsInterfaceArray) return true; return false; } } public bool IsIn => Attribute == CsParameterAttribute.In; public bool IsInInterfaceArrayLike => IsArray && PublicType is CsInterface {IsCallback: false} && !IsOut; public bool IsOptional { // Arrays of reference types (interfaces) support null values get => isOptional || PublicType is CsInterface && !IsOut && IsArray; private set => isOptional = value; } /// <summary> /// Parameter is an Out parameter and passed by pointer. /// </summary> public override bool IsOut => Attribute == CsParameterAttribute.Out; /// <summary> /// Parameter is an In/Out parameter and passed by pointer. /// </summary> public bool IsRef => Attribute == CsParameterAttribute.Ref; /// <summary> /// Parameter is an In parameter and passed by pointer. /// </summary> public bool IsRefIn => Attribute == CsParameterAttribute.RefIn; private bool RefInPassedByValue => IsRefIn && IsValueType && !IsArray && (PublicType.Size <= SizeOfLimit && !HasNativeValueType || ForcePassByValue); public bool PassedByManagedReference => (IsRef || IsRefIn) && !(PassedByNullableInstance || RefInPassedByValue) && !IsStructClass; public bool PassedByNullableInstance => IsRefIn && IsValueType && !IsArray && IsOptional; public bool IsNullableStruct => PassedByNullableInstance && !IsStructClass; public bool IsNullable => IsOptional && (IsArray || IsInterface || IsNullableStruct || IsStructClass); public override bool PassedByNativeReference => !IsIn; public override bool IsLocalManagedReference => Attribute is CsParameterAttribute.Ref or CsParameterAttribute.Out; public override bool UsedAsReturn => usedAsReturn; internal void MarkUsedAsReturn() => usedAsReturn = true; public CsParameter Clone() { var parameter = (CsParameter) MemberwiseClone(); parameter.ResetParentAfterClone(); return parameter; } public CsParameter(Ioc ioc, CppParameter cppParameter, string name) : base(ioc, cppParameter, name) { if (cppParameter == null) return; var paramAttribute = cppParameter.Attribute; var paramRule = cppParameter.Rule; usedAsReturn = paramRule.ParameterUsedAsReturnType ?? UsedAsReturn; DefaultValue = paramRule.DefaultValue; if (HasFlag(paramAttribute, ParamAttribute.Buffer)) IsArray = true; if (HasFlag(paramAttribute, ParamAttribute.Fast)) IsFast = true; if (HasFlag(paramAttribute, ParamAttribute.Value)) ForcePassByValue = true; if (HasFlag(paramAttribute, ParamAttribute.Params)) HasParams = true; if (HasFlag(paramAttribute, ParamAttribute.Optional)) IsOptional = true; static bool HasFlag(ParamAttribute value, ParamAttribute flag) => (value & flag) == flag; } } <|start_filename|>SharpGen/VisualStudioSetup/ISetupPackageReference.cs<|end_filename|>  using System.Runtime.InteropServices; #pragma warning disable 0618 namespace SharpGen.VisualStudioSetup; [Guid("DA8D8A16-B2B6-4487-A2F1-594CCCCD6BF5")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [ComImport] public interface ISetupPackageReference { [return: MarshalAs(UnmanagedType.BStr)] string GetId(); [return: MarshalAs(UnmanagedType.BStr)] string GetVersion(); [return: MarshalAs(UnmanagedType.BStr)] string GetChip(); [return: MarshalAs(UnmanagedType.BStr)] string GetLanguage(); [return: MarshalAs(UnmanagedType.BStr)] string GetBranch(); [return: MarshalAs(UnmanagedType.BStr)] string GetType(); [return: MarshalAs(UnmanagedType.BStr)] string GetUniqueId(); [return: MarshalAs(UnmanagedType.VariantBool)] bool GetIsExtension(); } <|start_filename|>SharpGen.Runtime/CppObjectShadow.cs<|end_filename|> // Copyright (c) 2010-2014 SharpDX - <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. #nullable enable using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Runtime.InteropServices; namespace SharpGen.Runtime; /// <summary> /// A callback interface shadow, used to supplement interface implementers with additional logic, /// possibly to modify marshalling behavior. /// Using shadows incurs minor negative memory and performance impact, so use sparingly. /// In terms of .NET runtime, it's a COM Callable Wrapper (CCW). /// </summary> public abstract unsafe class CppObjectShadow { private GCHandle callbackHandle; static CppObjectShadow() { Debug.Assert(Marshal.SizeOf(typeof(CppObjectCallableWrapper)) == CppObjectCallableWrapper.Size); Debug.Assert(sizeof(CppObjectCallableWrapper) == CppObjectCallableWrapper.Size); } protected CppObjectShadow() { Debug.Assert(this is not ICallbackable); } internal void Initialize(GCHandle callbackHandle) { Debug.Assert(!this.callbackHandle.IsAllocated); Debug.Assert(callbackHandle.IsAllocated); Debug.Assert(callbackHandle.Target is CallbackBase); Debug.Assert(callbackHandle.Target is ICallbackable); this.callbackHandle = callbackHandle; } public static T ToAnyShadow<T>(IntPtr thisPtr) where T : CppObjectShadow { Debug.Assert(thisPtr != IntPtr.Zero); var handle = ((CppObjectCallableWrapper*) thisPtr)->Shadow; Debug.Assert(handle.IsAllocated); return handle.Target switch { T shadow => shadow, CppObjectMultiShadow multiShadow => multiShadow.ToShadow<T>() ?? throw new Exception($"Shadow {typeof(T).FullName} not found in the inheritance graph"), CallbackBase callback => callback.Shadows.OfType<T>().FirstOrDefault() ?? throw new Exception($"Shadow {typeof(T).FullName} not found in the inheritance graph"), null => throw new Exception($"Shadow {typeof(T).FullName} is dead"), ICallbackable value => throw new Exception( $"Shadow is of an unexpected {nameof(ICallbackable)} type {value.GetType().FullName}, expected {typeof(T).FullName}" ), { } value => throw new Exception( $"Shadow is of an unexpected type {value.GetType().FullName}, expected {typeof(T).FullName}" ) }; } public static IEnumerable<T> ToAllShadows<T>(IntPtr thisPtr) where T : CppObjectShadow => ToCallback<CallbackBase>(thisPtr).Shadows.OfType<T>(); public IEnumerable<T> ToAllShadows<T>() where T : CppObjectShadow => ToCallback<CallbackBase>().Shadows.OfType<T>(); public static T ToCallback<T>(IntPtr thisPtr) where T : ICallbackable { Debug.Assert(thisPtr != IntPtr.Zero); var handle = ((CppObjectCallableWrapper*) thisPtr)->Shadow; Debug.Assert(handle.IsAllocated); return handle.Target switch { T value => value, CppObjectShadow shadow => shadow.ToCallback<T>(), CppObjectMultiShadow multiShadow when multiShadow.ToCallback(out T? callback) => callback, CppObjectMultiShadow => throw new Exception($"Shadow {typeof(T).FullName} is missing the callback in the whole inheritance graph"), null => throw new Exception($"Shadow {typeof(T).FullName} is dead"), { } value => throw new Exception( $"Shadow is of an unexpected type {value.GetType().FullName}, expected {typeof(T).FullName}" ) }; } public T ToCallback<T>() where T : ICallbackable { var handle = callbackHandle; Debug.Assert(handle.IsAllocated); return handle.Target switch { T value => value, null => throw new Exception($"Shadow {typeof(T).FullName} references dead callback"), { } value => throw new Exception( $"Shadow references an unexpected callback of type {value.GetType().FullName}, expected {typeof(T).FullName}" ) }; } } <|start_filename|>SharpGen/VisualStudioSetup/ISetupInstance.cs<|end_filename|>  using System.Runtime.InteropServices; using System.Runtime.InteropServices.ComTypes; namespace SharpGen.VisualStudioSetup; [Guid("B41463C3-8866-43B5-BC33-2B0676F7F42E")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [ComImport] public interface ISetupInstance { [return: MarshalAs(UnmanagedType.BStr)] string GetInstanceId(); FILETIME GetInstallDate(); [return: MarshalAs(UnmanagedType.BStr)] string GetInstallationName(); [return: MarshalAs(UnmanagedType.BStr)] string GetInstallationPath(); [return: MarshalAs(UnmanagedType.BStr)] string GetInstallationVersion(); [return: MarshalAs(UnmanagedType.BStr)] string GetDisplayName([MarshalAs(UnmanagedType.U4), In] int lcid = 0); [return: MarshalAs(UnmanagedType.BStr)] string GetDescription([MarshalAs(UnmanagedType.U4), In] int lcid = 0); [return: MarshalAs(UnmanagedType.BStr)] string ResolvePath([MarshalAs(UnmanagedType.LPWStr), In] string pwszRelativePath = null); } <|start_filename|>SharpGen/VisualStudioSetup/SetupConfiguration.cs<|end_filename|>  using System.Runtime.InteropServices; namespace SharpGen.VisualStudioSetup; [Guid("42843719-DB4C-46C2-8E7C-64F1816EFD5B")] [CoClass(typeof (SetupConfigurationClass))] [ComImport] public interface SetupConfiguration : ISetupConfiguration2, ISetupConfiguration { } <|start_filename|>SharpGen/Generator/ExpressionPlatformSingleCodeGeneratorBase.cs<|end_filename|> using System.Collections.Generic; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using SharpGen.Model; namespace SharpGen.Generator; internal abstract class ExpressionPlatformSingleCodeGeneratorBase<T> : StatementCodeGeneratorBase<T>, IPlatformSingleCodeGenerator<T, StatementSyntax>, IPlatformSingleCodeGenerator<T, ExpressionSyntax> where T : CsBase { protected ExpressionPlatformSingleCodeGeneratorBase(Ioc ioc) : base(ioc) { } public abstract IEnumerable<PlatformDetectionType> GetPlatforms(T csElement); ExpressionSyntax IPlatformSingleCodeGenerator<T, ExpressionSyntax>.GenerateCode( T csElement, PlatformDetectionType platform ) => Generate(csElement, platform); StatementSyntax IPlatformSingleCodeGenerator<T, StatementSyntax>.GenerateCode( T csElement, PlatformDetectionType platform ) => Generate(csElement, platform) is { } value ? SyntaxFactory.ExpressionStatement(value) : null; protected abstract ExpressionSyntax Generate(T csElement, PlatformDetectionType platform); } <|start_filename|>SharpGen/Generator/ExpressionMultiCodeGeneratorBase.cs<|end_filename|> using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using SharpGen.Model; namespace SharpGen.Generator; internal abstract class ExpressionMultiCodeGeneratorBase<T> : StatementCodeGeneratorBase<T>, IMultiCodeGenerator<T, StatementSyntax>, IMultiCodeGenerator<T, ExpressionSyntax> where T : CsBase { protected ExpressionMultiCodeGeneratorBase(Ioc ioc) : base(ioc) { } IEnumerable<StatementSyntax> IMultiCodeGenerator<T, StatementSyntax>.GenerateCode(T csElement) => Generate(csElement) .Where(static x => x != null) .Select(SyntaxFactory.ExpressionStatement); IEnumerable<ExpressionSyntax> IMultiCodeGenerator<T, ExpressionSyntax>.GenerateCode(T csElement) => Generate(csElement); protected abstract IEnumerable<ExpressionSyntax> Generate(T csElement); } <|start_filename|>SharpGen.Runtime/Diagnostics/ObjectTrackerReadOnlyConfiguration.cs<|end_filename|> namespace SharpGen.Runtime.Diagnostics; internal static class ObjectTrackerReadOnlyConfiguration { public static readonly bool IsEnabled = Configuration.EnableObjectTracking; public static readonly bool IsReleaseOnFinalizerEnabled = Configuration.EnableReleaseOnFinalizer; public static readonly bool IsObjectTrackingThreadStatic = Configuration.UseThreadStaticObjectTracking; static ObjectTrackerReadOnlyConfiguration() { Configuration.ObjectTrackerImmutable = true; } } <|start_filename|>SharpGen/Logging/Logger.cs<|end_filename|> // Copyright (c) 2010-2014 SharpDX - <NAME> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Collections.Generic; namespace SharpGen.Logging; /// <summary> /// Root Logger class. /// </summary> public sealed class Logger : LoggerBase { private int _errorCount; private readonly List<string> contextStack = new(); private readonly Stack<LogLocation> fileLocationStack = new(); public Logger(ILogger output, IProgressReport progress = null) { LoggerOutput = output; ProgressReport = progress; } /// <summary> /// Gets the context as a string. /// </summary> private string ContextAsText => HasContext ? string.Join("/", contextStack) : null; public override ILogger LoggerOutput { get; } private bool HasContext => contextStack.Count > 0; public override bool HasErrors => _errorCount > 0; public override IProgressReport ProgressReport { get; } /// <summary> /// Pushes a context string. /// </summary> public override void PushContext(string context) { contextStack.Add(context); } /// <summary> /// Pushes a context location. /// </summary> public override void PushLocation(string fileName, int line = 1, int column = 1) { fileLocationStack.Push(new LogLocation(fileName, line, column)); } /// <summary> /// Pops the context location. /// </summary> public override void PopLocation() { fileLocationStack.Pop(); } /// <summary> /// Pushes a context formatted string. /// </summary> public override void PushContext(string context, params object[] parameters) { contextStack.Add(string.Format(context, parameters)); } /// <summary> /// Pops the context. /// </summary> public override void PopContext() { if (contextStack.Count > 0) contextStack.RemoveAt(contextStack.Count - 1); } /// <summary> /// Logs the specified progress level and message. /// </summary> public override void Progress(int level, string message, params object[] parameters) { Message(message, parameters); if (ProgressReport?.ProgressStatus(level, string.Format(message, parameters)) == true) Exit("Process aborted manually"); } /// <summary> /// Exits the process. /// </summary> public override void Exit(string reason, params object[] parameters) { var message = string.Format(reason, parameters); ProgressReport?.FatalExit(message); LoggerOutput?.Exit(message, 1); } /// <summary> /// Logs the raw message to the LoggerOutput. /// </summary> public override void LogRawMessage(LogLevel type, string code, string message, Exception exception, params object[] parameters) { var logLocation = fileLocationStack.Count > 0 ? fileLocationStack.Peek() : null; if (LoggerOutput == null) Console.WriteLine("Warning, unable to log error. No LoggerOutput configured"); else LoggerOutput.Log(type, logLocation, ContextAsText, code, message, exception, parameters); if (type is LogLevel.Error or LogLevel.Fatal) _errorCount++; } } <|start_filename|>SharpGen/Generator/VtblGenerator.cs<|end_filename|> using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using SharpGen.Config; using SharpGen.Model; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; namespace SharpGen.Generator; internal sealed class VtblGenerator : MemberSingleCodeGeneratorBase<CsInterface> { private static readonly SyntaxToken DelegateCacheGlobalIdentifier = Identifier("DelegateCache"); private static readonly SyntaxToken VtblIdentifier = Identifier("Vtbl"); public override MemberDeclarationSyntax GenerateCode(CsInterface csElement) { var vtblClassName = csElement.VtblName.Split('.').Last(); // Default: at least protected to enable inheritance. var vtblVisibility = csElement.VtblVisibility ?? Visibility.Internal; bool AnyOffsetDiffersPredicate() { bool Predicate(CsMethod x) => x.WindowsOffset != x.Offset || x.InteropSignatures is not { Count: 1 } v || !v.ContainsKey(PlatformDetectionType.Any); return csElement.Methods.Any(Predicate); } ExpressionSyntax MethodArrayBuilder(bool withFunctionPointers) { InitializerExpressionSyntax Generate(PlatformDetectionType platform) => InitializerExpression( SyntaxKind.ArrayInitializerExpression, SeparatedList( GetOrderedMethods(csElement.Methods, platform) .Select(x => MethodBuilder(x, platform, withFunctionPointers)) ) ); return GeneratorHelpers.PlatformSpecificExpression( GlobalNamespace, Generators.Config.Platforms, AnyOffsetDiffersPredicate, () => Generate(PlatformDetectionType.Windows), () => Generate(PlatformDetectionType.ItaniumSystemV), ImplicitArrayCreationExpression ); } var members = NewMemberList; List<CsMethod> legacyMethods = new(); foreach (var method in csElement.Methods) { if (method.IsFunctionPointerInVtbl) { legacyMethods.Add(method); continue; } members.AddRange(method.InteropSignatures.Keys, platform => DelegateCacheDecl(method, platform)); } var conditionalStart = members.Count; members.Add(VtblDecl(MethodArrayBuilder(true)).WithTrailingElseDirective()); foreach (var method in legacyMethods) members.AddRange(method.InteropSignatures.Keys, platform => DelegateCacheDecl(method, platform)); members.Add(VtblDecl(MethodArrayBuilder(false)).WithTrailingEndIfDirective()); members[conditionalStart] = members[conditionalStart].WithLeadingIfDirective(GeneratorHelpers.PreprocessorNameSyntax); #if false ImplicitArrayCreationExpressionSyntax GenerateDelegateCacheFill(PlatformDetectionType platform) => ImplicitArrayCreationExpression( InitializerExpression( SyntaxKind.ArrayInitializerExpression, SeparatedList( GetOrderedMethods(csElement.Methods, platform) .Select(x => DelegateCacheBuilder(x, platform)) ) ) ); members.Add( ConstructorDeclaration(vtblClassName) .WithModifiers(TokenList(Token(SyntaxKind.StaticKeyword))) .WithBody( Block( ExpressionStatement( AssignmentExpression( SyntaxKind.SimpleAssignmentExpression, IdentifierName(DelegateCacheGlobalIdentifier), GeneratorHelpers.PlatformSpecificExpression( GlobalNamespace, Generators.Config.Platforms, AnyOffsetDiffersPredicate, () => GenerateDelegateCacheFill(PlatformDetectionType.Windows), () => GenerateDelegateCacheFill(PlatformDetectionType.ItaniumSystemV) ) ) ) ) ) .WithTrailingEndIfDirective() ); #endif members.AddRange(csElement.Methods, Generators.ShadowCallable); return ClassDeclaration(vtblClassName) .WithModifiers( ModelUtilities.VisibilityToTokenList( vtblVisibility, SyntaxKind.StaticKeyword, SyntaxKind.UnsafeKeyword, SyntaxKind.PartialKeyword ) ) .WithMembers(List(members)); } private ExpressionSyntax GetMarshalFunctionPointerForDelegate(CsMethod method, PlatformDetectionType platform) => InvocationExpression( MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, GlobalNamespace.GetTypeNameSyntax(BuiltinType.Marshal), IdentifierName("GetFunctionPointerForDelegate") ), ArgumentList(SingletonSeparatedList(Argument(IdentifierName(GetMethodCacheName(method, platform))))) ); private static void CoercePlatform(CsMethod csMethod, ref PlatformDetectionType platform) { var interopSignatures = csMethod.InteropSignatures; if (interopSignatures.ContainsKey(platform)) return; platform = PlatformDetectionType.Any; Debug.Assert(interopSignatures.ContainsKey(platform)); } private FieldDeclarationSyntax DelegateCacheDecl(CsMethod method, PlatformDetectionType platform) => FieldDeclaration( default, TokenList( Token(SyntaxKind.PrivateKeyword), Token(SyntaxKind.StaticKeyword), Token(SyntaxKind.ReadOnlyKeyword) ), VariableDeclaration( IdentifierName(GetMethodDelegateName(method, platform)), SingletonSeparatedList( VariableDeclarator( GetMethodCacheName(method, platform), default, EqualsValueClause( platform != PlatformDetectionType.Any ? ConditionalExpression( GeneratorHelpers.PlatformCondition(GlobalNamespace, platform), IdentifierName(GetMethodImplName(method, platform)), NullLiteral ) : IdentifierName(GetMethodImplName(method, platform)) ) ) ) ) ); private FieldDeclarationSyntax VtblDecl(ExpressionSyntax value) => FieldDeclaration( default, TokenList( Token(SyntaxKind.PublicKeyword), Token(SyntaxKind.StaticKeyword), Token(SyntaxKind.ReadOnlyKeyword) ), VariableDeclaration( ArrayType( GeneratorHelpers.IntPtrType, SingletonList( ArrayRankSpecifier(SingletonSeparatedList<ExpressionSyntax>(OmittedArraySizeExpression())) ) ), SingletonSeparatedList(VariableDeclarator(VtblIdentifier, default, EqualsValueClause(value))) ) ); private ExpressionSyntax MethodBuilder(CsMethod method, PlatformDetectionType platform, bool withFunctionPointers) { CoercePlatform(method, ref platform); var vtblMethodName = IdentifierName(GetMethodImplName(method, platform)); FunctionPointerTypeSyntax FnPtrType() { var sig = method.InteropSignatures[platform]; var fnptrParameters = sig.ParameterTypes .Select(x => x.InteropTypeSyntax) .Prepend(GeneratorHelpers.IntPtrType) .Append(sig.ReturnTypeSyntax) .Select(FunctionPointerParameter); return FunctionPointerType( FunctionPointerCallingConvention( Token(SyntaxKind.UnmanagedKeyword), FunctionPointerUnmanagedCallingConventionList( SingletonSeparatedList( FunctionPointerUnmanagedCallingConvention( Identifier(method.CppCallingConvention.ToCallConvShortName()) ) ) ) ), FunctionPointerParameterList(SeparatedList(fnptrParameters)) ); } return method.IsFunctionPointerInVtbl && withFunctionPointers ? GeneratorHelpers.CastExpression( GeneratorHelpers.IntPtrType, GeneratorHelpers.CastExpression( FnPtrType(), PrefixUnaryExpression(SyntaxKind.AddressOfExpression, vtblMethodName) ) ) : GetMarshalFunctionPointerForDelegate(method, platform); } private CsMethod[] GetOrderedMethods(IEnumerable<CsMethod> methods, PlatformDetectionType platform) { var getter = GeneratorHelpers.GetOffsetGetter(platform); var items = methods.OrderBy(getter).ToArray(); var count = items.Length; if (count == 0) return items; var offsets = items.Select(getter).ToArray(); var minOffset = offsets[0]; var maxOffset = offsets.Last(); Debug.Assert(maxOffset - minOffset + 1 == count); for (var i = 0; i < count; i++) Debug.Assert(offsets[i] == minOffset + i); return items; } internal static SyntaxToken GetMethodDelegateName(CsCallable csElement, PlatformDetectionType platform) => Identifier(csElement.Name + "Delegate" + GeneratorHelpers.GetPlatformSpecificSuffix(platform)); internal static SyntaxToken GetMethodCacheName(CsCallable csElement, PlatformDetectionType platform) => Identifier(csElement.Name + "DelegateCache" + GeneratorHelpers.GetPlatformSpecificSuffix(platform)); internal static SyntaxToken GetMethodImplName(CsCallable csElement, PlatformDetectionType platform) => Identifier(csElement.Name + "Impl" + GeneratorHelpers.GetPlatformSpecificSuffix(platform)); public VtblGenerator(Ioc ioc) : base(ioc) { } } <|start_filename|>SdkTests/Functions/StructWithStaticMarshal.cs<|end_filename|> namespace Functions; public partial struct StructWithStaticMarshal { internal static void __MarshalTo(ref StructWithStaticMarshal @this, ref StructWithStaticMarshal.__Native @ref) { @this.__MarshalTo(ref @ref); } internal static void __MarshalFrom(ref StructWithStaticMarshal @this, ref StructWithStaticMarshal.__Native @ref) { @this.__MarshalFrom(ref @ref); } internal static void __MarshalFree(ref StructWithStaticMarshal @this, ref StructWithStaticMarshal.__Native @ref) { @this.__MarshalFree(ref @ref); } } <|start_filename|>SdkTests/Struct/SimpleStructTests.cs<|end_filename|> using System; using Xunit; namespace Struct; public class SimpleStructTests { [Fact] public void SimpleStructMarshalledCorrectly() { var simple = Functions.GetSimpleStruct(); Assert.Equal(10, simple.I); Assert.Equal(3, simple.J); } } <|start_filename|>SharpGen/Generator/MemberMultiCodeGeneratorBase.cs<|end_filename|> using System.Collections.Generic; using Microsoft.CodeAnalysis.CSharp.Syntax; using SharpGen.Model; namespace SharpGen.Generator; internal abstract class MemberMultiCodeGeneratorBase<T> : MemberCodeGeneratorBase<T>, IMultiCodeGenerator<T, MemberDeclarationSyntax> where T : CsBase { protected MemberMultiCodeGeneratorBase(Ioc ioc) : base(ioc) { } public abstract IEnumerable<MemberDeclarationSyntax> GenerateCode(T csElement); } <|start_filename|>SharpGen.Runtime/BooleanHelpers.BoolToInt.Span.cs<|end_filename|> using System; using System.Runtime.InteropServices; namespace SharpGen.Runtime; public static partial class BooleanHelpers { /// <summary> /// Converts bool array to an array of integers. /// </summary> /// <param name="array">The bool array.</param> /// <param name="dest">The destination array of integers.</param> public static void ConvertToIntArray(Span<bool> array, Span<byte> dest) => MemoryMarshal.AsBytes(array).CopyTo(dest); /// <summary> /// Converts bool array to an array of integers. /// </summary> /// <param name="array">The bool array.</param> /// <param name="dest">The destination array of integers.</param> public static void ConvertToIntArray(Span<bool> array, Span<short> dest) { var arrayLength = array.Length; for (var i = 0; i < arrayLength; i++) dest[i] = (short) (array[i] ? 1 : 0); } /// <summary> /// Converts bool array to an array of integers. /// </summary> /// <param name="array">The bool array.</param> /// <param name="dest">The destination array of integers.</param> public static void ConvertToIntArray(Span<bool> array, Span<int> dest) { var arrayLength = array.Length; for (var i = 0; i < arrayLength; i++) dest[i] = array[i] ? 1 : 0; } /// <summary> /// Converts bool array to an array of integers. /// </summary> /// <param name="array">The bool array.</param> /// <param name="dest">The destination array of integers.</param> public static void ConvertToIntArray(Span<bool> array, Span<long> dest) { var arrayLength = array.Length; for (var i = 0; i < arrayLength; i++) dest[i] = array[i] ? 1 : 0; } /// <summary> /// Converts bool array to an array of integers. /// </summary> /// <param name="array">The bool array.</param> /// <param name="dest">The destination array of integers.</param> public static void ConvertToIntArray(Span<bool> array, Span<sbyte> dest) => MemoryMarshal.AsBytes(array).CopyTo(MemoryMarshal.AsBytes(dest)); /// <summary> /// Converts bool array to an array of integers. /// </summary> /// <param name="array">The bool array.</param> /// <param name="dest">The destination array of integers.</param> public static void ConvertToIntArray(Span<bool> array, Span<ushort> dest) { var arrayLength = array.Length; for (var i = 0; i < arrayLength; i++) dest[i] = (ushort) (array[i] ? 1 : 0); } /// <summary> /// Converts bool array to an array of integers. /// </summary> /// <param name="array">The bool array.</param> /// <param name="dest">The destination array of integers.</param> public static void ConvertToIntArray(Span<bool> array, Span<uint> dest) { var arrayLength = array.Length; for (var i = 0; i < arrayLength; i++) dest[i] = (uint) (array[i] ? 1 : 0); } /// <summary> /// Converts bool array to an array of integers. /// </summary> /// <param name="array">The bool array.</param> /// <param name="dest">The destination array of integers.</param> public static void ConvertToIntArray(Span<bool> array, Span<ulong> dest) { var arrayLength = array.Length; for (var i = 0; i < arrayLength; i++) dest[i] = (ulong) (array[i] ? 1 : 0); } } <|start_filename|>SharpGen.UnitTests/PropertyBuilderTests.cs<|end_filename|> using SharpGen.Config; using SharpGen.CppModel; using SharpGen.Model; using SharpGen.Transform; using Xunit; using Xunit.Abstractions; namespace SharpGen.UnitTests; public class PropertyBuilderTests : TestBase { private readonly PropertyBuilder propertyBuilder; public PropertyBuilderTests(ITestOutputHelper outputHelper) : base(outputHelper) { propertyBuilder = new PropertyBuilder(Ioc); } [Fact] public void MethodWithNameStartingWithIsCreatesProperty() { var returnType = TypeRegistry.Int32; CsMethod isMethod = new(Ioc, null, "IsActive") { ReturnValue = new CsReturnValue(Ioc, null) { PublicType = returnType, MarshalType = returnType } }; var properties = propertyBuilder.CreateProperties(new[] { isMethod }); Assert.True(properties.ContainsKey("IsActive")); var prop = properties["IsActive"]; Assert.Equal(returnType, prop.PublicType); } [Fact] public void MethodWithNameStartingWithGetCreatesProperty() { var returnType = TypeRegistry.Int32; CsMethod getMethod = new(Ioc, null, "GetActive") { ReturnValue = new CsReturnValue(Ioc, null) { PublicType = returnType, MarshalType = returnType } }; var properties = propertyBuilder.CreateProperties(new[] { getMethod }); Assert.True(properties.ContainsKey("Active")); var prop = properties["Active"]; Assert.Equal(returnType, prop.PublicType); } [Fact] public void MethodWithNameStartingWithSetCreatesProperty() { var paramType = TypeRegistry.Int32; CsMethod setMethod = new(Ioc, null, "SetActive") { ReturnValue = new CsReturnValue(Ioc, null) { PublicType = TypeRegistry.Void } }; setMethod.Add(new CsParameter(Ioc, null, null) { PublicType = paramType }); var properties = propertyBuilder.CreateProperties(new[] { setMethod }); Assert.True(properties.ContainsKey("Active")); var prop = properties["Active"]; Assert.Equal(paramType, prop.PublicType); } [Fact] public void MethodWithNameStartingWithSetAndReturningResultGeneratesProperty() { var paramType = TypeRegistry.Int32; CsMethod setMethod = new(Ioc, null, "SetActive") { ReturnValue = new CsReturnValue(Ioc, null) { PublicType = new CsStruct(null, "SharpGen.Runtime.Result") } }; setMethod.Add(new CsParameter(Ioc, null, null) { PublicType = paramType }); var properties = propertyBuilder.CreateProperties(new[] { setMethod }); Assert.True(properties.ContainsKey("Active"), "Property not created"); var prop = properties["Active"]; Assert.Equal(paramType, prop.PublicType); } [Fact] public void GetterMethodReturningStatusCodeWithOutParamGeneratesProperty() { var paramType = TypeRegistry.Int32; CsMethod getMethod = new(Ioc, null, "GetActive") { ReturnValue = new CsReturnValue(Ioc, null) { PublicType = new CsStruct(null, "SharpGen.Runtime.Result") } }; getMethod.Add(new CsParameter(Ioc, null, null) { PublicType = paramType, Attribute = CsParameterAttribute.Out }); var properties = propertyBuilder.CreateProperties(new[] { getMethod }); Assert.True(properties.ContainsKey("Active")); var prop = properties["Active"]; Assert.True(prop.IsPropertyParam); Assert.Equal(paramType, prop.PublicType); } [Fact] public void GetterWithInvalidSetterDoesNotGenerateProperty() { var returnType = TypeRegistry.Int32; CsMethod getMethod = new(Ioc, null, "GetActive") { ReturnValue = new CsReturnValue(Ioc, null) { PublicType = returnType, MarshalType = returnType } }; var invalidSetMethod = new CsMethod(Ioc, null, "SetActive") { ReturnValue = new CsReturnValue(Ioc, null) { PublicType = TypeRegistry.Void } }; Assert.Empty(propertyBuilder.CreateProperties(new[] { getMethod, invalidSetMethod })); Assert.Empty(propertyBuilder.CreateProperties(new[] { invalidSetMethod, getMethod })); } [Fact] public void InvalidGetterDoesNotCreateProperty() { var returnType = TypeRegistry.Void; CsMethod getMethod = new(Ioc, null, "GetActive") { ReturnValue = new CsReturnValue(Ioc, null) { PublicType = returnType, MarshalType = returnType } }; Assert.Empty(propertyBuilder.CreateProperties(new[] { getMethod })); } [Fact] public void InvalidSetterDoesNotCreateProperty() { CsMethod setMethod = new(Ioc, null, "SetActive") { ReturnValue = new CsReturnValue(Ioc, null) { PublicType = TypeRegistry.Void } }; Assert.Empty(propertyBuilder.CreateProperties(new[] { setMethod })); } [Fact] public void GeneratePropertyIfGetterAndSetterMatch() { var paramType = TypeRegistry.Int32; CsMethod getMethod = new(Ioc, null, "GetActive") { ReturnValue = new CsReturnValue(Ioc, null) { PublicType = paramType, MarshalType = paramType } }; CsMethod setMethod = new(Ioc, null, "SetActive") { ReturnValue = new CsReturnValue(Ioc, null) { PublicType = TypeRegistry.Void } }; setMethod.Add(new CsParameter(Ioc, null, null) { PublicType = paramType }); var props = propertyBuilder.CreateProperties(new[] { getMethod, setMethod }); Assert.Single(props); Assert.NotNull(props["Active"].Getter); Assert.NotNull(props["Active"].Setter); } [Fact] public void DoesNotGeneratePropertyIfGetterAndSetterMismatch() { var paramType = TypeRegistry.Int32; CsMethod getMethod = new(Ioc, null, "GetActive") { ReturnValue = new CsReturnValue(Ioc, null) { PublicType = paramType, MarshalType = paramType } }; CsMethod setMethod = new(Ioc, null, "SetActive") { ReturnValue = new CsReturnValue(Ioc, null) { PublicType = TypeRegistry.Void } }; setMethod.Add(new CsParameter(Ioc, null, null) { PublicType = TypeRegistry.Int16 }); var props = propertyBuilder.CreateProperties(new[] { getMethod, setMethod }); Assert.Empty(props); } [Fact] public void DoesNotGeneratePropertyIfGetterAndSetterMismatch_ParameterizedGetter() { var paramType = TypeRegistry.Int32; CsMethod getMethod = new(Ioc, null, "GetActive") { ReturnValue = new CsReturnValue(Ioc, null) { PublicType = new CsStruct(null, "SharpGen.Runtime.Result") } }; getMethod.Add(new CsParameter(Ioc, null, null) { PublicType = paramType, Attribute = CsParameterAttribute.Out }); CsMethod setMethod = new(Ioc, null, "SetActive") { ReturnValue = new CsReturnValue(Ioc, null) { PublicType = TypeRegistry.Void } }; setMethod.Add(new CsParameter(Ioc, null, null) { PublicType = TypeRegistry.Int16 }); var props = propertyBuilder.CreateProperties(new[] { getMethod, setMethod }); Assert.Empty(props); } [Fact] public void DoesNotGeneratePropertyIfOverloaded() { var paramType = TypeRegistry.Int32; CsMethod getMethod = new(Ioc, null, "GetActive") { ReturnValue = new CsReturnValue(Ioc, null) { PublicType = paramType, MarshalType = paramType } }; CsMethod getMethodOverload = new(Ioc, null, "GetActive") { ReturnValue = new CsReturnValue(Ioc, null) { PublicType = paramType, MarshalType = paramType }, }; CsMethod setMethod = new(Ioc, null, "SetActive") { ReturnValue = new CsReturnValue(Ioc, null) { PublicType = TypeRegistry.Void } }; setMethod.Add(new CsParameter(Ioc, null, null) { PublicType = paramType }); Assert.Empty(propertyBuilder.CreateProperties(new[] { getMethod, setMethod, getMethodOverload })); Assert.Empty(propertyBuilder.CreateProperties(new[] { getMethod, getMethodOverload, setMethod })); } [Fact] public void PropertyAttachedToGetterType() { var paramType = TypeRegistry.Int32; CppMethod cppGetMethod = new("GetActive") { Rule = { Property = true } }; CsMethod getMethod = new(Ioc, cppGetMethod, cppGetMethod.Name) { ReturnValue = new CsReturnValue(Ioc, null) { PublicType = paramType, MarshalType = paramType } }; var iface = new CsInterface(null, null); iface.Add(getMethod); CsProperty prop = new(Ioc, null, "Active", getMethod, null); propertyBuilder.AttachPropertyToParent(prop); Assert.Equal(iface, prop.Parent); } [Fact] public void SetOnlyPropertyAttachedToSetterType() { CppMethod cppSetMethod = new("SetActive") { Rule = { Property = true } }; var paramType = TypeRegistry.Int32; CsMethod setMethod = new(Ioc, cppSetMethod, cppSetMethod.Name) { ReturnValue = new CsReturnValue(Ioc, null) { PublicType = TypeRegistry.Void } }; setMethod.Add(new CsParameter(Ioc, null, null) { PublicType = paramType }); var iface = new CsInterface(null, null); iface.Add(setMethod); CsProperty prop = new(Ioc, null, "Active", null, setMethod); propertyBuilder.AttachPropertyToParent(prop); Assert.Equal(iface, prop.Parent); } [Fact] public void PropertyNotAttachedWhenGetterAllowPropertyIsFalse() { CppMethod cppGetMethod = new("GetActive") { Rule = { Property = false } }; var paramType = TypeRegistry.Int32; CsMethod getMethod = new(Ioc, cppGetMethod, cppGetMethod.Name) { ReturnValue = new CsReturnValue(Ioc, null) { PublicType = paramType, MarshalType = paramType } }; var iface = new CsInterface(null, null); iface.Add(getMethod); CsProperty prop = new(Ioc, null, "Active", getMethod, null); propertyBuilder.AttachPropertyToParent(prop); Assert.Null(prop.Parent); } [Fact] public void PropertyNotAttachedWhenSetterAllowPropertyIsFalse() { CppMethod cppSetMethod = new("SetActive") { Rule = { Property = false } }; var paramType = TypeRegistry.Int32; CsMethod setMethod = new(Ioc, cppSetMethod, cppSetMethod.Name) { ReturnValue = new CsReturnValue(Ioc, null) { PublicType = TypeRegistry.Void } }; setMethod.Add(new CsParameter(Ioc, null, null) { PublicType = paramType }); var iface = new CsInterface(null, null); iface.Add(setMethod); CsProperty prop = new(Ioc, null, "Active", null, setMethod); propertyBuilder.AttachPropertyToParent(prop); Assert.Null(prop.Parent); } [Fact] public void PersistentGetterGeneratesPersistentProperty() { CppMethod cppGetMethod = new("GetActive") { Rule = { Property = true, Persist = true } }; var paramType = TypeRegistry.Int32; CsMethod getMethod = new(Ioc, cppGetMethod, cppGetMethod.Name) { ReturnValue = new CsReturnValue(Ioc, null) { PublicType = paramType, MarshalType = paramType } }; var iface = new CsInterface(null, null); iface.Add(getMethod); CsProperty prop = new(Ioc, null, "Active", getMethod, null); propertyBuilder.AttachPropertyToParent(prop); Assert.True(prop.IsPersistent); } [Fact] public void GetterVisibiltyInternal() { CppMethod cppGetMethod = new("GetActive") { Rule = { Property = true } }; var paramType = TypeRegistry.Int32; CsMethod getMethod = new(Ioc, cppGetMethod, cppGetMethod.Name) { ReturnValue = new CsReturnValue(Ioc, null) { PublicType = paramType, MarshalType = paramType } }; var iface = new CsInterface(null, null); iface.Add(getMethod); CsProperty prop = new(Ioc, null, "Active", getMethod, null); propertyBuilder.AttachPropertyToParent(prop); Assert.Equal(Visibility.Internal, getMethod.Visibility); } [Fact] public void SetterVisibilityInternal() { CppMethod cppSetMethod = new("SetActive") { Rule = { Property = true } }; var paramType = TypeRegistry.Int32; CsMethod setMethod = new(Ioc, cppSetMethod, cppSetMethod.Name) { ReturnValue = new CsReturnValue(Ioc, null) { PublicType = TypeRegistry.Void } }; setMethod.Add(new CsParameter(Ioc, null, null) { PublicType = paramType }); var iface = new CsInterface(null, null); iface.Add(setMethod); CsProperty prop = new(Ioc, null, "Active", null, setMethod); propertyBuilder.AttachPropertyToParent(prop); Assert.Equal(Visibility.Internal, setMethod.Visibility); } [Fact] public void NonPropertyMethodWithNonPropertyNameShouldNotCreateProperty() { CsMethod setMethod = new(Ioc, null, "MyMethod") { ReturnValue = new CsReturnValue(Ioc, null) { PublicType = TypeRegistry.Void } }; Assert.Empty(propertyBuilder.CreateProperties(new[] { setMethod })); } } <|start_filename|>SharpGen/Generator/Marshallers/BitfieldMarshaller.cs<|end_filename|> using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using SharpGen.Model; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; namespace SharpGen.Generator.Marshallers; internal sealed class BitfieldMarshaller : FieldMarshallerBase { protected override bool AllowNativeCleanup => true; protected override bool CanMarshal(CsField csField) => csField.IsBitField; protected override StatementSyntax GenerateManagedToNative(CsField csField, bool singleStackFrame) => ExpressionStatement( AssignmentExpression( SyntaxKind.OrAssignmentExpression, GetMarshalStorageLocation(csField), GeneratorHelpers.CastExpression( ParseTypeName(csField.MarshalType.QualifiedName), BinaryExpression( SyntaxKind.BitwiseAndExpression, IdentifierName(csField.IntermediateMarshalName), LiteralExpression( SyntaxKind.NumericLiteralExpression, Literal(csField.BitMask << csField.BitOffset) ) ) ) ) ); protected override StatementSyntax GenerateNativeToManaged(CsField csField, bool singleStackFrame) => ExpressionStatement( AssignmentExpression( SyntaxKind.SimpleAssignmentExpression, IdentifierName(csField.IntermediateMarshalName), GetMarshalStorageLocation(csField) ) ); public BitfieldMarshaller(Ioc ioc) : base(ioc) { } } <|start_filename|>SharpGen/Parser/CppHeaderGenerator.cs<|end_filename|> using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using SharpGen.Config; using SharpGen.Logging; namespace SharpGen.Parser; public sealed class CppHeaderGenerator { private readonly Ioc ioc; private const string Version = "1.1"; private Logger Logger => ioc.Logger; private string OutputPath { get; } public CppHeaderGenerator(string outputPath, Ioc ioc) { OutputPath = outputPath; this.ioc = ioc ?? throw new ArgumentNullException(nameof(ioc)); } public readonly struct Result { public HashSet<ConfigFile> UpdatedConfigs { get; } public string Prologue { get; } public Result(HashSet<ConfigFile> updatedConfigs, string prolog) { UpdatedConfigs = updatedConfigs ?? throw new ArgumentNullException(nameof(updatedConfigs)); Prologue = prolog ?? throw new ArgumentNullException(nameof(prolog)); } } public Result GenerateCppHeaders(ConfigFile configRoot, IReadOnlyCollection<ConfigFile> configsWithIncludes, ISet<ConfigFile> configsWithExtensionHeaders) { var updatedConfigs = new HashSet<ConfigFile>(ConfigFile.IdComparer); var prologue = GeneratePrologue(configRoot); // Dump includes foreach (var configFile in configsWithIncludes) { var outputConfigStr = GenerateIncludeConfigContents( configRoot, configFile, configsWithIncludes, configsWithExtensionHeaders, prologue ); var fileName = Path.Combine(OutputPath, configFile.HeaderFileName); // Test if Last config file was generated. If not, then we need to generate it // If it exists, then we need to test if it is the same than previous run bool isConfigUpdated; if (File.Exists(fileName)) isConfigUpdated = outputConfigStr != File.ReadAllText(fileName); else isConfigUpdated = true; // Small optim: just write the header file when the file is updated or new if (!isConfigUpdated) continue; Logger.Message("Config file changed for C++ headers [{0}]/[{1}]", configFile.Id, configFile.FilePath); updatedConfigs.Add(configFile); File.WriteAllText(fileName, outputConfigStr, Encoding.UTF8); } return new Result(updatedConfigs, prologue); } private static string GeneratePrologue(ConfigFile configRoot) { var prolog = new StringBuilder(); foreach (var prologItem in configRoot.ConfigFilesLoaded.SelectMany(file => file.IncludeProlog)) { prolog.Append(prologItem); } prolog.AppendLine(); return prolog.ToString(); } private static string GenerateIncludeConfigContents(ConfigFile configRoot, ConfigFile configFile, IReadOnlyCollection<ConfigFile> configsWithIncludes, ISet<ConfigFile> configsWithExtensionHeaders, string prolog) { using var outputConfig = new StringWriter(); outputConfig.WriteLine("// SharpGen include config [{0}] - Version {1}", configFile.Id, Version); if (configRoot.Id == configFile.Id) outputConfig.Write(prolog); // Write includes foreach (var includeRule in configFile.Includes) { if (!string.IsNullOrEmpty(includeRule.Pre)) { outputConfig.WriteLine(includeRule.Pre); } outputConfig.WriteLine("#include \"{0}\"", includeRule.File); if (!string.IsNullOrEmpty(includeRule.Post)) { outputConfig.WriteLine(includeRule.Post); } } // Write includes to references foreach (var reference in configFile.References) { if (configsWithIncludes.Contains(reference)) outputConfig.WriteLine("#include \"{0}\"", reference.HeaderFileName); } // Dump Create from macros if (configsWithExtensionHeaders.Contains(configFile)) { foreach (var typeBaseRule in configFile.Extension) { if (typeBaseRule.GeneratesExtensionHeader()) outputConfig.WriteLine("// {0}", typeBaseRule); } // Include extension header if it exists // so we can generate extension headers without needing them to already exist. outputConfig.WriteLine("#if __has_include(\"{0}\")", configFile.ExtensionFileName); outputConfig.WriteLine("#include \"{0}\"", configFile.ExtensionFileName); outputConfig.WriteLine("#endif"); } return outputConfig.ToString(); } } <|start_filename|>SharpGen/Transform/NamingRulesManager.cs<|end_filename|> // Copyright (c) 2010-2014 SharpDX - <NAME> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System.Diagnostics; using System.Linq; using SharpGen.Config; using SharpGen.CppModel; namespace SharpGen.Transform; /// <summary> /// This class handles renaming according to conventions. Pascal case (NamingRulesManager) for global types, /// Camel case (namingRulesManager) for parameters. /// </summary> public sealed partial class NamingRulesManager { /// <summary> /// Renames a C++ element from <see cref="originalName"/>. /// </summary> /// <param name="rootName">Name of the root to strip away.</param> /// <returns>The new C# name</returns> private static string RenameCore(string originalName, MappingRule tag, string rootName, out bool isFinal, out bool isPrematureBreak) { var name = originalName; if (tag.MappingNameFinal is { Length: > 0 } mappingNameFinal) { // Rename is tagged as final, then return the string isFinal = true; isPrematureBreak = false; return mappingNameFinal; } // Handle Tag bool nameModifiedByTag; if (tag.MappingName is { Length: > 0 } mappingName) { nameModifiedByTag = true; name = mappingName; } else { nameModifiedByTag = false; } isFinal = false; if (!name.Contains("_") && name.Any(char.IsLower) && char.IsUpper(name[0])) { isPrematureBreak = true; return name; } isPrematureBreak = false; // Remove Prefix (for enums). Don't modify names that are modified by tag if (!nameModifiedByTag && rootName != null && originalName.StartsWith(rootName)) name = originalName.Substring(rootName.Length, originalName.Length - rootName.Length); // Remove leading '_' return name.TrimStart('_'); } /// <summary> /// Renames a C++ element /// </summary> /// <param name="cppElement">The C++ element.</param> /// <param name="rootName">Name of the root.</param> /// <returns>The new name</returns> private string RenameCore(CppElement cppElement, string rootName = null) { Debug.Assert(cppElement is not CppField and not CppParameter); var originalName = cppElement.Name; var tag = cppElement.Rule; var name = RenameCore(originalName, tag, rootName, out var isFinal, out var isPreempted); if (isFinal) return name; var namingFlags = tag.NamingFlags is { } flags ? flags : NamingFlags.Default; if (isPreempted && (namingFlags & NamingFlags.NoPrematureBreak) == 0) return name; // Convert rest of the string in CamelCase return ConvertToPascalCase(name, namingFlags); } /// <summary> /// Renames the specified C++ element. /// </summary> /// <param name="cppElement">The C++ element.</param> /// <returns>The C# name</returns> public string Rename(CppElement cppElement) => UnKeyword(RenameCore(cppElement)); /// <summary> /// Renames the specified C++ enum item. /// </summary> /// <param name="cppEnumItem">The C++ enum item.</param> /// <param name="rootEnumName">Name of the root C++ enum.</param> /// <returns>The C# name of this enum item</returns> public string Rename(CppEnumItem cppEnumItem, string rootEnumName) => UnKeyword(FixDigitName(RenameCore(cppEnumItem, rootEnumName), "Value")); private static string FixDigitName(string name, string prefix) => char.IsDigit(name[0]) ? prefix + name : name; } <|start_filename|>SharpGen/Config/ContextRule.cs<|end_filename|> // Copyright (c) 2010-2014 SharpDX - <NAME> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System.Collections.Generic; using System.Globalization; using System.Xml.Serialization; namespace SharpGen.Config; [XmlType("context")] public class ContextRule : ExtensionBaseRule { public ContextRule() { Ids = new List<string>(); } public ContextRule(string context) { Ids = new List<string> {context}; } public ContextRule(IEnumerable<string> ids) { Ids = new List<string>(ids); } [XmlAttribute("id")] public string ContextSetId { get; set; } [XmlText] public List<string> Ids { get; set; } [ExcludeFromCodeCoverage] public override string ToString() { return string.Format(CultureInfo.InvariantCulture, "{0} Ids:{1}", base.ToString(), (Ids != null) ? Ids.ToString() : ""); } } [XmlType("context-clear")] public class ClearContextRule : ContextRule { public ClearContextRule() { Ids = null; } } <|start_filename|>SharpGen/Generator/ReverseCallablePrologCodeGenerator.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Threading; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using SharpGen.Generator.Marshallers; using SharpGen.Model; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; namespace SharpGen.Generator; internal sealed class ReverseCallablePrologCodeGenerator : StatementPlatformMultiCodeGeneratorBase<CsCallable> { public override IEnumerable<PlatformDetectionType> GetPlatforms(CsCallable csElement) => csElement.InteropSignatures.Keys; public override IEnumerable<StatementSyntax> GenerateCode(CsCallable csElement, PlatformDetectionType platform) { var interopSig = csElement.InteropSignatures[platform]; if (!interopSig.ForcedReturnBufferSig && csElement.HasReturnTypeValue) { foreach (var statement in GenerateProlog(csElement.ReturnValue, null, null)) { yield return statement; } } foreach (var signatureParameter in interopSig.ParameterTypes) { var publicParameter = signatureParameter.Item; var nativeParameter = IdentifierName(signatureParameter.Name); var interopTypeSyntax = signatureParameter.InteropTypeSyntax; var builder = GetPrologBuilder(publicParameter); foreach (var statement in builder(publicParameter, nativeParameter, interopTypeSyntax)) yield return statement; } } private readonly Lazy<PrologGenerationDelegate> _nativeByRefPrologDelegate; private readonly Lazy<PrologGenerationDelegate> _prologDelegate; private PrologGenerationDelegate GetPrologBuilder(CsMarshalCallableBase publicParameter) => publicParameter.PassedByNativeReference && !publicParameter.IsArray ? _nativeByRefPrologDelegate.Value : _prologDelegate.Value; private delegate IEnumerable<StatementSyntax> PrologGenerationDelegate( CsMarshalCallableBase publicElement, ExpressionSyntax nativeParameter, TypeSyntax nativeParameterType ); private IEnumerable<StatementSyntax> GenerateProlog(CsMarshalCallableBase publicElement, ExpressionSyntax nativeParameter, TypeSyntax nativeParameterType) { ExpressionSyntax CastToPublicType(TypeSyntax targetType, ExpressionSyntax expression) => targetType.IsEquivalentTo(nativeParameterType) ? expression : GeneratorHelpers.CastExpression(targetType, expression); var marshaller = GetMarshaller(publicElement); var publicType = GetPublicType(publicElement); var generatesMarshalVariable = marshaller.GeneratesMarshalVariable(publicElement); var publicTypeVariableValue = nativeParameter != null && !generatesMarshalVariable ? CastToPublicType(publicType, nativeParameter) : DefaultLiteral; yield return LocalDeclarationStatement( VariableDeclaration( publicType, SingletonSeparatedList( VariableDeclarator(Identifier(publicElement.Name)) .WithInitializer(EqualsValueClause(publicTypeVariableValue)) ) ) ); if (generatesMarshalVariable) { var marshalTypeSyntax = marshaller.GetMarshalTypeSyntax(publicElement); var initializerExpression = nativeParameter != null ? CastToPublicType(marshalTypeSyntax, nativeParameter) : DefaultLiteral; yield return LocalDeclarationStatement( VariableDeclaration( marshalTypeSyntax, SingletonSeparatedList( VariableDeclarator( MarshallerBase.GetMarshalStorageLocationIdentifier(publicElement), null, EqualsValueClause(initializerExpression) ) ) ) ); } } internal static TypeSyntax GetPublicType(CsMarshalCallableBase publicElement) { var publicType = ParseTypeName(publicElement.PublicType.QualifiedName); return publicElement.IsArray ? ArrayType(publicType, SingletonList(ArrayRankSpecifier())) : publicType; } private IEnumerable<StatementSyntax> GenerateNativeByRefProlog(CsMarshalCallableBase publicElement, ExpressionSyntax nativeParameter, TypeSyntax nativeParameterType) { var marshaller = GetMarshaller(publicElement); var marshalTypeSyntax = marshaller.GetMarshalTypeSyntax(publicElement); var publicType = ParseTypeName(publicElement.PublicType.QualifiedName); var generatesMarshalVariable = marshaller.GeneratesMarshalVariable(publicElement); ExpressionSyntax publicDefaultValue = publicElement.UsedAsReturn ? default : DefaultLiteral; var refToNativeClause = GenerateAsRefInitializer(publicElement, nativeParameter, marshalTypeSyntax); TypeSyntax publicVariableType, marshalVariableType; ExpressionSyntax publicVariableInitializer, marshalVariableInitializer; if (publicElement is CsParameter {IsOptional: true, IsLocalManagedReference: true} parameter) { Debug.Assert(marshaller is RefWrapperMarshaller); var refVariableDeclaration = LocalDeclarationStatement( VariableDeclaration( RefType(marshalTypeSyntax), SingletonSeparatedList( VariableDeclarator( MarshallerBase.GetRefLocationIdentifier(publicElement), default, EqualsValueClause(refToNativeClause) ) ) ) ); publicVariableType = publicType; marshalVariableType = marshalTypeSyntax; publicVariableInitializer = publicDefaultValue; marshalVariableInitializer = DefaultLiteral; if (generatesMarshalVariable && parameter is {IsRef: true}) { Logger.Error( null, "Optional ref parameter [{0}] that requires generating marshal variable is unsupported.", parameter.QualifiedName ); } else { Debug.Assert(!generatesMarshalVariable || parameter is {IsOut: true}); } yield return refVariableDeclaration; } else { Debug.Assert(marshaller is not RefWrapperMarshaller); marshalVariableInitializer = refToNativeClause; if (publicElement is {IsLocalManagedReference: true}) { Debug.Assert(publicElement is CsReturnValue or CsParameter {IsOptional: false}); marshalVariableType = RefType(marshalTypeSyntax); publicVariableType = generatesMarshalVariable ? publicType : RefType(publicType); publicVariableInitializer = generatesMarshalVariable ? publicDefaultValue : refToNativeClause; } else { Debug.Assert(publicElement is CsParameter {IsRefIn: true}); var isNullable = publicElement is CsParameter {PassedByNullableInstance: true}; marshalVariableType = marshalTypeSyntax; publicVariableType = isNullable ? NullableType(publicType) : publicType; publicVariableInitializer = generatesMarshalVariable ? isNullable ? ConditionalExpression( BinaryExpression( SyntaxKind.NotEqualsExpression, nativeParameter, DefaultLiteral ), ImplicitObjectCreationExpression(), NullLiteral ) : publicDefaultValue : refToNativeClause; } } if (generatesMarshalVariable) { yield return LocalDeclarationStatement( VariableDeclaration( marshalVariableType, SingletonSeparatedList( VariableDeclarator( MarshallerBase.GetMarshalStorageLocationIdentifier(publicElement), default, EqualsValueClause(marshalVariableInitializer) ) ) ) ); } yield return LocalDeclarationStatement( VariableDeclaration( publicVariableType, SingletonSeparatedList( VariableDeclarator( Identifier(publicElement.Name), default, publicVariableInitializer != default ? EqualsValueClause(publicVariableInitializer) : default ) ) ) ); } private ExpressionSyntax GenerateAsRefInitializer(CsMarshalCallableBase publicElement, ExpressionSyntax nativeParameter, TypeSyntax marshalTypeSyntax) { var refToNativeExpression = InvocationExpression( MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, GlobalNamespace.GetTypeNameSyntax(BuiltinType.Unsafe), GenericName( Identifier(nameof(Unsafe.AsRef)), TypeArgumentList(SingletonSeparatedList(marshalTypeSyntax)) ) ), ArgumentList(SingletonSeparatedList(Argument(nativeParameter))) ); ExpressionSyntax refToNativeClauseExpression; if (publicElement.IsLocalManagedReference) { Debug.Assert( publicElement is CsReturnValue or CsParameter { Attribute: CsParameterAttribute.Ref or CsParameterAttribute.Out } ); refToNativeClauseExpression = RefExpression(refToNativeExpression); } else { Debug.Assert(publicElement is CsParameter {IsRefIn: true}); if (publicElement is CsParameter {IsOptional: true}) { refToNativeClauseExpression = ConditionalExpression( BinaryExpression(SyntaxKind.NotEqualsExpression, nativeParameter, DefaultLiteral), refToNativeExpression, DefaultLiteral ); } else { refToNativeClauseExpression = refToNativeExpression; } } return refToNativeClauseExpression; } public ReverseCallablePrologCodeGenerator(Ioc ioc) : base(ioc) { _nativeByRefPrologDelegate = new(() => GenerateNativeByRefProlog, LazyThreadSafetyMode.None); _prologDelegate = new(() => GenerateProlog, LazyThreadSafetyMode.None); } } <|start_filename|>SharpGen/Generator/StatementCodeGeneratorBase.cs<|end_filename|> using SharpGen.Model; namespace SharpGen.Generator; internal abstract class StatementCodeGeneratorBase<T> : CodeGeneratorBase, IStatementCodeGenerator<T> where T : CsBase { protected StatementCodeGeneratorBase(Ioc ioc) : base(ioc) { } protected StatementSyntaxList NewStatementList => new(Ioc); protected MemberSyntaxList NewMemberList => new(Ioc); } <|start_filename|>SharpGen.Runtime/ExcludeFromTypeListAttribute.cs<|end_filename|> using System; using System.Reflection; using System.Runtime.CompilerServices; namespace SharpGen.Runtime; [AttributeUsage(AttributeTargets.Interface)] public sealed class ExcludeFromTypeListAttribute : Attribute { /// <summary> /// Check presence of <see cref="ExcludeFromTypeListAttribute"/> on the specified type. /// </summary> /// <returns>true if attribute was found on the specified type</returns> [MethodImpl(Utilities.MethodAggressiveOptimization)] internal static bool Has(Type type) => Has(type.GetTypeInfo()); /// <summary> /// Check presence of <see cref="ExcludeFromTypeListAttribute"/> on the specified type. /// </summary> /// <returns>true if attribute was found on the specified type</returns> [MethodImpl(Utilities.MethodAggressiveOptimization)] internal static bool Has(TypeInfo type) => type.GetCustomAttribute<ExcludeFromTypeListAttribute>() != null; } <|start_filename|>SharpGen/Config/BindRule.cs<|end_filename|> // Copyright (c) 2010-2014 SharpDX - <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. #nullable enable using System.ComponentModel; using System.Globalization; using System.Xml.Serialization; namespace SharpGen.Config; /// <summary> /// Binding rule. Bind a cpp type to a C#/.Net type. /// Usage: bind from="CPP_TYPE_NAME" to="C#_FULLTYPE_NAME" /// </summary> [XmlType("bind")] public class BindRule : ConfigBaseRule { public BindRule() { } /// <param name="from">The C++ type</param> /// <param name="to">The C# public type</param> /// <param name="marshal">The C# marshal type</param> /// <param name="source">The source of the definition</param> public BindRule(string from, string to, string? marshal = null, string? source = null) { From = from; To = to; Marshal = marshal; Source = source; } /// <summary> /// Gets or sets the cpp from type. /// </summary> /// <value>From cpp type</value> [XmlAttribute("from")] public string From { get; set; } /// <summary> /// Gets or sets the C# to type /// </summary> /// <value>To.</value> [XmlAttribute("to")] public string To { get; set; } /// <summary> /// Gets or sets the C# the marshal type /// </summary> [XmlAttribute("marshal")] public string? Marshal { get; set; } /// <value>The source of the definition</value> [XmlAttribute("source")] [DefaultValue(null)] public string? Source { get; set; } /// <summary> /// Provides an ability to override an existing mapping /// </summary> [XmlIgnore] public bool? Override { get; set; } [XmlAttribute("override")] public bool _Override_ { get => Override.Value; set => Override = value; } public bool ShouldSerialize_Override_() => Override != null; /// <inheritdoc /> [ExcludeFromCodeCoverage] public override string ToString() => string.Format( CultureInfo.InvariantCulture, "{0} from:{1} to:{2} marshal:{3} source:{4} override:{5}", base.ToString(), From, To, Marshal, Source, Override ); } <|start_filename|>SharpGen/Transform/ConstantManager.cs<|end_filename|> using System; using System.Collections.Generic; using System.Text; using System.Text.RegularExpressions; using System.Threading; using SharpGen.Config; using SharpGen.CppModel; using SharpGen.Model; namespace SharpGen.Transform; public sealed class ConstantManager { private readonly Dictionary<string, List<CsConstantBase>> _mapConstantToCSharpType = new(); private readonly Ioc ioc; public ConstantManager(NamingRulesManager namingRules, Ioc ioc) { NamingRules = namingRules ?? throw new ArgumentNullException(nameof(namingRules)); this.ioc = ioc ?? throw new ArgumentNullException(nameof(ioc)); } private NamingRulesManager NamingRules { get; } private IDocumentationLinker DocumentationLinker => ioc.DocumentationLinker; /// <summary> /// Adds a list of constant gathered from macros/guids to a C# type. /// </summary> public void AddConstantFromMacroToCSharpType(CppElementFinder elementFinder, string macroRegexp, string fullNameCSharpType, string type, string fieldName, string valueMap, Visibility? visibility, string nameSpace, bool isResultDescriptor) { var elementRegex = CppElementExtensions.BuildFindFullRegex(macroRegexp); string ValueMapFactory() { // $0: Name of the C++ macro // $1: Value of the C++ macro // $2: Name of the C# // $3: Name of current namespace StringBuilder sb = new(valueMap, valueMap.Length * 3 / 2); sb.Replace("{", "{{"); sb.Replace("}", "}}"); sb.Replace("$0", "{0}"); sb.Replace("$1", "{1}"); sb.Replace("$2", "{2}"); sb.Replace("$3", "{3}"); return sb.ToString(); } Lazy<string> valueMapProcessed = valueMap is null ? null : new(ValueMapFactory, LazyThreadSafetyMode.None); foreach (var macroDef in elementFinder.Find<CppConstant>(elementRegex)) { AddConstant( macroDef, isResultDescriptor ? name => new CsResultConstant(macroDef, name, macroDef.Value, nameSpace) : name => new CsExpressionConstant(macroDef, name, FindType(macroDef), MapValue(macroDef, name, macroDef.Value)) ); } foreach (var guidDef in elementFinder.Find<CppGuid>(elementRegex)) { var constantType = string.IsNullOrEmpty(type) ? ioc.TypeRegistry.ImportNonPrimitiveType(typeof(Guid)) : ioc.TypeRegistry.ImportType(type); AddConstant( guidDef, constantType is CsFundamentalType {IsGuid: true} ? name => new CsGuidConstant(guidDef, name, guidDef.Guid) : name => new CsExpressionConstant(guidDef, name, constantType, MapValue(guidDef, name, guidDef.Guid.ToString())) ); } void AddConstant(CppElement cppDef, ConstantCreatorDelegate creator) { var finalFieldName = fieldName == null ? cppDef.Name : NamingRules.ConvertToPascalCase( Regex.Replace(cppDef.Name, macroRegexp, fieldName), NamingFlags.Default ); var constant = AddConstantToCSharpType( cppDef, fullNameCSharpType, finalFieldName, creator ); if (visibility is { } visibilityValue) constant.Visibility = visibilityValue; } string MapValue(CppElement cppDef, string finalFieldName, string value) => valueMap is null ? value : string.Format(valueMapProcessed!.Value, cppDef.Name, value, finalFieldName, nameSpace); CsTypeBase FindType(CppConstant constant) => ioc.TypeRegistry.ImportType( string.IsNullOrEmpty(type) ? constant.TypeName : type ); } private delegate CsConstantBase ConstantCreatorDelegate(string csName); /// <summary> /// Adds a specific C++ constant name/value to a C# type. /// </summary> /// <param name="cppElement">The C++ element to get the constant from.</param> /// <param name="csClassName">Name of the C# class to receive this constant.</param> /// <param name="fieldName">Name of the field.</param> /// <param name="creator"></param> /// <returns>The C# variable declared.</returns> private CsConstantBase AddConstantToCSharpType(CppElement cppElement, string csClassName, string fieldName, ConstantCreatorDelegate creator) { if (!_mapConstantToCSharpType.TryGetValue(csClassName, out var constantDefinitions)) { constantDefinitions = new(); _mapConstantToCSharpType.Add(csClassName, constantDefinitions); } // Check that the constant is not already present foreach (var constantDefinition in constantDefinitions) { if (constantDefinition.CppElementName == cppElement.Name) return constantDefinition; } var constantToAdd = creator(fieldName); constantDefinitions.Add(constantToAdd); DocumentationLinker.AddOrUpdateDocLink(cppElement.Name, constantToAdd.QualifiedName); return constantToAdd; } /// <summary> /// Tries to attach declared constants to this C# type. /// </summary> /// <param name="csType">The C# type</param> public void AttachConstants(CsBase csType) { foreach (var innerElement in csType.Items) AttachConstants(innerElement); var qualifiedName = csType.QualifiedName; if (!_mapConstantToCSharpType.TryGetValue(qualifiedName, out var list)) return; foreach (var constantDef in list) csType.Add(constantDef); } } <|start_filename|>SharpGen/Transform/ExternalDocCommentsReader.cs<|end_filename|> using System.Collections.Generic; using System.Xml; using SharpGen.Model; namespace SharpGen.Transform; public class ExternalDocCommentsReader { public static string GetCodeCommentsXPath(CsBase element) { return $"/comments/comment[@id='{GetExternalDocCommentId(element)}']"; } public ExternalDocCommentsReader(Dictionary<string, XmlDocument> externalCommentsDocuments) { ExternalCommentsDocuments = externalCommentsDocuments; } private Dictionary<string, XmlDocument> ExternalCommentsDocuments { get; } public string GetDocumentWithExternalComments(CsBase element) { string externalDocCommentId = GetExternalDocCommentId(element); foreach (var document in ExternalCommentsDocuments) { foreach (XmlNode topLevelNode in document.Value.ChildNodes) { if (topLevelNode.Name == "comments") { foreach (XmlNode node in topLevelNode.ChildNodes) { if (node.Name == "comment" && node.Attributes["id"].Value == externalDocCommentId) { return document.Key; } } } } } return null; } private static string GetExternalDocCommentId(CsBase element) { return element.CppElementFullName ?? element.QualifiedName; } } <|start_filename|>SharpGen/Generator/IMultiCodeGenerator.cs<|end_filename|> using System.Collections.Generic; using Microsoft.CodeAnalysis; using SharpGen.Model; namespace SharpGen.Generator; public interface IMultiCodeGenerator<in TCsElement, out TSyntax> where TCsElement : CsBase where TSyntax : SyntaxNode { IEnumerable<TSyntax> GenerateCode(TCsElement csElement); } <|start_filename|>SharpGen.Runtime/PlatformDetection.cs<|end_filename|> // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Runtime.InteropServices; namespace SharpGen.Runtime; public static partial class PlatformDetection { private const string NtDll = "ntdll.dll"; private const string Advapi32 = "advapi32.dll"; private const string Kernel32 = "kernel32.dll"; private static volatile bool _isAppContainerProcess; private static volatile bool _isAppContainerProcessInitialized; public static readonly bool IsWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows); public static readonly bool IsItaniumSystemV = RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX); public static bool IsAppContainerProcess { get { if (!_isAppContainerProcessInitialized) { if (IsWindows) { var osVersion = OSVersion; if (osVersion.Major < 6 || osVersion.Major == 6 && osVersion.Minor <= 1) // Windows 7 or older. _isAppContainerProcess = false; else _isAppContainerProcess = HasAppContainerToken(); } else { _isAppContainerProcess = false; } _isAppContainerProcessInitialized = true; } return _isAppContainerProcess; } } } <|start_filename|>SharpGen/Generator/Marshallers/EnumParameterWrapperMarshaller.cs<|end_filename|> using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using SharpGen.Model; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; namespace SharpGen.Generator.Marshallers; internal sealed class EnumParameterWrapperMarshaller : WrapperMarshallerBase { public EnumParameterWrapperMarshaller(Ioc ioc, IMarshaller implementation) : base(ioc, implementation) { } public static bool IsApplicable(CsMarshalBase csElement) => csElement is CsParameter {PublicType: CsEnum}; public override ArgumentSyntax GenerateNativeArgument(CsMarshalCallableBase csElement) { var argument = base.GenerateNativeArgument(csElement); return csElement.PassedByNativeReference ? argument : Argument( CheckedExpression( SyntaxKind.UncheckedExpression, GeneratorHelpers.CastExpression( ParseTypeName(((CsEnum) csElement.PublicType).UnderlyingType.Name), argument.Expression ) ) ); } } <|start_filename|>SharpGen.Runtime/TypeDataRegistrationHelper.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; namespace SharpGen.Runtime; public unsafe ref struct TypeDataRegistrationHelper { private List<IntPtr[]> _pointers; private uint _size; private static readonly uint PointerSize = (uint) IntPtr.Size; private void InitializeIfNeeded() { if (_pointers is not null) return; _pointers = new List<IntPtr[]>(6); _size = 0; } public void Add<T>() where T : ICallbackable => Add(TypeDataStorage.GetSourceVtbl<T>()); public void Add(IntPtr[] vtbl) { InitializeIfNeeded(); Debug.Assert(vtbl is not null); _pointers.Add(vtbl); _size += (uint) vtbl.Length; } public void Register<T>() where T : ICallbackable => TypeDataStorage.Register<T>(RegisterImpl()); internal IntPtr Register(TypeInfo type) { var vtbl = RegisterImpl(); TypeDataStorage.Register(type.GUID, vtbl); return new IntPtr(vtbl); } private void** RegisterImpl() { InitializeIfNeeded(); var nativePointer = (void**) MemoryHelpers.AllocateMemory(PointerSize * _size); var offset = 0; var pointers = _pointers; for (int i = 0, count = pointers.Count; i < count; ++i) { var item = pointers[i]; var length = item.Length; item.CopyTo(new Span<IntPtr>(nativePointer + offset, length)); offset += length; } pointers.Clear(); _size = 0; return nativePointer; } } <|start_filename|>SharpGen.UnitTests/ConfigPreprocessorTests.cs<|end_filename|> using System.IO; using System.Xml; using System.Xml.Linq; using SharpGen.Config; using Xunit; namespace SharpGen.UnitTests; public class ConfigPreprocessorTests { [Fact] public void IfDefIncludesChildrenWhenMacroDefined() { var document = Preprocess( $"<root xmlns:pre='{ConfigFile.XmlNamespace}'><pre:ifdef name='Defined'><child /></pre:ifdef></root>", "Defined" ); Assert.Single(document.Descendants("child")); } private static XDocument Preprocess(string xml, params string[] macros) { using var ppReader = XmlReader.Create(new StringReader(xml)); using var ppWriter = new MemoryStream(); Preprocessor.Preprocess(ppReader, ppWriter, macros); ppWriter.Position = 0; using var stringReader = new StreamReader(ppWriter); return XDocument.Load(stringReader); } [Fact] public void IfDefExcludesChildrenWhenMacroUndefined() { var document = Preprocess( $"<root xmlns:pre='{ConfigFile.XmlNamespace}'><pre:ifdef name='Undefined'><child /></pre:ifdef><child /></root>" ); Assert.Single(document.Descendants("child")); } [Fact] public void IfDefSupportsOrOperator() { var document = Preprocess( $"<root xmlns:pre='{ConfigFile.XmlNamespace}'><pre:ifdef name='Undefined|Defined'><child /></pre:ifdef></root>", "Defined" ); Assert.Single(document.Descendants("child")); } [Fact] public void IfNDefExcludesChildrenWhenMacroDefined() { var document = Preprocess( $"<root xmlns:pre='{ConfigFile.XmlNamespace}'><pre:ifndef name='Defined'><child /></pre:ifndef></root>", "Defined" ); Assert.Empty(document.Descendants("child")); } [Fact] public void IfNDefIncludesChildrenWhenMacroUndefined() { var document = Preprocess( $"<root xmlns:pre='{ConfigFile.XmlNamespace}'><pre:ifndef name='Undefined'><child /></pre:ifndef></root>" ); Assert.Single(document.Descendants("child")); } } <|start_filename|>SharpGen/Generator/MemberSyntaxList.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Syntax; using SharpGen.Model; namespace SharpGen.Generator; internal sealed class MemberSyntaxList : SyntaxListBase<MemberDeclarationSyntax, MemberSyntaxList> { #nullable enable public MemberSyntaxList(Ioc? ioc = null) : base(ioc) { } protected override MemberSyntaxList New => new(ioc); protected override MemberDeclarationSyntax? Coerce<T>(T? value) where T : class => value switch { null => null, MemberDeclarationSyntax member => member, _ => throw new ArgumentOutOfRangeException(nameof(value), value, null) }; protected override IEnumerable<MemberDeclarationSyntax?> GetPlatformSpecificValue<TResult>( IEnumerable<PlatformDetectionType> types, Func<PlatformDetectionType, TResult> syntaxBuilder ) => types.Where(sig => (sig & Config.Platforms) != 0).Select(sig => Coerce(syntaxBuilder(sig))); protected override IEnumerable<MemberDeclarationSyntax?> GetPlatformSpecificValue<TResult>( IEnumerable<PlatformDetectionType> types, Func<PlatformDetectionType, IEnumerable<TResult>> syntaxBuilder ) => types.Where(sig => (sig & Config.Platforms) != 0).SelectMany(syntaxBuilder).Select(Coerce); public void Add<T>(T source, IMemberCodeGenerator<T> generator) where T : CsBase { if (TryAdd<T, MemberDeclarationSyntax, IMemberCodeGenerator<T>>(source, generator)) return; throw new ArgumentOutOfRangeException(nameof(generator)); } [SuppressMessage("ReSharper", "PossibleMultipleEnumeration")] public void AddRange<T>(IEnumerable<T> source, IMemberCodeGenerator<T> generator) where T : CsBase { if (TryAdd<T, MemberDeclarationSyntax, IMemberCodeGenerator<T>>(source, generator)) return; throw new ArgumentOutOfRangeException(nameof(generator)); } #nullable restore } <|start_filename|>SharpGen/Generator/Marshallers/ValueTypeMarshallerBase.cs<|end_filename|> using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using SharpGen.Model; namespace SharpGen.Generator.Marshallers; internal abstract class ValueTypeMarshallerBase : MarshallerBase, IMarshaller { protected ValueTypeMarshallerBase(Ioc ioc) : base(ioc) { } public abstract IEnumerable<StatementSyntax> GenerateManagedToNativeProlog(CsMarshalCallableBase csElement); public IEnumerable<StatementSyntax> GenerateNativeToManagedExtendedProlog(CsMarshalCallableBase csElement) => Enumerable.Empty<StatementSyntax>(); public StatementSyntax GenerateManagedToNative(CsMarshalBase csElement, bool singleStackFrame) => null; public StatementSyntax GenerateNativeToManaged(CsMarshalBase csElement, bool singleStackFrame) => null; public abstract ArgumentSyntax GenerateNativeArgument(CsMarshalCallableBase csElement); public ArgumentSyntax GenerateManagedArgument(CsParameter csElement) => GenerateManagedValueTypeArgument(csElement); public ParameterSyntax GenerateManagedParameter(CsParameter csElement) => GenerateManagedValueTypeParameter(csElement); public StatementSyntax GenerateNativeCleanup(CsMarshalBase csElement, bool singleStackFrame) => null; public abstract FixedStatementSyntax GeneratePin(CsParameter csElement); public bool CanMarshal(CsMarshalBase csElement) => csElement is CsMarshalCallableBase {IsArray: false} value && CanMarshal(value); protected abstract bool CanMarshal(CsMarshalCallableBase csElement); public bool GeneratesMarshalVariable(CsMarshalCallableBase csElement) => false; public TypeSyntax GetMarshalTypeSyntax(CsMarshalBase csElement) => SyntaxFactory.ParseTypeName(GetMarshalType(csElement).QualifiedName); protected abstract CsTypeBase GetMarshalType(CsMarshalBase csElement); } <|start_filename|>SharpGen.Runtime/IEnlightenedDisposable.cs<|end_filename|> namespace SharpGen.Runtime; public interface IEnlightenedDisposable { /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> void CheckAndDispose(bool disposing); } <|start_filename|>SharpGen/Transform/NamingRulesManager.MultipleMarshallable.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using SharpGen.Config; using SharpGen.CppModel; namespace SharpGen.Transform; public sealed partial class NamingRulesManager { /// <summary> /// Renames the specified C++ fields. /// </summary> /// <param name="cppFields">The C++ fields.</param> /// <returns>The C# names of these fields.</returns> public IReadOnlyList<string> Rename(IReadOnlyList<CppField> cppFields) => RenameMarshallableCore(cppFields, PostprocessFieldName); /// <summary> /// Renames the specified C++ parameters. /// </summary> /// <param name="cppParameters">The C++ parameters.</param> /// <returns>The C# names of these parameters.</returns> public IReadOnlyList<string> Rename(IReadOnlyList<CppParameter> cppParameters) => RenameMarshallableCore(cppParameters, PostprocessParameterName); private delegate string PostprocessName<in T>(T element, string name, bool isFinal) where T : CppMarshallable; private static string PostprocessFieldName(CppField element, string name, bool isFinal) => UnKeyword(FixDigitName(name, "Field")); private static string PostprocessParameterName(CppParameter element, string name, bool isFinal) { name = FixDigitName(name, "arg"); if (!isFinal && !char.IsLower(name[0])) name = char.ToLower(name[0]) + name.Substring(1); return UnKeyword(name); } private IReadOnlyList<string> RenameMarshallableCore<T>(IReadOnlyList<T> cppItems, PostprocessName<T> postprocessName) where T : CppMarshallable { if (cppItems == null) throw new ArgumentNullException(nameof(cppItems)); if (postprocessName == null) throw new ArgumentNullException(nameof(postprocessName)); var count = cppItems.Count; var names = new string[count][]; var result = new string[count]; HashSet<string> nameSet = new(); for (var index = 0; index < count; index++) { var cppItem = cppItems[index]; var originalName = cppItem.Name; var tag = cppItem.Rule; var name = RenameCore(originalName, tag, null, out var isFinal, out var isPreempted); if (isFinal) { Debug.Assert(!isPreempted); var finalName = postprocessName(cppItem, name, true); nameSet.Add(finalName); result[index] = finalName; } else { List<string> variantList = new(2); var namingFlags = tag.NamingFlags is { } flags ? flags : NamingFlags.Default; var noPrematureBreak = (namingFlags & NamingFlags.NoPrematureBreak) != 0; string PascalCaseIfNeeded(string name) { if (isPreempted && !noPrematureBreak) return name; return ConvertToPascalCase(name, namingFlags); } if (!isPreempted || noPrematureBreak) { if ((namingFlags & NamingFlags.NoHungarianNotationHandler) == 0) { var originalNameLower = originalName.ToLowerInvariant(); foreach (var prefix in _hungarianNotation) if (prefix.Apply(cppItem, name, originalName, originalNameLower, out var variants)) { variantList.AddRange(variants); break; } } } if (variantList.Count == 0) variantList.Add(name); names[index] = variantList.Select(x => postprocessName(cppItem, PascalCaseIfNeeded(x), false)) .ToArray(); } } Dictionary<string, uint> duplicateCount = new(); string DeduplicateName(string name) { if (nameSet.Add(name)) return name; string newName; do { if (!duplicateCount.TryGetValue(name, out var nameCount)) nameCount = 0; duplicateCount[name] = ++nameCount; newName = name + nameCount; } while (!nameSet.Add(newName)); return newName; } for (var index = 0; index < count; index++) { if (result[index] != null) continue; var nameList = names[index]; switch (nameList.Length) { case < 1: Debug.Fail($"Expected to have non-empty {nameof(nameList)}"); result[index] = "SHARPGEN_FAILURE"; continue; case 1: result[index] = DeduplicateName(nameList[0]); continue; } var withoutDuplicates = nameList.Except(nameSet).ToArray(); result[index] = DeduplicateName( withoutDuplicates.Length switch { >= 1 => withoutDuplicates[0], < 1 => nameList[0] } ); } return result; } } <|start_filename|>SharpGen.Runtime/DisposeBase.Events.cs<|end_filename|> using System; using System.ComponentModel; using System.Runtime.CompilerServices; using System.Threading; namespace SharpGen.Runtime; using EventTable = ConditionalWeakTable<DisposeBase, DisposeEventHandler>; /// <summary> /// Base class for a <see cref="IDisposable"/> class. /// </summary> public abstract partial class DisposeBase { private static readonly EventTable DisposingEventTable = new(); private static readonly EventTable DisposedEventTable = new(); private static readonly ReaderWriterLockSlim DisposingEventLock = new(LockRecursionPolicy.NoRecursion); private static readonly ReaderWriterLockSlim DisposedEventLock = new(LockRecursionPolicy.NoRecursion); [MethodImpl(Utilities.MethodAggressiveOptimization)] private void UpdateEventHandler(EventTable table, DisposeEventHandler value) { #if NETFRAMEWORK || NETSTANDARD1_3 || NETSTANDARD2_0 table.Remove(this); table.Add(this, value); #else table.AddOrUpdate(this, value); #endif } private void AddEventHandler(EventTable table, DisposeEventHandler value, ReaderWriterLockSlim rwLock) { rwLock.EnterWriteLock(); try { if (table.TryGetValue(this, out var handler)) UpdateEventHandler(table, handler + value); else table.Add(this, value); } finally { rwLock.ExitWriteLock(); } } private void RemoveEventHandler(EventTable table, DisposeEventHandler value, ReaderWriterLockSlim rwLock) { rwLock.EnterUpgradeableReadLock(); try { if (!table.TryGetValue(this, out var handler)) return; rwLock.EnterWriteLock(); try { UpdateEventHandler(table, handler - value); } finally { rwLock.ExitWriteLock(); } } finally { rwLock.ExitUpgradeableReadLock(); } } /// <summary> /// Occurs when this instance is starting to be disposed. /// </summary> [EditorBrowsable(EditorBrowsableState.Advanced)] public event DisposeEventHandler Disposing { add => AddEventHandler(DisposingEventTable, value, DisposingEventLock); remove => RemoveEventHandler(DisposingEventTable, value, DisposingEventLock); } /// <summary> /// Occurs when this instance is fully disposed. /// </summary> [EditorBrowsable(EditorBrowsableState.Advanced)] public event DisposeEventHandler Disposed { add => AddEventHandler(DisposedEventTable, value, DisposedEventLock); remove => RemoveEventHandler(DisposedEventTable, value, DisposedEventLock); } private void InvokeDisposeEventHandler(bool disposing, ReaderWriterLockSlim rwLock, EventTable table) { DisposeEventHandler value; rwLock.EnterReadLock(); try { table.TryGetValue(this, out value); } finally { rwLock.ExitReadLock(); } value?.Invoke(this, disposing); } } <|start_filename|>SharpGen/Model/CsConstantBase.cs<|end_filename|> using SharpGen.CppModel; namespace SharpGen.Model; public abstract class CsConstantBase : CsBase { protected CsConstantBase(CppElement cppElement, string name) : base(cppElement, name) { } } <|start_filename|>SharpGen/Transform/EnumTransform.cs<|end_filename|> // Copyright (c) 2010-2014 SharpDX - <NAME> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System.Linq; using SharpGen.CppModel; using SharpGen.Logging; using SharpGen.Model; namespace SharpGen.Transform; /// <summary> /// Transforms a C++ enum to a C# enum definition. /// </summary> public class EnumTransform : TransformBase<CsEnum, CppEnum>, ITransformPreparer<CppEnum, CsEnum>, ITransformer<CsEnum> { private TypeRegistry TypeRegistry => Ioc.TypeRegistry; private readonly NamespaceRegistry namespaceRegistry; public EnumTransform(NamingRulesManager namingRules, NamespaceRegistry namespaceRegistry, Ioc ioc) : base(namingRules, ioc) { this.namespaceRegistry = namespaceRegistry; } private static string GetTypeNameWithMapping(CppEnum cppEnum) { var rule = cppEnum.Rule; return rule is {MappingType: { } mapType} ? mapType : cppEnum.UnderlyingType; } /// <summary> /// Prepares the specified C++ element to a C# element. /// </summary> /// <param name="cppEnum">The C++ element.</param> /// <returns>The C# element created and registered to the <see cref="TransformManager"/></returns> public override CsEnum Prepare(CppEnum cppEnum) { // Determine enum type. Default is int var typeName = GetTypeNameWithMapping(cppEnum); var underlyingType = TypeRegistry.ImportPrimitiveType(typeName); if (underlyingType == null) { Logger.Error(LoggingCodes.InvalidUnderlyingType, "Invalid type [{0}] for enum [{1}]", typeName, cppEnum); return null; } // Create C# enum CsEnum newEnum = new(cppEnum, NamingRules.Rename(cppEnum), underlyingType); // Get the namespace for this particular include and enum var nameSpace = namespaceRegistry.ResolveNamespace(cppEnum); nameSpace.Add(newEnum); // Bind C++ enum to C# enum TypeRegistry.BindType(cppEnum.Name, newEnum, source: cppEnum.ParentInclude?.Name); return newEnum; } /// <summary> /// Maps a C++ Enum to a C# enum. /// </summary> /// <param name="newEnum">the C# enum.</param> public override void Process(CsEnum newEnum) { var cppEnum = (CppEnum) newEnum.CppElement; // Find Root Name of this enum // All enum items should start with the same root name and the root name should be at least 4 chars string rootName = cppEnum.Name; string rootNameFound = null; bool isRootNameFound = false; for (int i = rootName.Length; i >= 4 && !isRootNameFound; i--) { rootNameFound = rootName.Substring(0, i); isRootNameFound = true; foreach (var cppEnumItem in cppEnum.EnumItems) { if (!cppEnumItem.Name.StartsWith(rootNameFound)) { isRootNameFound = false; break; } } } if (isRootNameFound) rootName = rootNameFound; // Create enum items for enum foreach (var cppEnumItem in cppEnum.EnumItems) { var enumName = NamingRules.Rename(cppEnumItem, rootName); var enumValue = cppEnumItem.Value; var csharpEnumItem = new CsEnumItem(cppEnumItem, enumName, enumValue); newEnum.Add(csharpEnumItem); } var rule = cppEnum.Rule; // Add None if necessary const string noneElementName = "None"; bool tryToAddNone; if (rule.EnumHasNone is { } addNone) tryToAddNone = addNone; else if (newEnum.IsFlag) tryToAddNone = newEnum.EnumItems.All(item => item.Name != noneElementName); else tryToAddNone = false; if (tryToAddNone) { var csharpEnumItem = new CsEnumItem(null, noneElementName, "0") { CppElementName = noneElementName, Description = "Synthetic NONE value" }; newEnum.Add(csharpEnumItem); } } } <|start_filename|>SdkTests/Interface/NativeInterface.cs<|end_filename|> namespace Interface; public partial interface NativeInterface { MyValue Value { get; } } <|start_filename|>SdkTests/Functions/RelationTests.cs<|end_filename|> using System; using System.Linq; using SharpGen.Runtime; using Xunit; namespace Functions; public class RelationTests { [Fact] public void ValueType() { var test = new [] { new SimpleStruct {I = 1}, new SimpleStruct {I = 2}, new SimpleStruct {I = 3} }; Assert.Equal(6, NativeFunctions.Sum(test)); } [Fact] public void OutBoolArray() { var array = new bool[5]; NativeFunctions.InitBoolArray(array); Assert.All(array, x => Assert.True(x)); } [Fact] public void InterfaceOutArrays() { int num = 3; Interface[] results = new Interface[num]; NativeFunctions.GetInterfacesWithRelation(results); foreach (var result in results) { result.Method(); } } [Fact] public void InterfaceInArrays() { Interface[] results = new Interface[4]; NativeFunctions.GetInterfacesWithRelation(results); NativeFunctions.InInterfaceArray(results); } [Fact] public void StructWithMarshallingArrays() { int seed = 37; var rng = new Random(seed); StructWithMarshal[] array = new StructWithMarshal[5]; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array[i].I.Length; j++) { array[i].I[j] = rng.Next(); } } int result = NativeFunctions.SumStructWithMarshal(array); Assert.Equal(array.SelectMany(x => x.I).Aggregate((x, a) => x + a), result); } [Fact] public void ReservedParameter() { Assert.True(NativeFunctions.VerifyReservedParam()); } } <|start_filename|>SharpGen.Runtime/IExceptionCallback.cs<|end_filename|> using System; namespace SharpGen.Runtime; public interface IExceptionCallback { void RaiseException(Exception e); } <|start_filename|>SharpGen/Generator/Marshallers/InterfaceMarshaller.cs<|end_filename|> using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using SharpGen.Model; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; namespace SharpGen.Generator.Marshallers; internal sealed class InterfaceMarshaller : MarshallerBase, IMarshaller { public bool CanMarshal(CsMarshalBase csElement) => csElement.IsInterface && !csElement.IsArray; public ArgumentSyntax GenerateManagedArgument(CsParameter csElement) { var arg = Argument(IdentifierName(csElement.Name)); if (csElement.IsOut && !csElement.IsFast) return arg.WithRefOrOutKeyword(Token(SyntaxKind.OutKeyword)); if (csElement.IsRef || csElement.IsRefIn) return arg.WithRefOrOutKeyword(Token(SyntaxKind.RefKeyword)); return arg; } public ParameterSyntax GenerateManagedParameter(CsParameter csElement) { var param = Parameter(Identifier(csElement.Name)); TypeSyntax type; if (csElement.IsOut && csElement.IsFast) { type = ParseTypeName(csElement.PublicType.GetNativeImplementationQualifiedName()); } else { type = ParseTypeName(csElement.PublicType.QualifiedName); if (csElement.IsOut) { param = param.AddModifiers(Token(SyntaxKind.OutKeyword)); } else if (csElement.IsRef || csElement.IsRefIn) { param = param.AddModifiers(Token(SyntaxKind.RefKeyword)); } } return param.WithType(type); } public StatementSyntax GenerateManagedToNative(CsMarshalBase csElement, bool singleStackFrame) => MarshalInterfaceInstanceToNative( csElement, IdentifierName(csElement.Name), GetMarshalStorageLocation(csElement) ); public IEnumerable<StatementSyntax> GenerateManagedToNativeProlog(CsMarshalCallableBase csElement) { yield return LocalDeclarationStatement( VariableDeclaration( IntPtrType, SingletonSeparatedList( VariableDeclarator( GetMarshalStorageLocationIdentifier(csElement), default, EqualsValueClause(IntPtrZero) ) ) ) ); } public ArgumentSyntax GenerateNativeArgument(CsMarshalCallableBase csElement) => Argument( csElement.IsOut ? PrefixUnaryExpression(SyntaxKind.AddressOfExpression, GetMarshalStorageLocation(csElement)) : GeneratorHelpers.CastExpression(VoidPtrType, GetMarshalStorageLocation(csElement)) ); public StatementSyntax GenerateNativeCleanup(CsMarshalBase csElement, bool singleStackFrame) => GenerateGCKeepAlive(csElement); public StatementSyntax GenerateNativeToManaged(CsMarshalBase csElement, bool singleStackFrame) => MarshalInterfaceInstanceFromNative( csElement, IdentifierName(csElement.Name), GetMarshalStorageLocation(csElement) ); public IEnumerable<StatementSyntax> GenerateNativeToManagedExtendedProlog(CsMarshalCallableBase csElement) => Enumerable.Empty<StatementSyntax>(); public FixedStatementSyntax GeneratePin(CsParameter csElement) => null; public bool GeneratesMarshalVariable(CsMarshalCallableBase csElement) => true; public TypeSyntax GetMarshalTypeSyntax(CsMarshalBase csElement) => IntPtrType; public InterfaceMarshaller(Ioc ioc) : base(ioc) { } }
jkoritzinsky/SharpGenTools
<|start_filename|>include/caffe/layers/bilinear_layer.hpp<|end_filename|> /* Copyright ©2016. The Regents of the University of California (Regents). All Rights Reserved. Permission to use, copy, modify, and distribute this software and its documentation for educational, research, not-for-profit, and commercial purposes (such rights not subject to transfer), without fee, and without a signed licensing agreement, is hereby granted, provi ded that the above copyright notice, this paragraph and the following two paragraphs appear in all copies, modifications, and distributions. Contact The Office of Technology Licensi ng, UC Berkeley, 2150 Shattuck Avenue, Suite 510, Berkeley, CA 94720-1620, (510) 643-7201, for commercial licensing opportunities. <NAME>, University of California, Berkeley. IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE AND ACCOMP ANYING DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. */ #ifndef CAFFE_BILINEAR_LAYER_HPP_ #define CAFFE_BILINEAR_LAYER_HPP_ #include <vector> #include "caffe/blob.hpp" #include "caffe/layer.hpp" #include "caffe/proto/caffe.pb.h" namespace caffe { /** * @brief Computes @f$ y = \sum_p flatten(x_{1p} x_{2p}^T) @f$, * where p is the spatial index. The "flatten" operation * convert a matrix to a vector. * * @param bottom input Blob vector (length 2) * -# @f$ (N \times C_1 \times H \times W) @f$ * the inputs @f$ x_1 @f$ * -# @f$ (N \times C_2 \times H \times W) @f$ * the inputs @f$ x_2 @f$ * @param top output Blob vector (length 1) * -# @f$ (N \times C_1C_2 \times 1 \times 1) @f$ * the bilinear pooled vector @f$ y @f$ */ template<typename Dtype> class BilinearLayer: public Layer<Dtype> { public: explicit BilinearLayer(const LayerParameter& param) : Layer<Dtype>(param) { } virtual void LayerSetUp(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual void Reshape(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual inline const char* type() const { return "Bilinear"; } virtual inline int ExactNumBottomBlobs() const { return 2; } virtual inline int ExactNumTopBlobs() const { return 1; } protected: /// @copydoc BilinearLayer virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); /** * @brief Computes the error gradient w.r.t. the bilinear inputs. * * @param top output Blob vector (length 1), providing the error gradient with * respect to the outputs * -# @f$ (N \times C \times 1 \times 1) @f$ * containing error gradients @f$ \frac{\partial E}{\partial y} @f$ * with respect to computed outputs @f$ y @f$ * @param propagate_down see Layer::Backward. * @param bottom input Blob vector (length 2) * -# @f$ (N \times C_1/C_2 \times H \times W) @f$ * the inputs @f$ x_1/x_2 @f$; Backward fills their diff with * gradients if propagate_down[0] */ virtual void Backward_cpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom); virtual void Backward_gpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom); }; } // namespace caffe #endif // CAFFE_BILINEAR_LAYER_HPP_ <|start_filename|>src/caffe/layers/bilinear_layer.cu<|end_filename|> /* Copyright ©2016. The Regents of the University of California (Regents). All Rights Reserved. Permission to use, copy, modify, and distribute this software and its documentation for educational, research, not-for-profit, and commercial purposes (such rights not subject to transfer), without fee, and without a signed licensing agreement, is hereby granted, provi ded that the above copyright notice, this paragraph and the following two paragraphs appear in all copies, modifications, and distributions. Contact The Office of Technology Licensi ng, UC Berkeley, 2150 Shattuck Avenue, Suite 510, Berkeley, CA 94720-1620, (510) 643-7201, for commercial licensing opportunities. <NAME>, University of California, Berkeley. IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE AND ACCOMP ANYING DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. */ #include <vector> #include "caffe/layers/bilinear_layer.hpp" #include "caffe/util/math_functions.hpp" namespace caffe { template<typename Dtype> void BilinearLayer<Dtype>::Forward_gpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { Dtype* top_data = top[0]->mutable_gpu_data(); const Dtype* bottom_data_0 = bottom[0]->gpu_data(); const Dtype* bottom_data_1 = bottom[1]->gpu_data(); const int step_top = top[0]->count(1); const int step_bottom_0 = bottom[0]->count(1); const int step_bottom_1 = bottom[1]->count(1); for (int b = 0; b < bottom[0]->shape(0); ++b) { // bottom0: C1*hw; bottom1: C2*hw; // will compute bottom0*bottom1' caffe_gpu_gemm<Dtype>(CblasNoTrans, CblasTrans, bottom[0]->shape(1), bottom[1]->shape(1), bottom[0]->count(2), Dtype(1.0), bottom_data_0 + b * step_bottom_0, bottom_data_1 + b * step_bottom_1, Dtype(0.0), top_data + b * step_top); } } template<typename Dtype> void BilinearLayer<Dtype>::Backward_gpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) { if ((!propagate_down[0]) && (!propagate_down[1])) return; // process the same bottom case // when the two bottoms are the same, one propagate down requires the other vector<bool> pd = propagate_down; if (bottom[0] == bottom[1]) pd[0] = pd[1] = true; const Dtype* top_diff = top[0]->gpu_diff(); Dtype* bottom_diff[2] = { bottom[0]->mutable_gpu_diff(), bottom[1] ->mutable_gpu_diff() }; const Dtype* bottom_data[2] = { bottom[0]->gpu_data(), bottom[1]->gpu_data() }; const int step_top = top[0]->count(1); const int step_bottom[2] = { bottom[0]->count(1), bottom[1]->count(1) }; for (int b = 0; b < bottom[0]->shape(0); ++b) { for (int i = 0; i < 2; ++i) if (pd[i]) { // partial{L}/partial{bottomI} = // partial{L}/partial{y} * partial{y}/partial{bottomI} = // partial{L}/partial{y} * bottomJ // has to deal with the bottom[0]==bottom[1] case if ((bottom[0] == bottom[1]) && (i == 1)) { // then multiply the output by 2 caffe_gpu_scal<Dtype>(step_bottom[0], Dtype(2.0), bottom_diff[0] + b * step_bottom[0]); continue; } // top shape: C1*C2; For i==0, second is C2*hw, output is C1*hw CBLAS_TRANSPOSE TransTop = ((i == 0) ? CblasNoTrans : CblasTrans); caffe_gpu_gemm<Dtype>(TransTop, CblasNoTrans, bottom[i]->shape(1), bottom[0]->count(2), bottom[1 - i]->shape(1), Dtype(1.0), top_diff + b * step_top, bottom_data[1 - i] + b * step_bottom[1 - i], Dtype(0.0), bottom_diff[i] + b * step_bottom[i]); } } } INSTANTIATE_LAYER_GPU_FUNCS(BilinearLayer); } // namespace caffe <|start_filename|>include/caffe/layers/compact_bilinear_layer.hpp<|end_filename|> /* Copyright ©2016. The Regents of the University of California (Regents). All Rights Reserved. Permission to use, copy, modify, and distribute this software and its documentation for educational, research, not-for-profit, and commercial purposes (such rights not subject to transfer), without fee, and without a signed licensing agreement, is hereby granted, provi ded that the above copyright notice, this paragraph and the following two paragraphs appear in all copies, modifications, and distributions. Contact The Office of Technology Licensi ng, UC Berkeley, 2150 Shattuck Avenue, Suite 510, Berkeley, CA 94720-1620, (510) 643-7201, for commercial licensing opportunities. <NAME>, University of California, Berkeley. IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE AND ACCOMP ANYING DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. */ #ifndef CAFFE_COMPACT_BILINEAR_LAYER_HPP_ #define CAFFE_COMPACT_BILINEAR_LAYER_HPP_ #ifndef CPU_ONLY #include <cufft.h> #endif #include <vector> #include "caffe/blob.hpp" #include "caffe/layer.hpp" #include "caffe/proto/caffe.pb.h" #include "caffe/util/_kiss_fft_guts.h" #include "caffe/util/kiss_fftr.h" namespace caffe { template<typename Dtype> struct CaffeComplex { Dtype x; Dtype y; }; /** * @brief Computes @f$ y = compact_bilinear(x_1, x_2) @f$ * By default, we do spatial sum pooling. One could specify * in parameter, such that it doesn't pool spatially. * This implementation don't support learning the random * weights. Since in practice, it doesn't improve performance. * The weights were generated using a fixed random seed. * * @param bottom input Blob vector (length 2) * -# @f$ (N \times C_1 \times H \times W) @f$ * the inputs @f$ x_1 @f$ * -# @f$ (N \times C_2 \times H \times W) @f$ * the inputs @f$ x_2 @f$ * the two inputs could be the same blob * @param top output Blob vector (length 1) * -# @f$ (N \times num_output \times 1(H) \times 1(W)) @f$ * the compact bilinear pooled vector @f$ y @f$ * the output dimension depends on whether to have spatial * sum pooling (sum_pool). * num_output is the parameter required to be specified. */ template<typename Dtype> class CompactBilinearLayer: public Layer<Dtype> { public: explicit CompactBilinearLayer(const LayerParameter& param) : Layer<Dtype>(param) { } virtual void LayerSetUp(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual void Reshape(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual ~CompactBilinearLayer(); virtual inline const char* type() const { return "CompactBilinear"; } virtual inline int ExactNumBottomBlobs() const { return 2; } virtual inline int ExactNumTopBlobs() const { return 1; } protected: /// @copydoc CompactBilinearLayer virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual void Backward_cpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom); virtual void Backward_gpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom); // parameters cache int num_output_; bool sum_pool_; // internal data // random but fixed weights Blob<int> randh_[2]; Blob<Dtype> rands_[2]; // CPU kiss_fft execution plans kiss_fftr_cfg fft_cfg_noinv; kiss_fftr_cfg fft_cfg_inverse; float* buf_float; // the length of fft after the R2C transform // ==floor(1.0*num_output_/2)+1 int num_complex_out; #ifndef CPU_ONLY // whether the GPU specific caches have been initialized. bool plan_init; // the internal GPU batch size to do the compact bilinear transform int batchsz; // cufft plans cufftHandle plan_noinv_batch; cufftHandle plan_noinv_1; cufftHandle plan_inv_batch; cufftHandle plan_inv_1; // all one constant vector for spatial sum pooling Dtype* ones_hw; #endif // some internal helpers private: // CPU helpers void CPUCountAndTranspose(const Blob<int>& randh, const Blob<Dtype>& rands, const Dtype* bottom, Dtype* top, const int hw, Dtype* temptop); // GPU helpers void caffe_gpu_fft(const int batchlen, const int hw, const int nfft, const Dtype* src, CaffeComplex<Dtype>* output); void caffe_gpu_ifft(const int batchlen, const int hw, const int nfft, const CaffeComplex<Dtype>* src, Dtype* output); void Initializations(const int hw); }; } // namespace caffe #endif // CAFFE_COMPACT_BILINEAR_LAYER_HPP_
Jiawei-Gu/caffe_20170919
<|start_filename|>menu/menu.js<|end_filename|> 'use strict'; module.exports = function(electronApp, menuState) { return [ { label: 'Toggle Overlay', accelerator: 'Alt+Y', enabled: function() { return menuState.bpmn; }, action: function() { electronApp.emit('menu:action', 'togglePropertyOverlays'); } } ]; }; <|start_filename|>client/client.js<|end_filename|> var registerBpmnJSPlugin = require('camunda-modeler-plugin-helpers').registerBpmnJSPlugin; var plugin = require('./PropertyInfoPlugin'); registerBpmnJSPlugin(plugin); <|start_filename|>client/PropertyInfoPlugin.js<|end_filename|> 'use strict'; var _ = require('lodash'); var elementOverlays = []; var overlaysVisible = true; function PropertyInfoPlugin(eventBus, overlays, elementRegistry, editorActions) { eventBus.on('shape.changed', function (event) { _.defer(function () { changeShape(event); }); }); eventBus.on('shape.removed', function (event) { var element = event.element; _.defer(function () { removeShape(element); }); }); eventBus.on('shape.added', function (event) { _.defer(function () { changeShape(event); }); }); editorActions.register({ togglePropertyOverlays: function () { toggleOverlays(); } }); function changeShape(event) { var element = event.element; if (!(element.businessObject.$instanceOf('bpmn:FlowNode') || element.businessObject.$instanceOf('bpmn:Participant'))) { return; } _.defer(function () { addStyle(element); }); } function removeShape(element) { var elementObject = elementOverlays[element.id]; for (var overlay in elementObject) { overlays.remove(elementObject[overlay]); } delete elementOverlays[element.id]; } function toggleOverlays() { if (overlaysVisible) { overlaysVisible = false; if (elementOverlays !== undefined) { for (var elementCount in elementOverlays) { var elementObject = elementOverlays[elementCount]; for (var overlay in elementObject) { overlays.remove(elementObject[overlay]); } } } } else { overlaysVisible = true; var elements = elementRegistry.getAll(); for (var elementCount in elements) { var elementObject = elements[elementCount]; if (elementObject.businessObject.$instanceOf('bpmn:FlowNode') || elementObject.businessObject.$instanceOf('bpmn:Participant')) { addStyle(elementObject); } } } } function addStyle(element) { if (elementOverlays[element.id] !== undefined && elementOverlays[element.id].length !== 0) { for (var overlay in elementOverlays[element.id]) { overlays.remove(elementOverlays[element.id][overlay]); } } elementOverlays[element.id] = []; if( element.businessObject.documentation !== undefined && element.businessObject.documentation.length > 0 && element.businessObject.documentation[0].text.trim() !== "" && element.type !== "label"){ var text = element.businessObject.documentation[0].text; text = text.replace(/(?:\r\n|\r|\n)/g, '<br />'); elementOverlays[element.id].push( overlays.add(element, 'badge', { position: { top: 4, right: 4 }, html: '<div class="doc-val-true" data-badge="D"></div><div class="doc-val-hover" data-badge="D">'+text+'</div>' })); } if (element.businessObject.extensionElements === undefined && element.businessObject.$instanceOf('bpmn:FlowNode')) { return; } //Do not process the label of an element if (element.type === "label") { return; } if (!overlaysVisible) { return; } var badges = []; if(element.businessObject.$instanceOf('bpmn:Participant')) { var extensionElements = element.businessObject.processRef.extensionElements; var extensions = (extensionElements === undefined ? [] : extensionElements.values); var type = '&#9654;'; var background = 'badge-green'; if(element.businessObject.processRef.isExecutable === false) { type = '&#10074;&#10074;'; background = 'badge-red'; } badges.push({ badgeKey: 'isExecutable', badgeSort: 0, badgeType: type, badgeBackground: background, badgeLocation: 'left' }); } else { var extensions = element.businessObject.extensionElements.values; } for (var extension in extensions) { var type = ''; var background = ''; var location = 'right'; var sort = 0; var key = ''; switch (extensions[extension].$type) { case 'camunda:ExecutionListener': if (extensions[extension].event === 'start') { location = 'left'; key = 'camunda:ExecutionListener-start'; sort = 20; } else { location = 'right'; key = 'camunda:ExecutionListener-end'; sort = 70; } type = 'L'; background = 'badge-green'; break; case 'camunda:Properties': key = 'camunda:Properties'; sort = 80; type = 'E'; background = 'badge-violet'; break; case 'camunda:TaskListener': if (extensions[extension].event === 'create' || extensions[extension].event === 'assignment') { location = 'left'; key = 'camunda:TaskListener-start'; sort = 21; } else { location = 'right'; key = 'camunda:TaskListener-end'; sort = 71; } type = 'T'; background = 'badge-green'; break; case 'camunda:InputOutput': background = 'badge-blue'; break; case 'camunda:In': type = 'V'; key = 'camunda:In'; location = 'left'; sort = 10; background = 'badge-blue'; break; case 'camunda:Out': type = 'V'; key = 'camunda:Out'; location = 'right'; sort = 60; background = 'badge-blue'; break; case 'camunda:Field': key = 'camunda:Field'; sort = 90; type = 'F'; background = 'badge-red'; break; } if (extensions[extension].$type === 'camunda:InputOutput') { if (extensions[extension].hasOwnProperty('inputParameters') && extensions[extension].inputParameters.length > 0) { location = 'left'; type = 'I'; key = 'camunda:InputOutput-input'; sort = 10; badges.push({ badgeKey: key, badgeSort: sort, badgeType: type, badgeBackground: background, badgeLocation: location }); } if (extensions[extension].hasOwnProperty('outputParameters') && extensions[extension].outputParameters.length > 0) { location = 'right'; type = 'O'; key = 'camunda:InputOutput-output'; sort = 60; badges.push({ badgeKey: key, badgeSort: sort, badgeType: type, badgeBackground: background, badgeLocation: location }); } } else { if (key !== '') { badges.push({ badgeKey: key, badgeSort: sort, badgeType: type, badgeBackground: background, badgeLocation: location }); } } } addOverlays(badges, element); } function addOverlays(badgeList, element) { var badges = []; var leftCounter = 0; var rightCounter = 0; var sortedBadgeList = uniqBy(badgeList, function (item) { return item.badgeKey }); sortedBadgeList.sort(function (a, b) { return a.badgeSort - b.badgeSort; }); for (var overlayCounter in sortedBadgeList) { var overlayObject = sortedBadgeList[overlayCounter]; if (overlayObject.badgeLocation === 'left') { badges.push(overlays.add(element, 'badge', { position: { bottom: 0, left: leftCounter }, html: '<div class="badge ' + overlayObject.badgeBackground + '" data-badge="' + overlayObject.badgeType + '"></div>' })); leftCounter = leftCounter + 16; } else { badges.push(overlays.add(element, 'badge', { position: { bottom: 0, right: rightCounter }, html: '<div class="badge ' + overlayObject.badgeBackground + '" data-badge="' + overlayObject.badgeType + '"></div>' })); rightCounter = rightCounter + 16; } } pushArray(elementOverlays[element.id],badges); } function uniqBy(a, key) { var seen = {}; return a.filter(function (item) { var k = key(item); return seen.hasOwnProperty(k) ? false : (seen[k] = true); }) } function pushArray(list, other) { var len = other.length; var start = list.length; list.length = start + len; for (var i = 0; i < len; i++ , start++) { list[start] = other[i]; } } } PropertyInfoPlugin.$inject = ['eventBus', 'overlays', 'elementRegistry', 'editorActions']; module.exports = { __init__: ['clientPlugin'], clientPlugin: ['type', PropertyInfoPlugin] }; <|start_filename|>package.json<|end_filename|> { "name": "camunda-modeler-property-info-plugin", "version": "0.0.1", "description": "This plugin serves a better overview which properties are set per shape.", "main": "index.js", "scripts": { "build": "browserify client/client.js > client/client-bundle.js", "auto-build": "watchify client/client.js -o client/client-bundle.js" }, "repository": { "type": "git", "url": "git+https://github.com/umb/camunda-modeler-property-info-plugin.git" }, "keywords": [ "camunda", "modeler", "plugin", "properties" ], "author": "<NAME>", "license": "Apache License 2.0", "bugs": { "url": "https://github.com/umb/camunda-modeler-property-info-plugin/issues" }, "homepage": "https://github.com/umb/camunda-modeler-property-info-plugin#readme", "devDependencies": { "browserify": "^14.1.0", "camunda-modeler-plugin-helpers": "^1.7.0", "watchify": "^3.9.0" }, "dependencies": { "lodash": "^3.0.0" } }
sharedchains/camunda-modeler-property-info-plugin
<|start_filename|>__metadata.js<|end_filename|> export const name = "PostCSS"; /** @typedef {{ autoprefixer: boolean }} Options */ /** @type {import("../..").AdderOptions<Options>} */ export const options = { autoprefixer: { context: "https://github.com/postcss/autoprefixer", default: true, question: "Do you want to use Autoprefixer?", }, }; <|start_filename|>__detect.js<|end_filename|> import { extension } from "./stuff.js"; /** @type {import("../..").Heuristic[]} */ export const heuristics = [ { description: "`svelte-preprocess` reads PostCSS config implicitly in `svelte.config.js`", async detector({ readFile }) { const js = await readFile({ path: "/svelte.config.js" }); const cjs = await readFile({ path: "/svelte.config.cjs" }); /** @param {string} text */ const preprocessIsProbablySetup = (text) => { if (!text.includes("svelte-preprocess")) return false; return true; }; if (js.exists) return preprocessIsProbablySetup(js.text); else if (cjs.exists) return preprocessIsProbablySetup(cjs.text); return false; }, }, { description: "`postcss.config.cjs` exists and `postcss.config.js` does not exist", async detector({ readFile }) { const cjs = await readFile({ path: "/postcss.config.cjs" }); const js = await readFile({ path: "/postcss.config.js" }); return cjs.exists && !js.exists; }, }, { description: `\`src/app.${extension}\` exists`, async detector({ readFile }) { const postcss = await readFile({ path: `/src/app.${extension}` }); return postcss.exists; }, }, { description: "The main file (`src/routes/__layout.svelte` for SvelteKit, `src/main.js` or `src/main.ts` for Vite) imports `src/app.postcss`", async detector({ folderInfo, readFile }) { if (folderInfo.kit) { const { text } = await readFile({ path: "/src/routes/__layout.svelte" }); return text.includes(`../app.${extension}`); } const ts = await readFile({ path: "/src/main.ts" }); if (ts.exists) return ts.text.includes(`./app.${extension}`); const js = await readFile({ path: "/src/main.js" }); return js.text.includes(`./app.${extension}`); }, }, ]; <|start_filename|>__run.js<|end_filename|> import { setupStyleLanguage } from "../../adder-tools.js"; import { addImport, findImport, getConfigExpression, setDefault } from "../../ast-tools.js"; import { extension, postcssConfigCjsPath, stylesHint } from "./stuff.js"; /** * @param {import("../../ast-io.js").RecastAST} postcssConfigAst * @param {boolean} autoprefixer * @returns {import("../../ast-io.js").RecastAST} */ const updatePostcssConfig = (postcssConfigAst, autoprefixer) => { const configObject = getConfigExpression({ cjs: true, typeScriptEstree: postcssConfigAst, }); if (configObject.type !== "ObjectExpression") throw new Error("PostCSS config must be an object"); const pluginsList = setDefault({ default: /** @type {import("estree").ArrayExpression} */ ({ type: "ArrayExpression", elements: [], }), object: configObject, property: "plugins", }); if (pluginsList.type !== "ArrayExpression") throw new Error("`plugins` in PostCSS config must be an array"); if (autoprefixer) { let autoprefixerImportedAs = findImport({ cjs: true, package: "autoprefixer", typeScriptEstree: postcssConfigAst }).require; // Add an Autoprefixer import if it's not there if (!autoprefixerImportedAs) { autoprefixerImportedAs = "autoprefixer"; addImport({ require: autoprefixerImportedAs, cjs: true, package: "autoprefixer", typeScriptEstree: postcssConfigAst }); } pluginsList.elements.push({ type: "Identifier", name: autoprefixerImportedAs, }); } return postcssConfigAst; }; /** @type {import("../../index.js").AdderRun<import("./__metadata.js").Options>} */ export const run = async ({ folderInfo, install, options, updateCss, updateJavaScript, updateSvelte }) => { await setupStyleLanguage({ extension, folderInfo, mutateSveltePreprocessArgs() {}, stylesHint, updateCss, updateJavaScript, updateSvelte, }); await updateJavaScript({ path: postcssConfigCjsPath, async script({ typeScriptEstree }) { return { typeScriptEstree: updatePostcssConfig(typeScriptEstree, options.autoprefixer), }; }, }); await install({ package: "svelte-preprocess" }); if (options.autoprefixer) await install({ package: "autoprefixer" }); }; <|start_filename|>stuff.js<|end_filename|> export const extension = "css"; export const postcssConfigCjsPath = "/postcss.config.cjs"; export const stylesHint = "Write your global styles here, in PostCSS syntax";
svelte-add/postcss
<|start_filename|>Q-ComplexNumber.html<|end_filename|> <!DOCTYPE html> <html> <head> <title>Q ⟩ ComplexNumber</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width,initial-scale=1.0"> <meta name="description" content="Quantum computing in your browser."> <meta name="copyright" content="<NAME> 2019–2020"> <meta name="keywords" content=" Q, Q.js, Q-js, Qjs, quantum JavaScript, quantum, quantum physics, quantum mechanics, superposition, quantum computer, quantum computer programming, quantum computing, QC, quantum simulator, quantum computer simulator, qubit, qbit, gate, Hadamard, Bloch, Bloch Sphere, Web, Web site, website, Web browser, browser, HTML, HTML5, JavaScript, ES6, CSS, Chrome, Firefox, Safari, Opera, Brave, Edge, WebKit, Blink, Gecko, Mozilla, <NAME>, Stewart, Stew, Stuart, Steven, Steve, Stewdio, stewartsmith, stew_rtsmith, @stew_rtsmith, Moar, Moar Technologies Corp, MTC, Google, IBM, Microsoft, Amazon, NASA, DWave, D-Wave, Quil, OpenQASM, ProjectQ, Qiskit, Quantum Development Kit, Cirq, Strawberry Fields, t|ket>, QCL, Quantum pseudocode, Q#, Q|SI>, Q language, qGCL, QFC, QML, LIQUi|>, Quipper, Stanford CS 269 Q: Quantum Computer Programming"> <meta name="twitter:card" content="summary_large_image"> <meta name="twitter:site" content="@stew_rtsmith"> <meta name="twitter:creator" content="@stew_rtsmith"> <meta name="twitter:title" content="Q ⟩ ComplexNumber"> <meta name="twitter:description" content="Quantum computing in your browser."> <meta name="twitter:image" content="https://quantumjavascript.app/assets/Q-website-preview.jpg"> <meta property="og:type" content="website"> <meta property="og:title" content="Q ⟩ ComplexNumber"> <meta property="og:description" content="Quantum computing in your browser."> <meta property="og:image" content="https://quantumjavascript.app/assets/Q-website-preview.jpg"> <meta property="og:url" content="https://quantumjavascript.app/ComplexNumber.html"> <link rel="canonical" href="https://quantumjavascript.app/ComplexNumber.html"> <link href="assets/Q-favicon-064.png" rel="icon" type="image/png"> <link href="assets/Q-favicon-144.png" rel="apple-touch-icon"> <link rel="stylesheet" href="Q/Q.css"> <link rel="stylesheet" href="Q/Q-Circuit-Editor.css"> <link rel="stylesheet" href="assets/documentation.css"> <script src="https://www.googletagmanager.com/gtag/js" async></script> <script src="assets/ga.js"></script> <script src="Q/Q.js"></script> <script src="Q/Q-ComplexNumber.js"></script> <script src="Q/Q-Matrix.js"></script> <script src="Q/Q-Qubit.js"></script> <script src="Q/Q-Gate.js"></script> <script src="Q/Q-History.js"></script> <script src="Q/Q-Circuit.js"></script> <script src="Q/Q-Circuit-Editor.js"></script> <script src="assets/navigation.js"></script> </head> <body> <main class="api"> <p> Source code: <a href="https://github.com/stewdio/q.js/blob/master/source/Q-ComplexNumber.js?ts=4" target="_blank"> <code>Q-ComplexNumber.js</code> </a> </p> <hr> <h3 id="Real_numbers">Real numbers ℝ</h3> <p> Our regular, ordinary, everyday numbers are called <a href="https://en.wikipedia.org/wiki/Real_number" target="_blank">real numbers</a>. These include integers and decimals. You can visualize real numbers as existing along an infinite number line—with zero in the middle, positive numbers counting up forever to infinity on the right, and negative numbers doing the exact opposite on the left. </p> <svg class="complex-plane" viewBox="0 0 600 600"> <use xlink:href="#complex-plane-real"> </svg> <p> When a real number is multiplied by itself the product is always positive. For example, if we choose the number 2 we see that 2 × 2 = 4. Similarly, had we chosen the negative number -2, the product would still be positive because two negative numbers multiplied together also produce a positive result; -2 × -2 = 4. For brevity we could rewrite these equations as 2<sup>2</sup> = 4 and (-2)<sup>2</sup> = 4, respectively. </p> <p> The <a href="https://en.wikipedia.org/wiki/Square_root" target="_blank">square root</a> of a real number has two possible answers. The square root of 4, for example, is both 2 <em>and</em> -2 because both are solutions for <span class="symbol">x</span> in the equation <span class="symbol">x</span> = √4. </p> <h3 id="Imaginary_numbers">Imaginary numbers 𝕀</h3> <p> But suppose we wanted to find the square root of a <em>negative</em> number. Is there any number that could solve for <span class="symbol">x</span> in the equation <span class="symbol">x</span> = √(-4)? Sadly, there is not. Or more precisely: there is not any <em>real</em> solution for the square root of a negative number. </p> <p> In his 1991 address on “Creativity in Management”, Monty Python’s John Cleese articulates <NAME>’s concept of the <a href="https://youtu.be/Pb5oIIPO62g?t=1926" target="_blank">intermediate impossible (32:06)</a> as a useful stepping stone towards a novel and useful solution. <a href="https://en.wikipedia.org/wiki/Imaginary_number" target="_blank">Imaginary numbers</a> might be considered an intermediate impossible. The symbol <span class="symbol">i</span> is defined as the imaginary solution to the equation <span class="symbol">x</span> = √(-1), therefore <span class="symbol">i</span><sup>2</sup> = -1. With this imaginary device we now have a solution to the above equation <span class="symbol">x</span> = √(-4) and that solution is 2<span class="symbol">i</span>. (And also -2<span class="symbol">i</span>, of course! We can indicate this “plus or minus” possibility as ±2<span class="symbol">i</span>.) Let’s inspect this more closely. </p> <pre><code> 𝒙 = √(-4) 𝒙 = √( 4 × -1) 𝒙 = √4 × √(-1) 𝒙 = ±2 × √(-1) 𝒙 = ±2 × <span class="symbol">i</span> 𝒙 = ±2<span class="symbol">i</span> </code></pre> <p> 2<span class="symbol">i</span> is an <a href="https://en.wikipedia.org/wiki/Imaginary_number" target="_blank">imaginary number</a> that consists of a real number multiplier, 2, and our imaginary solution to √(-1), called <span class="symbol">i</span>. Like real numbers, imaginary numbers also exist along an infinite number line. We plotted our real number line horizontally, so let’s plot our imaginary number line vertically. </p> <svg class="complex-plane" viewBox="0 0 600 600"> <use xlink:href="#complex-plane-imaginary"> </svg> <h3 id="Complex_numbers">Complex numbers ℂ</h3> <p> We just saw that multiplying a real number by <span class="symbol">i</span> yields an imaginary number. But what if you <em>add</em> a real number to an imaginary one? Things get <em>complex</em>. A <a href="https://en.wikipedia.org/wiki/Complex_number" target="_blank">complex number</a> is a number that can be expressed in the form <span class="symbol">a</span> + <span class="symbol">bi</span>, where <span class="symbol">a</span> is the real component and <span class="symbol">bi</span> is the imaginary component. Some examples might be 1 + 2<span class="symbol">i</span> or 3 - 4<span class="symbol">i</span>. </p> <svg class="complex-plane" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 600 600" style="enable-background:new 0 0 600 600;" xml:space="preserve"> <style type="text/css"> svg #complex-plane { /*font-family: 'Roboto';*/ /*mix-blend-mode: difference;*/ /*mix-blend-mode: multiply;*/ /*background-blend-mode: screen;*/ stroke-width: 0.5; stroke-miterlimit: 10; } .light { opacity: 0.5; } .lighter { opacity: 0.15; } .lightest { opacity: 0.05; } line.dashed { stroke-dasharray: 1, 3; } line.strong { stroke-width: 1; } .negative-numbers { opacity: 0.25; } #complex-plane-real text, #complex-plane-real rect, #complex-plane-real polygon { fill: var( --Q-color-red ); stroke: none; } #complex-plane-real line { fill: none; stroke: var( --Q-color-red ); } #complex-plane-imaginary text, #complex-plane-imaginary rect, #complex-plane-imaginary polygon { fill: var( --Q-color-blue ); stroke: none; } #complex-plane-imaginary line { fill: none; stroke: var( --Q-color-blue ); } #examples line { fill: none; stroke: var( --Q-color-charcoal ); } </style> <g id="complex-plane-real"> <g id="real-overlays"> <rect class="lightest" x="300" width="300" height="600"/> <rect class="lighter" y="0" width="300" height="600"/> </g> <g id="real-ticks"> <g class="lighter"> <line x1="50" y1="290" x2="50" y2="300"/> <line x1="100" y1="290" x2="100" y2="300"/> <line x1="150" y1="290" x2="150" y2="300"/> <line x1="200" y1="290" x2="200" y2="300"/> <line x1="250" y1="290" x2="250" y2="300"/> </g> <line x1="300" y1="290" x2="300" y2="300"/> <line x1="350" y1="290" x2="350" y2="300"/> <line x1="373" y1="300" x2="373" y2="310"/> <line x1="400" y1="290" x2="400" y2="300"/> <line x1="438" y1="300" x2="438" y2="310"/> <line x1="450" y1="290" x2="450" y2="300"/> <line x1="458" y1="300" x2="458" y2="310"/> <line x1="500" y1="290" x2="500" y2="300"/> <line x1="550" y1="290" x2="550" y2="300"/> <g> <line class="strong" x1="32.2" y1="300" x2="567.8" y2="300"/> <polygon points="33.6,305 25,300 33.6,295"/> <polygon points="566.4,305 575,300 566.4,295"/> </g> <line class="dashed" x1="300" y1="0" x2="300" y2="260"/> <line class="dashed" x1="300" y1="300" x2="300" y2="600"/> </g> <g id="real-numbers"> <text transform="matrix(1 0 0 1 496 282)">4</text> <text transform="matrix(1 0 0 1 546 282)">5</text> <text transform="matrix(1 0 0 1 453 325)" class="symbol">π</text> <text transform="matrix(1 0 0 1 446 282)">3</text> <text transform="matrix(1 0 0 1 433 325)" class="symbol">e</text> <text transform="matrix(1 0 0 1 396 282)">2</text> <text transform="matrix(1 0 0 1 363 328)">√2</text> <text transform="matrix(1 0 0 1 347 282)">1</text> <text transform="matrix(1 0 0 1 296 282)">0</text> <g class="negative-numbers"> <text transform="matrix(1 0 0 1 240 282)">-1</text> <text transform="matrix(1 0 0 1 190 282)">-2</text> <text transform="matrix(1 0 0 1 140 282)">-3</text> <text transform="matrix(1 0 0 1 90 282)">-4</text> <text transform="matrix(1 0 0 1 40 282)">-5</text> </g> </g> </g> <g id="complex-plane-imaginary"> <g id="imaginary-overlays"> <rect class="lightest" width="600" height="300"/> <rect class="lighter" y="300" width="600" height="300"/> </g> <g id="imaginary-ticks"> <line x1="290" y1="50" x2="300" y2="50" /> <line x1="290" y1="100" x2="300" y2="100"/> <line x1="290" y1="150" x2="300" y2="150"/> <line x1="290" y1="200" x2="300" y2="200"/> <line x1="290" y1="250" x2="300" y2="250"/> <line x1="290" y1="300" x2="300" y2="300"/> <g class="lighter"> <line x1="290" y1="350" x2="300" y2="350"/> <line x1="290" y1="400" x2="300" y2="400"/> <line x1="290" y1="450" x2="300" y2="450"/> <line x1="290" y1="500" x2="300" y2="500"/> <line x1="290" y1="550" x2="300" y2="550"/> </g> <g> <line class="strong" x1="300" y1="32.2" x2="300" y2="567.8"/> <polygon points="295,33.6 300,25 305,33.6"/> <polygon points="295,566.4 300,575 305,566.4"/> </g> <line class="dashed" x1="0" y1="300" x2="260" y2="300"/> <line class="dashed" x1="300" y1="300" x2="600" y2="300"/> </g> <g id="imaginary-numbers"> <text transform="matrix(1 0 0 1 270 55)">5<tspan class="symbol">i</tspan></text> <text transform="matrix(1 0 0 1 270 105)">4<tspan class="symbol">i</tspan></text> <text transform="matrix(1 0 0 1 270 205)">2<tspan class="symbol">i</tspan></text> <text transform="matrix(1 0 0 1 270 155)">3<tspan class="symbol">i</tspan></text> <text transform="matrix(1 0 0 1 270 255)">1<tspan class="symbol">i</tspan></text> <text transform="matrix(1 0 0 1 270 305)">0<tspan class="symbol">i</tspan></text> <g class="negative-numbers"> <text transform="matrix(1 0 0 1 263.5 355)">-1<tspan class="symbol">i</tspan></text> <text transform="matrix(1 0 0 1 263.5 405)">-2<tspan class="symbol">i</tspan></text> <text transform="matrix(1 0 0 1 263.5 455)">-3<tspan class="symbol">i</tspan></text> <text transform="matrix(1 0 0 1 263.5 505)">-4<tspan class="symbol">i</tspan></text> <text transform="matrix(1 0 0 1 263.5 555)">-5<tspan class="symbol">i</tspan></text> </g> </g> </g> <g id="examples"> <line class="dashed strong" x1="300" y1="200" x2="350" y2="200"/> <line class="dashed strong" x1="350" y1="265" x2="350" y2="200"/> <circle cx="350" cy="200" r="4"/> <text transform="matrix(1 0 0 1 360 205)">1+2<tspan class="symbol">i</tspan></text> <line class="dashed strong" x1="300" y1="500" x2="450" y2="500"/> <line class="dashed strong" x1="450" y1="300" x2="450" y2="500"/> <circle cx="450" cy="500" r="4"/> <text transform="matrix(1 0 0 1 460 505)">3-4<tspan class="symbol">i</tspan></text> </g> <!-- <use xlink:href="#imaginary-numbers" /> --> <!-- <use xlink:href="#real-numbers" /> --> </svg> <!-- “Quantum Mechanics Concepts: 1 Dirac Notation and Photon Polarisation” https://youtu.be/pBh7Xqbh5JQ?t=352 Maybe someday add the above video’s bits about a^2 + b^2 = c^2 ? --> <p> This is what the <code>ComplexNumber</code> class was created to handle. Open up your JavaScript console and paste in the following: </p> <pre><code> var cat = new <a href="Q.html">Q</a>.ComplexNumber( 1, 2 ), dog = new <a href="Q.html">Q</a>.ComplexNumber( 3, -4 ) cat.<a href="#.prototype.toText">toText</a>()<span class="comment">// Returns '1 + 2i'</span> dog.<a href="#.prototype.toText">toText</a>()<span class="comment">// Returns '3 - 4i'</span> </pre></code> <p> Now we have two variables, <code>cat</code> and <code>dog</code>, that we can operate with. As you might guess, <code>ComplexNumber</code> includes instance methods for common operations like addition, subtraction, multiplication, and division. Try the following lines individually in your JavaScript console: </p> <pre><code> cat.<a href="#.prototype.add">add</a>( dog ).<a href="#.prototype.toText">toText</a>() <span class="comment">// Returns '4 - 2i'</span> cat.<a href="#.prototype.subtract">subtract</a>( dog ).<a href="#.prototype.toText">toText</a>()<span class="comment">// Returns '-2 + 6i'</span> cat.<a href="#.prototype.multiply">multiply</a>( dog ).<a href="#.prototype.toText">toText</a>()<span class="comment">// Returns '11 + 2i'</span> cat.<a href="#.prototype.divide">divide</a>( dog ).<a href="#.prototype.toText">toText</a>() <span class="comment">// Returns '-0.2 + 0.4i'</span> </pre></code> <p> We can now verify that <span class="symbol">i</span><sup>2</sup> = -1. </p> <pre><code> var i = new <a href="Q.html">Q</a>.ComplexNumber( 0, 1 ) i.<a href="#.prototype.toText">toText</a>()<span class="comment">// Returns 'i'</span> i.<a href="#.prototype.power">power</a>( 2 ).<a href="#.prototype.toText">toText</a>()<span class="comment">// Returns '-1'</span> </pre></code> <p> Operation functions on <code>Q.ComplexNumber</code> instances generally accept as arguments both sibling instances and pure <code>Number</code> instances, though the value returned is always an instance of <code>Q.ComplexNumber</code>. </p> <hr> <h3 id="Constructor">Constructor</h3> <p> <span class="constructor">ComplexNumber</span> <code class="value-type">Function([ real: Number or <a href="Q.html">Q</a>.ComplexNumber ][, imaginary: Number ]]) => <a href="Q.html">Q</a>.ComplexNumber</code> <br> Expects zero to two arguments. If the first argument is a <code>ComplexNumber</code> then that value is cloned and any remaining arguments are ignored. If either of the arguments are <code>undefined</code> they are assumed to be zero. If the first argument is not a <code>ComplexNumber</code> and either of the arguments are not <a href="Q-ComplexNumber.html#.isNumberLike">number-like</a> then an error is thrown. </p> <pre><code> var ape = new <a href="Q.html">Q</a>.ComplexNumber(), bee = new <a href="Q.html">Q</a>.ComplexNumber( 1 ), elk = new <a href="Q.html">Q</a>.ComplexNumber( 1, 2 ), fox = new <a href="Q.html">Q</a>.ComplexNumber( elk ) ape.<a href="#.prototype.toText">toText</a>()<span class="comment">// Returns '0'</span> bee.<a href="#.prototype.toText">toText</a>()<span class="comment">// Returns '1'</span> elk.<a href="#.prototype.toText">toText</a>()<span class="comment">// Returns '1 + 2i'</span> fox.<a href="#.prototype.toText">toText</a>()<span class="comment">// Returns '1 + 2i'</span> elk.<a href="#.prototype.isEqualTo">isEqualTo</a>( fox ) <span class="comment">// Returns true</span> elk.<a href="#this.index">index</a> === fox.<a href="#.prototype.index">index</a><span class="comment">// Returns false</span> </pre></code> <ul class="properties"> <li> <dt id="this.real">real</dt> <dd> <code class="value-type">Number</code> Traditionally the first argument, a <a href="Q-ComplexNumber.html#.isNumberLike">number-like</a> value representing the <em>real</em> component of the <a href="Q-ComplexNumber.html#Complex_numbers">complex number</a>. </dd> </li> <li> <dt id="this.imaginary">imaginary</dt> <dd> <code class="value-type">Number</code> Traditionally the second argument, a <a href="Q-ComplexNumber.html#.isNumberLike">number-like</a> value representing the <em>imaginary</em> component of the <a href="Q-ComplexNumber.html#Complex_numbers">complex number</a>. </dd> </li> <li> <dt id="this.index">index</dt> <dd> <code class="value-type">Number</code> An identification number assigned to the instance, used for minding the total number of instances created. </dd> </li> </ul> <hr> <h3>Static properties</h3> <ul class="properties"> <li> <dt id=".help">help</dt> <dd> <code class="value-type">Function ⇒ String</code> Calls and returns the value of <code><a href="Q.html">Q</a>.<a href="Q.html#help">help</a></code>, passing <code><a href="Q.html">Q</a>.ComplexNumber</code> as the argument. </dd> </li> <li> <dt id=".index">index</dt> <dd> <code class="value-type">Number</code> The number of instances created so far. </dd> </li> </ul> <h4>Constants and constant creation</h4> <ul class="properties"> <li> <dt id=".constants">constants</dt> <dd> <code class="value-type">Object</code> Constants are appended <em>directly</em> to the <code><a href="Q.html">Q</a>.ComplexNumber</code> object. For convenience they are also appended to this <code><a href="Q.html">Q</a>.ComplexNumber</code>.constants</code> object to make looking up constants in the JavaScript console trivial, and to make iterating across all constants convenient via functions like <code><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries" target="_blank">Object.entries</a></code>, <code><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys" target="_blank">Object.keys</a></code>, <code><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/values" target="_blank">Object.values</a></code>, and so on. <!-- Configured to be unwritable once appended via <code><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty" target="_blank">Object.defineProperty</a></code> and they are labeled in uppercase to signal to us that this is so. --> The intention that a property act as a constant is signaled by its labelling in all-uppercase. </dd> </li> <li> <dt id=".createConstant">createConstant</dt> <dd> <code class="value-type">Function( key: String, value: * )<!-- → undefined --></code> Appends a property named by <code>key</code> with a value of <code>value</code> to both the <code>Q</code> object and its <code><a href="#.constants">constants</a></code> property. </dd> </li> <li> <dt id=".createConstants">createConstants</dt> <dd> <code class="value-type">Function( … )</code> Expects an even number of arguments. Will use each pair in the sequence of arguments to call <code><a href="#.createConstant">createConstant</a></code>. </dd> </li> <li> <dt id=".ZERO">ZERO</dt> <dd> <code class="value-type"><a href="Q.html">Q</a>.ComplexNumber</code> Initialized as <code>new <a href="Q.html">Q</a>.ComplexNumber( 0, 0 )</code>. Described as 0. </dd> </li> <li> <dt id=".ONE">ONE</dt> <dd> <code class="value-type"><a href="Q.html">Q</a>.ComplexNumber</code> Initialized as <code>new <a href="Q.html">Q</a>.ComplexNumber( 1, 0 )</code>. Described as 1. </dd> </li> <li> <dt id=".E">E</dt> <dd> <code class="value-type"><a href="Q.html">Q</a>.ComplexNumber</code> Initialized as <code>new <a href="Q.html">Q</a>.ComplexNumber( Math.E, 0 )</code>. Described as <span class="symbol">e</span> ≈ 2.7183. </dd> </li> <li> <dt id=".PI">PI</dt> <dd> <code class="value-type"><a href="Q.html">Q</a>.ComplexNumber</code> Initialized as <code>new <a href="Q.html">Q</a>.ComplexNumber( Math.PI, 0 )</code>. Described as <a href="https://youtu.be/L1eegVTwDS0" target="_blank"><strong>exactly</strong> equal to 3</a>. </dd> </li> <li> <dt id=".I">I</dt> <dd> <code class="value-type"><a href="Q.html">Q</a>.ComplexNumber</code> Initialized as <code>new <a href="Q.html">Q</a>.ComplexNumber( 0, 1 )</code>. Described as <span class="symbol">i</span>. </dd> </li> <li> <dt id=".EPSILON">EPSILON</dt> <dd> <code class="value-type"><a href="Q.html">Q</a>.ComplexNumber</code> Initialized as <code>new <a href="Q.html">Q</a>.ComplexNumber( <a href="Q.html">Q</a>.<a href="Q.html#.EPSILON">EPSILON</a>, <a href="Q.html">Q</a>.<a href="Q.html#.EPSILON">EPSILON</a> )</code>. Described as ≈ 1.3323 × 10<sup>-15</sup> + 1.3323 × 10<sup>-15</sup><span class="symbol">i</span>. </dd> </li> <li> <dt id=".INFINITY">INFINITY</dt> <dd> <code class="value-type"><a href="Q.html">Q</a>.ComplexNumber</code> Initialized as <code>new <a href="Q.html">Q</a>.ComplexNumber( Infinity, Infinity )</code>. Described as <span class="symbol">∞</span> + <span class="symbol">∞i</span>. </dd> </li> <li> <dt id=".NAN">NAN</dt> <dd> <code class="value-type"><a href="Q.html">Q</a>.ComplexNumber</code> Initialized as <code>new <a href="Q.html">Q</a>.ComplexNumber( NaN, NaN )</code>. <code>Array( 16 ).join( NaN ) +' BATMAN!'</code> </dd> </li> </ul> <h4>Inspection</h4> <ul class="properties"> <li> <dt id=".isNumberLike">isNumberLike</dt> <dd> <code class="value-type">Function( n: * ) ⇒ Boolean</code> Returns true if <code>n</code>’s <code><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof" target="_blank">typeof</a></code> is equal to the <code>String</code> <code>'number'</code> or if <code>n <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/instanceof" target="_blank">instanceof</a> Number</code> is <code>true</code>, otherwise returns <code>false</code>. </dd> </li> <li> <dt id=".isNaN">isNaN</dt> <dd> <code class="value-type">Function( c: <a href="Q.html">Q</a>.ComplexNumber ) ⇒ Boolean</code> Returns <code>true</code> if either of this instance’s <code><a href="#this.real">real</a></code> or <code><a href="#this.real">imaginary</a></code> components are <code><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NaN" target="_blank">NaN</a></code>, otherwise returns <code>false</code>. </dd> </li> <li> <dt id=".isZero">isZero</dt> <dd> <code class="value-type">Function( c: <a href="Q.html">Q</a>.ComplexNumber ) ⇒ Boolean</code> Returns <code>true</code> if both of this instance’s <code><a href="#this.real">real</a></code> and <code><a href="#this.real">imaginary</a></code> absolute values are equal to zero, otherwise returns <code>false</code>. See <a href="https://en.wikipedia.org/wiki/Signed_zero" target="_blank">“Signed zero”</a> for an explanation of why the <em>absolute</em> value of zero must be taken. </dd> </li> <li> <dt id=".isFinite">isFinite</dt> <dd> <code class="value-type">Function( c: <a href="Q.html">Q</a>.ComplexNumber ) ⇒ Boolean</code> Returns <code>true</code> if both of this instance’s <code><a href="#this.real">real</a></code> and <code><a href="#this.real">imaginary</a></code> values are <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isFinite" target="_blank">finite</a>, otherwise returns <code>false</code>. </dd> </li> <li> <dt id=".isInfinite">isInfinite</dt> <dd> <code class="value-type">Function( c: <a href="Q.html">Q</a>.ComplexNumber ) ⇒ Boolean</code> Returns <code>true</code> if both of this instance’s <code><a href="#this.real">real</a></code> and <code><a href="#this.real">imaginary</a></code> values are not <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isFinite" target="_blank">finite</a> and are also not <code><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN" target="_blank">NaN</a></code>, otherwise returns <code>false</code>. </dd> </li> <li> <dt id=".areEqual">areEqual</dt> <dd> <code class="value-type">Function( a: Number or <a href="Q.html">Q</a>.ComplexNumber, b: Number or <a href="Q.html">Q</a>.ComplexNumber ) ⇒ Boolean</code> Returns <code>true</code> if the arguments <code>a</code> and <code>b</code> are within <code><a href="Q.html">Q</a>.<a href="Q.html#.EPSILON">EPSILON</a></code> of each other, otherwise returns <code>false</code>. </dd> </li> </ul> <h4>Maths</h4> <ul class="properties"> <li> <dt id=".absolute">absolute</dt> <dd> <code class="value-type">Function( c: <a href="Q.html">Q</a>.ComplexNumber ) ⇒ Number</code> Calls and returns the value of <code><a href="Q.html">Q</a>.<a href="Q.html#.hypotenuse">hypotenuse</a></code> using <code>c</code>’s <code><a href="#this.real">real</a></code> and <code><a href="#this.real">imaginary</a></code> properties as arguments. </dd> </li> <li> <dt id=".conjugate">conjugate</dt> <dd> <code class="value-type">Function( c: <a href="Q.html">Q</a>.ComplexNumber ) ⇒ <a href="Q.html">Q</a>.ComplexNumber</code> Returns a new complex number with the values <code>c.<a href="#this.real">real</a></code> and <code>c.<a href="#this.real">imaginary</a> * -1</code>. </dd> </li> <li> <dt id=".sine">sine</dt> <dd> <code class="value-type">Function( c: <a href="Q.html">Q</a>.ComplexNumber ) ⇒ <a href="Q.html">Q</a>.ComplexNumber</code> Returns the <a href="https://en.wikipedia.org/wiki/Sine#Sine_with_a_complex_argument" target="_blank">sine</a> of <code>c</code>. </dd> </li> <li> <dt id=".cosine">cosine</dt> <dd> <code class="value-type">Function( c: <a href="Q.html">Q</a>.ComplexNumber ) ⇒ <a href="Q.html">Q</a>.ComplexNumber</code> Returns the <a href="https://en.wikipedia.org/wiki/Trigonometric_functions#In_the_complex_plane" target="_blank">cosine</a> of <code>c</code>. </dd> </li> <li> <dt id=".arcCosine">arcCosine</dt> <dd> <code class="value-type">Function( c: <a href="Q.html">Q</a>.ComplexNumber ) ⇒ <a href="Q.html">Q</a>.ComplexNumber</code> Returns the <a href="https://en.wikipedia.org/wiki/Inverse_trigonometric_functions#Extension_to_complex_plane" target="_blank">arccosine</a> of <code>c</code>. </dd> </li> <li> <dt id=".arcTangent">arcTangent</dt> <dd> <code class="value-type">Function( c: <a href="Q.html">Q</a>.ComplexNumber ) ⇒ <a href="Q.html">Q</a>.ComplexNumber</code> Returns the <a href="https://en.wikipedia.org/wiki/Inverse_trigonometric_functions#Extension_to_complex_plane" target="_blank">arctangent</a> of <code>c</code>. </dd> </li> <li> <dt id=".power">power</dt> <dd> <code class="value-type">Function( a: Number or <a href="Q.html">Q</a>.ComplexNumber, b: Number or <a href="Q.html">Q</a>.ComplexNumber ) ⇒ <a href="Q.html">Q</a>.ComplexNumber</code> Returns <code>a</code> raised to the power of <code>b</code>. </dd> </li> <li> <dt id=".squareRoot">squareRoot</dt> <dd> <code class="value-type">Function( c: <a href="Q.html">Q</a>.ComplexNumber ) ⇒ <a href="Q.html">Q</a>.ComplexNumber</code> Returns the square root of <code>c</code>. </dd> </li> <li> <dt id=".log">log</dt> <dd> <code class="value-type">Function( c: <a href="Q.html">Q</a>.ComplexNumber ) ⇒ <a href="Q.html">Q</a>.ComplexNumber</code> Returns the log of <code>c</code>. </dd> </li> <li> <dt id=".operate">operate</dt> <dd> <code class="value-type">Function( name: String, a: Number or <a href="Q.html">Q</a>.ComplexNumber, b: Number or <a href="Q.html">Q</a>.ComplexNumber, numberAndNumber: Function, numberAndComplex: Function, complexAndNumber: Function, complexAndComplex: Function ) ⇒ *</code> Meta function for performing operations on two values that may each be either numbers or complex numbers. The <code>name</code> argument indicates the name of the operation being performed and is used in error logging should the operation fail. The intent is to return a <code><a href="Q.html">Q</a>.ComplexNumber</code>, though this is up to the functions passed in as it is their return values that are returned. </dd> </li> <li> <dt id=".multiply">multiply</dt> <dd> <code class="value-type">Function( a: Number or <a href="Q.html">Q</a>.ComplexNumber, b: Number or <a href="Q.html">Q</a>.ComplexNumber ) ⇒ <a href="Q.html">Q</a>.ComplexNumber</code> Uses <code><a href="Q.html">Q</a>.ComplexNumber.<a href="#.operate">operate</a></code> to return the result of multiplying <code>a</code> and <code>b</code>. </dd> </li> <li> <dt id=".divide">divide</dt> <dd> <code class="value-type">Function( a: Number or <a href="Q.html">Q</a>.ComplexNumber, b: Number or <a href="Q.html">Q</a>.ComplexNumber ) ⇒ <a href="Q.html">Q</a>.ComplexNumber</code> Uses <code><a href="Q.html">Q</a>.ComplexNumber.<a href="#.operate">operate</a></code> to return the result of dividing <code>a</code> by <code>b</code>. </dd> </li> <li> <dt id=".add">add</dt> <dd> <code class="value-type">Function( a: Number or <a href="Q.html">Q</a>.ComplexNumber, b: Number or <a href="Q.html">Q</a>.ComplexNumber ) ⇒ <a href="Q.html">Q</a>.ComplexNumber</code> Uses <code><a href="Q.html">Q</a>.ComplexNumber.<a href="#.operate">operate</a></code> to return the result of adding <code>a</code> and <code>b</code>. </dd> </li> <li> <dt id=".subtract">subtract</dt> <dd> <code class="value-type">Function( a: Number or <a href="Q.html">Q</a>.ComplexNumber, b: Number or <a href="Q.html">Q</a>.ComplexNumber ) ⇒ <a href="Q.html">Q</a>.ComplexNumber</code> Uses <code><a href="Q.html">Q</a>.ComplexNumber.<a href="#.operate">operate</a></code> to return the result of subtracting <code>b</code> from <code>a</code>. </dd> </li> </ul> <hr> <h3 id="Prototype_properties">Prototype properties</h3> <ul class="properties"> <li> <dt id=".prototype.clone">clone</dt> <dd> <code class="value-type">Function ⇒ <a href="Q.html">Q</a>.ComplexNumber</code> Returns a new instance with the values for <code><a href="#this.real">real</a></code> and <code><a href="#this.imaginary">imaginary</a></code> copied from this instance. </dd> </li> <li> <dt id=".prototype.copy$">copy$</dt> <dd> <code class="value-type">Function( c: <a href="Q.html">Q</a>.ComplexNumber ) ⇒ <a href="Q.html">Q</a>.ComplexNumber</code> Copies the values for <code><a href="#this.real">real</a></code> and <code><a href="#this.imaginary">imaginary</a></code> from the supplied <code><a href="Q.html">Q</a>.ComplexNumber</code> argument. </dd> </li> </ul> <h4>Inspections (non-destructive)</h4> <ul class="properties"> <li> <dt id=".prototype.isNaN">isNaN</dt> <dd> <code class="value-type">Function ⇒ Boolean</code> Calls and returns the result of the <a href="#.isNaN"><code>isNaN</code> static method</a>, passing the calling instance as the argument. Will return a <code>Boolean</code> value, thereby halting <a href="https://en.wikipedia.org/wiki/Fluent_interface" target="_blank">“Fluent interface” method chaining</a> for this instance. </dd> </li> <li> <dt id=".prototype.isZero">isZero</dt> <dd> <code class="value-type">Function ⇒ Boolean</code> Calls and returns the result of the <a href="#.isZero"><code>isZero</code> static method</a>, passing the calling instance as the argument. Will return a <code>Boolean</code> value, thereby halting <a href="https://en.wikipedia.org/wiki/Fluent_interface" target="_blank">“Fluent interface” method chaining</a> for this instance. </dd> </li> <li> <dt id=".prototype.isFinite">isFinite</dt> <dd> <code class="value-type">Function ⇒ Boolean</code> Calls and returns the result of the <a href="#.isFinite"><code>isFinite</code> static method</a>, passing the calling instance as the argument. Will return a <code>Boolean</code> value, thereby halting <a href="https://en.wikipedia.org/wiki/Fluent_interface" target="_blank">“Fluent interface” method chaining</a> for this instance. </dd> </li> <li> <dt id=".prototype.isInfinite">isInfinite</dt> <dd> <code class="value-type">Function ⇒ Boolean</code> Calls and returns the result of the <a href="#.isInfinite"><code>isInfinite</code> static method</a>, passing the calling instance as the argument. Will return a <code>Boolean</code> value, thereby halting <a href="https://en.wikipedia.org/wiki/Fluent_interface" target="_blank">“Fluent interface” method chaining</a> for this instance. </dd> </li> <li> <dt id=".prototype.isEqualTo">isEqualTo</dt> <dd> <code class="value-type">Function( n: Number or <a href="Q.html">Q</a>.ComplexNumber ) ⇒ Boolean</code> Calls and returns the result of the <a href="#.areEqual"><code>areEqual</code> static method</a>, passing the calling instance as the first argument and <code>n</code> as the second argument. Will return a <code>Boolean</code> value, thereby halting <a href="https://en.wikipedia.org/wiki/Fluent_interface" target="_blank">“Fluent interface” method chaining</a> for this instance. </dd> </li> <li> <dt id=".prototype.reduce">reduce</dt> <dd> <code class="value-type">Function ⇒ <a href="Q.html">Q</a>.ComplexNumber or Number</code> If no <code><a href="#this.imaginary">imaginary</a></code> component exists, returns a <code>Number</code> representing the <code><a href="Q.html">Q</a>.ComplexNumber <a href="#this.real">real</a></code> component, otherwise returns the instance itself. May return a <code>Number</code> value, thereby halting <a href="https://en.wikipedia.org/wiki/Fluent_interface" target="_blank">“Fluent interface” method chaining</a> for this instance. </dd> </li> <li> <dt id=".prototype.toText">toText</dt> <dd> <code class="value-type">Function([ roundToDecimal: Number ]) ⇒ String</code> Returns the value of this instance expressed as text in a form similar to <span class="symbol">a</span>+<span class="symbol">bi</span>. If <code>roundToDecimal</code> is supplied, will round both the <code><a href="#this.real">real</a></code> and <code><a href="#this.imaginary">imaginary</a></code> components by passing themselves and <code>roundToDecimal</code> to <code><a href="Q.html">Q</a>.<a href="Q.html#.round">round</a></code> as arguments. Will return a <code>String</code> value, thereby halting <a href="https://en.wikipedia.org/wiki/Fluent_interface" target="_blank">“Fluent interface” method chaining</a> for this instance. </dd> </li> </ul> <h4>Maths (non-destructive)</h4> <ul class="properties"> <li> <dt id=".prototype.absolute">absolute</dt> <dd> <code class="value-type">Function ⇒ Number</code> Passes this instance as an argument to the <a href="#.absolute"><code>absolute</code> static method</a> and returns the result. Will return a <code>Number</code> value, thereby halting <a href="https://en.wikipedia.org/wiki/Fluent_interface" target="_blank">“Fluent interface” method chaining</a> for this instance. </dd> </li> <li> <dt id=".prototype.conjugate">conjugate</dt> <dd> <code class="value-type">Function ⇒ <a href="Q.html">Q</a>.ComplexNumber</code> Passes this instance as an argument to the <a href="#.conjugate"><code>conjugate</code> static method</a> and returns the result. </dd> </li> <li> <dt id=".prototype.power">power</dt> <dd> <code class="value-type">Function( n: Number or <a href="Q.html">Q</a>.ComplexNumber ) ⇒ <a href="Q.html">Q</a>.ComplexNumber</code> Passes this instance as the first argument and <code>n</code> as the second argument to the <a href="#.power"><code>power</code> static method</a> and returns the result. </dd> </li> <li> <dt id=".prototype.squareRoot">squareRoot</dt> <dd> <code class="value-type">Function ⇒ <a href="Q.html">Q</a>.ComplexNumber</code> Passes this instance as an argument to the <a href="#.squareRoot"><code>squareRoot</code> static method</a> and returns the result. </dd> </li> <li> <dt id=".prototype.log">log</dt> <dd> <code class="value-type">Function ⇒ <a href="Q.html">Q</a>.ComplexNumber</code> Passes this instance as an argument to the <a href="#.log"><code>log</code> static method</a> and returns the result. </dd> </li> <li> <dt id=".prototype.multiply">multiply</dt> <dd> <code class="value-type">Function( n: Number or <a href="Q.html">Q</a>.ComplexNumber ) ⇒ <a href="Q.html">Q</a>.ComplexNumber</code> Passes this instance as the first argument and <code>n</code> as the second argument to the <a href="#.multiply"><code>multiply</code> static method</a> and returns the result. </dd> </li> <li> <dt id=".prototype.divide">divide</dt> <dd> <code class="value-type">Function( n: Number or <a href="Q.html">Q</a>.ComplexNumber ) ⇒ <a href="Q.html">Q</a>.ComplexNumber</code> Passes this instance as the first argument and <code>n</code> as the second argument to the <a href="#.divide"><code>divide</code> static method</a> and returns the result. </dd> </li> <li> <dt id=".prototype.add">add</dt> <dd> <code class="value-type">Function( n: Number or <a href="Q.html">Q</a>.ComplexNumber ) ⇒ <a href="Q.html">Q</a>.ComplexNumber</code> Passes this instance as the first argument and <code>n</code> as the second argument to the <a href="#.add"><code>add</code> static method</a> and returns the result. </dd> </li> <li> <dt id=".prototype.subtract">subtract</dt> <dd> <code class="value-type">Function( n: Number or <a href="Q.html">Q</a>.ComplexNumber ) ⇒ <a href="Q.html">Q</a>.ComplexNumber</code> Passes this instance as the first argument and <code>n</code> as the second argument to the <a href="#.subtract"><code>subtract</code> static method</a> and returns the result. </dd> </li> </ul> <h4>Maths (destructive)</h4> <ul class="properties"> <li> <dt id=".prototype.conjugate$">conjugate$</dt> <dd> <code class="value-type">Function ⇒ <a href="Q.html">Q</a>.ComplexNumber</code> Calls the <a href="#.prototype.conjugate"><code>conjugate</code> instance method</a> and <code><a href="#.copy$">copies</a></code> the result to this instance. </dd> </li> <li> <dt id=".prototype.power$">power$</dt> <dd> <code class="value-type">Function( n: Number or <a href="Q.html">Q</a>.ComplexNumber ) ⇒ <a href="Q.html">Q</a>.ComplexNumber</code> Calls the <a href="#.prototype.power"><code>power</code> instance method</a> with <code>n</code> as an argument and <code><a href="#.copy$">copies</a></code> the result to this instance. </dd> </li> <li> <dt id=".prototype.squareRoot$">squareRoot$</dt> <dd> <code class="value-type">Function ⇒ <a href="Q.html">Q</a>.ComplexNumber</code> Calls the <a href="#.prototype.squareRoot"><code>squareRoot</code> instance method</a> and <code><a href="#.copy$">copies</a></code> the result to this instance. </dd> </li> <li> <dt id=".prototype.log$">log$</dt> <dd> <code class="value-type">Function ⇒ <a href="Q.html">Q</a>.ComplexNumber</code> Calls the <a href="#.prototype.log"><code>log</code> instance method</a> and <code><a href="#.copy$">copies</a></code> the result to this instance. </dd> </li> <li> <dt id=".prototype.multiply$">multiply$</dt> <dd> <code class="value-type">Function( n: Number or <a href="Q.html">Q</a>.ComplexNumber ) ⇒ <a href="Q.html">Q</a>.ComplexNumber</code> Calls the <a href="#.prototype.multiply"><code>multiply</code> instance method</a> with <code>n</code> as an argument and <code><a href="#.copy$">copies</a></code> the result to this instance. </dd> </li> <li> <dt id=".prototype.divide$">divide$</dt> <dd> <code class="value-type">Function( n: Number or <a href="Q.html">Q</a>.ComplexNumber ) ⇒ <a href="Q.html">Q</a>.ComplexNumber</code> Calls the <a href="#.prototype.divide"><code>divide</code> instance method</a> with <code>n</code> as an argument and <code><a href="#.copy$">copies</a></code> the result to this instance. </dd> </li> <li> <dt id=".prototype.add$">add$</dt> <dd> <code class="value-type">Function( n: Number or <a href="Q.html">Q</a>.ComplexNumber ) ⇒ <a href="Q.html">Q</a>.ComplexNumber</code> Calls the <a href="#.prototype.add"><code>add</code> instance method</a> with <code>n</code> as an argument and <code><a href="#.copy$">copies</a></code> the result to this instance. </dd> </li> <li> <dt id=".prototype.subtract$">subtract$</dt> <dd> <code class="value-type">Function( n: Number or <a href="Q.html">Q</a>.ComplexNumber ) ⇒ <a href="Q.html">Q</a>.ComplexNumber</code> Calls the <a href="#.prototype.subtract"><code>subtract</code> instance method</a> with <code>n</code> as an argument and <code><a href="#.copy$">copies</a></code> the result to this instance. </dd> </li> </ul> </main> <script> // console.log( '\n\nQ.ComplexNumber\n\n', Q.ComplexNumber.help(), '\n\n' ) var cat = new Q.ComplexNumber( 1, 2 ), dog = new Q.ComplexNumber( 3, -4 ), i = new Q.ComplexNumber( 0, 1 ) var ape = new Q.ComplexNumber(), bee = new Q.ComplexNumber( 1 ), elk = new Q.ComplexNumber( 1, 2 ), fox = elk.clone()// We’re avoiding a warning here: new <a href="Q.html">Q</a>.ComplexNumber( cat ), </script> </body> </html>
NunoEdgarGFlowHub/q.js
<|start_filename|>Assets/Oculus/Spatializer/editor/ONSPReflectionCustomGUI.cs<|end_filename|> /************************************************************************************ Filename : ONSPReflectionCustomGUI.cs Content : GUI for Oculus Spatializer mixer effect Copyright : Copyright (c) Facebook Technologies, LLC and its affiliates. All rights reserved. Licensed under the Oculus SDK Version 3.5 (the "License"); you may not use the Oculus SDK except in compliance with the License, which is provided at the time of installation or download, or which otherwise accompanies this software in either electronic or hard copy form. You may obtain a copy of the License at https://developer.oculus.com/licenses/sdk-3.5/ Unless required by applicable law or agreed to in writing, the Oculus SDK 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 UnityEditor; using UnityEngine; using System.Runtime.InteropServices; public class OculusSpatializerReflectionCustomGUI : IAudioEffectPluginGUI { public override string Name { get { return "OculusSpatializerReflection"; } } public override string Description { get { return "Reflection parameters for Oculus Spatializer"; } } public override string Vendor { get { return "Oculus"; } } public override bool OnGUI(IAudioEffectPlugin plugin) { float fval = 0.0f; bool bval = false; Separator(); Label ("GLOBAL SCALE (0.00001 - 10000.0)"); plugin.GetFloatParameter("GScale", out fval); plugin.SetFloatParameter("GScale", EditorGUILayout.FloatField(" ", Mathf.Clamp (fval, 0.00001f, 10000.0f))); Separator(); Label ("REFLECTION ENGINE"); Label(""); // Treat these floats as bools in the inspector plugin.GetFloatParameter("E.Rflt On", out fval); bval = (fval == 0.0f) ? false : true; bval = EditorGUILayout.Toggle("Enable Early Reflections", bval); plugin.SetFloatParameter("E.Rflt On", (bval == false) ? 0.0f : 1.0f); plugin.GetFloatParameter("E.Rflt Rev On", out fval); bval = (fval == 0.0f) ? false : true; bval = EditorGUILayout.Toggle("Enable Reverberation", bval); plugin.SetFloatParameter("E.Rflt Rev On", (bval == false) ? 0.0f : 1.0f); Separator(); Label("ROOM DIMENSIONS (meters)"); Label(""); plugin.GetFloatParameter("Room X", out fval); plugin.SetFloatParameter("Room X", EditorGUILayout.Slider("Width", fval, 1.0f, 200.0f)); plugin.GetFloatParameter("Room Y", out fval); plugin.SetFloatParameter("Room Y", EditorGUILayout.Slider("Height", fval, 1.0f, 200.0f)); plugin.GetFloatParameter("Room Z", out fval); plugin.SetFloatParameter("Room Z", EditorGUILayout.Slider("Length", fval, 1.0f, 200.0f)); Separator(); Label("WALL REFLECTION COEFFICIENTS (0.0 - 0.97)"); Label(""); plugin.GetFloatParameter("Left", out fval); plugin.SetFloatParameter("Left", EditorGUILayout.Slider("Left", fval, 0.0f, 0.97f)); plugin.GetFloatParameter("Right", out fval); plugin.SetFloatParameter("Right", EditorGUILayout.Slider("Right", fval, 0.0f, 0.97f)); plugin.GetFloatParameter("Up", out fval); plugin.SetFloatParameter("Up", EditorGUILayout.Slider("Up", fval, 0.0f, 0.97f)); plugin.GetFloatParameter("Down", out fval); plugin.SetFloatParameter("Down", EditorGUILayout.Slider("Down", fval, 0.0f, 0.97f)); plugin.GetFloatParameter("Behind", out fval); plugin.SetFloatParameter("Behind", EditorGUILayout.Slider("Back", fval, 0.0f, 0.97f)); plugin.GetFloatParameter("Front", out fval); plugin.SetFloatParameter("Front", EditorGUILayout.Slider("Front", fval, 0.0f, 0.97f)); Separator(); Label("SHARED REVERB ATTENUATION RANGE (1.0 - 10000.0 meters)"); Label(""); plugin.GetFloatParameter("Shared Rev Min", out fval); plugin.SetFloatParameter("Shared Rev Min", EditorGUILayout.Slider("Minimum", fval, 1.0f, 10000.0f)); plugin.GetFloatParameter("Shared Rev Max", out fval); plugin.SetFloatParameter("Shared Rev Max", EditorGUILayout.Slider("Maximum", fval, 1.0f, 10000.0f)); Separator(); Label("SHARED REVERB WET MIX (-60.0 - 20.0 dB)"); Label(""); plugin.GetFloatParameter("Shared Rev Wet", out fval); plugin.SetFloatParameter("Shared Rev Wet", EditorGUILayout.Slider(" ", fval, -60.0f, 20.0f)); Separator(); Label("PROPAGATION QUALITY LEVEL (0.0 - 200.0%)"); Label(""); plugin.GetFloatParameter("Prop Quality", out fval); plugin.SetFloatParameter("Prop Quality", EditorGUILayout.Slider(" ", fval, 0.0f, 200.0f)); Separator(); // We will override the controls with our own, so return false return false; } // Separator void Separator() { GUI.color = new Color(1, 1, 1, 0.25f); GUILayout.Box("", "HorizontalSlider", GUILayout.Height(16)); GUI.color = Color.white; } // Label void Label(string label) { EditorGUILayout.LabelField (label); } }
siemprecollective/public-vr-portal
<|start_filename|>hex.cpp<|end_filename|> /* Copyright (c) 2014 Steve "Sc00bz" Thomas (steve at tobtu dot com) 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 "hex.h" #include <stdint.h> // ************************ // *** Helper Functions *** // ************************ inline int hexDecodeNibble(char src) { // 0-9 0x30-0x39 // A-F 0x41-0x46 or a-f 0x61-0x66 int ch = (unsigned char) src; int ret = -1; // if (ch > 0x2f && ch < 0x3a) ret += ch - 0x30 + 1; // -47 ret += (((0x2f - ch) & (ch - 0x3a)) >> 8) & (ch - 47); ch |= 0x20; // if (ch > 0x60 && ch < 0x67) ret += ch - 0x61 + 10 + 1; // -86 ret += (((0x60 - ch) & (ch - 0x67)) >> 8) & (ch - 86); return ret; } inline int hexDecodeNibbleLower(char src) { // 0-9 0x30-0x39 // a-f 0x61-0x66 int ch = (unsigned char) src; int ret = -1; // if (ch > 0x2f && ch < 0x3a) ret += ch - 0x30 + 1; // -47 ret += (((0x2f - ch) & (ch - 0x3a)) >> 8) & (ch - 47); // if (ch > 0x60 && ch < 0x67) ret += ch - 0x61 + 10 + 1; // -86 ret += (((0x60 - ch) & (ch - 0x67)) >> 8) & (ch - 86); return ret; } inline int hexDecodeNibbleUpper(char src) { // 0-9 0x30-0x39 // A-F 0x41-0x46 int ch = (unsigned char) src; int ret = -1; // if (ch > 0x2f && ch < 0x3a) ret += ch - 0x30 + 1; // -47 ret += (((0x2f - ch) & (ch - 0x3a)) >> 8) & (ch - 47); // if (ch > 0x40 && ch < 0x47) ret += ch - 0x41 + 10 + 1; // -54 ret += (((0x40 - ch) & (ch - 0x47)) >> 8) & (ch - 54); return ret; } inline int hexDecodeByte(const char src[2]) { return (hexDecodeNibble(src[0]) << 4) | hexDecodeNibble(src[1]); } inline int hexDecodeByteLower(const char src[2]) { return (hexDecodeNibbleLower(src[0]) << 4) | hexDecodeNibbleLower(src[1]); } inline int hexDecodeByteUpper(const char src[2]) { return (hexDecodeNibbleUpper(src[0]) << 4) | hexDecodeNibbleUpper(src[1]); } inline char hexEncodeNibbleLower(unsigned int src) { // 0-9 0x30-0x39 // a-f 0x61-0x66 src += 0x30; // if (in > 0x39) in += 0x61 - 0x3a; src += ((0x39 - src) >> 8) & (0x61 - 0x3a); return (char) src; } inline char hexEncodeNibbleUpper(unsigned int src) { // 0-9 0x30-0x39 // A-F 0x41-0x46 src += 0x30; // if (in > 0x39) in += 0x41 - 0x3a; src += ((0x39 - src) >> 8) & (0x41 - 0x3a); return (char) src; } inline void hexEncodeByteLower(char dest[2], uint8_t src) { dest[0] = hexEncodeNibbleLower(src >> 4); dest[1] = hexEncodeNibbleLower(src & 0x0f); } inline void hexEncodeByteUpper(char dest[2], uint8_t src) { dest[0] = hexEncodeNibbleUpper(src >> 4); dest[1] = hexEncodeNibbleUpper(src & 0x0f); } // ********************** // *** Main Functions *** // ********************** int hexDecode(void *dest, const char *src, size_t srcLen) { int err = 0; if (srcLen % 2 != 0) { return 1; } srcLen /= 2; for (size_t i = 0; i < srcLen; i++) { int tmp = hexDecodeByte(src + 2 * i); err |= tmp >> 8; ((uint8_t*) dest)[i] = (uint8_t) tmp; } return err != 0; } int hexDecodeLower(void *dest, const char *src, size_t srcLen) { int err = 0; if (srcLen % 2 != 0) { return 1; } srcLen /= 2; for (size_t i = 0; i < srcLen; i++) { int tmp = hexDecodeByteLower(src + 2 * i); err |= tmp >> 8; ((uint8_t*) dest)[i] = (uint8_t) tmp; } return err != 0; } int hexDecodeUpper(void *dest, const char *src, size_t srcLen) { int err = 0; if (srcLen % 2 != 0) { return 1; } srcLen /= 2; for (size_t i = 0; i < srcLen; i++) { int tmp = hexDecodeByteUpper(src + 2 * i); err |= tmp >> 8; ((uint8_t*) dest)[i] = (uint8_t) tmp; } return err != 0; } void hexEncode(char *dest, const void *src, size_t srcLen) { for (size_t i = 0; i < srcLen; i++) { hexEncodeByteLower(dest + 2 * i, ((const uint8_t*) src)[i]); } dest[2 * srcLen] = 0; } void hexEncodeUpper(char *dest, const void *src, size_t srcLen) { for (size_t i = 0; i < srcLen; i++) { hexEncodeByteUpper(dest + 2 * i, ((const uint8_t*) src)[i]); } dest[2 * srcLen] = 0; } <|start_filename|>main.cpp<|end_filename|> /* Copyright (c) 2014 Steve "Sc00bz" Thomas (steve at tobtu dot com) 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 "hex.h" #include "base64.h" #include <stdint.h> #include <stdio.h> #include <string.h> int testBase64() { int ret; bool good; bool hasErrors = false; uint8_t allData[64*6/8] = {0}; uint8_t testAllData[64*6/8] = {0}; char allDataBase64[(sizeof(allData)+2)/3*4+1]; char allDataBase64DotSlash[(sizeof(allData)+2)/3*4+1]; char allDataBase64DotSlashOrdered[(sizeof(allData)+2)/3*4+1]; for (int i = 0, j = 0; i < 64; i += 4, j += 3) { allData[j ] = (uint8_t) (( i << 2) | ((i + 1) >> 4)); allData[j+1] = (uint8_t) (((i + 1) << 4) | ((i + 2) >> 2)); allData[j+2] = (uint8_t) (((i + 2) << 6) | (i + 3) ); } for (size_t size = 1; size <= sizeof(allData); size++) { base64Encode(allDataBase64, allData, size); printf("base64Encode(allData) = %s\n", allDataBase64); base64EncodeDotSlash(allDataBase64DotSlash, allData, size); printf("base64EncodeDotSlash(allData) = %s\n", allDataBase64DotSlash); base64EncodeDotSlashOrdered(allDataBase64DotSlashOrdered, allData, size); printf("base64EncodeDotSlash(allData) = %s\n\n", allDataBase64DotSlashOrdered); for (size_t i = 0; i < size; i++) { testAllData[i] = 0; } ret = base64Decode(testAllData, allDataBase64, strlen(allDataBase64)); printf("base64Decode(allDataBase64) ret = %u: ", ret); good = true; for (size_t i = 0; i < size; i++) { if (allData[i] != testAllData[i]) { good = false; } } if (ret != 0 || !good) { hasErrors = true; } printf("%s\n", (good ? "good" : "bad")); for (size_t i = 0; i < size; i++) { testAllData[i] = 0; } ret = base64DecodeDotSlash(testAllData, allDataBase64DotSlash, strlen(allDataBase64DotSlash)); printf("base64DecodeDotSlash(allDataBase64DotSlash) ret = %u: ", ret); good = true; for (size_t i = 0; i < size; i++) { if (allData[i] != testAllData[i]) { good = false; } } if (ret != 0 || !good) { hasErrors = true; } printf("%s\n", (good ? "good" : "bad")); for (size_t i = 0; i < size; i++) { testAllData[i] = 0; } ret = base64DecodeDotSlashOrdered(testAllData, allDataBase64DotSlashOrdered, strlen(allDataBase64DotSlashOrdered)); printf("base64DecodeDotSlashOrdered(allDataBase64DotSlashOrdered) ret = %u: ", ret); good = true; for (size_t i = 0; i < size; i++) { if (allData[i] != testAllData[i]) { good = false; } } if (ret != 0 || !good) { hasErrors = true; } printf("%s\n\n\n", (good ? "good" : "bad")); } printf("Should error:\n"); ret = base64Decode(testAllData, allDataBase64DotSlash, sizeof(allDataBase64DotSlash) - 1); printf("base64Decode(allDataBase64DotSlash) ret = %u: %s\n", ret, (ret != 0 ? "good" : "bad")); if (ret == 0) { hasErrors = true; } ret = base64DecodeDotSlash(testAllData, allDataBase64, sizeof(allDataBase64) - 1); printf("base64DecodeDotSlash(allDataBase64) ret = %u: %s\n", ret, (ret != 0 ? "good" : "bad")); if (ret == 0) { hasErrors = true; } ret = base64DecodeDotSlashOrdered(testAllData, allDataBase64, sizeof(allDataBase64) - 1); printf("base64DecodeDotSlashOrdered(allDataBase64) ret = %u: %s\n", ret, (ret != 0 ? "good" : "bad")); if (ret == 0) { hasErrors = true; } if (hasErrors) { printf("*** FAILED ***\n"); } else { printf("*** PASSED ***\n"); } return hasErrors; } int testHex() { int ret; bool good; bool hasErrors = false; uint8_t allBytes[256]; char allBytesHex[2 * sizeof(allBytes) + 1]; char allBytesHexUpper[2 * sizeof(allBytes) + 1]; for (int i = 0; i < sizeof(allBytes); i++) { allBytes[i] = (uint8_t) i; } hexEncode(allBytesHex, allBytes, sizeof(allBytes)); printf("hexEncode(allBytes) = %s\n", allBytesHex); hexEncodeUpper(allBytesHexUpper, allBytes, sizeof(allBytes)); printf("hexEncodeUpper(allBytes) = %s\n\n", allBytesHexUpper); for (int i = 0; i < sizeof(allBytes); i++) { allBytes[i] = 0; } ret = hexDecode(allBytes, allBytesHex, sizeof(allBytesHex) - 1); printf("hexDecode(allBytesHexLower) ret = %u: ", ret); good = true; for (int i = 0; i < sizeof(allBytes); i++) { if (i != allBytes[i]) { good = false; } } if (ret != 0 || !good) { hasErrors = true; } printf("%s\n", (good ? "good" : "bad")); for (int i = 0; i < sizeof(allBytes); i++) { allBytes[i] = 0; } ret = hexDecode(allBytes, allBytesHexUpper, sizeof(allBytesHexUpper) - 1); printf("hexDecode(allBytesHexUpper) ret = %u: ", ret); good = true; for (int i = 0; i < sizeof(allBytes); i++) { if (i != allBytes[i]) { good = false; } } if (ret != 0 || !good) { hasErrors = true; } printf("%s\n", (good ? "good" : "bad")); for (int i = 0; i < sizeof(allBytes); i++) { allBytes[i] = 0; } ret = hexDecodeLower(allBytes, allBytesHex, sizeof(allBytesHex) - 1); printf("hexDecodeLower(allBytesHexLower) ret = %u: ", ret); good = true; for (int i = 0; i < sizeof(allBytes); i++) { if (i != allBytes[i]) { good = false; } } if (ret != 0 || !good) { hasErrors = true; } printf("%s\n", (good ? "good" : "bad")); for (int i = 0; i < sizeof(allBytes); i++) { allBytes[i] = 0; } ret = hexDecodeUpper(allBytes, allBytesHexUpper, sizeof(allBytesHexUpper) - 1); printf("hexDecodeUpper(allBytesHexUpper) ret = %u: ", ret); good = true; for (int i = 0; i < sizeof(allBytes); i++) { if (i != allBytes[i]) { good = false; } } if (ret != 0 || !good) { hasErrors = true; } printf("%s\n", (good ? "good" : "bad")); printf("\nShould error:\n"); ret = hexDecodeLower(allBytes, allBytesHexUpper, sizeof(allBytesHexUpper) - 1); printf("hexDecodeLower(allBytesHexUpper) ret = %u\n", ret, (ret != 0 ? "good" : "bad")); if (ret == 0) { hasErrors = true; } ret = hexDecodeUpper(allBytes, allBytesHex, sizeof(allBytesHex) - 1); printf("hexDecodeUpper(allBytesHexLower) ret = %u\n", ret, (ret != 0 ? "good" : "bad")); if (ret == 0) { hasErrors = true; } if (hasErrors) { printf("*** FAILED ***\n"); } else { printf("*** PASSED ***\n"); } return hasErrors; } int main() { bool hasErrors; printf("*** Base64 ***\n"); hasErrors = testBase64() != 0; printf("\n*** Hex ***\n"); hasErrors = testHex() != 0 || hasErrors; if (hasErrors) { printf("\n***** FAILED *****\n"); } else { printf("\n***** ALL GOOD *****\n"); } return 0; } <|start_filename|>base64.cpp<|end_filename|> /* Copyright (c) 2014 Steve "Sc00bz" Thomas (steve at tobtu dot com) 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 "base64.h" #include <stdint.h> // ************************ // *** Helper Functions *** // ************************ // Base64 character set: // [A-Z] [a-z] [0-9] + / // 0x41-0x5a, 0x61-0x7a, 0x30-0x39, 0x2b, 0x2f inline int base64Decode6Bits(char src) { int ch = (unsigned char) src; int ret = -1; // if (ch > 0x40 && ch < 0x5b) ret += ch - 0x41 + 1; // -64 ret += (((0x40 - ch) & (ch - 0x5b)) >> 8) & (ch - 64); // if (ch > 0x60 && ch < 0x7b) ret += ch - 0x61 + 26 + 1; // -70 ret += (((0x60 - ch) & (ch - 0x7b)) >> 8) & (ch - 70); // if (ch > 0x2f && ch < 0x3a) ret += ch - 0x30 + 52 + 1; // 5 ret += (((0x2f - ch) & (ch - 0x3a)) >> 8) & (ch + 5); // if (ch == 0x2b) ret += 62 + 1; ret += (((0x2a - ch) & (ch - 0x2c)) >> 8) & 63; // if (ch == 0x2f) ret += 63 + 1; ret += (((0x2e - ch) & (ch - 0x30)) >> 8) & 64; return ret; } inline int base64Decode3Bytes(uint8_t dest[3], const char src[4]) { int c0 = base64Decode6Bits(src[0]); int c1 = base64Decode6Bits(src[1]); int c2 = base64Decode6Bits(src[2]); int c3 = base64Decode6Bits(src[3]); dest[0] = (uint8_t) ((c0 << 2) | (c1 >> 4)); dest[1] = (uint8_t) ((c1 << 4) | (c2 >> 2)); dest[2] = (uint8_t) ((c2 << 6) | c3 ); return ((c0 | c1 | c2 | c3) >> 8) & 1; } inline char base64Encode6Bits(unsigned int src) { int diff = 0x41; // if (in > 25) diff += 0x61 - 0x41 - 26; // 6 diff += ((25 - src) >> 8) & 6; // if (in > 51) diff += 0x30 - 0x61 - 26; // -75 diff -= ((51 - src) >> 8) & 75; // if (in > 61) diff += 0x2b - 0x30 - 10; // -15 diff -= ((61 - src) >> 8) & 15; // if (in > 62) diff += 0x2f - 0x2b - 1; // 3 diff += ((62 - src) >> 8) & 3; return (char) (src + diff); } inline void base64Encode3Bytes(char dest[4], const uint8_t src[3]) { unsigned int b0 = src[0]; unsigned int b1 = src[1]; unsigned int b2 = src[2]; dest[0] = base64Encode6Bits( b0 >> 2 ); dest[1] = base64Encode6Bits(((b0 << 4) | (b1 >> 4)) & 63); dest[2] = base64Encode6Bits(((b1 << 2) | (b2 >> 6)) & 63); dest[3] = base64Encode6Bits( b2 & 63); } // Base64 character set: // ./ [A-Z] [a-z] [0-9] // 0x2e-0x2f, 0x41-0x5a, 0x61-0x7a, 0x30-0x39 inline int base64Decode6BitsDotSlash(char src) { int ch = (unsigned char) src; int ret = -1; // if (ch > 0x2d && ch < 0x30) ret += ch - 0x2e + 1; // -45 ret += (((0x2d - ch) & (ch - 0x30)) >> 8) & (ch - 45); // if (ch > 0x40 && ch < 0x5b) ret += ch - 0x41 + 2 + 1; // -62 ret += (((0x40 - ch) & (ch - 0x5b)) >> 8) & (ch - 62); // if (ch > 0x60 && ch < 0x7b) ret += ch - 0x61 + 28 + 1; // -68 ret += (((0x60 - ch) & (ch - 0x7b)) >> 8) & (ch - 68); // if (ch > 0x2f && ch < 0x3a) ret += ch - 0x30 + 54 + 1; // 7 ret += (((0x2f - ch) & (ch - 0x3a)) >> 8) & (ch + 7); return ret; } inline int base64Decode3BytesDotSlash(uint8_t dest[3], const char src[4]) { int c0 = base64Decode6BitsDotSlash(src[0]); int c1 = base64Decode6BitsDotSlash(src[1]); int c2 = base64Decode6BitsDotSlash(src[2]); int c3 = base64Decode6BitsDotSlash(src[3]); dest[0] = (uint8_t) ((c0 << 2) | (c1 >> 4)); dest[1] = (uint8_t) ((c1 << 4) | (c2 >> 2)); dest[2] = (uint8_t) ((c2 << 6) | c3 ); return ((c0 | c1 | c2 | c3) >> 8) & 1; } inline char base64Encode6BitsDotSlash(unsigned int src) { src += 0x2e; // if (in > 0x2f) in += 0x41 - 0x30; // 17 src += ((0x2f - src) >> 8) & 17; // if (in > 0x5a) in += 0x61 - 0x5b; // 6 src += ((0x5a - src) >> 8) & 6; // if (in > 0x7a) in += 0x30 - 0x7b; // -75 src -= ((0x7a - src) >> 8) & 75; return (char) src; } inline void base64Encode3BytesDotSlash(char dest[4], const uint8_t src[3]) { unsigned int b0 = src[0]; unsigned int b1 = src[1]; unsigned int b2 = src[2]; dest[0] = base64Encode6BitsDotSlash( b0 >> 2 ); dest[1] = base64Encode6BitsDotSlash(((b0 << 4) | (b1 >> 4)) & 63); dest[2] = base64Encode6BitsDotSlash(((b1 << 2) | (b2 >> 6)) & 63); dest[3] = base64Encode6BitsDotSlash( b2 & 63); } // Base64 character set: // [.-9] [A-Z] [a-z] // 0x2e-0x39, 0x41-0x5a, 0x61-0x7a inline int base64Decode6BitsDotSlashOrdered(char src) { int ch = (unsigned char) src; int ret = -1; // if (ch > 0x2d && ch < 0x3a) ret += ch - 0x2e + 1; // -45 ret += (((0x2d - ch) & (ch - 0x3a)) >> 8) & (ch - 45); // if (ch > 0x40 && ch < 0x5b) ret += ch - 0x41 + 12 + 1; // -52 ret += (((0x40 - ch) & (ch - 0x5b)) >> 8) & (ch - 52); // if (ch > 0x60 && ch < 0x7b) ret += ch - 0x61 + 38 + 1; // -58 ret += (((0x60 - ch) & (ch - 0x7b)) >> 8) & (ch - 58); return ret; } inline int base64Decode3BytesDotSlashOrdered(uint8_t dest[3], const char src[4]) { int c0 = base64Decode6BitsDotSlashOrdered(src[0]); int c1 = base64Decode6BitsDotSlashOrdered(src[1]); int c2 = base64Decode6BitsDotSlashOrdered(src[2]); int c3 = base64Decode6BitsDotSlashOrdered(src[3]); dest[0] = (uint8_t) ((c0 << 2) | (c1 >> 4)); dest[1] = (uint8_t) ((c1 << 4) | (c2 >> 2)); dest[2] = (uint8_t) ((c2 << 6) | c3 ); return ((c0 | c1 | c2 | c3) >> 8) & 1; } inline char base64Encode6BitsDotSlashOrdered(unsigned int src) { src += 0x2e; // if (in > 0x39) in += 0x41 - 0x3a; // 7 src += ((0x39 - src) >> 8) & 7; // if (in > 0x5a) in += 0x61 - 0x5b; // 6 src += ((0x5a - src) >> 8) & 6; return (char) src; } inline void base64Encode3BytesDotSlashOrdered(char dest[4], const uint8_t src[3]) { unsigned int b0 = src[0]; unsigned int b1 = src[1]; unsigned int b2 = src[2]; dest[0] = base64Encode6BitsDotSlashOrdered( b0 >> 2 ); dest[1] = base64Encode6BitsDotSlashOrdered(((b0 << 4) | (b1 >> 4)) & 63); dest[2] = base64Encode6BitsDotSlashOrdered(((b1 << 2) | (b2 >> 6)) & 63); dest[3] = base64Encode6BitsDotSlashOrdered( b2 & 63); } // ********************** // *** Main Functions *** // ********************** // Base64 character set "[A-Z][a-z][0-9]+/" void base64Encode(char *dest, const void *src, size_t srcLen) { for (; srcLen >= 3; srcLen -= 3) { base64Encode3Bytes(dest, (const uint8_t*) src); dest += 4; src = (const uint8_t*) src + 3; } if (srcLen > 0) { uint8_t tmp[3] = {0, 0, 0}; for (size_t i = 0; i < srcLen; i++) { tmp[i] = ((const uint8_t*) src)[i]; } base64Encode3Bytes(dest, tmp); dest[3] = '='; if (srcLen == 1) { dest[2] = '='; } dest += 4; } *dest = 0; } int base64Decode(void *dest, const char *src, size_t srcLen) { int err = 0; for (; srcLen > 4; srcLen -= 4) { err |= base64Decode3Bytes((uint8_t*) dest, src); dest = (uint8_t*) dest + 3; src += 4; } if (srcLen > 0) { size_t i; uint8_t tmpOut[3]; char tmpIn[4] = {'A', 'A', 'A', 'A'}; for (i = 0; i < srcLen && src[i] != '='; i++) { tmpIn[i] = src[i]; } if (i < 2) { err = 1; } srcLen = i - 1; err |= base64Decode3Bytes(tmpOut, tmpIn); for (i = 0; i < srcLen; i++) { ((uint8_t*) dest)[i] = tmpOut[i]; } } return err; } // Base64 character set "./[A-Z][a-z][0-9]" void base64EncodeDotSlash(char *dest, const void *src, size_t srcLen) { for (; srcLen >= 3; srcLen -= 3) { base64Encode3BytesDotSlash(dest, (const uint8_t*) src); dest += 4; src = (const uint8_t*) src + 3; } if (srcLen > 0) { uint8_t tmp[3] = {0, 0, 0}; for (size_t i = 0; i < srcLen; i++) { tmp[i] = ((const uint8_t*) src)[i]; } base64Encode3BytesDotSlash(dest, tmp); dest[3] = '='; if (srcLen == 1) { dest[2] = '='; } dest += 4; } *dest = 0; } int base64DecodeDotSlash(void *dest, const char *src, size_t srcLen) { int err = 0; for (; srcLen > 4; srcLen -= 4) { err |= base64Decode3BytesDotSlash((uint8_t*) dest, src); dest = (uint8_t*) dest + 3; src += 4; } if (srcLen > 0) { size_t i; uint8_t tmpOut[3]; char tmpIn[4] = {'A', 'A', 'A', 'A'}; for (i = 0; i < srcLen && src[i] != '='; i++) { tmpIn[i] = src[i]; } if (i < 2) { err = 1; } srcLen = i - 1; err |= base64Decode3BytesDotSlash(tmpOut, tmpIn); for (i = 0; i < srcLen; i++) { ((uint8_t*) dest)[i] = tmpOut[i]; } } return err; } // Base64 character set "[.-9][A-Z][a-z]" or "./[0-9][A-Z][a-z]" void base64EncodeDotSlashOrdered(char *dest, const void *src, size_t srcLen) { for (; srcLen >= 3; srcLen -= 3) { base64Encode3BytesDotSlashOrdered(dest, (const uint8_t*) src); dest += 4; src = (const uint8_t*) src + 3; } if (srcLen > 0) { uint8_t tmp[3] = {0, 0, 0}; for (size_t i = 0; i < srcLen; i++) { tmp[i] = ((const uint8_t*) src)[i]; } base64Encode3BytesDotSlashOrdered(dest, tmp); dest[3] = '='; if (srcLen == 1) { dest[2] = '='; } dest += 4; } *dest = 0; } int base64DecodeDotSlashOrdered(void *dest, const char *src, size_t srcLen) { int err = 0; for (; srcLen > 4; srcLen -= 4) { err |= base64Decode3BytesDotSlashOrdered((uint8_t*) dest, src); dest = (uint8_t*) dest + 3; src += 4; } if (srcLen > 0) { size_t i; uint8_t tmpOut[3]; char tmpIn[4] = {'A', 'A', 'A', 'A'}; for (i = 0; i < srcLen && src[i] != '='; i++) { tmpIn[i] = src[i]; } if (i < 2) { err = 1; } srcLen = i - 1; err |= base64Decode3BytesDotSlashOrdered(tmpOut, tmpIn); for (i = 0; i < srcLen; i++) { ((uint8_t*) dest)[i] = tmpOut[i]; } } return err; }
Sc00bz/ConstTimeEncoding
<|start_filename|>literate_run_nbconvert.jl<|end_filename|> """ literate_run_nbconvert(source_dir="."; output_dir=source_dir, config_dir=".") Convert all Julia ipynb notebooks to jl files, using nbconvert # Input - `source_dir`: directory where the ipynb files can be found - `output_dir::String`: path to output folder (defaults to `source_dir`) - `config_dir::String`: path to where literate_config.py and literate.tpl are """ function literate_run_nbconvert(source_dir="."; output_dir=source_dir, config_dir=".") files = filter(x->endswith(lowercase(x),".ipynb"), readdir(source_dir)) files = joinpath.(source_dir, files) config = joinpath(config_dir, "literate_config.py") template = joinpath(config_dir, "literate.tpl") for file in files printstyled("\n\n-------------Converting $(file)-------------\n", color=:blue) run(`jupyter nbconvert --to script $file --output-dir $output_dir --config $config --template $template --Application.log_level='DEBUG'`) end end <|start_filename|>demo/ODEIntroduction.jl<|end_filename|> # # An Intro to DifferentialEquations.jl # # ## Basic Introduction Via Ordinary Differential Equations # # This notebook will get you started with DifferentialEquations.jl by introducing you to the functionality for solving ordinary differential equations (ODEs). The corresponding documentation page is the [ODE tutorial](http://docs.juliadiffeq.org/latest/tutorials/ode_example.html). While some of the syntax may be different for other types of equations, the same general principles hold in each case. Our goal is to give a gentle and thorough introduction that highlights these principles in a way that will help you generalize what you have learned. # # ### Background # # If you are new to the study of differential equations, it can be helpful to do a quick background read on [the definition of ordinary differential equations](https://en.wikipedia.org/wiki/Ordinary_differential_equation). We define an ordinary differential equation as an equation which describes the way that a variable $u$ changes, that is # # $$ u' = f(u,p,t) $$ # # where $p$ are the parameters of the model, $t$ is the time variable, and $f$ is the nonlinear model of how $u$ changes. The initial value problem also includes the information about the starting value: # # $$ u(t_0) = u_0 $$ # # Together, if you know the starting value and you know how the value will change with time, then you know what the value will be at any time point in the future. This is the intuitive definition of a differential equation. # ### First Model: Exponential Growth # # Our first model will be the canonical exponential growth model. This model says that the rate of change is proportional to the current value, and is this: # # $$ u' = au $$ # # where we have a starting value $u(0)=u_0$. Let's say we put 1 dollar into Bitcoin which is increasing at a rate of $98\%$ per year. Then calling now $t=0$ and measuring time in years, our model is: # # $$ u' = 0.98u $$ # # and $u(0) = 1.0$. We encode this into Julia by noticing that, in this setup, we match the general form when # # $$ f(u,p,t) = 0.98u $$ # # with $ u_0 = 1.0 $. If we want to solve this model on a time span from `t=0.0` to `t=1.0`, then we define an `ODEProblem` by specifying this function `f`, this initial condition `u0`, and this time span as follows: using DifferentialEquations f(u,p,t) = 0.98u u0 = 1.0 tspan = (0.0,1.0) prob = ODEProblem(f,u0,tspan) #---------------------------------------------------------------------------- # To solve our `ODEProblem` we use the command `solve`. sol = solve(prob) #---------------------------------------------------------------------------- # and that's it: we have succesfully solved our first ODE! # # #### Analyzing the Solution # # Of course, the solution type is not interesting in and of itself. We want to understand the solution! The documentation page which explains in detail the functions for analyzing the solution is the [Solution Handling](http://docs.juliadiffeq.org/latest/basics/solution.html) page. Here we will describe some of the basics. You can plot the solution using the plot recipe provided by [Plots.jl](http://docs.juliaplots.org/latest/): using Plots; gr() plot(sol) #---------------------------------------------------------------------------- # From the picture we see that the solution is an exponential curve, which matches our intuition. As a plot recipe, we can annotate the result using any of the [Plots.jl attributes](http://docs.juliaplots.org/latest/attributes/). For example: plot(sol,linewidth=5,title="Solution to the linear ODE with a thick line", xaxis="Time (t)",yaxis="u(t) (in μm)",label="My Thick Line!") ## legend=false #---------------------------------------------------------------------------- # Using the mutating `plot!` command we can add other pieces to our plot. For this ODE we know that the true solution is $u(t) = u_0 exp(at)$, so let's add some of the true solution to our plot: plot!(sol.t, t->1.0*exp(0.98t),lw=3,ls=:dash,label="True Solution!") #---------------------------------------------------------------------------- # In the previous command I demonstrated `sol.t`, which grabs the array of time points that the solution was saved at: sol.t #---------------------------------------------------------------------------- # We can get the array of solution values using `sol.u`: sol.u #---------------------------------------------------------------------------- # `sol.u[i]` is the value of the solution at time `sol.t[i]`. We can compute arrays of functions of the solution values using standard comprehensions, like: [t+u for (u,t) in tuples(sol)] #---------------------------------------------------------------------------- # However, one interesting feature is that, by default, the solution is a continuous function. If we check the print out again: sol #---------------------------------------------------------------------------- # you see that it says that the solution has a 4th order interpolation, meaning that it is a continuous function of 4th order accuracy. We can call the solution as a function of time `sol(t)`. For example, to get the value at `t=0.45`, we can use the command: sol(0.45) #---------------------------------------------------------------------------- # #### Controlling the Solver # # DifferentialEquations.jl has a common set of solver controls among its algorithms which can be found [at the Common Solver Options](http://docs.juliadiffeq.org/latest/basics/common_solver_opts.html) page. We will detail some of the most widely used options. # # The most useful options are the tolerances `abstol` and `reltol`. These tell the internal adaptive time stepping engine how precise of a solution you want. Generally, `reltol` is the relative accuracy while `abstol` is the accuracy when `u` is near zero. These tolerances are local tolerances and thus are not global guarantees. However, a good rule of thumb is that the total solution accuracy is 1-2 digits less than the relative tolerances. Thus for the defaults `abstol=1e-6` and `reltol=1e-3`, you can expect a global accuracy of about 1-2 digits. If we want to get around 6 digits of accuracy, we can use the commands: sol = solve(prob,abstol=1e-8,reltol=1e-8) #---------------------------------------------------------------------------- # Now we can see no visible difference against the true solution: plot(sol) plot!(sol.t, t->1.0*exp(0.98t),lw=3,ls=:dash,label="True Solution!") #---------------------------------------------------------------------------- # Notice that by decreasing the tolerance, the number of steps the solver had to take was `9` instead of the previous `5`. There is a trade off between accuracy and speed, and it is up to you to determine what is the right balance for your problem. # # Another common option is to use `saveat` to make the solver save at specific time points. For example, if we want the solution at an even grid of `t=0.1k` for integers `k`, we would use the command: sol = solve(prob,saveat=0.1) #---------------------------------------------------------------------------- # Notice that when `saveat` is used the continuous output variables are no longer saved and thus `sol(t)`, the interpolation, is only first order. We can save at an uneven grid of points by passing a collection of values to `saveat`. For example: sol = solve(prob,saveat=[0.2,0.7,0.9]) #---------------------------------------------------------------------------- # By default it always saves the first and last values, but we can turn this off as well: sol = solve(prob,saveat=[0.2,0.7,0.9],save_start = false, save_end = false) #---------------------------------------------------------------------------- # If we need to reduce the amount of saving, we can also turn off the continuous output directly via `dense=false`: sol = solve(prob,dense=false) #---------------------------------------------------------------------------- # and to turn off all intermediate saving we can use `save_everystep=false`: sol = solve(prob,save_everystep=false) #---------------------------------------------------------------------------- # More advanced saving behaviors, such as saving functionals of the solution, are handled via the `SavingCallback` in the [Callback Library](http://docs.juliadiffeq.org/latest/features/callback_library.html#SavingCallback-1) which will be addressed later in the tutorial. # #### Choosing Solver Algorithms # # There is no best algorithm for numerically solving a differential equation. When you call `solve(prob)`, DifferentialEquations.jl makes a guess at a good algorithm for your problem, given the properties that you ask for (the tolerances, the saving information, etc.). However, in many cases you may want more direct control. A later notebook will help introduce the various *algorithms* in DifferentialEquations.jl, but for now let's introduce the *syntax*. # # The most crucial determining factor in choosing a numerical method is the stiffness of the model. Stiffness is roughly characterized by a Jacobian `f` with large eigenvalues. That's quite mathematical, and we can think of it more intuitively: if you have big numbers in `f` (like parameters of order `1e5`), then it's probably stiff. Or, as the creator of the MATLAB ODE Suite, <NAME>, likes to define it, if the standard algorithms are slow, then it's stiff. We will go into more depth about diagnosing stiffness in a later tutorial, but for now note that if you believe your model may be stiff, you can hint this to the algorithm chooser via `alg_hints = [:stiff]`. sol = solve(prob,alg_hints=[:stiff]) #---------------------------------------------------------------------------- # Stiff algorithms have to solve implicit equations and linear systems at each step so they should only be used when required. # # If we want to choose an algorithm directly, you can pass the algorithm type after the problem as `solve(prob,alg)`. For example, let's solve this problem using the `Tsit5()` algorithm, and just for show let's change the relative tolerance to `1e-6` at the same time: sol = solve(prob,Tsit5(),reltol=1e-6) #---------------------------------------------------------------------------- # ### Systems of ODEs: The Lorenz Equation # # Now let's move to a system of ODEs. The [Lorenz equation](https://en.wikipedia.org/wiki/Lorenz_system) is the famous "butterfly attractor" that spawned chaos theory. It is defined by the system of ODEs: # # $$ \frac{dx}{dt} = \sigma (y - x) $$ # $$ \frac{dy}{dt} = x (\rho - z) -y $$ # $$ \frac{dz}{dt} = xy - \beta z $$ # # To define a system of differential equations in DifferentialEquations.jl, we define our `f` as a vector function with a vector initial condition. Thus, for the vector `u = [x,y,z]'`, we have the derivative function: function lorenz!(du,u,p,t) σ,ρ,β = p du[1] = σ*(u[2]-u[1]) du[2] = u[1]*(ρ-u[3]) - u[2] du[3] = u[1]*u[2] - β*u[3] end #---------------------------------------------------------------------------- # Notice here we used the in-place format which writes the output to the preallocated vector `du`. For systems of equations the in-place format is faster. We use the initial condition $u_0 = [1.0,0.0,0.0]$ as follows: u0 = [1.0,0.0,0.0] #---------------------------------------------------------------------------- # Lastly, for this model we made use of the parameters `p`. We need to set this value in the `ODEProblem` as well. For our model we want to solve using the parameters $\sigma = 10$, $\rho = 28$, and $\beta = 8/3$, and thus we build the parameter collection: p = (10,28,8/3) ## we could also make this an array, or any other type! #---------------------------------------------------------------------------- # Now we generate the `ODEProblem` type. In this case, since we have parameters, we add the parameter values to the end of the constructor call. Let's solve this on a time span of `t=0` to `t=100`: tspan = (0.0,100.0) prob = ODEProblem(lorenz!,u0,tspan,p) #---------------------------------------------------------------------------- # Now, just as before, we solve the problem: sol = solve(prob) #---------------------------------------------------------------------------- # The same solution handling features apply to this case. Thus `sol.t` stores the time points and `sol.u` is an array storing the solution at the corresponding time points. # # However, there are a few extra features which are good to know when dealing with systems of equations. First of all, `sol` also acts like an array. `sol[i]` returns the solution at the `i`th time point. sol.t[10],sol[10] #---------------------------------------------------------------------------- # Additionally, the solution acts like a matrix where `sol[j,i]` is the value of the `j`th variable at time `i`: sol[2,10] #---------------------------------------------------------------------------- # We can get a real matrix by performing a conversion: A = convert(Array,sol) #---------------------------------------------------------------------------- # This is the same as sol, i.e. `sol[i,j] = A[i,j]`, but now it's a true matrix. Plotting will by default show the time series for each variable: plot(sol) #---------------------------------------------------------------------------- # If we instead want to plot values against each other, we can use the `vars` command. Let's plot variable `1` against variable `2` against variable `3`: plot(sol,vars=(1,2,3)) #---------------------------------------------------------------------------- # This is the classic Lorenz attractor plot, where the `x` axis is `u[1]`, the `y` axis is `u[2]`, and the `z` axis is `u[3]`. Note that the plot recipe by default uses the interpolation, but we can turn this off: plot(sol,vars=(1,2,3),denseplot=false) #---------------------------------------------------------------------------- # Yikes! This shows how calculating the continuous solution has saved a lot of computational effort by computing only a sparse solution and filling in the values! Note that in vars, `0=time`, and thus we can plot the time series of a single component like: plot(sol,vars=(0,2)) #---------------------------------------------------------------------------- # ### A DSL for Parameterized Functions # # In many cases you may be defining a lot of functions with parameters. There exists the domain-specific language (DSL) defined by the `@ode_def` macro for helping with this common problem. For example, we can define the Lotka-Volterra equation: # # $$ \frac{dx}{dt} = ax - bxy $$ # $$ \frac{dy}{dt} = -cy + dxy $$ # # as follows: function lotka_volterra!(du,u,p,t) du[1] = p[1]*u[1] - p[2]*u[1]*u[2] du[2] = -p[3]*u[2] + p[4]*u[1]*u[2] end #---------------------------------------------------------------------------- # However, that can be hard to follow since there's a lot of "programming" getting in the way. Instead, you can use the `@ode_def` macro: lv! = @ode_def LotkaVolterra begin dx = a*x - b*x*y dy = -c*y + d*x*y end a b c d #---------------------------------------------------------------------------- # We can then use the result just like an ODE function from before: u0 = [1.0,1.0] p = (1.5,1.0,3.0,1.0) tspan = (0.0,10.0) prob = ODEProblem(lv!,u0,tspan,p) sol = solve(prob) plot(sol) #---------------------------------------------------------------------------- # Not only is the DSL convenient syntax, but it does some magic behind the scenes. For example, further parts of the tutorial will describe how solvers for stiff differential equations have to make use of the Jacobian in calculations. Here, the DSL uses symbolic differentiation to automatically derive that function: lv!.Jex #---------------------------------------------------------------------------- # The DSL can derive many other functions; this ability is used to speed up the solvers. An extension to DifferentialEquations.jl, [Latexify.jl](https://korsbo.github.io/Latexify.jl/latest/tutorials/parameterizedfunctions.html), allows you to extract these pieces as LaTeX expressions. # ## Internal Types # # The last basic user-interface feature to explore is the choice of types. DifferentialEquations.jl respects your input types to determine the internal types that are used. Thus since in the previous cases, when we used `Float64` values for the initial condition, this meant that the internal values would be solved using `Float64`. We made sure that time was specified via `Float64` values, meaning that time steps would utilize 64-bit floats as well. But, by simply changing these types we can change what is used internally. # # As a quick example, let's say we want to solve an ODE defined by a matrix. To do this, we can simply use a matrix as input. A = [1. 0 0 -5 4 -2 4 -3 -4 0 0 1 5 -2 2 3] u0 = rand(4,2) tspan = (0.0,1.0) f(u,p,t) = A*u prob = ODEProblem(f,u0,tspan) sol = solve(prob) #---------------------------------------------------------------------------- # There is no real difference from what we did before, but now in this case `u0` is a `4x2` matrix. Because of that, the solution at each time point is matrix: sol[3] #---------------------------------------------------------------------------- # In DifferentialEquations.jl, you can use any type that defines `+`, `-`, `*`, `/`, and has an appropriate `norm`. For example, if we want arbitrary precision floating point numbers, we can change the input to be a matrix of `BigFloat`: big_u0 = big.(u0) #---------------------------------------------------------------------------- # and we can solve the `ODEProblem` with arbitrary precision numbers by using that initial condition: prob = ODEProblem(f,big_u0,tspan) sol = solve(prob) #---------------------------------------------------------------------------- sol[1,3] #---------------------------------------------------------------------------- # To really make use of this, we would want to change `abstol` and `reltol` to be small! Notice that the type for "time" is different than the type for the dependent variables, and this can be used to optimize the algorithm via keeping multiple precisions. We can convert time to be arbitrary precision as well by defining our time span with `BigFloat` variables: # prob = ODEProblem(f,big_u0,big.(tspan)) sol = solve(prob) #---------------------------------------------------------------------------- # Let's end by showing a more complicated use of types. For small arrays, it's usually faster to do operations on static arrays via the package [StaticArrays.jl](https://github.com/JuliaArrays/StaticArrays.jl). The syntax is similar to that of normal arrays, but for these special arrays we utilize the `@SMatrix` macro to indicate we want to create a static array. using StaticArrays A = @SMatrix [ 1.0 0.0 0.0 -5.0 4.0 -2.0 4.0 -3.0 -4.0 0.0 0.0 1.0 5.0 -2.0 2.0 3.0] u0 = @SMatrix rand(4,2) tspan = (0.0,1.0) f(u,p,t) = A*u prob = ODEProblem(f,u0,tspan) sol = solve(prob) #---------------------------------------------------------------------------- sol[3] #---------------------------------------------------------------------------- # ## Conclusion # # These are the basic controls in DifferentialEquations.jl. All equations are defined via a problem type, and the `solve` command is used with an algorithm choice (or the default) to get a solution. Every solution acts the same, like an array `sol[i]` with `sol.t[i]`, and also like a continuous function `sol(t)` with a nice plot command `plot(sol)`. The Common Solver Options can be used to control the solver for any equation type. Lastly, the types used in the numerical solving are determined by the input types, and this can be used to solve with arbitrary precision and add additional optimizations (this can be used to solve via GPUs for example!). While this was shown on ODEs, these techniques generalize to other types of equations as well. <|start_filename|>demo/literate_output/ODEIntroduction.jl<|end_filename|> using DifferentialEquations f(u,p,t) = 0.98u u0 = 1.0 tspan = (0.0,1.0) prob = ODEProblem(f,u0,tspan) sol = solve(prob) using Plots; gr() plot(sol) plot(sol,linewidth=5,title="Solution to the linear ODE with a thick line", xaxis="Time (t)",yaxis="u(t) (in μm)",label="My Thick Line!") ## legend=false plot!(sol.t, t->1.0*exp(0.98t),lw=3,ls=:dash,label="True Solution!") sol.t sol.u [t+u for (u,t) in tuples(sol)] sol sol(0.45) sol = solve(prob,abstol=1e-8,reltol=1e-8) plot(sol) plot!(sol.t, t->1.0*exp(0.98t),lw=3,ls=:dash,label="True Solution!") sol = solve(prob,saveat=0.1) sol = solve(prob,saveat=[0.2,0.7,0.9]) sol = solve(prob,saveat=[0.2,0.7,0.9],save_start = false, save_end = false) sol = solve(prob,dense=false) sol = solve(prob,save_everystep=false) sol = solve(prob,alg_hints=[:stiff]) sol = solve(prob,Tsit5(),reltol=1e-6) function lorenz!(du,u,p,t) σ,ρ,β = p du[1] = σ*(u[2]-u[1]) du[2] = u[1]*(ρ-u[3]) - u[2] du[3] = u[1]*u[2] - β*u[3] end u0 = [1.0,0.0,0.0] p = (10,28,8/3) ## we could also make this an array, or any other type! tspan = (0.0,100.0) prob = ODEProblem(lorenz!,u0,tspan,p) sol = solve(prob) sol.t[10],sol[10] sol[2,10] A = convert(Array,sol) plot(sol) plot(sol,vars=(1,2,3)) plot(sol,vars=(1,2,3),denseplot=false) plot(sol,vars=(0,2)) function lotka_volterra!(du,u,p,t) du[1] = p[1]*u[1] - p[2]*u[1]*u[2] du[2] = -p[3]*u[2] + p[4]*u[1]*u[2] end lv! = @ode_def LotkaVolterra begin dx = a*x - b*x*y dy = -c*y + d*x*y end a b c d u0 = [1.0,1.0] p = (1.5,1.0,3.0,1.0) tspan = (0.0,10.0) prob = ODEProblem(lv!,u0,tspan,p) sol = solve(prob) plot(sol) lv!.Jex A = [1. 0 0 -5 4 -2 4 -3 -4 0 0 1 5 -2 2 3] u0 = rand(4,2) tspan = (0.0,1.0) f(u,p,t) = A*u prob = ODEProblem(f,u0,tspan) sol = solve(prob) sol[3] big_u0 = big.(u0) prob = ODEProblem(f,big_u0,tspan) sol = solve(prob) sol[1,3] prob = ODEProblem(f,big_u0,big.(tspan)) sol = solve(prob) using StaticArrays A = @SMatrix [ 1.0 0.0 0.0 -5.0 4.0 -2.0 4.0 -3.0 -4.0 0.0 0.0 1.0 5.0 -2.0 2.0 3.0] u0 = @SMatrix rand(4,2) tspan = (0.0,1.0) f(u,p,t) = A*u prob = ODEProblem(f,u0,tspan) sol = solve(prob) sol[3] # This file was generated using Literate.jl, https://github.com/fredrikekre/Literate.jl
hdrake/ipynb2LiterateJulia
<|start_filename|>tslint.json<|end_filename|> { "extends": "tslint:latest", "defaultSeverity": "warning", "rules": { "curly": true, "import-spacing": false, "interface-name": false, "max-classes-per-file": false, "max-line-length": [ true, 140 ], "member-access": [ true, "no-public" ], "no-empty": false, "no-empty-interface": false, "no-implicit-dependencies": [ true, "dev" ], "no-floating-promises": true, "no-object-literal-type-assertion": false, "prefer-for-of": false, "prefer-object-spread": false, "quotemark": [ true, "single", "avoid-escape" ], "trailing-comma": [ true, { "multiline": "never", "singleline": "never" } ], "variable-name": [ true, "allow-leading-underscore" ] }, "jsRules": { "curly": true }, "rulesDirectory": [ ] }
candleshine/sakura-core
<|start_filename|>tests/integration/setup.js<|end_filename|> const path = require('path'); const fs = require('fs'); const os = require('os'); const axios = require('axios'); const async = require('async'); const argv = require('yargs').argv; const { callbackify } = require('util'); const { login } = require('./shared'); let target = argv.target; if (process.env.CIRRUS_BRANCH) { target += `-${process.env.CIRRUS_BRANCH}`; } else { target += `-${os.hostname()}`; } const dotenvPath = path.join(__dirname, '.env'); function updateDotEnv() { let env = ''; if (fs.existsSync(dotenvPath)) { env = fs.readFileSync(dotenvPath, { encoding: 'utf-8' }); } envLines = env.split('\n').slice(0, 8); envLines.push(`APP_KEY=${process.env.APP_KEY}`); envLines.push(`APP_SECRET=${process.env.APP_SECRET}`); envLines.push(`MASTER_SECRET=${process.env.MASTER_SECRET}`); envLines.push(`AUTH_SERVICE_ID=${process.env.AUTH_SERVICE_ID}`); envLines.push(`NO_REFRESH_AUTH_SERVICE_ID=${process.env.NO_REFRESH_AUTH_SERVICE_ID}`); envLines.push(`WRONG_AUTH_SERVICE_ID=${process.env.WRONG_AUTH_SERVICE_ID}`); envLines.push(`OFFLINE_STORAGE=${process.env.OFFLINE_STORAGE}`); envLines.push(''); fs.writeFileSync(dotenvPath, envLines.join('\n')); } function createApp() { return axios({ method: 'POST', url: '/apps', data: { name: `JSSDK-${target}-${new Date().getTime()}`, organizationId: process.env.TEST_ORG_ID, realtime: { enabled: true } } }).then(({ data }) => { const { id, appSecret, masterSecret } = data.environments[0]; process.env.APP_KEY = id; process.env.APP_SECRET = appSecret; process.env.MASTER_SECRET = masterSecret; }).catch((err) => { console.error(err.response.data); throw new Error('...'); }); } function createTestEndpoint() { return axios({ method: 'POST', url: `/environments/${process.env.APP_KEY}/business-logic/endpoints`, data: { name: 'testEndpoint', code: 'function onRequest(request, response, modules) {\n response.body = { property1: "value1", property2: "value2" };\n response.complete();\n}', } }).catch((err) => { console.error(err.response.data); throw new Error('...'); }); } function createTestEndpointReturnsArgs() { return axios({ method: 'POST', url: `/environments/${process.env.APP_KEY}/business-logic/endpoints`, data: { name: 'testEndpointReturnsArgs', code: 'function onRequest(request, response, modules) {\n response.body = request.body;\n response.complete();\n}', } }).catch((err) => { console.error(err.response.data); throw new Error('...'); }); } function createDeltaCollection(name) { return axios({ method: 'POST', url: `/environments/${process.env.APP_KEY}/collections`, data: { name, deltaSet: {enabled: true, deletedTTLInDays: 15}, } }).catch((err) => { console.error(err.response.data); throw new Error('...'); }); } function createIdStore(name) { return axios({ method: 'POST', url: `/identity-stores`, data: { name: `JSSDK-${target}-${name} Store`, access: { writers: { organizations: [process.env.TEST_ORG_ID] } }, } }).then(({ data }) => { return data.id; }).catch((err) => { console.error(err.response.data); throw new Error('...'); }); } function createAuth(identityStoreId, name, refresh, wrongConfig=false) { const data = { name: `JSSDK-${target}-${name}-${new Date().getTime()}`, redirectUri: ['http://localhost:9876/callback'], grantTtl: 10, tokenTtl: 3600, refresh: refresh, refreshTtl: 1209600, provider: { datalinkHeaderMapping: { client_token: 'X-Kinvey-Auth' }, allowedAttributes: ['id', 'audience'], type:'facebook', options: { clientId: process.env.FACEBOOK_APP_ID, clientSecret: process.env.FACEBOOK_APP_SECRET, } }, identityStoreId }; if (wrongConfig) { data.provider.options.userIdAttribute = 'adminbob'; } return axios({ method: 'POST', url: `/auth-services`, data }).catch((err) => { console.error(err.response.data); throw new Error('...'); }); } function setDefaultAuth(identityStoreId) { return axios({ method: 'PUT', url: `/environments/${process.env.APP_KEY}`, data: { name: "Development", apiVersion: 3, appSecret: process.env.APP_SECRET, defaultAuthServiceId: process.env.AUTH_SERVICE_ID, emailVerification: { required: false, auto: false }, identityStoreId, masterSecret: process.env.MASTER_SECRET, } }).catch((err) => { console.error(err.response.data); throw new Error('...'); }); } async.waterfall([ callbackify(login), callbackify(createApp), callbackify(createTestEndpoint), callbackify(createTestEndpointReturnsArgs), callbackify(() => createDeltaCollection('BooksDelta')), callbackify(() => createDeltaCollection('NewsDelta')), callbackify(() => createIdStore()), callbackify((identityStoreId) => createAuth(identityStoreId, 'FBAuth', true) .then(({ data }) => { process.env.AUTH_SERVICE_ID = data.id; }) .then(() => setDefaultAuth(identityStoreId))), callbackify(() => createIdStore()), callbackify((identityStoreId) => createAuth(identityStoreId, 'FBAuthNoRefresh', false) .then(({ data }) => { process.env.NO_REFRESH_AUTH_SERVICE_ID = data.id; })), callbackify(() => createIdStore()), callbackify((identityStoreId) => createAuth(identityStoreId, 'FBAuthWrongConfig', true, true) .then(({ data }) => { process.env.WRONG_AUTH_SERVICE_ID = data.id; })), ], () => updateDotEnv());
Kinvey/js-sdk
<|start_filename|>src/preprocess.c<|end_filename|> /* * Copyright 1992 by <NAME> and <NAME>, Technische * Universitaet Berlin. See the accompanying file "COPYRIGHT" for * details. THERE IS ABSOLUTELY NO WARRANTY FOR THIS SOFTWARE. */ /* $Header: /tmp_amd/presto/export/kbs/jutta/src/gsm/RCS/preprocess.c,v 1.2 1994/05/10 20:18:45 jutta Exp $ */ #include <stdio.h> #include <assert.h> #include "private.h" #include "gsm.h" #include "proto.h" /* 4.2.0 .. 4.2.3 PREPROCESSING SECTION * * After A-law to linear conversion (or directly from the * Ato D converter) the following scaling is assumed for * input to the RPE-LTP algorithm: * * in: 0.1.....................12 * S.v.v.v.v.v.v.v.v.v.v.v.v.*.*.* * * Where S is the sign bit, v a valid bit, and * a "don't care" bit. * The original signal is called sop[..] * * out: 0.1................... 12 * S.S.v.v.v.v.v.v.v.v.v.v.v.v.0.0 */ void Gsm_Preprocess P3((S, s, so), struct gsm_state * S, word * s, word * so ) /* [0..159] IN/OUT */ { word z1 = S->z1; longword L_z2 = S->L_z2; word mp = S->mp; word s1; longword L_s2; longword L_temp; word msp, lsp; word SO; longword ltmp; /* for ADD */ ulongword utmp; /* for L_ADD */ register int k = 160; while (k--) { /* 4.2.1 Downscaling of the input signal */ SO = SASR( *s, 3 ) << 2; s++; assert (SO >= -0x4000); /* downscaled by */ assert (SO <= 0x3FFC); /* previous routine. */ /* 4.2.2 Offset compensation * * This part implements a high-pass filter and requires extended * arithmetic precision for the recursive part of this filter. * The input of this procedure is the array so[0...159] and the * output the array sof[ 0...159 ]. */ /* Compute the non-recursive part */ s1 = SO - z1; /* s1 = gsm_sub( *so, z1 ); */ z1 = SO; assert(s1 != MIN_WORD); /* Compute the recursive part */ L_s2 = s1; L_s2 <<= 15; /* Execution of a 31 bv 16 bits multiplication */ msp = SASR( L_z2, 15 ); lsp = L_z2-((longword)msp<<15); /* gsm_L_sub(L_z2,(msp<<15)); */ L_s2 += GSM_MULT_R( lsp, 32735 ); L_temp = (longword)msp * 32735; /* GSM_L_MULT(msp,32735) >> 1;*/ L_z2 = GSM_L_ADD( L_temp, L_s2 ); /* Compute sof[k] with rounding */ L_temp = GSM_L_ADD( L_z2, 16384 ); /* 4.2.3 Preemphasis */ msp = GSM_MULT_R( mp, -28180 ); mp = SASR( L_temp, 15 ); *so++ = GSM_ADD( mp, msp ); } S->z1 = z1; S->L_z2 = L_z2; S->mp = mp; } <|start_filename|>src/gsm_create.c<|end_filename|> /* * Copyright 1992 by <NAME> and <NAME>, Technische * Universitaet Berlin. See the accompanying file "COPYRIGHT" for * details. THERE IS ABSOLUTELY NO WARRANTY FOR THIS SOFTWARE. */ static char const ident[] = "$Header: /tmp_amd/presto/export/kbs/jutta/src/gsm/RCS/gsm_create.c,v 1.4 1996/07/02 09:59:05 jutta Exp $"; #include "config.h" #ifdef HAS_STRING_H #include <string.h> #else # include "proto.h" extern char * memset P((char *, int, int)); #endif #ifdef HAS_STDLIB_H # include <stdlib.h> #else # ifdef HAS_MALLOC_H # include <malloc.h> # else extern char * malloc(); # endif #endif #include <stdio.h> #include "gsm.h" #include "private.h" #include "proto.h" gsm gsm_create P0() { gsm r; r = (gsm)malloc(sizeof(struct gsm_state)); if (!r) return r; memset((char *)r, 0, sizeof(*r)); r->nrp = 40; return r; } <|start_filename|>src/code.c<|end_filename|> /* * Copyright 1992 by <NAME> and <NAME>, Technische * Universitaet Berlin. See the accompanying file "COPYRIGHT" for * details. THERE IS ABSOLUTELY NO WARRANTY FOR THIS SOFTWARE. */ /* $Header: /tmp_amd/presto/export/kbs/jutta/src/gsm/RCS/code.c,v 1.3 1996/07/02 09:59:05 jutta Exp $ */ #include "config.h" #ifdef HAS_STDLIB_H #include <stdlib.h> #else # include "proto.h" extern char * memcpy P((char *, char *, int)); #endif #include "private.h" #include "gsm.h" #include "proto.h" /* * 4.2 FIXED POINT IMPLEMENTATION OF THE RPE-LTP CODER */ void Gsm_Coder P8((S,s,LARc,Nc,bc,Mc,xmaxc,xMc), struct gsm_state * S, word * s, /* [0..159] samples IN */ /* * The RPE-LTD coder works on a frame by frame basis. The length of * the frame is equal to 160 samples. Some computations are done * once per frame to produce at the output of the coder the * LARc[1..8] parameters which are the coded LAR coefficients and * also to realize the inverse filtering operation for the entire * frame (160 samples of signal d[0..159]). These parts produce at * the output of the coder: */ word * LARc, /* [0..7] LAR coefficients OUT */ /* * Procedure 4.2.11 to 4.2.18 are to be executed four times per * frame. That means once for each sub-segment RPE-LTP analysis of * 40 samples. These parts produce at the output of the coder: */ word * Nc, /* [0..3] LTP lag OUT */ word * bc, /* [0..3] coded LTP gain OUT */ word * Mc, /* [0..3] RPE grid selection OUT */ word * xmaxc,/* [0..3] Coded maximum amplitude OUT */ word * xMc /* [13*4] normalized RPE samples OUT */ ) { int k; word * dp = S->dp0 + 120; /* [ -120...-1 ] */ word * dpp = dp; /* [ 0...39 ] */ word so[160]; Gsm_Preprocess (S, s, so); Gsm_LPC_Analysis (S, so, LARc); Gsm_Short_Term_Analysis_Filter (S, LARc, so); for (k = 0; k <= 3; k++, xMc += 13) { Gsm_Long_Term_Predictor ( S, so+k*40, /* d [0..39] IN */ dp, /* dp [-120..-1] IN */ S->e + 5, /* e [0..39] OUT */ dpp, /* dpp [0..39] OUT */ Nc++, bc++); Gsm_RPE_Encoding ( S, S->e + 5,/* e ][0..39][ IN/OUT */ xmaxc++, Mc++, xMc ); /* * Gsm_Update_of_reconstructed_short_time_residual_signal * ( dpp, S->e + 5, dp ); */ { register int i; register longword ltmp; for (i = 0; i <= 39; i++) dp[ i ] = GSM_ADD( S->e[5 + i], dpp[i] ); } dp += 40; dpp += 40; } (void)memcpy( (char *)S->dp0, (char *)(S->dp0 + 160), 120 * sizeof(*S->dp0) ); }
ThirdProject/android_external_libgsm
<|start_filename|>src/vulkan-renderer/exception.cpp<|end_filename|> #include "inexor/vulkan-renderer/exception.hpp" #include "inexor/vulkan-renderer/vk_tools/representation.hpp" namespace inexor::vulkan_renderer { VulkanException::VulkanException(std::string message, const VkResult result) : InexorException(message.append(" (") .append(vk_tools::as_string<VkResult>(result)) .append(": ") .append(vk_tools::result_to_description(result)) .append(")")) {} } // namespace inexor::vulkan_renderer <|start_filename|>tests/world/cube.cpp<|end_filename|> #include <inexor/vulkan-renderer/world/cube.hpp> #include <gtest/gtest.h> namespace { using namespace inexor::vulkan_renderer::world; TEST(Cube, neighbor) { std::shared_ptr<Cube> root = std::make_shared<Cube>(2.0f, glm::vec3{0, -1, -1}); root->set_type(Cube::Type::OCTANT); for (const auto &child : root->children()) { child->set_type(Cube::Type::OCTANT); for (const auto &grandchild : child->children()) { grandchild->set_type(Cube::Type::OCTANT); } } EXPECT_EQ(root->children()[1]->neighbor(Cube::NeighborAxis::Y, Cube::NeighborDirection::POSITIVE), root->children()[3]); EXPECT_NE(root->children()[1]->neighbor(Cube::NeighborAxis::Y, Cube::NeighborDirection::POSITIVE), root->children()[0]); EXPECT_EQ(root->children()[1]->children()[2]->neighbor(Cube::NeighborAxis::Y, Cube::NeighborDirection::POSITIVE), root->children()[3]->children()[0]); EXPECT_EQ(root->children()[1]->children()[2]->neighbor(Cube::NeighborAxis::Z, Cube::NeighborDirection::NEGATIVE), root->children()[0]->children()[3]); } } // namespace <|start_filename|>include/inexor/vulkan-renderer/vk_tools/representation.hpp<|end_filename|> #pragma once #include <vulkan/vulkan_core.h> #include <string> namespace inexor::vulkan_renderer::vk_tools { /// @brief Convert a Vulkan data structure into a std::string_view. template <typename VulkanDataType> [[nodiscard]] std::string_view as_string(VulkanDataType); /// @brief Return a VkResult's description text as std::string_view. /// @note This function can be used for both VkResult error and success values. /// @param result The VkResult return value which will be turned into a std::string_view. [[nodiscard]] std::string_view result_to_description(VkResult result); } // namespace inexor::vulkan_renderer::vk_tools <|start_filename|>include/inexor/vulkan-renderer/input/keyboard_mouse_data.hpp<|end_filename|> #pragma once #include <GLFW/glfw3.h> #include <array> #include <shared_mutex> namespace inexor::vulkan_renderer::input { /// @brief A wrapper for keyboard and mouse input data. class KeyboardMouseInputData { private: std::array<std::int64_t, 2> m_previous_cursor_pos{0, 0}; std::array<std::int64_t, 2> m_current_cursor_pos{0, 0}; std::array<bool, GLFW_KEY_LAST> m_pressed_keys{false}; std::array<bool, GLFW_MOUSE_BUTTON_LAST> m_pressed_mouse_buttons{false}; bool m_keyboard_updated{false}; bool m_mouse_buttons_updated{false}; mutable std::shared_mutex m_input_mutex; public: KeyboardMouseInputData() = default; KeyboardMouseInputData(const KeyboardMouseInputData &) = delete; KeyboardMouseInputData(KeyboardMouseInputData &&) = delete; ~KeyboardMouseInputData() = default; KeyboardMouseInputData &operator=(const KeyboardMouseInputData &) = delete; KeyboardMouseInputData &operator=(KeyboardMouseInputData &&) = delete; /// @brief Change the key's state to pressed. /// @param key the key which was pressed and greater or equal to 0 void press_key(std::int32_t key); /// @brief Change the key's state to unpressed. /// @param key the key which was released /// @note key must be smaller than ``GLFW_KEY_LAST`` and greater or equal to 0 void release_key(std::int32_t key); /// @brief Check if the given key is currently pressed. /// @param key the key index /// @note key must be smaller than ``GLFW_KEY_LAST`` and greater or equal to 0 /// @return ``true`` if the key is pressed [[nodiscard]] bool is_key_pressed(std::int32_t key) const; /// @brief Checks if a key was pressed once. /// @param key The key index /// @note key must be smaller than ``GLFW_KEY_LAST`` and greater or equal to 0 /// @return ``true`` if the key was pressed [[nodiscard]] bool was_key_pressed_once(std::int32_t key); /// @brief Change the mouse button's state to pressed. /// @param button the mouse button which was pressed /// @note button must be smaller than ``GLFW_MOUSE_BUTTON_LAST`` and greater or equal to 0 void press_mouse_button(std::int32_t button); /// @brief Change the mouse button's state to unpressed. /// @param button the mouse button which was released /// @note button must be smaller than ``GLFW_MOUSE_BUTTON_LAST`` and greater or equal to 0 void release_mouse_button(std::int32_t button); /// @brief Check if the given mouse button is currently pressed. /// @param button the mouse button index /// @note button must be smaller than ``GLFW_MOUSE_BUTTON_LAST`` and greater or equal to 0 /// @return ``true`` if the mouse button is pressed [[nodiscard]] bool is_mouse_button_pressed(std::int32_t button) const; /// @brief Checks if a mouse button was pressed once. /// @param button the mouse button index /// @note button must be smaller than ``GLFW_MOUSE_BUTTON_LAST`` and greater or equal to 0 /// @return ``true`` if the mouse button was pressed [[nodiscard]] bool was_mouse_button_pressed_once(std::int32_t button); /// @brief Set the current cursor position. /// @param pos_x the current x-coordinate of the cursor /// @param pos_y the current y-coordinate of the cursor void set_cursor_pos(double pos_x, double pos_y); [[nodiscard]] std::array<std::int64_t, 2> get_cursor_pos() const; /// @brief Calculate the change in x- and y-position of the cursor. /// @return a std::array of size 2 which contains the change in x-position in index 0 and the change in y-position /// in index 1 [[nodiscard]] std::array<double, 2> calculate_cursor_position_delta(); }; } // namespace inexor::vulkan_renderer::input <|start_filename|>include/inexor/vulkan-renderer/world/cube.hpp<|end_filename|> #pragma once #include "inexor/vulkan-renderer/world/indentation.hpp" #include <glm/geometric.hpp> #include <glm/gtx/vector_angle.hpp> #include <glm/vec3.hpp> #include <spdlog/spdlog.h> #include <array> #include <cstdint> #include <functional> #include <memory> #include <optional> #include <utility> #include <vector> // forward declaration namespace inexor::vulkan_renderer::world { class Cube; } // namespace inexor::vulkan_renderer::world // forward declaration namespace inexor::vulkan_renderer::io { class ByteStream; class NXOCParser; } // namespace inexor::vulkan_renderer::io void swap(inexor::vulkan_renderer::world::Cube &lhs, inexor::vulkan_renderer::world::Cube &rhs) noexcept; namespace inexor::vulkan_renderer::world { /// std::vector<Polygon> can probably replaced with an array. using Polygon = std::array<glm::vec3, 3>; using PolygonCache = std::shared_ptr<std::vector<Polygon>>; class Cube : public std::enable_shared_from_this<Cube> { friend void ::swap(Cube &lhs, Cube &rhs) noexcept; friend class io::NXOCParser; public: /// Maximum of sub cubes (children) static constexpr std::size_t SUB_CUBES{8}; /// Cube edges. static constexpr std::size_t EDGES{12}; /// Cube Type. enum class Type { EMPTY = 0b00u, SOLID = 0b01u, NORMAL = 0b10u, OCTANT = 0b11u }; enum class NeighborAxis { X = 2, Y = 1, Z = 0 }; enum class NeighborDirection { POSITIVE, NEGATIVE }; /// IDs of the children and edges which will be swapped to receive the rotation. /// To achieve a 90 degree rotation the 0th index have to be swapped with the 1st and the 1st with the 2nd, etc. struct RotationAxis { using ChildType = std::array<std::array<std::size_t, 4>, 2>; using EdgeType = std::array<std::array<std::size_t, 4>, 3>; using Type = std::pair<ChildType, EdgeType>; /// IDs of the children / edges which will be swapped to receive the rotation around X axis. static constexpr Type X{{{{0, 1, 3, 2}, {4, 5, 7, 6}}}, {{{2, 4, 11, 1}, {5, 7, 8, 10}, {0, 9, 6, 3}}}}; /// IDs of the children / edges which will be swapped to receive the rotation around Y axis. static constexpr Type Y{{{{0, 4, 5, 1}, {2, 6, 7, 3}}}, {{{0, 5, 9, 2}, {3, 8, 6, 11}, {1, 10, 7, 4}}}}; /// IDs of the children / edges which will be swapped to receive the rotation around Z axis. static constexpr Type Z{{{{0, 2, 6, 4}, {1, 3, 7, 5}}}, {{{1, 3, 10, 0}, {4, 6, 7, 9}, {2, 11, 8, 5}}}}; }; private: Type m_type{Type::EMPTY}; float m_size{32}; glm::vec3 m_position{0.0f, 0.0f, 0.0f}; /// Root cube is empty. std::weak_ptr<Cube> m_parent{}; /// Index of this in m_parent.m_children; undefined behavior if root. std::uint8_t m_index_in_parent{}; /// Indentations, should only be used if it is a geometry cube. std::array<Indentation, Cube::EDGES> m_indentations; std::array<std::shared_ptr<Cube>, Cube::SUB_CUBES> m_children; /// Only geometry cube (Type::SOLID and Type::Normal) have a polygon cache. mutable PolygonCache m_polygon_cache; mutable bool m_polygon_cache_valid{false}; /// Removes all children recursive. void remove_children(); /// Get the root to this cube. [[nodiscard]] std::shared_ptr<Cube> root() noexcept; /// Get the vertices of this cube. Use only on geometry cubes. [[nodiscard]] std::array<glm::vec3, 8> vertices() const noexcept; /// Optimized implementations of 90°, 180° and 270° rotations. template <int Rotations> void rotate(const RotationAxis::Type &axis); public: /// Create an empty cube. Cube() = default; /// Create an empty cube. Cube(float size, const glm::vec3 &position); /// Create an empty cube. Cube(std::weak_ptr<Cube> parent, std::uint8_t index, float size, const glm::vec3 &position); /// Use clone() to create an independent copy of a cube. Cube(const Cube &rhs) = delete; Cube(Cube &&rhs) noexcept; ~Cube() = default; Cube &operator=(Cube rhs); Cube &operator=(Cube &&) = delete; /// Get child. std::shared_ptr<Cube> operator[](std::size_t idx); /// Get child. std::shared_ptr<const Cube> operator[](std::size_t idx) const; // NOLINT /// Clone a cube, which has no relations to the current one or its children. /// It will be a root cube. [[nodiscard]] std::shared_ptr<Cube> clone() const; /// Is the current cube root. [[nodiscard]] bool is_root() const noexcept; /// At which child level this cube is. /// root cube = 0 [[nodiscard]] std::size_t grid_level() const noexcept; /// Count the number of Type::SOLID and Type::NORMAL cubes. [[nodiscard]] std::size_t count_geometry_cubes() const noexcept; [[nodiscard]] glm::vec3 center() const noexcept { return m_position + 0.5f * m_size; } [[nodiscard]] glm::vec3 position() const noexcept { return m_position; } [[nodiscard]] std::array<glm::vec3, 2> bounding_box() const { return {m_position, {m_position.x + m_size, m_position.y + m_size, m_position.z + m_size}}; } [[nodiscard]] float size() const noexcept { return m_size; } /// Set a new type. void set_type(Type new_type); /// Get type. [[nodiscard]] Type type() const noexcept; /// Get children. [[nodiscard]] const std::array<std::shared_ptr<Cube>, Cube::SUB_CUBES> &children() const; /// Get indentations. [[nodiscard]] std::array<Indentation, Cube::EDGES> indentations() const noexcept; /// Set an indent by the edge id. void set_indent(std::uint8_t edge_id, Indentation indentation); /// Indent a specific edge by steps. /// @param positive_direction Indent in positive axis direction. void indent(std::uint8_t edge_id, bool positive_direction, std::uint8_t steps); /// Rotate the cube 90° clockwise around the given axis. Repeats with the given rotations. /// @param axis Only one index should be one. /// @param rotations Value does not need to be adjusted beforehand. (e.g. mod 4) void rotate(const RotationAxis::Type &axis, int rotations); /// TODO: in special cases some polygons have no surface, if completely surrounded by others /// \warning Will update the cache even if it is considered as valid. void update_polygon_cache() const; /// Invalidate polygon cache. void invalidate_polygon_cache() const; /// Recursive way to collect all the caches. /// @param update_invalid If true it will update invalid polygon caches. [[nodiscard]] std::vector<PolygonCache> polygons(bool update_invalid = false) const; /// Get the (face) neighbor of this cube by using a similar implementation to Samets "OT_GTEQ_FACE_NEIGHBOR(P,I)". /// @brief Get the (face) neighbor of this cube. /// @param axis The axis on which to get the neighboring cube /// @param direction Whether to get the cube which is above or below this cube on the selected axis /// @returns Same-sized neighbor if existent, else larger neighbor if exists, otherwise (i.e. when no neighbor /// exists) nullptr. /// @see <NAME>. (1989) [Neighbor finding in Images Represented by Octrees.] /// (https://web.archive.org/web/20190712063957/http://www.cs.umd.edu/~hjs/pubs/SameCVGIP89.pdf) /// Computer Vision, Graphics, and Image Processing. 46 (3), 367-386. [[nodiscard]] std::shared_ptr<Cube> neighbor(NeighborAxis axis, NeighborDirection direction); }; /// @brief Construct a randomly generated cube world. /// Using the following probabilities: /// empty: 30% /// solid: 30% /// normal: 40% /// The number of intendations are evenly distributed. Empty normal cubes are not generated. /// @param max_depth The maximum of nested octants. /// @param position The position where the root cube is placed. /// @param seed The seed used for the random number generator. std::shared_ptr<world::Cube> create_random_world(std::uint32_t max_depth, const glm::vec3 &position, std::optional<std::uint32_t> seed = std::nullopt); } // namespace inexor::vulkan_renderer::world <|start_filename|>src/vulkan-renderer/imgui.cpp<|end_filename|> #include "inexor/vulkan-renderer/imgui.hpp" #include "inexor/vulkan-renderer/exception.hpp" #include "inexor/vulkan-renderer/wrapper/cpu_texture.hpp" #include "inexor/vulkan-renderer/wrapper/descriptor_builder.hpp" #include "inexor/vulkan-renderer/wrapper/make_info.hpp" #include <cassert> #include <stdexcept> namespace inexor::vulkan_renderer { ImGUIOverlay::ImGUIOverlay(const wrapper::Device &device, const wrapper::Swapchain &swapchain, RenderGraph *render_graph, TextureResource *back_buffer) : m_device(device), m_swapchain(swapchain) { spdlog::debug("Creating ImGUI context"); ImGui::CreateContext(); ImGuiStyle &style = ImGui::GetStyle(); style.Colors[ImGuiCol_TitleBg] = ImVec4(1.0f, 0.0f, 0.0f, 1.0f); style.Colors[ImGuiCol_TitleBgActive] = ImVec4(1.0f, 0.0f, 0.0f, 1.0f); style.Colors[ImGuiCol_TitleBgCollapsed] = ImVec4(1.0f, 0.0f, 0.0f, 0.1f); style.Colors[ImGuiCol_MenuBarBg] = ImVec4(1.0f, 0.0f, 0.0f, 0.4f); style.Colors[ImGuiCol_Header] = ImVec4(0.8f, 0.0f, 0.0f, 0.4f); style.Colors[ImGuiCol_HeaderActive] = ImVec4(1.0f, 0.0f, 0.0f, 0.4f); style.Colors[ImGuiCol_HeaderHovered] = ImVec4(1.0f, 0.0f, 0.0f, 0.4f); style.Colors[ImGuiCol_FrameBg] = ImVec4(0.0f, 0.0f, 0.0f, 0.8f); style.Colors[ImGuiCol_CheckMark] = ImVec4(1.0f, 0.0f, 0.0f, 0.8f); style.Colors[ImGuiCol_SliderGrab] = ImVec4(1.0f, 0.0f, 0.0f, 0.4f); style.Colors[ImGuiCol_SliderGrabActive] = ImVec4(1.0f, 0.0f, 0.0f, 0.8f); style.Colors[ImGuiCol_FrameBgHovered] = ImVec4(1.0f, 1.0f, 1.0f, 0.1f); style.Colors[ImGuiCol_FrameBgActive] = ImVec4(1.0f, 1.0f, 1.0f, 0.2f); style.Colors[ImGuiCol_Button] = ImVec4(1.0f, 0.0f, 0.0f, 0.4f); style.Colors[ImGuiCol_ButtonHovered] = ImVec4(1.0f, 0.0f, 0.0f, 0.6f); style.Colors[ImGuiCol_ButtonActive] = ImVec4(1.0f, 0.0f, 0.0f, 0.8f); ImGuiIO &io = ImGui::GetIO(); io.FontGlobalScale = m_scale; spdlog::debug("Loading ImGUI shaders"); m_vertex_shader = std::make_unique<wrapper::Shader>(m_device, VK_SHADER_STAGE_VERTEX_BIT, "ImGUI vertex shader", "shaders/ui.vert.spv"); m_fragment_shader = std::make_unique<wrapper::Shader>(m_device, VK_SHADER_STAGE_FRAGMENT_BIT, "ImGUI fragment shader", "shaders/ui.frag.spv"); // Load font texture // TODO: Move this data into a container class; have container class also support bold and italic. constexpr const char *FONT_FILE_PATH = "assets/fonts/NotoSans-Bold.ttf"; constexpr float FONT_SIZE = 18.0f; spdlog::debug("Loading front '{}'", FONT_FILE_PATH); ImFont *font = io.Fonts->AddFontFromFileTTF(FONT_FILE_PATH, FONT_SIZE); unsigned char *font_texture_data{}; int font_texture_width{0}; int font_texture_height{0}; io.Fonts->GetTexDataAsRGBA32(&font_texture_data, &font_texture_width, &font_texture_height); if (font == nullptr || font_texture_data == nullptr) { spdlog::error("Unable to load font {}. Falling back to error texture.", FONT_FILE_PATH); m_imgui_texture = std::make_unique<wrapper::GpuTexture>(m_device, wrapper::CpuTexture()); } else { spdlog::debug("Creating ImGUI font texture"); // Our font textures always have 4 channels and a single mip level by definition. constexpr int FONT_TEXTURE_CHANNELS{4}; constexpr int FONT_MIP_LEVELS{1}; VkDeviceSize upload_size = static_cast<VkDeviceSize>(font_texture_width) * static_cast<VkDeviceSize>(font_texture_height) * static_cast<VkDeviceSize>(FONT_TEXTURE_CHANNELS); m_imgui_texture = std::make_unique<wrapper::GpuTexture>( m_device, font_texture_data, upload_size, font_texture_width, font_texture_height, FONT_TEXTURE_CHANNELS, FONT_MIP_LEVELS, "ImGUI font texture"); } // Create an instance of the resource descriptor builder. // This allows us to make resource descriptors with the help of a builder pattern. wrapper::DescriptorBuilder descriptor_builder(m_device, m_swapchain.image_count()); // Make use of the builder to create a resource descriptor for the combined image sampler. m_descriptor = std::make_unique<wrapper::ResourceDescriptor>( descriptor_builder.add_combined_image_sampler(m_imgui_texture->sampler(), m_imgui_texture->image_view(), 0) .build("ImGUI")); m_index_buffer = render_graph->add<BufferResource>("imgui index buffer", BufferUsage::INDEX_BUFFER); m_vertex_buffer = render_graph->add<BufferResource>("imgui vertex buffer", BufferUsage::VERTEX_BUFFER); m_vertex_buffer->add_vertex_attribute(VK_FORMAT_R32G32_SFLOAT, offsetof(ImDrawVert, pos)); m_vertex_buffer->add_vertex_attribute(VK_FORMAT_R32G32_SFLOAT, offsetof(ImDrawVert, uv)); m_vertex_buffer->add_vertex_attribute(VK_FORMAT_R8G8B8A8_UNORM, offsetof(ImDrawVert, col)); m_vertex_buffer->set_element_size(sizeof(ImDrawVert)); m_stage = render_graph->add<GraphicsStage>("imgui stage"); m_stage->writes_to(back_buffer); m_stage->reads_from(m_index_buffer); m_stage->reads_from(m_vertex_buffer); m_stage->bind_buffer(m_vertex_buffer, 0); m_stage->uses_shader(*m_vertex_shader); m_stage->uses_shader(*m_fragment_shader); // Setup push constant range for global translation and scale. VkPushConstantRange push_constant_range{}; push_constant_range.offset = 0; push_constant_range.size = sizeof(PushConstBlock); push_constant_range.stageFlags = VK_SHADER_STAGE_VERTEX_BIT; m_stage->add_descriptor_layout(m_descriptor->descriptor_set_layout()); m_stage->add_push_constant_range(push_constant_range); // Setup blend attachment. VkPipelineColorBlendAttachmentState blend_attachment; blend_attachment.blendEnable = VK_TRUE; blend_attachment.srcColorBlendFactor = VK_BLEND_FACTOR_SRC_ALPHA; blend_attachment.dstColorBlendFactor = VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA; blend_attachment.colorBlendOp = VK_BLEND_OP_ADD; blend_attachment.srcAlphaBlendFactor = VK_BLEND_FACTOR_ONE; blend_attachment.dstAlphaBlendFactor = VK_BLEND_FACTOR_ZERO; blend_attachment.alphaBlendOp = VK_BLEND_OP_ADD; m_stage->set_blend_attachment(blend_attachment); } ImGUIOverlay::~ImGUIOverlay() { ImGui::DestroyContext(); } void ImGUIOverlay::update() { ImDrawData *imgui_draw_data = ImGui::GetDrawData(); if (imgui_draw_data == nullptr) { return; } if (imgui_draw_data->TotalIdxCount == 0 || imgui_draw_data->TotalVtxCount == 0) { return; } bool should_update = false; if (m_index_data.size() != imgui_draw_data->TotalIdxCount) { m_index_data.clear(); for (std::size_t i = 0; i < imgui_draw_data->CmdListsCount; i++) { const ImDrawList *cmd_list = imgui_draw_data->CmdLists[i]; // NOLINT for (std::size_t j = 0; j < cmd_list->IdxBuffer.Size; j++) { m_index_data.push_back(cmd_list->IdxBuffer.Data[j]); // NOLINT } } m_index_buffer->upload_data(m_index_data); should_update = true; } if (m_vertex_data.size() != imgui_draw_data->TotalVtxCount) { m_vertex_data.clear(); for (std::size_t i = 0; i < imgui_draw_data->CmdListsCount; i++) { const ImDrawList *cmd_list = imgui_draw_data->CmdLists[i]; // NOLINT for (std::size_t j = 0; j < cmd_list->VtxBuffer.Size; j++) { m_vertex_data.push_back(cmd_list->VtxBuffer.Data[j]); // NOLINT } } m_vertex_buffer->upload_data(m_vertex_data); should_update = true; } if (!should_update) { return; } m_stage->set_on_record([this](const PhysicalStage &physical, const wrapper::CommandBuffer &cmd_buf) { ImDrawData *imgui_draw_data = ImGui::GetDrawData(); if (imgui_draw_data == nullptr) { return; } const ImGuiIO &io = ImGui::GetIO(); m_push_const_block.scale = glm::vec2(2.0f / io.DisplaySize.x, 2.0f / io.DisplaySize.y); m_push_const_block.translate = glm::vec2(-1.0f); cmd_buf.bind_descriptor(*m_descriptor, physical.pipeline_layout()); cmd_buf.push_constants(physical.pipeline_layout(), VK_SHADER_STAGE_VERTEX_BIT, sizeof(PushConstBlock), &m_push_const_block); std::uint32_t index_offset = 0; std::int32_t vertex_offset = 0; for (std::size_t i = 0; i < imgui_draw_data->CmdListsCount; i++) { const ImDrawList *cmd_list = imgui_draw_data->CmdLists[i]; // NOLINT for (std::int32_t j = 0; j < cmd_list->CmdBuffer.Size; j++) { const ImDrawCmd &draw_cmd = cmd_list->CmdBuffer[j]; vkCmdDrawIndexed(cmd_buf.get(), draw_cmd.ElemCount, 1, index_offset, vertex_offset, 0); index_offset += draw_cmd.ElemCount; } vertex_offset += cmd_list->VtxBuffer.Size; } }); } } // namespace inexor::vulkan_renderer <|start_filename|>include/inexor/vulkan-renderer/world/collision_query.hpp<|end_filename|> #pragma once #include "inexor/vulkan-renderer/world/collision.hpp" #include <glm/vec3.hpp> #include <optional> // Forward declaration namespace inexor::vulkan_renderer::world { class Cube; } // namespace inexor::vulkan_renderer::world namespace inexor::vulkan_renderer::world { // TODO: Implement PointCubeCollision /// @brief ``True`` of the ray build from the two vectors collides with the cube's bounding box. /// @note There is no such function as glm::intersectRayBox. /// @param box_bounds An array of two vectors which represent the edges of the bounding box. /// @param pos The start position of the ray. /// @param dir The direction of the ray. /// @return ``True`` if the ray collides with the octree cube's bounding box. [[nodiscard]] bool ray_box_collision(std::array<glm::vec3, 2> &box_bounds, glm::vec3 &pos, glm::vec3 &dir); /// @brief Check for a collision between a camera ray and octree geometry. /// @param cube The cube to check collisions with. /// @param pos The camera position. /// @param dir The camera view direction. /// @param max_depth The maximum subcube iteration depth. If this depth is reached and the cube is an octant, it /// will be treated as if it was a solid cube. This is the foundation for the implementation of grid size in octree /// editor. /// @note This does not account yet for octree indentation! /// @return A std::optional which contains the collision data (if any found). [[nodiscard]] std::optional<RayCubeCollision<Cube>> ray_cube_collision_check(const Cube &cube, glm::vec3 pos, glm::vec3 dir, std::optional<std::uint32_t> max_depth = std::nullopt); } // namespace inexor::vulkan_renderer::world <|start_filename|>include/inexor/vulkan-renderer/render_graph.hpp<|end_filename|> #pragma once // TODO: Forward declare. #include "inexor/vulkan-renderer/wrapper/command_buffer.hpp" #include "inexor/vulkan-renderer/wrapper/device.hpp" #include "inexor/vulkan-renderer/wrapper/fence.hpp" #include "inexor/vulkan-renderer/wrapper/framebuffer.hpp" #include "inexor/vulkan-renderer/wrapper/semaphore.hpp" #include "inexor/vulkan-renderer/wrapper/shader.hpp" #include "inexor/vulkan-renderer/wrapper/swapchain.hpp" #include <spdlog/spdlog.h> #include <vk_mem_alloc.h> #include <vulkan/vulkan_core.h> #include <functional> #include <memory> #include <string> #include <type_traits> #include <unordered_map> #include <utility> #include <vector> // TODO: Compute stages. // TODO: Uniform buffers. namespace inexor::vulkan_renderer { class PhysicalResource; class PhysicalStage; class RenderGraph; /// @brief Base class of all render graph objects (resources and stages). /// @note This is just for internal use. struct RenderGraphObject { RenderGraphObject() = default; RenderGraphObject(const RenderGraphObject &) = delete; RenderGraphObject(RenderGraphObject &&) = delete; virtual ~RenderGraphObject() = default; RenderGraphObject &operator=(const RenderGraphObject &) = delete; RenderGraphObject &operator=(RenderGraphObject &&) = delete; /// @brief Casts this object to type `T` /// @return The object as type `T` or `nullptr` if the cast failed template <typename T> [[nodiscard]] T *as(); /// @copydoc as template <typename T> [[nodiscard]] const T *as() const; }; /// @brief A single resource in the render graph. /// @note May become multiple physical (vulkan) resources during render graph compilation. class RenderResource : public RenderGraphObject { friend RenderGraph; private: const std::string m_name; std::shared_ptr<PhysicalResource> m_physical; protected: explicit RenderResource(std::string name) : m_name(std::move(name)) {} public: RenderResource(const RenderResource &) = delete; RenderResource(RenderResource &&) = delete; ~RenderResource() override = default; RenderResource &operator=(const RenderResource &) = delete; RenderResource &operator=(RenderResource &&) = delete; }; enum class BufferUsage { /// @brief Specifies that the buffer will be used to input index data. INDEX_BUFFER, /// @brief Specifies that the buffer will be used to input per vertex data to a vertex shader. VERTEX_BUFFER, }; class BufferResource : public RenderResource { friend RenderGraph; private: const BufferUsage m_usage; std::vector<VkVertexInputAttributeDescription> m_vertex_attributes; // Data to upload during render graph compilation. const void *m_data{nullptr}; std::size_t m_data_size{0}; bool m_data_upload_needed{false}; std::size_t m_element_size{0}; public: BufferResource(std::string &&name, BufferUsage usage) : RenderResource(name), m_usage(usage) {} /// @brief Specifies that element `offset` of this vertex buffer is of format `format`. /// @note Calling this function is only valid on buffers of type BufferUsage::VERTEX_BUFFER. void add_vertex_attribute(VkFormat format, std::uint32_t offset); /// @brief Specifies the element size of the buffer upfront if data is not to be uploaded immediately. /// @param element_size The element size in bytes void set_element_size(std::size_t element_size) { m_element_size = element_size; } /// @brief Specifies the data that should be uploaded to this buffer at the start of the next frame. /// @param count The number of elements (not bytes) to upload /// @param data A pointer to a contiguous block of memory that is at least `count * sizeof(T)` bytes long // TODO: Use std::span when we switch to C++ 20. template <typename T> void upload_data(const T *data, std::size_t count); /// @brief @copybrief upload_data(const T *, std::size_t) /// @note This is equivalent to doing `upload_data(data.data(), data.size() * sizeof(T))` /// @see upload_data(const T *data, std::size_t count) template <typename T> void upload_data(const std::vector<T> &data); }; enum class TextureUsage { /// @brief Specifies that this texture is the output of the render graph. // TODO: Refactor back buffer system more (remove need for BACK_BUFFER texture usage) BACK_BUFFER, /// @brief Specifies that this texture is a combined depth/stencil buffer. /// @note This may mean that this texture is completely GPU-sided and cannot be accessed by the CPU in any way. DEPTH_STENCIL_BUFFER, /// @brief Specifies that this texture isn't used for any special purpose. NORMAL, }; class TextureResource : public RenderResource { friend RenderGraph; private: const TextureUsage m_usage; VkFormat m_format{VK_FORMAT_UNDEFINED}; public: TextureResource(std::string &&name, TextureUsage usage) : RenderResource(name), m_usage(usage) {} /// @brief Specifies the format of this texture that is required when the physical texture is made. /// @details For TextureUsage::BACK_BUFFER textures, using the swapchain image format is preferable in most cases. /// For TextureUsage::DEPTH_STENCIL_BUFFER textures, a VK_FORMAT_D* must be used. void set_format(VkFormat format) { m_format = format; } }; /// @brief A single render stage in the render graph. /// @note Not to be confused with a vulkan render pass. class RenderStage : public RenderGraphObject { friend RenderGraph; private: const std::string m_name; std::unique_ptr<PhysicalStage> m_physical; std::vector<const RenderResource *> m_writes; std::vector<const RenderResource *> m_reads; std::vector<VkDescriptorSetLayout> m_descriptor_layouts; std::vector<VkPushConstantRange> m_push_constant_ranges; std::function<void(const PhysicalStage &, const wrapper::CommandBuffer &)> m_on_record{[](auto &, auto &) {}}; protected: explicit RenderStage(std::string name) : m_name(std::move(name)) {} public: RenderStage(const RenderStage &) = delete; RenderStage(RenderStage &&) = delete; ~RenderStage() override = default; RenderStage &operator=(const RenderStage &) = delete; RenderStage &operator=(RenderStage &&) = delete; /// @brief Specifies that this stage writes to `resource`. void writes_to(const RenderResource *resource); /// @brief Specifies that this stage reads from `resource`. void reads_from(const RenderResource *resource); /// @brief Binds a descriptor set layout to this render stage. /// @note This function will be removed in the near future, as we are aiming for users of the API to not have to /// deal with descriptors at all. // TODO: Refactor descriptor management in the render graph void add_descriptor_layout(VkDescriptorSetLayout layout) { m_descriptor_layouts.push_back(layout); } /// @brief Add a push constant range to this render stage. /// @param range The push constant range void add_push_constant_range(VkPushConstantRange range) { m_push_constant_ranges.push_back(range); } /// @brief Specifies a function that will be called during command buffer recording for this stage /// @details This function can be used to specify other vulkan commands during command buffer recording. The most /// common use for this is for draw commands. void set_on_record(std::function<void(const PhysicalStage &, const wrapper::CommandBuffer &)> on_record) { m_on_record = std::move(on_record); } }; class GraphicsStage : public RenderStage { friend RenderGraph; private: bool m_clears_screen{false}; bool m_depth_test{false}; bool m_depth_write{false}; VkPipelineColorBlendAttachmentState m_blend_attachment{}; std::unordered_map<const BufferResource *, std::uint32_t> m_buffer_bindings; std::vector<VkPipelineShaderStageCreateInfo> m_shaders; public: explicit GraphicsStage(std::string &&name) : RenderStage(name) {} GraphicsStage(const GraphicsStage &) = delete; GraphicsStage(GraphicsStage &&) = delete; ~GraphicsStage() override = default; GraphicsStage &operator=(const GraphicsStage &) = delete; GraphicsStage &operator=(GraphicsStage &&) = delete; /// @brief Specifies that this stage should clear the screen before rendering. void set_clears_screen(bool clears_screen) { m_clears_screen = clears_screen; } /// @brief Specifies the depth options for this stage. /// @param depth_test Whether depth testing should be performed /// @param depth_write Whether depth writing should be performed void set_depth_options(bool depth_test, bool depth_write) { m_depth_test = depth_test; m_depth_write = depth_write; } /// @brief Set the blend attachment for this stage. /// @param blend_attachment The blend attachment void set_blend_attachment(VkPipelineColorBlendAttachmentState blend_attachment) { m_blend_attachment = blend_attachment; } /// @brief Specifies that `buffer` should map to `binding` in the shaders of this stage. void bind_buffer(const BufferResource *buffer, std::uint32_t binding); /// @brief Specifies that `shader` should be used during the pipeline of this stage. /// @note Binding two shaders of same type (e.g. two vertex shaders) is undefined behaviour. void uses_shader(const wrapper::Shader &shader); }; // TODO: Add wrapper::Allocation that can be made by doing `device->make<Allocation>(...)`. class PhysicalResource : public RenderGraphObject { friend RenderGraph; protected: // TODO: Add OOP device functions (see above todo) and only store a wrapper::Device here. const VmaAllocator m_allocator; const VkDevice m_device; VmaAllocation m_allocation{VK_NULL_HANDLE}; PhysicalResource(VmaAllocator allocator, VkDevice device) : m_allocator(allocator), m_device(device) {} public: PhysicalResource(const PhysicalResource &) = delete; PhysicalResource(PhysicalResource &&) = delete; ~PhysicalResource() override = default; PhysicalResource &operator=(const PhysicalResource &) = delete; PhysicalResource &operator=(PhysicalResource &&) = delete; }; class PhysicalBuffer : public PhysicalResource { friend RenderGraph; private: VmaAllocationInfo m_alloc_info{}; VkBuffer m_buffer{VK_NULL_HANDLE}; public: PhysicalBuffer(VmaAllocator allocator, VkDevice device) : PhysicalResource(allocator, device) {} PhysicalBuffer(const PhysicalBuffer &) = delete; PhysicalBuffer(PhysicalBuffer &&) = delete; ~PhysicalBuffer() override; PhysicalBuffer &operator=(const PhysicalBuffer &) = delete; PhysicalBuffer &operator=(PhysicalBuffer &&) = delete; }; class PhysicalImage : public PhysicalResource { friend RenderGraph; private: VkImage m_image{VK_NULL_HANDLE}; VkImageView m_image_view{VK_NULL_HANDLE}; public: PhysicalImage(VmaAllocator allocator, VkDevice device) : PhysicalResource(allocator, device) {} PhysicalImage(const PhysicalImage &) = delete; PhysicalImage(PhysicalImage &&) = delete; ~PhysicalImage() override; PhysicalImage &operator=(const PhysicalImage &) = delete; PhysicalImage &operator=(PhysicalImage &&) = delete; }; class PhysicalBackBuffer : public PhysicalResource { friend RenderGraph; private: const wrapper::Swapchain &m_swapchain; public: PhysicalBackBuffer(VmaAllocator allocator, VkDevice device, const wrapper::Swapchain &swapchain) : PhysicalResource(allocator, device), m_swapchain(swapchain) {} PhysicalBackBuffer(const PhysicalBackBuffer &) = delete; PhysicalBackBuffer(PhysicalBackBuffer &&) = delete; ~PhysicalBackBuffer() override = default; PhysicalBackBuffer &operator=(const PhysicalBackBuffer &) = delete; PhysicalBackBuffer &operator=(PhysicalBackBuffer &&) = delete; }; class PhysicalStage : public RenderGraphObject { friend RenderGraph; private: std::vector<wrapper::CommandBuffer> m_command_buffers; const wrapper::Device &m_device; std::unique_ptr<wrapper::Semaphore> m_finished_semaphore; VkPipeline m_pipeline{VK_NULL_HANDLE}; VkPipelineLayout m_pipeline_layout{VK_NULL_HANDLE}; protected: [[nodiscard]] VkDevice device() const { return m_device.device(); } public: explicit PhysicalStage(const wrapper::Device &device) : m_device(device) {} PhysicalStage(const PhysicalStage &) = delete; PhysicalStage(PhysicalStage &&) = delete; ~PhysicalStage() override; PhysicalStage &operator=(const PhysicalStage &) = delete; PhysicalStage &operator=(PhysicalStage &&) = delete; /// @brief Retrieve the pipeline layout of this physical stage. // TODO: This can be removed once descriptors are properly implemented in the render graph. [[nodiscard]] VkPipelineLayout pipeline_layout() const { return m_pipeline_layout; } }; class PhysicalGraphicsStage : public PhysicalStage { friend RenderGraph; private: VkRenderPass m_render_pass{VK_NULL_HANDLE}; std::vector<wrapper::Framebuffer> m_framebuffers; public: explicit PhysicalGraphicsStage(const wrapper::Device &device) : PhysicalStage(device) {} PhysicalGraphicsStage(const PhysicalGraphicsStage &) = delete; PhysicalGraphicsStage(PhysicalGraphicsStage &&) = delete; ~PhysicalGraphicsStage() override; PhysicalGraphicsStage &operator=(const PhysicalGraphicsStage &) = delete; PhysicalGraphicsStage &operator=(PhysicalGraphicsStage &&) = delete; }; class RenderGraph { private: const wrapper::Device &m_device; VkCommandPool m_command_pool{VK_NULL_HANDLE}; const wrapper::Swapchain &m_swapchain; std::shared_ptr<spdlog::logger> m_log{spdlog::default_logger()->clone("render-graph")}; // Vectors of render resources and stages. std::vector<std::unique_ptr<BufferResource>> m_buffer_resources; std::vector<std::unique_ptr<TextureResource>> m_texture_resources; std::vector<std::unique_ptr<RenderStage>> m_stages; // Stage execution order. std::vector<RenderStage *> m_stage_stack; // Functions for building resource related vulkan objects. void build_buffer(const BufferResource &, PhysicalBuffer &) const; void build_image(const TextureResource &, PhysicalImage &, VmaAllocationCreateInfo *) const; void build_image_view(const TextureResource &, PhysicalImage &) const; // Functions for building stage related vulkan objects. void build_pipeline_layout(const RenderStage *, PhysicalStage &) const; void record_command_buffer(const RenderStage *, PhysicalStage &, std::uint32_t image_index) const; // Functions for building graphics stage related vulkan objects. void build_render_pass(const GraphicsStage *, PhysicalGraphicsStage &) const; void build_graphics_pipeline(const GraphicsStage *, PhysicalGraphicsStage &) const; public: RenderGraph(const wrapper::Device &device, VkCommandPool command_pool, const wrapper::Swapchain &swapchain) : m_device(device), m_command_pool(command_pool), m_swapchain(swapchain) {} /// @brief Adds either a render resource or render stage to the render graph. /// @return A mutable reference to the just-added resource or stage template <typename T, typename... Args> T *add(Args &&...args) { auto ptr = std::make_unique<T>(std::forward<Args>(args)...); if constexpr (std::is_same_v<T, BufferResource>) { return static_cast<T *>(m_buffer_resources.emplace_back(std::move(ptr)).get()); } else if constexpr (std::is_same_v<T, TextureResource>) { return static_cast<T *>(m_texture_resources.emplace_back(std::move(ptr)).get()); } else if constexpr (std::is_base_of_v<RenderStage, T>) { return static_cast<T *>(m_stages.emplace_back(std::move(ptr)).get()); } else { static_assert(!std::is_same_v<T, T>, "T must be a RenderResource or RenderStage"); } } /// @brief Compiles the render graph resources/stages into physical vulkan objects. /// @param target The target resource of the render graph (usually the back buffer) void compile(const RenderResource *target); /// @brief Submits the command frame's command buffers for drawing. /// @param image_index The current image index, retrieved from Swapchain::acquire_next_image /// @param wait_semaphore The semaphore to wait on before rendering, typically some kind of "swapchain image /// available" semaphore /// @param graphics_queue The graphics queue to push rendering commands to /// @param signal_fence The fence to signal on completion of the whole frame VkSemaphore render(std::uint32_t image_index, VkSemaphore wait_semaphore, VkQueue graphics_queue, VkFence signal_fence); }; template <typename T> [[nodiscard]] T *RenderGraphObject::as() { return dynamic_cast<T *>(this); } template <typename T> [[nodiscard]] const T *RenderGraphObject::as() const { return dynamic_cast<const T *>(this); } template <typename T> void BufferResource::upload_data(const T *data, std::size_t count) { m_data = data; m_data_size = count * (m_element_size = sizeof(T)); m_data_upload_needed = true; } template <typename T> void BufferResource::upload_data(const std::vector<T> &data) { upload_data(data.data(), data.size()); } } // namespace inexor::vulkan_renderer <|start_filename|>src/vulkan-renderer/fps_counter.cpp<|end_filename|> #include "inexor/vulkan-renderer/fps_counter.hpp" namespace inexor::vulkan_renderer { std::optional<std::uint32_t> FPSCounter::update() { const auto current_time = std::chrono::high_resolution_clock::now(); auto time_duration = std::chrono::duration<float, std::chrono::seconds::period>(current_time - m_last_time).count(); if (time_duration >= m_fps_update_interval) { auto fps_value = static_cast<std::uint32_t>(static_cast<float>(m_frames) / time_duration); m_last_time = current_time; m_frames = 0; return fps_value; } m_frames++; return std::nullopt; } } // namespace inexor::vulkan_renderer <|start_filename|>src/vulkan-renderer/wrapper/uniform_buffer.cpp<|end_filename|> #include "inexor/vulkan-renderer/wrapper/uniform_buffer.hpp" #include "inexor/vulkan-renderer/wrapper/gpu_memory_buffer.hpp" #include <cassert> #include <cstring> #include <utility> namespace inexor::vulkan_renderer::wrapper { UniformBuffer::UniformBuffer(const Device &device, const std::string &name, const VkDeviceSize &buffer_size) : GPUMemoryBuffer(device, name, buffer_size, VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU) {} UniformBuffer::UniformBuffer(UniformBuffer &&other) noexcept : GPUMemoryBuffer(std::move(other)) {} void UniformBuffer::update(void *data, const std::size_t size) { std::memcpy(m_allocation_info.pMappedData, data, size); } } // namespace inexor::vulkan_renderer::wrapper <|start_filename|>include/inexor/vulkan-renderer/standard_ubo.hpp<|end_filename|> #pragma once #include <glm/glm.hpp> namespace inexor::vulkan_renderer { /// @note We can exactly match the definition in the shader using data types in GLM. /// The data in the matrices is binary compatible with the way the shader expects /// it, so we can later just memcpy a UniformBufferObject to a VkBuffer. struct UniformBufferObject { glm::mat4 model; glm::mat4 view; glm::mat4 proj; }; } // namespace inexor::vulkan_renderer <|start_filename|>src/vulkan-renderer/world/collision_query.cpp<|end_filename|> #include "inexor/vulkan-renderer/world/collision_query.hpp" #include <inexor/vulkan-renderer/world/cube.hpp> #include <array> #include <glm/gtx/intersect.hpp> namespace inexor::vulkan_renderer::world { bool ray_box_collision(const std::array<glm::vec3, 2> &box_bounds, const glm::vec3 &position, const glm::vec3 &direction) { glm::vec3 inverse_dir{1 / direction.x, 1 / direction.y, 1 / direction.z}; std::array<std::int32_t, 3> sign{static_cast<std::int32_t>(inverse_dir.x < 0), static_cast<std::int32_t>(inverse_dir.y < 0), static_cast<std::int32_t>(inverse_dir.z < 0)}; float tmin{(box_bounds[sign[0]].x - position.x) * inverse_dir.x}; float tmax{(box_bounds[1 - sign[0]].x - position.x) * inverse_dir.x}; float tymin{(box_bounds[sign[1]].y - position.y) * inverse_dir.y}; float tymax{(box_bounds[1 - sign[1]].y - position.y) * inverse_dir.y}; if ((tmin > tymax) || (tymin > tmax)) { return false; } if (tymin > tmin) { tmin = tymin; } if (tymax < tmax) { tmax = tymax; } float tzmin{(box_bounds[sign[2]].z - position.z) * inverse_dir.z}; float tzmax{(box_bounds[1 - sign[2]].z - position.z) * inverse_dir.z}; return !((tmin > tzmax) || (tzmin > tmax)); } std::optional<RayCubeCollision<Cube>> ray_cube_collision_check(const Cube &cube, const glm::vec3 pos, const glm::vec3 dir, const std::optional<std::uint32_t> max_depth) { // If the cube is empty, a collision with a ray is not possible, // and there are no sub cubes to check for collision either. if (cube.type() == Cube::Type::EMPTY) { // No collision found. return std::nullopt; } // We need to pass this into glm::intersectRaySphere by reference, // although we are not interested into it. auto intersection_distance{0.0f}; const auto bounding_sphere_radius = static_cast<float>(glm::sqrt(3) * cube.size()) / 2.0f; const auto sphere_radius_squared = static_cast<float>(std::pow(bounding_sphere_radius, 2)); // First, check if ray collides with bounding sphere. // This is much easier to calculate than a collision with a bounding box. if (!glm::intersectRaySphere(pos, dir, cube.center(), sphere_radius_squared, intersection_distance)) { // No collision found. return std::nullopt; } // Second, check if ray collides with bounding box. // This again is also much faster than to check for collision with every one of the 8 sub cubes. // TODO: This is an axis aligned bounding box! Alignment must account for rotation in the future! if (!ray_box_collision(cube.bounding_box(), pos, dir)) { // No collision found. return std::nullopt; } if (cube.type() == Cube::Type::OCTANT) { std::size_t hit_candidate_count{0}; std::size_t collision_subcube_index{0}; float m_nearest_square_distance = std::numeric_limits<float>::max(); auto subcubes = cube.children(); if (max_depth.has_value()) { // Check if the maximum depth is reached. if (max_depth.value() == 0) { // If the maximum depth is reached but the cube is empty, no collision was found. if (cube.type() == Cube::Type::EMPTY) { return std::nullopt; } // The current cube is of type OCTANT but not of type SOLID, but since we reached the maximum depth of // iteration, we treat it as type SOLID. return std::make_optional<RayCubeCollision<Cube>>(cube, pos, dir); } } // Iterate through all sub cubes and check for collision. for (std::int32_t i = 0; i < 8; i++) { if (subcubes[i]->type() != Cube::Type::EMPTY) { const std::optional<std::uint32_t> next_depth = max_depth.has_value() ? std::make_optional<std::uint32_t>(max_depth.value() - 1) : std::nullopt; // No value for maximum depth given. Continue iterating until you find a leaf node of type SOLID. if (ray_cube_collision_check(*subcubes[i], pos, dir, next_depth)) { hit_candidate_count++; // If a ray collides with an octant, it can collide with multiple child cubes as it goes // through it. We need to find the cube which is nearest to the camera and also in front of // the camera. const auto squared_distance = glm::distance2(subcubes[i]->center(), pos); if (squared_distance < m_nearest_square_distance) { collision_subcube_index = i; m_nearest_square_distance = squared_distance; } } } // If a ray goes through a cube of 8 subcubes, no more than 4 collisions can take place. if (hit_candidate_count == 4) { break; } } if (hit_candidate_count > 0) { return std::make_optional<RayCubeCollision<Cube>>(*subcubes[collision_subcube_index], pos, dir); } } else if (cube.type() == Cube::Type::SOLID) { // We found a leaf collision. Now we need to determine the selected face, // nearest corner to intersection point and nearest edge to intersection point. return std::make_optional<RayCubeCollision<Cube>>(cube, pos, dir); } // No collision found. return std::nullopt; } } // namespace inexor::vulkan_renderer::world <|start_filename|>include/inexor/vulkan-renderer/wrapper/command_pool.hpp<|end_filename|> #pragma once #include <spdlog/spdlog.h> #include <vulkan/vulkan_core.h> #include <cassert> namespace inexor::vulkan_renderer::wrapper { class Device; /// @brief RAII wrapper class for VkCommandPool. class CommandPool { const Device &m_device; VkCommandPool m_command_pool{VK_NULL_HANDLE}; public: /// @brief Default constructor. /// @note It is important that the queue family index is specified in the abstraction above this command pool /// wrapper. We can't choose one queue family index automatically inside of this wrapper which fits every purpose, /// because some wrappers require a queue family index which supports graphics bit, other require transfer bit. /// @param device The const reference to the device RAII wrapper class. /// @param queue_family_index The queue family index which is used by this command pool. CommandPool(const Device &device, std::uint32_t queue_family_index); CommandPool(const CommandPool &) = delete; CommandPool(CommandPool &&) noexcept; ~CommandPool(); CommandPool &operator=(const CommandPool &) = delete; CommandPool &operator=(CommandPool &&) = delete; [[nodiscard]] VkCommandPool get() const { return m_command_pool; } [[nodiscard]] const VkCommandPool *ptr() const { return &m_command_pool; } }; } // namespace inexor::vulkan_renderer::wrapper <|start_filename|>benchmarks/world/cube_collision.cpp<|end_filename|> #include <benchmark/benchmark.h> #include <inexor/vulkan-renderer/world/collision_query.hpp> #include <inexor/vulkan-renderer/world/cube.hpp> namespace inexor::vulkan_renderer { void CubeCollision(benchmark::State &state) { for (auto _ : state) { const glm::vec3 world_pos{0, 0, 0}; world::Cube world(1.0f, world_pos); world.set_type(world::Cube::Type::SOLID); glm::vec3 cam_pos{0.0f, 0.0f, 10.0f}; glm::vec3 cam_direction{0.0f, 0.0f, -1.0f}; benchmark::DoNotOptimize(ray_cube_collision_check(world, cam_pos, cam_direction)); } } BENCHMARK(CubeCollision); } // namespace inexor::vulkan_renderer <|start_filename|>shaders/ui.vert<|end_filename|> #version 450 layout (location = 0) in vec2 in_pos; layout (location = 1) in vec2 in_uv; layout (location = 2) in vec4 in_color; layout (push_constant) uniform PushConstants { vec2 scale; vec2 translate; } push_constants; layout (location = 0) out vec2 out_uv; layout (location = 1) out vec4 out_color; void main() { out_uv = in_uv; out_color = in_color; gl_Position = vec4(in_pos * push_constants.scale + push_constants.translate, 0.0, 1.0); } <|start_filename|>shaders/main.vert<|end_filename|> #version 450 layout (location = 0) in vec3 in_position; layout (location = 1) in vec3 in_color; layout (binding = 0) uniform UniformBufferObject { mat4 model; mat4 view; mat4 proj; } ubo; layout (location = 0) out vec3 frag_color; void main() { gl_Position = ubo.proj * ubo.view * ubo.model * vec4(in_position, 1.0); frag_color = in_color; } <|start_filename|>src/vulkan-renderer/input/keyboard_mouse_data.cpp<|end_filename|> #include "inexor/vulkan-renderer/input/keyboard_mouse_data.hpp" #include <cassert> #include <mutex> namespace inexor::vulkan_renderer::input { void KeyboardMouseInputData::press_key(const std::int32_t key) { assert(key >= 0); assert(key < GLFW_KEY_LAST); std::scoped_lock lock(m_input_mutex); m_pressed_keys[key] = true; m_keyboard_updated = true; } void KeyboardMouseInputData::release_key(const std::int32_t key) { assert(key >= 0); assert(key < GLFW_KEY_LAST); std::scoped_lock lock(m_input_mutex); m_pressed_keys[key] = false; m_keyboard_updated = true; } bool KeyboardMouseInputData::is_key_pressed(const std::int32_t key) const { assert(key >= 0); assert(key < GLFW_KEY_LAST); std::shared_lock lock(m_input_mutex); return m_pressed_keys[key]; } bool KeyboardMouseInputData::was_key_pressed_once(const std::int32_t key) { assert(key >= 0); assert(key < GLFW_KEY_LAST); std::scoped_lock lock(m_input_mutex); if (!m_pressed_keys[key] || !m_keyboard_updated) { return false; } m_pressed_keys[key] = false; return true; } void KeyboardMouseInputData::press_mouse_button(const std::int32_t button) { assert(button >= 0); assert(button < GLFW_MOUSE_BUTTON_LAST); std::scoped_lock lock(m_input_mutex); m_pressed_mouse_buttons[button] = true; m_mouse_buttons_updated = true; } void KeyboardMouseInputData::release_mouse_button(const std::int32_t button) { assert(button >= 0); assert(button < GLFW_MOUSE_BUTTON_LAST); std::scoped_lock lock(m_input_mutex); m_pressed_mouse_buttons[button] = false; m_mouse_buttons_updated = true; } bool KeyboardMouseInputData::is_mouse_button_pressed(const std::int32_t button) const { assert(button >= 0); assert(button < GLFW_MOUSE_BUTTON_LAST); std::shared_lock lock(m_input_mutex); return m_pressed_mouse_buttons[button]; } bool KeyboardMouseInputData::was_mouse_button_pressed_once(const std::int32_t button) { assert(button >= 0); assert(button < GLFW_MOUSE_BUTTON_LAST); std::scoped_lock lock(m_input_mutex); if (!m_pressed_mouse_buttons[button] || !m_mouse_buttons_updated) { return false; } m_pressed_mouse_buttons[button] = false; return true; } void KeyboardMouseInputData::set_cursor_pos(const double pos_x, const double pos_y) { std::scoped_lock lock(m_input_mutex); m_current_cursor_pos[0] = static_cast<std::int64_t>(pos_x); m_current_cursor_pos[1] = static_cast<std::int64_t>(pos_y); } std::array<std::int64_t, 2> KeyboardMouseInputData::get_cursor_pos() const { std::shared_lock lock(m_input_mutex); return m_current_cursor_pos; } std::array<double, 2> KeyboardMouseInputData::calculate_cursor_position_delta() { std::scoped_lock lock(m_input_mutex); // Calculate the change in cursor position in x- and y-axis. const std::array m_cursor_pos_delta{ static_cast<double>(m_current_cursor_pos[0]) - static_cast<double>(m_previous_cursor_pos[0]), static_cast<double>(m_current_cursor_pos[1]) - static_cast<double>(m_previous_cursor_pos[1])}; m_previous_cursor_pos = m_current_cursor_pos; return m_cursor_pos_delta; } } // namespace inexor::vulkan_renderer::input <|start_filename|>include/inexor/vulkan-renderer/imgui.hpp<|end_filename|> #pragma once #include "inexor/vulkan-renderer/render_graph.hpp" #include "inexor/vulkan-renderer/wrapper/descriptor.hpp" #include "inexor/vulkan-renderer/wrapper/gpu_texture.hpp" #include "inexor/vulkan-renderer/wrapper/shader.hpp" #include <glm/vec2.hpp> #include <imgui.h> #include <vulkan/vulkan_core.h> #include <memory> #include <vector> namespace inexor::vulkan_renderer::wrapper { class Device; class Swapchain; } // namespace inexor::vulkan_renderer::wrapper namespace inexor::vulkan_renderer { class ImGUIOverlay { const wrapper::Device &m_device; const wrapper::Swapchain &m_swapchain; float m_scale{1.0f}; BufferResource *m_index_buffer{nullptr}; BufferResource *m_vertex_buffer{nullptr}; GraphicsStage *m_stage{nullptr}; std::unique_ptr<wrapper::GpuTexture> m_imgui_texture; std::unique_ptr<wrapper::Shader> m_vertex_shader; std::unique_ptr<wrapper::Shader> m_fragment_shader; std::unique_ptr<wrapper::ResourceDescriptor> m_descriptor; std::vector<std::uint32_t> m_index_data; std::vector<ImDrawVert> m_vertex_data; struct PushConstBlock { glm::vec2 scale; glm::vec2 translate; } m_push_const_block{}; public: /// @brief Construct a new ImGUI overlay. /// @param device A reference to the device wrapper /// @param swapchain A reference to the swapchain /// @param render_graph A pointer to the render graph /// @param back_buffer A pointer to the target of the ImGUI rendering ImGUIOverlay(const wrapper::Device &device, const wrapper::Swapchain &swapchain, RenderGraph *render_graph, TextureResource *back_buffer); ImGUIOverlay(const ImGUIOverlay &) = delete; ImGUIOverlay(ImGUIOverlay &&) = delete; ~ImGUIOverlay(); ImGUIOverlay &operator=(const ImGUIOverlay &) = delete; ImGUIOverlay &operator=(ImGUIOverlay &&) = delete; void update(); [[nodiscard]] float scale() const { return m_scale; } }; } // namespace inexor::vulkan_renderer <|start_filename|>include/inexor/vulkan-renderer/wrapper/descriptor.hpp<|end_filename|> #pragma once #include <vulkan/vulkan_core.h> #include <string> #include <vector> namespace inexor::vulkan_renderer::wrapper { class Device; /// @brief RAII wrapper class for resource descriptors. class ResourceDescriptor { std::string m_name; const Device &m_device; VkDescriptorPool m_descriptor_pool{VK_NULL_HANDLE}; VkDescriptorSetLayout m_descriptor_set_layout{VK_NULL_HANDLE}; std::vector<VkDescriptorSetLayoutBinding> m_descriptor_set_layout_bindings; std::vector<VkWriteDescriptorSet> m_write_descriptor_sets; std::vector<VkDescriptorSet> m_descriptor_sets; std::uint32_t m_swapchain_image_count{0}; public: /// @brief Default constructor. /// @param device The const reference to a device RAII wrapper instance. /// @param swapchain_image_count The number of images in swapchain. /// @param layout_bindings The descriptor layout bindings. /// @param descriptor_writes The write descriptor sets. /// @param name The internal debug marker name of the resource descriptor. ResourceDescriptor(const Device &device, std::uint32_t swapchain_image_count, std::vector<VkDescriptorSetLayoutBinding> &&layout_bindings, std::vector<VkWriteDescriptorSet> &&descriptor_writes, std::string &&name); ResourceDescriptor(const ResourceDescriptor &) = delete; ResourceDescriptor(ResourceDescriptor &&) noexcept; ~ResourceDescriptor(); ResourceDescriptor &operator=(const ResourceDescriptor &) = delete; ResourceDescriptor &operator=(ResourceDescriptor &&) = delete; [[nodiscard]] const auto &descriptor_sets() const { return m_descriptor_sets; } [[nodiscard]] auto descriptor_set_layout() const { return m_descriptor_set_layout; } [[nodiscard]] const auto &descriptor_set_layout_bindings() const { return m_descriptor_set_layout_bindings; } }; } // namespace inexor::vulkan_renderer::wrapper <|start_filename|>include/inexor/vulkan-renderer/io/exception.hpp<|end_filename|> #include "inexor/vulkan-renderer/exception.hpp" namespace inexor::vulkan_renderer::io { class IoException : public InexorException { using InexorException::InexorException; }; } // namespace inexor::vulkan_renderer::io <|start_filename|>src/vulkan-renderer/world/indentation.cpp<|end_filename|> #include "inexor/vulkan-renderer/world/indentation.hpp" #include <algorithm> #include <array> #include <cassert> #include <cmath> namespace inexor::vulkan_renderer::world { Indentation::Indentation(const std::uint8_t start, const std::uint8_t end) noexcept : m_start(start), m_end(end) {} Indentation::Indentation(const std::uint8_t uid) noexcept { assert(uid <= 44); constexpr std::array<std::uint8_t, Indentation::MAX> MASKS{44, 42, 39, 35, 30, 24, 17, 9}; for (std::uint8_t idx = 0; idx < Indentation::MAX; idx++) { if (MASKS[idx] <= uid) { m_start = Indentation::MAX - idx; m_end = m_start + (uid - MASKS[idx]); return; } } m_start = 0; m_end = uid; } bool Indentation::operator==(const Indentation &rhs) const { return this->m_start == rhs.m_start && this->m_end == rhs.m_end; } bool Indentation::operator!=(const Indentation &rhs) const { return !(*this == rhs); } void Indentation::set_start(std::uint8_t position) noexcept { this->m_start = std::clamp<std::uint8_t>(position, 0, Indentation::MAX); this->m_end = std::clamp<std::uint8_t>(this->m_end, this->m_start, Indentation::MAX); } void Indentation::set_end(std::uint8_t position) noexcept { this->m_end = std::clamp<std::uint8_t>(position, 0, Indentation::MAX); this->m_start = std::clamp<std::uint8_t>(this->m_start, 0, this->m_end); } std::uint8_t Indentation::start_abs() const noexcept { return this->m_start; } std::uint8_t Indentation::end_abs() const noexcept { return this->m_end; } std::uint8_t Indentation::start() const noexcept { return this->m_start; } std::uint8_t Indentation::end() const noexcept { return Indentation::MAX - this->m_end; } std::uint8_t Indentation::offset() const noexcept { return this->m_end - this->m_start; } void Indentation::indent_start(std::uint8_t steps) noexcept { this->set_start(this->m_start + steps); } void Indentation::indent_end(std::uint8_t steps) noexcept { this->set_end(this->m_end - steps); } void Indentation::mirror() noexcept { std::uint8_t new_start = end(); m_end = Indentation::MAX - m_start; m_start = new_start; } std::uint8_t Indentation::uid() const { return static_cast<std::uint8_t>(10 * m_start + offset() - (std::pow(m_start, 2) + m_start) / 2); } } // namespace inexor::vulkan_renderer::world <|start_filename|>include/inexor/vulkan-renderer/io/byte_stream.hpp<|end_filename|> #pragma once #include <cstdint> #include <filesystem> #include <vector> namespace inexor::vulkan_renderer::io { class ByteStream { protected: std::vector<std::uint8_t> m_buffer; /// Read from file. [[nodiscard]] static std::vector<std::uint8_t> read_file(const std::filesystem::path &path); public: ByteStream() = default; explicit ByteStream(std::vector<std::uint8_t> buffer); /// Read from file. explicit ByteStream(const std::filesystem::path &path); [[nodiscard]] std::size_t size() const; [[nodiscard]] const std::vector<std::uint8_t> &buffer() const; }; class ByteStreamReader { private: const ByteStream &m_stream; /// Stream iterator. std::vector<std::uint8_t>::const_iterator m_iter; void check_end(std::size_t size) const; public: explicit ByteStreamReader(const ByteStream &stream); [[nodiscard]] std::size_t remaining() const; /// Skip 'size' bytes (std::uint8_t). void skip(std::size_t size); /// Generic read method. template <typename T, typename... Args> [[nodiscard]] T read(const Args &...); }; class ByteStreamWriter : public ByteStream { public: using ByteStream::ByteStream; /// Generic write method. template <typename T> void write(const T &value); }; } // namespace inexor::vulkan_renderer::io <|start_filename|>src/vulkan-renderer/world/collision.cpp<|end_filename|> #include <inexor/vulkan-renderer/world/collision.hpp> #include <inexor/vulkan-renderer/world/cube.hpp> #include <glm/geometric.hpp> #include <glm/gtx/vector_angle.hpp> #include <array> #include <limits> #include <memory> #include <utility> namespace inexor::vulkan_renderer::world { template <typename T> RayCubeCollision<T>::RayCubeCollision(RayCubeCollision &&other) noexcept : m_cube{other.m_cube} { m_intersection = other.m_intersection; m_selected_face = other.m_selected_face; m_nearest_corner = other.m_nearest_corner; m_nearest_edge = other.m_nearest_edge; } template <typename T> RayCubeCollision<T>::RayCubeCollision(const T &cube, const glm::vec3 ray_pos, const glm::vec3 ray_dir) : m_cube(cube) { // This lambda adjusts the center points on a cube's face to the size of the octree, // so collision works with cubes of any size. This does not yet account for rotations! const auto adjust_coordinates = [=](const glm::vec3 pos) { // TODO: Take rotation of the cube into account. return m_cube.center() + pos * (m_cube.size() / 2); }; // x: left/right, y: front/back, z: top/bottom. static constexpr std::array BBOX_DIRECTIONS{ glm::vec3(-1.0f, 0.0f, 0.0f), // left glm::vec3(1.0f, 0.0f, 0.0f), // right glm::vec3(0.0f, -1.0f, 0.0f), // front glm::vec3(0.0f, 1.0f, 0.0f), // back glm::vec3(0.0f, 0.0f, 1.0f), // top glm::vec3(0.0f, 0.0f, -1.0f) // bottom }; // The coordinates of the center of every face of the cube. const std::array bbox_face_centers{adjust_coordinates(BBOX_DIRECTIONS[0]), // left adjust_coordinates(BBOX_DIRECTIONS[1]), // right adjust_coordinates(BBOX_DIRECTIONS[2]), // front adjust_coordinates(BBOX_DIRECTIONS[3]), // back adjust_coordinates(BBOX_DIRECTIONS[4]), // top adjust_coordinates(BBOX_DIRECTIONS[5])}; // bottom const std::array bbox_corners{adjust_coordinates({-1.0f, -1.0f, -1.0f}), // left front bottom adjust_coordinates({-1.0f, -1.0f, 1.0f}), // left front top adjust_coordinates({-1.0f, 1.0f, -1.0f}), // left back bottom adjust_coordinates({-1.0f, 1.0f, 1.0f}), // left back top adjust_coordinates({1.0f, -1.0f, -1.0f}), // right front bottom adjust_coordinates({1.0f, -1.0f, 1.0f}), // right front top adjust_coordinates({1.0f, 1.0f, 1.0f}), // right back bottom adjust_coordinates({1.0f, 1.0f, -1.0f})}; // right back top using bbox_corner_on_face_index = std::array<std::size_t, 4>; // These indices specify which 4 points describe the corners on the given face. static constexpr std::array BBOX_CORNERS_ON_FACE_INDICES{ bbox_corner_on_face_index{0, 1, 2, 3}, // left bbox_corner_on_face_index{4, 5, 6, 7}, // right bbox_corner_on_face_index{0, 1, 4, 5}, // front bbox_corner_on_face_index{2, 3, 6, 7}, // back bbox_corner_on_face_index{1, 3, 5, 7}, // top bbox_corner_on_face_index{0, 2, 4, 6} // bottom }; // The coordinates of the center of every edge of the cube. const std::array bbox_edges{adjust_coordinates({-1.0f, 0.0f, 1.0f}), // left top adjust_coordinates({-1.0f, 1.0f, 0.0f}), // left front adjust_coordinates({-1.0f, 0.0f, -1.0f}), // left bottom adjust_coordinates({-1.0f, -1.0f, 0.0f}), // left back adjust_coordinates({1.0f, 0.0f, 1.0f}), // right top adjust_coordinates({1.0f, 1.0f, 0.0f}), // right front adjust_coordinates({1.0f, 0.0f, -1.0f}), // right bottom adjust_coordinates({1.0f, -1.0f, 0.0f}), // right back adjust_coordinates({0.0f, -1.0f, -1.0f}), // middle bottom front adjust_coordinates({0.0f, 1.0f, -1.0f}), // middle bottom back adjust_coordinates({0.0f, -1.0f, 1.0f}), // middle top front adjust_coordinates({0.0f, 1.0f, 1.0f})}; // middle top back using edge_on_face_index = std::array<std::size_t, 4>; // These indices specify which 4 edges are associated with a given face of the bounding box. static constexpr std::array BBOX_EDGE_ON_FACE_INDICES{ edge_on_face_index{0, 1, 2, 3}, // left edge_on_face_index{4, 5, 6, 7}, // right edge_on_face_index{1, 5, 8, 11}, // front edge_on_face_index{3, 7, 9, 11}, // back edge_on_face_index{0, 4, 10, 11}, // top edge_on_face_index{2, 6, 8, 9} // bottom }; /// @brief Determine the intersection point between a ray and a plane. /// @note This function is not available in glm. /// @param plane_pos The position of the plane. /// @param plane_norm The normal vector of the plane. /// @param ray_pos Point a on the ray. /// @param ray_dir Point b on the ray. const auto ray_plane_intersection_point = [&](const glm::vec3 &plane_pos, const glm::vec3 &plane_norm, const glm::vec3 &ray_pos, const glm::vec3 &ray_dir) { return ray_pos - ray_dir * (glm::dot((ray_pos - plane_pos), plane_norm) / glm::dot(ray_dir, plane_norm)); }; /// @brief As soon as we determined which face is selected and we calculated the intersection point between the /// ray and the face plane, we need to determine the nearest corner in that face and the nearest edge on that /// face. In order to determine the nearest corner on a selected face for example, we would iterate through all /// corners on the selected face and calculate the distance between the intersection point and the corner's /// coordinates. The corner which is closest to the intersection point is the selected corner. /// However, we should not use ``glm::distance`` for this, because it performs a ``sqrt`` calculation on the /// vector coordinates. This is not necessary in this case, as we are not interested in the exact distance but /// rather in a value which allows us to determine the nearest corner. This means we can use the squared /// distance, which allows us to avoid the costly call of ``sqrt``. /// @param pos1 The first point. /// @param pos2 The second point. const auto square_of_distance = [&](const std::array<glm::vec3, 2> &points) { return glm::distance2(points[0], points[1]); }; float shortest_squared_distance{std::numeric_limits<float>::max()}; float squared_distance{std::numeric_limits<float>::max()}; // The index of the array which contains the coordinates of the face centers of the cube's bounding box. std::size_t selected_face_index{0}; // Loop though all faces of the cube and check for collision between ray and face plane. for (std::size_t i = 0; i < 6; i++) { // Check if the cube side is facing the camera: if the dot product of the two vectors is smaller than // zero, the corresponding angle is smaller than 90 degrees, so the side is facing the camera. Check the // references page for a detailed explanation of this formula. if (glm::dot(BBOX_DIRECTIONS[i], ray_dir) < 0.0f) { const auto intersection = ray_plane_intersection_point(bbox_face_centers[i], BBOX_DIRECTIONS[i], ray_pos, ray_dir); squared_distance = square_of_distance({m_cube.center(), intersection}); if (squared_distance < shortest_squared_distance) { selected_face_index = i; shortest_squared_distance = squared_distance; m_intersection = intersection; m_selected_face = bbox_face_centers[i]; } } } // Reset value to maximum for the search of the closest corner. shortest_squared_distance = std::numeric_limits<float>::max(); // Loop through all corners of this face and check for the nearest one. for (const auto corner_index : BBOX_CORNERS_ON_FACE_INDICES[selected_face_index]) { squared_distance = square_of_distance({bbox_corners[corner_index], m_intersection}); if (squared_distance < shortest_squared_distance) { shortest_squared_distance = squared_distance; m_nearest_corner = bbox_corners[corner_index]; } } // Reset value to maximum for the search of the closest edge. shortest_squared_distance = std::numeric_limits<float>::max(); // Iterate through all edges on this face and select the nearest one. for (const auto edge_index : BBOX_EDGE_ON_FACE_INDICES[selected_face_index]) { squared_distance = square_of_distance({bbox_edges[edge_index], m_intersection}); if (squared_distance < shortest_squared_distance) { shortest_squared_distance = squared_distance; m_nearest_edge = bbox_edges[edge_index]; } } } // Explicit instantiation template RayCubeCollision<Cube>::RayCubeCollision(const Cube &, const glm::vec3, const glm::vec3); } // namespace inexor::vulkan_renderer::world <|start_filename|>src/vulkan-renderer/vk_tools/representation.cpp<|end_filename|> #include "inexor/vulkan-renderer/vk_tools/representation.hpp" namespace inexor::vulkan_renderer::vk_tools { /// @brief Convert a VkPresentModeKHR value into a corresponding std::string_view. /// @param present_mode The present mode. /// @return A std::string_view which contains the presentation mode. template <> std::string_view as_string(const VkPresentModeKHR present_mode) { switch (present_mode) { case VK_PRESENT_MODE_IMMEDIATE_KHR: return "VK_PRESENT_MODE_IMMEDIATE_KHR"; case VK_PRESENT_MODE_MAILBOX_KHR: return "VK_PRESENT_MODE_MAILBOX_KHR"; case VK_PRESENT_MODE_FIFO_KHR: return "VK_PRESENT_MODE_FIFO_KHR"; case VK_PRESENT_MODE_FIFO_RELAXED_KHR: return "VK_PRESENT_MODE_FIFO_RELAXED_KHR"; case VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR: return "VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR"; case VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR: return "VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR"; default: break; } return "Unknown"; } /// @brief Convert a VkPhysicalDeviceType value into a corresponding std::string_view. /// @param gpu_type The type of the physical device. /// @return A std::string_view which contains the physical device type. template <> std::string_view as_string(const VkPhysicalDeviceType gpu_type) { switch (gpu_type) { case VK_PHYSICAL_DEVICE_TYPE_OTHER: return "VK_PHYSICAL_DEVICE_TYPE_OTHER"; case VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU: return "VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU"; case VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU: return "VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU"; case VK_PHYSICAL_DEVICE_TYPE_VIRTUAL_GPU: return "VK_PHYSICAL_DEVICE_TYPE_VIRTUAL_GPU"; case VK_PHYSICAL_DEVICE_TYPE_CPU: return "VK_PHYSICAL_DEVICE_TYPE_CPU"; default: break; } return "Unknown"; } /// @brief Convert a VkFormat value into the corresponding value as std::string_view. /// @param format The VkFormat to convert. /// @return A std::string_view which contains the VkFormat. template <> std::string_view as_string(const VkFormat format) { switch (format) { case VK_FORMAT_UNDEFINED: return "VK_FORMAT_UNDEFINED"; case VK_FORMAT_R4G4_UNORM_PACK8: return "VK_FORMAT_R4G4_UNORM_PACK8"; case VK_FORMAT_R4G4B4A4_UNORM_PACK16: return "VK_FORMAT_R4G4B4A4_UNORM_PACK16"; case VK_FORMAT_B4G4R4A4_UNORM_PACK16: return "VK_FORMAT_B4G4R4A4_UNORM_PACK16"; case VK_FORMAT_R5G6B5_UNORM_PACK16: return "VK_FORMAT_R5G6B5_UNORM_PACK16"; case VK_FORMAT_B5G6R5_UNORM_PACK16: return "VK_FORMAT_B5G6R5_UNORM_PACK16"; case VK_FORMAT_R5G5B5A1_UNORM_PACK16: return "VK_FORMAT_R5G5B5A1_UNORM_PACK16"; case VK_FORMAT_B5G5R5A1_UNORM_PACK16: return "VK_FORMAT_B5G5R5A1_UNORM_PACK16"; case VK_FORMAT_A1R5G5B5_UNORM_PACK16: return "VK_FORMAT_A1R5G5B5_UNORM_PACK16"; case VK_FORMAT_R8_UNORM: return "VK_FORMAT_R8_UNORM"; case VK_FORMAT_R8_SNORM: return "VK_FORMAT_R8_SNORM"; case VK_FORMAT_R8_USCALED: return "VK_FORMAT_R8_USCALED"; case VK_FORMAT_R8_SSCALED: return "VK_FORMAT_R8_SSCALED"; case VK_FORMAT_R8_UINT: return "VK_FORMAT_R8_UINT"; case VK_FORMAT_R8_SINT: return "VK_FORMAT_R8_SINT"; case VK_FORMAT_R8_SRGB: return "VK_FORMAT_R8_SRGB"; case VK_FORMAT_R8G8_UNORM: return "VK_FORMAT_R8G8_UNORM"; case VK_FORMAT_R8G8_SNORM: return "VK_FORMAT_R8G8_SNORM"; case VK_FORMAT_R8G8_USCALED: return "VK_FORMAT_R8G8_USCALED"; case VK_FORMAT_R8G8_SSCALED: return "VK_FORMAT_R8G8_SSCALED"; case VK_FORMAT_R8G8_UINT: return "VK_FORMAT_R8G8_UINT"; case VK_FORMAT_R8G8_SINT: return "VK_FORMAT_R8G8_SINT"; case VK_FORMAT_R8G8_SRGB: return "VK_FORMAT_R8G8_SRGB"; case VK_FORMAT_R8G8B8_UNORM: return "VK_FORMAT_R8G8B8_UNORM"; case VK_FORMAT_R8G8B8_SNORM: return "VK_FORMAT_R8G8B8_SNORM"; case VK_FORMAT_R8G8B8_USCALED: return "VK_FORMAT_R8G8B8_USCALED"; case VK_FORMAT_R8G8B8_SSCALED: return "VK_FORMAT_R8G8B8_SSCALED"; case VK_FORMAT_R8G8B8_UINT: return "VK_FORMAT_R8G8B8_UINT"; case VK_FORMAT_R8G8B8_SINT: return "VK_FORMAT_R8G8B8_SINT"; case VK_FORMAT_R8G8B8_SRGB: return "VK_FORMAT_R8G8B8_SRGB"; case VK_FORMAT_B8G8R8_UNORM: return "VK_FORMAT_B8G8R8_UNORM"; case VK_FORMAT_B8G8R8_SNORM: return "VK_FORMAT_B8G8R8_SNORM"; case VK_FORMAT_B8G8R8_USCALED: return "VK_FORMAT_B8G8R8_USCALED"; case VK_FORMAT_B8G8R8_SSCALED: return "VK_FORMAT_B8G8R8_SSCALED"; case VK_FORMAT_B8G8R8_UINT: return "VK_FORMAT_B8G8R8_UINT"; case VK_FORMAT_B8G8R8_SINT: return "VK_FORMAT_B8G8R8_SINT"; case VK_FORMAT_B8G8R8_SRGB: return "VK_FORMAT_B8G8R8_SRGB"; case VK_FORMAT_R8G8B8A8_UNORM: return "VK_FORMAT_R8G8B8A8_UNORM"; case VK_FORMAT_R8G8B8A8_SNORM: return "VK_FORMAT_R8G8B8A8_SNORM"; case VK_FORMAT_R8G8B8A8_USCALED: return "VK_FORMAT_R8G8B8A8_USCALED"; case VK_FORMAT_R8G8B8A8_SSCALED: return "VK_FORMAT_R8G8B8A8_SSCALED"; case VK_FORMAT_R8G8B8A8_UINT: return "VK_FORMAT_R8G8B8A8_UINT"; case VK_FORMAT_R8G8B8A8_SINT: return "VK_FORMAT_R8G8B8A8_SINT"; case VK_FORMAT_R8G8B8A8_SRGB: return "VK_FORMAT_R8G8B8A8_SRGB"; case VK_FORMAT_B8G8R8A8_UNORM: return "VK_FORMAT_B8G8R8A8_UNORM"; case VK_FORMAT_B8G8R8A8_SNORM: return "VK_FORMAT_B8G8R8A8_SNORM"; case VK_FORMAT_B8G8R8A8_USCALED: return "VK_FORMAT_B8G8R8A8_USCALED"; case VK_FORMAT_B8G8R8A8_SSCALED: return "VK_FORMAT_B8G8R8A8_SSCALED"; case VK_FORMAT_B8G8R8A8_UINT: return "VK_FORMAT_B8G8R8A8_UINT"; case VK_FORMAT_B8G8R8A8_SINT: return "VK_FORMAT_B8G8R8A8_SINT"; case VK_FORMAT_B8G8R8A8_SRGB: return "VK_FORMAT_B8G8R8A8_SRGB"; case VK_FORMAT_A8B8G8R8_UNORM_PACK32: return "VK_FORMAT_A8B8G8R8_UNORM_PACK32"; case VK_FORMAT_A8B8G8R8_SNORM_PACK32: return "VK_FORMAT_A8B8G8R8_SNORM_PACK32"; case VK_FORMAT_A8B8G8R8_USCALED_PACK32: return "VK_FORMAT_A8B8G8R8_USCALED_PACK32"; case VK_FORMAT_A8B8G8R8_SSCALED_PACK32: return "VK_FORMAT_A8B8G8R8_SSCALED_PACK32"; case VK_FORMAT_A8B8G8R8_UINT_PACK32: return "VK_FORMAT_A8B8G8R8_UINT_PACK32"; case VK_FORMAT_A8B8G8R8_SINT_PACK32: return "VK_FORMAT_A8B8G8R8_SINT_PACK32"; case VK_FORMAT_A8B8G8R8_SRGB_PACK32: return "VK_FORMAT_A8B8G8R8_SRGB_PACK32"; case VK_FORMAT_A2R10G10B10_UNORM_PACK32: return "VK_FORMAT_A2R10G10B10_UNORM_PACK32"; case VK_FORMAT_A2R10G10B10_SNORM_PACK32: return "VK_FORMAT_A2R10G10B10_SNORM_PACK32"; case VK_FORMAT_A2R10G10B10_USCALED_PACK32: return "VK_FORMAT_A2R10G10B10_USCALED_PACK32"; case VK_FORMAT_A2R10G10B10_SSCALED_PACK32: return "VK_FORMAT_A2R10G10B10_SSCALED_PACK32"; case VK_FORMAT_A2R10G10B10_UINT_PACK32: return "VK_FORMAT_A2R10G10B10_UINT_PACK32"; case VK_FORMAT_A2R10G10B10_SINT_PACK32: return "VK_FORMAT_A2R10G10B10_SINT_PACK32"; case VK_FORMAT_A2B10G10R10_UNORM_PACK32: return "VK_FORMAT_A2B10G10R10_UNORM_PACK32"; case VK_FORMAT_A2B10G10R10_SNORM_PACK32: return "VK_FORMAT_A2B10G10R10_SNORM_PACK32"; case VK_FORMAT_A2B10G10R10_USCALED_PACK32: return "VK_FORMAT_A2B10G10R10_USCALED_PACK32"; case VK_FORMAT_A2B10G10R10_SSCALED_PACK32: return "VK_FORMAT_A2B10G10R10_SSCALED_PACK32"; case VK_FORMAT_A2B10G10R10_UINT_PACK32: return "VK_FORMAT_A2B10G10R10_UINT_PACK32"; case VK_FORMAT_A2B10G10R10_SINT_PACK32: return "VK_FORMAT_A2B10G10R10_SINT_PACK32"; case VK_FORMAT_R16_UNORM: return "VK_FORMAT_R16_UNORM"; case VK_FORMAT_R16_SNORM: return "VK_FORMAT_R16_SNORM"; case VK_FORMAT_R16_USCALED: return "VK_FORMAT_R16_USCALED"; case VK_FORMAT_R16_SSCALED: return "VK_FORMAT_R16_SSCALED"; case VK_FORMAT_R16_UINT: return "VK_FORMAT_R16_UINT"; case VK_FORMAT_R16_SINT: return "VK_FORMAT_R16_SINT"; case VK_FORMAT_R16_SFLOAT: return "VK_FORMAT_R16_SFLOAT"; case VK_FORMAT_R16G16_UNORM: return "VK_FORMAT_R16G16_UNORM"; case VK_FORMAT_R16G16_SNORM: return "VK_FORMAT_R16G16_SNORM"; case VK_FORMAT_R16G16_USCALED: return "VK_FORMAT_R16G16_USCALED"; case VK_FORMAT_R16G16_SSCALED: return "VK_FORMAT_R16G16_SSCALED"; case VK_FORMAT_R16G16_UINT: return "VK_FORMAT_R16G16_UINT"; case VK_FORMAT_R16G16_SINT: return "VK_FORMAT_R16G16_SINT"; case VK_FORMAT_R16G16_SFLOAT: return "VK_FORMAT_R16G16_SFLOAT"; case VK_FORMAT_R16G16B16_UNORM: return "VK_FORMAT_R16G16B16_UNORM"; case VK_FORMAT_R16G16B16_SNORM: return "VK_FORMAT_R16G16B16_SNORM"; case VK_FORMAT_R16G16B16_USCALED: return "VK_FORMAT_R16G16B16_USCALED"; case VK_FORMAT_R16G16B16_SSCALED: return "VK_FORMAT_R16G16B16_SSCALED"; case VK_FORMAT_R16G16B16_UINT: return "VK_FORMAT_R16G16B16_UINT"; case VK_FORMAT_R16G16B16_SINT: return "VK_FORMAT_R16G16B16_SINT"; case VK_FORMAT_R16G16B16_SFLOAT: return "VK_FORMAT_R16G16B16_SFLOAT"; case VK_FORMAT_R16G16B16A16_UNORM: return "VK_FORMAT_R16G16B16A16_UNORM"; case VK_FORMAT_R16G16B16A16_SNORM: return "VK_FORMAT_R16G16B16A16_SNORM"; case VK_FORMAT_R16G16B16A16_USCALED: return "VK_FORMAT_R16G16B16A16_USCALED"; case VK_FORMAT_R16G16B16A16_SSCALED: return "VK_FORMAT_R16G16B16A16_SSCALED"; case VK_FORMAT_R16G16B16A16_UINT: return "VK_FORMAT_R16G16B16A16_UINT"; case VK_FORMAT_R16G16B16A16_SINT: return "VK_FORMAT_R16G16B16A16_SINT"; case VK_FORMAT_R16G16B16A16_SFLOAT: return "VK_FORMAT_R16G16B16A16_SFLOAT"; case VK_FORMAT_R32_UINT: return "VK_FORMAT_R32_UINT"; case VK_FORMAT_R32_SINT: return "VK_FORMAT_R32_SINT"; case VK_FORMAT_R32_SFLOAT: return "VK_FORMAT_R32_SFLOAT"; case VK_FORMAT_R32G32_UINT: return "VK_FORMAT_R32G32_UINT"; case VK_FORMAT_R32G32_SINT: return "VK_FORMAT_R32G32_SINT"; case VK_FORMAT_R32G32_SFLOAT: return "VK_FORMAT_R32G32_SFLOAT"; case VK_FORMAT_R32G32B32_UINT: return "VK_FORMAT_R32G32B32_UINT"; case VK_FORMAT_R32G32B32_SINT: return "VK_FORMAT_R32G32B32_SINT"; case VK_FORMAT_R32G32B32_SFLOAT: return "VK_FORMAT_R32G32B32_SFLOAT"; case VK_FORMAT_R32G32B32A32_UINT: return "VK_FORMAT_R32G32B32A32_UINT"; case VK_FORMAT_R32G32B32A32_SINT: return "VK_FORMAT_R32G32B32A32_SINT"; case VK_FORMAT_R32G32B32A32_SFLOAT: return "VK_FORMAT_R32G32B32A32_SFLOAT"; case VK_FORMAT_R64_UINT: return "VK_FORMAT_R64_UINT"; case VK_FORMAT_R64_SINT: return "VK_FORMAT_R64_SINT"; case VK_FORMAT_R64_SFLOAT: return "VK_FORMAT_R64_SFLOAT"; case VK_FORMAT_R64G64_UINT: return "VK_FORMAT_R64G64_UINT"; case VK_FORMAT_R64G64_SINT: return "VK_FORMAT_R64G64_SINT"; case VK_FORMAT_R64G64_SFLOAT: return "VK_FORMAT_R64G64_SFLOAT"; case VK_FORMAT_R64G64B64_UINT: return "VK_FORMAT_R64G64B64_UINT"; case VK_FORMAT_R64G64B64_SINT: return "VK_FORMAT_R64G64B64_SINT"; case VK_FORMAT_R64G64B64_SFLOAT: return "VK_FORMAT_R64G64B64_SFLOAT"; case VK_FORMAT_R64G64B64A64_UINT: return "VK_FORMAT_R64G64B64A64_UINT"; case VK_FORMAT_R64G64B64A64_SINT: return "VK_FORMAT_R64G64B64A64_SINT"; case VK_FORMAT_R64G64B64A64_SFLOAT: return "VK_FORMAT_R64G64B64A64_SFLOAT"; case VK_FORMAT_B10G11R11_UFLOAT_PACK32: return "VK_FORMAT_B10G11R11_UFLOAT_PACK32"; case VK_FORMAT_E5B9G9R9_UFLOAT_PACK32: return "VK_FORMAT_E5B9G9R9_UFLOAT_PACK32"; case VK_FORMAT_D16_UNORM: return "VK_FORMAT_D16_UNORM"; case VK_FORMAT_X8_D24_UNORM_PACK32: return "VK_FORMAT_X8_D24_UNORM_PACK32"; case VK_FORMAT_D32_SFLOAT: return "VK_FORMAT_D32_SFLOAT"; case VK_FORMAT_S8_UINT: return "VK_FORMAT_S8_UINT"; case VK_FORMAT_D16_UNORM_S8_UINT: return "VK_FORMAT_D16_UNORM_S8_UINT"; case VK_FORMAT_D24_UNORM_S8_UINT: return "VK_FORMAT_D24_UNORM_S8_UINT"; case VK_FORMAT_D32_SFLOAT_S8_UINT: return "VK_FORMAT_D32_SFLOAT_S8_UINT"; case VK_FORMAT_BC1_RGB_UNORM_BLOCK: return "VK_FORMAT_BC1_RGB_UNORM_BLOCK"; case VK_FORMAT_BC1_RGB_SRGB_BLOCK: return "VK_FORMAT_BC1_RGB_SRGB_BLOCK"; case VK_FORMAT_BC1_RGBA_UNORM_BLOCK: return "VK_FORMAT_BC1_RGBA_UNORM_BLOCK"; case VK_FORMAT_BC1_RGBA_SRGB_BLOCK: return "VK_FORMAT_BC1_RGBA_SRGB_BLOCK"; case VK_FORMAT_BC2_UNORM_BLOCK: return "VK_FORMAT_BC2_UNORM_BLOCK"; case VK_FORMAT_BC2_SRGB_BLOCK: return "VK_FORMAT_BC2_SRGB_BLOCK"; case VK_FORMAT_BC3_UNORM_BLOCK: return "VK_FORMAT_BC3_UNORM_BLOCK"; case VK_FORMAT_BC3_SRGB_BLOCK: return "VK_FORMAT_BC3_SRGB_BLOCK"; case VK_FORMAT_BC4_UNORM_BLOCK: return "VK_FORMAT_BC4_UNORM_BLOCK"; case VK_FORMAT_BC4_SNORM_BLOCK: return "VK_FORMAT_BC4_SNORM_BLOCK"; case VK_FORMAT_BC5_UNORM_BLOCK: return "VK_FORMAT_BC5_UNORM_BLOCK"; case VK_FORMAT_BC5_SNORM_BLOCK: return "VK_FORMAT_BC5_SNORM_BLOCK"; case VK_FORMAT_BC6H_UFLOAT_BLOCK: return "VK_FORMAT_BC6H_UFLOAT_BLOCK"; case VK_FORMAT_BC6H_SFLOAT_BLOCK: return "VK_FORMAT_BC6H_SFLOAT_BLOCK"; case VK_FORMAT_BC7_UNORM_BLOCK: return "VK_FORMAT_BC7_UNORM_BLOCK"; case VK_FORMAT_BC7_SRGB_BLOCK: return "VK_FORMAT_BC7_SRGB_BLOCK"; case VK_FORMAT_ETC2_R8G8B8_UNORM_BLOCK: return "VK_FORMAT_ETC2_R8G8B8_UNORM_BLOCK"; case VK_FORMAT_ETC2_R8G8B8_SRGB_BLOCK: return "VK_FORMAT_ETC2_R8G8B8_SRGB_BLOCK"; case VK_FORMAT_ETC2_R8G8B8A1_UNORM_BLOCK: return "VK_FORMAT_ETC2_R8G8B8A1_UNORM_BLOCK"; case VK_FORMAT_ETC2_R8G8B8A1_SRGB_BLOCK: return "VK_FORMAT_ETC2_R8G8B8A1_SRGB_BLOCK"; case VK_FORMAT_ETC2_R8G8B8A8_UNORM_BLOCK: return "VK_FORMAT_ETC2_R8G8B8A8_UNORM_BLOCK"; case VK_FORMAT_ETC2_R8G8B8A8_SRGB_BLOCK: return "VK_FORMAT_ETC2_R8G8B8A8_SRGB_BLOCK"; case VK_FORMAT_EAC_R11_UNORM_BLOCK: return "VK_FORMAT_EAC_R11_UNORM_BLOCK"; case VK_FORMAT_EAC_R11_SNORM_BLOCK: return "VK_FORMAT_EAC_R11_SNORM_BLOCK"; case VK_FORMAT_EAC_R11G11_UNORM_BLOCK: return "VK_FORMAT_EAC_R11G11_UNORM_BLOCK"; case VK_FORMAT_EAC_R11G11_SNORM_BLOCK: return "VK_FORMAT_EAC_R11G11_SNORM_BLOCK"; case VK_FORMAT_ASTC_4x4_UNORM_BLOCK: return "VK_FORMAT_ASTC_4x4_UNORM_BLOCK"; case VK_FORMAT_ASTC_4x4_SRGB_BLOCK: return "VK_FORMAT_ASTC_4x4_SRGB_BLOCK"; case VK_FORMAT_ASTC_5x4_UNORM_BLOCK: return "VK_FORMAT_ASTC_5x4_UNORM_BLOCK"; case VK_FORMAT_ASTC_5x4_SRGB_BLOCK: return "VK_FORMAT_ASTC_5x4_SRGB_BLOCK"; case VK_FORMAT_ASTC_5x5_UNORM_BLOCK: return "VK_FORMAT_ASTC_5x5_UNORM_BLOCK"; case VK_FORMAT_ASTC_5x5_SRGB_BLOCK: return "VK_FORMAT_ASTC_5x5_SRGB_BLOCK"; case VK_FORMAT_ASTC_6x5_UNORM_BLOCK: return "VK_FORMAT_ASTC_6x5_UNORM_BLOCK"; case VK_FORMAT_ASTC_6x5_SRGB_BLOCK: return "VK_FORMAT_ASTC_6x5_SRGB_BLOCK"; case VK_FORMAT_ASTC_6x6_UNORM_BLOCK: return "VK_FORMAT_ASTC_6x6_UNORM_BLOCK"; case VK_FORMAT_ASTC_6x6_SRGB_BLOCK: return "VK_FORMAT_ASTC_6x6_SRGB_BLOCK"; case VK_FORMAT_ASTC_8x5_UNORM_BLOCK: return "VK_FORMAT_ASTC_8x5_UNORM_BLOCK"; case VK_FORMAT_ASTC_8x5_SRGB_BLOCK: return "VK_FORMAT_ASTC_8x5_SRGB_BLOCK"; case VK_FORMAT_ASTC_8x6_UNORM_BLOCK: return "VK_FORMAT_ASTC_8x6_UNORM_BLOCK"; case VK_FORMAT_ASTC_8x6_SRGB_BLOCK: return "VK_FORMAT_ASTC_8x6_SRGB_BLOCK"; case VK_FORMAT_ASTC_8x8_UNORM_BLOCK: return "VK_FORMAT_ASTC_8x8_UNORM_BLOCK"; case VK_FORMAT_ASTC_8x8_SRGB_BLOCK: return "VK_FORMAT_ASTC_8x8_SRGB_BLOCK"; case VK_FORMAT_ASTC_10x5_UNORM_BLOCK: return "VK_FORMAT_ASTC_10x5_UNORM_BLOCK"; case VK_FORMAT_ASTC_10x5_SRGB_BLOCK: return "VK_FORMAT_ASTC_10x5_SRGB_BLOCK"; case VK_FORMAT_ASTC_10x6_UNORM_BLOCK: return "VK_FORMAT_ASTC_10x6_UNORM_BLOCK"; case VK_FORMAT_ASTC_10x6_SRGB_BLOCK: return "VK_FORMAT_ASTC_10x6_SRGB_BLOCK"; case VK_FORMAT_ASTC_10x8_UNORM_BLOCK: return "VK_FORMAT_ASTC_10x8_UNORM_BLOCK"; case VK_FORMAT_ASTC_10x8_SRGB_BLOCK: return "VK_FORMAT_ASTC_10x8_SRGB_BLOCK"; case VK_FORMAT_ASTC_10x10_UNORM_BLOCK: return "VK_FORMAT_ASTC_10x10_UNORM_BLOCK"; case VK_FORMAT_ASTC_10x10_SRGB_BLOCK: return "VK_FORMAT_ASTC_10x10_SRGB_BLOCK"; case VK_FORMAT_ASTC_12x10_UNORM_BLOCK: return "VK_FORMAT_ASTC_12x10_UNORM_BLOCK"; case VK_FORMAT_ASTC_12x10_SRGB_BLOCK: return "VK_FORMAT_ASTC_12x10_SRGB_BLOCK"; case VK_FORMAT_ASTC_12x12_UNORM_BLOCK: return "VK_FORMAT_ASTC_12x12_UNORM_BLOCK"; case VK_FORMAT_ASTC_12x12_SRGB_BLOCK: return "VK_FORMAT_ASTC_12x12_SRGB_BLOCK"; case VK_FORMAT_G8B8G8R8_422_UNORM: return "VK_FORMAT_G8B8G8R8_422_UNORM"; case VK_FORMAT_B8G8R8G8_422_UNORM: return "VK_FORMAT_B8G8R8G8_422_UNORM"; case VK_FORMAT_G8_B8_R8_3PLANE_420_UNORM: return "VK_FORMAT_G8_B8_R8_3PLANE_420_UNORM"; case VK_FORMAT_G8_B8R8_2PLANE_420_UNORM: return "VK_FORMAT_G8_B8R8_2PLANE_420_UNORM"; case VK_FORMAT_G8_B8_R8_3PLANE_422_UNORM: return "VK_FORMAT_G8_B8_R8_3PLANE_422_UNORM"; case VK_FORMAT_G8_B8R8_2PLANE_422_UNORM: return "VK_FORMAT_G8_B8R8_2PLANE_422_UNORM"; case VK_FORMAT_G8_B8_R8_3PLANE_444_UNORM: return "VK_FORMAT_G8_B8_R8_3PLANE_444_UNORM"; case VK_FORMAT_R10X6_UNORM_PACK16: return "VK_FORMAT_R10X6_UNORM_PACK16"; case VK_FORMAT_R10X6G10X6_UNORM_2PACK16: return "VK_FORMAT_R10X6G10X6_UNORM_2PACK16"; case VK_FORMAT_R10X6G10X6B10X6A10X6_UNORM_4PACK16: return "VK_FORMAT_R10X6G10X6B10X6A10X6_UNORM_4PACK16"; case VK_FORMAT_G10X6B10X6G10X6R10X6_422_UNORM_4PACK16: return "VK_FORMAT_G10X6B10X6G10X6R10X6_422_UNORM_4PACK16"; case VK_FORMAT_B10X6G10X6R10X6G10X6_422_UNORM_4PACK16: return "VK_FORMAT_B10X6G10X6R10X6G10X6_422_UNORM_4PACK16"; case VK_FORMAT_G10X6_B10X6_R10X6_3PLANE_420_UNORM_3PACK16: return "VK_FORMAT_G10X6_B10X6_R10X6_3PLANE_420_UNORM_3PACK16"; case VK_FORMAT_G10X6_B10X6R10X6_2PLANE_420_UNORM_3PACK16: return "VK_FORMAT_G10X6_B10X6R10X6_2PLANE_420_UNORM_3PACK16"; case VK_FORMAT_G10X6_B10X6_R10X6_3PLANE_422_UNORM_3PACK16: return "VK_FORMAT_G10X6_B10X6_R10X6_3PLANE_422_UNORM_3PACK16"; case VK_FORMAT_G10X6_B10X6R10X6_2PLANE_422_UNORM_3PACK16: return "VK_FORMAT_G10X6_B10X6R10X6_2PLANE_422_UNORM_3PACK16"; case VK_FORMAT_G10X6_B10X6_R10X6_3PLANE_444_UNORM_3PACK16: return "VK_FORMAT_G10X6_B10X6_R10X6_3PLANE_444_UNORM_3PACK16"; case VK_FORMAT_R12X4_UNORM_PACK16: return "VK_FORMAT_R12X4_UNORM_PACK16"; case VK_FORMAT_R12X4G12X4_UNORM_2PACK16: return "VK_FORMAT_R12X4G12X4_UNORM_2PACK16"; case VK_FORMAT_R12X4G12X4B12X4A12X4_UNORM_4PACK16: return "VK_FORMAT_R12X4G12X4B12X4A12X4_UNORM_4PACK16"; case VK_FORMAT_G12X4B12X4G12X4R12X4_422_UNORM_4PACK16: return "VK_FORMAT_G12X4B12X4G12X4R12X4_422_UNORM_4PACK16"; case VK_FORMAT_B12X4G12X4R12X4G12X4_422_UNORM_4PACK16: return "VK_FORMAT_B12X4G12X4R12X4G12X4_422_UNORM_4PACK16"; case VK_FORMAT_G12X4_B12X4_R12X4_3PLANE_420_UNORM_3PACK16: return "VK_FORMAT_G12X4_B12X4_R12X4_3PLANE_420_UNORM_3PACK16"; case VK_FORMAT_G12X4_B12X4R12X4_2PLANE_420_UNORM_3PACK16: return "VK_FORMAT_G12X4_B12X4R12X4_2PLANE_420_UNORM_3PACK16"; case VK_FORMAT_G12X4_B12X4_R12X4_3PLANE_422_UNORM_3PACK16: return "VK_FORMAT_G12X4_B12X4_R12X4_3PLANE_422_UNORM_3PACK16"; case VK_FORMAT_G12X4_B12X4R12X4_2PLANE_422_UNORM_3PACK16: return "VK_FORMAT_G12X4_B12X4R12X4_2PLANE_422_UNORM_3PACK16"; case VK_FORMAT_G12X4_B12X4_R12X4_3PLANE_444_UNORM_3PACK16: return "VK_FORMAT_G12X4_B12X4_R12X4_3PLANE_444_UNORM_3PACK16"; case VK_FORMAT_G16B16G16R16_422_UNORM: return "VK_FORMAT_G16B16G16R16_422_UNORM"; case VK_FORMAT_B16G16R16G16_422_UNORM: return "VK_FORMAT_B16G16R16G16_422_UNORM"; case VK_FORMAT_G16_B16_R16_3PLANE_420_UNORM: return "VK_FORMAT_G16_B16_R16_3PLANE_420_UNORM"; case VK_FORMAT_G16_B16R16_2PLANE_420_UNORM: return "VK_FORMAT_G16_B16R16_2PLANE_420_UNORM"; case VK_FORMAT_G16_B16_R16_3PLANE_422_UNORM: return "VK_FORMAT_G16_B16_R16_3PLANE_422_UNORM"; case VK_FORMAT_G16_B16R16_2PLANE_422_UNORM: return "VK_FORMAT_G16_B16R16_2PLANE_422_UNORM"; case VK_FORMAT_G16_B16_R16_3PLANE_444_UNORM: return "VK_FORMAT_G16_B16_R16_3PLANE_444_UNORM"; case VK_FORMAT_PVRTC1_2BPP_UNORM_BLOCK_IMG: return "VK_FORMAT_PVRTC1_2BPP_UNORM_BLOCK_IMG"; case VK_FORMAT_PVRTC1_4BPP_UNORM_BLOCK_IMG: return "VK_FORMAT_PVRTC1_4BPP_UNORM_BLOCK_IMG"; case VK_FORMAT_PVRTC2_2BPP_UNORM_BLOCK_IMG: return "VK_FORMAT_PVRTC2_2BPP_UNORM_BLOCK_IMG"; case VK_FORMAT_PVRTC2_4BPP_UNORM_BLOCK_IMG: return "VK_FORMAT_PVRTC2_4BPP_UNORM_BLOCK_IMG"; case VK_FORMAT_PVRTC1_2BPP_SRGB_BLOCK_IMG: return "VK_FORMAT_PVRTC1_2BPP_SRGB_BLOCK_IMG"; case VK_FORMAT_PVRTC1_4BPP_SRGB_BLOCK_IMG: return "VK_FORMAT_PVRTC1_4BPP_SRGB_BLOCK_IMG"; case VK_FORMAT_PVRTC2_2BPP_SRGB_BLOCK_IMG: return "VK_FORMAT_PVRTC2_2BPP_SRGB_BLOCK_IMG"; case VK_FORMAT_PVRTC2_4BPP_SRGB_BLOCK_IMG: return "VK_FORMAT_PVRTC2_4BPP_SRGB_BLOCK_IMG"; case VK_FORMAT_ASTC_4x4_SFLOAT_BLOCK_EXT: return "VK_FORMAT_ASTC_4x4_SFLOAT_BLOCK_EXT"; case VK_FORMAT_ASTC_5x4_SFLOAT_BLOCK_EXT: return "VK_FORMAT_ASTC_5x4_SFLOAT_BLOCK_EXT"; case VK_FORMAT_ASTC_5x5_SFLOAT_BLOCK_EXT: return "VK_FORMAT_ASTC_5x5_SFLOAT_BLOCK_EXT"; case VK_FORMAT_ASTC_6x5_SFLOAT_BLOCK_EXT: return "VK_FORMAT_ASTC_6x5_SFLOAT_BLOCK_EXT"; case VK_FORMAT_ASTC_6x6_SFLOAT_BLOCK_EXT: return "VK_FORMAT_ASTC_6x6_SFLOAT_BLOCK_EXT"; case VK_FORMAT_ASTC_8x5_SFLOAT_BLOCK_EXT: return "VK_FORMAT_ASTC_8x5_SFLOAT_BLOCK_EXT"; case VK_FORMAT_ASTC_8x6_SFLOAT_BLOCK_EXT: return "VK_FORMAT_ASTC_8x6_SFLOAT_BLOCK_EXT"; case VK_FORMAT_ASTC_8x8_SFLOAT_BLOCK_EXT: return "VK_FORMAT_ASTC_8x8_SFLOAT_BLOCK_EXT"; case VK_FORMAT_ASTC_10x5_SFLOAT_BLOCK_EXT: return "VK_FORMAT_ASTC_10x5_SFLOAT_BLOCK_EXT"; case VK_FORMAT_ASTC_10x6_SFLOAT_BLOCK_EXT: return "VK_FORMAT_ASTC_10x6_SFLOAT_BLOCK_EXT"; case VK_FORMAT_ASTC_10x8_SFLOAT_BLOCK_EXT: return "VK_FORMAT_ASTC_10x8_SFLOAT_BLOCK_EXT"; case VK_FORMAT_ASTC_10x10_SFLOAT_BLOCK_EXT: return "VK_FORMAT_ASTC_10x10_SFLOAT_BLOCK_EXT"; case VK_FORMAT_ASTC_12x10_SFLOAT_BLOCK_EXT: return "VK_FORMAT_ASTC_12x10_SFLOAT_BLOCK_EXT"; case VK_FORMAT_ASTC_12x12_SFLOAT_BLOCK_EXT: return "VK_FORMAT_ASTC_12x12_SFLOAT_BLOCK_EXT"; default: break; } return "Unknown"; } /// @brief Convert a VkResult value into the corresponding value as std::string_view. /// @param format The VkResult to convert. /// @return A std::string_view which contains the VkResult. template <> std::string_view as_string<VkResult>(const VkResult result) { switch (result) { case VK_SUCCESS: return "VK_SUCCESS"; case VK_NOT_READY: return "VK_NOT_READY"; case VK_TIMEOUT: return "VK_TIMEOUT"; case VK_EVENT_SET: return "VK_EVENT_SET"; case VK_EVENT_RESET: return "VK_EVENT_RESET"; case VK_INCOMPLETE: return "VK_INCOMPLETE"; case VK_SUBOPTIMAL_KHR: return "VK_SUBOPTIMAL_KHR"; case VK_ERROR_OUT_OF_HOST_MEMORY: return "VK_ERROR_OUT_OF_HOST_MEMORY"; case VK_ERROR_OUT_OF_DEVICE_MEMORY: return "VK_ERROR_OUT_OF_DEVICE_MEMORY"; case VK_ERROR_INITIALIZATION_FAILED: return "VK_ERROR_INITIALIZATION_FAILED"; case VK_ERROR_DEVICE_LOST: return "VK_ERROR_DEVICE_LOST"; case VK_ERROR_MEMORY_MAP_FAILED: return "VK_ERROR_MEMORY_MAP_FAILED"; case VK_ERROR_LAYER_NOT_PRESENT: return "VK_ERROR_LAYER_NOT_PRESENT"; case VK_ERROR_EXTENSION_NOT_PRESENT: return "VK_ERROR_EXTENSION_NOT_PRESENT"; case VK_ERROR_FEATURE_NOT_PRESENT: return "VK_ERROR_FEATURE_NOT_PRESENT"; case VK_ERROR_INCOMPATIBLE_DRIVER: return "VK_ERROR_INCOMPATIBLE_DRIVER"; case VK_ERROR_TOO_MANY_OBJECTS: return "VK_ERROR_TOO_MANY_OBJECTS"; case VK_ERROR_FORMAT_NOT_SUPPORTED: return "VK_ERROR_FORMAT_NOT_SUPPORTED"; case VK_ERROR_FRAGMENTED_POOL: return "VK_ERROR_FRAGMENTED_POOL"; case VK_ERROR_SURFACE_LOST_KHR: return "VK_ERROR_SURFACE_LOST_KHR"; case VK_ERROR_NATIVE_WINDOW_IN_USE_KHR: return "VK_ERROR_NATIVE_WINDOW_IN_USE_KHR"; case VK_ERROR_OUT_OF_DATE_KHR: return "VK_ERROR_OUT_OF_DATE_KHR"; case VK_ERROR_INCOMPATIBLE_DISPLAY_KHR: return "VK_ERROR_INCOMPATIBLE_DISPLAY_KHR"; case VK_ERROR_INVALID_SHADER_NV: return "VK_ERROR_INVALID_SHADER_NV"; case VK_ERROR_OUT_OF_POOL_MEMORY: return "VK_ERROR_OUT_OF_POOL_MEMORY"; case VK_ERROR_INVALID_EXTERNAL_HANDLE: return "VK_ERROR_INVALID_EXTERNAL_HANDLE"; case VK_ERROR_FRAGMENTATION: return "VK_ERROR_FRAGMENTATION"; case VK_ERROR_INVALID_DEVICE_ADDRESS_EXT: return "VK_ERROR_INVALID_DEVICE_ADDRESS_EXT"; case VK_ERROR_FULL_SCREEN_EXCLUSIVE_MODE_LOST_EXT: return "VK_ERROR_FULL_SCREEN_EXCLUSIVE_MODE_LOST_EXT"; case VK_ERROR_UNKNOWN: return "VK_ERROR_UNKNOWN"; default: break; } return "Unknown"; } std::string_view result_to_description(const VkResult result) { switch (result) { case VK_SUCCESS: return "Command successfully completed"; case VK_NOT_READY: return "A fence or query has not yet completed"; case VK_TIMEOUT: return "A wait operation has not completed in the specified time"; case VK_EVENT_SET: return "An event is signaled"; case VK_EVENT_RESET: return "An event is unsignaled"; case VK_INCOMPLETE: return "A return array was too small for the result"; case VK_SUBOPTIMAL_KHR: return "A swapchain no longer matches the surface properties exactly, but can still be used to present to the " "surface successfully"; case VK_ERROR_OUT_OF_HOST_MEMORY: return "A host memory allocation has failed"; case VK_ERROR_OUT_OF_DEVICE_MEMORY: return "A device memory allocation has failed"; case VK_ERROR_INITIALIZATION_FAILED: return "Initialization of an object could not be completed for implementation-specific reasons"; case VK_ERROR_DEVICE_LOST: return "The logical or physical device has been lost. See Lost Device"; case VK_ERROR_MEMORY_MAP_FAILED: return "Mapping of a memory object has failed"; case VK_ERROR_LAYER_NOT_PRESENT: return "A requested layer is not present or could not be loaded"; case VK_ERROR_EXTENSION_NOT_PRESENT: return "A requested extension is not supported"; case VK_ERROR_FEATURE_NOT_PRESENT: return "A requested feature is not supported"; case VK_ERROR_INCOMPATIBLE_DRIVER: return "The requested version of Vulkan is not supported by the driver or is otherwise incompatible for " "implementation-specific reasons"; case VK_ERROR_TOO_MANY_OBJECTS: return "Too many objects of the type have already been created"; case VK_ERROR_FORMAT_NOT_SUPPORTED: return "A requested format is not supported on this device"; case VK_ERROR_FRAGMENTED_POOL: return "A pool allocation has failed due to fragmentation of the pool's memory. This must only be returned if " "no attempt to allocate host or device memory was made to accommodate the new allocation. This should " "be returned in preference to VK_ERROR_OUT_OF_POOL_MEMORY, but only if the implementation is certain " "that the pool allocation failure was due to fragmentation"; case VK_ERROR_SURFACE_LOST_KHR: return "A surface is no longer available"; case VK_ERROR_NATIVE_WINDOW_IN_USE_KHR: return "The requested window is already in use by Vulkan or another API in a manner which prevents it from " "being used again"; case VK_ERROR_OUT_OF_DATE_KHR: return "A surface has changed in such a way that it is no longer compatible with the swapchain, and further " "presentation requests using the swapchain will fail. Applications must query the new surface " "properties and recreate their swapchain if they wish to continue presenting to the surface"; case VK_ERROR_INCOMPATIBLE_DISPLAY_KHR: return "The display used by a swapchain does not use the same presentable image layout, or is incompatible in " "a way that prevents sharing an image"; case VK_ERROR_INVALID_SHADER_NV: return "One or more shaders failed to compile or link. More details are reported back to the application via " "VK_EXT_debug_report if enabled"; case VK_ERROR_OUT_OF_POOL_MEMORY: return "A pool memory allocation has failed. This must only be returned if no attempt to allocate host or " "device memory was made to accommodate the new allocation. If the failure was definitely due to " "fragmentation of the pool, VK_ERROR_FRAGMENTED_POOL should be returned instead"; case VK_ERROR_INVALID_EXTERNAL_HANDLE: return "An external handle is not a valid handle of the specified type"; case VK_ERROR_FRAGMENTATION: return "A descriptor pool creation has failed due to fragmentation"; case VK_ERROR_INVALID_DEVICE_ADDRESS_EXT: return "A buffer creation failed because the requested address is not available"; case VK_ERROR_FULL_SCREEN_EXCLUSIVE_MODE_LOST_EXT: return "An operation on a swapchain created with VK_FULL_SCREEN_EXCLUSIVE_APPLICATION_CONTROLLED_EXT " "failed as it did not have exclusive full-screen access. This may occur due to implementation-dependent " "reasons, outside of the application's control"; case VK_ERROR_UNKNOWN: return "An unknown error has occurred; either the application has provided invalid input, or an implementation " "failure has occurred"; default: break; } return "Unknown"; } /// @brief Convert a VkQueueFlagBits value into the corresponding value as std::string_view. /// @param bit The queue flag bit. template <> std::string_view as_string(const VkQueueFlagBits queue_flag_bit) { switch (queue_flag_bit) { case VK_QUEUE_GRAPHICS_BIT: return "VK_QUEUE_GRAPHICS_BIT"; break; case VK_QUEUE_COMPUTE_BIT: return "VK_QUEUE_COMPUTE_BIT"; break; case VK_QUEUE_TRANSFER_BIT: return "VK_QUEUE_TRANSFER_BIT"; break; case VK_QUEUE_SPARSE_BINDING_BIT: return "VK_QUEUE_SPARSE_BINDING_BIT"; break; case VK_QUEUE_PROTECTED_BIT: return "VK_QUEUE_PROTECTED_BIT"; break; case VK_QUEUE_FLAG_BITS_MAX_ENUM: return "VK_QUEUE_FLAG_BITS_MAX_ENUM"; break; default: break; } return "Unknown"; } /// @brief Convert a VkMemoryPropertyFlags value into the corresponding value as std::string. /// @param bit The memory property flag bit. template <> std::string_view as_string(const VkMemoryPropertyFlags mem_prop_flag_bit) { switch (mem_prop_flag_bit) { case VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT: return "VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT"; case VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT: return "VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT"; case VK_MEMORY_PROPERTY_HOST_COHERENT_BIT: return "VK_MEMORY_PROPERTY_HOST_COHERENT_BIT"; case VK_MEMORY_PROPERTY_HOST_CACHED_BIT: return "VK_MEMORY_PROPERTY_HOST_CACHED_BIT"; case VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT: return "VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT"; case VK_MEMORY_PROPERTY_PROTECTED_BIT: return "VK_MEMORY_PROPERTY_PROTECTED_BIT"; case VK_MEMORY_PROPERTY_DEVICE_COHERENT_BIT_AMD: return "VK_MEMORY_PROPERTY_DEVICE_COHERENT_BIT_AMD"; case VK_MEMORY_PROPERTY_DEVICE_UNCACHED_BIT_AMD: return "VK_MEMORY_PROPERTY_DEVICE_UNCACHED_BIT_AMD"; case VK_MEMORY_PROPERTY_FLAG_BITS_MAX_ENUM: return "VK_MEMORY_PROPERTY_FLAG_BITS_MAX_ENUM"; default: break; } return "Unknown"; } /// @brief Convert a VkMemoryHeapFlagBits value into the corresponding value as std::string. /// @param bit The memory heap flag bit. template <> std::string_view as_string(const VkMemoryHeapFlagBits heap_flag_bit) { switch (heap_flag_bit) { case VK_MEMORY_HEAP_DEVICE_LOCAL_BIT: return "VK_MEMORY_HEAP_DEVICE_LOCAL_BIT"; case VK_MEMORY_HEAP_MULTI_INSTANCE_BIT: // same as VK_MEMORY_HEAP_MULTI_INSTANCE_BIT_KHR return "VK_MEMORY_HEAP_MULTI_INSTANCE_BIT"; case VK_MEMORY_HEAP_FLAG_BITS_MAX_ENUM: return "VK_MEMORY_HEAP_FLAG_BITS_MAX_ENUM"; default: break; } return "Unknown"; } } // namespace inexor::vulkan_renderer::vk_tools <|start_filename|>include/inexor/vulkan-renderer/wrapper/uniform_buffer.hpp<|end_filename|> #pragma once #include "inexor/vulkan-renderer/wrapper/gpu_memory_buffer.hpp" #include <vulkan/vulkan_core.h> #include <string> namespace inexor::vulkan_renderer::wrapper { class Device; /// @brief RAII wrapper class for uniform buffers. class UniformBuffer : public GPUMemoryBuffer { public: /// @brief Default constructor. /// @param device The const reference to a device RAII wrapper instance. /// @param name The internal debug marker name of the uniform buffer. /// @param size The size of the uniform buffer. /// @todo Add overloaded constructor which directly accepts the uniform buffer data. UniformBuffer(const Device &device, const std::string &name, const VkDeviceSize &size); UniformBuffer(const UniformBuffer &) = delete; UniformBuffer(UniformBuffer &&) noexcept; ~UniformBuffer() override = default; UniformBuffer &operator=(const UniformBuffer &) = delete; UniformBuffer &operator=(UniformBuffer &&) = delete; /// @brief Update uniform buffer data. /// @param data A pointer to the uniform buffer data. /// @param size The size of the uniform buffer memory to copy. void update(void *data, std::size_t size); }; } // namespace inexor::vulkan_renderer::wrapper <|start_filename|>include/inexor/vulkan-renderer/wrapper/cpu_texture.hpp<|end_filename|> #pragma once #include <string> #include <vector> #include <stb_image.h> namespace inexor::vulkan_renderer::wrapper { /// @brief RAII wrapper class for texture data. /// @todo Scan asset directory automatically. class CpuTexture { std::string m_name; int m_texture_width{0}; int m_texture_height{0}; int m_texture_channels{0}; int m_mip_levels{0}; stbi_uc *m_texture_data{nullptr}; /// @brief Generate a chessboard color pattern which will be used as error texture. void generate_error_texture_data(); public: /// @brief Create a CpuTexture instance with a default texture. CpuTexture(); /// @brief Read a texture from a file. /// @param file_name The file name of the texture. /// @param name The internal debug marker name of the command buffer. This must not be an empty string. CpuTexture(const std::string &file_name, std::string name); CpuTexture(const CpuTexture &) = delete; CpuTexture(CpuTexture &&) noexcept; ~CpuTexture(); CpuTexture &operator=(const CpuTexture &) = delete; CpuTexture &operator=(CpuTexture &&) = default; [[nodiscard]] std::string name() const { return m_name; } [[nodiscard]] int width() const { return m_texture_width; } [[nodiscard]] int height() const { return m_texture_height; } [[nodiscard]] int channels() const { return m_texture_channels; } [[nodiscard]] int mip_levels() const { return m_mip_levels; } [[nodiscard]] stbi_uc *data() const { return m_texture_data; } [[nodiscard]] std::size_t data_size() const { // TODO: We will need to update this once we fully support mip levels. return static_cast<std::size_t>(m_texture_width) * static_cast<std::size_t>(m_texture_height) * static_cast<std::size_t>(m_texture_channels); } }; } // namespace inexor::vulkan_renderer::wrapper <|start_filename|>include/inexor/vulkan-renderer/wrapper/shader.hpp<|end_filename|> #pragma once #include <vulkan/vulkan_core.h> #include <string> #include <vector> namespace inexor::vulkan_renderer::wrapper { class Device; /// @brief RAII wrapper class for VkShaderModules. class Shader { const Device &m_device; std::string m_name; std::string m_entry_point; VkShaderStageFlagBits m_type; VkShaderModule m_shader_module{VK_NULL_HANDLE}; public: /// @brief Construct a shader module from a block of SPIR-V memory. /// @param device The const reference to a device RAII wrapper instance. /// @param type The shader type. /// @param name The internal debug marker name of the VkShaderModule. /// @param code The memory block of the SPIR-V shader. /// @param entry_point The name of the entry point, "main" by default. Shader(const Device &m_device, VkShaderStageFlagBits type, const std::string &name, const std::vector<char> &code, const std::string &entry_point = "main"); /// @brief Construct a shader module from a SPIR-V file. /// This constructor loads the file content and just calls the other constructor. /// @param device The const reference to a device RAII wrapper instance. /// @param type The shader type. /// @param name The internal debug marker name of the VkShaderModule. /// @param file_name The name of the SPIR-V shader file to load. /// @param entry_point The name of the entry point, "main" by default. Shader(const Device &m_device, VkShaderStageFlagBits type, const std::string &name, const std::string &file_name, const std::string &entry_point = "main"); Shader(const Shader &) = delete; Shader(Shader &&) noexcept; ~Shader(); Shader &operator=(const Shader &) = delete; Shader &operator=(Shader &&) = delete; [[nodiscard]] const std::string &name() const { return m_name; } [[nodiscard]] const std::string &entry_point() const { return m_entry_point; } [[nodiscard]] VkShaderStageFlagBits type() const { return m_type; } [[nodiscard]] VkShaderModule module() const { return m_shader_module; } }; } // namespace inexor::vulkan_renderer::wrapper <|start_filename|>src/vulkan-renderer/io/nxoc_parser.cpp<|end_filename|> #include "inexor/vulkan-renderer/io/nxoc_parser.hpp" #include "inexor/vulkan-renderer/io/byte_stream.hpp" #include "inexor/vulkan-renderer/io/exception.hpp" #include "inexor/vulkan-renderer/world/cube.hpp" #include <fstream> #include <functional> #include <utility> namespace inexor::vulkan_renderer::io { template <> ByteStream NXOCParser::serialize_impl<0>(const std::shared_ptr<const world::Cube> cube) { // NOLINT ByteStreamWriter writer; writer.write<std::string>("Inexor Octree"); writer.write<std::uint32_t>(0); std::function<void(const std::shared_ptr<const world::Cube> &)> iter_func; // pre-order traversal iter_func = [&iter_func, &writer](const std::shared_ptr<const world::Cube> &cube) { writer.write(cube->type()); if (cube->type() == world::Cube::Type::OCTANT) { for (const auto &child : cube->children()) { iter_func(child); } return; } if (cube->type() == world::Cube::Type::NORMAL) { writer.write(cube->indentations()); } }; iter_func(cube); return writer; } template <> std::shared_ptr<world::Cube> NXOCParser::deserialize_impl<0>(const ByteStream &stream) { ByteStreamReader reader(stream); std::shared_ptr<world::Cube> root = std::make_shared<world::Cube>(); // Skip identifier, which is already checked. reader.skip(13); // Skip version. reader.skip(4); std::function<void(std::shared_ptr<world::Cube> &)> iter_func; // pre-order traversal iter_func = [&iter_func, &reader](std::shared_ptr<world::Cube> &cube) { cube->set_type(reader.read<world::Cube::Type>()); if (cube->type() == world::Cube::Type::OCTANT) { for (auto child : cube->children()) { iter_func(child); } return; } if (cube->type() == world::Cube::Type::NORMAL) { cube->m_indentations = reader.read<std::array<world::Indentation, world::Cube::EDGES>>(); } }; iter_func(root); return root; } ByteStream NXOCParser::serialize(const std::shared_ptr<const world::Cube> cube, const std::uint32_t version) { if (cube == nullptr) { throw std::invalid_argument("cube cannot be a nullptr."); } switch (version) { // NOLINT case 0: return serialize_impl<0>(cube); default: throw IoException("Unsupported octree version."); } } std::shared_ptr<world::Cube> NXOCParser::deserialize(const ByteStream &stream) { ByteStreamReader reader(stream); if (reader.read<std::string>(std::size_t(13)) != "Inexor Octree") { throw IoException("Wrong identifier."); } const auto version = reader.read<std::uint32_t>(); switch (version) { // NOLINT case 0: return deserialize_impl<0>(stream); default: throw IoException("Unsupported octree version."); } } } // namespace inexor::vulkan_renderer::io <|start_filename|>include/inexor/vulkan-renderer/application.hpp<|end_filename|> #pragma once #include "inexor/vulkan-renderer/input/keyboard_mouse_data.hpp" #include "inexor/vulkan-renderer/renderer.hpp" #include "inexor/vulkan-renderer/world/collision_query.hpp" #include "inexor/vulkan-renderer/world/cube.hpp" #include <GLFW/glfw3.h> #include <vulkan/vulkan_core.h> #include <cstdint> #include <memory> #include <string> #include <vector> // forward declarations namespace inexor::vulkan_renderer::input { class KeyboardMouseInputData; } // namespace inexor::vulkan_renderer::input namespace inexor::vulkan_renderer { class Application : public VulkanRenderer { std::vector<std::string> m_vertex_shader_files; std::vector<std::string> m_fragment_shader_files; std::vector<std::string> m_texture_files; std::vector<std::string> m_gltf_model_files; std::unique_ptr<input::KeyboardMouseInputData> m_input_data; bool m_enable_validation_layers{true}; /// Inexor engine supports a variable number of octrees. std::vector<std::shared_ptr<world::Cube>> m_worlds; // If the user specified command line argument "--stop-on-validation-message", the program will call // std::abort(); after reporting a validation layer (error) message. bool m_stop_on_validation_message{false}; /// @brief Load the configuration of the renderer from a TOML configuration file. /// @brief file_name The TOML configuration file. /// @note It was collectively decided not to use JSON for configuration files. void load_toml_configuration_file(const std::string &file_name); void load_textures(); void load_shaders(); /// @param initialize Initialize worlds with a fixed seed, which is useful for benchmarking and testing void load_octree_geometry(bool initialize); void setup_vulkan_debug_callback(); void setup_window_and_input_callbacks(); void update_imgui_overlay(); void check_application_specific_features(); void update_uniform_buffers(); /// Use the camera's position and view direction vector to check for ray-octree collisions with all octrees. void check_octree_collisions(); void process_mouse_input(); public: Application(int argc, char **argv); /// @brief Call glfwSetKeyCallback. /// @param window The window that received the event. /// @param key The keyboard key that was pressed or released. /// @param scancode The system-specific scancode of the key. /// @param action GLFW_PRESS, GLFW_RELEASE or GLFW_REPEAT. /// @param mods Bit field describing which modifier keys were held down. void key_callback(GLFWwindow *window, int key, int scancode, int action, int mods); /// @brief Call glfwSetCursorPosCallback. /// @param window The window that received the event. /// @param x_pos The new x-coordinate, in screen coordinates, of the cursor. /// @param y_pos The new y-coordinate, in screen coordinates, of the cursor. void cursor_position_callback(GLFWwindow *window, double x_pos, double y_pos); /// @brief Call glfwSetMouseButtonCallback. /// @param window The window that received the event. /// @param button The mouse button that was pressed or released. /// @param action One of GLFW_PRESS or GLFW_RELEASE. /// @param mods Bit field describing which modifier keys were held down. void mouse_button_callback(GLFWwindow *window, int button, int action, int mods); /// @brief Call camera's process_mouse_scroll method. /// @param window The window that received the event. /// @param x_offset The change of x-offset of the mouse wheel. /// @param y_offset The change of y-offset of the mouse wheel. void mouse_scroll_callback(GLFWwindow *window, double x_offset, double y_offset); void run(); }; } // namespace inexor::vulkan_renderer <|start_filename|>src/vulkan-renderer/tools/cla_parser.cpp<|end_filename|> #include "inexor/vulkan-renderer/tools/cla_parser.hpp" #include <spdlog/spdlog.h> #include <stdexcept> namespace inexor::vulkan_renderer::tools { template <> [[nodiscard]] int CommandLineArgumentValue::as() const { return std::stoi(m_value); } template <> [[nodiscard]] bool CommandLineArgumentValue::as() const { if (m_value == "false") { return false; } if (m_value == "true") { return true; } return static_cast<bool>(as<int>()); } template <> [[nodiscard]] std::uint32_t CommandLineArgumentValue::as() const { return static_cast<std::uint32_t>(as<int>()); } std::optional<CommandLineArgumentTemplate> CommandLineArgumentParser::make_arg_template(const std::string &argument_name) const { auto it = std::find_if(m_accepted_args.begin(), m_accepted_args.end(), [&](const auto &accepted_arg) { return argument_name == accepted_arg.argument(); }); if (it == m_accepted_args.end()) { return std::nullopt; } return *it; } // TODO: Take in an std::vector<std::string> of arguments? This would avoid any hard to debug out of bounds errors (with // argc being bigger than the number of elements actually in argv). void CommandLineArgumentParser::parse_args(int argc, char **argv) { for (int i = 1; i < argc; i++) { // NOLINTNEXTLINE std::string arg_name(argv[i]); // If a user enters an unrecognized argument, just warn them about it for now. auto arg_template = make_arg_template(arg_name); if (!arg_template) { spdlog::warn("Unknown command line argument {}!", arg_name); continue; } // Insert a dummy value if the argument doesn't take any. if (!arg_template->takes_values()) { m_parsed_arguments.insert(std::make_pair(arg_name, "")); continue; } // We have to fail if the user doesn't specify a value for an argument expecting one (since it would mess up the // rest of parsing). if (i++ >= argc) { throw std::runtime_error("No value specified for argument " + arg_name); } // NOLINTNEXTLINE std::string arg_value(argv[i]); m_parsed_arguments.insert(std::make_pair(arg_name, arg_value)); } } } // namespace inexor::vulkan_renderer::tools <|start_filename|>shaders/ui.frag<|end_filename|> #version 450 layout (binding = 0) uniform sampler2D font_sampler; layout (location = 0) in vec2 in_uv; layout (location = 1) in vec4 in_color; layout (location = 0) out vec4 out_color; void main() { out_color = in_color * texture(font_sampler, in_uv); } <|start_filename|>documentation/source/_static/js/svg-highlight.js<|end_filename|> /* support to highlight mermaid paths useful if you present a big image to others */ $(function () { let allPaths = $("path.path"); let allArrows = $("path.arrowheadPath"); allPaths.click(function (event) { if (!event.shiftKey) { allPaths.removeClass("svg-highlight"); allArrows.removeClass("svg-highlight"); } if ($(this).hasClass("svg-highlight")) { $(this).removeClass("svg-highlight"); $(this).find("+ defs > marker > path").removeClass("svg-highlight"); } else { $(this).addClass("svg-highlight"); $(this).find("+ defs > marker > path").addClass("svg-highlight"); } }); allPaths.hover( function () { $(this).addClass("svg-highlight-hover"); $(this).find("+ defs > marker > path").addClass("svg-highlight-hover"); }, function () { $(this).removeClass("svg-highlight-hover"); $(this).find("+ defs > marker > path").removeClass("svg-highlight-hover"); } ); }); <|start_filename|>include/inexor/vulkan-renderer/camera.hpp<|end_filename|> #pragma once #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <algorithm> #include <array> #include <vector> namespace inexor::vulkan_renderer { namespace directions { /// The default value of the camera's front vector. constexpr glm::vec3 DEFAULT_FRONT{1.0f, 0.0f, 0.0f}; /// The default value of the camera's right vector. constexpr glm::vec3 DEFAULT_RIGHT{0.0f, 1.0f, 0.0f}; /// The default value of the camera's up vector. constexpr glm::vec3 DEFAULT_UP{0.0f, 0.0f, 1.0f}; } // namespace directions enum class CameraMovement { FORWARD, BACKWARD, LEFT, RIGHT }; // TODO: Implement more camera types. enum class CameraType { LOOK_AT }; /// @warning Not thread safe! class Camera { private: /// The type of the camera. Currently only one type is implemented. CameraType m_type{CameraType::LOOK_AT}; /// The start position of the camera. glm::vec3 m_position{0.0f, 0.0f, 0.0f}; /// The vector of direction in which the camera is looking. glm::vec3 m_front{directions::DEFAULT_FRONT}; /// The vector of direction which points to the right. glm::vec3 m_right{directions::DEFAULT_RIGHT}; /// The vector which indicates "upwards". glm::vec3 m_up{directions::DEFAULT_UP}; /// The world vector which indicates "upwards". glm::vec3 m_world_up{directions::DEFAULT_UP}; glm::mat4 m_view_matrix{}; glm::mat4 m_perspective_matrix{}; /// The camera's yaw angle. float m_yaw{0.0f}; /// The camera's roll angle. float m_roll{0.0f}; /// The camera's pitch angle. float m_pitch{0.0f}; /// The camera's minimum pitch angle. /// Looking straight downwards is the maximum pitch angle. float m_pitch_min{-89.0f}; /// The camera's maximum pitch angle. /// Looking straight upwards is the maximum pitch angle. float m_pitch_max{+89.0f}; /// The camera's field of view. float m_fov{90.0f}; /// The camera's maximum field of view. float m_fov_max{90.0f}; /// The camera's minimum field of view. float m_fov_min{20.0f}; /// The zoom step when zooming in or out. float m_zoom_step{10.0f}; /// The camera's rotation speed. float m_rotation_speed{1.0f}; /// The camera's movement speed. float m_movement_speed{2.0f}; /// The camera's aspect ratio (width divided by height). float m_aspect_ratio{1920.0f / 1080.0f}; /// The sensitivity of the mouse. float m_mouse_sensitivity{0.005f}; /// The camera's near plane. float m_near_plane{0.001f}; /// The camera's far plane. float m_far_plane{1000.0f}; /// The keys for the movement FORWARD, BACKWARD, LEFT, RIGHT. std::array<bool, 4> m_keys{false, false, false, false}; /// Will be set to ``true`` if the matrices need to be recalculated. bool m_update_needed{true}; void update_vectors(); void update_matrices(); [[nodiscard]] bool is_moving() const; public: /// @brief Default constructor. /// @param position The camera's position. /// @param yaw The camera's yaw angle in degrees. /// @param pitch The camera's pitch angle in degrees. /// @param window_width The width of the window. /// @param window_height The height of the window. Camera(const glm::vec3 &position, float yaw, float pitch, float window_width, float window_height); // TODO: Add more overloaded constructors. /// @brief Set the camera type. /// @note We will implement more camera types in the future. /// @param type The camera type. void set_type(CameraType type); [[nodiscard]] const CameraType &type() const { return m_type; } /// @brief Notify the camera if a certain key is pressed or released. /// @param key The key which was pressed or released. /// @param pressed ``true`` if the key is pressed. void set_movement_state(CameraMovement key, bool pressed); /// @brief Set the position of the camera. /// @param position The position of the camera. void set_position(glm::vec3 position); [[nodiscard]] const glm::vec3 &position() const { return m_position; } /// @brief Set the aspect ratio (window width divided by window height) of the camera view matrix. /// @param width The width of the window. /// @param height The height of the window. void set_aspect_ratio(float width, float height); [[nodiscard]] float aspect_ratio() const { return m_aspect_ratio; } [[nodiscard]] float fov() const { return m_fov; } /// @brief Set the movement speed of the camera. /// @param speed The movement speed of the camera. void set_movement_speed(float speed); [[nodiscard]] float movement_speed() const { return m_movement_speed; } /// @brief Set the rotation speed of the camera. /// @param speed The rotation speed of the camera. void set_rotation_speed(float speed); [[nodiscard]] float rotation_speed() const { return m_rotation_speed; } /// @brief Rotates the camera around x, y, and z axis. /// @param delta_yaw The yaw angle. /// @param delta_pitch The pitch angle. /// @param delta_roll The roll angle. void rotate(float delta_yaw, float delta_pitch, float delta_roll = 0.0f); /// @brief Set the camera's rotation. /// @param yaw The yaw angle. /// @param pitch The pitch angle. /// @param roll The roll angle. void set_rotation(float yaw, float pitch, float roll); [[nodiscard]] const glm::vec3 &rotation() const { return m_front; } [[nodiscard]] float yaw() const { return m_yaw; } [[nodiscard]] float pitch() const { return m_pitch; } [[nodiscard]] float roll() const { return m_roll; } [[nodiscard]] const glm::vec3 &front() const { return m_front; } [[nodiscard]] const glm::vec3 &up() const { return m_up; } [[nodiscard]] const glm::vec3 &right() const { return m_right; } /// @brief Set the near plane distance of the camera. /// @param near_plane The near plane distance. void set_near_plane(float near_plane); [[nodiscard]] float near_plane() const { return m_near_plane; } /// @brief Set the far plane distance of the camera. /// @param far_plane The far plane distance. void set_far_plane(float far_plane); [[nodiscard]] float far_plane() const { return m_far_plane; } /// @brief Change the zoom of the camera. /// @param offset The mouse wheel offset change. void change_zoom(float offset); /// @brief Update the camera (recalculate vectors and matrices). /// @param delta_time The change in time since the last frame. void update(float delta_time); [[nodiscard]] const glm::mat4 &view_matrix() { if (m_update_needed) { update_matrices(); } return m_view_matrix; } [[nodiscard]] const glm::mat4 &perspective_matrix() { if (m_update_needed) { update_matrices(); } return m_perspective_matrix; } }; } // namespace inexor::vulkan_renderer <|start_filename|>tests/world/cube_collision.cpp<|end_filename|> #include <gtest/gtest.h> #include <inexor/vulkan-renderer/world/collision_query.hpp> #include <inexor/vulkan-renderer/world/cube.hpp> namespace inexor::vulkan_renderer { TEST(CubeCollision, CollisionCheck) { const glm::vec3 world_pos{0, 0, 0}; world::Cube world(1.0f, world_pos); world.set_type(world::Cube::Type::SOLID); glm::vec3 cam_pos{0.0f, 0.0f, 10.0f}; glm::vec3 cam_direction{0.0f, 0.0f, 0.0f}; auto collision1 = ray_cube_collision_check(world, cam_pos, cam_direction); bool collision_found = collision1.has_value(); // There must be no collision for this data setup. EXPECT_FALSE(collision_found); cam_direction = {0.0f, 0.0f, -1.0f}; auto collision2 = ray_cube_collision_check(world, cam_pos, cam_direction); collision_found = collision2.has_value(); // Since we are now directly looking down on the cube, we collide with it. EXPECT_TRUE(collision_found); } } // namespace inexor::vulkan_renderer <|start_filename|>src/vulkan-renderer/world/cube.cpp<|end_filename|> #include "inexor/vulkan-renderer/world/cube.hpp" #include "inexor/vulkan-renderer/world/indentation.hpp" #include <random> void swap(inexor::vulkan_renderer::world::Cube &lhs, inexor::vulkan_renderer::world::Cube &rhs) noexcept { std::swap(lhs.m_type, rhs.m_type); std::swap(lhs.m_size, rhs.m_size); std::swap(lhs.m_position, rhs.m_position); std::swap(lhs.m_parent, rhs.m_parent); std::swap(lhs.m_index_in_parent, rhs.m_index_in_parent); std::swap(lhs.m_indentations, rhs.m_indentations); std::swap(lhs.m_children, rhs.m_children); std::swap(lhs.m_polygon_cache, rhs.m_polygon_cache); std::swap(lhs.m_polygon_cache_valid, rhs.m_polygon_cache_valid); } namespace inexor::vulkan_renderer::world { void Cube::remove_children() { for (auto &child : m_children) { child->remove_children(); child.reset(); } } std::shared_ptr<Cube> Cube::root() noexcept { std::shared_ptr<Cube> new_parent = m_parent.lock(); if (!new_parent) { return shared_from_this(); } std::shared_ptr<Cube> parent; while (new_parent) { parent = new_parent; new_parent = parent->m_parent.lock(); } return parent; } std::array<glm::vec3, 8> Cube::vertices() const noexcept { assert(m_type == Type::SOLID || m_type == Type::NORMAL); const glm::vec3 pos = m_position; const glm::vec3 max = {m_position.x + m_size, m_position.y + m_size, m_position.z + m_size}; if (m_type == Type::SOLID) { return {{{pos.x, pos.y, pos.z}, {pos.x, pos.y, max.z}, {pos.x, max.y, pos.z}, {pos.x, max.y, max.z}, {max.x, pos.y, pos.z}, {max.x, pos.y, max.z}, {max.x, max.y, pos.z}, {max.x, max.y, max.z}}}; } if (m_type == Type::NORMAL) { const float step = m_size / Indentation::MAX; const std::array<Indentation, Cube::EDGES> &ind = m_indentations; return {{{pos.x + static_cast<float>(ind[0].start()) * step, pos.y + static_cast<float>(ind[1].start()) * step, pos.z + static_cast<float>(ind[2].start()) * step}, {pos.x + static_cast<float>(ind[9].start()) * step, pos.y + static_cast<float>(ind[4].start()) * step, max.z - static_cast<float>(ind[2].end()) * step}, {pos.x + static_cast<float>(ind[3].start()) * step, max.y - static_cast<float>(ind[1].end()) * step, pos.z + static_cast<float>(ind[11].start()) * step}, {pos.x + static_cast<float>(ind[6].start()) * step, max.y - static_cast<float>(ind[4].end()) * step, max.z - static_cast<float>(ind[11].end()) * step}, {max.x - static_cast<float>(ind[0].end()) * step, pos.y + static_cast<float>(ind[10].start()) * step, pos.z + static_cast<float>(ind[5].start()) * step}, {max.x - static_cast<float>(ind[9].end()) * step, pos.y + static_cast<float>(ind[7].start()) * step, max.z - static_cast<float>(ind[5].end()) * step}, {max.x - static_cast<float>(ind[3].end()) * step, max.y - static_cast<float>(ind[10].end()) * step, pos.z + static_cast<float>(ind[8].start()) * step}, {max.x - static_cast<float>(ind[6].end()) * step, max.y - static_cast<float>(ind[7].end()) * step, max.z - static_cast<float>(ind[8].end()) * step}}}; } return {}; } /// 90 degree rotation. template <> void Cube::rotate<1>(const RotationAxis::Type &axis) { // the reorder function can be replaced by a lambda and used both cases. // requires: constexpr vector if (m_type == Type::NORMAL) { const RotationAxis::EdgeType &edge_rotation = std::get<1>(axis); for (const auto &order : edge_rotation) { std::swap(m_indentations[order[0]], m_indentations[order[1]]); std::swap(m_indentations[order[1]], m_indentations[order[2]]); std::swap(m_indentations[order[2]], m_indentations[order[3]]); } // Some indentations need to be mirrored, as the direction has changed. // not the last array, as it contains the edges parallel to the axis around which we rotate for (int idx = 0; idx < edge_rotation.size() - 1; idx++) { m_indentations[edge_rotation[idx][0]].mirror(); m_indentations[edge_rotation[idx][2]].mirror(); } return; } if (m_type == Type::OCTANT) { const RotationAxis::ChildType &child_rotation = std::get<0>(axis); for (const auto &order : child_rotation) { std::swap(m_children[order[0]], m_children[order[1]]); std::swap(m_children[order[1]], m_children[order[2]]); std::swap(m_children[order[2]], m_children[order[3]]); } for (auto &child : m_children) { child->rotate<1>(axis); } } } /// 180 degree rotation. template <> void Cube::rotate<2>(const RotationAxis::Type &axis) { if (m_type == Type::NORMAL) { const RotationAxis::EdgeType &edge_rotation = std::get<1>(axis); for (const auto &order : edge_rotation) { std::swap(m_indentations[order[0]], m_indentations[order[2]]); std::swap(m_indentations[order[1]], m_indentations[order[3]]); } // Some indentations need to be mirrored, as the direction has changed. // not the last array, as it contains the edges parallel to the axis around which we rotate for (int idx = 0; idx < edge_rotation.size() - 1; idx++) { m_indentations[edge_rotation[idx][0]].mirror(); m_indentations[edge_rotation[idx][1]].mirror(); m_indentations[edge_rotation[idx][2]].mirror(); m_indentations[edge_rotation[idx][3]].mirror(); } return; } if (m_type == Type::OCTANT) { const RotationAxis::ChildType &child_rotation = std::get<0>(axis); for (const auto &order : child_rotation) { std::swap(m_children[order[0]], m_children[order[2]]); std::swap(m_children[order[1]], m_children[order[3]]); } for (auto &child : m_children) { child->rotate<2>(axis); } } } /// 270 degree rotation. template <> void Cube::rotate<3>(const RotationAxis::Type &axis) { if (m_type == Type::NORMAL) { const RotationAxis::EdgeType &edge_rotation = std::get<1>(axis); for (const auto &order : edge_rotation) { std::swap(m_indentations[order[0]], m_indentations[order[3]]); std::swap(m_indentations[order[3]], m_indentations[order[2]]); std::swap(m_indentations[order[2]], m_indentations[order[1]]); } // Some indentations need to be mirrored, as the direction has changed. // not the last array, as it contains the edges parallel to the axis around which we rotate m_indentations[edge_rotation[0][1]].mirror(); m_indentations[edge_rotation[0][3]].mirror(); m_indentations[edge_rotation[1][1]].mirror(); m_indentations[edge_rotation[1][3]].mirror(); return; } if (m_type == Type::OCTANT) { const RotationAxis::ChildType &child_rotation = std::get<0>(axis); for (const auto &order : child_rotation) { std::swap(m_children[order[0]], m_children[order[3]]); std::swap(m_children[order[3]], m_children[order[2]]); std::swap(m_children[order[2]], m_children[order[1]]); } for (auto &child : m_children) { child->rotate<3>(axis); } } } Cube::Cube(const float size, const glm::vec3 &position) : m_size(size), m_position(position) {} Cube::Cube(std::weak_ptr<Cube> parent, const std::uint8_t index, const float size, const glm::vec3 &position) : Cube(size, position) { m_parent = std::move(parent); m_index_in_parent = index; } Cube::Cube(Cube &&rhs) noexcept : Cube() { swap(*this, rhs); } Cube &Cube::operator=(Cube rhs) { swap(*this, rhs); return *this; } std::shared_ptr<Cube> Cube::operator[](std::size_t idx) { assert(idx <= SUB_CUBES); return m_children[idx]; } std::shared_ptr<const Cube> Cube::operator[](std::size_t idx) const { assert(idx <= SUB_CUBES); return m_children[idx]; } std::shared_ptr<Cube> Cube::clone() const { std::shared_ptr<Cube> clone = std::make_shared<Cube>(this->m_size, this->m_position); clone->m_type = this->m_type; clone->m_index_in_parent = this->m_index_in_parent; if (clone->m_type == Type::NORMAL) { clone->m_indentations = this->m_indentations; } else if (clone->m_type == Type::OCTANT) { for (std::size_t idx = 0; idx <= this->m_children.size(); idx++) { clone->m_children[idx] = this->m_children[idx]->clone(); clone->m_children[idx]->m_parent = clone; } } clone->m_polygon_cache_valid = this->m_polygon_cache_valid; if (clone->m_type == Type::NORMAL || clone->m_type == Type::SOLID) { clone->m_polygon_cache = std::make_shared<std::vector<Polygon>>(*this->m_polygon_cache); } return clone; } bool Cube::is_root() const noexcept { return m_parent.lock() == nullptr; } std::size_t Cube::grid_level() const noexcept { std::size_t level = 0; std::shared_ptr<Cube> parent = m_parent.lock(); while (!parent->is_root()) { parent = parent->m_parent.lock(); level++; } return level; } std::size_t Cube::count_geometry_cubes() const noexcept { if (m_type == Type::SOLID || m_type == Type::NORMAL) { return 1; } if (m_type == Type::OCTANT) { std::size_t count = 0; for (const auto &cube : m_children) { count += cube->count_geometry_cubes(); } return count; } return 0; } void Cube::set_type(const Type new_type) { if (m_type == new_type) { return; } switch (new_type) { case Type::EMPTY: case Type::SOLID: break; case Type::NORMAL: m_indentations = {}; break; case Type::OCTANT: const float half_size = m_size / 2; std::uint8_t index = 0; auto create_cube = [&](const glm::vec3 &offset) { return std::make_shared<Cube>(weak_from_this(), index++, half_size, m_position + offset); }; // Look into octree documentation to find information about the order of subcubes in space. // We can't use initializer list here because clang-tidy complains about it. // To the best of our knowledge, this is a false positive. m_children[0] = create_cube({0, 0, 0}); m_children[1] = create_cube({0, 0, half_size}); m_children[2] = create_cube({0, half_size, 0}); m_children[3] = create_cube({0, half_size, half_size}); m_children[4] = create_cube({half_size, 0, 0}); m_children[5] = create_cube({half_size, 0, half_size}); m_children[6] = create_cube({half_size, half_size, 0}); m_children[7] = create_cube({half_size, half_size, half_size}); break; } if (m_type == Type::OCTANT && new_type != Type::OCTANT) { remove_children(); } m_polygon_cache_valid = false; m_type = new_type; // TODO: clean up if whole octant is empty, etc. } Cube::Type Cube::type() const noexcept { return m_type; } const std::array<std::shared_ptr<Cube>, Cube::SUB_CUBES> &Cube::children() const { return m_children; } std::array<Indentation, Cube::EDGES> Cube::indentations() const noexcept { return m_indentations; } void Cube::set_indent(const std::uint8_t edge_id, Indentation indentation) { if (m_type != Type::NORMAL) { return; } assert(edge_id <= Cube::EDGES); m_indentations[edge_id] = indentation; } void Cube::indent(const std::uint8_t edge_id, const bool positive_direction, const std::uint8_t steps) { if (m_type != Type::NORMAL) { return; } assert(edge_id <= Cube::EDGES); if (positive_direction) { m_indentations[edge_id].indent_start(steps); } else { m_indentations[edge_id].indent_end(steps); } m_polygon_cache_valid = false; } void Cube::rotate(const RotationAxis::Type &axis, int rotations) { rotations = ((rotations % 4) + 4) % 4; if (rotations == 0 || m_type == Type::EMPTY || m_type == Type::SOLID) { return; } switch (rotations) { case 1: rotate<1>(axis); break; case 2: rotate<2>(axis); break; case 3: rotate<3>(axis); break; default: break; } } void Cube::update_polygon_cache() const { if (m_type == Type::OCTANT || m_type == Type::EMPTY) { m_polygon_cache = nullptr; m_polygon_cache_valid = true; return; } const std::array<glm::vec3, 8> v = vertices(); m_polygon_cache = std::make_shared<std::vector<Polygon>>(std::vector<Polygon>{ {{v[0], v[2], v[1]}}, // x = 0 {{v[1], v[2], v[3]}}, // x = 0 {{v[4], v[5], v[6]}}, // x = 1 {{v[5], v[7], v[6]}}, // x = 1 {{v[0], v[1], v[4]}}, // y = 0 {{v[1], v[5], v[4]}}, // y = 0 {{v[2], v[6], v[3]}}, // y = 1 {{v[3], v[6], v[7]}}, // y = 1 {{v[0], v[4], v[2]}}, // z = 0 {{v[2], v[4], v[6]}}, // z = 0 {{v[1], v[3], v[5]}}, // z = 1 {{v[3], v[7], v[5]}} // z = 1 }); if (m_type == Type::SOLID) { m_polygon_cache_valid = true; return; } if (m_type == Type::NORMAL) { const std::array<Indentation, Cube::EDGES> ind = m_indentations; // Check for each side if the side is convex, rotate the hypotenuse (middle diagonal edge) so it becomes convex! // x = 0 if (ind[0].start() + ind[6].start() < ind[9].start() + ind[3].start()) { (*m_polygon_cache)[0] = {{v[0], v[2], v[3]}}; (*m_polygon_cache)[1] = {{v[0], v[3], v[1]}}; } // x = 1 if (ind[0].end() + ind[6].end() < ind[9].end() + ind[3].end()) { (*m_polygon_cache)[2] = {{v[4], v[7], v[6]}}; (*m_polygon_cache)[3] = {{v[4], v[5], v[7]}}; } // y = 0 if (ind[1].start() + ind[7].start() < ind[4].start() + ind[10].start()) { (*m_polygon_cache)[4] = {{v[0], v[1], v[5]}}; (*m_polygon_cache)[5] = {{v[0], v[5], v[4]}}; } // y = 1 if (ind[1].end() + ind[7].end() < ind[4].end() + ind[10].end()) { (*m_polygon_cache)[6] = {{v[2], v[7], v[3]}}; (*m_polygon_cache)[7] = {{v[2], v[6], v[7]}}; } // z = 0 if (ind[2].start() + ind[8].start() < ind[11].start() + ind[5].start()) { (*m_polygon_cache)[8] = {{v[0], v[4], v[6]}}; (*m_polygon_cache)[9] = {{v[0], v[6], v[2]}}; } // z = 1 if (ind[2].end() + ind[8].end() < ind[11].end() + ind[5].end()) { (*m_polygon_cache)[10] = {{v[1], v[3], v[7]}}; (*m_polygon_cache)[11] = {{v[1], v[7], v[5]}}; } m_polygon_cache_valid = true; return; } // This point should not be reached. assert(false); } void Cube::invalidate_polygon_cache() const { m_polygon_cache_valid = false; } std::vector<PolygonCache> Cube::polygons(const bool update_invalid) const { std::vector<PolygonCache> polygons; polygons.reserve(count_geometry_cubes()); // post-order traversal std::function<void(const Cube &)> collect = [&collect, &polygons, &update_invalid](const Cube &cube) { if (cube.type() == world::Cube::Type::OCTANT) { for (const auto &child : cube.children()) { collect(*child); } return; } if (!cube.m_polygon_cache_valid && update_invalid) { cube.update_polygon_cache(); } if (cube.m_polygon_cache != nullptr) { polygons.push_back(cube.m_polygon_cache); } }; collect(*this); return polygons; } std::shared_ptr<Cube> Cube::neighbor(const NeighborAxis axis, const NeighborDirection direction) { if (is_root()) { return nullptr; } // Each axis only requires information and manipulation of one (relevant) bit to find the neighbor. const auto relevant_index_bit = static_cast<std::uint8_t>(axis); // bit index of the axis we are working on auto get_bit = [&relevant_index_bit](const std::uint8_t cube_index) { return ((cube_index >> relevant_index_bit) & 1u) != 0; }; auto toggle_bit = [&relevant_index_bit](const std::uint8_t cube_index) { return cube_index ^ (1u << relevant_index_bit); }; auto parent = m_parent.lock(); const std::uint8_t index = m_index_in_parent; const bool home_bit = get_bit(index); // The relevant bit denotes whether `m_parent` and `this` share a face on the upper side of the relevant axis. // If they share one and also the user wants to go in the positive direction, then the neighbor is not a sibling. // (Same for opposite, i.e. share face on lower side and going negative direction.) if (home_bit && direction == NeighborDirection::NEGATIVE || !home_bit && direction == NeighborDirection::POSITIVE) { // The demanded neighbor is a sibling! Return the neighboring sibling. return parent->m_children[toggle_bit(index)]; } if (parent->is_root()) { return nullptr; } // the neighbor is further away than a sibling // Keep the history of indices because we just need to mirror indices (i.e. toggle the relevant bit) // to find the desired neighboring cube. std::vector<std::uint8_t> history; history.push_back(index); // Find the first cube where the bit (of `get_bit`) is different to `this_bit`. // That cubes parent is the first mutual parent of the desired neighbor and `this`. std::uint8_t p_index = parent->m_index_in_parent; history.push_back(p_index); while (get_bit(p_index) == home_bit) { parent = parent->m_parent.lock(); if (parent->is_root()) { return nullptr; } p_index = parent->m_index_in_parent; history.push_back(p_index); } // get the first mutual parent of neighbor and `this`. std::shared_ptr<Cube> child = parent->m_parent.lock(); // Now mirror the path we took by just flipping the relevant bit of each index in the history. while (!history.empty()) { if (child->m_type != Type::OCTANT) { // The neighbor is larger but still a neighbor! return std::shared_ptr<Cube>(child); } child = child->m_children[toggle_bit(history.back())]; history.pop_back(); } // We found a same-sized neighbor! return std::shared_ptr<Cube>(child); } std::shared_ptr<Cube> create_random_world(std::uint32_t max_depth, const glm::vec3 &position, std::optional<std::uint32_t> seed) { static std::random_device rd; std::mt19937 mt(seed ? *seed : rd()); std::uniform_int_distribution<std::uint32_t> indent(0, 44); std::uniform_int_distribution<std::uint32_t> cube_type(0, 100); std::shared_ptr<Cube> cube = std::make_shared<Cube>(4.0f, position); cube->set_type(Cube::Type::OCTANT); std::function<void(const Cube &, std::uint32_t)> populate_cube = [&](const Cube &parent, std::uint32_t depth) { for (const auto &child : parent.children()) { if (depth != max_depth) { child->set_type(Cube::Type::OCTANT); populate_cube(*child, depth + 1); continue; } auto ty = cube_type(mt); if (ty < 30) { child->set_type(Cube::Type::EMPTY); continue; } if (ty < 60) { child->set_type(Cube::Type::SOLID); continue; } if (ty < 100) { child->set_type(Cube::Type::NORMAL); for (int i = 0; i < 12; i++) { child->set_indent(i, Indentation(indent(mt))); } continue; } } }; populate_cube(*cube, 0); return cube; } } // namespace inexor::vulkan_renderer::world <|start_filename|>include/inexor/vulkan-renderer/io/nxoc_parser.hpp<|end_filename|> #pragma once #include "inexor/vulkan-renderer/io/octree_parser.hpp" #include <cstdint> #include <memory> #include <utility> // forward declaration namespace inexor::vulkan_renderer::world { class Cube; } // namespace inexor::vulkan_renderer::world // forward declaration namespace inexor::vulkan_renderer::io { class ByteStream; } // namespace inexor::vulkan_renderer::io namespace inexor::vulkan_renderer::io { class NXOCParser : public OctreeParser { private: static constexpr std::uint32_t LATEST_VERSION{0}; /// Specific version serialization. template <std::size_t version> [[nodiscard]] ByteStream serialize_impl(std::shared_ptr<const world::Cube> cube); /// Specific version deserialization. template <std::size_t version> [[nodiscard]] std::shared_ptr<world::Cube> deserialize_impl(const ByteStream &stream); public: /// Serialization of an octree. [[nodiscard]] ByteStream serialize(std::shared_ptr<const world::Cube> cube, std::uint32_t version) final; /// Deserialization of an octree. [[nodiscard]] std::shared_ptr<world::Cube> deserialize(const ByteStream &stream) final; }; } // namespace inexor::vulkan_renderer::io <|start_filename|>include/inexor/vulkan-renderer/fps_counter.hpp<|end_filename|> #pragma once #include <chrono> #include <cstdint> #include <optional> namespace inexor::vulkan_renderer { /// @brief A class for counting frames per seconds. class FPSCounter { std::uint32_t m_frames{0}; std::chrono::time_point<std::chrono::high_resolution_clock> m_last_time; float m_fps_update_interval{1.0f}; public: std::optional<std::uint32_t> update(); }; } // namespace inexor::vulkan_renderer <|start_filename|>documentation/cmake/sphinx-config.cmake<|end_filename|> # https://eb2.co/blog/2012/03/sphinx-and-cmake-beautiful-documentation-for-c---projects/ find_program( SPHINX_EXECUTABLE NAMES sphinx-build HINTS $ENV{SPHINX_DIR} PATH_SUFFIXES bin DOC "Sphinx documentation generator" ) include(FindPackageHandleStandardArgs) find_package_handle_standard_args( Sphinx DEFAULT_MSG SPHINX_EXECUTABLE ) mark_as_advanced(SPHINX_EXECUTABLE) <|start_filename|>include/inexor/vulkan-renderer/wrapper/command_buffer.hpp<|end_filename|> #pragma once #include <vulkan/vulkan_core.h> #include <cstdint> #include <string> #include <vector> namespace inexor::vulkan_renderer::wrapper { class Device; class ResourceDescriptor; /// @brief RAII wrapper class for VkCommandBuffer. /// @todo Make trivially copyable (this class doesn't really "own" the command buffer, more just an OOP wrapper). class CommandBuffer { VkCommandBuffer m_command_buffer{VK_NULL_HANDLE}; const wrapper::Device &m_device; std::string m_name; public: /// @brief Default constructor. /// @param device The const reference to the device RAII wrapper class. /// @param command_pool The command pool from which the command buffer will be allocated. /// @param name The internal debug marker name of the command buffer. This must not be an empty string. CommandBuffer(const wrapper::Device &device, VkCommandPool command_pool, std::string name); CommandBuffer(const CommandBuffer &) = delete; CommandBuffer(CommandBuffer &&) noexcept; ~CommandBuffer() = default; CommandBuffer &operator=(const CommandBuffer &) = delete; CommandBuffer &operator=(CommandBuffer &&) = delete; /// @brief Call vkBeginCommandBuffer. /// @note Sometimes it's useful to pass VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT to specify that a command /// buffer can be resubmitted to a queue while it is in the pending state, and recorded into multiple primary /// command buffers. Otherwise, synchronization must be done using a VkFence. /// @param flags The command buffer usage flags, 0 by default. void begin(VkCommandBufferUsageFlags flags = 0) const; /// @brief Call vkCmdBindDescriptorSets. /// @param descriptor The const reference to the resource descriptor RAII wrapper instance. /// @param layout The pipeline layout which will be used to bind the resource descriptor. void bind_descriptor(const ResourceDescriptor &descriptor, VkPipelineLayout layout) const; /// @brief Update push constant data. /// @param layout The pipeline layout /// @param stage The shader stage that will be accepting the push constants /// @param size The size of the push constant data in bytes /// @param data A pointer to the push constant data void push_constants(VkPipelineLayout layout, VkShaderStageFlags stage, std::uint32_t size, void *data) const; /// @brief Call vkEndCommandBuffer. void end() const; // Graphics commands // TODO(): Switch to taking in OOP wrappers when we have them (e.g. bind_vertex_buffers takes in a VertexBuffer) /// @brief Call vkCmdBeginRenderPass. /// @param render_pass_bi The const reference to the VkRenderPassBeginInfo which is used. void begin_render_pass(const VkRenderPassBeginInfo &render_pass_bi) const; /// @brief Call vkCmdBindPipeline. /// @param pipeline The graphics pipeline to bind. void bind_graphics_pipeline(VkPipeline pipeline) const; /// @brief Call vkCmdBindIndexBuffer. /// @todo Don't hardcode 16 for index bit width here. /// @param buffer The index buffer to bind. void bind_index_buffer(VkBuffer buffer) const; /// @brief Call vkCmdBindVertexBuffers. /// @param buffers A std::vector of vertex buffers to bind. /// @todo Expose more parameters from vkCmdBindVertexBuffers as method arguments. void bind_vertex_buffers(const std::vector<VkBuffer> &buffers) const; /// @brief Call vkCmdDraw. /// @param vertex_count The number of vertices to draw. void draw(std::size_t vertex_count) const; /// @brief Call vkCmdDrawIndexed. /// @param index_count The number of indices to draw. void draw_indexed(std::size_t index_count) const; /// @brief Call vkCmdEndRenderPass. void end_render_pass() const; [[nodiscard]] VkCommandBuffer get() const { return m_command_buffer; } [[nodiscard]] const VkCommandBuffer *ptr() const { return &m_command_buffer; } }; } // namespace inexor::vulkan_renderer::wrapper <|start_filename|>src/vulkan-renderer/wrapper/image.cpp<|end_filename|> #include "inexor/vulkan-renderer/wrapper/image.hpp" #include "inexor/vulkan-renderer/exception.hpp" #include "inexor/vulkan-renderer/wrapper/device.hpp" #include "inexor/vulkan-renderer/wrapper/make_info.hpp" #include <spdlog/spdlog.h> #include <utility> namespace inexor::vulkan_renderer::wrapper { Image::Image(const Device &device, const VkFormat format, const VkImageUsageFlags image_usage, const VkImageAspectFlags aspect_flags, const VkSampleCountFlagBits sample_count, const std::string &name, const VkExtent2D image_extent) : m_device(device), m_format(format), m_name(name) { assert(device.device()); assert(device.physical_device()); assert(device.allocator()); assert(image_extent.width > 0); assert(image_extent.height > 0); assert(!name.empty()); auto image_ci = make_info<VkImageCreateInfo>(); image_ci.imageType = VK_IMAGE_TYPE_2D; image_ci.extent.width = image_extent.width; image_ci.extent.height = image_extent.height; image_ci.extent.depth = 1; image_ci.mipLevels = 1; image_ci.arrayLayers = 1; image_ci.format = format; image_ci.tiling = VK_IMAGE_TILING_OPTIMAL; image_ci.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; image_ci.usage = image_usage; image_ci.samples = sample_count; image_ci.sharingMode = VK_SHARING_MODE_EXCLUSIVE; VmaAllocationCreateInfo vma_allocation_ci{}; vma_allocation_ci.usage = VMA_MEMORY_USAGE_GPU_ONLY; #if VMA_RECORDING_ENABLED vma_allocation_ci.flags = VMA_ALLOCATION_CREATE_MAPPED_BIT | VMA_ALLOCATION_CREATE_USER_DATA_COPY_STRING_BIT; vma_allocation_ci.pUserData = m_name.data(); #else vma_allocation_ci.flags = VMA_ALLOCATION_CREATE_MAPPED_BIT; #endif if (const auto result = vmaCreateImage(m_device.allocator(), &image_ci, &vma_allocation_ci, &m_image, &m_allocation, &m_allocation_info); result != VK_SUCCESS) { throw VulkanException("Error: vmaCreateImage failed for image " + m_name + "!", result); } // Assign an internal name using Vulkan debug markers. m_device.set_debug_marker_name(m_image, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT, m_name); auto image_view_ci = make_info<VkImageViewCreateInfo>(); image_view_ci.image = m_image; image_view_ci.viewType = VK_IMAGE_VIEW_TYPE_2D; image_view_ci.format = format; image_view_ci.subresourceRange.aspectMask = aspect_flags; image_view_ci.subresourceRange.baseMipLevel = 0; image_view_ci.subresourceRange.levelCount = 1; image_view_ci.subresourceRange.baseArrayLayer = 0; image_view_ci.subresourceRange.layerCount = 1; if (const auto result = vkCreateImageView(device.device(), &image_view_ci, nullptr, &m_image_view); result != VK_SUCCESS) { throw VulkanException("Error: vkCreateImageView failed for image view " + m_name + "!", result); } // Assign an internal name using Vulkan debug markers. m_device.set_debug_marker_name(m_image_view, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_VIEW_EXT, m_name); } Image::Image(Image &&other) noexcept : m_device(other.m_device) { m_allocation = other.m_allocation; m_allocation_info = other.m_allocation_info; m_image = other.m_image; m_format = other.m_format; m_image_view = other.m_image_view; m_name = std::move(other.m_name); } Image::~Image() { vkDestroyImageView(m_device.device(), m_image_view, nullptr); vmaDestroyImage(m_device.allocator(), m_image, m_allocation); } } // namespace inexor::vulkan_renderer::wrapper <|start_filename|>include/inexor/vulkan-renderer/world/collision.hpp<|end_filename|> #pragma once #include <glm/vec3.hpp> #include <string> #include <tuple> namespace inexor::vulkan_renderer::world { /// @brief A wrapper for collisions between a ray and octree geometry. /// This class is used for octree collision, but it can be used for every cube-like data structure /// @tparam T A template type which offers a size() and center() method. template <typename T> class RayCubeCollision { const T &m_cube; glm::vec3 m_intersection; glm::vec3 m_selected_face; glm::vec3 m_nearest_corner; glm::vec3 m_nearest_edge; public: /// @brief Calculate point of intersection, selected face, /// nearest corner on that face, and nearest edge on that face. /// @param cube The cube to check for collision. /// @param ray_pos The start point of the ray. /// @param ray_dir The direction of the ray. RayCubeCollision(const T &cube, glm::vec3 ray_pos, glm::vec3 ray_dir); RayCubeCollision(const RayCubeCollision &) = delete; RayCubeCollision(RayCubeCollision &&other) noexcept; ~RayCubeCollision() = default; RayCubeCollision &operator=(const RayCubeCollision &) = delete; RayCubeCollision &operator=(RayCubeCollision &&) = delete; [[nodiscard]] const T &cube() const noexcept { return m_cube; } [[nodiscard]] const glm::vec3 &intersection() const noexcept { return m_intersection; } [[nodiscard]] const glm::vec3 &face() const noexcept { return m_selected_face; } [[nodiscard]] const glm::vec3 &corner() const noexcept { return m_nearest_corner; } [[nodiscard]] const glm::vec3 &edge() const noexcept { return m_nearest_edge; } }; } // namespace inexor::vulkan_renderer::world <|start_filename|>include/inexor/vulkan-renderer/wrapper/make_info.hpp<|end_filename|> #pragma once namespace inexor::vulkan_renderer::wrapper { /// @brief A small helper function that return vulkan create infos with sType already set /// @code{.cpp} /// auto render_pass_ci = make_info<VkRenderPassCreateInfo>(); /// @endcode /// @note Also zeros the returned struct template <typename T> [[nodiscard]] T make_info(); } // namespace inexor::vulkan_renderer::wrapper <|start_filename|>tests/unit_tests_main.cpp<|end_filename|> #include <gtest/gtest.h> #include "inexor/vulkan-renderer/meta.hpp" #include <iostream> int main(int argc, char **argv) { using namespace inexor::vulkan_renderer; // Print engine and application metadata. std::cout << ENGINE_NAME << ", version " << ENGINE_VERSION_STR << std::endl; std::cout << APP_NAME << ", version " << APP_VERSION_STR << std::endl; std::cout << "Configuration: " << BUILD_TYPE << ", Git SHA " << BUILD_GIT << std::endl; testing::InitGoogleTest(&argc, argv); RUN_ALL_TESTS(); std::cout << "Press Enter to close" << std::endl; std::cin.get(); } <|start_filename|>src/vulkan-renderer/io/byte_stream.cpp<|end_filename|> #include "inexor/vulkan-renderer/io/byte_stream.hpp" #include "inexor/vulkan-renderer/world/cube.hpp" #include <fstream> namespace inexor::vulkan_renderer::io { std::vector<std::uint8_t> ByteStream::read_file(const std::filesystem::path &path) { std::ifstream stream(path, std::ios::in | std::ios::binary); return {std::istreambuf_iterator<char>(stream), std::istreambuf_iterator<char>()}; } ByteStream::ByteStream(std::vector<std::uint8_t> buffer) : m_buffer(std::move(buffer)) {} ByteStream::ByteStream(const std::filesystem::path &path) : ByteStream(read_file(path)) {} std::size_t ByteStream::size() const { return m_buffer.size(); } const std::vector<std::uint8_t> &ByteStream::buffer() const { return m_buffer; } void ByteStreamReader::check_end(const std::size_t size) const { if (static_cast<std::size_t>(std::distance(m_iter, m_stream.buffer().end())) < size) { throw std::runtime_error("end would be overrun"); } } ByteStreamReader::ByteStreamReader(const ByteStream &stream) : m_stream(stream), m_iter(stream.buffer().begin()) {} void ByteStreamReader::skip(const std::size_t size) { const std::size_t skip = std::min( size, std::size_t(std::distance<std::vector<std::uint8_t>::const_iterator>(m_iter, m_stream.buffer().end()))); std::advance(m_iter, skip); } std::size_t ByteStreamReader::remaining() const { return std::distance<std::vector<std::uint8_t>::const_iterator>(m_iter, m_stream.buffer().end()); } template <> std::uint8_t ByteStreamReader::read() { check_end(1); return *m_iter++; } template <> std::uint32_t ByteStreamReader::read() { check_end(4); return (*m_iter++ << 0u) | (*m_iter++ << 8u) | (*m_iter++ << 16u) | (*m_iter++ << 24u); } template <> std::string ByteStreamReader::read(const std::size_t &size) { check_end(size); auto start = m_iter; std::advance(m_iter, size); return std::string(start, m_iter); } template <> world::Cube::Type ByteStreamReader::read() { return static_cast<world::Cube::Type>(read<std::uint8_t>()); } template <> std::array<world::Indentation, 12> ByteStreamReader::read() { check_end(9); std::array<world::Indentation, 12> indentations; auto writer = indentations.begin(); // NOLINT const auto end = m_iter + 9; while (m_iter != end) { *writer++ = world::Indentation(*m_iter >> 2u); *writer++ = world::Indentation(((*m_iter & 0b00000011u) << 4u) | (*(++m_iter) >> 4u)); *writer++ = world::Indentation(((*m_iter & 0b00001111u) << 2u) | (*(++m_iter) >> 6u)); *writer++ = world::Indentation(*m_iter++ & 0b00111111u); } return indentations; } template <> void ByteStreamWriter::write(const std::uint8_t &value) { m_buffer.emplace_back(value); } template <> void ByteStreamWriter::write(const std::uint32_t &value) { m_buffer.emplace_back(value >> 24u); m_buffer.emplace_back(value >> 16u); m_buffer.emplace_back(value >> 8u); m_buffer.emplace_back(value); } template <> void ByteStreamWriter::write(const std::string &value) { std::copy(value.begin(), value.end(), std::back_inserter(m_buffer)); } template <> void ByteStreamWriter::write(const world::Cube::Type &value) { write(static_cast<std::uint8_t>(value)); } template <> void ByteStreamWriter::write(const std::array<world::Indentation, 12> &value) { for (auto iter = value.begin(); iter != value.end(); iter++) { // NOLINT write<std::uint8_t>((iter->uid() << 2u) | ((++iter)->uid() >> 4)); write<std::uint8_t>((iter->uid() << 4u) | ((++iter)->uid() >> 2)); write<std::uint8_t>((iter->uid() << 6u) | ((++iter)->uid())); } } } // namespace inexor::vulkan_renderer::io
JoseETeixeira/vulkan-renderer
<|start_filename|>aws/tagsGeneric_test.go<|end_filename|> package aws import ( "reflect" "testing" "github.com/aws/aws-sdk-go/aws" ) // go test -v -run="TestDiffGenericTags" func TestDiffGenericTags(t *testing.T) { cases := []struct { Old, New map[string]interface{} Create, Remove map[string]string }{ // Basic add/remove { Old: map[string]interface{}{ "foo": "bar", }, New: map[string]interface{}{ "bar": "baz", }, Create: map[string]string{ "bar": "baz", }, Remove: map[string]string{ "foo": "bar", }, }, // Modify { Old: map[string]interface{}{ "foo": "bar", }, New: map[string]interface{}{ "foo": "baz", }, Create: map[string]string{ "foo": "baz", }, Remove: map[string]string{ "foo": "bar", }, }, } for i, tc := range cases { c, r := diffTagsGeneric(tc.Old, tc.New) cm := tagsToMapGeneric(c) rm := tagsToMapGeneric(r) if !reflect.DeepEqual(cm, tc.Create) { t.Fatalf("%d: bad create: %#v", i, cm) } if !reflect.DeepEqual(rm, tc.Remove) { t.Fatalf("%d: bad remove: %#v", i, rm) } } } // go test -v -run="TestIgnoringTagsGeneric" func TestIgnoringTagsGeneric(t *testing.T) { ignoredTags := map[string]*string{ "aws:cloudformation:logical-id": aws.String("foo"), "aws:foo:bar": aws.String("baz"), } for k, v := range ignoredTags { if !tagIgnoredGeneric(k) { t.Fatalf("Tag %v with value %v not ignored, but should be!", k, *v) } } }
alessandromr/terraform-provider-aws-serverless
<|start_filename|>examples/game_data.json<|end_filename|> {"GDDB_ver":"2.0","db_name":"game_data","tables":[{"table_name":"resources","props":[{"name":"id","type":"1","auto_increment":"1"},{"name":"name","type":"3","auto_increment":"0"},{"name":"img_path","type":"4","auto_increment":"0"}],"data":["1","Energy","res://examples/resources/energy.png","2","Food","res://examples/resources/food.png","3","Wood","res://examples/resources/wood.png","4","Stone","res://examples/resources/stone.png"]},{"table_name":"users","props":[{"name":"id","type":"1","auto_increment":"1"},{"name":"name","type":"3","auto_increment":"0"},{"name":"energy","type":"table","table_name":"resources","auto_increment":"0"},{"name":"energy_amount","type":"1","auto_increment":"0"},{"name":"food","type":"table","table_name":"resources","auto_increment":"0"},{"name":"food_amount","type":"1","auto_increment":"0"},{"name":"wood","type":"table","table_name":"resources","auto_increment":"0"},{"name":"wood_amount","type":"1","auto_increment":"0"},{"name":"stone","type":"table","table_name":"resources","auto_increment":"0"},{"name":"stone_amount","type":"1","auto_increment":"0"}],"data":["1","PlayerName","0","100","1","10000","2","10000","3","10000"]}]}
plazarotello/Godot-Database-Manager
<|start_filename|>app.js<|end_filename|> // Provide custom regenerator runtime and core-js require("babel-polyfill"); // Node babel source map support require("source-map-support").install(); // Javascript require hook require("babel-core/register", { ignore: /.css$/ }); // Css modules hook require("css-modules-require-hook")({ generateScopedName: "[name]_[local]_[hash:base64:3]", camelCase: true, rootDir: "./client/*" }); // Image required hook require("asset-require-hook")({ extensions: ["jpg", "png", "gif", "webp"], name: "/dist/img/[name].[ext]", limit: 2000 }); const common = require("./common.json"); let koa = require("koa"), logger = require("koa-logger"), serve = require("koa-static2"), compress = require("koa-compress"), bodyParser = require("koa-bodyparser"), json = require("koa-json"), passport = require("koa-passport"), session = require("koa-session"), routers = require("./server/routes/router.js"); const App = () => { let app = new koa(); // 路由 app.keys = ["hello-ssr"]; app.use(logger()); // 使用logger日志库 // 使用gzip压缩 app.use( compress({ filter: function(content_type) { return /text/i.test(content_type); }, threshold: 2048, flush: require("zlib").Z_SYNC_FLUSH }) ); app.use(bodyParser()); // get request body app.use(json({ pretty: false })); // send request json app.use(serve("", __dirname + "/public")); // use static dir // session const CONFIG = { key: "ssr-react", maxAge: 86400000, overwrite: true, httpOnly: true, signed: true }; app.use(session(CONFIG, app)); // authentication require("./server/auth/passport.js"); // passport app.use(passport.initialize()); app.use(passport.session()); app.use(routers); // 路由 return app; }; // Create koa server and listen var creatServer = () => { const app = App(); app.listen(common.serverPort, function() { console.log("Listening at localhost:" + common.serverPort); }); }; creatServer(); <|start_filename|>client/src/view/containers/notFound/index.js<|end_filename|> import React,{Component} from 'react'; import Nav from '../../components/nav/index.js'; import './index.css'; export default class App extends Component { constructor(props) { super(props); } render() { return ( <div> <Nav/> <div className="wrapper"> <p>404!</p> <p>找不到页面</p> </div> </div> ); } } <|start_filename|>client/src/view/containers/login/index.js<|end_filename|> import React, { Component } from "react"; import PropTypes from "prop-types"; import Nav from "./../../components/nav/index.js"; import LoginForm from "./loginForm"; import "./index.css"; class App extends Component { constructor(props) { super(props); } render() { return ( <div> <Nav /> <LoginForm history={this.props.history} /> <div className="form-reg"> 还没有账号? <a href="#">立即注册</a> </div> </div> ); } } App.propTypes = { history: PropTypes.object }; export default App; <|start_filename|>server/config/db.js<|end_filename|> import Sequelize from 'sequelize'; import configs from './db.json'; const dbHost = configs.mysql.host, dbPort = configs.mysql.port, dbUsername = configs.mysql.username, dbPassword = configs.mysql.password, dbName = configs.mysql.dbName; // mysql 连接配置 const db = { sequelize: new Sequelize(dbName, dbUsername, dbPassword, { host: dbHost, dialect: 'mysql', port: dbPort, pool: { max: 5, min: 0, idle: 10000 }, define: { freezeTableName: true, // 数据库中的表明与程序中的保持一致,否则数据库中的表名会以复数的形式命名 timestamps: false } }) }; // user table model db.User = db.sequelize.import ('../models/user.js'); db.UserInfo = db.sequelize.import ('../models/userInfo.js'); export default db; <|start_filename|>client/src/redux/constants/ActionTypes.js<|end_filename|> export const INCREMENT = 'INCREMENT'; export const LOGIN = 'LOGIN'; //user logined export const LOGOUT = 'LOGOUT'; //user logout <|start_filename|>server/models/user.js<|end_filename|> // model 定义格式为sequelize.define('name', {attributes}, {options}) // model 模版数据库,建立数据库的摸板 export default function(sequelize, DataTypes) { var User = sequelize.define("user", { id: { type: DataTypes.INTEGER, primaryKey: true, allowNull: false, autoIncrement: true }, username: { type: DataTypes.STRING(20), allowNull: false, validate: { is: /^[\\u4e00-\\u9fa5_a-zA-Z0-9-]{3,16}$/ } }, captcha: DataTypes.STRING(4), password: DataTypes.STRING, email: { type: DataTypes.STRING(32), allowNull: false, validate: { isEmail: true } } }); User.sync(); return User; } <|start_filename|>client/src/redux/reducers/user_reducer.js<|end_filename|> const initialState = { logined: false }; const userReducer = (state = initialState, action) => { switch (action.type) { case 'LOGIN': return {logined: true}; case 'LOGOUT': return {logined: false}; default: return state; } }; export default userReducer; <|start_filename|>public/dist/css/style.css<|end_filename|> .main-header { position: relative; background: #fff; border-bottom: 1px solid #f1f1f1; color: #909090; height: 60px; line-height: 60px; } .main-header .nav { transition: opacity 250ms ease-in-out; text-align: center; position: fixed; top: 0; left: 0; right: 0; z-index: 9; } .main-header .nav li { color: #71777c; font-size: 16px; -ms-flex-pack: center; justify-content: center; } .main-header .nav li a { padding: 10px; height: 50px; color: #71777c; } .main-header .nav li.fl { border-left: 1px solid #eee; float: left; } .main-header .nav li.fr { border-right: 1px solid #eee; float: right; } .main-header .nav li.login_visable { display: none; } .main-container { position: relative; margin: 0 auto; width: 100%; max-width: 960px; } .view { margin-top: 1.7rem; display: -ms-flexbox; display: flex; } .welcome-feed { background: #fff; overflow: hidden; -ms-flex-positive: 1; flex-grow: 1; } .welcome-side { background: #fff; width: 240px; min-width: 240px; margin-left: 20px; display: block; } .category-nav { background-color: #fff; padding: 1.5rem 2rem; display: -ms-flexbox; display: flex; -ms-flex-pack: justify; justify-content: space-between; border-bottom: 1px solid #f6f6f6; } .nav-list { display: -ms-flexbox; display: flex; -ms-flex-align: baseline; align-items: baseline; } .nav-item { position: relative; cursor: pointer; font-size: 14px; } li.nav-item.route-active { color: #007fff; } li.nav-item:not(:last-child) { margin-right: 20px; } .category-nav .nav-list li.nav-item.route-active { color: #007fff; } .section { background-color: #fff; border-radius: 2px; margin-bottom: 1.5rem; overflow: hidden; padding: 1.333rem; } .section .title { font-weight: 600; margin-bottom: 0.5rem; font-size: 1.167rem; color: #2e3135; } .ticket { font-size: 14px; color: #8f969c; margin-bottom: 1rem; } .input-box { position: relative; margin-bottom: 0.833rem; } .input { padding: 0.5rem 0.6rem; width: 100%; background-color: #fbfbfb; border: 1px solid #f4f4f4; border-radius: 2px; outline: none; box-sizing: border-box; } .submit-btn { padding: 0.7rem 0; width: 100%; font-size: 1.167rem; border-radius: 2px; -webkit-appearance: none; -moz-appearance: none; appearance: none; background-color: #007fff; color: #fff; border-radius: 2px; border: none; padding: 0.5rem 1.3rem; outline: none; transition: background-color 0.3s, color 0.3s; cursor: pointer; border: none; padding: 0.5rem 1.3rem; outline: none; transition: background-color 0.3s, color 0.3s; cursor: pointer; } .submit-btn:hover { background-color: #0371df; color: #fff; } html { -webkit-text-size-adjust: 100%; -ms-text-size-adjust: 100%; background-color: #f4f5f5; } body, div, dl, dt, dd, ul, ol, li, h1, h2, h3, h4, h5, h6, pre, code, form, fieldset, legend, input, textarea, p, blockquote, th, td, hr, button, article, aside, details, figcaption, figure, footer, header, hgroup, menu, nav, section { margin: 0; padding: 0; } article, aside, details, figcaption, figure, footer, header, hgroup, menu, nav, section { display: block; } audio, canvas, video { display: inline-block; *display: inline; *zoom: 1; } body, button, input, select, textarea { font: 12px/1.5 "Source Sans Pro", -apple-system, BlinkMacSystemFont, "PingFang SC", "Helvetica Neue", STHeiti, "Microsoft Yahei", Tahoma, Simsun, sans-serif; font-weight: 200; } input, select, textarea { font-size: 100%; } table { border-collapse: collapse; border-spacing: 0; } th { text-align: inherit; } fieldset, img { border: 0; } iframe { display: block; } abbr, acronym { border: 0; font-variant: normal; } del { text-decoration: line-through; } address, caption, cite, code, dfn, em, th, var { font-style: normal; font-weight: 500; } ol, ul { list-style: none; } /* 对齐是排版最重要的因素, 别让什么都居中 */ caption, th { text-align: left; } h1, h2, h3, h4, h5, h6 { font-size: 100%; font-weight: 500; } q:before, q:after { content: ""; } sub, sup { font-size: 75%; line-height: 0; position: relative; vertical-align: baseline; } sup { top: -0.5em; } sub { bottom: -0.25em; } a:hover { /*text-decoration: underline;*/ } ins, a { text-decoration: none; } .reg-container { // background: #fff; position: relative; margin: 0 auto; width: 100%; max-width: 960px; } .reg-form { margin-top: 1.7rem; display: -ms-flexbox; display: flex; } .reg-form .form { background: #fff; width: 280px; margin: 0 auto; padding-bottom: 80px; } .reg-form .form li { text-align: center; padding: 10px 0; font-size: 16px; color: #575757; position: relative; } .reg-form .form li .segmentation { background: #eeeeee; border-radius: 5px; display: inline-block; width: 74px; height: 6px; } .reg-form .form li input { border: none; text-align: center; outline: none; width: 100%; } .reg-form .form li span.error { color: #f00; position: absolute; right: -115px; font-size: 12px; line-height: 15px; bottom: 8px; width: 110px; text-align: left; } .reg-form .form li .form-submit { border: 1px solid #c9c9c9; width: 100%; background: #ffffff; height: 45px; line-height: 45px; color: #727272; cursor: pointer; border-radius: 5px; outline: none; font-size: 14px; } .reg-form .form li .remmber_input { width: auto; } .reg-form .form li .remmber_pw { font-size: 14px; margin-left: 5px; } .reg-form .form li.form-border { padding-top : 40px; border-bottom : 1px solid #eee; } .reg-form .form li.form_pw { padding-bottom : 40px; } .reg-form .form li.form-top { padding-top : 40px; } .reg-form .tips { background: #fff; height: 40px; position: fixed; top: 46px; width: 400px; margin-left: -200px; left: 50%; border-radius: 3px; display: none; line-height: 40px; text-align: center; font-size: 14px; color: #000000; font-weight: 200; z-index: 10; box-shadow: 1px 1px 3px #ccc; } .reg-form .tips-show { display: block; }/* login page style */ .form { width: 280px; margin: 0 auto; padding-bottom: 80px; } .form li { text-align: center; padding: 10px 0; font-size: 16px; color: #575757; position: relative; } .form li .segmentation { background: #eeeeee; border-radius: 5px; display: inline-block; width: 74px; height: 6px; } .form li input { border: none; text-align: center; outline: none; width: 100%; } .form li span.error { color: #f00; position: absolute; right: -115px; font-size: 12px; line-height: 15px; bottom: 8px; width: 110px; text-align: left; } .form li .form_submit { border: 1px solid #c9c9c9; width: 100%; background: #ffffff; height: 45px; line-height: 45px; color: #727272; cursor: pointer; border-radius: 5px; outline: none; font-size: 14px; } .form li .remmber_input { width: auto; } .form li .remmber_pw { font-size: 14px; margin-left: 5px; } .form li.form_border { padding-top: 40px; border-bottom: 1px solid #eee; } .form li.form_pw { padding-bottom: 40px; } .form li.form-top { padding-top: 40px; } .form .tips-show { display: block; } .wrapper { text-align: center; padding-top: 38px; line-height: 2em; font-size: 12px; } .wrapper img { margin-bottom: 30px; } /*# sourceMappingURL=style.css.map*/ <|start_filename|>client/src/view/components/nav/index.css<|end_filename|> .main-header { position: relative; background: #fff; border-bottom: 1px solid #f1f1f1; color: #909090; height: 60px; line-height: 60px; } .main-header .nav { transition: opacity 250ms ease-in-out; text-align: center; position: fixed; top: 0; left: 0; right: 0; z-index: 9; li { color: #71777c; font-size: 16px; justify-content: center; a { padding: 10px; height: 50px; color: #71777c; } &.fl { border-left: 1px solid #eee; float: left; } &.fr { border-right: 1px solid #eee; float: right; } &.login_visable { display: none; } } } <|start_filename|>server/controllers/login.js<|end_filename|> import React from "react"; import { renderToString } from "react-dom/server"; import { StaticRouter } from "react-router-dom"; import { layout } from "../view/layout.js"; import { Provider } from "react-redux"; import bcrypt from "<PASSWORD>js"; import passport from "koa-passport"; import configureStore from "../../client/src/redux/store/configureStore"; import App from "../../client/src/view/containers/login/index.js"; import db from "../config/db.js"; const User = db.User; // get page and switch json and html export function index(ctx) { if (ctx.isAuthenticated()) { ctx.redirect("/"); } switch (ctx.accepts("json", "html")) { case "html": { //init store let loginStore = { user: { logined: ctx.isAuthenticated() } }; const store = configureStore(loginStore); const html = layout( renderToString( <Provider store={store}> <StaticRouter location={ctx.url} context={{}}> <App /> </StaticRouter> </Provider> ), store.getState() ); ctx.body = html; } break; case "json": { let callBackData = { status: 200, message: "这个是登录页", data: {} }; ctx.body = callBackData; } break; default: { // allow json and html only ctx.throw(406, "allow json and html only"); return; } } } // user login export async function login(ctx) { if (ctx.accepts("json", "html") == "json") { let data = ctx.request.body; //If reg data is null,reback some tips if (!data.username || !data.password) { let callBackData = { success: false, status: 200, message: "请输入您的账号或邮箱和密码!", data: {} }; ctx.body = callBackData; } else { await User.findOne({ attributes: ["id", "username", "password"], where: { $or: [ { username: data.username }, { email: data.username } ] } }).then( async user => { if (user) { let isMatch = bcrypt.compareSync(data.password, user.password); if (isMatch) { await passport.authenticate("local", function(err, user) { let callBackData = { success: true, status: 200, message: "登录成功!", data: {} }; ctx.body = callBackData; return ctx.login(user); })(ctx); } else { let callBackData = { success: false, status: 200, message: "请输入您的账号或邮箱和密码错误!", data: {} }; ctx.body = callBackData; } } else { let callBackData = { success: false, status: 200, message: "用户名或邮箱不存在!", data: {} }; ctx.body = callBackData; } }, function() { let callBackData = { success: false, status: 200, message: "登录失败!", data: {} }; ctx.body = callBackData; } ); } } } // user logout export function logout(ctx) { ctx.logout(); switch (ctx.accepts("json", "html")) { case "html": { let callBackData = { success: true, status: 200, message: "登出成功!", data: {} }; ctx.body = callBackData; ctx.redirect("/"); } break; case "json": { let callBackData = { success: true, status: 200, message: "登出成功!", data: {} }; ctx.body = callBackData; } break; default: { // allow json and html only ctx.throw(406, "allow json and html only"); return; } } } <|start_filename|>client/src/dist/css/style.css<|end_filename|> ::-webkit-input-placeholder { color: #c5c5c5; transition: opacity 250ms ease-in-out; } :focus::-webkit-input-placeholder { opacity: 0.5; } body { padding-top: 46px; } .nav { transition: opacity 250ms ease-in-out; height: 45px; line-height: 45px; background: #fff; border-bottom: 1px solid #eeeeee; text-align: center; position: fixed; top: 0; left: 0; right: 0; z-index: 9; li { display: inline-block; padding: 0 20px; a { color: #626262; } &.fl { border-left: 1px solid #eee; } &.fr { border-right: 1px solid #eee; } &.login_visable { display: none; } .logo { /* background: url(../img/logo.png) no-repeat center; */ background-size: 100% 100%; width: 26px; height: 22px; display: inline-block; vertical-align: middle; } } } .fl { float: left; } .fr { float: right; } /* .avatar { float: right; position: relative; img { width: 30px; vertical-align: middle; border-radius: 50%; } &:hover { dl { display: block; } } dl { position: absolute; width: 100%; left: -1px; text-align: center; line-height: 23px; border: 1px solid #eee; display: none; color: #686868; background: #fff; dt { cursor: pointer; &:hover { background: #f3f3f3; } } } } */ <|start_filename|>server/routes/router.js<|end_filename|> /** * router.get/post('/path', async fn) */ import Router from "koa-router"; const router = new Router(); // 首页路由 router.get("/", require("../controllers/index.js").index); router.post("/rest/v1/getList", require("../controllers/index.js").getList); // 登录页 router.get("/login", require("../controllers/login.js").index); router.post("/rest/v1/login", require("../controllers/login.js").login); router.get("/logout", require("../controllers/login.js").logout); // 注册页 router.get("/reg", require("../controllers/reg.js").index); router.post("/regUser", require("../controllers/reg.js").reg); router.post("/vaildateUser", require("../controllers/reg.js").vaildateUser); router.post("/vaildateEmail", require("../controllers/reg.js").vaildateEmail); // 404 router.get("/notFound", require("../controllers/notFound.js").index); // set a router module.exports = router.routes(); <|start_filename|>client/src/redux/actions/index.js<|end_filename|> import * as types from "../constants/ActionTypes"; export const increment = () => ({ type: types.INCREMENT }); //user export const login = () => ({ type: types.LOGIN }); export const logout = () => ({ type: types.LOGOUT }); <|start_filename|>client/config/webpack.config.dev.js<|end_filename|> /** 加载常用模块及Webpack需要的模块组件 **/ //加载Node的Path模块 const path = require("path"), //加载webpack模块 webpack = require("webpack"), //加载自动化HTML自动化编译插件 HtmlWebpackPlugin = require("html-webpack-plugin"), autoprefixer = require("autoprefixer"), precss = require("precss"); /** 设置默认常用路径 **/ //srcDir为当前开发目录(默认:/src) const srcDir = path.resolve(process.cwd(), "src"); //assetsDir为当前建立目录(默认:/assets) const assetsDir = path.resolve(process.cwd(), "assets"); //生成JS的目录地址(默认:) const jsDir = "dist/js/"; //生成css的目录地址(默认:) const cssDir = "dist/css/"; const config = { devtool: "source-map", entry: { // index: ['react-hot-loader/patch', 'webpack-hot-middleware/client', './src/index.js'] index: [ "react-hot-loader/patch", "webpack-dev-server/client?http://0.0.0.0:8000", "webpack/hot/only-dev-server", "./src/index.js" ], vendor: [ "react", "react-dom", "redux", "react-redux", "react-router", "axios" ] }, output: { path: assetsDir, filename: jsDir + "[name].js", publicPath: "/" }, module: { //加载器配置 rules: [ { test: /\.css$/, include: [path.resolve(srcDir, cssDir)], use: [ { loader: "style-loader" }, { loader: "css-loader", options: { modules: true, camelCase: true, localIdentName: "[name]_[local]_[hash:base64:3]", importLoaders: 1, sourceMap: true } }, { loader: "postcss-loader", options: { sourceMap: true, plugins: () => [ precss(), autoprefixer({ browsers: ["last 3 version", "ie >= 10"] }) // postcsseasysprites({imagePath: '../img', spritePath: './assets/dist/img'}) ] } } ] }, { test: /\.css$/, exclude: [path.resolve(srcDir, cssDir)], use: [ { loader: "style-loader" }, { loader: "css-loader", options: { importLoaders: 1, sourceMap: true } }, { loader: "postcss-loader", options: { sourceMap: true, plugins: () => [ precss(), autoprefixer({ browsers: ["last 3 version", "ie >= 10"] }) // postcsseasysprites({ // imagePath: "../img", // spritePath: "./assets/dist/img" // }) ] } } ] }, { test: /\.js$/, exclude: /node_modules/, use: [ { loader: "babel-loader" // options: { // presets: ['react-hmre'] // } } ] }, { test: /\.(png|jpeg|jpg|gif|svg)$/, use: [ { loader: "file-loader", options: { name: "dist/img/[name].[ext]" } } ] } ] }, plugins: [ new HtmlWebpackPlugin({ template: "src/index.html", inject: true, hash: true, minify: { removeComments: true, collapseWhitespace: false }, chunks: ["index", "vendor", "manifest"], filename: "index.html" }), new webpack.optimize.CommonsChunkPlugin({ names: ["vendor", "manifest"], filename: jsDir + "[name].js" }), new webpack.HotModuleReplacementPlugin(), new webpack.NamedModulesPlugin(), new webpack.NoEmitOnErrorsPlugin() ] }; module.exports = config; <|start_filename|>server/auth/passport.js<|end_filename|> import passport from "koa-passport"; import { Strategy } from "passport-local"; import db from "../config/db.js"; const User = db.User; // 序列化ctx.login()触发 passport.serializeUser(function(user, done) { console.log("serializeUser: ", user); done(null, user.id); }); // 反序列化(请求时,session中存在"passport":{"user":"1"}触发) passport.deserializeUser(function(id, done) { console.log('deserializeUser: ', id) User.findById(id).then(function(user) { if (user) { done(null, user.get()); } else { done(user.errors, null); } }); }); // 提交数据(策略) passport.use( new Strategy( { usernameField: "username", passwordField: "password", passReqToCallback: true }, function(req, username, password, done) { console.log(11111111) User.findOne({ attributes: ["id", "username"], where: { username: username } }) .then(function(user) { if (!user) { return done(null, false, { message: "Email does not exist" }); } return done(null, user.get()); }) .catch(function() { return done(null, false); }); } ) ); <|start_filename|>client/src/view/containers/login/loginForm.js<|end_filename|> import React, { Component } from "react"; import PropTypes from "prop-types"; import { Field, reduxForm, SubmissionError } from "redux-form"; import { connect } from "react-redux"; import axios from "axios"; import * as actions from "../../../redux/actions/index"; if (process.env.NODE_ENV !== "production") { require("../../../mock/mock"); } const submit = async function submit(values) { let _this = this; await axios.post("/rest/v1/login", values).then(function(response) { if (!response.data.success) { throw new SubmissionError({ _error: response.data.message }); } else { _this.props.login(); _this.props.history.push("/"); } }); }; class LoginForm extends Component { constructor(props) { super(props); } render() { const { error, handleSubmit, pristine, submitting } = this.props; return ( <form onSubmit={handleSubmit(submit.bind(this))}> <div className={error ? "tips-show" : "tips"}>{error}</div> <ul className="form"> <li> <b>去登录</b> </li> <li className="form_border"> <Field component="input" name="username" placeholder="用户名 / 邮箱" type="text" /> </li> <li className="form_pw"> <Field component="input" name="password" placeholder="密码" type="password" /> </li> <li> <Field className="remmber_input" component="input" name="remmberPw" id="remmberPw" type="checkbox" /> <label htmlFor="remmberPw" className="remmber_pw"> 记住密码 </label> </li> <li> <button className="form_submit" disabled={pristine || submitting} type="submit" > 登录 </button> </li> </ul> </form> ); } } LoginForm.propTypes = { error: PropTypes.object, pristine: PropTypes.bool, handleSubmit: PropTypes.func, submitting: PropTypes.bool }; export default connect( null, actions )(reduxForm({ form: "loginForm" })(LoginForm)); <|start_filename|>server/models/userInfo.js<|end_filename|> export default function(sequelize, DataTypes) { var UserInfo = sequelize.define('UserInfo', { // id: { // type: DataTypes.INTEGER, // primaryKey: true, // allowNull: false, // autoIncrement: true // }, phoneNum:{ type: DataTypes.STRING(11), allowNull: false, validate: { is:/^[\\u4e00-\\u9fa5_a-zA-Z0-9-]{3,16}$/ } } }); UserInfo.sync(); return UserInfo; } <|start_filename|>server/controllers/index.js<|end_filename|> import React from "react"; import { renderToString } from "react-dom/server"; import { StaticRouter } from "react-router-dom"; import { layout } from "../view/layout.js"; import { Provider } from "react-redux"; import configureStore from "../../client/src/redux/store/configureStore"; import App from "../../client/src/view/homePage.js"; import db from "../config/db.js"; const User = db.User; // get page and switch json and html export function index(ctx) { switch (ctx.accepts("json", "html")) { case "html": { // init store let loginStore = { user: { logined: ctx.isAuthenticated() } }; const store = configureStore(loginStore); const html = layout( renderToString( <Provider store={store}> <StaticRouter location={ctx.url} context={{}}> <App /> </StaticRouter> </Provider> ), store.getState() ); ctx.body = html; } break; case "json": { let callBackData = { status: 200, message: "这个是主页", data: {} }; ctx.body = callBackData; } break; default: { // allow json and html only ctx.throw(406, "allow json and html only"); return; } } } // demo Post export async function getList(ctx) { if (ctx.accepts("json", "html") == "json") { const result = await User.findAll(); // 用 Sequelize 查询数据库 const callBackData = { success: true, data: result }; ctx.body = callBackData; } } <|start_filename|>client/src/view/containers/login/index.css<|end_filename|> /* login page style */ .form { width: 280px; margin: 0 auto; padding-bottom: 80px; li { text-align: center; padding: 10px 0; font-size: 16px; color: #575757; position: relative; &.form_border { padding-top: 40px; border-bottom: 1px solid #eee; } &.form_pw { padding-bottom: 40px; } &.form-top { padding-top: 40px; } .segmentation { background: #eeeeee; border-radius: 5px; display: inline-block; width: 74px; height: 6px; } input { border: none; text-align: center; outline: none; width: 100%; } span.error { color: #f00; position: absolute; right: -115px; font-size: 12px; line-height: 15px; bottom: 8px; width: 110px; text-align: left; } .form_submit { border: 1px solid #c9c9c9; width: 100%; background: #ffffff; height: 45px; line-height: 45px; color: #727272; cursor: pointer; border-radius: 5px; outline: none; font-size: 14px; } .remmber_input { width: auto; } .remmber_pw { font-size: 14px; margin-left: 5px; } } .tips-show { display: block; } } <|start_filename|>client/src/redux/store/middlewares.js<|end_filename|> import {applyMiddleware} from 'redux'; import thunk from 'redux-thunk'; import logger from 'redux-logger'; let middleWare; if (process.env.NODE_ENV === 'production') { middleWare = applyMiddleware(thunk); } else { middleWare = applyMiddleware(thunk, logger); } export default middleWare; <|start_filename|>client/src/view/containers/reg/index.js<|end_filename|> import React, { Component } from "react"; import PropTypes from "prop-types"; import Nav from "../../../view/components/nav/index.js"; import RegForm from "./regForm"; import "./index.css"; class App extends Component { constructor(props) { super(props); } render() { let { history } = this.props; return ( <React.Fragment> <Nav /> <div className="reg-container"> <RegForm history={history} /> <div className="form-reg"> 点击 注册 按钮表示同意 <a href="#">《用户注册规则》</a> </div> </div> </React.Fragment> ); } } App.propTypes = { history: PropTypes.object }; export default App; <|start_filename|>client/src/redux/store/configureStore.prod.js<|end_filename|> import { createStore } from 'redux'; import rootReducer from '../reducers'; import middlewares from './middlewares'; export default function configureStore (initialState) { return createStore(rootReducer, initialState, middlewares); } <|start_filename|>client/config/webpack.config.prod.js<|end_filename|> /** 加载常用模块及Webpack需要的模块组件 **/ //加载Node的Path模块 const path = require("path"), //加载webpack模块 webpack = require("webpack"), //加载自动化css独立加载插件 ExtractTextPlugin = require("extract-text-webpack-plugin"), //加载自动化HTML自动化编译插件 HtmlWebpackPlugin = require("html-webpack-plugin"), autoprefixer = require("autoprefixer"), precss = require("precss"), //加载JS模块压缩编译插件 UglifyJsPlugin = webpack.optimize.UglifyJsPlugin; /** 设置默认常用路径 **/ //srcDir为当前开发目录(默认:/src) const srcDir = path.resolve(process.cwd(), "src"), //assetsDir为当前建立目录(默认:/assets) assetsDir = path.resolve(process.cwd(), "../public"), //生成JS的目录地址(默认:) jsDir = "dist/js/", //生成css的目录地址(默认:) cssDir = "dist/css/", //载入默认配置 common = require("../../common.json"); const config = { devtool: "source-map", entry: { index: "./src/index.js", vendor: [ "react", "react-dom", "redux", "react-redux", "react-router", "axios" ] }, output: { path: assetsDir, filename: jsDir + "[name].js", publicPath: common.publicPath }, module: { //加载器配置 rules: [ { test: /\.css$/, include: [path.resolve(srcDir, cssDir)], use: ExtractTextPlugin.extract({ fallback: "style-loader", use: [ { loader: "css-loader", options: { modules: true, camelCase: true, localIdentName: "[name]_[local]_[hash:base64:3]", importLoaders: 1, sourceMap: true } }, { loader: "postcss-loader", options: { sourceMap: true, plugins: () => [ precss(), autoprefixer({ browsers: ["last 3 version", "ie >= 10"] }) ] } } ] }) }, { test: /\.css$/, exclude: [path.resolve(srcDir, cssDir)], use: ExtractTextPlugin.extract({ fallback: "style-loader", use: [ { loader: "css-loader", options: { importLoaders: 1, sourceMap: true } }, { loader: "postcss-loader", options: { sourceMap: true, plugins: () => [ precss(), autoprefixer({ browsers: ["last 3 version", "ie >= 10"] }) ] } } ] }) }, { test: /\.js$/, exclude: /node_modules/, use: [ { loader: "babel-loader" } ] }, { test: /\.(png|jpeg|jpg|gif|svg)$/, use: [ { loader: "file-loader", options: { name: "dist/img/[name].[ext]" } } ] } ] }, plugins: [ new ExtractTextPlugin("dist/css/style.css"), new webpack.DefinePlugin({ "process.env": { NODE_ENV: JSON.stringify("production") } }), new HtmlWebpackPlugin({ template: "src/index.html", inject: true, hash: true, minify: { removeComments: true, collapseWhitespace: false }, chunks: ["index", "vendor", "manifest"], filename: "index.html" }), new webpack.optimize.CommonsChunkPlugin({ names: ["vendor", "manifest"], filename: jsDir + "[name].js" }), new UglifyJsPlugin({ // 最紧凑的输出 beautify: false, // 删除所有的注释 comments: false, compress: { // 在UglifyJs删除没有用到的代码时不输出警告 warnings: false, // 删除所有的 `console` 语句 // 还可以兼容ie浏览器 drop_console: true, // 内嵌定义了但是只用到一次的变量 collapse_vars: true, // 提取出出现多次但是没有定义成变量去引用的静态值 reduce_vars: true } }), new webpack.NoEmitOnErrorsPlugin() ] }; module.exports = config; <|start_filename|>client/src/view/containers/reg/index.css<|end_filename|> .reg-container { // background: #fff; position: relative; margin: 0 auto; width: 100%; max-width: 960px; } .reg-form { margin-top: 1.7rem; display: flex; .form { background: #fff; width: 280px; margin: 0 auto; padding-bottom: 80px; li { text-align: center; padding: 10px 0; font-size: 16px; color: #575757; position: relative; &.form-border { padding-top: 40px; border-bottom: 1px solid #eee; } &.form_pw { padding-bottom: 40px; } &.form-top { padding-top: 40px; } .segmentation { background: #eeeeee; border-radius: 5px; display: inline-block; width: 74px; height: 6px; } input { border: none; text-align: center; outline: none; width: 100%; } span.error { color: #f00; position: absolute; right: -115px; font-size: 12px; line-height: 15px; bottom: 8px; width: 110px; text-align: left; } .form-submit { border: 1px solid #c9c9c9; width: 100%; background: #ffffff; height: 45px; line-height: 45px; color: #727272; cursor: pointer; border-radius: 5px; outline: none; font-size: 14px; } .remmber_input { width: auto; } .remmber_pw { font-size: 14px; margin-left: 5px; } } } .tips { background: #fff; height: 40px; position: fixed; top: 46px; width: 400px; margin-left: -200px; left: 50%; border-radius: 3px; display: none; line-height: 40px; text-align: center; font-size: 14px; color: #000000; font-weight: 200; z-index: 10; box-shadow: 1px 1px 3px #ccc; } .tips-show { display: block; } } <|start_filename|>client/src/view/containers/reg/regForm.js<|end_filename|> import React, { Component } from "react"; import PropTypes from "prop-types"; import { Field, reduxForm, SubmissionError } from "redux-form"; import { connect } from "react-redux"; import axios from "axios"; import * as actions from "../../../redux/actions/index"; if (process.env.NODE_ENV !== "production") { require("../../../mock/mock"); } let validataUsername = false; let validataEmail = false; const asyncValidate = async (values, dispatch, props, field) => { if (field == "username") { await axios.post("/vaildateUser", values).then(function(response) { if (!response.data.success) { validataUsername = true; console.log(validataUsername, validataEmail); if (validataUsername && validataEmail) { throw { username: "用户名已被占用", email: "邮箱已被占用" }; } else { throw { username: "用户名已被占用" }; } } else { if (validataEmail) { throw { email: "邮箱已被占用" }; } validataUsername = false; } }); } if (field == "email") { await axios.post("/vaildateEmail", values).then(function(response) { if (!response.data.success) { validataEmail = true; console.log(validataUsername, validataEmail); if (validataUsername && validataEmail) { throw { username: "用户名已被占用", email: "邮箱已被占用" }; } else { throw { email: "邮箱已被占用" }; } } else { if (validataUsername) { throw { username: "用户名已被占用" }; } validataEmail = false; } }); } }; const submit = async function submit(values) { let _this = this; console.log(111); await axios.post("/regUser", values).then(function(response) { console.log(response); if (!response.data.success) { throw new SubmissionError({ _error: response.data.message }); } else { _this.props.history.push("/login"); } }); }; const validate = values => { const errors = {}; if (!values.username) { errors.username = "必填"; } else if (values.username.length > 15) { errors.username = "不能大于15个字符"; } else if (values.username.length < 5) { errors.username = "不能小于5个字符"; } if (!values.password) { errors.password = "必填"; } else if (values.password.length > 30) { errors.password = "不能大于30位密码"; } else if (values.password.length < 5) { errors.password = "不能小于5位密码"; } if (!values.repassword) { errors.repassword = "必填"; } else if (values.password != values.repassword) { errors.repassword = "两次密码不同"; } if (!values.email) { errors.email = "必填"; } else if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(values.email)) { errors.email = "邮箱格式不正确"; } return errors; }; const renderField = ({ input, label, type, meta: { touched, error } }) => ( <div> <input {...input} placeholder={label} type={type} />{" "} {touched && (error && <span className="error">{error}</span>)} </div> ); renderField.propTypes = { meta: PropTypes.object, type: PropTypes.string, label: PropTypes.string, input: PropTypes.object }; class RegForm extends Component { constructor(props) { super(props); } render() { const { error, handleSubmit } = this.props; return ( <form onSubmit={handleSubmit(submit.bind(this))} className="reg-form"> <div className={error ? "tips-show" : "tips"}>{error}</div> <ul className="form"> <li> <b>注册账户</b> </li> <li className="form-border"> <Field component={renderField} label="用户名" name="username" type="text" /> </li> <li className="form-bordre"> <Field component={renderField} label="密码" name="password" type="password" /> </li> <li className="form-border"> <Field component={renderField} label="重复密码" name="repassword" type="password" /> </li> <li className="form-border"> <Field component={renderField} label="邮箱" name="email" type="text" /> </li> <li className=""> <p>请输入下列验证码</p> </li> <li className="form-border"> <Field component={renderField} name="captcha" placeholder="验证码" type="text" /> </li> <li className="form-top"> <button className="form-submit" type="submit"> 注册 </button> </li> </ul> </form> ); } } RegForm.propTypes = { error: PropTypes.object, handleSubmit: PropTypes.func }; export default connect( null, actions )( reduxForm({ form: "reg_form", validate, asyncValidate, asyncBlurFields: ["username", "email"] })(RegForm) ); <|start_filename|>client/src/view/components/nav/index.js<|end_filename|> import React, { Component } from "react"; import { Link } from "react-router-dom"; import PropTypes from "prop-types"; import { connect } from "react-redux"; import "./index.css"; class Nav extends Component { constructor(props) { super(props); } render() { let logined = this.props.user.logined; return ( <header className="main-header"> <ul className="nav"> <li className="fl"> <Link to="/">首 页</Link> </li> <li className="fl"> <Link to="/notFound">发现</Link> </li> {logined ? ( <li className="avatar"> {/* <img src={defaultAvatar} /> */} <dl> <Link to="/">我的主页</Link> <Link to="/logout">退出</Link> </dl> </li> ) : ( <li className="fr"> <Link to="/reg"> <b>注 册</b> </Link> <Link to="/login">登 录</Link> </li> )} </ul> </header> ); } } Nav.propTypes = { user: PropTypes.object }; function user(state) { return { user: state.user }; } export default connect(user)(Nav); <|start_filename|>client/src/view/containers/logout/logout.js<|end_filename|> import React, { Component } from "react"; import { connect } from "react-redux"; import axios from "axios"; import * as actions from "../../../redux/actions/index"; import Nav from "../../components/nav/index.js"; class App extends Component { componentDidMount() { let _this = this; axios .get("/logout") .then(function(response) { if (response.data.success) { _this.props.logout(); _this.props.history.push("/"); } }) .catch(function(error) { _this.props.logout(); _this.props.history.push("/"); console.log(error); }); } render() { return ( <div> <Nav /> <div> <p>正在退出登录...</p> </div> </div> ); } } export default connect( null, actions )(App); <|start_filename|>client/src/dist/css/home.css<|end_filename|> body { background: #fff; } .banner { height: 300px; border-bottom: 1px solid #eee; color: #626262; p { text-align: center; } } .banner_text { padding: 30px 0; } .logo_en { text-align: center; padding-top: 80px; } .upload_btn { border: 1px solid #c9c9c9; width: 110px; background: #ffffff; height: 35px; line-height: 35px; color: #727272; cursor: pointer; border-radius: 5px; outline: none; font-size: 12px; margin-top: 5px; &:hover { background:#000; color:#fff; border: 1px solid #000; } } <|start_filename|>server/view/layout.js<|end_filename|> import common from '../../common.json'; exports.layout = function(content, data) { return ` <!DOCTYPE html> <html> <head> <meta charSet='utf-8'/> <meta httpEquiv='X-UA-Compatible' content='IE=edge'/> <meta name='renderer' content='webkit'/> <meta name='keywords' content='demo'/> <meta name='description' content='demo'/> <meta name='viewport' content='width=device-width, initial-scale=1'/> <link rel="stylesheet" href="/dist/css/style.css"> </head> <body> <div id="root"><div>${content}</div></div> <script> window.__REDUX_DATA__ = ${JSON.stringify(data)}; </script> <script src="${common.publicPath}dist/js/manifest.js"></script> <script src="${common.publicPath}dist/js/vendor.js"></script> <script src="${common.publicPath}dist/js/index.js"></script> </body> </html> `; }; <|start_filename|>client/src/routes.js<|end_filename|> import React, { Component } from "react"; import { BrowserRouter as Router, Route, Switch } from "react-router-dom"; import HomePage from "./view/homePage.js"; import Reg from "./view/containers/reg/index.js"; import Login from "./view/containers/login/index.js"; import Logout from "./view/containers/logout/logout.js"; import NotFound from "./view/containers/notFound/index.js"; export default class routes extends Component { render() { return ( <Router> <Switch> <Route path="/" exact component={HomePage} /> <Route path="/login" component={Login} /> <Route path="/reg" component={Reg} /> <Route path="/logout" component={Logout} /> <Route component={NotFound} /> </Switch> </Router> ); } } // export default ( // <Router > // <div> // <Switch> // <Route path="/" exact component={Home}/> // <Route path="/user" component={User}/> // <Route path="/login" component={Login}/> // <Route path="/reg" component={Reg}/> // <Route path="/logout" component={Logout}/> // <Route component={PagenotFound}/> // </Switch> // </div> // </Router> // ) <|start_filename|>client/src/redux/reducers/index.js<|end_filename|> import { combineReducers } from "redux"; // import counter from './counter'; import userReducer from "./user_reducer"; //load redux-form plugin import { reducer as formReducer } from "redux-form"; export default combineReducers({ user: userReducer, form: formReducer }); <|start_filename|>client/src/view/reset.css<|end_filename|> html { -webkit-text-size-adjust: 100%; -ms-text-size-adjust: 100%; background-color: #f4f5f5; } body, div, dl, dt, dd, ul, ol, li, h1, h2, h3, h4, h5, h6, pre, code, form, fieldset, legend, input, textarea, p, blockquote, th, td, hr, button, article, aside, details, figcaption, figure, footer, header, hgroup, menu, nav, section { margin: 0; padding: 0; } article, aside, details, figcaption, figure, footer, header, hgroup, menu, nav, section { display: block; } audio, canvas, video { display: inline-block; *display: inline; *zoom: 1; } body, button, input, select, textarea { font: 12px/1.5 "Source Sans Pro", -apple-system, BlinkMacSystemFont, "PingFang SC", "Helvetica Neue", STHeiti, "Microsoft Yahei", Tahoma, Simsun, sans-serif; font-weight: 200; } input, select, textarea { font-size: 100%; } table { border-collapse: collapse; border-spacing: 0; } th { text-align: inherit; } fieldset, img { border: 0; } iframe { display: block; } abbr, acronym { border: 0; font-variant: normal; } del { text-decoration: line-through; } address, caption, cite, code, dfn, em, th, var { font-style: normal; font-weight: 500; } ol, ul { list-style: none; } /* 对齐是排版最重要的因素, 别让什么都居中 */ caption, th { text-align: left; } h1, h2, h3, h4, h5, h6 { font-size: 100%; font-weight: 500; } q:before, q:after { content: ""; } sub, sup { font-size: 75%; line-height: 0; position: relative; vertical-align: baseline; } sup { top: -0.5em; } sub { bottom: -0.25em; } a:hover { /*text-decoration: underline;*/ } ins, a { text-decoration: none; } <|start_filename|>client/src/redux/store/index.js<|end_filename|> import configureStore from "./configureStore"; const store = configureStore(window.__REDUX_DATA__); export default store; <|start_filename|>client/src/view/homePage.css<|end_filename|> .main-container { position: relative; margin: 0 auto; width: 100%; max-width: 960px; } .view { margin-top: 1.7rem; display: flex; } .welcome-feed { background: #fff; overflow: hidden; -webkit-box-flex: 1; -ms-flex-positive: 1; flex-grow: 1; } .welcome-side { background: #fff; width: 240px; min-width: 240px; margin-left: 20px; display: block; } .category-nav { background-color: #fff; padding: 1.5rem 2rem; display: flex; -webkit-box-pack: justify; -ms-flex-pack: justify; justify-content: space-between; border-bottom: 1px solid #f6f6f6; } .nav-list { display: flex; align-items: baseline; } .nav-item { position: relative; cursor: pointer; font-size: 14px; } li.nav-item.route-active { color: #007fff; } li.nav-item:not(:last-child) { margin-right: 20px; } .category-nav .nav-list li.nav-item.route-active { color: #007fff; } .section { background-color: #fff; border-radius: 2px; margin-bottom: 1.5rem; overflow: hidden; padding: 1.333rem; } .section .title { font-weight: 600; margin-bottom: 0.5rem; font-size: 1.167rem; color: #2e3135; } .ticket { font-size: 14px; color: #8f969c; margin-bottom: 1rem; } .input-box { position: relative; margin-bottom: 0.833rem; } .input { padding: 0.5rem 0.6rem; width: 100%; background-color: #fbfbfb; border: 1px solid #f4f4f4; border-radius: 2px; outline: none; box-sizing: border-box; } .submit-btn { padding: 0.7rem 0; width: 100%; font-size: 1.167rem; border-radius: 2px; appearance: none; background-color: #007fff; color: #fff; border-radius: 2px; border: none; padding: 0.5rem 1.3rem; outline: none; transition: background-color 0.3s, color 0.3s; cursor: pointer; border: none; padding: 0.5rem 1.3rem; outline: none; transition: background-color 0.3s, color 0.3s; cursor: pointer; } .submit-btn:hover { background-color: #0371df; color: #fff; } <|start_filename|>client/src/view/containers/notFound/index.css<|end_filename|> .wrapper { text-align: center; padding-top: 38px; line-height: 2em; font-size: 12px; img { margin-bottom: 30px; } } <|start_filename|>client/src/view/homePage.js<|end_filename|> import React, { Component } from "react"; import Nav from "./components/nav/index.js"; import axios from "axios"; import "./homePage.css"; import "./reset.css"; class App extends Component { componentDidMount() { axios.post("/rest/v1/getList").then(res => { console.log(res); }); } render() { return ( <React.Fragment> <Nav /> <main className="main-container"> <div className="view"> <div className="welcome-feed"> <nav className="category-nav"> <h5>热门文章</h5> <ul className="nav-list"> <li className="nav-item router-link-exact-active"> <span className="title">推荐</span> </li> <li className="nav-item router-link-exact-active"> <span className="title">前端</span> </li> <li className="nav-item router-link-exact-active"> <span className="title">Android</span> </li> <li className="nav-item router-link-exact-active"> <span className="title">后端</span> </li> <li className="nav-item router-link-exact-active"> <span className="title">人工智能</span> </li> <li className="nav-item router-link-exact-active"> <span className="title">IOS</span> </li> <li className="nav-item router-link-exact-active"> <span className="title">工具资源</span> </li> <li className="nav-item router-link-exact-active"> <span className="title">阅读</span> </li> <li className="nav-item router-link-exact-active"> <span className="title">运维</span> </li> </ul> </nav> <ul> <li> <a href="">接下来自己倒腾吧</a> </li> </ul> </div> <aside className="welcome-side"> <section className="shadow section auth-section"> <div className="title">掘金 - juejin.im</div> <div className="slogan">一个帮助开发者成长的社区</div> <div className="ticket"> 现在注册,送你 <a href="/books" className="highlight"> 45元 </a> 买小册 </div> <div className="input-group"> <div className="input-box"> <input maxLength="20" placeholder="用户名" className="input" /> </div> <div className="input-box"> <input maxLength="64" placeholder="手机号" className="input" /> </div> <div className="input-box"> <input name="registerPassword" type="password" maxLength="64" placeholder="密码(不少于 6 位)" className="input" /> </div> </div> <button className="btn submit-btn">立即注册</button> </section> </aside> </div> </main> </React.Fragment> ); } } export default App; <|start_filename|>client/src/mock/mock.js<|end_filename|> import Mock from 'mockjs'; Mock.mock('/rest/v1/getList', { 'success': true, 'status': 200, 'message': '!!!!', 'data': {} }); Mock.mock('/rest/v1/login', { 'success': true, 'status': 200, 'message': '登录失败!', 'data': {} }); Mock.mock('/vaildateUser', { 'success': true, 'status': 200, 'message': '用户名有重复!', 'data': {} }); Mock.mock('/vaildateEmail', { 'success': true, 'status': 200, 'message': '邮箱已被占用!', 'data': {} }); Mock.mock('/regUser', { 'success': true, 'status': 200, 'message': '注册失败!', 'data': {} });
shawn-yee/react-ssr
<|start_filename|>docs/1.6/book/mutability.html<|end_filename|> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="generator" content="rustdoc"> <title>ミュータビリティ</title> <link rel="stylesheet" type="text/css" href="rustbook.css"> <meta name="robots" content="noindex"> </head> <body class="rustdoc"> <!--[if lte IE 8]> <div class="warning"> This old browser is unsupported and will most likely display funky things. </div> <![endif]--> <div id="nav"> <button id="toggle-nav"> <span class="sr-only">Toggle navigation</span> <span class="bar"></span> <span class="bar"></span> <span class="bar"></span> </button> </div> <div id='toc' class='mobile-hidden'> <ul class='chapter'> <li><a href='README.html'><b>1.</b> Introduction</a> </li> <li><a href='getting-started.html'><b>2.</b> はじめる</a> </li> <li><a href='learn-rust.html'><b>3.</b> Rustを学ぶ</a> <ul class='section'> <li><a href='guessing-game.html'><b>3.1.</b> 数当てゲーム</a> </li> <li><a href='dining-philosophers.html'><b>3.2.</b> 食事する哲学者</a> </li> <li><a href='rust-inside-other-languages.html'><b>3.3.</b> 他言語と共存する</a> </li> </ul> </li> <li><a href='syntax-and-semantics.html'><b>4.</b> シンタックスとセマンティクス</a> <ul class='section'> <li><a href='variable-bindings.html'><b>4.1.</b> 変数束縛</a> </li> <li><a href='functions.html'><b>4.2.</b> 関数</a> </li> <li><a href='primitive-types.html'><b>4.3.</b> プリミティブ型</a> </li> <li><a href='comments.html'><b>4.4.</b> コメント</a> </li> <li><a href='if.html'><b>4.5.</b> if</a> </li> <li><a href='loops.html'><b>4.6.</b> ループ</a> </li> <li><a href='ownership.html'><b>4.7.</b> 所有権</a> </li> <li><a href='references-and-borrowing.html'><b>4.8.</b> 参照と借用</a> </li> <li><a href='lifetimes.html'><b>4.9.</b> ライフタイム</a> </li> <li><a class='active' href='mutability.html'><b>4.10.</b> ミュータビリティ</a> </li> <li><a href='structs.html'><b>4.11.</b> 構造体</a> </li> <li><a href='enums.html'><b>4.12.</b> 列挙型</a> </li> <li><a href='match.html'><b>4.13.</b> マッチ</a> </li> <li><a href='patterns.html'><b>4.14.</b> パターン</a> </li> <li><a href='method-syntax.html'><b>4.15.</b> メソッド構文</a> </li> <li><a href='vectors.html'><b>4.16.</b> ベクタ</a> </li> <li><a href='strings.html'><b>4.17.</b> 文字列</a> </li> <li><a href='generics.html'><b>4.18.</b> ジェネリクス</a> </li> <li><a href='traits.html'><b>4.19.</b> トレイト</a> </li> <li><a href='drop.html'><b>4.20.</b> Drop</a> </li> <li><a href='if-let.html'><b>4.21.</b> if let</a> </li> <li><a href='trait-objects.html'><b>4.22.</b> トレイトオブジェクト</a> </li> <li><a href='closures.html'><b>4.23.</b> クロージャ</a> </li> <li><a href='ufcs.html'><b>4.24.</b> 共通の関数呼出構文</a> </li> <li><a href='crates-and-modules.html'><b>4.25.</b> クレートとモジュール</a> </li> <li><a href='const-and-static.html'><b>4.26.</b> `const` と `static`</a> </li> <li><a href='attributes.html'><b>4.27.</b> アトリビュート</a> </li> <li><a href='type-aliases.html'><b>4.28.</b> `type` エイリアス</a> </li> <li><a href='casting-between-types.html'><b>4.29.</b> 型間のキャスト</a> </li> <li><a href='associated-types.html'><b>4.30.</b> 関連型</a> </li> <li><a href='unsized-types.html'><b>4.31.</b> サイズ不定型</a> </li> <li><a href='operators-and-overloading.html'><b>4.32.</b> 演算子とオーバーロード</a> </li> <li><a href='deref-coercions.html'><b>4.33.</b> Derefによる型強制</a> </li> <li><a href='macros.html'><b>4.34.</b> マクロ</a> </li> <li><a href='raw-pointers.html'><b>4.35.</b> 生ポインタ</a> </li> <li><a href='unsafe.html'><b>4.36.</b> `unsafe`</a> </li> </ul> </li> <li><a href='effective-rust.html'><b>5.</b> Effective Rust</a> <ul class='section'> <li><a href='the-stack-and-the-heap.html'><b>5.1.</b> スタックとヒープ</a> </li> <li><a href='testing.html'><b>5.2.</b> テスト</a> </li> <li><a href='conditional-compilation.html'><b>5.3.</b> 条件付きコンパイル</a> </li> <li><a href='documentation.html'><b>5.4.</b> ドキュメント</a> </li> <li><a href='iterators.html'><b>5.5.</b> イテレータ</a> </li> <li><a href='concurrency.html'><b>5.6.</b> 並行性</a> </li> <li><a href='error-handling.html'><b>5.7.</b> エラーハンドリング</a> </li> <li><a href='choosing-your-guarantees.html'><b>5.8.</b> 保証を選ぶ</a> </li> <li><a href='ffi.html'><b>5.9.</b> 他言語関数インターフェース</a> </li> <li><a href='borrow-and-asref.html'><b>5.10.</b> BorrowとAsRef</a> </li> <li><a href='release-channels.html'><b>5.11.</b> リリースチャネル</a> </li> <li><a href='using-rust-without-the-standard-library.html'><b>5.12.</b> 標準ライブラリ無しでRustを使う</a> </li> </ul> </li> <li><a href='nightly-rust.html'><b>6.</b> Nightly Rust</a> <ul class='section'> <li><a href='compiler-plugins.html'><b>6.1.</b> コンパイラプラグイン</a> </li> <li><a href='inline-assembly.html'><b>6.2.</b> インラインアセンブリ</a> </li> <li><a href='no-stdlib.html'><b>6.3.</b> No stdlib</a> </li> <li><a href='intrinsics.html'><b>6.4.</b> Intrinsic</a> </li> <li><a href='lang-items.html'><b>6.5.</b> 言語アイテム</a> </li> <li><a href='advanced-linking.html'><b>6.6.</b> 高度なリンキング</a> </li> <li><a href='benchmark-tests.html'><b>6.7.</b> ベンチマークテスト</a> </li> <li><a href='box-syntax-and-patterns.html'><b>6.8.</b> Box構文とパターン</a> </li> <li><a href='slice-patterns.html'><b>6.9.</b> スライスパターン</a> </li> <li><a href='associated-constants.html'><b>6.10.</b> 関連定数</a> </li> <li><a href='custom-allocators.html'><b>6.11.</b> カスタムアロケータ</a> </li> </ul> </li> <li><a href='glossary.html'><b>7.</b> 用語集</a> </li> <li><a href='syntax-index.html'><b>8.</b> 構文の索引</a> </li> <li><a href='bibliography.html'><b>9.</b> 関係書目</a> </li> </ul> </div> <div id='page-wrapper'> <div id='page'> <blockquote class="header-caveat"> <p> <strong>注意: <a href="https://doc.rust-jp.rs/book-ja/">最新版のドキュメントをご覧ください。</a></strong>この第1版ドキュメントは古くなっており、最新情報が反映されていません。リンク先のドキュメントが現在の Rust の最新のドキュメントです。 </p> </blockquote> <h1 class="title">ミュータビリティ</h1> <!-- % Mutability --> <!-- Mutability, the ability to change something, works a bit differently in Rust --> <!-- than in other languages. The first aspect of mutability is its non-default --> <!-- status: --> <p>Rustにおけるミュータビリティ、何かを変更する能力は、他のプログラミング言語とはすこし異なっています。 ミュータビリティの一つ目の特徴は、それがデフォルトでは無いという点です:</p> <span class='rusttest'>fn main() { let x = 5; // x = 6; // error! x = 6; // エラー! }</span><pre class='rust rust-example-rendered'> <span class='kw'>let</span> <span class='ident'>x</span> <span class='op'>=</span> <span class='number'>5</span>; <span class='ident'>x</span> <span class='op'>=</span> <span class='number'>6</span>; <span class='comment'>// エラー!</span></pre> <!-- We can introduce mutability with the `mut` keyword: --> <p><code>mut</code> キーワードによりミュータビリティを導入できます:</p> <span class='rusttest'>fn main() { let mut x = 5; // x = 6; // no problem! x = 6; // 問題なし! }</span><pre class='rust rust-example-rendered'> <span class='kw'>let</span> <span class='kw-2'>mut</span> <span class='ident'>x</span> <span class='op'>=</span> <span class='number'>5</span>; <span class='ident'>x</span> <span class='op'>=</span> <span class='number'>6</span>; <span class='comment'>// 問題なし!</span></pre> <!-- This is a mutable [variable binding][vb]. When a binding is mutable, it means --> <!-- you’re allowed to change what the binding points to. So in the above example, --> <!-- it’s not so much that the value at `x` is changing, but that the binding --> <!-- changed from one `i32` to another. --> <p>これはミュータブルな <a href="variable-bindings.html">変数束縛</a> です。束縛がミュータブルであるとき、その束縛が何を指すかを変更して良いことを意味します。 つまり上記の例では、<code>x</code> の値を変更したのではなく、ある <code>i32</code> から別の値へと束縛が変わったのです。</p> <!-- If you want to change what the binding points to, you’ll need a [mutable reference][mr]: --> <p>束縛が指す先を変更する場合は、<a href="references-and-borrowing.html">ミュータブル参照</a> を使う必要があるでしょう:</p> <span class='rusttest'>fn main() { let mut x = 5; let y = &amp;mut x; }</span><pre class='rust rust-example-rendered'> <span class='kw'>let</span> <span class='kw-2'>mut</span> <span class='ident'>x</span> <span class='op'>=</span> <span class='number'>5</span>; <span class='kw'>let</span> <span class='ident'>y</span> <span class='op'>=</span> <span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='ident'>x</span>;</pre> <!-- `y` is an immutable binding to a mutable reference, which means that you can’t --> <!-- bind `y` to something else (`y = &mut z`), but you can mutate the thing that’s --> <!-- bound to `y` (`*y = 5`). A subtle distinction. --> <p><code>y</code> はミュータブル参照へのイミュータブルな束縛であり、 <code>y</code> を他の束縛に変える(<code>y = &amp;mut z</code>)ことはできません。 しかし、<code>y</code> に束縛されているものを変化させること(<code>*y = 5</code>)は可能です。微妙な区別です。</p> <!-- Of course, if you need both: --> <p>もちろん、両方が必要ならば:</p> <span class='rusttest'>fn main() { let mut x = 5; let mut y = &amp;mut x; }</span><pre class='rust rust-example-rendered'> <span class='kw'>let</span> <span class='kw-2'>mut</span> <span class='ident'>x</span> <span class='op'>=</span> <span class='number'>5</span>; <span class='kw'>let</span> <span class='kw-2'>mut</span> <span class='ident'>y</span> <span class='op'>=</span> <span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='ident'>x</span>;</pre> <!-- Now `y` can be bound to another value, and the value it’s referencing can be --> <!-- changed. --> <p>今度は <code>y</code> が他の値を束縛することもできますし、参照している値を変更することもできます。</p> <!-- It’s important to note that `mut` is part of a [pattern][pattern], so you --> <!-- can do things like this: --> <p><code>mut</code> は <a href="patterns.html">パターン</a> の一部を成すことに十分注意してください。 つまり、次のようなことが可能です:</p> <span class='rusttest'>fn main() { let (mut x, y) = (5, 6); fn foo(mut x: i32) { } }</span><pre class='rust rust-example-rendered'> <span class='kw'>let</span> (<span class='kw-2'>mut</span> <span class='ident'>x</span>, <span class='ident'>y</span>) <span class='op'>=</span> (<span class='number'>5</span>, <span class='number'>6</span>); <span class='kw'>fn</span> <span class='ident'>foo</span>(<span class='kw-2'>mut</span> <span class='ident'>x</span>: <span class='ident'>i32</span>) {</pre> <!-- # Interior vs. Exterior Mutability --> <h1 id='内側-vs-外側のミュータビリティ' class='section-header'><a href='#内側-vs-外側のミュータビリティ'>内側 vs. 外側のミュータビリティ</a></h1> <!-- However, when we say something is ‘immutable’ in Rust, that doesn’t mean that --> <!-- it’s not able to be changed: we mean something has ‘exterior mutability’. Consider, --> <!-- for example, [`Arc<T>`][arc]: --> <p>一方で、Rustで「イミュータブル(immutable)」について言及するとき、変更不可能であることを意味しない: 「外側のミュータビリティ(exterior mutability)」を表します。例として、<a href="../std/sync/struct.Arc.html"><code>Arc&lt;T&gt;</code></a> を考えます:</p> <span class='rusttest'>fn main() { use std::sync::Arc; let x = Arc::new(5); let y = x.clone(); }</span><pre class='rust rust-example-rendered'> <span class='kw'>use</span> <span class='ident'>std</span>::<span class='ident'>sync</span>::<span class='ident'>Arc</span>; <span class='kw'>let</span> <span class='ident'>x</span> <span class='op'>=</span> <span class='ident'>Arc</span>::<span class='ident'>new</span>(<span class='number'>5</span>); <span class='kw'>let</span> <span class='ident'>y</span> <span class='op'>=</span> <span class='ident'>x</span>.<span class='ident'>clone</span>();</pre> <!-- When we call `clone()`, the `Arc<T>` needs to update the reference count. Yet --> <!-- we’ve not used any `mut`s here, `x` is an immutable binding, and we didn’t take --> <!-- `&mut 5` or anything. So what gives? --> <p><code>clone()</code> を呼び出すとき、<code>Arc&lt;T&gt;</code> は参照カウントを更新する必要があります。しかし、 ここでは <code>mut</code> を一切使っていません。つまり <code>x</code> はイミュータブルな束縛であり、 <code>&amp;mut 5</code> のような引数もとりません。一体どうなっているの?</p> <!-- To understand this, we have to go back to the core of Rust’s guiding --> <!-- philosophy, memory safety, and the mechanism by which Rust guarantees it, the --> <!-- [ownership][ownership] system, and more specifically, [borrowing][borrowing]: --> <p>これを理解するには、Rust言語の設計哲学の中心をなすメモリ安全性と、Rustがそれを保証するメカニズムである <a href="ownership.html">所有権</a> システム、 特に <a href="references-and-borrowing.html#borrowing">借用</a> に立ち返る必要があります。</p> <!-- > You may have one or the other of these two kinds of borrows, but not both at --> <!-- > the same time: --> <!-- > --> <!-- > * one or more references (`&T`) to a resource, --> <!-- > * exactly one mutable reference (`&mut T`). --> <blockquote> <p>次の2種類の借用のどちらか1つを持つことはありますが、両方を同時に持つことはありません。</p> <ul> <li>リソースに対する1つ以上の参照(<code>&amp;T</code>)</li> <li>ただ1つのミュータブルな参照(<code>&amp;mut T</code>)</li> </ul> </blockquote> <!-- So, that’s the real definition of ‘immutability’: is this safe to have two --> <!-- pointers to? In `Arc<T>`’s case, yes: the mutation is entirely contained inside --> <!-- the structure itself. It’s not user facing. For this reason, it hands out `&T` --> <!-- with `clone()`. If it handed out `&mut T`s, though, that would be a problem. --> <p>つまり、「イミュータビリティ」の真の定義はこうです: これは2箇所から指されても安全ですか? <code>Arc&lt;T&gt;</code> の例では、イエス: 変更は完全にそれ自身の構造の内側で行われます。ユーザからは見えません。 このような理由により、 <code>clone()</code> を用いて <code>&amp;T</code> を配るのです。仮に <code>&amp;mut T</code> を配ってしまうと、 問題になるでしょう。 (訳注: <code>Arc&lt;T&gt;</code>を用いて複数スレッドにイミュータブル参照を配布し、スレッド間でオブジェクトを共有できます。)</p> <!-- Other types, like the ones in the [`std::cell`][stdcell] module, have the --> <!-- opposite: interior mutability. For example: --> <p><a href="../std/cell/index.html"><code>std::cell</code></a> モジュールにあるような別の型では、反対の性質: 内側のミュータビリティ(interior mutability)を持ちます。 例えば:</p> <span class='rusttest'>fn main() { use std::cell::RefCell; let x = RefCell::new(42); let y = x.borrow_mut(); }</span><pre class='rust rust-example-rendered'> <span class='kw'>use</span> <span class='ident'>std</span>::<span class='ident'>cell</span>::<span class='ident'>RefCell</span>; <span class='kw'>let</span> <span class='ident'>x</span> <span class='op'>=</span> <span class='ident'>RefCell</span>::<span class='ident'>new</span>(<span class='number'>42</span>); <span class='kw'>let</span> <span class='ident'>y</span> <span class='op'>=</span> <span class='ident'>x</span>.<span class='ident'>borrow_mut</span>();</pre> <!-- RefCell hands out `&mut` references to what’s inside of it with the --> <!-- `borrow_mut()` method. Isn’t that dangerous? What if we do: --> <p>RefCellでは <code>borrow_mut()</code> メソッドによって、その内側にある値への <code>&amp;mut</code> 参照を配ります。 それって危ないのでは? もし次のようにすると:</p> <span class='rusttest'>fn main() { use std::cell::RefCell; let x = RefCell::new(42); let y = x.borrow_mut(); let z = x.borrow_mut(); (y, z); }</span><pre class='rust rust-example-rendered'> <span class='kw'>use</span> <span class='ident'>std</span>::<span class='ident'>cell</span>::<span class='ident'>RefCell</span>; <span class='kw'>let</span> <span class='ident'>x</span> <span class='op'>=</span> <span class='ident'>RefCell</span>::<span class='ident'>new</span>(<span class='number'>42</span>); <span class='kw'>let</span> <span class='ident'>y</span> <span class='op'>=</span> <span class='ident'>x</span>.<span class='ident'>borrow_mut</span>(); <span class='kw'>let</span> <span class='ident'>z</span> <span class='op'>=</span> <span class='ident'>x</span>.<span class='ident'>borrow_mut</span>();</pre> <!-- This will in fact panic, at runtime. This is what `RefCell` does: it enforces --> <!-- Rust’s borrowing rules at runtime, and `panic!`s if they’re violated. This --> <!-- allows us to get around another aspect of Rust’s mutability rules. Let’s talk --> <!-- about it first. --> <p>実際に、このコードは実行時にパニックするでしょう。これが <code>RefCell</code> が行うことです: Rustの借用ルールを実行時に強制し、違反したときには <code>panic!</code> を呼び出します。 これによりRustのミュータビリティ・ルールのもう一つの特徴を回避できるようになります。 最初に見ていきましょう。</p> <!-- ## Field-level mutability --> <h2 id='フィールドレベルのミュータビリティ' class='section-header'><a href='#フィールドレベルのミュータビリティ'>フィールド・レベルのミュータビリティ</a></h2> <!-- Mutability is a property of either a borrow (`&mut`) or a binding (`let mut`). --> <!-- This means that, for example, you cannot have a [`struct`][struct] with --> <!-- some fields mutable and some immutable: --> <p>ミュータビリティとは、借用(<code>&amp;mut</code>)や束縛(<code>let mut</code>)に関する属性です。これが意味するのは、 例えば、一部がミュータブルで一部がイミュータブルなフィールドを持つ <a href="structs.html"><code>struct</code></a> は作れないということです。</p> <span class='rusttest'>fn main() { struct Point { x: i32, // mut y: i32, // nope mut y: i32, // ダメ } }</span><pre class='rust rust-example-rendered'> <span class='kw'>struct</span> <span class='ident'>Point</span> { <span class='ident'>x</span>: <span class='ident'>i32</span>, <span class='kw-2'>mut</span> <span class='ident'>y</span>: <span class='ident'>i32</span>, <span class='comment'>// ダメ</span> }</pre> <!-- The mutability of a struct is in its binding: --> <p>構造体のミュータビリティは、それへの束縛の一部です。</p> <span class='rusttest'>fn main() { struct Point { x: i32, y: i32, } let mut a = Point { x: 5, y: 6 }; a.x = 10; let b = Point { x: 5, y: 6}; // b.x = 10; // error: cannot assign to immutable field `b.x` b.x = 10; // エラー: イミュータブルなフィールド `b.x` へ代入できない }</span><pre class='rust rust-example-rendered'> <span class='kw'>struct</span> <span class='ident'>Point</span> { <span class='ident'>x</span>: <span class='ident'>i32</span>, <span class='ident'>y</span>: <span class='ident'>i32</span>, } <span class='kw'>let</span> <span class='kw-2'>mut</span> <span class='ident'>a</span> <span class='op'>=</span> <span class='ident'>Point</span> { <span class='ident'>x</span>: <span class='number'>5</span>, <span class='ident'>y</span>: <span class='number'>6</span> }; <span class='ident'>a</span>.<span class='ident'>x</span> <span class='op'>=</span> <span class='number'>10</span>; <span class='kw'>let</span> <span class='ident'>b</span> <span class='op'>=</span> <span class='ident'>Point</span> { <span class='ident'>x</span>: <span class='number'>5</span>, <span class='ident'>y</span>: <span class='number'>6</span>}; <span class='ident'>b</span>.<span class='ident'>x</span> <span class='op'>=</span> <span class='number'>10</span>; <span class='comment'>// エラー: イミュータブルなフィールド `b.x` へ代入できない</span></pre> <!-- However, by using [`Cell<T>`][cell], you can emulate field-level mutability: --> <p>しかし、<a href="../std/cell/struct.Cell.html"><code>Cell&lt;T&gt;</code></a> を使えば、フィールド・レベルのミュータビリティをエミュレートできます。</p> <span class='rusttest'>fn main() { use std::cell::Cell; struct Point { x: i32, y: Cell&lt;i32&gt;, } let point = Point { x: 5, y: Cell::new(6) }; point.y.set(7); println!(&quot;y: {:?}&quot;, point.y); }</span><pre class='rust rust-example-rendered'> <span class='kw'>use</span> <span class='ident'>std</span>::<span class='ident'>cell</span>::<span class='ident'>Cell</span>; <span class='kw'>struct</span> <span class='ident'>Point</span> { <span class='ident'>x</span>: <span class='ident'>i32</span>, <span class='ident'>y</span>: <span class='ident'>Cell</span><span class='op'>&lt;</span><span class='ident'>i32</span><span class='op'>&gt;</span>, } <span class='kw'>let</span> <span class='ident'>point</span> <span class='op'>=</span> <span class='ident'>Point</span> { <span class='ident'>x</span>: <span class='number'>5</span>, <span class='ident'>y</span>: <span class='ident'>Cell</span>::<span class='ident'>new</span>(<span class='number'>6</span>) }; <span class='ident'>point</span>.<span class='ident'>y</span>.<span class='ident'>set</span>(<span class='number'>7</span>); <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;y: {:?}&quot;</span>, <span class='ident'>point</span>.<span class='ident'>y</span>);</pre> <!-- This will print `y: Cell { value: 7 }`. We’ve successfully updated `y`. --> <p>このコードは <code>y: Cell { value: 7 }</code> と表示するでしょう。ちゃんと <code>y</code> を更新できました。</p> <script type="text/javascript"> window.playgroundUrl = "https://play.rust-lang.org"; </script> <script src='rustbook.js'></script> <script src='playpen.js'></script> </div></div> </body> </html> <|start_filename|>docs/1.9/book/const-and-static.html<|end_filename|> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="generator" content="rustdoc"> <title>`const` と `static`</title> <link rel="stylesheet" type="text/css" href="rustbook.css"> <meta name="robots" content="noindex"> </head> <body class="rustdoc"> <!--[if lte IE 8]> <div class="warning"> This old browser is unsupported and will most likely display funky things. </div> <![endif]--> <div id="nav"> <button id="toggle-nav"> <span class="sr-only">Toggle navigation</span> <span class="bar"></span> <span class="bar"></span> <span class="bar"></span> </button> </div> <div id='toc' class='mobile-hidden'> <ul class='chapter'> <li><a href='README.html'><b>1.</b> Introduction</a> </li> <li><a href='getting-started.html'><b>2.</b> はじめる</a> </li> <li><a href='guessing-game.html'><b>3.</b> チュートリアル:数当てゲーム</a> </li> <li><a href='syntax-and-semantics.html'><b>4.</b> シンタックスとセマンティクス</a> <ul class='section'> <li><a href='variable-bindings.html'><b>4.1.</b> 変数束縛</a> </li> <li><a href='functions.html'><b>4.2.</b> 関数</a> </li> <li><a href='primitive-types.html'><b>4.3.</b> プリミティブ型</a> </li> <li><a href='comments.html'><b>4.4.</b> コメント</a> </li> <li><a href='if.html'><b>4.5.</b> if</a> </li> <li><a href='loops.html'><b>4.6.</b> ループ</a> </li> <li><a href='vectors.html'><b>4.7.</b> ベクタ</a> </li> <li><a href='ownership.html'><b>4.8.</b> 所有権</a> </li> <li><a href='references-and-borrowing.html'><b>4.9.</b> 参照と借用</a> </li> <li><a href='lifetimes.html'><b>4.10.</b> ライフタイム</a> </li> <li><a href='mutability.html'><b>4.11.</b> ミュータビリティ</a> </li> <li><a href='structs.html'><b>4.12.</b> 構造体</a> </li> <li><a href='enums.html'><b>4.13.</b> 列挙型</a> </li> <li><a href='match.html'><b>4.14.</b> マッチ</a> </li> <li><a href='patterns.html'><b>4.15.</b> パターン</a> </li> <li><a href='method-syntax.html'><b>4.16.</b> メソッド構文</a> </li> <li><a href='strings.html'><b>4.17.</b> 文字列</a> </li> <li><a href='generics.html'><b>4.18.</b> ジェネリクス</a> </li> <li><a href='traits.html'><b>4.19.</b> トレイト</a> </li> <li><a href='drop.html'><b>4.20.</b> Drop</a> </li> <li><a href='if-let.html'><b>4.21.</b> if let</a> </li> <li><a href='trait-objects.html'><b>4.22.</b> トレイトオブジェクト</a> </li> <li><a href='closures.html'><b>4.23.</b> クロージャ</a> </li> <li><a href='ufcs.html'><b>4.24.</b> 共通の関数呼出構文</a> </li> <li><a href='crates-and-modules.html'><b>4.25.</b> クレートとモジュール</a> </li> <li><a class='active' href='const-and-static.html'><b>4.26.</b> `const` と `static`</a> </li> <li><a href='attributes.html'><b>4.27.</b> アトリビュート</a> </li> <li><a href='type-aliases.html'><b>4.28.</b> `type` エイリアス</a> </li> <li><a href='casting-between-types.html'><b>4.29.</b> 型間のキャスト</a> </li> <li><a href='associated-types.html'><b>4.30.</b> 関連型</a> </li> <li><a href='unsized-types.html'><b>4.31.</b> サイズ不定型</a> </li> <li><a href='operators-and-overloading.html'><b>4.32.</b> 演算子とオーバーロード</a> </li> <li><a href='deref-coercions.html'><b>4.33.</b> Derefによる型強制</a> </li> <li><a href='macros.html'><b>4.34.</b> マクロ</a> </li> <li><a href='raw-pointers.html'><b>4.35.</b> 生ポインタ</a> </li> <li><a href='unsafe.html'><b>4.36.</b> `unsafe`</a> </li> </ul> </li> <li><a href='effective-rust.html'><b>5.</b> Effective Rust</a> <ul class='section'> <li><a href='the-stack-and-the-heap.html'><b>5.1.</b> スタックとヒープ</a> </li> <li><a href='testing.html'><b>5.2.</b> テスト</a> </li> <li><a href='conditional-compilation.html'><b>5.3.</b> 条件付きコンパイル</a> </li> <li><a href='documentation.html'><b>5.4.</b> ドキュメント</a> </li> <li><a href='iterators.html'><b>5.5.</b> イテレータ</a> </li> <li><a href='concurrency.html'><b>5.6.</b> 並行性</a> </li> <li><a href='error-handling.html'><b>5.7.</b> エラーハンドリング</a> </li> <li><a href='choosing-your-guarantees.html'><b>5.8.</b> 保証を選ぶ</a> </li> <li><a href='ffi.html'><b>5.9.</b> 他言語関数インターフェース</a> </li> <li><a href='borrow-and-asref.html'><b>5.10.</b> BorrowとAsRef</a> </li> <li><a href='release-channels.html'><b>5.11.</b> リリースチャネル</a> </li> <li><a href='using-rust-without-the-standard-library.html'><b>5.12.</b> 標準ライブラリ無しでRustを使う</a> </li> </ul> </li> <li><a href='nightly-rust.html'><b>6.</b> Nightly Rust</a> <ul class='section'> <li><a href='compiler-plugins.html'><b>6.1.</b> コンパイラプラグイン</a> </li> <li><a href='inline-assembly.html'><b>6.2.</b> インラインアセンブリ</a> </li> <li><a href='no-stdlib.html'><b>6.3.</b> No stdlib</a> </li> <li><a href='intrinsics.html'><b>6.4.</b> Intrinsic</a> </li> <li><a href='lang-items.html'><b>6.5.</b> 言語アイテム</a> </li> <li><a href='advanced-linking.html'><b>6.6.</b> 高度なリンキング</a> </li> <li><a href='benchmark-tests.html'><b>6.7.</b> ベンチマークテスト</a> </li> <li><a href='box-syntax-and-patterns.html'><b>6.8.</b> Box構文とパターン</a> </li> <li><a href='slice-patterns.html'><b>6.9.</b> スライスパターン</a> </li> <li><a href='associated-constants.html'><b>6.10.</b> 関連定数</a> </li> <li><a href='custom-allocators.html'><b>6.11.</b> カスタムアロケータ</a> </li> </ul> </li> <li><a href='glossary.html'><b>7.</b> 用語集</a> </li> <li><a href='syntax-index.html'><b>8.</b> 構文の索引</a> </li> <li><a href='bibliography.html'><b>9.</b> 関係書目</a> </li> </ul> </div> <div id='page-wrapper'> <div id='page'> <blockquote class="header-caveat"> <p> <strong>注意: <a href="https://doc.rust-jp.rs/book-ja/">最新版のドキュメントをご覧ください。</a></strong>この第1版ドキュメントは古くなっており、最新情報が反映されていません。リンク先のドキュメントが現在の Rust の最新のドキュメントです。 </p> </blockquote> <h1 class="title">`const` と `static`</h1> <!-- % `const` and `static` --> <!-- Rust has a way of defining constants with the `const` keyword: --> <p>Rustでは <code>const</code> を用いることで定数を定義できます:</p> <span class='rusttest'>fn main() { const N: i32 = 5; }</span><pre class='rust rust-example-rendered'> <span class='kw'>const</span> <span class='ident'>N</span>: <span class='ident'>i32</span> <span class='op'>=</span> <span class='number'>5</span>;</pre> <!-- Unlike [`let`][let] bindings, you must annotate the type of a `const`. --> <p><a href="variable-bindings.html"><code>let</code></a> による束縛とは異なり、<code>const</code> を用いるときは型を明示する必要があります。</p> <!-- Constants live for the entire lifetime of a program. More specifically, --> <!-- constants in Rust have no fixed address in memory. This is because they’re --> <!-- effectively inlined to each place that they’re used. References to the same --> <!-- constant are not necessarily guaranteed to refer to the same memory address for --> <!-- this reason. --> <p>定数はプログラム全体のライフタイムの間生きています。 さらに言えば、Rustプログラム中で定数はメモリ中に固定のアドレスを持ちません。 これは定数が利用されている時にそれらが効率的にインライン化されるためです。 このため、同じ定数への参照が必ずしも同じアドレスを指しているとは保証されません。</p> <h1 id='static' class='section-header'><a href='#static'><code>static</code></a></h1> <!-- Rust provides a ‘global variable’ sort of facility in static items. They’re --> <!-- similar to constants, but static items aren’t inlined upon use. This means that --> <!-- there is only one instance for each value, and it’s at a fixed location in --> <!-- memory. --> <p>Rustは「グローバル変数」と呼ばれる静的アイテムを提供します。 「グローバル変数」は定数と似ていますが、静的アイテムは使用にあたってインライン化は行われません。 これは、「グローバル変数」にはそれぞれに対しただひとつのインスタンスのみが存在することを意味し、 メモリ上に固定の位置を持つことになります。</p> <!-- Here’s an example: --> <p>以下に例を示します:</p> <span class='rusttest'>fn main() { static N: i32 = 5; }</span><pre class='rust rust-example-rendered'> <span class='kw'>static</span> <span class='ident'>N</span>: <span class='ident'>i32</span> <span class='op'>=</span> <span class='number'>5</span>;</pre> <!-- Unlike [`let`][let] bindings, you must annotate the type of a `static`. --> <p><a href="variable-bindings.html"><code>let</code></a> による束縛とは異なり、<code>static</code> を用いるときは型を明示する必要があります。</p> <!-- Statics live for the entire lifetime of a program, and therefore any --> <!-- reference stored in a constant has a [`'static` lifetime][lifetimes]: --> <p>静的アイテムはプログラム全体のライフタイムの間生きています。 そのため定数に保存されている参照は <a href="lifetimes.html"><code>static</code> ライフタイム</a> を持ちます:</p> <span class='rusttest'>fn main() { static NAME: &amp;&#39;static str = &quot;Steve&quot;; }</span><pre class='rust rust-example-rendered'> <span class='kw'>static</span> <span class='ident'>NAME</span>: <span class='kw-2'>&amp;</span><span class='lifetime'>&#39;static</span> <span class='ident'>str</span> <span class='op'>=</span> <span class='string'>&quot;Steve&quot;</span>;</pre> <!-- ## Mutability --> <h2 id='ミュータビリティ' class='section-header'><a href='#ミュータビリティ'>ミュータビリティ</a></h2> <!-- You can introduce mutability with the `mut` keyword: --> <p><code>mut</code> を利用することでミュータビリティを導入できます:</p> <span class='rusttest'>fn main() { static mut N: i32 = 5; }</span><pre class='rust rust-example-rendered'> <span class='kw'>static</span> <span class='kw-2'>mut</span> <span class='ident'>N</span>: <span class='ident'>i32</span> <span class='op'>=</span> <span class='number'>5</span>;</pre> <!-- Because this is mutable, one thread could be updating `N` while another is --> <!-- reading it, causing memory unsafety. As such both accessing and mutating a --> <!-- `static mut` is [`unsafe`][unsafe], and so must be done in an `unsafe` block: --> <p>この静的な変数 <code>N</code> はミュータブルであるため、別のスレッドから読まれている間に変更される可能性があり、メモリの不安全性の原因となります。 そのため <code>static mut</code> な変数にアクセスを行うことは <a href="unsafe.html"><code>unsafe</code></a> であり、 <code>unsafe</code> ブロック中で行う必要があります。</p> <span class='rusttest'>fn main() { static mut N: i32 = 5; unsafe { N += 1; println!(&quot;N: {}&quot;, N); } }</span><pre class='rust rust-example-rendered'> <span class='kw'>unsafe</span> { <span class='ident'>N</span> <span class='op'>+=</span> <span class='number'>1</span>; <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;N: {}&quot;</span>, <span class='ident'>N</span>); }</pre> <!-- Furthermore, any type stored in a `static` must be `Sync`, and must not have --> <!-- a [`Drop`][drop] implementation. --> <p>さらに言えば、 <code>static</code> な変数に格納される値の型は <code>Sync</code> を実装しており、かつ <a href="drop.html"><code>Drop</code></a> は実装していない必要があります。</p> <!-- # Initializing --> <h1 id='初期化' class='section-header'><a href='#初期化'>初期化</a></h1> <!-- Both `const` and `static` have requirements for giving them a value. They must --> <!-- be given a value that’s a constant expression. In other words, you cannot use --> <!-- the result of a function call or anything similarly complex or at runtime. --> <p><code>const</code> 、 <code>static</code> どちらも値に対してそれらが定数式でなければならないという要件があります。 言い換えると、関数の呼び出しのような複雑なものや実行時の値を指定することはできないということです。</p> <!-- # Which construct should I use? --> <h1 id='どちらを使うべきか' class='section-header'><a href='#どちらを使うべきか'>どちらを使うべきか</a></h1> <!-- Almost always, if you can choose between the two, choose `const`. It’s pretty --> <!-- rare that you actually want a memory location associated with your constant, --> <!-- and using a const allows for optimizations like constant propagation not only --> <!-- in your crate but downstream crates. --> <p>大抵の場合、<code>static</code> か <code>const</code> で選ぶときは <code>const</code> を選ぶと良いでしょう。 定数を定義したい時に、そのメモリロケーションが固定であることを必要とする場面は珍しく、また <code>const</code> を用いることで定数伝播によってあなたのクレートだけでなく、それを利用するクレートでも最適化が行われます。</p> <script type="text/javascript"> window.playgroundUrl = "https://play.rust-lang.org"; </script> <script src='rustbook.js'></script> <script src='playpen.js'></script> </div></div> </body> </html> <|start_filename|>docs/1.6/book/syntax-index.html<|end_filename|> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="generator" content="rustdoc"> <title>構文の索引</title> <link rel="stylesheet" type="text/css" href="rustbook.css"> <meta name="robots" content="noindex"> </head> <body class="rustdoc"> <!--[if lte IE 8]> <div class="warning"> This old browser is unsupported and will most likely display funky things. </div> <![endif]--> <div id="nav"> <button id="toggle-nav"> <span class="sr-only">Toggle navigation</span> <span class="bar"></span> <span class="bar"></span> <span class="bar"></span> </button> </div> <div id='toc' class='mobile-hidden'> <ul class='chapter'> <li><a href='README.html'><b>1.</b> Introduction</a> </li> <li><a href='getting-started.html'><b>2.</b> はじめる</a> </li> <li><a href='learn-rust.html'><b>3.</b> Rustを学ぶ</a> <ul class='section'> <li><a href='guessing-game.html'><b>3.1.</b> 数当てゲーム</a> </li> <li><a href='dining-philosophers.html'><b>3.2.</b> 食事する哲学者</a> </li> <li><a href='rust-inside-other-languages.html'><b>3.3.</b> 他言語と共存する</a> </li> </ul> </li> <li><a href='syntax-and-semantics.html'><b>4.</b> シンタックスとセマンティクス</a> <ul class='section'> <li><a href='variable-bindings.html'><b>4.1.</b> 変数束縛</a> </li> <li><a href='functions.html'><b>4.2.</b> 関数</a> </li> <li><a href='primitive-types.html'><b>4.3.</b> プリミティブ型</a> </li> <li><a href='comments.html'><b>4.4.</b> コメント</a> </li> <li><a href='if.html'><b>4.5.</b> if</a> </li> <li><a href='loops.html'><b>4.6.</b> ループ</a> </li> <li><a href='ownership.html'><b>4.7.</b> 所有権</a> </li> <li><a href='references-and-borrowing.html'><b>4.8.</b> 参照と借用</a> </li> <li><a href='lifetimes.html'><b>4.9.</b> ライフタイム</a> </li> <li><a href='mutability.html'><b>4.10.</b> ミュータビリティ</a> </li> <li><a href='structs.html'><b>4.11.</b> 構造体</a> </li> <li><a href='enums.html'><b>4.12.</b> 列挙型</a> </li> <li><a href='match.html'><b>4.13.</b> マッチ</a> </li> <li><a href='patterns.html'><b>4.14.</b> パターン</a> </li> <li><a href='method-syntax.html'><b>4.15.</b> メソッド構文</a> </li> <li><a href='vectors.html'><b>4.16.</b> ベクタ</a> </li> <li><a href='strings.html'><b>4.17.</b> 文字列</a> </li> <li><a href='generics.html'><b>4.18.</b> ジェネリクス</a> </li> <li><a href='traits.html'><b>4.19.</b> トレイト</a> </li> <li><a href='drop.html'><b>4.20.</b> Drop</a> </li> <li><a href='if-let.html'><b>4.21.</b> if let</a> </li> <li><a href='trait-objects.html'><b>4.22.</b> トレイトオブジェクト</a> </li> <li><a href='closures.html'><b>4.23.</b> クロージャ</a> </li> <li><a href='ufcs.html'><b>4.24.</b> 共通の関数呼出構文</a> </li> <li><a href='crates-and-modules.html'><b>4.25.</b> クレートとモジュール</a> </li> <li><a href='const-and-static.html'><b>4.26.</b> `const` と `static`</a> </li> <li><a href='attributes.html'><b>4.27.</b> アトリビュート</a> </li> <li><a href='type-aliases.html'><b>4.28.</b> `type` エイリアス</a> </li> <li><a href='casting-between-types.html'><b>4.29.</b> 型間のキャスト</a> </li> <li><a href='associated-types.html'><b>4.30.</b> 関連型</a> </li> <li><a href='unsized-types.html'><b>4.31.</b> サイズ不定型</a> </li> <li><a href='operators-and-overloading.html'><b>4.32.</b> 演算子とオーバーロード</a> </li> <li><a href='deref-coercions.html'><b>4.33.</b> Derefによる型強制</a> </li> <li><a href='macros.html'><b>4.34.</b> マクロ</a> </li> <li><a href='raw-pointers.html'><b>4.35.</b> 生ポインタ</a> </li> <li><a href='unsafe.html'><b>4.36.</b> `unsafe`</a> </li> </ul> </li> <li><a href='effective-rust.html'><b>5.</b> Effective Rust</a> <ul class='section'> <li><a href='the-stack-and-the-heap.html'><b>5.1.</b> スタックとヒープ</a> </li> <li><a href='testing.html'><b>5.2.</b> テスト</a> </li> <li><a href='conditional-compilation.html'><b>5.3.</b> 条件付きコンパイル</a> </li> <li><a href='documentation.html'><b>5.4.</b> ドキュメント</a> </li> <li><a href='iterators.html'><b>5.5.</b> イテレータ</a> </li> <li><a href='concurrency.html'><b>5.6.</b> 並行性</a> </li> <li><a href='error-handling.html'><b>5.7.</b> エラーハンドリング</a> </li> <li><a href='choosing-your-guarantees.html'><b>5.8.</b> 保証を選ぶ</a> </li> <li><a href='ffi.html'><b>5.9.</b> 他言語関数インターフェース</a> </li> <li><a href='borrow-and-asref.html'><b>5.10.</b> BorrowとAsRef</a> </li> <li><a href='release-channels.html'><b>5.11.</b> リリースチャネル</a> </li> <li><a href='using-rust-without-the-standard-library.html'><b>5.12.</b> 標準ライブラリ無しでRustを使う</a> </li> </ul> </li> <li><a href='nightly-rust.html'><b>6.</b> Nightly Rust</a> <ul class='section'> <li><a href='compiler-plugins.html'><b>6.1.</b> コンパイラプラグイン</a> </li> <li><a href='inline-assembly.html'><b>6.2.</b> インラインアセンブリ</a> </li> <li><a href='no-stdlib.html'><b>6.3.</b> No stdlib</a> </li> <li><a href='intrinsics.html'><b>6.4.</b> Intrinsic</a> </li> <li><a href='lang-items.html'><b>6.5.</b> 言語アイテム</a> </li> <li><a href='advanced-linking.html'><b>6.6.</b> 高度なリンキング</a> </li> <li><a href='benchmark-tests.html'><b>6.7.</b> ベンチマークテスト</a> </li> <li><a href='box-syntax-and-patterns.html'><b>6.8.</b> Box構文とパターン</a> </li> <li><a href='slice-patterns.html'><b>6.9.</b> スライスパターン</a> </li> <li><a href='associated-constants.html'><b>6.10.</b> 関連定数</a> </li> <li><a href='custom-allocators.html'><b>6.11.</b> カスタムアロケータ</a> </li> </ul> </li> <li><a href='glossary.html'><b>7.</b> 用語集</a> </li> <li><a class='active' href='syntax-index.html'><b>8.</b> 構文の索引</a> </li> <li><a href='bibliography.html'><b>9.</b> 関係書目</a> </li> </ul> </div> <div id='page-wrapper'> <div id='page'> <blockquote class="header-caveat"> <p> <strong>注意: <a href="https://doc.rust-jp.rs/book-ja/">最新版のドキュメントをご覧ください。</a></strong>この第1版ドキュメントは古くなっており、最新情報が反映されていません。リンク先のドキュメントが現在の Rust の最新のドキュメントです。 </p> </blockquote> <h1 class="title">構文の索引</h1> <!-- % Syntax Index --> <!-- ## Keywords --> <h2 id='キーワード' class='section-header'><a href='#キーワード'>キーワード</a></h2> <!-- * `as`: primitive casting. See [Casting Between Types (`as`)]. --> <!-- * `break`: break out of loop. See [Loops (Ending Iteration Early)]. --> <!-- * `const`: constant items and constant raw pointers. See [`const` and `static`], [Raw Pointers]. --> <!-- * `continue`: continue to next loop iteration. See [Loops (Ending Iteration Early)]. --> <!-- * `crate`: external crate linkage. See [Crates and Modules (Importing External Crates)]. --> <!-- * `else`: fallback for `if` and `if let` constructs. See [`if`], [`if let`]. --> <!-- * `enum`: defining enumeration. See [Enums]. --> <!-- * `extern`: external crate, function, and variable linkage. See [Crates and Modules (Importing External Crates)], [Foreign Function Interface]. --> <!-- * `false`: boolean false literal. See [Primitive Types (Booleans)]. --> <!-- * `fn`: function definition and function pointer types. See [Functions]. --> <!-- * `for`: iterator loop, part of trait `impl` syntax, and higher-ranked lifetime syntax. See [Loops (`for`)], [Method Syntax]. --> <!-- * `if`: conditional branching. See [`if`], [`if let`]. --> <!-- * `impl`: inherent and trait implementation blocks. See [Method Syntax]. --> <!-- * `in`: part of `for` loop syntax. See [Loops (`for`)]. --> <!-- * `let`: variable binding. See [Variable Bindings]. --> <!-- * `loop`: unconditional, infinite loop. See [Loops (`loop`)]. --> <!-- * `match`: pattern matching. See [Match]. --> <!-- * `mod`: module declaration. See [Crates and Modules (Defining Modules)]. --> <!-- * `move`: part of closure syntax. See [Closures (`move` closures)]. --> <!-- * `mut`: denotes mutability in pointer types and pattern bindings. See [Mutability]. --> <!-- * `pub`: denotes public visibility in `struct` fields, `impl` blocks, and modules. See [Crates and Modules (Exporting a Public Interface)]. --> <!-- * `ref`: by-reference binding. See [Patterns (`ref` and `ref mut`)]. --> <!-- * `return`: return from function. See [Functions (Early Returns)]. --> <!-- * `Self`: implementor type alias. See [Traits]. --> <!-- * `self`: method subject. See [Method Syntax (Method Calls)]. --> <!-- * `static`: global variable. See [`const` and `static` (`static`)]. --> <!-- * `struct`: structure definition. See [Structs]. --> <!-- * `trait`: trait definition. See [Traits]. --> <!-- * `true`: boolean true literal. See [Primitive Types (Booleans)]. --> <!-- * `type`: type alias, and associated type definition. See [`type` Aliases], [Associated Types]. --> <!-- * `unsafe`: denotes unsafe code, functions, traits, and implementations. See [Unsafe]. --> <!-- * `use`: import symbols into scope. See [Crates and Modules (Importing Modules with `use`)]. --> <!-- * `where`: type constraint clauses. See [Traits (`where` clause)]. --> <!-- * `while`: conditional loop. See [Loops (`while`)]. --> <ul> <li><code>as</code>: プリミティブのキャスト。 <a href="casting-between-types.html#as">型間のキャスト (<code>as</code>)</a> 参照。</li> <li><code>break</code>: ループからの脱却。<a href="loops.html#%E5%8F%8D%E5%BE%A9%E3%81%AE%E6%97%A9%E6%9C%9F%E7%B5%82%E4%BA%86">ループ (反復の早期終了)</a> 参照。</li> <li><code>const</code>: 定数および定数ポインタ。 <a href="const-and-static.html"><code>const</code> と <code>static</code></a> 、 <a href="raw-pointers.html">生ポインタ</a> 参照。</li> <li><code>continue</code>: 次の反復への継続。 <a href="loops.html#%E5%8F%8D%E5%BE%A9%E3%81%AE%E6%97%A9%E6%9C%9F%E7%B5%82%E4%BA%86">ループ (反復の早期終了)</a> 参照。</li> <li><code>crate</code>: 外部クレートのリンク。 <a href="crates-and-modules.html#%E5%A4%96%E9%83%A8%E3%82%AF%E3%83%AC%E3%83%BC%E3%83%88%E3%81%AE%E3%82%A4%E3%83%B3%E3%83%9D%E3%83%BC%E3%83%88">クレートとモジュール (外部クレートのインポート)</a> 参照</li> <li><code>else</code>: <code>if</code> と <code>if let</code> が形成するフォールバック。 <a href="if.html"><code>if</code></a> 、 <a href="if-let.html"><code>if let</code></a> 参照。</li> <li><code>enum</code>: 列挙型の定義。 <a href="enums.html">列挙型</a> 参照。</li> <li><code>extern</code>: 外部クレート、関数、変数のリンク。 <a href="crates-and-modules.html#%E5%A4%96%E9%83%A8%E3%82%AF%E3%83%AC%E3%83%BC%E3%83%88%E3%81%AE%E3%82%A4%E3%83%B3%E3%83%9D%E3%83%BC%E3%83%88">クレートとモジュール (外部クレートのインポート)</a>、 <a href="ffi.html">他言語関数インターフェイス</a> 参照。</li> <li><code>false</code>: ブーリアン型の偽値のリテラル。 <a href="primitive-types.html#%E3%83%96%E3%83%BC%E3%83%AA%E3%82%A2%E3%83%B3%E5%9E%8B">プリミティブ型 (ブーリアン型)</a> 参照。</li> <li><code>fn</code>: 関数定義及び関数ポインタ型。 <a href="functions.html">関数</a> 参照。</li> <li><code>for</code>: イテレータループ、 トレイト <code>impl</code> 構文の一部、 あるいは 高階ライフタイム構文。 <a href="loops.html#for">ループ (<code>for</code>)</a> 、 <a href="method-syntax.html">メソッド構文</a> 参照。</li> <li><code>if</code>: 条件分岐 <a href="if.html"><code>if</code></a> 、 <a href="if-let.html"><code>if let</code></a> 参照。</li> <li><code>impl</code>: 固有及びトレイト実装のブロック。 <a href="method-syntax.html">メソッド構文</a> 参照。</li> <li><code>in</code>: <code>for</code> ループ構文の一部。 <a href="loops.html#for">ループ (<code>for</code>)</a> 参照。</li> <li><code>let</code>: 変数束縛。 <a href="variable-bindings.html">変数束縛</a> 参照。</li> <li><code>loop</code>: 条件無しの無限ループ。 <a href="loops.html#loop">ループ (<code>loop</code>)</a> 参照。</li> <li><code>match</code>: パターンマッチ。 <a href="match.html">マッチ</a> 参照。</li> <li><code>mod</code>: モジュール宣言。 <a href="crates-and-modules.html#%E3%83%A2%E3%82%B8%E3%83%A5%E3%83%BC%E3%83%AB%E3%82%92%E5%AE%9A%E7%BE%A9%E3%81%99%E3%82%8B">クレートとモジュール (モジュールを定義する)</a> 参照。</li> <li><code>move</code>: クロージャ構文の一部。 <a href="closures.html#move-%E3%82%AF%E3%83%AD%E3%83%BC%E3%82%B8%E3%83%A3">クロージャ (<code>move</code> クロージャ)</a> 参照。</li> <li><code>mut</code>: ポインタ型とパターン束縛におけるミュータビリティを表す。 <a href="mutability.html">ミュータビリティ</a> 参照。</li> <li><code>pub</code>: <code>struct</code> のフィールド、 <code>impl</code> ブロック、 モジュールにおいて可視性を表す。 <a href="crates-and-modules.html#%E3%83%91%E3%83%96%E3%83%AA%E3%83%83%E3%82%AF%E3%81%AA%E3%82%A4%E3%83%B3%E3%82%BF%E3%83%BC%E3%83%95%E3%82%A7%E3%83%BC%E3%82%B9%E3%81%AE%E3%82%A8%E3%82%AF%E3%82%B9%E3%83%9D%E3%83%BC%E3%83%88">クレートとモジュール (パブリックなインターフェースのエクスポート)</a> 参照。</li> <li><code>ref</code>: 参照束縛。 <a href="patterns.html#ref-%E3%81%A8-ref-mut">パターン (<code>ref</code> と <code>ref mut</code>)</a> 参照。</li> <li><code>return</code>: 関数からのリターン。 <a href="functions.html#%E6%97%A9%E6%9C%9F%E3%83%AA%E3%82%BF%E3%83%BC%E3%83%B3">関数 (早期リターン)</a> 参照。</li> <li><code>Self</code>: 実装者の型のエイリアス。 <a href="traits.html">トレイト</a> 参照。</li> <li><code>self</code>: メソッドの主語。 <a href="method-syntax.html#%E3%83%A1%E3%82%BD%E3%83%83%E3%83%89%E5%91%BC%E3%81%B3%E5%87%BA%E3%81%97">メソッド構文 (メソッド呼び出し)</a> 参照。</li> <li><code>static</code>: グローバル変数。 <a href="const-and-static.html#static"><code>const</code> と <code>static</code> (<code>static</code>)</a> 参照。</li> <li><code>struct</code>: 構造体定義。 <a href="structs.html">構造体</a> 参照。</li> <li><code>trait</code>: トレイト定義。 <a href="traits.html">トレイト</a> 参照。</li> <li><code>true</code>: ブーリアン型の真値のリテラル。 <a href="primitive-types.html#%E3%83%96%E3%83%BC%E3%83%AA%E3%82%A2%E3%83%B3%E5%9E%8B">プリミティブ型 (ブーリアン型)</a> 参照。</li> <li><code>type</code>: 型エイリアス、または関連型定義。 <a href="type-aliases.html"><code>type</code> エイリアス</a> 、 <a href="associated-types.html">関連型</a> 参照。</li> <li><code>unsafe</code>: アンセーフなコード、関数、トレイト、そして実装を表す。 <a href="unsafe.html">Unsafe</a> 参照。</li> <li><code>use</code>: スコープにシンボルをインポートする。 <a href="crates-and-modules.html#use-%E3%81%A7%E3%83%A2%E3%82%B8%E3%83%A5%E3%83%BC%E3%83%AB%E3%82%92%E3%82%A4%E3%83%B3%E3%83%9D%E3%83%BC%E3%83%88%E3%81%99%E3%82%8B">クレートとモジュール (<code>use</code> でモジュールをインポートする)</a> 参照。</li> <li><code>where</code>: 型制約節。 <a href="traits.html#where-%E7%AF%80">トレイト (<code>where</code> 節)</a> 参照。</li> <li><code>while</code>: 条件付きループ。 <a href="loops.html#while">ループ (<code>while</code>)</a> 参照。</li> </ul> <!-- ## Operators and Symbols --> <h2 id='演算子とシンボル' class='section-header'><a href='#演算子とシンボル'>演算子とシンボル</a></h2> <!-- * `!` (`ident!(…)`, `ident!{…}`, `ident![…]`): denotes macro expansion. See [Macros]. --> <!-- * `!` (`!expr`): bitwise or logical complement. Overloadable (`Not`). --> <!-- * `%` (`expr % expr`): arithmetic remainder. Overloadable (`Rem`). --> <!-- * `%=` (`var %= expr`): arithmetic remainder & assignment. --> <!-- * `&` (`expr & expr`): bitwise and. Overloadable (`BitAnd`). --> <!-- * `&` (`&expr`): borrow. See [References and Borrowing]. --> <!-- * `&` (`&type`, `&mut type`, `&'a type`, `&'a mut type`): borrowed pointer type. See [References and Borrowing]. --> <!-- * `&=` (`var &= expr`): bitwise and & assignment. --> <!-- * `&&` (`expr && expr`): logical and. --> <!-- * `*` (`expr * expr`): arithmetic multiplication. Overloadable (`Mul`). --> <!-- * `*` (`*expr`): dereference. --> <!-- * `*` (`*const type`, `*mut type`): raw pointer. See [Raw Pointers]. --> <!-- * `*=` (`var *= expr`): arithmetic multiplication & assignment. --> <!-- * `+` (`expr + expr`): arithmetic addition. Overloadable (`Add`). --> <!-- * `+` (`trait + trait`, `'a + trait`): compound type constraint. See [Traits (Multiple Trait Bounds)]. --> <!-- * `+=` (`var += expr`): arithmetic addition & assignment. --> <!-- * `,`: argument and element separator. See [Attributes], [Functions], [Structs], [Generics], [Match], [Closures], [Crates and Modules (Importing Modules with `use`)]. --> <!-- * `-` (`expr - expr`): arithmetic subtraction. Overloadable (`Sub`). --> <!-- * `-` (`- expr`): arithmetic negation. Overloadable (`Neg`). --> <!-- * `-=` (`var -= expr`): arithmetic subtraction & assignment. --> <!-- * `->` (`fn(…) -> type`, `|…| -> type`): function and closure return type. See [Functions], [Closures]. --> <!-- * `-> !` (`fn(…) -> !`, `|…| -> !`): diverging function or closure. See [Diverging Functions]. --> <!-- * `.` (`expr.ident`): member access. See [Structs], [Method Syntax]. --> <!-- * `..` (`..`, `expr..`, `..expr`, `expr..expr`): right-exclusive range literal. --> <!-- * `..` (`..expr`): struct literal update syntax. See [Structs (Update syntax)]. --> <!-- * `..` (`variant(x, ..)`, `struct_type { x, .. }`): "and the rest" pattern binding. See [Patterns (Ignoring bindings)]. --> <!-- * `...` (`expr ... expr`): inclusive range pattern. See [Patterns (Ranges)]. --> <!-- * `/` (`expr / expr`): arithmetic division. Overloadable (`Div`). --> <!-- * `/=` (`var /= expr`): arithmetic division & assignment. --> <!-- * `:` (`pat: type`, `ident: type`): constraints. See [Variable Bindings], [Functions], [Structs], [Traits]. --> <!-- * `:` (`ident: expr`): struct field initializer. See [Structs]. --> <!-- * `:` (`'a: loop {…}`): loop label. See [Loops (Loops Labels)]. --> <!-- * `;`: statement and item terminator. --> <!-- * `;` (`[…; len]`): part of fixed-size array syntax. See [Primitive Types (Arrays)]. --> <!-- * `<<` (`expr << expr`): left-shift. Overloadable (`Shl`). --> <!-- * `<<=` (`var <<= expr`): left-shift & assignment. --> <!-- * `<` (`expr < expr`): less-than comparison. Overloadable (`Cmp`, `PartialCmp`). --> <!-- * `<=` (`var <= expr`): less-than or equal-to comparison. Overloadable (`Cmp`, `PartialCmp`). --> <!-- * `=` (`var = expr`, `ident = type`): assignment/equivalence. See [Variable Bindings], [`type` Aliases], generic parameter defaults. --> <!-- * `==` (`var == expr`): comparison. Overloadable (`Eq`, `PartialEq`). --> <!-- * `=>` (`pat => expr`): part of match arm syntax. See [Match]. --> <!-- * `>` (`expr > expr`): greater-than comparison. Overloadable (`Cmp`, `PartialCmp`). --> <!-- * `>=` (`var >= expr`): greater-than or equal-to comparison. Overloadable (`Cmp`, `PartialCmp`). --> <!-- * `>>` (`expr >> expr`): right-shift. Overloadable (`Shr`). --> <!-- * `>>=` (`var >>= expr`): right-shift & assignment. --> <!-- * `@` (`ident @ pat`): pattern binding. See [Patterns (Bindings)]. --> <!-- * `^` (`expr ^ expr`): bitwise exclusive or. Overloadable (`BitXor`). --> <!-- * `^=` (`var ^= expr`): bitwise exclusive or & assignment. --> <!-- * `|` (`expr | expr`): bitwise or. Overloadable (`BitOr`). --> <!-- * `|` (`pat | pat`): pattern alternatives. See [Patterns (Multiple patterns)]. --> <!-- * `|` (`|…| expr`): closures. See [Closures]. --> <!-- * `|=` (`var |= expr`): bitwise or & assignment. --> <!-- * `||` (`expr || expr`): logical or. --> <!-- * `_`: "ignored" pattern binding. See [Patterns (Ignoring bindings)]. --> <ul> <li><code>!</code> (<code>ident!(…)</code>, <code>ident!{…}</code>, <code>ident![…]</code>): マクロ展開を表す。 <a href="macros.html">マクロ</a>参照</li> <li><code>!</code> (<code>!expr</code>): ビット毎、あるいは論理の補数。 オーバロード可能 (<code>Not</code>)。</li> <li><code>%</code> (<code>expr % expr</code>): 算術剰余算。オーバーロード可能 (<code>Rem</code>)。</li> <li><code>%=</code> (<code>var %= expr</code>): 算術剰余算をして代入。</li> <li><code>&amp;</code> (<code>expr &amp; expr</code>):ビット毎の論理積。 オーバーロード可能 (<code>BitAnd</code>)。</li> <li><code>&amp;</code> (<code>&amp;expr</code>): 借用。 <a href="references-and-borrowing.html">参照と借用</a> 参照</li> <li><code>&amp;</code> (<code>&amp;type</code>, <code>&amp;mut type</code>, <code>&amp;&#39;a type</code>, <code>&amp;&#39;a mut type</code>): 借用されたポインタの型。 <a href="references-and-borrowing.html">参照と借用</a>参照。</li> <li><code>&amp;=</code> (<code>var &amp;= expr</code>): ビット毎の論理積をして代入。</li> <li><code>&amp;&amp;</code> (<code>expr &amp;&amp; expr</code>): 論理積。</li> <li><code>*</code> (<code>expr * expr</code>): 算術乗算。 オーバーロード可能 (<code>Mul</code>)。</li> <li><code>*</code> (<code>*expr</code>): 参照外し。</li> <li><code>*</code> (<code>*const type</code>, <code>*mut type</code>): 生ポインタ。 <a href="raw-pointers.html">生ポインタ</a>参照。</li> <li><code>*=</code> (<code>var *= expr</code>): 算術乗算をして代入。</li> <li><code>+</code> (<code>expr + expr</code>): 算術加算。オーバーロード可能 (<code>Add</code>)。</li> <li><code>+</code> (<code>trait + trait</code>, <code>&#39;a + trait</code>): 合成型制約。 <a href="traits.html#%E8%A4%87%E6%95%B0%E3%81%AE%E3%83%88%E3%83%AC%E3%82%A4%E3%83%88%E5%A2%83%E7%95%8C">トレイト (複数のトレイト境界)</a>参照。</li> <li><code>+=</code> (<code>var += expr</code>): 算術加算をして代入。</li> <li><code>,</code>: 引数または要素の区切り。 <a href="attributes.html">アトリビュート</a>、 <a href="functions.html">関数</a> 、 <a href="structs.html">構造体</a> 、 <a href="generics.html">ジェネリクス</a> 、 <a href="match.html">マッチ</a> 、 <a href="closures.html">クロージャ</a> 、 <a href="crates-and-modules.html#use-%E3%81%A7%E3%83%A2%E3%82%B8%E3%83%A5%E3%83%BC%E3%83%AB%E3%82%92%E3%82%A4%E3%83%B3%E3%83%9D%E3%83%BC%E3%83%88%E3%81%99%E3%82%8B">クレートとモジュール (<code>use</code> でモジュールをインポートする)</a> 参照。</li> <li><code>-</code> (<code>expr - expr</code>): 算術減算。オーバーロード可能 (<code>Sub</code>)。</li> <li><code>-</code> (<code>- expr</code>): 算術負。オーバーロード可能 (<code>Neg</code>)。</li> <li><code>-=</code> (<code>var -= expr</code>): 算術減算をして代入。</li> <li><code>-&gt;</code> (<code>fn(…) -&gt; type</code>, <code>|…| -&gt; type</code>): 関数とクロージャの返り型。 <a href="functions.html">関数</a>、<a href="closures.html">クロージャ</a>参照。</li> <li><code>-&gt; !</code> (<code>fn(…) -&gt; !</code>, <code>|…| -&gt; !</code>): 発散する関数またはクロージャ。<a href="functions.html#%E7%99%BA%E6%95%A3%E3%81%99%E3%82%8B%E9%96%A2%E6%95%B0">発散する関数</a>参照。</li> <li><code>.</code> (<code>expr.ident</code>): メンバへのアクセス。 <a href="structs.html">構造体</a>、 <a href="method-syntax.html">メソッド構文</a>参照。</li> <li><code>..</code> (<code>..</code>, <code>expr..</code>, <code>..expr</code>, <code>expr..expr</code>): 右に開な区間のリテラル。</li> <li><code>..</code> (<code>..expr</code>): 構造体リテラルのアップデート構文。<a href="structs.html#%E3%82%A2%E3%83%83%E3%83%97%E3%83%87%E3%83%BC%E3%83%88%E6%A7%8B%E6%96%87">構造体 (アップデート構文)</a>参照。</li> <li><code>..</code> (<code>variant(x, ..)</code>, <code>struct_type { x, .. }</code>): 「〜と残り」のパターン束縛。 <a href="patterns.html#%E6%9D%9F%E7%B8%9B%E3%81%AE%E7%84%A1%E8%A6%96">パターン (束縛の無視)</a> 参照。</li> <li><code>...</code> (<code>expr ... expr</code>): 閉区間リテラル。 <a href="patterns.html#%E3%83%AC%E3%83%B3%E3%82%B8">パターン (レンジ)</a> 参照。</li> <li><code>/</code> (<code>expr / expr</code>): 算術除算。オーバーロード可能 (<code>Div</code>)。</li> <li><code>/=</code> (<code>var /= expr</code>): 算術除算と代入。</li> <li><code>:</code> (<code>pat: type</code>, <code>ident: type</code>): 制約。<a href="variable-bindings.html">変数束縛</a> 、 <a href="functions.html">関数</a> 、 <a href="structs.html">構造体</a> 、 <a href="traits.html">トレイト</a> 参照。</li> <li><code>:</code> (<code>ident: expr</code>): 構造体のフィールドの初期化。 <a href="structs.html">構造体</a> 参照。</li> <li><code>:</code> (<code>&#39;a: loop {…}</code>): ループラベル。 <a href="loops.html#%E3%83%AB%E3%83%BC%E3%83%97%E3%83%A9%E3%83%99%E3%83%AB">ループ (ループラベル)</a> 参照。</li> <li><code>;</code>: 文またはアイテムの区切り。</li> <li><code>;</code> (<code>[…; len]</code>): 固定長配列構文の一部。 <a href="primitive-types.html#%E9%85%8D%E5%88%97">プリミティブ型 (配列)</a> 参照。</li> <li><code>&lt;&lt;</code> (<code>expr &lt;&lt; expr</code>): 左シフト。オーバーロード可能 (<code>Shl</code>)。</li> <li><code>&lt;&lt;=</code> (<code>var &lt;&lt;= expr</code>): 左シフトして代入。</li> <li><code>&lt;</code> (<code>expr &lt; expr</code>): 「より小さい」の比較。オーバーロード可能 (<code>Cmp</code>, <code>PartialCmp</code>)。</li> <li><code>&lt;=</code> (<code>var &lt;= expr</code>): 「以下」の比較。オーバーロード可能 (<code>Cmp</code>, <code>PartialCmp</code>)。</li> <li><code>=</code> (<code>var = expr</code>, <code>ident = type</code>): 代入/等価比較。 <a href="variable-bindings.html">変数束縛</a> 、 <a href="type-aliases.html"><code>type</code> エイリアス</a>、 ジェネリックパラメータのデフォルトを参照。</li> <li><code>==</code> (<code>var == expr</code>): 比較。オーバーロード可能 (<code>Eq</code>, <code>PartialEq</code>)。</li> <li><code>=&gt;</code> (<code>pat =&gt; expr</code>): マッチの腕の構文の一部。 <a href="match.html">マッチ</a> 参照。</li> <li><code>&gt;</code> (<code>expr &gt; expr</code>): 「より大きい」の比較。オーバーロード可能 (<code>Cmp</code>, <code>PartialCmp</code>)。</li> <li><code>&gt;=</code> (<code>var &gt;= expr</code>): 「以上」の比較。オーバーロード可能 (<code>Cmp</code>, <code>PartialCmp</code>)。</li> <li><code>&gt;&gt;</code> (<code>expr &gt;&gt; expr</code>): 右シフト。オーバーロード可能 (<code>Shr</code>)。</li> <li><code>&gt;&gt;=</code> (<code>var &gt;&gt;= expr</code>): 右シフトして代入。</li> <li><code>@</code> (<code>ident @ pat</code>): パターン束縛。 <a href="patterns.html#%E6%9D%9F%E7%B8%9B">パターン (束縛)</a> 参照。</li> <li><code>^</code> (<code>expr ^ expr</code>): ビット毎の排他的論理和。オーバーロード可能 (<code>BitXor</code>)。</li> <li><code>^=</code> (<code>var ^= expr</code>): ビット毎の排他的論理和をして代入。</li> <li><code>|</code> (<code>expr | expr</code>): ビット毎の論理和。 オーバーロード可能 (<code>BitOr</code>)。</li> <li><code>|</code> (<code>pat | pat</code>): パターンの「または」。 <a href="patterns.html#%E8%A4%87%E5%BC%8F%E3%83%91%E3%82%BF%E3%83%BC%E3%83%B3">パターン (複式パターン)</a> 参照</li> <li><code>|</code> (<code>|…| expr</code>): クロージャ。<a href="closures.html">クロージャ</a> 参照。</li> <li><code>|=</code> (<code>var |= expr</code>): ビット毎の論理和をして代入。</li> <li><code>||</code> (<code>expr || expr</code>): 論理和。</li> <li><code>_</code>: 「無視」するパターン束縛。 <a href="patterns.html#%E6%9D%9F%E7%B8%9B%E3%81%AE%E7%84%A1%E8%A6%96">パターン (束縛の無視)</a>。</li> </ul> <!-- ## Other Syntax --> <h2 id='他の構文' class='section-header'><a href='#他の構文'>他の構文</a></h2> <!-- Various bits of standalone stuff. --> <!-- * `'ident`: named lifetime or loop label. See [Lifetimes], [Loops (Loops Labels)]. --> <!-- * `…u8`, `…i32`, `…f64`, `…usize`, …: numeric literal of specific type. --> <!-- * `"…"`: string literal. See [Strings]. --> <!-- * `r"…"`, `r#"…"#`, `r##"…"##`, …: raw string literal, escape characters are not processed. See [Reference (Raw String Literals)]. --> <!-- * `b"…"`: byte string literal, constructs a `[u8]` instead of a string. See [Reference (Byte String Literals)]. --> <!-- * `br"…"`, `br#"…"#`, `br##"…"##`, …: raw byte string literal, combination of raw and byte string literal. See [Reference (Raw Byte String Literals)]. --> <!-- * `'…'`: character literal. See [Primitive Types (`char`)]. --> <!-- * `b'…'`: ASCII byte literal. --> <!-- * `|…| expr`: closure. See [Closures]. --> <ul> <li><code>&#39;ident</code>: 名前付きライフタイムまたはループラベル。 <a href="lifetimes.html">ライフタイム</a> 、 <a href="loops.html#%E3%83%AB%E3%83%BC%E3%83%97%E3%83%A9%E3%83%99%E3%83%AB">ループ (ループラベル)</a> 参照。</li> <li><code>…u8</code>, <code>…i32</code>, <code>…f64</code>, <code>…usize</code>, …: その型の数値リテラル。</li> <li><code>&quot;…&quot;</code>: 文字列リテラル。 <a href="strings.html">文字列</a> 参照。</li> <li><code>r&quot;…&quot;</code>, <code>r#&quot;…&quot;#</code>, <code>r##&quot;…&quot;##</code>, …: 生文字列リテラル、 エスケープ文字は処理されない。 <a href="../reference.html#raw-string-literals">リファレンス (生文字列リテラル)</a> 参照。</li> <li><code>b&quot;…&quot;</code>: バイト列リテラル、文字列ではなく <code>[u8]</code> を作る。 <a href="../reference.html#byte-string-literals">リファレンス (バイト列リテラル)</a> 参照。</li> <li><code>br&quot;…&quot;</code>, <code>br#&quot;…&quot;#</code>, <code>br##&quot;…&quot;##</code>, …: 生バイト列リテラル。生文字列とバイト列リテラルの組み合わせ。 <a href="../reference.html#raw-byte-string-literals">リファレンス (生バイト列リテラル)</a> 参照</li> <li><code>&#39;…&#39;</code>: 文字リテラル。 <a href="primitive-types.html#char">プリミティブ型 (<code>char</code>)</a> 参照。</li> <li><code>b&#39;…&#39;</code>: ASCIIバイトリテラル。</li> <li><code>|…| expr</code>: クロージャ。 <a href="closures.html">クロージャ</a> 参照。</li> </ul> <!-- Path-related syntax --> <!-- * `ident::ident`: path. See [Crates and Modules (Defining Modules)]. --> <!-- * `::path`: path relative to the crate root (*i.e.* an explicitly absolute path). See [Crates and Modules (Re-exporting with `pub use`)]. --> <!-- * `self::path`: path relative to the current module (*i.e.* an explicitly relative path). See [Crates and Modules (Re-exporting with `pub use`)]. --> <!-- * `super::path`: path relative to the parent of the current module. See [Crates and Modules (Re-exporting with `pub use`)]. --> <!-- * `type::ident`: associated constants, functions, and types. See [Associated Types]. --> <!-- * `<type>::…`: associated item for a type which cannot be directly named (*e.g.* `<&T>::…`, `<[T]>::…`, *etc.*). See [Associated Types]. --> <ul> <li><code>ident::ident</code>: パス。<a href="crates-and-modules.html#%E3%83%A2%E3%82%B8%E3%83%A5%E3%83%BC%E3%83%AB%E3%82%92%E5%AE%9A%E7%BE%A9%E3%81%99%E3%82%8B">クレートとモジュール (モジュールを定義する)</a> 参照。</li> <li><code>::path</code>: クレートのルートからの相対パス (<em>つまり</em> 明示的な絶対パス)。 <a href="crates-and-modules.html#pub-use-%E3%81%AB%E3%82%88%E3%82%8B%E5%86%8D%E3%82%A8%E3%82%AF%E3%82%B9%E3%83%9D%E3%83%BC%E3%83%88">クレートとモジュール (<code>pub use</code> による再エクスポート)</a> 参照。</li> <li><code>self::path</code>: 現在のモジュールからの相対パス (<em>つまり</em> 明示的な相対パス)。 <a href="crates-and-modules.html#pub-use-%E3%81%AB%E3%82%88%E3%82%8B%E5%86%8D%E3%82%A8%E3%82%AF%E3%82%B9%E3%83%9D%E3%83%BC%E3%83%88">クレートとモジュール (<code>pub use</code> による再エクスポート)</a> 参照。</li> <li><code>super::path</code>: 現在のモジュールの親からの相対パス。 <a href="crates-and-modules.html#pub-use-%E3%81%AB%E3%82%88%E3%82%8B%E5%86%8D%E3%82%A8%E3%82%AF%E3%82%B9%E3%83%9D%E3%83%BC%E3%83%88">クレートとモジュール (<code>pub use</code> による再エクスポート)</a> 参照。</li> <li><code>type::ident</code>: 関連定数、関数、型。 <a href="associated-types.html">関連型</a> 参照。</li> <li><code>&lt;type&gt;::…</code>: 直接名前付けられない型の関連アイテム (<em>例えば</em> <code>&lt;&amp;T&gt;::…</code> 、 <code>&lt;[T]&gt;::…</code> 、 <em>など</em>)。 <a href="associated-types.html">関連型</a> 参照。</li> </ul> <!-- Generics --> <!-- * `path<…>` (*e.g.* `Vec<u8>`): specifies parameters to generic type *in a type*. See [Generics]. --> <!-- * `path::<…>`, `method::<…>` (*e.g.* `"42".parse::<i32>()`): specifies parameters to generic type, function, or method *in an expression*. --> <!-- * `fn ident<…> …`: define generic function. See [Generics]. --> <!-- * `struct ident<…> …`: define generic structure. See [Generics]. --> <!-- * `enum ident<…> …`: define generic enumeration. See [Generics]. --> <!-- * `impl<…> …`: define generic implementation. --> <!-- * `for<…> type`: higher-ranked lifetime bounds. --> <!-- * `type<ident=type>` (*e.g.* `Iterator<Item=T>`): a generic type where one or more associated types have specific assignments. See [Associated Types]. --> <ul> <li><code>path&lt;…&gt;</code> (<em>例えば</em> <code>Vec&lt;u8&gt;</code>): <em>型での</em> ジェネリック型のパラメータの指定。 <a href="generics.html">ジェネリクス</a> 。</li> <li><code>path::&lt;…&gt;</code>, <code>method::&lt;…&gt;</code> (<em>例えば</em> <code>&quot;42&quot;.parse::&lt;i32&gt;()</code>): <em>式での</em> ジェネリック型あるいは関数、メソッドの型の指定。</li> <li><code>fn ident&lt;…&gt; …</code>: ジェネリック関数を定義。 <a href="generics.html">ジェネリクス</a> 参照。</li> <li><code>struct ident&lt;…&gt; …</code>: ジェネリック構造体を定義。 <a href="generics.html">ジェネリクス</a> 参照。</li> <li><code>enum ident&lt;…&gt; …</code>: ジェネリック列挙型を定義。 <a href="generics.html">ジェネリクス</a> 参照。</li> <li><code>impl&lt;…&gt; …</code>: ジェネリック実装を定義。</li> <li><code>for&lt;…&gt; type</code>: 高階ライフタイム境界。</li> <li><code>type&lt;ident=type&gt;</code> (<em>例えば</em> <code>Iterator&lt;Item=T&gt;</code>): 1つ以上の関連型について指定のあるジェネリック型。 <a href="associated-types.html">関連型</a> 参照。</li> </ul> <!-- Constraints --> <!-- * `T: U`: generic parameter `T` constrained to types that implement `U`. See [Traits]. --> <!-- * `T: 'a`: generic type `T` must outlive lifetime `'a`. --> <!-- * `'b: 'a`: generic lifetime `'b` must outlive lifetime `'a`. --> <!-- * `T: ?Sized`: allow generic type parameter to be a dynamically-sized type. See [Unsized Types (`?Sized`)]. --> <!-- * `'a + trait`, `trait + trait`: compound type constraint. See [Traits (Multiple Trait Bounds)]. --> <ul> <li><code>T: U</code>: <code>U</code> を実装する型に制約されたジェネリックパラメータ <code>T</code> 。 <a href="traits.html">トレイト</a> 参照。</li> <li><code>T: &#39;a</code>: ジェネリック型 <code>T</code> はライフタイム <code>&#39;a</code> より長生きしなければならない。</li> <li><code>&#39;b: &#39;a</code>: ジェネリックライフタイム <code>&#39;b</code> はライフタイム <code>&#39;a</code> より長生きしなければならない。</li> <li><code>T: ?Sized</code>: ジェネリック型パラメータが動的サイズ型になること許可する。 <a href="unsized-types.html#sized">サイズ不定型 (<code>?Sized</code>)</a> 参照。</li> <li><code>&#39;a + trait</code>, <code>trait + trait</code>: 合成型制約。 <a href="traits.html#%E8%A4%87%E6%95%B0%E3%81%AE%E3%83%88%E3%83%AC%E3%82%A4%E3%83%88%E5%A2%83%E7%95%8C">トレイト (複数のトレイト境界)</a> 参照。</li> </ul> <!-- Macros and attributes --> <!-- * `#[meta]`: outer attribute. See [Attributes]. --> <!-- * `#![meta]`: inner attribute. See [Attributes]. --> <!-- * `$ident`: macro substitution. See [Macros]. --> <!-- * `$ident:kind`: macro capture. See [Macros]. --> <!-- * `$(…)…`: macro repetition. See [Macros]. --> <ul> <li><code>#[meta]</code>: 外側のアトリビュート。 <a href="attributes.html">アトリビュート</a> 参照。</li> <li><code>#![meta]</code>: 内側のアトリビュート。 <a href="attributes.html">アトリビュート</a> 参照。</li> <li><code>$ident</code>: マクロでの置換。 <a href="macros.html">マクロ</a> 参照。</li> <li><code>$ident:kind</code>: マクロでの捕捉。 <a href="macros.html">マクロ</a> 参照。</li> <li><code>$(…)…</code>: マクロでの繰り返し。 <a href="macros.html">マクロ</a> 参照。</li> </ul> <!-- Comments --> <!-- * `//`: line comment. See [Comments]. --> <!-- * `//!`: inner line doc comment. See [Comments]. --> <!-- * `///`: outer line doc comment. See [Comments]. --> <!-- * `/*…*/`: block comment. See [Comments]. --> <!-- * `/*!…*/`: inner block doc comment. See [Comments]. --> <!-- * `/**…*/`: outer block doc comment. See [Comments]. --> <ul> <li><code>//</code>: ラインコメント。 <a href="comments.html">コメント</a> 参照。</li> <li><code>//!</code>: 内側の行ドキュメントコメント。 <a href="comments.html">コメント</a> 参照。</li> <li><code>///</code>: 外側の行ドキュメントコメント <a href="comments.html">コメント</a> 参照。</li> <li><code>/*…*/</code>: ブロックコメント。 <a href="comments.html">コメント</a> 参照。</li> <li><code>/*!…*/</code>: 内側のブロックドキュメントコメント。 <a href="comments.html">コメント</a> 参照。</li> <li><code>/**…*/</code>: 外側のブロックドキュメントコメント。 <a href="comments.html">コメント</a> 参照。</li> </ul> <!-- Various things involving parens and tuples --> <!-- * `()`: empty tuple (*a.k.a.* unit), both literal and type. --> <!-- * `(expr)`: parenthesized expression. --> <!-- * `(expr,)`: single-element tuple expression. See [Primitive Types (Tuples)]. --> <!-- * `(type,)`: single-element tuple type. See [Primitive Types (Tuples)]. --> <!-- * `(expr, …)`: tuple expression. See [Primitive Types (Tuples)]. --> <!-- * `(type, …)`: tuple type. See [Primitive Types (Tuples)]. --> <!-- * `expr(expr, …)`: function call expression. Also used to initialize tuple `struct`s and tuple `enum` variants. See [Functions]. --> <!-- * `ident!(…)`, `ident!{…}`, `ident![…]`: macro invocation. See [Macros]. --> <!-- * `expr.0`, `expr.1`, …: tuple indexing. See [Primitive Types (Tuple Indexing)]. --> <ul> <li><code>()</code>: 空タプル(<em>あるいは</em> ユニット)の、リテラルと型両方。</li> <li><code>(expr)</code>: 括弧付きの式。</li> <li><code>(expr,)</code>: 1要素タプルの式。 <a href="primitive-types.html#%E3%82%BF%E3%83%97%E3%83%AB">プリミティブ型 (タプル)</a> 参照。</li> <li><code>(type,)</code>: 1要素タプルの型。 <a href="primitive-types.html#%E3%82%BF%E3%83%97%E3%83%AB">プリミティブ型 (タプル)</a> 参照。</li> <li><code>(expr, …)</code>: タプル式。 <a href="primitive-types.html#%E3%82%BF%E3%83%97%E3%83%AB">プリミティブ型 (タプル)</a> 参照。</li> <li><code>(type, …)</code>: タプル型。 <a href="primitive-types.html#%E3%82%BF%E3%83%97%E3%83%AB">プリミティブ型 (タプル)</a> 参照。</li> <li><code>expr(expr, …)</code>: 関数呼び出し式。また、 タプル <code>struct</code> 、 タプル <code>enum</code> のヴァリアントを初期化するのにも使われる。 <a href="functions.html">関数</a> 参照。</li> <li><code>ident!(…)</code>, <code>ident!{…}</code>, <code>ident![…]</code>: マクロの起動。 <a href="macros.html">マクロ</a> 参照。</li> <li><code>expr.0</code>, <code>expr.1</code>, …: タプルのインデックス。 <a href="primitive-types.html#%E3%82%BF%E3%83%97%E3%83%AB%E3%81%AE%E3%82%A4%E3%83%B3%E3%83%87%E3%83%83%E3%82%AF%E3%82%B9">プリミティブ型 (タプルのインデックス)</a> 参照。</li> </ul> <!-- Bracey things --> <!-- * `{…}`: block expression. --> <!-- * `Type {…}`: `struct` literal. See [Structs]. --> <ul> <li><code>{…}</code>: ブロック式。</li> <li><code>Type {…}</code>: <code>struct</code> リテラル。 <a href="structs.html">構造体</a> 参照。</li> </ul> <!-- Brackety things --> <!-- * `[…]`: array literal. See [Primitive Types (Arrays)]. --> <!-- * `[expr; len]`: array literal containing `len` copies of `expr`. See [Primitive Types (Arrays)]. --> <!-- * `[type; len]`: array type containing `len` instances of `type`. See [Primitive Types (Arrays)]. --> <!-- * `expr[expr]`: collection indexing. Overloadable (`Index`, `IndexMut`). --> <!-- * `expr[..]`, `expr[a..]`, `expr[..b]`, `expr[a..b]`: collection indexing pretending to be collection slicing, using `Range`, `RangeFrom`, `RangeTo`, `RangeFull` as the "index". --> <ul> <li><code>[…]</code>: 配列リテラル。 <a href="primitive-types.html#%E9%85%8D%E5%88%97">プリミティブ型 (配列)</a> 参照。</li> <li><code>[expr; len]</code>: <code>len</code> 個の <code>expr</code> を要素に持つ配列リテラル。 <a href="primitive-types.html#%E9%85%8D%E5%88%97">プリミティブ型 (配列)</a> 参照。</li> <li><code>[type; len]</code>: <code>len</code> 個の<code>type</code> のインスタンスを要素に持つ配列型。 <a href="primitive-types.html#%E9%85%8D%E5%88%97">プリミティブ型 (配列)</a> 参照。</li> <li><code>expr[expr]</code>: コレクションのインデックス。 オーバーロード可能(<code>Index</code>, <code>IndexMut</code>)。</li> <li><code>expr[..]</code>, <code>expr[a..]</code>, <code>expr[..b]</code>, <code>expr[a..b]</code>: コレクションのスライスのようなコレクションのインデックス。 <code>Range</code> 、 <code>RangeFrom</code> 、 <code>RangeTo</code> 、 <code>RangeFull</code> を「インデックス」として使う。</li> </ul> <script type="text/javascript"> window.playgroundUrl = "https://play.rust-lang.org"; </script> <script src='rustbook.js'></script> <script src='playpen.js'></script> </div></div> </body> </html> <|start_filename|>docs/1.6/book/loops.html<|end_filename|> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="generator" content="rustdoc"> <title>ループ</title> <link rel="stylesheet" type="text/css" href="rustbook.css"> <meta name="robots" content="noindex"> </head> <body class="rustdoc"> <!--[if lte IE 8]> <div class="warning"> This old browser is unsupported and will most likely display funky things. </div> <![endif]--> <div id="nav"> <button id="toggle-nav"> <span class="sr-only">Toggle navigation</span> <span class="bar"></span> <span class="bar"></span> <span class="bar"></span> </button> </div> <div id='toc' class='mobile-hidden'> <ul class='chapter'> <li><a href='README.html'><b>1.</b> Introduction</a> </li> <li><a href='getting-started.html'><b>2.</b> はじめる</a> </li> <li><a href='learn-rust.html'><b>3.</b> Rustを学ぶ</a> <ul class='section'> <li><a href='guessing-game.html'><b>3.1.</b> 数当てゲーム</a> </li> <li><a href='dining-philosophers.html'><b>3.2.</b> 食事する哲学者</a> </li> <li><a href='rust-inside-other-languages.html'><b>3.3.</b> 他言語と共存する</a> </li> </ul> </li> <li><a href='syntax-and-semantics.html'><b>4.</b> シンタックスとセマンティクス</a> <ul class='section'> <li><a href='variable-bindings.html'><b>4.1.</b> 変数束縛</a> </li> <li><a href='functions.html'><b>4.2.</b> 関数</a> </li> <li><a href='primitive-types.html'><b>4.3.</b> プリミティブ型</a> </li> <li><a href='comments.html'><b>4.4.</b> コメント</a> </li> <li><a href='if.html'><b>4.5.</b> if</a> </li> <li><a class='active' href='loops.html'><b>4.6.</b> ループ</a> </li> <li><a href='ownership.html'><b>4.7.</b> 所有権</a> </li> <li><a href='references-and-borrowing.html'><b>4.8.</b> 参照と借用</a> </li> <li><a href='lifetimes.html'><b>4.9.</b> ライフタイム</a> </li> <li><a href='mutability.html'><b>4.10.</b> ミュータビリティ</a> </li> <li><a href='structs.html'><b>4.11.</b> 構造体</a> </li> <li><a href='enums.html'><b>4.12.</b> 列挙型</a> </li> <li><a href='match.html'><b>4.13.</b> マッチ</a> </li> <li><a href='patterns.html'><b>4.14.</b> パターン</a> </li> <li><a href='method-syntax.html'><b>4.15.</b> メソッド構文</a> </li> <li><a href='vectors.html'><b>4.16.</b> ベクタ</a> </li> <li><a href='strings.html'><b>4.17.</b> 文字列</a> </li> <li><a href='generics.html'><b>4.18.</b> ジェネリクス</a> </li> <li><a href='traits.html'><b>4.19.</b> トレイト</a> </li> <li><a href='drop.html'><b>4.20.</b> Drop</a> </li> <li><a href='if-let.html'><b>4.21.</b> if let</a> </li> <li><a href='trait-objects.html'><b>4.22.</b> トレイトオブジェクト</a> </li> <li><a href='closures.html'><b>4.23.</b> クロージャ</a> </li> <li><a href='ufcs.html'><b>4.24.</b> 共通の関数呼出構文</a> </li> <li><a href='crates-and-modules.html'><b>4.25.</b> クレートとモジュール</a> </li> <li><a href='const-and-static.html'><b>4.26.</b> `const` と `static`</a> </li> <li><a href='attributes.html'><b>4.27.</b> アトリビュート</a> </li> <li><a href='type-aliases.html'><b>4.28.</b> `type` エイリアス</a> </li> <li><a href='casting-between-types.html'><b>4.29.</b> 型間のキャスト</a> </li> <li><a href='associated-types.html'><b>4.30.</b> 関連型</a> </li> <li><a href='unsized-types.html'><b>4.31.</b> サイズ不定型</a> </li> <li><a href='operators-and-overloading.html'><b>4.32.</b> 演算子とオーバーロード</a> </li> <li><a href='deref-coercions.html'><b>4.33.</b> Derefによる型強制</a> </li> <li><a href='macros.html'><b>4.34.</b> マクロ</a> </li> <li><a href='raw-pointers.html'><b>4.35.</b> 生ポインタ</a> </li> <li><a href='unsafe.html'><b>4.36.</b> `unsafe`</a> </li> </ul> </li> <li><a href='effective-rust.html'><b>5.</b> Effective Rust</a> <ul class='section'> <li><a href='the-stack-and-the-heap.html'><b>5.1.</b> スタックとヒープ</a> </li> <li><a href='testing.html'><b>5.2.</b> テスト</a> </li> <li><a href='conditional-compilation.html'><b>5.3.</b> 条件付きコンパイル</a> </li> <li><a href='documentation.html'><b>5.4.</b> ドキュメント</a> </li> <li><a href='iterators.html'><b>5.5.</b> イテレータ</a> </li> <li><a href='concurrency.html'><b>5.6.</b> 並行性</a> </li> <li><a href='error-handling.html'><b>5.7.</b> エラーハンドリング</a> </li> <li><a href='choosing-your-guarantees.html'><b>5.8.</b> 保証を選ぶ</a> </li> <li><a href='ffi.html'><b>5.9.</b> 他言語関数インターフェース</a> </li> <li><a href='borrow-and-asref.html'><b>5.10.</b> BorrowとAsRef</a> </li> <li><a href='release-channels.html'><b>5.11.</b> リリースチャネル</a> </li> <li><a href='using-rust-without-the-standard-library.html'><b>5.12.</b> 標準ライブラリ無しでRustを使う</a> </li> </ul> </li> <li><a href='nightly-rust.html'><b>6.</b> Nightly Rust</a> <ul class='section'> <li><a href='compiler-plugins.html'><b>6.1.</b> コンパイラプラグイン</a> </li> <li><a href='inline-assembly.html'><b>6.2.</b> インラインアセンブリ</a> </li> <li><a href='no-stdlib.html'><b>6.3.</b> No stdlib</a> </li> <li><a href='intrinsics.html'><b>6.4.</b> Intrinsic</a> </li> <li><a href='lang-items.html'><b>6.5.</b> 言語アイテム</a> </li> <li><a href='advanced-linking.html'><b>6.6.</b> 高度なリンキング</a> </li> <li><a href='benchmark-tests.html'><b>6.7.</b> ベンチマークテスト</a> </li> <li><a href='box-syntax-and-patterns.html'><b>6.8.</b> Box構文とパターン</a> </li> <li><a href='slice-patterns.html'><b>6.9.</b> スライスパターン</a> </li> <li><a href='associated-constants.html'><b>6.10.</b> 関連定数</a> </li> <li><a href='custom-allocators.html'><b>6.11.</b> カスタムアロケータ</a> </li> </ul> </li> <li><a href='glossary.html'><b>7.</b> 用語集</a> </li> <li><a href='syntax-index.html'><b>8.</b> 構文の索引</a> </li> <li><a href='bibliography.html'><b>9.</b> 関係書目</a> </li> </ul> </div> <div id='page-wrapper'> <div id='page'> <blockquote class="header-caveat"> <p> <strong>注意: <a href="https://doc.rust-jp.rs/book-ja/">最新版のドキュメントをご覧ください。</a></strong>この第1版ドキュメントは古くなっており、最新情報が反映されていません。リンク先のドキュメントが現在の Rust の最新のドキュメントです。 </p> </blockquote> <h1 class="title">ループ</h1> <!-- % Loops --> <!-- Rust currently provides three approaches to performing some kind of iterative activity. They are: `loop`, `while` and `for`. Each approach has its own set of uses. --> <p>なんらかの繰り返しを伴う処理に対して、Rust言語は3種類のアプローチ: <code>loop</code>, <code>while</code>, <code>for</code> を提供します。 各アプローチにはそれぞれの使い道があります。</p> <h2 id='loop' class='section-header'><a href='#loop'>loop</a></h2> <!-- The infinite `loop` is the simplest form of loop available in Rust. Using the keyword `loop`, Rust provides a way to loop indefinitely until some terminating statement is reached. Rust's infinite `loop`s look like this: --> <p>Rustで使えるループのなかで最もシンプルな形式が、無限 <code>loop</code> です。Rustのキーワード <code>loop</code> によって、 何らかの終了状態に到達するまでずっとループし続ける手段を提供します。Rustの無限 <code>loop</code> はこのように:</p> <span class='rusttest'>fn main() { loop { println!(&quot;Loop forever!&quot;); } }</span><pre class='rust rust-example-rendered'> <span class='kw'>loop</span> { <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;Loop forever!&quot;</span>); }</pre> <h2 id='while' class='section-header'><a href='#while'>while</a></h2> <!-- Rust also has a `while` loop. It looks like this: --> <p>Rustには <code>while</code> ループもあります。このように:</p> <span class='rusttest'>fn main() { let mut x = 5; // mut x: i32 let mut done = false; // mut done: bool while !done { x += x - 3; println!(&quot;{}&quot;, x); if x % 5 == 0 { done = true; } } }</span><pre class='rust rust-example-rendered'> <span class='kw'>let</span> <span class='kw-2'>mut</span> <span class='ident'>x</span> <span class='op'>=</span> <span class='number'>5</span>; <span class='comment'>// mut x: i32</span> <span class='kw'>let</span> <span class='kw-2'>mut</span> <span class='ident'>done</span> <span class='op'>=</span> <span class='boolvalue'>false</span>; <span class='comment'>// mut done: bool</span> <span class='kw'>while</span> <span class='op'>!</span><span class='ident'>done</span> { <span class='ident'>x</span> <span class='op'>+=</span> <span class='ident'>x</span> <span class='op'>-</span> <span class='number'>3</span>; <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;{}&quot;</span>, <span class='ident'>x</span>); <span class='kw'>if</span> <span class='ident'>x</span> <span class='op'>%</span> <span class='number'>5</span> <span class='op'>==</span> <span class='number'>0</span> { <span class='ident'>done</span> <span class='op'>=</span> <span class='boolvalue'>true</span>; } }</pre> <!-- `while` loops are the correct choice when you’re not sure how many times --> <!-- you need to loop. --> <p>何回ループする必要があるか明らかではない状況で、<code>while</code> ループは正しい選択肢です。</p> <!-- If you need an infinite loop, you may be tempted to write this: --> <p>無限ループの必要があるとき、次のように書きたくなるかもしれません:</p> <span class='rusttest'>fn main() { while true { }</span><pre class='rust rust-example-rendered'> <span class='kw'>while</span> <span class='boolvalue'>true</span> {</pre> <!-- However, `loop` is far better suited to handle this case: --> <p>しかし、こういった場合には <code>loop</code> の方がずっと適しています。</p> <span class='rusttest'>fn main() { loop { }</span><pre class='rust rust-example-rendered'> <span class='kw'>loop</span> {</pre> <!-- Rust’s control-flow analysis treats this construct differently than a `while --> <!-- true`, since we know that it will always loop. In general, the more information --> <!-- we can give to the compiler, the better it can do with safety and code --> <!-- generation, so you should always prefer `loop` when you plan to loop --> <!-- infinitely. --> <p>Rustの制御フロー解析では、必ずループすると知っていることから、これを <code>while true</code> とは異なる構造として扱います。 一般に、コンパイラへ与える情報量が多いほど、安全性が高くより良いコード生成につながるため、 無限にループするつもりなら常に <code>loop</code> を使うべきです。</p> <h2 id='for' class='section-header'><a href='#for'>for</a></h2> <!-- The `for` loop is used to loop a particular number of times. Rust’s `for` loops --> <!-- work a bit differently than in other systems languages, however. Rust’s `for` --> <!-- loop doesn’t look like this “C-style” `for` loop: --> <p>特定の回数だけループするときには <code>for</code> ループを使います。しかし、Rustの <code>for</code> ループは他のシステムプログラミング言語のそれとは少し異なる働きをします。 Rustの <code>for</code> ループは、次のような「Cスタイル」 <code>for</code> ループとは似ていません:</p> <pre><code class="language-c">for (x = 0; x &lt; 10; x++) { printf( &quot;%d\n&quot;, x ); } </code></pre> <!-- Instead, it looks like this: --> <p>代わりに、このように書きます:</p> <span class='rusttest'>fn main() { for x in 0..10 { println!(&quot;{}&quot;, x); // x: i32 } }</span><pre class='rust rust-example-rendered'> <span class='kw'>for</span> <span class='ident'>x</span> <span class='kw'>in</span> <span class='number'>0</span>..<span class='number'>10</span> { <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;{}&quot;</span>, <span class='ident'>x</span>); <span class='comment'>// x: i32</span> }</pre> <!-- In slightly more abstract terms, --> <p>もう少し抽象的な用語を使うと、</p> <span class='rusttest'>fn main() { for var in expression { code } }</span><pre class='rust rust-example-rendered'> <span class='kw'>for</span> <span class='ident'>var</span> <span class='kw'>in</span> <span class='ident'>expression</span> { <span class='ident'>code</span> }</pre> <!-- The expression is an item that can be converted into an [iterator] using --> <!-- [`IntoIterator`]. The iterator gives back a series of elements. Each element is --> <!-- one iteration of the loop. That value is then bound to the name `var`, which is --> <!-- valid for the loop body. Once the body is over, the next value is fetched from --> <!-- the iterator, and we loop another time. When there are no more values, the `for` --> <!-- loop is over. --> <p>式(expression)は<a href="../std/iter/trait.IntoIterator.html"><code>IntoIterator</code></a>を用いて<a href="iterators.html">イテレータ</a>へと変換可能なアイテムです。 イテレータは要素の連なりを返します。それぞれの要素がループの1回の反復になります。 その値は名前 <code>var</code> に束縛されて、ループ本体にて有効になります。いったんループ本体を抜けると、 次の値がイテレータから取り出され、次のループ処理を行います。それ以上の値が存在しない時は、 <code>for</code> ループは終了します。</p> <!-- In our example, `0..10` is an expression that takes a start and an end position, --> <!-- and gives an iterator over those values. The upper bound is exclusive, though, --> <!-- so our loop will print `0` through `9`, not `10`. --> <p>例示では、<code>0..10</code> が開始位置と終了位置をとる式であり、同範囲の値を返すイテレータを与えます。 上界はその値自身を含まないため、このループは <code>0</code> から <code>9</code> までを表示します。 <code>10</code> ではありません。</p> <!-- Rust does not have the “C-style” `for` loop on purpose. Manually controlling --> <!-- each element of the loop is complicated and error prone, even for experienced C --> <!-- developers. --> <p>Rustでは意図的に「Cスタイル」 <code>for</code> ループを持ちません。経験豊富なC開発者でさえ、 ループの各要素を手動制御することは複雑であり、また間違いを犯しやすいのです。</p> <!-- ### Enumerate --> <h3 id='列挙' class='section-header'><a href='#列挙'>列挙</a></h3> <!-- When you need to keep track of how many times you already looped, you can use the `.enumerate()` function. --> <p>ループ中で何回目の繰り返しかを知る必要があるなら、 <code>.enumerate()</code> 関数が使えます。</p> <!-- #### On ranges: --> <h4 id='レンジを対象に' class='section-header'><a href='#レンジを対象に'>レンジを対象に:</a></h4> <span class='rusttest'>fn main() { for (i,j) in (5..10).enumerate() { println!(&quot;i = {} and j = {}&quot;, i, j); } }</span><pre class='rust rust-example-rendered'> <span class='kw'>for</span> (<span class='ident'>i</span>,<span class='ident'>j</span>) <span class='kw'>in</span> (<span class='number'>5</span>..<span class='number'>10</span>).<span class='ident'>enumerate</span>() { <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;i = {} and j = {}&quot;</span>, <span class='ident'>i</span>, <span class='ident'>j</span>); }</pre> <!-- Outputs: --> <p>出力:</p> <pre><code class="language-text">i = 0 and j = 5 i = 1 and j = 6 i = 2 and j = 7 i = 3 and j = 8 i = 4 and j = 9 </code></pre> <!-- Don't forget to add the parentheses around the range. --> <p>レンジを括弧で囲うのを忘れないで下さい。</p> <!-- #### On iterators: --> <h4 id='イテレータを対象に' class='section-header'><a href='#イテレータを対象に'>イテレータを対象に:</a></h4> <span class='rusttest'>fn main() { let lines = &quot;hello\nworld&quot;.lines(); for (linenumber, line) in lines.enumerate() { println!(&quot;{}: {}&quot;, linenumber, line); } }</span><pre class='rust rust-example-rendered'> <span class='kw'>for</span> (<span class='ident'>linenumber</span>, <span class='ident'>line</span>) <span class='kw'>in</span> <span class='ident'>lines</span>.<span class='ident'>enumerate</span>() { <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;{}: {}&quot;</span>, <span class='ident'>linenumber</span>, <span class='ident'>line</span>); }</pre> <!-- Outputs: --> <p>出力:</p> <pre><code class="language-text">0: Content of line one 1: Content of line two 2: Content of line three 3: Content of line four </code></pre> <!-- ## Ending iteration early --> <h2 id='反復の早期終了' class='section-header'><a href='#反復の早期終了'>反復の早期終了</a></h2> <!-- Let’s take a look at that `while` loop we had earlier: --> <p>さきほどの <code>while</code> ループを見てみましょう:</p> <span class='rusttest'>fn main() { let mut x = 5; let mut done = false; while !done { x += x - 3; println!(&quot;{}&quot;, x); if x % 5 == 0 { done = true; } } }</span><pre class='rust rust-example-rendered'> <span class='kw'>let</span> <span class='kw-2'>mut</span> <span class='ident'>x</span> <span class='op'>=</span> <span class='number'>5</span>; <span class='kw'>let</span> <span class='kw-2'>mut</span> <span class='ident'>done</span> <span class='op'>=</span> <span class='boolvalue'>false</span>; <span class='kw'>while</span> <span class='op'>!</span><span class='ident'>done</span> { <span class='ident'>x</span> <span class='op'>+=</span> <span class='ident'>x</span> <span class='op'>-</span> <span class='number'>3</span>; <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;{}&quot;</span>, <span class='ident'>x</span>); <span class='kw'>if</span> <span class='ident'>x</span> <span class='op'>%</span> <span class='number'>5</span> <span class='op'>==</span> <span class='number'>0</span> { <span class='ident'>done</span> <span class='op'>=</span> <span class='boolvalue'>true</span>; } }</pre> <!-- We had to keep a dedicated `mut` boolean variable binding, `done`, to know --> <!-- when we should exit out of the loop. Rust has two keywords to help us with --> <!-- modifying iteration: `break` and `continue`. --> <p>ループをいつ終了すべきか知るため、ここでは専用の <code>mut</code> なboolean変数束縛 <code>done</code> を用いました。 Rustには反復の変更を手伝う2つキーワード: <code>break</code> と <code>continue</code> があります。</p> <!-- In this case, we can write the loop in a better way with `break`: --> <p>この例では、 <code>break</code> を使ってループを記述した方が良いでしょう:</p> <span class='rusttest'>fn main() { let mut x = 5; loop { x += x - 3; println!(&quot;{}&quot;, x); if x % 5 == 0 { break; } } }</span><pre class='rust rust-example-rendered'> <span class='kw'>let</span> <span class='kw-2'>mut</span> <span class='ident'>x</span> <span class='op'>=</span> <span class='number'>5</span>; <span class='kw'>loop</span> { <span class='ident'>x</span> <span class='op'>+=</span> <span class='ident'>x</span> <span class='op'>-</span> <span class='number'>3</span>; <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;{}&quot;</span>, <span class='ident'>x</span>); <span class='kw'>if</span> <span class='ident'>x</span> <span class='op'>%</span> <span class='number'>5</span> <span class='op'>==</span> <span class='number'>0</span> { <span class='kw'>break</span>; } }</pre> <!-- We now loop forever with `loop` and use `break` to break out early. Issuing an explicit `return` statement will also serve to terminate the loop early. --> <p>ここでは <code>loop</code> による永久ループと <code>break</code> による早期脱出を使っています。 明示的な <code>return</code> 文の発行でもループの早期終了になります。</p> <!-- `continue` is similar, but instead of ending the loop, goes to the next --> <!-- iteration. This will only print the odd numbers: --> <p><code>continue</code> も似ていますが、ループを終了させるのではなく、次の反復へと進めます。 これは奇数だけを表示するでしょう:</p> <span class='rusttest'>fn main() { for x in 0..10 { if x % 2 == 0 { continue; } println!(&quot;{}&quot;, x); } }</span><pre class='rust rust-example-rendered'> <span class='kw'>for</span> <span class='ident'>x</span> <span class='kw'>in</span> <span class='number'>0</span>..<span class='number'>10</span> { <span class='kw'>if</span> <span class='ident'>x</span> <span class='op'>%</span> <span class='number'>2</span> <span class='op'>==</span> <span class='number'>0</span> { <span class='kw'>continue</span>; } <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;{}&quot;</span>, <span class='ident'>x</span>); }</pre> <!-- ## Loop labels --> <h2 id='ループラベル' class='section-header'><a href='#ループラベル'>ループラベル</a></h2> <!-- You may also encounter situations where you have nested loops and need to --> <!-- specify which one your `break` or `continue` statement is for. Like most --> <!-- other languages, by default a `break` or `continue` will apply to innermost --> <!-- loop. In a situation where you would like to a `break` or `continue` for one --> <!-- of the outer loops, you can use labels to specify which loop the `break` or --> <!-- `continue` statement applies to. This will only print when both `x` and `y` are --> <!-- odd: --> <p>入れ子のループがあり、<code>break</code> や <code>continue</code> 文がどのループに対応するか指定する必要がある、 そんな状況に出会うこともあるでしょう。大抵の他言語と同様に、 <code>break</code> や <code>continue</code> は最内ループに適用されるのがデフォルトです。 外側のループに <code>break</code> や <code>continue</code> を使いたいという状況では、 <code>break</code> や <code>continue</code> 文の適用先を指定するラベルを使えます。 これは <code>x</code> と <code>y</code> 両方が奇数のときだけ表示を行います:</p> <span class='rusttest'>fn main() { &#39;outer: for x in 0..10 { &#39;inner: for y in 0..10 { // if x % 2 == 0 { continue &#39;outer; } // continues the loop over x if x % 2 == 0 { continue &#39;outer; } // x のループを継続 // if y % 2 == 0 { continue &#39;inner; } // continues the loop over y if y % 2 == 0 { continue &#39;inner; } // y のループを継続 println!(&quot;x: {}, y: {}&quot;, x, y); } } }</span><pre class='rust rust-example-rendered'> <span class='lifetime'>&#39;outer</span>: <span class='kw'>for</span> <span class='ident'>x</span> <span class='kw'>in</span> <span class='number'>0</span>..<span class='number'>10</span> { <span class='lifetime'>&#39;inner</span>: <span class='kw'>for</span> <span class='ident'>y</span> <span class='kw'>in</span> <span class='number'>0</span>..<span class='number'>10</span> { <span class='kw'>if</span> <span class='ident'>x</span> <span class='op'>%</span> <span class='number'>2</span> <span class='op'>==</span> <span class='number'>0</span> { <span class='kw'>continue</span> <span class='lifetime'>&#39;outer</span>; } <span class='comment'>// x のループを継続</span> <span class='kw'>if</span> <span class='ident'>y</span> <span class='op'>%</span> <span class='number'>2</span> <span class='op'>==</span> <span class='number'>0</span> { <span class='kw'>continue</span> <span class='lifetime'>&#39;inner</span>; } <span class='comment'>// y のループを継続</span> <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;x: {}, y: {}&quot;</span>, <span class='ident'>x</span>, <span class='ident'>y</span>); } }</pre> <script type="text/javascript"> window.playgroundUrl = "https://play.rust-lang.org"; </script> <script src='rustbook.js'></script> <script src='playpen.js'></script> </div></div> </body> </html> <|start_filename|>docs/1.9/book/lifetimes.html<|end_filename|> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="generator" content="rustdoc"> <title>ライフタイム</title> <link rel="stylesheet" type="text/css" href="rustbook.css"> <meta name="robots" content="noindex"> </head> <body class="rustdoc"> <!--[if lte IE 8]> <div class="warning"> This old browser is unsupported and will most likely display funky things. </div> <![endif]--> <div id="nav"> <button id="toggle-nav"> <span class="sr-only">Toggle navigation</span> <span class="bar"></span> <span class="bar"></span> <span class="bar"></span> </button> </div> <div id='toc' class='mobile-hidden'> <ul class='chapter'> <li><a href='README.html'><b>1.</b> Introduction</a> </li> <li><a href='getting-started.html'><b>2.</b> はじめる</a> </li> <li><a href='guessing-game.html'><b>3.</b> チュートリアル:数当てゲーム</a> </li> <li><a href='syntax-and-semantics.html'><b>4.</b> シンタックスとセマンティクス</a> <ul class='section'> <li><a href='variable-bindings.html'><b>4.1.</b> 変数束縛</a> </li> <li><a href='functions.html'><b>4.2.</b> 関数</a> </li> <li><a href='primitive-types.html'><b>4.3.</b> プリミティブ型</a> </li> <li><a href='comments.html'><b>4.4.</b> コメント</a> </li> <li><a href='if.html'><b>4.5.</b> if</a> </li> <li><a href='loops.html'><b>4.6.</b> ループ</a> </li> <li><a href='vectors.html'><b>4.7.</b> ベクタ</a> </li> <li><a href='ownership.html'><b>4.8.</b> 所有権</a> </li> <li><a href='references-and-borrowing.html'><b>4.9.</b> 参照と借用</a> </li> <li><a class='active' href='lifetimes.html'><b>4.10.</b> ライフタイム</a> </li> <li><a href='mutability.html'><b>4.11.</b> ミュータビリティ</a> </li> <li><a href='structs.html'><b>4.12.</b> 構造体</a> </li> <li><a href='enums.html'><b>4.13.</b> 列挙型</a> </li> <li><a href='match.html'><b>4.14.</b> マッチ</a> </li> <li><a href='patterns.html'><b>4.15.</b> パターン</a> </li> <li><a href='method-syntax.html'><b>4.16.</b> メソッド構文</a> </li> <li><a href='strings.html'><b>4.17.</b> 文字列</a> </li> <li><a href='generics.html'><b>4.18.</b> ジェネリクス</a> </li> <li><a href='traits.html'><b>4.19.</b> トレイト</a> </li> <li><a href='drop.html'><b>4.20.</b> Drop</a> </li> <li><a href='if-let.html'><b>4.21.</b> if let</a> </li> <li><a href='trait-objects.html'><b>4.22.</b> トレイトオブジェクト</a> </li> <li><a href='closures.html'><b>4.23.</b> クロージャ</a> </li> <li><a href='ufcs.html'><b>4.24.</b> 共通の関数呼出構文</a> </li> <li><a href='crates-and-modules.html'><b>4.25.</b> クレートとモジュール</a> </li> <li><a href='const-and-static.html'><b>4.26.</b> `const` と `static`</a> </li> <li><a href='attributes.html'><b>4.27.</b> アトリビュート</a> </li> <li><a href='type-aliases.html'><b>4.28.</b> `type` エイリアス</a> </li> <li><a href='casting-between-types.html'><b>4.29.</b> 型間のキャスト</a> </li> <li><a href='associated-types.html'><b>4.30.</b> 関連型</a> </li> <li><a href='unsized-types.html'><b>4.31.</b> サイズ不定型</a> </li> <li><a href='operators-and-overloading.html'><b>4.32.</b> 演算子とオーバーロード</a> </li> <li><a href='deref-coercions.html'><b>4.33.</b> Derefによる型強制</a> </li> <li><a href='macros.html'><b>4.34.</b> マクロ</a> </li> <li><a href='raw-pointers.html'><b>4.35.</b> 生ポインタ</a> </li> <li><a href='unsafe.html'><b>4.36.</b> `unsafe`</a> </li> </ul> </li> <li><a href='effective-rust.html'><b>5.</b> Effective Rust</a> <ul class='section'> <li><a href='the-stack-and-the-heap.html'><b>5.1.</b> スタックとヒープ</a> </li> <li><a href='testing.html'><b>5.2.</b> テスト</a> </li> <li><a href='conditional-compilation.html'><b>5.3.</b> 条件付きコンパイル</a> </li> <li><a href='documentation.html'><b>5.4.</b> ドキュメント</a> </li> <li><a href='iterators.html'><b>5.5.</b> イテレータ</a> </li> <li><a href='concurrency.html'><b>5.6.</b> 並行性</a> </li> <li><a href='error-handling.html'><b>5.7.</b> エラーハンドリング</a> </li> <li><a href='choosing-your-guarantees.html'><b>5.8.</b> 保証を選ぶ</a> </li> <li><a href='ffi.html'><b>5.9.</b> 他言語関数インターフェース</a> </li> <li><a href='borrow-and-asref.html'><b>5.10.</b> BorrowとAsRef</a> </li> <li><a href='release-channels.html'><b>5.11.</b> リリースチャネル</a> </li> <li><a href='using-rust-without-the-standard-library.html'><b>5.12.</b> 標準ライブラリ無しでRustを使う</a> </li> </ul> </li> <li><a href='nightly-rust.html'><b>6.</b> Nightly Rust</a> <ul class='section'> <li><a href='compiler-plugins.html'><b>6.1.</b> コンパイラプラグイン</a> </li> <li><a href='inline-assembly.html'><b>6.2.</b> インラインアセンブリ</a> </li> <li><a href='no-stdlib.html'><b>6.3.</b> No stdlib</a> </li> <li><a href='intrinsics.html'><b>6.4.</b> Intrinsic</a> </li> <li><a href='lang-items.html'><b>6.5.</b> 言語アイテム</a> </li> <li><a href='advanced-linking.html'><b>6.6.</b> 高度なリンキング</a> </li> <li><a href='benchmark-tests.html'><b>6.7.</b> ベンチマークテスト</a> </li> <li><a href='box-syntax-and-patterns.html'><b>6.8.</b> Box構文とパターン</a> </li> <li><a href='slice-patterns.html'><b>6.9.</b> スライスパターン</a> </li> <li><a href='associated-constants.html'><b>6.10.</b> 関連定数</a> </li> <li><a href='custom-allocators.html'><b>6.11.</b> カスタムアロケータ</a> </li> </ul> </li> <li><a href='glossary.html'><b>7.</b> 用語集</a> </li> <li><a href='syntax-index.html'><b>8.</b> 構文の索引</a> </li> <li><a href='bibliography.html'><b>9.</b> 関係書目</a> </li> </ul> </div> <div id='page-wrapper'> <div id='page'> <blockquote class="header-caveat"> <p> <strong>注意: <a href="https://doc.rust-jp.rs/book-ja/">最新版のドキュメントをご覧ください。</a></strong>この第1版ドキュメントは古くなっており、最新情報が反映されていません。リンク先のドキュメントが現在の Rust の最新のドキュメントです。 </p> </blockquote> <h1 class="title">ライフタイム</h1> <!-- % Lifetimes --> <!-- This guide is three of three presenting Rust’s ownership system. This is one of --> <!-- Rust’s most unique and compelling features, with which Rust developers should --> <!-- become quite acquainted. Ownership is how Rust achieves its largest goal, --> <!-- memory safety. There are a few distinct concepts, each with its own chapter: --> <p>このガイドはRustの所有権システムの3つの解説の3つ目です。 これはRustの最も独特で注目されている機能です。そして、Rust開発者はそれについて高度に精通しておくべきです。 所有権こそはRustがその最大の目標、メモリ安全性を得るための方法です。 そこにはいくつかの別個の概念があり、各概念が独自の章を持ちます。</p> <!-- * [ownership][ownership], the key concept --> <!-- * [borrowing][borrowing], and their associated feature ‘references’ --> <!-- * lifetimes, which you’re reading now --> <ul> <li>キーとなる概念、 <a href="ownership.html">所有権</a></li> <li><a href="references-and-borrowing.html">借用</a> 、そしてそれらに関連する機能、「参照」</li> <li>今読んでいる、ライフタイム</li> </ul> <!-- These three chapters are related, and in order. You’ll need all three to fully --> <!-- understand the ownership system. --> <p>それらの3つの章は関連していて、それらは順番に並んでいます。 所有権システムを完全に理解するためには、3つ全てを必要とするでしょう。</p> <!-- # Meta --> <h1 id='概論' class='section-header'><a href='#概論'>概論</a></h1> <!-- Before we get to the details, two important notes about the ownership system. --> <p>詳細に入る前に、所有権システムについての2つの重要な注意があります。</p> <!-- Rust has a focus on safety and speed. It accomplishes these goals through many --> <!-- ‘zero-cost abstractions’, which means that in Rust, abstractions cost as little --> <!-- as possible in order to make them work. The ownership system is a prime example --> <!-- of a zero-cost abstraction. All of the analysis we’ll talk about in this guide --> <!-- is _done at compile time_. You do not pay any run-time cost for any of these --> <!-- features. --> <p>Rustは安全性とスピードに焦点を合わせます。 Rustはそれらの目標を、様々な「ゼロコスト抽象化」を通じて成し遂げます。 それは、Rustでは抽象化を機能させるためのコストをできる限り小さくすることを意味します。 所有権システムはゼロコスト抽象化の主な例です。 このガイドの中で話すであろう解析の全ては <em>コンパイル時に行われます</em> 。 それらのどの機能に対しても実行時のコストは全く掛かりません。</p> <!-- However, this system does have a certain cost: learning curve. Many new users --> <!-- to Rust experience something we like to call ‘fighting with the borrow --> <!-- checker’, where the Rust compiler refuses to compile a program that the author --> <!-- thinks is valid. This often happens because the programmer’s mental model of --> <!-- how ownership should work doesn’t match the actual rules that Rust implements. --> <!-- You probably will experience similar things at first. There is good news, --> <!-- however: more experienced Rust developers report that once they work with the --> <!-- rules of the ownership system for a period of time, they fight the borrow --> <!-- checker less and less. --> <p>しかし、このシステムはあるコストを持ちます。それは学習曲線です。 多くのRust入門者は、私たちが「借用チェッカとの戦い」と呼ぶものを経験します。 そこではRustコンパイラが、開発者が正しいと考えるプログラムをコンパイルすることを拒絶します。 所有権がどのように機能するのかについてのプログラマのメンタルモデルがRustの実装する実際のルールにマッチしないため、これはしばしば起きます。 しかし、よいニュースがあります。より経験豊富なRustの開発者は次のことを報告します。 それは、所有権システムのルールと共にしばらく仕事をすれば、借用チェッカと戦うことは次第に少なくなっていく、というものです。</p> <!-- With that in mind, let’s learn about lifetimes. --> <p>それを念頭に置いて、ライフタイムについて学びましょう。</p> <!-- # Lifetimes --> <h1 id='ライフタイム' class='section-header'><a href='#ライフタイム'>ライフタイム</a></h1> <!-- Lending out a reference to a resource that someone else owns can be --> <!-- complicated. For example, imagine this set of operations: --> <p>他の誰かの所有するリソースへの参照の貸付けは複雑になることがあります。 例えば、次のような一連の作業を想像しましょう。</p> <!-- 1. I acquire a handle to some kind of resource. --> <!-- 2. I lend you a reference to the resource. --> <!-- 3. I decide I’m done with the resource, and deallocate it, while you still have --> <!-- your reference. --> <!-- 4. You decide to use the resource. --> <ol> <li>私はある種のリソースへのハンドルを取得する</li> <li>私はあなたにリソースへの参照を貸し付ける</li> <li>私はリソースを使い終わり、それを解放することを決めるが、あなたはそれに対する参照をまだ持っている</li> <li>あなたはリソースを使うことを決める</li> </ol> <!-- Uh oh! Your reference is pointing to an invalid resource. This is called a --> <!-- dangling pointer or ‘use after free’, when the resource is memory. --> <p>あー! あなたの参照は無効なリソースを指しています。 リソースがメモリであるとき、これはダングリングポインタまたは「解放後の使用」と呼ばれます。</p> <!-- To fix this, we have to make sure that step four never happens after step --> <!-- three. The ownership system in Rust does this through a concept called --> <!-- lifetimes, which describe the scope that a reference is valid for. --> <p>これを修正するためには、ステップ3の後にステップ4が絶対に起こらないようにしなければなりません。 Rustでの所有権システムはこれをライフタイムと呼ばれる概念を通じて行います。それは参照の有効なスコープを記述するものです。</p> <!-- When we have a function that takes an argument by reference, we can be --> <!-- implicit or explicit about the lifetime of the reference: --> <p>引数として参照を受け取る関数について、参照のライフタイムを黙示または明示できます。</p> <span class='rusttest'>fn main() { // implicit // 黙示的に fn foo(x: &amp;i32) { } // explicit // 明示的に fn bar&lt;&#39;a&gt;(x: &amp;&#39;a i32) { } }</span><pre class='rust rust-example-rendered'> <span class='comment'>// 黙示的に</span> <span class='kw'>fn</span> <span class='ident'>foo</span>(<span class='ident'>x</span>: <span class='kw-2'>&amp;</span><span class='ident'>i32</span>) { } <span class='comment'>// 明示的に</span> <span class='kw'>fn</span> <span class='ident'>bar</span><span class='op'>&lt;</span><span class='lifetime'>&#39;a</span><span class='op'>&gt;</span>(<span class='ident'>x</span>: <span class='kw-2'>&amp;</span><span class='lifetime'>&#39;a</span> <span class='ident'>i32</span>) { }</pre> <!-- The `'a` reads ‘the lifetime a’. Technically, every reference has some lifetime --> <!-- associated with it, but the compiler lets you elide (i.e. omit, see --> <!-- ["Lifetime Elision"][lifetime-elision] below) them in common cases. --> <!-- Before we get to that, though, let’s break the explicit example down: --> <p><code>&#39;a</code>は「ライフタイムa」と読みます。 技術的には参照は全てそれに関連するライフタイムを持ちますが、一般的な場合にはコンパイラがそれらを省略してもよいように計らってくれます(つまり、「省略」できるということです。 <a href="#lifetime-elision">「ライフタイムの省略」</a> 以下を見ましょう)。 しかし、それに入る前に、明示の例を分解しましょう。</p> <span class='rusttest'>fn main() { fn bar&lt;&#39;a&gt;(...) }</span><pre class='rust rust-example-rendered'> <span class='kw'>fn</span> <span class='ident'>bar</span><span class='op'>&lt;</span><span class='lifetime'>&#39;a</span><span class='op'>&gt;</span>(...)</pre> <!-- We previously talked a little about [function syntax][functions], but we didn’t --> <!-- discuss the `<>`s after a function’s name. A function can have ‘generic --> <!-- parameters’ between the `<>`s, of which lifetimes are one kind. We’ll discuss --> <!-- other kinds of generics [later in the book][generics], but for now, let’s --> <!-- focus on the lifetimes aspect. --> <p><a href="functions.html">関数の構文</a> については前に少し話しました。しかし、関数名の後の <code>&lt;&gt;</code> については議論しませんでした。 関数は <code>&lt;&gt;</code> の間に「ジェネリックパラメータ」を持つことができ、ライフタイムはその一種です。 他の種類のジェネリクスについては <a href="generics.html">本書の後の方</a> で議論しますが、とりあえず、ライフタイムの面に焦点を合わせましょう。</p> <!-- We use `<>` to declare our lifetimes. This says that `bar` has one lifetime, --> <!-- `'a`. If we had two reference parameters, it would look like this: --> <p><code>&lt;&gt;</code> はライフタイムを宣言するために使われます。 これは <code>bar</code> が1つのライフタイム <code>&#39;a</code> を持つことを意味します。 もし2つの参照引数があれば、それは次のような感じになるでしょう。</p> <span class='rusttest'>fn main() { fn bar&lt;&#39;a, &#39;b&gt;(...) }</span><pre class='rust rust-example-rendered'> <span class='kw'>fn</span> <span class='ident'>bar</span><span class='op'>&lt;</span><span class='lifetime'>&#39;a</span>, <span class='lifetime'>&#39;b</span><span class='op'>&gt;</span>(...)</pre> <!-- Then in our parameter list, we use the lifetimes we’ve named: --> <p>そして引数リストでは、名付けたライフタイムを使います。</p> <span class='rusttest'>fn main() { ...(x: &amp;&#39;a i32) }</span><pre class='rust rust-example-rendered'> ...(<span class='ident'>x</span>: <span class='kw-2'>&amp;</span><span class='lifetime'>&#39;a</span> <span class='ident'>i32</span>)</pre> <!-- If we wanted a `&mut` reference, we’d do this: --> <p>もし <code>&amp;mut</code> 参照が欲しいのならば、次のようにします。</p> <span class='rusttest'>fn main() { ...(x: &amp;&#39;a mut i32) }</span><pre class='rust rust-example-rendered'> ...(<span class='ident'>x</span>: <span class='kw-2'>&amp;</span><span class='lifetime'>&#39;a</span> <span class='kw-2'>mut</span> <span class='ident'>i32</span>)</pre> <!-- If you compare `&mut i32` to `&'a mut i32`, they’re the same, it’s that --> <!-- the lifetime `'a` has snuck in between the `&` and the `mut i32`. We read `&mut --> <!-- i32` as ‘a mutable reference to an `i32`’ and `&'a mut i32` as ‘a mutable --> <!-- reference to an `i32` with the lifetime `'a`’. --> <p>もし <code>&amp;mut i32</code> を <code>&amp;&#39;a mut i32</code> と比較するならば、それらは同じです。それはライフタイム <code>&#39;a</code> が <code>&amp;</code> と <code>mut i32</code> の間にこっそり入っているだけです。 <code>&amp;mut i32</code> は「 <code>i32</code> へのミュータブルな参照」のように読み、 <code>&amp;&#39;a mut i32</code> は「ライフタイム <code>&#39;a</code> を持つ <code>i32</code> へのミュータブルな参照」のように読みます。</p> <!-- # In `struct`s --> <h1 id='struct-の中' class='section-header'><a href='#struct-の中'><code>struct</code> の中</a></h1> <!-- You’ll also need explicit lifetimes when working with [`struct`][structs]s that --> <!-- contain references: --> <p>参照を含む <a href="structs.html"><code>struct</code></a> を使うときにも、明示的なライフタイムを必要とするでしょう。</p> <span class='rusttest'>struct Foo&lt;&#39;a&gt; { x: &amp;&#39;a i32, } fn main() { // let y = &amp;5; // this is the same as `let _y = 5; let y = &amp;_y;` let y = &amp;5; // これは`let _y = 5; let y = &amp;_y;`と同じ let f = Foo { x: y }; println!(&quot;{}&quot;, f.x); } </span><pre class='rust rust-example-rendered'> <span class='kw'>struct</span> <span class='ident'>Foo</span><span class='op'>&lt;</span><span class='lifetime'>&#39;a</span><span class='op'>&gt;</span> { <span class='ident'>x</span>: <span class='kw-2'>&amp;</span><span class='lifetime'>&#39;a</span> <span class='ident'>i32</span>, } <span class='kw'>fn</span> <span class='ident'>main</span>() { <span class='kw'>let</span> <span class='ident'>y</span> <span class='op'>=</span> <span class='kw-2'>&amp;</span><span class='number'>5</span>; <span class='comment'>// これは`let _y = 5; let y = &amp;_y;`と同じ</span> <span class='kw'>let</span> <span class='ident'>f</span> <span class='op'>=</span> <span class='ident'>Foo</span> { <span class='ident'>x</span>: <span class='ident'>y</span> }; <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;{}&quot;</span>, <span class='ident'>f</span>.<span class='ident'>x</span>); }</pre> <!-- As you can see, `struct`s can also have lifetimes. In a similar way to functions, --> <p>見てのとおり、 <code>struct</code> もライフタイムを持てます。 これは関数と同じ方法です。</p> <span class='rusttest'>fn main() { struct Foo&lt;&#39;a&gt; { x: &amp;&#39;a i32, } }</span><pre class='rust rust-example-rendered'> <span class='kw'>struct</span> <span class='ident'>Foo</span><span class='op'>&lt;</span><span class='lifetime'>&#39;a</span><span class='op'>&gt;</span> {</pre> <!-- declares a lifetime, and --> <p>このようにライフタイムを宣言します。</p> <span class='rusttest'>fn main() { struct Foo&lt;&#39;a&gt; { x: &amp;&#39;a i32, } }</span><pre class='rust rust-example-rendered'> <span class='ident'>x</span>: <span class='kw-2'>&amp;</span><span class='lifetime'>&#39;a</span> <span class='ident'>i32</span>,</pre> <!-- uses it. So why do we need a lifetime here? We need to ensure that any reference --> <!-- to a `Foo` cannot outlive the reference to an `i32` it contains. --> <p>そしてそれを使います。 それではなぜここでライフタイムを必要とするのでしょうか。 <code>Foo</code> への全ての参照がそれの含む <code>i32</code> への参照より長い間有効にはならないことを保証する必要があるからです。</p> <!-- ## `impl` blocks --> <h2 id='impl-ブロック' class='section-header'><a href='#impl-ブロック'><code>impl</code> ブロック</a></h2> <!-- Let’s implement a method on `Foo`: --> <p><code>Foo</code> に次のようなメソッドを実装しましょう。</p> <span class='rusttest'>struct Foo&lt;&#39;a&gt; { x: &amp;&#39;a i32, } impl&lt;&#39;a&gt; Foo&lt;&#39;a&gt; { fn x(&amp;self) -&gt; &amp;&#39;a i32 { self.x } } fn main() { // let y = &amp;5; // this is the same as `let _y = 5; let y = &amp;_y;` let y = &amp;5; // これは`let _y = 5; let y = &amp;_y;`と同じ let f = Foo { x: y }; println!(&quot;x is: {}&quot;, f.x()); } </span><pre class='rust rust-example-rendered'> <span class='kw'>struct</span> <span class='ident'>Foo</span><span class='op'>&lt;</span><span class='lifetime'>&#39;a</span><span class='op'>&gt;</span> { <span class='ident'>x</span>: <span class='kw-2'>&amp;</span><span class='lifetime'>&#39;a</span> <span class='ident'>i32</span>, } <span class='kw'>impl</span><span class='op'>&lt;</span><span class='lifetime'>&#39;a</span><span class='op'>&gt;</span> <span class='ident'>Foo</span><span class='op'>&lt;</span><span class='lifetime'>&#39;a</span><span class='op'>&gt;</span> { <span class='kw'>fn</span> <span class='ident'>x</span>(<span class='kw-2'>&amp;</span><span class='self'>self</span>) <span class='op'>-&gt;</span> <span class='kw-2'>&amp;</span><span class='lifetime'>&#39;a</span> <span class='ident'>i32</span> { <span class='self'>self</span>.<span class='ident'>x</span> } } <span class='kw'>fn</span> <span class='ident'>main</span>() { <span class='kw'>let</span> <span class='ident'>y</span> <span class='op'>=</span> <span class='kw-2'>&amp;</span><span class='number'>5</span>; <span class='comment'>// これは`let _y = 5; let y = &amp;_y;`と同じ</span> <span class='kw'>let</span> <span class='ident'>f</span> <span class='op'>=</span> <span class='ident'>Foo</span> { <span class='ident'>x</span>: <span class='ident'>y</span> }; <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;x is: {}&quot;</span>, <span class='ident'>f</span>.<span class='ident'>x</span>()); }</pre> <!-- As you can see, we need to declare a lifetime for `Foo` in the `impl` line. We repeat --> <!-- `'a` twice, like on functions: `impl<'a>` defines a lifetime `'a`, and `Foo<'a>` --> <!-- uses it. --> <p>見てのとおり、 <code>Foo</code> のライフタイムは <code>impl</code> 行で宣言する必要があります。 関数のときのように <code>&#39;a</code> は2回繰り返されます。つまり、 <code>impl&lt;&#39;a&gt;</code> はライフタイム <code>&#39;a</code> を定義し、 <code>Foo&lt;&#39;a&gt;</code> はそれを使うのです。</p> <!-- ## Multiple lifetimes --> <h2 id='複数のライフタイム' class='section-header'><a href='#複数のライフタイム'>複数のライフタイム</a></h2> <!-- If you have multiple references, you can use the same lifetime multiple times: --> <p>もし複数の参照があるなら、同じライフタイムを何度でも使えます。</p> <span class='rusttest'>fn main() { fn x_or_y&lt;&#39;a&gt;(x: &amp;&#39;a str, y: &amp;&#39;a str) -&gt; &amp;&#39;a str { x } }</span><pre class='rust rust-example-rendered'> <span class='kw'>fn</span> <span class='ident'>x_or_y</span><span class='op'>&lt;</span><span class='lifetime'>&#39;a</span><span class='op'>&gt;</span>(<span class='ident'>x</span>: <span class='kw-2'>&amp;</span><span class='lifetime'>&#39;a</span> <span class='ident'>str</span>, <span class='ident'>y</span>: <span class='kw-2'>&amp;</span><span class='lifetime'>&#39;a</span> <span class='ident'>str</span>) <span class='op'>-&gt;</span> <span class='kw-2'>&amp;</span><span class='lifetime'>&#39;a</span> <span class='ident'>str</span> {</pre> <!-- This says that `x` and `y` both are alive for the same scope, and that the --> <!-- return value is also alive for that scope. If you wanted `x` and `y` to have --> <!-- different lifetimes, you can use multiple lifetime parameters: --> <p>これは <code>x</code> と <code>y</code> が両方とも同じスコープで有効であり、戻り値もそのスコープで有効であることを示します。 もし <code>x</code> と <code>y</code> に違うライフタイムを持たせたいのであれば、複数のライフタイムパラメータを使えます。</p> <span class='rusttest'>fn main() { fn x_or_y&lt;&#39;a, &#39;b&gt;(x: &amp;&#39;a str, y: &amp;&#39;b str) -&gt; &amp;&#39;a str { x } }</span><pre class='rust rust-example-rendered'> <span class='kw'>fn</span> <span class='ident'>x_or_y</span><span class='op'>&lt;</span><span class='lifetime'>&#39;a</span>, <span class='lifetime'>&#39;b</span><span class='op'>&gt;</span>(<span class='ident'>x</span>: <span class='kw-2'>&amp;</span><span class='lifetime'>&#39;a</span> <span class='ident'>str</span>, <span class='ident'>y</span>: <span class='kw-2'>&amp;</span><span class='lifetime'>&#39;b</span> <span class='ident'>str</span>) <span class='op'>-&gt;</span> <span class='kw-2'>&amp;</span><span class='lifetime'>&#39;a</span> <span class='ident'>str</span> {</pre> <!-- In this example, `x` and `y` have different valid scopes, but the return value --> <!-- has the same lifetime as `x`. --> <p>この例では <code>x</code> と <code>y</code> が異なる有効なスコープを持ちますが、戻り値は <code>x</code> と同じライフタイムを持ちます。</p> <!-- ## Thinking in scopes --> <h2 id='スコープの考え方' class='section-header'><a href='#スコープの考え方'>スコープの考え方</a></h2> <!-- A way to think about lifetimes is to visualize the scope that a reference is --> <!-- valid for. For example: --> <p>ライフタイムについて考えるには、参照の有効なスコープを可視化することです。 例えばこうです。</p> <span class='rusttest'>fn main() { // let y = &amp;5; // -+ y goes into scope // // | // // stuff // | // // | // } // -+ y goes out of scope let y = &amp;5; // -+ yがスコープに入る // | // stuff // | // | } // -+ yがスコープから出る </span><pre class='rust rust-example-rendered'> <span class='kw'>fn</span> <span class='ident'>main</span>() { <span class='kw'>let</span> <span class='ident'>y</span> <span class='op'>=</span> <span class='kw-2'>&amp;</span><span class='number'>5</span>; <span class='comment'>// -+ yがスコープに入る</span> <span class='comment'>// |</span> <span class='comment'>// stuff // |</span> <span class='comment'>// |</span> } <span class='comment'>// -+ yがスコープから出る</span></pre> <!-- Adding in our `Foo`: --> <p><code>Foo</code> を追加するとこうなります。</p> <span class='rusttest'>struct Foo&lt;&#39;a&gt; { x: &amp;&#39;a i32, } fn main() { // let y = &amp;5; // -+ y goes into scope // let f = Foo { x: y }; // -+ f goes into scope // // stuff // | // // | // } // -+ f and y go out of scope let y = &amp;5; // -+ yがスコープに入る let f = Foo { x: y }; // -+ fがスコープに入る // stuff // | // | } // -+ fとyがスコープから出る </span><pre class='rust rust-example-rendered'> <span class='kw'>struct</span> <span class='ident'>Foo</span><span class='op'>&lt;</span><span class='lifetime'>&#39;a</span><span class='op'>&gt;</span> { <span class='ident'>x</span>: <span class='kw-2'>&amp;</span><span class='lifetime'>&#39;a</span> <span class='ident'>i32</span>, } <span class='kw'>fn</span> <span class='ident'>main</span>() { <span class='kw'>let</span> <span class='ident'>y</span> <span class='op'>=</span> <span class='kw-2'>&amp;</span><span class='number'>5</span>; <span class='comment'>// -+ yがスコープに入る</span> <span class='kw'>let</span> <span class='ident'>f</span> <span class='op'>=</span> <span class='ident'>Foo</span> { <span class='ident'>x</span>: <span class='ident'>y</span> }; <span class='comment'>// -+ fがスコープに入る</span> <span class='comment'>// stuff // |</span> <span class='comment'>// |</span> } <span class='comment'>// -+ fとyがスコープから出る</span></pre> <!-- Our `f` lives within the scope of `y`, so everything works. What if it didn’t? --> <!-- This code won’t work: --> <p><code>f</code> は <code>y</code> のスコープの中で有効なので、全て動きます。 もしそれがそうではなかったらどうでしょうか。 このコードは動かないでしょう。</p> <span class='rusttest'>struct Foo&lt;&#39;a&gt; { x: &amp;&#39;a i32, } fn main() { // let x; // -+ x goes into scope // // | // { // | // let y = &amp;5; // ---+ y goes into scope // let f = Foo { x: y }; // ---+ f goes into scope // x = &amp;f.x; // | | error here // } // ---+ f and y go out of scope // // | // println!(&quot;{}&quot;, x); // | // } // -+ x goes out of scope let x; // -+ xがスコープに入る // | { // | let y = &amp;5; // ---+ yがスコープに入る let f = Foo { x: y }; // ---+ fがスコープに入る x = &amp;f.x; // | | ここでエラーが起きる } // ---+ fとyがスコープから出る // | println!(&quot;{}&quot;, x); // | } // -+ xがスコープから出る </span><pre class='rust rust-example-rendered'> <span class='kw'>struct</span> <span class='ident'>Foo</span><span class='op'>&lt;</span><span class='lifetime'>&#39;a</span><span class='op'>&gt;</span> { <span class='ident'>x</span>: <span class='kw-2'>&amp;</span><span class='lifetime'>&#39;a</span> <span class='ident'>i32</span>, } <span class='kw'>fn</span> <span class='ident'>main</span>() { <span class='kw'>let</span> <span class='ident'>x</span>; <span class='comment'>// -+ xがスコープに入る</span> <span class='comment'>// |</span> { <span class='comment'>// |</span> <span class='kw'>let</span> <span class='ident'>y</span> <span class='op'>=</span> <span class='kw-2'>&amp;</span><span class='number'>5</span>; <span class='comment'>// ---+ yがスコープに入る</span> <span class='kw'>let</span> <span class='ident'>f</span> <span class='op'>=</span> <span class='ident'>Foo</span> { <span class='ident'>x</span>: <span class='ident'>y</span> }; <span class='comment'>// ---+ fがスコープに入る</span> <span class='ident'>x</span> <span class='op'>=</span> <span class='kw-2'>&amp;</span><span class='ident'>f</span>.<span class='ident'>x</span>; <span class='comment'>// | | ここでエラーが起きる</span> } <span class='comment'>// ---+ fとyがスコープから出る</span> <span class='comment'>// |</span> <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;{}&quot;</span>, <span class='ident'>x</span>); <span class='comment'>// |</span> } <span class='comment'>// -+ xがスコープから出る</span></pre> <!-- Whew! As you can see here, the scopes of `f` and `y` are smaller than the scope --> <!-- of `x`. But when we do `x = &f.x`, we make `x` a reference to something that’s --> <!-- about to go out of scope. --> <p>ふう! 見てのとおり、ここでは <code>f</code> と <code>y</code> のスコープは <code>x</code> のスコープよりも小さいです。 しかし <code>x = &amp;f.x</code> を実行するとき、 <code>x</code> をまさにスコープから外れた何かの参照にしてしまいます。</p> <!-- Named lifetimes are a way of giving these scopes a name. Giving something a --> <!-- name is the first step towards being able to talk about it. --> <p>名前の付いたライフタイムはそれらのスコープに名前を与える方法です。 何かに名前を与えることはそれについて話をできるようになるための最初のステップです。</p> <!-- ## 'static --> <h2 id='static' class='section-header'><a href='#static'>&#39;static</a></h2> <!-- The lifetime named ‘static’ is a special lifetime. It signals that something --> <!-- has the lifetime of the entire program. Most Rust programmers first come across --> <!-- `'static` when dealing with strings: --> <p>「static」と名付けられたライフタイムは特別なライフタイムです。 それは何かがプログラム全体に渡るライフタイムを持つことを示します。 ほとんどのRustのプログラマが最初に <code>&#39;static</code> に出会うのは、文字列を扱うときです。</p> <span class='rusttest'>fn main() { let x: &amp;&#39;static str = &quot;Hello, world.&quot;; }</span><pre class='rust rust-example-rendered'> <span class='kw'>let</span> <span class='ident'>x</span>: <span class='kw-2'>&amp;</span><span class='lifetime'>&#39;static</span> <span class='ident'>str</span> <span class='op'>=</span> <span class='string'>&quot;Hello, world.&quot;</span>;</pre> <!-- String literals have the type `&'static str` because the reference is always --> <!-- alive: they are baked into the data segment of the final binary. Another --> <!-- example are globals: --> <p>文字列リテラルは <code>&amp;&#39;static str</code> 型を持ちます。なぜなら、参照が常に有効だからです。それらは最終的なバイナリのデータセグメントに焼き付けられます。 もう1つの例はグローバルです。</p> <span class='rusttest'>fn main() { static FOO: i32 = 5; let x: &amp;&#39;static i32 = &amp;FOO; }</span><pre class='rust rust-example-rendered'> <span class='kw'>static</span> <span class='ident'>FOO</span>: <span class='ident'>i32</span> <span class='op'>=</span> <span class='number'>5</span>; <span class='kw'>let</span> <span class='ident'>x</span>: <span class='kw-2'>&amp;</span><span class='lifetime'>&#39;static</span> <span class='ident'>i32</span> <span class='op'>=</span> <span class='kw-2'>&amp;</span><span class='ident'>FOO</span>;</pre> <!-- This adds an `i32` to the data segment of the binary, and `x` is a reference --> <!-- to it. --> <p>これはバイナリのデータセグメントに <code>i32</code> を追加します。そして、 <code>x</code> はそれへの参照です。</p> <!-- ## Lifetime Elision --> <h2 id='ライフタイムの省略' class='section-header'><a href='#ライフタイムの省略'>ライフタイムの省略</a></h2> <!-- Rust supports powerful local type inference in the bodies of functions but not in their item signatures. --> <!-- It's forbidden to allow reasoning about types based on the item signature alone. --> <!-- However, for ergonomic reasons, a very restricted secondary inference algorithm called --> <!-- “lifetime elision” does apply when judging lifetimes. Lifetime elision is concerned solely to infer --> <!-- lifetime parameters using three easily memorizable and unambiguous rules. This means lifetime elision --> <!-- acts as a shorthand for writing an item signature, while not hiding --> <!-- away the actual types involved as full local inference would if applied to it. --> <p>Rustは関数本体については強力なローカル型推論をサポートしますが、要素のシグネチャについては別です。 そこで型推論が許されていないのは、要素のシグネチャだけで型がわかるようにするためです。 とはいえ、エルゴノミック(人間にとっての扱いやすさ)上の理由により、ライフタイムを決定する際には、「ライフタイムの省略」と呼ばれる、非常に制限された第二の推論アルゴリズムが適用されます。 ライフタイムの推論は、ライフタイムパラメータの推論だけに関係しており、たった3つの覚えやすく明確なルールに従います。 ライフタイムの省略は要素のシグネチャを短く書けることを意味しますが、ローカル型推論が適用されるときのように実際の型を隠すことはできません。</p> <!-- When talking about lifetime elision, we use the term *input lifetime* and --> <!-- *output lifetime*. An *input lifetime* is a lifetime associated with a parameter --> <!-- of a function, and an *output lifetime* is a lifetime associated with the return --> <!-- value of a function. For example, this function has an input lifetime: --> <p>ライフタイムの省略について話すときには、 <em>入力ライフタイム</em> と <em>出力ライフタイム</em> という用語を使います。 <em>入力ライフタイム</em> は関数の引数に関連するライフタイムで、 <em>出力ライフタイム</em> は関数の戻り値に関連するライフタイムです。 例えば、次の関数は入力ライフタイムを持ちます。</p> <span class='rusttest'>fn main() { fn foo&lt;&#39;a&gt;(bar: &amp;&#39;a str) }</span><pre class='rust rust-example-rendered'> <span class='kw'>fn</span> <span class='ident'>foo</span><span class='op'>&lt;</span><span class='lifetime'>&#39;a</span><span class='op'>&gt;</span>(<span class='ident'>bar</span>: <span class='kw-2'>&amp;</span><span class='lifetime'>&#39;a</span> <span class='ident'>str</span>)</pre> <!-- This one has an output lifetime: --> <p>この関数は出力ライフタイムを持ちます。</p> <span class='rusttest'>fn main() { fn foo&lt;&#39;a&gt;() -&gt; &amp;&#39;a str }</span><pre class='rust rust-example-rendered'> <span class='kw'>fn</span> <span class='ident'>foo</span><span class='op'>&lt;</span><span class='lifetime'>&#39;a</span><span class='op'>&gt;</span>() <span class='op'>-&gt;</span> <span class='kw-2'>&amp;</span><span class='lifetime'>&#39;a</span> <span class='ident'>str</span></pre> <!-- This one has a lifetime in both positions: --> <p>この関数は両方の位置のライフタイムを持ちます。</p> <span class='rusttest'>fn main() { fn foo&lt;&#39;a&gt;(bar: &amp;&#39;a str) -&gt; &amp;&#39;a str }</span><pre class='rust rust-example-rendered'> <span class='kw'>fn</span> <span class='ident'>foo</span><span class='op'>&lt;</span><span class='lifetime'>&#39;a</span><span class='op'>&gt;</span>(<span class='ident'>bar</span>: <span class='kw-2'>&amp;</span><span class='lifetime'>&#39;a</span> <span class='ident'>str</span>) <span class='op'>-&gt;</span> <span class='kw-2'>&amp;</span><span class='lifetime'>&#39;a</span> <span class='ident'>str</span></pre> <!-- Here are the three rules: --> <p>3つのルールを以下に示します。</p> <!-- * Each elided lifetime in a function’s arguments becomes a distinct lifetime --> <!-- parameter. --> <ul> <li>関数の引数の中の省略された各ライフタイムは、互いに異なるライフタイムパラメータになる</li> </ul> <!-- * If there is exactly one input lifetime, elided or not, that lifetime is --> <!-- assigned to all elided lifetimes in the return values of that function. --> <ul> <li>もし入力ライフタイムが1つだけならば、省略されたかどうかにかかわらず、そのライフタイムはその関数の戻り値の中の省略されたライフタイム全てに割り当てられる</li> </ul> <!-- * If there are multiple input lifetimes, but one of them is `&self` or `&mut --> <!-- self`, the lifetime of `self` is assigned to all elided output lifetimes. --> <ul> <li>もし入力ライフタイムが複数あるが、その1つが <code>&amp;self</code> または <code>&amp;mut self</code> であれば、 <code>self</code> のライフタイムは省略された出力ライフタイム全てに割り当てられる</li> </ul> <!-- Otherwise, it is an error to elide an output lifetime. --> <p>そうでないときは、出力ライフタイムの省略はエラーです。</p> <!-- ### Examples --> <h1 id='例' class='section-header'><a href='#例'>例</a></h1> <!-- Here are some examples of functions with elided lifetimes. We’ve paired each --> <!-- example of an elided lifetime with its expanded form. --> <p>ここにライフタイムの省略された関数の例を示します。 省略されたライフタイムの各例をその展開した形式と組み合わせています。</p> <span class='rusttest'>fn main() { // fn print(s: &amp;str); // elided // fn print&lt;&#39;a&gt;(s: &amp;&#39;a str); // expanded fn print(s: &amp;str); // 省略された形 fn print&lt;&#39;a&gt;(s: &amp;&#39;a str); // 展開した形 // fn debug(lvl: u32, s: &amp;str); // elided // fn debug&lt;&#39;a&gt;(lvl: u32, s: &amp;&#39;a str); // expanded fn debug(lvl: u32, s: &amp;str); // 省略された形 fn debug&lt;&#39;a&gt;(lvl: u32, s: &amp;&#39;a str); // 展開された形 // In the preceding example, `lvl` doesn’t need a lifetime because it’s not a // reference (`&amp;`). Only things relating to references (such as a `struct` // which contains a reference) need lifetimes. // 前述の例では`lvl`はライフタイムを必要としません。なぜなら、それは参照(`&amp;`) // ではないからです。(参照を含む`struct`のような)参照に関係するものだけがライ // フタイムを必要とします。 // fn substr(s: &amp;str, until: u32) -&gt; &amp;str; // elided // fn substr&lt;&#39;a&gt;(s: &amp;&#39;a str, until: u32) -&gt; &amp;&#39;a str; // expanded fn substr(s: &amp;str, until: u32) -&gt; &amp;str; // 省略された形 fn substr&lt;&#39;a&gt;(s: &amp;&#39;a str, until: u32) -&gt; &amp;&#39;a str; // 展開された形 // fn get_str() -&gt; &amp;str; // ILLEGAL, no inputs fn get_str() -&gt; &amp;str; // 不正。入力がない // fn frob(s: &amp;str, t: &amp;str) -&gt; &amp;str; // ILLEGAL, two inputs // fn frob&lt;&#39;a, &#39;b&gt;(s: &amp;&#39;a str, t: &amp;&#39;b str) -&gt; &amp;str; // Expanded: Output lifetime is ambiguous fn frob(s: &amp;str, t: &amp;str) -&gt; &amp;str; // 不正。入力が2つある fn frob&lt;&#39;a, &#39;b&gt;(s: &amp;&#39;a str, t: &amp;&#39;b str) -&gt; &amp;str; // 展開された形。出力ライフタイムが決まらない // fn get_mut(&amp;mut self) -&gt; &amp;mut T; // elided // fn get_mut&lt;&#39;a&gt;(&amp;&#39;a mut self) -&gt; &amp;&#39;a mut T; // expanded fn get_mut(&amp;mut self) -&gt; &amp;mut T; // 省略された形 fn get_mut&lt;&#39;a&gt;(&amp;&#39;a mut self) -&gt; &amp;&#39;a mut T; // 展開された形 // fn args&lt;T: ToCStr&gt;(&amp;mut self, args: &amp;[T]) -&gt; &amp;mut Command; // elided // fn args&lt;&#39;a, &#39;b, T: ToCStr&gt;(&amp;&#39;a mut self, args: &amp;&#39;b [T]) -&gt; &amp;&#39;a mut Command; // expanded fn args&lt;T: ToCStr&gt;(&amp;mut self, args: &amp;[T]) -&gt; &amp;mut Command; // 省略された形 fn args&lt;&#39;a, &#39;b, T: ToCStr&gt;(&amp;&#39;a mut self, args: &amp;&#39;b [T]) -&gt; &amp;&#39;a mut Command; // 展開された形 // fn new(buf: &amp;mut [u8]) -&gt; BufWriter; // elided // fn new&lt;&#39;a&gt;(buf: &amp;&#39;a mut [u8]) -&gt; BufWriter&lt;&#39;a&gt;; // expanded fn new(buf: &amp;mut [u8]) -&gt; BufWriter; // 省略された形 fn new&lt;&#39;a&gt;(buf: &amp;&#39;a mut [u8]) -&gt; BufWriter&lt;&#39;a&gt;; // 展開された形 }</span><pre class='rust rust-example-rendered'> <span class='kw'>fn</span> <span class='ident'>print</span>(<span class='ident'>s</span>: <span class='kw-2'>&amp;</span><span class='ident'>str</span>); <span class='comment'>// 省略された形</span> <span class='kw'>fn</span> <span class='ident'>print</span><span class='op'>&lt;</span><span class='lifetime'>&#39;a</span><span class='op'>&gt;</span>(<span class='ident'>s</span>: <span class='kw-2'>&amp;</span><span class='lifetime'>&#39;a</span> <span class='ident'>str</span>); <span class='comment'>// 展開した形</span> <span class='kw'>fn</span> <span class='ident'>debug</span>(<span class='ident'>lvl</span>: <span class='ident'>u32</span>, <span class='ident'>s</span>: <span class='kw-2'>&amp;</span><span class='ident'>str</span>); <span class='comment'>// 省略された形</span> <span class='kw'>fn</span> <span class='ident'>debug</span><span class='op'>&lt;</span><span class='lifetime'>&#39;a</span><span class='op'>&gt;</span>(<span class='ident'>lvl</span>: <span class='ident'>u32</span>, <span class='ident'>s</span>: <span class='kw-2'>&amp;</span><span class='lifetime'>&#39;a</span> <span class='ident'>str</span>); <span class='comment'>// 展開された形</span> <span class='comment'>// 前述の例では`lvl`はライフタイムを必要としません。なぜなら、それは参照(`&amp;`)</span> <span class='comment'>// ではないからです。(参照を含む`struct`のような)参照に関係するものだけがライ</span> <span class='comment'>// フタイムを必要とします。</span> <span class='kw'>fn</span> <span class='ident'>substr</span>(<span class='ident'>s</span>: <span class='kw-2'>&amp;</span><span class='ident'>str</span>, <span class='ident'>until</span>: <span class='ident'>u32</span>) <span class='op'>-&gt;</span> <span class='kw-2'>&amp;</span><span class='ident'>str</span>; <span class='comment'>// 省略された形</span> <span class='kw'>fn</span> <span class='ident'>substr</span><span class='op'>&lt;</span><span class='lifetime'>&#39;a</span><span class='op'>&gt;</span>(<span class='ident'>s</span>: <span class='kw-2'>&amp;</span><span class='lifetime'>&#39;a</span> <span class='ident'>str</span>, <span class='ident'>until</span>: <span class='ident'>u32</span>) <span class='op'>-&gt;</span> <span class='kw-2'>&amp;</span><span class='lifetime'>&#39;a</span> <span class='ident'>str</span>; <span class='comment'>// 展開された形</span> <span class='kw'>fn</span> <span class='ident'>get_str</span>() <span class='op'>-&gt;</span> <span class='kw-2'>&amp;</span><span class='ident'>str</span>; <span class='comment'>// 不正。入力がない</span> <span class='kw'>fn</span> <span class='ident'>frob</span>(<span class='ident'>s</span>: <span class='kw-2'>&amp;</span><span class='ident'>str</span>, <span class='ident'>t</span>: <span class='kw-2'>&amp;</span><span class='ident'>str</span>) <span class='op'>-&gt;</span> <span class='kw-2'>&amp;</span><span class='ident'>str</span>; <span class='comment'>// 不正。入力が2つある</span> <span class='kw'>fn</span> <span class='ident'>frob</span><span class='op'>&lt;</span><span class='lifetime'>&#39;a</span>, <span class='lifetime'>&#39;b</span><span class='op'>&gt;</span>(<span class='ident'>s</span>: <span class='kw-2'>&amp;</span><span class='lifetime'>&#39;a</span> <span class='ident'>str</span>, <span class='ident'>t</span>: <span class='kw-2'>&amp;</span><span class='lifetime'>&#39;b</span> <span class='ident'>str</span>) <span class='op'>-&gt;</span> <span class='kw-2'>&amp;</span><span class='ident'>str</span>; <span class='comment'>// 展開された形。出力ライフタイムが決まらない</span> <span class='kw'>fn</span> <span class='ident'>get_mut</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>) <span class='op'>-&gt;</span> <span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='ident'>T</span>; <span class='comment'>// 省略された形</span> <span class='kw'>fn</span> <span class='ident'>get_mut</span><span class='op'>&lt;</span><span class='lifetime'>&#39;a</span><span class='op'>&gt;</span>(<span class='kw-2'>&amp;</span><span class='lifetime'>&#39;a</span> <span class='kw-2'>mut</span> <span class='self'>self</span>) <span class='op'>-&gt;</span> <span class='kw-2'>&amp;</span><span class='lifetime'>&#39;a</span> <span class='kw-2'>mut</span> <span class='ident'>T</span>; <span class='comment'>// 展開された形</span> <span class='kw'>fn</span> <span class='ident'>args</span><span class='op'>&lt;</span><span class='ident'>T</span>: <span class='ident'>ToCStr</span><span class='op'>&gt;</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>, <span class='ident'>args</span>: <span class='kw-2'>&amp;</span>[<span class='ident'>T</span>]) <span class='op'>-&gt;</span> <span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='ident'>Command</span>; <span class='comment'>// 省略された形</span> <span class='kw'>fn</span> <span class='ident'>args</span><span class='op'>&lt;</span><span class='lifetime'>&#39;a</span>, <span class='lifetime'>&#39;b</span>, <span class='ident'>T</span>: <span class='ident'>ToCStr</span><span class='op'>&gt;</span>(<span class='kw-2'>&amp;</span><span class='lifetime'>&#39;a</span> <span class='kw-2'>mut</span> <span class='self'>self</span>, <span class='ident'>args</span>: <span class='kw-2'>&amp;</span><span class='lifetime'>&#39;b</span> [<span class='ident'>T</span>]) <span class='op'>-&gt;</span> <span class='kw-2'>&amp;</span><span class='lifetime'>&#39;a</span> <span class='kw-2'>mut</span> <span class='ident'>Command</span>; <span class='comment'>// 展開された形</span> <span class='kw'>fn</span> <span class='ident'>new</span>(<span class='ident'>buf</span>: <span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> [<span class='ident'>u8</span>]) <span class='op'>-&gt;</span> <span class='ident'>BufWriter</span>; <span class='comment'>// 省略された形</span> <span class='kw'>fn</span> <span class='ident'>new</span><span class='op'>&lt;</span><span class='lifetime'>&#39;a</span><span class='op'>&gt;</span>(<span class='ident'>buf</span>: <span class='kw-2'>&amp;</span><span class='lifetime'>&#39;a</span> <span class='kw-2'>mut</span> [<span class='ident'>u8</span>]) <span class='op'>-&gt;</span> <span class='ident'>BufWriter</span><span class='op'>&lt;</span><span class='lifetime'>&#39;a</span><span class='op'>&gt;</span>; <span class='comment'>// 展開された形</span></pre> <script type="text/javascript"> window.playgroundUrl = "https://play.rust-lang.org"; </script> <script src='rustbook.js'></script> <script src='playpen.js'></script> </div></div> </body> </html> <|start_filename|>docs/1.6/book/method-syntax.html<|end_filename|> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="generator" content="rustdoc"> <title>メソッド構文</title> <link rel="stylesheet" type="text/css" href="rustbook.css"> <meta name="robots" content="noindex"> </head> <body class="rustdoc"> <!--[if lte IE 8]> <div class="warning"> This old browser is unsupported and will most likely display funky things. </div> <![endif]--> <div id="nav"> <button id="toggle-nav"> <span class="sr-only">Toggle navigation</span> <span class="bar"></span> <span class="bar"></span> <span class="bar"></span> </button> </div> <div id='toc' class='mobile-hidden'> <ul class='chapter'> <li><a href='README.html'><b>1.</b> Introduction</a> </li> <li><a href='getting-started.html'><b>2.</b> はじめる</a> </li> <li><a href='learn-rust.html'><b>3.</b> Rustを学ぶ</a> <ul class='section'> <li><a href='guessing-game.html'><b>3.1.</b> 数当てゲーム</a> </li> <li><a href='dining-philosophers.html'><b>3.2.</b> 食事する哲学者</a> </li> <li><a href='rust-inside-other-languages.html'><b>3.3.</b> 他言語と共存する</a> </li> </ul> </li> <li><a href='syntax-and-semantics.html'><b>4.</b> シンタックスとセマンティクス</a> <ul class='section'> <li><a href='variable-bindings.html'><b>4.1.</b> 変数束縛</a> </li> <li><a href='functions.html'><b>4.2.</b> 関数</a> </li> <li><a href='primitive-types.html'><b>4.3.</b> プリミティブ型</a> </li> <li><a href='comments.html'><b>4.4.</b> コメント</a> </li> <li><a href='if.html'><b>4.5.</b> if</a> </li> <li><a href='loops.html'><b>4.6.</b> ループ</a> </li> <li><a href='ownership.html'><b>4.7.</b> 所有権</a> </li> <li><a href='references-and-borrowing.html'><b>4.8.</b> 参照と借用</a> </li> <li><a href='lifetimes.html'><b>4.9.</b> ライフタイム</a> </li> <li><a href='mutability.html'><b>4.10.</b> ミュータビリティ</a> </li> <li><a href='structs.html'><b>4.11.</b> 構造体</a> </li> <li><a href='enums.html'><b>4.12.</b> 列挙型</a> </li> <li><a href='match.html'><b>4.13.</b> マッチ</a> </li> <li><a href='patterns.html'><b>4.14.</b> パターン</a> </li> <li><a class='active' href='method-syntax.html'><b>4.15.</b> メソッド構文</a> </li> <li><a href='vectors.html'><b>4.16.</b> ベクタ</a> </li> <li><a href='strings.html'><b>4.17.</b> 文字列</a> </li> <li><a href='generics.html'><b>4.18.</b> ジェネリクス</a> </li> <li><a href='traits.html'><b>4.19.</b> トレイト</a> </li> <li><a href='drop.html'><b>4.20.</b> Drop</a> </li> <li><a href='if-let.html'><b>4.21.</b> if let</a> </li> <li><a href='trait-objects.html'><b>4.22.</b> トレイトオブジェクト</a> </li> <li><a href='closures.html'><b>4.23.</b> クロージャ</a> </li> <li><a href='ufcs.html'><b>4.24.</b> 共通の関数呼出構文</a> </li> <li><a href='crates-and-modules.html'><b>4.25.</b> クレートとモジュール</a> </li> <li><a href='const-and-static.html'><b>4.26.</b> `const` と `static`</a> </li> <li><a href='attributes.html'><b>4.27.</b> アトリビュート</a> </li> <li><a href='type-aliases.html'><b>4.28.</b> `type` エイリアス</a> </li> <li><a href='casting-between-types.html'><b>4.29.</b> 型間のキャスト</a> </li> <li><a href='associated-types.html'><b>4.30.</b> 関連型</a> </li> <li><a href='unsized-types.html'><b>4.31.</b> サイズ不定型</a> </li> <li><a href='operators-and-overloading.html'><b>4.32.</b> 演算子とオーバーロード</a> </li> <li><a href='deref-coercions.html'><b>4.33.</b> Derefによる型強制</a> </li> <li><a href='macros.html'><b>4.34.</b> マクロ</a> </li> <li><a href='raw-pointers.html'><b>4.35.</b> 生ポインタ</a> </li> <li><a href='unsafe.html'><b>4.36.</b> `unsafe`</a> </li> </ul> </li> <li><a href='effective-rust.html'><b>5.</b> Effective Rust</a> <ul class='section'> <li><a href='the-stack-and-the-heap.html'><b>5.1.</b> スタックとヒープ</a> </li> <li><a href='testing.html'><b>5.2.</b> テスト</a> </li> <li><a href='conditional-compilation.html'><b>5.3.</b> 条件付きコンパイル</a> </li> <li><a href='documentation.html'><b>5.4.</b> ドキュメント</a> </li> <li><a href='iterators.html'><b>5.5.</b> イテレータ</a> </li> <li><a href='concurrency.html'><b>5.6.</b> 並行性</a> </li> <li><a href='error-handling.html'><b>5.7.</b> エラーハンドリング</a> </li> <li><a href='choosing-your-guarantees.html'><b>5.8.</b> 保証を選ぶ</a> </li> <li><a href='ffi.html'><b>5.9.</b> 他言語関数インターフェース</a> </li> <li><a href='borrow-and-asref.html'><b>5.10.</b> BorrowとAsRef</a> </li> <li><a href='release-channels.html'><b>5.11.</b> リリースチャネル</a> </li> <li><a href='using-rust-without-the-standard-library.html'><b>5.12.</b> 標準ライブラリ無しでRustを使う</a> </li> </ul> </li> <li><a href='nightly-rust.html'><b>6.</b> Nightly Rust</a> <ul class='section'> <li><a href='compiler-plugins.html'><b>6.1.</b> コンパイラプラグイン</a> </li> <li><a href='inline-assembly.html'><b>6.2.</b> インラインアセンブリ</a> </li> <li><a href='no-stdlib.html'><b>6.3.</b> No stdlib</a> </li> <li><a href='intrinsics.html'><b>6.4.</b> Intrinsic</a> </li> <li><a href='lang-items.html'><b>6.5.</b> 言語アイテム</a> </li> <li><a href='advanced-linking.html'><b>6.6.</b> 高度なリンキング</a> </li> <li><a href='benchmark-tests.html'><b>6.7.</b> ベンチマークテスト</a> </li> <li><a href='box-syntax-and-patterns.html'><b>6.8.</b> Box構文とパターン</a> </li> <li><a href='slice-patterns.html'><b>6.9.</b> スライスパターン</a> </li> <li><a href='associated-constants.html'><b>6.10.</b> 関連定数</a> </li> <li><a href='custom-allocators.html'><b>6.11.</b> カスタムアロケータ</a> </li> </ul> </li> <li><a href='glossary.html'><b>7.</b> 用語集</a> </li> <li><a href='syntax-index.html'><b>8.</b> 構文の索引</a> </li> <li><a href='bibliography.html'><b>9.</b> 関係書目</a> </li> </ul> </div> <div id='page-wrapper'> <div id='page'> <blockquote class="header-caveat"> <p> <strong>注意: <a href="https://doc.rust-jp.rs/book-ja/">最新版のドキュメントをご覧ください。</a></strong>この第1版ドキュメントは古くなっており、最新情報が反映されていません。リンク先のドキュメントが現在の Rust の最新のドキュメントです。 </p> </blockquote> <h1 class="title">メソッド構文</h1> <!-- % Method Syntax --> <!-- Functions are great, but if you want to call a bunch of them on some data, it can be awkward. Consider this code: --> <p>関数は素晴らしいのですが、幾つかのデータに対し複数の関数をまとめて呼び出したい時、困ったことになります。以下のコードについて考えてみます。</p> <span class='rusttest'>fn main() { baz(bar(foo)); }</span><pre class='rust rust-example-rendered'> <span class='ident'>baz</span>(<span class='ident'>bar</span>(<span class='ident'>foo</span>));</pre> <!-- We would read this left-to-right, and so we see ‘baz bar foo’. But this isn’t the order that the functions would get called in, that’s inside-out: ‘foo bar baz’. Wouldn’t it be nice if we could do this instead? --> <p>私たちはこれを左から右へ、「baz bar foo」と読むことになりますが、関数が呼び出される順番は異なり、内側から外へ「foo bar baz」となります。もし代わりにこうできたらいいとは思いませんか?</p> <span class='rusttest'>fn main() { foo.bar().baz(); }</span><pre class='rust rust-example-rendered'> <span class='ident'>foo</span>.<span class='ident'>bar</span>().<span class='ident'>baz</span>();</pre> <!-- Luckily, as you may have guessed with the leading question, you can! Rust provides the ability to use this ‘method call syntax’ via the `impl` keyword. --> <p>最初の質問でもう分かっているかもしれませんが、幸いにもこれは可能です!Rustは <code>impl</code> キーワードによってこの「メソッド呼び出し構文」の機能を提供しています。</p> <!-- # Method calls --> <h1 id='メソッド呼び出し' class='section-header'><a href='#メソッド呼び出し'>メソッド呼び出し</a></h1> <!-- Here’s how it works: --> <p>どんな風に動作するかが以下になります。</p> <span class='rusttest'>struct Circle { x: f64, y: f64, radius: f64, } impl Circle { fn area(&amp;self) -&gt; f64 { std::f64::consts::PI * (self.radius * self.radius) } } fn main() { let c = Circle { x: 0.0, y: 0.0, radius: 2.0 }; println!(&quot;{}&quot;, c.area()); } </span><pre class='rust rust-example-rendered'> <span class='kw'>struct</span> <span class='ident'>Circle</span> { <span class='ident'>x</span>: <span class='ident'>f64</span>, <span class='ident'>y</span>: <span class='ident'>f64</span>, <span class='ident'>radius</span>: <span class='ident'>f64</span>, } <span class='kw'>impl</span> <span class='ident'>Circle</span> { <span class='kw'>fn</span> <span class='ident'>area</span>(<span class='kw-2'>&amp;</span><span class='self'>self</span>) <span class='op'>-&gt;</span> <span class='ident'>f64</span> { <span class='ident'>std</span>::<span class='ident'>f64</span>::<span class='ident'>consts</span>::<span class='ident'>PI</span> <span class='op'>*</span> (<span class='self'>self</span>.<span class='ident'>radius</span> <span class='op'>*</span> <span class='self'>self</span>.<span class='ident'>radius</span>) } } <span class='kw'>fn</span> <span class='ident'>main</span>() { <span class='kw'>let</span> <span class='ident'>c</span> <span class='op'>=</span> <span class='ident'>Circle</span> { <span class='ident'>x</span>: <span class='number'>0.0</span>, <span class='ident'>y</span>: <span class='number'>0.0</span>, <span class='ident'>radius</span>: <span class='number'>2.0</span> }; <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;{}&quot;</span>, <span class='ident'>c</span>.<span class='ident'>area</span>()); }</pre> <!-- This will print `12.566371`. --> <p>これは <code>12.566371</code> と出力します。</p> <!-- We’ve made a `struct` that represents a circle. We then write an `impl` block, and inside it, define a method, `area`. --> <p>私たちは円を表す <code>struct</code> を作りました。その際 <code>impl</code> ブロックを書き、その中に <code>area</code> というメソッドを定義しています。</p> <!-- Methods take a special first parameter, of which there are three variants: `self`, `&self`, and `&mut self`. You can think of this first parameter as being the `foo` in `foo.bar()`. The three variants correspond to the three kinds of things `foo` could be: `self` if it’s just a value on the stack, `&self` if it’s a reference, and `&mut self` if it’s a mutable reference. Because we took the `&self` parameter to `area`, we can use it just like any other parameter. Because we know it’s a `Circle`, we can access the `radius` just like we would with any other `struct`. --> <p>メソッドに渡す特別な第1引数として、 <code>self</code> 、 <code>&amp;self</code> 、 <code>&amp;mut self</code> という3つの変形があります。第一引数は <code>foo.bar()</code> に於ける <code>foo</code> だと考えて下さい。3つの変形は <code>foo</code> が成り得る3種類の状態に対応しており、それぞれ <code>self</code> がスタック上の値である場合、 <code>&amp;self</code> が参照である場合、 <code>&amp;mut self</code> がミュータブルな参照である場合となっています。 <code>area</code> では <code>&amp;self</code> を受け取っているため、他の引数と同じように扱えます。引数が <code>Circle</code> であるのは分かっていますから、他の <code>struct</code> でするように <code>radius</code> へアクセスできます。</p> <!-- We should default to using `&self`, as you should prefer borrowing over taking ownership, as well as taking immutable references over mutable ones. Here’s an example of all three variants: --> <p>所有権を渡すよりも借用を好んで使うべきなのは勿論のこと、ミュータブルな参照よりもイミュータブルな参照を渡すべきですから、 <code>&amp;self</code> を常用すべきです。以下が3種類全ての例です。</p> <span class='rusttest'>fn main() { struct Circle { x: f64, y: f64, radius: f64, } impl Circle { fn reference(&amp;self) { println!(&quot;taking self by reference!&quot;); } fn mutable_reference(&amp;mut self) { println!(&quot;taking self by mutable reference!&quot;); } fn takes_ownership(self) { println!(&quot;taking ownership of self!&quot;); } } }</span><pre class='rust rust-example-rendered'> <span class='kw'>struct</span> <span class='ident'>Circle</span> { <span class='ident'>x</span>: <span class='ident'>f64</span>, <span class='ident'>y</span>: <span class='ident'>f64</span>, <span class='ident'>radius</span>: <span class='ident'>f64</span>, } <span class='kw'>impl</span> <span class='ident'>Circle</span> { <span class='kw'>fn</span> <span class='ident'>reference</span>(<span class='kw-2'>&amp;</span><span class='self'>self</span>) { <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;taking self by reference!&quot;</span>); } <span class='kw'>fn</span> <span class='ident'>mutable_reference</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>) { <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;taking self by mutable reference!&quot;</span>); } <span class='kw'>fn</span> <span class='ident'>takes_ownership</span>(<span class='self'>self</span>) { <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;taking ownership of self!&quot;</span>); } }</pre> <!--You can use as many `impl` blocks as you’d like. The previous example could have also been written like this: --> <p>好きな数だけ <code>impl</code> ブロックを使用することができます。前述の例は以下のように書くこともできるでしょう。</p> <span class='rusttest'>fn main() { struct Circle { x: f64, y: f64, radius: f64, } impl Circle { fn reference(&amp;self) { println!(&quot;taking self by reference!&quot;); } } impl Circle { fn mutable_reference(&amp;mut self) { println!(&quot;taking self by mutable reference!&quot;); } } impl Circle { fn takes_ownership(self) { println!(&quot;taking ownership of self!&quot;); } } }</span><pre class='rust rust-example-rendered'> <span class='kw'>struct</span> <span class='ident'>Circle</span> { <span class='ident'>x</span>: <span class='ident'>f64</span>, <span class='ident'>y</span>: <span class='ident'>f64</span>, <span class='ident'>radius</span>: <span class='ident'>f64</span>, } <span class='kw'>impl</span> <span class='ident'>Circle</span> { <span class='kw'>fn</span> <span class='ident'>reference</span>(<span class='kw-2'>&amp;</span><span class='self'>self</span>) { <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;taking self by reference!&quot;</span>); } } <span class='kw'>impl</span> <span class='ident'>Circle</span> { <span class='kw'>fn</span> <span class='ident'>mutable_reference</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>) { <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;taking self by mutable reference!&quot;</span>); } } <span class='kw'>impl</span> <span class='ident'>Circle</span> { <span class='kw'>fn</span> <span class='ident'>takes_ownership</span>(<span class='self'>self</span>) { <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;taking ownership of self!&quot;</span>); } }</pre> <!-- # Chaining method calls --> <h1 id='メソッドチェーン' class='section-header'><a href='#メソッドチェーン'>メソッドチェーン</a></h1> <!-- So, now we know how to call a method, such as `foo.bar()`. But what about our original example, `foo.bar().baz()`? This is called ‘method chaining’. Let’s look at an example: --> <p>ここまでで、<code>foo.bar()</code> というようなメソッドの呼び出し方が分かりましたね。ですが元の例の <code>foo.bar().baz()</code> はどうなっているのでしょう?これは「メソッドチェーン」と呼ばれています。以下の例を見て下さい。</p> <span class='rusttest'>struct Circle { x: f64, y: f64, radius: f64, } impl Circle { fn area(&amp;self) -&gt; f64 { std::f64::consts::PI * (self.radius * self.radius) } fn grow(&amp;self, increment: f64) -&gt; Circle { Circle { x: self.x, y: self.y, radius: self.radius + increment } } } fn main() { let c = Circle { x: 0.0, y: 0.0, radius: 2.0 }; println!(&quot;{}&quot;, c.area()); let d = c.grow(2.0).area(); println!(&quot;{}&quot;, d); } </span><pre class='rust rust-example-rendered'> <span class='kw'>struct</span> <span class='ident'>Circle</span> { <span class='ident'>x</span>: <span class='ident'>f64</span>, <span class='ident'>y</span>: <span class='ident'>f64</span>, <span class='ident'>radius</span>: <span class='ident'>f64</span>, } <span class='kw'>impl</span> <span class='ident'>Circle</span> { <span class='kw'>fn</span> <span class='ident'>area</span>(<span class='kw-2'>&amp;</span><span class='self'>self</span>) <span class='op'>-&gt;</span> <span class='ident'>f64</span> { <span class='ident'>std</span>::<span class='ident'>f64</span>::<span class='ident'>consts</span>::<span class='ident'>PI</span> <span class='op'>*</span> (<span class='self'>self</span>.<span class='ident'>radius</span> <span class='op'>*</span> <span class='self'>self</span>.<span class='ident'>radius</span>) } <span class='kw'>fn</span> <span class='ident'>grow</span>(<span class='kw-2'>&amp;</span><span class='self'>self</span>, <span class='ident'>increment</span>: <span class='ident'>f64</span>) <span class='op'>-&gt;</span> <span class='ident'>Circle</span> { <span class='ident'>Circle</span> { <span class='ident'>x</span>: <span class='self'>self</span>.<span class='ident'>x</span>, <span class='ident'>y</span>: <span class='self'>self</span>.<span class='ident'>y</span>, <span class='ident'>radius</span>: <span class='self'>self</span>.<span class='ident'>radius</span> <span class='op'>+</span> <span class='ident'>increment</span> } } } <span class='kw'>fn</span> <span class='ident'>main</span>() { <span class='kw'>let</span> <span class='ident'>c</span> <span class='op'>=</span> <span class='ident'>Circle</span> { <span class='ident'>x</span>: <span class='number'>0.0</span>, <span class='ident'>y</span>: <span class='number'>0.0</span>, <span class='ident'>radius</span>: <span class='number'>2.0</span> }; <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;{}&quot;</span>, <span class='ident'>c</span>.<span class='ident'>area</span>()); <span class='kw'>let</span> <span class='ident'>d</span> <span class='op'>=</span> <span class='ident'>c</span>.<span class='ident'>grow</span>(<span class='number'>2.0</span>).<span class='ident'>area</span>(); <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;{}&quot;</span>, <span class='ident'>d</span>); }</pre> <!-- Check the return type: --> <p>以下の返す型を確認して下さい。</p> <span class='rusttest'>fn main() { struct Circle; impl Circle { fn grow(&amp;self, increment: f64) -&gt; Circle { Circle } } }</span><pre class='rust rust-example-rendered'> <span class='kw'>fn</span> <span class='ident'>grow</span>(<span class='kw-2'>&amp;</span><span class='self'>self</span>, <span class='ident'>increment</span>: <span class='ident'>f64</span>) <span class='op'>-&gt;</span> <span class='ident'>Circle</span> {</pre> <!-- We just say we’re returning a `Circle`. With this method, we can grow a new `Circle` to any arbitrary size. --> <p>単に <code>Circle</code> を返しているだけです。このメソッドにより、私たちは新しい <code>Circle</code> を任意の大きさに拡大することができます。</p> <!-- # Associated functions --> <h1 id='関連関数' class='section-header'><a href='#関連関数'>関連関数</a></h1> <!-- You can also define associated functions that do not take a `self` parameter. Here’s a pattern that’s very common in Rust code: --> <p>あなたは <code>self</code> を引数に取らない関連関数を定義することもできます。以下のパターンはRustのコードにおいて非常にありふれた物です。</p> <span class='rusttest'>struct Circle { x: f64, y: f64, radius: f64, } impl Circle { fn new(x: f64, y: f64, radius: f64) -&gt; Circle { Circle { x: x, y: y, radius: radius, } } } fn main() { let c = Circle::new(0.0, 0.0, 2.0); } </span><pre class='rust rust-example-rendered'> <span class='kw'>struct</span> <span class='ident'>Circle</span> { <span class='ident'>x</span>: <span class='ident'>f64</span>, <span class='ident'>y</span>: <span class='ident'>f64</span>, <span class='ident'>radius</span>: <span class='ident'>f64</span>, } <span class='kw'>impl</span> <span class='ident'>Circle</span> { <span class='kw'>fn</span> <span class='ident'>new</span>(<span class='ident'>x</span>: <span class='ident'>f64</span>, <span class='ident'>y</span>: <span class='ident'>f64</span>, <span class='ident'>radius</span>: <span class='ident'>f64</span>) <span class='op'>-&gt;</span> <span class='ident'>Circle</span> { <span class='ident'>Circle</span> { <span class='ident'>x</span>: <span class='ident'>x</span>, <span class='ident'>y</span>: <span class='ident'>y</span>, <span class='ident'>radius</span>: <span class='ident'>radius</span>, } } } <span class='kw'>fn</span> <span class='ident'>main</span>() { <span class='kw'>let</span> <span class='ident'>c</span> <span class='op'>=</span> <span class='ident'>Circle</span>::<span class='ident'>new</span>(<span class='number'>0.0</span>, <span class='number'>0.0</span>, <span class='number'>2.0</span>); }</pre> <!-- This ‘associated function’ builds a new `Circle` for us. Note that associated functions are called with the `Struct::function()` syntax, rather than the `ref.method()` syntax. Some other languages call associated functions ‘static methods’. --> <p>この「関連関数」(associated function)は新たに <code>Circle</code> を構築します。この関数は <code>ref.method()</code> ではなく、 <code>Struct::function()</code> という構文で呼び出されることに注意して下さい。幾つかの言語では、関連関数を「静的メソッド」(static methods)と呼んでいます。</p> <!-- # Builder Pattern --> <h1 id='builderパターン' class='section-header'><a href='#builderパターン'>Builderパターン</a></h1> <!-- Let’s say that we want our users to be able to create `Circle`s, but we will allow them to only set the properties they care about. Otherwise, the `x` and `y` attributes will be `0.0`, and the `radius` will be `1.0`. Rust doesn’t have method overloading, named arguments, or variable arguments. We employ the builder pattern instead. It looks like this: --> <p>ユーザが <code>Circle</code> を作成できるようにしつつも、書き換えたいプロパティだけを設定すれば良いようにしたいとしましょう。もし指定が無ければ <code>x</code> と <code>y</code> が <code>0.0</code> 、 <code>radius</code> が <code>1.0</code> であるものとします。Rustはメソッドのオーバーロードや名前付き引数、可変個引数といった機能がない代わりにBuilderパターンを採用しており、それは以下のようになります。</p> <span class='rusttest'>struct Circle { x: f64, y: f64, radius: f64, } impl Circle { fn area(&amp;self) -&gt; f64 { std::f64::consts::PI * (self.radius * self.radius) } } struct CircleBuilder { x: f64, y: f64, radius: f64, } impl CircleBuilder { fn new() -&gt; CircleBuilder { CircleBuilder { x: 0.0, y: 0.0, radius: 1.0, } } fn x(&amp;mut self, coordinate: f64) -&gt; &amp;mut CircleBuilder { self.x = coordinate; self } fn y(&amp;mut self, coordinate: f64) -&gt; &amp;mut CircleBuilder { self.y = coordinate; self } fn radius(&amp;mut self, radius: f64) -&gt; &amp;mut CircleBuilder { self.radius = radius; self } fn finalize(&amp;self) -&gt; Circle { Circle { x: self.x, y: self.y, radius: self.radius } } } fn main() { let c = CircleBuilder::new() .x(1.0) .y(2.0) .radius(2.0) .finalize(); println!(&quot;area: {}&quot;, c.area()); println!(&quot;x: {}&quot;, c.x); println!(&quot;y: {}&quot;, c.y); } </span><pre class='rust rust-example-rendered'> <span class='kw'>struct</span> <span class='ident'>Circle</span> { <span class='ident'>x</span>: <span class='ident'>f64</span>, <span class='ident'>y</span>: <span class='ident'>f64</span>, <span class='ident'>radius</span>: <span class='ident'>f64</span>, } <span class='kw'>impl</span> <span class='ident'>Circle</span> { <span class='kw'>fn</span> <span class='ident'>area</span>(<span class='kw-2'>&amp;</span><span class='self'>self</span>) <span class='op'>-&gt;</span> <span class='ident'>f64</span> { <span class='ident'>std</span>::<span class='ident'>f64</span>::<span class='ident'>consts</span>::<span class='ident'>PI</span> <span class='op'>*</span> (<span class='self'>self</span>.<span class='ident'>radius</span> <span class='op'>*</span> <span class='self'>self</span>.<span class='ident'>radius</span>) } } <span class='kw'>struct</span> <span class='ident'>CircleBuilder</span> { <span class='ident'>x</span>: <span class='ident'>f64</span>, <span class='ident'>y</span>: <span class='ident'>f64</span>, <span class='ident'>radius</span>: <span class='ident'>f64</span>, } <span class='kw'>impl</span> <span class='ident'>CircleBuilder</span> { <span class='kw'>fn</span> <span class='ident'>new</span>() <span class='op'>-&gt;</span> <span class='ident'>CircleBuilder</span> { <span class='ident'>CircleBuilder</span> { <span class='ident'>x</span>: <span class='number'>0.0</span>, <span class='ident'>y</span>: <span class='number'>0.0</span>, <span class='ident'>radius</span>: <span class='number'>1.0</span>, } } <span class='kw'>fn</span> <span class='ident'>x</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>, <span class='ident'>coordinate</span>: <span class='ident'>f64</span>) <span class='op'>-&gt;</span> <span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='ident'>CircleBuilder</span> { <span class='self'>self</span>.<span class='ident'>x</span> <span class='op'>=</span> <span class='ident'>coordinate</span>; <span class='self'>self</span> } <span class='kw'>fn</span> <span class='ident'>y</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>, <span class='ident'>coordinate</span>: <span class='ident'>f64</span>) <span class='op'>-&gt;</span> <span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='ident'>CircleBuilder</span> { <span class='self'>self</span>.<span class='ident'>y</span> <span class='op'>=</span> <span class='ident'>coordinate</span>; <span class='self'>self</span> } <span class='kw'>fn</span> <span class='ident'>radius</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>, <span class='ident'>radius</span>: <span class='ident'>f64</span>) <span class='op'>-&gt;</span> <span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='ident'>CircleBuilder</span> { <span class='self'>self</span>.<span class='ident'>radius</span> <span class='op'>=</span> <span class='ident'>radius</span>; <span class='self'>self</span> } <span class='kw'>fn</span> <span class='ident'>finalize</span>(<span class='kw-2'>&amp;</span><span class='self'>self</span>) <span class='op'>-&gt;</span> <span class='ident'>Circle</span> { <span class='ident'>Circle</span> { <span class='ident'>x</span>: <span class='self'>self</span>.<span class='ident'>x</span>, <span class='ident'>y</span>: <span class='self'>self</span>.<span class='ident'>y</span>, <span class='ident'>radius</span>: <span class='self'>self</span>.<span class='ident'>radius</span> } } } <span class='kw'>fn</span> <span class='ident'>main</span>() { <span class='kw'>let</span> <span class='ident'>c</span> <span class='op'>=</span> <span class='ident'>CircleBuilder</span>::<span class='ident'>new</span>() .<span class='ident'>x</span>(<span class='number'>1.0</span>) .<span class='ident'>y</span>(<span class='number'>2.0</span>) .<span class='ident'>radius</span>(<span class='number'>2.0</span>) .<span class='ident'>finalize</span>(); <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;area: {}&quot;</span>, <span class='ident'>c</span>.<span class='ident'>area</span>()); <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;x: {}&quot;</span>, <span class='ident'>c</span>.<span class='ident'>x</span>); <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;y: {}&quot;</span>, <span class='ident'>c</span>.<span class='ident'>y</span>); }</pre> <!-- What we’ve done here is make another `struct`, `CircleBuilder`. We’ve defined our builder methods on it. We’ve also defined our `area()` method on `Circle`. We also made one more method on `CircleBuilder`: `finalize()`. This method creates our final `Circle` from the builder. Now, we’ve used the type system to enforce our concerns: we can use the methods on `CircleBuilder` to constrain making `Circle`s in any way we choose. --> <p>ここではもう1つの <code>struct</code> である <code>CircleBuilder</code> を作成しています。その中にBuilderメソッドを定義しました。また <code>Circle</code> に <code>area()</code> メソッドを定義しました。 そして <code>CircleBuilder</code> にもう1つ <code>finalize()</code> というメソッドを作りました。このメソッドはBuilderから最終的な <code>Circle</code> を作成します。さて、先程の要求を実施するために型システムを使いました。 <code>CircleBuilder</code> のメソッドを好きなように組み合わせ、作る <code>Circle</code> への制約を与えることができます。</p> <script type="text/javascript"> window.playgroundUrl = "https://play.rust-lang.org"; </script> <script src='rustbook.js'></script> <script src='playpen.js'></script> </div></div> </body> </html> <|start_filename|>docs/1.9/nomicon/vec-raw.html<|end_filename|> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="generator" content="rustdoc"> <title>RawVec</title> <link rel="stylesheet" type="text/css" href="rustbook.css"> <meta name="robots" content="noindex"> </head> <body class="rustdoc"> <!--[if lte IE 8]> <div class="warning"> This old browser is unsupported and will most likely display funky things. </div> <![endif]--> <div id="nav"> <button id="toggle-nav"> <span class="sr-only">Toggle navigation</span> <span class="bar"></span> <span class="bar"></span> <span class="bar"></span> </button> </div> <div id='toc' class='mobile-hidden'> <ul class='chapter'> <li><a href='README.html'><b>1.</b> Introduction</a> </li> <li><a href='meet-safe-and-unsafe.html'><b>2.</b> Meet Safe and Unsafe</a> <ul class='section'> <li><a href='safe-unsafe-meaning.html'><b>2.1.</b> How Safe and Unsafe Interact</a> </li> <li><a href='working-with-unsafe.html'><b>2.2.</b> Working with Unsafe</a> </li> </ul> </li> <li><a href='data.html'><b>3.</b> Data Layout</a> <ul class='section'> <li><a href='repr-rust.html'><b>3.1.</b> repr(Rust)</a> </li> <li><a href='exotic-sizes.html'><b>3.2.</b> Exotically Sized Types</a> </li> <li><a href='other-reprs.html'><b>3.3.</b> Other reprs</a> </li> </ul> </li> <li><a href='ownership.html'><b>4.</b> Ownership</a> <ul class='section'> <li><a href='references.html'><b>4.1.</b> References</a> </li> <li><a href='lifetimes.html'><b>4.2.</b> Lifetimes</a> </li> <li><a href='lifetime-mismatch.html'><b>4.3.</b> Limits of Lifetimes</a> </li> <li><a href='lifetime-elision.html'><b>4.4.</b> Lifetime Elision</a> </li> <li><a href='unbounded-lifetimes.html'><b>4.5.</b> Unbounded Lifetimes</a> </li> <li><a href='hrtb.html'><b>4.6.</b> Higher-Rank Trait Bounds</a> </li> <li><a href='subtyping.html'><b>4.7.</b> Subtyping and Variance</a> </li> <li><a href='dropck.html'><b>4.8.</b> Drop Check</a> </li> <li><a href='phantom-data.html'><b>4.9.</b> PhantomData</a> </li> <li><a href='borrow-splitting.html'><b>4.10.</b> Splitting Borrows</a> </li> </ul> </li> <li><a href='conversions.html'><b>5.</b> Type Conversions</a> <ul class='section'> <li><a href='coercions.html'><b>5.1.</b> Coercions</a> </li> <li><a href='dot-operator.html'><b>5.2.</b> The Dot Operator</a> </li> <li><a href='casts.html'><b>5.3.</b> Casts</a> </li> <li><a href='transmutes.html'><b>5.4.</b> Transmutes</a> </li> </ul> </li> <li><a href='uninitialized.html'><b>6.</b> Uninitialized Memory</a> <ul class='section'> <li><a href='checked-uninit.html'><b>6.1.</b> Checked</a> </li> <li><a href='drop-flags.html'><b>6.2.</b> Drop Flags</a> </li> <li><a href='unchecked-uninit.html'><b>6.3.</b> Unchecked</a> </li> </ul> </li> <li><a href='obrm.html'><b>7.</b> Ownership Based Resource Management</a> <ul class='section'> <li><a href='constructors.html'><b>7.1.</b> Constructors</a> </li> <li><a href='destructors.html'><b>7.2.</b> Destructors</a> </li> <li><a href='leaking.html'><b>7.3.</b> Leaking</a> </li> </ul> </li> <li><a href='unwinding.html'><b>8.</b> Unwinding</a> <ul class='section'> <li><a href='exception-safety.html'><b>8.1.</b> Exception Safety</a> </li> <li><a href='poisoning.html'><b>8.2.</b> Poisoning</a> </li> </ul> </li> <li><a href='concurrency.html'><b>9.</b> Concurrency</a> <ul class='section'> <li><a href='races.html'><b>9.1.</b> Races</a> </li> <li><a href='send-and-sync.html'><b>9.2.</b> Send and Sync</a> </li> <li><a href='atomics.html'><b>9.3.</b> Atomics</a> </li> </ul> </li> <li><a href='vec.html'><b>10.</b> Implementing Vec</a> <ul class='section'> <li><a href='vec-layout.html'><b>10.1.</b> Layout</a> </li> <li><a href='vec-alloc.html'><b>10.2.</b> Allocating</a> </li> <li><a href='vec-push-pop.html'><b>10.3.</b> Push and Pop</a> </li> <li><a href='vec-dealloc.html'><b>10.4.</b> Deallocating</a> </li> <li><a href='vec-deref.html'><b>10.5.</b> Deref</a> </li> <li><a href='vec-insert-remove.html'><b>10.6.</b> Insert and Remove</a> </li> <li><a href='vec-into-iter.html'><b>10.7.</b> IntoIter</a> </li> <li><a class='active' href='vec-raw.html'><b>10.8.</b> RawVec</a> </li> <li><a href='vec-drain.html'><b>10.9.</b> Drain</a> </li> <li><a href='vec-zsts.html'><b>10.10.</b> Handling Zero-Sized Types</a> </li> <li><a href='vec-final.html'><b>10.11.</b> Final Code</a> </li> </ul> </li> <li><a href='arc-and-mutex.html'><b>11.</b> Implementing Arc and Mutex</a> </li> </ul> </div> <div id='page-wrapper'> <div id='page'> <blockquote class="header-caveat"> <p> <strong>注意: <a href="https://doc.rust-jp.rs/book-ja/">最新版のドキュメントをご覧ください。</a></strong>この第1版ドキュメントは古くなっており、最新情報が反映されていません。リンク先のドキュメントが現在の Rust の最新のドキュメントです。 </p> </blockquote> <h1 class="title">RawVec</h1> <p>We&#39;ve actually reached an interesting situation here: we&#39;ve duplicated the logic for specifying a buffer and freeing its memory in Vec and IntoIter. Now that we&#39;ve implemented it and identified <em>actual</em> logic duplication, this is a good time to perform some logic compression.</p> <p>We&#39;re going to abstract out the <code>(ptr, cap)</code> pair and give them the logic for allocating, growing, and freeing:</p> <span class='rusttest'>fn main() { struct RawVec&lt;T&gt; { ptr: Unique&lt;T&gt;, cap: usize, } impl&lt;T&gt; RawVec&lt;T&gt; { fn new() -&gt; Self { assert!(mem::size_of::&lt;T&gt;() != 0, &quot;TODO: implement ZST support&quot;); unsafe { RawVec { ptr: Unique::new(heap::EMPTY as *mut T), cap: 0 } } } // unchanged from Vec fn grow(&amp;mut self) { unsafe { let align = mem::align_of::&lt;T&gt;(); let elem_size = mem::size_of::&lt;T&gt;(); let (new_cap, ptr) = if self.cap == 0 { let ptr = heap::allocate(elem_size, align); (1, ptr) } else { let new_cap = 2 * self.cap; let ptr = heap::reallocate(*self.ptr as *mut _, self.cap * elem_size, new_cap * elem_size, align); (new_cap, ptr) }; // If allocate or reallocate fail, we&#39;ll get `null` back if ptr.is_null() { oom() } self.ptr = Unique::new(ptr as *mut _); self.cap = new_cap; } } } impl&lt;T&gt; Drop for RawVec&lt;T&gt; { fn drop(&amp;mut self) { if self.cap != 0 { let align = mem::align_of::&lt;T&gt;(); let elem_size = mem::size_of::&lt;T&gt;(); let num_bytes = elem_size * self.cap; unsafe { heap::deallocate(*self.ptr as *mut _, num_bytes, align); } } } } }</span><pre class='rust rust-example-rendered'> <span class='kw'>struct</span> <span class='ident'>RawVec</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> { <span class='ident'>ptr</span>: <span class='ident'>Unique</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span>, <span class='ident'>cap</span>: <span class='ident'>usize</span>, } <span class='kw'>impl</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> <span class='ident'>RawVec</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> { <span class='kw'>fn</span> <span class='ident'>new</span>() <span class='op'>-&gt;</span> <span class='self'>Self</span> { <span class='macro'>assert</span><span class='macro'>!</span>(<span class='ident'>mem</span>::<span class='ident'>size_of</span>::<span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span>() <span class='op'>!=</span> <span class='number'>0</span>, <span class='string'>&quot;TODO: implement ZST support&quot;</span>); <span class='kw'>unsafe</span> { <span class='ident'>RawVec</span> { <span class='ident'>ptr</span>: <span class='ident'>Unique</span>::<span class='ident'>new</span>(<span class='ident'>heap</span>::<span class='ident'>EMPTY</span> <span class='kw'>as</span> <span class='op'>*</span><span class='kw-2'>mut</span> <span class='ident'>T</span>), <span class='ident'>cap</span>: <span class='number'>0</span> } } } <span class='comment'>// unchanged from Vec</span> <span class='kw'>fn</span> <span class='ident'>grow</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>) { <span class='kw'>unsafe</span> { <span class='kw'>let</span> <span class='ident'>align</span> <span class='op'>=</span> <span class='ident'>mem</span>::<span class='ident'>align_of</span>::<span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span>(); <span class='kw'>let</span> <span class='ident'>elem_size</span> <span class='op'>=</span> <span class='ident'>mem</span>::<span class='ident'>size_of</span>::<span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span>(); <span class='kw'>let</span> (<span class='ident'>new_cap</span>, <span class='ident'>ptr</span>) <span class='op'>=</span> <span class='kw'>if</span> <span class='self'>self</span>.<span class='ident'>cap</span> <span class='op'>==</span> <span class='number'>0</span> { <span class='kw'>let</span> <span class='ident'>ptr</span> <span class='op'>=</span> <span class='ident'>heap</span>::<span class='ident'>allocate</span>(<span class='ident'>elem_size</span>, <span class='ident'>align</span>); (<span class='number'>1</span>, <span class='ident'>ptr</span>) } <span class='kw'>else</span> { <span class='kw'>let</span> <span class='ident'>new_cap</span> <span class='op'>=</span> <span class='number'>2</span> <span class='op'>*</span> <span class='self'>self</span>.<span class='ident'>cap</span>; <span class='kw'>let</span> <span class='ident'>ptr</span> <span class='op'>=</span> <span class='ident'>heap</span>::<span class='ident'>reallocate</span>(<span class='op'>*</span><span class='self'>self</span>.<span class='ident'>ptr</span> <span class='kw'>as</span> <span class='op'>*</span><span class='kw-2'>mut</span> _, <span class='self'>self</span>.<span class='ident'>cap</span> <span class='op'>*</span> <span class='ident'>elem_size</span>, <span class='ident'>new_cap</span> <span class='op'>*</span> <span class='ident'>elem_size</span>, <span class='ident'>align</span>); (<span class='ident'>new_cap</span>, <span class='ident'>ptr</span>) }; <span class='comment'>// If allocate or reallocate fail, we&#39;ll get `null` back</span> <span class='kw'>if</span> <span class='ident'>ptr</span>.<span class='ident'>is_null</span>() { <span class='ident'>oom</span>() } <span class='self'>self</span>.<span class='ident'>ptr</span> <span class='op'>=</span> <span class='ident'>Unique</span>::<span class='ident'>new</span>(<span class='ident'>ptr</span> <span class='kw'>as</span> <span class='op'>*</span><span class='kw-2'>mut</span> _); <span class='self'>self</span>.<span class='ident'>cap</span> <span class='op'>=</span> <span class='ident'>new_cap</span>; } } } <span class='kw'>impl</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> <span class='ident'>Drop</span> <span class='kw'>for</span> <span class='ident'>RawVec</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> { <span class='kw'>fn</span> <span class='ident'>drop</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>) { <span class='kw'>if</span> <span class='self'>self</span>.<span class='ident'>cap</span> <span class='op'>!=</span> <span class='number'>0</span> { <span class='kw'>let</span> <span class='ident'>align</span> <span class='op'>=</span> <span class='ident'>mem</span>::<span class='ident'>align_of</span>::<span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span>(); <span class='kw'>let</span> <span class='ident'>elem_size</span> <span class='op'>=</span> <span class='ident'>mem</span>::<span class='ident'>size_of</span>::<span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span>(); <span class='kw'>let</span> <span class='ident'>num_bytes</span> <span class='op'>=</span> <span class='ident'>elem_size</span> <span class='op'>*</span> <span class='self'>self</span>.<span class='ident'>cap</span>; <span class='kw'>unsafe</span> { <span class='ident'>heap</span>::<span class='ident'>deallocate</span>(<span class='op'>*</span><span class='self'>self</span>.<span class='ident'>ptr</span> <span class='kw'>as</span> <span class='op'>*</span><span class='kw-2'>mut</span> _, <span class='ident'>num_bytes</span>, <span class='ident'>align</span>); } } } }</pre> <p>And change Vec as follows:</p> <span class='rusttest'>fn main() { pub struct Vec&lt;T&gt; { buf: RawVec&lt;T&gt;, len: usize, } impl&lt;T&gt; Vec&lt;T&gt; { fn ptr(&amp;self) -&gt; *mut T { *self.buf.ptr } fn cap(&amp;self) -&gt; usize { self.buf.cap } pub fn new() -&gt; Self { Vec { buf: RawVec::new(), len: 0 } } // push/pop/insert/remove largely unchanged: // * `self.ptr -&gt; self.ptr()` // * `self.cap -&gt; self.cap()` // * `self.grow -&gt; self.buf.grow()` } impl&lt;T&gt; Drop for Vec&lt;T&gt; { fn drop(&amp;mut self) { while let Some(_) = self.pop() {} // deallocation is handled by RawVec } } }</span><pre class='rust rust-example-rendered'> <span class='kw'>pub</span> <span class='kw'>struct</span> <span class='ident'>Vec</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> { <span class='ident'>buf</span>: <span class='ident'>RawVec</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span>, <span class='ident'>len</span>: <span class='ident'>usize</span>, } <span class='kw'>impl</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> <span class='ident'>Vec</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> { <span class='kw'>fn</span> <span class='ident'>ptr</span>(<span class='kw-2'>&amp;</span><span class='self'>self</span>) <span class='op'>-&gt;</span> <span class='op'>*</span><span class='kw-2'>mut</span> <span class='ident'>T</span> { <span class='op'>*</span><span class='self'>self</span>.<span class='ident'>buf</span>.<span class='ident'>ptr</span> } <span class='kw'>fn</span> <span class='ident'>cap</span>(<span class='kw-2'>&amp;</span><span class='self'>self</span>) <span class='op'>-&gt;</span> <span class='ident'>usize</span> { <span class='self'>self</span>.<span class='ident'>buf</span>.<span class='ident'>cap</span> } <span class='kw'>pub</span> <span class='kw'>fn</span> <span class='ident'>new</span>() <span class='op'>-&gt;</span> <span class='self'>Self</span> { <span class='ident'>Vec</span> { <span class='ident'>buf</span>: <span class='ident'>RawVec</span>::<span class='ident'>new</span>(), <span class='ident'>len</span>: <span class='number'>0</span> } } <span class='comment'>// push/pop/insert/remove largely unchanged:</span> <span class='comment'>// * `self.ptr -&gt; self.ptr()`</span> <span class='comment'>// * `self.cap -&gt; self.cap()`</span> <span class='comment'>// * `self.grow -&gt; self.buf.grow()`</span> } <span class='kw'>impl</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> <span class='ident'>Drop</span> <span class='kw'>for</span> <span class='ident'>Vec</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> { <span class='kw'>fn</span> <span class='ident'>drop</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>) { <span class='kw'>while</span> <span class='kw'>let</span> <span class='prelude-val'>Some</span>(_) <span class='op'>=</span> <span class='self'>self</span>.<span class='ident'>pop</span>() {} <span class='comment'>// deallocation is handled by RawVec</span> } }</pre> <p>And finally we can really simplify IntoIter:</p> <span class='rusttest'>fn main() { struct IntoIter&lt;T&gt; { _buf: RawVec&lt;T&gt;, // we don&#39;t actually care about this. Just need it to live. start: *const T, end: *const T, } // next and next_back literally unchanged since they never referred to the buf impl&lt;T&gt; Drop for IntoIter&lt;T&gt; { fn drop(&amp;mut self) { // only need to ensure all our elements are read; // buffer will clean itself up afterwards. for _ in &amp;mut *self {} } } impl&lt;T&gt; Vec&lt;T&gt; { pub fn into_iter(self) -&gt; IntoIter&lt;T&gt; { unsafe { // need to use ptr::read to unsafely move the buf out since it&#39;s // not Copy, and Vec implements Drop (so we can&#39;t destructure it). let buf = ptr::read(&amp;self.buf); let len = self.len; mem::forget(self); IntoIter { start: *buf.ptr, end: buf.ptr.offset(len as isize), _buf: buf, } } } } }</span><pre class='rust rust-example-rendered'> <span class='kw'>struct</span> <span class='ident'>IntoIter</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> { <span class='ident'>_buf</span>: <span class='ident'>RawVec</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span>, <span class='comment'>// we don&#39;t actually care about this. Just need it to live.</span> <span class='ident'>start</span>: <span class='op'>*</span><span class='kw'>const</span> <span class='ident'>T</span>, <span class='ident'>end</span>: <span class='op'>*</span><span class='kw'>const</span> <span class='ident'>T</span>, } <span class='comment'>// next and next_back literally unchanged since they never referred to the buf</span> <span class='kw'>impl</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> <span class='ident'>Drop</span> <span class='kw'>for</span> <span class='ident'>IntoIter</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> { <span class='kw'>fn</span> <span class='ident'>drop</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>) { <span class='comment'>// only need to ensure all our elements are read;</span> <span class='comment'>// buffer will clean itself up afterwards.</span> <span class='kw'>for</span> _ <span class='kw'>in</span> <span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='op'>*</span><span class='self'>self</span> {} } } <span class='kw'>impl</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> <span class='ident'>Vec</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> { <span class='kw'>pub</span> <span class='kw'>fn</span> <span class='ident'>into_iter</span>(<span class='self'>self</span>) <span class='op'>-&gt;</span> <span class='ident'>IntoIter</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> { <span class='kw'>unsafe</span> { <span class='comment'>// need to use ptr::read to unsafely move the buf out since it&#39;s</span> <span class='comment'>// not Copy, and Vec implements Drop (so we can&#39;t destructure it).</span> <span class='kw'>let</span> <span class='ident'>buf</span> <span class='op'>=</span> <span class='ident'>ptr</span>::<span class='ident'>read</span>(<span class='kw-2'>&amp;</span><span class='self'>self</span>.<span class='ident'>buf</span>); <span class='kw'>let</span> <span class='ident'>len</span> <span class='op'>=</span> <span class='self'>self</span>.<span class='ident'>len</span>; <span class='ident'>mem</span>::<span class='ident'>forget</span>(<span class='self'>self</span>); <span class='ident'>IntoIter</span> { <span class='ident'>start</span>: <span class='op'>*</span><span class='ident'>buf</span>.<span class='ident'>ptr</span>, <span class='ident'>end</span>: <span class='ident'>buf</span>.<span class='ident'>ptr</span>.<span class='ident'>offset</span>(<span class='ident'>len</span> <span class='kw'>as</span> <span class='ident'>isize</span>), <span class='ident'>_buf</span>: <span class='ident'>buf</span>, } } } }</pre> <p>Much better.</p> <script type="text/javascript"> window.playgroundUrl = "https://play.rust-lang.org"; </script> <script src='rustbook.js'></script> <script src='playpen.js'></script> </div></div> </body> </html> <|start_filename|>docs/1.6/book/slice-patterns.html<|end_filename|> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="generator" content="rustdoc"> <title>スライスパターン</title> <link rel="stylesheet" type="text/css" href="rustbook.css"> <meta name="robots" content="noindex"> </head> <body class="rustdoc"> <!--[if lte IE 8]> <div class="warning"> This old browser is unsupported and will most likely display funky things. </div> <![endif]--> <div id="nav"> <button id="toggle-nav"> <span class="sr-only">Toggle navigation</span> <span class="bar"></span> <span class="bar"></span> <span class="bar"></span> </button> </div> <div id='toc' class='mobile-hidden'> <ul class='chapter'> <li><a href='README.html'><b>1.</b> Introduction</a> </li> <li><a href='getting-started.html'><b>2.</b> はじめる</a> </li> <li><a href='learn-rust.html'><b>3.</b> Rustを学ぶ</a> <ul class='section'> <li><a href='guessing-game.html'><b>3.1.</b> 数当てゲーム</a> </li> <li><a href='dining-philosophers.html'><b>3.2.</b> 食事する哲学者</a> </li> <li><a href='rust-inside-other-languages.html'><b>3.3.</b> 他言語と共存する</a> </li> </ul> </li> <li><a href='syntax-and-semantics.html'><b>4.</b> シンタックスとセマンティクス</a> <ul class='section'> <li><a href='variable-bindings.html'><b>4.1.</b> 変数束縛</a> </li> <li><a href='functions.html'><b>4.2.</b> 関数</a> </li> <li><a href='primitive-types.html'><b>4.3.</b> プリミティブ型</a> </li> <li><a href='comments.html'><b>4.4.</b> コメント</a> </li> <li><a href='if.html'><b>4.5.</b> if</a> </li> <li><a href='loops.html'><b>4.6.</b> ループ</a> </li> <li><a href='ownership.html'><b>4.7.</b> 所有権</a> </li> <li><a href='references-and-borrowing.html'><b>4.8.</b> 参照と借用</a> </li> <li><a href='lifetimes.html'><b>4.9.</b> ライフタイム</a> </li> <li><a href='mutability.html'><b>4.10.</b> ミュータビリティ</a> </li> <li><a href='structs.html'><b>4.11.</b> 構造体</a> </li> <li><a href='enums.html'><b>4.12.</b> 列挙型</a> </li> <li><a href='match.html'><b>4.13.</b> マッチ</a> </li> <li><a href='patterns.html'><b>4.14.</b> パターン</a> </li> <li><a href='method-syntax.html'><b>4.15.</b> メソッド構文</a> </li> <li><a href='vectors.html'><b>4.16.</b> ベクタ</a> </li> <li><a href='strings.html'><b>4.17.</b> 文字列</a> </li> <li><a href='generics.html'><b>4.18.</b> ジェネリクス</a> </li> <li><a href='traits.html'><b>4.19.</b> トレイト</a> </li> <li><a href='drop.html'><b>4.20.</b> Drop</a> </li> <li><a href='if-let.html'><b>4.21.</b> if let</a> </li> <li><a href='trait-objects.html'><b>4.22.</b> トレイトオブジェクト</a> </li> <li><a href='closures.html'><b>4.23.</b> クロージャ</a> </li> <li><a href='ufcs.html'><b>4.24.</b> 共通の関数呼出構文</a> </li> <li><a href='crates-and-modules.html'><b>4.25.</b> クレートとモジュール</a> </li> <li><a href='const-and-static.html'><b>4.26.</b> `const` と `static`</a> </li> <li><a href='attributes.html'><b>4.27.</b> アトリビュート</a> </li> <li><a href='type-aliases.html'><b>4.28.</b> `type` エイリアス</a> </li> <li><a href='casting-between-types.html'><b>4.29.</b> 型間のキャスト</a> </li> <li><a href='associated-types.html'><b>4.30.</b> 関連型</a> </li> <li><a href='unsized-types.html'><b>4.31.</b> サイズ不定型</a> </li> <li><a href='operators-and-overloading.html'><b>4.32.</b> 演算子とオーバーロード</a> </li> <li><a href='deref-coercions.html'><b>4.33.</b> Derefによる型強制</a> </li> <li><a href='macros.html'><b>4.34.</b> マクロ</a> </li> <li><a href='raw-pointers.html'><b>4.35.</b> 生ポインタ</a> </li> <li><a href='unsafe.html'><b>4.36.</b> `unsafe`</a> </li> </ul> </li> <li><a href='effective-rust.html'><b>5.</b> Effective Rust</a> <ul class='section'> <li><a href='the-stack-and-the-heap.html'><b>5.1.</b> スタックとヒープ</a> </li> <li><a href='testing.html'><b>5.2.</b> テスト</a> </li> <li><a href='conditional-compilation.html'><b>5.3.</b> 条件付きコンパイル</a> </li> <li><a href='documentation.html'><b>5.4.</b> ドキュメント</a> </li> <li><a href='iterators.html'><b>5.5.</b> イテレータ</a> </li> <li><a href='concurrency.html'><b>5.6.</b> 並行性</a> </li> <li><a href='error-handling.html'><b>5.7.</b> エラーハンドリング</a> </li> <li><a href='choosing-your-guarantees.html'><b>5.8.</b> 保証を選ぶ</a> </li> <li><a href='ffi.html'><b>5.9.</b> 他言語関数インターフェース</a> </li> <li><a href='borrow-and-asref.html'><b>5.10.</b> BorrowとAsRef</a> </li> <li><a href='release-channels.html'><b>5.11.</b> リリースチャネル</a> </li> <li><a href='using-rust-without-the-standard-library.html'><b>5.12.</b> 標準ライブラリ無しでRustを使う</a> </li> </ul> </li> <li><a href='nightly-rust.html'><b>6.</b> Nightly Rust</a> <ul class='section'> <li><a href='compiler-plugins.html'><b>6.1.</b> コンパイラプラグイン</a> </li> <li><a href='inline-assembly.html'><b>6.2.</b> インラインアセンブリ</a> </li> <li><a href='no-stdlib.html'><b>6.3.</b> No stdlib</a> </li> <li><a href='intrinsics.html'><b>6.4.</b> Intrinsic</a> </li> <li><a href='lang-items.html'><b>6.5.</b> 言語アイテム</a> </li> <li><a href='advanced-linking.html'><b>6.6.</b> 高度なリンキング</a> </li> <li><a href='benchmark-tests.html'><b>6.7.</b> ベンチマークテスト</a> </li> <li><a href='box-syntax-and-patterns.html'><b>6.8.</b> Box構文とパターン</a> </li> <li><a class='active' href='slice-patterns.html'><b>6.9.</b> スライスパターン</a> </li> <li><a href='associated-constants.html'><b>6.10.</b> 関連定数</a> </li> <li><a href='custom-allocators.html'><b>6.11.</b> カスタムアロケータ</a> </li> </ul> </li> <li><a href='glossary.html'><b>7.</b> 用語集</a> </li> <li><a href='syntax-index.html'><b>8.</b> 構文の索引</a> </li> <li><a href='bibliography.html'><b>9.</b> 関係書目</a> </li> </ul> </div> <div id='page-wrapper'> <div id='page'> <blockquote class="header-caveat"> <p> <strong>注意: <a href="https://doc.rust-jp.rs/book-ja/">最新版のドキュメントをご覧ください。</a></strong>この第1版ドキュメントは古くなっており、最新情報が反映されていません。リンク先のドキュメントが現在の Rust の最新のドキュメントです。 </p> </blockquote> <h1 class="title">スライスパターン</h1> <!-- % Slice patterns --> <!-- If you want to match against a slice or array, you can use `&` with the --> <!-- `slice_patterns` feature: --> <p>スライスや配列に対してマッチを行いたい場合、 <code>slice_patterns</code> フィーチャを有効にすると以下のように <code>&amp;</code> を使うことができます。</p> <span class='rusttest'>#![feature(slice_patterns)] fn main() { let v = vec![&quot;match_this&quot;, &quot;1&quot;]; match &amp;v[..] { [&quot;match_this&quot;, second] =&gt; println!(&quot;The second element is {}&quot;, second), _ =&gt; {}, } } </span><pre class='rust rust-example-rendered'> <span class='attribute'>#<span class='op'>!</span>[<span class='ident'>feature</span>(<span class='ident'>slice_patterns</span>)]</span> <span class='kw'>fn</span> <span class='ident'>main</span>() { <span class='kw'>let</span> <span class='ident'>v</span> <span class='op'>=</span> <span class='macro'>vec</span><span class='macro'>!</span>[<span class='string'>&quot;match_this&quot;</span>, <span class='string'>&quot;1&quot;</span>]; <span class='kw'>match</span> <span class='kw-2'>&amp;</span><span class='ident'>v</span>[..] { [<span class='string'>&quot;match_this&quot;</span>, <span class='ident'>second</span>] <span class='op'>=&gt;</span> <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;The second element is {}&quot;</span>, <span class='ident'>second</span>), _ <span class='op'>=&gt;</span> {}, } }</pre> <!-- The `advanced_slice_patterns` gate lets you use `..` to indicate any number of --> <!-- elements inside a pattern matching a slice. This wildcard can only be used once --> <!-- for a given array. If there's an identifier before the `..`, the result of the --> <!-- slice will be bound to that name. For example: --> <p><code>advanced_slice_patterns</code> フィーチャを有効にすると、スライスにマッチするパターンの中で <code>..</code> を使ってその要素の数が任意であることを示すことができます。このワイルドカードは与えるパターン配列の中で一度だけ使うことができます。もし <code>..</code> の前に識別子(訳注: 以下の例では <code>inside</code> )があれば、そのスライスの結果はその識別子名に束縛されます。例えば以下のようになります。</p> <span class='rusttest'>#![feature(advanced_slice_patterns, slice_patterns)] fn is_symmetric(list: &amp;[u32]) -&gt; bool { match list { [] | [_] =&gt; true, [x, inside.., y] if x == y =&gt; is_symmetric(inside), _ =&gt; false } } fn main() { let sym = &amp;[0, 1, 4, 2, 4, 1, 0]; assert!(is_symmetric(sym)); let not_sym = &amp;[0, 1, 7, 2, 4, 1, 0]; assert!(!is_symmetric(not_sym)); } </span><pre class='rust rust-example-rendered'> <span class='attribute'>#<span class='op'>!</span>[<span class='ident'>feature</span>(<span class='ident'>advanced_slice_patterns</span>, <span class='ident'>slice_patterns</span>)]</span> <span class='kw'>fn</span> <span class='ident'>is_symmetric</span>(<span class='ident'>list</span>: <span class='kw-2'>&amp;</span>[<span class='ident'>u32</span>]) <span class='op'>-&gt;</span> <span class='ident'>bool</span> { <span class='kw'>match</span> <span class='ident'>list</span> { [] <span class='op'>|</span> [_] <span class='op'>=&gt;</span> <span class='boolvalue'>true</span>, [<span class='ident'>x</span>, <span class='ident'>inside</span>.., <span class='ident'>y</span>] <span class='kw'>if</span> <span class='ident'>x</span> <span class='op'>==</span> <span class='ident'>y</span> <span class='op'>=&gt;</span> <span class='ident'>is_symmetric</span>(<span class='ident'>inside</span>), _ <span class='op'>=&gt;</span> <span class='boolvalue'>false</span> } } <span class='kw'>fn</span> <span class='ident'>main</span>() { <span class='kw'>let</span> <span class='ident'>sym</span> <span class='op'>=</span> <span class='kw-2'>&amp;</span>[<span class='number'>0</span>, <span class='number'>1</span>, <span class='number'>4</span>, <span class='number'>2</span>, <span class='number'>4</span>, <span class='number'>1</span>, <span class='number'>0</span>]; <span class='macro'>assert</span><span class='macro'>!</span>(<span class='ident'>is_symmetric</span>(<span class='ident'>sym</span>)); <span class='kw'>let</span> <span class='ident'>not_sym</span> <span class='op'>=</span> <span class='kw-2'>&amp;</span>[<span class='number'>0</span>, <span class='number'>1</span>, <span class='number'>7</span>, <span class='number'>2</span>, <span class='number'>4</span>, <span class='number'>1</span>, <span class='number'>0</span>]; <span class='macro'>assert</span><span class='macro'>!</span>(<span class='op'>!</span><span class='ident'>is_symmetric</span>(<span class='ident'>not_sym</span>)); }</pre> <script type="text/javascript"> window.playgroundUrl = "https://play.rust-lang.org"; </script> <script src='rustbook.js'></script> <script src='playpen.js'></script> </div></div> </body> </html> <|start_filename|>docs/1.6/book/patterns.html<|end_filename|> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="generator" content="rustdoc"> <title>パターン</title> <link rel="stylesheet" type="text/css" href="rustbook.css"> <meta name="robots" content="noindex"> </head> <body class="rustdoc"> <!--[if lte IE 8]> <div class="warning"> This old browser is unsupported and will most likely display funky things. </div> <![endif]--> <div id="nav"> <button id="toggle-nav"> <span class="sr-only">Toggle navigation</span> <span class="bar"></span> <span class="bar"></span> <span class="bar"></span> </button> </div> <div id='toc' class='mobile-hidden'> <ul class='chapter'> <li><a href='README.html'><b>1.</b> Introduction</a> </li> <li><a href='getting-started.html'><b>2.</b> はじめる</a> </li> <li><a href='learn-rust.html'><b>3.</b> Rustを学ぶ</a> <ul class='section'> <li><a href='guessing-game.html'><b>3.1.</b> 数当てゲーム</a> </li> <li><a href='dining-philosophers.html'><b>3.2.</b> 食事する哲学者</a> </li> <li><a href='rust-inside-other-languages.html'><b>3.3.</b> 他言語と共存する</a> </li> </ul> </li> <li><a href='syntax-and-semantics.html'><b>4.</b> シンタックスとセマンティクス</a> <ul class='section'> <li><a href='variable-bindings.html'><b>4.1.</b> 変数束縛</a> </li> <li><a href='functions.html'><b>4.2.</b> 関数</a> </li> <li><a href='primitive-types.html'><b>4.3.</b> プリミティブ型</a> </li> <li><a href='comments.html'><b>4.4.</b> コメント</a> </li> <li><a href='if.html'><b>4.5.</b> if</a> </li> <li><a href='loops.html'><b>4.6.</b> ループ</a> </li> <li><a href='ownership.html'><b>4.7.</b> 所有権</a> </li> <li><a href='references-and-borrowing.html'><b>4.8.</b> 参照と借用</a> </li> <li><a href='lifetimes.html'><b>4.9.</b> ライフタイム</a> </li> <li><a href='mutability.html'><b>4.10.</b> ミュータビリティ</a> </li> <li><a href='structs.html'><b>4.11.</b> 構造体</a> </li> <li><a href='enums.html'><b>4.12.</b> 列挙型</a> </li> <li><a href='match.html'><b>4.13.</b> マッチ</a> </li> <li><a class='active' href='patterns.html'><b>4.14.</b> パターン</a> </li> <li><a href='method-syntax.html'><b>4.15.</b> メソッド構文</a> </li> <li><a href='vectors.html'><b>4.16.</b> ベクタ</a> </li> <li><a href='strings.html'><b>4.17.</b> 文字列</a> </li> <li><a href='generics.html'><b>4.18.</b> ジェネリクス</a> </li> <li><a href='traits.html'><b>4.19.</b> トレイト</a> </li> <li><a href='drop.html'><b>4.20.</b> Drop</a> </li> <li><a href='if-let.html'><b>4.21.</b> if let</a> </li> <li><a href='trait-objects.html'><b>4.22.</b> トレイトオブジェクト</a> </li> <li><a href='closures.html'><b>4.23.</b> クロージャ</a> </li> <li><a href='ufcs.html'><b>4.24.</b> 共通の関数呼出構文</a> </li> <li><a href='crates-and-modules.html'><b>4.25.</b> クレートとモジュール</a> </li> <li><a href='const-and-static.html'><b>4.26.</b> `const` と `static`</a> </li> <li><a href='attributes.html'><b>4.27.</b> アトリビュート</a> </li> <li><a href='type-aliases.html'><b>4.28.</b> `type` エイリアス</a> </li> <li><a href='casting-between-types.html'><b>4.29.</b> 型間のキャスト</a> </li> <li><a href='associated-types.html'><b>4.30.</b> 関連型</a> </li> <li><a href='unsized-types.html'><b>4.31.</b> サイズ不定型</a> </li> <li><a href='operators-and-overloading.html'><b>4.32.</b> 演算子とオーバーロード</a> </li> <li><a href='deref-coercions.html'><b>4.33.</b> Derefによる型強制</a> </li> <li><a href='macros.html'><b>4.34.</b> マクロ</a> </li> <li><a href='raw-pointers.html'><b>4.35.</b> 生ポインタ</a> </li> <li><a href='unsafe.html'><b>4.36.</b> `unsafe`</a> </li> </ul> </li> <li><a href='effective-rust.html'><b>5.</b> Effective Rust</a> <ul class='section'> <li><a href='the-stack-and-the-heap.html'><b>5.1.</b> スタックとヒープ</a> </li> <li><a href='testing.html'><b>5.2.</b> テスト</a> </li> <li><a href='conditional-compilation.html'><b>5.3.</b> 条件付きコンパイル</a> </li> <li><a href='documentation.html'><b>5.4.</b> ドキュメント</a> </li> <li><a href='iterators.html'><b>5.5.</b> イテレータ</a> </li> <li><a href='concurrency.html'><b>5.6.</b> 並行性</a> </li> <li><a href='error-handling.html'><b>5.7.</b> エラーハンドリング</a> </li> <li><a href='choosing-your-guarantees.html'><b>5.8.</b> 保証を選ぶ</a> </li> <li><a href='ffi.html'><b>5.9.</b> 他言語関数インターフェース</a> </li> <li><a href='borrow-and-asref.html'><b>5.10.</b> BorrowとAsRef</a> </li> <li><a href='release-channels.html'><b>5.11.</b> リリースチャネル</a> </li> <li><a href='using-rust-without-the-standard-library.html'><b>5.12.</b> 標準ライブラリ無しでRustを使う</a> </li> </ul> </li> <li><a href='nightly-rust.html'><b>6.</b> Nightly Rust</a> <ul class='section'> <li><a href='compiler-plugins.html'><b>6.1.</b> コンパイラプラグイン</a> </li> <li><a href='inline-assembly.html'><b>6.2.</b> インラインアセンブリ</a> </li> <li><a href='no-stdlib.html'><b>6.3.</b> No stdlib</a> </li> <li><a href='intrinsics.html'><b>6.4.</b> Intrinsic</a> </li> <li><a href='lang-items.html'><b>6.5.</b> 言語アイテム</a> </li> <li><a href='advanced-linking.html'><b>6.6.</b> 高度なリンキング</a> </li> <li><a href='benchmark-tests.html'><b>6.7.</b> ベンチマークテスト</a> </li> <li><a href='box-syntax-and-patterns.html'><b>6.8.</b> Box構文とパターン</a> </li> <li><a href='slice-patterns.html'><b>6.9.</b> スライスパターン</a> </li> <li><a href='associated-constants.html'><b>6.10.</b> 関連定数</a> </li> <li><a href='custom-allocators.html'><b>6.11.</b> カスタムアロケータ</a> </li> </ul> </li> <li><a href='glossary.html'><b>7.</b> 用語集</a> </li> <li><a href='syntax-index.html'><b>8.</b> 構文の索引</a> </li> <li><a href='bibliography.html'><b>9.</b> 関係書目</a> </li> </ul> </div> <div id='page-wrapper'> <div id='page'> <blockquote class="header-caveat"> <p> <strong>注意: <a href="https://doc.rust-jp.rs/book-ja/">最新版のドキュメントをご覧ください。</a></strong>この第1版ドキュメントは古くなっており、最新情報が反映されていません。リンク先のドキュメントが現在の Rust の最新のドキュメントです。 </p> </blockquote> <h1 class="title">パターン</h1> <!-- % Patterns --> <!-- Patterns are quite common in Rust. --> <p>パターンはRustにおいて極めて一般的です。</p> <!-- We use them in [variable bindings][bindings], [match statements][match], and other places, too.--> <p>パターンは <a href="variable-bindings.html">変数束縛</a>、 <a href="match.html">マッチ文</a> などで使われています。</p> <!--Let’s go on a whirlwind tour of all of the things patterns can do!--> <p>さあ、めくるめくパターンの旅を始めましょう!</p> <!-- A quick refresher: you can match against literals directly, and `_` acts as an ‘any’ case: --> <p>簡単な復習:リテラルに対しては直接マッチさせられます。また、 <code>_</code> は「任意の」ケースとして振る舞います。</p> <span class='rusttest'>fn main() { let x = 1; match x { 1 =&gt; println!(&quot;one&quot;), 2 =&gt; println!(&quot;two&quot;), 3 =&gt; println!(&quot;three&quot;), _ =&gt; println!(&quot;anything&quot;), } }</span><pre class='rust rust-example-rendered'> <span class='kw'>let</span> <span class='ident'>x</span> <span class='op'>=</span> <span class='number'>1</span>; <span class='kw'>match</span> <span class='ident'>x</span> { <span class='number'>1</span> <span class='op'>=&gt;</span> <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;one&quot;</span>), <span class='number'>2</span> <span class='op'>=&gt;</span> <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;two&quot;</span>), <span class='number'>3</span> <span class='op'>=&gt;</span> <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;three&quot;</span>), _ <span class='op'>=&gt;</span> <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;anything&quot;</span>), }</pre> <!-- This prints `one`. --> <p>これは <code>one</code> を表示します。</p> <!-- There’s one pitfall with patterns: like anything that introduces a new binding,they introduce shadowing. For example: --> <p>パターンには一つ落とし穴があります。新しい束縛を導入する他の構文と同様、パターンはシャドーイングをします。例えば:</p> <span class='rusttest'>fn main() { let x = &#39;x&#39;; let c = &#39;c&#39;; match c { x =&gt; println!(&quot;x: {} c: {}&quot;, x, c), } println!(&quot;x: {}&quot;, x) }</span><pre class='rust rust-example-rendered'> <span class='kw'>let</span> <span class='ident'>x</span> <span class='op'>=</span> <span class='string'>&#39;x&#39;</span>; <span class='kw'>let</span> <span class='ident'>c</span> <span class='op'>=</span> <span class='string'>&#39;c&#39;</span>; <span class='kw'>match</span> <span class='ident'>c</span> { <span class='ident'>x</span> <span class='op'>=&gt;</span> <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;x: {} c: {}&quot;</span>, <span class='ident'>x</span>, <span class='ident'>c</span>), } <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;x: {}&quot;</span>, <span class='ident'>x</span>)</pre> <!-- This prints:--> <p>これは以下のように出力します。</p> <pre><code class="language-text">x: c c: c x: x </code></pre> <!-- In other words, `x =>` matches the pattern and introduces a new binding named `x` that’s in scope for the match arm. Because we already have a binding named `x`, this new `x` shadows it. --> <p>別の言い方をすると、 <code>x =&gt;</code> は値をパターンにマッチさせ、マッチの腕内で有効な <code>x</code> という名前の束縛を導入します。既に <code>x</code> という束縛が存在していたので、新たに導入した <code>x</code> は、その古い <code>x</code> をシャドーイングします。</p> <!-- # Multiple patterns --> <h1 id='複式パターン' class='section-header'><a href='#複式パターン'>複式パターン</a></h1> <!-- You can match multiple patterns with `|`: --> <p><code>|</code> を使うと、複数のパターンにマッチさせることができます:</p> <span class='rusttest'>fn main() { let x = 1; match x { 1 | 2 =&gt; println!(&quot;one or two&quot;), 3 =&gt; println!(&quot;three&quot;), _ =&gt; println!(&quot;anything&quot;), } }</span><pre class='rust rust-example-rendered'> <span class='kw'>let</span> <span class='ident'>x</span> <span class='op'>=</span> <span class='number'>1</span>; <span class='kw'>match</span> <span class='ident'>x</span> { <span class='number'>1</span> <span class='op'>|</span> <span class='number'>2</span> <span class='op'>=&gt;</span> <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;one or two&quot;</span>), <span class='number'>3</span> <span class='op'>=&gt;</span> <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;three&quot;</span>), _ <span class='op'>=&gt;</span> <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;anything&quot;</span>), }</pre> <!--This prints `one or two`.--> <p>これは、 <code>one or two</code> を出力します。</p> <!-- # Destructuring --> <h1 id='分配束縛' class='section-header'><a href='#分配束縛'>分配束縛</a></h1> <!-- If you have a compound data type, like a [`struct`][struct], you can destructure it inside of a pattern: --> <p><a href="structs.html"><code>struct</code></a> のような複合データ型が存在するとき、パターン内でその値を分解することができます。</p> <span class='rusttest'>fn main() { struct Point { x: i32, y: i32, } let origin = Point { x: 0, y: 0 }; match origin { Point { x, y } =&gt; println!(&quot;({},{})&quot;, x, y), } }</span><pre class='rust rust-example-rendered'> <span class='kw'>struct</span> <span class='ident'>Point</span> { <span class='ident'>x</span>: <span class='ident'>i32</span>, <span class='ident'>y</span>: <span class='ident'>i32</span>, } <span class='kw'>let</span> <span class='ident'>origin</span> <span class='op'>=</span> <span class='ident'>Point</span> { <span class='ident'>x</span>: <span class='number'>0</span>, <span class='ident'>y</span>: <span class='number'>0</span> }; <span class='kw'>match</span> <span class='ident'>origin</span> { <span class='ident'>Point</span> { <span class='ident'>x</span>, <span class='ident'>y</span> } <span class='op'>=&gt;</span> <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;({},{})&quot;</span>, <span class='ident'>x</span>, <span class='ident'>y</span>), }</pre> <!-- We can use `:` to give a value a different name.--> <p>値に別の名前を付けたいときは、 <code>:</code> を使うことができます。</p> <span class='rusttest'>fn main() { struct Point { x: i32, y: i32, } let origin = Point { x: 0, y: 0 }; match origin { Point { x: x1, y: y1 } =&gt; println!(&quot;({},{})&quot;, x1, y1), } }</span><pre class='rust rust-example-rendered'> <span class='kw'>struct</span> <span class='ident'>Point</span> { <span class='ident'>x</span>: <span class='ident'>i32</span>, <span class='ident'>y</span>: <span class='ident'>i32</span>, } <span class='kw'>let</span> <span class='ident'>origin</span> <span class='op'>=</span> <span class='ident'>Point</span> { <span class='ident'>x</span>: <span class='number'>0</span>, <span class='ident'>y</span>: <span class='number'>0</span> }; <span class='kw'>match</span> <span class='ident'>origin</span> { <span class='ident'>Point</span> { <span class='ident'>x</span>: <span class='ident'>x1</span>, <span class='ident'>y</span>: <span class='ident'>y1</span> } <span class='op'>=&gt;</span> <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;({},{})&quot;</span>, <span class='ident'>x1</span>, <span class='ident'>y1</span>), }</pre> <!-- If we only care about some of the values, we don’t have to give them all names: --> <p>値の一部にだけ興味がある場合は、値のすべてに名前を付ける必要はありません。</p> <span class='rusttest'>fn main() { struct Point { x: i32, y: i32, } let origin = Point { x: 0, y: 0 }; match origin { Point { x, .. } =&gt; println!(&quot;x is {}&quot;, x), } }</span><pre class='rust rust-example-rendered'> <span class='kw'>struct</span> <span class='ident'>Point</span> { <span class='ident'>x</span>: <span class='ident'>i32</span>, <span class='ident'>y</span>: <span class='ident'>i32</span>, } <span class='kw'>let</span> <span class='ident'>origin</span> <span class='op'>=</span> <span class='ident'>Point</span> { <span class='ident'>x</span>: <span class='number'>0</span>, <span class='ident'>y</span>: <span class='number'>0</span> }; <span class='kw'>match</span> <span class='ident'>origin</span> { <span class='ident'>Point</span> { <span class='ident'>x</span>, .. } <span class='op'>=&gt;</span> <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;x is {}&quot;</span>, <span class='ident'>x</span>), }</pre> <!-- This prints `x is 0`. --> <p>これは <code>x is 0</code> を出力します。</p> <!-- You can do this kind of match on any member, not just the first:--> <p>最初のメンバだけでなく、どのメンバに対してもこの種のマッチを行うことができます。</p> <span class='rusttest'>fn main() { struct Point { x: i32, y: i32, } let origin = Point { x: 0, y: 0 }; match origin { Point { y, .. } =&gt; println!(&quot;y is {}&quot;, y), } }</span><pre class='rust rust-example-rendered'> <span class='kw'>struct</span> <span class='ident'>Point</span> { <span class='ident'>x</span>: <span class='ident'>i32</span>, <span class='ident'>y</span>: <span class='ident'>i32</span>, } <span class='kw'>let</span> <span class='ident'>origin</span> <span class='op'>=</span> <span class='ident'>Point</span> { <span class='ident'>x</span>: <span class='number'>0</span>, <span class='ident'>y</span>: <span class='number'>0</span> }; <span class='kw'>match</span> <span class='ident'>origin</span> { <span class='ident'>Point</span> { <span class='ident'>y</span>, .. } <span class='op'>=&gt;</span> <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;y is {}&quot;</span>, <span class='ident'>y</span>), }</pre> <!-- This prints `y is 0`. --> <p>これは <code>y is 0</code> を出力します。</p> <!-- This ‘destructuring’ behavior works on any compound data type, like [tuples][tuples] or [enums][enums]. --> <p>この「分配束縛」 (destructuring) と呼ばれる振る舞いは、 <a href="primitive-types.html#tuples">タプル</a> や <a href="enums.html">列挙型</a> のような、任意の複合データ型で使用できます。</p> <!-- # Ignoring bindings --> <h1 id='束縛の無視' class='section-header'><a href='#束縛の無視'>束縛の無視</a></h1> <!-- You can use `_` in a pattern to disregard the type and value.--> <p>パターン内の型や値を無視するために <code>_</code> を使うことができます。</p> <!-- For example, here’s a `match` against a `Result<T, E>`: --> <p>例として、 <code>Result&lt;T, E&gt;</code> に対して <code>match</code> をしてみましょう:</p> <span class='rusttest'>fn main() { let some_value: Result&lt;i32, &amp;&#39;static str&gt; = Err(&quot;There was an error&quot;); match some_value { Ok(value) =&gt; println!(&quot;got a value: {}&quot;, value), Err(_) =&gt; println!(&quot;an error occurred&quot;), } }</span><pre class='rust rust-example-rendered'> <span class='kw'>match</span> <span class='ident'>some_value</span> { <span class='prelude-val'>Ok</span>(<span class='ident'>value</span>) <span class='op'>=&gt;</span> <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;got a value: {}&quot;</span>, <span class='ident'>value</span>), <span class='prelude-val'>Err</span>(_) <span class='op'>=&gt;</span> <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;an error occurred&quot;</span>), }</pre> <!-- In the first arm, we bind the value inside the `Ok` variant to `value`. But in the `Err` arm, we use `_` to disregard the specific error, and just print a general error message. --> <p>最初の部分では <code>Ok</code> ヴァリアント内の値に <code>value</code> を束縛しています。しかし <code>Err</code> 部分では、ヴァリアント内のエラー情報を無視して一般的なエラーメッセージを表示するために <code>_</code> を使っています。</p> <!-- `_` is valid in any pattern that creates a binding. This can be useful to ignore parts of a larger structure: --> <p><code>_</code> は束縛を導入するどのようなパターンにおいても有効です。これは大きな構造の一部を無視する際に有用です。</p> <span class='rusttest'>fn main() { fn coordinate() -&gt; (i32, i32, i32) { // generate and return some sort of triple tuple // 3要素のタプルを生成して返す (1, 2, 3) } let (x, _, z) = coordinate(); }</span><pre class='rust rust-example-rendered'> <span class='kw'>fn</span> <span class='ident'>coordinate</span>() <span class='op'>-&gt;</span> (<span class='ident'>i32</span>, <span class='ident'>i32</span>, <span class='ident'>i32</span>) { <span class='comment'>// 3要素のタプルを生成して返す</span> } <span class='kw'>let</span> (<span class='ident'>x</span>, _, <span class='ident'>z</span>) <span class='op'>=</span> <span class='ident'>coordinate</span>();</pre> <!-- Here, we bind the first and last element of the tuple to `x` and `z`, but ignore the middle element. --> <p>ここでは、タプルの最初と最後の要素に <code>x</code> と <code>z</code> を束縛します。</p> <!-- Similarly, you can use `..` in a pattern to disregard multiple values. --> <p>同様に <code>..</code> でパターン内の複数の値を無視することができます。</p> <span class='rusttest'>fn main() { enum OptionalTuple { Value(i32, i32, i32), Missing, } let x = OptionalTuple::Value(5, -2, 3); match x { OptionalTuple::Value(..) =&gt; println!(&quot;Got a tuple!&quot;), OptionalTuple::Missing =&gt; println!(&quot;No such luck.&quot;), } }</span><pre class='rust rust-example-rendered'> <span class='kw'>enum</span> <span class='ident'>OptionalTuple</span> { <span class='ident'>Value</span>(<span class='ident'>i32</span>, <span class='ident'>i32</span>, <span class='ident'>i32</span>), <span class='ident'>Missing</span>, } <span class='kw'>let</span> <span class='ident'>x</span> <span class='op'>=</span> <span class='ident'>OptionalTuple</span>::<span class='ident'>Value</span>(<span class='number'>5</span>, <span class='op'>-</span><span class='number'>2</span>, <span class='number'>3</span>); <span class='kw'>match</span> <span class='ident'>x</span> { <span class='ident'>OptionalTuple</span>::<span class='ident'>Value</span>(..) <span class='op'>=&gt;</span> <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;Got a tuple!&quot;</span>), <span class='ident'>OptionalTuple</span>::<span class='ident'>Missing</span> <span class='op'>=&gt;</span> <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;No such luck.&quot;</span>), }</pre> <!--This prints `Got a tuple!`. --> <p>これは <code>Got a tuple!</code> を出力します。</p> <!-- # ref and ref mut --> <h1 id='ref-と-ref-mut' class='section-header'><a href='#ref-と-ref-mut'>ref と ref mut</a></h1> <!-- If you want to get a [reference][ref], use the `ref` keyword:--> <p><a href="references-and-borrowing.html">参照</a> を取得したいときは <code>ref</code> キーワードを使いましょう。</p> <span class='rusttest'>fn main() { let x = 5; match x { ref r =&gt; println!(&quot;Got a reference to {}&quot;, r), } }</span><pre class='rust rust-example-rendered'> <span class='kw'>let</span> <span class='ident'>x</span> <span class='op'>=</span> <span class='number'>5</span>; <span class='kw'>match</span> <span class='ident'>x</span> { <span class='kw-2'>ref</span> <span class='ident'>r</span> <span class='op'>=&gt;</span> <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;Got a reference to {}&quot;</span>, <span class='ident'>r</span>), }</pre> <!--This prints `Got a reference to 5`. --> <p>これは <code>Got a reference to 5</code> を出力します。</p> <!-- Here, the `r` inside the `match` has the type `&i32`. In other words, the `ref` keyword _creates_ a reference, for use in the pattern. If you need a mutable reference, `ref mut` will work in the same way: --> <p>ここで <code>match</code> 内の <code>r</code> は <code>&amp;i32</code> 型を持っています。言い換えると、 <code>ref</code> キーワードはパターン内で使う参照を <em>作り出します</em> 。ミュータブルな参照が必要な場合は、同様に <code>ref mut</code> を使います。</p> <span class='rusttest'>fn main() { let mut x = 5; match x { ref mut mr =&gt; println!(&quot;Got a mutable reference to {}&quot;, mr), } }</span><pre class='rust rust-example-rendered'> <span class='kw'>let</span> <span class='kw-2'>mut</span> <span class='ident'>x</span> <span class='op'>=</span> <span class='number'>5</span>; <span class='kw'>match</span> <span class='ident'>x</span> { <span class='kw-2'>ref</span> <span class='kw-2'>mut</span> <span class='ident'>mr</span> <span class='op'>=&gt;</span> <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;Got a mutable reference to {}&quot;</span>, <span class='ident'>mr</span>), }</pre> <!-- # Ranges --> <h1 id='範囲' class='section-header'><a href='#範囲'>範囲</a></h1> <!-- You can match a range of values with `...`: --> <p><code>...</code> で値の範囲をマッチさせることができます:</p> <span class='rusttest'>fn main() { let x = 1; match x { 1 ... 5 =&gt; println!(&quot;one through five&quot;), _ =&gt; println!(&quot;anything&quot;), } }</span><pre class='rust rust-example-rendered'> <span class='kw'>let</span> <span class='ident'>x</span> <span class='op'>=</span> <span class='number'>1</span>; <span class='kw'>match</span> <span class='ident'>x</span> { <span class='number'>1</span> ... <span class='number'>5</span> <span class='op'>=&gt;</span> <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;one through five&quot;</span>), _ <span class='op'>=&gt;</span> <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;anything&quot;</span>), }</pre> <!-- This prints `one through five`. --> <p>これは <code>one through five</code> を出力します。</p> <!-- Ranges are mostly used with integers and `char`s: --> <p>範囲は多くの場合、整数か <code>char</code> 型で使われます:</p> <span class='rusttest'>fn main() { let x = &#39;💅&#39;; match x { &#39;a&#39; ... &#39;j&#39; =&gt; println!(&quot;early letter&quot;), &#39;k&#39; ... &#39;z&#39; =&gt; println!(&quot;late letter&quot;), _ =&gt; println!(&quot;something else&quot;), } }</span><pre class='rust rust-example-rendered'> <span class='kw'>let</span> <span class='ident'>x</span> <span class='op'>=</span> <span class='string'>&#39;💅&#39;</span>; <span class='kw'>match</span> <span class='ident'>x</span> { <span class='string'>&#39;a&#39;</span> ... <span class='string'>&#39;j&#39;</span> <span class='op'>=&gt;</span> <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;early letter&quot;</span>), <span class='string'>&#39;k&#39;</span> ... <span class='string'>&#39;z&#39;</span> <span class='op'>=&gt;</span> <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;late letter&quot;</span>), _ <span class='op'>=&gt;</span> <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;something else&quot;</span>), }</pre> <!-- This prints `something else`. --> <p>これは <code>something else</code> を出力します。</p> <!-- # Bindings --> <h1 id='束縛' class='section-header'><a href='#束縛'>束縛</a></h1> <!-- You can bind values to names with `@`: --> <p><code>@</code> で値に名前を束縛することができます。</p> <span class='rusttest'>fn main() { let x = 1; match x { e @ 1 ... 5 =&gt; println!(&quot;got a range element {}&quot;, e), _ =&gt; println!(&quot;anything&quot;), } }</span><pre class='rust rust-example-rendered'> <span class='kw'>let</span> <span class='ident'>x</span> <span class='op'>=</span> <span class='number'>1</span>; <span class='kw'>match</span> <span class='ident'>x</span> { <span class='ident'>e</span> @ <span class='number'>1</span> ... <span class='number'>5</span> <span class='op'>=&gt;</span> <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;got a range element {}&quot;</span>, <span class='ident'>e</span>), _ <span class='op'>=&gt;</span> <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;anything&quot;</span>), }</pre> <!-- This prints `got a range element 1`. This is useful when you want to do a complicated match of part of a data structure: --> <p>これは <code>got a range element 1</code> を出力します。 データ構造の一部に対して複雑なマッチングをしたいときに有用です:</p> <span class='rusttest'>fn main() { #[derive(Debug)] struct Person { name: Option&lt;String&gt;, } let name = &quot;Steve&quot;.to_string(); let mut x: Option&lt;Person&gt; = Some(Person { name: Some(name) }); match x { Some(Person { name: ref a @ Some(_), .. }) =&gt; println!(&quot;{:?}&quot;, a), _ =&gt; {} } }</span><pre class='rust rust-example-rendered'> <span class='attribute'>#[<span class='ident'>derive</span>(<span class='ident'>Debug</span>)]</span> <span class='kw'>struct</span> <span class='ident'>Person</span> { <span class='ident'>name</span>: <span class='prelude-ty'>Option</span><span class='op'>&lt;</span><span class='ident'>String</span><span class='op'>&gt;</span>, } <span class='kw'>let</span> <span class='ident'>name</span> <span class='op'>=</span> <span class='string'>&quot;Steve&quot;</span>.<span class='ident'>to_string</span>(); <span class='kw'>let</span> <span class='kw-2'>mut</span> <span class='ident'>x</span>: <span class='prelude-ty'>Option</span><span class='op'>&lt;</span><span class='ident'>Person</span><span class='op'>&gt;</span> <span class='op'>=</span> <span class='prelude-val'>Some</span>(<span class='ident'>Person</span> { <span class='ident'>name</span>: <span class='prelude-val'>Some</span>(<span class='ident'>name</span>) }); <span class='kw'>match</span> <span class='ident'>x</span> { <span class='prelude-val'>Some</span>(<span class='ident'>Person</span> { <span class='ident'>name</span>: <span class='kw-2'>ref</span> <span class='ident'>a</span> @ <span class='prelude-val'>Some</span>(_), .. }) <span class='op'>=&gt;</span> <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;{:?}&quot;</span>, <span class='ident'>a</span>), _ <span class='op'>=&gt;</span> {} }</pre> <!--This prints `Some("Steve")`: we’ve bound the inner `name` to `a`.--> <p>これは <code>Some(&quot;Steve&quot;)</code> を出力します。内側の <code>name</code> の値への参照に <code>a</code> を束縛します。</p> <!-- If you use `@` with `|`, you need to make sure the name is bound in each part of the pattern: --> <p><code>@</code> を <code>|</code> と組み合わせて使う場合は、それぞれのパターンで同じ名前が束縛されるようにする必要があります:</p> <span class='rusttest'>fn main() { let x = 5; match x { e @ 1 ... 5 | e @ 8 ... 10 =&gt; println!(&quot;got a range element {}&quot;, e), _ =&gt; println!(&quot;anything&quot;), } }</span><pre class='rust rust-example-rendered'> <span class='kw'>let</span> <span class='ident'>x</span> <span class='op'>=</span> <span class='number'>5</span>; <span class='kw'>match</span> <span class='ident'>x</span> { <span class='ident'>e</span> @ <span class='number'>1</span> ... <span class='number'>5</span> <span class='op'>|</span> <span class='ident'>e</span> @ <span class='number'>8</span> ... <span class='number'>10</span> <span class='op'>=&gt;</span> <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;got a range element {}&quot;</span>, <span class='ident'>e</span>), _ <span class='op'>=&gt;</span> <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;anything&quot;</span>), }</pre> <!-- # Guards --> <h1 id='ガード' class='section-header'><a href='#ガード'>ガード</a></h1> <!--You can introduce ‘match guards’ with `if`: --> <p><code>if</code> を使うことでマッチガードを導入することができます:</p> <span class='rusttest'>fn main() { enum OptionalInt { Value(i32), Missing, } let x = OptionalInt::Value(5); match x { OptionalInt::Value(i) if i &gt; 5 =&gt; println!(&quot;Got an int bigger than five!&quot;), OptionalInt::Value(..) =&gt; println!(&quot;Got an int!&quot;), OptionalInt::Missing =&gt; println!(&quot;No such luck.&quot;), } }</span><pre class='rust rust-example-rendered'> <span class='kw'>enum</span> <span class='ident'>OptionalInt</span> { <span class='ident'>Value</span>(<span class='ident'>i32</span>), <span class='ident'>Missing</span>, } <span class='kw'>let</span> <span class='ident'>x</span> <span class='op'>=</span> <span class='ident'>OptionalInt</span>::<span class='ident'>Value</span>(<span class='number'>5</span>); <span class='kw'>match</span> <span class='ident'>x</span> { <span class='ident'>OptionalInt</span>::<span class='ident'>Value</span>(<span class='ident'>i</span>) <span class='kw'>if</span> <span class='ident'>i</span> <span class='op'>&gt;</span> <span class='number'>5</span> <span class='op'>=&gt;</span> <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;Got an int bigger than five!&quot;</span>), <span class='ident'>OptionalInt</span>::<span class='ident'>Value</span>(..) <span class='op'>=&gt;</span> <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;Got an int!&quot;</span>), <span class='ident'>OptionalInt</span>::<span class='ident'>Missing</span> <span class='op'>=&gt;</span> <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;No such luck.&quot;</span>), }</pre> <!--This prints `Got an int!`. --> <p>これは <code>Got an int!</code> を出力します。</p> <!--If you’re using `if` with multiple patterns, the `if` applies to both sides:--> <p>複式パターンで <code>if</code> を使うと、 <code>if</code> は <code>|</code> の両側に適用されます:</p> <span class='rusttest'>fn main() { let x = 4; let y = false; match x { 4 | 5 if y =&gt; println!(&quot;yes&quot;), _ =&gt; println!(&quot;no&quot;), } }</span><pre class='rust rust-example-rendered'> <span class='kw'>let</span> <span class='ident'>x</span> <span class='op'>=</span> <span class='number'>4</span>; <span class='kw'>let</span> <span class='ident'>y</span> <span class='op'>=</span> <span class='boolvalue'>false</span>; <span class='kw'>match</span> <span class='ident'>x</span> { <span class='number'>4</span> <span class='op'>|</span> <span class='number'>5</span> <span class='kw'>if</span> <span class='ident'>y</span> <span class='op'>=&gt;</span> <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;yes&quot;</span>), _ <span class='op'>=&gt;</span> <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;no&quot;</span>), }</pre> <!--This prints `no`, because the `if` applies to the whole of `4 | 5`, and not to just the `5`. In other words, the precedence of `if` behaves like this: --> <p>これは <code>no</code> を出力します。なぜなら <code>if</code> は <code>4 | 5</code> 全体に適用されるのであって、 <code>5</code> 単独に対して適用されるのではないからです。つまり <code>if</code> 節は以下のように振舞います:</p> <pre><code class="language-text">(4 | 5) if y =&gt; ... </code></pre> <!--not this: --> <p>次のようには解釈されません:</p> <pre><code class="language-text">4 | (5 if y) =&gt; ... </code></pre> <!-- # Mix and Match --> <h1 id='混ぜてマッチ' class='section-header'><a href='#混ぜてマッチ'>混ぜてマッチ</a></h1> <!--Whew! That’s a lot of different ways to match things, and they can all be mixed and matched, depending on what you’re doing: --> <p>ふう、マッチには様々な方法があるのですね。やりたいことに応じて、それらを混ぜてマッチさせることもできます:</p> <span class='rusttest'>fn main() { match x { Foo { x: Some(ref name), y: None } =&gt; ... } }</span><pre class='rust rust-example-rendered'> <span class='kw'>match</span> <span class='ident'>x</span> { <span class='ident'>Foo</span> { <span class='ident'>x</span>: <span class='prelude-val'>Some</span>(<span class='kw-2'>ref</span> <span class='ident'>name</span>), <span class='ident'>y</span>: <span class='prelude-val'>None</span> } <span class='op'>=&gt;</span> ... }</pre> <!-- Patterns are very powerful. Make good use of them. --> <p>パターンはとても強力です。上手に使いましょう。</p> <script type="text/javascript"> window.playgroundUrl = "https://play.rust-lang.org"; </script> <script src='rustbook.js'></script> <script src='playpen.js'></script> </div></div> </body> </html> <|start_filename|>docs/1.9/nomicon/phantom-data.html<|end_filename|> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="generator" content="rustdoc"> <title>PhantomData</title> <link rel="stylesheet" type="text/css" href="rustbook.css"> <meta name="robots" content="noindex"> </head> <body class="rustdoc"> <!--[if lte IE 8]> <div class="warning"> This old browser is unsupported and will most likely display funky things. </div> <![endif]--> <div id="nav"> <button id="toggle-nav"> <span class="sr-only">Toggle navigation</span> <span class="bar"></span> <span class="bar"></span> <span class="bar"></span> </button> </div> <div id='toc' class='mobile-hidden'> <ul class='chapter'> <li><a href='README.html'><b>1.</b> Introduction</a> </li> <li><a href='meet-safe-and-unsafe.html'><b>2.</b> Meet Safe and Unsafe</a> <ul class='section'> <li><a href='safe-unsafe-meaning.html'><b>2.1.</b> How Safe and Unsafe Interact</a> </li> <li><a href='working-with-unsafe.html'><b>2.2.</b> Working with Unsafe</a> </li> </ul> </li> <li><a href='data.html'><b>3.</b> Data Layout</a> <ul class='section'> <li><a href='repr-rust.html'><b>3.1.</b> repr(Rust)</a> </li> <li><a href='exotic-sizes.html'><b>3.2.</b> Exotically Sized Types</a> </li> <li><a href='other-reprs.html'><b>3.3.</b> Other reprs</a> </li> </ul> </li> <li><a href='ownership.html'><b>4.</b> Ownership</a> <ul class='section'> <li><a href='references.html'><b>4.1.</b> References</a> </li> <li><a href='lifetimes.html'><b>4.2.</b> Lifetimes</a> </li> <li><a href='lifetime-mismatch.html'><b>4.3.</b> Limits of Lifetimes</a> </li> <li><a href='lifetime-elision.html'><b>4.4.</b> Lifetime Elision</a> </li> <li><a href='unbounded-lifetimes.html'><b>4.5.</b> Unbounded Lifetimes</a> </li> <li><a href='hrtb.html'><b>4.6.</b> Higher-Rank Trait Bounds</a> </li> <li><a href='subtyping.html'><b>4.7.</b> Subtyping and Variance</a> </li> <li><a href='dropck.html'><b>4.8.</b> Drop Check</a> </li> <li><a class='active' href='phantom-data.html'><b>4.9.</b> PhantomData</a> </li> <li><a href='borrow-splitting.html'><b>4.10.</b> Splitting Borrows</a> </li> </ul> </li> <li><a href='conversions.html'><b>5.</b> Type Conversions</a> <ul class='section'> <li><a href='coercions.html'><b>5.1.</b> Coercions</a> </li> <li><a href='dot-operator.html'><b>5.2.</b> The Dot Operator</a> </li> <li><a href='casts.html'><b>5.3.</b> Casts</a> </li> <li><a href='transmutes.html'><b>5.4.</b> Transmutes</a> </li> </ul> </li> <li><a href='uninitialized.html'><b>6.</b> Uninitialized Memory</a> <ul class='section'> <li><a href='checked-uninit.html'><b>6.1.</b> Checked</a> </li> <li><a href='drop-flags.html'><b>6.2.</b> Drop Flags</a> </li> <li><a href='unchecked-uninit.html'><b>6.3.</b> Unchecked</a> </li> </ul> </li> <li><a href='obrm.html'><b>7.</b> Ownership Based Resource Management</a> <ul class='section'> <li><a href='constructors.html'><b>7.1.</b> Constructors</a> </li> <li><a href='destructors.html'><b>7.2.</b> Destructors</a> </li> <li><a href='leaking.html'><b>7.3.</b> Leaking</a> </li> </ul> </li> <li><a href='unwinding.html'><b>8.</b> Unwinding</a> <ul class='section'> <li><a href='exception-safety.html'><b>8.1.</b> Exception Safety</a> </li> <li><a href='poisoning.html'><b>8.2.</b> Poisoning</a> </li> </ul> </li> <li><a href='concurrency.html'><b>9.</b> Concurrency</a> <ul class='section'> <li><a href='races.html'><b>9.1.</b> Races</a> </li> <li><a href='send-and-sync.html'><b>9.2.</b> Send and Sync</a> </li> <li><a href='atomics.html'><b>9.3.</b> Atomics</a> </li> </ul> </li> <li><a href='vec.html'><b>10.</b> Implementing Vec</a> <ul class='section'> <li><a href='vec-layout.html'><b>10.1.</b> Layout</a> </li> <li><a href='vec-alloc.html'><b>10.2.</b> Allocating</a> </li> <li><a href='vec-push-pop.html'><b>10.3.</b> Push and Pop</a> </li> <li><a href='vec-dealloc.html'><b>10.4.</b> Deallocating</a> </li> <li><a href='vec-deref.html'><b>10.5.</b> Deref</a> </li> <li><a href='vec-insert-remove.html'><b>10.6.</b> Insert and Remove</a> </li> <li><a href='vec-into-iter.html'><b>10.7.</b> IntoIter</a> </li> <li><a href='vec-raw.html'><b>10.8.</b> RawVec</a> </li> <li><a href='vec-drain.html'><b>10.9.</b> Drain</a> </li> <li><a href='vec-zsts.html'><b>10.10.</b> Handling Zero-Sized Types</a> </li> <li><a href='vec-final.html'><b>10.11.</b> Final Code</a> </li> </ul> </li> <li><a href='arc-and-mutex.html'><b>11.</b> Implementing Arc and Mutex</a> </li> </ul> </div> <div id='page-wrapper'> <div id='page'> <blockquote class="header-caveat"> <p> <strong>注意: <a href="https://doc.rust-jp.rs/book-ja/">最新版のドキュメントをご覧ください。</a></strong>この第1版ドキュメントは古くなっており、最新情報が反映されていません。リンク先のドキュメントが現在の Rust の最新のドキュメントです。 </p> </blockquote> <h1 class="title">PhantomData</h1> <p>When working with unsafe code, we can often end up in a situation where types or lifetimes are logically associated with a struct, but not actually part of a field. This most commonly occurs with lifetimes. For instance, the <code>Iter</code> for <code>&amp;&#39;a [T]</code> is (approximately) defined as follows:</p> <span class='rusttest'>fn main() { struct Iter&lt;&#39;a, T: &#39;a&gt; { ptr: *const T, end: *const T, } }</span><pre class='rust rust-example-rendered'> <span class='kw'>struct</span> <span class='ident'>Iter</span><span class='op'>&lt;</span><span class='lifetime'>&#39;a</span>, <span class='ident'>T</span>: <span class='lifetime'>&#39;a</span><span class='op'>&gt;</span> { <span class='ident'>ptr</span>: <span class='op'>*</span><span class='kw'>const</span> <span class='ident'>T</span>, <span class='ident'>end</span>: <span class='op'>*</span><span class='kw'>const</span> <span class='ident'>T</span>, }</pre> <p>However because <code>&#39;a</code> is unused within the struct&#39;s body, it&#39;s <em>unbounded</em>. Because of the troubles this has historically caused, unbounded lifetimes and types are <em>forbidden</em> in struct definitions. Therefore we must somehow refer to these types in the body. Correctly doing this is necessary to have correct variance and drop checking.</p> <p>We do this using <code>PhantomData</code>, which is a special marker type. <code>PhantomData</code> consumes no space, but simulates a field of the given type for the purpose of static analysis. This was deemed to be less error-prone than explicitly telling the type-system the kind of variance that you want, while also providing other useful such as the information needed by drop check.</p> <p>Iter logically contains a bunch of <code>&amp;&#39;a T</code>s, so this is exactly what we tell the PhantomData to simulate:</p> <span class='rusttest'>fn main() { use std::marker; struct Iter&lt;&#39;a, T: &#39;a&gt; { ptr: *const T, end: *const T, _marker: marker::PhantomData&lt;&amp;&#39;a T&gt;, } }</span><pre class='rust rust-example-rendered'> <span class='kw'>use</span> <span class='ident'>std</span>::<span class='ident'>marker</span>; <span class='kw'>struct</span> <span class='ident'>Iter</span><span class='op'>&lt;</span><span class='lifetime'>&#39;a</span>, <span class='ident'>T</span>: <span class='lifetime'>&#39;a</span><span class='op'>&gt;</span> { <span class='ident'>ptr</span>: <span class='op'>*</span><span class='kw'>const</span> <span class='ident'>T</span>, <span class='ident'>end</span>: <span class='op'>*</span><span class='kw'>const</span> <span class='ident'>T</span>, <span class='ident'>_marker</span>: <span class='ident'>marker</span>::<span class='ident'>PhantomData</span><span class='op'>&lt;</span><span class='kw-2'>&amp;</span><span class='lifetime'>&#39;a</span> <span class='ident'>T</span><span class='op'>&gt;</span>, }</pre> <p>and that&#39;s it. The lifetime will be bounded, and your iterator will be variant over <code>&#39;a</code> and <code>T</code>. Everything Just Works.</p> <p>Another important example is Vec, which is (approximately) defined as follows:</p> <span class='rusttest'>fn main() { struct Vec&lt;T&gt; { data: *const T, // *const for variance! len: usize, cap: usize, } }</span><pre class='rust rust-example-rendered'> <span class='kw'>struct</span> <span class='ident'>Vec</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> { <span class='ident'>data</span>: <span class='op'>*</span><span class='kw'>const</span> <span class='ident'>T</span>, <span class='comment'>// *const for variance!</span> <span class='ident'>len</span>: <span class='ident'>usize</span>, <span class='ident'>cap</span>: <span class='ident'>usize</span>, }</pre> <p>Unlike the previous example it <em>appears</em> that everything is exactly as we want. Every generic argument to Vec shows up in the at least one field. Good to go!</p> <p>Nope.</p> <p>The drop checker will generously determine that Vec<T> does not own any values of type T. This will in turn make it conclude that it doesn&#39;t need to worry about Vec dropping any T&#39;s in its destructor for determining drop check soundness. This will in turn allow people to create unsoundness using Vec&#39;s destructor.</p> <p>In order to tell dropck that we <em>do</em> own values of type T, and therefore may drop some T&#39;s when <em>we</em> drop, we must add an extra PhantomData saying exactly that:</p> <span class='rusttest'>fn main() { use std::marker; struct Vec&lt;T&gt; { data: *const T, // *const for covariance! len: usize, cap: usize, _marker: marker::PhantomData&lt;T&gt;, } }</span><pre class='rust rust-example-rendered'> <span class='kw'>use</span> <span class='ident'>std</span>::<span class='ident'>marker</span>; <span class='kw'>struct</span> <span class='ident'>Vec</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> { <span class='ident'>data</span>: <span class='op'>*</span><span class='kw'>const</span> <span class='ident'>T</span>, <span class='comment'>// *const for covariance!</span> <span class='ident'>len</span>: <span class='ident'>usize</span>, <span class='ident'>cap</span>: <span class='ident'>usize</span>, <span class='ident'>_marker</span>: <span class='ident'>marker</span>::<span class='ident'>PhantomData</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span>, }</pre> <p>Raw pointers that own an allocation is such a pervasive pattern that the standard library made a utility for itself called <code>Unique&lt;T&gt;</code> which:</p> <ul> <li>wraps a <code>*const T</code> for variance</li> <li>includes a <code>PhantomData&lt;T&gt;</code>,</li> <li>auto-derives Send/Sync as if T was contained</li> <li>marks the pointer as NonZero for the null-pointer optimization</li> </ul> <script type="text/javascript"> window.playgroundUrl = "https://play.rust-lang.org"; </script> <script src='rustbook.js'></script> <script src='playpen.js'></script> </div></div> </body> </html> <|start_filename|>docs/1.9/style/features/modules.html<|end_filename|> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="generator" content="rustdoc"> <title>Modules</title> <link rel="stylesheet" type="text/css" href="../rustbook.css"> <meta name="robots" content="noindex"> </head> <body class="rustdoc"> <!--[if lte IE 8]> <div class="warning"> This old browser is unsupported and will most likely display funky things. </div> <![endif]--> <div id="nav"> <button id="toggle-nav"> <span class="sr-only">Toggle navigation</span> <span class="bar"></span> <span class="bar"></span> <span class="bar"></span> </button> </div> <div id='toc' class='mobile-hidden'> <ul class='chapter'> <li><a href='../README.html'><b>1.</b> Introduction</a> </li> <li><a href='../style/README.html'><b>2.</b> Style</a> <ul class='section'> <li><a href='../style/whitespace.html'><b>2.1.</b> Whitespace</a> </li> <li><a href='../style/comments.html'><b>2.2.</b> Comments</a> </li> <li><a href='../style/braces.html'><b>2.3.</b> Braces, semicolons, commas</a> </li> <li><a href='../style/naming/README.html'><b>2.4.</b> Naming</a> <ul class='section'> <li><a href='../style/naming/ownership.html'><b>2.4.1.</b> Ownership variants</a> </li> <li><a href='../style/naming/containers.html'><b>2.4.2.</b> Containers/wrappers</a> </li> <li><a href='../style/naming/conversions.html'><b>2.4.3.</b> Conversions</a> </li> <li><a href='../style/naming/iterators.html'><b>2.4.4.</b> Iterators</a> </li> </ul> </li> <li><a href='../style/imports.html'><b>2.5.</b> Imports</a> </li> <li><a href='../style/organization.html'><b>2.6.</b> Organization</a> </li> </ul> </li> <li><a href='../features/README.html'><b>3.</b> Guidelines by Rust feature</a> <ul class='section'> <li><a href='../features/let.html'><b>3.1.</b> Let binding</a> </li> <li><a href='../features/match.html'><b>3.2.</b> Pattern matching</a> </li> <li><a href='../features/loops.html'><b>3.3.</b> Loops</a> </li> <li><a href='../features/functions-and-methods/README.html'><b>3.4.</b> Functions and methods</a> <ul class='section'> <li><a href='../features/functions-and-methods/input.html'><b>3.4.1.</b> Input</a> </li> <li><a href='../features/functions-and-methods/output.html'><b>3.4.2.</b> Output</a> </li> <li><a href='../features/functions-and-methods/convenience.html'><b>3.4.3.</b> For convenience</a> </li> </ul> </li> <li><a href='../features/types/README.html'><b>3.5.</b> Types</a> <ul class='section'> <li><a href='../features/types/conversions.html'><b>3.5.1.</b> Conversions</a> </li> <li><a href='../features/types/newtype.html'><b>3.5.2.</b> The newtype pattern</a> </li> </ul> </li> <li><a href='../features/traits/README.html'><b>3.6.</b> Traits</a> <ul class='section'> <li><a href='../features/traits/generics.html'><b>3.6.1.</b> For generics</a> </li> <li><a href='../features/traits/objects.html'><b>3.6.2.</b> For objects</a> </li> <li><a href='../features/traits/overloading.html'><b>3.6.3.</b> For overloading</a> </li> <li><a href='../features/traits/extensions.html'><b>3.6.4.</b> For extensions</a> </li> <li><a href='../features/traits/reuse.html'><b>3.6.5.</b> For reuse</a> </li> <li><a href='../features/traits/common.html'><b>3.6.6.</b> Common traits</a> </li> </ul> </li> <li><a class='active' href='../features/modules.html'><b>3.7.</b> Modules</a> </li> <li><a href='../features/crates.html'><b>3.8.</b> Crates</a> </li> </ul> </li> <li><a href='../ownership/README.html'><b>4.</b> Ownership and resources</a> <ul class='section'> <li><a href='../ownership/constructors.html'><b>4.1.</b> Constructors</a> </li> <li><a href='../ownership/builders.html'><b>4.2.</b> Builders</a> </li> <li><a href='../ownership/destructors.html'><b>4.3.</b> Destructors</a> </li> <li><a href='../ownership/raii.html'><b>4.4.</b> RAII</a> </li> <li><a href='../ownership/cell-smart.html'><b>4.5.</b> Cells and smart pointers</a> </li> </ul> </li> <li><a href='../errors/README.html'><b>5.</b> Errors</a> <ul class='section'> <li><a href='../errors/signaling.html'><b>5.1.</b> Signaling</a> </li> <li><a href='../errors/handling.html'><b>5.2.</b> Handling</a> </li> <li><a href='../errors/propagation.html'><b>5.3.</b> Propagation</a> </li> <li><a href='../errors/ergonomics.html'><b>5.4.</b> Ergonomics</a> </li> </ul> </li> <li><a href='../safety/README.html'><b>6.</b> Safety and guarantees</a> <ul class='section'> <li><a href='../safety/unsafe.html'><b>6.1.</b> Using unsafe</a> </li> <li><a href='../safety/lib-guarantees.html'><b>6.2.</b> Library guarantees</a> </li> </ul> </li> <li><a href='../testing/README.html'><b>7.</b> Testing</a> <ul class='section'> <li><a href='../testing/unit.html'><b>7.1.</b> Unit testing</a> </li> </ul> </li> <li><a href='../platform.html'><b>8.</b> FFI, platform-specific code</a> </li> </ul> </div> <div id='page-wrapper'> <div id='page'> <blockquote class="header-caveat"> <p> <strong>注意: <a href="https://doc.rust-jp.rs/book-ja/">最新版のドキュメントをご覧ください。</a></strong>この第1版ドキュメントは古くなっており、最新情報が反映されていません。リンク先のドキュメントが現在の Rust の最新のドキュメントです。 </p> </blockquote> <h1 class="title">Modules</h1> <blockquote> <p><strong>[FIXME]</strong> What general guidelines should we provide for module design?</p> <p>We should discuss visibility, nesting, <code>mod.rs</code>, and any interesting patterns around modules.</p> </blockquote> <h3 id='headers-fixme-needs-rfc' class='section-header'><a href='#headers-fixme-needs-rfc'>Headers [FIXME: needs RFC]</a></h3> <p>Organize module headers as follows: 1. <a href="../style/imports.html">Imports</a>. 1. <code>mod</code> declarations. 1. <code>pub mod</code> declarations.</p> <h3 id='avoid-path-directives-fixme-needs-rfc' class='section-header'><a href='#avoid-path-directives-fixme-needs-rfc'>Avoid <code>path</code> directives. [FIXME: needs RFC]</a></h3> <p>Avoid using <code>#[path=&quot;...&quot;]</code> directives; make the file system and module hierarchy match, instead.</p> <h3 id='use-the-module-hierarchy-to-organize-apis-into-coherent-sections-fixme' class='section-header'><a href='#use-the-module-hierarchy-to-organize-apis-into-coherent-sections-fixme'>Use the module hierarchy to organize APIs into coherent sections. [FIXME]</a></h3> <blockquote> <p><strong>[FIXME]</strong> Flesh this out with examples; explain what a &quot;coherent section&quot; is with examples.</p> <p>The module hierarchy defines both the public and internal API of your module. Breaking related functionality into submodules makes it understandable to both users and contributors to the module.</p> </blockquote> <h3 id='place-modules-in-their-own-file-fixme-needs-rfc' class='section-header'><a href='#place-modules-in-their-own-file-fixme-needs-rfc'>Place modules in their own file. [FIXME: needs RFC]</a></h3> <blockquote> <p><strong>[FIXME]</strong> - &quot;&lt;100 lines&quot; is arbitrary, but it&#39;s a clearer recommendation than &quot;~1 page&quot; or similar suggestions that vary by screen size, etc.</p> </blockquote> <p>For all except very short modules (&lt;100 lines) and <a href="../testing/README.html">tests</a>, place the module <code>foo</code> in a separate file, as in:</p> <span class='rusttest'>fn main() { pub mod foo; // in foo.rs or foo/mod.rs pub fn bar() { println!(&quot;...&quot;); } /* ... */ }</span><pre class='rust rust-example-rendered'> <span class='kw'>pub</span> <span class='kw'>mod</span> <span class='ident'>foo</span>; <span class='comment'>// in foo.rs or foo/mod.rs</span> <span class='kw'>pub</span> <span class='kw'>fn</span> <span class='ident'>bar</span>() { <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;...&quot;</span>); } <span class='comment'>/* ... */</span></pre> <p>rather than declaring it inline:</p> <span class='rusttest'>fn main() { pub mod foo { pub fn bar() { println!(&quot;...&quot;); } /* ... */ } }</span><pre class='rust rust-example-rendered'> <span class='kw'>pub</span> <span class='kw'>mod</span> <span class='ident'>foo</span> { <span class='kw'>pub</span> <span class='kw'>fn</span> <span class='ident'>bar</span>() { <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;...&quot;</span>); } <span class='comment'>/* ... */</span> }</pre> <h4 id='use-subdirectories-for-modules-with-children-fixme-needs-rfc' class='section-header'><a href='#use-subdirectories-for-modules-with-children-fixme-needs-rfc'>Use subdirectories for modules with children. [FIXME: needs RFC]</a></h4> <p>For modules that themselves have submodules, place the module in a separate directory (e.g., <code>bar/mod.rs</code> for a module <code>bar</code>) rather than the same directory.</p> <p>Note the structure of <a href="https://doc.rust-lang.org/std/io/"><code>std::io</code></a>. Many of the submodules lack children, like <a href="https://doc.rust-lang.org/std/io/fs/"><code>io::fs</code></a> and <a href="https://doc.rust-lang.org/std/io/stdio/"><code>io::stdio</code></a>. On the other hand, <a href="https://doc.rust-lang.org/std/io/net/"><code>io::net</code></a> contains submodules, so it lives in a separate directory:</p> <span class='rusttest'>fn main() { io/mod.rs io/extensions.rs io/fs.rs io/net/mod.rs io/net/addrinfo.rs io/net/ip.rs io/net/tcp.rs io/net/udp.rs io/net/unix.rs io/pipe.rs ... }</span><pre class='rust rust-example-rendered'> <span class='ident'>io</span><span class='op'>/</span><span class='kw'>mod</span>.<span class='ident'>rs</span> <span class='ident'>io</span><span class='op'>/</span><span class='ident'>extensions</span>.<span class='ident'>rs</span> <span class='ident'>io</span><span class='op'>/</span><span class='ident'>fs</span>.<span class='ident'>rs</span> <span class='ident'>io</span><span class='op'>/</span><span class='ident'>net</span><span class='op'>/</span><span class='kw'>mod</span>.<span class='ident'>rs</span> <span class='ident'>io</span><span class='op'>/</span><span class='ident'>net</span><span class='op'>/</span><span class='ident'>addrinfo</span>.<span class='ident'>rs</span> <span class='ident'>io</span><span class='op'>/</span><span class='ident'>net</span><span class='op'>/</span><span class='ident'>ip</span>.<span class='ident'>rs</span> <span class='ident'>io</span><span class='op'>/</span><span class='ident'>net</span><span class='op'>/</span><span class='ident'>tcp</span>.<span class='ident'>rs</span> <span class='ident'>io</span><span class='op'>/</span><span class='ident'>net</span><span class='op'>/</span><span class='ident'>udp</span>.<span class='ident'>rs</span> <span class='ident'>io</span><span class='op'>/</span><span class='ident'>net</span><span class='op'>/</span><span class='ident'>unix</span>.<span class='ident'>rs</span> <span class='ident'>io</span><span class='op'>/</span><span class='ident'>pipe</span>.<span class='ident'>rs</span> ...</pre> <p>While it is possible to define all of <code>io</code> within a single directory, mirroring the module hierarchy in the directory structure makes submodules of <code>io::net</code> easier to find.</p> <h3 id='consider-top-level-definitions-or-reexports-fixme-needs-rfc' class='section-header'><a href='#consider-top-level-definitions-or-reexports-fixme-needs-rfc'>Consider top-level definitions or reexports. [FIXME: needs RFC]</a></h3> <p>For modules with submodules, define or <a href="https://doc.rust-lang.org/std/io/#reexports">reexport</a> commonly used definitions at the top level:</p> <ul> <li>Functionality relevant to the module itself or to many of its children should be defined in <code>mod.rs</code>.</li> <li>Functionality specific to a submodule should live in that submodule. Reexport at the top level for the most important or common definitions.</li> </ul> <p>For example, <a href="https://doc.rust-lang.org/std/io/struct.IoError.html"><code>IoError</code></a> is defined in <code>io/mod.rs</code>, since it pertains to the entirety of <code>io</code>, while <a href="https://doc.rust-lang.org/std/io/net/tcp/struct.TcpStream.html"><code>TcpStream</code></a> is defined in <code>io/net/tcp.rs</code> and reexported in the <code>io</code> module.</p> <h3 id='use-internal-module-hierarchies-for-organization-fixme-needs-rfc' class='section-header'><a href='#use-internal-module-hierarchies-for-organization-fixme-needs-rfc'>Use internal module hierarchies for organization. [FIXME: needs RFC]</a></h3> <blockquote> <p><strong>[FIXME]</strong> - Referencing internal modules from the standard library is subject to becoming outdated.</p> </blockquote> <p>Internal module hierarchies (i.e., private submodules) may be used to hide implementation details that are not part of the module&#39;s API.</p> <p>For example, in <a href="https://doc.rust-lang.org/std/io/"><code>std::io</code></a>, <code>mod mem</code> provides implementations for <a href="https://doc.rust-lang.org/std/io/struct.BufReader.html"><code>BufReader</code></a> and <a href="https://doc.rust-lang.org/std/io/struct.BufWriter.html"><code>BufWriter</code></a>, but these are re-exported in <code>io/mod.rs</code> at the top level of the module:</p> <span class='rusttest'>fn main() { // libstd/io/mod.rs pub use self::mem::{MemReader, BufReader, MemWriter, BufWriter}; /* ... */ mod mem; }</span><pre class='rust rust-example-rendered'> <span class='comment'>// libstd/io/mod.rs</span> <span class='kw'>pub</span> <span class='kw'>use</span> <span class='self'>self</span>::<span class='ident'>mem</span>::{<span class='ident'>MemReader</span>, <span class='ident'>BufReader</span>, <span class='ident'>MemWriter</span>, <span class='ident'>BufWriter</span>}; <span class='comment'>/* ... */</span> <span class='kw'>mod</span> <span class='ident'>mem</span>;</pre> <p>This hides the detail that there even exists a <code>mod mem</code> in <code>io</code>, and helps keep code organized while offering freedom to change the implementation.</p> <script type="text/javascript"> window.playgroundUrl = "https://play.rust-lang.org"; </script> <script src='rustbook.js'></script> <script src='playpen.js'></script> </div></div> </body> </html> <|start_filename|>docs/1.9/book/release-channels.html<|end_filename|> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="generator" content="rustdoc"> <title>リリースチャネル</title> <link rel="stylesheet" type="text/css" href="rustbook.css"> <meta name="robots" content="noindex"> </head> <body class="rustdoc"> <!--[if lte IE 8]> <div class="warning"> This old browser is unsupported and will most likely display funky things. </div> <![endif]--> <div id="nav"> <button id="toggle-nav"> <span class="sr-only">Toggle navigation</span> <span class="bar"></span> <span class="bar"></span> <span class="bar"></span> </button> </div> <div id='toc' class='mobile-hidden'> <ul class='chapter'> <li><a href='README.html'><b>1.</b> Introduction</a> </li> <li><a href='getting-started.html'><b>2.</b> はじめる</a> </li> <li><a href='guessing-game.html'><b>3.</b> チュートリアル:数当てゲーム</a> </li> <li><a href='syntax-and-semantics.html'><b>4.</b> シンタックスとセマンティクス</a> <ul class='section'> <li><a href='variable-bindings.html'><b>4.1.</b> 変数束縛</a> </li> <li><a href='functions.html'><b>4.2.</b> 関数</a> </li> <li><a href='primitive-types.html'><b>4.3.</b> プリミティブ型</a> </li> <li><a href='comments.html'><b>4.4.</b> コメント</a> </li> <li><a href='if.html'><b>4.5.</b> if</a> </li> <li><a href='loops.html'><b>4.6.</b> ループ</a> </li> <li><a href='vectors.html'><b>4.7.</b> ベクタ</a> </li> <li><a href='ownership.html'><b>4.8.</b> 所有権</a> </li> <li><a href='references-and-borrowing.html'><b>4.9.</b> 参照と借用</a> </li> <li><a href='lifetimes.html'><b>4.10.</b> ライフタイム</a> </li> <li><a href='mutability.html'><b>4.11.</b> ミュータビリティ</a> </li> <li><a href='structs.html'><b>4.12.</b> 構造体</a> </li> <li><a href='enums.html'><b>4.13.</b> 列挙型</a> </li> <li><a href='match.html'><b>4.14.</b> マッチ</a> </li> <li><a href='patterns.html'><b>4.15.</b> パターン</a> </li> <li><a href='method-syntax.html'><b>4.16.</b> メソッド構文</a> </li> <li><a href='strings.html'><b>4.17.</b> 文字列</a> </li> <li><a href='generics.html'><b>4.18.</b> ジェネリクス</a> </li> <li><a href='traits.html'><b>4.19.</b> トレイト</a> </li> <li><a href='drop.html'><b>4.20.</b> Drop</a> </li> <li><a href='if-let.html'><b>4.21.</b> if let</a> </li> <li><a href='trait-objects.html'><b>4.22.</b> トレイトオブジェクト</a> </li> <li><a href='closures.html'><b>4.23.</b> クロージャ</a> </li> <li><a href='ufcs.html'><b>4.24.</b> 共通の関数呼出構文</a> </li> <li><a href='crates-and-modules.html'><b>4.25.</b> クレートとモジュール</a> </li> <li><a href='const-and-static.html'><b>4.26.</b> `const` と `static`</a> </li> <li><a href='attributes.html'><b>4.27.</b> アトリビュート</a> </li> <li><a href='type-aliases.html'><b>4.28.</b> `type` エイリアス</a> </li> <li><a href='casting-between-types.html'><b>4.29.</b> 型間のキャスト</a> </li> <li><a href='associated-types.html'><b>4.30.</b> 関連型</a> </li> <li><a href='unsized-types.html'><b>4.31.</b> サイズ不定型</a> </li> <li><a href='operators-and-overloading.html'><b>4.32.</b> 演算子とオーバーロード</a> </li> <li><a href='deref-coercions.html'><b>4.33.</b> Derefによる型強制</a> </li> <li><a href='macros.html'><b>4.34.</b> マクロ</a> </li> <li><a href='raw-pointers.html'><b>4.35.</b> 生ポインタ</a> </li> <li><a href='unsafe.html'><b>4.36.</b> `unsafe`</a> </li> </ul> </li> <li><a href='effective-rust.html'><b>5.</b> Effective Rust</a> <ul class='section'> <li><a href='the-stack-and-the-heap.html'><b>5.1.</b> スタックとヒープ</a> </li> <li><a href='testing.html'><b>5.2.</b> テスト</a> </li> <li><a href='conditional-compilation.html'><b>5.3.</b> 条件付きコンパイル</a> </li> <li><a href='documentation.html'><b>5.4.</b> ドキュメント</a> </li> <li><a href='iterators.html'><b>5.5.</b> イテレータ</a> </li> <li><a href='concurrency.html'><b>5.6.</b> 並行性</a> </li> <li><a href='error-handling.html'><b>5.7.</b> エラーハンドリング</a> </li> <li><a href='choosing-your-guarantees.html'><b>5.8.</b> 保証を選ぶ</a> </li> <li><a href='ffi.html'><b>5.9.</b> 他言語関数インターフェース</a> </li> <li><a href='borrow-and-asref.html'><b>5.10.</b> BorrowとAsRef</a> </li> <li><a class='active' href='release-channels.html'><b>5.11.</b> リリースチャネル</a> </li> <li><a href='using-rust-without-the-standard-library.html'><b>5.12.</b> 標準ライブラリ無しでRustを使う</a> </li> </ul> </li> <li><a href='nightly-rust.html'><b>6.</b> Nightly Rust</a> <ul class='section'> <li><a href='compiler-plugins.html'><b>6.1.</b> コンパイラプラグイン</a> </li> <li><a href='inline-assembly.html'><b>6.2.</b> インラインアセンブリ</a> </li> <li><a href='no-stdlib.html'><b>6.3.</b> No stdlib</a> </li> <li><a href='intrinsics.html'><b>6.4.</b> Intrinsic</a> </li> <li><a href='lang-items.html'><b>6.5.</b> 言語アイテム</a> </li> <li><a href='advanced-linking.html'><b>6.6.</b> 高度なリンキング</a> </li> <li><a href='benchmark-tests.html'><b>6.7.</b> ベンチマークテスト</a> </li> <li><a href='box-syntax-and-patterns.html'><b>6.8.</b> Box構文とパターン</a> </li> <li><a href='slice-patterns.html'><b>6.9.</b> スライスパターン</a> </li> <li><a href='associated-constants.html'><b>6.10.</b> 関連定数</a> </li> <li><a href='custom-allocators.html'><b>6.11.</b> カスタムアロケータ</a> </li> </ul> </li> <li><a href='glossary.html'><b>7.</b> 用語集</a> </li> <li><a href='syntax-index.html'><b>8.</b> 構文の索引</a> </li> <li><a href='bibliography.html'><b>9.</b> 関係書目</a> </li> </ul> </div> <div id='page-wrapper'> <div id='page'> <blockquote class="header-caveat"> <p> <strong>注意: <a href="https://doc.rust-jp.rs/book-ja/">最新版のドキュメントをご覧ください。</a></strong>この第1版ドキュメントは古くなっており、最新情報が反映されていません。リンク先のドキュメントが現在の Rust の最新のドキュメントです。 </p> </blockquote> <h1 class="title">リリースチャネル</h1> <!-- % Release Channels --> <!-- The Rust project uses a concept called ‘release channels’ to manage releases. --> <!-- It’s important to understand this process to choose which version of Rust --> <!-- your project should use. --> <p>Rustプロジェクトではリリースを管理するために「リリースチャネル」という考え方を採用しています。どのバージョンのRustを使用するか決めるためには、この考え方を理解することが重要になります。</p> <!-- # Overview --> <h1 id='概要' class='section-header'><a href='#概要'>概要</a></h1> <!-- There are three channels for Rust releases: --> <p>Rustのリリースには以下の3つのチャネルがあります。</p> <ul> <li>Nightly</li> <li>Beta</li> <li>Stable</li> </ul> <!-- New nightly releases are created once a day. Every six weeks, the latest --> <!-- nightly release is promoted to ‘Beta’. At that point, it will only receive --> <!-- patches to fix serious errors. Six weeks later, the beta is promoted to --> <!-- ‘Stable’, and becomes the next release of `1.x`. --> <p>新しいnightlyリリースは毎日作られます。6週間ごとに、最新のnightlyリリースが「Beta」に格上げされます。これ以降は深刻なエラーを修正するパッチのみが受け付けられます。さらに6週間後、betaは「Stable」に格上げされ、次の「1.x」リリースになります。</p> <!-- This process happens in parallel. So every six weeks, on the same day, --> <!-- nightly goes to beta, beta goes to stable. When `1.x` is released, at --> <!-- the same time, `1.(x + 1)-beta` is released, and the nightly becomes the --> <!-- first version of `1.(x + 2)-nightly`. --> <p>このプロセスは並行して行われます。つまり6週間毎の同じ日に、nightlyはbetaに、betaはstableになります。「1.x」がリリースされると同時に「1.(x + 1)-beta」がリリースされ、nightlyは「1.(x + 2)-nightly」の最初のバージョンになる、ということです。</p> <!-- # Choosing a version --> <h1 id='バージョンを選ぶ' class='section-header'><a href='#バージョンを選ぶ'>バージョンを選ぶ</a></h1> <!-- Generally speaking, unless you have a specific reason, you should be using the --> <!-- stable release channel. These releases are intended for a general audience. --> <p>一般的に言って、特別な理由がなければstableリリースチャネルを使うべきです。このリリースは一般のユーザ向けになっています。</p> <!-- However, depending on your interest in Rust, you may choose to use nightly --> <!-- instead. The basic tradeoff is this: in the nightly channel, you can use --> <!-- unstable, new Rust features. However, unstable features are subject to change, --> <!-- and so any new nightly release may break your code. If you use the stable --> <!-- release, you cannot use experimental features, but the next release of Rust --> <!-- will not cause significant issues through breaking changes. --> <p>しかしRustに特に関心のある方は、代わりにnightlyを選んでも構いません。基本的な交換条件は次の通りです。nightlyチャネルを選ぶと不安定で新しいフィーチャを使うことができます。しかし、不安定なフィーチャは変更されやすく、新しいnightlyリリースでソースコードが動かなくなってしまうかもしれません。stableリリースを使えば、実験的なフィーチャを使うことはできませんが、Rustのバージョンが上がっても破壊的な変更によるトラブルは起きないでしょう。</p> <!-- # Helping the ecosystem through CI --> <h1 id='ciによるエコシステム支援' class='section-header'><a href='#ciによるエコシステム支援'>CIによるエコシステム支援</a></h1> <!-- What about beta? We encourage all Rust users who use the stable release channel --> <!-- to also test against the beta channel in their continuous integration systems. --> <!-- This will help alert the team in case there’s an accidental regression. --> <p>betaとはどういうチャネルでしょうか?stableリリースチャネルを使う全てのユーザは、継続的インテグレーションシステムを使ってbetaリリースに対してもテストすることを推奨しています。こうすることで、突発的なリグレッションに備えることができます。</p> <!-- Additionally, testing against nightly can catch regressions even sooner, and so --> <!-- if you don’t mind a third build, we’d appreciate testing against all channels. --> <p>さらに、nightlyに対してもテストすることでより早くリグレッションを捉えることができます。もし差し支えなければ、この3つ目のビルドを含めた全てのチャネルに対してテストしてもらえると嬉しいです。</p> <!-- As an example, many Rust programmers use [Travis](https://travis-ci.org/) to --> <!-- test their crates, which is free for open source projects. Travis [supports --> <!-- Rust directly][travis], and you can use a `.travis.yml` file like this to --> <!-- test on all channels: --> <p>例えば、多くのRustプログラマが <a href="https://travis-ci.org/">Travis</a> をクレートのテストに使っています。(このサービスはオープンソースプロジェクトについては無料で使えます) Travisは <a href="http://docs.travis-ci.com/user/languages/rust/">Rustを直接サポート</a> しており、「<code>.travis.yml</code>」に以下のように書くことですべてのチャネルに対するテストを行うことができます。</p> <pre><code class="language-yaml">language: rust rust: - nightly - beta - stable matrix: allow_failures: - rust: nightly </code></pre> <!-- With this configuration, Travis will test all three channels, but if something --> <!-- breaks on nightly, it won’t fail your build. A similar configuration is --> <!-- recommended for any CI system, check the documentation of the one you’re --> <!-- using for more details. --> <p>この設定で、Travisは3つ全てのチャネルに対してテストを行いますが、nightlyで何かおかしくなったとしてもビルドが失敗にはなりません。他のCIシステムでも同様の設定をお勧めします。詳細はお使いのシステムのドキュメントを参照してください。</p> <script type="text/javascript"> window.playgroundUrl = "https://play.rust-lang.org"; </script> <script src='rustbook.js'></script> <script src='playpen.js'></script> </div></div> </body> </html> <|start_filename|>docs/1.9/book/closures.html<|end_filename|> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="generator" content="rustdoc"> <title>クロージャ</title> <link rel="stylesheet" type="text/css" href="rustbook.css"> <meta name="robots" content="noindex"> </head> <body class="rustdoc"> <!--[if lte IE 8]> <div class="warning"> This old browser is unsupported and will most likely display funky things. </div> <![endif]--> <div id="nav"> <button id="toggle-nav"> <span class="sr-only">Toggle navigation</span> <span class="bar"></span> <span class="bar"></span> <span class="bar"></span> </button> </div> <div id='toc' class='mobile-hidden'> <ul class='chapter'> <li><a href='README.html'><b>1.</b> Introduction</a> </li> <li><a href='getting-started.html'><b>2.</b> はじめる</a> </li> <li><a href='guessing-game.html'><b>3.</b> チュートリアル:数当てゲーム</a> </li> <li><a href='syntax-and-semantics.html'><b>4.</b> シンタックスとセマンティクス</a> <ul class='section'> <li><a href='variable-bindings.html'><b>4.1.</b> 変数束縛</a> </li> <li><a href='functions.html'><b>4.2.</b> 関数</a> </li> <li><a href='primitive-types.html'><b>4.3.</b> プリミティブ型</a> </li> <li><a href='comments.html'><b>4.4.</b> コメント</a> </li> <li><a href='if.html'><b>4.5.</b> if</a> </li> <li><a href='loops.html'><b>4.6.</b> ループ</a> </li> <li><a href='vectors.html'><b>4.7.</b> ベクタ</a> </li> <li><a href='ownership.html'><b>4.8.</b> 所有権</a> </li> <li><a href='references-and-borrowing.html'><b>4.9.</b> 参照と借用</a> </li> <li><a href='lifetimes.html'><b>4.10.</b> ライフタイム</a> </li> <li><a href='mutability.html'><b>4.11.</b> ミュータビリティ</a> </li> <li><a href='structs.html'><b>4.12.</b> 構造体</a> </li> <li><a href='enums.html'><b>4.13.</b> 列挙型</a> </li> <li><a href='match.html'><b>4.14.</b> マッチ</a> </li> <li><a href='patterns.html'><b>4.15.</b> パターン</a> </li> <li><a href='method-syntax.html'><b>4.16.</b> メソッド構文</a> </li> <li><a href='strings.html'><b>4.17.</b> 文字列</a> </li> <li><a href='generics.html'><b>4.18.</b> ジェネリクス</a> </li> <li><a href='traits.html'><b>4.19.</b> トレイト</a> </li> <li><a href='drop.html'><b>4.20.</b> Drop</a> </li> <li><a href='if-let.html'><b>4.21.</b> if let</a> </li> <li><a href='trait-objects.html'><b>4.22.</b> トレイトオブジェクト</a> </li> <li><a class='active' href='closures.html'><b>4.23.</b> クロージャ</a> </li> <li><a href='ufcs.html'><b>4.24.</b> 共通の関数呼出構文</a> </li> <li><a href='crates-and-modules.html'><b>4.25.</b> クレートとモジュール</a> </li> <li><a href='const-and-static.html'><b>4.26.</b> `const` と `static`</a> </li> <li><a href='attributes.html'><b>4.27.</b> アトリビュート</a> </li> <li><a href='type-aliases.html'><b>4.28.</b> `type` エイリアス</a> </li> <li><a href='casting-between-types.html'><b>4.29.</b> 型間のキャスト</a> </li> <li><a href='associated-types.html'><b>4.30.</b> 関連型</a> </li> <li><a href='unsized-types.html'><b>4.31.</b> サイズ不定型</a> </li> <li><a href='operators-and-overloading.html'><b>4.32.</b> 演算子とオーバーロード</a> </li> <li><a href='deref-coercions.html'><b>4.33.</b> Derefによる型強制</a> </li> <li><a href='macros.html'><b>4.34.</b> マクロ</a> </li> <li><a href='raw-pointers.html'><b>4.35.</b> 生ポインタ</a> </li> <li><a href='unsafe.html'><b>4.36.</b> `unsafe`</a> </li> </ul> </li> <li><a href='effective-rust.html'><b>5.</b> Effective Rust</a> <ul class='section'> <li><a href='the-stack-and-the-heap.html'><b>5.1.</b> スタックとヒープ</a> </li> <li><a href='testing.html'><b>5.2.</b> テスト</a> </li> <li><a href='conditional-compilation.html'><b>5.3.</b> 条件付きコンパイル</a> </li> <li><a href='documentation.html'><b>5.4.</b> ドキュメント</a> </li> <li><a href='iterators.html'><b>5.5.</b> イテレータ</a> </li> <li><a href='concurrency.html'><b>5.6.</b> 並行性</a> </li> <li><a href='error-handling.html'><b>5.7.</b> エラーハンドリング</a> </li> <li><a href='choosing-your-guarantees.html'><b>5.8.</b> 保証を選ぶ</a> </li> <li><a href='ffi.html'><b>5.9.</b> 他言語関数インターフェース</a> </li> <li><a href='borrow-and-asref.html'><b>5.10.</b> BorrowとAsRef</a> </li> <li><a href='release-channels.html'><b>5.11.</b> リリースチャネル</a> </li> <li><a href='using-rust-without-the-standard-library.html'><b>5.12.</b> 標準ライブラリ無しでRustを使う</a> </li> </ul> </li> <li><a href='nightly-rust.html'><b>6.</b> Nightly Rust</a> <ul class='section'> <li><a href='compiler-plugins.html'><b>6.1.</b> コンパイラプラグイン</a> </li> <li><a href='inline-assembly.html'><b>6.2.</b> インラインアセンブリ</a> </li> <li><a href='no-stdlib.html'><b>6.3.</b> No stdlib</a> </li> <li><a href='intrinsics.html'><b>6.4.</b> Intrinsic</a> </li> <li><a href='lang-items.html'><b>6.5.</b> 言語アイテム</a> </li> <li><a href='advanced-linking.html'><b>6.6.</b> 高度なリンキング</a> </li> <li><a href='benchmark-tests.html'><b>6.7.</b> ベンチマークテスト</a> </li> <li><a href='box-syntax-and-patterns.html'><b>6.8.</b> Box構文とパターン</a> </li> <li><a href='slice-patterns.html'><b>6.9.</b> スライスパターン</a> </li> <li><a href='associated-constants.html'><b>6.10.</b> 関連定数</a> </li> <li><a href='custom-allocators.html'><b>6.11.</b> カスタムアロケータ</a> </li> </ul> </li> <li><a href='glossary.html'><b>7.</b> 用語集</a> </li> <li><a href='syntax-index.html'><b>8.</b> 構文の索引</a> </li> <li><a href='bibliography.html'><b>9.</b> 関係書目</a> </li> </ul> </div> <div id='page-wrapper'> <div id='page'> <blockquote class="header-caveat"> <p> <strong>注意: <a href="https://doc.rust-jp.rs/book-ja/">最新版のドキュメントをご覧ください。</a></strong>この第1版ドキュメントは古くなっており、最新情報が反映されていません。リンク先のドキュメントが現在の Rust の最新のドキュメントです。 </p> </blockquote> <h1 class="title">クロージャ</h1> <!-- % Closures --> <!-- Sometimes it is useful to wrap up a function and _free variables_ for better --> <!-- clarity and reuse. The free variables that can be used come from the --> <!-- enclosing scope and are ‘closed over’ when used in the function. From this, we --> <!-- get the name ‘closures’ and Rust provides a really great implementation of --> <!-- them, as we’ll see. --> <p>しばしば、関数と <em>自由変数</em> を一つにまとめておくことがコードの明確さや再利用に役立つ場合が有ります。 自由変数は外部のスコープから来て、関数中で使われるときに「閉じ込め」られます。 そのためそのようなまとまりを「クロージャ」と呼び、 Rustはこれから見ていくようにクロージャの非常に良い実装を提供しています。</p> <!-- # Syntax --> <h1 id='構文' class='section-header'><a href='#構文'>構文</a></h1> <!-- Closures look like this: --> <p>クロージャは以下のような見た目です:</p> <span class='rusttest'>fn main() { let plus_one = |x: i32| x + 1; assert_eq!(2, plus_one(1)); }</span><pre class='rust rust-example-rendered'> <span class='kw'>let</span> <span class='ident'>plus_one</span> <span class='op'>=</span> <span class='op'>|</span><span class='ident'>x</span>: <span class='ident'>i32</span><span class='op'>|</span> <span class='ident'>x</span> <span class='op'>+</span> <span class='number'>1</span>; <span class='macro'>assert_eq</span><span class='macro'>!</span>(<span class='number'>2</span>, <span class='ident'>plus_one</span>(<span class='number'>1</span>));</pre> <!-- We create a binding, `plus_one`, and assign it to a closure. The closure’s --> <!-- arguments go between the pipes (`|`), and the body is an expression, in this --> <!-- case, `x + 1`. Remember that `{ }` is an expression, so we can have multi-line --> <!-- closures too: --> <p>束縛 <code>plus_one</code> を作成し、クロージャを代入しています。 クロージャの引数はパイプ( <code>|</code> )の間に書きます、そしてクロージャの本体は式です、 この場合は <code>x + 1</code> がそれに当たります。 <code>{ }</code> が式であることを思い出して下さい、 そのため複数行のクロージャを作成することも可能です:</p> <span class='rusttest'>fn main() { let plus_two = |x| { let mut result: i32 = x; result += 1; result += 1; result }; assert_eq!(4, plus_two(2)); }</span><pre class='rust rust-example-rendered'> <span class='kw'>let</span> <span class='ident'>plus_two</span> <span class='op'>=</span> <span class='op'>|</span><span class='ident'>x</span><span class='op'>|</span> { <span class='kw'>let</span> <span class='kw-2'>mut</span> <span class='ident'>result</span>: <span class='ident'>i32</span> <span class='op'>=</span> <span class='ident'>x</span>; <span class='ident'>result</span> <span class='op'>+=</span> <span class='number'>1</span>; <span class='ident'>result</span> <span class='op'>+=</span> <span class='number'>1</span>; <span class='ident'>result</span> }; <span class='macro'>assert_eq</span><span class='macro'>!</span>(<span class='number'>4</span>, <span class='ident'>plus_two</span>(<span class='number'>2</span>));</pre> <!-- You’ll notice a few things about closures that are a bit different from regular --> <!-- named functions defined with `fn`. The first is that we did not need to --> <!-- annotate the types of arguments the closure takes or the values it returns. We --> <!-- can: --> <p>いくつかクロージャと通常の <code>fn</code> で定義される関数との間の違いに気がつくことでしょう。 一つ目はクロージャの引数や返り値の型を示す必要が無いことです。 型を以下のように示すことも可能です:</p> <span class='rusttest'>fn main() { let plus_one = |x: i32| -&gt; i32 { x + 1 }; assert_eq!(2, plus_one(1)); }</span><pre class='rust rust-example-rendered'> <span class='kw'>let</span> <span class='ident'>plus_one</span> <span class='op'>=</span> <span class='op'>|</span><span class='ident'>x</span>: <span class='ident'>i32</span><span class='op'>|</span> <span class='op'>-&gt;</span> <span class='ident'>i32</span> { <span class='ident'>x</span> <span class='op'>+</span> <span class='number'>1</span> }; <span class='macro'>assert_eq</span><span class='macro'>!</span>(<span class='number'>2</span>, <span class='ident'>plus_one</span>(<span class='number'>1</span>));</pre> <!-- But we don’t have to. Why is this? Basically, it was chosen for ergonomic --> <!-- reasons. While specifying the full type for named functions is helpful with --> <!-- things like documentation and type inference, the full type signatures of --> <!-- closures are rarely documented since they’re anonymous, and they don’t cause --> <!-- the kinds of error-at-a-distance problems that inferring named function types --> <!-- can. --> <p>しかし、このように型を示す必要はありません。 なぜでしょう?一言で言えば、これは使いやすさのためです。 名前の有る関数の型を全て指定するのはドキュメンテーションや型推論の役に立ちますが、 クロージャの型は殆ど示されません、これはクロージャたちが匿名であり、 さらに名前付きの関数が引き起こすと思われるような定義から離れた箇所で発生するエラーの要因ともならないためです。</p> <!-- The second is that the syntax is similar, but a bit different. I’ve added --> <!-- spaces here for easier comparison: --> <p>通常の関数との違いの二つ目は、構文が大部分は似ていますがほんの少しだけ違うという点です。 比較がしやすいようにスペースを適宜補って以下に示します:</p> <span class='rusttest'>fn main() { fn plus_one_v1 (x: i32) -&gt; i32 { x + 1 } let plus_one_v2 = |x: i32| -&gt; i32 { x + 1 }; let plus_one_v3 = |x: i32| x + 1 ; }</span><pre class='rust rust-example-rendered'> <span class='kw'>fn</span> <span class='ident'>plus_one_v1</span> (<span class='ident'>x</span>: <span class='ident'>i32</span>) <span class='op'>-&gt;</span> <span class='ident'>i32</span> { <span class='ident'>x</span> <span class='op'>+</span> <span class='number'>1</span> } <span class='kw'>let</span> <span class='ident'>plus_one_v2</span> <span class='op'>=</span> <span class='op'>|</span><span class='ident'>x</span>: <span class='ident'>i32</span><span class='op'>|</span> <span class='op'>-&gt;</span> <span class='ident'>i32</span> { <span class='ident'>x</span> <span class='op'>+</span> <span class='number'>1</span> }; <span class='kw'>let</span> <span class='ident'>plus_one_v3</span> <span class='op'>=</span> <span class='op'>|</span><span class='ident'>x</span>: <span class='ident'>i32</span><span class='op'>|</span> <span class='ident'>x</span> <span class='op'>+</span> <span class='number'>1</span> ;</pre> <!-- Small differences, but they’re similar. --> <p>小さな違いは有りますが殆どの部分は同じです。</p> <!-- # Closures and their environment --> <h1 id='クロージャとクロージャの環境' class='section-header'><a href='#クロージャとクロージャの環境'>クロージャとクロージャの環境</a></h1> <!-- The environment for a closure can include bindings from its enclosing scope in --> <!-- addition to parameters and local bindings. It looks like this: --> <p>クロージャの環境は引数やローカルな束縛に加えてクロージャを囲んでいるスコープ中の束縛を含むことができます。 例えば以下のようになります:</p> <span class='rusttest'>fn main() { let num = 5; let plus_num = |x: i32| x + num; assert_eq!(10, plus_num(5)); }</span><pre class='rust rust-example-rendered'> <span class='kw'>let</span> <span class='ident'>num</span> <span class='op'>=</span> <span class='number'>5</span>; <span class='kw'>let</span> <span class='ident'>plus_num</span> <span class='op'>=</span> <span class='op'>|</span><span class='ident'>x</span>: <span class='ident'>i32</span><span class='op'>|</span> <span class='ident'>x</span> <span class='op'>+</span> <span class='ident'>num</span>; <span class='macro'>assert_eq</span><span class='macro'>!</span>(<span class='number'>10</span>, <span class='ident'>plus_num</span>(<span class='number'>5</span>));</pre> <!-- This closure, `plus_num`, refers to a `let` binding in its scope: `num`. More --> <!-- specifically, it borrows the binding. If we do something that would conflict --> <!-- with that binding, we get an error. Like this one: --> <p>クロージャ <code>plus_num</code> はスコープ内の <code>let</code> 束縛 <code>num</code> を参照しています。 より厳密に言うと、クロージャ <code>plus_num</code> は束縛を借用しています。 もし、この束縛と衝突する処理を行うとエラーが発生します。 例えば、以下のようなコードでは:</p> <span class='rusttest'>fn main() { let mut num = 5; let plus_num = |x: i32| x + num; let y = &amp;mut num; }</span><pre class='rust rust-example-rendered'> <span class='kw'>let</span> <span class='kw-2'>mut</span> <span class='ident'>num</span> <span class='op'>=</span> <span class='number'>5</span>; <span class='kw'>let</span> <span class='ident'>plus_num</span> <span class='op'>=</span> <span class='op'>|</span><span class='ident'>x</span>: <span class='ident'>i32</span><span class='op'>|</span> <span class='ident'>x</span> <span class='op'>+</span> <span class='ident'>num</span>; <span class='kw'>let</span> <span class='ident'>y</span> <span class='op'>=</span> <span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='ident'>num</span>;</pre> <!-- Which errors with: --> <p>以下のエラーを発生させます:</p> <pre><code class="language-text">error: cannot borrow `num` as mutable because it is also borrowed as immutable let y = &amp;mut num; ^~~ note: previous borrow of `num` occurs here due to use in closure; the immutable borrow prevents subsequent moves or mutable borrows of `num` until the borrow ends let plus_num = |x| x + num; ^~~~~~~~~~~ note: previous borrow ends here fn main() { let mut num = 5; let plus_num = |x| x + num; let y = &amp;mut num; } ^ </code></pre> <!-- A verbose yet helpful error message! As it says, we can’t take a mutable borrow --> <!-- on `num` because the closure is already borrowing it. If we let the closure go --> <!-- out of scope, we can: --> <p>冗長ですが役に立つエラーメッセージです! エラーが示しているように、クロージャが既に <code>num</code> を借用しているために、 <code>num</code> の変更可能な借用を取得することはできません。 もしクロージャがスコープ外になるようにした場合以下のようにできます:</p> <span class='rusttest'>fn main() { let mut num = 5; { let plus_num = |x: i32| x + num; // } // plus_num goes out of scope, borrow of num ends } // plus_numがスコープ外に出て、numの借用が終わります let y = &amp;mut num; }</span><pre class='rust rust-example-rendered'> <span class='kw'>let</span> <span class='kw-2'>mut</span> <span class='ident'>num</span> <span class='op'>=</span> <span class='number'>5</span>; { <span class='kw'>let</span> <span class='ident'>plus_num</span> <span class='op'>=</span> <span class='op'>|</span><span class='ident'>x</span>: <span class='ident'>i32</span><span class='op'>|</span> <span class='ident'>x</span> <span class='op'>+</span> <span class='ident'>num</span>; } <span class='comment'>// plus_numがスコープ外に出て、numの借用が終わります</span> <span class='kw'>let</span> <span class='ident'>y</span> <span class='op'>=</span> <span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='ident'>num</span>;</pre> <!-- If your closure requires it, however, Rust will take ownership and move --> <!-- the environment instead. This doesn’t work: --> <p>もしクロージャが <code>num</code> を要求した場合、Rustは借用する代わりに環境の所有権を取りムーブします。 そのため、以下のコードは動作しません:</p> <span class='rusttest'>fn main() { let nums = vec![1, 2, 3]; let takes_nums = || nums; println!(&quot;{:?}&quot;, nums); }</span><pre class='rust rust-example-rendered'> <span class='kw'>let</span> <span class='ident'>nums</span> <span class='op'>=</span> <span class='macro'>vec</span><span class='macro'>!</span>[<span class='number'>1</span>, <span class='number'>2</span>, <span class='number'>3</span>]; <span class='kw'>let</span> <span class='ident'>takes_nums</span> <span class='op'>=</span> <span class='op'>||</span> <span class='ident'>nums</span>; <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;{:?}&quot;</span>, <span class='ident'>nums</span>);</pre> <!-- We get this error: --> <p>このコードは以下の様なエラーを発生させます:</p> <pre><code class="language-text">note: `nums` moved into closure environment here because it has type `[closure(()) -&gt; collections::vec::Vec&lt;i32&gt;]`, which is non-copyable let takes_nums = || nums; ^~~~~~~ </code></pre> <!-- `Vec<T>` has ownership over its contents, and therefore, when we refer to it --> <!-- in our closure, we have to take ownership of `nums`. It’s the same as if we’d --> <!-- passed `nums` to a function that took ownership of it. --> <p><code>Vec&lt;T&gt;</code> はその要素に対する所有権を持っています、 それゆえそれらの要素をクロージャ内で参照した場合、 <code>nums</code> の所有権を取ることになります。 これは <code>nums</code>を <code>nums</code> の所有権を取る関数に渡した場合と同じです。</p> <!-- ## `move` closures --> <h2 id='move-クロージャ' class='section-header'><a href='#move-クロージャ'><code>move</code> クロージャ</a></h2> <!-- We can force our closure to take ownership of its environment with the `move` --> <!-- keyword: --> <p><code>move</code> キーワードを用いることで、クロージャに環境の所有権を取得することを強制することができます。</p> <span class='rusttest'>fn main() { let num = 5; let owns_num = move |x: i32| x + num; }</span><pre class='rust rust-example-rendered'> <span class='kw'>let</span> <span class='ident'>num</span> <span class='op'>=</span> <span class='number'>5</span>; <span class='kw'>let</span> <span class='ident'>owns_num</span> <span class='op'>=</span> <span class='kw'>move</span> <span class='op'>|</span><span class='ident'>x</span>: <span class='ident'>i32</span><span class='op'>|</span> <span class='ident'>x</span> <span class='op'>+</span> <span class='ident'>num</span>;</pre> <!-- Now, even though the keyword is `move`, the variables follow normal move semantics. --> <!-- In this case, `5` implements `Copy`, and so `owns_num` takes ownership of a copy --> <!-- of `num`. So what’s the difference? --> <p>このようにすると <code>move</code> というキーワードにもかかわらず、変数は通常のmoveのセマンティクスに従います。 この場合、 <code>5</code> は <code>Copy</code> を実装しています、 そのため <code>owns_num</code> は <code>num</code> のコピーの所有権を取得します。 では、なにが異なるのでしょうか?</p> <span class='rusttest'>fn main() { let mut num = 5; { let mut add_num = |x: i32| num += x; add_num(5); } assert_eq!(10, num); }</span><pre class='rust rust-example-rendered'> <span class='kw'>let</span> <span class='kw-2'>mut</span> <span class='ident'>num</span> <span class='op'>=</span> <span class='number'>5</span>; { <span class='kw'>let</span> <span class='kw-2'>mut</span> <span class='ident'>add_num</span> <span class='op'>=</span> <span class='op'>|</span><span class='ident'>x</span>: <span class='ident'>i32</span><span class='op'>|</span> <span class='ident'>num</span> <span class='op'>+=</span> <span class='ident'>x</span>; <span class='ident'>add_num</span>(<span class='number'>5</span>); } <span class='macro'>assert_eq</span><span class='macro'>!</span>(<span class='number'>10</span>, <span class='ident'>num</span>);</pre> <!-- So in this case, our closure took a mutable reference to `num`, and then when --> <!-- we called `add_num`, it mutated the underlying value, as we’d expect. We also --> <!-- needed to declare `add_num` as `mut` too, because we’re mutating its --> <!-- environment. --> <p>このケースでは、クロージャは <code>num</code> の変更可能な参照を取得し、 <code>add_num</code> を呼び出した時、期待通りに <code>num</code> の値を変更します。 またクロージャ <code>add_num</code> はその環境を変更するため <code>mut</code> として宣言する必要があります。</p> <!-- If we change to a `move` closure, it’s different: --> <p>もしクロージャを <code>move</code> に変更した場合、結果が異なります:</p> <span class='rusttest'>fn main() { let mut num = 5; { let mut add_num = move |x: i32| num += x; add_num(5); } assert_eq!(5, num); }</span><pre class='rust rust-example-rendered'> <span class='kw'>let</span> <span class='kw-2'>mut</span> <span class='ident'>num</span> <span class='op'>=</span> <span class='number'>5</span>; { <span class='kw'>let</span> <span class='kw-2'>mut</span> <span class='ident'>add_num</span> <span class='op'>=</span> <span class='kw'>move</span> <span class='op'>|</span><span class='ident'>x</span>: <span class='ident'>i32</span><span class='op'>|</span> <span class='ident'>num</span> <span class='op'>+=</span> <span class='ident'>x</span>; <span class='ident'>add_num</span>(<span class='number'>5</span>); } <span class='macro'>assert_eq</span><span class='macro'>!</span>(<span class='number'>5</span>, <span class='ident'>num</span>);</pre> <!-- We only get `5`. Rather than taking a mutable borrow out on our `num`, we took --> <!-- ownership of a copy. --> <p>結果は <code>5</code> になります。 <code>num</code> の変更可能な借用を取得するのではなく、 <code>num</code> のコピーの所有権を取得します。</p> <!-- Another way to think about `move` closures: they give a closure its own stack --> <!-- frame. Without `move`, a closure may be tied to the stack frame that created --> <!-- it, while a `move` closure is self-contained. This means that you cannot --> <!-- generally return a non-`move` closure from a function, for example. --> <p><code>move</code> クロージャを捉えるもう一つの観点は: <code>move</code> クロージャは独自のスタックフレームを持っているという点です。 <code>move</code> クロージャは自己従属していますが、 <code>move</code> でないクロージャはクロージャを作成したスタックフレームと紐付いています。 これは一般的に、<code>move</code> でないクロージャを関数から返すことはできないということを意味しています。</p> <!-- But before we talk about taking and returning closures, we should talk some --> <!-- more about the way that closures are implemented. As a systems language, Rust --> <!-- gives you tons of control over what your code does, and closures are no --> <!-- different. --> <p>クロージャを引数や返り値にすることについて説明する間に、クロージャの実装についてもう少し説明する必要があります。 システム言語としてRustはコードの動作についてコントロールする方法を大量に提供しています、 そしてそれはクロージャも例外ではありません。</p> <!-- # Closure implementation --> <h1 id='クロージャの実装' class='section-header'><a href='#クロージャの実装'>クロージャの実装</a></h1> <!-- Rust’s implementation of closures is a bit different than other languages. They --> <!-- are effectively syntax sugar for traits. You’ll want to make sure to have read --> <!-- the [traits][traits] section before this one, as well as the section on [trait --> <!-- objects][trait-objects]. --> <p>Rustにおけるクロージャの実装は他の言語とは少し異なります。 Rustにおけるクロージャは実質的にトレイトへの糖衣構文です。 続きの説明を読む前に <a href="traits.html">トレイト</a> や <a href="trait-objects.html">トレイトオブジェクト</a> についてのセクションを読みたくなるでしょう。</p> <!-- Got all that? Good. --> <p>よろしいですか? では、続きを説明いたします。</p> <!-- The key to understanding how closures work under the hood is something a bit --> <!-- strange: Using `()` to call a function, like `foo()`, is an overloadable --> <!-- operator. From this, everything else clicks into place. In Rust, we use the --> <!-- trait system to overload operators. Calling functions is no different. We have --> <!-- three separate traits to overload with: --> <p>クロージャの内部的な動作を理解するための鍵は少し変わっています: 関数を呼び出すのに <code>()</code> を 例えば <code>foo()</code> の様に使いますが、この <code>()</code> はオーバーロード可能な演算子です。 この事実から残りの全てを正しく理解することができます。 Rustでは、トレイトを演算子のオーバーロードに利用します。 それは関数の呼び出しも例外ではありません。 <code>()</code> をオーバーロードするのに利用可能な、3つの異なるトレイトが存在します:</p> <span class='rusttest'>fn main() { mod foo { pub trait Fn&lt;Args&gt; : FnMut&lt;Args&gt; { extern &quot;rust-call&quot; fn call(&amp;self, args: Args) -&gt; Self::Output; } pub trait FnMut&lt;Args&gt; : FnOnce&lt;Args&gt; { extern &quot;rust-call&quot; fn call_mut(&amp;mut self, args: Args) -&gt; Self::Output; } pub trait FnOnce&lt;Args&gt; { type Output; extern &quot;rust-call&quot; fn call_once(self, args: Args) -&gt; Self::Output; } } }</span><pre class='rust rust-example-rendered'> <span class='kw'>pub</span> <span class='kw'>trait</span> <span class='ident'>Fn</span><span class='op'>&lt;</span><span class='ident'>Args</span><span class='op'>&gt;</span> : <span class='ident'>FnMut</span><span class='op'>&lt;</span><span class='ident'>Args</span><span class='op'>&gt;</span> { <span class='kw'>extern</span> <span class='string'>&quot;rust-call&quot;</span> <span class='kw'>fn</span> <span class='ident'>call</span>(<span class='kw-2'>&amp;</span><span class='self'>self</span>, <span class='ident'>args</span>: <span class='ident'>Args</span>) <span class='op'>-&gt;</span> <span class='self'>Self</span>::<span class='ident'>Output</span>; } <span class='kw'>pub</span> <span class='kw'>trait</span> <span class='ident'>FnMut</span><span class='op'>&lt;</span><span class='ident'>Args</span><span class='op'>&gt;</span> : <span class='ident'>FnOnce</span><span class='op'>&lt;</span><span class='ident'>Args</span><span class='op'>&gt;</span> { <span class='kw'>extern</span> <span class='string'>&quot;rust-call&quot;</span> <span class='kw'>fn</span> <span class='ident'>call_mut</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>, <span class='ident'>args</span>: <span class='ident'>Args</span>) <span class='op'>-&gt;</span> <span class='self'>Self</span>::<span class='ident'>Output</span>; } <span class='kw'>pub</span> <span class='kw'>trait</span> <span class='ident'>FnOnce</span><span class='op'>&lt;</span><span class='ident'>Args</span><span class='op'>&gt;</span> { <span class='kw'>type</span> <span class='ident'>Output</span>; <span class='kw'>extern</span> <span class='string'>&quot;rust-call&quot;</span> <span class='kw'>fn</span> <span class='ident'>call_once</span>(<span class='self'>self</span>, <span class='ident'>args</span>: <span class='ident'>Args</span>) <span class='op'>-&gt;</span> <span class='self'>Self</span>::<span class='ident'>Output</span>; }</pre> <!-- You’ll notice a few differences between these traits, but a big one is `self`: --> <!-- `Fn` takes `&self`, `FnMut` takes `&mut self`, and `FnOnce` takes `self`. This --> <!-- covers all three kinds of `self` via the usual method call syntax. But we’ve --> <!-- split them up into three traits, rather than having a single one. This gives us --> <!-- a large amount of control over what kind of closures we can take. --> <p>これらのトレイトの間のいくつかの違いに気がつくことでしょう、しかし大きな違いは <code>self</code> についてです: <code>Fn</code> は <code>&amp;self</code> を引数に取ります、 <code>FnMut</code> は <code>&amp;mut self</code> を引数に取ります、そして <code>FnOnce</code> は <code>self</code> を引数に取ります。 これは通常のメソッド呼び出しにおける <code>self</code> のすべての種類をカバーしています。 しかし、これら <code>self</code> の各種類を一つの大きなトレイトにまとめるのではなく異なるトレイトに分けています。 このようにすることで、どのような種類のクロージャを取るのかについて多くをコントロールすることができます。</p> <!-- The `|| {}` syntax for closures is sugar for these three traits. Rust will --> <!-- generate a struct for the environment, `impl` the appropriate trait, and then --> <!-- use it. --> <p>クロージャの構文 <code>|| {}</code> は上述の3つのトレイトへの糖衣構文です。 Rustは環境用の構造体を作成し、 適切なトレイトを <code>impl</code> し、それを利用します。</p> <!-- # Taking closures as arguments --> <h1 id='クロージャを引数に取る' class='section-header'><a href='#クロージャを引数に取る'>クロージャを引数に取る</a></h1> <!-- Now that we know that closures are traits, we already know how to accept and --> <!-- return closures: the same as any other trait! --> <p>クロージャが実際にはトレイトであることを学んだので、 クロージャを引数としたり返り値としたりする方法を既に知っていることになります: 通常のトレイトと全く同様に行うのです!</p> <!-- This also means that we can choose static vs dynamic dispatch as well. First, --> <!-- let’s write a function which takes something callable, calls it, and returns --> <!-- the result: --> <p>これは、静的ディスパッチと動的ディスパッチを選択することができるということも意味しています。 手始めに呼び出し可能な何かを引数にとり、それを呼び出し、結果を返す関数を書いてみましょう:</p> <span class='rusttest'>fn main() { fn call_with_one&lt;F&gt;(some_closure: F) -&gt; i32 where F : Fn(i32) -&gt; i32 { some_closure(1) } let answer = call_with_one(|x| x + 2); assert_eq!(3, answer); }</span><pre class='rust rust-example-rendered'> <span class='kw'>fn</span> <span class='ident'>call_with_one</span><span class='op'>&lt;</span><span class='ident'>F</span><span class='op'>&gt;</span>(<span class='ident'>some_closure</span>: <span class='ident'>F</span>) <span class='op'>-&gt;</span> <span class='ident'>i32</span> <span class='kw'>where</span> <span class='ident'>F</span> : <span class='ident'>Fn</span>(<span class='ident'>i32</span>) <span class='op'>-&gt;</span> <span class='ident'>i32</span> { <span class='ident'>some_closure</span>(<span class='number'>1</span>) } <span class='kw'>let</span> <span class='ident'>answer</span> <span class='op'>=</span> <span class='ident'>call_with_one</span>(<span class='op'>|</span><span class='ident'>x</span><span class='op'>|</span> <span class='ident'>x</span> <span class='op'>+</span> <span class='number'>2</span>); <span class='macro'>assert_eq</span><span class='macro'>!</span>(<span class='number'>3</span>, <span class='ident'>answer</span>);</pre> <!-- We pass our closure, `|x| x + 2`, to `call_with_one`. It does what it --> <!-- suggests: it calls the closure, giving it `1` as an argument. --> <p>クロージャ <code>|x| x + 2</code> を <code>call_with_one</code> に渡しました。 <code>call_with_one</code> はその関数名から推測される処理を行います: クロージャに <code>1</code> を与えて呼び出します。</p> <!-- Let’s examine the signature of `call_with_one` in more depth: --> <p><code>call_with_one</code> のシグネチャを詳細に見ていきましょう:</p> <span class='rusttest'>fn main() { fn call_with_one&lt;F&gt;(some_closure: F) -&gt; i32 where F : Fn(i32) -&gt; i32 { some_closure(1) } }</span><pre class='rust rust-example-rendered'> <span class='kw'>fn</span> <span class='ident'>call_with_one</span><span class='op'>&lt;</span><span class='ident'>F</span><span class='op'>&gt;</span>(<span class='ident'>some_closure</span>: <span class='ident'>F</span>) <span class='op'>-&gt;</span> <span class='ident'>i32</span></pre> <!-- We take one parameter, and it has the type `F`. We also return a `i32`. This part --> <!-- isn’t interesting. The next part is: --> <p>型 <code>F</code> の引数を1つ取り、返り値として <code>i32</code> を返します。 この部分は特に注目には値しません。次の部分は:</p> <span class='rusttest'>fn main() { fn call_with_one&lt;F&gt;(some_closure: F) -&gt; i32 where F : Fn(i32) -&gt; i32 { some_closure(1) } }</span><pre class='rust rust-example-rendered'> <span class='kw'>where</span> <span class='ident'>F</span> : <span class='ident'>Fn</span>(<span class='ident'>i32</span>) <span class='op'>-&gt;</span> <span class='ident'>i32</span> {</pre> <!-- Because `Fn` is a trait, we can bound our generic with it. In this case, our --> <!-- closure takes a `i32` as an argument and returns an `i32`, and so the generic --> <!-- bound we use is `Fn(i32) -> i32`. --> <p><code>Fn</code> がトレイトであるために、ジェネリックの境界として <code>Fn</code> を指定することができます。 この場合はクロージャは <code>i32</code> を引数として取り、 <code>i32</code> を返します、そのため ジェネリックの境界として <code>Fn(i32) -&gt; i32</code> を指定します。</p> <!-- There’s one other key point here: because we’re bounding a generic with a --> <!-- trait, this will get monomorphized, and therefore, we’ll be doing static --> <!-- dispatch into the closure. That’s pretty neat. In many languages, closures are --> <!-- inherently heap allocated, and will always involve dynamic dispatch. In Rust, --> <!-- we can stack allocate our closure environment, and statically dispatch the --> <!-- call. This happens quite often with iterators and their adapters, which often --> <!-- take closures as arguments. --> <p>キーポイントがほかにもあります: ジェネリックをトレイトで境界を指定したために、 この関数は単相化され、静的ディスパッチをクロージャに対して行います。これはとても素敵です。 多くの言語では、クロージャは常にヒープにアロケートされ、常に動的ディスパッチが行われます。 Rustではスタックにクロージャの環境をアロケートし、呼び出しを静的ディスパッチすることができます。 これは、しばしばクロージャを引数として取る、イテレータやそれらのアダプタにおいて頻繁に行われます。</p> <!-- Of course, if we want dynamic dispatch, we can get that too. A trait object --> <!-- handles this case, as usual: --> <p>もちろん、動的ディスパッチを行いたいときは、そうすることもできます。 そのような場合もトレイトオブジェクトが通常どおりに対応します:</p> <span class='rusttest'>fn main() { fn call_with_one(some_closure: &amp;Fn(i32) -&gt; i32) -&gt; i32 { some_closure(1) } let answer = call_with_one(&amp;|x| x + 2); assert_eq!(3, answer); }</span><pre class='rust rust-example-rendered'> <span class='kw'>fn</span> <span class='ident'>call_with_one</span>(<span class='ident'>some_closure</span>: <span class='kw-2'>&amp;</span><span class='ident'>Fn</span>(<span class='ident'>i32</span>) <span class='op'>-&gt;</span> <span class='ident'>i32</span>) <span class='op'>-&gt;</span> <span class='ident'>i32</span> { <span class='ident'>some_closure</span>(<span class='number'>1</span>) } <span class='kw'>let</span> <span class='ident'>answer</span> <span class='op'>=</span> <span class='ident'>call_with_one</span>(<span class='kw-2'>&amp;</span><span class='op'>|</span><span class='ident'>x</span><span class='op'>|</span> <span class='ident'>x</span> <span class='op'>+</span> <span class='number'>2</span>); <span class='macro'>assert_eq</span><span class='macro'>!</span>(<span class='number'>3</span>, <span class='ident'>answer</span>);</pre> <!-- Now we take a trait object, a `&Fn`. And we have to make a reference --> <!-- to our closure when we pass it to `call_with_one`, so we use `&||`. --> <p>トレイトオブジェクト <code>&amp;Fn</code> を引数にとります。 また <code>call_with_one</code> にクロージャを渡すときに参照を利用するようにしました、 そのため <code>&amp;||</code> を利用しています。</p> <!-- # Function pointers and closures --> <h1 id='関数ポインタとクロージャ' class='section-header'><a href='#関数ポインタとクロージャ'>関数ポインタとクロージャ</a></h1> <!-- A function pointer is kind of like a closure that has no environment. As such, --> <!-- you can pass a function pointer to any function expecting a closure argument, --> <!-- and it will work: --> <p>関数ポインタは環境を持たないクロージャのようなものです。 そのため、クロージャを引数として期待している関数に関数ポインタを渡すことができます。</p> <span class='rusttest'>fn main() { fn call_with_one(some_closure: &amp;Fn(i32) -&gt; i32) -&gt; i32 { some_closure(1) } fn add_one(i: i32) -&gt; i32 { i + 1 } let f = add_one; let answer = call_with_one(&amp;f); assert_eq!(2, answer); }</span><pre class='rust rust-example-rendered'> <span class='kw'>fn</span> <span class='ident'>call_with_one</span>(<span class='ident'>some_closure</span>: <span class='kw-2'>&amp;</span><span class='ident'>Fn</span>(<span class='ident'>i32</span>) <span class='op'>-&gt;</span> <span class='ident'>i32</span>) <span class='op'>-&gt;</span> <span class='ident'>i32</span> { <span class='ident'>some_closure</span>(<span class='number'>1</span>) } <span class='kw'>fn</span> <span class='ident'>add_one</span>(<span class='ident'>i</span>: <span class='ident'>i32</span>) <span class='op'>-&gt;</span> <span class='ident'>i32</span> { <span class='ident'>i</span> <span class='op'>+</span> <span class='number'>1</span> } <span class='kw'>let</span> <span class='ident'>f</span> <span class='op'>=</span> <span class='ident'>add_one</span>; <span class='kw'>let</span> <span class='ident'>answer</span> <span class='op'>=</span> <span class='ident'>call_with_one</span>(<span class='kw-2'>&amp;</span><span class='ident'>f</span>); <span class='macro'>assert_eq</span><span class='macro'>!</span>(<span class='number'>2</span>, <span class='ident'>answer</span>);</pre> <!-- In this example, we don’t strictly need the intermediate variable `f`, --> <!-- the name of the function works just fine too: --> <p>この例では、中間の変数 <code>f</code> が必ずしも必要なわけではありません、関数名を指定することでもきちんと動作します:</p> <span class='rusttest'>fn main() { let answer = call_with_one(&amp;add_one); }</span><pre class='rust rust-example-rendered'> <span class='kw'>let</span> <span class='ident'>answer</span> <span class='op'>=</span> <span class='ident'>call_with_one</span>(<span class='kw-2'>&amp;</span><span class='ident'>add_one</span>);</pre> <!-- # Returning closures --> <h1 id='クロージャを返す' class='section-header'><a href='#クロージャを返す'>クロージャを返す</a></h1> <!-- It’s very common for functional-style code to return closures in various --> <!-- situations. If you try to return a closure, you may run into an error. At --> <!-- first, it may seem strange, but we’ll figure it out. Here’s how you’d probably --> <!-- try to return a closure from a function: --> <p>関数を用いたスタイルのコードでは、クロージャを返すことは非常によく見られます。 もし、クロージャを返すことを試みた場合、エラーが発生します。これは一見奇妙に思われますが、理解することができます。 以下は、関数からクロージャを返すことを試みた場合のコードです:</p> <span class='rusttest'>fn main() { fn factory() -&gt; (Fn(i32) -&gt; i32) { let num = 5; |x| x + num } let f = factory(); let answer = f(1); assert_eq!(6, answer); }</span><pre class='rust rust-example-rendered'> <span class='kw'>fn</span> <span class='ident'>factory</span>() <span class='op'>-&gt;</span> (<span class='ident'>Fn</span>(<span class='ident'>i32</span>) <span class='op'>-&gt;</span> <span class='ident'>i32</span>) { <span class='kw'>let</span> <span class='ident'>num</span> <span class='op'>=</span> <span class='number'>5</span>; <span class='op'>|</span><span class='ident'>x</span><span class='op'>|</span> <span class='ident'>x</span> <span class='op'>+</span> <span class='ident'>num</span> } <span class='kw'>let</span> <span class='ident'>f</span> <span class='op'>=</span> <span class='ident'>factory</span>(); <span class='kw'>let</span> <span class='ident'>answer</span> <span class='op'>=</span> <span class='ident'>f</span>(<span class='number'>1</span>); <span class='macro'>assert_eq</span><span class='macro'>!</span>(<span class='number'>6</span>, <span class='ident'>answer</span>);</pre> <!-- This gives us these long, related errors: --> <p>このコードは以下の長いエラーを発生させます:</p> <pre><code class="language-text">error: the trait bound `core::ops::Fn(i32) -&gt; i32 : core::marker::Sized` is not satisfied [E0277] fn factory() -&gt; (Fn(i32) -&gt; i32) { ^~~~~~~~~~~~~~~~ note: `core::ops::Fn(i32) -&gt; i32` does not have a constant size known at compile-time fn factory() -&gt; (Fn(i32) -&gt; i32) { ^~~~~~~~~~~~~~~~ error: the trait bound `core::ops::Fn(i32) -&gt; i32 : core::marker::Sized` is not satisfied [E0277] let f = factory(); ^ note: `core::ops::Fn(i32) -&gt; i32` does not have a constant size known at compile-time let f = factory(); ^ </code></pre> <!-- In order to return something from a function, Rust needs to know what --> <!-- size the return type is. But since `Fn` is a trait, it could be various --> <!-- things of various sizes: many different types can implement `Fn`. An easy --> <!-- way to give something a size is to take a reference to it, as references --> <!-- have a known size. So we’d write this: --> <p>関数から何かを返すにあたって、Rustは返り値の型のサイズを知る必要があります。 しかし、 <code>Fn</code> はトレイトであるため、そのサイズや種類は多岐にわたることになります: 多くの異なる型が <code>Fn</code> を実装できます。 何かにサイズを与える簡単な方法は、それに対する参照を取得する方法です、参照は既知のサイズを持っています。 そのため、以下のように書くことができます:</p> <span class='rusttest'>fn main() { fn factory() -&gt; &amp;(Fn(i32) -&gt; i32) { let num = 5; |x| x + num } let f = factory(); let answer = f(1); assert_eq!(6, answer); }</span><pre class='rust rust-example-rendered'> <span class='kw'>fn</span> <span class='ident'>factory</span>() <span class='op'>-&gt;</span> <span class='kw-2'>&amp;</span>(<span class='ident'>Fn</span>(<span class='ident'>i32</span>) <span class='op'>-&gt;</span> <span class='ident'>i32</span>) { <span class='kw'>let</span> <span class='ident'>num</span> <span class='op'>=</span> <span class='number'>5</span>; <span class='op'>|</span><span class='ident'>x</span><span class='op'>|</span> <span class='ident'>x</span> <span class='op'>+</span> <span class='ident'>num</span> } <span class='kw'>let</span> <span class='ident'>f</span> <span class='op'>=</span> <span class='ident'>factory</span>(); <span class='kw'>let</span> <span class='ident'>answer</span> <span class='op'>=</span> <span class='ident'>f</span>(<span class='number'>1</span>); <span class='macro'>assert_eq</span><span class='macro'>!</span>(<span class='number'>6</span>, <span class='ident'>answer</span>);</pre> <!-- But we get another error: --> <p>しかし、他のエラーが発生してしまいます:</p> <pre><code class="language-text">error: missing lifetime specifier [E0106] fn factory() -&gt; &amp;(Fn(i32) -&gt; i32) { ^~~~~~~~~~~~~~~~~ </code></pre> <!-- Right. Because we have a reference, we need to give it a lifetime. But --> <!-- our `factory()` function takes no arguments, so --> <!-- [elision](lifetimes.html#lifetime-elision) doesn’t kick in here. Then what --> <!-- choices do we have? Try `'static`: --> <p>ふむ。これはリファレンスを利用したので、ライフタイムを指定する必要が有るためです。 しかし、 <code>factory()</code> 関数は引数を何も取りません、 そのため <a href="lifetimes.html#lifetime-elision">ライフタイムの省略</a> は実施されません。 では、どのような選択肢が有るのでしょうか? <code>&#39;static</code> を試してみましょう:</p> <span class='rusttest'>fn main() { fn factory() -&gt; &amp;&#39;static (Fn(i32) -&gt; i32) { let num = 5; |x| x + num } let f = factory(); let answer = f(1); assert_eq!(6, answer); }</span><pre class='rust rust-example-rendered'> <span class='kw'>fn</span> <span class='ident'>factory</span>() <span class='op'>-&gt;</span> <span class='kw-2'>&amp;</span><span class='lifetime'>&#39;static</span> (<span class='ident'>Fn</span>(<span class='ident'>i32</span>) <span class='op'>-&gt;</span> <span class='ident'>i32</span>) { <span class='kw'>let</span> <span class='ident'>num</span> <span class='op'>=</span> <span class='number'>5</span>; <span class='op'>|</span><span class='ident'>x</span><span class='op'>|</span> <span class='ident'>x</span> <span class='op'>+</span> <span class='ident'>num</span> } <span class='kw'>let</span> <span class='ident'>f</span> <span class='op'>=</span> <span class='ident'>factory</span>(); <span class='kw'>let</span> <span class='ident'>answer</span> <span class='op'>=</span> <span class='ident'>f</span>(<span class='number'>1</span>); <span class='macro'>assert_eq</span><span class='macro'>!</span>(<span class='number'>6</span>, <span class='ident'>answer</span>);</pre> <!-- But we get another error: --> <p>しかし、以下の別のエラーが発生します:</p> <pre><code class="language-text">error: mismatched types: expected `&amp;&#39;static core::ops::Fn(i32) -&gt; i32`, found `[closure@&lt;anon&gt;:7:9: 7:20]` (expected &amp;-ptr, found closure) [E0308] |x| x + num ^~~~~~~~~~~ </code></pre> <!-- This error is letting us know that we don’t have a `&'static Fn(i32) -> i32`, --> <!-- we have a `[closure@<anon>:7:9: 7:20]`. Wait, what? --> <p>このエラーは <code>&amp;&#39;static Fn(i32) -&gt; i32</code> ではなく、 <code>[closure@&lt;anon&gt;:7:9: 7:20]</code> を使ってしまっているということを伝えています。 ちょっと待ってください、一体これはどういう意味でしょう?</p> <!-- Because each closure generates its own environment `struct` and implementation --> <!-- of `Fn` and friends, these types are anonymous. They exist solely for --> <!-- this closure. So Rust shows them as `closure@<anon>`, rather than some --> <!-- autogenerated name. --> <p>それぞれのクロージャはそれぞれの環境用の <code>struct</code> を生成し、 <code>Fn</code> やそれに準ずるものを実装するため、それぞれの型は匿名となります。 それらの型はそれらのクロージャのためだけに存在します。 そのためRustはそれらの型を自動生成された名前の代わりに <code>closure@&lt;anon&gt;</code> と表示します。</p> <!-- The error also points out that the return type is expected to be a reference, --> <!-- but what we are trying to return is not. Further, we cannot directly assign a --> <!-- `'static` lifetime to an object. So we'll take a different approach and return --> <!-- a ‘trait object’ by `Box`ing up the `Fn`. This _almost_ works: --> <p>また、このエラーは返り値の型が参照であることを期待しているが、 上のコードではそうなっていないということについても指摘しています。 もうちょっというと、直接的に <code>&#39;static</code> ライフタイムをオブジェクトに割り当てることはできません。 そこで、<code>Fn</code> をボックス化することで「トレイトオブジェクト」を返すという方法を取ります。 そうすると、動作するまであと一歩のところまで来ます:</p> <span class='rusttest'>fn factory() -&gt; Box&lt;Fn(i32) -&gt; i32&gt; { let num = 5; Box::new(|x| x + num) } fn main() { let f = factory(); let answer = f(1); assert_eq!(6, answer); } </span><pre class='rust rust-example-rendered'> <span class='kw'>fn</span> <span class='ident'>factory</span>() <span class='op'>-&gt;</span> <span class='ident'>Box</span><span class='op'>&lt;</span><span class='ident'>Fn</span>(<span class='ident'>i32</span>) <span class='op'>-&gt;</span> <span class='ident'>i32</span><span class='op'>&gt;</span> { <span class='kw'>let</span> <span class='ident'>num</span> <span class='op'>=</span> <span class='number'>5</span>; <span class='ident'>Box</span>::<span class='ident'>new</span>(<span class='op'>|</span><span class='ident'>x</span><span class='op'>|</span> <span class='ident'>x</span> <span class='op'>+</span> <span class='ident'>num</span>) } <span class='kw'>let</span> <span class='ident'>f</span> <span class='op'>=</span> <span class='ident'>factory</span>(); <span class='kw'>let</span> <span class='ident'>answer</span> <span class='op'>=</span> <span class='ident'>f</span>(<span class='number'>1</span>); <span class='macro'>assert_eq</span><span class='macro'>!</span>(<span class='number'>6</span>, <span class='ident'>answer</span>);</pre> <!-- There’s just one last problem: --> <p>最後に残されたエラーは以下のとおりです:</p> <pre><code class="language-text">error: closure may outlive the current function, but it borrows `num`, which is owned by the current function [E0373] Box::new(|x| x + num) ^~~~~~~~~~~ </code></pre> <!-- Well, as we discussed before, closures borrow their environment. And in this --> <!-- case, our environment is based on a stack-allocated `5`, the `num` variable --> <!-- binding. So the borrow has a lifetime of the stack frame. So if we returned --> <!-- this closure, the function call would be over, the stack frame would go away, --> <!-- and our closure is capturing an environment of garbage memory! With one last --> <!-- fix, we can make this work: --> <p>以前説明したように、クロージャはその環境を借用します。 今回の場合は、環境はスタックにアロケートされた <code>5</code> に束縛された <code>num</code> からできていることから、 環境の借用はスタックフレームと同じライフタイムを持っています。 そのため、もしこのクロージャを返り値とした場合、 そのあと <code>factory()</code> 関数の処理は終了し、スタックフレームが取り除かれクロージャはゴミとなったメモリを参照することになります! 上のコードに最後の修正を施すことによって動作させることができるようになります:</p> <span class='rusttest'>fn factory() -&gt; Box&lt;Fn(i32) -&gt; i32&gt; { let num = 5; Box::new(move |x| x + num) } fn main() { let f = factory(); let answer = f(1); assert_eq!(6, answer); } </span><pre class='rust rust-example-rendered'> <span class='kw'>fn</span> <span class='ident'>factory</span>() <span class='op'>-&gt;</span> <span class='ident'>Box</span><span class='op'>&lt;</span><span class='ident'>Fn</span>(<span class='ident'>i32</span>) <span class='op'>-&gt;</span> <span class='ident'>i32</span><span class='op'>&gt;</span> { <span class='kw'>let</span> <span class='ident'>num</span> <span class='op'>=</span> <span class='number'>5</span>; <span class='ident'>Box</span>::<span class='ident'>new</span>(<span class='kw'>move</span> <span class='op'>|</span><span class='ident'>x</span><span class='op'>|</span> <span class='ident'>x</span> <span class='op'>+</span> <span class='ident'>num</span>) } <span class='kw'>let</span> <span class='ident'>f</span> <span class='op'>=</span> <span class='ident'>factory</span>(); <span class='kw'>let</span> <span class='ident'>answer</span> <span class='op'>=</span> <span class='ident'>f</span>(<span class='number'>1</span>); <span class='macro'>assert_eq</span><span class='macro'>!</span>(<span class='number'>6</span>, <span class='ident'>answer</span>);</pre> <!-- By making the inner closure a `move Fn`, we create a new stack frame for our --> <!-- closure. By `Box`ing it up, we’ve given it a known size, allowing it to --> <!-- escape our stack frame. --> <p><code>factory()</code> 内のクロージャを <code>move Fn</code> にすることで、新しいスタックフレームをクロージャのために生成します。 そしてボックス化することによって、既知のサイズとなり、現在のスタックフレームから抜けることが可能になります。</p> <script type="text/javascript"> window.playgroundUrl = "https://play.rust-lang.org"; </script> <script src='rustbook.js'></script> <script src='playpen.js'></script> </div></div> </body> </html> <|start_filename|>docs/1.9/nomicon/vec-zsts.html<|end_filename|> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="generator" content="rustdoc"> <title>Handling Zero-Sized Types</title> <link rel="stylesheet" type="text/css" href="rustbook.css"> <meta name="robots" content="noindex"> </head> <body class="rustdoc"> <!--[if lte IE 8]> <div class="warning"> This old browser is unsupported and will most likely display funky things. </div> <![endif]--> <div id="nav"> <button id="toggle-nav"> <span class="sr-only">Toggle navigation</span> <span class="bar"></span> <span class="bar"></span> <span class="bar"></span> </button> </div> <div id='toc' class='mobile-hidden'> <ul class='chapter'> <li><a href='README.html'><b>1.</b> Introduction</a> </li> <li><a href='meet-safe-and-unsafe.html'><b>2.</b> Meet Safe and Unsafe</a> <ul class='section'> <li><a href='safe-unsafe-meaning.html'><b>2.1.</b> How Safe and Unsafe Interact</a> </li> <li><a href='working-with-unsafe.html'><b>2.2.</b> Working with Unsafe</a> </li> </ul> </li> <li><a href='data.html'><b>3.</b> Data Layout</a> <ul class='section'> <li><a href='repr-rust.html'><b>3.1.</b> repr(Rust)</a> </li> <li><a href='exotic-sizes.html'><b>3.2.</b> Exotically Sized Types</a> </li> <li><a href='other-reprs.html'><b>3.3.</b> Other reprs</a> </li> </ul> </li> <li><a href='ownership.html'><b>4.</b> Ownership</a> <ul class='section'> <li><a href='references.html'><b>4.1.</b> References</a> </li> <li><a href='lifetimes.html'><b>4.2.</b> Lifetimes</a> </li> <li><a href='lifetime-mismatch.html'><b>4.3.</b> Limits of Lifetimes</a> </li> <li><a href='lifetime-elision.html'><b>4.4.</b> Lifetime Elision</a> </li> <li><a href='unbounded-lifetimes.html'><b>4.5.</b> Unbounded Lifetimes</a> </li> <li><a href='hrtb.html'><b>4.6.</b> Higher-Rank Trait Bounds</a> </li> <li><a href='subtyping.html'><b>4.7.</b> Subtyping and Variance</a> </li> <li><a href='dropck.html'><b>4.8.</b> Drop Check</a> </li> <li><a href='phantom-data.html'><b>4.9.</b> PhantomData</a> </li> <li><a href='borrow-splitting.html'><b>4.10.</b> Splitting Borrows</a> </li> </ul> </li> <li><a href='conversions.html'><b>5.</b> Type Conversions</a> <ul class='section'> <li><a href='coercions.html'><b>5.1.</b> Coercions</a> </li> <li><a href='dot-operator.html'><b>5.2.</b> The Dot Operator</a> </li> <li><a href='casts.html'><b>5.3.</b> Casts</a> </li> <li><a href='transmutes.html'><b>5.4.</b> Transmutes</a> </li> </ul> </li> <li><a href='uninitialized.html'><b>6.</b> Uninitialized Memory</a> <ul class='section'> <li><a href='checked-uninit.html'><b>6.1.</b> Checked</a> </li> <li><a href='drop-flags.html'><b>6.2.</b> Drop Flags</a> </li> <li><a href='unchecked-uninit.html'><b>6.3.</b> Unchecked</a> </li> </ul> </li> <li><a href='obrm.html'><b>7.</b> Ownership Based Resource Management</a> <ul class='section'> <li><a href='constructors.html'><b>7.1.</b> Constructors</a> </li> <li><a href='destructors.html'><b>7.2.</b> Destructors</a> </li> <li><a href='leaking.html'><b>7.3.</b> Leaking</a> </li> </ul> </li> <li><a href='unwinding.html'><b>8.</b> Unwinding</a> <ul class='section'> <li><a href='exception-safety.html'><b>8.1.</b> Exception Safety</a> </li> <li><a href='poisoning.html'><b>8.2.</b> Poisoning</a> </li> </ul> </li> <li><a href='concurrency.html'><b>9.</b> Concurrency</a> <ul class='section'> <li><a href='races.html'><b>9.1.</b> Races</a> </li> <li><a href='send-and-sync.html'><b>9.2.</b> Send and Sync</a> </li> <li><a href='atomics.html'><b>9.3.</b> Atomics</a> </li> </ul> </li> <li><a href='vec.html'><b>10.</b> Implementing Vec</a> <ul class='section'> <li><a href='vec-layout.html'><b>10.1.</b> Layout</a> </li> <li><a href='vec-alloc.html'><b>10.2.</b> Allocating</a> </li> <li><a href='vec-push-pop.html'><b>10.3.</b> Push and Pop</a> </li> <li><a href='vec-dealloc.html'><b>10.4.</b> Deallocating</a> </li> <li><a href='vec-deref.html'><b>10.5.</b> Deref</a> </li> <li><a href='vec-insert-remove.html'><b>10.6.</b> Insert and Remove</a> </li> <li><a href='vec-into-iter.html'><b>10.7.</b> IntoIter</a> </li> <li><a href='vec-raw.html'><b>10.8.</b> RawVec</a> </li> <li><a href='vec-drain.html'><b>10.9.</b> Drain</a> </li> <li><a class='active' href='vec-zsts.html'><b>10.10.</b> Handling Zero-Sized Types</a> </li> <li><a href='vec-final.html'><b>10.11.</b> Final Code</a> </li> </ul> </li> <li><a href='arc-and-mutex.html'><b>11.</b> Implementing Arc and Mutex</a> </li> </ul> </div> <div id='page-wrapper'> <div id='page'> <blockquote class="header-caveat"> <p> <strong>注意: <a href="https://doc.rust-jp.rs/book-ja/">最新版のドキュメントをご覧ください。</a></strong>この第1版ドキュメントは古くなっており、最新情報が反映されていません。リンク先のドキュメントが現在の Rust の最新のドキュメントです。 </p> </blockquote> <h1 class="title">Handling Zero-Sized Types</h1> <p>It&#39;s time. We&#39;re going to fight the specter that is zero-sized types. Safe Rust <em>never</em> needs to care about this, but Vec is very intensive on raw pointers and raw allocations, which are exactly the two things that care about zero-sized types. We need to be careful of two things:</p> <ul> <li>The raw allocator API has undefined behavior if you pass in 0 for an allocation size.</li> <li>raw pointer offsets are no-ops for zero-sized types, which will break our C-style pointer iterator.</li> </ul> <p>Thankfully we abstracted out pointer-iterators and allocating handling into RawValIter and RawVec respectively. How mysteriously convenient.</p> <h2 id='allocating-zero-sized-types' class='section-header'><a href='#allocating-zero-sized-types'>Allocating Zero-Sized Types</a></h2> <p>So if the allocator API doesn&#39;t support zero-sized allocations, what on earth do we store as our allocation? Why, <code>heap::EMPTY</code> of course! Almost every operation with a ZST is a no-op since ZSTs have exactly one value, and therefore no state needs to be considered to store or load them. This actually extends to <code>ptr::read</code> and <code>ptr::write</code>: they won&#39;t actually look at the pointer at all. As such we never need to change the pointer.</p> <p>Note however that our previous reliance on running out of memory before overflow is no longer valid with zero-sized types. We must explicitly guard against capacity overflow for zero-sized types.</p> <p>Due to our current architecture, all this means is writing 3 guards, one in each method of RawVec.</p> <span class='rusttest'>fn main() { impl&lt;T&gt; RawVec&lt;T&gt; { fn new() -&gt; Self { unsafe { // !0 is usize::MAX. This branch should be stripped at compile time. let cap = if mem::size_of::&lt;T&gt;() == 0 { !0 } else { 0 }; // heap::EMPTY doubles as &quot;unallocated&quot; and &quot;zero-sized allocation&quot; RawVec { ptr: Unique::new(heap::EMPTY as *mut T), cap: cap } } } fn grow(&amp;mut self) { unsafe { let elem_size = mem::size_of::&lt;T&gt;(); // since we set the capacity to usize::MAX when elem_size is // 0, getting to here necessarily means the Vec is overfull. assert!(elem_size != 0, &quot;capacity overflow&quot;); let align = mem::align_of::&lt;T&gt;(); let (new_cap, ptr) = if self.cap == 0 { let ptr = heap::allocate(elem_size, align); (1, ptr) } else { let new_cap = 2 * self.cap; let ptr = heap::reallocate(*self.ptr as *mut _, self.cap * elem_size, new_cap * elem_size, align); (new_cap, ptr) }; // If allocate or reallocate fail, we&#39;ll get `null` back if ptr.is_null() { oom() } self.ptr = Unique::new(ptr as *mut _); self.cap = new_cap; } } } impl&lt;T&gt; Drop for RawVec&lt;T&gt; { fn drop(&amp;mut self) { let elem_size = mem::size_of::&lt;T&gt;(); // don&#39;t free zero-sized allocations, as they were never allocated. if self.cap != 0 &amp;&amp; elem_size != 0 { let align = mem::align_of::&lt;T&gt;(); let num_bytes = elem_size * self.cap; unsafe { heap::deallocate(*self.ptr as *mut _, num_bytes, align); } } } } }</span><pre class='rust rust-example-rendered'> <span class='kw'>impl</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> <span class='ident'>RawVec</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> { <span class='kw'>fn</span> <span class='ident'>new</span>() <span class='op'>-&gt;</span> <span class='self'>Self</span> { <span class='kw'>unsafe</span> { <span class='comment'>// !0 is usize::MAX. This branch should be stripped at compile time.</span> <span class='kw'>let</span> <span class='ident'>cap</span> <span class='op'>=</span> <span class='kw'>if</span> <span class='ident'>mem</span>::<span class='ident'>size_of</span>::<span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span>() <span class='op'>==</span> <span class='number'>0</span> { <span class='op'>!</span><span class='number'>0</span> } <span class='kw'>else</span> { <span class='number'>0</span> }; <span class='comment'>// heap::EMPTY doubles as &quot;unallocated&quot; and &quot;zero-sized allocation&quot;</span> <span class='ident'>RawVec</span> { <span class='ident'>ptr</span>: <span class='ident'>Unique</span>::<span class='ident'>new</span>(<span class='ident'>heap</span>::<span class='ident'>EMPTY</span> <span class='kw'>as</span> <span class='op'>*</span><span class='kw-2'>mut</span> <span class='ident'>T</span>), <span class='ident'>cap</span>: <span class='ident'>cap</span> } } } <span class='kw'>fn</span> <span class='ident'>grow</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>) { <span class='kw'>unsafe</span> { <span class='kw'>let</span> <span class='ident'>elem_size</span> <span class='op'>=</span> <span class='ident'>mem</span>::<span class='ident'>size_of</span>::<span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span>(); <span class='comment'>// since we set the capacity to usize::MAX when elem_size is</span> <span class='comment'>// 0, getting to here necessarily means the Vec is overfull.</span> <span class='macro'>assert</span><span class='macro'>!</span>(<span class='ident'>elem_size</span> <span class='op'>!=</span> <span class='number'>0</span>, <span class='string'>&quot;capacity overflow&quot;</span>); <span class='kw'>let</span> <span class='ident'>align</span> <span class='op'>=</span> <span class='ident'>mem</span>::<span class='ident'>align_of</span>::<span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span>(); <span class='kw'>let</span> (<span class='ident'>new_cap</span>, <span class='ident'>ptr</span>) <span class='op'>=</span> <span class='kw'>if</span> <span class='self'>self</span>.<span class='ident'>cap</span> <span class='op'>==</span> <span class='number'>0</span> { <span class='kw'>let</span> <span class='ident'>ptr</span> <span class='op'>=</span> <span class='ident'>heap</span>::<span class='ident'>allocate</span>(<span class='ident'>elem_size</span>, <span class='ident'>align</span>); (<span class='number'>1</span>, <span class='ident'>ptr</span>) } <span class='kw'>else</span> { <span class='kw'>let</span> <span class='ident'>new_cap</span> <span class='op'>=</span> <span class='number'>2</span> <span class='op'>*</span> <span class='self'>self</span>.<span class='ident'>cap</span>; <span class='kw'>let</span> <span class='ident'>ptr</span> <span class='op'>=</span> <span class='ident'>heap</span>::<span class='ident'>reallocate</span>(<span class='op'>*</span><span class='self'>self</span>.<span class='ident'>ptr</span> <span class='kw'>as</span> <span class='op'>*</span><span class='kw-2'>mut</span> _, <span class='self'>self</span>.<span class='ident'>cap</span> <span class='op'>*</span> <span class='ident'>elem_size</span>, <span class='ident'>new_cap</span> <span class='op'>*</span> <span class='ident'>elem_size</span>, <span class='ident'>align</span>); (<span class='ident'>new_cap</span>, <span class='ident'>ptr</span>) }; <span class='comment'>// If allocate or reallocate fail, we&#39;ll get `null` back</span> <span class='kw'>if</span> <span class='ident'>ptr</span>.<span class='ident'>is_null</span>() { <span class='ident'>oom</span>() } <span class='self'>self</span>.<span class='ident'>ptr</span> <span class='op'>=</span> <span class='ident'>Unique</span>::<span class='ident'>new</span>(<span class='ident'>ptr</span> <span class='kw'>as</span> <span class='op'>*</span><span class='kw-2'>mut</span> _); <span class='self'>self</span>.<span class='ident'>cap</span> <span class='op'>=</span> <span class='ident'>new_cap</span>; } } } <span class='kw'>impl</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> <span class='ident'>Drop</span> <span class='kw'>for</span> <span class='ident'>RawVec</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> { <span class='kw'>fn</span> <span class='ident'>drop</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>) { <span class='kw'>let</span> <span class='ident'>elem_size</span> <span class='op'>=</span> <span class='ident'>mem</span>::<span class='ident'>size_of</span>::<span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span>(); <span class='comment'>// don&#39;t free zero-sized allocations, as they were never allocated.</span> <span class='kw'>if</span> <span class='self'>self</span>.<span class='ident'>cap</span> <span class='op'>!=</span> <span class='number'>0</span> <span class='op'>&amp;&amp;</span> <span class='ident'>elem_size</span> <span class='op'>!=</span> <span class='number'>0</span> { <span class='kw'>let</span> <span class='ident'>align</span> <span class='op'>=</span> <span class='ident'>mem</span>::<span class='ident'>align_of</span>::<span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span>(); <span class='kw'>let</span> <span class='ident'>num_bytes</span> <span class='op'>=</span> <span class='ident'>elem_size</span> <span class='op'>*</span> <span class='self'>self</span>.<span class='ident'>cap</span>; <span class='kw'>unsafe</span> { <span class='ident'>heap</span>::<span class='ident'>deallocate</span>(<span class='op'>*</span><span class='self'>self</span>.<span class='ident'>ptr</span> <span class='kw'>as</span> <span class='op'>*</span><span class='kw-2'>mut</span> _, <span class='ident'>num_bytes</span>, <span class='ident'>align</span>); } } } }</pre> <p>That&#39;s it. We support pushing and popping zero-sized types now. Our iterators (that aren&#39;t provided by slice Deref) are still busted, though.</p> <h2 id='iterating-zero-sized-types' class='section-header'><a href='#iterating-zero-sized-types'>Iterating Zero-Sized Types</a></h2> <p>Zero-sized offsets are no-ops. This means that our current design will always initialize <code>start</code> and <code>end</code> as the same value, and our iterators will yield nothing. The current solution to this is to cast the pointers to integers, increment, and then cast them back:</p> <span class='rusttest'>fn main() { impl&lt;T&gt; RawValIter&lt;T&gt; { unsafe fn new(slice: &amp;[T]) -&gt; Self { RawValIter { start: slice.as_ptr(), end: if mem::size_of::&lt;T&gt;() == 0 { ((slice.as_ptr() as usize) + slice.len()) as *const _ } else if slice.len() == 0 { slice.as_ptr() } else { slice.as_ptr().offset(slice.len() as isize) } } } } }</span><pre class='rust rust-example-rendered'> <span class='kw'>impl</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> <span class='ident'>RawValIter</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> { <span class='kw'>unsafe</span> <span class='kw'>fn</span> <span class='ident'>new</span>(<span class='ident'>slice</span>: <span class='kw-2'>&amp;</span>[<span class='ident'>T</span>]) <span class='op'>-&gt;</span> <span class='self'>Self</span> { <span class='ident'>RawValIter</span> { <span class='ident'>start</span>: <span class='ident'>slice</span>.<span class='ident'>as_ptr</span>(), <span class='ident'>end</span>: <span class='kw'>if</span> <span class='ident'>mem</span>::<span class='ident'>size_of</span>::<span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span>() <span class='op'>==</span> <span class='number'>0</span> { ((<span class='ident'>slice</span>.<span class='ident'>as_ptr</span>() <span class='kw'>as</span> <span class='ident'>usize</span>) <span class='op'>+</span> <span class='ident'>slice</span>.<span class='ident'>len</span>()) <span class='kw'>as</span> <span class='op'>*</span><span class='kw'>const</span> _ } <span class='kw'>else</span> <span class='kw'>if</span> <span class='ident'>slice</span>.<span class='ident'>len</span>() <span class='op'>==</span> <span class='number'>0</span> { <span class='ident'>slice</span>.<span class='ident'>as_ptr</span>() } <span class='kw'>else</span> { <span class='ident'>slice</span>.<span class='ident'>as_ptr</span>().<span class='ident'>offset</span>(<span class='ident'>slice</span>.<span class='ident'>len</span>() <span class='kw'>as</span> <span class='ident'>isize</span>) } } } }</pre> <p>Now we have a different bug. Instead of our iterators not running at all, our iterators now run <em>forever</em>. We need to do the same trick in our iterator impls. Also, our size_hint computation code will divide by 0 for ZSTs. Since we&#39;ll basically be treating the two pointers as if they point to bytes, we&#39;ll just map size 0 to divide by 1.</p> <span class='rusttest'>fn main() { impl&lt;T&gt; Iterator for RawValIter&lt;T&gt; { type Item = T; fn next(&amp;mut self) -&gt; Option&lt;T&gt; { if self.start == self.end { None } else { unsafe { let result = ptr::read(self.start); self.start = if mem::size_of::&lt;T&gt;() == 0 { (self.start as usize + 1) as *const _ } else { self.start.offset(1); } Some(result) } } } fn size_hint(&amp;self) -&gt; (usize, Option&lt;usize&gt;) { let elem_size = mem::size_of::&lt;T&gt;(); let len = (self.end as usize - self.start as usize) / if elem_size == 0 { 1 } else { elem_size }; (len, Some(len)) } } impl&lt;T&gt; DoubleEndedIterator for RawValIter&lt;T&gt; { fn next_back(&amp;mut self) -&gt; Option&lt;T&gt; { if self.start == self.end { None } else { unsafe { self.end = if mem::size_of::&lt;T&gt;() == 0 { (self.end as usize - 1) as *const _ } else { self.end.offset(-1); } Some(ptr::read(self.end)) } } } } }</span><pre class='rust rust-example-rendered'> <span class='kw'>impl</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> <span class='ident'>Iterator</span> <span class='kw'>for</span> <span class='ident'>RawValIter</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> { <span class='kw'>type</span> <span class='ident'>Item</span> <span class='op'>=</span> <span class='ident'>T</span>; <span class='kw'>fn</span> <span class='ident'>next</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>) <span class='op'>-&gt;</span> <span class='prelude-ty'>Option</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> { <span class='kw'>if</span> <span class='self'>self</span>.<span class='ident'>start</span> <span class='op'>==</span> <span class='self'>self</span>.<span class='ident'>end</span> { <span class='prelude-val'>None</span> } <span class='kw'>else</span> { <span class='kw'>unsafe</span> { <span class='kw'>let</span> <span class='ident'>result</span> <span class='op'>=</span> <span class='ident'>ptr</span>::<span class='ident'>read</span>(<span class='self'>self</span>.<span class='ident'>start</span>); <span class='self'>self</span>.<span class='ident'>start</span> <span class='op'>=</span> <span class='kw'>if</span> <span class='ident'>mem</span>::<span class='ident'>size_of</span>::<span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span>() <span class='op'>==</span> <span class='number'>0</span> { (<span class='self'>self</span>.<span class='ident'>start</span> <span class='kw'>as</span> <span class='ident'>usize</span> <span class='op'>+</span> <span class='number'>1</span>) <span class='kw'>as</span> <span class='op'>*</span><span class='kw'>const</span> _ } <span class='kw'>else</span> { <span class='self'>self</span>.<span class='ident'>start</span>.<span class='ident'>offset</span>(<span class='number'>1</span>); } <span class='prelude-val'>Some</span>(<span class='ident'>result</span>) } } } <span class='kw'>fn</span> <span class='ident'>size_hint</span>(<span class='kw-2'>&amp;</span><span class='self'>self</span>) <span class='op'>-&gt;</span> (<span class='ident'>usize</span>, <span class='prelude-ty'>Option</span><span class='op'>&lt;</span><span class='ident'>usize</span><span class='op'>&gt;</span>) { <span class='kw'>let</span> <span class='ident'>elem_size</span> <span class='op'>=</span> <span class='ident'>mem</span>::<span class='ident'>size_of</span>::<span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span>(); <span class='kw'>let</span> <span class='ident'>len</span> <span class='op'>=</span> (<span class='self'>self</span>.<span class='ident'>end</span> <span class='kw'>as</span> <span class='ident'>usize</span> <span class='op'>-</span> <span class='self'>self</span>.<span class='ident'>start</span> <span class='kw'>as</span> <span class='ident'>usize</span>) <span class='op'>/</span> <span class='kw'>if</span> <span class='ident'>elem_size</span> <span class='op'>==</span> <span class='number'>0</span> { <span class='number'>1</span> } <span class='kw'>else</span> { <span class='ident'>elem_size</span> }; (<span class='ident'>len</span>, <span class='prelude-val'>Some</span>(<span class='ident'>len</span>)) } } <span class='kw'>impl</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> <span class='ident'>DoubleEndedIterator</span> <span class='kw'>for</span> <span class='ident'>RawValIter</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> { <span class='kw'>fn</span> <span class='ident'>next_back</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>) <span class='op'>-&gt;</span> <span class='prelude-ty'>Option</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> { <span class='kw'>if</span> <span class='self'>self</span>.<span class='ident'>start</span> <span class='op'>==</span> <span class='self'>self</span>.<span class='ident'>end</span> { <span class='prelude-val'>None</span> } <span class='kw'>else</span> { <span class='kw'>unsafe</span> { <span class='self'>self</span>.<span class='ident'>end</span> <span class='op'>=</span> <span class='kw'>if</span> <span class='ident'>mem</span>::<span class='ident'>size_of</span>::<span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span>() <span class='op'>==</span> <span class='number'>0</span> { (<span class='self'>self</span>.<span class='ident'>end</span> <span class='kw'>as</span> <span class='ident'>usize</span> <span class='op'>-</span> <span class='number'>1</span>) <span class='kw'>as</span> <span class='op'>*</span><span class='kw'>const</span> _ } <span class='kw'>else</span> { <span class='self'>self</span>.<span class='ident'>end</span>.<span class='ident'>offset</span>(<span class='op'>-</span><span class='number'>1</span>); } <span class='prelude-val'>Some</span>(<span class='ident'>ptr</span>::<span class='ident'>read</span>(<span class='self'>self</span>.<span class='ident'>end</span>)) } } } }</pre> <p>And that&#39;s it. Iteration works!</p> <script type="text/javascript"> window.playgroundUrl = "https://play.rust-lang.org"; </script> <script src='rustbook.js'></script> <script src='playpen.js'></script> </div></div> </body> </html> <|start_filename|>docs/1.6/book/associated-types.html<|end_filename|> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="generator" content="rustdoc"> <title>関連型</title> <link rel="stylesheet" type="text/css" href="rustbook.css"> <meta name="robots" content="noindex"> </head> <body class="rustdoc"> <!--[if lte IE 8]> <div class="warning"> This old browser is unsupported and will most likely display funky things. </div> <![endif]--> <div id="nav"> <button id="toggle-nav"> <span class="sr-only">Toggle navigation</span> <span class="bar"></span> <span class="bar"></span> <span class="bar"></span> </button> </div> <div id='toc' class='mobile-hidden'> <ul class='chapter'> <li><a href='README.html'><b>1.</b> Introduction</a> </li> <li><a href='getting-started.html'><b>2.</b> はじめる</a> </li> <li><a href='learn-rust.html'><b>3.</b> Rustを学ぶ</a> <ul class='section'> <li><a href='guessing-game.html'><b>3.1.</b> 数当てゲーム</a> </li> <li><a href='dining-philosophers.html'><b>3.2.</b> 食事する哲学者</a> </li> <li><a href='rust-inside-other-languages.html'><b>3.3.</b> 他言語と共存する</a> </li> </ul> </li> <li><a href='syntax-and-semantics.html'><b>4.</b> シンタックスとセマンティクス</a> <ul class='section'> <li><a href='variable-bindings.html'><b>4.1.</b> 変数束縛</a> </li> <li><a href='functions.html'><b>4.2.</b> 関数</a> </li> <li><a href='primitive-types.html'><b>4.3.</b> プリミティブ型</a> </li> <li><a href='comments.html'><b>4.4.</b> コメント</a> </li> <li><a href='if.html'><b>4.5.</b> if</a> </li> <li><a href='loops.html'><b>4.6.</b> ループ</a> </li> <li><a href='ownership.html'><b>4.7.</b> 所有権</a> </li> <li><a href='references-and-borrowing.html'><b>4.8.</b> 参照と借用</a> </li> <li><a href='lifetimes.html'><b>4.9.</b> ライフタイム</a> </li> <li><a href='mutability.html'><b>4.10.</b> ミュータビリティ</a> </li> <li><a href='structs.html'><b>4.11.</b> 構造体</a> </li> <li><a href='enums.html'><b>4.12.</b> 列挙型</a> </li> <li><a href='match.html'><b>4.13.</b> マッチ</a> </li> <li><a href='patterns.html'><b>4.14.</b> パターン</a> </li> <li><a href='method-syntax.html'><b>4.15.</b> メソッド構文</a> </li> <li><a href='vectors.html'><b>4.16.</b> ベクタ</a> </li> <li><a href='strings.html'><b>4.17.</b> 文字列</a> </li> <li><a href='generics.html'><b>4.18.</b> ジェネリクス</a> </li> <li><a href='traits.html'><b>4.19.</b> トレイト</a> </li> <li><a href='drop.html'><b>4.20.</b> Drop</a> </li> <li><a href='if-let.html'><b>4.21.</b> if let</a> </li> <li><a href='trait-objects.html'><b>4.22.</b> トレイトオブジェクト</a> </li> <li><a href='closures.html'><b>4.23.</b> クロージャ</a> </li> <li><a href='ufcs.html'><b>4.24.</b> 共通の関数呼出構文</a> </li> <li><a href='crates-and-modules.html'><b>4.25.</b> クレートとモジュール</a> </li> <li><a href='const-and-static.html'><b>4.26.</b> `const` と `static`</a> </li> <li><a href='attributes.html'><b>4.27.</b> アトリビュート</a> </li> <li><a href='type-aliases.html'><b>4.28.</b> `type` エイリアス</a> </li> <li><a href='casting-between-types.html'><b>4.29.</b> 型間のキャスト</a> </li> <li><a class='active' href='associated-types.html'><b>4.30.</b> 関連型</a> </li> <li><a href='unsized-types.html'><b>4.31.</b> サイズ不定型</a> </li> <li><a href='operators-and-overloading.html'><b>4.32.</b> 演算子とオーバーロード</a> </li> <li><a href='deref-coercions.html'><b>4.33.</b> Derefによる型強制</a> </li> <li><a href='macros.html'><b>4.34.</b> マクロ</a> </li> <li><a href='raw-pointers.html'><b>4.35.</b> 生ポインタ</a> </li> <li><a href='unsafe.html'><b>4.36.</b> `unsafe`</a> </li> </ul> </li> <li><a href='effective-rust.html'><b>5.</b> Effective Rust</a> <ul class='section'> <li><a href='the-stack-and-the-heap.html'><b>5.1.</b> スタックとヒープ</a> </li> <li><a href='testing.html'><b>5.2.</b> テスト</a> </li> <li><a href='conditional-compilation.html'><b>5.3.</b> 条件付きコンパイル</a> </li> <li><a href='documentation.html'><b>5.4.</b> ドキュメント</a> </li> <li><a href='iterators.html'><b>5.5.</b> イテレータ</a> </li> <li><a href='concurrency.html'><b>5.6.</b> 並行性</a> </li> <li><a href='error-handling.html'><b>5.7.</b> エラーハンドリング</a> </li> <li><a href='choosing-your-guarantees.html'><b>5.8.</b> 保証を選ぶ</a> </li> <li><a href='ffi.html'><b>5.9.</b> 他言語関数インターフェース</a> </li> <li><a href='borrow-and-asref.html'><b>5.10.</b> BorrowとAsRef</a> </li> <li><a href='release-channels.html'><b>5.11.</b> リリースチャネル</a> </li> <li><a href='using-rust-without-the-standard-library.html'><b>5.12.</b> 標準ライブラリ無しでRustを使う</a> </li> </ul> </li> <li><a href='nightly-rust.html'><b>6.</b> Nightly Rust</a> <ul class='section'> <li><a href='compiler-plugins.html'><b>6.1.</b> コンパイラプラグイン</a> </li> <li><a href='inline-assembly.html'><b>6.2.</b> インラインアセンブリ</a> </li> <li><a href='no-stdlib.html'><b>6.3.</b> No stdlib</a> </li> <li><a href='intrinsics.html'><b>6.4.</b> Intrinsic</a> </li> <li><a href='lang-items.html'><b>6.5.</b> 言語アイテム</a> </li> <li><a href='advanced-linking.html'><b>6.6.</b> 高度なリンキング</a> </li> <li><a href='benchmark-tests.html'><b>6.7.</b> ベンチマークテスト</a> </li> <li><a href='box-syntax-and-patterns.html'><b>6.8.</b> Box構文とパターン</a> </li> <li><a href='slice-patterns.html'><b>6.9.</b> スライスパターン</a> </li> <li><a href='associated-constants.html'><b>6.10.</b> 関連定数</a> </li> <li><a href='custom-allocators.html'><b>6.11.</b> カスタムアロケータ</a> </li> </ul> </li> <li><a href='glossary.html'><b>7.</b> 用語集</a> </li> <li><a href='syntax-index.html'><b>8.</b> 構文の索引</a> </li> <li><a href='bibliography.html'><b>9.</b> 関係書目</a> </li> </ul> </div> <div id='page-wrapper'> <div id='page'> <blockquote class="header-caveat"> <p> <strong>注意: <a href="https://doc.rust-jp.rs/book-ja/">最新版のドキュメントをご覧ください。</a></strong>この第1版ドキュメントは古くなっており、最新情報が反映されていません。リンク先のドキュメントが現在の Rust の最新のドキュメントです。 </p> </blockquote> <h1 class="title">関連型</h1> <!-- % Associated Types --> <!-- Associated types are a powerful part of Rust’s type system. They’re related to --> <!-- the idea of a ‘type family’, in other words, grouping multiple types together. That --> <!-- description is a bit abstract, so let’s dive right into an example. If you want --> <!-- to write a `Graph` trait, you have two types to be generic over: the node type --> <!-- and the edge type. So you might write a trait, `Graph<N, E>`, that looks like --> <!-- this: --> <p>関連型は、Rust型システムの強力な部分です。関連型は、「型族」という概念と関連が有り、 言い換えると、複数の型をグループ化するものです。 この説明はすこし抽象的なので、実際の例を見ていきましょう。 例えば、 <code>Graph</code> トレイトを定義したいとしましょう、このときジェネリックになる2つの型: 頂点の型、辺の型 が存在します。 そのため、以下のように <code>Graph&lt;N, E&gt;</code> と書きたくなるでしょう:</p> <span class='rusttest'>fn main() { trait Graph&lt;N, E&gt; { fn has_edge(&amp;self, &amp;N, &amp;N) -&gt; bool; fn edges(&amp;self, &amp;N) -&gt; Vec&lt;E&gt;; // etc } }</span><pre class='rust rust-example-rendered'> <span class='kw'>trait</span> <span class='ident'>Graph</span><span class='op'>&lt;</span><span class='ident'>N</span>, <span class='ident'>E</span><span class='op'>&gt;</span> { <span class='kw'>fn</span> <span class='ident'>has_edge</span>(<span class='kw-2'>&amp;</span><span class='self'>self</span>, <span class='kw-2'>&amp;</span><span class='ident'>N</span>, <span class='kw-2'>&amp;</span><span class='ident'>N</span>) <span class='op'>-&gt;</span> <span class='ident'>bool</span>; <span class='kw'>fn</span> <span class='ident'>edges</span>(<span class='kw-2'>&amp;</span><span class='self'>self</span>, <span class='kw-2'>&amp;</span><span class='ident'>N</span>) <span class='op'>-&gt;</span> <span class='ident'>Vec</span><span class='op'>&lt;</span><span class='ident'>E</span><span class='op'>&gt;</span>; <span class='comment'>// etc</span> }</pre> <!-- While this sort of works, it ends up being awkward. For example, any function --> <!-- that wants to take a `Graph` as a parameter now _also_ needs to be generic over --> <!-- the `N`ode and `E`dge types too: --> <p>たしかに上のようなコードは動作しますが、この <code>Graph</code> の定義は少し扱いづらいです。 たとえば、任意の <code>Graph</code> を引数に取る関数は、 <em>同時に</em> 頂点 <code>N</code> と辺 <code>E</code> についてもジェネリックとなることになります:</p> <span class='rusttest'>fn main() { fn distance&lt;N, E, G: Graph&lt;N, E&gt;&gt;(graph: &amp;G, start: &amp;N, end: &amp;N) -&gt; u32 { ... } }</span><pre class='rust rust-example-rendered'> <span class='kw'>fn</span> <span class='ident'>distance</span><span class='op'>&lt;</span><span class='ident'>N</span>, <span class='ident'>E</span>, <span class='ident'>G</span>: <span class='ident'>Graph</span><span class='op'>&lt;</span><span class='ident'>N</span>, <span class='ident'>E</span><span class='op'>&gt;&gt;</span>(<span class='ident'>graph</span>: <span class='kw-2'>&amp;</span><span class='ident'>G</span>, <span class='ident'>start</span>: <span class='kw-2'>&amp;</span><span class='ident'>N</span>, <span class='ident'>end</span>: <span class='kw-2'>&amp;</span><span class='ident'>N</span>) <span class='op'>-&gt;</span> <span class='ident'>u32</span> { ... }</pre> <!-- Our distance calculation works regardless of our `Edge` type, so the `E` stuff in --> <!-- this signature is just a distraction. --> <p>この距離を計算する関数distanceは、辺の型に関わらず動作します、そのためシグネチャに含まれる <code>E</code> に関連する部分は邪魔でしかありません。</p> <!-- What we really want to say is that a certain `E`dge and `N`ode type come together --> <!-- to form each kind of `Graph`. We can do that with associated types: --> <p>本当に表現したいことは、それぞれのグラフ( <code>Graph</code> )は辺( <code>E</code> )や頂点( <code>N</code> )で構成されているということです。 それは、以下のように関連型を用いて表現することができます:</p> <span class='rusttest'>fn main() { trait Graph { type N; type E; fn has_edge(&amp;self, &amp;Self::N, &amp;Self::N) -&gt; bool; fn edges(&amp;self, &amp;Self::N) -&gt; Vec&lt;Self::E&gt;; // etc } }</span><pre class='rust rust-example-rendered'> <span class='kw'>trait</span> <span class='ident'>Graph</span> { <span class='kw'>type</span> <span class='ident'>N</span>; <span class='kw'>type</span> <span class='ident'>E</span>; <span class='kw'>fn</span> <span class='ident'>has_edge</span>(<span class='kw-2'>&amp;</span><span class='self'>self</span>, <span class='kw-2'>&amp;</span><span class='self'>Self</span>::<span class='ident'>N</span>, <span class='kw-2'>&amp;</span><span class='self'>Self</span>::<span class='ident'>N</span>) <span class='op'>-&gt;</span> <span class='ident'>bool</span>; <span class='kw'>fn</span> <span class='ident'>edges</span>(<span class='kw-2'>&amp;</span><span class='self'>self</span>, <span class='kw-2'>&amp;</span><span class='self'>Self</span>::<span class='ident'>N</span>) <span class='op'>-&gt;</span> <span class='ident'>Vec</span><span class='op'>&lt;</span><span class='self'>Self</span>::<span class='ident'>E</span><span class='op'>&gt;</span>; <span class='comment'>// etc</span> }</pre> <!-- Now, our clients can be abstract over a given `Graph`: --> <p>このようにすると、<code>Graph</code> を使った関数は以下のように書くことができます:</p> <span class='rusttest'>fn main() { fn distance&lt;G: Graph&gt;(graph: &amp;G, start: &amp;G::N, end: &amp;G::N) -&gt; u32 { ... } }</span><pre class='rust rust-example-rendered'> <span class='kw'>fn</span> <span class='ident'>distance</span><span class='op'>&lt;</span><span class='ident'>G</span>: <span class='ident'>Graph</span><span class='op'>&gt;</span>(<span class='ident'>graph</span>: <span class='kw-2'>&amp;</span><span class='ident'>G</span>, <span class='ident'>start</span>: <span class='kw-2'>&amp;</span><span class='ident'>G</span>::<span class='ident'>N</span>, <span class='ident'>end</span>: <span class='kw-2'>&amp;</span><span class='ident'>G</span>::<span class='ident'>N</span>) <span class='op'>-&gt;</span> <span class='ident'>u32</span> { ... }</pre> <!-- No need to deal with the `E`dge type here! --> <p>もう <code>E</code> について扱う必要はありません!</p> <!-- Let’s go over all this in more detail. --> <p>もっと詳しく見ていきましょう。</p> <!-- ## Defining associated types --> <h2 id='関連型を定義する' class='section-header'><a href='#関連型を定義する'>関連型を定義する</a></h2> <!-- Let’s build that `Graph` trait. Here’s the definition: --> <p>早速、<code>Graph</code> トレイトを定義しましょう。以下がその定義です:</p> <span class='rusttest'>fn main() { trait Graph { type N; type E; fn has_edge(&amp;self, &amp;Self::N, &amp;Self::N) -&gt; bool; fn edges(&amp;self, &amp;Self::N) -&gt; Vec&lt;Self::E&gt;; } }</span><pre class='rust rust-example-rendered'> <span class='kw'>trait</span> <span class='ident'>Graph</span> { <span class='kw'>type</span> <span class='ident'>N</span>; <span class='kw'>type</span> <span class='ident'>E</span>; <span class='kw'>fn</span> <span class='ident'>has_edge</span>(<span class='kw-2'>&amp;</span><span class='self'>self</span>, <span class='kw-2'>&amp;</span><span class='self'>Self</span>::<span class='ident'>N</span>, <span class='kw-2'>&amp;</span><span class='self'>Self</span>::<span class='ident'>N</span>) <span class='op'>-&gt;</span> <span class='ident'>bool</span>; <span class='kw'>fn</span> <span class='ident'>edges</span>(<span class='kw-2'>&amp;</span><span class='self'>self</span>, <span class='kw-2'>&amp;</span><span class='self'>Self</span>::<span class='ident'>N</span>) <span class='op'>-&gt;</span> <span class='ident'>Vec</span><span class='op'>&lt;</span><span class='self'>Self</span>::<span class='ident'>E</span><span class='op'>&gt;</span>; }</pre> <!-- Simple enough. Associated types use the `type` keyword, and go inside the body --> <!-- of the trait, with the functions. --> <p>非常にシンプルですね。関連型には <code>type</code> キーワードを使い、そしてトレイトの本体や関数で利用します。</p> <!-- These `type` declarations can have all the same thing as functions do. For example, --> <!-- if we wanted our `N` type to implement `Display`, so we can print the nodes out, --> <!-- we could do this: --> <p>これらの <code>type</code> 宣言は、関数で利用できるものと同じものが全て利用できます。 たとえば、 <code>N</code> 型が <code>Display</code> を実装していて欲しい時、つまり私達が頂点を出力したい時、以下のようにして指定することができます:</p> <span class='rusttest'>fn main() { use std::fmt; trait Graph { type N: fmt::Display; type E; fn has_edge(&amp;self, &amp;Self::N, &amp;Self::N) -&gt; bool; fn edges(&amp;self, &amp;Self::N) -&gt; Vec&lt;Self::E&gt;; } }</span><pre class='rust rust-example-rendered'> <span class='kw'>use</span> <span class='ident'>std</span>::<span class='ident'>fmt</span>; <span class='kw'>trait</span> <span class='ident'>Graph</span> { <span class='kw'>type</span> <span class='ident'>N</span>: <span class='ident'>fmt</span>::<span class='ident'>Display</span>; <span class='kw'>type</span> <span class='ident'>E</span>; <span class='kw'>fn</span> <span class='ident'>has_edge</span>(<span class='kw-2'>&amp;</span><span class='self'>self</span>, <span class='kw-2'>&amp;</span><span class='self'>Self</span>::<span class='ident'>N</span>, <span class='kw-2'>&amp;</span><span class='self'>Self</span>::<span class='ident'>N</span>) <span class='op'>-&gt;</span> <span class='ident'>bool</span>; <span class='kw'>fn</span> <span class='ident'>edges</span>(<span class='kw-2'>&amp;</span><span class='self'>self</span>, <span class='kw-2'>&amp;</span><span class='self'>Self</span>::<span class='ident'>N</span>) <span class='op'>-&gt;</span> <span class='ident'>Vec</span><span class='op'>&lt;</span><span class='self'>Self</span>::<span class='ident'>E</span><span class='op'>&gt;</span>; }</pre> <!-- ## Implementing associated types --> <h2 id='関連型を実装する' class='section-header'><a href='#関連型を実装する'>関連型を実装する</a></h2> <!-- Just like any trait, traits that use associated types use the `impl` keyword to --> <!-- provide implementations. Here’s a simple implementation of Graph: --> <p>通常のトレイトと同様に、関連型を使っているトレイトは実装するために <code>impl</code> を利用します。 以下は、シンプルなGraphの実装例です:</p> <span class='rusttest'>fn main() { trait Graph { type N; type E; fn has_edge(&amp;self, &amp;Self::N, &amp;Self::N) -&gt; bool; fn edges(&amp;self, &amp;Self::N) -&gt; Vec&lt;Self::E&gt;; } struct Node; struct Edge; struct MyGraph; impl Graph for MyGraph { type N = Node; type E = Edge; fn has_edge(&amp;self, n1: &amp;Node, n2: &amp;Node) -&gt; bool { true } fn edges(&amp;self, n: &amp;Node) -&gt; Vec&lt;Edge&gt; { Vec::new() } } }</span><pre class='rust rust-example-rendered'> <span class='kw'>struct</span> <span class='ident'>Node</span>; <span class='kw'>struct</span> <span class='ident'>Edge</span>; <span class='kw'>struct</span> <span class='ident'>MyGraph</span>; <span class='kw'>impl</span> <span class='ident'>Graph</span> <span class='kw'>for</span> <span class='ident'>MyGraph</span> { <span class='kw'>type</span> <span class='ident'>N</span> <span class='op'>=</span> <span class='ident'>Node</span>; <span class='kw'>type</span> <span class='ident'>E</span> <span class='op'>=</span> <span class='ident'>Edge</span>; <span class='kw'>fn</span> <span class='ident'>has_edge</span>(<span class='kw-2'>&amp;</span><span class='self'>self</span>, <span class='ident'>n1</span>: <span class='kw-2'>&amp;</span><span class='ident'>Node</span>, <span class='ident'>n2</span>: <span class='kw-2'>&amp;</span><span class='ident'>Node</span>) <span class='op'>-&gt;</span> <span class='ident'>bool</span> { <span class='boolvalue'>true</span> } <span class='kw'>fn</span> <span class='ident'>edges</span>(<span class='kw-2'>&amp;</span><span class='self'>self</span>, <span class='ident'>n</span>: <span class='kw-2'>&amp;</span><span class='ident'>Node</span>) <span class='op'>-&gt;</span> <span class='ident'>Vec</span><span class='op'>&lt;</span><span class='ident'>Edge</span><span class='op'>&gt;</span> { <span class='ident'>Vec</span>::<span class='ident'>new</span>() } }</pre> <!-- This silly implementation always returns `true` and an empty `Vec<Edge>`, but it --> <!-- gives you an idea of how to implement this kind of thing. We first need three --> <!-- `struct`s, one for the graph, one for the node, and one for the edge. If it made --> <!-- more sense to use a different type, that would work as well, we’re just going to --> <!-- use `struct`s for all three here. --> <p>この奇妙な実装は、つねに <code>true</code> と空の <code>Vec&lt;Edge&gt;</code> を返しますが、どのように定義したら良いかのアイデアをくれます。 まず、はじめに3つの <code>struct</code> が必要です、ひとつはグラフのため、そしてひとつは頂点のため、そしてもうひとつは辺のため。 もし異なる型を利用することが適切ならば、そのようにすると良いでしょう、今回はこの3つの <code>struct</code> を用います。</p> <!-- Next is the `impl` line, which is just like implementing any other trait. --> <p>次は <code>impl</code> の行です、これは他のトレイトを実装するときと同様です。</p> <!-- From here, we use `=` to define our associated types. The name the trait uses --> <!-- goes on the left of the `=`, and the concrete type we’re `impl`ementing this --> <!-- for goes on the right. Finally, we use the concrete types in our function --> <!-- declarations. --> <p>そして、<code>=</code> を関連型を定義するために利用します。 トレイトが利用する名前は <code>=</code> の左側にある名前で、実装に用いる具体的な型は右側にあるものになります。 最後に、具体的な型を関数の宣言に利用します。</p> <!-- ## Trait objects with associated types --> <h2 id='関連型を伴うトレイト' class='section-header'><a href='#関連型を伴うトレイト'>関連型を伴うトレイト</a></h2> <!-- There’s one more bit of syntax we should talk about: trait objects. If you --> <!-- try to create a trait object from an associated type, like this: --> <p>すこし触れておきたい構文: トレイトオブジェクト が有ります。 もし、トレイトオブジェクトを以下のように関連型から作成しようとした場合:</p> <span class='rusttest'>fn main() { trait Graph { type N; type E; fn has_edge(&amp;self, &amp;Self::N, &amp;Self::N) -&gt; bool; fn edges(&amp;self, &amp;Self::N) -&gt; Vec&lt;Self::E&gt;; } struct Node; struct Edge; struct MyGraph; impl Graph for MyGraph { type N = Node; type E = Edge; fn has_edge(&amp;self, n1: &amp;Node, n2: &amp;Node) -&gt; bool { true } fn edges(&amp;self, n: &amp;Node) -&gt; Vec&lt;Edge&gt; { Vec::new() } } let graph = MyGraph; let obj = Box::new(graph) as Box&lt;Graph&gt;; }</span><pre class='rust rust-example-rendered'> <span class='kw'>let</span> <span class='ident'>graph</span> <span class='op'>=</span> <span class='ident'>MyGraph</span>; <span class='kw'>let</span> <span class='ident'>obj</span> <span class='op'>=</span> <span class='ident'>Box</span>::<span class='ident'>new</span>(<span class='ident'>graph</span>) <span class='kw'>as</span> <span class='ident'>Box</span><span class='op'>&lt;</span><span class='ident'>Graph</span><span class='op'>&gt;</span>;</pre> <!-- You’ll get two errors: --> <p>以下の様なエラーが発生します:</p> <pre><code class="language-text">error: the value of the associated type `E` (from the trait `main::Graph`) must be specified [E0191] let obj = Box::new(graph) as Box&lt;Graph&gt;; ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 24:44 error: the value of the associated type `N` (from the trait `main::Graph`) must be specified [E0191] let obj = Box::new(graph) as Box&lt;Graph&gt;; ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </code></pre> <!-- We can’t create a trait object like this, because we don’t know the associated --> <!-- types. Instead, we can write this: --> <p>上のようにしてトレイトオブジェクトを作ることはできません、なぜなら関連型について知らないからです 代わりに以下のように書くことができます:</p> <span class='rusttest'>fn main() { trait Graph { type N; type E; fn has_edge(&amp;self, &amp;Self::N, &amp;Self::N) -&gt; bool; fn edges(&amp;self, &amp;Self::N) -&gt; Vec&lt;Self::E&gt;; } struct Node; struct Edge; struct MyGraph; impl Graph for MyGraph { type N = Node; type E = Edge; fn has_edge(&amp;self, n1: &amp;Node, n2: &amp;Node) -&gt; bool { true } fn edges(&amp;self, n: &amp;Node) -&gt; Vec&lt;Edge&gt; { Vec::new() } } let graph = MyGraph; let obj = Box::new(graph) as Box&lt;Graph&lt;N=Node, E=Edge&gt;&gt;; }</span><pre class='rust rust-example-rendered'> <span class='kw'>let</span> <span class='ident'>graph</span> <span class='op'>=</span> <span class='ident'>MyGraph</span>; <span class='kw'>let</span> <span class='ident'>obj</span> <span class='op'>=</span> <span class='ident'>Box</span>::<span class='ident'>new</span>(<span class='ident'>graph</span>) <span class='kw'>as</span> <span class='ident'>Box</span><span class='op'>&lt;</span><span class='ident'>Graph</span><span class='op'>&lt;</span><span class='ident'>N</span><span class='op'>=</span><span class='ident'>Node</span>, <span class='ident'>E</span><span class='op'>=</span><span class='ident'>Edge</span><span class='op'>&gt;&gt;</span>;</pre> <!-- The `N=Node` syntax allows us to provide a concrete type, `Node`, for the `N` --> <!-- type parameter. Same with `E=Edge`. If we didn’t provide this constraint, we --> <!-- couldn’t be sure which `impl` to match this trait object to. --> <p><code>N=Node</code> 構文を用いて型パラメータ <code>N</code> にたいして具体的な型 <code>Node</code> を指定することができます、<code>E=Edge</code> についても同様です。 もしこの制約を指定しなかった場合、このトレイトオブジェクトに対してどの <code>impl</code> がマッチするのか定まりません。</p> <script type="text/javascript"> window.playgroundUrl = "https://play.rust-lang.org"; </script> <script src='rustbook.js'></script> <script src='playpen.js'></script> </div></div> </body> </html> <|start_filename|>docs/1.9/nomicon/leaking.html<|end_filename|> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="generator" content="rustdoc"> <title>Leaking</title> <link rel="stylesheet" type="text/css" href="rustbook.css"> <meta name="robots" content="noindex"> </head> <body class="rustdoc"> <!--[if lte IE 8]> <div class="warning"> This old browser is unsupported and will most likely display funky things. </div> <![endif]--> <div id="nav"> <button id="toggle-nav"> <span class="sr-only">Toggle navigation</span> <span class="bar"></span> <span class="bar"></span> <span class="bar"></span> </button> </div> <div id='toc' class='mobile-hidden'> <ul class='chapter'> <li><a href='README.html'><b>1.</b> Introduction</a> </li> <li><a href='meet-safe-and-unsafe.html'><b>2.</b> Meet Safe and Unsafe</a> <ul class='section'> <li><a href='safe-unsafe-meaning.html'><b>2.1.</b> How Safe and Unsafe Interact</a> </li> <li><a href='working-with-unsafe.html'><b>2.2.</b> Working with Unsafe</a> </li> </ul> </li> <li><a href='data.html'><b>3.</b> Data Layout</a> <ul class='section'> <li><a href='repr-rust.html'><b>3.1.</b> repr(Rust)</a> </li> <li><a href='exotic-sizes.html'><b>3.2.</b> Exotically Sized Types</a> </li> <li><a href='other-reprs.html'><b>3.3.</b> Other reprs</a> </li> </ul> </li> <li><a href='ownership.html'><b>4.</b> Ownership</a> <ul class='section'> <li><a href='references.html'><b>4.1.</b> References</a> </li> <li><a href='lifetimes.html'><b>4.2.</b> Lifetimes</a> </li> <li><a href='lifetime-mismatch.html'><b>4.3.</b> Limits of Lifetimes</a> </li> <li><a href='lifetime-elision.html'><b>4.4.</b> Lifetime Elision</a> </li> <li><a href='unbounded-lifetimes.html'><b>4.5.</b> Unbounded Lifetimes</a> </li> <li><a href='hrtb.html'><b>4.6.</b> Higher-Rank Trait Bounds</a> </li> <li><a href='subtyping.html'><b>4.7.</b> Subtyping and Variance</a> </li> <li><a href='dropck.html'><b>4.8.</b> Drop Check</a> </li> <li><a href='phantom-data.html'><b>4.9.</b> PhantomData</a> </li> <li><a href='borrow-splitting.html'><b>4.10.</b> Splitting Borrows</a> </li> </ul> </li> <li><a href='conversions.html'><b>5.</b> Type Conversions</a> <ul class='section'> <li><a href='coercions.html'><b>5.1.</b> Coercions</a> </li> <li><a href='dot-operator.html'><b>5.2.</b> The Dot Operator</a> </li> <li><a href='casts.html'><b>5.3.</b> Casts</a> </li> <li><a href='transmutes.html'><b>5.4.</b> Transmutes</a> </li> </ul> </li> <li><a href='uninitialized.html'><b>6.</b> Uninitialized Memory</a> <ul class='section'> <li><a href='checked-uninit.html'><b>6.1.</b> Checked</a> </li> <li><a href='drop-flags.html'><b>6.2.</b> Drop Flags</a> </li> <li><a href='unchecked-uninit.html'><b>6.3.</b> Unchecked</a> </li> </ul> </li> <li><a href='obrm.html'><b>7.</b> Ownership Based Resource Management</a> <ul class='section'> <li><a href='constructors.html'><b>7.1.</b> Constructors</a> </li> <li><a href='destructors.html'><b>7.2.</b> Destructors</a> </li> <li><a class='active' href='leaking.html'><b>7.3.</b> Leaking</a> </li> </ul> </li> <li><a href='unwinding.html'><b>8.</b> Unwinding</a> <ul class='section'> <li><a href='exception-safety.html'><b>8.1.</b> Exception Safety</a> </li> <li><a href='poisoning.html'><b>8.2.</b> Poisoning</a> </li> </ul> </li> <li><a href='concurrency.html'><b>9.</b> Concurrency</a> <ul class='section'> <li><a href='races.html'><b>9.1.</b> Races</a> </li> <li><a href='send-and-sync.html'><b>9.2.</b> Send and Sync</a> </li> <li><a href='atomics.html'><b>9.3.</b> Atomics</a> </li> </ul> </li> <li><a href='vec.html'><b>10.</b> Implementing Vec</a> <ul class='section'> <li><a href='vec-layout.html'><b>10.1.</b> Layout</a> </li> <li><a href='vec-alloc.html'><b>10.2.</b> Allocating</a> </li> <li><a href='vec-push-pop.html'><b>10.3.</b> Push and Pop</a> </li> <li><a href='vec-dealloc.html'><b>10.4.</b> Deallocating</a> </li> <li><a href='vec-deref.html'><b>10.5.</b> Deref</a> </li> <li><a href='vec-insert-remove.html'><b>10.6.</b> Insert and Remove</a> </li> <li><a href='vec-into-iter.html'><b>10.7.</b> IntoIter</a> </li> <li><a href='vec-raw.html'><b>10.8.</b> RawVec</a> </li> <li><a href='vec-drain.html'><b>10.9.</b> Drain</a> </li> <li><a href='vec-zsts.html'><b>10.10.</b> Handling Zero-Sized Types</a> </li> <li><a href='vec-final.html'><b>10.11.</b> Final Code</a> </li> </ul> </li> <li><a href='arc-and-mutex.html'><b>11.</b> Implementing Arc and Mutex</a> </li> </ul> </div> <div id='page-wrapper'> <div id='page'> <blockquote class="header-caveat"> <p> <strong>注意: <a href="https://doc.rust-jp.rs/book-ja/">最新版のドキュメントをご覧ください。</a></strong>この第1版ドキュメントは古くなっており、最新情報が反映されていません。リンク先のドキュメントが現在の Rust の最新のドキュメントです。 </p> </blockquote> <h1 class="title">Leaking</h1> <p>Ownership-based resource management is intended to simplify composition. You acquire resources when you create the object, and you release the resources when it gets destroyed. Since destruction is handled for you, it means you can&#39;t forget to release the resources, and it happens as soon as possible! Surely this is perfect and all of our problems are solved.</p> <p>Everything is terrible and we have new and exotic problems to try to solve.</p> <p>Many people like to believe that Rust eliminates resource leaks. In practice, this is basically true. You would be surprised to see a Safe Rust program leak resources in an uncontrolled way.</p> <p>However from a theoretical perspective this is absolutely not the case, no matter how you look at it. In the strictest sense, &quot;leaking&quot; is so abstract as to be unpreventable. It&#39;s quite trivial to initialize a collection at the start of a program, fill it with tons of objects with destructors, and then enter an infinite event loop that never refers to it. The collection will sit around uselessly, holding on to its precious resources until the program terminates (at which point all those resources would have been reclaimed by the OS anyway).</p> <p>We may consider a more restricted form of leak: failing to drop a value that is unreachable. Rust also doesn&#39;t prevent this. In fact Rust <em>has a function for doing this</em>: <code>mem::forget</code>. This function consumes the value it is passed <em>and then doesn&#39;t run its destructor</em>.</p> <p>In the past <code>mem::forget</code> was marked as unsafe as a sort of lint against using it, since failing to call a destructor is generally not a well-behaved thing to do (though useful for some special unsafe code). However this was generally determined to be an untenable stance to take: there are many ways to fail to call a destructor in safe code. The most famous example is creating a cycle of reference-counted pointers using interior mutability.</p> <p>It is reasonable for safe code to assume that destructor leaks do not happen, as any program that leaks destructors is probably wrong. However <em>unsafe</em> code cannot rely on destructors to be run in order to be safe. For most types this doesn&#39;t matter: if you leak the destructor then the type is by definition inaccessible, so it doesn&#39;t matter, right? For instance, if you leak a <code>Box&lt;u8&gt;</code> then you waste some memory but that&#39;s hardly going to violate memory-safety.</p> <p>However where we must be careful with destructor leaks are <em>proxy</em> types. These are types which manage access to a distinct object, but don&#39;t actually own it. Proxy objects are quite rare. Proxy objects you&#39;ll need to care about are even rarer. However we&#39;ll focus on three interesting examples in the standard library:</p> <ul> <li><code>vec::Drain</code></li> <li><code>Rc</code></li> <li><code>thread::scoped::JoinGuard</code></li> </ul> <h2 id='drain' class='section-header'><a href='#drain'>Drain</a></h2> <p><code>drain</code> is a collections API that moves data out of the container without consuming the container. This enables us to reuse the allocation of a <code>Vec</code> after claiming ownership over all of its contents. It produces an iterator (Drain) that returns the contents of the Vec by-value.</p> <p>Now, consider Drain in the middle of iteration: some values have been moved out, and others haven&#39;t. This means that part of the Vec is now full of logically uninitialized data! We could backshift all the elements in the Vec every time we remove a value, but this would have pretty catastrophic performance consequences.</p> <p>Instead, we would like Drain to fix the Vec&#39;s backing storage when it is dropped. It should run itself to completion, backshift any elements that weren&#39;t removed (drain supports subranges), and then fix Vec&#39;s <code>len</code>. It&#39;s even unwinding-safe! Easy!</p> <p>Now consider the following:</p> <span class='rusttest'>fn main() { let mut vec = vec![Box::new(0); 4]; { // start draining, vec can no longer be accessed let mut drainer = vec.drain(..); // pull out two elements and immediately drop them drainer.next(); drainer.next(); // get rid of drainer, but don&#39;t call its destructor mem::forget(drainer); } // Oops, vec[0] was dropped, we&#39;re reading a pointer into free&#39;d memory! println!(&quot;{}&quot;, vec[0]); }</span><pre class='rust rust-example-rendered'> <span class='kw'>let</span> <span class='kw-2'>mut</span> <span class='ident'>vec</span> <span class='op'>=</span> <span class='macro'>vec</span><span class='macro'>!</span>[<span class='ident'>Box</span>::<span class='ident'>new</span>(<span class='number'>0</span>); <span class='number'>4</span>]; { <span class='comment'>// start draining, vec can no longer be accessed</span> <span class='kw'>let</span> <span class='kw-2'>mut</span> <span class='ident'>drainer</span> <span class='op'>=</span> <span class='ident'>vec</span>.<span class='ident'>drain</span>(..); <span class='comment'>// pull out two elements and immediately drop them</span> <span class='ident'>drainer</span>.<span class='ident'>next</span>(); <span class='ident'>drainer</span>.<span class='ident'>next</span>(); <span class='comment'>// get rid of drainer, but don&#39;t call its destructor</span> <span class='ident'>mem</span>::<span class='ident'>forget</span>(<span class='ident'>drainer</span>); } <span class='comment'>// Oops, vec[0] was dropped, we&#39;re reading a pointer into free&#39;d memory!</span> <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;{}&quot;</span>, <span class='ident'>vec</span>[<span class='number'>0</span>]);</pre> <p>This is pretty clearly Not Good. Unfortunately, we&#39;re kind of stuck between a rock and a hard place: maintaining consistent state at every step has an enormous cost (and would negate any benefits of the API). Failing to maintain consistent state gives us Undefined Behavior in safe code (making the API unsound).</p> <p>So what can we do? Well, we can pick a trivially consistent state: set the Vec&#39;s len to be 0 when we start the iteration, and fix it up if necessary in the destructor. That way, if everything executes like normal we get the desired behavior with minimal overhead. But if someone has the <em>audacity</em> to mem::forget us in the middle of the iteration, all that does is <em>leak even more</em> (and possibly leave the Vec in an unexpected but otherwise consistent state). Since we&#39;ve accepted that mem::forget is safe, this is definitely safe. We call leaks causing more leaks a <em>leak amplification</em>.</p> <h2 id='rc' class='section-header'><a href='#rc'>Rc</a></h2> <p>Rc is an interesting case because at first glance it doesn&#39;t appear to be a proxy value at all. After all, it manages the data it points to, and dropping all the Rcs for a value will drop that value. Leaking an Rc doesn&#39;t seem like it would be particularly dangerous. It will leave the refcount permanently incremented and prevent the data from being freed or dropped, but that seems just like Box, right?</p> <p>Nope.</p> <p>Let&#39;s consider a simplified implementation of Rc:</p> <span class='rusttest'>fn main() { struct Rc&lt;T&gt; { ptr: *mut RcBox&lt;T&gt;, } struct RcBox&lt;T&gt; { data: T, ref_count: usize, } impl&lt;T&gt; Rc&lt;T&gt; { fn new(data: T) -&gt; Self { unsafe { // Wouldn&#39;t it be nice if heap::allocate worked like this? let ptr = heap::allocate::&lt;RcBox&lt;T&gt;&gt;(); ptr::write(ptr, RcBox { data: data, ref_count: 1, }); Rc { ptr: ptr } } } fn clone(&amp;self) -&gt; Self { unsafe { (*self.ptr).ref_count += 1; } Rc { ptr: self.ptr } } } impl&lt;T&gt; Drop for Rc&lt;T&gt; { fn drop(&amp;mut self) { unsafe { (*self.ptr).ref_count -= 1; if (*self.ptr).ref_count == 0 { // drop the data and then free it ptr::read(self.ptr); heap::deallocate(self.ptr); } } } } }</span><pre class='rust rust-example-rendered'> <span class='kw'>struct</span> <span class='ident'>Rc</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> { <span class='ident'>ptr</span>: <span class='op'>*</span><span class='kw-2'>mut</span> <span class='ident'>RcBox</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span>, } <span class='kw'>struct</span> <span class='ident'>RcBox</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> { <span class='ident'>data</span>: <span class='ident'>T</span>, <span class='ident'>ref_count</span>: <span class='ident'>usize</span>, } <span class='kw'>impl</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> <span class='ident'>Rc</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> { <span class='kw'>fn</span> <span class='ident'>new</span>(<span class='ident'>data</span>: <span class='ident'>T</span>) <span class='op'>-&gt;</span> <span class='self'>Self</span> { <span class='kw'>unsafe</span> { <span class='comment'>// Wouldn&#39;t it be nice if heap::allocate worked like this?</span> <span class='kw'>let</span> <span class='ident'>ptr</span> <span class='op'>=</span> <span class='ident'>heap</span>::<span class='ident'>allocate</span>::<span class='op'>&lt;</span><span class='ident'>RcBox</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;&gt;</span>(); <span class='ident'>ptr</span>::<span class='ident'>write</span>(<span class='ident'>ptr</span>, <span class='ident'>RcBox</span> { <span class='ident'>data</span>: <span class='ident'>data</span>, <span class='ident'>ref_count</span>: <span class='number'>1</span>, }); <span class='ident'>Rc</span> { <span class='ident'>ptr</span>: <span class='ident'>ptr</span> } } } <span class='kw'>fn</span> <span class='ident'>clone</span>(<span class='kw-2'>&amp;</span><span class='self'>self</span>) <span class='op'>-&gt;</span> <span class='self'>Self</span> { <span class='kw'>unsafe</span> { (<span class='op'>*</span><span class='self'>self</span>.<span class='ident'>ptr</span>).<span class='ident'>ref_count</span> <span class='op'>+=</span> <span class='number'>1</span>; } <span class='ident'>Rc</span> { <span class='ident'>ptr</span>: <span class='self'>self</span>.<span class='ident'>ptr</span> } } } <span class='kw'>impl</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> <span class='ident'>Drop</span> <span class='kw'>for</span> <span class='ident'>Rc</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> { <span class='kw'>fn</span> <span class='ident'>drop</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>) { <span class='kw'>unsafe</span> { (<span class='op'>*</span><span class='self'>self</span>.<span class='ident'>ptr</span>).<span class='ident'>ref_count</span> <span class='op'>-=</span> <span class='number'>1</span>; <span class='kw'>if</span> (<span class='op'>*</span><span class='self'>self</span>.<span class='ident'>ptr</span>).<span class='ident'>ref_count</span> <span class='op'>==</span> <span class='number'>0</span> { <span class='comment'>// drop the data and then free it</span> <span class='ident'>ptr</span>::<span class='ident'>read</span>(<span class='self'>self</span>.<span class='ident'>ptr</span>); <span class='ident'>heap</span>::<span class='ident'>deallocate</span>(<span class='self'>self</span>.<span class='ident'>ptr</span>); } } } }</pre> <p>This code contains an implicit and subtle assumption: <code>ref_count</code> can fit in a <code>usize</code>, because there can&#39;t be more than <code>usize::MAX</code> Rcs in memory. However this itself assumes that the <code>ref_count</code> accurately reflects the number of Rcs in memory, which we know is false with <code>mem::forget</code>. Using <code>mem::forget</code> we can overflow the <code>ref_count</code>, and then get it down to 0 with outstanding Rcs. Then we can happily use-after-free the inner data. Bad Bad Not Good.</p> <p>This can be solved by just checking the <code>ref_count</code> and doing <em>something</em>. The standard library&#39;s stance is to just abort, because your program has become horribly degenerate. Also <em>oh my gosh</em> it&#39;s such a ridiculous corner case.</p> <h2 id='threadscopedjoinguard' class='section-header'><a href='#threadscopedjoinguard'>thread::scoped::JoinGuard</a></h2> <p>The thread::scoped API intends to allow threads to be spawned that reference data on their parent&#39;s stack without any synchronization over that data by ensuring the parent joins the thread before any of the shared data goes out of scope.</p> <span class='rusttest'>fn main() { pub fn scoped&lt;&#39;a, F&gt;(f: F) -&gt; JoinGuard&lt;&#39;a&gt; where F: FnOnce() + Send + &#39;a }</span><pre class='rust rust-example-rendered'> <span class='kw'>pub</span> <span class='kw'>fn</span> <span class='ident'>scoped</span><span class='op'>&lt;</span><span class='lifetime'>&#39;a</span>, <span class='ident'>F</span><span class='op'>&gt;</span>(<span class='ident'>f</span>: <span class='ident'>F</span>) <span class='op'>-&gt;</span> <span class='ident'>JoinGuard</span><span class='op'>&lt;</span><span class='lifetime'>&#39;a</span><span class='op'>&gt;</span> <span class='kw'>where</span> <span class='ident'>F</span>: <span class='ident'>FnOnce</span>() <span class='op'>+</span> <span class='ident'>Send</span> <span class='op'>+</span> <span class='lifetime'>&#39;a</span></pre> <p>Here <code>f</code> is some closure for the other thread to execute. Saying that <code>F: Send +&#39;a</code> is saying that it closes over data that lives for <code>&#39;a</code>, and it either owns that data or the data was Sync (implying <code>&amp;data</code> is Send).</p> <p>Because JoinGuard has a lifetime, it keeps all the data it closes over borrowed in the parent thread. This means the JoinGuard can&#39;t outlive the data that the other thread is working on. When the JoinGuard <em>does</em> get dropped it blocks the parent thread, ensuring the child terminates before any of the closed-over data goes out of scope in the parent.</p> <p>Usage looked like:</p> <span class='rusttest'>fn main() { let mut data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; { let guards = vec![]; for x in &amp;mut data { // Move the mutable reference into the closure, and execute // it on a different thread. The closure has a lifetime bound // by the lifetime of the mutable reference `x` we store in it. // The guard that is returned is in turn assigned the lifetime // of the closure, so it also mutably borrows `data` as `x` did. // This means we cannot access `data` until the guard goes away. let guard = thread::scoped(move || { *x *= 2; }); // store the thread&#39;s guard for later guards.push(guard); } // All guards are dropped here, forcing the threads to join // (this thread blocks here until the others terminate). // Once the threads join, the borrow expires and the data becomes // accessible again in this thread. } // data is definitely mutated here. }</span><pre class='rust rust-example-rendered'> <span class='kw'>let</span> <span class='kw-2'>mut</span> <span class='ident'>data</span> <span class='op'>=</span> [<span class='number'>1</span>, <span class='number'>2</span>, <span class='number'>3</span>, <span class='number'>4</span>, <span class='number'>5</span>, <span class='number'>6</span>, <span class='number'>7</span>, <span class='number'>8</span>, <span class='number'>9</span>, <span class='number'>10</span>]; { <span class='kw'>let</span> <span class='ident'>guards</span> <span class='op'>=</span> <span class='macro'>vec</span><span class='macro'>!</span>[]; <span class='kw'>for</span> <span class='ident'>x</span> <span class='kw'>in</span> <span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='ident'>data</span> { <span class='comment'>// Move the mutable reference into the closure, and execute</span> <span class='comment'>// it on a different thread. The closure has a lifetime bound</span> <span class='comment'>// by the lifetime of the mutable reference `x` we store in it.</span> <span class='comment'>// The guard that is returned is in turn assigned the lifetime</span> <span class='comment'>// of the closure, so it also mutably borrows `data` as `x` did.</span> <span class='comment'>// This means we cannot access `data` until the guard goes away.</span> <span class='kw'>let</span> <span class='ident'>guard</span> <span class='op'>=</span> <span class='ident'>thread</span>::<span class='ident'>scoped</span>(<span class='kw'>move</span> <span class='op'>||</span> { <span class='op'>*</span><span class='ident'>x</span> <span class='op'>*=</span> <span class='number'>2</span>; }); <span class='comment'>// store the thread&#39;s guard for later</span> <span class='ident'>guards</span>.<span class='ident'>push</span>(<span class='ident'>guard</span>); } <span class='comment'>// All guards are dropped here, forcing the threads to join</span> <span class='comment'>// (this thread blocks here until the others terminate).</span> <span class='comment'>// Once the threads join, the borrow expires and the data becomes</span> <span class='comment'>// accessible again in this thread.</span> } <span class='comment'>// data is definitely mutated here.</span></pre> <p>In principle, this totally works! Rust&#39;s ownership system perfectly ensures it! ...except it relies on a destructor being called to be safe.</p> <span class='rusttest'>fn main() { let mut data = Box::new(0); { let guard = thread::scoped(|| { // This is at best a data race. At worst, it&#39;s also a use-after-free. *data += 1; }); // Because the guard is forgotten, expiring the loan without blocking this // thread. mem::forget(guard); } // So the Box is dropped here while the scoped thread may or may not be trying // to access it. }</span><pre class='rust rust-example-rendered'> <span class='kw'>let</span> <span class='kw-2'>mut</span> <span class='ident'>data</span> <span class='op'>=</span> <span class='ident'>Box</span>::<span class='ident'>new</span>(<span class='number'>0</span>); { <span class='kw'>let</span> <span class='ident'>guard</span> <span class='op'>=</span> <span class='ident'>thread</span>::<span class='ident'>scoped</span>(<span class='op'>||</span> { <span class='comment'>// This is at best a data race. At worst, it&#39;s also a use-after-free.</span> <span class='op'>*</span><span class='ident'>data</span> <span class='op'>+=</span> <span class='number'>1</span>; }); <span class='comment'>// Because the guard is forgotten, expiring the loan without blocking this</span> <span class='comment'>// thread.</span> <span class='ident'>mem</span>::<span class='ident'>forget</span>(<span class='ident'>guard</span>); } <span class='comment'>// So the Box is dropped here while the scoped thread may or may not be trying</span> <span class='comment'>// to access it.</span></pre> <p>Dang. Here the destructor running was pretty fundamental to the API, and it had to be scrapped in favor of a completely different design.</p> <script type="text/javascript"> window.playgroundUrl = "https://play.rust-lang.org"; </script> <script src='rustbook.js'></script> <script src='playpen.js'></script> </div></div> </body> </html> <|start_filename|>docs/1.9/nomicon/vec-layout.html<|end_filename|> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="generator" content="rustdoc"> <title>Layout</title> <link rel="stylesheet" type="text/css" href="rustbook.css"> <meta name="robots" content="noindex"> </head> <body class="rustdoc"> <!--[if lte IE 8]> <div class="warning"> This old browser is unsupported and will most likely display funky things. </div> <![endif]--> <div id="nav"> <button id="toggle-nav"> <span class="sr-only">Toggle navigation</span> <span class="bar"></span> <span class="bar"></span> <span class="bar"></span> </button> </div> <div id='toc' class='mobile-hidden'> <ul class='chapter'> <li><a href='README.html'><b>1.</b> Introduction</a> </li> <li><a href='meet-safe-and-unsafe.html'><b>2.</b> Meet Safe and Unsafe</a> <ul class='section'> <li><a href='safe-unsafe-meaning.html'><b>2.1.</b> How Safe and Unsafe Interact</a> </li> <li><a href='working-with-unsafe.html'><b>2.2.</b> Working with Unsafe</a> </li> </ul> </li> <li><a href='data.html'><b>3.</b> Data Layout</a> <ul class='section'> <li><a href='repr-rust.html'><b>3.1.</b> repr(Rust)</a> </li> <li><a href='exotic-sizes.html'><b>3.2.</b> Exotically Sized Types</a> </li> <li><a href='other-reprs.html'><b>3.3.</b> Other reprs</a> </li> </ul> </li> <li><a href='ownership.html'><b>4.</b> Ownership</a> <ul class='section'> <li><a href='references.html'><b>4.1.</b> References</a> </li> <li><a href='lifetimes.html'><b>4.2.</b> Lifetimes</a> </li> <li><a href='lifetime-mismatch.html'><b>4.3.</b> Limits of Lifetimes</a> </li> <li><a href='lifetime-elision.html'><b>4.4.</b> Lifetime Elision</a> </li> <li><a href='unbounded-lifetimes.html'><b>4.5.</b> Unbounded Lifetimes</a> </li> <li><a href='hrtb.html'><b>4.6.</b> Higher-Rank Trait Bounds</a> </li> <li><a href='subtyping.html'><b>4.7.</b> Subtyping and Variance</a> </li> <li><a href='dropck.html'><b>4.8.</b> Drop Check</a> </li> <li><a href='phantom-data.html'><b>4.9.</b> PhantomData</a> </li> <li><a href='borrow-splitting.html'><b>4.10.</b> Splitting Borrows</a> </li> </ul> </li> <li><a href='conversions.html'><b>5.</b> Type Conversions</a> <ul class='section'> <li><a href='coercions.html'><b>5.1.</b> Coercions</a> </li> <li><a href='dot-operator.html'><b>5.2.</b> The Dot Operator</a> </li> <li><a href='casts.html'><b>5.3.</b> Casts</a> </li> <li><a href='transmutes.html'><b>5.4.</b> Transmutes</a> </li> </ul> </li> <li><a href='uninitialized.html'><b>6.</b> Uninitialized Memory</a> <ul class='section'> <li><a href='checked-uninit.html'><b>6.1.</b> Checked</a> </li> <li><a href='drop-flags.html'><b>6.2.</b> Drop Flags</a> </li> <li><a href='unchecked-uninit.html'><b>6.3.</b> Unchecked</a> </li> </ul> </li> <li><a href='obrm.html'><b>7.</b> Ownership Based Resource Management</a> <ul class='section'> <li><a href='constructors.html'><b>7.1.</b> Constructors</a> </li> <li><a href='destructors.html'><b>7.2.</b> Destructors</a> </li> <li><a href='leaking.html'><b>7.3.</b> Leaking</a> </li> </ul> </li> <li><a href='unwinding.html'><b>8.</b> Unwinding</a> <ul class='section'> <li><a href='exception-safety.html'><b>8.1.</b> Exception Safety</a> </li> <li><a href='poisoning.html'><b>8.2.</b> Poisoning</a> </li> </ul> </li> <li><a href='concurrency.html'><b>9.</b> Concurrency</a> <ul class='section'> <li><a href='races.html'><b>9.1.</b> Races</a> </li> <li><a href='send-and-sync.html'><b>9.2.</b> Send and Sync</a> </li> <li><a href='atomics.html'><b>9.3.</b> Atomics</a> </li> </ul> </li> <li><a href='vec.html'><b>10.</b> Implementing Vec</a> <ul class='section'> <li><a class='active' href='vec-layout.html'><b>10.1.</b> Layout</a> </li> <li><a href='vec-alloc.html'><b>10.2.</b> Allocating</a> </li> <li><a href='vec-push-pop.html'><b>10.3.</b> Push and Pop</a> </li> <li><a href='vec-dealloc.html'><b>10.4.</b> Deallocating</a> </li> <li><a href='vec-deref.html'><b>10.5.</b> Deref</a> </li> <li><a href='vec-insert-remove.html'><b>10.6.</b> Insert and Remove</a> </li> <li><a href='vec-into-iter.html'><b>10.7.</b> IntoIter</a> </li> <li><a href='vec-raw.html'><b>10.8.</b> RawVec</a> </li> <li><a href='vec-drain.html'><b>10.9.</b> Drain</a> </li> <li><a href='vec-zsts.html'><b>10.10.</b> Handling Zero-Sized Types</a> </li> <li><a href='vec-final.html'><b>10.11.</b> Final Code</a> </li> </ul> </li> <li><a href='arc-and-mutex.html'><b>11.</b> Implementing Arc and Mutex</a> </li> </ul> </div> <div id='page-wrapper'> <div id='page'> <blockquote class="header-caveat"> <p> <strong>注意: <a href="https://doc.rust-jp.rs/book-ja/">最新版のドキュメントをご覧ください。</a></strong>この第1版ドキュメントは古くなっており、最新情報が反映されていません。リンク先のドキュメントが現在の Rust の最新のドキュメントです。 </p> </blockquote> <h1 class="title">Layout</h1> <p>First off, we need to come up with the struct layout. A Vec has three parts: a pointer to the allocation, the size of the allocation, and the number of elements that have been initialized.</p> <p>Naively, this means we just want this design:</p> <span class='rusttest'>pub struct Vec&lt;T&gt; { ptr: *mut T, cap: usize, len: usize, } fn main() {} </span><pre class='rust rust-example-rendered'> <span class='kw'>pub</span> <span class='kw'>struct</span> <span class='ident'>Vec</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> { <span class='ident'>ptr</span>: <span class='op'>*</span><span class='kw-2'>mut</span> <span class='ident'>T</span>, <span class='ident'>cap</span>: <span class='ident'>usize</span>, <span class='ident'>len</span>: <span class='ident'>usize</span>, }</pre> <p>And indeed this would compile. Unfortunately, it would be incorrect. First, the compiler will give us too strict variance. So a <code>&amp;Vec&lt;&amp;&#39;static str&gt;</code> couldn&#39;t be used where an <code>&amp;Vec&lt;&amp;&#39;a str&gt;</code> was expected. More importantly, it will give incorrect ownership information to the drop checker, as it will conservatively assume we don&#39;t own any values of type <code>T</code>. See <a href="ownership.html">the chapter on ownership and lifetimes</a> for all the details on variance and drop check.</p> <p>As we saw in the ownership chapter, we should use <code>Unique&lt;T&gt;</code> in place of <code>*mut T</code> when we have a raw pointer to an allocation we own. Unique is unstable, so we&#39;d like to not use it if possible, though.</p> <p>As a recap, Unique is a wrapper around a raw pointer that declares that:</p> <ul> <li>We are variant over <code>T</code></li> <li>We may own a value of type <code>T</code> (for drop check)</li> <li>We are Send/Sync if <code>T</code> is Send/Sync</li> <li>We deref to <code>*mut T</code> (so it largely acts like a <code>*mut</code> in our code)</li> <li>Our pointer is never null (so <code>Option&lt;Vec&lt;T&gt;&gt;</code> is null-pointer-optimized)</li> </ul> <p>We can implement all of the above requirements except for the last one in stable Rust:</p> <span class='rusttest'>use std::marker::PhantomData; use std::ops::Deref; use std::mem; struct Unique&lt;T&gt; { ptr: *const T, // *const for variance _marker: PhantomData&lt;T&gt;, // For the drop checker } // Deriving Send and Sync is safe because we are the Unique owners // of this data. It&#39;s like Unique&lt;T&gt; is &quot;just&quot; T. unsafe impl&lt;T: Send&gt; Send for Unique&lt;T&gt; {} unsafe impl&lt;T: Sync&gt; Sync for Unique&lt;T&gt; {} impl&lt;T&gt; Unique&lt;T&gt; { pub fn new(ptr: *mut T) -&gt; Self { Unique { ptr: ptr, _marker: PhantomData } } } impl&lt;T&gt; Deref for Unique&lt;T&gt; { type Target = *mut T; fn deref(&amp;self) -&gt; &amp;*mut T { // There&#39;s no way to cast the *const to a *mut // while also taking a reference. So we just // transmute it since it&#39;s all &quot;just pointers&quot;. unsafe { mem::transmute(&amp;self.ptr) } } } fn main() {} </span><pre class='rust rust-example-rendered'> <span class='kw'>use</span> <span class='ident'>std</span>::<span class='ident'>marker</span>::<span class='ident'>PhantomData</span>; <span class='kw'>use</span> <span class='ident'>std</span>::<span class='ident'>ops</span>::<span class='ident'>Deref</span>; <span class='kw'>use</span> <span class='ident'>std</span>::<span class='ident'>mem</span>; <span class='kw'>struct</span> <span class='ident'>Unique</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> { <span class='ident'>ptr</span>: <span class='op'>*</span><span class='kw'>const</span> <span class='ident'>T</span>, <span class='comment'>// *const for variance</span> <span class='ident'>_marker</span>: <span class='ident'>PhantomData</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span>, <span class='comment'>// For the drop checker</span> } <span class='comment'>// Deriving Send and Sync is safe because we are the Unique owners</span> <span class='comment'>// of this data. It&#39;s like Unique&lt;T&gt; is &quot;just&quot; T.</span> <span class='kw'>unsafe</span> <span class='kw'>impl</span><span class='op'>&lt;</span><span class='ident'>T</span>: <span class='ident'>Send</span><span class='op'>&gt;</span> <span class='ident'>Send</span> <span class='kw'>for</span> <span class='ident'>Unique</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> {} <span class='kw'>unsafe</span> <span class='kw'>impl</span><span class='op'>&lt;</span><span class='ident'>T</span>: <span class='ident'>Sync</span><span class='op'>&gt;</span> <span class='ident'>Sync</span> <span class='kw'>for</span> <span class='ident'>Unique</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> {} <span class='kw'>impl</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> <span class='ident'>Unique</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> { <span class='kw'>pub</span> <span class='kw'>fn</span> <span class='ident'>new</span>(<span class='ident'>ptr</span>: <span class='op'>*</span><span class='kw-2'>mut</span> <span class='ident'>T</span>) <span class='op'>-&gt;</span> <span class='self'>Self</span> { <span class='ident'>Unique</span> { <span class='ident'>ptr</span>: <span class='ident'>ptr</span>, <span class='ident'>_marker</span>: <span class='ident'>PhantomData</span> } } } <span class='kw'>impl</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> <span class='ident'>Deref</span> <span class='kw'>for</span> <span class='ident'>Unique</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> { <span class='kw'>type</span> <span class='ident'>Target</span> <span class='op'>=</span> <span class='op'>*</span><span class='kw-2'>mut</span> <span class='ident'>T</span>; <span class='kw'>fn</span> <span class='ident'>deref</span>(<span class='kw-2'>&amp;</span><span class='self'>self</span>) <span class='op'>-&gt;</span> <span class='kw-2'>&amp;</span><span class='op'>*</span><span class='kw-2'>mut</span> <span class='ident'>T</span> { <span class='comment'>// There&#39;s no way to cast the *const to a *mut</span> <span class='comment'>// while also taking a reference. So we just</span> <span class='comment'>// transmute it since it&#39;s all &quot;just pointers&quot;.</span> <span class='kw'>unsafe</span> { <span class='ident'>mem</span>::<span class='ident'>transmute</span>(<span class='kw-2'>&amp;</span><span class='self'>self</span>.<span class='ident'>ptr</span>) } } }</pre> <p>Unfortunately the mechanism for stating that your value is non-zero is unstable and unlikely to be stabilized soon. As such we&#39;re just going to take the hit and use std&#39;s Unique:</p> <span class='rusttest'>#![feature(unique)] use std::ptr::{Unique, self}; pub struct Vec&lt;T&gt; { ptr: Unique&lt;T&gt;, cap: usize, len: usize, } fn main() {} </span><pre class='rust rust-example-rendered'> <span class='attribute'>#<span class='op'>!</span>[<span class='ident'>feature</span>(<span class='ident'>unique</span>)]</span> <span class='kw'>use</span> <span class='ident'>std</span>::<span class='ident'>ptr</span>::{<span class='ident'>Unique</span>, <span class='self'>self</span>}; <span class='kw'>pub</span> <span class='kw'>struct</span> <span class='ident'>Vec</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> { <span class='ident'>ptr</span>: <span class='ident'>Unique</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span>, <span class='ident'>cap</span>: <span class='ident'>usize</span>, <span class='ident'>len</span>: <span class='ident'>usize</span>, } </pre> <p>If you don&#39;t care about the null-pointer optimization, then you can use the stable code. However we will be designing the rest of the code around enabling the optimization. In particular, <code>Unique::new</code> is unsafe to call, because putting <code>null</code> inside of it is Undefined Behavior. Our stable Unique doesn&#39;t need <code>new</code> to be unsafe because it doesn&#39;t make any interesting guarantees about its contents.</p> <script type="text/javascript"> window.playgroundUrl = "https://play.rust-lang.org"; </script> <script src='rustbook.js'></script> <script src='playpen.js'></script> </div></div> </body> </html> <|start_filename|>docs/1.6/book/generics.html<|end_filename|> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="generator" content="rustdoc"> <title>ジェネリクス</title> <link rel="stylesheet" type="text/css" href="rustbook.css"> <meta name="robots" content="noindex"> </head> <body class="rustdoc"> <!--[if lte IE 8]> <div class="warning"> This old browser is unsupported and will most likely display funky things. </div> <![endif]--> <div id="nav"> <button id="toggle-nav"> <span class="sr-only">Toggle navigation</span> <span class="bar"></span> <span class="bar"></span> <span class="bar"></span> </button> </div> <div id='toc' class='mobile-hidden'> <ul class='chapter'> <li><a href='README.html'><b>1.</b> Introduction</a> </li> <li><a href='getting-started.html'><b>2.</b> はじめる</a> </li> <li><a href='learn-rust.html'><b>3.</b> Rustを学ぶ</a> <ul class='section'> <li><a href='guessing-game.html'><b>3.1.</b> 数当てゲーム</a> </li> <li><a href='dining-philosophers.html'><b>3.2.</b> 食事する哲学者</a> </li> <li><a href='rust-inside-other-languages.html'><b>3.3.</b> 他言語と共存する</a> </li> </ul> </li> <li><a href='syntax-and-semantics.html'><b>4.</b> シンタックスとセマンティクス</a> <ul class='section'> <li><a href='variable-bindings.html'><b>4.1.</b> 変数束縛</a> </li> <li><a href='functions.html'><b>4.2.</b> 関数</a> </li> <li><a href='primitive-types.html'><b>4.3.</b> プリミティブ型</a> </li> <li><a href='comments.html'><b>4.4.</b> コメント</a> </li> <li><a href='if.html'><b>4.5.</b> if</a> </li> <li><a href='loops.html'><b>4.6.</b> ループ</a> </li> <li><a href='ownership.html'><b>4.7.</b> 所有権</a> </li> <li><a href='references-and-borrowing.html'><b>4.8.</b> 参照と借用</a> </li> <li><a href='lifetimes.html'><b>4.9.</b> ライフタイム</a> </li> <li><a href='mutability.html'><b>4.10.</b> ミュータビリティ</a> </li> <li><a href='structs.html'><b>4.11.</b> 構造体</a> </li> <li><a href='enums.html'><b>4.12.</b> 列挙型</a> </li> <li><a href='match.html'><b>4.13.</b> マッチ</a> </li> <li><a href='patterns.html'><b>4.14.</b> パターン</a> </li> <li><a href='method-syntax.html'><b>4.15.</b> メソッド構文</a> </li> <li><a href='vectors.html'><b>4.16.</b> ベクタ</a> </li> <li><a href='strings.html'><b>4.17.</b> 文字列</a> </li> <li><a class='active' href='generics.html'><b>4.18.</b> ジェネリクス</a> </li> <li><a href='traits.html'><b>4.19.</b> トレイト</a> </li> <li><a href='drop.html'><b>4.20.</b> Drop</a> </li> <li><a href='if-let.html'><b>4.21.</b> if let</a> </li> <li><a href='trait-objects.html'><b>4.22.</b> トレイトオブジェクト</a> </li> <li><a href='closures.html'><b>4.23.</b> クロージャ</a> </li> <li><a href='ufcs.html'><b>4.24.</b> 共通の関数呼出構文</a> </li> <li><a href='crates-and-modules.html'><b>4.25.</b> クレートとモジュール</a> </li> <li><a href='const-and-static.html'><b>4.26.</b> `const` と `static`</a> </li> <li><a href='attributes.html'><b>4.27.</b> アトリビュート</a> </li> <li><a href='type-aliases.html'><b>4.28.</b> `type` エイリアス</a> </li> <li><a href='casting-between-types.html'><b>4.29.</b> 型間のキャスト</a> </li> <li><a href='associated-types.html'><b>4.30.</b> 関連型</a> </li> <li><a href='unsized-types.html'><b>4.31.</b> サイズ不定型</a> </li> <li><a href='operators-and-overloading.html'><b>4.32.</b> 演算子とオーバーロード</a> </li> <li><a href='deref-coercions.html'><b>4.33.</b> Derefによる型強制</a> </li> <li><a href='macros.html'><b>4.34.</b> マクロ</a> </li> <li><a href='raw-pointers.html'><b>4.35.</b> 生ポインタ</a> </li> <li><a href='unsafe.html'><b>4.36.</b> `unsafe`</a> </li> </ul> </li> <li><a href='effective-rust.html'><b>5.</b> Effective Rust</a> <ul class='section'> <li><a href='the-stack-and-the-heap.html'><b>5.1.</b> スタックとヒープ</a> </li> <li><a href='testing.html'><b>5.2.</b> テスト</a> </li> <li><a href='conditional-compilation.html'><b>5.3.</b> 条件付きコンパイル</a> </li> <li><a href='documentation.html'><b>5.4.</b> ドキュメント</a> </li> <li><a href='iterators.html'><b>5.5.</b> イテレータ</a> </li> <li><a href='concurrency.html'><b>5.6.</b> 並行性</a> </li> <li><a href='error-handling.html'><b>5.7.</b> エラーハンドリング</a> </li> <li><a href='choosing-your-guarantees.html'><b>5.8.</b> 保証を選ぶ</a> </li> <li><a href='ffi.html'><b>5.9.</b> 他言語関数インターフェース</a> </li> <li><a href='borrow-and-asref.html'><b>5.10.</b> BorrowとAsRef</a> </li> <li><a href='release-channels.html'><b>5.11.</b> リリースチャネル</a> </li> <li><a href='using-rust-without-the-standard-library.html'><b>5.12.</b> 標準ライブラリ無しでRustを使う</a> </li> </ul> </li> <li><a href='nightly-rust.html'><b>6.</b> Nightly Rust</a> <ul class='section'> <li><a href='compiler-plugins.html'><b>6.1.</b> コンパイラプラグイン</a> </li> <li><a href='inline-assembly.html'><b>6.2.</b> インラインアセンブリ</a> </li> <li><a href='no-stdlib.html'><b>6.3.</b> No stdlib</a> </li> <li><a href='intrinsics.html'><b>6.4.</b> Intrinsic</a> </li> <li><a href='lang-items.html'><b>6.5.</b> 言語アイテム</a> </li> <li><a href='advanced-linking.html'><b>6.6.</b> 高度なリンキング</a> </li> <li><a href='benchmark-tests.html'><b>6.7.</b> ベンチマークテスト</a> </li> <li><a href='box-syntax-and-patterns.html'><b>6.8.</b> Box構文とパターン</a> </li> <li><a href='slice-patterns.html'><b>6.9.</b> スライスパターン</a> </li> <li><a href='associated-constants.html'><b>6.10.</b> 関連定数</a> </li> <li><a href='custom-allocators.html'><b>6.11.</b> カスタムアロケータ</a> </li> </ul> </li> <li><a href='glossary.html'><b>7.</b> 用語集</a> </li> <li><a href='syntax-index.html'><b>8.</b> 構文の索引</a> </li> <li><a href='bibliography.html'><b>9.</b> 関係書目</a> </li> </ul> </div> <div id='page-wrapper'> <div id='page'> <blockquote class="header-caveat"> <p> <strong>注意: <a href="https://doc.rust-jp.rs/book-ja/">最新版のドキュメントをご覧ください。</a></strong>この第1版ドキュメントは古くなっており、最新情報が反映されていません。リンク先のドキュメントが現在の Rust の最新のドキュメントです。 </p> </blockquote> <h1 class="title">ジェネリクス</h1> <!-- % Generics --> <!-- Sometimes, when writing a function or data type, we may want it to work for multiple types of arguments. In Rust, we can do this with generics. Generics are called ‘parametric polymorphism’ in type theory, which means that they are types or functions that have multiple forms (‘poly’ is multiple, ‘morph’ is form) over a given parameter (‘parametric’). --> <p>時々、関数やデータ型を書いていると、引数が複数の型に対応したものが欲しくなることもあります。Rustでは、ジェネリクスを用いてこれを実現しています。ジェネリクスは型理論において「パラメトリック多相」(parametric polymorphism)と呼ばれ、与えられたパラメータにより(「parametric」)型もしくは関数が多くの相(「poly」は「多くの」、「morph」は「相(かたち)」を意味します)(訳注: ここで「相」は型を指します)を持つことを意味しています。</p> <!-- Anyway, enough type theory, let’s check out some generic code. Rust’s standard library provides a type, `Option<T>`, that’s generic: --> <p>さて、型理論はもう十分です。続いてジェネリックなコードを幾つか見ていきましょう。Rustが標準ライブラリで提供している型 <code>Option&lt;T&gt;</code> はジェネリックです。</p> <span class='rusttest'>fn main() { enum Option&lt;T&gt; { Some(T), None, } }</span><pre class='rust rust-example-rendered'> <span class='kw'>enum</span> <span class='prelude-ty'>Option</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> { <span class='prelude-val'>Some</span>(<span class='ident'>T</span>), <span class='prelude-val'>None</span>, }</pre> <!-- The `<T>` part, which you’ve seen a few times before, indicates that this is a generic data type. Inside the declaration of our `enum`, wherever we see a `T`, we substitute that type for the same type used in the generic. Here’s an example of using `Option<T>`, with some extra type annotations: --> <p><code>&lt;T&gt;</code> の部分は、前に少し見たことがあると思いますが、これがジェネリックなデータ型であることを示しています。 <code>enum</code> の宣言内であれば、どこでも <code>T</code> を使うことができ、宣言内に登場する同じ型をジェネリック内で <code>T</code> 型に置き換えています。型注釈を用いた<code>Option&lt;T&gt;</code>の使用例が以下になります。</p> <span class='rusttest'>fn main() { let x: Option&lt;i32&gt; = Some(5); }</span><pre class='rust rust-example-rendered'> <span class='kw'>let</span> <span class='ident'>x</span>: <span class='prelude-ty'>Option</span><span class='op'>&lt;</span><span class='ident'>i32</span><span class='op'>&gt;</span> <span class='op'>=</span> <span class='prelude-val'>Some</span>(<span class='number'>5</span>);</pre> <!-- In the type declaration, we say `Option<i32>`. Note how similar this looks to `Option<T>`. So, in this particular `Option`, `T` has the value of `i32`. On the right-hand side of the binding, we make a `Some(T)`, where `T` is `5`. Since that’s an `i32`, the two sides match, and Rust is happy. If they didn’t match, we’d get an error: --> <p>この型宣言では <code>Option&lt;i32&gt;</code> と書かれています。 <code>Option&lt;T&gt;</code> の違いに注目して下さい。そう、上記の <code>Option</code> では <code>T</code> の値は <code>i32</code> です。この束縛の右辺の <code>Some(T)</code> では、 <code>T</code> は <code>5</code> となります。それが <code>i32</code> なので、両辺の型が一致するため、Rustは満足します。型が不一致であれば、以下のようなエラーが発生します。</p> <span class='rusttest'>fn main() { let x: Option&lt;f64&gt; = Some(5); // error: mismatched types: expected `core::option::Option&lt;f64&gt;`, // found `core::option::Option&lt;_&gt;` (expected f64 but found integral variable) }</span><pre class='rust rust-example-rendered'> <span class='kw'>let</span> <span class='ident'>x</span>: <span class='prelude-ty'>Option</span><span class='op'>&lt;</span><span class='ident'>f64</span><span class='op'>&gt;</span> <span class='op'>=</span> <span class='prelude-val'>Some</span>(<span class='number'>5</span>); <span class='comment'>// error: mismatched types: expected `core::option::Option&lt;f64&gt;`,</span> <span class='comment'>// found `core::option::Option&lt;_&gt;` (expected f64 but found integral variable)</span></pre> <!-- That doesn’t mean we can’t make `Option<T>`s that hold an `f64`! They just have to match up: --> <p>これは <code>f64</code> を保持する <code>Option&lt;T&gt;</code> が作れないという意味ではありませんからね!リテラルと宣言の型をぴったり合わせなければなりません。</p> <span class='rusttest'>fn main() { let x: Option&lt;i32&gt; = Some(5); let y: Option&lt;f64&gt; = Some(5.0f64); }</span><pre class='rust rust-example-rendered'> <span class='kw'>let</span> <span class='ident'>x</span>: <span class='prelude-ty'>Option</span><span class='op'>&lt;</span><span class='ident'>i32</span><span class='op'>&gt;</span> <span class='op'>=</span> <span class='prelude-val'>Some</span>(<span class='number'>5</span>); <span class='kw'>let</span> <span class='ident'>y</span>: <span class='prelude-ty'>Option</span><span class='op'>&lt;</span><span class='ident'>f64</span><span class='op'>&gt;</span> <span class='op'>=</span> <span class='prelude-val'>Some</span>(<span class='number'>5.0f64</span>);</pre> <!-- This is just fine. One definition, multiple uses. --> <p>これだけで結構です。1つの定義で、多くの用途が得られます。</p> <!-- Generics don’t have to only be generic over one type. Consider another type from Rust’s standard library that’s similar, `Result<T, E>`: --> <p>ジェネリクスにおいてジェネリックな型は1つまで、といった制限はありません。Rustの標準ライブラリに入っている類似の型 <code>Result&lt;T, E&gt;</code> について考えてみます。</p> <span class='rusttest'>fn main() { enum Result&lt;T, E&gt; { Ok(T), Err(E), } }</span><pre class='rust rust-example-rendered'> <span class='kw'>enum</span> <span class='prelude-ty'>Result</span><span class='op'>&lt;</span><span class='ident'>T</span>, <span class='ident'>E</span><span class='op'>&gt;</span> { <span class='prelude-val'>Ok</span>(<span class='ident'>T</span>), <span class='prelude-val'>Err</span>(<span class='ident'>E</span>), }</pre> <!-- This type is generic over _two_ types: `T` and `E`. By the way, the capital letters can be any letter you’d like. We could define `Result<T, E>` as: --> <p>この型では <code>T</code> と <code>E</code> の <em>2つ</em> がジェネリックです。ちなみに、大文字の部分はあなたの好きな文字で構いません。もしあなたが望むなら <code>Result&lt;T, E&gt;</code> を、</p> <span class='rusttest'>fn main() { enum Result&lt;A, Z&gt; { Ok(A), Err(Z), } }</span><pre class='rust rust-example-rendered'> <span class='kw'>enum</span> <span class='prelude-ty'>Result</span><span class='op'>&lt;</span><span class='ident'>A</span>, <span class='ident'>Z</span><span class='op'>&gt;</span> { <span class='prelude-val'>Ok</span>(<span class='ident'>A</span>), <span class='prelude-val'>Err</span>(<span class='ident'>Z</span>), }</pre> <!-- if we wanted to. Convention says that the first generic parameter should be `T`, for ‘type’, and that we use `E` for ‘error’. Rust doesn’t care, however. --> <p>のように定義できます。慣習としては、「Type」から第1ジェネリックパラメータは <code>T</code> であるべきですし、「Error」から <code>E</code> を用いるのですが、Rustは気にしません。</p> <!-- The `Result<T, E>` type is intended to be used to return the result of a computation, and to have the ability to return an error if it didn’t work out. --> <p><code>Result&lt;T, E&gt;</code> 型は計算の結果を返すために使われることが想定されており、正常に動作しなかった場合にエラーの値を返す機能を持っています。</p> <!-- ## Generic functions --> <h2 id='ジェネリック関数' class='section-header'><a href='#ジェネリック関数'>ジェネリック関数</a></h2> <!-- We can write functions that take generic types with a similar syntax: --> <p>似た構文でジェネリックな型を取る関数を記述できます。</p> <span class='rusttest'>fn main() { fn takes_anything&lt;T&gt;(x: T) { // do something with x // xで何か行う } }</span><pre class='rust rust-example-rendered'> <span class='kw'>fn</span> <span class='ident'>takes_anything</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span>(<span class='ident'>x</span>: <span class='ident'>T</span>) { <span class='comment'>// xで何か行う</span> }</pre> <!-- The syntax has two parts: the `<T>` says “this function is generic over one type, `T`”, and the `x: T` says “x has the type `T`.” --> <p>構文は2つのパーツから成ります。 <code>&lt;T&gt;</code> は「この関数は1つの型、 <code>T</code> に対してジェネリックである」ということであり、 <code>x: T</code> は「xは <code>T</code> 型である」という意味です。</p> <!-- Multiple arguments can have the same generic type: --> <p>複数の引数が同じジェネリックな型を持つこともできます。</p> <span class='rusttest'>fn main() { fn takes_two_of_the_same_things&lt;T&gt;(x: T, y: T) { // ... } }</span><pre class='rust rust-example-rendered'> <span class='kw'>fn</span> <span class='ident'>takes_two_of_the_same_things</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span>(<span class='ident'>x</span>: <span class='ident'>T</span>, <span class='ident'>y</span>: <span class='ident'>T</span>) { <span class='comment'>// ...</span> }</pre> <!-- We could write a version that takes multiple types: --> <p>複数の型を取るバージョンを記述することも可能です。</p> <span class='rusttest'>fn main() { fn takes_two_things&lt;T, U&gt;(x: T, y: U) { // ... } }</span><pre class='rust rust-example-rendered'> <span class='kw'>fn</span> <span class='ident'>takes_two_things</span><span class='op'>&lt;</span><span class='ident'>T</span>, <span class='ident'>U</span><span class='op'>&gt;</span>(<span class='ident'>x</span>: <span class='ident'>T</span>, <span class='ident'>y</span>: <span class='ident'>U</span>) { <span class='comment'>// ...</span> }</pre> <!-- ## Generic structs --> <h2 id='ジェネリック構造体' class='section-header'><a href='#ジェネリック構造体'>ジェネリック構造体</a></h2> <!-- You can store a generic type in a `struct` as well: --> <p>また、 <code>struct</code> 内にジェネリックな型の値を保存することもできます。</p> <span class='rusttest'>fn main() { struct Point&lt;T&gt; { x: T, y: T, } let int_origin = Point { x: 0, y: 0 }; let float_origin = Point { x: 0.0, y: 0.0 }; }</span><pre class='rust rust-example-rendered'> <span class='kw'>struct</span> <span class='ident'>Point</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> { <span class='ident'>x</span>: <span class='ident'>T</span>, <span class='ident'>y</span>: <span class='ident'>T</span>, } <span class='kw'>let</span> <span class='ident'>int_origin</span> <span class='op'>=</span> <span class='ident'>Point</span> { <span class='ident'>x</span>: <span class='number'>0</span>, <span class='ident'>y</span>: <span class='number'>0</span> }; <span class='kw'>let</span> <span class='ident'>float_origin</span> <span class='op'>=</span> <span class='ident'>Point</span> { <span class='ident'>x</span>: <span class='number'>0.0</span>, <span class='ident'>y</span>: <span class='number'>0.0</span> };</pre> <!-- Similar to functions, the `<T>` is where we declare the generic parameters, and we then use `x: T` in the type declaration, too. --> <p>関数と同様に、 <code>&lt;T&gt;</code> がジェネリックパラメータを宣言する場所であり、型宣言において <code>x: T</code> を使うのも同じです。</p> <!-- When you want to add an implementation for the generic `struct`, you just declare the type parameter after the `impl`: --> <p>ジェネリックな <code>struct</code> に実装を追加したい場合、 <code>impl</code> の後に型パラメータを宣言するだけです。</p> <span class='rusttest'>fn main() { struct Point&lt;T&gt; { x: T, y: T, } impl&lt;T&gt; Point&lt;T&gt; { fn swap(&amp;mut self) { std::mem::swap(&amp;mut self.x, &amp;mut self.y); } } }</span><pre class='rust rust-example-rendered'> <span class='kw'>impl</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> <span class='ident'>Point</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> { <span class='kw'>fn</span> <span class='ident'>swap</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>) { <span class='ident'>std</span>::<span class='ident'>mem</span>::<span class='ident'>swap</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>.<span class='ident'>x</span>, <span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>.<span class='ident'>y</span>); } }</pre> <!-- So far you’ve seen generics that take absolutely any type. These are useful in many cases: you’ve already seen `Option<T>`, and later you’ll meet universal container types like [`Vec<T>`][Vec]. On the other hand, often you want to trade that flexibility for increased expressive power. Read about [trait bounds][traits] to see why and how. --> <p>ここまででありとあらゆる型をとることのできるジェネリクスについて見てきました。多くの場合これらは有用です。 <code>Option&lt;T&gt;</code> は既に見た通りですし、のちに <code>Vec&lt;T&gt;</code> のような普遍的なコンテナ型を知ることになるでしょう。一方で、その柔軟性と引き換えに表現力を増加させたくなることもあります。それは何故か、そしてその方法を知るためには <a href="traits.html">トレイト境界</a> を読んで下さい。</p> <script type="text/javascript"> window.playgroundUrl = "https://play.rust-lang.org"; </script> <script src='rustbook.js'></script> <script src='playpen.js'></script> </div></div> </body> </html> <|start_filename|>docs/1.9/nomicon/borrow-splitting.html<|end_filename|> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="generator" content="rustdoc"> <title>Splitting Borrows</title> <link rel="stylesheet" type="text/css" href="rustbook.css"> <meta name="robots" content="noindex"> </head> <body class="rustdoc"> <!--[if lte IE 8]> <div class="warning"> This old browser is unsupported and will most likely display funky things. </div> <![endif]--> <div id="nav"> <button id="toggle-nav"> <span class="sr-only">Toggle navigation</span> <span class="bar"></span> <span class="bar"></span> <span class="bar"></span> </button> </div> <div id='toc' class='mobile-hidden'> <ul class='chapter'> <li><a href='README.html'><b>1.</b> Introduction</a> </li> <li><a href='meet-safe-and-unsafe.html'><b>2.</b> Meet Safe and Unsafe</a> <ul class='section'> <li><a href='safe-unsafe-meaning.html'><b>2.1.</b> How Safe and Unsafe Interact</a> </li> <li><a href='working-with-unsafe.html'><b>2.2.</b> Working with Unsafe</a> </li> </ul> </li> <li><a href='data.html'><b>3.</b> Data Layout</a> <ul class='section'> <li><a href='repr-rust.html'><b>3.1.</b> repr(Rust)</a> </li> <li><a href='exotic-sizes.html'><b>3.2.</b> Exotically Sized Types</a> </li> <li><a href='other-reprs.html'><b>3.3.</b> Other reprs</a> </li> </ul> </li> <li><a href='ownership.html'><b>4.</b> Ownership</a> <ul class='section'> <li><a href='references.html'><b>4.1.</b> References</a> </li> <li><a href='lifetimes.html'><b>4.2.</b> Lifetimes</a> </li> <li><a href='lifetime-mismatch.html'><b>4.3.</b> Limits of Lifetimes</a> </li> <li><a href='lifetime-elision.html'><b>4.4.</b> Lifetime Elision</a> </li> <li><a href='unbounded-lifetimes.html'><b>4.5.</b> Unbounded Lifetimes</a> </li> <li><a href='hrtb.html'><b>4.6.</b> Higher-Rank Trait Bounds</a> </li> <li><a href='subtyping.html'><b>4.7.</b> Subtyping and Variance</a> </li> <li><a href='dropck.html'><b>4.8.</b> Drop Check</a> </li> <li><a href='phantom-data.html'><b>4.9.</b> PhantomData</a> </li> <li><a class='active' href='borrow-splitting.html'><b>4.10.</b> Splitting Borrows</a> </li> </ul> </li> <li><a href='conversions.html'><b>5.</b> Type Conversions</a> <ul class='section'> <li><a href='coercions.html'><b>5.1.</b> Coercions</a> </li> <li><a href='dot-operator.html'><b>5.2.</b> The Dot Operator</a> </li> <li><a href='casts.html'><b>5.3.</b> Casts</a> </li> <li><a href='transmutes.html'><b>5.4.</b> Transmutes</a> </li> </ul> </li> <li><a href='uninitialized.html'><b>6.</b> Uninitialized Memory</a> <ul class='section'> <li><a href='checked-uninit.html'><b>6.1.</b> Checked</a> </li> <li><a href='drop-flags.html'><b>6.2.</b> Drop Flags</a> </li> <li><a href='unchecked-uninit.html'><b>6.3.</b> Unchecked</a> </li> </ul> </li> <li><a href='obrm.html'><b>7.</b> Ownership Based Resource Management</a> <ul class='section'> <li><a href='constructors.html'><b>7.1.</b> Constructors</a> </li> <li><a href='destructors.html'><b>7.2.</b> Destructors</a> </li> <li><a href='leaking.html'><b>7.3.</b> Leaking</a> </li> </ul> </li> <li><a href='unwinding.html'><b>8.</b> Unwinding</a> <ul class='section'> <li><a href='exception-safety.html'><b>8.1.</b> Exception Safety</a> </li> <li><a href='poisoning.html'><b>8.2.</b> Poisoning</a> </li> </ul> </li> <li><a href='concurrency.html'><b>9.</b> Concurrency</a> <ul class='section'> <li><a href='races.html'><b>9.1.</b> Races</a> </li> <li><a href='send-and-sync.html'><b>9.2.</b> Send and Sync</a> </li> <li><a href='atomics.html'><b>9.3.</b> Atomics</a> </li> </ul> </li> <li><a href='vec.html'><b>10.</b> Implementing Vec</a> <ul class='section'> <li><a href='vec-layout.html'><b>10.1.</b> Layout</a> </li> <li><a href='vec-alloc.html'><b>10.2.</b> Allocating</a> </li> <li><a href='vec-push-pop.html'><b>10.3.</b> Push and Pop</a> </li> <li><a href='vec-dealloc.html'><b>10.4.</b> Deallocating</a> </li> <li><a href='vec-deref.html'><b>10.5.</b> Deref</a> </li> <li><a href='vec-insert-remove.html'><b>10.6.</b> Insert and Remove</a> </li> <li><a href='vec-into-iter.html'><b>10.7.</b> IntoIter</a> </li> <li><a href='vec-raw.html'><b>10.8.</b> RawVec</a> </li> <li><a href='vec-drain.html'><b>10.9.</b> Drain</a> </li> <li><a href='vec-zsts.html'><b>10.10.</b> Handling Zero-Sized Types</a> </li> <li><a href='vec-final.html'><b>10.11.</b> Final Code</a> </li> </ul> </li> <li><a href='arc-and-mutex.html'><b>11.</b> Implementing Arc and Mutex</a> </li> </ul> </div> <div id='page-wrapper'> <div id='page'> <blockquote class="header-caveat"> <p> <strong>注意: <a href="https://doc.rust-jp.rs/book-ja/">最新版のドキュメントをご覧ください。</a></strong>この第1版ドキュメントは古くなっており、最新情報が反映されていません。リンク先のドキュメントが現在の Rust の最新のドキュメントです。 </p> </blockquote> <h1 class="title">Splitting Borrows</h1> <p>The mutual exclusion property of mutable references can be very limiting when working with a composite structure. The borrow checker understands some basic stuff, but will fall over pretty easily. It does understand structs sufficiently to know that it&#39;s possible to borrow disjoint fields of a struct simultaneously. So this works today:</p> <span class='rusttest'>fn main() { struct Foo { a: i32, b: i32, c: i32, } let mut x = Foo {a: 0, b: 0, c: 0}; let a = &amp;mut x.a; let b = &amp;mut x.b; let c = &amp;x.c; *b += 1; let c2 = &amp;x.c; *a += 10; println!(&quot;{} {} {} {}&quot;, a, b, c, c2); }</span><pre class='rust rust-example-rendered'> <span class='kw'>struct</span> <span class='ident'>Foo</span> { <span class='ident'>a</span>: <span class='ident'>i32</span>, <span class='ident'>b</span>: <span class='ident'>i32</span>, <span class='ident'>c</span>: <span class='ident'>i32</span>, } <span class='kw'>let</span> <span class='kw-2'>mut</span> <span class='ident'>x</span> <span class='op'>=</span> <span class='ident'>Foo</span> {<span class='ident'>a</span>: <span class='number'>0</span>, <span class='ident'>b</span>: <span class='number'>0</span>, <span class='ident'>c</span>: <span class='number'>0</span>}; <span class='kw'>let</span> <span class='ident'>a</span> <span class='op'>=</span> <span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='ident'>x</span>.<span class='ident'>a</span>; <span class='kw'>let</span> <span class='ident'>b</span> <span class='op'>=</span> <span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='ident'>x</span>.<span class='ident'>b</span>; <span class='kw'>let</span> <span class='ident'>c</span> <span class='op'>=</span> <span class='kw-2'>&amp;</span><span class='ident'>x</span>.<span class='ident'>c</span>; <span class='op'>*</span><span class='ident'>b</span> <span class='op'>+=</span> <span class='number'>1</span>; <span class='kw'>let</span> <span class='ident'>c2</span> <span class='op'>=</span> <span class='kw-2'>&amp;</span><span class='ident'>x</span>.<span class='ident'>c</span>; <span class='op'>*</span><span class='ident'>a</span> <span class='op'>+=</span> <span class='number'>10</span>; <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;{} {} {} {}&quot;</span>, <span class='ident'>a</span>, <span class='ident'>b</span>, <span class='ident'>c</span>, <span class='ident'>c2</span>);</pre> <p>However borrowck doesn&#39;t understand arrays or slices in any way, so this doesn&#39;t work:</p> <span class='rusttest'>fn main() { let mut x = [1, 2, 3]; let a = &amp;mut x[0]; let b = &amp;mut x[1]; println!(&quot;{} {}&quot;, a, b); }</span><pre class='rust rust-example-rendered'> <span class='kw'>let</span> <span class='kw-2'>mut</span> <span class='ident'>x</span> <span class='op'>=</span> [<span class='number'>1</span>, <span class='number'>2</span>, <span class='number'>3</span>]; <span class='kw'>let</span> <span class='ident'>a</span> <span class='op'>=</span> <span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='ident'>x</span>[<span class='number'>0</span>]; <span class='kw'>let</span> <span class='ident'>b</span> <span class='op'>=</span> <span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='ident'>x</span>[<span class='number'>1</span>]; <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;{} {}&quot;</span>, <span class='ident'>a</span>, <span class='ident'>b</span>);</pre> <pre><code class="language-text">&lt;anon&gt;:4:14: 4:18 error: cannot borrow `x[..]` as mutable more than once at a time &lt;anon&gt;:4 let b = &amp;mut x[1]; ^~~~ &lt;anon&gt;:3:14: 3:18 note: previous borrow of `x[..]` occurs here; the mutable borrow prevents subsequent moves, borrows, or modification of `x[..]` until the borrow ends &lt;anon&gt;:3 let a = &amp;mut x[0]; ^~~~ &lt;anon&gt;:6:2: 6:2 note: previous borrow ends here &lt;anon&gt;:1 fn main() { &lt;anon&gt;:2 let mut x = [1, 2, 3]; &lt;anon&gt;:3 let a = &amp;mut x[0]; &lt;anon&gt;:4 let b = &amp;mut x[1]; &lt;anon&gt;:5 println!(&quot;{} {}&quot;, a, b); &lt;anon&gt;:6 } ^ error: aborting due to 2 previous errors </code></pre> <p>While it was plausible that borrowck could understand this simple case, it&#39;s pretty clearly hopeless for borrowck to understand disjointness in general container types like a tree, especially if distinct keys actually <em>do</em> map to the same value.</p> <p>In order to &quot;teach&quot; borrowck that what we&#39;re doing is ok, we need to drop down to unsafe code. For instance, mutable slices expose a <code>split_at_mut</code> function that consumes the slice and returns two mutable slices. One for everything to the left of the index, and one for everything to the right. Intuitively we know this is safe because the slices don&#39;t overlap, and therefore alias. However the implementation requires some unsafety:</p> <span class='rusttest'>fn main() { fn split_at_mut(&amp;mut self, mid: usize) -&gt; (&amp;mut [T], &amp;mut [T]) { let len = self.len(); let ptr = self.as_mut_ptr(); assert!(mid &lt;= len); unsafe { (from_raw_parts_mut(ptr, mid), from_raw_parts_mut(ptr.offset(mid as isize), len - mid)) } } }</span><pre class='rust rust-example-rendered'> <span class='kw'>fn</span> <span class='ident'>split_at_mut</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>, <span class='ident'>mid</span>: <span class='ident'>usize</span>) <span class='op'>-&gt;</span> (<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> [<span class='ident'>T</span>], <span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> [<span class='ident'>T</span>]) { <span class='kw'>let</span> <span class='ident'>len</span> <span class='op'>=</span> <span class='self'>self</span>.<span class='ident'>len</span>(); <span class='kw'>let</span> <span class='ident'>ptr</span> <span class='op'>=</span> <span class='self'>self</span>.<span class='ident'>as_mut_ptr</span>(); <span class='macro'>assert</span><span class='macro'>!</span>(<span class='ident'>mid</span> <span class='op'>&lt;=</span> <span class='ident'>len</span>); <span class='kw'>unsafe</span> { (<span class='ident'>from_raw_parts_mut</span>(<span class='ident'>ptr</span>, <span class='ident'>mid</span>), <span class='ident'>from_raw_parts_mut</span>(<span class='ident'>ptr</span>.<span class='ident'>offset</span>(<span class='ident'>mid</span> <span class='kw'>as</span> <span class='ident'>isize</span>), <span class='ident'>len</span> <span class='op'>-</span> <span class='ident'>mid</span>)) } }</pre> <p>This is actually a bit subtle. So as to avoid ever making two <code>&amp;mut</code>&#39;s to the same value, we explicitly construct brand-new slices through raw pointers.</p> <p>However more subtle is how iterators that yield mutable references work. The iterator trait is defined as follows:</p> <span class='rusttest'>fn main() { trait Iterator { type Item; fn next(&amp;mut self) -&gt; Option&lt;Self::Item&gt;; } }</span><pre class='rust rust-example-rendered'> <span class='kw'>trait</span> <span class='ident'>Iterator</span> { <span class='kw'>type</span> <span class='ident'>Item</span>; <span class='kw'>fn</span> <span class='ident'>next</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>) <span class='op'>-&gt;</span> <span class='prelude-ty'>Option</span><span class='op'>&lt;</span><span class='self'>Self</span>::<span class='ident'>Item</span><span class='op'>&gt;</span>; }</pre> <p>Given this definition, Self::Item has <em>no</em> connection to <code>self</code>. This means that we can call <code>next</code> several times in a row, and hold onto all the results <em>concurrently</em>. This is perfectly fine for by-value iterators, which have exactly these semantics. It&#39;s also actually fine for shared references, as they admit arbitrarily many references to the same thing (although the iterator needs to be a separate object from the thing being shared).</p> <p>But mutable references make this a mess. At first glance, they might seem completely incompatible with this API, as it would produce multiple mutable references to the same object!</p> <p>However it actually <em>does</em> work, exactly because iterators are one-shot objects. Everything an IterMut yields will be yielded at most once, so we don&#39;t actually ever yield multiple mutable references to the same piece of data.</p> <p>Perhaps surprisingly, mutable iterators don&#39;t require unsafe code to be implemented for many types!</p> <p>For instance here&#39;s a singly linked list:</p> <span class='rusttest'>fn main() {} type Link&lt;T&gt; = Option&lt;Box&lt;Node&lt;T&gt;&gt;&gt;; struct Node&lt;T&gt; { elem: T, next: Link&lt;T&gt;, } pub struct LinkedList&lt;T&gt; { head: Link&lt;T&gt;, } pub struct IterMut&lt;&#39;a, T: &#39;a&gt;(Option&lt;&amp;&#39;a mut Node&lt;T&gt;&gt;); impl&lt;T&gt; LinkedList&lt;T&gt; { fn iter_mut(&amp;mut self) -&gt; IterMut&lt;T&gt; { IterMut(self.head.as_mut().map(|node| &amp;mut **node)) } } impl&lt;&#39;a, T&gt; Iterator for IterMut&lt;&#39;a, T&gt; { type Item = &amp;&#39;a mut T; fn next(&amp;mut self) -&gt; Option&lt;Self::Item&gt; { self.0.take().map(|node| { self.0 = node.next.as_mut().map(|node| &amp;mut **node); &amp;mut node.elem }) } } </span><pre class='rust rust-example-rendered'> <span class='kw'>type</span> <span class='ident'>Link</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> <span class='op'>=</span> <span class='prelude-ty'>Option</span><span class='op'>&lt;</span><span class='ident'>Box</span><span class='op'>&lt;</span><span class='ident'>Node</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;&gt;</span><span class='op'>&gt;</span>; <span class='kw'>struct</span> <span class='ident'>Node</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> { <span class='ident'>elem</span>: <span class='ident'>T</span>, <span class='ident'>next</span>: <span class='ident'>Link</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span>, } <span class='kw'>pub</span> <span class='kw'>struct</span> <span class='ident'>LinkedList</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> { <span class='ident'>head</span>: <span class='ident'>Link</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span>, } <span class='kw'>pub</span> <span class='kw'>struct</span> <span class='ident'>IterMut</span><span class='op'>&lt;</span><span class='lifetime'>&#39;a</span>, <span class='ident'>T</span>: <span class='lifetime'>&#39;a</span><span class='op'>&gt;</span>(<span class='prelude-ty'>Option</span><span class='op'>&lt;</span><span class='kw-2'>&amp;</span><span class='lifetime'>&#39;a</span> <span class='kw-2'>mut</span> <span class='ident'>Node</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;&gt;</span>); <span class='kw'>impl</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> <span class='ident'>LinkedList</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> { <span class='kw'>fn</span> <span class='ident'>iter_mut</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>) <span class='op'>-&gt;</span> <span class='ident'>IterMut</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> { <span class='ident'>IterMut</span>(<span class='self'>self</span>.<span class='ident'>head</span>.<span class='ident'>as_mut</span>().<span class='ident'>map</span>(<span class='op'>|</span><span class='ident'>node</span><span class='op'>|</span> <span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='op'>*</span><span class='op'>*</span><span class='ident'>node</span>)) } } <span class='kw'>impl</span><span class='op'>&lt;</span><span class='lifetime'>&#39;a</span>, <span class='ident'>T</span><span class='op'>&gt;</span> <span class='ident'>Iterator</span> <span class='kw'>for</span> <span class='ident'>IterMut</span><span class='op'>&lt;</span><span class='lifetime'>&#39;a</span>, <span class='ident'>T</span><span class='op'>&gt;</span> { <span class='kw'>type</span> <span class='ident'>Item</span> <span class='op'>=</span> <span class='kw-2'>&amp;</span><span class='lifetime'>&#39;a</span> <span class='kw-2'>mut</span> <span class='ident'>T</span>; <span class='kw'>fn</span> <span class='ident'>next</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>) <span class='op'>-&gt;</span> <span class='prelude-ty'>Option</span><span class='op'>&lt;</span><span class='self'>Self</span>::<span class='ident'>Item</span><span class='op'>&gt;</span> { <span class='self'>self</span>.<span class='number'>0</span>.<span class='ident'>take</span>().<span class='ident'>map</span>(<span class='op'>|</span><span class='ident'>node</span><span class='op'>|</span> { <span class='self'>self</span>.<span class='number'>0</span> <span class='op'>=</span> <span class='ident'>node</span>.<span class='ident'>next</span>.<span class='ident'>as_mut</span>().<span class='ident'>map</span>(<span class='op'>|</span><span class='ident'>node</span><span class='op'>|</span> <span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='op'>*</span><span class='op'>*</span><span class='ident'>node</span>); <span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='ident'>node</span>.<span class='ident'>elem</span> }) } }</pre> <p>Here&#39;s a mutable slice:</p> <span class='rusttest'>fn main() {} use std::mem; pub struct IterMut&lt;&#39;a, T: &#39;a&gt;(&amp;&#39;a mut[T]); impl&lt;&#39;a, T&gt; Iterator for IterMut&lt;&#39;a, T&gt; { type Item = &amp;&#39;a mut T; fn next(&amp;mut self) -&gt; Option&lt;Self::Item&gt; { let slice = mem::replace(&amp;mut self.0, &amp;mut []); if slice.is_empty() { return None; } let (l, r) = slice.split_at_mut(1); self.0 = r; l.get_mut(0) } } impl&lt;&#39;a, T&gt; DoubleEndedIterator for IterMut&lt;&#39;a, T&gt; { fn next_back(&amp;mut self) -&gt; Option&lt;Self::Item&gt; { let slice = mem::replace(&amp;mut self.0, &amp;mut []); if slice.is_empty() { return None; } let new_len = slice.len() - 1; let (l, r) = slice.split_at_mut(new_len); self.0 = l; r.get_mut(0) } } </span><pre class='rust rust-example-rendered'> <span class='kw'>use</span> <span class='ident'>std</span>::<span class='ident'>mem</span>; <span class='kw'>pub</span> <span class='kw'>struct</span> <span class='ident'>IterMut</span><span class='op'>&lt;</span><span class='lifetime'>&#39;a</span>, <span class='ident'>T</span>: <span class='lifetime'>&#39;a</span><span class='op'>&gt;</span>(<span class='kw-2'>&amp;</span><span class='lifetime'>&#39;a</span> <span class='kw-2'>mut</span>[<span class='ident'>T</span>]); <span class='kw'>impl</span><span class='op'>&lt;</span><span class='lifetime'>&#39;a</span>, <span class='ident'>T</span><span class='op'>&gt;</span> <span class='ident'>Iterator</span> <span class='kw'>for</span> <span class='ident'>IterMut</span><span class='op'>&lt;</span><span class='lifetime'>&#39;a</span>, <span class='ident'>T</span><span class='op'>&gt;</span> { <span class='kw'>type</span> <span class='ident'>Item</span> <span class='op'>=</span> <span class='kw-2'>&amp;</span><span class='lifetime'>&#39;a</span> <span class='kw-2'>mut</span> <span class='ident'>T</span>; <span class='kw'>fn</span> <span class='ident'>next</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>) <span class='op'>-&gt;</span> <span class='prelude-ty'>Option</span><span class='op'>&lt;</span><span class='self'>Self</span>::<span class='ident'>Item</span><span class='op'>&gt;</span> { <span class='kw'>let</span> <span class='ident'>slice</span> <span class='op'>=</span> <span class='ident'>mem</span>::<span class='ident'>replace</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>.<span class='number'>0</span>, <span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> []); <span class='kw'>if</span> <span class='ident'>slice</span>.<span class='ident'>is_empty</span>() { <span class='kw'>return</span> <span class='prelude-val'>None</span>; } <span class='kw'>let</span> (<span class='ident'>l</span>, <span class='ident'>r</span>) <span class='op'>=</span> <span class='ident'>slice</span>.<span class='ident'>split_at_mut</span>(<span class='number'>1</span>); <span class='self'>self</span>.<span class='number'>0</span> <span class='op'>=</span> <span class='ident'>r</span>; <span class='ident'>l</span>.<span class='ident'>get_mut</span>(<span class='number'>0</span>) } } <span class='kw'>impl</span><span class='op'>&lt;</span><span class='lifetime'>&#39;a</span>, <span class='ident'>T</span><span class='op'>&gt;</span> <span class='ident'>DoubleEndedIterator</span> <span class='kw'>for</span> <span class='ident'>IterMut</span><span class='op'>&lt;</span><span class='lifetime'>&#39;a</span>, <span class='ident'>T</span><span class='op'>&gt;</span> { <span class='kw'>fn</span> <span class='ident'>next_back</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>) <span class='op'>-&gt;</span> <span class='prelude-ty'>Option</span><span class='op'>&lt;</span><span class='self'>Self</span>::<span class='ident'>Item</span><span class='op'>&gt;</span> { <span class='kw'>let</span> <span class='ident'>slice</span> <span class='op'>=</span> <span class='ident'>mem</span>::<span class='ident'>replace</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>.<span class='number'>0</span>, <span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> []); <span class='kw'>if</span> <span class='ident'>slice</span>.<span class='ident'>is_empty</span>() { <span class='kw'>return</span> <span class='prelude-val'>None</span>; } <span class='kw'>let</span> <span class='ident'>new_len</span> <span class='op'>=</span> <span class='ident'>slice</span>.<span class='ident'>len</span>() <span class='op'>-</span> <span class='number'>1</span>; <span class='kw'>let</span> (<span class='ident'>l</span>, <span class='ident'>r</span>) <span class='op'>=</span> <span class='ident'>slice</span>.<span class='ident'>split_at_mut</span>(<span class='ident'>new_len</span>); <span class='self'>self</span>.<span class='number'>0</span> <span class='op'>=</span> <span class='ident'>l</span>; <span class='ident'>r</span>.<span class='ident'>get_mut</span>(<span class='number'>0</span>) } }</pre> <p>And here&#39;s a binary tree:</p> <span class='rusttest'>fn main() {} use std::collections::VecDeque; type Link&lt;T&gt; = Option&lt;Box&lt;Node&lt;T&gt;&gt;&gt;; struct Node&lt;T&gt; { elem: T, left: Link&lt;T&gt;, right: Link&lt;T&gt;, } pub struct Tree&lt;T&gt; { root: Link&lt;T&gt;, } struct NodeIterMut&lt;&#39;a, T: &#39;a&gt; { elem: Option&lt;&amp;&#39;a mut T&gt;, left: Option&lt;&amp;&#39;a mut Node&lt;T&gt;&gt;, right: Option&lt;&amp;&#39;a mut Node&lt;T&gt;&gt;, } enum State&lt;&#39;a, T: &#39;a&gt; { Elem(&amp;&#39;a mut T), Node(&amp;&#39;a mut Node&lt;T&gt;), } pub struct IterMut&lt;&#39;a, T: &#39;a&gt;(VecDeque&lt;NodeIterMut&lt;&#39;a, T&gt;&gt;); impl&lt;T&gt; Tree&lt;T&gt; { pub fn iter_mut(&amp;mut self) -&gt; IterMut&lt;T&gt; { let mut deque = VecDeque::new(); self.root.as_mut().map(|root| deque.push_front(root.iter_mut())); IterMut(deque) } } impl&lt;T&gt; Node&lt;T&gt; { pub fn iter_mut(&amp;mut self) -&gt; NodeIterMut&lt;T&gt; { NodeIterMut { elem: Some(&amp;mut self.elem), left: self.left.as_mut().map(|node| &amp;mut **node), right: self.right.as_mut().map(|node| &amp;mut **node), } } } impl&lt;&#39;a, T&gt; Iterator for NodeIterMut&lt;&#39;a, T&gt; { type Item = State&lt;&#39;a, T&gt;; fn next(&amp;mut self) -&gt; Option&lt;Self::Item&gt; { match self.left.take() { Some(node) =&gt; Some(State::Node(node)), None =&gt; match self.elem.take() { Some(elem) =&gt; Some(State::Elem(elem)), None =&gt; match self.right.take() { Some(node) =&gt; Some(State::Node(node)), None =&gt; None, } } } } } impl&lt;&#39;a, T&gt; DoubleEndedIterator for NodeIterMut&lt;&#39;a, T&gt; { fn next_back(&amp;mut self) -&gt; Option&lt;Self::Item&gt; { match self.right.take() { Some(node) =&gt; Some(State::Node(node)), None =&gt; match self.elem.take() { Some(elem) =&gt; Some(State::Elem(elem)), None =&gt; match self.left.take() { Some(node) =&gt; Some(State::Node(node)), None =&gt; None, } } } } } impl&lt;&#39;a, T&gt; Iterator for IterMut&lt;&#39;a, T&gt; { type Item = &amp;&#39;a mut T; fn next(&amp;mut self) -&gt; Option&lt;Self::Item&gt; { loop { match self.0.front_mut().and_then(|node_it| node_it.next()) { Some(State::Elem(elem)) =&gt; return Some(elem), Some(State::Node(node)) =&gt; self.0.push_front(node.iter_mut()), None =&gt; if let None = self.0.pop_front() { return None }, } } } } impl&lt;&#39;a, T&gt; DoubleEndedIterator for IterMut&lt;&#39;a, T&gt; { fn next_back(&amp;mut self) -&gt; Option&lt;Self::Item&gt; { loop { match self.0.back_mut().and_then(|node_it| node_it.next_back()) { Some(State::Elem(elem)) =&gt; return Some(elem), Some(State::Node(node)) =&gt; self.0.push_back(node.iter_mut()), None =&gt; if let None = self.0.pop_back() { return None }, } } } } </span><pre class='rust rust-example-rendered'> <span class='kw'>use</span> <span class='ident'>std</span>::<span class='ident'>collections</span>::<span class='ident'>VecDeque</span>; <span class='kw'>type</span> <span class='ident'>Link</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> <span class='op'>=</span> <span class='prelude-ty'>Option</span><span class='op'>&lt;</span><span class='ident'>Box</span><span class='op'>&lt;</span><span class='ident'>Node</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;&gt;</span><span class='op'>&gt;</span>; <span class='kw'>struct</span> <span class='ident'>Node</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> { <span class='ident'>elem</span>: <span class='ident'>T</span>, <span class='ident'>left</span>: <span class='ident'>Link</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span>, <span class='ident'>right</span>: <span class='ident'>Link</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span>, } <span class='kw'>pub</span> <span class='kw'>struct</span> <span class='ident'>Tree</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> { <span class='ident'>root</span>: <span class='ident'>Link</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span>, } <span class='kw'>struct</span> <span class='ident'>NodeIterMut</span><span class='op'>&lt;</span><span class='lifetime'>&#39;a</span>, <span class='ident'>T</span>: <span class='lifetime'>&#39;a</span><span class='op'>&gt;</span> { <span class='ident'>elem</span>: <span class='prelude-ty'>Option</span><span class='op'>&lt;</span><span class='kw-2'>&amp;</span><span class='lifetime'>&#39;a</span> <span class='kw-2'>mut</span> <span class='ident'>T</span><span class='op'>&gt;</span>, <span class='ident'>left</span>: <span class='prelude-ty'>Option</span><span class='op'>&lt;</span><span class='kw-2'>&amp;</span><span class='lifetime'>&#39;a</span> <span class='kw-2'>mut</span> <span class='ident'>Node</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;&gt;</span>, <span class='ident'>right</span>: <span class='prelude-ty'>Option</span><span class='op'>&lt;</span><span class='kw-2'>&amp;</span><span class='lifetime'>&#39;a</span> <span class='kw-2'>mut</span> <span class='ident'>Node</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;&gt;</span>, } <span class='kw'>enum</span> <span class='ident'>State</span><span class='op'>&lt;</span><span class='lifetime'>&#39;a</span>, <span class='ident'>T</span>: <span class='lifetime'>&#39;a</span><span class='op'>&gt;</span> { <span class='ident'>Elem</span>(<span class='kw-2'>&amp;</span><span class='lifetime'>&#39;a</span> <span class='kw-2'>mut</span> <span class='ident'>T</span>), <span class='ident'>Node</span>(<span class='kw-2'>&amp;</span><span class='lifetime'>&#39;a</span> <span class='kw-2'>mut</span> <span class='ident'>Node</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span>), } <span class='kw'>pub</span> <span class='kw'>struct</span> <span class='ident'>IterMut</span><span class='op'>&lt;</span><span class='lifetime'>&#39;a</span>, <span class='ident'>T</span>: <span class='lifetime'>&#39;a</span><span class='op'>&gt;</span>(<span class='ident'>VecDeque</span><span class='op'>&lt;</span><span class='ident'>NodeIterMut</span><span class='op'>&lt;</span><span class='lifetime'>&#39;a</span>, <span class='ident'>T</span><span class='op'>&gt;&gt;</span>); <span class='kw'>impl</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> <span class='ident'>Tree</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> { <span class='kw'>pub</span> <span class='kw'>fn</span> <span class='ident'>iter_mut</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>) <span class='op'>-&gt;</span> <span class='ident'>IterMut</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> { <span class='kw'>let</span> <span class='kw-2'>mut</span> <span class='ident'>deque</span> <span class='op'>=</span> <span class='ident'>VecDeque</span>::<span class='ident'>new</span>(); <span class='self'>self</span>.<span class='ident'>root</span>.<span class='ident'>as_mut</span>().<span class='ident'>map</span>(<span class='op'>|</span><span class='ident'>root</span><span class='op'>|</span> <span class='ident'>deque</span>.<span class='ident'>push_front</span>(<span class='ident'>root</span>.<span class='ident'>iter_mut</span>())); <span class='ident'>IterMut</span>(<span class='ident'>deque</span>) } } <span class='kw'>impl</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> <span class='ident'>Node</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> { <span class='kw'>pub</span> <span class='kw'>fn</span> <span class='ident'>iter_mut</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>) <span class='op'>-&gt;</span> <span class='ident'>NodeIterMut</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> { <span class='ident'>NodeIterMut</span> { <span class='ident'>elem</span>: <span class='prelude-val'>Some</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>.<span class='ident'>elem</span>), <span class='ident'>left</span>: <span class='self'>self</span>.<span class='ident'>left</span>.<span class='ident'>as_mut</span>().<span class='ident'>map</span>(<span class='op'>|</span><span class='ident'>node</span><span class='op'>|</span> <span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='op'>*</span><span class='op'>*</span><span class='ident'>node</span>), <span class='ident'>right</span>: <span class='self'>self</span>.<span class='ident'>right</span>.<span class='ident'>as_mut</span>().<span class='ident'>map</span>(<span class='op'>|</span><span class='ident'>node</span><span class='op'>|</span> <span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='op'>*</span><span class='op'>*</span><span class='ident'>node</span>), } } } <span class='kw'>impl</span><span class='op'>&lt;</span><span class='lifetime'>&#39;a</span>, <span class='ident'>T</span><span class='op'>&gt;</span> <span class='ident'>Iterator</span> <span class='kw'>for</span> <span class='ident'>NodeIterMut</span><span class='op'>&lt;</span><span class='lifetime'>&#39;a</span>, <span class='ident'>T</span><span class='op'>&gt;</span> { <span class='kw'>type</span> <span class='ident'>Item</span> <span class='op'>=</span> <span class='ident'>State</span><span class='op'>&lt;</span><span class='lifetime'>&#39;a</span>, <span class='ident'>T</span><span class='op'>&gt;</span>; <span class='kw'>fn</span> <span class='ident'>next</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>) <span class='op'>-&gt;</span> <span class='prelude-ty'>Option</span><span class='op'>&lt;</span><span class='self'>Self</span>::<span class='ident'>Item</span><span class='op'>&gt;</span> { <span class='kw'>match</span> <span class='self'>self</span>.<span class='ident'>left</span>.<span class='ident'>take</span>() { <span class='prelude-val'>Some</span>(<span class='ident'>node</span>) <span class='op'>=&gt;</span> <span class='prelude-val'>Some</span>(<span class='ident'>State</span>::<span class='ident'>Node</span>(<span class='ident'>node</span>)), <span class='prelude-val'>None</span> <span class='op'>=&gt;</span> <span class='kw'>match</span> <span class='self'>self</span>.<span class='ident'>elem</span>.<span class='ident'>take</span>() { <span class='prelude-val'>Some</span>(<span class='ident'>elem</span>) <span class='op'>=&gt;</span> <span class='prelude-val'>Some</span>(<span class='ident'>State</span>::<span class='ident'>Elem</span>(<span class='ident'>elem</span>)), <span class='prelude-val'>None</span> <span class='op'>=&gt;</span> <span class='kw'>match</span> <span class='self'>self</span>.<span class='ident'>right</span>.<span class='ident'>take</span>() { <span class='prelude-val'>Some</span>(<span class='ident'>node</span>) <span class='op'>=&gt;</span> <span class='prelude-val'>Some</span>(<span class='ident'>State</span>::<span class='ident'>Node</span>(<span class='ident'>node</span>)), <span class='prelude-val'>None</span> <span class='op'>=&gt;</span> <span class='prelude-val'>None</span>, } } } } } <span class='kw'>impl</span><span class='op'>&lt;</span><span class='lifetime'>&#39;a</span>, <span class='ident'>T</span><span class='op'>&gt;</span> <span class='ident'>DoubleEndedIterator</span> <span class='kw'>for</span> <span class='ident'>NodeIterMut</span><span class='op'>&lt;</span><span class='lifetime'>&#39;a</span>, <span class='ident'>T</span><span class='op'>&gt;</span> { <span class='kw'>fn</span> <span class='ident'>next_back</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>) <span class='op'>-&gt;</span> <span class='prelude-ty'>Option</span><span class='op'>&lt;</span><span class='self'>Self</span>::<span class='ident'>Item</span><span class='op'>&gt;</span> { <span class='kw'>match</span> <span class='self'>self</span>.<span class='ident'>right</span>.<span class='ident'>take</span>() { <span class='prelude-val'>Some</span>(<span class='ident'>node</span>) <span class='op'>=&gt;</span> <span class='prelude-val'>Some</span>(<span class='ident'>State</span>::<span class='ident'>Node</span>(<span class='ident'>node</span>)), <span class='prelude-val'>None</span> <span class='op'>=&gt;</span> <span class='kw'>match</span> <span class='self'>self</span>.<span class='ident'>elem</span>.<span class='ident'>take</span>() { <span class='prelude-val'>Some</span>(<span class='ident'>elem</span>) <span class='op'>=&gt;</span> <span class='prelude-val'>Some</span>(<span class='ident'>State</span>::<span class='ident'>Elem</span>(<span class='ident'>elem</span>)), <span class='prelude-val'>None</span> <span class='op'>=&gt;</span> <span class='kw'>match</span> <span class='self'>self</span>.<span class='ident'>left</span>.<span class='ident'>take</span>() { <span class='prelude-val'>Some</span>(<span class='ident'>node</span>) <span class='op'>=&gt;</span> <span class='prelude-val'>Some</span>(<span class='ident'>State</span>::<span class='ident'>Node</span>(<span class='ident'>node</span>)), <span class='prelude-val'>None</span> <span class='op'>=&gt;</span> <span class='prelude-val'>None</span>, } } } } } <span class='kw'>impl</span><span class='op'>&lt;</span><span class='lifetime'>&#39;a</span>, <span class='ident'>T</span><span class='op'>&gt;</span> <span class='ident'>Iterator</span> <span class='kw'>for</span> <span class='ident'>IterMut</span><span class='op'>&lt;</span><span class='lifetime'>&#39;a</span>, <span class='ident'>T</span><span class='op'>&gt;</span> { <span class='kw'>type</span> <span class='ident'>Item</span> <span class='op'>=</span> <span class='kw-2'>&amp;</span><span class='lifetime'>&#39;a</span> <span class='kw-2'>mut</span> <span class='ident'>T</span>; <span class='kw'>fn</span> <span class='ident'>next</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>) <span class='op'>-&gt;</span> <span class='prelude-ty'>Option</span><span class='op'>&lt;</span><span class='self'>Self</span>::<span class='ident'>Item</span><span class='op'>&gt;</span> { <span class='kw'>loop</span> { <span class='kw'>match</span> <span class='self'>self</span>.<span class='number'>0</span>.<span class='ident'>front_mut</span>().<span class='ident'>and_then</span>(<span class='op'>|</span><span class='ident'>node_it</span><span class='op'>|</span> <span class='ident'>node_it</span>.<span class='ident'>next</span>()) { <span class='prelude-val'>Some</span>(<span class='ident'>State</span>::<span class='ident'>Elem</span>(<span class='ident'>elem</span>)) <span class='op'>=&gt;</span> <span class='kw'>return</span> <span class='prelude-val'>Some</span>(<span class='ident'>elem</span>), <span class='prelude-val'>Some</span>(<span class='ident'>State</span>::<span class='ident'>Node</span>(<span class='ident'>node</span>)) <span class='op'>=&gt;</span> <span class='self'>self</span>.<span class='number'>0</span>.<span class='ident'>push_front</span>(<span class='ident'>node</span>.<span class='ident'>iter_mut</span>()), <span class='prelude-val'>None</span> <span class='op'>=&gt;</span> <span class='kw'>if</span> <span class='kw'>let</span> <span class='prelude-val'>None</span> <span class='op'>=</span> <span class='self'>self</span>.<span class='number'>0</span>.<span class='ident'>pop_front</span>() { <span class='kw'>return</span> <span class='prelude-val'>None</span> }, } } } } <span class='kw'>impl</span><span class='op'>&lt;</span><span class='lifetime'>&#39;a</span>, <span class='ident'>T</span><span class='op'>&gt;</span> <span class='ident'>DoubleEndedIterator</span> <span class='kw'>for</span> <span class='ident'>IterMut</span><span class='op'>&lt;</span><span class='lifetime'>&#39;a</span>, <span class='ident'>T</span><span class='op'>&gt;</span> { <span class='kw'>fn</span> <span class='ident'>next_back</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>) <span class='op'>-&gt;</span> <span class='prelude-ty'>Option</span><span class='op'>&lt;</span><span class='self'>Self</span>::<span class='ident'>Item</span><span class='op'>&gt;</span> { <span class='kw'>loop</span> { <span class='kw'>match</span> <span class='self'>self</span>.<span class='number'>0</span>.<span class='ident'>back_mut</span>().<span class='ident'>and_then</span>(<span class='op'>|</span><span class='ident'>node_it</span><span class='op'>|</span> <span class='ident'>node_it</span>.<span class='ident'>next_back</span>()) { <span class='prelude-val'>Some</span>(<span class='ident'>State</span>::<span class='ident'>Elem</span>(<span class='ident'>elem</span>)) <span class='op'>=&gt;</span> <span class='kw'>return</span> <span class='prelude-val'>Some</span>(<span class='ident'>elem</span>), <span class='prelude-val'>Some</span>(<span class='ident'>State</span>::<span class='ident'>Node</span>(<span class='ident'>node</span>)) <span class='op'>=&gt;</span> <span class='self'>self</span>.<span class='number'>0</span>.<span class='ident'>push_back</span>(<span class='ident'>node</span>.<span class='ident'>iter_mut</span>()), <span class='prelude-val'>None</span> <span class='op'>=&gt;</span> <span class='kw'>if</span> <span class='kw'>let</span> <span class='prelude-val'>None</span> <span class='op'>=</span> <span class='self'>self</span>.<span class='number'>0</span>.<span class='ident'>pop_back</span>() { <span class='kw'>return</span> <span class='prelude-val'>None</span> }, } } } }</pre> <p>All of these are completely safe and work on stable Rust! This ultimately falls out of the simple struct case we saw before: Rust understands that you can safely split a mutable reference into subfields. We can then encode permanently consuming a reference via Options (or in the case of slices, replacing with an empty slice).</p> <script type="text/javascript"> window.playgroundUrl = "https://play.rust-lang.org"; </script> <script src='rustbook.js'></script> <script src='playpen.js'></script> </div></div> </body> </html> <|start_filename|>docs/1.9/nomicon/coercions.html<|end_filename|> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="generator" content="rustdoc"> <title>Coercions</title> <link rel="stylesheet" type="text/css" href="rustbook.css"> <meta name="robots" content="noindex"> </head> <body class="rustdoc"> <!--[if lte IE 8]> <div class="warning"> This old browser is unsupported and will most likely display funky things. </div> <![endif]--> <div id="nav"> <button id="toggle-nav"> <span class="sr-only">Toggle navigation</span> <span class="bar"></span> <span class="bar"></span> <span class="bar"></span> </button> </div> <div id='toc' class='mobile-hidden'> <ul class='chapter'> <li><a href='README.html'><b>1.</b> Introduction</a> </li> <li><a href='meet-safe-and-unsafe.html'><b>2.</b> Meet Safe and Unsafe</a> <ul class='section'> <li><a href='safe-unsafe-meaning.html'><b>2.1.</b> How Safe and Unsafe Interact</a> </li> <li><a href='working-with-unsafe.html'><b>2.2.</b> Working with Unsafe</a> </li> </ul> </li> <li><a href='data.html'><b>3.</b> Data Layout</a> <ul class='section'> <li><a href='repr-rust.html'><b>3.1.</b> repr(Rust)</a> </li> <li><a href='exotic-sizes.html'><b>3.2.</b> Exotically Sized Types</a> </li> <li><a href='other-reprs.html'><b>3.3.</b> Other reprs</a> </li> </ul> </li> <li><a href='ownership.html'><b>4.</b> Ownership</a> <ul class='section'> <li><a href='references.html'><b>4.1.</b> References</a> </li> <li><a href='lifetimes.html'><b>4.2.</b> Lifetimes</a> </li> <li><a href='lifetime-mismatch.html'><b>4.3.</b> Limits of Lifetimes</a> </li> <li><a href='lifetime-elision.html'><b>4.4.</b> Lifetime Elision</a> </li> <li><a href='unbounded-lifetimes.html'><b>4.5.</b> Unbounded Lifetimes</a> </li> <li><a href='hrtb.html'><b>4.6.</b> Higher-Rank Trait Bounds</a> </li> <li><a href='subtyping.html'><b>4.7.</b> Subtyping and Variance</a> </li> <li><a href='dropck.html'><b>4.8.</b> Drop Check</a> </li> <li><a href='phantom-data.html'><b>4.9.</b> PhantomData</a> </li> <li><a href='borrow-splitting.html'><b>4.10.</b> Splitting Borrows</a> </li> </ul> </li> <li><a href='conversions.html'><b>5.</b> Type Conversions</a> <ul class='section'> <li><a class='active' href='coercions.html'><b>5.1.</b> Coercions</a> </li> <li><a href='dot-operator.html'><b>5.2.</b> The Dot Operator</a> </li> <li><a href='casts.html'><b>5.3.</b> Casts</a> </li> <li><a href='transmutes.html'><b>5.4.</b> Transmutes</a> </li> </ul> </li> <li><a href='uninitialized.html'><b>6.</b> Uninitialized Memory</a> <ul class='section'> <li><a href='checked-uninit.html'><b>6.1.</b> Checked</a> </li> <li><a href='drop-flags.html'><b>6.2.</b> Drop Flags</a> </li> <li><a href='unchecked-uninit.html'><b>6.3.</b> Unchecked</a> </li> </ul> </li> <li><a href='obrm.html'><b>7.</b> Ownership Based Resource Management</a> <ul class='section'> <li><a href='constructors.html'><b>7.1.</b> Constructors</a> </li> <li><a href='destructors.html'><b>7.2.</b> Destructors</a> </li> <li><a href='leaking.html'><b>7.3.</b> Leaking</a> </li> </ul> </li> <li><a href='unwinding.html'><b>8.</b> Unwinding</a> <ul class='section'> <li><a href='exception-safety.html'><b>8.1.</b> Exception Safety</a> </li> <li><a href='poisoning.html'><b>8.2.</b> Poisoning</a> </li> </ul> </li> <li><a href='concurrency.html'><b>9.</b> Concurrency</a> <ul class='section'> <li><a href='races.html'><b>9.1.</b> Races</a> </li> <li><a href='send-and-sync.html'><b>9.2.</b> Send and Sync</a> </li> <li><a href='atomics.html'><b>9.3.</b> Atomics</a> </li> </ul> </li> <li><a href='vec.html'><b>10.</b> Implementing Vec</a> <ul class='section'> <li><a href='vec-layout.html'><b>10.1.</b> Layout</a> </li> <li><a href='vec-alloc.html'><b>10.2.</b> Allocating</a> </li> <li><a href='vec-push-pop.html'><b>10.3.</b> Push and Pop</a> </li> <li><a href='vec-dealloc.html'><b>10.4.</b> Deallocating</a> </li> <li><a href='vec-deref.html'><b>10.5.</b> Deref</a> </li> <li><a href='vec-insert-remove.html'><b>10.6.</b> Insert and Remove</a> </li> <li><a href='vec-into-iter.html'><b>10.7.</b> IntoIter</a> </li> <li><a href='vec-raw.html'><b>10.8.</b> RawVec</a> </li> <li><a href='vec-drain.html'><b>10.9.</b> Drain</a> </li> <li><a href='vec-zsts.html'><b>10.10.</b> Handling Zero-Sized Types</a> </li> <li><a href='vec-final.html'><b>10.11.</b> Final Code</a> </li> </ul> </li> <li><a href='arc-and-mutex.html'><b>11.</b> Implementing Arc and Mutex</a> </li> </ul> </div> <div id='page-wrapper'> <div id='page'> <blockquote class="header-caveat"> <p> <strong>注意: <a href="https://doc.rust-jp.rs/book-ja/">最新版のドキュメントをご覧ください。</a></strong>この第1版ドキュメントは古くなっており、最新情報が反映されていません。リンク先のドキュメントが現在の Rust の最新のドキュメントです。 </p> </blockquote> <h1 class="title">Coercions</h1> <p>Types can implicitly be coerced to change in certain contexts. These changes are generally just <em>weakening</em> of types, largely focused around pointers and lifetimes. They mostly exist to make Rust &quot;just work&quot; in more cases, and are largely harmless.</p> <p>Here&#39;s all the kinds of coercion:</p> <p>Coercion is allowed between the following types:</p> <ul> <li>Transitivity: <code>T_1</code> to <code>T_3</code> where <code>T_1</code> coerces to <code>T_2</code> and <code>T_2</code> coerces to <code>T_3</code></li> <li>Pointer Weakening: <ul> <li><code>&amp;mut T</code> to <code>&amp;T</code></li> <li><code>*mut T</code> to <code>*const T</code></li> <li><code>&amp;T</code> to <code>*const T</code></li> <li><code>&amp;mut T</code> to <code>*mut T</code></li> </ul></li> <li>Unsizing: <code>T</code> to <code>U</code> if <code>T</code> implements <code>CoerceUnsized&lt;U&gt;</code></li> </ul> <p><code>CoerceUnsized&lt;Pointer&lt;U&gt;&gt; for Pointer&lt;T&gt; where T: Unsize&lt;U&gt;</code> is implemented for all pointer types (including smart pointers like Box and Rc). Unsize is only implemented automatically, and enables the following transformations:</p> <ul> <li><code>[T; n]</code> =&gt; <code>[T]</code></li> <li><code>T</code> =&gt; <code>Trait</code> where <code>T: Trait</code></li> <li><code>Foo&lt;..., T, ...&gt;</code> =&gt; <code>Foo&lt;..., U, ...&gt;</code> where: <ul> <li><code>T: Unsize&lt;U&gt;</code></li> <li><code>Foo</code> is a struct</li> <li>Only the last field of <code>Foo</code> has type <code>T</code></li> <li><code>T</code> is not part of the type of any other fields</li> </ul></li> </ul> <p>Coercions occur at a <em>coercion site</em>. Any location that is explicitly typed will cause a coercion to its type. If inference is necessary, the coercion will not be performed. Exhaustively, the coercion sites for an expression <code>e</code> to type <code>U</code> are:</p> <ul> <li>let statements, statics, and consts: <code>let x: U = e</code></li> <li>Arguments to functions: <code>takes_a_U(e)</code></li> <li>Any expression that will be returned: <code>fn foo() -&gt; U { e }</code></li> <li>Struct literals: <code>Foo { some_u: e }</code></li> <li>Array literals: <code>let x: [U; 10] = [e, ..]</code></li> <li>Tuple literals: <code>let x: (U, ..) = (e, ..)</code></li> <li>The last expression in a block: <code>let x: U = { ..; e }</code></li> </ul> <p>Note that we do not perform coercions when matching traits (except for receivers, see below). If there is an impl for some type <code>U</code> and <code>T</code> coerces to <code>U</code>, that does not constitute an implementation for <code>T</code>. For example, the following will not type check, even though it is OK to coerce <code>t</code> to <code>&amp;T</code> and there is an impl for <code>&amp;T</code>:</p> <span class='rusttest'>trait Trait {} fn foo&lt;X: Trait&gt;(t: X) {} impl&lt;&#39;a&gt; Trait for &amp;&#39;a i32 {} fn main() { let t: &amp;mut i32 = &amp;mut 0; foo(t); } </span><pre class='rust rust-example-rendered'> <span class='kw'>trait</span> <span class='ident'>Trait</span> {} <span class='kw'>fn</span> <span class='ident'>foo</span><span class='op'>&lt;</span><span class='ident'>X</span>: <span class='ident'>Trait</span><span class='op'>&gt;</span>(<span class='ident'>t</span>: <span class='ident'>X</span>) {} <span class='kw'>impl</span><span class='op'>&lt;</span><span class='lifetime'>&#39;a</span><span class='op'>&gt;</span> <span class='ident'>Trait</span> <span class='kw'>for</span> <span class='kw-2'>&amp;</span><span class='lifetime'>&#39;a</span> <span class='ident'>i32</span> {} <span class='kw'>fn</span> <span class='ident'>main</span>() { <span class='kw'>let</span> <span class='ident'>t</span>: <span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='ident'>i32</span> <span class='op'>=</span> <span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='number'>0</span>; <span class='ident'>foo</span>(<span class='ident'>t</span>); }</pre> <pre><code class="language-text">&lt;anon&gt;:10:5: 10:8 error: the trait `Trait` is not implemented for the type `&amp;mut i32` [E0277] &lt;anon&gt;:10 foo(t); ^~~ </code></pre> <script type="text/javascript"> window.playgroundUrl = "https://play.rust-lang.org"; </script> <script src='rustbook.js'></script> <script src='playpen.js'></script> </div></div> </body> </html> <|start_filename|>docs/1.9/book/variable-bindings.html<|end_filename|> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="generator" content="rustdoc"> <title>変数束縛</title> <link rel="stylesheet" type="text/css" href="rustbook.css"> <meta name="robots" content="noindex"> </head> <body class="rustdoc"> <!--[if lte IE 8]> <div class="warning"> This old browser is unsupported and will most likely display funky things. </div> <![endif]--> <div id="nav"> <button id="toggle-nav"> <span class="sr-only">Toggle navigation</span> <span class="bar"></span> <span class="bar"></span> <span class="bar"></span> </button> </div> <div id='toc' class='mobile-hidden'> <ul class='chapter'> <li><a href='README.html'><b>1.</b> Introduction</a> </li> <li><a href='getting-started.html'><b>2.</b> はじめる</a> </li> <li><a href='guessing-game.html'><b>3.</b> チュートリアル:数当てゲーム</a> </li> <li><a href='syntax-and-semantics.html'><b>4.</b> シンタックスとセマンティクス</a> <ul class='section'> <li><a class='active' href='variable-bindings.html'><b>4.1.</b> 変数束縛</a> </li> <li><a href='functions.html'><b>4.2.</b> 関数</a> </li> <li><a href='primitive-types.html'><b>4.3.</b> プリミティブ型</a> </li> <li><a href='comments.html'><b>4.4.</b> コメント</a> </li> <li><a href='if.html'><b>4.5.</b> if</a> </li> <li><a href='loops.html'><b>4.6.</b> ループ</a> </li> <li><a href='vectors.html'><b>4.7.</b> ベクタ</a> </li> <li><a href='ownership.html'><b>4.8.</b> 所有権</a> </li> <li><a href='references-and-borrowing.html'><b>4.9.</b> 参照と借用</a> </li> <li><a href='lifetimes.html'><b>4.10.</b> ライフタイム</a> </li> <li><a href='mutability.html'><b>4.11.</b> ミュータビリティ</a> </li> <li><a href='structs.html'><b>4.12.</b> 構造体</a> </li> <li><a href='enums.html'><b>4.13.</b> 列挙型</a> </li> <li><a href='match.html'><b>4.14.</b> マッチ</a> </li> <li><a href='patterns.html'><b>4.15.</b> パターン</a> </li> <li><a href='method-syntax.html'><b>4.16.</b> メソッド構文</a> </li> <li><a href='strings.html'><b>4.17.</b> 文字列</a> </li> <li><a href='generics.html'><b>4.18.</b> ジェネリクス</a> </li> <li><a href='traits.html'><b>4.19.</b> トレイト</a> </li> <li><a href='drop.html'><b>4.20.</b> Drop</a> </li> <li><a href='if-let.html'><b>4.21.</b> if let</a> </li> <li><a href='trait-objects.html'><b>4.22.</b> トレイトオブジェクト</a> </li> <li><a href='closures.html'><b>4.23.</b> クロージャ</a> </li> <li><a href='ufcs.html'><b>4.24.</b> 共通の関数呼出構文</a> </li> <li><a href='crates-and-modules.html'><b>4.25.</b> クレートとモジュール</a> </li> <li><a href='const-and-static.html'><b>4.26.</b> `const` と `static`</a> </li> <li><a href='attributes.html'><b>4.27.</b> アトリビュート</a> </li> <li><a href='type-aliases.html'><b>4.28.</b> `type` エイリアス</a> </li> <li><a href='casting-between-types.html'><b>4.29.</b> 型間のキャスト</a> </li> <li><a href='associated-types.html'><b>4.30.</b> 関連型</a> </li> <li><a href='unsized-types.html'><b>4.31.</b> サイズ不定型</a> </li> <li><a href='operators-and-overloading.html'><b>4.32.</b> 演算子とオーバーロード</a> </li> <li><a href='deref-coercions.html'><b>4.33.</b> Derefによる型強制</a> </li> <li><a href='macros.html'><b>4.34.</b> マクロ</a> </li> <li><a href='raw-pointers.html'><b>4.35.</b> 生ポインタ</a> </li> <li><a href='unsafe.html'><b>4.36.</b> `unsafe`</a> </li> </ul> </li> <li><a href='effective-rust.html'><b>5.</b> Effective Rust</a> <ul class='section'> <li><a href='the-stack-and-the-heap.html'><b>5.1.</b> スタックとヒープ</a> </li> <li><a href='testing.html'><b>5.2.</b> テスト</a> </li> <li><a href='conditional-compilation.html'><b>5.3.</b> 条件付きコンパイル</a> </li> <li><a href='documentation.html'><b>5.4.</b> ドキュメント</a> </li> <li><a href='iterators.html'><b>5.5.</b> イテレータ</a> </li> <li><a href='concurrency.html'><b>5.6.</b> 並行性</a> </li> <li><a href='error-handling.html'><b>5.7.</b> エラーハンドリング</a> </li> <li><a href='choosing-your-guarantees.html'><b>5.8.</b> 保証を選ぶ</a> </li> <li><a href='ffi.html'><b>5.9.</b> 他言語関数インターフェース</a> </li> <li><a href='borrow-and-asref.html'><b>5.10.</b> BorrowとAsRef</a> </li> <li><a href='release-channels.html'><b>5.11.</b> リリースチャネル</a> </li> <li><a href='using-rust-without-the-standard-library.html'><b>5.12.</b> 標準ライブラリ無しでRustを使う</a> </li> </ul> </li> <li><a href='nightly-rust.html'><b>6.</b> Nightly Rust</a> <ul class='section'> <li><a href='compiler-plugins.html'><b>6.1.</b> コンパイラプラグイン</a> </li> <li><a href='inline-assembly.html'><b>6.2.</b> インラインアセンブリ</a> </li> <li><a href='no-stdlib.html'><b>6.3.</b> No stdlib</a> </li> <li><a href='intrinsics.html'><b>6.4.</b> Intrinsic</a> </li> <li><a href='lang-items.html'><b>6.5.</b> 言語アイテム</a> </li> <li><a href='advanced-linking.html'><b>6.6.</b> 高度なリンキング</a> </li> <li><a href='benchmark-tests.html'><b>6.7.</b> ベンチマークテスト</a> </li> <li><a href='box-syntax-and-patterns.html'><b>6.8.</b> Box構文とパターン</a> </li> <li><a href='slice-patterns.html'><b>6.9.</b> スライスパターン</a> </li> <li><a href='associated-constants.html'><b>6.10.</b> 関連定数</a> </li> <li><a href='custom-allocators.html'><b>6.11.</b> カスタムアロケータ</a> </li> </ul> </li> <li><a href='glossary.html'><b>7.</b> 用語集</a> </li> <li><a href='syntax-index.html'><b>8.</b> 構文の索引</a> </li> <li><a href='bibliography.html'><b>9.</b> 関係書目</a> </li> </ul> </div> <div id='page-wrapper'> <div id='page'> <blockquote class="header-caveat"> <p> <strong>注意: <a href="https://doc.rust-jp.rs/book-ja/">最新版のドキュメントをご覧ください。</a></strong>この第1版ドキュメントは古くなっており、最新情報が反映されていません。リンク先のドキュメントが現在の Rust の最新のドキュメントです。 </p> </blockquote> <h1 class="title">変数束縛</h1> <!-- % Variable Bindings --> <!-- Virtually every non-'Hello World’ Rust program uses *variable bindings*. They --> <!-- bind some value to a name, so it can be used later. `let` is --> <!-- used to introduce a binding, like this: --> <p>事実上全ての「Hello World」でないRustのプログラムは <em>変数束縛</em> を使っています。 変数束縛は何らかの値を名前へと束縛するので、後でその値を使えます。 このように、 <code>let</code> が束縛を導入するのに使われています。</p> <blockquote> <p>訳注: 普通、束縛というときは名前 <em>を</em> 値 <em>へ</em> と束縛しますが、このドキュメントでは逆になっています。 Rustでは他の言語と違って1つの値に対して1つの名前が対応するのであえてこう書いてるのかもしれません。</p> </blockquote> <span class='rusttest'>fn main() { let x = 5; } </span><pre class='rust rust-example-rendered'> <span class='kw'>fn</span> <span class='ident'>main</span>() { <span class='kw'>let</span> <span class='ident'>x</span> <span class='op'>=</span> <span class='number'>5</span>; }</pre> <!-- Putting `fn main() {` in each example is a bit tedious, so we’ll leave that out --> <!-- in the future. If you’re following along, make sure to edit your `main()` --> <!-- function, rather than leaving it off. Otherwise, you’ll get an error. --> <p>例で毎回 <code>fn main() {</code> と書くのは長ったらしいのでこれ以後は省略します。 もし試しながら読んでいるのならそのまま書くのではなくちゃんと <code>main()</code> 関数の中身を編集するようにしてください。そうしないとエラーになります。</p> <!-- # Patterns --> <h1 id='パターン' class='section-header'><a href='#パターン'>パターン</a></h1> <!-- In many languages, a variable binding would be called a *variable*, but Rust’s --> <!-- variable bindings have a few tricks up their sleeves. For example the --> <!-- left-hand side of a `let` statement is a ‘[pattern][pattern]’, not just a --> <!-- variable name. This means we can do things like: --> <p>多くの言語では変数束縛は <em>変数</em> と呼ばれるでしょうが、Rustの変数束縛は多少皮を被せてあります。 例えば、 <code>let</code> 文の左側は「<a href="patterns.html">パターン</a>」であって、ただの変数名ではありません。 これはこのようなことができるということです。</p> <span class='rusttest'>fn main() { let (x, y) = (1, 2); }</span><pre class='rust rust-example-rendered'> <span class='kw'>let</span> (<span class='ident'>x</span>, <span class='ident'>y</span>) <span class='op'>=</span> (<span class='number'>1</span>, <span class='number'>2</span>);</pre> <!-- After this statement is evaluated, `x` will be one, and `y` will be two. --> <!-- Patterns are really powerful, and have [their own section][pattern] in the --> <!-- book. We don’t need those features for now, so we’ll keep this in the back --> <!-- of our minds as we go forward. --> <p>この文が評価されたあと、 <code>x</code> は1になり、 <code>y</code> は2になります。 パターンは本当に強力で、本書には<a href="patterns.html">パターンのセクション</a>もあります。 今のところこの機能は必要ないので頭の片隅に留めておいてだけいてください。</p> <!-- # Type annotations --> <h1 id='型アノテーション' class='section-header'><a href='#型アノテーション'>型アノテーション</a></h1> <!-- Rust is a statically typed language, which means that we specify our types up --> <!-- front, and they’re checked at compile time. So why does our first example --> <!-- compile? Well, Rust has this thing called ‘type inference’. If it can figure --> <!-- out what the type of something is, Rust doesn’t require you to actually type it --> <!-- out. --> <p>Rustは静的な型付言語であり、前もって型を与えておいて、それがコンパイル時に検査されます。 じゃあなぜ最初の例はコンパイルが通るのでしょう?ええと、Rustには「型推論」と呼ばれるものがあります。 型推論が型が何であるか判断できるなら、型を書く必要はなくなります。</p> <!-- We can add the type if we want to, though. Types come after a colon (`:`): --> <p>書きたいなら型を書くこともできます。型はコロン(<code>:</code>)のあとに書きます。</p> <span class='rusttest'>fn main() { let x: i32 = 5; }</span><pre class='rust rust-example-rendered'> <span class='kw'>let</span> <span class='ident'>x</span>: <span class='ident'>i32</span> <span class='op'>=</span> <span class='number'>5</span>;</pre> <!-- If I asked you to read this out loud to the rest of the class, you’d say “`x` --> <!-- is a binding with the type `i32` and the value `five`.” --> <p>これをクラスのみんなに聞こえるように声に出して読むなら、「 <code>x</code> は型 <code>i32</code> を持つ束縛で、値は <code>五</code> である。」となります。</p> <!-- In this case we chose to represent `x` as a 32-bit signed integer. Rust has --> <!-- many different primitive integer types. They begin with `i` for signed integers --> <!-- and `u` for unsigned integers. The possible integer sizes are 8, 16, 32, and 64 --> <!-- bits. --> <p>この場合 <code>x</code> を32bit符号付き整数として表現することを選びました。 Rustには多くのプリミティブな整数型があります。プリミティブな整数型は符号付き型は <code>i</code> 、符号無し型は <code>u</code> から始まります。 整数型として可能なサイズは8、16、32、64ビットです。</p> <!-- In future examples, we may annotate the type in a comment. The examples will --> <!-- look like this: --> <p>以後の例では型はコメントで注釈することにします。 先の例はこのようになります。</p> <span class='rusttest'>fn main() { let x = 5; // x: i32 } </span><pre class='rust rust-example-rendered'> <span class='kw'>fn</span> <span class='ident'>main</span>() { <span class='kw'>let</span> <span class='ident'>x</span> <span class='op'>=</span> <span class='number'>5</span>; <span class='comment'>// x: i32</span> }</pre> <!-- Note the similarities between this annotation and the syntax you use with --> <!-- `let`. Including these kinds of comments is not idiomatic Rust, but we'll --> <!-- occasionally include them to help you understand what the types that Rust --> <!-- infers are. --> <p>この注釈と <code>let</code> の時に使う記法の類似性に留意してください。 このようなコメントを書くのはRust的ではありませんが、時折理解の手助けのためにRustが推論する型をコメントで注釈します。</p> <!-- # Mutability --> <h1 id='可変性' class='section-header'><a href='#可変性'>可変性</a></h1> <!-- By default, bindings are *immutable*. This code will not compile: --> <p>デフォルトで、 束縛は <em>イミュータブル</em> です。このコードのコンパイルは通りません。</p> <span class='rusttest'>fn main() { let x = 5; x = 10; }</span><pre class='rust rust-example-rendered'> <span class='kw'>let</span> <span class='ident'>x</span> <span class='op'>=</span> <span class='number'>5</span>; <span class='ident'>x</span> <span class='op'>=</span> <span class='number'>10</span>;</pre> <!-- It will give you this error: --> <p>次のようなエラーが出ます。</p> <pre><code class="language-text">error: re-assignment of immutable variable `x` x = 10; ^~~~~~~ </code></pre> <blockquote> <p>訳注: <code>エラー: イミュータブルな変数 `x` に再代入しています</code></p> </blockquote> <!-- If you want a binding to be mutable, you can use `mut`: --> <p>束縛をミュータブルにしたいなら、<code>mut</code>が使えます。</p> <span class='rusttest'>fn main() { let mut x = 5; // mut x: i32 x = 10; }</span><pre class='rust rust-example-rendered'> <span class='kw'>let</span> <span class='kw-2'>mut</span> <span class='ident'>x</span> <span class='op'>=</span> <span class='number'>5</span>; <span class='comment'>// mut x: i32</span> <span class='ident'>x</span> <span class='op'>=</span> <span class='number'>10</span>;</pre> <!-- There is no single reason that bindings are immutable by default, but we can --> <!-- think about it through one of Rust’s primary focuses: safety. If you forget to --> <!-- say `mut`, the compiler will catch it, and let you know that you have mutated --> <!-- something you may not have intended to mutate. If bindings were mutable by --> <!-- default, the compiler would not be able to tell you this. If you _did_ intend --> <!-- mutation, then the solution is quite easy: add `mut`. --> <p>束縛がデフォルトでイミュータブルであるのは複合的な理由によるものですが、Rustの主要な焦点、安全性の一環だと考えることができます。 もし <code>mut</code> を忘れたらコンパイラが捕捉して、変更するつもりでなかったものを変更した旨を教えてくれます。 束縛がデフォルトでミュータブルだったらコンパイラはこれを捕捉できません。 もし <em>本当に</em> 変更を意図していたのなら話は簡単です。 <code>mut</code> をつけ加えればいいのです。</p> <!-- There are other good reasons to avoid mutable state when possible, but they’re --> <!-- out of the scope of this guide. In general, you can often avoid explicit --> <!-- mutation, and so it is preferable in Rust. That said, sometimes, mutation is --> <!-- what you need, so it’s not verboten. --> <p>可能な時にはミュータブルを避けた方が良い理由は他にもあるのですがそれはこのガイドの範囲を越えています。 一般に、明示的な変更は避けられることが多いのでRustでもそうした方が良いのです。 しかし変更が本当に必要なこともあるという意味で、厳禁という訳ではないのです。</p> <!-- # Initializing bindings --> <h1 id='束縛を初期化する' class='section-header'><a href='#束縛を初期化する'>束縛を初期化する</a></h1> <!-- Rust variable bindings have one more aspect that differs from other languages: --> <!-- bindings are required to be initialized with a value before you're allowed to --> <!-- use them. --> <p>Rustの束縛はもう1つ他の言語と異る点があります。束縛を使う前に値で初期化されている必要があるのです。</p> <!-- Let’s try it out. Change your `src/main.rs` file to look like this: --> <p>試してみましょう。 <code>src/main.rs</code> をいじってこのようにしてみてください。</p> <span class='rusttest'>fn main() { let x: i32; println!(&quot;Hello world!&quot;); } </span><pre class='rust rust-example-rendered'> <span class='kw'>fn</span> <span class='ident'>main</span>() { <span class='kw'>let</span> <span class='ident'>x</span>: <span class='ident'>i32</span>; <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;Hello world!&quot;</span>); }</pre> <!-- You can use `cargo build` on the command line to build it. You’ll get a --> <!-- warning, but it will still print "Hello, world!": --> <p>コマンドラインで <code>cargo build</code> を使ってビルドできます。 警告が出ますが、それでもまだ「Hello, world!」は表示されます。</p> <pre><code class="language-text"> Compiling hello_world v0.0.1 (file:///home/you/projects/hello_world) src/main.rs:2:9: 2:10 warning: unused variable: `x`, #[warn(unused_variable)] on by default src/main.rs:2 let x: i32; ^ </code></pre> <!-- Rust warns us that we never use the variable binding, but since we never use --> <!-- it, no harm, no foul. Things change if we try to actually use this `x`, --> <!-- however. Let’s do that. Change your program to look like this: --> <p>Rustは一度も使われない変数について警告を出しますが、一度も使われないので人畜無害です。 ところがこの <code>x</code> を使おうとすると事は一変します。やってみましょう。 プログラムをこのように変更してください。</p> <span class='rusttest'>fn main() { let x: i32; println!(&quot;The value of x is: {}&quot;, x); } </span><pre class='rust rust-example-rendered'> <span class='kw'>fn</span> <span class='ident'>main</span>() { <span class='kw'>let</span> <span class='ident'>x</span>: <span class='ident'>i32</span>; <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;The value of x is: {}&quot;</span>, <span class='ident'>x</span>); }</pre> <!-- And try to build it. You’ll get an error: --> <p>そしてビルドしてみてください。このようなエラーが出るはずです。</p> <pre><code class="language-bash">$ cargo build Compiling hello_world v0.0.1 (file:///home/you/projects/hello_world) src/main.rs:4:39: 4:40 error: use of possibly uninitialized variable: `x` src/main.rs:4 println!(&quot;The value of x is: {}&quot;, x); ^ note: in expansion of format_args! &lt;std macros&gt;:2:23: 2:77 note: expansion site &lt;std macros&gt;:1:1: 3:2 note: in expansion of println! src/main.rs:4:5: 4:42 note: expansion site error: aborting due to previous error Could not compile `hello_world`. </code></pre> <!-- Rust will not let us use a value that has not been initialized. Next, let’s --> <!-- talk about this stuff we've added to `println!`. --> <p>Rustでは未初期化の値を使うことは許されていません。 次に、 <code>println!</code> に追加したものについて話しましょう。</p> <!-- If you include two curly braces (`{}`, some call them moustaches...) in your --> <!-- string to print, Rust will interpret this as a request to interpolate some sort --> <!-- of value. *String interpolation* is a computer science term that means "stick --> <!-- in the middle of a string." We add a comma, and then `x`, to indicate that we --> <!-- want `x` to be the value we’re interpolating. The comma is used to separate --> <!-- arguments we pass to functions and macros, if you’re passing more than one. --> <p>表示する文字列に2つの波括弧(<code>{}</code>、口髭という人もいます…(訳注: 海外の顔文字は横になっているので首を傾けて <code>{</code> を眺めてみてください。また、日本語だと「中括弧」と呼ぶ人もいますね))を入れました。 Rustはこれを、何かの値で補間(interpolate)してほしいのだと解釈します。 <em>文字列補間</em> (string interpolation)はコンピュータサイエンスの用語で、「文字列の間に差し込む」という意味です。 その後に続けてカンマ、そして <code>x</code> を置いて、 <code>x</code> が補間に使う値だと指示しています。 カンマは2つ以上の引数を関数やマクロに渡す時に使われます。</p> <!-- When you use the curly braces, Rust will attempt to display the value in a --> <!-- meaningful way by checking out its type. If you want to specify the format in a --> <!-- more detailed manner, there are a [wide number of options available][format]. --> <!-- For now, we'll stick to the default: integers aren't very complicated to --> <!-- print. --> <p>波括弧を使うと、Rustは補間に使う値の型を調べて意味のある方法で表示しようとします。 フォーマットをさらに詳しく指定したいなら<a href="../std/fmt/index.html">数多くのオプションが利用できます</a>。 とりあえずのところ、デフォルトに従いましょう。整数の表示はそれほど複雑ではありません。</p> <!-- # Scope and shadowing --> <h1 id='スコープとシャドーイング' class='section-header'><a href='#スコープとシャドーイング'>スコープとシャドーイング</a></h1> <!-- Let’s get back to bindings. Variable bindings have a scope - they are --> <!-- constrained to live in a block they were defined in. A block is a collection --> <!-- of statements enclosed by `{` and `}`. Function definitions are also blocks! --> <!-- In the following example we define two variable bindings, `x` and `y`, which --> <!-- live in different blocks. `x` can be accessed from inside the `fn main() {}` --> <!-- block, while `y` can be accessed only from inside the inner block: --> <p>束縛に話を戻しましょう。変数束縛にはスコープがあります。変数束縛は定義されたブロック内でしか有効でありません。 ブロックは <code>{</code> と <code>}</code> に囲まれた文の集まりです。関数定義もブロックです! 以下の例では異なるブロックで有効な2つの変数束縛、 <code>x</code> と <code>y</code> を定義しています。 <code>x</code> は <code>fn main() {}</code> ブロックの中でアクセス可能ですが、 <code>y</code> は内側のブロックからのみアクセスできます。</p> <span class='rusttest'>fn main() { let x: i32 = 17; { let y: i32 = 3; println!(&quot;The value of x is {} and value of y is {}&quot;, x, y); } // println!(&quot;The value of x is {} and value of y is {}&quot;, x, y); // This won&#39;t work println!(&quot;The value of x is {} and value of y is {}&quot;, x, y); // これは動きません } </span><pre class='rust rust-example-rendered'> <span class='kw'>fn</span> <span class='ident'>main</span>() { <span class='kw'>let</span> <span class='ident'>x</span>: <span class='ident'>i32</span> <span class='op'>=</span> <span class='number'>17</span>; { <span class='kw'>let</span> <span class='ident'>y</span>: <span class='ident'>i32</span> <span class='op'>=</span> <span class='number'>3</span>; <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;The value of x is {} and value of y is {}&quot;</span>, <span class='ident'>x</span>, <span class='ident'>y</span>); } <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;The value of x is {} and value of y is {}&quot;</span>, <span class='ident'>x</span>, <span class='ident'>y</span>); <span class='comment'>// これは動きません</span> }</pre> <!-- The first `println!` would print "The value of x is 17 and the value of y is --> <!-- 3", but this example cannot be compiled successfully, because the second --> <!-- `println!` cannot access the value of `y`, since it is not in scope anymore. --> <!-- Instead we get this error: --> <p>最初の <code>println!</code> は「The value of x is 17 and the value of y is 3」(訳注: 「xの値は17でyの値は3」)と表示するはずですが、 2つめの <code>println!</code> は <code>y</code> がもうスコープにいないため <code>y</code> にアクセスできないのでこの例はコンパイルできません。 代わりに以下のようなエラーが出ます。</p> <pre><code class="language-bash">$ cargo build Compiling hello v0.1.0 (file:///home/you/projects/hello_world) main.rs:7:62: 7:63 error: unresolved name `y`. Did you mean `x`? [E0425] main.rs:7 println!(&quot;The value of x is {} and value of y is {}&quot;, x, y); // これは動きません ^ note: in expansion of format_args! &lt;std macros&gt;:2:25: 2:56 note: expansion site &lt;std macros&gt;:1:1: 2:62 note: in expansion of print! &lt;std macros&gt;:3:1: 3:54 note: expansion site &lt;std macros&gt;:1:1: 3:58 note: in expansion of println! main.rs:7:5: 7:65 note: expansion site main.rs:7:62: 7:63 help: run `rustc --explain E0425` to see a detailed explanation error: aborting due to previous error Could not compile `hello`. To learn more, run the command again with --verbose. </code></pre> <!-- Additionally, variable bindings can be shadowed. This means that a later --> <!-- variable binding with the same name as another binding, that's currently in --> <!-- scope, will override the previous binding. --> <p>さらに加えて、変数束縛は覆い隠すことができます(訳注: このことをシャドーイングと言います)。 つまり後に出てくる同じ名前の変数束縛があるとそれがスコープに入り、以前の束縛を上書きするのです。</p> <span class='rusttest'>fn main() { let x: i32 = 8; { // println!(&quot;{}&quot;, x); // Prints &quot;8&quot; println!(&quot;{}&quot;, x); // &quot;8&quot;を表示する let x = 12; // println!(&quot;{}&quot;, x); // Prints &quot;12&quot; println!(&quot;{}&quot;, x); // &quot;12&quot;を表示する } // println!(&quot;{}&quot;, x); // Prints &quot;8&quot; println!(&quot;{}&quot;, x); // &quot;8&quot;を表示する let x = 42; // println!(&quot;{}&quot;, x); // Prints &quot;42&quot; println!(&quot;{}&quot;, x); // &quot;42&quot;を表示する }</span><pre class='rust rust-example-rendered'> <span class='kw'>let</span> <span class='ident'>x</span>: <span class='ident'>i32</span> <span class='op'>=</span> <span class='number'>8</span>; { <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;{}&quot;</span>, <span class='ident'>x</span>); <span class='comment'>// &quot;8&quot;を表示する</span> <span class='kw'>let</span> <span class='ident'>x</span> <span class='op'>=</span> <span class='number'>12</span>; <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;{}&quot;</span>, <span class='ident'>x</span>); <span class='comment'>// &quot;12&quot;を表示する</span> } <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;{}&quot;</span>, <span class='ident'>x</span>); <span class='comment'>// &quot;8&quot;を表示する</span> <span class='kw'>let</span> <span class='ident'>x</span> <span class='op'>=</span> <span class='number'>42</span>; <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;{}&quot;</span>, <span class='ident'>x</span>); <span class='comment'>// &quot;42&quot;を表示する</span></pre> <!-- Shadowing and mutable bindings may appear as two sides of the same coin, but --> <!-- they are two distinct concepts that can't always be used interchangeably. For --> <!-- one, shadowing enables us to rebind a name to a value of a different type. It --> <!-- is also possible to change the mutability of a binding. --> <p>シャドーイングとミュータブルな束縛はコインの表と裏のように見えるかもしれませんが、それぞれ独立な概念であり互いに代用ができないケースがあります。 その1つにシャドーイングは同じ名前に違う型の値を再束縛することができます。</p> <span class='rusttest'>fn main() { let mut x: i32 = 1; x = 7; // let x = x; // x is now immutable and is bound to 7 let x = x; // xはイミュータブルになって7に束縛されました let y = 4; // let y = &quot;I can also be bound to text!&quot;; // y is now of a different type let y = &quot;I can also be bound to text!&quot;; // yは違う型になりました }</span><pre class='rust rust-example-rendered'> <span class='kw'>let</span> <span class='kw-2'>mut</span> <span class='ident'>x</span>: <span class='ident'>i32</span> <span class='op'>=</span> <span class='number'>1</span>; <span class='ident'>x</span> <span class='op'>=</span> <span class='number'>7</span>; <span class='kw'>let</span> <span class='ident'>x</span> <span class='op'>=</span> <span class='ident'>x</span>; <span class='comment'>// xはイミュータブルになって7に束縛されました</span> <span class='kw'>let</span> <span class='ident'>y</span> <span class='op'>=</span> <span class='number'>4</span>; <span class='kw'>let</span> <span class='ident'>y</span> <span class='op'>=</span> <span class='string'>&quot;I can also be bound to text!&quot;</span>; <span class='comment'>// yは違う型になりました</span></pre> <script type="text/javascript"> window.playgroundUrl = "https://play.rust-lang.org"; </script> <script src='rustbook.js'></script> <script src='playpen.js'></script> </div></div> </body> </html> <|start_filename|>docs/1.9/style/features/traits/generics.html<|end_filename|> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="generator" content="rustdoc"> <title>Using traits for bounds on generics</title> <link rel="stylesheet" type="text/css" href="../../rustbook.css"> <meta name="robots" content="noindex"> </head> <body class="rustdoc"> <!--[if lte IE 8]> <div class="warning"> This old browser is unsupported and will most likely display funky things. </div> <![endif]--> <div id="nav"> <button id="toggle-nav"> <span class="sr-only">Toggle navigation</span> <span class="bar"></span> <span class="bar"></span> <span class="bar"></span> </button> </div> <div id='toc' class='mobile-hidden'> <ul class='chapter'> <li><a href='../../README.html'><b>1.</b> Introduction</a> </li> <li><a href='../../style/README.html'><b>2.</b> Style</a> <ul class='section'> <li><a href='../../style/whitespace.html'><b>2.1.</b> Whitespace</a> </li> <li><a href='../../style/comments.html'><b>2.2.</b> Comments</a> </li> <li><a href='../../style/braces.html'><b>2.3.</b> Braces, semicolons, commas</a> </li> <li><a href='../../style/naming/README.html'><b>2.4.</b> Naming</a> <ul class='section'> <li><a href='../../style/naming/ownership.html'><b>2.4.1.</b> Ownership variants</a> </li> <li><a href='../../style/naming/containers.html'><b>2.4.2.</b> Containers/wrappers</a> </li> <li><a href='../../style/naming/conversions.html'><b>2.4.3.</b> Conversions</a> </li> <li><a href='../../style/naming/iterators.html'><b>2.4.4.</b> Iterators</a> </li> </ul> </li> <li><a href='../../style/imports.html'><b>2.5.</b> Imports</a> </li> <li><a href='../../style/organization.html'><b>2.6.</b> Organization</a> </li> </ul> </li> <li><a href='../../features/README.html'><b>3.</b> Guidelines by Rust feature</a> <ul class='section'> <li><a href='../../features/let.html'><b>3.1.</b> Let binding</a> </li> <li><a href='../../features/match.html'><b>3.2.</b> Pattern matching</a> </li> <li><a href='../../features/loops.html'><b>3.3.</b> Loops</a> </li> <li><a href='../../features/functions-and-methods/README.html'><b>3.4.</b> Functions and methods</a> <ul class='section'> <li><a href='../../features/functions-and-methods/input.html'><b>3.4.1.</b> Input</a> </li> <li><a href='../../features/functions-and-methods/output.html'><b>3.4.2.</b> Output</a> </li> <li><a href='../../features/functions-and-methods/convenience.html'><b>3.4.3.</b> For convenience</a> </li> </ul> </li> <li><a href='../../features/types/README.html'><b>3.5.</b> Types</a> <ul class='section'> <li><a href='../../features/types/conversions.html'><b>3.5.1.</b> Conversions</a> </li> <li><a href='../../features/types/newtype.html'><b>3.5.2.</b> The newtype pattern</a> </li> </ul> </li> <li><a href='../../features/traits/README.html'><b>3.6.</b> Traits</a> <ul class='section'> <li><a class='active' href='../../features/traits/generics.html'><b>3.6.1.</b> For generics</a> </li> <li><a href='../../features/traits/objects.html'><b>3.6.2.</b> For objects</a> </li> <li><a href='../../features/traits/overloading.html'><b>3.6.3.</b> For overloading</a> </li> <li><a href='../../features/traits/extensions.html'><b>3.6.4.</b> For extensions</a> </li> <li><a href='../../features/traits/reuse.html'><b>3.6.5.</b> For reuse</a> </li> <li><a href='../../features/traits/common.html'><b>3.6.6.</b> Common traits</a> </li> </ul> </li> <li><a href='../../features/modules.html'><b>3.7.</b> Modules</a> </li> <li><a href='../../features/crates.html'><b>3.8.</b> Crates</a> </li> </ul> </li> <li><a href='../../ownership/README.html'><b>4.</b> Ownership and resources</a> <ul class='section'> <li><a href='../../ownership/constructors.html'><b>4.1.</b> Constructors</a> </li> <li><a href='../../ownership/builders.html'><b>4.2.</b> Builders</a> </li> <li><a href='../../ownership/destructors.html'><b>4.3.</b> Destructors</a> </li> <li><a href='../../ownership/raii.html'><b>4.4.</b> RAII</a> </li> <li><a href='../../ownership/cell-smart.html'><b>4.5.</b> Cells and smart pointers</a> </li> </ul> </li> <li><a href='../../errors/README.html'><b>5.</b> Errors</a> <ul class='section'> <li><a href='../../errors/signaling.html'><b>5.1.</b> Signaling</a> </li> <li><a href='../../errors/handling.html'><b>5.2.</b> Handling</a> </li> <li><a href='../../errors/propagation.html'><b>5.3.</b> Propagation</a> </li> <li><a href='../../errors/ergonomics.html'><b>5.4.</b> Ergonomics</a> </li> </ul> </li> <li><a href='../../safety/README.html'><b>6.</b> Safety and guarantees</a> <ul class='section'> <li><a href='../../safety/unsafe.html'><b>6.1.</b> Using unsafe</a> </li> <li><a href='../../safety/lib-guarantees.html'><b>6.2.</b> Library guarantees</a> </li> </ul> </li> <li><a href='../../testing/README.html'><b>7.</b> Testing</a> <ul class='section'> <li><a href='../../testing/unit.html'><b>7.1.</b> Unit testing</a> </li> </ul> </li> <li><a href='../../platform.html'><b>8.</b> FFI, platform-specific code</a> </li> </ul> </div> <div id='page-wrapper'> <div id='page'> <blockquote class="header-caveat"> <p> <strong>注意: <a href="https://doc.rust-jp.rs/book-ja/">最新版のドキュメントをご覧ください。</a></strong>この第1版ドキュメントは古くなっており、最新情報が反映されていません。リンク先のドキュメントが現在の Rust の最新のドキュメントです。 </p> </blockquote> <h1 class="title">Using traits for bounds on generics</h1> <p>The most widespread use of traits is for writing generic functions or types. For example, the following signature describes a function for consuming any iterator yielding items of type <code>A</code> to produce a collection of <code>A</code>:</p> <span class='rusttest'>fn main() { fn from_iter&lt;T: Iterator&lt;A&gt;&gt;(iterator: T) -&gt; SomeCollection&lt;A&gt; }</span><pre class='rust rust-example-rendered'> <span class='kw'>fn</span> <span class='ident'>from_iter</span><span class='op'>&lt;</span><span class='ident'>T</span>: <span class='ident'>Iterator</span><span class='op'>&lt;</span><span class='ident'>A</span><span class='op'>&gt;&gt;</span>(<span class='ident'>iterator</span>: <span class='ident'>T</span>) <span class='op'>-&gt;</span> <span class='ident'>SomeCollection</span><span class='op'>&lt;</span><span class='ident'>A</span><span class='op'>&gt;</span></pre> <p>Here, the <code>Iterator</code> trait specifies an interface that a type <code>T</code> must explicitly implement to be used by this generic function.</p> <p><strong>Pros</strong>:</p> <ul> <li><em>Reusability</em>. Generic functions can be applied to an open-ended collection of types, while giving a clear contract for the functionality those types must provide.</li> <li><em>Static dispatch and optimization</em>. Each use of a generic function is specialized (&quot;monomorphized&quot;) to the particular types implementing the trait bounds, which means that (1) invocations of trait methods are static, direct calls to the implementation and (2) the compiler can inline and otherwise optimize these calls.</li> <li><em>Inline layout</em>. If a <code>struct</code> and <code>enum</code> type is generic over some type parameter <code>T</code>, values of type <code>T</code> will be laid out <em>inline</em> in the <code>struct</code>/<code>enum</code>, without any indirection.</li> <li><em>Inference</em>. Since the type parameters to generic functions can usually be inferred, generic functions can help cut down on verbosity in code where explicit conversions or other method calls would usually be necessary. See the <a href="#use-case-limited-overloading-andor-implicit-conversions">overloading/implicits use case</a> below.</li> <li><p><em>Precise types</em>. Because generics give a <em>name</em> to the specific type implementing a trait, it is possible to be precise about places where that exact type is required or produced. For example, a function</p> <span class='rusttest'>fn main() { fn binary&lt;T: Trait&gt;(x: T, y: T) -&gt; T }</span><pre class='rust rust-example-rendered'> <span class='kw'>fn</span> <span class='ident'>binary</span><span class='op'>&lt;</span><span class='ident'>T</span>: <span class='ident'>Trait</span><span class='op'>&gt;</span>(<span class='ident'>x</span>: <span class='ident'>T</span>, <span class='ident'>y</span>: <span class='ident'>T</span>) <span class='op'>-&gt;</span> <span class='ident'>T</span></pre> <p>is guaranteed to consume and produce elements of exactly the same type <code>T</code>; it cannot be invoked with parameters of different types that both implement <code>Trait</code>.</p></li> </ul> <p><strong>Cons</strong>:</p> <ul> <li><em>Code size</em>. Specializing generic functions means that the function body is duplicated. The increase in code size must be weighed against the performance benefits of static dispatch.</li> <li><em>Homogeneous types</em>. This is the other side of the &quot;precise types&quot; coin: if <code>T</code> is a type parameter, it stands for a <em>single</em> actual type. So for example a <code>Vec&lt;T&gt;</code> contains elements of a single concrete type (and, indeed, the vector representation is specialized to lay these out in line). Sometimes heterogeneous collections are useful; see <a href="#use-case-trait-objects">trait objects</a> below.</li> <li><em>Signature verbosity</em>. Heavy use of generics can bloat function signatures. <strong>[Ed. note]</strong> This problem may be mitigated by some language improvements; stay tuned.</li> </ul> <h3 id='favor-widespread-traits-fixme-needs-rfc' class='section-header'><a href='#favor-widespread-traits-fixme-needs-rfc'>Favor widespread traits. <strong>[FIXME: needs RFC]</strong></a></h3> <p>Generic types are a form of abstraction, which entails a mental indirection: if a function takes an argument of type <code>T</code> bounded by <code>Trait</code>, clients must first think about the concrete types that implement <code>Trait</code> to understand how and when the function is callable.</p> <p>To keep the cost of abstraction low, favor widely-known traits. Whenever possible, implement and use traits provided as part of the standard library. Do not introduce new traits for generics lightly; wait until there are a wide range of types that can implement the type.</p> <script type="text/javascript"> window.playgroundUrl = "https://play.rust-lang.org"; </script> <script src='rustbook.js'></script> <script src='playpen.js'></script> </div></div> </body> </html> <|start_filename|>docs/1.9/style/ownership/builders.html<|end_filename|> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="generator" content="rustdoc"> <title>The builder pattern</title> <link rel="stylesheet" type="text/css" href="../rustbook.css"> <meta name="robots" content="noindex"> </head> <body class="rustdoc"> <!--[if lte IE 8]> <div class="warning"> This old browser is unsupported and will most likely display funky things. </div> <![endif]--> <div id="nav"> <button id="toggle-nav"> <span class="sr-only">Toggle navigation</span> <span class="bar"></span> <span class="bar"></span> <span class="bar"></span> </button> </div> <div id='toc' class='mobile-hidden'> <ul class='chapter'> <li><a href='../README.html'><b>1.</b> Introduction</a> </li> <li><a href='../style/README.html'><b>2.</b> Style</a> <ul class='section'> <li><a href='../style/whitespace.html'><b>2.1.</b> Whitespace</a> </li> <li><a href='../style/comments.html'><b>2.2.</b> Comments</a> </li> <li><a href='../style/braces.html'><b>2.3.</b> Braces, semicolons, commas</a> </li> <li><a href='../style/naming/README.html'><b>2.4.</b> Naming</a> <ul class='section'> <li><a href='../style/naming/ownership.html'><b>2.4.1.</b> Ownership variants</a> </li> <li><a href='../style/naming/containers.html'><b>2.4.2.</b> Containers/wrappers</a> </li> <li><a href='../style/naming/conversions.html'><b>2.4.3.</b> Conversions</a> </li> <li><a href='../style/naming/iterators.html'><b>2.4.4.</b> Iterators</a> </li> </ul> </li> <li><a href='../style/imports.html'><b>2.5.</b> Imports</a> </li> <li><a href='../style/organization.html'><b>2.6.</b> Organization</a> </li> </ul> </li> <li><a href='../features/README.html'><b>3.</b> Guidelines by Rust feature</a> <ul class='section'> <li><a href='../features/let.html'><b>3.1.</b> Let binding</a> </li> <li><a href='../features/match.html'><b>3.2.</b> Pattern matching</a> </li> <li><a href='../features/loops.html'><b>3.3.</b> Loops</a> </li> <li><a href='../features/functions-and-methods/README.html'><b>3.4.</b> Functions and methods</a> <ul class='section'> <li><a href='../features/functions-and-methods/input.html'><b>3.4.1.</b> Input</a> </li> <li><a href='../features/functions-and-methods/output.html'><b>3.4.2.</b> Output</a> </li> <li><a href='../features/functions-and-methods/convenience.html'><b>3.4.3.</b> For convenience</a> </li> </ul> </li> <li><a href='../features/types/README.html'><b>3.5.</b> Types</a> <ul class='section'> <li><a href='../features/types/conversions.html'><b>3.5.1.</b> Conversions</a> </li> <li><a href='../features/types/newtype.html'><b>3.5.2.</b> The newtype pattern</a> </li> </ul> </li> <li><a href='../features/traits/README.html'><b>3.6.</b> Traits</a> <ul class='section'> <li><a href='../features/traits/generics.html'><b>3.6.1.</b> For generics</a> </li> <li><a href='../features/traits/objects.html'><b>3.6.2.</b> For objects</a> </li> <li><a href='../features/traits/overloading.html'><b>3.6.3.</b> For overloading</a> </li> <li><a href='../features/traits/extensions.html'><b>3.6.4.</b> For extensions</a> </li> <li><a href='../features/traits/reuse.html'><b>3.6.5.</b> For reuse</a> </li> <li><a href='../features/traits/common.html'><b>3.6.6.</b> Common traits</a> </li> </ul> </li> <li><a href='../features/modules.html'><b>3.7.</b> Modules</a> </li> <li><a href='../features/crates.html'><b>3.8.</b> Crates</a> </li> </ul> </li> <li><a href='../ownership/README.html'><b>4.</b> Ownership and resources</a> <ul class='section'> <li><a href='../ownership/constructors.html'><b>4.1.</b> Constructors</a> </li> <li><a class='active' href='../ownership/builders.html'><b>4.2.</b> Builders</a> </li> <li><a href='../ownership/destructors.html'><b>4.3.</b> Destructors</a> </li> <li><a href='../ownership/raii.html'><b>4.4.</b> RAII</a> </li> <li><a href='../ownership/cell-smart.html'><b>4.5.</b> Cells and smart pointers</a> </li> </ul> </li> <li><a href='../errors/README.html'><b>5.</b> Errors</a> <ul class='section'> <li><a href='../errors/signaling.html'><b>5.1.</b> Signaling</a> </li> <li><a href='../errors/handling.html'><b>5.2.</b> Handling</a> </li> <li><a href='../errors/propagation.html'><b>5.3.</b> Propagation</a> </li> <li><a href='../errors/ergonomics.html'><b>5.4.</b> Ergonomics</a> </li> </ul> </li> <li><a href='../safety/README.html'><b>6.</b> Safety and guarantees</a> <ul class='section'> <li><a href='../safety/unsafe.html'><b>6.1.</b> Using unsafe</a> </li> <li><a href='../safety/lib-guarantees.html'><b>6.2.</b> Library guarantees</a> </li> </ul> </li> <li><a href='../testing/README.html'><b>7.</b> Testing</a> <ul class='section'> <li><a href='../testing/unit.html'><b>7.1.</b> Unit testing</a> </li> </ul> </li> <li><a href='../platform.html'><b>8.</b> FFI, platform-specific code</a> </li> </ul> </div> <div id='page-wrapper'> <div id='page'> <blockquote class="header-caveat"> <p> <strong>注意: <a href="https://doc.rust-jp.rs/book-ja/">最新版のドキュメントをご覧ください。</a></strong>この第1版ドキュメントは古くなっており、最新情報が反映されていません。リンク先のドキュメントが現在の Rust の最新のドキュメントです。 </p> </blockquote> <h1 class="title">The builder pattern</h1> <p>Some data structures are complicated to construct, due to their construction needing:</p> <ul> <li>a large number of inputs</li> <li>compound data (e.g. slices)</li> <li>optional configuration data</li> <li>choice between several flavors</li> </ul> <p>which can easily lead to a large number of distinct constructors with many arguments each.</p> <p>If <code>T</code> is such a data structure, consider introducing a <code>T</code> <em>builder</em>:</p> <ol> <li>Introduce a separate data type <code>TBuilder</code> for incrementally configuring a <code>T</code> value. When possible, choose a better name: e.g. <code>Command</code> is the builder for <code>Process</code>.</li> <li>The builder constructor should take as parameters only the data <em>required</em> to make a <code>T</code>.</li> <li>The builder should offer a suite of convenient methods for configuration, including setting up compound inputs (like slices) incrementally. These methods should return <code>self</code> to allow chaining.</li> <li>The builder should provide one or more &quot;_terminal_&quot; methods for actually building a <code>T</code>.</li> </ol> <p>The builder pattern is especially appropriate when building a <code>T</code> involves side effects, such as spawning a thread or launching a process.</p> <p>In Rust, there are two variants of the builder pattern, differing in the treatment of ownership, as described below.</p> <h3 id='non-consuming-builders-preferred' class='section-header'><a href='#non-consuming-builders-preferred'>Non-consuming builders (preferred):</a></h3> <p>In some cases, constructing the final <code>T</code> does not require the builder itself to be consumed. The follow variant on <a href="https://doc.rust-lang.org/stable/std/process/struct.Command.html"><code>std::process::Command</code></a> is one example:</p> <span class='rusttest'>fn main() { // NOTE: the actual Command API does not use owned Strings; // this is a simplified version. pub struct Command { program: String, args: Vec&lt;String&gt;, cwd: Option&lt;String&gt;, // etc } impl Command { pub fn new(program: String) -&gt; Command { Command { program: program, args: Vec::new(), cwd: None, } } /// Add an argument to pass to the program. pub fn arg&lt;&#39;a&gt;(&amp;&#39;a mut self, arg: String) -&gt; &amp;&#39;a mut Command { self.args.push(arg); self } /// Add multiple arguments to pass to the program. pub fn args&lt;&#39;a&gt;(&amp;&#39;a mut self, args: &amp;[String]) -&gt; &amp;&#39;a mut Command { self.args.push_all(args); self } /// Set the working directory for the child process. pub fn cwd&lt;&#39;a&gt;(&amp;&#39;a mut self, dir: String) -&gt; &amp;&#39;a mut Command { self.cwd = Some(dir); self } /// Executes the command as a child process, which is returned. pub fn spawn(&amp;self) -&gt; std::io::Result&lt;Process&gt; { ... } } }</span><pre class='rust rust-example-rendered'> <span class='comment'>// NOTE: the actual Command API does not use owned Strings;</span> <span class='comment'>// this is a simplified version.</span> <span class='kw'>pub</span> <span class='kw'>struct</span> <span class='ident'>Command</span> { <span class='ident'>program</span>: <span class='ident'>String</span>, <span class='ident'>args</span>: <span class='ident'>Vec</span><span class='op'>&lt;</span><span class='ident'>String</span><span class='op'>&gt;</span>, <span class='ident'>cwd</span>: <span class='prelude-ty'>Option</span><span class='op'>&lt;</span><span class='ident'>String</span><span class='op'>&gt;</span>, <span class='comment'>// etc</span> } <span class='kw'>impl</span> <span class='ident'>Command</span> { <span class='kw'>pub</span> <span class='kw'>fn</span> <span class='ident'>new</span>(<span class='ident'>program</span>: <span class='ident'>String</span>) <span class='op'>-&gt;</span> <span class='ident'>Command</span> { <span class='ident'>Command</span> { <span class='ident'>program</span>: <span class='ident'>program</span>, <span class='ident'>args</span>: <span class='ident'>Vec</span>::<span class='ident'>new</span>(), <span class='ident'>cwd</span>: <span class='prelude-val'>None</span>, } } <span class='doccomment'>/// Add an argument to pass to the program.</span> <span class='kw'>pub</span> <span class='kw'>fn</span> <span class='ident'>arg</span><span class='op'>&lt;</span><span class='lifetime'>&#39;a</span><span class='op'>&gt;</span>(<span class='kw-2'>&amp;</span><span class='lifetime'>&#39;a</span> <span class='kw-2'>mut</span> <span class='self'>self</span>, <span class='ident'>arg</span>: <span class='ident'>String</span>) <span class='op'>-&gt;</span> <span class='kw-2'>&amp;</span><span class='lifetime'>&#39;a</span> <span class='kw-2'>mut</span> <span class='ident'>Command</span> { <span class='self'>self</span>.<span class='ident'>args</span>.<span class='ident'>push</span>(<span class='ident'>arg</span>); <span class='self'>self</span> } <span class='doccomment'>/// Add multiple arguments to pass to the program.</span> <span class='kw'>pub</span> <span class='kw'>fn</span> <span class='ident'>args</span><span class='op'>&lt;</span><span class='lifetime'>&#39;a</span><span class='op'>&gt;</span>(<span class='kw-2'>&amp;</span><span class='lifetime'>&#39;a</span> <span class='kw-2'>mut</span> <span class='self'>self</span>, <span class='ident'>args</span>: <span class='kw-2'>&amp;</span>[<span class='ident'>String</span>]) <span class='op'>-&gt;</span> <span class='kw-2'>&amp;</span><span class='lifetime'>&#39;a</span> <span class='kw-2'>mut</span> <span class='ident'>Command</span> { <span class='self'>self</span>.<span class='ident'>args</span>.<span class='ident'>push_all</span>(<span class='ident'>args</span>); <span class='self'>self</span> } <span class='doccomment'>/// Set the working directory for the child process.</span> <span class='kw'>pub</span> <span class='kw'>fn</span> <span class='ident'>cwd</span><span class='op'>&lt;</span><span class='lifetime'>&#39;a</span><span class='op'>&gt;</span>(<span class='kw-2'>&amp;</span><span class='lifetime'>&#39;a</span> <span class='kw-2'>mut</span> <span class='self'>self</span>, <span class='ident'>dir</span>: <span class='ident'>String</span>) <span class='op'>-&gt;</span> <span class='kw-2'>&amp;</span><span class='lifetime'>&#39;a</span> <span class='kw-2'>mut</span> <span class='ident'>Command</span> { <span class='self'>self</span>.<span class='ident'>cwd</span> <span class='op'>=</span> <span class='prelude-val'>Some</span>(<span class='ident'>dir</span>); <span class='self'>self</span> } <span class='doccomment'>/// Executes the command as a child process, which is returned.</span> <span class='kw'>pub</span> <span class='kw'>fn</span> <span class='ident'>spawn</span>(<span class='kw-2'>&amp;</span><span class='self'>self</span>) <span class='op'>-&gt;</span> <span class='ident'>std</span>::<span class='ident'>io</span>::<span class='prelude-ty'>Result</span><span class='op'>&lt;</span><span class='ident'>Process</span><span class='op'>&gt;</span> { ... } }</pre> <p>Note that the <code>spawn</code> method, which actually uses the builder configuration to spawn a process, takes the builder by immutable reference. This is possible because spawning the process does not require ownership of the configuration data.</p> <p>Because the terminal <code>spawn</code> method only needs a reference, the configuration methods take and return a mutable borrow of <code>self</code>.</p> <h4 id='the-benefit' class='section-header'><a href='#the-benefit'>The benefit</a></h4> <p>By using borrows throughout, <code>Command</code> can be used conveniently for both one-liner and more complex constructions:</p> <span class='rusttest'>fn main() { // One-liners Command::new(&quot;/bin/cat&quot;).arg(&quot;file.txt&quot;).spawn(); // Complex configuration let mut cmd = Command::new(&quot;/bin/ls&quot;); cmd.arg(&quot;.&quot;); if size_sorted { cmd.arg(&quot;-S&quot;); } cmd.spawn(); }</span><pre class='rust rust-example-rendered'> <span class='comment'>// One-liners</span> <span class='ident'>Command</span>::<span class='ident'>new</span>(<span class='string'>&quot;/bin/cat&quot;</span>).<span class='ident'>arg</span>(<span class='string'>&quot;file.txt&quot;</span>).<span class='ident'>spawn</span>(); <span class='comment'>// Complex configuration</span> <span class='kw'>let</span> <span class='kw-2'>mut</span> <span class='ident'>cmd</span> <span class='op'>=</span> <span class='ident'>Command</span>::<span class='ident'>new</span>(<span class='string'>&quot;/bin/ls&quot;</span>); <span class='ident'>cmd</span>.<span class='ident'>arg</span>(<span class='string'>&quot;.&quot;</span>); <span class='kw'>if</span> <span class='ident'>size_sorted</span> { <span class='ident'>cmd</span>.<span class='ident'>arg</span>(<span class='string'>&quot;-S&quot;</span>); } <span class='ident'>cmd</span>.<span class='ident'>spawn</span>();</pre> <h3 id='consuming-builders' class='section-header'><a href='#consuming-builders'>Consuming builders:</a></h3> <p>Sometimes builders must transfer ownership when constructing the final type <code>T</code>, meaning that the terminal methods must take <code>self</code> rather than <code>&amp;self</code>:</p> <span class='rusttest'>fn main() { // A simplified excerpt from std::thread::Builder impl ThreadBuilder { /// Name the thread-to-be. Currently the name is used for identification /// only in failure messages. pub fn named(mut self, name: String) -&gt; ThreadBuilder { self.name = Some(name); self } /// Redirect thread-local stdout. pub fn stdout(mut self, stdout: Box&lt;Writer + Send&gt;) -&gt; ThreadBuilder { self.stdout = Some(stdout); // ^~~~~~ this is owned and cannot be cloned/re-used self } /// Creates and executes a new child thread. pub fn spawn(self, f: proc():Send) { // consume self ... } } }</span><pre class='rust rust-example-rendered'> <span class='comment'>// A simplified excerpt from std::thread::Builder</span> <span class='kw'>impl</span> <span class='ident'>ThreadBuilder</span> { <span class='doccomment'>/// Name the thread-to-be. Currently the name is used for identification</span> <span class='doccomment'>/// only in failure messages.</span> <span class='kw'>pub</span> <span class='kw'>fn</span> <span class='ident'>named</span>(<span class='kw-2'>mut</span> <span class='self'>self</span>, <span class='ident'>name</span>: <span class='ident'>String</span>) <span class='op'>-&gt;</span> <span class='ident'>ThreadBuilder</span> { <span class='self'>self</span>.<span class='ident'>name</span> <span class='op'>=</span> <span class='prelude-val'>Some</span>(<span class='ident'>name</span>); <span class='self'>self</span> } <span class='doccomment'>/// Redirect thread-local stdout.</span> <span class='kw'>pub</span> <span class='kw'>fn</span> <span class='ident'>stdout</span>(<span class='kw-2'>mut</span> <span class='self'>self</span>, <span class='ident'>stdout</span>: <span class='ident'>Box</span><span class='op'>&lt;</span><span class='ident'>Writer</span> <span class='op'>+</span> <span class='ident'>Send</span><span class='op'>&gt;</span>) <span class='op'>-&gt;</span> <span class='ident'>ThreadBuilder</span> { <span class='self'>self</span>.<span class='ident'>stdout</span> <span class='op'>=</span> <span class='prelude-val'>Some</span>(<span class='ident'>stdout</span>); <span class='comment'>// ^~~~~~ this is owned and cannot be cloned/re-used</span> <span class='self'>self</span> } <span class='doccomment'>/// Creates and executes a new child thread.</span> <span class='kw'>pub</span> <span class='kw'>fn</span> <span class='ident'>spawn</span>(<span class='self'>self</span>, <span class='ident'>f</span>: <span class='kw'>proc</span>():<span class='ident'>Send</span>) { <span class='comment'>// consume self</span> ... } }</pre> <p>Here, the <code>stdout</code> configuration involves passing ownership of a <code>Writer</code>, which must be transferred to the thread upon construction (in <code>spawn</code>).</p> <p>When the terminal methods of the builder require ownership, there is a basic tradeoff:</p> <ul> <li><p>If the other builder methods take/return a mutable borrow, the complex configuration case will work well, but one-liner configuration becomes <em>impossible</em>.</p></li> <li><p>If the other builder methods take/return an owned <code>self</code>, one-liners continue to work well but complex configuration is less convenient.</p></li> </ul> <p>Under the rubric of making easy things easy and hard things possible, <em>all</em> builder methods for a consuming builder should take and returned an owned <code>self</code>. Then client code works as follows:</p> <span class='rusttest'>fn main() { // One-liners ThreadBuilder::new().named(&quot;my_thread&quot;).spawn(proc() { ... }); // Complex configuration let mut thread = ThreadBuilder::new(); thread = thread.named(&quot;my_thread_2&quot;); // must re-assign to retain ownership if reroute { thread = thread.stdout(mywriter); } thread.spawn(proc() { ... }); }</span><pre class='rust rust-example-rendered'> <span class='comment'>// One-liners</span> <span class='ident'>ThreadBuilder</span>::<span class='ident'>new</span>().<span class='ident'>named</span>(<span class='string'>&quot;my_thread&quot;</span>).<span class='ident'>spawn</span>(<span class='kw'>proc</span>() { ... }); <span class='comment'>// Complex configuration</span> <span class='kw'>let</span> <span class='kw-2'>mut</span> <span class='ident'>thread</span> <span class='op'>=</span> <span class='ident'>ThreadBuilder</span>::<span class='ident'>new</span>(); <span class='ident'>thread</span> <span class='op'>=</span> <span class='ident'>thread</span>.<span class='ident'>named</span>(<span class='string'>&quot;my_thread_2&quot;</span>); <span class='comment'>// must re-assign to retain ownership</span> <span class='kw'>if</span> <span class='ident'>reroute</span> { <span class='ident'>thread</span> <span class='op'>=</span> <span class='ident'>thread</span>.<span class='ident'>stdout</span>(<span class='ident'>mywriter</span>); } <span class='ident'>thread</span>.<span class='ident'>spawn</span>(<span class='kw'>proc</span>() { ... });</pre> <p>One-liners work as before, because ownership is threaded through each of the builder methods until being consumed by <code>spawn</code>. Complex configuration, however, is more verbose: it requires re-assigning the builder at each step.</p> <script type="text/javascript"> window.playgroundUrl = "https://play.rust-lang.org"; </script> <script src='rustbook.js'></script> <script src='playpen.js'></script> </div></div> </body> </html> <|start_filename|>docs/1.6/book/ufcs.html<|end_filename|> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="generator" content="rustdoc"> <title>共通の関数呼び出し構文</title> <link rel="stylesheet" type="text/css" href="rustbook.css"> <meta name="robots" content="noindex"> </head> <body class="rustdoc"> <!--[if lte IE 8]> <div class="warning"> This old browser is unsupported and will most likely display funky things. </div> <![endif]--> <div id="nav"> <button id="toggle-nav"> <span class="sr-only">Toggle navigation</span> <span class="bar"></span> <span class="bar"></span> <span class="bar"></span> </button> </div> <div id='toc' class='mobile-hidden'> <ul class='chapter'> <li><a href='README.html'><b>1.</b> Introduction</a> </li> <li><a href='getting-started.html'><b>2.</b> はじめる</a> </li> <li><a href='learn-rust.html'><b>3.</b> Rustを学ぶ</a> <ul class='section'> <li><a href='guessing-game.html'><b>3.1.</b> 数当てゲーム</a> </li> <li><a href='dining-philosophers.html'><b>3.2.</b> 食事する哲学者</a> </li> <li><a href='rust-inside-other-languages.html'><b>3.3.</b> 他言語と共存する</a> </li> </ul> </li> <li><a href='syntax-and-semantics.html'><b>4.</b> シンタックスとセマンティクス</a> <ul class='section'> <li><a href='variable-bindings.html'><b>4.1.</b> 変数束縛</a> </li> <li><a href='functions.html'><b>4.2.</b> 関数</a> </li> <li><a href='primitive-types.html'><b>4.3.</b> プリミティブ型</a> </li> <li><a href='comments.html'><b>4.4.</b> コメント</a> </li> <li><a href='if.html'><b>4.5.</b> if</a> </li> <li><a href='loops.html'><b>4.6.</b> ループ</a> </li> <li><a href='ownership.html'><b>4.7.</b> 所有権</a> </li> <li><a href='references-and-borrowing.html'><b>4.8.</b> 参照と借用</a> </li> <li><a href='lifetimes.html'><b>4.9.</b> ライフタイム</a> </li> <li><a href='mutability.html'><b>4.10.</b> ミュータビリティ</a> </li> <li><a href='structs.html'><b>4.11.</b> 構造体</a> </li> <li><a href='enums.html'><b>4.12.</b> 列挙型</a> </li> <li><a href='match.html'><b>4.13.</b> マッチ</a> </li> <li><a href='patterns.html'><b>4.14.</b> パターン</a> </li> <li><a href='method-syntax.html'><b>4.15.</b> メソッド構文</a> </li> <li><a href='vectors.html'><b>4.16.</b> ベクタ</a> </li> <li><a href='strings.html'><b>4.17.</b> 文字列</a> </li> <li><a href='generics.html'><b>4.18.</b> ジェネリクス</a> </li> <li><a href='traits.html'><b>4.19.</b> トレイト</a> </li> <li><a href='drop.html'><b>4.20.</b> Drop</a> </li> <li><a href='if-let.html'><b>4.21.</b> if let</a> </li> <li><a href='trait-objects.html'><b>4.22.</b> トレイトオブジェクト</a> </li> <li><a href='closures.html'><b>4.23.</b> クロージャ</a> </li> <li><a class='active' href='ufcs.html'><b>4.24.</b> 共通の関数呼出構文</a> </li> <li><a href='crates-and-modules.html'><b>4.25.</b> クレートとモジュール</a> </li> <li><a href='const-and-static.html'><b>4.26.</b> `const` と `static`</a> </li> <li><a href='attributes.html'><b>4.27.</b> アトリビュート</a> </li> <li><a href='type-aliases.html'><b>4.28.</b> `type` エイリアス</a> </li> <li><a href='casting-between-types.html'><b>4.29.</b> 型間のキャスト</a> </li> <li><a href='associated-types.html'><b>4.30.</b> 関連型</a> </li> <li><a href='unsized-types.html'><b>4.31.</b> サイズ不定型</a> </li> <li><a href='operators-and-overloading.html'><b>4.32.</b> 演算子とオーバーロード</a> </li> <li><a href='deref-coercions.html'><b>4.33.</b> Derefによる型強制</a> </li> <li><a href='macros.html'><b>4.34.</b> マクロ</a> </li> <li><a href='raw-pointers.html'><b>4.35.</b> 生ポインタ</a> </li> <li><a href='unsafe.html'><b>4.36.</b> `unsafe`</a> </li> </ul> </li> <li><a href='effective-rust.html'><b>5.</b> Effective Rust</a> <ul class='section'> <li><a href='the-stack-and-the-heap.html'><b>5.1.</b> スタックとヒープ</a> </li> <li><a href='testing.html'><b>5.2.</b> テスト</a> </li> <li><a href='conditional-compilation.html'><b>5.3.</b> 条件付きコンパイル</a> </li> <li><a href='documentation.html'><b>5.4.</b> ドキュメント</a> </li> <li><a href='iterators.html'><b>5.5.</b> イテレータ</a> </li> <li><a href='concurrency.html'><b>5.6.</b> 並行性</a> </li> <li><a href='error-handling.html'><b>5.7.</b> エラーハンドリング</a> </li> <li><a href='choosing-your-guarantees.html'><b>5.8.</b> 保証を選ぶ</a> </li> <li><a href='ffi.html'><b>5.9.</b> 他言語関数インターフェース</a> </li> <li><a href='borrow-and-asref.html'><b>5.10.</b> BorrowとAsRef</a> </li> <li><a href='release-channels.html'><b>5.11.</b> リリースチャネル</a> </li> <li><a href='using-rust-without-the-standard-library.html'><b>5.12.</b> 標準ライブラリ無しでRustを使う</a> </li> </ul> </li> <li><a href='nightly-rust.html'><b>6.</b> Nightly Rust</a> <ul class='section'> <li><a href='compiler-plugins.html'><b>6.1.</b> コンパイラプラグイン</a> </li> <li><a href='inline-assembly.html'><b>6.2.</b> インラインアセンブリ</a> </li> <li><a href='no-stdlib.html'><b>6.3.</b> No stdlib</a> </li> <li><a href='intrinsics.html'><b>6.4.</b> Intrinsic</a> </li> <li><a href='lang-items.html'><b>6.5.</b> 言語アイテム</a> </li> <li><a href='advanced-linking.html'><b>6.6.</b> 高度なリンキング</a> </li> <li><a href='benchmark-tests.html'><b>6.7.</b> ベンチマークテスト</a> </li> <li><a href='box-syntax-and-patterns.html'><b>6.8.</b> Box構文とパターン</a> </li> <li><a href='slice-patterns.html'><b>6.9.</b> スライスパターン</a> </li> <li><a href='associated-constants.html'><b>6.10.</b> 関連定数</a> </li> <li><a href='custom-allocators.html'><b>6.11.</b> カスタムアロケータ</a> </li> </ul> </li> <li><a href='glossary.html'><b>7.</b> 用語集</a> </li> <li><a href='syntax-index.html'><b>8.</b> 構文の索引</a> </li> <li><a href='bibliography.html'><b>9.</b> 関係書目</a> </li> </ul> </div> <div id='page-wrapper'> <div id='page'> <blockquote class="header-caveat"> <p> <strong>注意: <a href="https://doc.rust-jp.rs/book-ja/">最新版のドキュメントをご覧ください。</a></strong>この第1版ドキュメントは古くなっており、最新情報が反映されていません。リンク先のドキュメントが現在の Rust の最新のドキュメントです。 </p> </blockquote> <h1 class="title">共通の関数呼び出し構文</h1> <!-- % Universal Function Call Syntax --> <!-- Sometimes, functions can have the same names. Consider this code: --> <p>しばしば、同名の関数が存在する時があります。たとえば、以下のコードでは:</p> <span class='rusttest'>fn main() { trait Foo { fn f(&amp;self); } trait Bar { fn f(&amp;self); } struct Baz; impl Foo for Baz { fn f(&amp;self) { println!(&quot;Baz’s impl of Foo&quot;); } } impl Bar for Baz { fn f(&amp;self) { println!(&quot;Baz’s impl of Bar&quot;); } } let b = Baz; }</span><pre class='rust rust-example-rendered'> <span class='kw'>trait</span> <span class='ident'>Foo</span> { <span class='kw'>fn</span> <span class='ident'>f</span>(<span class='kw-2'>&amp;</span><span class='self'>self</span>); } <span class='kw'>trait</span> <span class='ident'>Bar</span> { <span class='kw'>fn</span> <span class='ident'>f</span>(<span class='kw-2'>&amp;</span><span class='self'>self</span>); } <span class='kw'>struct</span> <span class='ident'>Baz</span>; <span class='kw'>impl</span> <span class='ident'>Foo</span> <span class='kw'>for</span> <span class='ident'>Baz</span> { <span class='kw'>fn</span> <span class='ident'>f</span>(<span class='kw-2'>&amp;</span><span class='self'>self</span>) { <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;Baz’s impl of Foo&quot;</span>); } } <span class='kw'>impl</span> <span class='ident'>Bar</span> <span class='kw'>for</span> <span class='ident'>Baz</span> { <span class='kw'>fn</span> <span class='ident'>f</span>(<span class='kw-2'>&amp;</span><span class='self'>self</span>) { <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;Baz’s impl of Bar&quot;</span>); } } <span class='kw'>let</span> <span class='ident'>b</span> <span class='op'>=</span> <span class='ident'>Baz</span>;</pre> <!-- If we were to try to call `b.f()`, we’d get an error: --> <p>もしここで、 <code>b.f()</code> を呼びだそうとすると、以下の様なエラーが発生します:</p> <pre><code class="language-text">error: multiple applicable methods in scope [E0034] b.f(); ^~~ note: candidate #1 is defined in an impl of the trait `main::Foo` for the type `main::Baz` fn f(&amp;self) { println!(&quot;Baz’s impl of Foo&quot;); } ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ note: candidate #2 is defined in an impl of the trait `main::Bar` for the type `main::Baz` fn f(&amp;self) { println!(&quot;Baz’s impl of Bar&quot;); } ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </code></pre> <!-- We need a way to disambiguate which method we need. This feature is called --> <!-- ‘universal function call syntax’, and it looks like this: --> <p>このような場合は、どのメソッドを呼び出す必要があるのかについて曖昧性を排除する手段が必要です。 そのようなフィーチャーは 「共通の関数呼び出し構文」と呼ばれ、以下のように書けます:</p> <span class='rusttest'>fn main() { trait Foo { fn f(&amp;self); } trait Bar { fn f(&amp;self); } struct Baz; impl Foo for Baz { fn f(&amp;self) { println!(&quot;Baz’s impl of Foo&quot;); } } impl Bar for Baz { fn f(&amp;self) { println!(&quot;Baz’s impl of Bar&quot;); } } let b = Baz; Foo::f(&amp;b); Bar::f(&amp;b); }</span><pre class='rust rust-example-rendered'> <span class='ident'>Foo</span>::<span class='ident'>f</span>(<span class='kw-2'>&amp;</span><span class='ident'>b</span>); <span class='ident'>Bar</span>::<span class='ident'>f</span>(<span class='kw-2'>&amp;</span><span class='ident'>b</span>);</pre> <!-- Let’s break it down. --> <p>部分的に見ていきましょう。</p> <span class='rusttest'>fn main() { Foo:: Bar:: }</span><pre class='rust rust-example-rendered'> <span class='ident'>Foo</span>:: <span class='ident'>Bar</span>::</pre> <!-- These halves of the invocation are the types of the two traits: `Foo` and --> <!-- `Bar`. This is what ends up actually doing the disambiguation between the two: --> <!-- Rust calls the one from the trait name you use. --> <p>まず、呼び出しのこの部分は2つのトレイト <code>Foo</code> と <code>Bar</code> の型を表しています。 この部分が、実際にどちらのトレイトのメソッドを呼び出しているのかを指定し、曖昧性を排除している箇所になります。</p> <span class='rusttest'>fn main() { f(&amp;b) }</span><pre class='rust rust-example-rendered'> <span class='ident'>f</span>(<span class='kw-2'>&amp;</span><span class='ident'>b</span>)</pre> <!-- When we call a method like `b.f()` using [method syntax][methodsyntax], Rust --> <!-- will automatically borrow `b` if `f()` takes `&self`. In this case, Rust will --> <!-- not, and so we need to pass an explicit `&b`. --> <p><code>b.f()</code> のように <a href="method-syntax.html">メソッド構文</a> を利用して呼び出した時、Rustは <code>f()</code> が <code>&amp;self</code> を引数に取る場合自動的に <code>b</code> を借用します。 今回の場合は、そのようには呼び出していないので、明示的に <code>&amp;b</code> を渡してやる必要があります。</p> <h1 id='山括弧形式' class='section-header'><a href='#山括弧形式'>山括弧形式</a></h1> <!-- The form of UFCS we just talked about: --> <p>すぐ上で説明した、以下のような共通の関数呼び出し構文:</p> <span class='rusttest'>fn main() { Trait::method(args); }</span><pre class='rust rust-example-rendered'> <span class='ident'>Trait</span>::<span class='ident'>method</span>(<span class='ident'>args</span>);</pre> <!-- Is a short-hand. There’s an expanded form of this that’s needed in some --> <!-- situations: --> <p>これは短縮形であり、時々必要になる以下の様な展開された形式もあります:</p> <span class='rusttest'>fn main() { &lt;Type as Trait&gt;::method(args); }</span><pre class='rust rust-example-rendered'> <span class='op'>&lt;</span><span class='ident'>Type</span> <span class='kw'>as</span> <span class='ident'>Trait</span><span class='op'>&gt;</span>::<span class='ident'>method</span>(<span class='ident'>args</span>);</pre> <!-- The `<>::` syntax is a means of providing a type hint. The type goes inside --> <!-- the `<>`s. In this case, the type is `Type as Trait`, indicating that we want --> <!-- `Trait`’s version of `method` to be called here. The `as Trait` part is --> <!-- optional if it’s not ambiguous. Same with the angle brackets, hence the --> <!-- shorter form. --> <p><code>&lt;&gt;::</code> という構文は型のヒントを意味しており、 <code>&lt;&gt;</code> のなかに型が入ります。 この場合、型は <code>Type as Trait</code> となり、 <code>Trait</code>のバージョンの <code>method</code> が呼ばれる事を期待していることを意味しています。 <code>as Trait</code> という部分は、曖昧でない場合は省略可能です。山括弧についても同様に省略可能であり、なので先程のさらに短い形になるのです。</p> <!-- Here’s an example of using the longer form. --> <p>長い形式を用いたサンプルコードは以下の通りです:</p> <span class='rusttest'>trait Foo { fn foo() -&gt; i32; } struct Bar; impl Bar { fn foo() -&gt; i32 { 20 } } impl Foo for Bar { fn foo() -&gt; i32 { 10 } } fn main() { assert_eq!(10, &lt;Bar as Foo&gt;::foo()); assert_eq!(20, Bar::foo()); } </span><pre class='rust rust-example-rendered'> <span class='kw'>trait</span> <span class='ident'>Foo</span> { <span class='kw'>fn</span> <span class='ident'>foo</span>() <span class='op'>-&gt;</span> <span class='ident'>i32</span>; } <span class='kw'>struct</span> <span class='ident'>Bar</span>; <span class='kw'>impl</span> <span class='ident'>Bar</span> { <span class='kw'>fn</span> <span class='ident'>foo</span>() <span class='op'>-&gt;</span> <span class='ident'>i32</span> { <span class='number'>20</span> } } <span class='kw'>impl</span> <span class='ident'>Foo</span> <span class='kw'>for</span> <span class='ident'>Bar</span> { <span class='kw'>fn</span> <span class='ident'>foo</span>() <span class='op'>-&gt;</span> <span class='ident'>i32</span> { <span class='number'>10</span> } } <span class='kw'>fn</span> <span class='ident'>main</span>() { <span class='macro'>assert_eq</span><span class='macro'>!</span>(<span class='number'>10</span>, <span class='op'>&lt;</span><span class='ident'>Bar</span> <span class='kw'>as</span> <span class='ident'>Foo</span><span class='op'>&gt;</span>::<span class='ident'>foo</span>()); <span class='macro'>assert_eq</span><span class='macro'>!</span>(<span class='number'>20</span>, <span class='ident'>Bar</span>::<span class='ident'>foo</span>()); }</pre> <!-- Using the angle bracket syntax lets you call the trait method instead of the --> <!-- inherent one. --> <p>山括弧構文を用いることでトレイトのメソッドを固有メソッドの代わりに呼び出すことができます。</p> <script type="text/javascript"> window.playgroundUrl = "https://play.rust-lang.org"; </script> <script src='rustbook.js'></script> <script src='playpen.js'></script> </div></div> </body> </html> <|start_filename|>docs/1.9/nomicon/lifetime-elision.html<|end_filename|> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="generator" content="rustdoc"> <title>Lifetime Elision</title> <link rel="stylesheet" type="text/css" href="rustbook.css"> <meta name="robots" content="noindex"> </head> <body class="rustdoc"> <!--[if lte IE 8]> <div class="warning"> This old browser is unsupported and will most likely display funky things. </div> <![endif]--> <div id="nav"> <button id="toggle-nav"> <span class="sr-only">Toggle navigation</span> <span class="bar"></span> <span class="bar"></span> <span class="bar"></span> </button> </div> <div id='toc' class='mobile-hidden'> <ul class='chapter'> <li><a href='README.html'><b>1.</b> Introduction</a> </li> <li><a href='meet-safe-and-unsafe.html'><b>2.</b> Meet Safe and Unsafe</a> <ul class='section'> <li><a href='safe-unsafe-meaning.html'><b>2.1.</b> How Safe and Unsafe Interact</a> </li> <li><a href='working-with-unsafe.html'><b>2.2.</b> Working with Unsafe</a> </li> </ul> </li> <li><a href='data.html'><b>3.</b> Data Layout</a> <ul class='section'> <li><a href='repr-rust.html'><b>3.1.</b> repr(Rust)</a> </li> <li><a href='exotic-sizes.html'><b>3.2.</b> Exotically Sized Types</a> </li> <li><a href='other-reprs.html'><b>3.3.</b> Other reprs</a> </li> </ul> </li> <li><a href='ownership.html'><b>4.</b> Ownership</a> <ul class='section'> <li><a href='references.html'><b>4.1.</b> References</a> </li> <li><a href='lifetimes.html'><b>4.2.</b> Lifetimes</a> </li> <li><a href='lifetime-mismatch.html'><b>4.3.</b> Limits of Lifetimes</a> </li> <li><a class='active' href='lifetime-elision.html'><b>4.4.</b> Lifetime Elision</a> </li> <li><a href='unbounded-lifetimes.html'><b>4.5.</b> Unbounded Lifetimes</a> </li> <li><a href='hrtb.html'><b>4.6.</b> Higher-Rank Trait Bounds</a> </li> <li><a href='subtyping.html'><b>4.7.</b> Subtyping and Variance</a> </li> <li><a href='dropck.html'><b>4.8.</b> Drop Check</a> </li> <li><a href='phantom-data.html'><b>4.9.</b> PhantomData</a> </li> <li><a href='borrow-splitting.html'><b>4.10.</b> Splitting Borrows</a> </li> </ul> </li> <li><a href='conversions.html'><b>5.</b> Type Conversions</a> <ul class='section'> <li><a href='coercions.html'><b>5.1.</b> Coercions</a> </li> <li><a href='dot-operator.html'><b>5.2.</b> The Dot Operator</a> </li> <li><a href='casts.html'><b>5.3.</b> Casts</a> </li> <li><a href='transmutes.html'><b>5.4.</b> Transmutes</a> </li> </ul> </li> <li><a href='uninitialized.html'><b>6.</b> Uninitialized Memory</a> <ul class='section'> <li><a href='checked-uninit.html'><b>6.1.</b> Checked</a> </li> <li><a href='drop-flags.html'><b>6.2.</b> Drop Flags</a> </li> <li><a href='unchecked-uninit.html'><b>6.3.</b> Unchecked</a> </li> </ul> </li> <li><a href='obrm.html'><b>7.</b> Ownership Based Resource Management</a> <ul class='section'> <li><a href='constructors.html'><b>7.1.</b> Constructors</a> </li> <li><a href='destructors.html'><b>7.2.</b> Destructors</a> </li> <li><a href='leaking.html'><b>7.3.</b> Leaking</a> </li> </ul> </li> <li><a href='unwinding.html'><b>8.</b> Unwinding</a> <ul class='section'> <li><a href='exception-safety.html'><b>8.1.</b> Exception Safety</a> </li> <li><a href='poisoning.html'><b>8.2.</b> Poisoning</a> </li> </ul> </li> <li><a href='concurrency.html'><b>9.</b> Concurrency</a> <ul class='section'> <li><a href='races.html'><b>9.1.</b> Races</a> </li> <li><a href='send-and-sync.html'><b>9.2.</b> Send and Sync</a> </li> <li><a href='atomics.html'><b>9.3.</b> Atomics</a> </li> </ul> </li> <li><a href='vec.html'><b>10.</b> Implementing Vec</a> <ul class='section'> <li><a href='vec-layout.html'><b>10.1.</b> Layout</a> </li> <li><a href='vec-alloc.html'><b>10.2.</b> Allocating</a> </li> <li><a href='vec-push-pop.html'><b>10.3.</b> Push and Pop</a> </li> <li><a href='vec-dealloc.html'><b>10.4.</b> Deallocating</a> </li> <li><a href='vec-deref.html'><b>10.5.</b> Deref</a> </li> <li><a href='vec-insert-remove.html'><b>10.6.</b> Insert and Remove</a> </li> <li><a href='vec-into-iter.html'><b>10.7.</b> IntoIter</a> </li> <li><a href='vec-raw.html'><b>10.8.</b> RawVec</a> </li> <li><a href='vec-drain.html'><b>10.9.</b> Drain</a> </li> <li><a href='vec-zsts.html'><b>10.10.</b> Handling Zero-Sized Types</a> </li> <li><a href='vec-final.html'><b>10.11.</b> Final Code</a> </li> </ul> </li> <li><a href='arc-and-mutex.html'><b>11.</b> Implementing Arc and Mutex</a> </li> </ul> </div> <div id='page-wrapper'> <div id='page'> <blockquote class="header-caveat"> <p> <strong>注意: <a href="https://doc.rust-jp.rs/book-ja/">最新版のドキュメントをご覧ください。</a></strong>この第1版ドキュメントは古くなっており、最新情報が反映されていません。リンク先のドキュメントが現在の Rust の最新のドキュメントです。 </p> </blockquote> <h1 class="title">Lifetime Elision</h1> <p>In order to make common patterns more ergonomic, Rust allows lifetimes to be <em>elided</em> in function signatures.</p> <p>A <em>lifetime position</em> is anywhere you can write a lifetime in a type:</p> <span class='rusttest'>fn main() { &amp;&#39;a T &amp;&#39;a mut T T&lt;&#39;a&gt; }</span><pre class='rust rust-example-rendered'> <span class='kw-2'>&amp;</span><span class='lifetime'>&#39;a</span> <span class='ident'>T</span> <span class='kw-2'>&amp;</span><span class='lifetime'>&#39;a</span> <span class='kw-2'>mut</span> <span class='ident'>T</span> <span class='ident'>T</span><span class='op'>&lt;</span><span class='lifetime'>&#39;a</span><span class='op'>&gt;</span></pre> <p>Lifetime positions can appear as either &quot;input&quot; or &quot;output&quot;:</p> <ul> <li><p>For <code>fn</code> definitions, input refers to the types of the formal arguments in the <code>fn</code> definition, while output refers to result types. So <code>fn foo(s: &amp;str) -&gt; (&amp;str, &amp;str)</code> has elided one lifetime in input position and two lifetimes in output position. Note that the input positions of a <code>fn</code> method definition do not include the lifetimes that occur in the method&#39;s <code>impl</code> header (nor lifetimes that occur in the trait header, for a default method).</p></li> <li><p>In the future, it should be possible to elide <code>impl</code> headers in the same manner.</p></li> </ul> <p>Elision rules are as follows:</p> <ul> <li><p>Each elided lifetime in input position becomes a distinct lifetime parameter.</p></li> <li><p>If there is exactly one input lifetime position (elided or not), that lifetime is assigned to <em>all</em> elided output lifetimes.</p></li> <li><p>If there are multiple input lifetime positions, but one of them is <code>&amp;self</code> or <code>&amp;mut self</code>, the lifetime of <code>self</code> is assigned to <em>all</em> elided output lifetimes.</p></li> <li><p>Otherwise, it is an error to elide an output lifetime.</p></li> </ul> <p>Examples:</p> <span class='rusttest'>fn main() { fn print(s: &amp;str); // elided fn print&lt;&#39;a&gt;(s: &amp;&#39;a str); // expanded fn debug(lvl: uint, s: &amp;str); // elided fn debug&lt;&#39;a&gt;(lvl: uint, s: &amp;&#39;a str); // expanded fn substr(s: &amp;str, until: uint) -&gt; &amp;str; // elided fn substr&lt;&#39;a&gt;(s: &amp;&#39;a str, until: uint) -&gt; &amp;&#39;a str; // expanded fn get_str() -&gt; &amp;str; // ILLEGAL fn frob(s: &amp;str, t: &amp;str) -&gt; &amp;str; // ILLEGAL fn get_mut(&amp;mut self) -&gt; &amp;mut T; // elided fn get_mut&lt;&#39;a&gt;(&amp;&#39;a mut self) -&gt; &amp;&#39;a mut T; // expanded fn args&lt;T:ToCStr&gt;(&amp;mut self, args: &amp;[T]) -&gt; &amp;mut Command // elided fn args&lt;&#39;a, &#39;b, T:ToCStr&gt;(&amp;&#39;a mut self, args: &amp;&#39;b [T]) -&gt; &amp;&#39;a mut Command // expanded fn new(buf: &amp;mut [u8]) -&gt; BufWriter; // elided fn new&lt;&#39;a&gt;(buf: &amp;&#39;a mut [u8]) -&gt; BufWriter&lt;&#39;a&gt; // expanded }</span><pre class='rust rust-example-rendered'> <span class='kw'>fn</span> <span class='ident'>print</span>(<span class='ident'>s</span>: <span class='kw-2'>&amp;</span><span class='ident'>str</span>); <span class='comment'>// elided</span> <span class='kw'>fn</span> <span class='ident'>print</span><span class='op'>&lt;</span><span class='lifetime'>&#39;a</span><span class='op'>&gt;</span>(<span class='ident'>s</span>: <span class='kw-2'>&amp;</span><span class='lifetime'>&#39;a</span> <span class='ident'>str</span>); <span class='comment'>// expanded</span> <span class='kw'>fn</span> <span class='ident'>debug</span>(<span class='ident'>lvl</span>: <span class='ident'>uint</span>, <span class='ident'>s</span>: <span class='kw-2'>&amp;</span><span class='ident'>str</span>); <span class='comment'>// elided</span> <span class='kw'>fn</span> <span class='ident'>debug</span><span class='op'>&lt;</span><span class='lifetime'>&#39;a</span><span class='op'>&gt;</span>(<span class='ident'>lvl</span>: <span class='ident'>uint</span>, <span class='ident'>s</span>: <span class='kw-2'>&amp;</span><span class='lifetime'>&#39;a</span> <span class='ident'>str</span>); <span class='comment'>// expanded</span> <span class='kw'>fn</span> <span class='ident'>substr</span>(<span class='ident'>s</span>: <span class='kw-2'>&amp;</span><span class='ident'>str</span>, <span class='ident'>until</span>: <span class='ident'>uint</span>) <span class='op'>-&gt;</span> <span class='kw-2'>&amp;</span><span class='ident'>str</span>; <span class='comment'>// elided</span> <span class='kw'>fn</span> <span class='ident'>substr</span><span class='op'>&lt;</span><span class='lifetime'>&#39;a</span><span class='op'>&gt;</span>(<span class='ident'>s</span>: <span class='kw-2'>&amp;</span><span class='lifetime'>&#39;a</span> <span class='ident'>str</span>, <span class='ident'>until</span>: <span class='ident'>uint</span>) <span class='op'>-&gt;</span> <span class='kw-2'>&amp;</span><span class='lifetime'>&#39;a</span> <span class='ident'>str</span>; <span class='comment'>// expanded</span> <span class='kw'>fn</span> <span class='ident'>get_str</span>() <span class='op'>-&gt;</span> <span class='kw-2'>&amp;</span><span class='ident'>str</span>; <span class='comment'>// ILLEGAL</span> <span class='kw'>fn</span> <span class='ident'>frob</span>(<span class='ident'>s</span>: <span class='kw-2'>&amp;</span><span class='ident'>str</span>, <span class='ident'>t</span>: <span class='kw-2'>&amp;</span><span class='ident'>str</span>) <span class='op'>-&gt;</span> <span class='kw-2'>&amp;</span><span class='ident'>str</span>; <span class='comment'>// ILLEGAL</span> <span class='kw'>fn</span> <span class='ident'>get_mut</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>) <span class='op'>-&gt;</span> <span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='ident'>T</span>; <span class='comment'>// elided</span> <span class='kw'>fn</span> <span class='ident'>get_mut</span><span class='op'>&lt;</span><span class='lifetime'>&#39;a</span><span class='op'>&gt;</span>(<span class='kw-2'>&amp;</span><span class='lifetime'>&#39;a</span> <span class='kw-2'>mut</span> <span class='self'>self</span>) <span class='op'>-&gt;</span> <span class='kw-2'>&amp;</span><span class='lifetime'>&#39;a</span> <span class='kw-2'>mut</span> <span class='ident'>T</span>; <span class='comment'>// expanded</span> <span class='kw'>fn</span> <span class='ident'>args</span><span class='op'>&lt;</span><span class='ident'>T</span>:<span class='ident'>ToCStr</span><span class='op'>&gt;</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>, <span class='ident'>args</span>: <span class='kw-2'>&amp;</span>[<span class='ident'>T</span>]) <span class='op'>-&gt;</span> <span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='ident'>Command</span> <span class='comment'>// elided</span> <span class='kw'>fn</span> <span class='ident'>args</span><span class='op'>&lt;</span><span class='lifetime'>&#39;a</span>, <span class='lifetime'>&#39;b</span>, <span class='ident'>T</span>:<span class='ident'>ToCStr</span><span class='op'>&gt;</span>(<span class='kw-2'>&amp;</span><span class='lifetime'>&#39;a</span> <span class='kw-2'>mut</span> <span class='self'>self</span>, <span class='ident'>args</span>: <span class='kw-2'>&amp;</span><span class='lifetime'>&#39;b</span> [<span class='ident'>T</span>]) <span class='op'>-&gt;</span> <span class='kw-2'>&amp;</span><span class='lifetime'>&#39;a</span> <span class='kw-2'>mut</span> <span class='ident'>Command</span> <span class='comment'>// expanded</span> <span class='kw'>fn</span> <span class='ident'>new</span>(<span class='ident'>buf</span>: <span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> [<span class='ident'>u8</span>]) <span class='op'>-&gt;</span> <span class='ident'>BufWriter</span>; <span class='comment'>// elided</span> <span class='kw'>fn</span> <span class='ident'>new</span><span class='op'>&lt;</span><span class='lifetime'>&#39;a</span><span class='op'>&gt;</span>(<span class='ident'>buf</span>: <span class='kw-2'>&amp;</span><span class='lifetime'>&#39;a</span> <span class='kw-2'>mut</span> [<span class='ident'>u8</span>]) <span class='op'>-&gt;</span> <span class='ident'>BufWriter</span><span class='op'>&lt;</span><span class='lifetime'>&#39;a</span><span class='op'>&gt;</span> <span class='comment'>// expanded</span> </pre> <script type="text/javascript"> window.playgroundUrl = "https://play.rust-lang.org"; </script> <script src='rustbook.js'></script> <script src='playpen.js'></script> </div></div> </body> </html> <|start_filename|>docs/1.6/book/lang-items.html<|end_filename|> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="generator" content="rustdoc"> <title>言語アイテム</title> <link rel="stylesheet" type="text/css" href="rustbook.css"> <meta name="robots" content="noindex"> </head> <body class="rustdoc"> <!--[if lte IE 8]> <div class="warning"> This old browser is unsupported and will most likely display funky things. </div> <![endif]--> <div id="nav"> <button id="toggle-nav"> <span class="sr-only">Toggle navigation</span> <span class="bar"></span> <span class="bar"></span> <span class="bar"></span> </button> </div> <div id='toc' class='mobile-hidden'> <ul class='chapter'> <li><a href='README.html'><b>1.</b> Introduction</a> </li> <li><a href='getting-started.html'><b>2.</b> はじめる</a> </li> <li><a href='learn-rust.html'><b>3.</b> Rustを学ぶ</a> <ul class='section'> <li><a href='guessing-game.html'><b>3.1.</b> 数当てゲーム</a> </li> <li><a href='dining-philosophers.html'><b>3.2.</b> 食事する哲学者</a> </li> <li><a href='rust-inside-other-languages.html'><b>3.3.</b> 他言語と共存する</a> </li> </ul> </li> <li><a href='syntax-and-semantics.html'><b>4.</b> シンタックスとセマンティクス</a> <ul class='section'> <li><a href='variable-bindings.html'><b>4.1.</b> 変数束縛</a> </li> <li><a href='functions.html'><b>4.2.</b> 関数</a> </li> <li><a href='primitive-types.html'><b>4.3.</b> プリミティブ型</a> </li> <li><a href='comments.html'><b>4.4.</b> コメント</a> </li> <li><a href='if.html'><b>4.5.</b> if</a> </li> <li><a href='loops.html'><b>4.6.</b> ループ</a> </li> <li><a href='ownership.html'><b>4.7.</b> 所有権</a> </li> <li><a href='references-and-borrowing.html'><b>4.8.</b> 参照と借用</a> </li> <li><a href='lifetimes.html'><b>4.9.</b> ライフタイム</a> </li> <li><a href='mutability.html'><b>4.10.</b> ミュータビリティ</a> </li> <li><a href='structs.html'><b>4.11.</b> 構造体</a> </li> <li><a href='enums.html'><b>4.12.</b> 列挙型</a> </li> <li><a href='match.html'><b>4.13.</b> マッチ</a> </li> <li><a href='patterns.html'><b>4.14.</b> パターン</a> </li> <li><a href='method-syntax.html'><b>4.15.</b> メソッド構文</a> </li> <li><a href='vectors.html'><b>4.16.</b> ベクタ</a> </li> <li><a href='strings.html'><b>4.17.</b> 文字列</a> </li> <li><a href='generics.html'><b>4.18.</b> ジェネリクス</a> </li> <li><a href='traits.html'><b>4.19.</b> トレイト</a> </li> <li><a href='drop.html'><b>4.20.</b> Drop</a> </li> <li><a href='if-let.html'><b>4.21.</b> if let</a> </li> <li><a href='trait-objects.html'><b>4.22.</b> トレイトオブジェクト</a> </li> <li><a href='closures.html'><b>4.23.</b> クロージャ</a> </li> <li><a href='ufcs.html'><b>4.24.</b> 共通の関数呼出構文</a> </li> <li><a href='crates-and-modules.html'><b>4.25.</b> クレートとモジュール</a> </li> <li><a href='const-and-static.html'><b>4.26.</b> `const` と `static`</a> </li> <li><a href='attributes.html'><b>4.27.</b> アトリビュート</a> </li> <li><a href='type-aliases.html'><b>4.28.</b> `type` エイリアス</a> </li> <li><a href='casting-between-types.html'><b>4.29.</b> 型間のキャスト</a> </li> <li><a href='associated-types.html'><b>4.30.</b> 関連型</a> </li> <li><a href='unsized-types.html'><b>4.31.</b> サイズ不定型</a> </li> <li><a href='operators-and-overloading.html'><b>4.32.</b> 演算子とオーバーロード</a> </li> <li><a href='deref-coercions.html'><b>4.33.</b> Derefによる型強制</a> </li> <li><a href='macros.html'><b>4.34.</b> マクロ</a> </li> <li><a href='raw-pointers.html'><b>4.35.</b> 生ポインタ</a> </li> <li><a href='unsafe.html'><b>4.36.</b> `unsafe`</a> </li> </ul> </li> <li><a href='effective-rust.html'><b>5.</b> Effective Rust</a> <ul class='section'> <li><a href='the-stack-and-the-heap.html'><b>5.1.</b> スタックとヒープ</a> </li> <li><a href='testing.html'><b>5.2.</b> テスト</a> </li> <li><a href='conditional-compilation.html'><b>5.3.</b> 条件付きコンパイル</a> </li> <li><a href='documentation.html'><b>5.4.</b> ドキュメント</a> </li> <li><a href='iterators.html'><b>5.5.</b> イテレータ</a> </li> <li><a href='concurrency.html'><b>5.6.</b> 並行性</a> </li> <li><a href='error-handling.html'><b>5.7.</b> エラーハンドリング</a> </li> <li><a href='choosing-your-guarantees.html'><b>5.8.</b> 保証を選ぶ</a> </li> <li><a href='ffi.html'><b>5.9.</b> 他言語関数インターフェース</a> </li> <li><a href='borrow-and-asref.html'><b>5.10.</b> BorrowとAsRef</a> </li> <li><a href='release-channels.html'><b>5.11.</b> リリースチャネル</a> </li> <li><a href='using-rust-without-the-standard-library.html'><b>5.12.</b> 標準ライブラリ無しでRustを使う</a> </li> </ul> </li> <li><a href='nightly-rust.html'><b>6.</b> Nightly Rust</a> <ul class='section'> <li><a href='compiler-plugins.html'><b>6.1.</b> コンパイラプラグイン</a> </li> <li><a href='inline-assembly.html'><b>6.2.</b> インラインアセンブリ</a> </li> <li><a href='no-stdlib.html'><b>6.3.</b> No stdlib</a> </li> <li><a href='intrinsics.html'><b>6.4.</b> Intrinsic</a> </li> <li><a class='active' href='lang-items.html'><b>6.5.</b> 言語アイテム</a> </li> <li><a href='advanced-linking.html'><b>6.6.</b> 高度なリンキング</a> </li> <li><a href='benchmark-tests.html'><b>6.7.</b> ベンチマークテスト</a> </li> <li><a href='box-syntax-and-patterns.html'><b>6.8.</b> Box構文とパターン</a> </li> <li><a href='slice-patterns.html'><b>6.9.</b> スライスパターン</a> </li> <li><a href='associated-constants.html'><b>6.10.</b> 関連定数</a> </li> <li><a href='custom-allocators.html'><b>6.11.</b> カスタムアロケータ</a> </li> </ul> </li> <li><a href='glossary.html'><b>7.</b> 用語集</a> </li> <li><a href='syntax-index.html'><b>8.</b> 構文の索引</a> </li> <li><a href='bibliography.html'><b>9.</b> 関係書目</a> </li> </ul> </div> <div id='page-wrapper'> <div id='page'> <blockquote class="header-caveat"> <p> <strong>注意: <a href="https://doc.rust-jp.rs/book-ja/">最新版のドキュメントをご覧ください。</a></strong>この第1版ドキュメントは古くなっており、最新情報が反映されていません。リンク先のドキュメントが現在の Rust の最新のドキュメントです。 </p> </blockquote> <h1 class="title">言語アイテム</h1> <!-- % Lang items --> <!-- &gt; **Note**: lang items are often provided by crates in the Rust distribution, --> <!-- &gt; and lang items themselves have an unstable interface. It is recommended to use --> <!-- &gt; officially distributed crates instead of defining your own lang items. --> <blockquote> <p><strong>注意</strong> : 言語アイテムは大抵Rustの配布物内のクレートから提供されていますし言語アイテムのインターフェース自体安定していません。 自身で言語アイテムを定義するのではなく公式の配布物のクレートを使うことが推奨されています。</p> </blockquote> <!-- The `rustc` compiler has certain pluggable operations, that is, --> <!-- functionality that isn't hard-coded into the language, but is --> <!-- implemented in libraries, with a special marker to tell the compiler --> <!-- it exists. The marker is the attribute `#[lang = "..."]` and there are --> <!-- various different values of `...`, i.e. various different 'lang --> <!-- items'. --> <p><code>rustc</code> コンパイラはあるプラガブルな操作、つまり機能が言語にハードコードされているのではなくライブラリで実装されているものを持っており、特別なマーカによってそれが存在することをコンパイラに伝えます。 マーカとは <code>#[lang = &quot;...&quot;]</code> アトリビュートで、 <code>...</code> には様々な値が、つまり様々な「言語アイテム」あります。</p> <!-- For example, `Box` pointers require two lang items, one for allocation --> <!-- and one for deallocation. A freestanding program that uses the `Box` --> <!-- sugar for dynamic allocations via `malloc` and `free`: --> <p>例えば、 <code>Box</code> ポインタは2つの言語アイテムを必要とします。1つはアロケーションのため、もう1つはデアロケーションのため。 フリースタンディング環境で動くプログラムは <code>Box</code> を <code>malloc</code> と <code>free</code> による動的アロケーションの糖衣として使います。</p> <span class='rusttest'>#![feature(lang_items, box_syntax, start, libc)] #![no_std] extern crate libc; extern { fn abort() -&gt; !; } #[lang = &quot;owned_box&quot;] pub struct Box&lt;T&gt;(*mut T); #[lang = &quot;exchange_malloc&quot;] unsafe fn allocate(size: usize, _align: usize) -&gt; *mut u8 { let p = libc::malloc(size as libc::size_t) as *mut u8; // malloc failed if p as usize == 0 { abort(); } p } #[lang = &quot;exchange_free&quot;] unsafe fn deallocate(ptr: *mut u8, _size: usize, _align: usize) { libc::free(ptr as *mut libc::c_void) } #[start] fn main(argc: isize, argv: *const *const u8) -&gt; isize { let x = box 1; 0 } #[lang = &quot;eh_personality&quot;] extern fn eh_personality() {} #[lang = &quot;panic_fmt&quot;] fn panic_fmt() -&gt; ! { loop {} } #[lang = &quot;eh_unwind_resume&quot;] extern fn rust_eh_unwind_resume() {} #[no_mangle] pub extern fn rust_eh_register_frames () {} #[no_mangle] pub extern fn rust_eh_unregister_frames () {} </span><pre class='rust rust-example-rendered'> <span class='attribute'>#<span class='op'>!</span>[<span class='ident'>feature</span>(<span class='ident'>lang_items</span>, <span class='ident'>box_syntax</span>, <span class='ident'>start</span>, <span class='ident'>libc</span>)]</span> <span class='attribute'>#<span class='op'>!</span>[<span class='ident'>no_std</span>]</span> <span class='kw'>extern</span> <span class='kw'>crate</span> <span class='ident'>libc</span>; <span class='kw'>extern</span> { <span class='kw'>fn</span> <span class='ident'>abort</span>() <span class='op'>-&gt;</span> <span class='op'>!</span>; } <span class='attribute'>#[<span class='ident'>lang</span> <span class='op'>=</span> <span class='string'>&quot;owned_box&quot;</span>]</span> <span class='kw'>pub</span> <span class='kw'>struct</span> <span class='ident'>Box</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span>(<span class='op'>*</span><span class='kw-2'>mut</span> <span class='ident'>T</span>); <span class='attribute'>#[<span class='ident'>lang</span> <span class='op'>=</span> <span class='string'>&quot;exchange_malloc&quot;</span>]</span> <span class='kw'>unsafe</span> <span class='kw'>fn</span> <span class='ident'>allocate</span>(<span class='ident'>size</span>: <span class='ident'>usize</span>, <span class='ident'>_align</span>: <span class='ident'>usize</span>) <span class='op'>-&gt;</span> <span class='op'>*</span><span class='kw-2'>mut</span> <span class='ident'>u8</span> { <span class='kw'>let</span> <span class='ident'>p</span> <span class='op'>=</span> <span class='ident'>libc</span>::<span class='ident'>malloc</span>(<span class='ident'>size</span> <span class='kw'>as</span> <span class='ident'>libc</span>::<span class='ident'>size_t</span>) <span class='kw'>as</span> <span class='op'>*</span><span class='kw-2'>mut</span> <span class='ident'>u8</span>; <span class='comment'>// malloc failed</span> <span class='kw'>if</span> <span class='ident'>p</span> <span class='kw'>as</span> <span class='ident'>usize</span> <span class='op'>==</span> <span class='number'>0</span> { <span class='ident'>abort</span>(); } <span class='ident'>p</span> } <span class='attribute'>#[<span class='ident'>lang</span> <span class='op'>=</span> <span class='string'>&quot;exchange_free&quot;</span>]</span> <span class='kw'>unsafe</span> <span class='kw'>fn</span> <span class='ident'>deallocate</span>(<span class='ident'>ptr</span>: <span class='op'>*</span><span class='kw-2'>mut</span> <span class='ident'>u8</span>, <span class='ident'>_size</span>: <span class='ident'>usize</span>, <span class='ident'>_align</span>: <span class='ident'>usize</span>) { <span class='ident'>libc</span>::<span class='ident'>free</span>(<span class='ident'>ptr</span> <span class='kw'>as</span> <span class='op'>*</span><span class='kw-2'>mut</span> <span class='ident'>libc</span>::<span class='ident'>c_void</span>) } <span class='attribute'>#[<span class='ident'>start</span>]</span> <span class='kw'>fn</span> <span class='ident'>main</span>(<span class='ident'>argc</span>: <span class='ident'>isize</span>, <span class='ident'>argv</span>: <span class='op'>*</span><span class='kw'>const</span> <span class='op'>*</span><span class='kw'>const</span> <span class='ident'>u8</span>) <span class='op'>-&gt;</span> <span class='ident'>isize</span> { <span class='kw'>let</span> <span class='ident'>x</span> <span class='op'>=</span> <span class='kw'>box</span> <span class='number'>1</span>; <span class='number'>0</span> } <span class='attribute'>#[<span class='ident'>lang</span> <span class='op'>=</span> <span class='string'>&quot;eh_personality&quot;</span>]</span> <span class='kw'>extern</span> <span class='kw'>fn</span> <span class='ident'>eh_personality</span>() {} <span class='attribute'>#[<span class='ident'>lang</span> <span class='op'>=</span> <span class='string'>&quot;panic_fmt&quot;</span>]</span> <span class='kw'>fn</span> <span class='ident'>panic_fmt</span>() <span class='op'>-&gt;</span> <span class='op'>!</span> { <span class='kw'>loop</span> {} }</pre> <!-- Note the use of `abort`: the `exchange_malloc` lang item is assumed to --> <!-- return a valid pointer, and so needs to do the check internally. --> <p><code>abort</code> を使ってることに注意して下さい: <code>exchange_malloc</code> 言語アイテムは有効なポインタを返すものとされており、内部でその検査をする必要があるのです。</p> <!-- Other features provided by lang items include: --> <p>言語アイテムによって提供される機能には以下のようなものがあります。:</p> <!-- - overloadable operators via traits: the traits corresponding to the --> <!-- `==`, `<`, dereferencing (`*`) and `+` (etc.) operators are all --> <!-- marked with lang items; those specific four are `eq`, `ord`, --> <!-- `deref`, and `add` respectively. --> <!-- - stack unwinding and general failure; the `eh_personality`, `fail` --> <!-- and `fail_bounds_checks` lang items. --> <!-- - the traits in `std::marker` used to indicate types of --> <!-- various kinds; lang items `send`, `sync` and `copy`. --> <!-- - the marker types and variance indicators found in --> <!-- `std::marker`; lang items `covariant_type`, --> <!-- `contravariant_lifetime`, etc. --> <ul> <li>トレイトによるオーバーロード可能な演算子: <code>==</code> 、 <code>&lt;</code> 、 参照外し( <code>*</code> ) そして <code>+</code> (など)の演算子は全て言語アイテムでマークされています。 これら4つはそれぞれ <code>eq</code> 、 <code>ord</code> 、 <code>deref</code> 、 <code>add</code> です</li> <li>スタックの巻き戻しと一般の失敗は <code>eh_personality</code> 、 <code>fail</code> そして <code>fail_bounds_check</code> 言語アイテムです。</li> <li><code>std::marker</code> 内のトレイトで様々な型を示すのに使われています。 <code>send</code> 、 <code>sync</code> そして <code>copy</code> 言語アイテム。</li> <li>マーカ型と <code>std::marker</code> にある変性指示子。 <code>covariant_type</code> 、 <code>contravariant_lifetime</code> 言語アイテムなどなど。</li> </ul> <!-- Lang items are loaded lazily by the compiler; e.g. if one never uses --> <!-- `Box` then there is no need to define functions for `exchange_malloc` --> <!-- and `exchange_free`. `rustc` will emit an error when an item is needed --> <!-- but not found in the current crate or any that it depends on. --> <p>言語アイテムはコンパイラによって必要に応じてロードされます、例えば、 <code>Box</code> を一度も使わないなら <code>exchange_malloc</code> と <code>exchange_free</code> の関数を定義する必要はありません。 <code>rustc</code> はアイテムが必要なのに現在のクレートあるいはその依存するクレート内で見付からないときにエラーを出します。</p> <script type="text/javascript"> window.playgroundUrl = "https://play.rust-lang.org"; </script> <script src='rustbook.js'></script> <script src='playpen.js'></script> </div></div> </body> </html> <|start_filename|>docs/1.9/nomicon/repr-rust.html<|end_filename|> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="generator" content="rustdoc"> <title>repr(Rust)</title> <link rel="stylesheet" type="text/css" href="rustbook.css"> <meta name="robots" content="noindex"> </head> <body class="rustdoc"> <!--[if lte IE 8]> <div class="warning"> This old browser is unsupported and will most likely display funky things. </div> <![endif]--> <div id="nav"> <button id="toggle-nav"> <span class="sr-only">Toggle navigation</span> <span class="bar"></span> <span class="bar"></span> <span class="bar"></span> </button> </div> <div id='toc' class='mobile-hidden'> <ul class='chapter'> <li><a href='README.html'><b>1.</b> Introduction</a> </li> <li><a href='meet-safe-and-unsafe.html'><b>2.</b> Meet Safe and Unsafe</a> <ul class='section'> <li><a href='safe-unsafe-meaning.html'><b>2.1.</b> How Safe and Unsafe Interact</a> </li> <li><a href='working-with-unsafe.html'><b>2.2.</b> Working with Unsafe</a> </li> </ul> </li> <li><a href='data.html'><b>3.</b> Data Layout</a> <ul class='section'> <li><a class='active' href='repr-rust.html'><b>3.1.</b> repr(Rust)</a> </li> <li><a href='exotic-sizes.html'><b>3.2.</b> Exotically Sized Types</a> </li> <li><a href='other-reprs.html'><b>3.3.</b> Other reprs</a> </li> </ul> </li> <li><a href='ownership.html'><b>4.</b> Ownership</a> <ul class='section'> <li><a href='references.html'><b>4.1.</b> References</a> </li> <li><a href='lifetimes.html'><b>4.2.</b> Lifetimes</a> </li> <li><a href='lifetime-mismatch.html'><b>4.3.</b> Limits of Lifetimes</a> </li> <li><a href='lifetime-elision.html'><b>4.4.</b> Lifetime Elision</a> </li> <li><a href='unbounded-lifetimes.html'><b>4.5.</b> Unbounded Lifetimes</a> </li> <li><a href='hrtb.html'><b>4.6.</b> Higher-Rank Trait Bounds</a> </li> <li><a href='subtyping.html'><b>4.7.</b> Subtyping and Variance</a> </li> <li><a href='dropck.html'><b>4.8.</b> Drop Check</a> </li> <li><a href='phantom-data.html'><b>4.9.</b> PhantomData</a> </li> <li><a href='borrow-splitting.html'><b>4.10.</b> Splitting Borrows</a> </li> </ul> </li> <li><a href='conversions.html'><b>5.</b> Type Conversions</a> <ul class='section'> <li><a href='coercions.html'><b>5.1.</b> Coercions</a> </li> <li><a href='dot-operator.html'><b>5.2.</b> The Dot Operator</a> </li> <li><a href='casts.html'><b>5.3.</b> Casts</a> </li> <li><a href='transmutes.html'><b>5.4.</b> Transmutes</a> </li> </ul> </li> <li><a href='uninitialized.html'><b>6.</b> Uninitialized Memory</a> <ul class='section'> <li><a href='checked-uninit.html'><b>6.1.</b> Checked</a> </li> <li><a href='drop-flags.html'><b>6.2.</b> Drop Flags</a> </li> <li><a href='unchecked-uninit.html'><b>6.3.</b> Unchecked</a> </li> </ul> </li> <li><a href='obrm.html'><b>7.</b> Ownership Based Resource Management</a> <ul class='section'> <li><a href='constructors.html'><b>7.1.</b> Constructors</a> </li> <li><a href='destructors.html'><b>7.2.</b> Destructors</a> </li> <li><a href='leaking.html'><b>7.3.</b> Leaking</a> </li> </ul> </li> <li><a href='unwinding.html'><b>8.</b> Unwinding</a> <ul class='section'> <li><a href='exception-safety.html'><b>8.1.</b> Exception Safety</a> </li> <li><a href='poisoning.html'><b>8.2.</b> Poisoning</a> </li> </ul> </li> <li><a href='concurrency.html'><b>9.</b> Concurrency</a> <ul class='section'> <li><a href='races.html'><b>9.1.</b> Races</a> </li> <li><a href='send-and-sync.html'><b>9.2.</b> Send and Sync</a> </li> <li><a href='atomics.html'><b>9.3.</b> Atomics</a> </li> </ul> </li> <li><a href='vec.html'><b>10.</b> Implementing Vec</a> <ul class='section'> <li><a href='vec-layout.html'><b>10.1.</b> Layout</a> </li> <li><a href='vec-alloc.html'><b>10.2.</b> Allocating</a> </li> <li><a href='vec-push-pop.html'><b>10.3.</b> Push and Pop</a> </li> <li><a href='vec-dealloc.html'><b>10.4.</b> Deallocating</a> </li> <li><a href='vec-deref.html'><b>10.5.</b> Deref</a> </li> <li><a href='vec-insert-remove.html'><b>10.6.</b> Insert and Remove</a> </li> <li><a href='vec-into-iter.html'><b>10.7.</b> IntoIter</a> </li> <li><a href='vec-raw.html'><b>10.8.</b> RawVec</a> </li> <li><a href='vec-drain.html'><b>10.9.</b> Drain</a> </li> <li><a href='vec-zsts.html'><b>10.10.</b> Handling Zero-Sized Types</a> </li> <li><a href='vec-final.html'><b>10.11.</b> Final Code</a> </li> </ul> </li> <li><a href='arc-and-mutex.html'><b>11.</b> Implementing Arc and Mutex</a> </li> </ul> </div> <div id='page-wrapper'> <div id='page'> <blockquote class="header-caveat"> <p> <strong>注意: <a href="https://doc.rust-jp.rs/book-ja/">最新版のドキュメントをご覧ください。</a></strong>この第1版ドキュメントは古くなっており、最新情報が反映されていません。リンク先のドキュメントが現在の Rust の最新のドキュメントです。 </p> </blockquote> <h1 class="title">repr(Rust)</h1> <p>First and foremost, all types have an alignment specified in bytes. The alignment of a type specifies what addresses are valid to store the value at. A value of alignment <code>n</code> must only be stored at an address that is a multiple of <code>n</code>. So alignment 2 means you must be stored at an even address, and 1 means that you can be stored anywhere. Alignment is at least 1, and always a power of 2. Most primitives are generally aligned to their size, although this is platform-specific behavior. In particular, on x86 <code>u64</code> and <code>f64</code> may be only aligned to 32 bits.</p> <p>A type&#39;s size must always be a multiple of its alignment. This ensures that an array of that type may always be indexed by offsetting by a multiple of its size. Note that the size and alignment of a type may not be known statically in the case of <a href="exotic-sizes.html#dynamically-sized-types-dsts">dynamically sized types</a>.</p> <p>Rust gives you the following ways to lay out composite data:</p> <ul> <li>structs (named product types)</li> <li>tuples (anonymous product types)</li> <li>arrays (homogeneous product types)</li> <li>enums (named sum types -- tagged unions)</li> </ul> <p>An enum is said to be <em>C-like</em> if none of its variants have associated data.</p> <p>Composite structures will have an alignment equal to the maximum of their fields&#39; alignment. Rust will consequently insert padding where necessary to ensure that all fields are properly aligned and that the overall type&#39;s size is a multiple of its alignment. For instance:</p> <span class='rusttest'>fn main() { struct A { a: u8, b: u32, c: u16, } }</span><pre class='rust rust-example-rendered'> <span class='kw'>struct</span> <span class='ident'>A</span> { <span class='ident'>a</span>: <span class='ident'>u8</span>, <span class='ident'>b</span>: <span class='ident'>u32</span>, <span class='ident'>c</span>: <span class='ident'>u16</span>, }</pre> <p>will be 32-bit aligned on an architecture that aligns these primitives to their respective sizes. The whole struct will therefore have a size that is a multiple of 32-bits. It will potentially become:</p> <span class='rusttest'>fn main() { struct A { a: u8, _pad1: [u8; 3], // to align `b` b: u32, c: u16, _pad2: [u8; 2], // to make overall size multiple of 4 } }</span><pre class='rust rust-example-rendered'> <span class='kw'>struct</span> <span class='ident'>A</span> { <span class='ident'>a</span>: <span class='ident'>u8</span>, <span class='ident'>_pad1</span>: [<span class='ident'>u8</span>; <span class='number'>3</span>], <span class='comment'>// to align `b`</span> <span class='ident'>b</span>: <span class='ident'>u32</span>, <span class='ident'>c</span>: <span class='ident'>u16</span>, <span class='ident'>_pad2</span>: [<span class='ident'>u8</span>; <span class='number'>2</span>], <span class='comment'>// to make overall size multiple of 4</span> }</pre> <p>There is <em>no indirection</em> for these types; all data is stored within the struct, as you would expect in C. However with the exception of arrays (which are densely packed and in-order), the layout of data is not by default specified in Rust. Given the two following struct definitions:</p> <span class='rusttest'>fn main() { struct A { a: i32, b: u64, } struct B { a: i32, b: u64, } }</span><pre class='rust rust-example-rendered'> <span class='kw'>struct</span> <span class='ident'>A</span> { <span class='ident'>a</span>: <span class='ident'>i32</span>, <span class='ident'>b</span>: <span class='ident'>u64</span>, } <span class='kw'>struct</span> <span class='ident'>B</span> { <span class='ident'>a</span>: <span class='ident'>i32</span>, <span class='ident'>b</span>: <span class='ident'>u64</span>, }</pre> <p>Rust <em>does</em> guarantee that two instances of A have their data laid out in exactly the same way. However Rust <em>does not</em> currently guarantee that an instance of A has the same field ordering or padding as an instance of B, though in practice there&#39;s no reason why they wouldn&#39;t.</p> <p>With A and B as written, this point would seem to be pedantic, but several other features of Rust make it desirable for the language to play with data layout in complex ways.</p> <p>For instance, consider this struct:</p> <span class='rusttest'>fn main() { struct Foo&lt;T, U&gt; { count: u16, data1: T, data2: U, } }</span><pre class='rust rust-example-rendered'> <span class='kw'>struct</span> <span class='ident'>Foo</span><span class='op'>&lt;</span><span class='ident'>T</span>, <span class='ident'>U</span><span class='op'>&gt;</span> { <span class='ident'>count</span>: <span class='ident'>u16</span>, <span class='ident'>data1</span>: <span class='ident'>T</span>, <span class='ident'>data2</span>: <span class='ident'>U</span>, }</pre> <p>Now consider the monomorphizations of <code>Foo&lt;u32, u16&gt;</code> and <code>Foo&lt;u16, u32&gt;</code>. If Rust lays out the fields in the order specified, we expect it to pad the values in the struct to satisfy their alignment requirements. So if Rust didn&#39;t reorder fields, we would expect it to produce the following:</p> <span class='rusttest'>fn main() { struct Foo&lt;u16, u32&gt; { count: u16, data1: u16, data2: u32, } struct Foo&lt;u32, u16&gt; { count: u16, _pad1: u16, data1: u32, data2: u16, _pad2: u16, } }</span><pre class='rust rust-example-rendered'> <span class='kw'>struct</span> <span class='ident'>Foo</span><span class='op'>&lt;</span><span class='ident'>u16</span>, <span class='ident'>u32</span><span class='op'>&gt;</span> { <span class='ident'>count</span>: <span class='ident'>u16</span>, <span class='ident'>data1</span>: <span class='ident'>u16</span>, <span class='ident'>data2</span>: <span class='ident'>u32</span>, } <span class='kw'>struct</span> <span class='ident'>Foo</span><span class='op'>&lt;</span><span class='ident'>u32</span>, <span class='ident'>u16</span><span class='op'>&gt;</span> { <span class='ident'>count</span>: <span class='ident'>u16</span>, <span class='ident'>_pad1</span>: <span class='ident'>u16</span>, <span class='ident'>data1</span>: <span class='ident'>u32</span>, <span class='ident'>data2</span>: <span class='ident'>u16</span>, <span class='ident'>_pad2</span>: <span class='ident'>u16</span>, }</pre> <p>The latter case quite simply wastes space. An optimal use of space therefore requires different monomorphizations to have <em>different field orderings</em>.</p> <p><strong>Note: this is a hypothetical optimization that is not yet implemented in Rust 1.0</strong></p> <p>Enums make this consideration even more complicated. Naively, an enum such as:</p> <span class='rusttest'>fn main() { enum Foo { A(u32), B(u64), C(u8), } }</span><pre class='rust rust-example-rendered'> <span class='kw'>enum</span> <span class='ident'>Foo</span> { <span class='ident'>A</span>(<span class='ident'>u32</span>), <span class='ident'>B</span>(<span class='ident'>u64</span>), <span class='ident'>C</span>(<span class='ident'>u8</span>), }</pre> <p>would be laid out as:</p> <span class='rusttest'>fn main() { struct FooRepr { data: u64, // this is either a u64, u32, or u8 based on `tag` tag: u8, // 0 = A, 1 = B, 2 = C } }</span><pre class='rust rust-example-rendered'> <span class='kw'>struct</span> <span class='ident'>FooRepr</span> { <span class='ident'>data</span>: <span class='ident'>u64</span>, <span class='comment'>// this is either a u64, u32, or u8 based on `tag`</span> <span class='ident'>tag</span>: <span class='ident'>u8</span>, <span class='comment'>// 0 = A, 1 = B, 2 = C</span> }</pre> <p>And indeed this is approximately how it would be laid out in general (modulo the size and position of <code>tag</code>).</p> <p>However there are several cases where such a representation is inefficient. The classic case of this is Rust&#39;s &quot;null pointer optimization&quot;: an enum consisting of a single outer unit variant (e.g. <code>None</code>) and a (potentially nested) non- nullable pointer variant (e.g. <code>&amp;T</code>) makes the tag unnecessary, because a null pointer value can safely be interpreted to mean that the unit variant is chosen instead. The net result is that, for example, <code>size_of::&lt;Option&lt;&amp;T&gt;&gt;() == size_of::&lt;&amp;T&gt;()</code>.</p> <p>There are many types in Rust that are, or contain, non-nullable pointers such as <code>Box&lt;T&gt;</code>, <code>Vec&lt;T&gt;</code>, <code>String</code>, <code>&amp;T</code>, and <code>&amp;mut T</code>. Similarly, one can imagine nested enums pooling their tags into a single discriminant, as they are by definition known to have a limited range of valid values. In principle enums could use fairly elaborate algorithms to cache bits throughout nested types with special constrained representations. As such it is <em>especially</em> desirable that we leave enum layout unspecified today.</p> <script type="text/javascript"> window.playgroundUrl = "https://play.rust-lang.org"; </script> <script src='rustbook.js'></script> <script src='playpen.js'></script> </div></div> </body> </html> <|start_filename|>docs/1.6/book/box-syntax-and-patterns.html<|end_filename|> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="generator" content="rustdoc"> <title>Box構文とパターン</title> <link rel="stylesheet" type="text/css" href="rustbook.css"> <meta name="robots" content="noindex"> </head> <body class="rustdoc"> <!--[if lte IE 8]> <div class="warning"> This old browser is unsupported and will most likely display funky things. </div> <![endif]--> <div id="nav"> <button id="toggle-nav"> <span class="sr-only">Toggle navigation</span> <span class="bar"></span> <span class="bar"></span> <span class="bar"></span> </button> </div> <div id='toc' class='mobile-hidden'> <ul class='chapter'> <li><a href='README.html'><b>1.</b> Introduction</a> </li> <li><a href='getting-started.html'><b>2.</b> はじめる</a> </li> <li><a href='learn-rust.html'><b>3.</b> Rustを学ぶ</a> <ul class='section'> <li><a href='guessing-game.html'><b>3.1.</b> 数当てゲーム</a> </li> <li><a href='dining-philosophers.html'><b>3.2.</b> 食事する哲学者</a> </li> <li><a href='rust-inside-other-languages.html'><b>3.3.</b> 他言語と共存する</a> </li> </ul> </li> <li><a href='syntax-and-semantics.html'><b>4.</b> シンタックスとセマンティクス</a> <ul class='section'> <li><a href='variable-bindings.html'><b>4.1.</b> 変数束縛</a> </li> <li><a href='functions.html'><b>4.2.</b> 関数</a> </li> <li><a href='primitive-types.html'><b>4.3.</b> プリミティブ型</a> </li> <li><a href='comments.html'><b>4.4.</b> コメント</a> </li> <li><a href='if.html'><b>4.5.</b> if</a> </li> <li><a href='loops.html'><b>4.6.</b> ループ</a> </li> <li><a href='ownership.html'><b>4.7.</b> 所有権</a> </li> <li><a href='references-and-borrowing.html'><b>4.8.</b> 参照と借用</a> </li> <li><a href='lifetimes.html'><b>4.9.</b> ライフタイム</a> </li> <li><a href='mutability.html'><b>4.10.</b> ミュータビリティ</a> </li> <li><a href='structs.html'><b>4.11.</b> 構造体</a> </li> <li><a href='enums.html'><b>4.12.</b> 列挙型</a> </li> <li><a href='match.html'><b>4.13.</b> マッチ</a> </li> <li><a href='patterns.html'><b>4.14.</b> パターン</a> </li> <li><a href='method-syntax.html'><b>4.15.</b> メソッド構文</a> </li> <li><a href='vectors.html'><b>4.16.</b> ベクタ</a> </li> <li><a href='strings.html'><b>4.17.</b> 文字列</a> </li> <li><a href='generics.html'><b>4.18.</b> ジェネリクス</a> </li> <li><a href='traits.html'><b>4.19.</b> トレイト</a> </li> <li><a href='drop.html'><b>4.20.</b> Drop</a> </li> <li><a href='if-let.html'><b>4.21.</b> if let</a> </li> <li><a href='trait-objects.html'><b>4.22.</b> トレイトオブジェクト</a> </li> <li><a href='closures.html'><b>4.23.</b> クロージャ</a> </li> <li><a href='ufcs.html'><b>4.24.</b> 共通の関数呼出構文</a> </li> <li><a href='crates-and-modules.html'><b>4.25.</b> クレートとモジュール</a> </li> <li><a href='const-and-static.html'><b>4.26.</b> `const` と `static`</a> </li> <li><a href='attributes.html'><b>4.27.</b> アトリビュート</a> </li> <li><a href='type-aliases.html'><b>4.28.</b> `type` エイリアス</a> </li> <li><a href='casting-between-types.html'><b>4.29.</b> 型間のキャスト</a> </li> <li><a href='associated-types.html'><b>4.30.</b> 関連型</a> </li> <li><a href='unsized-types.html'><b>4.31.</b> サイズ不定型</a> </li> <li><a href='operators-and-overloading.html'><b>4.32.</b> 演算子とオーバーロード</a> </li> <li><a href='deref-coercions.html'><b>4.33.</b> Derefによる型強制</a> </li> <li><a href='macros.html'><b>4.34.</b> マクロ</a> </li> <li><a href='raw-pointers.html'><b>4.35.</b> 生ポインタ</a> </li> <li><a href='unsafe.html'><b>4.36.</b> `unsafe`</a> </li> </ul> </li> <li><a href='effective-rust.html'><b>5.</b> Effective Rust</a> <ul class='section'> <li><a href='the-stack-and-the-heap.html'><b>5.1.</b> スタックとヒープ</a> </li> <li><a href='testing.html'><b>5.2.</b> テスト</a> </li> <li><a href='conditional-compilation.html'><b>5.3.</b> 条件付きコンパイル</a> </li> <li><a href='documentation.html'><b>5.4.</b> ドキュメント</a> </li> <li><a href='iterators.html'><b>5.5.</b> イテレータ</a> </li> <li><a href='concurrency.html'><b>5.6.</b> 並行性</a> </li> <li><a href='error-handling.html'><b>5.7.</b> エラーハンドリング</a> </li> <li><a href='choosing-your-guarantees.html'><b>5.8.</b> 保証を選ぶ</a> </li> <li><a href='ffi.html'><b>5.9.</b> 他言語関数インターフェース</a> </li> <li><a href='borrow-and-asref.html'><b>5.10.</b> BorrowとAsRef</a> </li> <li><a href='release-channels.html'><b>5.11.</b> リリースチャネル</a> </li> <li><a href='using-rust-without-the-standard-library.html'><b>5.12.</b> 標準ライブラリ無しでRustを使う</a> </li> </ul> </li> <li><a href='nightly-rust.html'><b>6.</b> Nightly Rust</a> <ul class='section'> <li><a href='compiler-plugins.html'><b>6.1.</b> コンパイラプラグイン</a> </li> <li><a href='inline-assembly.html'><b>6.2.</b> インラインアセンブリ</a> </li> <li><a href='no-stdlib.html'><b>6.3.</b> No stdlib</a> </li> <li><a href='intrinsics.html'><b>6.4.</b> Intrinsic</a> </li> <li><a href='lang-items.html'><b>6.5.</b> 言語アイテム</a> </li> <li><a href='advanced-linking.html'><b>6.6.</b> 高度なリンキング</a> </li> <li><a href='benchmark-tests.html'><b>6.7.</b> ベンチマークテスト</a> </li> <li><a class='active' href='box-syntax-and-patterns.html'><b>6.8.</b> Box構文とパターン</a> </li> <li><a href='slice-patterns.html'><b>6.9.</b> スライスパターン</a> </li> <li><a href='associated-constants.html'><b>6.10.</b> 関連定数</a> </li> <li><a href='custom-allocators.html'><b>6.11.</b> カスタムアロケータ</a> </li> </ul> </li> <li><a href='glossary.html'><b>7.</b> 用語集</a> </li> <li><a href='syntax-index.html'><b>8.</b> 構文の索引</a> </li> <li><a href='bibliography.html'><b>9.</b> 関係書目</a> </li> </ul> </div> <div id='page-wrapper'> <div id='page'> <blockquote class="header-caveat"> <p> <strong>注意: <a href="https://doc.rust-jp.rs/book-ja/">最新版のドキュメントをご覧ください。</a></strong>この第1版ドキュメントは古くなっており、最新情報が反映されていません。リンク先のドキュメントが現在の Rust の最新のドキュメントです。 </p> </blockquote> <h1 class="title">Box構文とパターン</h1> <!-- % Box Syntax and Patterns --> <!-- Currently the only stable way to create a `Box` is via the `Box::new` method. --> <!-- Also it is not possible in stable Rust to destructure a `Box` in a match --> <!-- pattern. The unstable `box` keyword can be used to both create and destructure --> <!-- a `Box`. An example usage would be: --> <p>今のところ、安定版において <code>Box</code> を作成する唯一の方法は <code>Box::new</code> メソッドです。安定版のRustではパターンマッチで <code>Box</code> を分解することもできません。不安定版の <code>box</code> キーワードは <code>Box</code> の作成と分解の両方に使えます。使い方は以下の通りです。</p> <span class='rusttest'>#![feature(box_syntax, box_patterns)] fn main() { let b = Some(box 5); match b { Some(box n) if n &lt; 0 =&gt; { println!(&quot;Box contains negative number {}&quot;, n); }, Some(box n) if n &gt;= 0 =&gt; { println!(&quot;Box contains non-negative number {}&quot;, n); }, None =&gt; { println!(&quot;No box&quot;); }, _ =&gt; unreachable!() } } </span><pre class='rust rust-example-rendered'> <span class='attribute'>#<span class='op'>!</span>[<span class='ident'>feature</span>(<span class='ident'>box_syntax</span>, <span class='ident'>box_patterns</span>)]</span> <span class='kw'>fn</span> <span class='ident'>main</span>() { <span class='kw'>let</span> <span class='ident'>b</span> <span class='op'>=</span> <span class='prelude-val'>Some</span>(<span class='kw'>box</span> <span class='number'>5</span>); <span class='kw'>match</span> <span class='ident'>b</span> { <span class='prelude-val'>Some</span>(<span class='kw'>box</span> <span class='ident'>n</span>) <span class='kw'>if</span> <span class='ident'>n</span> <span class='op'>&lt;</span> <span class='number'>0</span> <span class='op'>=&gt;</span> { <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;Box contains negative number {}&quot;</span>, <span class='ident'>n</span>); }, <span class='prelude-val'>Some</span>(<span class='kw'>box</span> <span class='ident'>n</span>) <span class='kw'>if</span> <span class='ident'>n</span> <span class='op'>&gt;=</span> <span class='number'>0</span> <span class='op'>=&gt;</span> { <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;Box contains non-negative number {}&quot;</span>, <span class='ident'>n</span>); }, <span class='prelude-val'>None</span> <span class='op'>=&gt;</span> { <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;No box&quot;</span>); }, _ <span class='op'>=&gt;</span> <span class='macro'>unreachable</span><span class='macro'>!</span>() } }</pre> <!-- Note that these features are currently hidden behind the `box_syntax` (box --> <!-- creation) and `box_patterns` (destructuring and pattern matching) gates --> <!-- because the syntax may still change in the future. --> <p>注記: 将来的にこの構文は変わる可能性があるため、現時点でこれらのフィーチャは <code>box_syntax</code> (boxの作成)、 <code>box_patterns</code> (分解とパターンマッチ)を明示しなければ使えません。</p> <!-- # Returning Pointers --> <h1 id='ポインタ返し' class='section-header'><a href='#ポインタ返し'>ポインタ返し</a></h1> <!-- In many languages with pointers, you'd return a pointer from a function --> <!-- so as to avoid copying a large data structure. For example: --> <p>ポインタを持つ多くのプログラミング言語では、巨大なデータ構造のコピーを避けるため、関数からポインタを返してきました。例えば以下のように書くことができます。</p> <span class='rusttest'>struct BigStruct { one: i32, two: i32, // etc one_hundred: i32, } fn foo(x: Box&lt;BigStruct&gt;) -&gt; Box&lt;BigStruct&gt; { Box::new(*x) } fn main() { let x = Box::new(BigStruct { one: 1, two: 2, one_hundred: 100, }); let y = foo(x); } </span><pre class='rust rust-example-rendered'> <span class='kw'>struct</span> <span class='ident'>BigStruct</span> { <span class='ident'>one</span>: <span class='ident'>i32</span>, <span class='ident'>two</span>: <span class='ident'>i32</span>, <span class='comment'>// etc</span> <span class='ident'>one_hundred</span>: <span class='ident'>i32</span>, } <span class='kw'>fn</span> <span class='ident'>foo</span>(<span class='ident'>x</span>: <span class='ident'>Box</span><span class='op'>&lt;</span><span class='ident'>BigStruct</span><span class='op'>&gt;</span>) <span class='op'>-&gt;</span> <span class='ident'>Box</span><span class='op'>&lt;</span><span class='ident'>BigStruct</span><span class='op'>&gt;</span> { <span class='ident'>Box</span>::<span class='ident'>new</span>(<span class='op'>*</span><span class='ident'>x</span>) } <span class='kw'>fn</span> <span class='ident'>main</span>() { <span class='kw'>let</span> <span class='ident'>x</span> <span class='op'>=</span> <span class='ident'>Box</span>::<span class='ident'>new</span>(<span class='ident'>BigStruct</span> { <span class='ident'>one</span>: <span class='number'>1</span>, <span class='ident'>two</span>: <span class='number'>2</span>, <span class='ident'>one_hundred</span>: <span class='number'>100</span>, }); <span class='kw'>let</span> <span class='ident'>y</span> <span class='op'>=</span> <span class='ident'>foo</span>(<span class='ident'>x</span>); }</pre> <!-- The idea is that by passing around a box, you're only copying a pointer, rather --> <!-- than the hundred `i32`s that make up the `BigStruct`. --> <p>考え方としては、boxで渡すことで <code>BigStruct</code> を構成する100個の <code>i32</code> の代わりにポインタのみのコピーで済む、というものです。</p> <!-- This is an antipattern in Rust. Instead, write this: --> <p>これはRustではアンチパターンです。代わりに以下のように書きます。</p> <span class='rusttest'>#![feature(box_syntax)] struct BigStruct { one: i32, two: i32, // etc one_hundred: i32, } fn foo(x: Box&lt;BigStruct&gt;) -&gt; BigStruct { *x } fn main() { let x = Box::new(BigStruct { one: 1, two: 2, one_hundred: 100, }); let y: Box&lt;BigStruct&gt; = box foo(x); } </span><pre class='rust rust-example-rendered'> <span class='attribute'>#<span class='op'>!</span>[<span class='ident'>feature</span>(<span class='ident'>box_syntax</span>)]</span> <span class='kw'>struct</span> <span class='ident'>BigStruct</span> { <span class='ident'>one</span>: <span class='ident'>i32</span>, <span class='ident'>two</span>: <span class='ident'>i32</span>, <span class='comment'>// etc</span> <span class='ident'>one_hundred</span>: <span class='ident'>i32</span>, } <span class='kw'>fn</span> <span class='ident'>foo</span>(<span class='ident'>x</span>: <span class='ident'>Box</span><span class='op'>&lt;</span><span class='ident'>BigStruct</span><span class='op'>&gt;</span>) <span class='op'>-&gt;</span> <span class='ident'>BigStruct</span> { <span class='op'>*</span><span class='ident'>x</span> } <span class='kw'>fn</span> <span class='ident'>main</span>() { <span class='kw'>let</span> <span class='ident'>x</span> <span class='op'>=</span> <span class='ident'>Box</span>::<span class='ident'>new</span>(<span class='ident'>BigStruct</span> { <span class='ident'>one</span>: <span class='number'>1</span>, <span class='ident'>two</span>: <span class='number'>2</span>, <span class='ident'>one_hundred</span>: <span class='number'>100</span>, }); <span class='kw'>let</span> <span class='ident'>y</span>: <span class='ident'>Box</span><span class='op'>&lt;</span><span class='ident'>BigStruct</span><span class='op'>&gt;</span> <span class='op'>=</span> <span class='kw'>box</span> <span class='ident'>foo</span>(<span class='ident'>x</span>); }</pre> <!-- This gives you flexibility without sacrificing performance. --> <p>このように書くことでパフォーマンスを犠牲にすることなく、柔軟性を確保することができます。</p> <!-- You may think that this gives us terrible performance: return a value and then --> <!-- immediately box it up ?! Isn't this pattern the worst of both worlds? Rust is --> <!-- smarter than that. There is no copy in this code. `main` allocates enough room --> <!-- for the `box`, passes a pointer to that memory into `foo` as `x`, and then --> <!-- `foo` writes the value straight into the `Box<T>`. --> <p>このコードはひどいパフォーマンス低下をもたらすと感じるかもしれません。値を返して即座にboxに入れるなんて?! このパターンは悪いところどりになっているのでは? Rustはもう少し賢いため、このコードでコピーは発生しません。 <code>main</code> 内では <code>box</code> のために十分なメモリ領域を確保し、そのメモリへのポインタを <code>foo</code> へ <code>x</code> として渡します。 <code>foo</code> はその値を直接 <code>Box&lt;T&gt;</code> (訳注: すなわち <code>y</code> )の中に書き込みます。</p> <!-- This is important enough that it bears repeating: pointers are not for --> <!-- optimizing returning values from your code. Allow the caller to choose how they --> <!-- want to use your output. --> <p>重要なことなので繰り返しますが、ポインタを戻り値の最適化のために使うべきではありません。呼び出し側が戻り値をどのように使うかを選択できるようにしましょう。</p> <script type="text/javascript"> window.playgroundUrl = "https://play.rust-lang.org"; </script> <script src='rustbook.js'></script> <script src='playpen.js'></script> </div></div> </body> </html> <|start_filename|>docs/1.9/nomicon/exception-safety.html<|end_filename|> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="generator" content="rustdoc"> <title>Exception Safety</title> <link rel="stylesheet" type="text/css" href="rustbook.css"> <meta name="robots" content="noindex"> </head> <body class="rustdoc"> <!--[if lte IE 8]> <div class="warning"> This old browser is unsupported and will most likely display funky things. </div> <![endif]--> <div id="nav"> <button id="toggle-nav"> <span class="sr-only">Toggle navigation</span> <span class="bar"></span> <span class="bar"></span> <span class="bar"></span> </button> </div> <div id='toc' class='mobile-hidden'> <ul class='chapter'> <li><a href='README.html'><b>1.</b> Introduction</a> </li> <li><a href='meet-safe-and-unsafe.html'><b>2.</b> Meet Safe and Unsafe</a> <ul class='section'> <li><a href='safe-unsafe-meaning.html'><b>2.1.</b> How Safe and Unsafe Interact</a> </li> <li><a href='working-with-unsafe.html'><b>2.2.</b> Working with Unsafe</a> </li> </ul> </li> <li><a href='data.html'><b>3.</b> Data Layout</a> <ul class='section'> <li><a href='repr-rust.html'><b>3.1.</b> repr(Rust)</a> </li> <li><a href='exotic-sizes.html'><b>3.2.</b> Exotically Sized Types</a> </li> <li><a href='other-reprs.html'><b>3.3.</b> Other reprs</a> </li> </ul> </li> <li><a href='ownership.html'><b>4.</b> Ownership</a> <ul class='section'> <li><a href='references.html'><b>4.1.</b> References</a> </li> <li><a href='lifetimes.html'><b>4.2.</b> Lifetimes</a> </li> <li><a href='lifetime-mismatch.html'><b>4.3.</b> Limits of Lifetimes</a> </li> <li><a href='lifetime-elision.html'><b>4.4.</b> Lifetime Elision</a> </li> <li><a href='unbounded-lifetimes.html'><b>4.5.</b> Unbounded Lifetimes</a> </li> <li><a href='hrtb.html'><b>4.6.</b> Higher-Rank Trait Bounds</a> </li> <li><a href='subtyping.html'><b>4.7.</b> Subtyping and Variance</a> </li> <li><a href='dropck.html'><b>4.8.</b> Drop Check</a> </li> <li><a href='phantom-data.html'><b>4.9.</b> PhantomData</a> </li> <li><a href='borrow-splitting.html'><b>4.10.</b> Splitting Borrows</a> </li> </ul> </li> <li><a href='conversions.html'><b>5.</b> Type Conversions</a> <ul class='section'> <li><a href='coercions.html'><b>5.1.</b> Coercions</a> </li> <li><a href='dot-operator.html'><b>5.2.</b> The Dot Operator</a> </li> <li><a href='casts.html'><b>5.3.</b> Casts</a> </li> <li><a href='transmutes.html'><b>5.4.</b> Transmutes</a> </li> </ul> </li> <li><a href='uninitialized.html'><b>6.</b> Uninitialized Memory</a> <ul class='section'> <li><a href='checked-uninit.html'><b>6.1.</b> Checked</a> </li> <li><a href='drop-flags.html'><b>6.2.</b> Drop Flags</a> </li> <li><a href='unchecked-uninit.html'><b>6.3.</b> Unchecked</a> </li> </ul> </li> <li><a href='obrm.html'><b>7.</b> Ownership Based Resource Management</a> <ul class='section'> <li><a href='constructors.html'><b>7.1.</b> Constructors</a> </li> <li><a href='destructors.html'><b>7.2.</b> Destructors</a> </li> <li><a href='leaking.html'><b>7.3.</b> Leaking</a> </li> </ul> </li> <li><a href='unwinding.html'><b>8.</b> Unwinding</a> <ul class='section'> <li><a class='active' href='exception-safety.html'><b>8.1.</b> Exception Safety</a> </li> <li><a href='poisoning.html'><b>8.2.</b> Poisoning</a> </li> </ul> </li> <li><a href='concurrency.html'><b>9.</b> Concurrency</a> <ul class='section'> <li><a href='races.html'><b>9.1.</b> Races</a> </li> <li><a href='send-and-sync.html'><b>9.2.</b> Send and Sync</a> </li> <li><a href='atomics.html'><b>9.3.</b> Atomics</a> </li> </ul> </li> <li><a href='vec.html'><b>10.</b> Implementing Vec</a> <ul class='section'> <li><a href='vec-layout.html'><b>10.1.</b> Layout</a> </li> <li><a href='vec-alloc.html'><b>10.2.</b> Allocating</a> </li> <li><a href='vec-push-pop.html'><b>10.3.</b> Push and Pop</a> </li> <li><a href='vec-dealloc.html'><b>10.4.</b> Deallocating</a> </li> <li><a href='vec-deref.html'><b>10.5.</b> Deref</a> </li> <li><a href='vec-insert-remove.html'><b>10.6.</b> Insert and Remove</a> </li> <li><a href='vec-into-iter.html'><b>10.7.</b> IntoIter</a> </li> <li><a href='vec-raw.html'><b>10.8.</b> RawVec</a> </li> <li><a href='vec-drain.html'><b>10.9.</b> Drain</a> </li> <li><a href='vec-zsts.html'><b>10.10.</b> Handling Zero-Sized Types</a> </li> <li><a href='vec-final.html'><b>10.11.</b> Final Code</a> </li> </ul> </li> <li><a href='arc-and-mutex.html'><b>11.</b> Implementing Arc and Mutex</a> </li> </ul> </div> <div id='page-wrapper'> <div id='page'> <blockquote class="header-caveat"> <p> <strong>注意: <a href="https://doc.rust-jp.rs/book-ja/">最新版のドキュメントをご覧ください。</a></strong>この第1版ドキュメントは古くなっており、最新情報が反映されていません。リンク先のドキュメントが現在の Rust の最新のドキュメントです。 </p> </blockquote> <h1 class="title">Exception Safety</h1> <p>Although programs should use unwinding sparingly, there&#39;s a lot of code that <em>can</em> panic. If you unwrap a None, index out of bounds, or divide by 0, your program will panic. On debug builds, every arithmetic operation can panic if it overflows. Unless you are very careful and tightly control what code runs, pretty much everything can unwind, and you need to be ready for it.</p> <p>Being ready for unwinding is often referred to as <em>exception safety</em> in the broader programming world. In Rust, there are two levels of exception safety that one may concern themselves with:</p> <ul> <li><p>In unsafe code, we <em>must</em> be exception safe to the point of not violating memory safety. We&#39;ll call this <em>minimal</em> exception safety.</p></li> <li><p>In safe code, it is <em>good</em> to be exception safe to the point of your program doing the right thing. We&#39;ll call this <em>maximal</em> exception safety.</p></li> </ul> <p>As is the case in many places in Rust, Unsafe code must be ready to deal with bad Safe code when it comes to unwinding. Code that transiently creates unsound states must be careful that a panic does not cause that state to be used. Generally this means ensuring that only non-panicking code is run while these states exist, or making a guard that cleans up the state in the case of a panic. This does not necessarily mean that the state a panic witnesses is a fully coherent state. We need only guarantee that it&#39;s a <em>safe</em> state.</p> <p>Most Unsafe code is leaf-like, and therefore fairly easy to make exception-safe. It controls all the code that runs, and most of that code can&#39;t panic. However it is not uncommon for Unsafe code to work with arrays of temporarily uninitialized data while repeatedly invoking caller-provided code. Such code needs to be careful and consider exception safety.</p> <h2 id='vecpush_all' class='section-header'><a href='#vecpush_all'>Vec::push_all</a></h2> <p><code>Vec::push_all</code> is a temporary hack to get extending a Vec by a slice reliably efficient without specialization. Here&#39;s a simple implementation:</p> <span class='rusttest'>fn main() { impl&lt;T: Clone&gt; Vec&lt;T&gt; { fn push_all(&amp;mut self, to_push: &amp;[T]) { self.reserve(to_push.len()); unsafe { // can&#39;t overflow because we just reserved this self.set_len(self.len() + to_push.len()); for (i, x) in to_push.iter().enumerate() { self.ptr().offset(i as isize).write(x.clone()); } } } } }</span><pre class='rust rust-example-rendered'> <span class='kw'>impl</span><span class='op'>&lt;</span><span class='ident'>T</span>: <span class='ident'>Clone</span><span class='op'>&gt;</span> <span class='ident'>Vec</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> { <span class='kw'>fn</span> <span class='ident'>push_all</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>, <span class='ident'>to_push</span>: <span class='kw-2'>&amp;</span>[<span class='ident'>T</span>]) { <span class='self'>self</span>.<span class='ident'>reserve</span>(<span class='ident'>to_push</span>.<span class='ident'>len</span>()); <span class='kw'>unsafe</span> { <span class='comment'>// can&#39;t overflow because we just reserved this</span> <span class='self'>self</span>.<span class='ident'>set_len</span>(<span class='self'>self</span>.<span class='ident'>len</span>() <span class='op'>+</span> <span class='ident'>to_push</span>.<span class='ident'>len</span>()); <span class='kw'>for</span> (<span class='ident'>i</span>, <span class='ident'>x</span>) <span class='kw'>in</span> <span class='ident'>to_push</span>.<span class='ident'>iter</span>().<span class='ident'>enumerate</span>() { <span class='self'>self</span>.<span class='ident'>ptr</span>().<span class='ident'>offset</span>(<span class='ident'>i</span> <span class='kw'>as</span> <span class='ident'>isize</span>).<span class='ident'>write</span>(<span class='ident'>x</span>.<span class='ident'>clone</span>()); } } } }</pre> <p>We bypass <code>push</code> in order to avoid redundant capacity and <code>len</code> checks on the Vec that we definitely know has capacity. The logic is totally correct, except there&#39;s a subtle problem with our code: it&#39;s not exception-safe! <code>set_len</code>, <code>offset</code>, and <code>write</code> are all fine; <code>clone</code> is the panic bomb we over-looked.</p> <p>Clone is completely out of our control, and is totally free to panic. If it does, our function will exit early with the length of the Vec set too large. If the Vec is looked at or dropped, uninitialized memory will be read!</p> <p>The fix in this case is fairly simple. If we want to guarantee that the values we <em>did</em> clone are dropped, we can set the <code>len</code> every loop iteration. If we just want to guarantee that uninitialized memory can&#39;t be observed, we can set the <code>len</code> after the loop.</p> <h2 id='binaryheapsift_up' class='section-header'><a href='#binaryheapsift_up'>BinaryHeap::sift_up</a></h2> <p>Bubbling an element up a heap is a bit more complicated than extending a Vec. The pseudocode is as follows:</p> <pre><code class="language-text">bubble_up(heap, index): while index != 0 &amp;&amp; heap[index] &lt; heap[parent(index)]: heap.swap(index, parent(index)) index = parent(index) </code></pre> <p>A literal transcription of this code to Rust is totally fine, but has an annoying performance characteristic: the <code>self</code> element is swapped over and over again uselessly. We would rather have the following:</p> <pre><code class="language-text">bubble_up(heap, index): let elem = heap[index] while index != 0 &amp;&amp; element &lt; heap[parent(index)]: heap[index] = heap[parent(index)] index = parent(index) heap[index] = elem </code></pre> <p>This code ensures that each element is copied as little as possible (it is in fact necessary that elem be copied twice in general). However it now exposes some exception safety trouble! At all times, there exists two copies of one value. If we panic in this function something will be double-dropped. Unfortunately, we also don&#39;t have full control of the code: that comparison is user-defined!</p> <p>Unlike Vec, the fix isn&#39;t as easy here. One option is to break the user-defined code and the unsafe code into two separate phases:</p> <pre><code class="language-text">bubble_up(heap, index): let end_index = index; while end_index != 0 &amp;&amp; heap[end_index] &lt; heap[parent(end_index)]: end_index = parent(end_index) let elem = heap[index] while index != end_index: heap[index] = heap[parent(index)] index = parent(index) heap[index] = elem </code></pre> <p>If the user-defined code blows up, that&#39;s no problem anymore, because we haven&#39;t actually touched the state of the heap yet. Once we do start messing with the heap, we&#39;re working with only data and functions that we trust, so there&#39;s no concern of panics.</p> <p>Perhaps you&#39;re not happy with this design. Surely it&#39;s cheating! And we have to do the complex heap traversal <em>twice</em>! Alright, let&#39;s bite the bullet. Let&#39;s intermix untrusted and unsafe code <em>for reals</em>.</p> <p>If Rust had <code>try</code> and <code>finally</code> like in Java, we could do the following:</p> <pre><code class="language-text">bubble_up(heap, index): let elem = heap[index] try: while index != 0 &amp;&amp; element &lt; heap[parent(index)]: heap[index] = heap[parent(index)] index = parent(index) finally: heap[index] = elem </code></pre> <p>The basic idea is simple: if the comparison panics, we just toss the loose element in the logically uninitialized index and bail out. Anyone who observes the heap will see a potentially <em>inconsistent</em> heap, but at least it won&#39;t cause any double-drops! If the algorithm terminates normally, then this operation happens to coincide precisely with the how we finish up regardless.</p> <p>Sadly, Rust has no such construct, so we&#39;re going to need to roll our own! The way to do this is to store the algorithm&#39;s state in a separate struct with a destructor for the &quot;finally&quot; logic. Whether we panic or not, that destructor will run and clean up after us.</p> <span class='rusttest'>fn main() { struct Hole&lt;&#39;a, T: &#39;a&gt; { data: &amp;&#39;a mut [T], /// `elt` is always `Some` from new until drop. elt: Option&lt;T&gt;, pos: usize, } impl&lt;&#39;a, T&gt; Hole&lt;&#39;a, T&gt; { fn new(data: &amp;&#39;a mut [T], pos: usize) -&gt; Self { unsafe { let elt = ptr::read(&amp;data[pos]); Hole { data: data, elt: Some(elt), pos: pos, } } } fn pos(&amp;self) -&gt; usize { self.pos } fn removed(&amp;self) -&gt; &amp;T { self.elt.as_ref().unwrap() } unsafe fn get(&amp;self, index: usize) -&gt; &amp;T { &amp;self.data[index] } unsafe fn move_to(&amp;mut self, index: usize) { let index_ptr: *const _ = &amp;self.data[index]; let hole_ptr = &amp;mut self.data[self.pos]; ptr::copy_nonoverlapping(index_ptr, hole_ptr, 1); self.pos = index; } } impl&lt;&#39;a, T&gt; Drop for Hole&lt;&#39;a, T&gt; { fn drop(&amp;mut self) { // fill the hole again unsafe { let pos = self.pos; ptr::write(&amp;mut self.data[pos], self.elt.take().unwrap()); } } } impl&lt;T: Ord&gt; BinaryHeap&lt;T&gt; { fn sift_up(&amp;mut self, pos: usize) { unsafe { // Take out the value at `pos` and create a hole. let mut hole = Hole::new(&amp;mut self.data, pos); while hole.pos() != 0 { let parent = parent(hole.pos()); if hole.removed() &lt;= hole.get(parent) { break } hole.move_to(parent); } // Hole will be unconditionally filled here; panic or not! } } } }</span><pre class='rust rust-example-rendered'> <span class='kw'>struct</span> <span class='ident'>Hole</span><span class='op'>&lt;</span><span class='lifetime'>&#39;a</span>, <span class='ident'>T</span>: <span class='lifetime'>&#39;a</span><span class='op'>&gt;</span> { <span class='ident'>data</span>: <span class='kw-2'>&amp;</span><span class='lifetime'>&#39;a</span> <span class='kw-2'>mut</span> [<span class='ident'>T</span>], <span class='doccomment'>/// `elt` is always `Some` from new until drop.</span> <span class='ident'>elt</span>: <span class='prelude-ty'>Option</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span>, <span class='ident'>pos</span>: <span class='ident'>usize</span>, } <span class='kw'>impl</span><span class='op'>&lt;</span><span class='lifetime'>&#39;a</span>, <span class='ident'>T</span><span class='op'>&gt;</span> <span class='ident'>Hole</span><span class='op'>&lt;</span><span class='lifetime'>&#39;a</span>, <span class='ident'>T</span><span class='op'>&gt;</span> { <span class='kw'>fn</span> <span class='ident'>new</span>(<span class='ident'>data</span>: <span class='kw-2'>&amp;</span><span class='lifetime'>&#39;a</span> <span class='kw-2'>mut</span> [<span class='ident'>T</span>], <span class='ident'>pos</span>: <span class='ident'>usize</span>) <span class='op'>-&gt;</span> <span class='self'>Self</span> { <span class='kw'>unsafe</span> { <span class='kw'>let</span> <span class='ident'>elt</span> <span class='op'>=</span> <span class='ident'>ptr</span>::<span class='ident'>read</span>(<span class='kw-2'>&amp;</span><span class='ident'>data</span>[<span class='ident'>pos</span>]); <span class='ident'>Hole</span> { <span class='ident'>data</span>: <span class='ident'>data</span>, <span class='ident'>elt</span>: <span class='prelude-val'>Some</span>(<span class='ident'>elt</span>), <span class='ident'>pos</span>: <span class='ident'>pos</span>, } } } <span class='kw'>fn</span> <span class='ident'>pos</span>(<span class='kw-2'>&amp;</span><span class='self'>self</span>) <span class='op'>-&gt;</span> <span class='ident'>usize</span> { <span class='self'>self</span>.<span class='ident'>pos</span> } <span class='kw'>fn</span> <span class='ident'>removed</span>(<span class='kw-2'>&amp;</span><span class='self'>self</span>) <span class='op'>-&gt;</span> <span class='kw-2'>&amp;</span><span class='ident'>T</span> { <span class='self'>self</span>.<span class='ident'>elt</span>.<span class='ident'>as_ref</span>().<span class='ident'>unwrap</span>() } <span class='kw'>unsafe</span> <span class='kw'>fn</span> <span class='ident'>get</span>(<span class='kw-2'>&amp;</span><span class='self'>self</span>, <span class='ident'>index</span>: <span class='ident'>usize</span>) <span class='op'>-&gt;</span> <span class='kw-2'>&amp;</span><span class='ident'>T</span> { <span class='kw-2'>&amp;</span><span class='self'>self</span>.<span class='ident'>data</span>[<span class='ident'>index</span>] } <span class='kw'>unsafe</span> <span class='kw'>fn</span> <span class='ident'>move_to</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>, <span class='ident'>index</span>: <span class='ident'>usize</span>) { <span class='kw'>let</span> <span class='ident'>index_ptr</span>: <span class='op'>*</span><span class='kw'>const</span> _ <span class='op'>=</span> <span class='kw-2'>&amp;</span><span class='self'>self</span>.<span class='ident'>data</span>[<span class='ident'>index</span>]; <span class='kw'>let</span> <span class='ident'>hole_ptr</span> <span class='op'>=</span> <span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>.<span class='ident'>data</span>[<span class='self'>self</span>.<span class='ident'>pos</span>]; <span class='ident'>ptr</span>::<span class='ident'>copy_nonoverlapping</span>(<span class='ident'>index_ptr</span>, <span class='ident'>hole_ptr</span>, <span class='number'>1</span>); <span class='self'>self</span>.<span class='ident'>pos</span> <span class='op'>=</span> <span class='ident'>index</span>; } } <span class='kw'>impl</span><span class='op'>&lt;</span><span class='lifetime'>&#39;a</span>, <span class='ident'>T</span><span class='op'>&gt;</span> <span class='ident'>Drop</span> <span class='kw'>for</span> <span class='ident'>Hole</span><span class='op'>&lt;</span><span class='lifetime'>&#39;a</span>, <span class='ident'>T</span><span class='op'>&gt;</span> { <span class='kw'>fn</span> <span class='ident'>drop</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>) { <span class='comment'>// fill the hole again</span> <span class='kw'>unsafe</span> { <span class='kw'>let</span> <span class='ident'>pos</span> <span class='op'>=</span> <span class='self'>self</span>.<span class='ident'>pos</span>; <span class='ident'>ptr</span>::<span class='ident'>write</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>.<span class='ident'>data</span>[<span class='ident'>pos</span>], <span class='self'>self</span>.<span class='ident'>elt</span>.<span class='ident'>take</span>().<span class='ident'>unwrap</span>()); } } } <span class='kw'>impl</span><span class='op'>&lt;</span><span class='ident'>T</span>: <span class='ident'>Ord</span><span class='op'>&gt;</span> <span class='ident'>BinaryHeap</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> { <span class='kw'>fn</span> <span class='ident'>sift_up</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>, <span class='ident'>pos</span>: <span class='ident'>usize</span>) { <span class='kw'>unsafe</span> { <span class='comment'>// Take out the value at `pos` and create a hole.</span> <span class='kw'>let</span> <span class='kw-2'>mut</span> <span class='ident'>hole</span> <span class='op'>=</span> <span class='ident'>Hole</span>::<span class='ident'>new</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>.<span class='ident'>data</span>, <span class='ident'>pos</span>); <span class='kw'>while</span> <span class='ident'>hole</span>.<span class='ident'>pos</span>() <span class='op'>!=</span> <span class='number'>0</span> { <span class='kw'>let</span> <span class='ident'>parent</span> <span class='op'>=</span> <span class='ident'>parent</span>(<span class='ident'>hole</span>.<span class='ident'>pos</span>()); <span class='kw'>if</span> <span class='ident'>hole</span>.<span class='ident'>removed</span>() <span class='op'>&lt;=</span> <span class='ident'>hole</span>.<span class='ident'>get</span>(<span class='ident'>parent</span>) { <span class='kw'>break</span> } <span class='ident'>hole</span>.<span class='ident'>move_to</span>(<span class='ident'>parent</span>); } <span class='comment'>// Hole will be unconditionally filled here; panic or not!</span> } } }</pre> <script type="text/javascript"> window.playgroundUrl = "https://play.rust-lang.org"; </script> <script src='rustbook.js'></script> <script src='playpen.js'></script> </div></div> </body> </html> <|start_filename|>docs/1.6/book/strings.html<|end_filename|> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="generator" content="rustdoc"> <title>文字列</title> <link rel="stylesheet" type="text/css" href="rustbook.css"> <meta name="robots" content="noindex"> </head> <body class="rustdoc"> <!--[if lte IE 8]> <div class="warning"> This old browser is unsupported and will most likely display funky things. </div> <![endif]--> <div id="nav"> <button id="toggle-nav"> <span class="sr-only">Toggle navigation</span> <span class="bar"></span> <span class="bar"></span> <span class="bar"></span> </button> </div> <div id='toc' class='mobile-hidden'> <ul class='chapter'> <li><a href='README.html'><b>1.</b> Introduction</a> </li> <li><a href='getting-started.html'><b>2.</b> はじめる</a> </li> <li><a href='learn-rust.html'><b>3.</b> Rustを学ぶ</a> <ul class='section'> <li><a href='guessing-game.html'><b>3.1.</b> 数当てゲーム</a> </li> <li><a href='dining-philosophers.html'><b>3.2.</b> 食事する哲学者</a> </li> <li><a href='rust-inside-other-languages.html'><b>3.3.</b> 他言語と共存する</a> </li> </ul> </li> <li><a href='syntax-and-semantics.html'><b>4.</b> シンタックスとセマンティクス</a> <ul class='section'> <li><a href='variable-bindings.html'><b>4.1.</b> 変数束縛</a> </li> <li><a href='functions.html'><b>4.2.</b> 関数</a> </li> <li><a href='primitive-types.html'><b>4.3.</b> プリミティブ型</a> </li> <li><a href='comments.html'><b>4.4.</b> コメント</a> </li> <li><a href='if.html'><b>4.5.</b> if</a> </li> <li><a href='loops.html'><b>4.6.</b> ループ</a> </li> <li><a href='ownership.html'><b>4.7.</b> 所有権</a> </li> <li><a href='references-and-borrowing.html'><b>4.8.</b> 参照と借用</a> </li> <li><a href='lifetimes.html'><b>4.9.</b> ライフタイム</a> </li> <li><a href='mutability.html'><b>4.10.</b> ミュータビリティ</a> </li> <li><a href='structs.html'><b>4.11.</b> 構造体</a> </li> <li><a href='enums.html'><b>4.12.</b> 列挙型</a> </li> <li><a href='match.html'><b>4.13.</b> マッチ</a> </li> <li><a href='patterns.html'><b>4.14.</b> パターン</a> </li> <li><a href='method-syntax.html'><b>4.15.</b> メソッド構文</a> </li> <li><a href='vectors.html'><b>4.16.</b> ベクタ</a> </li> <li><a class='active' href='strings.html'><b>4.17.</b> 文字列</a> </li> <li><a href='generics.html'><b>4.18.</b> ジェネリクス</a> </li> <li><a href='traits.html'><b>4.19.</b> トレイト</a> </li> <li><a href='drop.html'><b>4.20.</b> Drop</a> </li> <li><a href='if-let.html'><b>4.21.</b> if let</a> </li> <li><a href='trait-objects.html'><b>4.22.</b> トレイトオブジェクト</a> </li> <li><a href='closures.html'><b>4.23.</b> クロージャ</a> </li> <li><a href='ufcs.html'><b>4.24.</b> 共通の関数呼出構文</a> </li> <li><a href='crates-and-modules.html'><b>4.25.</b> クレートとモジュール</a> </li> <li><a href='const-and-static.html'><b>4.26.</b> `const` と `static`</a> </li> <li><a href='attributes.html'><b>4.27.</b> アトリビュート</a> </li> <li><a href='type-aliases.html'><b>4.28.</b> `type` エイリアス</a> </li> <li><a href='casting-between-types.html'><b>4.29.</b> 型間のキャスト</a> </li> <li><a href='associated-types.html'><b>4.30.</b> 関連型</a> </li> <li><a href='unsized-types.html'><b>4.31.</b> サイズ不定型</a> </li> <li><a href='operators-and-overloading.html'><b>4.32.</b> 演算子とオーバーロード</a> </li> <li><a href='deref-coercions.html'><b>4.33.</b> Derefによる型強制</a> </li> <li><a href='macros.html'><b>4.34.</b> マクロ</a> </li> <li><a href='raw-pointers.html'><b>4.35.</b> 生ポインタ</a> </li> <li><a href='unsafe.html'><b>4.36.</b> `unsafe`</a> </li> </ul> </li> <li><a href='effective-rust.html'><b>5.</b> Effective Rust</a> <ul class='section'> <li><a href='the-stack-and-the-heap.html'><b>5.1.</b> スタックとヒープ</a> </li> <li><a href='testing.html'><b>5.2.</b> テスト</a> </li> <li><a href='conditional-compilation.html'><b>5.3.</b> 条件付きコンパイル</a> </li> <li><a href='documentation.html'><b>5.4.</b> ドキュメント</a> </li> <li><a href='iterators.html'><b>5.5.</b> イテレータ</a> </li> <li><a href='concurrency.html'><b>5.6.</b> 並行性</a> </li> <li><a href='error-handling.html'><b>5.7.</b> エラーハンドリング</a> </li> <li><a href='choosing-your-guarantees.html'><b>5.8.</b> 保証を選ぶ</a> </li> <li><a href='ffi.html'><b>5.9.</b> 他言語関数インターフェース</a> </li> <li><a href='borrow-and-asref.html'><b>5.10.</b> BorrowとAsRef</a> </li> <li><a href='release-channels.html'><b>5.11.</b> リリースチャネル</a> </li> <li><a href='using-rust-without-the-standard-library.html'><b>5.12.</b> 標準ライブラリ無しでRustを使う</a> </li> </ul> </li> <li><a href='nightly-rust.html'><b>6.</b> Nightly Rust</a> <ul class='section'> <li><a href='compiler-plugins.html'><b>6.1.</b> コンパイラプラグイン</a> </li> <li><a href='inline-assembly.html'><b>6.2.</b> インラインアセンブリ</a> </li> <li><a href='no-stdlib.html'><b>6.3.</b> No stdlib</a> </li> <li><a href='intrinsics.html'><b>6.4.</b> Intrinsic</a> </li> <li><a href='lang-items.html'><b>6.5.</b> 言語アイテム</a> </li> <li><a href='advanced-linking.html'><b>6.6.</b> 高度なリンキング</a> </li> <li><a href='benchmark-tests.html'><b>6.7.</b> ベンチマークテスト</a> </li> <li><a href='box-syntax-and-patterns.html'><b>6.8.</b> Box構文とパターン</a> </li> <li><a href='slice-patterns.html'><b>6.9.</b> スライスパターン</a> </li> <li><a href='associated-constants.html'><b>6.10.</b> 関連定数</a> </li> <li><a href='custom-allocators.html'><b>6.11.</b> カスタムアロケータ</a> </li> </ul> </li> <li><a href='glossary.html'><b>7.</b> 用語集</a> </li> <li><a href='syntax-index.html'><b>8.</b> 構文の索引</a> </li> <li><a href='bibliography.html'><b>9.</b> 関係書目</a> </li> </ul> </div> <div id='page-wrapper'> <div id='page'> <blockquote class="header-caveat"> <p> <strong>注意: <a href="https://doc.rust-jp.rs/book-ja/">最新版のドキュメントをご覧ください。</a></strong>この第1版ドキュメントは古くなっており、最新情報が反映されていません。リンク先のドキュメントが現在の Rust の最新のドキュメントです。 </p> </blockquote> <h1 class="title">文字列</h1> <!-- % Strings --> <!-- Strings are an important concept for any programmer to master. Rust’s string --> <!-- handling system is a bit different from other languages, due to its systems --> <!-- focus. Any time you have a data structure of variable size, things can get --> <!-- tricky, and strings are a re-sizable data structure. That being said, Rust’s --> <!-- strings also work differently than in some other systems languages, such as C. --> <p>文字列は、プログラマがマスタすべき重要な概念です。 Rustの文字列の扱いは、Rust言語がシステムプログラミングにフォーカスしているため、少し他の言語と異なります。 動的なサイズを持つデータ構造があるといつも、物事は複雑性を孕みます。 そして文字列もまたサイズを変更することができるデータ構造です。 これはつまり、Rustの文字列もまた、Cのような他のシステム言語とは少し異なる振る舞いをするということです。</p> <!-- Let’s dig into the details. A ‘string’ is a sequence of Unicode scalar values --> <!-- encoded as a stream of UTF-8 bytes. All strings are guaranteed to be a valid --> <!-- encoding of UTF-8 sequences. Additionally, unlike some systems languages, --> <!-- strings are not null-terminated and can contain null bytes. --> <p>詳しく見ていきましょう。「文字列」は、UTF-8のバイトストリームとしてエンコードされたユニコードのスカラ値のシーケンスです。 すべての文字列は、妥当なUTF-8のシーケンスであることが保証されています。 また、他のシステム言語とは異なり、文字列はnull終端でなく、nullバイトを保持することもできます。</p> <!-- Rust has two main types of strings: `&str` and `String`. Let’s talk about --> <!-- `&str` first. These are called ‘string slices’. A string slice has a fixed --> <!-- size, and cannot be mutated. It is a reference to a sequence of UTF-8 bytes. --> <p>Rustには主要な文字列型が二種類あります。<code>&amp;str</code> と <code>String</code>です。 まず <code>&amp;str</code> について説明しましょう。 <code>&amp;str</code> は「文字列スライス」と呼ばれます。 文字列スライスは固定サイズで変更不可能です。文字列スライスはUTF-8のバイトシーケンスへの参照です。</p> <span class='rusttest'>fn main() { let greeting = &quot;Hello there.&quot;; // greeting: &amp;&#39;static str }</span><pre class='rust rust-example-rendered'> <span class='kw'>let</span> <span class='ident'>greeting</span> <span class='op'>=</span> <span class='string'>&quot;Hello there.&quot;</span>; <span class='comment'>// greeting: &amp;&#39;static str</span></pre> <!-- `"Hello there."` is a string literal and its type is `&'static str`. A string --> <!-- literal is a string slice that is statically allocated, meaning that it’s saved --> <!-- inside our compiled program, and exists for the entire duration it runs. The --> <!-- `greeting` binding is a reference to this statically allocated string. Any --> <!-- function expecting a string slice will also accept a string literal. --> <p><code>&quot;Hello there.&quot;</code> は文字列リテラルで、 <code>&amp;&#39;static str</code> 型を持ちます。 文字列リテラルは、静的にアロケートされた文字列スライスです。これはつまりコンパイルされたプログラム内に保存されていて、 プログラムの実行中全てにわたって存在しているということです。 <code>greeting</code>の束縛はこのように静的にアロケートされた文字列を参照しています。 文字列スライスを引数として期待している関数はすべて文字列リテラルを引数に取ることができます。</p> <!-- String literals can span multiple lines. There are two forms. The first will --> <!-- include the newline and the leading spaces: --> <p>文字列リテラルは複数行にわたることができます。 複数行文字列リテラルには2つの形式があります。 一つ目の形式は、改行と行頭の空白を含む形式です:</p> <span class='rusttest'>fn main() { let s = &quot;foo bar&quot;; assert_eq!(&quot;foo\n bar&quot;, s); }</span><pre class='rust rust-example-rendered'> <span class='kw'>let</span> <span class='ident'>s</span> <span class='op'>=</span> <span class='string'>&quot;foo bar&quot;</span>; <span class='macro'>assert_eq</span><span class='macro'>!</span>(<span class='string'>&quot;foo\n bar&quot;</span>, <span class='ident'>s</span>);</pre> <!-- The second, with a `\`, trims the spaces and the newline: --> <p>もう一つは <code>\</code> を使って空白と改行を削る形式です:</p> <span class='rusttest'>fn main() { let s = &quot;foo\ bar&quot;; assert_eq!(&quot;foobar&quot;, s); }</span><pre class='rust rust-example-rendered'> <span class='kw'>let</span> <span class='ident'>s</span> <span class='op'>=</span> <span class='string'>&quot;foo\ bar&quot;</span>; <span class='macro'>assert_eq</span><span class='macro'>!</span>(<span class='string'>&quot;foobar&quot;</span>, <span class='ident'>s</span>);</pre> <!-- Rust has more than just `&str`s though. A `String`, is a heap-allocated string. --> <!-- This string is growable, and is also guaranteed to be UTF-8. `String`s are --> <!-- commonly created by converting from a string slice using the `to_string` --> <!-- method. --> <p>Rustには <code>&amp;str</code> だけでなく、 <code>String</code> というヒープアロケートされる文字列もあります。 この文字列は伸張可能であり、またUTF-8であることも保証されています。 <code>String</code> は一般的に文字列スライスを <code>to_string</code> メソッドで変換することで作成されます。</p> <span class='rusttest'>fn main() { let mut s = &quot;Hello&quot;.to_string(); // mut s: String println!(&quot;{}&quot;, s); s.push_str(&quot;, world.&quot;); println!(&quot;{}&quot;, s); }</span><pre class='rust rust-example-rendered'> <span class='kw'>let</span> <span class='kw-2'>mut</span> <span class='ident'>s</span> <span class='op'>=</span> <span class='string'>&quot;Hello&quot;</span>.<span class='ident'>to_string</span>(); <span class='comment'>// mut s: String</span> <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;{}&quot;</span>, <span class='ident'>s</span>); <span class='ident'>s</span>.<span class='ident'>push_str</span>(<span class='string'>&quot;, world.&quot;</span>); <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;{}&quot;</span>, <span class='ident'>s</span>);</pre> <!-- `String`s will coerce into `&str` with an `&`: --> <p><code>String</code> は <code>&amp;</code> によって <code>&amp;str</code> に型強制されます。</p> <span class='rusttest'>fn takes_slice(slice: &amp;str) { println!(&quot;Got: {}&quot;, slice); } fn main() { let s = &quot;Hello&quot;.to_string(); takes_slice(&amp;s); } </span><pre class='rust rust-example-rendered'> <span class='kw'>fn</span> <span class='ident'>takes_slice</span>(<span class='ident'>slice</span>: <span class='kw-2'>&amp;</span><span class='ident'>str</span>) { <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;Got: {}&quot;</span>, <span class='ident'>slice</span>); } <span class='kw'>fn</span> <span class='ident'>main</span>() { <span class='kw'>let</span> <span class='ident'>s</span> <span class='op'>=</span> <span class='string'>&quot;Hello&quot;</span>.<span class='ident'>to_string</span>(); <span class='ident'>takes_slice</span>(<span class='kw-2'>&amp;</span><span class='ident'>s</span>); }</pre> <!-- This coercion does not happen for functions that accept one of `&str`’s traits --> <!-- instead of `&str`. For example, [`TcpStream::connect`][connect] has a parameter --> <!-- of type `ToSocketAddrs`. A `&str` is okay but a `String` must be explicitly --> <!-- converted using `&*`. --> <p>このような変換は <code>&amp;str</code> ではなく <code>&amp;str</code> の実装するトレイトを引数として取る関数に対しては自動的には行われません。 たとえば、 <a href="../std/net/struct.TcpStream.html#method.connect"><code>TcpStream::connect</code></a> は引数として型 <code>ToSocketAddrs</code> を要求しています。 このような関数には <code>&amp;str</code> は渡せますが、 <code>String</code> は <code>&amp;*</code> を用いて明示的に変換しなければなりません。</p> <span class='rusttest'>fn main() { use std::net::TcpStream; // TcpStream::connect(&quot;192.168.0.1:3000&quot;); // &amp;str parameter TcpStream::connect(&quot;192.168.0.1:3000&quot;); // 引数として &amp;str を渡す let addr_string = &quot;192.168.0.1:3000&quot;.to_string(); // TcpStream::connect(&amp;*addr_string); // convert addr_string to &amp;str TcpStream::connect(&amp;*addr_string); // addr_string を &amp;str に変換して渡す }</span><pre class='rust rust-example-rendered'> <span class='kw'>use</span> <span class='ident'>std</span>::<span class='ident'>net</span>::<span class='ident'>TcpStream</span>; <span class='ident'>TcpStream</span>::<span class='ident'>connect</span>(<span class='string'>&quot;192.168.0.1:3000&quot;</span>); <span class='comment'>// 引数として &amp;str を渡す</span> <span class='kw'>let</span> <span class='ident'>addr_string</span> <span class='op'>=</span> <span class='string'>&quot;192.168.0.1:3000&quot;</span>.<span class='ident'>to_string</span>(); <span class='ident'>TcpStream</span>::<span class='ident'>connect</span>(<span class='kw-2'>&amp;</span><span class='op'>*</span><span class='ident'>addr_string</span>); <span class='comment'>// addr_string を &amp;str に変換して渡す</span></pre> <!-- Viewing a `String` as a `&str` is cheap, but converting the `&str` to a --> <!-- `String` involves allocating memory. No reason to do that unless you have to! --> <p><code>String</code> を <code>&amp;str</code> として見るコストは低いのですが、<code>&amp;str</code> を <code>String</code> に変換するとメモリアロケーションが発生します。 必要がなければ、やるべきではないでしょう!</p> <!-- ## Indexing --> <h2 id='インデクシング' class='section-header'><a href='#インデクシング'>インデクシング</a></h2> <!-- Because strings are valid UTF-8, strings do not support indexing: --> <p>文字列は妥当なUTF-8であるため、文字列はインデクシングをサポートしていません:</p> <span class='rusttest'>fn main() { let s = &quot;hello&quot;; // println!(&quot;The first letter of s is {}&quot;, s[0]); // ERROR!!! println!(&quot;The first letter of s is {}&quot;, s[0]); // エラー!!! }</span><pre class='rust rust-example-rendered'> <span class='kw'>let</span> <span class='ident'>s</span> <span class='op'>=</span> <span class='string'>&quot;hello&quot;</span>; <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;The first letter of s is {}&quot;</span>, <span class='ident'>s</span>[<span class='number'>0</span>]); <span class='comment'>// エラー!!!</span></pre> <!-- Usually, access to a vector with `[]` is very fast. But, because each character --> <!-- in a UTF-8 encoded string can be multiple bytes, you have to walk over the --> <!-- string to find the nᵗʰ letter of a string. This is a significantly more --> <!-- expensive operation, and we don’t want to be misleading. Furthermore, ‘letter’ --> <!-- isn’t something defined in Unicode, exactly. We can choose to look at a string as --> <!-- individual bytes, or as codepoints:--> <p>普通、ベクタへの <code>[]</code> を用いたアクセスはとても高速です。 しかし、UTF-8でエンコードされた文字列内の文字は複数のバイト対応することがあるため、 文字列のn番目の文字を探すには文字列上を走査していく必要があります。 そのような処理はベクタのアクセスに比べると非常に高コストな演算であり、誤解を招きたくなかったのです。 さらに言えば、上の「文字 (letter)」というのはUnicodeでの定義と厳密には一致しません。 文字列をバイト列として見るかコードポイント列として見るか選ぶことができます。</p> <span class='rusttest'>fn main() { let hachiko = &quot;忠犬ハチ公&quot;; for b in hachiko.as_bytes() { print!(&quot;{}, &quot;, b); } println!(&quot;&quot;); for c in hachiko.chars() { print!(&quot;{}, &quot;, c); } println!(&quot;&quot;); }</span><pre class='rust rust-example-rendered'> <span class='kw'>let</span> <span class='ident'>hachiko</span> <span class='op'>=</span> <span class='string'>&quot;忠犬ハチ公&quot;</span>; <span class='kw'>for</span> <span class='ident'>b</span> <span class='kw'>in</span> <span class='ident'>hachiko</span>.<span class='ident'>as_bytes</span>() { <span class='macro'>print</span><span class='macro'>!</span>(<span class='string'>&quot;{}, &quot;</span>, <span class='ident'>b</span>); } <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;&quot;</span>); <span class='kw'>for</span> <span class='ident'>c</span> <span class='kw'>in</span> <span class='ident'>hachiko</span>.<span class='ident'>chars</span>() { <span class='macro'>print</span><span class='macro'>!</span>(<span class='string'>&quot;{}, &quot;</span>, <span class='ident'>c</span>); } <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;&quot;</span>);</pre> <!-- This prints: --> <p>これは、以下の様な出力をします:</p> <pre><code class="language-text">229, 191, 160, 231, 138, 172, 227, 131, 143, 227, 131, 129, 229, 133, 172, 忠, 犬, ハ, チ, 公, </code></pre> <!-- As you can see, there are more bytes than `char`s.--> <p>ご覧のように、 <code>char</code> の数よりも多くのバイトが含まれています。</p> <!-- You can get something similar to an index like this: --> <p>インデクシングするのと近い結果を以下の様にして得ることができます:</p> <span class='rusttest'>fn main() { let hachiko = &quot;忠犬ハチ公&quot;; let dog = hachiko.chars().nth(1); // hachiko[1]のような感じで }</span><pre class='rust rust-example-rendered'> <span class='kw'>let</span> <span class='ident'>dog</span> <span class='op'>=</span> <span class='ident'>hachiko</span>.<span class='ident'>chars</span>().<span class='ident'>nth</span>(<span class='number'>1</span>); <span class='comment'>// hachiko[1]のような感じで</span></pre> <!-- This emphasizes that we have to walk from the beginning of the list of `chars`. --> <p>このコードは、<code>chars</code> のリストの上を先頭から走査しなければならないことを強調しています。</p> <h2 id='スライシング' class='section-header'><a href='#スライシング'>スライシング</a></h2> <!-- You can get a slice of a string with slicing syntax: --> <p>文字列スライスは以下のようにスライス構文を使って取得することができます:</p> <span class='rusttest'>fn main() { let dog = &quot;hachiko&quot;; let hachi = &amp;dog[0..5]; }</span><pre class='rust rust-example-rendered'> <span class='kw'>let</span> <span class='ident'>dog</span> <span class='op'>=</span> <span class='string'>&quot;hachiko&quot;</span>; <span class='kw'>let</span> <span class='ident'>hachi</span> <span class='op'>=</span> <span class='kw-2'>&amp;</span><span class='ident'>dog</span>[<span class='number'>0</span>..<span class='number'>5</span>];</pre> <!-- But note that these are _byte_ offsets, not _character_ offsets. So --> <!-- this will fail at runtime: --> <p>しかし、注意しなくてはならない点はこれらのオフセットは <em>バイト</em> であって <em>文字</em> のオフセットではないという点です。 そのため、以下のコードは実行時に失敗します:</p> <span class='rusttest'>fn main() { let dog = &quot;忠犬ハチ公&quot;; let hachi = &amp;dog[0..2]; }</span><pre class='rust rust-example-rendered'> <span class='kw'>let</span> <span class='ident'>dog</span> <span class='op'>=</span> <span class='string'>&quot;忠犬ハチ公&quot;</span>; <span class='kw'>let</span> <span class='ident'>hachi</span> <span class='op'>=</span> <span class='kw-2'>&amp;</span><span class='ident'>dog</span>[<span class='number'>0</span>..<span class='number'>2</span>];</pre> <!-- with this error: --> <p>そして、次のようなエラーが発生します:</p> <pre><code class="language-text">thread &#39;&lt;main&gt;&#39; panicked at &#39;index 0 and/or 2 in `忠犬ハチ公` do not lie on character boundary&#39; </code></pre> <!-- ## Concatenation --> <h2 id='連結' class='section-header'><a href='#連結'>連結</a></h2> <!-- If you have a `String`, you can concatenate a `&str` to the end of it: --> <p><code>String</code> が存在するとき、 <code>&amp;str</code> を末尾に連結することができます:</p> <span class='rusttest'>fn main() { let hello = &quot;Hello &quot;.to_string(); let world = &quot;world!&quot;; let hello_world = hello + world; }</span><pre class='rust rust-example-rendered'> <span class='kw'>let</span> <span class='ident'>hello</span> <span class='op'>=</span> <span class='string'>&quot;Hello &quot;</span>.<span class='ident'>to_string</span>(); <span class='kw'>let</span> <span class='ident'>world</span> <span class='op'>=</span> <span class='string'>&quot;world!&quot;</span>; <span class='kw'>let</span> <span class='ident'>hello_world</span> <span class='op'>=</span> <span class='ident'>hello</span> <span class='op'>+</span> <span class='ident'>world</span>;</pre> <!-- But if you have two `String`s, you need an `&`: --> <p>しかし、2つの <code>String</code> を連結するには、 <code>&amp;</code> が必要になります:</p> <span class='rusttest'>fn main() { let hello = &quot;Hello &quot;.to_string(); let world = &quot;world!&quot;.to_string(); let hello_world = hello + &amp;world; }</span><pre class='rust rust-example-rendered'> <span class='kw'>let</span> <span class='ident'>hello</span> <span class='op'>=</span> <span class='string'>&quot;Hello &quot;</span>.<span class='ident'>to_string</span>(); <span class='kw'>let</span> <span class='ident'>world</span> <span class='op'>=</span> <span class='string'>&quot;world!&quot;</span>.<span class='ident'>to_string</span>(); <span class='kw'>let</span> <span class='ident'>hello_world</span> <span class='op'>=</span> <span class='ident'>hello</span> <span class='op'>+</span> <span class='kw-2'>&amp;</span><span class='ident'>world</span>;</pre> <!-- This is because `&String` can automatically coerce to a `&str`. This is a --> <!-- feature called ‘[`Deref` coercions][dc]’. --> <p>これは、 <code>&amp;String</code> が自動的に <code>&amp;str</code> に型強制されるためです。 このフィーチャは 「 <a href="deref-coercions.html"><code>Deref</code> による型強制</a> 」と呼ばれています。</p> <script type="text/javascript"> window.playgroundUrl = "https://play.rust-lang.org"; </script> <script src='rustbook.js'></script> <script src='playpen.js'></script> </div></div> </body> </html> <|start_filename|>docs/1.9/nomicon/destructors.html<|end_filename|> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="generator" content="rustdoc"> <title>Destructors</title> <link rel="stylesheet" type="text/css" href="rustbook.css"> <meta name="robots" content="noindex"> </head> <body class="rustdoc"> <!--[if lte IE 8]> <div class="warning"> This old browser is unsupported and will most likely display funky things. </div> <![endif]--> <div id="nav"> <button id="toggle-nav"> <span class="sr-only">Toggle navigation</span> <span class="bar"></span> <span class="bar"></span> <span class="bar"></span> </button> </div> <div id='toc' class='mobile-hidden'> <ul class='chapter'> <li><a href='README.html'><b>1.</b> Introduction</a> </li> <li><a href='meet-safe-and-unsafe.html'><b>2.</b> Meet Safe and Unsafe</a> <ul class='section'> <li><a href='safe-unsafe-meaning.html'><b>2.1.</b> How Safe and Unsafe Interact</a> </li> <li><a href='working-with-unsafe.html'><b>2.2.</b> Working with Unsafe</a> </li> </ul> </li> <li><a href='data.html'><b>3.</b> Data Layout</a> <ul class='section'> <li><a href='repr-rust.html'><b>3.1.</b> repr(Rust)</a> </li> <li><a href='exotic-sizes.html'><b>3.2.</b> Exotically Sized Types</a> </li> <li><a href='other-reprs.html'><b>3.3.</b> Other reprs</a> </li> </ul> </li> <li><a href='ownership.html'><b>4.</b> Ownership</a> <ul class='section'> <li><a href='references.html'><b>4.1.</b> References</a> </li> <li><a href='lifetimes.html'><b>4.2.</b> Lifetimes</a> </li> <li><a href='lifetime-mismatch.html'><b>4.3.</b> Limits of Lifetimes</a> </li> <li><a href='lifetime-elision.html'><b>4.4.</b> Lifetime Elision</a> </li> <li><a href='unbounded-lifetimes.html'><b>4.5.</b> Unbounded Lifetimes</a> </li> <li><a href='hrtb.html'><b>4.6.</b> Higher-Rank Trait Bounds</a> </li> <li><a href='subtyping.html'><b>4.7.</b> Subtyping and Variance</a> </li> <li><a href='dropck.html'><b>4.8.</b> Drop Check</a> </li> <li><a href='phantom-data.html'><b>4.9.</b> PhantomData</a> </li> <li><a href='borrow-splitting.html'><b>4.10.</b> Splitting Borrows</a> </li> </ul> </li> <li><a href='conversions.html'><b>5.</b> Type Conversions</a> <ul class='section'> <li><a href='coercions.html'><b>5.1.</b> Coercions</a> </li> <li><a href='dot-operator.html'><b>5.2.</b> The Dot Operator</a> </li> <li><a href='casts.html'><b>5.3.</b> Casts</a> </li> <li><a href='transmutes.html'><b>5.4.</b> Transmutes</a> </li> </ul> </li> <li><a href='uninitialized.html'><b>6.</b> Uninitialized Memory</a> <ul class='section'> <li><a href='checked-uninit.html'><b>6.1.</b> Checked</a> </li> <li><a href='drop-flags.html'><b>6.2.</b> Drop Flags</a> </li> <li><a href='unchecked-uninit.html'><b>6.3.</b> Unchecked</a> </li> </ul> </li> <li><a href='obrm.html'><b>7.</b> Ownership Based Resource Management</a> <ul class='section'> <li><a href='constructors.html'><b>7.1.</b> Constructors</a> </li> <li><a class='active' href='destructors.html'><b>7.2.</b> Destructors</a> </li> <li><a href='leaking.html'><b>7.3.</b> Leaking</a> </li> </ul> </li> <li><a href='unwinding.html'><b>8.</b> Unwinding</a> <ul class='section'> <li><a href='exception-safety.html'><b>8.1.</b> Exception Safety</a> </li> <li><a href='poisoning.html'><b>8.2.</b> Poisoning</a> </li> </ul> </li> <li><a href='concurrency.html'><b>9.</b> Concurrency</a> <ul class='section'> <li><a href='races.html'><b>9.1.</b> Races</a> </li> <li><a href='send-and-sync.html'><b>9.2.</b> Send and Sync</a> </li> <li><a href='atomics.html'><b>9.3.</b> Atomics</a> </li> </ul> </li> <li><a href='vec.html'><b>10.</b> Implementing Vec</a> <ul class='section'> <li><a href='vec-layout.html'><b>10.1.</b> Layout</a> </li> <li><a href='vec-alloc.html'><b>10.2.</b> Allocating</a> </li> <li><a href='vec-push-pop.html'><b>10.3.</b> Push and Pop</a> </li> <li><a href='vec-dealloc.html'><b>10.4.</b> Deallocating</a> </li> <li><a href='vec-deref.html'><b>10.5.</b> Deref</a> </li> <li><a href='vec-insert-remove.html'><b>10.6.</b> Insert and Remove</a> </li> <li><a href='vec-into-iter.html'><b>10.7.</b> IntoIter</a> </li> <li><a href='vec-raw.html'><b>10.8.</b> RawVec</a> </li> <li><a href='vec-drain.html'><b>10.9.</b> Drain</a> </li> <li><a href='vec-zsts.html'><b>10.10.</b> Handling Zero-Sized Types</a> </li> <li><a href='vec-final.html'><b>10.11.</b> Final Code</a> </li> </ul> </li> <li><a href='arc-and-mutex.html'><b>11.</b> Implementing Arc and Mutex</a> </li> </ul> </div> <div id='page-wrapper'> <div id='page'> <blockquote class="header-caveat"> <p> <strong>注意: <a href="https://doc.rust-jp.rs/book-ja/">最新版のドキュメントをご覧ください。</a></strong>この第1版ドキュメントは古くなっており、最新情報が反映されていません。リンク先のドキュメントが現在の Rust の最新のドキュメントです。 </p> </blockquote> <h1 class="title">Destructors</h1> <p>What the language <em>does</em> provide is full-blown automatic destructors through the <code>Drop</code> trait, which provides the following method:</p> <span class='rusttest'>fn main() { fn drop(&amp;mut self); }</span><pre class='rust rust-example-rendered'> <span class='kw'>fn</span> <span class='ident'>drop</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>);</pre> <p>This method gives the type time to somehow finish what it was doing.</p> <p><strong>After <code>drop</code> is run, Rust will recursively try to drop all of the fields of <code>self</code>.</strong></p> <p>This is a convenience feature so that you don&#39;t have to write &quot;destructor boilerplate&quot; to drop children. If a struct has no special logic for being dropped other than dropping its children, then it means <code>Drop</code> doesn&#39;t need to be implemented at all!</p> <p><strong>There is no stable way to prevent this behavior in Rust 1.0.</strong></p> <p>Note that taking <code>&amp;mut self</code> means that even if you could suppress recursive Drop, Rust will prevent you from e.g. moving fields out of self. For most types, this is totally fine.</p> <p>For instance, a custom implementation of <code>Box</code> might write <code>Drop</code> like this:</p> <span class='rusttest'>#![feature(alloc, heap_api, drop_in_place, unique)] extern crate alloc; use std::ptr::{drop_in_place, Unique}; use std::mem; use alloc::heap; struct Box&lt;T&gt;{ ptr: Unique&lt;T&gt; } impl&lt;T&gt; Drop for Box&lt;T&gt; { fn drop(&amp;mut self) { unsafe { drop_in_place(*self.ptr); heap::deallocate((*self.ptr) as *mut u8, mem::size_of::&lt;T&gt;(), mem::align_of::&lt;T&gt;()); } } } fn main() {} </span><pre class='rust rust-example-rendered'> <span class='attribute'>#<span class='op'>!</span>[<span class='ident'>feature</span>(<span class='ident'>alloc</span>, <span class='ident'>heap_api</span>, <span class='ident'>drop_in_place</span>, <span class='ident'>unique</span>)]</span> <span class='kw'>extern</span> <span class='kw'>crate</span> <span class='ident'>alloc</span>; <span class='kw'>use</span> <span class='ident'>std</span>::<span class='ident'>ptr</span>::{<span class='ident'>drop_in_place</span>, <span class='ident'>Unique</span>}; <span class='kw'>use</span> <span class='ident'>std</span>::<span class='ident'>mem</span>; <span class='kw'>use</span> <span class='ident'>alloc</span>::<span class='ident'>heap</span>; <span class='kw'>struct</span> <span class='ident'>Box</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span>{ <span class='ident'>ptr</span>: <span class='ident'>Unique</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> } <span class='kw'>impl</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> <span class='ident'>Drop</span> <span class='kw'>for</span> <span class='ident'>Box</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> { <span class='kw'>fn</span> <span class='ident'>drop</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>) { <span class='kw'>unsafe</span> { <span class='ident'>drop_in_place</span>(<span class='op'>*</span><span class='self'>self</span>.<span class='ident'>ptr</span>); <span class='ident'>heap</span>::<span class='ident'>deallocate</span>((<span class='op'>*</span><span class='self'>self</span>.<span class='ident'>ptr</span>) <span class='kw'>as</span> <span class='op'>*</span><span class='kw-2'>mut</span> <span class='ident'>u8</span>, <span class='ident'>mem</span>::<span class='ident'>size_of</span>::<span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span>(), <span class='ident'>mem</span>::<span class='ident'>align_of</span>::<span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span>()); } } }</pre> <p>and this works fine because when Rust goes to drop the <code>ptr</code> field it just sees a <a href="phantom-data.html">Unique</a> that has no actual <code>Drop</code> implementation. Similarly nothing can use-after-free the <code>ptr</code> because when drop exits, it becomes inaccessible.</p> <p>However this wouldn&#39;t work:</p> <span class='rusttest'>#![feature(alloc, heap_api, drop_in_place, unique)] extern crate alloc; use std::ptr::{drop_in_place, Unique}; use std::mem; use alloc::heap; struct Box&lt;T&gt;{ ptr: Unique&lt;T&gt; } impl&lt;T&gt; Drop for Box&lt;T&gt; { fn drop(&amp;mut self) { unsafe { drop_in_place(*self.ptr); heap::deallocate((*self.ptr) as *mut u8, mem::size_of::&lt;T&gt;(), mem::align_of::&lt;T&gt;()); } } } struct SuperBox&lt;T&gt; { my_box: Box&lt;T&gt; } impl&lt;T&gt; Drop for SuperBox&lt;T&gt; { fn drop(&amp;mut self) { unsafe { // Hyper-optimized: deallocate the box&#39;s contents for it // without `drop`ing the contents heap::deallocate((*self.my_box.ptr) as *mut u8, mem::size_of::&lt;T&gt;(), mem::align_of::&lt;T&gt;()); } } } fn main() {} </span><pre class='rust rust-example-rendered'> <span class='attribute'>#<span class='op'>!</span>[<span class='ident'>feature</span>(<span class='ident'>alloc</span>, <span class='ident'>heap_api</span>, <span class='ident'>drop_in_place</span>, <span class='ident'>unique</span>)]</span> <span class='kw'>extern</span> <span class='kw'>crate</span> <span class='ident'>alloc</span>; <span class='kw'>use</span> <span class='ident'>std</span>::<span class='ident'>ptr</span>::{<span class='ident'>drop_in_place</span>, <span class='ident'>Unique</span>}; <span class='kw'>use</span> <span class='ident'>std</span>::<span class='ident'>mem</span>; <span class='kw'>use</span> <span class='ident'>alloc</span>::<span class='ident'>heap</span>; <span class='kw'>struct</span> <span class='ident'>Box</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span>{ <span class='ident'>ptr</span>: <span class='ident'>Unique</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> } <span class='kw'>impl</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> <span class='ident'>Drop</span> <span class='kw'>for</span> <span class='ident'>Box</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> { <span class='kw'>fn</span> <span class='ident'>drop</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>) { <span class='kw'>unsafe</span> { <span class='ident'>drop_in_place</span>(<span class='op'>*</span><span class='self'>self</span>.<span class='ident'>ptr</span>); <span class='ident'>heap</span>::<span class='ident'>deallocate</span>((<span class='op'>*</span><span class='self'>self</span>.<span class='ident'>ptr</span>) <span class='kw'>as</span> <span class='op'>*</span><span class='kw-2'>mut</span> <span class='ident'>u8</span>, <span class='ident'>mem</span>::<span class='ident'>size_of</span>::<span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span>(), <span class='ident'>mem</span>::<span class='ident'>align_of</span>::<span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span>()); } } } <span class='kw'>struct</span> <span class='ident'>SuperBox</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> { <span class='ident'>my_box</span>: <span class='ident'>Box</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> } <span class='kw'>impl</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> <span class='ident'>Drop</span> <span class='kw'>for</span> <span class='ident'>SuperBox</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> { <span class='kw'>fn</span> <span class='ident'>drop</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>) { <span class='kw'>unsafe</span> { <span class='comment'>// Hyper-optimized: deallocate the box&#39;s contents for it</span> <span class='comment'>// without `drop`ing the contents</span> <span class='ident'>heap</span>::<span class='ident'>deallocate</span>((<span class='op'>*</span><span class='self'>self</span>.<span class='ident'>my_box</span>.<span class='ident'>ptr</span>) <span class='kw'>as</span> <span class='op'>*</span><span class='kw-2'>mut</span> <span class='ident'>u8</span>, <span class='ident'>mem</span>::<span class='ident'>size_of</span>::<span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span>(), <span class='ident'>mem</span>::<span class='ident'>align_of</span>::<span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span>()); } } }</pre> <p>After we deallocate the <code>box</code>&#39;s ptr in SuperBox&#39;s destructor, Rust will happily proceed to tell the box to Drop itself and everything will blow up with use-after-frees and double-frees.</p> <p>Note that the recursive drop behavior applies to all structs and enums regardless of whether they implement Drop. Therefore something like</p> <span class='rusttest'>fn main() { struct Boxy&lt;T&gt; { data1: Box&lt;T&gt;, data2: Box&lt;T&gt;, info: u32, } }</span><pre class='rust rust-example-rendered'> <span class='kw'>struct</span> <span class='ident'>Boxy</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> { <span class='ident'>data1</span>: <span class='ident'>Box</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span>, <span class='ident'>data2</span>: <span class='ident'>Box</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span>, <span class='ident'>info</span>: <span class='ident'>u32</span>, }</pre> <p>will have its data1 and data2&#39;s fields destructors whenever it &quot;would&quot; be dropped, even though it itself doesn&#39;t implement Drop. We say that such a type <em>needs Drop</em>, even though it is not itself Drop.</p> <p>Similarly,</p> <span class='rusttest'>fn main() { enum Link { Next(Box&lt;Link&gt;), None, } }</span><pre class='rust rust-example-rendered'> <span class='kw'>enum</span> <span class='ident'>Link</span> { <span class='ident'>Next</span>(<span class='ident'>Box</span><span class='op'>&lt;</span><span class='ident'>Link</span><span class='op'>&gt;</span>), <span class='prelude-val'>None</span>, }</pre> <p>will have its inner Box field dropped if and only if an instance stores the Next variant.</p> <p>In general this works really nicely because you don&#39;t need to worry about adding/removing drops when you refactor your data layout. Still there&#39;s certainly many valid usecases for needing to do trickier things with destructors.</p> <p>The classic safe solution to overriding recursive drop and allowing moving out of Self during <code>drop</code> is to use an Option:</p> <span class='rusttest'>#![feature(alloc, heap_api, drop_in_place, unique)] extern crate alloc; use std::ptr::{drop_in_place, Unique}; use std::mem; use alloc::heap; struct Box&lt;T&gt;{ ptr: Unique&lt;T&gt; } impl&lt;T&gt; Drop for Box&lt;T&gt; { fn drop(&amp;mut self) { unsafe { drop_in_place(*self.ptr); heap::deallocate((*self.ptr) as *mut u8, mem::size_of::&lt;T&gt;(), mem::align_of::&lt;T&gt;()); } } } struct SuperBox&lt;T&gt; { my_box: Option&lt;Box&lt;T&gt;&gt; } impl&lt;T&gt; Drop for SuperBox&lt;T&gt; { fn drop(&amp;mut self) { unsafe { // Hyper-optimized: deallocate the box&#39;s contents for it // without `drop`ing the contents. Need to set the `box` // field as `None` to prevent Rust from trying to Drop it. let my_box = self.my_box.take().unwrap(); heap::deallocate((*my_box.ptr) as *mut u8, mem::size_of::&lt;T&gt;(), mem::align_of::&lt;T&gt;()); mem::forget(my_box); } } } fn main() {} </span><pre class='rust rust-example-rendered'> <span class='attribute'>#<span class='op'>!</span>[<span class='ident'>feature</span>(<span class='ident'>alloc</span>, <span class='ident'>heap_api</span>, <span class='ident'>drop_in_place</span>, <span class='ident'>unique</span>)]</span> <span class='kw'>extern</span> <span class='kw'>crate</span> <span class='ident'>alloc</span>; <span class='kw'>use</span> <span class='ident'>std</span>::<span class='ident'>ptr</span>::{<span class='ident'>drop_in_place</span>, <span class='ident'>Unique</span>}; <span class='kw'>use</span> <span class='ident'>std</span>::<span class='ident'>mem</span>; <span class='kw'>use</span> <span class='ident'>alloc</span>::<span class='ident'>heap</span>; <span class='kw'>struct</span> <span class='ident'>Box</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span>{ <span class='ident'>ptr</span>: <span class='ident'>Unique</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> } <span class='kw'>impl</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> <span class='ident'>Drop</span> <span class='kw'>for</span> <span class='ident'>Box</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> { <span class='kw'>fn</span> <span class='ident'>drop</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>) { <span class='kw'>unsafe</span> { <span class='ident'>drop_in_place</span>(<span class='op'>*</span><span class='self'>self</span>.<span class='ident'>ptr</span>); <span class='ident'>heap</span>::<span class='ident'>deallocate</span>((<span class='op'>*</span><span class='self'>self</span>.<span class='ident'>ptr</span>) <span class='kw'>as</span> <span class='op'>*</span><span class='kw-2'>mut</span> <span class='ident'>u8</span>, <span class='ident'>mem</span>::<span class='ident'>size_of</span>::<span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span>(), <span class='ident'>mem</span>::<span class='ident'>align_of</span>::<span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span>()); } } } <span class='kw'>struct</span> <span class='ident'>SuperBox</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> { <span class='ident'>my_box</span>: <span class='prelude-ty'>Option</span><span class='op'>&lt;</span><span class='ident'>Box</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;&gt;</span> } <span class='kw'>impl</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> <span class='ident'>Drop</span> <span class='kw'>for</span> <span class='ident'>SuperBox</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> { <span class='kw'>fn</span> <span class='ident'>drop</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>) { <span class='kw'>unsafe</span> { <span class='comment'>// Hyper-optimized: deallocate the box&#39;s contents for it</span> <span class='comment'>// without `drop`ing the contents. Need to set the `box`</span> <span class='comment'>// field as `None` to prevent Rust from trying to Drop it.</span> <span class='kw'>let</span> <span class='ident'>my_box</span> <span class='op'>=</span> <span class='self'>self</span>.<span class='ident'>my_box</span>.<span class='ident'>take</span>().<span class='ident'>unwrap</span>(); <span class='ident'>heap</span>::<span class='ident'>deallocate</span>((<span class='op'>*</span><span class='ident'>my_box</span>.<span class='ident'>ptr</span>) <span class='kw'>as</span> <span class='op'>*</span><span class='kw-2'>mut</span> <span class='ident'>u8</span>, <span class='ident'>mem</span>::<span class='ident'>size_of</span>::<span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span>(), <span class='ident'>mem</span>::<span class='ident'>align_of</span>::<span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span>()); <span class='ident'>mem</span>::<span class='ident'>forget</span>(<span class='ident'>my_box</span>); } } }</pre> <p>However this has fairly odd semantics: you&#39;re saying that a field that <em>should</em> always be Some <em>may</em> be None, just because that happens in the destructor. Of course this conversely makes a lot of sense: you can call arbitrary methods on self during the destructor, and this should prevent you from ever doing so after deinitializing the field. Not that it will prevent you from producing any other arbitrarily invalid state in there.</p> <p>On balance this is an ok choice. Certainly what you should reach for by default. However, in the future we expect there to be a first-class way to announce that a field shouldn&#39;t be automatically dropped.</p> <script type="text/javascript"> window.playgroundUrl = "https://play.rust-lang.org"; </script> <script src='rustbook.js'></script> <script src='playpen.js'></script> </div></div> </body> </html> <|start_filename|>docs/1.9/book/match.html<|end_filename|> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="generator" content="rustdoc"> <title>マッチ</title> <link rel="stylesheet" type="text/css" href="rustbook.css"> <meta name="robots" content="noindex"> </head> <body class="rustdoc"> <!--[if lte IE 8]> <div class="warning"> This old browser is unsupported and will most likely display funky things. </div> <![endif]--> <div id="nav"> <button id="toggle-nav"> <span class="sr-only">Toggle navigation</span> <span class="bar"></span> <span class="bar"></span> <span class="bar"></span> </button> </div> <div id='toc' class='mobile-hidden'> <ul class='chapter'> <li><a href='README.html'><b>1.</b> Introduction</a> </li> <li><a href='getting-started.html'><b>2.</b> はじめる</a> </li> <li><a href='guessing-game.html'><b>3.</b> チュートリアル:数当てゲーム</a> </li> <li><a href='syntax-and-semantics.html'><b>4.</b> シンタックスとセマンティクス</a> <ul class='section'> <li><a href='variable-bindings.html'><b>4.1.</b> 変数束縛</a> </li> <li><a href='functions.html'><b>4.2.</b> 関数</a> </li> <li><a href='primitive-types.html'><b>4.3.</b> プリミティブ型</a> </li> <li><a href='comments.html'><b>4.4.</b> コメント</a> </li> <li><a href='if.html'><b>4.5.</b> if</a> </li> <li><a href='loops.html'><b>4.6.</b> ループ</a> </li> <li><a href='vectors.html'><b>4.7.</b> ベクタ</a> </li> <li><a href='ownership.html'><b>4.8.</b> 所有権</a> </li> <li><a href='references-and-borrowing.html'><b>4.9.</b> 参照と借用</a> </li> <li><a href='lifetimes.html'><b>4.10.</b> ライフタイム</a> </li> <li><a href='mutability.html'><b>4.11.</b> ミュータビリティ</a> </li> <li><a href='structs.html'><b>4.12.</b> 構造体</a> </li> <li><a href='enums.html'><b>4.13.</b> 列挙型</a> </li> <li><a class='active' href='match.html'><b>4.14.</b> マッチ</a> </li> <li><a href='patterns.html'><b>4.15.</b> パターン</a> </li> <li><a href='method-syntax.html'><b>4.16.</b> メソッド構文</a> </li> <li><a href='strings.html'><b>4.17.</b> 文字列</a> </li> <li><a href='generics.html'><b>4.18.</b> ジェネリクス</a> </li> <li><a href='traits.html'><b>4.19.</b> トレイト</a> </li> <li><a href='drop.html'><b>4.20.</b> Drop</a> </li> <li><a href='if-let.html'><b>4.21.</b> if let</a> </li> <li><a href='trait-objects.html'><b>4.22.</b> トレイトオブジェクト</a> </li> <li><a href='closures.html'><b>4.23.</b> クロージャ</a> </li> <li><a href='ufcs.html'><b>4.24.</b> 共通の関数呼出構文</a> </li> <li><a href='crates-and-modules.html'><b>4.25.</b> クレートとモジュール</a> </li> <li><a href='const-and-static.html'><b>4.26.</b> `const` と `static`</a> </li> <li><a href='attributes.html'><b>4.27.</b> アトリビュート</a> </li> <li><a href='type-aliases.html'><b>4.28.</b> `type` エイリアス</a> </li> <li><a href='casting-between-types.html'><b>4.29.</b> 型間のキャスト</a> </li> <li><a href='associated-types.html'><b>4.30.</b> 関連型</a> </li> <li><a href='unsized-types.html'><b>4.31.</b> サイズ不定型</a> </li> <li><a href='operators-and-overloading.html'><b>4.32.</b> 演算子とオーバーロード</a> </li> <li><a href='deref-coercions.html'><b>4.33.</b> Derefによる型強制</a> </li> <li><a href='macros.html'><b>4.34.</b> マクロ</a> </li> <li><a href='raw-pointers.html'><b>4.35.</b> 生ポインタ</a> </li> <li><a href='unsafe.html'><b>4.36.</b> `unsafe`</a> </li> </ul> </li> <li><a href='effective-rust.html'><b>5.</b> Effective Rust</a> <ul class='section'> <li><a href='the-stack-and-the-heap.html'><b>5.1.</b> スタックとヒープ</a> </li> <li><a href='testing.html'><b>5.2.</b> テスト</a> </li> <li><a href='conditional-compilation.html'><b>5.3.</b> 条件付きコンパイル</a> </li> <li><a href='documentation.html'><b>5.4.</b> ドキュメント</a> </li> <li><a href='iterators.html'><b>5.5.</b> イテレータ</a> </li> <li><a href='concurrency.html'><b>5.6.</b> 並行性</a> </li> <li><a href='error-handling.html'><b>5.7.</b> エラーハンドリング</a> </li> <li><a href='choosing-your-guarantees.html'><b>5.8.</b> 保証を選ぶ</a> </li> <li><a href='ffi.html'><b>5.9.</b> 他言語関数インターフェース</a> </li> <li><a href='borrow-and-asref.html'><b>5.10.</b> BorrowとAsRef</a> </li> <li><a href='release-channels.html'><b>5.11.</b> リリースチャネル</a> </li> <li><a href='using-rust-without-the-standard-library.html'><b>5.12.</b> 標準ライブラリ無しでRustを使う</a> </li> </ul> </li> <li><a href='nightly-rust.html'><b>6.</b> Nightly Rust</a> <ul class='section'> <li><a href='compiler-plugins.html'><b>6.1.</b> コンパイラプラグイン</a> </li> <li><a href='inline-assembly.html'><b>6.2.</b> インラインアセンブリ</a> </li> <li><a href='no-stdlib.html'><b>6.3.</b> No stdlib</a> </li> <li><a href='intrinsics.html'><b>6.4.</b> Intrinsic</a> </li> <li><a href='lang-items.html'><b>6.5.</b> 言語アイテム</a> </li> <li><a href='advanced-linking.html'><b>6.6.</b> 高度なリンキング</a> </li> <li><a href='benchmark-tests.html'><b>6.7.</b> ベンチマークテスト</a> </li> <li><a href='box-syntax-and-patterns.html'><b>6.8.</b> Box構文とパターン</a> </li> <li><a href='slice-patterns.html'><b>6.9.</b> スライスパターン</a> </li> <li><a href='associated-constants.html'><b>6.10.</b> 関連定数</a> </li> <li><a href='custom-allocators.html'><b>6.11.</b> カスタムアロケータ</a> </li> </ul> </li> <li><a href='glossary.html'><b>7.</b> 用語集</a> </li> <li><a href='syntax-index.html'><b>8.</b> 構文の索引</a> </li> <li><a href='bibliography.html'><b>9.</b> 関係書目</a> </li> </ul> </div> <div id='page-wrapper'> <div id='page'> <blockquote class="header-caveat"> <p> <strong>注意: <a href="https://doc.rust-jp.rs/book-ja/">最新版のドキュメントをご覧ください。</a></strong>この第1版ドキュメントは古くなっており、最新情報が反映されていません。リンク先のドキュメントが現在の Rust の最新のドキュメントです。 </p> </blockquote> <h1 class="title">マッチ</h1> <!-- % Match --> <!-- Often, a simple [`if`][if]/`else` isn’t enough, because you have more than two --> <!-- possible options. Also, conditions can get quite complex. Rust --> <!-- has a keyword, `match`, that allows you to replace complicated `if`/`else` --> <!-- groupings with something more powerful. Check it out: --> <p>しばしば、2つ以上の可能な処理が存在するためや、分岐条件が非常に複雑になるために単純な <a href="if.html"><code>if</code></a>/<code>else</code> では充分でない場合があります。 Rustにはキーワード <code>match</code> が存在し、複雑な <code>if</code>/<code>else</code> のグループをさらに強力なもので置き換えられます。 以下の例を見てみましょう:</p> <span class='rusttest'>fn main() { let x = 5; match x { 1 =&gt; println!(&quot;one&quot;), 2 =&gt; println!(&quot;two&quot;), 3 =&gt; println!(&quot;three&quot;), 4 =&gt; println!(&quot;four&quot;), 5 =&gt; println!(&quot;five&quot;), _ =&gt; println!(&quot;something else&quot;), } }</span><pre class='rust rust-example-rendered'> <span class='kw'>let</span> <span class='ident'>x</span> <span class='op'>=</span> <span class='number'>5</span>; <span class='kw'>match</span> <span class='ident'>x</span> { <span class='number'>1</span> <span class='op'>=&gt;</span> <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;one&quot;</span>), <span class='number'>2</span> <span class='op'>=&gt;</span> <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;two&quot;</span>), <span class='number'>3</span> <span class='op'>=&gt;</span> <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;three&quot;</span>), <span class='number'>4</span> <span class='op'>=&gt;</span> <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;four&quot;</span>), <span class='number'>5</span> <span class='op'>=&gt;</span> <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;five&quot;</span>), _ <span class='op'>=&gt;</span> <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;something else&quot;</span>), }</pre> <!-- `match` takes an expression and then branches based on its value. Each ‘arm’ of --> <!-- the branch is of the form `val => expression`. When the value matches, that arm’s --> <!-- expression will be evaluated. It’s called `match` because of the term ‘pattern --> <!-- matching’, which `match` is an implementation of. There’s a [separate section on --> <!-- patterns][patterns] that covers all the patterns that are possible here. --> <p><code>match</code> は一つの式とその式の値に基づく複数のブランチを取ります。 一つ一つの「腕」は <code>val =&gt; expression</code> という形式を取ります。 値がマッチした時に、対応する腕の式が評価されます。 このような式が <code>match</code> と呼ばれるのは「パターンマッチ」という用語に由来します。 <a href="patterns.html">パターン</a> のセクションではこの部分に書けるすべてのパターンを説明しています。</p> <!-- One of the many advantages of `match` is it enforces ‘exhaustiveness checking’. --> <!-- For example if we remove the last arm with the underscore `_`, the compiler will --> <!-- give us an error: --> <p>数ある <code>match</code> の利点のうちの一つに「網羅性検査」を行なうということが上げられます。 例えば最後の <code>_</code> の腕を消すと、コンパイラはエラーを出します。</p> <pre><code class="language-text">error: non-exhaustive patterns: `_` not covered </code></pre> <!-- Rust is telling us that we forgot some value. The compiler infers from `x` that it --> <!-- can have any 32bit integer value; for example -2,147,483,648 to 2,147,483,647. The `_` acts --> <!-- as a 'catch-all', and will catch all possible values that *aren't* specified in --> <!-- an arm of `match`. As you can see in the previous example, we provide `match` --> <!-- arms for integers 1-5, if `x` is 6 or any other value, then it is caught by `_`. --> <p>Rustは何かしらの値を忘れていると教えてくれています。 コンパイラは <code>x</code> が任意の32bitの値、例えば-2,147,483,648から2,147,483,647を取り得ると推論します。 <code>_</code> が「がらくた入れ」として振舞います、 <code>match</code> の腕で指定され <em>なかった</em> 可能な値全てを捕捉します。 先の例で見た通り、 <code>match</code> の腕は 1〜5の値を書いたので、 <code>x</code> が6、あるいは他の値だった時は <code>_</code> に捕捉されます。</p> <!-- `match` is also an expression, which means we can use it on the right-hand --> <!-- side of a `let` binding or directly where an expression is used: --> <p><code>match</code> は式でもあります、これはつまり <code>let</code> 束縛の右側や式が使われているところで利用することができるということを意味しています。</p> <span class='rusttest'>fn main() { let x = 5; let number = match x { 1 =&gt; &quot;one&quot;, 2 =&gt; &quot;two&quot;, 3 =&gt; &quot;three&quot;, 4 =&gt; &quot;four&quot;, 5 =&gt; &quot;five&quot;, _ =&gt; &quot;something else&quot;, }; }</span><pre class='rust rust-example-rendered'> <span class='kw'>let</span> <span class='ident'>x</span> <span class='op'>=</span> <span class='number'>5</span>; <span class='kw'>let</span> <span class='ident'>number</span> <span class='op'>=</span> <span class='kw'>match</span> <span class='ident'>x</span> { <span class='number'>1</span> <span class='op'>=&gt;</span> <span class='string'>&quot;one&quot;</span>, <span class='number'>2</span> <span class='op'>=&gt;</span> <span class='string'>&quot;two&quot;</span>, <span class='number'>3</span> <span class='op'>=&gt;</span> <span class='string'>&quot;three&quot;</span>, <span class='number'>4</span> <span class='op'>=&gt;</span> <span class='string'>&quot;four&quot;</span>, <span class='number'>5</span> <span class='op'>=&gt;</span> <span class='string'>&quot;five&quot;</span>, _ <span class='op'>=&gt;</span> <span class='string'>&quot;something else&quot;</span>, };</pre> <!-- Sometimes it’s a nice way of converting something from one type to another; in --> <!-- this example the integers are converted to `String`. --> <p>このようにして、ある型から他の型への変換がうまく書ける場合があります。 この例では整数が <code>String</code> に変換されています。</p> <!-- # Matching on enums --> <h1 id='列挙型に対するマッチ' class='section-header'><a href='#列挙型に対するマッチ'>列挙型に対するマッチ</a></h1> <!-- Another important use of the `match` keyword is to process the possible --> <!-- variants of an enum: --> <p><code>match</code> の他の重要な利用方法としては列挙型のバリアントを処理することがあります:</p> <span class='rusttest'>fn main() { enum Message { Quit, ChangeColor(i32, i32, i32), Move { x: i32, y: i32 }, Write(String), } fn quit() { /* ... */ } fn change_color(r: i32, g: i32, b: i32) { /* ... */ } fn move_cursor(x: i32, y: i32) { /* ... */ } fn process_message(msg: Message) { match msg { Message::Quit =&gt; quit(), Message::ChangeColor(r, g, b) =&gt; change_color(r, g, b), Message::Move { x: x, y: y } =&gt; move_cursor(x, y), Message::Write(s) =&gt; println!(&quot;{}&quot;, s), }; } }</span><pre class='rust rust-example-rendered'> <span class='kw'>enum</span> <span class='ident'>Message</span> { <span class='ident'>Quit</span>, <span class='ident'>ChangeColor</span>(<span class='ident'>i32</span>, <span class='ident'>i32</span>, <span class='ident'>i32</span>), <span class='ident'>Move</span> { <span class='ident'>x</span>: <span class='ident'>i32</span>, <span class='ident'>y</span>: <span class='ident'>i32</span> }, <span class='ident'>Write</span>(<span class='ident'>String</span>), } <span class='kw'>fn</span> <span class='ident'>quit</span>() { <span class='comment'>/* ... */</span> } <span class='kw'>fn</span> <span class='ident'>change_color</span>(<span class='ident'>r</span>: <span class='ident'>i32</span>, <span class='ident'>g</span>: <span class='ident'>i32</span>, <span class='ident'>b</span>: <span class='ident'>i32</span>) { <span class='comment'>/* ... */</span> } <span class='kw'>fn</span> <span class='ident'>move_cursor</span>(<span class='ident'>x</span>: <span class='ident'>i32</span>, <span class='ident'>y</span>: <span class='ident'>i32</span>) { <span class='comment'>/* ... */</span> } <span class='kw'>fn</span> <span class='ident'>process_message</span>(<span class='ident'>msg</span>: <span class='ident'>Message</span>) { <span class='kw'>match</span> <span class='ident'>msg</span> { <span class='ident'>Message</span>::<span class='ident'>Quit</span> <span class='op'>=&gt;</span> <span class='ident'>quit</span>(), <span class='ident'>Message</span>::<span class='ident'>ChangeColor</span>(<span class='ident'>r</span>, <span class='ident'>g</span>, <span class='ident'>b</span>) <span class='op'>=&gt;</span> <span class='ident'>change_color</span>(<span class='ident'>r</span>, <span class='ident'>g</span>, <span class='ident'>b</span>), <span class='ident'>Message</span>::<span class='ident'>Move</span> { <span class='ident'>x</span>: <span class='ident'>x</span>, <span class='ident'>y</span>: <span class='ident'>y</span> } <span class='op'>=&gt;</span> <span class='ident'>move_cursor</span>(<span class='ident'>x</span>, <span class='ident'>y</span>), <span class='ident'>Message</span>::<span class='ident'>Write</span>(<span class='ident'>s</span>) <span class='op'>=&gt;</span> <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;{}&quot;</span>, <span class='ident'>s</span>), }; }</pre> <!-- Again, the Rust compiler checks exhaustiveness, so it demands that you --> <!-- have a match arm for every variant of the enum. If you leave one off, it --> <!-- will give you a compile-time error unless you use `_` or provide all possible --> <!-- arms. --> <p>繰り返しになりますが、Rustコンパイラは網羅性のチェックを行い、列挙型のすべてのバリアントに対して、マッチする腕が存在することを要求します。 もし、一つでもマッチする腕のないバリアントを残している場合、 <code>_</code> を用いるか可能な腕を全て書くかしなければコンパイルエラーが発生します。</p> <!-- Unlike the previous uses of `match`, you can’t use the normal `if` --> <!-- statement to do this. You can use the [`if let`][if-let] statement, --> <!-- which can be seen as an abbreviated form of `match`. --> <p>先ほど説明した値に対する <code>match</code> の利用とは異なり、列挙型のバリアントに基いた分岐に <code>if</code> を用いることはできません。 列挙型のバリアントに基いた分岐には <a href="if-let.html"><code>if let</code></a> 文を用いることが可能です。 <code>if let</code> は <code>match</code> の短縮形と捉えることができます。</p> <script type="text/javascript"> window.playgroundUrl = "https://play.rust-lang.org"; </script> <script src='rustbook.js'></script> <script src='playpen.js'></script> </div></div> </body> </html> <|start_filename|>docs/1.9/nomicon/subtyping.html<|end_filename|> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="generator" content="rustdoc"> <title>Subtyping and Variance</title> <link rel="stylesheet" type="text/css" href="rustbook.css"> <meta name="robots" content="noindex"> </head> <body class="rustdoc"> <!--[if lte IE 8]> <div class="warning"> This old browser is unsupported and will most likely display funky things. </div> <![endif]--> <div id="nav"> <button id="toggle-nav"> <span class="sr-only">Toggle navigation</span> <span class="bar"></span> <span class="bar"></span> <span class="bar"></span> </button> </div> <div id='toc' class='mobile-hidden'> <ul class='chapter'> <li><a href='README.html'><b>1.</b> Introduction</a> </li> <li><a href='meet-safe-and-unsafe.html'><b>2.</b> Meet Safe and Unsafe</a> <ul class='section'> <li><a href='safe-unsafe-meaning.html'><b>2.1.</b> How Safe and Unsafe Interact</a> </li> <li><a href='working-with-unsafe.html'><b>2.2.</b> Working with Unsafe</a> </li> </ul> </li> <li><a href='data.html'><b>3.</b> Data Layout</a> <ul class='section'> <li><a href='repr-rust.html'><b>3.1.</b> repr(Rust)</a> </li> <li><a href='exotic-sizes.html'><b>3.2.</b> Exotically Sized Types</a> </li> <li><a href='other-reprs.html'><b>3.3.</b> Other reprs</a> </li> </ul> </li> <li><a href='ownership.html'><b>4.</b> Ownership</a> <ul class='section'> <li><a href='references.html'><b>4.1.</b> References</a> </li> <li><a href='lifetimes.html'><b>4.2.</b> Lifetimes</a> </li> <li><a href='lifetime-mismatch.html'><b>4.3.</b> Limits of Lifetimes</a> </li> <li><a href='lifetime-elision.html'><b>4.4.</b> Lifetime Elision</a> </li> <li><a href='unbounded-lifetimes.html'><b>4.5.</b> Unbounded Lifetimes</a> </li> <li><a href='hrtb.html'><b>4.6.</b> Higher-Rank Trait Bounds</a> </li> <li><a class='active' href='subtyping.html'><b>4.7.</b> Subtyping and Variance</a> </li> <li><a href='dropck.html'><b>4.8.</b> Drop Check</a> </li> <li><a href='phantom-data.html'><b>4.9.</b> PhantomData</a> </li> <li><a href='borrow-splitting.html'><b>4.10.</b> Splitting Borrows</a> </li> </ul> </li> <li><a href='conversions.html'><b>5.</b> Type Conversions</a> <ul class='section'> <li><a href='coercions.html'><b>5.1.</b> Coercions</a> </li> <li><a href='dot-operator.html'><b>5.2.</b> The Dot Operator</a> </li> <li><a href='casts.html'><b>5.3.</b> Casts</a> </li> <li><a href='transmutes.html'><b>5.4.</b> Transmutes</a> </li> </ul> </li> <li><a href='uninitialized.html'><b>6.</b> Uninitialized Memory</a> <ul class='section'> <li><a href='checked-uninit.html'><b>6.1.</b> Checked</a> </li> <li><a href='drop-flags.html'><b>6.2.</b> Drop Flags</a> </li> <li><a href='unchecked-uninit.html'><b>6.3.</b> Unchecked</a> </li> </ul> </li> <li><a href='obrm.html'><b>7.</b> Ownership Based Resource Management</a> <ul class='section'> <li><a href='constructors.html'><b>7.1.</b> Constructors</a> </li> <li><a href='destructors.html'><b>7.2.</b> Destructors</a> </li> <li><a href='leaking.html'><b>7.3.</b> Leaking</a> </li> </ul> </li> <li><a href='unwinding.html'><b>8.</b> Unwinding</a> <ul class='section'> <li><a href='exception-safety.html'><b>8.1.</b> Exception Safety</a> </li> <li><a href='poisoning.html'><b>8.2.</b> Poisoning</a> </li> </ul> </li> <li><a href='concurrency.html'><b>9.</b> Concurrency</a> <ul class='section'> <li><a href='races.html'><b>9.1.</b> Races</a> </li> <li><a href='send-and-sync.html'><b>9.2.</b> Send and Sync</a> </li> <li><a href='atomics.html'><b>9.3.</b> Atomics</a> </li> </ul> </li> <li><a href='vec.html'><b>10.</b> Implementing Vec</a> <ul class='section'> <li><a href='vec-layout.html'><b>10.1.</b> Layout</a> </li> <li><a href='vec-alloc.html'><b>10.2.</b> Allocating</a> </li> <li><a href='vec-push-pop.html'><b>10.3.</b> Push and Pop</a> </li> <li><a href='vec-dealloc.html'><b>10.4.</b> Deallocating</a> </li> <li><a href='vec-deref.html'><b>10.5.</b> Deref</a> </li> <li><a href='vec-insert-remove.html'><b>10.6.</b> Insert and Remove</a> </li> <li><a href='vec-into-iter.html'><b>10.7.</b> IntoIter</a> </li> <li><a href='vec-raw.html'><b>10.8.</b> RawVec</a> </li> <li><a href='vec-drain.html'><b>10.9.</b> Drain</a> </li> <li><a href='vec-zsts.html'><b>10.10.</b> Handling Zero-Sized Types</a> </li> <li><a href='vec-final.html'><b>10.11.</b> Final Code</a> </li> </ul> </li> <li><a href='arc-and-mutex.html'><b>11.</b> Implementing Arc and Mutex</a> </li> </ul> </div> <div id='page-wrapper'> <div id='page'> <blockquote class="header-caveat"> <p> <strong>注意: <a href="https://doc.rust-jp.rs/book-ja/">最新版のドキュメントをご覧ください。</a></strong>この第1版ドキュメントは古くなっており、最新情報が反映されていません。リンク先のドキュメントが現在の Rust の最新のドキュメントです。 </p> </blockquote> <h1 class="title">Subtyping and Variance</h1> <p>Although Rust doesn&#39;t have any notion of structural inheritance, it <em>does</em> include subtyping. In Rust, subtyping derives entirely from lifetimes. Since lifetimes are scopes, we can partially order them based on the <em>contains</em> (outlives) relationship. We can even express this as a generic bound.</p> <p>Subtyping on lifetimes is in terms of that relationship: if <code>&#39;a: &#39;b</code> (&quot;a contains b&quot; or &quot;a outlives b&quot;), then <code>&#39;a</code> is a subtype of <code>&#39;b</code>. This is a large source of confusion, because it seems intuitively backwards to many: the bigger scope is a <em>subtype</em> of the smaller scope.</p> <p>This does in fact make sense, though. The intuitive reason for this is that if you expect an <code>&amp;&#39;a u8</code>, then it&#39;s totally fine for me to hand you an <code>&amp;&#39;static u8</code>, in the same way that if you expect an Animal in Java, it&#39;s totally fine for me to hand you a Cat. Cats are just Animals <em>and more</em>, just as <code>&#39;static</code> is just <code>&#39;a</code> <em>and more</em>.</p> <p>(Note, the subtyping relationship and typed-ness of lifetimes is a fairly arbitrary construct that some disagree with. However it simplifies our analysis to treat lifetimes and types uniformly.)</p> <p>Higher-ranked lifetimes are also subtypes of every concrete lifetime. This is because taking an arbitrary lifetime is strictly more general than taking a specific one.</p> <h1 id='variance' class='section-header'><a href='#variance'>Variance</a></h1> <p>Variance is where things get a bit complicated.</p> <p>Variance is a property that <em>type constructors</em> have with respect to their arguments. A type constructor in Rust is a generic type with unbound arguments. For instance <code>Vec</code> is a type constructor that takes a <code>T</code> and returns a <code>Vec&lt;T&gt;</code>. <code>&amp;</code> and <code>&amp;mut</code> are type constructors that take two inputs: a lifetime, and a type to point to.</p> <p>A type constructor&#39;s <em>variance</em> is how the subtyping of its inputs affects the subtyping of its outputs. There are two kinds of variance in Rust:</p> <ul> <li>F is <em>variant</em> over <code>T</code> if <code>T</code> being a subtype of <code>U</code> implies <code>F&lt;T&gt;</code> is a subtype of <code>F&lt;U&gt;</code> (subtyping &quot;passes through&quot;)</li> <li>F is <em>invariant</em> over <code>T</code> otherwise (no subtyping relation can be derived)</li> </ul> <p>(For those of you who are familiar with variance from other languages, what we refer to as &quot;just&quot; variance is in fact <em>covariance</em>. Rust does not have contravariance. Historically Rust did have some contravariance but it was scrapped due to poor interactions with other features. If you experience contravariance in Rust call your local compiler developer for medical advice.)</p> <p>Some important variances:</p> <ul> <li><code>&amp;&#39;a T</code> is variant over <code>&#39;a</code> and <code>T</code> (as is <code>*const T</code> by metaphor)</li> <li><code>&amp;&#39;a mut T</code> is variant with over <code>&#39;a</code> but invariant over <code>T</code></li> <li><code>Fn(T) -&gt; U</code> is invariant over <code>T</code>, but variant over <code>U</code></li> <li><code>Box</code>, <code>Vec</code>, and all other collections are variant over the types of their contents</li> <li><code>UnsafeCell&lt;T&gt;</code>, <code>Cell&lt;T&gt;</code>, <code>RefCell&lt;T&gt;</code>, <code>Mutex&lt;T&gt;</code> and all other interior mutability types are invariant over T (as is <code>*mut T</code> by metaphor)</li> </ul> <p>To understand why these variances are correct and desirable, we will consider several examples.</p> <p>We have already covered why <code>&amp;&#39;a T</code> should be variant over <code>&#39;a</code> when introducing subtyping: it&#39;s desirable to be able to pass longer-lived things where shorter-lived things are needed.</p> <p>Similar reasoning applies to why it should be variant over T. It is reasonable to be able to pass <code>&amp;&amp;&#39;static str</code> where an <code>&amp;&amp;&#39;a str</code> is expected. The additional level of indirection does not change the desire to be able to pass longer lived things where shorted lived things are expected.</p> <p>However this logic doesn&#39;t apply to <code>&amp;mut</code>. To see why <code>&amp;mut</code> should be invariant over T, consider the following code:</p> <span class='rusttest'>fn overwrite&lt;T: Copy&gt;(input: &amp;mut T, new: &amp;mut T) { *input = *new; } fn main() { let mut forever_str: &amp;&#39;static str = &quot;hello&quot;; { let string = String::from(&quot;world&quot;); overwrite(&amp;mut forever_str, &amp;mut &amp;*string); } // Oops, printing free&#39;d memory println!(&quot;{}&quot;, forever_str); } </span><pre class='rust rust-example-rendered'> <span class='kw'>fn</span> <span class='ident'>overwrite</span><span class='op'>&lt;</span><span class='ident'>T</span>: <span class='ident'>Copy</span><span class='op'>&gt;</span>(<span class='ident'>input</span>: <span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='ident'>T</span>, <span class='ident'>new</span>: <span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='ident'>T</span>) { <span class='op'>*</span><span class='ident'>input</span> <span class='op'>=</span> <span class='op'>*</span><span class='ident'>new</span>; } <span class='kw'>fn</span> <span class='ident'>main</span>() { <span class='kw'>let</span> <span class='kw-2'>mut</span> <span class='ident'>forever_str</span>: <span class='kw-2'>&amp;</span><span class='lifetime'>&#39;static</span> <span class='ident'>str</span> <span class='op'>=</span> <span class='string'>&quot;hello&quot;</span>; { <span class='kw'>let</span> <span class='ident'>string</span> <span class='op'>=</span> <span class='ident'>String</span>::<span class='ident'>from</span>(<span class='string'>&quot;world&quot;</span>); <span class='ident'>overwrite</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='ident'>forever_str</span>, <span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='kw-2'>&amp;</span><span class='op'>*</span><span class='ident'>string</span>); } <span class='comment'>// Oops, printing free&#39;d memory</span> <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;{}&quot;</span>, <span class='ident'>forever_str</span>); }</pre> <p>The signature of <code>overwrite</code> is clearly valid: it takes mutable references to two values of the same type, and overwrites one with the other. If <code>&amp;mut T</code> was variant over T, then <code>&amp;mut &amp;&#39;static str</code> would be a subtype of <code>&amp;mut &amp;&#39;a str</code>, since <code>&amp;&#39;static str</code> is a subtype of <code>&amp;&#39;a str</code>. Therefore the lifetime of <code>forever_str</code> would successfully be &quot;shrunk&quot; down to the shorter lifetime of <code>string</code>, and <code>overwrite</code> would be called successfully. <code>string</code> would subsequently be dropped, and <code>forever_str</code> would point to freed memory when we print it! Therefore <code>&amp;mut</code> should be invariant.</p> <p>This is the general theme of variance vs invariance: if variance would allow you to store a short-lived value into a longer-lived slot, then you must be invariant.</p> <p>However it <em>is</em> sound for <code>&amp;&#39;a mut T</code> to be variant over <code>&#39;a</code>. The key difference between <code>&#39;a</code> and T is that <code>&#39;a</code> is a property of the reference itself, while T is something the reference is borrowing. If you change T&#39;s type, then the source still remembers the original type. However if you change the lifetime&#39;s type, no one but the reference knows this information, so it&#39;s fine. Put another way: <code>&amp;&#39;a mut T</code> owns <code>&#39;a</code>, but only <em>borrows</em> T.</p> <p><code>Box</code> and <code>Vec</code> are interesting cases because they&#39;re variant, but you can definitely store values in them! This is where Rust gets really clever: it&#39;s fine for them to be variant because you can only store values in them <em>via a mutable reference</em>! The mutable reference makes the whole type invariant, and therefore prevents you from smuggling a short-lived type into them.</p> <p>Being variant allows <code>Box</code> and <code>Vec</code> to be weakened when shared immutably. So you can pass a <code>&amp;Box&lt;&amp;&#39;static str&gt;</code> where a <code>&amp;Box&lt;&amp;&#39;a str&gt;</code> is expected.</p> <p>However what should happen when passing <em>by-value</em> is less obvious. It turns out that, yes, you can use subtyping when passing by-value. That is, this works:</p> <span class='rusttest'>fn main() { fn get_box&lt;&#39;a&gt;(str: &amp;&#39;a str) -&gt; Box&lt;&amp;&#39;a str&gt; { // string literals are `&amp;&#39;static str`s Box::new(&quot;hello&quot;) } }</span><pre class='rust rust-example-rendered'> <span class='kw'>fn</span> <span class='ident'>get_box</span><span class='op'>&lt;</span><span class='lifetime'>&#39;a</span><span class='op'>&gt;</span>(<span class='ident'>str</span>: <span class='kw-2'>&amp;</span><span class='lifetime'>&#39;a</span> <span class='ident'>str</span>) <span class='op'>-&gt;</span> <span class='ident'>Box</span><span class='op'>&lt;</span><span class='kw-2'>&amp;</span><span class='lifetime'>&#39;a</span> <span class='ident'>str</span><span class='op'>&gt;</span> { <span class='comment'>// string literals are `&amp;&#39;static str`s</span> <span class='ident'>Box</span>::<span class='ident'>new</span>(<span class='string'>&quot;hello&quot;</span>) }</pre> <p>Weakening when you pass by-value is fine because there&#39;s no one else who &quot;remembers&quot; the old lifetime in the Box. The reason a variant <code>&amp;mut</code> was trouble was because there&#39;s always someone else who remembers the original subtype: the actual owner.</p> <p>The invariance of the cell types can be seen as follows: <code>&amp;</code> is like an <code>&amp;mut</code> for a cell, because you can still store values in them through an <code>&amp;</code>. Therefore cells must be invariant to avoid lifetime smuggling.</p> <p><code>Fn</code> is the most subtle case because it has mixed variance. To see why <code>Fn(T) -&gt; U</code> should be invariant over T, consider the following function signature:</p> <span class='rusttest'>fn main() { // &#39;a is derived from some parent scope fn foo(&amp;&#39;a str) -&gt; usize; }</span><pre class='rust rust-example-rendered'> <span class='comment'>// &#39;a is derived from some parent scope</span> <span class='kw'>fn</span> <span class='ident'>foo</span>(<span class='kw-2'>&amp;</span><span class='lifetime'>&#39;a</span> <span class='ident'>str</span>) <span class='op'>-&gt;</span> <span class='ident'>usize</span>;</pre> <p>This signature claims that it can handle any <code>&amp;str</code> that lives at least as long as <code>&#39;a</code>. Now if this signature was variant over <code>&amp;&#39;a str</code>, that would mean</p> <span class='rusttest'>fn main() { fn foo(&amp;&#39;static str) -&gt; usize; }</span><pre class='rust rust-example-rendered'> <span class='kw'>fn</span> <span class='ident'>foo</span>(<span class='kw-2'>&amp;</span><span class='lifetime'>&#39;static</span> <span class='ident'>str</span>) <span class='op'>-&gt;</span> <span class='ident'>usize</span>;</pre> <p>could be provided in its place, as it would be a subtype. However this function has a stronger requirement: it says that it can only handle <code>&amp;&#39;static str</code>s, and nothing else. Giving <code>&amp;&#39;a str</code>s to it would be unsound, as it&#39;s free to assume that what it&#39;s given lives forever. Therefore functions are not variant over their arguments.</p> <p>To see why <code>Fn(T) -&gt; U</code> should be variant over U, consider the following function signature:</p> <span class='rusttest'>fn main() { // &#39;a is derived from some parent scope fn foo(usize) -&gt; &amp;&#39;a str; }</span><pre class='rust rust-example-rendered'> <span class='comment'>// &#39;a is derived from some parent scope</span> <span class='kw'>fn</span> <span class='ident'>foo</span>(<span class='ident'>usize</span>) <span class='op'>-&gt;</span> <span class='kw-2'>&amp;</span><span class='lifetime'>&#39;a</span> <span class='ident'>str</span>;</pre> <p>This signature claims that it will return something that outlives <code>&#39;a</code>. It is therefore completely reasonable to provide</p> <span class='rusttest'>fn main() { fn foo(usize) -&gt; &amp;&#39;static str; }</span><pre class='rust rust-example-rendered'> <span class='kw'>fn</span> <span class='ident'>foo</span>(<span class='ident'>usize</span>) <span class='op'>-&gt;</span> <span class='kw-2'>&amp;</span><span class='lifetime'>&#39;static</span> <span class='ident'>str</span>;</pre> <p>in its place. Therefore functions are variant over their return type.</p> <p><code>*const</code> has the exact same semantics as <code>&amp;</code>, so variance follows. <code>*mut</code> on the other hand can dereference to an <code>&amp;mut</code> whether shared or not, so it is marked as invariant just like cells.</p> <p>This is all well and good for the types the standard library provides, but how is variance determined for type that <em>you</em> define? A struct, informally speaking, inherits the variance of its fields. If a struct <code>Foo</code> has a generic argument <code>A</code> that is used in a field <code>a</code>, then Foo&#39;s variance over <code>A</code> is exactly <code>a</code>&#39;s variance. However this is complicated if <code>A</code> is used in multiple fields.</p> <ul> <li>If all uses of A are variant, then Foo is variant over A</li> <li>Otherwise, Foo is invariant over A</li> </ul> <span class='rusttest'>fn main() { use std::cell::Cell; struct Foo&lt;&#39;a, &#39;b, A: &#39;a, B: &#39;b, C, D, E, F, G, H&gt; { a: &amp;&#39;a A, // variant over &#39;a and A b: &amp;&#39;b mut B, // invariant over &#39;b and B c: *const C, // variant over C d: *mut D, // invariant over D e: Vec&lt;E&gt;, // variant over E f: Cell&lt;F&gt;, // invariant over F g: G, // variant over G h1: H, // would also be variant over H except... h2: Cell&lt;H&gt;, // invariant over H, because invariance wins } }</span><pre class='rust rust-example-rendered'> <span class='kw'>use</span> <span class='ident'>std</span>::<span class='ident'>cell</span>::<span class='ident'>Cell</span>; <span class='kw'>struct</span> <span class='ident'>Foo</span><span class='op'>&lt;</span><span class='lifetime'>&#39;a</span>, <span class='lifetime'>&#39;b</span>, <span class='ident'>A</span>: <span class='lifetime'>&#39;a</span>, <span class='ident'>B</span>: <span class='lifetime'>&#39;b</span>, <span class='ident'>C</span>, <span class='ident'>D</span>, <span class='ident'>E</span>, <span class='ident'>F</span>, <span class='ident'>G</span>, <span class='ident'>H</span><span class='op'>&gt;</span> { <span class='ident'>a</span>: <span class='kw-2'>&amp;</span><span class='lifetime'>&#39;a</span> <span class='ident'>A</span>, <span class='comment'>// variant over &#39;a and A</span> <span class='ident'>b</span>: <span class='kw-2'>&amp;</span><span class='lifetime'>&#39;b</span> <span class='kw-2'>mut</span> <span class='ident'>B</span>, <span class='comment'>// invariant over &#39;b and B</span> <span class='ident'>c</span>: <span class='op'>*</span><span class='kw'>const</span> <span class='ident'>C</span>, <span class='comment'>// variant over C</span> <span class='ident'>d</span>: <span class='op'>*</span><span class='kw-2'>mut</span> <span class='ident'>D</span>, <span class='comment'>// invariant over D</span> <span class='ident'>e</span>: <span class='ident'>Vec</span><span class='op'>&lt;</span><span class='ident'>E</span><span class='op'>&gt;</span>, <span class='comment'>// variant over E</span> <span class='ident'>f</span>: <span class='ident'>Cell</span><span class='op'>&lt;</span><span class='ident'>F</span><span class='op'>&gt;</span>, <span class='comment'>// invariant over F</span> <span class='ident'>g</span>: <span class='ident'>G</span>, <span class='comment'>// variant over G</span> <span class='ident'>h1</span>: <span class='ident'>H</span>, <span class='comment'>// would also be variant over H except...</span> <span class='ident'>h2</span>: <span class='ident'>Cell</span><span class='op'>&lt;</span><span class='ident'>H</span><span class='op'>&gt;</span>, <span class='comment'>// invariant over H, because invariance wins</span> }</pre> <script type="text/javascript"> window.playgroundUrl = "https://play.rust-lang.org"; </script> <script src='rustbook.js'></script> <script src='playpen.js'></script> </div></div> </body> </html> <|start_filename|>docs/1.9/book/iterators.html<|end_filename|> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="generator" content="rustdoc"> <title>イテレータ</title> <link rel="stylesheet" type="text/css" href="rustbook.css"> <meta name="robots" content="noindex"> </head> <body class="rustdoc"> <!--[if lte IE 8]> <div class="warning"> This old browser is unsupported and will most likely display funky things. </div> <![endif]--> <div id="nav"> <button id="toggle-nav"> <span class="sr-only">Toggle navigation</span> <span class="bar"></span> <span class="bar"></span> <span class="bar"></span> </button> </div> <div id='toc' class='mobile-hidden'> <ul class='chapter'> <li><a href='README.html'><b>1.</b> Introduction</a> </li> <li><a href='getting-started.html'><b>2.</b> はじめる</a> </li> <li><a href='guessing-game.html'><b>3.</b> チュートリアル:数当てゲーム</a> </li> <li><a href='syntax-and-semantics.html'><b>4.</b> シンタックスとセマンティクス</a> <ul class='section'> <li><a href='variable-bindings.html'><b>4.1.</b> 変数束縛</a> </li> <li><a href='functions.html'><b>4.2.</b> 関数</a> </li> <li><a href='primitive-types.html'><b>4.3.</b> プリミティブ型</a> </li> <li><a href='comments.html'><b>4.4.</b> コメント</a> </li> <li><a href='if.html'><b>4.5.</b> if</a> </li> <li><a href='loops.html'><b>4.6.</b> ループ</a> </li> <li><a href='vectors.html'><b>4.7.</b> ベクタ</a> </li> <li><a href='ownership.html'><b>4.8.</b> 所有権</a> </li> <li><a href='references-and-borrowing.html'><b>4.9.</b> 参照と借用</a> </li> <li><a href='lifetimes.html'><b>4.10.</b> ライフタイム</a> </li> <li><a href='mutability.html'><b>4.11.</b> ミュータビリティ</a> </li> <li><a href='structs.html'><b>4.12.</b> 構造体</a> </li> <li><a href='enums.html'><b>4.13.</b> 列挙型</a> </li> <li><a href='match.html'><b>4.14.</b> マッチ</a> </li> <li><a href='patterns.html'><b>4.15.</b> パターン</a> </li> <li><a href='method-syntax.html'><b>4.16.</b> メソッド構文</a> </li> <li><a href='strings.html'><b>4.17.</b> 文字列</a> </li> <li><a href='generics.html'><b>4.18.</b> ジェネリクス</a> </li> <li><a href='traits.html'><b>4.19.</b> トレイト</a> </li> <li><a href='drop.html'><b>4.20.</b> Drop</a> </li> <li><a href='if-let.html'><b>4.21.</b> if let</a> </li> <li><a href='trait-objects.html'><b>4.22.</b> トレイトオブジェクト</a> </li> <li><a href='closures.html'><b>4.23.</b> クロージャ</a> </li> <li><a href='ufcs.html'><b>4.24.</b> 共通の関数呼出構文</a> </li> <li><a href='crates-and-modules.html'><b>4.25.</b> クレートとモジュール</a> </li> <li><a href='const-and-static.html'><b>4.26.</b> `const` と `static`</a> </li> <li><a href='attributes.html'><b>4.27.</b> アトリビュート</a> </li> <li><a href='type-aliases.html'><b>4.28.</b> `type` エイリアス</a> </li> <li><a href='casting-between-types.html'><b>4.29.</b> 型間のキャスト</a> </li> <li><a href='associated-types.html'><b>4.30.</b> 関連型</a> </li> <li><a href='unsized-types.html'><b>4.31.</b> サイズ不定型</a> </li> <li><a href='operators-and-overloading.html'><b>4.32.</b> 演算子とオーバーロード</a> </li> <li><a href='deref-coercions.html'><b>4.33.</b> Derefによる型強制</a> </li> <li><a href='macros.html'><b>4.34.</b> マクロ</a> </li> <li><a href='raw-pointers.html'><b>4.35.</b> 生ポインタ</a> </li> <li><a href='unsafe.html'><b>4.36.</b> `unsafe`</a> </li> </ul> </li> <li><a href='effective-rust.html'><b>5.</b> Effective Rust</a> <ul class='section'> <li><a href='the-stack-and-the-heap.html'><b>5.1.</b> スタックとヒープ</a> </li> <li><a href='testing.html'><b>5.2.</b> テスト</a> </li> <li><a href='conditional-compilation.html'><b>5.3.</b> 条件付きコンパイル</a> </li> <li><a href='documentation.html'><b>5.4.</b> ドキュメント</a> </li> <li><a class='active' href='iterators.html'><b>5.5.</b> イテレータ</a> </li> <li><a href='concurrency.html'><b>5.6.</b> 並行性</a> </li> <li><a href='error-handling.html'><b>5.7.</b> エラーハンドリング</a> </li> <li><a href='choosing-your-guarantees.html'><b>5.8.</b> 保証を選ぶ</a> </li> <li><a href='ffi.html'><b>5.9.</b> 他言語関数インターフェース</a> </li> <li><a href='borrow-and-asref.html'><b>5.10.</b> BorrowとAsRef</a> </li> <li><a href='release-channels.html'><b>5.11.</b> リリースチャネル</a> </li> <li><a href='using-rust-without-the-standard-library.html'><b>5.12.</b> 標準ライブラリ無しでRustを使う</a> </li> </ul> </li> <li><a href='nightly-rust.html'><b>6.</b> Nightly Rust</a> <ul class='section'> <li><a href='compiler-plugins.html'><b>6.1.</b> コンパイラプラグイン</a> </li> <li><a href='inline-assembly.html'><b>6.2.</b> インラインアセンブリ</a> </li> <li><a href='no-stdlib.html'><b>6.3.</b> No stdlib</a> </li> <li><a href='intrinsics.html'><b>6.4.</b> Intrinsic</a> </li> <li><a href='lang-items.html'><b>6.5.</b> 言語アイテム</a> </li> <li><a href='advanced-linking.html'><b>6.6.</b> 高度なリンキング</a> </li> <li><a href='benchmark-tests.html'><b>6.7.</b> ベンチマークテスト</a> </li> <li><a href='box-syntax-and-patterns.html'><b>6.8.</b> Box構文とパターン</a> </li> <li><a href='slice-patterns.html'><b>6.9.</b> スライスパターン</a> </li> <li><a href='associated-constants.html'><b>6.10.</b> 関連定数</a> </li> <li><a href='custom-allocators.html'><b>6.11.</b> カスタムアロケータ</a> </li> </ul> </li> <li><a href='glossary.html'><b>7.</b> 用語集</a> </li> <li><a href='syntax-index.html'><b>8.</b> 構文の索引</a> </li> <li><a href='bibliography.html'><b>9.</b> 関係書目</a> </li> </ul> </div> <div id='page-wrapper'> <div id='page'> <blockquote class="header-caveat"> <p> <strong>注意: <a href="https://doc.rust-jp.rs/book-ja/">最新版のドキュメントをご覧ください。</a></strong>この第1版ドキュメントは古くなっており、最新情報が反映されていません。リンク先のドキュメントが現在の Rust の最新のドキュメントです。 </p> </blockquote> <h1 class="title">イテレータ</h1> <!-- % Iterators --> <!-- Let's talk about loops. --> <p>ループの話をしましょう。</p> <!-- Remember Rust's `for` loop? Here's an example: --> <p>Rustの <code>for</code> ループを覚えていますか?以下が例です。</p> <span class='rusttest'>fn main() { for x in 0..10 { println!(&quot;{}&quot;, x); } }</span><pre class='rust rust-example-rendered'> <span class='kw'>for</span> <span class='ident'>x</span> <span class='kw'>in</span> <span class='number'>0</span>..<span class='number'>10</span> { <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;{}&quot;</span>, <span class='ident'>x</span>); }</pre> <!-- Now that you know more Rust, we can talk in detail about how this works. Ranges (the `0..10`) are 'iterators'. An iterator is something that we can call the `.next()` method on repeatedly, and it gives us a sequence of things. --> <p>あなたはもうRustに詳しいので、私たちはどのようにこれが動作しているのか詳しく話すことができます。 レンジ(ranges、ここでは <code>0..10</code> )は「イテレータ」(iterators)です。イテレータは <code>.next()</code> メソッドを繰り返し呼び出すことができ、その都度順番に値を返すものです。</p> <!-- (By the way, a range with two dots like `0..10` is inclusive on the left (so it starts at 0) and exclusive on the right (so it ends at 9). A mathematician would write "[0, 10)". To get a range that goes all the way up to 10 you can write `0...10`.) --> <p>(ところで、 <code>0..10</code> のようにドット2つのレンジは左端を含み(つまり0から始まる)右端を含みません(つまり9で終わる)。数学的な書き方をすれば 「[0, 10)」です。10まで含むレンジが欲しければ <code>0...10</code> と書きます。)</p> <!-- Like this: --> <p>こんな風に:</p> <span class='rusttest'>fn main() { let mut range = 0..10; loop { match range.next() { Some(x) =&gt; { println!(&quot;{}&quot;, x); }, None =&gt; { break } } } }</span><pre class='rust rust-example-rendered'> <span class='kw'>let</span> <span class='kw-2'>mut</span> <span class='ident'>range</span> <span class='op'>=</span> <span class='number'>0</span>..<span class='number'>10</span>; <span class='kw'>loop</span> { <span class='kw'>match</span> <span class='ident'>range</span>.<span class='ident'>next</span>() { <span class='prelude-val'>Some</span>(<span class='ident'>x</span>) <span class='op'>=&gt;</span> { <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;{}&quot;</span>, <span class='ident'>x</span>); }, <span class='prelude-val'>None</span> <span class='op'>=&gt;</span> { <span class='kw'>break</span> } } }</pre> <!-- We make a mutable binding to the range, which is our iterator. We then `loop`, with an inner `match`. This `match` is used on the result of `range.next()`, which gives us a reference to the next value of the iterator. `next` returns an `Option<i32>`, in this case, which will be `Some(i32)` when we have a value and `None` once we run out. If we get `Some(i32)`, we print it out, and if we get `None`, we `break` out of the loop. --> <p>始めに変数rangeへミュータブルな束縛を行っていますが、これがイテレータです。その次には中に <code>match</code> が入った <code>loop</code> があります。この <code>match</code> は <code>range.next()</code> を呼び出し、イテレータから得た次の値への参照を使用しています。 <code>next</code> は <code>Option&lt;i32&gt;</code> を返します。このケースでは、次の値があればその値は <code>Some(i32)</code> であり、返ってくる値が無くなれば <code>None</code> が返ってきます。もし <code>Some(i32)</code> であればそれを表示し、 <code>None</code> であれば <code>break</code> によりループから脱出しています。</p> <!-- This code sample is basically the same as our `for` loop version. The `for` loop is a handy way to write this `loop`/`match`/`break` construct. --> <p>このコードは、基本的に <code>for</code> ループバージョンと同じ動作です。 <code>for</code> ループはこの <code>loop</code>/ <code>match</code> / <code>break</code> で構成された処理を手軽に書ける方法というわけです。</p> <!-- `for` loops aren't the only thing that uses iterators, however. Writing your own iterator involves implementing the `Iterator` trait. While doing that is outside of the scope of this guide, Rust provides a number of useful iterators to accomplish various tasks. But first, a few notes about limitations of ranges. --> <p>しかしながら <code>for</code> ループだけがイテレータを使う訳ではありません。自作のイテレータを書く時は <code>Iterator</code> トレイトを実装する必要があります。それは本書の範囲外ですが、Rustは多様な反復処理を実現するために便利なイテレータを幾つか提供しています。ただその前に、少しばかりレンジの限界について言及しておきましょう。</p> <!-- Ranges are very primitive, and we often can use better alternatives. Consider the following Rust anti-pattern: using ranges to emulate a C-style `for` loop. Let’s suppose you needed to iterate over the contents of a vector. You may be tempted to write this: --> <p>レンジはとても素朴な機能ですから、度々別のより良い手段を用いることもあります。ここであるRustのアンチパターンについて考えてみましょう。それはレンジをC言語ライクな <code>for</code> ループの再現に用いることです。例えばベクタの中身をイテレートする必要があったとしましょう。あなたはこう書きたくなるかもしれません。</p> <span class='rusttest'>fn main() { let nums = vec![1, 2, 3]; for i in 0..nums.len() { println!(&quot;{}&quot;, nums[i]); } }</span><pre class='rust rust-example-rendered'> <span class='kw'>let</span> <span class='ident'>nums</span> <span class='op'>=</span> <span class='macro'>vec</span><span class='macro'>!</span>[<span class='number'>1</span>, <span class='number'>2</span>, <span class='number'>3</span>]; <span class='kw'>for</span> <span class='ident'>i</span> <span class='kw'>in</span> <span class='number'>0</span>..<span class='ident'>nums</span>.<span class='ident'>len</span>() { <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;{}&quot;</span>, <span class='ident'>nums</span>[<span class='ident'>i</span>]); }</pre> <!-- This is strictly worse than using an actual iterator. You can iterate over vectors directly, so write this: --> <p>これは実際のイテレータの使い方からすれば全く正しくありません。あなたはベクタを直接反復処理できるのですから、こう書くべきです。</p> <span class='rusttest'>fn main() { let nums = vec![1, 2, 3]; for num in &amp;nums { println!(&quot;{}&quot;, num); } }</span><pre class='rust rust-example-rendered'> <span class='kw'>let</span> <span class='ident'>nums</span> <span class='op'>=</span> <span class='macro'>vec</span><span class='macro'>!</span>[<span class='number'>1</span>, <span class='number'>2</span>, <span class='number'>3</span>]; <span class='kw'>for</span> <span class='ident'>num</span> <span class='kw'>in</span> <span class='kw-2'>&amp;</span><span class='ident'>nums</span> { <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;{}&quot;</span>, <span class='ident'>num</span>); }</pre> <!-- There are two reasons for this. First, this more directly expresses what we mean. We iterate through the entire vector, rather than iterating through indexes, and then indexing the vector. Second, this version is more efficient: the first version will have extra bounds checking because it used indexing, `nums[i]`. But since we yield a reference to each element of the vector in turn with the iterator, there's no bounds checking in the second example. This is very common with iterators: we can ignore unnecessary bounds checks, but still know that we're safe. --> <p>これには2つの理由があります。第一に、この方が書き手の意図をはっきり表せています。私たちはベクタのインデックスを作成してからその要素を繰り返し参照したいのではなく、ベクタ自体を反復処理したいのです。第二に、このバージョンのほうがより効率的です。1つ目の例では <code>num[i]</code> というようにインデックスを介し参照しているため、余計な境界チェックが発生します。しかし、イテレータが順番にベクタの各要素への参照を生成していくため、2つ目の例では境界チェックが発生しません。これはイテレータにとってごく一般的な性質です。不要な境界チェックを省くことができ、それでもなお安全なままなのです。</p> <!-- There's another detail here that's not 100% clear because of how `println!` works. `num` is actually of type `&i32`. That is, it's a reference to an `i32`, not an `i32` itself. `println!` handles the dereferencing for us, so we don't see it. This code works fine too: --> <p>ここにはもう1つ、<code>println!</code> の動作という詳細が100%はっきりしていない処理があります。 <code>num</code> は実際には <code>&amp;i32</code> 型です。これは <code>i32</code> の参照であり、 <code>i32</code> それ自体ではありません。 <code>println!</code> は上手い具合に参照外し(dereferencing)をしてくれますから、これ以上深追いはしないことにします。以下のコードも正しく動作します。</p> <span class='rusttest'>fn main() { let nums = vec![1, 2, 3]; for num in &amp;nums { println!(&quot;{}&quot;, *num); } }</span><pre class='rust rust-example-rendered'> <span class='kw'>let</span> <span class='ident'>nums</span> <span class='op'>=</span> <span class='macro'>vec</span><span class='macro'>!</span>[<span class='number'>1</span>, <span class='number'>2</span>, <span class='number'>3</span>]; <span class='kw'>for</span> <span class='ident'>num</span> <span class='kw'>in</span> <span class='kw-2'>&amp;</span><span class='ident'>nums</span> { <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;{}&quot;</span>, <span class='op'>*</span><span class='ident'>num</span>); }</pre> <!-- Now we're explicitly dereferencing `num`. Why does `&nums` give us references? Firstly, because we explicitly asked it to with `&`. Secondly, if it gave us the data itself, we would have to be its owner, which would involve making a copy of the data and giving us the copy. With references, we're only borrowing a reference to the data, and so it's only passing a reference, without needing to do the move. --> <p>今、私たちは明示的に <code>num</code> の参照外しを行いました。なぜ <code>&amp;nums</code> は私たちに参照を渡すのでしょうか?第一に、<code>&amp;</code>を用いて私たちが明示的に要求したからです。第二に、もしデータそれ自体を渡す場合、私たちはデータの所有者でなければならないため、データの複製と、それを私たちに渡す操作が伴います。参照を使えば、データへの参照を借用して渡すだけで済み、ムーブを行う必要がなくなります。</p> <!-- So, now that we've established that ranges are often not what you want, let's talk about what you do want instead. --> <p>ここまでで、多くの場合レンジはあなたの欲する物ではないとわかりましたから、あなたが実際に欲しているものについて話しましょう。</p> <!-- There are three broad classes of things that are relevant here: iterators, *iterator adaptors*, and *consumers*. Here's some definitions: --> <p>それは大きく分けてイテレータ、 <em>イテレータアダプタ</em> (iterator adaptors)、そして <em>コンシューマ</em> (consumers)の3つです。以下が定義となります。</p> <!-- * *iterators* give you a sequence of values. * *iterator adaptors* operate on an iterator, producing a new iterator with a different output sequence. * *consumers* operate on an iterator, producing some final set of values. --> <ul> <li><em>イテレータ</em> は値のシーケンスを渡します。</li> <li><em>イテレータアダプタ</em> はイテレータに作用し、出力の異なるイテレータを生成します。</li> <li><em>コンシューマ</em> はイテレータに作用し、幾つかの最終的な値の組を生成します。</li> </ul> <!-- Let's talk about consumers first, since you've already seen an iterator, ranges. --> <p>既にイテレータとレンジについて見てきましたから、初めにコンシューマについて話しましょう。</p> <!-- ## Consumers --> <h2 id='コンシューマ' class='section-header'><a href='#コンシューマ'>コンシューマ</a></h2> <!-- A *consumer* operates on an iterator, returning some kind of value or values. The most common consumer is `collect()`. This code doesn't quite compile, but it shows the intention: --> <p><em>コンシューマ</em> とはイテレータに作用し、何らかの値を返すものです。最も一般的なコンシューマは <code>collect()</code> です。このコードは全くコンパイルできませんが、意図するところは伝わるでしょう。</p> <span class='rusttest'>fn main() { let one_to_one_hundred = (1..101).collect(); }</span><pre class='rust rust-example-rendered'> <span class='kw'>let</span> <span class='ident'>one_to_one_hundred</span> <span class='op'>=</span> (<span class='number'>1</span>..<span class='number'>101</span>).<span class='ident'>collect</span>();</pre> <!-- As you can see, we call `collect()` on our iterator. `collect()` takes as many values as the iterator will give it, and returns a collection of the results. So why won't this compile? Rust can't determine what type of things you want to collect, and so you need to let it know. Here's the version that does compile: --> <p>ご覧のとおり、ここではイテレータの <code>collect()</code> を呼び出しています。 <code>collect()</code> はイテレータが渡す沢山の値を全て受け取り、その結果をコレクションとして返します。それならなぜこのコードはコンパイルできないのでしょうか?Rustはあなたが集めたい値の型を判断することができないため、あなたが欲しい型を指定する必要があります。以下のバージョンはコンパイルできます。</p> <span class='rusttest'>fn main() { let one_to_one_hundred = (1..101).collect::&lt;Vec&lt;i32&gt;&gt;(); }</span><pre class='rust rust-example-rendered'> <span class='kw'>let</span> <span class='ident'>one_to_one_hundred</span> <span class='op'>=</span> (<span class='number'>1</span>..<span class='number'>101</span>).<span class='ident'>collect</span>::<span class='op'>&lt;</span><span class='ident'>Vec</span><span class='op'>&lt;</span><span class='ident'>i32</span><span class='op'>&gt;&gt;</span>();</pre> <!-- If you remember, the `::<>` syntax allows us to give a type hint, and so we tell it that we want a vector of integers. You don't always need to use the whole type, though. Using a `_` will let you provide a partial hint: --> <p>もしあなたが覚えているなら、 <code>::&lt;&gt;</code> 構文で型ヒント(type hint)を与え、整数型のベクタが欲しいと伝えることができます。かといって常に型をまるごとを書く必要はありません。 <code>_</code> を用いることで部分的に推論してくれます。</p> <span class='rusttest'>fn main() { let one_to_one_hundred = (1..101).collect::&lt;Vec&lt;_&gt;&gt;(); }</span><pre class='rust rust-example-rendered'> <span class='kw'>let</span> <span class='ident'>one_to_one_hundred</span> <span class='op'>=</span> (<span class='number'>1</span>..<span class='number'>101</span>).<span class='ident'>collect</span>::<span class='op'>&lt;</span><span class='ident'>Vec</span><span class='op'>&lt;</span>_<span class='op'>&gt;&gt;</span>();</pre> <!-- This says "Collect into a `Vec<T>`, please, but infer what the `T` is for me." `_` is sometimes called a "type placeholder" for this reason. --> <p>これは「値を <code>Vec&lt;T&gt;</code> の中に集めて下さい、しかし <code>T</code> は私のために推論して下さい」という意味です。このため <code>_</code> は「型プレースホルダ」(type placeholder)と呼ばれることもあります。</p> <!-- `collect()` is the most common consumer, but there are others too. `find()` is one: --> <p><code>collect()</code> は最も一般的なコンシューマですが、他にもあります。 <code>find()</code> はそのひとつです。</p> <span class='rusttest'>fn main() { let greater_than_forty_two = (0..100) .find(|x| *x &gt; 42); match greater_than_forty_two { Some(_) =&gt; println!(&quot;Found a match!&quot;), None =&gt; println!(&quot;No match found :(&quot;), } }</span><pre class='rust rust-example-rendered'> <span class='kw'>let</span> <span class='ident'>greater_than_forty_two</span> <span class='op'>=</span> (<span class='number'>0</span>..<span class='number'>100</span>) .<span class='ident'>find</span>(<span class='op'>|</span><span class='ident'>x</span><span class='op'>|</span> <span class='op'>*</span><span class='ident'>x</span> <span class='op'>&gt;</span> <span class='number'>42</span>); <span class='kw'>match</span> <span class='ident'>greater_than_forty_two</span> { <span class='prelude-val'>Some</span>(_) <span class='op'>=&gt;</span> <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;Found a match!&quot;</span>), <span class='prelude-val'>None</span> <span class='op'>=&gt;</span> <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;No match found :(&quot;</span>), }</pre> <!-- `find` takes a closure, and works on a reference to each element of an iterator. This closure returns `true` if the element is the element we're looking for, and `false` otherwise. `find` returns the first element satisfying the specified predicate. Because we might not find a matching element, `find` returns an `Option` rather than the element itself. --> <p><code>find</code> はクロージャを引数にとり、イテレータの各要素の参照に対して処理を行います。ある要素が私たちの期待するものであれば、このクロージャは <code>true</code> を返し、そうでなければ <code>false</code> を返します。マッチングする要素が無いかもしれないので、 <code>find</code> は要素それ自体ではなく <code>Option</code> を返します。</p> <!-- Another important consumer is `fold`. Here's what it looks like: --> <p>もう一つの重要なコンシューマは <code>fold</code> です。こんな風になります。</p> <span class='rusttest'>fn main() { let sum = (1..4).fold(0, |sum, x| sum + x); }</span><pre class='rust rust-example-rendered'> <span class='kw'>let</span> <span class='ident'>sum</span> <span class='op'>=</span> (<span class='number'>1</span>..<span class='number'>4</span>).<span class='ident'>fold</span>(<span class='number'>0</span>, <span class='op'>|</span><span class='ident'>sum</span>, <span class='ident'>x</span><span class='op'>|</span> <span class='ident'>sum</span> <span class='op'>+</span> <span class='ident'>x</span>);</pre> <!-- `fold()` is a consumer that looks like this: `fold(base, |accumulator, element| ...)`. It takes two arguments: the first is an element called the *base*. The second is a closure that itself takes two arguments: the first is called the *accumulator*, and the second is an *element*. Upon each iteration, the closure is called, and the result is the value of the accumulator on the next iteration. On the first iteration, the base is the value of the accumulator. --> <p><code>fold()</code> は <code>fold(base, |accumulator, element| ...)</code> というシグネチャのコンシューマで、2つの引数を取ります。第1引数は <em>base</em> (基底)と呼ばれます。第2引数は2つ引数を受け取るクロージャです。クロージャの第1引数は <em>accumulator</em> (累積値)と呼ばれており、第2引数は <em>element</em> (要素)です。各反復毎にクロージャが呼び出され、その結果が次の反復のaccumulatorの値となります。反復処理の開始時は、baseがaccumulatorの値となります。</p> <!-- Okay, that's a bit confusing. Let's examine the values of all of these things in this iterator: --> <p>ええ、ちょっとややこしいですね。ではこのイテレータを以下の値で試してみましょう。</p> <table> <thead> <tr> <th>base</th> <th>accumulator</th> <th>element</th> <th>クロージャの結果</th> </tr> </thead> <tbody> <tr> <td>0</td> <td>0</td> <td>1</td> <td>1</td> </tr> <tr> <td>0</td> <td>1</td> <td>2</td> <td>3</td> </tr> <tr> <td>0</td> <td>3</td> <td>3</td> <td>6</td> </tr> </tbody> </table> <!-- We called `fold()` with these arguments: --> <p>これらの引数で <code>fold()</code> を呼び出してみました。</p> <span class='rusttest'>fn main() { (1..4) .fold(0, |sum, x| sum + x); }</span><pre class='rust rust-example-rendered'> .<span class='ident'>fold</span>(<span class='number'>0</span>, <span class='op'>|</span><span class='ident'>sum</span>, <span class='ident'>x</span><span class='op'>|</span> <span class='ident'>sum</span> <span class='op'>+</span> <span class='ident'>x</span>);</pre> <!-- So, `0` is our base, `sum` is our accumulator, and `x` is our element. On the first iteration, we set `sum` to `0`, and `x` is the first element of `nums`, `1`. We then add `sum` and `x`, which gives us `0 + 1 = 1`. On the second iteration, that value becomes our accumulator, `sum`, and the element is the second element of the array, `2`. `1 + 2 = 3`, and so that becomes the value of the accumulator for the last iteration. On that iteration, `x` is the last element, `3`, and `3 + 3 = 6`, which is our final result for our sum. `1 + 2 + 3 = 6`, and that's the result we got. --> <p>というわけで、 <code>0</code> がbaseで、 <code>sum</code> がaccumulatorで、xがelementです。1度目の反復では、私たちはsumに0をセットし、 <code>nums</code> の1つ目の要素 <code>1</code> が <code>x</code> になります。その後 <code>sum</code> と <code>x</code> を足し、 <code>0 + 1 = 1</code> を計算します。2度目の反復では前回の <code>sum</code> がaccumulatorになり、elementは値の列の2番目の要素 <code>2</code> になります。 <code>1 + 2 = 3</code> の結果は最後の反復処理におけるaccumulatorの値になります。最後の反復処理において、 <code>x</code> は最後の要素 <code>3</code> であり、 <code>3 + 3 = 6</code> が最終的な結果となります。 <code>1 + 2 + 3 = 6</code> 、これが得られる結果となります。</p> <!-- Whew. `fold` can be a bit strange the first few times you see it, but once it clicks, you can use it all over the place. Any time you have a list of things, and you want a single result, `fold` is appropriate. --> <p>ふぅ、ようやく説明し終わりました。 <code>fold</code> は初めのうちこそ少し奇妙に見えるかもしれませんが、一度理解すればあらゆる場面で使えるでしょう。何らかのリストを持っていて、そこから1つの結果を求めたい時ならいつでも、 <code>fold</code> は適切な処理です。</p> <!-- Consumers are important due to one additional property of iterators we haven't talked about yet: laziness. Let's talk some more about iterators, and you'll see why consumers matter. --> <p>イテレータにはまだ話していないもう1つの性質、遅延性があり、コンシューマはそれに関連して重要な役割を担っています。それではもっと詳しくイテレータについて話していきましょう、そうすればなぜコンシューマが重要なのか理解できるはずです。</p> <!-- ## Iterators --> <h2 id='イテレータ' class='section-header'><a href='#イテレータ'>イテレータ</a></h2> <!-- As we've said before, an iterator is something that we can call the `.next()` method on repeatedly, and it gives us a sequence of things. Because you need to call the method, this means that iterators can be *lazy* and not generate all of the values upfront. This code, for example, does not actually generate the numbers `1-99`, instead creating a value that merely represents the sequence: --> <p>前に言ったように、イテレータは <code>.next()</code> メソッドを繰り返し呼び出すことができ、その都度順番に値を返すものです。メソッドを繰り返し呼ぶ必要があることから、イテレータは <em>lazy</em> であり、前もって全ての値を生成できないことがわかります。このコードでは、例えば <code>1-99</code> の値は実際には生成されておらず、代わりにただシーケンスを表すだけの値を生成しています。</p> <span class='rusttest'>fn main() { let nums = 1..100; }</span><pre class='rust rust-example-rendered'> <span class='kw'>let</span> <span class='ident'>nums</span> <span class='op'>=</span> <span class='number'>1</span>..<span class='number'>100</span>;</pre> <!-- Since we didn't do anything with the range, it didn't generate the sequence. Let's add the consumer: --> <p>私たちはレンジを何にも使っていないため、値を生成しません。コンシューマを追加してみましょう。</p> <span class='rusttest'>fn main() { let nums = (1..100).collect::&lt;Vec&lt;i32&gt;&gt;(); }</span><pre class='rust rust-example-rendered'> <span class='kw'>let</span> <span class='ident'>nums</span> <span class='op'>=</span> (<span class='number'>1</span>..<span class='number'>100</span>).<span class='ident'>collect</span>::<span class='op'>&lt;</span><span class='ident'>Vec</span><span class='op'>&lt;</span><span class='ident'>i32</span><span class='op'>&gt;&gt;</span>();</pre> <!-- Now, `collect()` will require that the range gives it some numbers, and so it will do the work of generating the sequence. --> <p><code>collect()</code> は幾つかの数値を渡してくれるレンジを要求し、シーケンスを生成する作業を行います。</p> <!-- Ranges are one of two basic iterators that you'll see. The other is `iter()`. `iter()` can turn a vector into a simple iterator that gives you each element in turn: --> <p>レンジは基本的な2つのイテレータのうちの1つです。もう片方は <code>iter()</code> です。 <code>iter()</code> はベクタを順に各要素を渡すシンプルなイテレータへ変換できます。</p> <span class='rusttest'>fn main() { let nums = vec![1, 2, 3]; for num in nums.iter() { println!(&quot;{}&quot;, num); } }</span><pre class='rust rust-example-rendered'> <span class='kw'>let</span> <span class='ident'>nums</span> <span class='op'>=</span> <span class='macro'>vec</span><span class='macro'>!</span>[<span class='number'>1</span>, <span class='number'>2</span>, <span class='number'>3</span>]; <span class='kw'>for</span> <span class='ident'>num</span> <span class='kw'>in</span> <span class='ident'>nums</span>.<span class='ident'>iter</span>() { <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;{}&quot;</span>, <span class='ident'>num</span>); }</pre> <!-- These two basic iterators should serve you well. There are some more advanced iterators, including ones that are infinite. --> <p>これら2つの基本的なイテレータはあなたの役に立つはずです。無限を扱えるものも含め、より応用的なイテレータも幾つか用意されています。</p> <!-- That's enough about iterators. Iterator adaptors are the last concept we need to talk about with regards to iterators. Let's get to it! --> <p>これでイテレータについては十分でしょう。私たちがイテレータに関して最後に話しておくべき概念がイテレータアダプタです。それでは説明しましょう!</p> <!-- ## Iterator adaptors --> <h2 id='イテレータアダプタ' class='section-header'><a href='#イテレータアダプタ'>イテレータアダプタ</a></h2> <!-- *Iterator adaptors* take an iterator and modify it somehow, producing a new iterator. The simplest one is called `map`: --> <p><em>イテレータアダプタ</em> はイテレータを受け取って何らかの方法で加工し、新たなイテレータを生成します。 <code>map</code> はその中でも最も単純なものです。</p> <span class='rusttest'>fn main() { (1..100).map(|x| x + 1); }</span><pre class='rust rust-example-rendered'> (<span class='number'>1</span>..<span class='number'>100</span>).<span class='ident'>map</span>(<span class='op'>|</span><span class='ident'>x</span><span class='op'>|</span> <span class='ident'>x</span> <span class='op'>+</span> <span class='number'>1</span>);</pre> <!-- `map` is called upon another iterator, and produces a new iterator where each element reference has the closure it's been given as an argument called on it. So this would give us the numbers from `2-100`. Well, almost! If you compile the example, you'll get a warning: --> <p><code>map</code> は別のイテレータについて呼び出され、各要素の参照をクロージャに引数として与えた結果を新しいイテレータとして生成します。つまりこのコードは私たちに <code>2-100</code> の値を返してくれるでしょう。えーっと、厳密には少し違います!もしこの例をコンパイルすると、こんな警告が出るはずです。</p> <pre><code class="language-text">warning: unused result which must be used: iterator adaptors are lazy and do nothing unless consumed, #[warn(unused_must_use)] on by default (1..100).map(|x| x + 1); ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </code></pre> <!-- Laziness strikes again! That closure will never execute. This example doesn't print any numbers: --> <p>また遅延性にぶつかりました!このクロージャは実行されませんね。例えば以下の例は何の数字も出力されません。</p> <span class='rusttest'>fn main() { (1..100).map(|x| println!(&quot;{}&quot;, x)); }</span><pre class='rust rust-example-rendered'> (<span class='number'>1</span>..<span class='number'>100</span>).<span class='ident'>map</span>(<span class='op'>|</span><span class='ident'>x</span><span class='op'>|</span> <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;{}&quot;</span>, <span class='ident'>x</span>));</pre> <!-- If you are trying to execute a closure on an iterator for its side effects, use `for` instead. --> <p>もし副作用のためにイテレータに対してクロージャの実行を試みるのであれば、代わりに <code>for</code> を使いましょう。</p> <!-- There are tons of interesting iterator adaptors. `take(n)` will return an iterator over the next `n` elements of the original iterator. Let's try it out with an infinite iterator: --> <p>他にも面白いイテレータアダプタは山ほどあります。 <code>take(n)</code> は元のイテレータの <code>n</code> 要素目までを実行するイテレータを返します。先程言及していた無限を扱えるイテレータで試してみましょう。</p> <span class='rusttest'>fn main() { for i in (1..).take(5) { println!(&quot;{}&quot;, i); } }</span><pre class='rust rust-example-rendered'> <span class='kw'>for</span> <span class='ident'>i</span> <span class='kw'>in</span> (<span class='number'>1</span>..).<span class='ident'>take</span>(<span class='number'>5</span>) { <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;{}&quot;</span>, <span class='ident'>i</span>); }</pre> <!-- This will print --> <p>これの出力は、</p> <pre><code class="language-text">1 2 3 4 5 </code></pre> <!-- `filter()` is an adapter that takes a closure as an argument. This closure returns `true` or `false`. The new iterator `filter()` produces only the elements that the closure returns `true` for: --> <p><code>filter()</code> は引数としてクロージャをとるアダプタです。このクロージャは <code>true</code> か <code>false</code> を返します。 <code>filter()</code> が生成する新たなイテレータはそのクロージャが <code>true</code> を返した要素のみとなります。</p> <span class='rusttest'>fn main() { for i in (1..100).filter(|&amp;x| x % 2 == 0) { println!(&quot;{}&quot;, i); } }</span><pre class='rust rust-example-rendered'> <span class='kw'>for</span> <span class='ident'>i</span> <span class='kw'>in</span> (<span class='number'>1</span>..<span class='number'>100</span>).<span class='ident'>filter</span>(<span class='op'>|</span><span class='kw-2'>&amp;</span><span class='ident'>x</span><span class='op'>|</span> <span class='ident'>x</span> <span class='op'>%</span> <span class='number'>2</span> <span class='op'>==</span> <span class='number'>0</span>) { <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;{}&quot;</span>, <span class='ident'>i</span>); }</pre> <!-- This will print all of the even numbers between one and a hundred. (Note that, unlike `map`, the closure passed to `filter` is passed a reference to the element instead of the element itself. The filter predicate here uses the `&x` pattern to extract the integer. The filter closure is passed a reference because it returns `true` or `false` instead of the element, so the `filter` implementation must retain ownership to put the elements into the newly constructed iterator.) --> <p>これは1から100の間の偶数を全て出力します。 (<code>map</code> と違って、<code>filter</code> に渡されたクロージャには要素そのものではなく要素への参照が渡されます。 フィルタする述語は <code>&amp;x</code> パターンを使って整数を取り出しています。 フィルタするクロージャは要素ではなく <code>true</code> 又は <code>false</code> を返すので、 <code>filter</code> の実装は返り値のイテレータに所有権を渡すために要素への所有権を保持しておかないとならないのです。)</p> <blockquote> <p>訳注: クロージャで用いられている <code>&amp;x</code> パターンは <a href="patterns.html">パターン</a> の章では紹介されていません。簡単に解説すると、何らかの参照 <code>&amp;T</code> から <strong>内容のみを取り出してコピー</strong> するのが <code>&amp;x</code> パターンです。参照をそのまま受け取る <code>ref x</code> パターンとは異なりますので注意して下さい。</p> </blockquote> <!-- You can chain all three things together: start with an iterator, adapt it a few times, and then consume the result. Check it out: --> <p>あなたはここまでに説明された3つの概念を全て繋げることができます。イテレータから始まり、アダプタを幾つか繋ぎ、結果を消費するといった感じです。これを見て下さい。</p> <span class='rusttest'>fn main() { (1..) .filter(|&amp;x| x % 2 == 0) .filter(|&amp;x| x % 3 == 0) .take(5) .collect::&lt;Vec&lt;i32&gt;&gt;(); }</span><pre class='rust rust-example-rendered'> (<span class='number'>1</span>..) .<span class='ident'>filter</span>(<span class='op'>|</span><span class='kw-2'>&amp;</span><span class='ident'>x</span><span class='op'>|</span> <span class='ident'>x</span> <span class='op'>%</span> <span class='number'>2</span> <span class='op'>==</span> <span class='number'>0</span>) .<span class='ident'>filter</span>(<span class='op'>|</span><span class='kw-2'>&amp;</span><span class='ident'>x</span><span class='op'>|</span> <span class='ident'>x</span> <span class='op'>%</span> <span class='number'>3</span> <span class='op'>==</span> <span class='number'>0</span>) .<span class='ident'>take</span>(<span class='number'>5</span>) .<span class='ident'>collect</span>::<span class='op'>&lt;</span><span class='ident'>Vec</span><span class='op'>&lt;</span><span class='ident'>i32</span><span class='op'>&gt;&gt;</span>();</pre> <!-- This will give you a vector containing `6`, `12`, `18`, `24`, and `30`. --> <p>これは <code>6, 12, 18, 24,</code> 、そして <code>30</code> が入ったベクタがあなたに渡されます。</p> <!-- This is just a small taste of what iterators, iterator adaptors, and consumers can help you with. There are a number of really useful iterators, and you can write your own as well. Iterators provide a safe, efficient way to manipulate all kinds of lists. They're a little unusual at first, but if you play with them, you'll get hooked. For a full list of the different iterators and consumers, check out the [iterator module documentation](../std/iter/index.html). --> <p>イテレータ、イテレータアダプタ、そしてコンシューマがあなたの助けになることをほんの少しだけ体験できました。本当に便利なイテレータが幾つも用意されていますし、あなたがイテレータを自作することもできます。イテレータは全ての種類のリストに対し効率的な処理方法と安全性を提供します。これらは初めこそ珍しいかもしれませんが、もし使えばあなたは夢中になることでしょう。全てのイテレータとコンシューマのリストは <a href="../std/iter/index.html">イテレータモジュールのドキュメンテーション</a> を参照して下さい。</p> <script type="text/javascript"> window.playgroundUrl = "https://play.rust-lang.org"; </script> <script src='rustbook.js'></script> <script src='playpen.js'></script> </div></div> </body> </html> <|start_filename|>docs/1.6/book/macros.html<|end_filename|> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="generator" content="rustdoc"> <title>マクロ</title> <link rel="stylesheet" type="text/css" href="rustbook.css"> <meta name="robots" content="noindex"> </head> <body class="rustdoc"> <!--[if lte IE 8]> <div class="warning"> This old browser is unsupported and will most likely display funky things. </div> <![endif]--> <div id="nav"> <button id="toggle-nav"> <span class="sr-only">Toggle navigation</span> <span class="bar"></span> <span class="bar"></span> <span class="bar"></span> </button> </div> <div id='toc' class='mobile-hidden'> <ul class='chapter'> <li><a href='README.html'><b>1.</b> Introduction</a> </li> <li><a href='getting-started.html'><b>2.</b> はじめる</a> </li> <li><a href='learn-rust.html'><b>3.</b> Rustを学ぶ</a> <ul class='section'> <li><a href='guessing-game.html'><b>3.1.</b> 数当てゲーム</a> </li> <li><a href='dining-philosophers.html'><b>3.2.</b> 食事する哲学者</a> </li> <li><a href='rust-inside-other-languages.html'><b>3.3.</b> 他言語と共存する</a> </li> </ul> </li> <li><a href='syntax-and-semantics.html'><b>4.</b> シンタックスとセマンティクス</a> <ul class='section'> <li><a href='variable-bindings.html'><b>4.1.</b> 変数束縛</a> </li> <li><a href='functions.html'><b>4.2.</b> 関数</a> </li> <li><a href='primitive-types.html'><b>4.3.</b> プリミティブ型</a> </li> <li><a href='comments.html'><b>4.4.</b> コメント</a> </li> <li><a href='if.html'><b>4.5.</b> if</a> </li> <li><a href='loops.html'><b>4.6.</b> ループ</a> </li> <li><a href='ownership.html'><b>4.7.</b> 所有権</a> </li> <li><a href='references-and-borrowing.html'><b>4.8.</b> 参照と借用</a> </li> <li><a href='lifetimes.html'><b>4.9.</b> ライフタイム</a> </li> <li><a href='mutability.html'><b>4.10.</b> ミュータビリティ</a> </li> <li><a href='structs.html'><b>4.11.</b> 構造体</a> </li> <li><a href='enums.html'><b>4.12.</b> 列挙型</a> </li> <li><a href='match.html'><b>4.13.</b> マッチ</a> </li> <li><a href='patterns.html'><b>4.14.</b> パターン</a> </li> <li><a href='method-syntax.html'><b>4.15.</b> メソッド構文</a> </li> <li><a href='vectors.html'><b>4.16.</b> ベクタ</a> </li> <li><a href='strings.html'><b>4.17.</b> 文字列</a> </li> <li><a href='generics.html'><b>4.18.</b> ジェネリクス</a> </li> <li><a href='traits.html'><b>4.19.</b> トレイト</a> </li> <li><a href='drop.html'><b>4.20.</b> Drop</a> </li> <li><a href='if-let.html'><b>4.21.</b> if let</a> </li> <li><a href='trait-objects.html'><b>4.22.</b> トレイトオブジェクト</a> </li> <li><a href='closures.html'><b>4.23.</b> クロージャ</a> </li> <li><a href='ufcs.html'><b>4.24.</b> 共通の関数呼出構文</a> </li> <li><a href='crates-and-modules.html'><b>4.25.</b> クレートとモジュール</a> </li> <li><a href='const-and-static.html'><b>4.26.</b> `const` と `static`</a> </li> <li><a href='attributes.html'><b>4.27.</b> アトリビュート</a> </li> <li><a href='type-aliases.html'><b>4.28.</b> `type` エイリアス</a> </li> <li><a href='casting-between-types.html'><b>4.29.</b> 型間のキャスト</a> </li> <li><a href='associated-types.html'><b>4.30.</b> 関連型</a> </li> <li><a href='unsized-types.html'><b>4.31.</b> サイズ不定型</a> </li> <li><a href='operators-and-overloading.html'><b>4.32.</b> 演算子とオーバーロード</a> </li> <li><a href='deref-coercions.html'><b>4.33.</b> Derefによる型強制</a> </li> <li><a class='active' href='macros.html'><b>4.34.</b> マクロ</a> </li> <li><a href='raw-pointers.html'><b>4.35.</b> 生ポインタ</a> </li> <li><a href='unsafe.html'><b>4.36.</b> `unsafe`</a> </li> </ul> </li> <li><a href='effective-rust.html'><b>5.</b> Effective Rust</a> <ul class='section'> <li><a href='the-stack-and-the-heap.html'><b>5.1.</b> スタックとヒープ</a> </li> <li><a href='testing.html'><b>5.2.</b> テスト</a> </li> <li><a href='conditional-compilation.html'><b>5.3.</b> 条件付きコンパイル</a> </li> <li><a href='documentation.html'><b>5.4.</b> ドキュメント</a> </li> <li><a href='iterators.html'><b>5.5.</b> イテレータ</a> </li> <li><a href='concurrency.html'><b>5.6.</b> 並行性</a> </li> <li><a href='error-handling.html'><b>5.7.</b> エラーハンドリング</a> </li> <li><a href='choosing-your-guarantees.html'><b>5.8.</b> 保証を選ぶ</a> </li> <li><a href='ffi.html'><b>5.9.</b> 他言語関数インターフェース</a> </li> <li><a href='borrow-and-asref.html'><b>5.10.</b> BorrowとAsRef</a> </li> <li><a href='release-channels.html'><b>5.11.</b> リリースチャネル</a> </li> <li><a href='using-rust-without-the-standard-library.html'><b>5.12.</b> 標準ライブラリ無しでRustを使う</a> </li> </ul> </li> <li><a href='nightly-rust.html'><b>6.</b> Nightly Rust</a> <ul class='section'> <li><a href='compiler-plugins.html'><b>6.1.</b> コンパイラプラグイン</a> </li> <li><a href='inline-assembly.html'><b>6.2.</b> インラインアセンブリ</a> </li> <li><a href='no-stdlib.html'><b>6.3.</b> No stdlib</a> </li> <li><a href='intrinsics.html'><b>6.4.</b> Intrinsic</a> </li> <li><a href='lang-items.html'><b>6.5.</b> 言語アイテム</a> </li> <li><a href='advanced-linking.html'><b>6.6.</b> 高度なリンキング</a> </li> <li><a href='benchmark-tests.html'><b>6.7.</b> ベンチマークテスト</a> </li> <li><a href='box-syntax-and-patterns.html'><b>6.8.</b> Box構文とパターン</a> </li> <li><a href='slice-patterns.html'><b>6.9.</b> スライスパターン</a> </li> <li><a href='associated-constants.html'><b>6.10.</b> 関連定数</a> </li> <li><a href='custom-allocators.html'><b>6.11.</b> カスタムアロケータ</a> </li> </ul> </li> <li><a href='glossary.html'><b>7.</b> 用語集</a> </li> <li><a href='syntax-index.html'><b>8.</b> 構文の索引</a> </li> <li><a href='bibliography.html'><b>9.</b> 関係書目</a> </li> </ul> </div> <div id='page-wrapper'> <div id='page'> <blockquote class="header-caveat"> <p> <strong>注意: <a href="https://doc.rust-jp.rs/book-ja/">最新版のドキュメントをご覧ください。</a></strong>この第1版ドキュメントは古くなっており、最新情報が反映されていません。リンク先のドキュメントが現在の Rust の最新のドキュメントです。 </p> </blockquote> <h1 class="title">マクロ</h1> <!-- % Macros --> <!-- By now you’ve learned about many of the tools Rust provides for abstracting and --> <!-- reusing code. These units of code reuse have a rich semantic structure. For --> <!-- example, functions have a type signature, type parameters have trait bounds, --> <!-- and overloaded functions must belong to a particular trait. --> <p>Rustが提供している多くのコードの再利用や抽象化に利用できるツールを学びました。 それらのコードの再利用のユニットは豊富な意味論的構造を持っています。 例えば、関数は型シグネチャ、型パラメータはトレイト境界、オーバーロードされた関数はトレイトに所属していなければならない等です。</p> <!-- This structure means that Rust’s core abstractions have powerful compile-time --> <!-- correctness checking. But this comes at the price of reduced flexibility. If --> <!-- you visually identify a pattern of repeated code, you may find it’s difficult --> <!-- or cumbersome to express that pattern as a generic function, a trait, or --> <!-- anything else within Rust’s semantics. --> <p>このような構造はRustのコアの抽象化が強力なコンパイル時の正確性のチェックを持っているという事を意味しています。 しかし、それは柔軟性の減少というコストを払っています。 もし、視覚的に繰り返しているコードのパターンを発見した時に、 それらをジェネリックな関数やトレイトや、他のRustのセマンティクスとして表現することが困難であると気がつくかもしれません。</p> <!-- Macros allow us to abstract at a syntactic level. A macro invocation is --> <!-- shorthand for an "expanded" syntactic form. This expansion happens early in --> <!-- compilation, before any static checking. As a result, macros can capture many --> <!-- patterns of code reuse that Rust’s core abstractions cannot. --> <p>マクロは構文レベルでの抽象化をすることを可能にします。 マクロ呼出は「展開された」構文への短縮表現です。 展開はコンパイルの初期段階、すべての静的なチェックが実行される前に行われます。 その結果として、マクロはRustのコアの抽象化では不可能な多くのパターンのコードの再利用を可能としています。</p> <!-- The drawback is that macro-based code can be harder to understand, because --> <!-- fewer of the built-in rules apply. Like an ordinary function, a well-behaved --> <!-- macro can be used without understanding its implementation. However, it can be --> <!-- difficult to design a well-behaved macro! Additionally, compiler errors in --> <!-- macro code are harder to interpret, because they describe problems in the --> <!-- expanded code, not the source-level form that developers use. --> <p>マクロベースのコードの欠点は、組み込みルールの少なさに由来するそのコードの理解のしづらさです。 普通の関数と同じように、良いマクロはその実装について理解しなくても使うことができます。 しかしながら、そのような良いマクロを設計するのは困難です! 加えて、マクロコード中のコンパイルエラーは開発者が書いたソースレベルではなく、 展開した結果のコードの中の問題について書かれているために、とても理解しづらいです。</p> <!-- These drawbacks make macros something of a "feature of last resort". That’s not --> <!-- to say that macros are bad; they are part of Rust because sometimes they’re --> <!-- needed for truly concise, well-abstracted code. Just keep this tradeoff in --> <!-- mind. --> <p>これらの欠点はマクロを「最終手段となる機能」にしています。 これは、マクロが良くないものだと言っているわけではありません、マクロはRustの一部です、 なぜならばマクロを使うことで簡潔になったり、適切な抽象化が可能になる場面がしばしば存在するからです。 ただ、このトレードオフを頭に入れておいて欲しいのです。</p> <!-- # Defining a macro --> <h1 id='マクロを定義する' class='section-header'><a href='#マクロを定義する'>マクロを定義する</a></h1> <!-- You may have seen the `vec!` macro, used to initialize a [vector][vector] with --> <!-- any number of elements. --> <p><code>vec!</code> マクロを見たことがあるでしょう、 <a href="vectors.html">ベクタ</a> を任意の要素で初期化するために使われていました。</p> <span class='rusttest'>fn main() { let x: Vec&lt;u32&gt; = vec![1, 2, 3]; assert_eq!(x, [1, 2, 3]); }</span><pre class='rust rust-example-rendered'> <span class='kw'>let</span> <span class='ident'>x</span>: <span class='ident'>Vec</span><span class='op'>&lt;</span><span class='ident'>u32</span><span class='op'>&gt;</span> <span class='op'>=</span> <span class='macro'>vec</span><span class='macro'>!</span>[<span class='number'>1</span>, <span class='number'>2</span>, <span class='number'>3</span>];</pre> <!-- This can’t be an ordinary function, because it takes any number of arguments. --> <!-- But we can imagine it as syntactic shorthand for --> <p><code>vec!</code> は通常の関数として定義することはできません、なぜなら <code>vec!</code> は任意の個数の引数を取るためです。 しかし、 <code>vec!</code> を以下のコードの構文上の短縮形であると考えることができます:</p> <span class='rusttest'>fn main() { let x: Vec&lt;u32&gt; = { let mut temp_vec = Vec::new(); temp_vec.push(1); temp_vec.push(2); temp_vec.push(3); temp_vec }; assert_eq!(x, [1, 2, 3]); }</span><pre class='rust rust-example-rendered'> <span class='kw'>let</span> <span class='ident'>x</span>: <span class='ident'>Vec</span><span class='op'>&lt;</span><span class='ident'>u32</span><span class='op'>&gt;</span> <span class='op'>=</span> { <span class='kw'>let</span> <span class='kw-2'>mut</span> <span class='ident'>temp_vec</span> <span class='op'>=</span> <span class='ident'>Vec</span>::<span class='ident'>new</span>(); <span class='ident'>temp_vec</span>.<span class='ident'>push</span>(<span class='number'>1</span>); <span class='ident'>temp_vec</span>.<span class='ident'>push</span>(<span class='number'>2</span>); <span class='ident'>temp_vec</span>.<span class='ident'>push</span>(<span class='number'>3</span>); <span class='ident'>temp_vec</span> };</pre> <!-- We can implement this shorthand, using a macro: [^actual] --> <p>このような短縮形をマクロ: <sup id="fnref1"><a href="#fn1" rel="footnote">1</a></sup> を用いることで実装することができます</p> <!-- [^actual]: The actual definition of `vec!` in libcollections differs from the --> <!-- one presented here, for reasons of efficiency and reusability. --> <span class='rusttest'>macro_rules! vec { ( $( $x:expr ),* ) =&gt; { { let mut temp_vec = Vec::new(); $( temp_vec.push($x); )* temp_vec } }; } fn main() { assert_eq!(vec![1,2,3], [1, 2, 3]); } </span><pre class='rust rust-example-rendered'> <span class='macro'>macro_rules</span><span class='macro'>!</span> <span class='ident'>vec</span> { ( $( <span class='macro-nonterminal'>$</span><span class='macro-nonterminal'>x</span>:<span class='ident'>expr</span> ),<span class='op'>*</span> ) <span class='op'>=&gt;</span> { { <span class='kw'>let</span> <span class='kw-2'>mut</span> <span class='ident'>temp_vec</span> <span class='op'>=</span> <span class='ident'>Vec</span>::<span class='ident'>new</span>(); $( <span class='ident'>temp_vec</span>.<span class='ident'>push</span>(<span class='macro-nonterminal'>$</span><span class='macro-nonterminal'>x</span>); )<span class='op'>*</span> <span class='ident'>temp_vec</span> } }; }</pre> <!-- Whoa, that’s a lot of new syntax! Let’s break it down. --> <p>ワオ!たくさんの新しい構文が現れました!細かく見ていきましょう。</p> <span class='rusttest'>fn main() { macro_rules! vec { ... } }</span><pre class='rust rust-example-rendered'> <span class='macro'>macro_rules</span><span class='macro'>!</span> <span class='ident'>vec</span> { ... }</pre> <!-- This says we’re defining a macro named `vec`, much as `fn vec` would define a --> <!-- function named `vec`. In prose, we informally write a macro’s name with an --> <!-- exclamation point, e.g. `vec!`. The exclamation point is part of the invocation --> <!-- syntax and serves to distinguish a macro from an ordinary function. --> <p>これは、新しいマクロ <code>vec</code> を定義していることを意味しています、<code>vec</code> という関数を定義するときに <code>fn vec</code> と書くのと同じです。 非公式ですが、実際には、マクロ名をエクスクラメーションマーク(!) と共に記述します、例えば: <code>vec!</code> のように示します。 エクスクラメーションマークはマクロ呼び出しの構文の一部で、マクロと通常の関数の区別をつけるためのものです。</p> <!-- ## Matching --> <h2 id='マッチング' class='section-header'><a href='#マッチング'>マッチング</a></h2> <!-- The macro is defined through a series of rules, which are pattern-matching --> <!-- cases. Above, we had --> <p>マクロは、幾つかのパターンマッチのケースを利用したルールに従って定義されています、 上のコード中では、以下の様なパターンが見られました:</p> <span class='rusttest'>fn main() { ( $( $x:expr ),* ) =&gt; { ... }; }</span><pre class='rust rust-example-rendered'> ( $( <span class='macro-nonterminal'>$</span><span class='macro-nonterminal'>x</span>:<span class='ident'>expr</span> ),<span class='op'>*</span> ) <span class='op'>=&gt;</span> { ... };</pre> <!-- This is like a `match` expression arm, but the matching happens on Rust syntax --> <!-- trees, at compile time. The semicolon is optional on the last (here, only) --> <!-- case. The "pattern" on the left-hand side of `=>` is known as a ‘matcher’. --> <!-- These have [their own little grammar] within the language. --> <p>これは <code>match</code> 式の腕に似ていますが、Rustの構文木に対してコンパイル時にマッチします。 セミコロンはケースの末尾でだけ使うことのでき、省略可能です。 <code>=&gt;</code> の左辺にある「パターン」は「マッチャ」として知られています。 マッチャは <a href="../reference.html#macros">小さなマッチャ独自の構文</a> を持っています。</p> <!-- The matcher `$x:expr` will match any Rust expression, binding that syntax tree --> <!-- to the ‘metavariable’ `$x`. The identifier `expr` is a ‘fragment specifier’; --> <!-- the full possibilities are enumerated later in this chapter. --> <!-- Surrounding the matcher with `$(...),*` will match zero or more expressions, --> <!-- separated by commas. --> <p>マッチャ <code>$x:expr</code> は任意のRustの式にマッチし、マッチした構文木を「メタ変数」 <code>$x</code> に束縛します。 識別子 <code>expr</code> は「フラグメント指定子」です。全てのフラグメント指定子の一覧はこの章で後ほど紹介します。 マッチャを <code>$(...),*</code> で囲むと0個以上のコンマで句切られた式にマッチします。</p> <!-- Aside from the special matcher syntax, any Rust tokens that appear in a matcher --> <!-- must match exactly. For example, --> <p>特別なマッチャ構文は別にして、マッチャ中に登場するその他の任意のトークンはそれ自身に正確にマッチする必要があります。 例えば:</p> <span class='rusttest'>macro_rules! foo { (x =&gt; $e:expr) =&gt; (println!(&quot;mode X: {}&quot;, $e)); (y =&gt; $e:expr) =&gt; (println!(&quot;mode Y: {}&quot;, $e)); } fn main() { foo!(y =&gt; 3); } </span><pre class='rust rust-example-rendered'> <span class='macro'>macro_rules</span><span class='macro'>!</span> <span class='ident'>foo</span> { (<span class='ident'>x</span> <span class='op'>=&gt;</span> <span class='macro-nonterminal'>$</span><span class='macro-nonterminal'>e</span>:<span class='ident'>expr</span>) <span class='op'>=&gt;</span> (<span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;mode X: {}&quot;</span>, <span class='macro-nonterminal'>$</span><span class='macro-nonterminal'>e</span>)); (<span class='ident'>y</span> <span class='op'>=&gt;</span> <span class='macro-nonterminal'>$</span><span class='macro-nonterminal'>e</span>:<span class='ident'>expr</span>) <span class='op'>=&gt;</span> (<span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;mode Y: {}&quot;</span>, <span class='macro-nonterminal'>$</span><span class='macro-nonterminal'>e</span>)); } <span class='kw'>fn</span> <span class='ident'>main</span>() { <span class='macro'>foo</span><span class='macro'>!</span>(<span class='ident'>y</span> <span class='op'>=&gt;</span> <span class='number'>3</span>); }</pre> <!-- will print --> <p>上のコードは以下の様な出力をします</p> <pre><code class="language-text">mode Y: 3 </code></pre> <!-- With --> <p>また、以下のようなコードでは</p> <span class='rusttest'>fn main() { foo!(z =&gt; 3); }</span><pre class='rust rust-example-rendered'> <span class='macro'>foo</span><span class='macro'>!</span>(<span class='ident'>z</span> <span class='op'>=&gt;</span> <span class='number'>3</span>);</pre> <!-- we get the compiler error --> <p>以下の様なコンパイルエラーが発生します</p> <pre><code class="language-text">error: no rules expected the token `z` </code></pre> <!-- ## Expansion --> <h2 id='展開' class='section-header'><a href='#展開'>展開</a></h2> <!-- The right-hand side of a macro rule is ordinary Rust syntax, for the most part. --> <!-- But we can splice in bits of syntax captured by the matcher. From the original --> <!-- example: --> <p>マクロルールの右辺は大部分が通常のRustの構文です。 しかし、マッチャによってキャプチャされた構文を繋げる事ができます。 最初に示した <code>vec!</code> の例を見てみましょう:</p> <span class='rusttest'>fn main() { $( temp_vec.push($x); )* }</span><pre class='rust rust-example-rendered'> $( <span class='ident'>temp_vec</span>.<span class='ident'>push</span>(<span class='macro-nonterminal'>$</span><span class='macro-nonterminal'>x</span>); )<span class='op'>*</span></pre> <!-- Each matched expression `$x` will produce a single `push` statement in the --> <!-- macro expansion. The repetition in the expansion proceeds in "lockstep" with --> <!-- repetition in the matcher (more on this in a moment). --> <p><code>$x</code> にマッチしたそれぞれの式はマクロ展開中に <code>push</code> 文を生成します。 マクロ展開中の繰り返しはマッチャ中の繰り返しと足並みを揃えて実行されます(これについてはもう少し説明します)。</p> <!-- Because `$x` was already declared as matching an expression, we don’t repeat --> <!-- `:expr` on the right-hand side. Also, we don’t include a separating comma as --> <!-- part of the repetition operator. Instead, we have a terminating semicolon --> <!-- within the repeated block. --> <p><code>$x</code> が既に式にマッチすると宣言されているために、<code>=&gt;</code> の右辺では <code>:expr</code> を繰り返しません。 また、区切りのコンマは繰り返し演算子の一部には含めません。 そのかわり、繰り返しブロックをセミコロンを用いて閉じます。</p> <!-- Another detail: the `vec!` macro has *two* pairs of braces on the right-hand --> <!-- side. They are often combined like so: --> <p>そのほかの詳細としては: <code>vec!</code> マクロは <em>2つ</em> の括弧のペアを右辺に含みます。 それらの括弧はよく以下のように合せられます:</p> <span class='rusttest'>fn main() { macro_rules! foo { () =&gt; {{ ... }} } }</span><pre class='rust rust-example-rendered'> <span class='macro'>macro_rules</span><span class='macro'>!</span> <span class='ident'>foo</span> { () <span class='op'>=&gt;</span> {{ ... }} }</pre> <!-- The outer braces are part of the syntax of `macro_rules!`. In fact, you can use --> <!-- `()` or `[]` instead. They simply delimit the right-hand side as a whole. --> <p>外側の括弧は <code>macro_rules!</code> 構文の一部です。事実、<code>()</code> や <code>[]</code> をかわりに使うことができます。 括弧は単純に右辺を区切るために利用されています。</p> <!-- The inner braces are part of the expanded syntax. Remember, the `vec!` macro is --> <!-- used in an expression context. To write an expression with multiple statements, --> <!-- including `let`-bindings, we use a block. If your macro expands to a single --> <!-- expression, you don’t need this extra layer of braces. --> <p>内側の括弧は展開結果の一部です。 <code>vec!</code> マクロは式を必要としているコンテキストで利用されていることを思いだしてください。 複数の文や、 <code>let</code> 束縛を含む式を書きたいときにはブロックを利用します。 もし、マクロが単一の式に展開されるときは、追加の括弧は必要ありません。</p> <!-- Note that we never *declared* that the macro produces an expression. In fact, --> <!-- this is not determined until we use the macro as an expression. With care, you --> <!-- can write a macro whose expansion works in several contexts. For example, --> <!-- shorthand for a data type could be valid as either an expression or a pattern. --> <p>マクロが式を生成すると <em>宣言</em> した事はないという点に注意してください。 事実、それはマクロを式として利用するまでは決定されません。 注意深くすれば、複数のコンテキストで適切に展開されるマクロを書く事ができます。 例えば、データ型の短縮形は、式としてもパターンとしても正しく動作します。</p> <!-- ## Repetition --> <h2 id='繰り返し' class='section-header'><a href='#繰り返し'>繰り返し</a></h2> <!-- The repetition operator follows two principal rules: --> <p>繰り返し演算子は以下の2つの重要なルールに従います:</p> <!-- 1. `$(...)*` walks through one "layer" of repetitions, for all of the `$name`s --> <!-- it contains, in lockstep, and --> <!-- 2. each `$name` must be under at least as many `$(...)*`s as it was matched --> <!-- against. If it is under more, it’ll be duplicated, as appropriate. --> <ol> <li><code>$(...)*</code> は繰り返しの一つの「レイヤ」上で動作し、 レイヤが含んでいる <code>$name</code> について足並みを揃えて動作します。</li> <li>それぞれの <code>$name</code> はマッチしたときと同じ個数の <code>$(...)*</code> の内側になければなりません。 もし更に多くの <code>$(...)*</code> の中に表われた際には適切に複製されます。</li> </ol> <!-- This baroque macro illustrates the duplication of variables from outer --> <!-- repetition levels. --> <p>以下の複雑なマクロは一つ外の繰り返しのレベルから値を複製している例です:</p> <span class='rusttest'>macro_rules! o_O { ( $( $x:expr; [ $( $y:expr ),* ] );* ) =&gt; { &amp;[ $($( $x + $y ),*),* ] } } fn main() { let a: &amp;[i32] = o_O!(10; [1, 2, 3]; 20; [4, 5, 6]); assert_eq!(a, [11, 12, 13, 24, 25, 26]); } </span><pre class='rust rust-example-rendered'> <span class='macro'>macro_rules</span><span class='macro'>!</span> <span class='ident'>o_O</span> { ( $( <span class='macro-nonterminal'>$</span><span class='macro-nonterminal'>x</span>:<span class='ident'>expr</span>; [ $( <span class='macro-nonterminal'>$</span><span class='macro-nonterminal'>y</span>:<span class='ident'>expr</span> ),<span class='op'>*</span> ] );<span class='op'>*</span> ) <span class='op'>=&gt;</span> { <span class='kw-2'>&amp;</span>[ $($( <span class='macro-nonterminal'>$</span><span class='macro-nonterminal'>x</span> <span class='op'>+</span> <span class='macro-nonterminal'>$</span><span class='macro-nonterminal'>y</span> ),<span class='op'>*</span>),<span class='op'>*</span> ] } } <span class='kw'>fn</span> <span class='ident'>main</span>() { <span class='kw'>let</span> <span class='ident'>a</span>: <span class='kw-2'>&amp;</span>[<span class='ident'>i32</span>] <span class='op'>=</span> <span class='macro'>o_O</span><span class='macro'>!</span>(<span class='number'>10</span>; [<span class='number'>1</span>, <span class='number'>2</span>, <span class='number'>3</span>]; <span class='number'>20</span>; [<span class='number'>4</span>, <span class='number'>5</span>, <span class='number'>6</span>]); <span class='macro'>assert_eq</span><span class='macro'>!</span>(<span class='ident'>a</span>, [<span class='number'>11</span>, <span class='number'>12</span>, <span class='number'>13</span>, <span class='number'>24</span>, <span class='number'>25</span>, <span class='number'>26</span>]); }</pre> <!-- That’s most of the matcher syntax. These examples use `$(...)*`, which is a --> <!-- "zero or more" match. Alternatively you can write `$(...)+` for a "one or --> <!-- more" match. Both forms optionally include a separator, which can be any token --> <!-- except `+` or `*`. --> <p>上のコードはほとんどのマッチャの構文を利用しています。 この例では0個以上にマッチする <code>$(...)*</code> を利用しています、 1つ以上にマッチさせたい場合は <code>$(...)+</code> を代わりに利用する事ができます。 また、どちらも補助的に区切りを指定する事ができます。区切りには、 <code>+</code> と <code>*</code> 以外の任意のトークンを指定することが可能です。</p> <!-- This system is based on --> <!-- "[Macro-by-Example](https://www.cs.indiana.edu/ftp/techreports/TR206.pdf)" --> <!-- (PDF link). --> <p>このシステムは: &quot;<a href="https://www.cs.indiana.edu/ftp/techreports/TR206.pdf">Macro-by-Example</a>&quot; (PDFリンク) に基づいています。</p> <!-- # Hygiene --> <h1 id='健全性' class='section-header'><a href='#健全性'>健全性</a></h1> <!-- Some languages implement macros using simple text substitution, which leads to --> <!-- various problems. For example, this C program prints `13` instead of the --> <!-- expected `25`. --> <p>いくつかの言語に組込まれているマクロは単純なテキストの置換を用いています、しかしこれは多くの問題を発生させます。 例えば、以下のC言語のプログラムは期待している <code>25</code> の代わりに <code>13</code> と出力します:</p> <pre><code class="language-text">#define FIVE_TIMES(x) 5 * x int main() { printf(&quot;%d\n&quot;, FIVE_TIMES(2 + 3)); return 0; } </code></pre> <!-- After expansion we have `5 * 2 + 3`, and multiplication has greater precedence --> <!-- than addition. If you’ve used C macros a lot, you probably know the standard --> <!-- idioms for avoiding this problem, as well as five or six others. In Rust, we --> <!-- don’t have to worry about it. --> <p>展開した結果は <code>5 * 2 + 3</code> となり、乗算は加算よりも優先度が高くなります。 もしC言語のマクロを頻繁に利用しているなら、この問題を避けるためのイディオムを5、6個は知っているでしょう。 Rustではこのような問題を恐れる必要はありません。</p> <span class='rusttest'>macro_rules! five_times { ($x:expr) =&gt; (5 * $x); } fn main() { assert_eq!(25, five_times!(2 + 3)); } </span><pre class='rust rust-example-rendered'> <span class='macro'>macro_rules</span><span class='macro'>!</span> <span class='ident'>five_times</span> { (<span class='macro-nonterminal'>$</span><span class='macro-nonterminal'>x</span>:<span class='ident'>expr</span>) <span class='op'>=&gt;</span> (<span class='number'>5</span> <span class='op'>*</span> <span class='macro-nonterminal'>$</span><span class='macro-nonterminal'>x</span>); } <span class='kw'>fn</span> <span class='ident'>main</span>() { <span class='macro'>assert_eq</span><span class='macro'>!</span>(<span class='number'>25</span>, <span class='macro'>five_times</span><span class='macro'>!</span>(<span class='number'>2</span> <span class='op'>+</span> <span class='number'>3</span>)); }</pre> <!-- The metavariable `$x` is parsed as a single expression node, and keeps its --> <!-- place in the syntax tree even after substitution. --> <p>メタ変数 <code>$x</code> は一つの式の頂点としてパースされ、構文木上の位置は置換されたあとも保存されます。</p> <!-- Another common problem in macro systems is ‘variable capture’. Here’s a C --> <!-- macro, using [a GNU C extension] to emulate Rust’s expression blocks. --> <p>他のマクロシステムで良くみられる問題は、「変数のキャプチャ」です。 以下のC言語のマクロは <a href="https://gcc.gnu.org/onlinedocs/gcc/Statement-Exprs.html">GNU C拡張</a> をRustの式のブロックをエミュレートするために利用しています。</p> <pre><code class="language-text">#define LOG(msg) ({ \ int state = get_log_state(); \ if (state &gt; 0) { \ printf(&quot;log(%d): %s\n&quot;, state, msg); \ } \ }) </code></pre> <!-- Here’s a simple use case that goes terribly wrong: --> <p>以下はこのマクロを利用したときにひどい事になる単純な利用例です:</p> <pre><code class="language-text">const char *state = &quot;reticulating splines&quot;; LOG(state) </code></pre> <!-- This expands to --> <p>このコードは以下のように展開されます</p> <pre><code class="language-text">const char *state = &quot;reticulating splines&quot;; int state = get_log_state(); if (state &gt; 0) { printf(&quot;log(%d): %s\n&quot;, state, state); } </code></pre> <!-- The second variable named `state` shadows the first one. This is a problem --> <!-- because the print statement should refer to both of them. --> <p>2番目の変数 <code>state</code> は1つめの <code>state</code> を隠してしまいます。 この問題は、print文が両方の変数を参照する必要があるために起こります。</p> <!-- The equivalent Rust macro has the desired behavior. --> <p>Rustにおける同様のマクロは期待する通りの動作をします。</p> <span class='rusttest'>fn get_log_state() -&gt; i32 { 3 } macro_rules! log { ($msg:expr) =&gt; {{ let state: i32 = get_log_state(); if state &gt; 0 { println!(&quot;log({}): {}&quot;, state, $msg); } }}; } fn main() { let state: &amp;str = &quot;reticulating splines&quot;; log!(state); } </span><pre class='rust rust-example-rendered'> <span class='macro'>macro_rules</span><span class='macro'>!</span> <span class='ident'>log</span> { (<span class='macro-nonterminal'>$</span><span class='macro-nonterminal'>msg</span>:<span class='ident'>expr</span>) <span class='op'>=&gt;</span> {{ <span class='kw'>let</span> <span class='ident'>state</span>: <span class='ident'>i32</span> <span class='op'>=</span> <span class='ident'>get_log_state</span>(); <span class='kw'>if</span> <span class='ident'>state</span> <span class='op'>&gt;</span> <span class='number'>0</span> { <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;log({}): {}&quot;</span>, <span class='ident'>state</span>, <span class='macro-nonterminal'>$</span><span class='macro-nonterminal'>msg</span>); } }}; } <span class='kw'>fn</span> <span class='ident'>main</span>() { <span class='kw'>let</span> <span class='ident'>state</span>: <span class='kw-2'>&amp;</span><span class='ident'>str</span> <span class='op'>=</span> <span class='string'>&quot;reticulating splines&quot;</span>; <span class='macro'>log</span><span class='macro'>!</span>(<span class='ident'>state</span>); }</pre> <!-- This works because Rust has a [hygienic macro system]. Each macro expansion --> <!-- happens in a distinct ‘syntax context’, and each variable is tagged with the --> <!-- syntax context where it was introduced. It’s as though the variable `state` --> <!-- inside `main` is painted a different "color" from the variable `state` inside --> <!-- the macro, and therefore they don’t conflict. --> <p>このマクロはRustが <a href="https://en.wikipedia.org/wiki/Hygienic_macro">健全なマクロシステム</a> を持っているためです。 それぞれのマクロ展開は分離された「構文コンテキスト」で行なわれ、 それぞれの変数はその変数が導入された構文コンテキストでタグ付けされます。 これは、 <code>main</code> 中の <code>state</code> がマクロの中の <code>state</code> とは異なる「色」で塗られているためにコンフリクトしないという風に考える事ができます。</p> <!-- This also restricts the ability of macros to introduce new bindings at the --> <!-- invocation site. Code such as the following will not work: --> <p>この健全性のシステムはマクロが新しい束縛を呼出時に導入する事を制限します。 以下のようなコードは動作しません:</p> <span class='rusttest'>macro_rules! foo { () =&gt; (let x = 3); } fn main() { foo!(); println!(&quot;{}&quot;, x); } </span><pre class='rust rust-example-rendered'> <span class='macro'>macro_rules</span><span class='macro'>!</span> <span class='ident'>foo</span> { () <span class='op'>=&gt;</span> (<span class='kw'>let</span> <span class='ident'>x</span> <span class='op'>=</span> <span class='number'>3</span>); } <span class='kw'>fn</span> <span class='ident'>main</span>() { <span class='macro'>foo</span><span class='macro'>!</span>(); <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;{}&quot;</span>, <span class='ident'>x</span>); }</pre> <!-- Instead you need to pass the variable name into the invocation, so it’s tagged --> <!-- with the right syntax context. --> <p>代わりに変数名を呼出時に渡す必要があります、 呼出時に渡す事で正しい構文コンテキストでタグ付けされます。</p> <span class='rusttest'>macro_rules! foo { ($v:ident) =&gt; (let $v = 3); } fn main() { foo!(x); println!(&quot;{}&quot;, x); } </span><pre class='rust rust-example-rendered'> <span class='macro'>macro_rules</span><span class='macro'>!</span> <span class='ident'>foo</span> { (<span class='macro-nonterminal'>$</span><span class='macro-nonterminal'>v</span>:<span class='ident'>ident</span>) <span class='op'>=&gt;</span> (<span class='kw'>let</span> <span class='macro-nonterminal'>$</span><span class='macro-nonterminal'>v</span> <span class='op'>=</span> <span class='number'>3</span>); } <span class='kw'>fn</span> <span class='ident'>main</span>() { <span class='macro'>foo</span><span class='macro'>!</span>(<span class='ident'>x</span>); <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;{}&quot;</span>, <span class='ident'>x</span>); }</pre> <!-- This holds for `let` bindings and loop labels, but not for [items][items]. --> <!-- So the following code does compile: --> <p>このルールは <code>let</code> 束縛やループについても同様ですが、 <a href="../reference.html#items">アイテム</a> については適用されません。 そのため、以下のコードはコンパイルが通ります:</p> <span class='rusttest'>macro_rules! foo { () =&gt; (fn x() { }); } fn main() { foo!(); x(); } </span><pre class='rust rust-example-rendered'> <span class='macro'>macro_rules</span><span class='macro'>!</span> <span class='ident'>foo</span> { () <span class='op'>=&gt;</span> (<span class='kw'>fn</span> <span class='ident'>x</span>() { }); } <span class='kw'>fn</span> <span class='ident'>main</span>() { <span class='macro'>foo</span><span class='macro'>!</span>(); <span class='ident'>x</span>(); }</pre> <!-- # Recursive macros --> <h1 id='再帰的マクロ' class='section-header'><a href='#再帰的マクロ'>再帰的マクロ</a></h1> <!-- A macro’s expansion can include more macro invocations, including invocations --> <!-- of the very same macro being expanded. These recursive macros are useful for --> <!-- processing tree-structured input, as illustrated by this (simplistic) HTML --> <!-- shorthand: --> <p>マクロの展開は、展開中のマクロ自身も含めたその他のマクロ呼出しを含んでいることが可能です。 そのような再帰的なマクロは、以下の(単純化した)HTMLの短縮形のような、木構造を持つ入力の処理に便利です:</p> <span class='rusttest'>#![allow(unused_must_use)] macro_rules! write_html { ($w:expr, ) =&gt; (()); ($w:expr, $e:tt) =&gt; (write!($w, &quot;{}&quot;, $e)); ($w:expr, $tag:ident [ $($inner:tt)* ] $($rest:tt)*) =&gt; {{ write!($w, &quot;&lt;{}&gt;&quot;, stringify!($tag)); write_html!($w, $($inner)*); write!($w, &quot;&lt;/{}&gt;&quot;, stringify!($tag)); write_html!($w, $($rest)*); }}; } fn main() { // FIXME(#21826) use std::fmt::Write; let mut out = String::new(); write_html!(&amp;mut out, html[ head[title[&quot;Macros guide&quot;]] body[h1[&quot;Macros are the best!&quot;]] ]); assert_eq!(out, &quot;&lt;html&gt;&lt;head&gt;&lt;title&gt;Macros guide&lt;/title&gt;&lt;/head&gt;\ &lt;body&gt;&lt;h1&gt;Macros are the best!&lt;/h1&gt;&lt;/body&gt;&lt;/html&gt;&quot;); } </span><pre class='rust rust-example-rendered'> <span class='macro'>macro_rules</span><span class='macro'>!</span> <span class='ident'>write_html</span> { (<span class='macro-nonterminal'>$</span><span class='macro-nonterminal'>w</span>:<span class='ident'>expr</span>, ) <span class='op'>=&gt;</span> (()); (<span class='macro-nonterminal'>$</span><span class='macro-nonterminal'>w</span>:<span class='ident'>expr</span>, <span class='macro-nonterminal'>$</span><span class='macro-nonterminal'>e</span>:<span class='ident'>tt</span>) <span class='op'>=&gt;</span> (<span class='macro'>write</span><span class='macro'>!</span>(<span class='macro-nonterminal'>$</span><span class='macro-nonterminal'>w</span>, <span class='string'>&quot;{}&quot;</span>, <span class='macro-nonterminal'>$</span><span class='macro-nonterminal'>e</span>)); (<span class='macro-nonterminal'>$</span><span class='macro-nonterminal'>w</span>:<span class='ident'>expr</span>, <span class='macro-nonterminal'>$</span><span class='macro-nonterminal'>tag</span>:<span class='ident'>ident</span> [ $(<span class='macro-nonterminal'>$</span><span class='macro-nonterminal'>inner</span>:<span class='ident'>tt</span>)<span class='op'>*</span> ] $(<span class='macro-nonterminal'>$</span><span class='macro-nonterminal'>rest</span>:<span class='ident'>tt</span>)<span class='op'>*</span>) <span class='op'>=&gt;</span> {{ <span class='macro'>write</span><span class='macro'>!</span>(<span class='macro-nonterminal'>$</span><span class='macro-nonterminal'>w</span>, <span class='string'>&quot;&lt;{}&gt;&quot;</span>, <span class='macro'>stringify</span><span class='macro'>!</span>(<span class='macro-nonterminal'>$</span><span class='macro-nonterminal'>tag</span>)); <span class='macro'>write_html</span><span class='macro'>!</span>(<span class='macro-nonterminal'>$</span><span class='macro-nonterminal'>w</span>, $(<span class='macro-nonterminal'>$</span><span class='macro-nonterminal'>inner</span>)<span class='op'>*</span>); <span class='macro'>write</span><span class='macro'>!</span>(<span class='macro-nonterminal'>$</span><span class='macro-nonterminal'>w</span>, <span class='string'>&quot;&lt;/{}&gt;&quot;</span>, <span class='macro'>stringify</span><span class='macro'>!</span>(<span class='macro-nonterminal'>$</span><span class='macro-nonterminal'>tag</span>)); <span class='macro'>write_html</span><span class='macro'>!</span>(<span class='macro-nonterminal'>$</span><span class='macro-nonterminal'>w</span>, $(<span class='macro-nonterminal'>$</span><span class='macro-nonterminal'>rest</span>)<span class='op'>*</span>); }}; } <span class='kw'>fn</span> <span class='ident'>main</span>() { <span class='kw'>use</span> <span class='ident'>std</span>::<span class='ident'>fmt</span>::<span class='ident'>Write</span>; <span class='kw'>let</span> <span class='kw-2'>mut</span> <span class='ident'>out</span> <span class='op'>=</span> <span class='ident'>String</span>::<span class='ident'>new</span>(); <span class='macro'>write_html</span><span class='macro'>!</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='ident'>out</span>, <span class='ident'>html</span>[ <span class='ident'>head</span>[<span class='ident'>title</span>[<span class='string'>&quot;Macros guide&quot;</span>]] <span class='ident'>body</span>[<span class='ident'>h1</span>[<span class='string'>&quot;Macros are the best!&quot;</span>]] ]); <span class='macro'>assert_eq</span><span class='macro'>!</span>(<span class='ident'>out</span>, <span class='string'>&quot;&lt;html&gt;&lt;head&gt;&lt;title&gt;Macros guide&lt;/title&gt;&lt;/head&gt;\ &lt;body&gt;&lt;h1&gt;Macros are the best!&lt;/h1&gt;&lt;/body&gt;&lt;/html&gt;&quot;</span>); }</pre> <!-- # Debugging macro code --> <h1 id='マクロをデバッグする' class='section-header'><a href='#マクロをデバッグする'>マクロをデバッグする</a></h1> <!-- To see the results of expanding macros, run `rustc --pretty expanded`. The --> <!-- output represents a whole crate, so you can also feed it back in to `rustc`, --> <!-- which will sometimes produce better error messages than the original --> <!-- compilation. Note that the `--pretty expanded` output may have a different --> <!-- meaning if multiple variables of the same name (but different syntax contexts) --> <!-- are in play in the same scope. In this case `--pretty expanded,hygiene` will --> <!-- tell you about the syntax contexts. --> <p>マクロの展開結果を見るには、 <code>rustc --pretty expanded</code> を実行して下さい。 出力結果はクレートの全体を表しています、そのため出力結果を再び <code>rustc</code> に与えることができます、 そのようにすると時々、直接コンパイルした場合よりもより良いエラーメッセージを得ることができます。 しかし、 <code>--pretty expanded</code> は同じ名前の変数(構文コンテキストは異なる)が同じスコープに複数存在する場合、 出力結果のコード自体は、元のコードと意味が変わってくる場合があります。 そのようになってしまう場合、 <code>--pretty expanded,hygiene</code> のようにすることで、構文コンテキストについて知ることができます。</p> <!-- `rustc` provides two syntax extensions that help with macro debugging. For now, --> <!-- they are unstable and require feature gates. --> <p><code>rustc</code> はマクロのデバッグを補助する2つの構文拡張を提供しています。 今のところは、それらの構文は不安定であり、フィーチャーゲートを必要としています。</p> <!-- * `log_syntax!(...)` will print its arguments to standard output, at compile --> <!-- time, and "expand" to nothing. --> <ul> <li><code>log_syntax!(...)</code> は与えられた引数をコンパイル時に標準入力に出力し、展開結果は何も生じません。</li> </ul> <!-- * `trace_macros!(true)` will enable a compiler message every time a macro is --> <!-- expanded. Use `trace_macros!(false)` later in expansion to turn it off. --> <ul> <li><code>trace_macros!(true)</code> はマクロが展開されるたびにコンパイラがメッセージを出力するように設定できます、 <code>trace_macros!(false)</code> を展開の終わりごろに用いることで、メッセージの出力をオフにできます。</li> </ul> <!-- # Syntactic requirements --> <h1 id='構文的な要求' class='section-header'><a href='#構文的な要求'>構文的な要求</a></h1> <!-- Even when Rust code contains un-expanded macros, it can be parsed as a full --> <!-- [syntax tree][ast]. This property can be very useful for editors and other --> <!-- tools that process code. It also has a few consequences for the design of --> <!-- Rust’s macro system. --> <p>Rustのコードに展開されていないマクロが含まれていても、 <a href="glossary.html#abstract-syntax-tree">構文木</a> としてパースすることができます。 このような特性はテキストエディタや、その他のコードを処理するツールにとって非常に便利です。 また、このような特性はRustのマクロシステムの設計にも影響を及ぼしています。</p> <!-- One consequence is that Rust must determine, when it parses a macro invocation, --> <!-- whether the macro stands in for --> <p>一つの影響としては、マクロ呼出をパースした時、マクロが以下のどれを意味しているかを判定する必要があります:</p> <!-- * zero or more items, --> <!-- * zero or more methods, --> <!-- * an expression, --> <!-- * a statement, or --> <!-- * a pattern. --> <ul> <li>0個以上のアイテム</li> <li>0個以上のメソッド</li> <li>式</li> <li>文</li> <li>パターン</li> </ul> <!-- A macro invocation within a block could stand for some items, or for an --> <!-- expression / statement. Rust uses a simple rule to resolve this ambiguity. A --> <!-- macro invocation that stands for items must be either --> <p>ブロック中でのマクロ呼出は、幾つかのアイテムや、一つの式 / 文 に対応します。 Rustはこの曖昧性を判定するために単純なルールを利用します。 アイテムに対応しているマクロ呼出は以下のどちらかでなければなりません</p> <!-- * delimited by curly braces, e.g. `foo! { ... }`, or --> <!-- * terminated by a semicolon, e.g. `foo!(...);` --> <ul> <li>波括弧で区切られている 例: <code>foo! { ... }</code></li> <li>セミコロンで終了している 例: <code>foo!(...);</code></li> </ul> <!-- Another consequence of pre-expansion parsing is that the macro invocation must --> <!-- consist of valid Rust tokens. Furthermore, parentheses, brackets, and braces --> <!-- must be balanced within a macro invocation. For example, `foo!([)` is --> <!-- forbidden. This allows Rust to know where the macro invocation ends. --> <p>その他の展開前にパース可能である事による制約はマクロ呼出は正しいRustトークンで構成されている必要があるというものです。 そのうえ、括弧や、角カッコ、波括弧はマクロ呼出し中でバランスしてなければなりません。 例えば: <code>foo!([)</code> は禁止されています。 これによってRustはマクロ呼出しがどこで終わっているかを知ることができます。</p> <!-- More formally, the macro invocation body must be a sequence of ‘token trees’. --> <!-- A token tree is defined recursively as either --> <p>もっと厳密に言うと、マクロ呼出しの本体は「トークンの木」のシーケンスである必要があります。 トークンの木は以下のいずれかの条件により再帰的に定義されています</p> <!-- * a sequence of token trees surrounded by matching `()`, `[]`, or `{}`, or --> <!-- * any other single token. --> <ul> <li>マッチャ、 <code>()</code> 、 <code>[]</code> または <code>{}</code> で囲まれたトークンの木、あるいは、</li> <li>その他の単一のトークン</li> </ul> <!-- Within a matcher, each metavariable has a ‘fragment specifier’, identifying --> <!-- which syntactic form it matches. --> <p>マッチャ内部ではそれぞれのメタ変数はマッチする構文を指定する「フラグメント指定子」を持っています。</p> <!-- * `ident`: an identifier. Examples: `x`; `foo`. --> <!-- * `path`: a qualified name. Example: `T::SpecialA`. --> <!-- * `expr`: an expression. Examples: `2 + 2`; `if true { 1 } else { 2 }`; `f(42)`. --> <!-- * `ty`: a type. Examples: `i32`; `Vec<(char, String)>`; `&T`. --> <!-- * `pat`: a pattern. Examples: `Some(t)`; `(17, 'a')`; `_`. --> <!-- * `stmt`: a single statement. Example: `let x = 3`. --> <!-- * `block`: a brace-delimited sequence of statements. Example: --> <!-- `{ log(error, "hi"); return 12; }`. --> <!-- * `item`: an [item][item]. Examples: `fn foo() { }`; `struct Bar;`. --> <!-- * `meta`: a "meta item", as found in attributes. Example: `cfg(target_os = "windows")`. --> <!-- * `tt`: a single token tree. --> <ul> <li><code>ident</code>: 識別子。 例: <code>x</code>; <code>foo</code></li> <li><code>path</code>: 修飾された名前。例: <code>T::SpecialA</code></li> <li><code>expr</code>: 式。 例: <code>2 + 2</code>; <code>if true { 1 } else { 2 }</code>; <code>f(42)</code></li> <li><code>ty</code>: 型。 例: <code>i32</code>; <code>Vec&lt;(char, String)&gt;</code>; <code>&amp;T</code></li> <li><code>pat</code>: パターン。 例: <code>Some(t)</code>; <code>(17, &#39;a&#39;)</code>; <code>_</code></li> <li><code>stmt</code>: 単一の文。 例: <code>let x = 3</code></li> <li><code>block</code>: 波括弧で区切られた文のシーケンス。 例: <code>{ log(error, &quot;hi&quot;); return 12 }</code></li> <li><code>item</code>: <a href="../reference.html#items">アイテム</a>。 例: <code>fn foo() { }</code>; <code>struct Bar;</code></li> <li><code>meta</code>: アトリビュートで見られるような「メタアイテム」。 例: <code>cfg(target_os = &quot;windows&quot;)</code></li> <li><code>tt</code>: 単一のトークンの木</li> </ul> <!-- There are additional rules regarding the next token after a metavariable: --> <p>またメタ変数の次のトークンについて以下のルールが存在します:</p> <!-- * `expr` variables may only be followed by one of: `=> , ;` --> <!-- * `ty` and `path` variables may only be followed by one of: `=> , : = > as` --> <!-- * `pat` variables may only be followed by one of: `=> , = if in` --> <!-- * Other variables may be followed by any token. --> <ul> <li><code>expr</code> 変数は <code>=&gt; , ;</code> のどれか一つのみが次に現れます</li> <li><code>ty</code> と <code>path</code> 変数は <code>=&gt; , : = &gt; as</code> のどれか一つのみが次に現れます</li> <li><code>pat</code> 変数は <code>=&gt; , = if in</code> のどれか一つのみが次に現れます</li> <li>その他の変数は任意のトークンが次に現れます</li> </ul> <!-- These rules provide some flexibility for Rust’s syntax to evolve without --> <!-- breaking existing macros. --> <p>これらのルールは既存のマクロを破壊すること無くRustの構文を拡張するための自由度を与えます。</p> <!-- The macro system does not deal with parse ambiguity at all. For example, the --> <!-- grammar `$($t:ty)* $e:expr` will always fail to parse, because the parser would --> <!-- be forced to choose between parsing `$t` and parsing `$e`. Changing the --> <!-- invocation syntax to put a distinctive token in front can solve the problem. In --> <!-- this case, you can write `$(T $t:ty)* E $e:exp`. --> <p>マクロシステムはパースの曖昧さについては何も対処しません。 例えば、 <code>$($t:ty)* $e:expr</code> は常にパースが失敗します、 なぜならパーサーは <code>$t</code> をパースするか、 <code>$e</code> をパースするかを選ぶことを強制されるためです。 呼出構文を変更して識別可能なトークンを先頭につけることでこの問題は回避することができます。 そのようにする場合、例えば <code>$(T $t:ty)* E $e:exp</code> のように書くことができます。</p> <!-- # Scoping and macro import/export --> <h1 id='スコープとマクロのインポートエクスポート' class='section-header'><a href='#スコープとマクロのインポートエクスポート'>スコープとマクロのインポート/エクスポート</a></h1> <!-- Macros are expanded at an early stage in compilation, before name resolution. --> <!-- One downside is that scoping works differently for macros, compared to other --> <!-- constructs in the language. --> <p>マクロはコンパイルの早い段階、名前解決が行われる前に展開されます。 一つの悪い側面としては、言語中のその他の構造とは異なり、マクロではスコープが少し違って動作するということです。</p> <!-- Definition and expansion of macros both happen in a single depth-first, --> <!-- lexical-order traversal of a crate’s source. So a macro defined at module scope --> <!-- is visible to any subsequent code in the same module, which includes the body --> <!-- of any subsequent child `mod` items. --> <p>マクロの定義と展開はクレートの字面上の順序どおりに単一の深さ優先探索で行われます。 そのため、モジュールスコープで定義されたマクロは、 後続する子供の <code>mod</code> アイテムも含む、同じモジュール中のコードから見えます。</p> <!-- A macro defined within the body of a single `fn`, or anywhere else not at --> <!-- module scope, is visible only within that item. --> <p><code>fn</code> の本体の中やその他のモジュールのスコープでない箇所で定義されたマクロはそのアイテム中でしか見えません。</p> <!-- If a module has the `macro_use` attribute, its macros are also visible in its --> <!-- parent module after the child’s `mod` item. If the parent also has `macro_use` --> <!-- then the macros will be visible in the grandparent after the parent’s `mod` --> <!-- item, and so forth. --> <p>もし、モジュールが <code>macro_use</code> アトリビュートを持っていた場合、 それらのマクロは子供の <code>mod</code> アイテムの後で、親モジュールからも見えます。 もし親モジュールが同様に <code>macro_use</code> アトリビュートを持っていた場合、 親の親モジュールから親の <code>mod</code> アイテムが終わった後に見えます。 その後についても同様です。</p> <!-- The `macro_use` attribute can also appear on `extern crate`. In this context --> <!-- it controls which macros are loaded from the external crate, e.g. --> <p>また、 <code>macro_use</code> アトリビュートは <code>extern crate</code> の上でも利用することができます。 そのようにした場合、 <code>macro_use</code> アトリビュートは外部のクレートからどのマクロをロードするのかを指定します。 以下がその例です:</p> <span class='rusttest'>fn main() { #[macro_use(foo, bar)] extern crate baz; }</span><pre class='rust rust-example-rendered'> <span class='attribute'>#[<span class='ident'>macro_use</span>(<span class='ident'>foo</span>, <span class='ident'>bar</span>)]</span> <span class='kw'>extern</span> <span class='kw'>crate</span> <span class='ident'>baz</span>;</pre> <!-- If the attribute is given simply as `#[macro_use]`, all macros are loaded. If --> <!-- there is no `#[macro_use]` attribute then no macros are loaded. Only macros --> <!-- defined with the `#[macro_export]` attribute may be loaded. --> <p>もしアトリビュートが単純に <code>#[macro_use]</code> という形で指定されていた場合、全てのマクロがロードされます。 もし、 <code>#[macro_use]</code> が指定されていなかった場合、 <code>#[macro_export]</code> アトリビュートとともに定義されているマクロ以外は、 どのマクロもロードされません。</p> <!-- To load a crate’s macros without linking it into the output, use `#[no_link]` --> <!-- as well. --> <p>クレートのマクロを出力にリンクさせずにロードするには、 <code>#[no_link]</code> を利用して下さい。</p> <!-- An example: --> <p>一例としては:</p> <span class='rusttest'>macro_rules! m1 { () =&gt; (()) } // // visible here: m1 // ここで見えるのは: m1 mod foo { // // visible here: m1 // ここで見えるのは: m1 #[macro_export] macro_rules! m2 { () =&gt; (()) } // // visible here: m1, m2 // ここで見えるのは: m1、m2 } // // visible here: m1 // ここで見えるのは: m1 macro_rules! m3 { () =&gt; (()) } // // visible here: m1, m3 // ここで見えるのは: m1、m3 #[macro_use] mod bar { // // visible here: m1, m3 // ここで見えるのは: m1、m3 macro_rules! m4 { () =&gt; (()) } // // visible here: m1, m3, m4 // ここで見えるのは: m1、m3、m4 } // // visible here: m1, m3, m4 // ここで見えるのは: m1、m3、m4 fn main() { } </span><pre class='rust rust-example-rendered'> <span class='macro'>macro_rules</span><span class='macro'>!</span> <span class='ident'>m1</span> { () <span class='op'>=&gt;</span> (()) } <span class='comment'>// ここで見えるのは: m1</span> <span class='kw'>mod</span> <span class='ident'>foo</span> { <span class='comment'>// ここで見えるのは: m1</span> <span class='attribute'>#[<span class='ident'>macro_export</span>]</span> <span class='macro'>macro_rules</span><span class='macro'>!</span> <span class='ident'>m2</span> { () <span class='op'>=&gt;</span> (()) } <span class='comment'>// ここで見えるのは: m1、m2</span> } <span class='comment'>// ここで見えるのは: m1</span> <span class='macro'>macro_rules</span><span class='macro'>!</span> <span class='ident'>m3</span> { () <span class='op'>=&gt;</span> (()) } <span class='comment'>// ここで見えるのは: m1、m3</span> <span class='attribute'>#[<span class='ident'>macro_use</span>]</span> <span class='kw'>mod</span> <span class='ident'>bar</span> { <span class='comment'>// ここで見えるのは: m1、m3</span> <span class='macro'>macro_rules</span><span class='macro'>!</span> <span class='ident'>m4</span> { () <span class='op'>=&gt;</span> (()) } <span class='comment'>// ここで見えるのは: m1、m3、m4</span> } <span class='comment'>// ここで見えるのは: m1、m3、m4</span></pre> <!-- When this library is loaded with `#[macro_use] extern crate`, only `m2` will --> <!-- be imported. --> <p>ライブラリが <code>#[macro_use]</code> と共に外部のクレートをロードした場合、 <code>m2</code> だけがインポートされます。</p> <!-- The Rust Reference has a [listing of macro-related --> <!-- attributes](../reference.html#macro-related-attributes). --> <p>Rustのリファレンスは <a href="../reference.html#macro-related-attributes">マクロに関連するアトリビュートの一覧</a> を掲載しています。</p> <!-- # The variable `$crate` --> <h1 id='crate-変数' class='section-header'><a href='#crate-変数'><code>$crate</code> 変数</a></h1> <!-- A further difficulty occurs when a macro is used in multiple crates. Say that --> <!-- `mylib` defines --> <p>さらなる困難はマクロが複数のクレートで利用された時に発生します。 <code>mylib</code> が以下のように定義されているとしましょう</p> <span class='rusttest'>pub fn increment(x: u32) -&gt; u32 { x + 1 } #[macro_export] macro_rules! inc_a { ($x:expr) =&gt; ( ::increment($x) ) } #[macro_export] macro_rules! inc_b { ($x:expr) =&gt; ( ::mylib::increment($x) ) } fn main() { } </span><pre class='rust rust-example-rendered'> <span class='kw'>pub</span> <span class='kw'>fn</span> <span class='ident'>increment</span>(<span class='ident'>x</span>: <span class='ident'>u32</span>) <span class='op'>-&gt;</span> <span class='ident'>u32</span> { <span class='ident'>x</span> <span class='op'>+</span> <span class='number'>1</span> } <span class='attribute'>#[<span class='ident'>macro_export</span>]</span> <span class='macro'>macro_rules</span><span class='macro'>!</span> <span class='ident'>inc_a</span> { (<span class='macro-nonterminal'>$</span><span class='macro-nonterminal'>x</span>:<span class='ident'>expr</span>) <span class='op'>=&gt;</span> ( ::<span class='ident'>increment</span>(<span class='macro-nonterminal'>$</span><span class='macro-nonterminal'>x</span>) ) } <span class='attribute'>#[<span class='ident'>macro_export</span>]</span> <span class='macro'>macro_rules</span><span class='macro'>!</span> <span class='ident'>inc_b</span> { (<span class='macro-nonterminal'>$</span><span class='macro-nonterminal'>x</span>:<span class='ident'>expr</span>) <span class='op'>=&gt;</span> ( ::<span class='ident'>mylib</span>::<span class='ident'>increment</span>(<span class='macro-nonterminal'>$</span><span class='macro-nonterminal'>x</span>) ) }</pre> <!-- `inc_a` only works within `mylib`, while `inc_b` only works outside the --> <!-- library. Furthermore, `inc_b` will break if the user imports `mylib` under --> <!-- another name. --> <p><code>inc_a</code> は <code>mylib</code> の中でだけ動作します、かたや <code>inc_b</code> は <code>mylib</code> の外部でだけ動作します。 さらにいえば、 <code>inc_b</code> はユーザーが <code>mylib</code> を異なる名前でインポートした際には動作しません。</p> <!-- Rust does not (yet) have a hygiene system for crate references, but it does --> <!-- provide a simple workaround for this problem. Within a macro imported from a --> <!-- crate named `foo`, the special macro variable `$crate` will expand to `::foo`. --> <!-- By contrast, when a macro is defined and then used in the same crate, `$crate` --> <!-- will expand to nothing. This means we can write --> <p>Rustは(まだ)健全なクレートの参照の仕組みを持っていません、 しかし、この問題に対する簡単な対処方法を提供しています。 <code>foo</code>というクレートからインポートされたマクロ中において、 特別なマクロ変数 <code>$crate</code> は <code>::foo</code> に展開されます。 対照的に、マクロが同じクレートの中で定義され利用された場合、 <code>$crate</code> は何にも展開されません。これはつまり以下のように書けることを意味しています:</p> <span class='rusttest'>#[macro_export] macro_rules! inc { ($x:expr) =&gt; ( $crate::increment($x) ) } fn main() { } </span><pre class='rust rust-example-rendered'> <span class='attribute'>#[<span class='ident'>macro_export</span>]</span> <span class='macro'>macro_rules</span><span class='macro'>!</span> <span class='ident'>inc</span> { (<span class='macro-nonterminal'>$</span><span class='macro-nonterminal'>x</span>:<span class='ident'>expr</span>) <span class='op'>=&gt;</span> ( <span class='macro-nonterminal'>$</span><span class='kw'>crate</span>::<span class='macro-nonterminal'>increment</span>(<span class='macro-nonterminal'>$</span><span class='macro-nonterminal'>x</span>) ) }</pre> <!-- to define a single macro that works both inside and outside our library. The --> <!-- function name will expand to either `::increment` or `::mylib::increment`. --> <p>これは、ライブラリの中でも外でも動作するマクロを定義しています。 関数の名前は <code>::increment</code> または <code>::mylib::increment</code> に展開されます。</p> <!-- To keep this system simple and correct, `#[macro_use] extern crate ...` may --> <!-- only appear at the root of your crate, not inside `mod`. This ensures that --> <!-- `$crate` is a single identifier. --> <p>このシステムを簡潔で正しく保つために、 <code>#[macro_use] extern crate ...</code> はクレートのルートにしか登場せず、 <code>mod</code> の中には現れません。これは <code>$crate</code> が単一の識別子を持つことを確実にします。</p> <!-- # The deep end --> <h1 id='最難関部' class='section-header'><a href='#最難関部'>最難関部</a></h1> <!-- The introductory chapter mentioned recursive macros, but it did not give the --> <!-- full story. Recursive macros are useful for another reason: Each recursive --> <!-- invocation gives you another opportunity to pattern-match the macro’s --> <!-- arguments. --> <p>入門のチャプタで再帰的なマクロについて言及しました、しかしそのチャプタでは詳細について話していませんでした。 再帰的なマクロが便利な他の理由は、それぞれの再帰的な呼出はマクロに与えられた引数にたいしてパターンマッチを行える可能性を与えてくれることです。</p> <!-- As an extreme example, it is possible, though hardly advisable, to implement --> <!-- the [Bitwise Cyclic Tag](https://esolangs.org/wiki/Bitwise_Cyclic_Tag) automaton --> <!-- within Rust’s macro system. --> <p>極端な例としては、 望ましくはありませんが、 <a href="https://esolangs.org/wiki/Bitwise_Cyclic_Tag">Bitwise Cyclic Tag</a> のオートマトンをRustのマクロで実装する事が可能です。</p> <span class='rusttest'>fn main() { macro_rules! bct { // cmd 0: d ... =&gt; ... (0, $($ps:tt),* ; $_d:tt) =&gt; (bct!($($ps),*, 0 ; )); (0, $($ps:tt),* ; $_d:tt, $($ds:tt),*) =&gt; (bct!($($ps),*, 0 ; $($ds),*)); // cmd 1p: 1 ... =&gt; 1 ... p (1, $p:tt, $($ps:tt),* ; 1) =&gt; (bct!($($ps),*, 1, $p ; 1, $p)); (1, $p:tt, $($ps:tt),* ; 1, $($ds:tt),*) =&gt; (bct!($($ps),*, 1, $p ; 1, $($ds),*, $p)); // cmd 1p: 0 ... =&gt; 0 ... (1, $p:tt, $($ps:tt),* ; $($ds:tt),*) =&gt; (bct!($($ps),*, 1, $p ; $($ds),*)); // // halt on empty data string // 空のデータ文字列で停止します ( $($ps:tt),* ; ) =&gt; (()); } }</span><pre class='rust rust-example-rendered'> <span class='macro'>macro_rules</span><span class='macro'>!</span> <span class='ident'>bct</span> { <span class='comment'>// cmd 0: d ... =&gt; ...</span> (<span class='number'>0</span>, $(<span class='macro-nonterminal'>$</span><span class='macro-nonterminal'>ps</span>:<span class='ident'>tt</span>),<span class='op'>*</span> ; <span class='macro-nonterminal'>$</span><span class='macro-nonterminal'>_d</span>:<span class='ident'>tt</span>) <span class='op'>=&gt;</span> (<span class='macro'>bct</span><span class='macro'>!</span>($(<span class='macro-nonterminal'>$</span><span class='macro-nonterminal'>ps</span>),<span class='op'>*</span>, <span class='number'>0</span> ; )); (<span class='number'>0</span>, $(<span class='macro-nonterminal'>$</span><span class='macro-nonterminal'>ps</span>:<span class='ident'>tt</span>),<span class='op'>*</span> ; <span class='macro-nonterminal'>$</span><span class='macro-nonterminal'>_d</span>:<span class='ident'>tt</span>, $(<span class='macro-nonterminal'>$</span><span class='macro-nonterminal'>ds</span>:<span class='ident'>tt</span>),<span class='op'>*</span>) <span class='op'>=&gt;</span> (<span class='macro'>bct</span><span class='macro'>!</span>($(<span class='macro-nonterminal'>$</span><span class='macro-nonterminal'>ps</span>),<span class='op'>*</span>, <span class='number'>0</span> ; $(<span class='macro-nonterminal'>$</span><span class='macro-nonterminal'>ds</span>),<span class='op'>*</span>)); <span class='comment'>// cmd 1p: 1 ... =&gt; 1 ... p</span> (<span class='number'>1</span>, <span class='macro-nonterminal'>$</span><span class='macro-nonterminal'>p</span>:<span class='ident'>tt</span>, $(<span class='macro-nonterminal'>$</span><span class='macro-nonterminal'>ps</span>:<span class='ident'>tt</span>),<span class='op'>*</span> ; <span class='number'>1</span>) <span class='op'>=&gt;</span> (<span class='macro'>bct</span><span class='macro'>!</span>($(<span class='macro-nonterminal'>$</span><span class='macro-nonterminal'>ps</span>),<span class='op'>*</span>, <span class='number'>1</span>, <span class='macro-nonterminal'>$</span><span class='macro-nonterminal'>p</span> ; <span class='number'>1</span>, <span class='macro-nonterminal'>$</span><span class='macro-nonterminal'>p</span>)); (<span class='number'>1</span>, <span class='macro-nonterminal'>$</span><span class='macro-nonterminal'>p</span>:<span class='ident'>tt</span>, $(<span class='macro-nonterminal'>$</span><span class='macro-nonterminal'>ps</span>:<span class='ident'>tt</span>),<span class='op'>*</span> ; <span class='number'>1</span>, $(<span class='macro-nonterminal'>$</span><span class='macro-nonterminal'>ds</span>:<span class='ident'>tt</span>),<span class='op'>*</span>) <span class='op'>=&gt;</span> (<span class='macro'>bct</span><span class='macro'>!</span>($(<span class='macro-nonterminal'>$</span><span class='macro-nonterminal'>ps</span>),<span class='op'>*</span>, <span class='number'>1</span>, <span class='macro-nonterminal'>$</span><span class='macro-nonterminal'>p</span> ; <span class='number'>1</span>, $(<span class='macro-nonterminal'>$</span><span class='macro-nonterminal'>ds</span>),<span class='op'>*</span>, <span class='macro-nonterminal'>$</span><span class='macro-nonterminal'>p</span>)); <span class='comment'>// cmd 1p: 0 ... =&gt; 0 ...</span> (<span class='number'>1</span>, <span class='macro-nonterminal'>$</span><span class='macro-nonterminal'>p</span>:<span class='ident'>tt</span>, $(<span class='macro-nonterminal'>$</span><span class='macro-nonterminal'>ps</span>:<span class='ident'>tt</span>),<span class='op'>*</span> ; $(<span class='macro-nonterminal'>$</span><span class='macro-nonterminal'>ds</span>:<span class='ident'>tt</span>),<span class='op'>*</span>) <span class='op'>=&gt;</span> (<span class='macro'>bct</span><span class='macro'>!</span>($(<span class='macro-nonterminal'>$</span><span class='macro-nonterminal'>ps</span>),<span class='op'>*</span>, <span class='number'>1</span>, <span class='macro-nonterminal'>$</span><span class='macro-nonterminal'>p</span> ; $(<span class='macro-nonterminal'>$</span><span class='macro-nonterminal'>ds</span>),<span class='op'>*</span>)); <span class='comment'>// 空のデータ文字列で停止します</span> ( $(<span class='macro-nonterminal'>$</span><span class='macro-nonterminal'>ps</span>:<span class='ident'>tt</span>),<span class='op'>*</span> ; ) <span class='op'>=&gt;</span> (()); }</pre> <!-- Exercise: use macros to reduce duplication in the above definition of the --> <!-- `bct!` macro. --> <p>演習: マクロを使って上の <code>bct!</code> マクロの定義の重複している部分を減らしてみましょう。</p> <!-- # Common macros --> <h1 id='よく見られるマクロ' class='section-header'><a href='#よく見られるマクロ'>よく見られるマクロ</a></h1> <!-- Here are some common macros you’ll see in Rust code. --> <p>以下は、Rustコード中でよく見られるマクロたちです。</p> <h2 id='panic' class='section-header'><a href='#panic'>panic!</a></h2> <!-- This macro causes the current thread to panic. You can give it a message --> <!-- to panic with: --> <p>このマクロは現在のスレッドをパニック状態にします。 パニック時のメッセージを指定することができます。</p> <span class='rusttest'>fn main() { panic!(&quot;oh no!&quot;); }</span><pre class='rust rust-example-rendered'> <span class='macro'>panic</span><span class='macro'>!</span>(<span class='string'>&quot;oh no!&quot;</span>);</pre> <h2 id='vec' class='section-header'><a href='#vec'>vec!</a></h2> <!-- The `vec!` macro is used throughout the book, so you’ve probably seen it --> <!-- already. It creates `Vec<T>`s with ease: --> <p><code>vec!</code> マクロはこの本のなかで使われてきましたので、 すでに見たことがあるでしょう。 <code>vec!</code> マクロは <code>Vec&lt;T&gt;</code> を簡単に作成できます:</p> <span class='rusttest'>fn main() { let v = vec![1, 2, 3, 4, 5]; }</span><pre class='rust rust-example-rendered'> <span class='kw'>let</span> <span class='ident'>v</span> <span class='op'>=</span> <span class='macro'>vec</span><span class='macro'>!</span>[<span class='number'>1</span>, <span class='number'>2</span>, <span class='number'>3</span>, <span class='number'>4</span>, <span class='number'>5</span>];</pre> <!-- It also lets you make vectors with repeating values. For example, a hundred --> <!-- zeroes: --> <p>また、値の繰り返しのベクタを作成することも可能です。 たとえば、以下は100個の0を含むベクタの例です:</p> <span class='rusttest'>fn main() { let v = vec![0; 100]; }</span><pre class='rust rust-example-rendered'> <span class='kw'>let</span> <span class='ident'>v</span> <span class='op'>=</span> <span class='macro'>vec</span><span class='macro'>!</span>[<span class='number'>0</span>; <span class='number'>100</span>];</pre> <!-- ## assert! and assert_eq! --> <h2 id='assert-と-assert_eq' class='section-header'><a href='#assert-と-assert_eq'>assert! と assert_eq!</a></h2> <!-- These two macros are used in tests. `assert!` takes a boolean. `assert_eq!` --> <!-- takes two values and checks them for equality. `true` passes, `false` `panic!`s. --> <!-- Like this: --> <p>この2つのマクロはテスト時に利用されています。 <code>assert!</code> は真偽値を引数に取ります。 <code>assert_eq!</code> は2つの等価性をチェックする値を引数に取ります。 <code>true</code> ならばパスし、 <code>false</code> だった場合 <code>panic!</code> を起こします:</p> <span class='rusttest'>fn main() { // // A-ok! // Okです! assert!(true); assert_eq!(5, 3 + 2); // // nope :( // 駄目だぁ :( assert!(5 &lt; 3); assert_eq!(5, 3); }</span><pre class='rust rust-example-rendered'> <span class='comment'>// Okです!</span> <span class='macro'>assert</span><span class='macro'>!</span>(<span class='boolvalue'>true</span>); <span class='macro'>assert_eq</span><span class='macro'>!</span>(<span class='number'>5</span>, <span class='number'>3</span> <span class='op'>+</span> <span class='number'>2</span>); <span class='comment'>// 駄目だぁ :(</span> <span class='macro'>assert</span><span class='macro'>!</span>(<span class='number'>5</span> <span class='op'>&lt;</span> <span class='number'>3</span>); <span class='macro'>assert_eq</span><span class='macro'>!</span>(<span class='number'>5</span>, <span class='number'>3</span>);</pre> <h2 id='try' class='section-header'><a href='#try'>try!</a></h2> <!-- `try!` is used for error handling. It takes something that can return a --> <!-- `Result<T, E>`, and gives `T` if it’s a `Ok<T>`, and `return`s with the --> <!-- `Err(E)` if it’s that. Like this: --> <p><code>try!</code> はエラーハンドリングのために利用されています。 <code>try!</code> は <code>Result&lt;T, E&gt;</code> を返す何らかの物を引数に取り、もし <code>Result&lt;T, E&gt;</code> が <code>Ok&lt;T&gt;</code> だった場合 <code>T</code> を返し、 そうでなく <code>Err(E)</code> だった場合はそれを <code>return</code> します。 例えば以下のように利用します:</p> <span class='rusttest'>fn main() { use std::fs::File; fn foo() -&gt; std::io::Result&lt;()&gt; { let f = try!(File::create(&quot;foo.txt&quot;)); Ok(()) } }</span><pre class='rust rust-example-rendered'> <span class='kw'>use</span> <span class='ident'>std</span>::<span class='ident'>fs</span>::<span class='ident'>File</span>; <span class='kw'>fn</span> <span class='ident'>foo</span>() <span class='op'>-&gt;</span> <span class='ident'>std</span>::<span class='ident'>io</span>::<span class='prelude-ty'>Result</span><span class='op'>&lt;</span>()<span class='op'>&gt;</span> { <span class='kw'>let</span> <span class='ident'>f</span> <span class='op'>=</span> <span class='macro'>try</span><span class='macro'>!</span>(<span class='ident'>File</span>::<span class='ident'>create</span>(<span class='string'>&quot;foo.txt&quot;</span>)); <span class='prelude-val'>Ok</span>(()) }</pre> <!-- This is cleaner than doing this: --> <p>このコードは以下のコードよりも綺麗です:</p> <span class='rusttest'>fn main() { use std::fs::File; fn foo() -&gt; std::io::Result&lt;()&gt; { let f = File::create(&quot;foo.txt&quot;); let f = match f { Ok(t) =&gt; t, Err(e) =&gt; return Err(e), }; Ok(()) } }</span><pre class='rust rust-example-rendered'> <span class='kw'>use</span> <span class='ident'>std</span>::<span class='ident'>fs</span>::<span class='ident'>File</span>; <span class='kw'>fn</span> <span class='ident'>foo</span>() <span class='op'>-&gt;</span> <span class='ident'>std</span>::<span class='ident'>io</span>::<span class='prelude-ty'>Result</span><span class='op'>&lt;</span>()<span class='op'>&gt;</span> { <span class='kw'>let</span> <span class='ident'>f</span> <span class='op'>=</span> <span class='ident'>File</span>::<span class='ident'>create</span>(<span class='string'>&quot;foo.txt&quot;</span>); <span class='kw'>let</span> <span class='ident'>f</span> <span class='op'>=</span> <span class='kw'>match</span> <span class='ident'>f</span> { <span class='prelude-val'>Ok</span>(<span class='ident'>t</span>) <span class='op'>=&gt;</span> <span class='ident'>t</span>, <span class='prelude-val'>Err</span>(<span class='ident'>e</span>) <span class='op'>=&gt;</span> <span class='kw'>return</span> <span class='prelude-val'>Err</span>(<span class='ident'>e</span>), }; <span class='prelude-val'>Ok</span>(()) }</pre> <h2 id='unreachable' class='section-header'><a href='#unreachable'>unreachable!</a></h2> <!-- This macro is used when you think some code should never execute: --> <p>このマクロはあるコードが絶対に実行されるべきでないと考えている時に利用します。</p> <span class='rusttest'>fn main() { if false { unreachable!(); } }</span><pre class='rust rust-example-rendered'> <span class='kw'>if</span> <span class='boolvalue'>false</span> { <span class='macro'>unreachable</span><span class='macro'>!</span>(); }</pre> <!-- Sometimes, the compiler may make you have a different branch that you know --> <!-- will never, ever run. In these cases, use this macro, so that if you end --> <!-- up wrong, you’ll get a `panic!` about it. --> <p>時々、コンパイラによって絶対に呼び出されるはずがないと考えているブランチを作成することになる時があります。 そういった時には、このマクロを利用しましょう、そうすることでもし何か誤ってしまった時に、 <code>panic!</code> で知ることができます。</p> <span class='rusttest'>fn main() { let x: Option&lt;i32&gt; = None; match x { Some(_) =&gt; unreachable!(), None =&gt; println!(&quot;I know x is None!&quot;), } }</span><pre class='rust rust-example-rendered'> <span class='kw'>let</span> <span class='ident'>x</span>: <span class='prelude-ty'>Option</span><span class='op'>&lt;</span><span class='ident'>i32</span><span class='op'>&gt;</span> <span class='op'>=</span> <span class='prelude-val'>None</span>; <span class='kw'>match</span> <span class='ident'>x</span> { <span class='prelude-val'>Some</span>(_) <span class='op'>=&gt;</span> <span class='macro'>unreachable</span><span class='macro'>!</span>(), <span class='prelude-val'>None</span> <span class='op'>=&gt;</span> <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;I know x is None!&quot;</span>), }</pre> <h2 id='unimplemented' class='section-header'><a href='#unimplemented'>unimplemented!</a></h2> <!-- The `unimplemented!` macro can be used when you’re trying to get your functions --> <!-- to typecheck, and don’t want to worry about writing out the body of the --> <!-- function. One example of this situation is implementing a trait with multiple --> <!-- required methods, where you want to tackle one at a time. Define the others --> <!-- as `unimplemented!` until you’re ready to write them. --> <p><code>unimplemented!</code> マクロはもし関数の本体の実装はしていないが、型チェックだけは行いたいという時に利用します。 このような状況の一つの例としては複数のメソッドを必要としているトレイトのメソッドの一つを実装しようと試みている時などです。 残りのメソッドたちの実装に取り掛かれるようになるまで <code>unimplemented!</code> として定義しましょう。</p> <!-- # Procedural macros --> <h1 id='手続きマクロ' class='section-header'><a href='#手続きマクロ'>手続きマクロ</a></h1> <!-- If Rust’s macro system can’t do what you need, you may want to write a --> <!-- [compiler plugin](compiler-plugins.html) instead. Compared to `macro_rules!` --> <!-- macros, this is significantly more work, the interfaces are much less stable, --> <!-- and bugs can be much harder to track down. In exchange you get the --> <!-- flexibility of running arbitrary Rust code within the compiler. Syntax --> <!-- extension plugins are sometimes called ‘procedural macros’ for this reason. --> <p>もしRustのマクロシステムでは必要としていることができない場合、 <a href="compiler-plugins.html">コンパイラプラグイン</a> を代わりに書きたくなるでしょう。 コンパイラプラグインは <code>macro_rules!</code> マクロとくらべて、更に多くの作業が必要になり、 インタフェースはかなり不安定であり、バグはさらに追跡が困難になります。 引き換えに、任意のコードをコンパイラ中で実行できるという自由度を得ることができます。 構文拡張プラグインがしばしば「手続きマクロ」と呼ばれるのはこのためです。</p> <div class="footnotes"> <hr> <ol> <li id="fn1"> <p><code>vec!</code> のlibcollectionsにおける実際の実装と、ここで示したコードは効率性や再利用性のために異なります。&nbsp;<a href="#fnref1" rev="footnote">&#8617;</a></p> </li> </ol> </div> <script type="text/javascript"> window.playgroundUrl = "https://play.rust-lang.org"; </script> <script src='rustbook.js'></script> <script src='playpen.js'></script> </div></div> </body> </html> <|start_filename|>docs/1.9/nomicon/checked-uninit.html<|end_filename|> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="generator" content="rustdoc"> <title>Checked Uninitialized Memory</title> <link rel="stylesheet" type="text/css" href="rustbook.css"> <meta name="robots" content="noindex"> </head> <body class="rustdoc"> <!--[if lte IE 8]> <div class="warning"> This old browser is unsupported and will most likely display funky things. </div> <![endif]--> <div id="nav"> <button id="toggle-nav"> <span class="sr-only">Toggle navigation</span> <span class="bar"></span> <span class="bar"></span> <span class="bar"></span> </button> </div> <div id='toc' class='mobile-hidden'> <ul class='chapter'> <li><a href='README.html'><b>1.</b> Introduction</a> </li> <li><a href='meet-safe-and-unsafe.html'><b>2.</b> Meet Safe and Unsafe</a> <ul class='section'> <li><a href='safe-unsafe-meaning.html'><b>2.1.</b> How Safe and Unsafe Interact</a> </li> <li><a href='working-with-unsafe.html'><b>2.2.</b> Working with Unsafe</a> </li> </ul> </li> <li><a href='data.html'><b>3.</b> Data Layout</a> <ul class='section'> <li><a href='repr-rust.html'><b>3.1.</b> repr(Rust)</a> </li> <li><a href='exotic-sizes.html'><b>3.2.</b> Exotically Sized Types</a> </li> <li><a href='other-reprs.html'><b>3.3.</b> Other reprs</a> </li> </ul> </li> <li><a href='ownership.html'><b>4.</b> Ownership</a> <ul class='section'> <li><a href='references.html'><b>4.1.</b> References</a> </li> <li><a href='lifetimes.html'><b>4.2.</b> Lifetimes</a> </li> <li><a href='lifetime-mismatch.html'><b>4.3.</b> Limits of Lifetimes</a> </li> <li><a href='lifetime-elision.html'><b>4.4.</b> Lifetime Elision</a> </li> <li><a href='unbounded-lifetimes.html'><b>4.5.</b> Unbounded Lifetimes</a> </li> <li><a href='hrtb.html'><b>4.6.</b> Higher-Rank Trait Bounds</a> </li> <li><a href='subtyping.html'><b>4.7.</b> Subtyping and Variance</a> </li> <li><a href='dropck.html'><b>4.8.</b> Drop Check</a> </li> <li><a href='phantom-data.html'><b>4.9.</b> PhantomData</a> </li> <li><a href='borrow-splitting.html'><b>4.10.</b> Splitting Borrows</a> </li> </ul> </li> <li><a href='conversions.html'><b>5.</b> Type Conversions</a> <ul class='section'> <li><a href='coercions.html'><b>5.1.</b> Coercions</a> </li> <li><a href='dot-operator.html'><b>5.2.</b> The Dot Operator</a> </li> <li><a href='casts.html'><b>5.3.</b> Casts</a> </li> <li><a href='transmutes.html'><b>5.4.</b> Transmutes</a> </li> </ul> </li> <li><a href='uninitialized.html'><b>6.</b> Uninitialized Memory</a> <ul class='section'> <li><a class='active' href='checked-uninit.html'><b>6.1.</b> Checked</a> </li> <li><a href='drop-flags.html'><b>6.2.</b> Drop Flags</a> </li> <li><a href='unchecked-uninit.html'><b>6.3.</b> Unchecked</a> </li> </ul> </li> <li><a href='obrm.html'><b>7.</b> Ownership Based Resource Management</a> <ul class='section'> <li><a href='constructors.html'><b>7.1.</b> Constructors</a> </li> <li><a href='destructors.html'><b>7.2.</b> Destructors</a> </li> <li><a href='leaking.html'><b>7.3.</b> Leaking</a> </li> </ul> </li> <li><a href='unwinding.html'><b>8.</b> Unwinding</a> <ul class='section'> <li><a href='exception-safety.html'><b>8.1.</b> Exception Safety</a> </li> <li><a href='poisoning.html'><b>8.2.</b> Poisoning</a> </li> </ul> </li> <li><a href='concurrency.html'><b>9.</b> Concurrency</a> <ul class='section'> <li><a href='races.html'><b>9.1.</b> Races</a> </li> <li><a href='send-and-sync.html'><b>9.2.</b> Send and Sync</a> </li> <li><a href='atomics.html'><b>9.3.</b> Atomics</a> </li> </ul> </li> <li><a href='vec.html'><b>10.</b> Implementing Vec</a> <ul class='section'> <li><a href='vec-layout.html'><b>10.1.</b> Layout</a> </li> <li><a href='vec-alloc.html'><b>10.2.</b> Allocating</a> </li> <li><a href='vec-push-pop.html'><b>10.3.</b> Push and Pop</a> </li> <li><a href='vec-dealloc.html'><b>10.4.</b> Deallocating</a> </li> <li><a href='vec-deref.html'><b>10.5.</b> Deref</a> </li> <li><a href='vec-insert-remove.html'><b>10.6.</b> Insert and Remove</a> </li> <li><a href='vec-into-iter.html'><b>10.7.</b> IntoIter</a> </li> <li><a href='vec-raw.html'><b>10.8.</b> RawVec</a> </li> <li><a href='vec-drain.html'><b>10.9.</b> Drain</a> </li> <li><a href='vec-zsts.html'><b>10.10.</b> Handling Zero-Sized Types</a> </li> <li><a href='vec-final.html'><b>10.11.</b> Final Code</a> </li> </ul> </li> <li><a href='arc-and-mutex.html'><b>11.</b> Implementing Arc and Mutex</a> </li> </ul> </div> <div id='page-wrapper'> <div id='page'> <blockquote class="header-caveat"> <p> <strong>注意: <a href="https://doc.rust-jp.rs/book-ja/">最新版のドキュメントをご覧ください。</a></strong>この第1版ドキュメントは古くなっており、最新情報が反映されていません。リンク先のドキュメントが現在の Rust の最新のドキュメントです。 </p> </blockquote> <h1 class="title">Checked Uninitialized Memory</h1> <p>Like C, all stack variables in Rust are uninitialized until a value is explicitly assigned to them. Unlike C, Rust statically prevents you from ever reading them until you do:</p> <span class='rusttest'>fn main() { let x: i32; println!(&quot;{}&quot;, x); } </span><pre class='rust rust-example-rendered'> <span class='kw'>fn</span> <span class='ident'>main</span>() { <span class='kw'>let</span> <span class='ident'>x</span>: <span class='ident'>i32</span>; <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;{}&quot;</span>, <span class='ident'>x</span>); }</pre> <pre><code class="language-text">src/main.rs:3:20: 3:21 error: use of possibly uninitialized variable: `x` src/main.rs:3 println!(&quot;{}&quot;, x); ^ </code></pre> <p>This is based off of a basic branch analysis: every branch must assign a value to <code>x</code> before it is first used. Interestingly, Rust doesn&#39;t require the variable to be mutable to perform a delayed initialization if every branch assigns exactly once. However the analysis does not take advantage of constant analysis or anything like that. So this compiles:</p> <span class='rusttest'>fn main() { let x: i32; if true { x = 1; } else { x = 2; } println!(&quot;{}&quot;, x); } </span><pre class='rust rust-example-rendered'> <span class='kw'>fn</span> <span class='ident'>main</span>() { <span class='kw'>let</span> <span class='ident'>x</span>: <span class='ident'>i32</span>; <span class='kw'>if</span> <span class='boolvalue'>true</span> { <span class='ident'>x</span> <span class='op'>=</span> <span class='number'>1</span>; } <span class='kw'>else</span> { <span class='ident'>x</span> <span class='op'>=</span> <span class='number'>2</span>; } <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;{}&quot;</span>, <span class='ident'>x</span>); }</pre> <p>but this doesn&#39;t:</p> <span class='rusttest'>fn main() { let x: i32; if true { x = 1; } println!(&quot;{}&quot;, x); } </span><pre class='rust rust-example-rendered'> <span class='kw'>fn</span> <span class='ident'>main</span>() { <span class='kw'>let</span> <span class='ident'>x</span>: <span class='ident'>i32</span>; <span class='kw'>if</span> <span class='boolvalue'>true</span> { <span class='ident'>x</span> <span class='op'>=</span> <span class='number'>1</span>; } <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;{}&quot;</span>, <span class='ident'>x</span>); }</pre> <pre><code class="language-text">src/main.rs:6:17: 6:18 error: use of possibly uninitialized variable: `x` src/main.rs:6 println!(&quot;{}&quot;, x); </code></pre> <p>while this does:</p> <span class='rusttest'>fn main() { let x: i32; if true { x = 1; println!(&quot;{}&quot;, x); } // Don&#39;t care that there are branches where it&#39;s not initialized // since we don&#39;t use the value in those branches } </span><pre class='rust rust-example-rendered'> <span class='kw'>fn</span> <span class='ident'>main</span>() { <span class='kw'>let</span> <span class='ident'>x</span>: <span class='ident'>i32</span>; <span class='kw'>if</span> <span class='boolvalue'>true</span> { <span class='ident'>x</span> <span class='op'>=</span> <span class='number'>1</span>; <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;{}&quot;</span>, <span class='ident'>x</span>); } <span class='comment'>// Don&#39;t care that there are branches where it&#39;s not initialized</span> <span class='comment'>// since we don&#39;t use the value in those branches</span> }</pre> <p>Of course, while the analysis doesn&#39;t consider actual values, it does have a relatively sophisticated understanding of dependencies and control flow. For instance, this works:</p> <span class='rusttest'>fn main() { let x: i32; loop { // Rust doesn&#39;t understand that this branch will be taken unconditionally, // because it relies on actual values. if true { // But it does understand that it will only be taken once because // we unconditionally break out of it. Therefore `x` doesn&#39;t // need to be marked as mutable. x = 0; break; } } // It also knows that it&#39;s impossible to get here without reaching the break. // And therefore that `x` must be initialized here! println!(&quot;{}&quot;, x); }</span><pre class='rust rust-example-rendered'> <span class='kw'>let</span> <span class='ident'>x</span>: <span class='ident'>i32</span>; <span class='kw'>loop</span> { <span class='comment'>// Rust doesn&#39;t understand that this branch will be taken unconditionally,</span> <span class='comment'>// because it relies on actual values.</span> <span class='kw'>if</span> <span class='boolvalue'>true</span> { <span class='comment'>// But it does understand that it will only be taken once because</span> <span class='comment'>// we unconditionally break out of it. Therefore `x` doesn&#39;t</span> <span class='comment'>// need to be marked as mutable.</span> <span class='ident'>x</span> <span class='op'>=</span> <span class='number'>0</span>; <span class='kw'>break</span>; } } <span class='comment'>// It also knows that it&#39;s impossible to get here without reaching the break.</span> <span class='comment'>// And therefore that `x` must be initialized here!</span> <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;{}&quot;</span>, <span class='ident'>x</span>);</pre> <p>If a value is moved out of a variable, that variable becomes logically uninitialized if the type of the value isn&#39;t Copy. That is:</p> <span class='rusttest'>fn main() { let x = 0; let y = Box::new(0); let z1 = x; // x is still valid because i32 is Copy let z2 = y; // y is now logically uninitialized because Box isn&#39;t Copy } </span><pre class='rust rust-example-rendered'> <span class='kw'>fn</span> <span class='ident'>main</span>() { <span class='kw'>let</span> <span class='ident'>x</span> <span class='op'>=</span> <span class='number'>0</span>; <span class='kw'>let</span> <span class='ident'>y</span> <span class='op'>=</span> <span class='ident'>Box</span>::<span class='ident'>new</span>(<span class='number'>0</span>); <span class='kw'>let</span> <span class='ident'>z1</span> <span class='op'>=</span> <span class='ident'>x</span>; <span class='comment'>// x is still valid because i32 is Copy</span> <span class='kw'>let</span> <span class='ident'>z2</span> <span class='op'>=</span> <span class='ident'>y</span>; <span class='comment'>// y is now logically uninitialized because Box isn&#39;t Copy</span> }</pre> <p>However reassigning <code>y</code> in this example <em>would</em> require <code>y</code> to be marked as mutable, as a Safe Rust program could observe that the value of <code>y</code> changed:</p> <span class='rusttest'>fn main() { let mut y = Box::new(0); let z = y; // y is now logically uninitialized because Box isn&#39;t Copy y = Box::new(1); // reinitialize y } </span><pre class='rust rust-example-rendered'> <span class='kw'>fn</span> <span class='ident'>main</span>() { <span class='kw'>let</span> <span class='kw-2'>mut</span> <span class='ident'>y</span> <span class='op'>=</span> <span class='ident'>Box</span>::<span class='ident'>new</span>(<span class='number'>0</span>); <span class='kw'>let</span> <span class='ident'>z</span> <span class='op'>=</span> <span class='ident'>y</span>; <span class='comment'>// y is now logically uninitialized because Box isn&#39;t Copy</span> <span class='ident'>y</span> <span class='op'>=</span> <span class='ident'>Box</span>::<span class='ident'>new</span>(<span class='number'>1</span>); <span class='comment'>// reinitialize y</span> }</pre> <p>Otherwise it&#39;s like <code>y</code> is a brand new variable.</p> <script type="text/javascript"> window.playgroundUrl = "https://play.rust-lang.org"; </script> <script src='rustbook.js'></script> <script src='playpen.js'></script> </div></div> </body> </html> <|start_filename|>docs/1.9/book/ffi.html<|end_filename|> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="generator" content="rustdoc"> <title>他言語関数インターフェイス</title> <link rel="stylesheet" type="text/css" href="rustbook.css"> <meta name="robots" content="noindex"> </head> <body class="rustdoc"> <!--[if lte IE 8]> <div class="warning"> This old browser is unsupported and will most likely display funky things. </div> <![endif]--> <div id="nav"> <button id="toggle-nav"> <span class="sr-only">Toggle navigation</span> <span class="bar"></span> <span class="bar"></span> <span class="bar"></span> </button> </div> <div id='toc' class='mobile-hidden'> <ul class='chapter'> <li><a href='README.html'><b>1.</b> Introduction</a> </li> <li><a href='getting-started.html'><b>2.</b> はじめる</a> </li> <li><a href='guessing-game.html'><b>3.</b> チュートリアル:数当てゲーム</a> </li> <li><a href='syntax-and-semantics.html'><b>4.</b> シンタックスとセマンティクス</a> <ul class='section'> <li><a href='variable-bindings.html'><b>4.1.</b> 変数束縛</a> </li> <li><a href='functions.html'><b>4.2.</b> 関数</a> </li> <li><a href='primitive-types.html'><b>4.3.</b> プリミティブ型</a> </li> <li><a href='comments.html'><b>4.4.</b> コメント</a> </li> <li><a href='if.html'><b>4.5.</b> if</a> </li> <li><a href='loops.html'><b>4.6.</b> ループ</a> </li> <li><a href='vectors.html'><b>4.7.</b> ベクタ</a> </li> <li><a href='ownership.html'><b>4.8.</b> 所有権</a> </li> <li><a href='references-and-borrowing.html'><b>4.9.</b> 参照と借用</a> </li> <li><a href='lifetimes.html'><b>4.10.</b> ライフタイム</a> </li> <li><a href='mutability.html'><b>4.11.</b> ミュータビリティ</a> </li> <li><a href='structs.html'><b>4.12.</b> 構造体</a> </li> <li><a href='enums.html'><b>4.13.</b> 列挙型</a> </li> <li><a href='match.html'><b>4.14.</b> マッチ</a> </li> <li><a href='patterns.html'><b>4.15.</b> パターン</a> </li> <li><a href='method-syntax.html'><b>4.16.</b> メソッド構文</a> </li> <li><a href='strings.html'><b>4.17.</b> 文字列</a> </li> <li><a href='generics.html'><b>4.18.</b> ジェネリクス</a> </li> <li><a href='traits.html'><b>4.19.</b> トレイト</a> </li> <li><a href='drop.html'><b>4.20.</b> Drop</a> </li> <li><a href='if-let.html'><b>4.21.</b> if let</a> </li> <li><a href='trait-objects.html'><b>4.22.</b> トレイトオブジェクト</a> </li> <li><a href='closures.html'><b>4.23.</b> クロージャ</a> </li> <li><a href='ufcs.html'><b>4.24.</b> 共通の関数呼出構文</a> </li> <li><a href='crates-and-modules.html'><b>4.25.</b> クレートとモジュール</a> </li> <li><a href='const-and-static.html'><b>4.26.</b> `const` と `static`</a> </li> <li><a href='attributes.html'><b>4.27.</b> アトリビュート</a> </li> <li><a href='type-aliases.html'><b>4.28.</b> `type` エイリアス</a> </li> <li><a href='casting-between-types.html'><b>4.29.</b> 型間のキャスト</a> </li> <li><a href='associated-types.html'><b>4.30.</b> 関連型</a> </li> <li><a href='unsized-types.html'><b>4.31.</b> サイズ不定型</a> </li> <li><a href='operators-and-overloading.html'><b>4.32.</b> 演算子とオーバーロード</a> </li> <li><a href='deref-coercions.html'><b>4.33.</b> Derefによる型強制</a> </li> <li><a href='macros.html'><b>4.34.</b> マクロ</a> </li> <li><a href='raw-pointers.html'><b>4.35.</b> 生ポインタ</a> </li> <li><a href='unsafe.html'><b>4.36.</b> `unsafe`</a> </li> </ul> </li> <li><a href='effective-rust.html'><b>5.</b> Effective Rust</a> <ul class='section'> <li><a href='the-stack-and-the-heap.html'><b>5.1.</b> スタックとヒープ</a> </li> <li><a href='testing.html'><b>5.2.</b> テスト</a> </li> <li><a href='conditional-compilation.html'><b>5.3.</b> 条件付きコンパイル</a> </li> <li><a href='documentation.html'><b>5.4.</b> ドキュメント</a> </li> <li><a href='iterators.html'><b>5.5.</b> イテレータ</a> </li> <li><a href='concurrency.html'><b>5.6.</b> 並行性</a> </li> <li><a href='error-handling.html'><b>5.7.</b> エラーハンドリング</a> </li> <li><a href='choosing-your-guarantees.html'><b>5.8.</b> 保証を選ぶ</a> </li> <li><a class='active' href='ffi.html'><b>5.9.</b> 他言語関数インターフェース</a> </li> <li><a href='borrow-and-asref.html'><b>5.10.</b> BorrowとAsRef</a> </li> <li><a href='release-channels.html'><b>5.11.</b> リリースチャネル</a> </li> <li><a href='using-rust-without-the-standard-library.html'><b>5.12.</b> 標準ライブラリ無しでRustを使う</a> </li> </ul> </li> <li><a href='nightly-rust.html'><b>6.</b> Nightly Rust</a> <ul class='section'> <li><a href='compiler-plugins.html'><b>6.1.</b> コンパイラプラグイン</a> </li> <li><a href='inline-assembly.html'><b>6.2.</b> インラインアセンブリ</a> </li> <li><a href='no-stdlib.html'><b>6.3.</b> No stdlib</a> </li> <li><a href='intrinsics.html'><b>6.4.</b> Intrinsic</a> </li> <li><a href='lang-items.html'><b>6.5.</b> 言語アイテム</a> </li> <li><a href='advanced-linking.html'><b>6.6.</b> 高度なリンキング</a> </li> <li><a href='benchmark-tests.html'><b>6.7.</b> ベンチマークテスト</a> </li> <li><a href='box-syntax-and-patterns.html'><b>6.8.</b> Box構文とパターン</a> </li> <li><a href='slice-patterns.html'><b>6.9.</b> スライスパターン</a> </li> <li><a href='associated-constants.html'><b>6.10.</b> 関連定数</a> </li> <li><a href='custom-allocators.html'><b>6.11.</b> カスタムアロケータ</a> </li> </ul> </li> <li><a href='glossary.html'><b>7.</b> 用語集</a> </li> <li><a href='syntax-index.html'><b>8.</b> 構文の索引</a> </li> <li><a href='bibliography.html'><b>9.</b> 関係書目</a> </li> </ul> </div> <div id='page-wrapper'> <div id='page'> <blockquote class="header-caveat"> <p> <strong>注意: <a href="https://doc.rust-jp.rs/book-ja/">最新版のドキュメントをご覧ください。</a></strong>この第1版ドキュメントは古くなっており、最新情報が反映されていません。リンク先のドキュメントが現在の Rust の最新のドキュメントです。 </p> </blockquote> <h1 class="title">他言語関数インターフェイス</h1> <!-- % Foreign Function Interface --> <!-- # Introduction --> <h1 id='導入' class='section-header'><a href='#導入'>導入</a></h1> <!-- This guide will use the [snappy](https://github.com/google/snappy) --> <!-- compression/decompression library as an introduction to writing bindings for --> <!-- foreign code. Rust is currently unable to call directly into a C++ library, but --> <!-- snappy includes a C interface (documented in --> <!-- [`snappy-c.h`](https://github.com/google/snappy/blob/master/snappy-c.h)). --> <p>このガイドでは、他言語コードのためのバインディングを書く導入に <a href="https://github.com/google/snappy">snappy</a> という圧縮・展開ライブラリを使います。 Rustは現在、C++ライブラリを直接呼び出すことができませんが、snappyはCのインターフェイスを持っています(ドキュメントが <a href="https://github.com/google/snappy/blob/master/snappy-c.h"><code>snappy-c.h</code></a> にあります)。</p> <!-- ## A note about libc --> <h2 id='libcについてのメモ' class='section-header'><a href='#libcについてのメモ'>libcについてのメモ</a></h2> <!-- Many of these examples use [the `libc` crate][libc], which provides various --> <!-- type definitions for C types, among other things. If you’re trying these --> <!-- examples yourself, you’ll need to add `libc` to your `Cargo.toml`: --> <p>これらの例の多くは <a href="https://crates.io/crates/libc"><code>libc</code>クレート</a> を使っています。これは、主にCの様々な型の定義を提供するものです。 もしこれらの例を自分で試すのであれば、次のように <code>libc</code> を <code>Cargo.toml</code> に追加する必要があるでしょう。</p> <pre><code class="language-toml">[dependencies] libc = &quot;0.2.0&quot; </code></pre> <!-- and add `extern crate libc;` to your crate root. --> <p>そして、クレートのルートに <code>extern crate libc;</code> を追加しましょう。</p> <!-- ## Calling foreign functions --> <h2 id='他言語関数の呼出し' class='section-header'><a href='#他言語関数の呼出し'>他言語関数の呼出し</a></h2> <!-- The following is a minimal example of calling a foreign function which will --> <!-- compile if snappy is installed: --> <p>次のコードは、snappyがインストールされていればコンパイルできる他言語関数を呼び出す最小の例です。</p> <span class='rusttest'>#![feature(libc)] extern crate libc; use libc::size_t; #[link(name = &quot;snappy&quot;)] extern { fn snappy_max_compressed_length(source_length: size_t) -&gt; size_t; } fn main() { let x = unsafe { snappy_max_compressed_length(100) }; println!(&quot;max compressed length of a 100 byte buffer: {}&quot;, x); } </span><pre class='rust rust-example-rendered'> <span class='kw'>extern</span> <span class='kw'>crate</span> <span class='ident'>libc</span>; <span class='kw'>use</span> <span class='ident'>libc</span>::<span class='ident'>size_t</span>; <span class='attribute'>#[<span class='ident'>link</span>(<span class='ident'>name</span> <span class='op'>=</span> <span class='string'>&quot;snappy&quot;</span>)]</span> <span class='kw'>extern</span> { <span class='kw'>fn</span> <span class='ident'>snappy_max_compressed_length</span>(<span class='ident'>source_length</span>: <span class='ident'>size_t</span>) <span class='op'>-&gt;</span> <span class='ident'>size_t</span>; } <span class='kw'>fn</span> <span class='ident'>main</span>() { <span class='kw'>let</span> <span class='ident'>x</span> <span class='op'>=</span> <span class='kw'>unsafe</span> { <span class='ident'>snappy_max_compressed_length</span>(<span class='number'>100</span>) }; <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;max compressed length of a 100 byte buffer: {}&quot;</span>, <span class='ident'>x</span>); }</pre> <!-- The `extern` block is a list of function signatures in a foreign library, in --> <!-- this case with the platform's C ABI. The `#[link(...)]` attribute is used to --> <!-- instruct the linker to link against the snappy library so the symbols are --> <!-- resolved. --> <p><code>extern</code> ブロックは他言語ライブラリの中の関数のシグネチャ、この例ではそのプラットフォーム上のC ABIによるもののリストです。 <code>#[link(...)]</code> アトリビュートは、シンボルが解決できるように、リンカに対してsnappyのライブラリをリンクするよう指示するために使われています。</p> <!-- Foreign functions are assumed to be unsafe so calls to them need to be wrapped --> <!-- with `unsafe {}` as a promise to the compiler that everything contained within --> <!-- truly is safe. C libraries often expose interfaces that aren't thread-safe, and --> <!-- almost any function that takes a pointer argument isn't valid for all possible --> <!-- inputs since the pointer could be dangling, and raw pointers fall outside of --> <!-- Rust's safe memory model. --> <p>他言語関数はアンセーフとみなされるので、それらを呼び出すには、この中に含まれているすべてのものが本当に安全であるということをコンパイラに対して約束するために、 <code>unsafe {}</code> で囲まなければなりません。 Cライブラリは、スレッドセーフでないインターフェイスを公開していることがありますし、ポインタを引数に取る関数のほとんどは、ポインタがダングリングポインタになる可能性を有しているので、すべての入力に対して有効なわけではありません。そして、生ポインタはRustの安全なメモリモデルから外れてしまいます。</p> <!-- When declaring the argument types to a foreign function, the Rust compiler can --> <!-- not check if the declaration is correct, so specifying it correctly is part of --> <!-- keeping the binding correct at runtime. --> <p>他言語関数について引数の型を宣言するとき、Rustのコンパイラはその宣言が正しいかどうかを確認することができません。それを正しく指定することは実行時にバインディングを正しく動作させるために必要なことです。</p> <!-- The `extern` block can be extended to cover the entire snappy API: --> <p><code>extern</code> ブロックはsnappyのAPI全体をカバーするように拡張することができます。</p> <span class='rusttest'>#![feature(libc)] extern crate libc; use libc::{c_int, size_t}; #[link(name = &quot;snappy&quot;)] extern { fn snappy_compress(input: *const u8, input_length: size_t, compressed: *mut u8, compressed_length: *mut size_t) -&gt; c_int; fn snappy_uncompress(compressed: *const u8, compressed_length: size_t, uncompressed: *mut u8, uncompressed_length: *mut size_t) -&gt; c_int; fn snappy_max_compressed_length(source_length: size_t) -&gt; size_t; fn snappy_uncompressed_length(compressed: *const u8, compressed_length: size_t, result: *mut size_t) -&gt; c_int; fn snappy_validate_compressed_buffer(compressed: *const u8, compressed_length: size_t) -&gt; c_int; } fn main() {} </span><pre class='rust rust-example-rendered'> <span class='kw'>extern</span> <span class='kw'>crate</span> <span class='ident'>libc</span>; <span class='kw'>use</span> <span class='ident'>libc</span>::{<span class='ident'>c_int</span>, <span class='ident'>size_t</span>}; <span class='attribute'>#[<span class='ident'>link</span>(<span class='ident'>name</span> <span class='op'>=</span> <span class='string'>&quot;snappy&quot;</span>)]</span> <span class='kw'>extern</span> { <span class='kw'>fn</span> <span class='ident'>snappy_compress</span>(<span class='ident'>input</span>: <span class='op'>*</span><span class='kw'>const</span> <span class='ident'>u8</span>, <span class='ident'>input_length</span>: <span class='ident'>size_t</span>, <span class='ident'>compressed</span>: <span class='op'>*</span><span class='kw-2'>mut</span> <span class='ident'>u8</span>, <span class='ident'>compressed_length</span>: <span class='op'>*</span><span class='kw-2'>mut</span> <span class='ident'>size_t</span>) <span class='op'>-&gt;</span> <span class='ident'>c_int</span>; <span class='kw'>fn</span> <span class='ident'>snappy_uncompress</span>(<span class='ident'>compressed</span>: <span class='op'>*</span><span class='kw'>const</span> <span class='ident'>u8</span>, <span class='ident'>compressed_length</span>: <span class='ident'>size_t</span>, <span class='ident'>uncompressed</span>: <span class='op'>*</span><span class='kw-2'>mut</span> <span class='ident'>u8</span>, <span class='ident'>uncompressed_length</span>: <span class='op'>*</span><span class='kw-2'>mut</span> <span class='ident'>size_t</span>) <span class='op'>-&gt;</span> <span class='ident'>c_int</span>; <span class='kw'>fn</span> <span class='ident'>snappy_max_compressed_length</span>(<span class='ident'>source_length</span>: <span class='ident'>size_t</span>) <span class='op'>-&gt;</span> <span class='ident'>size_t</span>; <span class='kw'>fn</span> <span class='ident'>snappy_uncompressed_length</span>(<span class='ident'>compressed</span>: <span class='op'>*</span><span class='kw'>const</span> <span class='ident'>u8</span>, <span class='ident'>compressed_length</span>: <span class='ident'>size_t</span>, <span class='ident'>result</span>: <span class='op'>*</span><span class='kw-2'>mut</span> <span class='ident'>size_t</span>) <span class='op'>-&gt;</span> <span class='ident'>c_int</span>; <span class='kw'>fn</span> <span class='ident'>snappy_validate_compressed_buffer</span>(<span class='ident'>compressed</span>: <span class='op'>*</span><span class='kw'>const</span> <span class='ident'>u8</span>, <span class='ident'>compressed_length</span>: <span class='ident'>size_t</span>) <span class='op'>-&gt;</span> <span class='ident'>c_int</span>; }</pre> <!-- # Creating a safe interface --> <h1 id='安全なインターフェイスの作成' class='section-header'><a href='#安全なインターフェイスの作成'>安全なインターフェイスの作成</a></h1> <!-- The raw C API needs to be wrapped to provide memory safety and make use of higher-level concepts --> <!-- like vectors. A library can choose to expose only the safe, high-level interface and hide the unsafe --> <!-- internal details. --> <p>生のC APIは、メモリの安全性を提供し、ベクタのようなもっと高レベルの概念を使うようにラップしなければなりません。 ライブラリは安全で高レベルなインターフェイスのみを公開するように選択し、アンセーフな内部の詳細を隠すことができます。</p> <!-- Wrapping the functions which expect buffers involves using the `slice::raw` module to manipulate Rust --> <!-- vectors as pointers to memory. Rust's vectors are guaranteed to be a contiguous block of memory. The --> <!-- length is number of elements currently contained, and the capacity is the total size in elements of --> <!-- the allocated memory. The length is less than or equal to the capacity. --> <p>バッファを期待する関数をラップするには、Rustのベクタをメモリへのポインタとして操作するために <code>slice::raw</code> モジュールを使います。 Rustのベクタは隣接したメモリのブロックであることが保証されています。 その長さは現在含んでいる要素の数で、容量は割り当てられたメモリの要素の合計のサイズです。 長さは、容量以下です。</p> <span class='rusttest'>#![feature(libc)] extern crate libc; use libc::{c_int, size_t}; unsafe fn snappy_validate_compressed_buffer(_: *const u8, _: size_t) -&gt; c_int { 0 } fn main() {} pub fn validate_compressed_buffer(src: &amp;[u8]) -&gt; bool { unsafe { snappy_validate_compressed_buffer(src.as_ptr(), src.len() as size_t) == 0 } } </span><pre class='rust rust-example-rendered'> <span class='kw'>pub</span> <span class='kw'>fn</span> <span class='ident'>validate_compressed_buffer</span>(<span class='ident'>src</span>: <span class='kw-2'>&amp;</span>[<span class='ident'>u8</span>]) <span class='op'>-&gt;</span> <span class='ident'>bool</span> { <span class='kw'>unsafe</span> { <span class='ident'>snappy_validate_compressed_buffer</span>(<span class='ident'>src</span>.<span class='ident'>as_ptr</span>(), <span class='ident'>src</span>.<span class='ident'>len</span>() <span class='kw'>as</span> <span class='ident'>size_t</span>) <span class='op'>==</span> <span class='number'>0</span> } }</pre> <!-- The `validate_compressed_buffer` wrapper above makes use of an `unsafe` block, but it makes the --> <!-- guarantee that calling it is safe for all inputs by leaving off `unsafe` from the function --> <!-- signature. --> <p>上の <code>validate_compressed_buffer</code> ラッパは <code>unsafe</code> ブロックを使っていますが、関数のシグネチャを <code>unsafe</code> から外すことによって、その呼出しがすべての入力に対して安全であることが保証されています。</p> <!-- The `snappy_compress` and `snappy_uncompress` functions are more complex, since a buffer has to be --> <!-- allocated to hold the output too. --> <p>結果を保持するようにバッファを割り当てなければならないため、 <code>snappy_compress</code> 関数と <code>snappy_uncompress</code> 関数はもっと複雑です。</p> <!-- The `snappy_max_compressed_length` function can be used to allocate a vector with the maximum --> <!-- required capacity to hold the compressed output. The vector can then be passed to the --> <!-- `snappy_compress` function as an output parameter. An output parameter is also passed to retrieve --> <!-- the true length after compression for setting the length. --> <p><code>snappy_max_compressed_length</code> 関数は、圧縮後の結果を保持するために必要な最大の容量のベクタを割り当てるために使うことができます。 そして、そのベクタは結果を受け取るための引数として<code>snappy_compress</code>関数に渡されます。 結果を受け取るための引数は、長さをセットするために、圧縮後の本当の長さを取得するためにも渡されます。</p> <span class='rusttest'>#![feature(libc)] extern crate libc; use libc::{size_t, c_int}; unsafe fn snappy_compress(a: *const u8, b: size_t, c: *mut u8, d: *mut size_t) -&gt; c_int { 0 } unsafe fn snappy_max_compressed_length(a: size_t) -&gt; size_t { a } fn main() {} pub fn compress(src: &amp;[u8]) -&gt; Vec&lt;u8&gt; { unsafe { let srclen = src.len() as size_t; let psrc = src.as_ptr(); let mut dstlen = snappy_max_compressed_length(srclen); let mut dst = Vec::with_capacity(dstlen as usize); let pdst = dst.as_mut_ptr(); snappy_compress(psrc, srclen, pdst, &amp;mut dstlen); dst.set_len(dstlen as usize); dst } } </span><pre class='rust rust-example-rendered'> <span class='kw'>pub</span> <span class='kw'>fn</span> <span class='ident'>compress</span>(<span class='ident'>src</span>: <span class='kw-2'>&amp;</span>[<span class='ident'>u8</span>]) <span class='op'>-&gt;</span> <span class='ident'>Vec</span><span class='op'>&lt;</span><span class='ident'>u8</span><span class='op'>&gt;</span> { <span class='kw'>unsafe</span> { <span class='kw'>let</span> <span class='ident'>srclen</span> <span class='op'>=</span> <span class='ident'>src</span>.<span class='ident'>len</span>() <span class='kw'>as</span> <span class='ident'>size_t</span>; <span class='kw'>let</span> <span class='ident'>psrc</span> <span class='op'>=</span> <span class='ident'>src</span>.<span class='ident'>as_ptr</span>(); <span class='kw'>let</span> <span class='kw-2'>mut</span> <span class='ident'>dstlen</span> <span class='op'>=</span> <span class='ident'>snappy_max_compressed_length</span>(<span class='ident'>srclen</span>); <span class='kw'>let</span> <span class='kw-2'>mut</span> <span class='ident'>dst</span> <span class='op'>=</span> <span class='ident'>Vec</span>::<span class='ident'>with_capacity</span>(<span class='ident'>dstlen</span> <span class='kw'>as</span> <span class='ident'>usize</span>); <span class='kw'>let</span> <span class='ident'>pdst</span> <span class='op'>=</span> <span class='ident'>dst</span>.<span class='ident'>as_mut_ptr</span>(); <span class='ident'>snappy_compress</span>(<span class='ident'>psrc</span>, <span class='ident'>srclen</span>, <span class='ident'>pdst</span>, <span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='ident'>dstlen</span>); <span class='ident'>dst</span>.<span class='ident'>set_len</span>(<span class='ident'>dstlen</span> <span class='kw'>as</span> <span class='ident'>usize</span>); <span class='ident'>dst</span> } }</pre> <!-- Decompression is similar, because snappy stores the uncompressed size as part of the compression --> <!-- format and `snappy_uncompressed_length` will retrieve the exact buffer size required. --> <p>snappyは展開後のサイズを圧縮フォーマットの一部として保存していて、 <code>snappy_uncompressed_length</code> が必要となるバッファの正確なサイズを取得するため、展開も同様です。</p> <span class='rusttest'>#![feature(libc)] extern crate libc; use libc::{size_t, c_int}; unsafe fn snappy_uncompress(compressed: *const u8, compressed_length: size_t, uncompressed: *mut u8, uncompressed_length: *mut size_t) -&gt; c_int { 0 } unsafe fn snappy_uncompressed_length(compressed: *const u8, compressed_length: size_t, result: *mut size_t) -&gt; c_int { 0 } fn main() {} pub fn uncompress(src: &amp;[u8]) -&gt; Option&lt;Vec&lt;u8&gt;&gt; { unsafe { let srclen = src.len() as size_t; let psrc = src.as_ptr(); let mut dstlen: size_t = 0; snappy_uncompressed_length(psrc, srclen, &amp;mut dstlen); let mut dst = Vec::with_capacity(dstlen as usize); let pdst = dst.as_mut_ptr(); if snappy_uncompress(psrc, srclen, pdst, &amp;mut dstlen) == 0 { dst.set_len(dstlen as usize); Some(dst) } else { None // SNAPPY_INVALID_INPUT } } } </span><pre class='rust rust-example-rendered'> <span class='kw'>pub</span> <span class='kw'>fn</span> <span class='ident'>uncompress</span>(<span class='ident'>src</span>: <span class='kw-2'>&amp;</span>[<span class='ident'>u8</span>]) <span class='op'>-&gt;</span> <span class='prelude-ty'>Option</span><span class='op'>&lt;</span><span class='ident'>Vec</span><span class='op'>&lt;</span><span class='ident'>u8</span><span class='op'>&gt;&gt;</span> { <span class='kw'>unsafe</span> { <span class='kw'>let</span> <span class='ident'>srclen</span> <span class='op'>=</span> <span class='ident'>src</span>.<span class='ident'>len</span>() <span class='kw'>as</span> <span class='ident'>size_t</span>; <span class='kw'>let</span> <span class='ident'>psrc</span> <span class='op'>=</span> <span class='ident'>src</span>.<span class='ident'>as_ptr</span>(); <span class='kw'>let</span> <span class='kw-2'>mut</span> <span class='ident'>dstlen</span>: <span class='ident'>size_t</span> <span class='op'>=</span> <span class='number'>0</span>; <span class='ident'>snappy_uncompressed_length</span>(<span class='ident'>psrc</span>, <span class='ident'>srclen</span>, <span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='ident'>dstlen</span>); <span class='kw'>let</span> <span class='kw-2'>mut</span> <span class='ident'>dst</span> <span class='op'>=</span> <span class='ident'>Vec</span>::<span class='ident'>with_capacity</span>(<span class='ident'>dstlen</span> <span class='kw'>as</span> <span class='ident'>usize</span>); <span class='kw'>let</span> <span class='ident'>pdst</span> <span class='op'>=</span> <span class='ident'>dst</span>.<span class='ident'>as_mut_ptr</span>(); <span class='kw'>if</span> <span class='ident'>snappy_uncompress</span>(<span class='ident'>psrc</span>, <span class='ident'>srclen</span>, <span class='ident'>pdst</span>, <span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='ident'>dstlen</span>) <span class='op'>==</span> <span class='number'>0</span> { <span class='ident'>dst</span>.<span class='ident'>set_len</span>(<span class='ident'>dstlen</span> <span class='kw'>as</span> <span class='ident'>usize</span>); <span class='prelude-val'>Some</span>(<span class='ident'>dst</span>) } <span class='kw'>else</span> { <span class='prelude-val'>None</span> <span class='comment'>// SNAPPY_INVALID_INPUT</span> } } }</pre> <!-- For reference, the examples used here are also available as a [library on --> <!-- GitHub](https://github.com/thestinger/rust-snappy). --> <p>参考のために、ここで使った例は <a href="https://github.com/thestinger/rust-snappy">GitHub上のライブラリ</a> としても置いておきます。</p> <!-- # Destructors --> <h1 id='デストラクタ' class='section-header'><a href='#デストラクタ'>デストラクタ</a></h1> <!-- Foreign libraries often hand off ownership of resources to the calling code. --> <!-- When this occurs, we must use Rust's destructors to provide safety and guarantee --> <!-- the release of these resources (especially in the case of panic). --> <p>他言語ライブラリはリソースの所有権を呼出先のコードに手渡してしまうことがあります。 そういうことが起きる場合には、安全性を提供し、それらのリソースが解放されることを保証するために、Rustのデストラクタを使わなければなりません(特にパニックした場合)。</p> <!-- For more about destructors, see the [Drop trait](../std/ops/trait.Drop.html). --> <p>デストラクタについて詳しくは、<a href="../std/ops/trait.Drop.html">Dropトレイト</a>を見てください。</p> <!-- # Callbacks from C code to Rust functions --> <h1 id='cのコードからrustの関数へのコールバック' class='section-header'><a href='#cのコードからrustの関数へのコールバック'>CのコードからRustの関数へのコールバック</a></h1> <!-- Some external libraries require the usage of callbacks to report back their --> <!-- current state or intermediate data to the caller. --> <!-- It is possible to pass functions defined in Rust to an external library. --> <!-- The requirement for this is that the callback function is marked as `extern` --> <!-- with the correct calling convention to make it callable from C code. --> <p>外部のライブラリの中には、現在の状況や中間的なデータを呼出元に報告するためにコールバックを使わなければならないものがあります。 Rustで定義された関数を外部のライブラリに渡すことは可能です。 これをするために必要なのは、Cのコードから呼び出すことができるように正しい呼出規則に従って、コールバック関数を <code>extern</code> としてマークしておくことです。</p> <!-- The callback function can then be sent through a registration call --> <!-- to the C library and afterwards be invoked from there. --> <p>そして、登録呼出しを通じてコールバック関数をCのライブラリに送ることができるようになり、後でそれらから呼び出すことができるようになります。</p> <!-- A basic example is: --> <p>基本的な例は次のとおりです。</p> <!-- Rust code: --> <p>これがRustのコードです。</p> <span class='rusttest'>extern fn callback(a: i32) { println!(&quot;I&#39;m called from C with value {0}&quot;, a); } #[link(name = &quot;extlib&quot;)] extern { fn register_callback(cb: extern fn(i32)) -&gt; i32; fn trigger_callback(); } fn main() { unsafe { register_callback(callback); // trigger_callback(); // Triggers the callback trigger_callback(); // コールバックをトリガする } } </span><pre class='rust rust-example-rendered'> <span class='kw'>extern</span> <span class='kw'>fn</span> <span class='ident'>callback</span>(<span class='ident'>a</span>: <span class='ident'>i32</span>) { <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;I&#39;m called from C with value {0}&quot;</span>, <span class='ident'>a</span>); } <span class='attribute'>#[<span class='ident'>link</span>(<span class='ident'>name</span> <span class='op'>=</span> <span class='string'>&quot;extlib&quot;</span>)]</span> <span class='kw'>extern</span> { <span class='kw'>fn</span> <span class='ident'>register_callback</span>(<span class='ident'>cb</span>: <span class='kw'>extern</span> <span class='kw'>fn</span>(<span class='ident'>i32</span>)) <span class='op'>-&gt;</span> <span class='ident'>i32</span>; <span class='kw'>fn</span> <span class='ident'>trigger_callback</span>(); } <span class='kw'>fn</span> <span class='ident'>main</span>() { <span class='kw'>unsafe</span> { <span class='ident'>register_callback</span>(<span class='ident'>callback</span>); <span class='ident'>trigger_callback</span>(); <span class='comment'>// コールバックをトリガする</span> } }</pre> <!-- C code: --> <p>これがCのコードです。</p> <pre><code class="language-c">typedef void (*rust_callback)(int32_t); rust_callback cb; int32_t register_callback(rust_callback callback) { cb = callback; return 1; } void trigger_callback() { cb(7); // Rustのcallback(7)を呼び出す } </code></pre> <!-- In this example Rust's `main()` will call `trigger_callback()` in C, --> <!-- which would, in turn, call back to `callback()` in Rust. --> <p>この例では、Rustの <code>main()</code> がCの <code>trigger_callback()</code> を呼び出し、今度はそれが、Rustの <code>callback()</code> をコールバックしています。</p> <!-- ## Targeting callbacks to Rust objects --> <h2 id='rustのオブジェクトを対象にしたコールバック' class='section-header'><a href='#rustのオブジェクトを対象にしたコールバック'>Rustのオブジェクトを対象にしたコールバック</a></h2> <!-- The former example showed how a global function can be called from C code. --> <!-- However it is often desired that the callback is targeted to a special --> <!-- Rust object. This could be the object that represents the wrapper for the --> <!-- respective C object. --> <p>先程の例では、グローバルな関数をCのコードから呼ぶための方法を示してきました。 しかし、特別なRustのオブジェクトをコールバックの対象にしたいことがあります。 これは、そのオブジェクトをそれぞれCのオブジェクトのラッパとして表現することで可能になります。</p> <!-- This can be achieved by passing an raw pointer to the object down to the --> <!-- C library. The C library can then include the pointer to the Rust object in --> <!-- the notification. This will allow the callback to unsafely access the --> <!-- referenced Rust object. --> <p>これは、そのオブジェクトへの生ポインタをCライブラリに渡すことで実現できます。 そして、CのライブラリはRustのオブジェクトへのポインタをその通知の中に含むことができるようになります。 これにより、そのコールバックは参照されるRustのオブジェクトにアンセーフな形でアクセスできるようになります。</p> <!-- Rust code: --> <p>これがRustのコードです。</p> <span class='rusttest'>#[repr(C)] struct RustObject { a: i32, // other members // その他のメンバ } extern &quot;C&quot; fn callback(target: *mut RustObject, a: i32) { println!(&quot;I&#39;m called from C with value {0}&quot;, a); unsafe { // Update the value in RustObject with the value received from the callback // コールバックから受け取った値でRustObjectの中の値をアップデートする (*target).a = a; } } #[link(name = &quot;extlib&quot;)] extern { fn register_callback(target: *mut RustObject, cb: extern fn(*mut RustObject, i32)) -&gt; i32; fn trigger_callback(); } fn main() { // Create the object that will be referenced in the callback // コールバックから参照されるオブジェクトを作成する let mut rust_object = Box::new(RustObject { a: 5 }); unsafe { register_callback(&amp;mut *rust_object, callback); trigger_callback(); } } </span><pre class='rust rust-example-rendered'> <span class='attribute'>#[<span class='ident'>repr</span>(<span class='ident'>C</span>)]</span> <span class='kw'>struct</span> <span class='ident'>RustObject</span> { <span class='ident'>a</span>: <span class='ident'>i32</span>, <span class='comment'>// その他のメンバ</span> } <span class='kw'>extern</span> <span class='string'>&quot;C&quot;</span> <span class='kw'>fn</span> <span class='ident'>callback</span>(<span class='ident'>target</span>: <span class='op'>*</span><span class='kw-2'>mut</span> <span class='ident'>RustObject</span>, <span class='ident'>a</span>: <span class='ident'>i32</span>) { <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;I&#39;m called from C with value {0}&quot;</span>, <span class='ident'>a</span>); <span class='kw'>unsafe</span> { <span class='comment'>// コールバックから受け取った値でRustObjectの中の値をアップデートする</span> (<span class='op'>*</span><span class='ident'>target</span>).<span class='ident'>a</span> <span class='op'>=</span> <span class='ident'>a</span>; } } <span class='attribute'>#[<span class='ident'>link</span>(<span class='ident'>name</span> <span class='op'>=</span> <span class='string'>&quot;extlib&quot;</span>)]</span> <span class='kw'>extern</span> { <span class='kw'>fn</span> <span class='ident'>register_callback</span>(<span class='ident'>target</span>: <span class='op'>*</span><span class='kw-2'>mut</span> <span class='ident'>RustObject</span>, <span class='ident'>cb</span>: <span class='kw'>extern</span> <span class='kw'>fn</span>(<span class='op'>*</span><span class='kw-2'>mut</span> <span class='ident'>RustObject</span>, <span class='ident'>i32</span>)) <span class='op'>-&gt;</span> <span class='ident'>i32</span>; <span class='kw'>fn</span> <span class='ident'>trigger_callback</span>(); } <span class='kw'>fn</span> <span class='ident'>main</span>() { <span class='comment'>// コールバックから参照されるオブジェクトを作成する</span> <span class='kw'>let</span> <span class='kw-2'>mut</span> <span class='ident'>rust_object</span> <span class='op'>=</span> <span class='ident'>Box</span>::<span class='ident'>new</span>(<span class='ident'>RustObject</span> { <span class='ident'>a</span>: <span class='number'>5</span> }); <span class='kw'>unsafe</span> { <span class='ident'>register_callback</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='op'>*</span><span class='ident'>rust_object</span>, <span class='ident'>callback</span>); <span class='ident'>trigger_callback</span>(); } }</pre> <!-- C code: --> <p>これがCのコードです。</p> <pre><code class="language-c">typedef void (*rust_callback)(void*, int32_t); void* cb_target; rust_callback cb; int32_t register_callback(void* callback_target, rust_callback callback) { cb_target = callback_target; cb = callback; return 1; } void trigger_callback() { cb(cb_target, 7); // Rustのcallback(&amp;rustObject, 7)を呼び出す } </code></pre> <!-- ## Asynchronous callbacks --> <h2 id='非同期コールバック' class='section-header'><a href='#非同期コールバック'>非同期コールバック</a></h2> <!-- In the previously given examples the callbacks are invoked as a direct reaction --> <!-- to a function call to the external C library. --> <!-- The control over the current thread is switched from Rust to C to Rust for the --> <!-- execution of the callback, but in the end the callback is executed on the --> <!-- same thread that called the function which triggered the callback. --> <p>先程の例では、コールバックは外部のCライブラリへの関数呼出しに対する直接の反応として呼びだされました。 実行中のスレッドの制御はコールバックの実行のためにRustからCへ、そしてRustへと切り替わりますが、最後には、コールバックはコールバックを引き起こした関数を呼び出したものと同じスレッドで実行されます。</p> <!-- Things get more complicated when the external library spawns its own threads --> <!-- and invokes callbacks from there. --> <!-- In these cases access to Rust data structures inside the callbacks is --> <!-- especially unsafe and proper synchronization mechanisms must be used. --> <!-- Besides classical synchronization mechanisms like mutexes, one possibility in --> <!-- Rust is to use channels (in `std::sync::mpsc`) to forward data from the C --> <!-- thread that invoked the callback into a Rust thread. --> <p>外部のライブラリが独自のスレッドを生成し、そこからコールバックを呼び出すときには、事態はもっと複雑になります。 そのような場合、コールバックの中のRustのデータ構造へのアクセスは特にアンセーフであり、適切な同期メカニズムを使わなければなりません。 ミューテックスのような古典的な同期メカニズムの他にも、Rustではコールバックを呼び出したCのスレッドからRustのスレッドにデータを転送するために( <code>std::sync::mpsc</code> の中の)チャネルを使うという手もあります。</p> <!-- If an asynchronous callback targets a special object in the Rust address space --> <!-- it is also absolutely necessary that no more callbacks are performed by the --> <!-- C library after the respective Rust object gets destroyed. --> <!-- This can be achieved by unregistering the callback in the object's --> <!-- destructor and designing the library in a way that guarantees that no --> <!-- callback will be performed after deregistration. --> <p>もし、非同期のコールバックがRustのアドレス空間の中の特別なオブジェクトを対象としていれば、それぞれのRustのオブジェクトが破壊された後、Cのライブラリからそれ以上コールバックが実行されないようにすることが絶対に必要です。 これは、オブジェクトのデストラクタでコールバックの登録を解除し、登録解除後にコールバックが実行されないようにライブラリを設計することで実現できます。</p> <!-- # Linking --> <h1 id='リンク' class='section-header'><a href='#リンク'>リンク</a></h1> <!-- The `link` attribute on `extern` blocks provides the basic building block for --> <!-- instructing rustc how it will link to native libraries. There are two accepted --> <!-- forms of the link attribute today: --> <p><code>extern</code> ブロックの中の <code>link</code> アトリビュートは、rustcに対してネイティブライブラリをどのようにリンクするかを指示するための基本的な構成ブロックです。 今のところ、2つの形式のlinkアトリビュートが認められています。</p> <!-- * `#[link(name = "foo")]` --> <!-- * `#[link(name = "foo", kind = "bar")]` --> <ul> <li><code>#[link(name = &quot;foo&quot;)]</code></li> <li><code>#[link(name = &quot;foo&quot;, kind = &quot;bar&quot;)]</code></li> </ul> <!-- In both of these cases, `foo` is the name of the native library that we're --> <!-- linking to, and in the second case `bar` is the type of native library that the --> <!-- compiler is linking to. There are currently three known types of native --> <!-- libraries: --> <p>これらのどちらの形式でも、 <code>foo</code> はリンクするネイティブライブラリの名前で、2つ目の形式の <code>bar</code> はコンパイラがリンクするネイティブライブラリの種類です。 3つのネイティブライブラリの種類が知られています。</p> <!-- * Dynamic - `#[link(name = "readline")]` --> <!-- * Static - `#[link(name = "my_build_dependency", kind = "static")]` --> <!-- * Frameworks - `#[link(name = "CoreFoundation", kind = "framework")]` --> <ul> <li>ダイナミック - <code>#[link(name = &quot;readline&quot;)]</code></li> <li>スタティック - <code>#[link(name = &quot;my_build_dependency&quot;, kind = &quot;static&quot;)]</code></li> <li>フレームワーク - <code>#[link(name = &quot;CoreFoundation&quot;, kind = &quot;framework&quot;)]</code></li> </ul> <!-- Note that frameworks are only available on OSX targets. --> <p>フレームワークはOSXターゲットでのみ利用可能であることに注意しましょう。</p> <!-- The different `kind` values are meant to differentiate how the native library --> <!-- participates in linkage. From a linkage perspective, the Rust compiler creates --> <!-- two flavors of artifacts: partial (rlib/staticlib) and final (dylib/binary). --> <!-- Native dynamic library and framework dependencies are propagated to the final --> <!-- artifact boundary, while static library dependencies are not propagated at --> <!-- all, because the static libraries are integrated directly into the subsequent --> <!-- artifact. --> <p>異なる <code>kind</code> の値はリンク時のネイティブライブラリの使われ方の違いを意味します。 リンクの視点からすると、Rustコンパイラは2種類の生成物を作ります。 部分生成物(rlib/staticlib)と最終生成物(dylib/binary)です。 ネイティブダイナミックライブラリとフレームワークの依存関係は最終生成物を作るときまで伝播され解決されますが、スタティックライブラリの依存関係は全く伝えません。なぜなら、スタティックライブラリはその後に続く生成物に直接統合されてしまうからです。</p> <!-- A few examples of how this model can be used are: --> <p>このモデルをどのように使うことができるのかという例は次のとおりです。</p> <!-- * A native build dependency. Sometimes some C/C++ glue is needed when writing --> <!-- some Rust code, but distribution of the C/C++ code in a library format is just --> <!-- a burden. In this case, the code will be archived into `libfoo.a` and then the --> <!-- Rust crate would declare a dependency via `#[link(name = "foo", kind = --> <!-- "static")]`. --> <ul> <li>ネイティブビルドの依存関係。 ときどき、Rustのコードを書くときにC/C++のグルーが必要になりますが、ライブラリの形式でのC/C++のコードの配布は重荷でしかありません。 このような場合、 コードは <code>libfoo.a</code> にアーカイブされ、それからRustのクレートで <code>#[link(name = &quot;foo&quot;, kind = &quot;static&quot;)]</code> によって依存関係を宣言します。</li> </ul> <!-- Regardless of the flavor of output for the crate, the native static library --> <!-- will be included in the output, meaning that distribution of the native static --> <!-- library is not necessary. --> <p>クレートの成果物の種類にかかわらず、ネイティブスタティックライブラリは成果物に含まれます。これは、ネイティブスタティックライブラリの配布は不要だということを意味します。</p> <!-- * A normal dynamic dependency. Common system libraries (like `readline`) are --> <!-- available on a large number of systems, and often a static copy of these --> <!-- libraries cannot be found. When this dependency is included in a Rust crate, --> <!-- partial targets (like rlibs) will not link to the library, but when the rlib --> <!-- is included in a final target (like a binary), the native library will be --> <!-- linked in. --> <ul> <li> 通常のダイナミックな依存関係。 ( <code>readline</code> のような)一般的なシステムライブラリは多くのシステムで利用可能となっていますが、それらのライブラリのスタティックなコピーは見付からないことがしばしばあります。 この依存関係をRustのクレートに含めるときには、(rlibのような)部分生成物のターゲットはライブラリをリンクしませんが、(binaryのような)最終生成物にrlibを含めるときには、ネイティブライブラリはリンクされます。</li> </ul> <!-- On OSX, frameworks behave with the same semantics as a dynamic library. --> <p>OSXでは、フレームワークはダイナミックライブラリと同じ意味で振る舞います。</p> <!-- # Unsafe blocks --> <h1 id='アンセーフブロック' class='section-header'><a href='#アンセーフブロック'>アンセーフブロック</a></h1> <!-- Some operations, like dereferencing raw pointers or calling functions that have been marked --> <!-- unsafe are only allowed inside unsafe blocks. Unsafe blocks isolate unsafety and are a promise to --> <!-- the compiler that the unsafety does not leak out of the block. --> <p>生ポインタの参照外しやアンセーフであるとマークされた関数の呼出しなど、いくつかの作業はアンセーフブロックの中でのみ許されます。 アンセーフブロックはアンセーフ性を隔離し、コンパイラに対してアンセーフ性がブロックの外に漏れ出さないことを約束します。</p> <!-- Unsafe functions, on the other hand, advertise it to the world. An unsafe function is written like --> <!-- this: --> <p>一方、アンセーフな関数はそれを全世界に向けて広告します。 アンセーフな関数はこのように書きます。</p> <span class='rusttest'>fn main() { unsafe fn kaboom(ptr: *const i32) -&gt; i32 { *ptr } }</span><pre class='rust rust-example-rendered'> <span class='kw'>unsafe</span> <span class='kw'>fn</span> <span class='ident'>kaboom</span>(<span class='ident'>ptr</span>: <span class='op'>*</span><span class='kw'>const</span> <span class='ident'>i32</span>) <span class='op'>-&gt;</span> <span class='ident'>i32</span> { <span class='op'>*</span><span class='ident'>ptr</span> }</pre> <!-- This function can only be called from an `unsafe` block or another `unsafe` function. --> <p>この関数は <code>unsafe</code> ブロック又は他の <code>unsafe</code> な関数からのみ呼び出すことができます。</p> <!-- # Accessing foreign globals --> <h1 id='他言語のグローバル変数へのアクセス' class='section-header'><a href='#他言語のグローバル変数へのアクセス'>他言語のグローバル変数へのアクセス</a></h1> <!-- Foreign APIs often export a global variable which could do something like track --> <!-- global state. In order to access these variables, you declare them in `extern` --> <!-- blocks with the `static` keyword: --> <p>他言語APIはしばしばグローバルな状態を追跡するようなことをするためのグローバル変数をエクスポートします。 それらの値にアクセスするために、それらを <code>extern</code> ブロックの中で <code>static</code> キーワードを付けて宣言します。</p> <span class='rusttest'>#![feature(libc)] extern crate libc; #[link(name = &quot;readline&quot;)] extern { static rl_readline_version: libc::c_int; } fn main() { println!(&quot;You have readline version {} installed.&quot;, rl_readline_version as i32); } </span><pre class='rust rust-example-rendered'> <span class='kw'>extern</span> <span class='kw'>crate</span> <span class='ident'>libc</span>; <span class='attribute'>#[<span class='ident'>link</span>(<span class='ident'>name</span> <span class='op'>=</span> <span class='string'>&quot;readline&quot;</span>)]</span> <span class='kw'>extern</span> { <span class='kw'>static</span> <span class='ident'>rl_readline_version</span>: <span class='ident'>libc</span>::<span class='ident'>c_int</span>; } <span class='kw'>fn</span> <span class='ident'>main</span>() { <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;You have readline version {} installed.&quot;</span>, <span class='ident'>rl_readline_version</span> <span class='kw'>as</span> <span class='ident'>i32</span>); }</pre> <!-- Alternatively, you may need to alter global state provided by a foreign --> <!-- interface. To do this, statics can be declared with `mut` so we can mutate --> <!-- them. --> <p>あるいは、他言語インターフェイスが提供するグローバルな状態を変更しなければならないこともあるかもしれません。 これをするために、スタティックな値を変更することができるように <code>mut</code> 付きで宣言することができます。</p> <span class='rusttest'>#![feature(libc)] extern crate libc; use std::ffi::CString; use std::ptr; #[link(name = &quot;readline&quot;)] extern { static mut rl_prompt: *const libc::c_char; } fn main() { let prompt = CString::new(&quot;[my-awesome-shell] $&quot;).unwrap(); unsafe { rl_prompt = prompt.as_ptr(); println!(&quot;{:?}&quot;, rl_prompt); rl_prompt = ptr::null(); } } </span><pre class='rust rust-example-rendered'> <span class='kw'>extern</span> <span class='kw'>crate</span> <span class='ident'>libc</span>; <span class='kw'>use</span> <span class='ident'>std</span>::<span class='ident'>ffi</span>::<span class='ident'>CString</span>; <span class='kw'>use</span> <span class='ident'>std</span>::<span class='ident'>ptr</span>; <span class='attribute'>#[<span class='ident'>link</span>(<span class='ident'>name</span> <span class='op'>=</span> <span class='string'>&quot;readline&quot;</span>)]</span> <span class='kw'>extern</span> { <span class='kw'>static</span> <span class='kw-2'>mut</span> <span class='ident'>rl_prompt</span>: <span class='op'>*</span><span class='kw'>const</span> <span class='ident'>libc</span>::<span class='ident'>c_char</span>; } <span class='kw'>fn</span> <span class='ident'>main</span>() { <span class='kw'>let</span> <span class='ident'>prompt</span> <span class='op'>=</span> <span class='ident'>CString</span>::<span class='ident'>new</span>(<span class='string'>&quot;[my-awesome-shell] $&quot;</span>).<span class='ident'>unwrap</span>(); <span class='kw'>unsafe</span> { <span class='ident'>rl_prompt</span> <span class='op'>=</span> <span class='ident'>prompt</span>.<span class='ident'>as_ptr</span>(); <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;{:?}&quot;</span>, <span class='ident'>rl_prompt</span>); <span class='ident'>rl_prompt</span> <span class='op'>=</span> <span class='ident'>ptr</span>::<span class='ident'>null</span>(); } }</pre> <!-- Note that all interaction with a `static mut` is unsafe, both reading and --> <!-- writing. Dealing with global mutable state requires a great deal of care. --> <p><code>static mut</code> の付いた作用は全て、読込みと書込みの双方についてアンセーフであることに注意しましょう。 グローバルでミュータブルな状態の扱いには多大な注意が必要です。</p> <!-- # Foreign calling conventions --> <h1 id='他言語呼出規則' class='section-header'><a href='#他言語呼出規則'>他言語呼出規則</a></h1> <!-- Most foreign code exposes a C ABI, and Rust uses the platform's C calling convention by default when --> <!-- calling foreign functions. Some foreign functions, most notably the Windows API, use other calling --> <!-- conventions. Rust provides a way to tell the compiler which convention to use: --> <p>他言語で書かれたコードの多くはC ABIをエクスポートしていて、Rustは他言語関数の呼出しのときのデフォルトとしてそのプラットフォーム上のCの呼出規則を使います。 他言語関数の中には、特にWindows APIですが、他の呼出規則を使うものもあります。 Rustにはコンパイラに対してどの規則を使うかを教える方法があります。</p> <span class='rusttest'>#![feature(libc)] extern crate libc; #[cfg(all(target_os = &quot;win32&quot;, target_arch = &quot;x86&quot;))] #[link(name = &quot;kernel32&quot;)] #[allow(non_snake_case)] extern &quot;stdcall&quot; { fn SetEnvironmentVariableA(n: *const u8, v: *const u8) -&gt; libc::c_int; } fn main() { } </span><pre class='rust rust-example-rendered'> <span class='kw'>extern</span> <span class='kw'>crate</span> <span class='ident'>libc</span>; <span class='attribute'>#[<span class='ident'>cfg</span>(<span class='ident'>all</span>(<span class='ident'>target_os</span> <span class='op'>=</span> <span class='string'>&quot;win32&quot;</span>, <span class='ident'>target_arch</span> <span class='op'>=</span> <span class='string'>&quot;x86&quot;</span>))]</span> <span class='attribute'>#[<span class='ident'>link</span>(<span class='ident'>name</span> <span class='op'>=</span> <span class='string'>&quot;kernel32&quot;</span>)]</span> <span class='attribute'>#[<span class='ident'>allow</span>(<span class='ident'>non_snake_case</span>)]</span> <span class='kw'>extern</span> <span class='string'>&quot;stdcall&quot;</span> { <span class='kw'>fn</span> <span class='ident'>SetEnvironmentVariableA</span>(<span class='ident'>n</span>: <span class='op'>*</span><span class='kw'>const</span> <span class='ident'>u8</span>, <span class='ident'>v</span>: <span class='op'>*</span><span class='kw'>const</span> <span class='ident'>u8</span>) <span class='op'>-&gt;</span> <span class='ident'>libc</span>::<span class='ident'>c_int</span>; }</pre> <!-- This applies to the entire `extern` block. The list of supported ABI constraints --> <!-- are: --> <p>これは <code>extern</code> ブロック全体に適用されます。 サポートされているABIの規則は次のとおりです。</p> <ul> <li><code>stdcall</code></li> <li><code>aapcs</code></li> <li><code>cdecl</code></li> <li><code>fastcall</code></li> <li><code>Rust</code></li> <li><code>rust-intrinsic</code></li> <li><code>system</code></li> <li><code>C</code></li> <li><code>win64</code></li> </ul> <!-- Most of the abis in this list are self-explanatory, but the `system` abi may --> <!-- seem a little odd. This constraint selects whatever the appropriate ABI is for --> <!-- interoperating with the target's libraries. For example, on win32 with a x86 --> <!-- architecture, this means that the abi used would be `stdcall`. On x86_64, --> <!-- however, windows uses the `C` calling convention, so `C` would be used. This --> <!-- means that in our previous example, we could have used `extern "system" { ... }` --> <!-- to define a block for all windows systems, not just x86 ones. --> <p>このリストのABIのほとんどは名前のとおりですが、 <code>system</code> ABIは少し変わっています。 この規則はターゲットのライブラリを相互利用するために適切なABIを選択します。 例えば、x86アーキテクチャのWin32では、使われるABIは <code>stdcall</code> になります。 しかし、x86_64では、Windowsは <code>C</code> の呼出規則を使うので、 <code>C</code> が使われます。 先程の例で言えば、 <code>extern &quot;system&quot; { ... }</code> を使って、x86のためだけではなく全てのWindowsシステムのためのブロックを定義することができるということです。</p> <!-- # Interoperability with foreign code --> <h1 id='他言語コードの相互利用' class='section-header'><a href='#他言語コードの相互利用'>他言語コードの相互利用</a></h1> <!-- Rust guarantees that the layout of a `struct` is compatible with the platform's --> <!-- representation in C only if the `#[repr(C)]` attribute is applied to it. --> <!-- `#[repr(C, packed)]` can be used to lay out struct members without padding. --> <!-- `#[repr(C)]` can also be applied to an enum. --> <p><code>#[repr(C)]</code> アトリビュートが適用されている場合に限り、Rustは <code>struct</code> のレイアウトとそのプラットフォーム上のCでの表現方法との互換性を保証します。 <code>#[repr(C, packed)]</code> を使えば、パディングなしで構造体のメンバをレイアウトすることができます。 <code>#[repr(C)]</code> は列挙型にも適用することができます。</p> <!-- Rust's owned boxes (`Box<T>`) use non-nullable pointers as handles which point --> <!-- to the contained object. However, they should not be manually created because --> <!-- they are managed by internal allocators. References can safely be assumed to be --> <!-- non-nullable pointers directly to the type. However, breaking the borrow --> <!-- checking or mutability rules is not guaranteed to be safe, so prefer using raw --> <!-- pointers (`*`) if that's needed because the compiler can't make as many --> <!-- assumptions about them. --> <p>Rust独自のボックス( <code>Box&lt;T&gt;</code> )は包んでいるオブジェクトを指すハンドルとして非ヌルポインタを使います。 しかし、それらは内部のアロケータによって管理されるため、手で作るべきではありません。 参照は型を直接指す非ヌルポインタとみなすことが安全にできます。 しかし、借用チェックやミュータブルについてのルールが破られた場合、安全性は保証されません。生ポインタについてはコンパイラは借用チェックやミュータブルほどには仮定を置かないので、必要なときには、生ポインタ( <code>*</code> )を使いましょう。</p> <!-- Vectors and strings share the same basic memory layout, and utilities are --> <!-- available in the `vec` and `str` modules for working with C APIs. However, --> <!-- strings are not terminated with `\0`. If you need a NUL-terminated string for --> <!-- interoperability with C, you should use the `CString` type in the `std::ffi` --> <!-- module. --> <p>ベクタと文字列は基本的なメモリレイアウトを共有していて、 <code>vec</code> モジュールと <code>str</code> モジュールの中のユーティリティはC APIで扱うために使うことができます。 ただし、文字列は <code>\0</code> で終わりません。 Cと相互利用するためにNUL終端の文字列が必要であれば、 <code>std::ffi</code> モジュールの <code>CString</code> 型を使う必要があります。</p> <!-- The [`libc` crate on crates.io][libc] includes type aliases and function --> <!-- definitions for the C standard library in the `libc` module, and Rust links --> <!-- against `libc` and `libm` by default. --> <p><a href="https://crates.io/crates/libc">crates.ioの<code>libc</code>クレート</a> は <code>libc</code> モジュール内にCの標準ライブラリの型の別名や関数の定義を含んでいて、Rustは <code>libc</code> と <code>libm</code> をデフォルトでリンクします。</p> <!-- # The "nullable pointer optimization" --> <h1 id='ヌルになり得るポインタの最適化' class='section-header'><a href='#ヌルになり得るポインタの最適化'>「ヌルになり得るポインタの最適化」</a></h1> <!-- Certain types are defined to not be `null`. This includes references (`&T`, --> <!-- `&mut T`), boxes (`Box<T>`), and function pointers (`extern "abi" fn()`). --> <!-- When interfacing with C, pointers that might be null are often used. --> <!-- As a special case, a generic `enum` that contains exactly two variants, one of --> <!-- which contains no data and the other containing a single field, is eligible --> <!-- for the "nullable pointer optimization". When such an enum is instantiated --> <!-- with one of the non-nullable types, it is represented as a single pointer, --> <!-- and the non-data variant is represented as the null pointer. So --> <!-- `Option<extern "C" fn(c_int) -> c_int>` is how one represents a nullable --> <!-- function pointer using the C ABI. --> <p>いくつかの型は非 <code>null</code> であると定義されています。 このようなものには、参照( <code>&amp;T</code> 、 <code>&amp;mut T</code> )、ボックス( <code>Box&lt;T&gt;</code> )、そして関数ポインタ( <code>extern &quot;abi&quot; fn()</code> )があります。 Cとのインターフェイスにおいては、ヌルになり得るポインタが使われることがしばしばあります。 特別な場合として、ジェネリックな <code>enum</code> がちょうど2つのバリアントを持ち、そのうちの1つが値を持っていなくてもう1つが単一のフィールドを持っているとき、それは「ヌルになり得るポインタの最適化」の対象になります。 そのような列挙型が非ヌルの型でインスタンス化されたとき、それは単一のポインタとして表現され、データを持っていない方のバリアントはヌルポインタとして表現されます。 <code>Option&lt;extern &quot;C&quot; fn(c_int) -&gt; c_int&gt;</code> は、C ABIで使われるヌルになり得る関数ポインタの表現方法の1つです。</p> <!-- # Calling Rust code from C --> <h1 id='cからのrustのコードの呼出し' class='section-header'><a href='#cからのrustのコードの呼出し'>CからのRustのコードの呼出し</a></h1> <!-- You may wish to compile Rust code in a way so that it can be called from C. This is --> <!-- fairly easy, but requires a few things: --> <p>RustのコードをCから呼び出せる方法でコンパイルしたいときがあるかもしれません。 これは割と簡単ですが、いくつか必要なことがあります。</p> <span class='rusttest'>#[no_mangle] pub extern fn hello_rust() -&gt; *const u8 { &quot;Hello, world!\0&quot;.as_ptr() } fn main() {} </span><pre class='rust rust-example-rendered'> <span class='attribute'>#[<span class='ident'>no_mangle</span>]</span> <span class='kw'>pub</span> <span class='kw'>extern</span> <span class='kw'>fn</span> <span class='ident'>hello_rust</span>() <span class='op'>-&gt;</span> <span class='op'>*</span><span class='kw'>const</span> <span class='ident'>u8</span> { <span class='string'>&quot;Hello, world!\0&quot;</span>.<span class='ident'>as_ptr</span>() }</pre> <!-- The `extern` makes this function adhere to the C calling convention, as --> <!-- discussed above in "[Foreign Calling --> <!-- Conventions](ffi.html#foreign-calling-conventions)". The `no_mangle` --> <!-- attribute turns off Rust's name mangling, so that it is easier to link to. --> <p><code>extern</code> は先程「 <a href="ffi.html#foreign-calling-conventions">他言語呼出規則</a> 」で議論したように、この関数をCの呼出規則に従うようにします。 <code>no_mangle</code> アトリビュートはRustによる名前のマングリングをオフにして、リンクしやすいようにします。</p> <!-- # FFI and panics --> <h1 id='ffiとパニック' class='section-header'><a href='#ffiとパニック'>FFIとパニック</a></h1> <!-- It’s important to be mindful of `panic!`s when working with FFI. A `panic!` --> <!-- across an FFI boundary is undefined behavior. If you’re writing code that may --> <!-- panic, you should run it in another thread, so that the panic doesn’t bubble up --> <!-- to C: --> <p>FFIを扱うときに <code>panic!</code> に注意することは重要です。 FFIの境界をまたぐ <code>panic!</code> の動作は未定義です。 もしあなたがパニックし得るコードを書いているのであれば、他のスレッドで実行して、パニックがCに波及しないようにすべきです。</p> <span class='rusttest'>use std::thread; #[no_mangle] pub extern fn oh_no() -&gt; i32 { let h = thread::spawn(|| { panic!(&quot;Oops!&quot;); }); match h.join() { Ok(_) =&gt; 1, Err(_) =&gt; 0, } } fn main() {} </span><pre class='rust rust-example-rendered'> <span class='kw'>use</span> <span class='ident'>std</span>::<span class='ident'>thread</span>; <span class='attribute'>#[<span class='ident'>no_mangle</span>]</span> <span class='kw'>pub</span> <span class='kw'>extern</span> <span class='kw'>fn</span> <span class='ident'>oh_no</span>() <span class='op'>-&gt;</span> <span class='ident'>i32</span> { <span class='kw'>let</span> <span class='ident'>h</span> <span class='op'>=</span> <span class='ident'>thread</span>::<span class='ident'>spawn</span>(<span class='op'>||</span> { <span class='macro'>panic</span><span class='macro'>!</span>(<span class='string'>&quot;Oops!&quot;</span>); }); <span class='kw'>match</span> <span class='ident'>h</span>.<span class='ident'>join</span>() { <span class='prelude-val'>Ok</span>(_) <span class='op'>=&gt;</span> <span class='number'>1</span>, <span class='prelude-val'>Err</span>(_) <span class='op'>=&gt;</span> <span class='number'>0</span>, } }</pre> <!-- # Representing opaque structs --> <h1 id='オペーク構造体の表現' class='section-header'><a href='#オペーク構造体の表現'>オペーク構造体の表現</a></h1> <!-- Sometimes, a C library wants to provide a pointer to something, but not let you --> <!-- know the internal details of the thing it wants. The simplest way is to use a --> <!-- `void *` argument: --> <p>ときどき、Cのライブラリが何かのポインタを要求してくるにもかかわらず、その要求されているものの内部的な詳細を教えてくれないことがあります。 最も単純な方法は <code>void *</code> 引数を使うことです。</p> <pre><code class="language-c">void foo(void *arg); void bar(void *arg); </code></pre> <!-- We can represent this in Rust with the `c_void` type: --> <p>Rustではこれを <code>c_void</code> 型で表現することができます。</p> <span class='rusttest'>#![feature(libc)] extern crate libc; extern &quot;C&quot; { pub fn foo(arg: *mut libc::c_void); pub fn bar(arg: *mut libc::c_void); } fn main() {} </span><pre class='rust rust-example-rendered'> <span class='kw'>extern</span> <span class='kw'>crate</span> <span class='ident'>libc</span>; <span class='kw'>extern</span> <span class='string'>&quot;C&quot;</span> { <span class='kw'>pub</span> <span class='kw'>fn</span> <span class='ident'>foo</span>(<span class='ident'>arg</span>: <span class='op'>*</span><span class='kw-2'>mut</span> <span class='ident'>libc</span>::<span class='ident'>c_void</span>); <span class='kw'>pub</span> <span class='kw'>fn</span> <span class='ident'>bar</span>(<span class='ident'>arg</span>: <span class='op'>*</span><span class='kw-2'>mut</span> <span class='ident'>libc</span>::<span class='ident'>c_void</span>); }</pre> <!-- This is a perfectly valid way of handling the situation. However, we can do a bit --> <!-- better. To solve this, some C libraries will instead create a `struct`, where --> <!-- the details and memory layout of the struct are private. This gives some amount --> <!-- of type safety. These structures are called ‘opaque’. Here’s an example, in C: --> <p>これはその状況に対処するための完全に正当な方法です。 しかし、もっとよい方法があります。 これを解決するために、いくつかのCライブラリでは、代わりに <code>struct</code> を作っています。そこでは構造体の詳細とメモリレイアウトはプライベートです。 これは型の安全性をいくらか満たします。 それらの構造体は「オペーク」と呼ばれます。 これがCによる例です。</p> <pre><code class="language-c">struct Foo; /* Fooは構造体だが、その内容は公開インターフェイスの一部ではない */ struct Bar; void foo(struct Foo *arg); void bar(struct Bar *arg); </code></pre> <!-- To do this in Rust, let’s create our own opaque types with `enum`: --> <p>これをRustで実現するために、<code>enum</code>で独自のオペーク型を作りましょう。</p> <span class='rusttest'>pub enum Foo {} pub enum Bar {} extern &quot;C&quot; { pub fn foo(arg: *mut Foo); pub fn bar(arg: *mut Bar); } fn main() {} </span><pre class='rust rust-example-rendered'> <span class='kw'>pub</span> <span class='kw'>enum</span> <span class='ident'>Foo</span> {} <span class='kw'>pub</span> <span class='kw'>enum</span> <span class='ident'>Bar</span> {} <span class='kw'>extern</span> <span class='string'>&quot;C&quot;</span> { <span class='kw'>pub</span> <span class='kw'>fn</span> <span class='ident'>foo</span>(<span class='ident'>arg</span>: <span class='op'>*</span><span class='kw-2'>mut</span> <span class='ident'>Foo</span>); <span class='kw'>pub</span> <span class='kw'>fn</span> <span class='ident'>bar</span>(<span class='ident'>arg</span>: <span class='op'>*</span><span class='kw-2'>mut</span> <span class='ident'>Bar</span>); }</pre> <!-- By using an `enum` with no variants, we create an opaque type that we can’t --> <!-- instantiate, as it has no variants. But because our `Foo` and `Bar` types are --> <!-- different, we’ll get type safety between the two of them, so we cannot --> <!-- accidentally pass a pointer to `Foo` to `bar()`. --> <p>バリアントなしの <code>enum</code> を使って、バリアントがないためにインスタンス化できないオペーク型を作ります。 しかし、 <code>Foo</code> 型と <code>Bar</code> 型は異なる型であり、2つものの間の型の安全性を満たすので、 <code>Foo</code> のポインタを間違って <code>bar()</code> に渡すことはなくなります。</p> <script type="text/javascript"> window.playgroundUrl = "https://play.rust-lang.org"; </script> <script src='rustbook.js'></script> <script src='playpen.js'></script> </div></div> </body> </html> <|start_filename|>docs/1.9/book/choosing-your-guarantees.html<|end_filename|> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="generator" content="rustdoc"> <title>保証を選ぶ</title> <link rel="stylesheet" type="text/css" href="rustbook.css"> <meta name="robots" content="noindex"> </head> <body class="rustdoc"> <!--[if lte IE 8]> <div class="warning"> This old browser is unsupported and will most likely display funky things. </div> <![endif]--> <div id="nav"> <button id="toggle-nav"> <span class="sr-only">Toggle navigation</span> <span class="bar"></span> <span class="bar"></span> <span class="bar"></span> </button> </div> <div id='toc' class='mobile-hidden'> <ul class='chapter'> <li><a href='README.html'><b>1.</b> Introduction</a> </li> <li><a href='getting-started.html'><b>2.</b> はじめる</a> </li> <li><a href='guessing-game.html'><b>3.</b> チュートリアル:数当てゲーム</a> </li> <li><a href='syntax-and-semantics.html'><b>4.</b> シンタックスとセマンティクス</a> <ul class='section'> <li><a href='variable-bindings.html'><b>4.1.</b> 変数束縛</a> </li> <li><a href='functions.html'><b>4.2.</b> 関数</a> </li> <li><a href='primitive-types.html'><b>4.3.</b> プリミティブ型</a> </li> <li><a href='comments.html'><b>4.4.</b> コメント</a> </li> <li><a href='if.html'><b>4.5.</b> if</a> </li> <li><a href='loops.html'><b>4.6.</b> ループ</a> </li> <li><a href='vectors.html'><b>4.7.</b> ベクタ</a> </li> <li><a href='ownership.html'><b>4.8.</b> 所有権</a> </li> <li><a href='references-and-borrowing.html'><b>4.9.</b> 参照と借用</a> </li> <li><a href='lifetimes.html'><b>4.10.</b> ライフタイム</a> </li> <li><a href='mutability.html'><b>4.11.</b> ミュータビリティ</a> </li> <li><a href='structs.html'><b>4.12.</b> 構造体</a> </li> <li><a href='enums.html'><b>4.13.</b> 列挙型</a> </li> <li><a href='match.html'><b>4.14.</b> マッチ</a> </li> <li><a href='patterns.html'><b>4.15.</b> パターン</a> </li> <li><a href='method-syntax.html'><b>4.16.</b> メソッド構文</a> </li> <li><a href='strings.html'><b>4.17.</b> 文字列</a> </li> <li><a href='generics.html'><b>4.18.</b> ジェネリクス</a> </li> <li><a href='traits.html'><b>4.19.</b> トレイト</a> </li> <li><a href='drop.html'><b>4.20.</b> Drop</a> </li> <li><a href='if-let.html'><b>4.21.</b> if let</a> </li> <li><a href='trait-objects.html'><b>4.22.</b> トレイトオブジェクト</a> </li> <li><a href='closures.html'><b>4.23.</b> クロージャ</a> </li> <li><a href='ufcs.html'><b>4.24.</b> 共通の関数呼出構文</a> </li> <li><a href='crates-and-modules.html'><b>4.25.</b> クレートとモジュール</a> </li> <li><a href='const-and-static.html'><b>4.26.</b> `const` と `static`</a> </li> <li><a href='attributes.html'><b>4.27.</b> アトリビュート</a> </li> <li><a href='type-aliases.html'><b>4.28.</b> `type` エイリアス</a> </li> <li><a href='casting-between-types.html'><b>4.29.</b> 型間のキャスト</a> </li> <li><a href='associated-types.html'><b>4.30.</b> 関連型</a> </li> <li><a href='unsized-types.html'><b>4.31.</b> サイズ不定型</a> </li> <li><a href='operators-and-overloading.html'><b>4.32.</b> 演算子とオーバーロード</a> </li> <li><a href='deref-coercions.html'><b>4.33.</b> Derefによる型強制</a> </li> <li><a href='macros.html'><b>4.34.</b> マクロ</a> </li> <li><a href='raw-pointers.html'><b>4.35.</b> 生ポインタ</a> </li> <li><a href='unsafe.html'><b>4.36.</b> `unsafe`</a> </li> </ul> </li> <li><a href='effective-rust.html'><b>5.</b> Effective Rust</a> <ul class='section'> <li><a href='the-stack-and-the-heap.html'><b>5.1.</b> スタックとヒープ</a> </li> <li><a href='testing.html'><b>5.2.</b> テスト</a> </li> <li><a href='conditional-compilation.html'><b>5.3.</b> 条件付きコンパイル</a> </li> <li><a href='documentation.html'><b>5.4.</b> ドキュメント</a> </li> <li><a href='iterators.html'><b>5.5.</b> イテレータ</a> </li> <li><a href='concurrency.html'><b>5.6.</b> 並行性</a> </li> <li><a href='error-handling.html'><b>5.7.</b> エラーハンドリング</a> </li> <li><a class='active' href='choosing-your-guarantees.html'><b>5.8.</b> 保証を選ぶ</a> </li> <li><a href='ffi.html'><b>5.9.</b> 他言語関数インターフェース</a> </li> <li><a href='borrow-and-asref.html'><b>5.10.</b> BorrowとAsRef</a> </li> <li><a href='release-channels.html'><b>5.11.</b> リリースチャネル</a> </li> <li><a href='using-rust-without-the-standard-library.html'><b>5.12.</b> 標準ライブラリ無しでRustを使う</a> </li> </ul> </li> <li><a href='nightly-rust.html'><b>6.</b> Nightly Rust</a> <ul class='section'> <li><a href='compiler-plugins.html'><b>6.1.</b> コンパイラプラグイン</a> </li> <li><a href='inline-assembly.html'><b>6.2.</b> インラインアセンブリ</a> </li> <li><a href='no-stdlib.html'><b>6.3.</b> No stdlib</a> </li> <li><a href='intrinsics.html'><b>6.4.</b> Intrinsic</a> </li> <li><a href='lang-items.html'><b>6.5.</b> 言語アイテム</a> </li> <li><a href='advanced-linking.html'><b>6.6.</b> 高度なリンキング</a> </li> <li><a href='benchmark-tests.html'><b>6.7.</b> ベンチマークテスト</a> </li> <li><a href='box-syntax-and-patterns.html'><b>6.8.</b> Box構文とパターン</a> </li> <li><a href='slice-patterns.html'><b>6.9.</b> スライスパターン</a> </li> <li><a href='associated-constants.html'><b>6.10.</b> 関連定数</a> </li> <li><a href='custom-allocators.html'><b>6.11.</b> カスタムアロケータ</a> </li> </ul> </li> <li><a href='glossary.html'><b>7.</b> 用語集</a> </li> <li><a href='syntax-index.html'><b>8.</b> 構文の索引</a> </li> <li><a href='bibliography.html'><b>9.</b> 関係書目</a> </li> </ul> </div> <div id='page-wrapper'> <div id='page'> <blockquote class="header-caveat"> <p> <strong>注意: <a href="https://doc.rust-jp.rs/book-ja/">最新版のドキュメントをご覧ください。</a></strong>この第1版ドキュメントは古くなっており、最新情報が反映されていません。リンク先のドキュメントが現在の Rust の最新のドキュメントです。 </p> </blockquote> <h1 class="title">保証を選ぶ</h1> <!--% Choosing your Guarantees--> <!--One important feature of Rust is that it lets us control the costs and guarantees--> <!--of a program.--> <p>Rustの重要な特長の1つは、プログラムのコストと保証を制御することができるということです。</p> <!--There are various &ldquo;wrapper type&rdquo; abstractions in the Rust standard library which embody--> <!--a multitude of tradeoffs between cost, ergonomics, and guarantees. Many let one choose between--> <!--run time and compile time enforcement. This section will explain a few selected abstractions in--> <!--detail.--> <p>Rustの標準ライブラリには、様々な「ラッパ型」の抽象があり、それらはコスト、エルゴノミクス、保証の間の多数のトレードオフをまとめています。 それらのトレードオフの多くでは実行時とコンパイル時のどちらかを選ばせてくれます。 このセクションでは、いくつかの抽象を選び、詳細に説明します。</p> <!--Before proceeding, it is highly recommended that one reads about [ownership][ownership] and--> <!--[borrowing][borrowing] in Rust.--> <p>先に進む前に、Rustにおける <a href="ownership.html">所有権</a> と <a href="references-and-borrowing.html">借用</a> について読んでおくことを強く推奨します。</p> <!--# Basic pointer types--> <h1 id='基本的なポインタ型' class='section-header'><a href='#基本的なポインタ型'>基本的なポインタ型</a></h1> <h2 id='boxt' class='section-header'><a href='#boxt'><code>Box&lt;T&gt;</code></a></h2> <!--[`Box<T>`][box] is an &ldquo;owned&rdquo; pointer, or a &ldquo;box&rdquo;. While it can hand--> <!--out references to the contained data, it is the only owner of the data. In particular, consider--> <!--the following:--> <p><a href="../std/boxed/struct.Box.html"><code>Box&lt;T&gt;</code></a> は「所有される」ポインタ、すなわち「ボックス」です。 ボックスは中身のデータへの参照を渡すことができますが、ボックスだけがそのデータの唯一の所有者です。 特に、次のことを考えましょう。</p> <span class='rusttest'>fn main() { let x = Box::new(1); let y = x; // x no longer accessible here // ここではもうxにアクセスできない }</span><pre class='rust rust-example-rendered'> <span class='kw'>let</span> <span class='ident'>x</span> <span class='op'>=</span> <span class='ident'>Box</span>::<span class='ident'>new</span>(<span class='number'>1</span>); <span class='kw'>let</span> <span class='ident'>y</span> <span class='op'>=</span> <span class='ident'>x</span>; <span class='comment'>// ここではもうxにアクセスできない</span></pre> <!--Here, the box was _moved_ into `y`. As `x` no longer owns it, the compiler will no longer allow the--> <!--programmer to use `x` after this. A box can similarly be moved _out_ of a function by returning it.--> <p>ここで、そのボックスは <code>y</code> に <em>ムーブ</em> されました。 <code>x</code> はもはやそれを所有していないので、これ以降、コンパイラはプログラマが <code>x</code> を使うことを許しません。 同様に、ボックスはそれを返すことで関数の <em>外</em> にムーブさせることもできます。</p> <!--When a box (that hasn't been moved) goes out of scope, destructors are run. These destructors take--> <!--care of deallocating the inner data.--> <p>(ムーブされていない)ボックスがスコープから外れると、デストラクタが実行されます。 それらのデストラクタは中身のデータを解放して片付けます。</p> <!--This is a zero-cost abstraction for dynamic allocation. If you want to allocate some memory on the--> <!--heap and safely pass around a pointer to that memory, this is ideal. Note that you will only be--> <!--allowed to share references to this by the regular borrowing rules, checked at compile time.--> <p>これは動的割当てのゼロコスト抽象化です。 もしヒープにメモリを割り当てたくて、そのメモリへのポインタを安全に取り回したいのであれば、これは理想的です。 コンパイル時にチェックされる通常の借用のルールに基づいてこれへの参照を共有することが許されているだけだということに注意しましょう。</p> <!--## `&T` and `&mut T`--> <h2 id='t-と-mut-t' class='section-header'><a href='#t-と-mut-t'><code>&amp;T</code> と <code>&amp;mut T</code></a></h2> <!--These are immutable and mutable references respectively. They follow the &ldquo;read-write lock&rdquo;--> <!--pattern, such that one may either have only one mutable reference to some data, or any number of--> <!--immutable ones, but not both. This guarantee is enforced at compile time, and has no visible cost at--> <!--runtime. In most cases these two pointer types suffice for sharing cheap references between sections--> <!--of code.--> <p>参照にはイミュータブルな参照とミュータブルな参照がそれぞれあります。 それらは「読み書きロック」パターンに従います。それは、あるデータへのミュータブルな参照を1つだけ持つこと、又は複数のイミュータブルな参照を持つことはあり得るが、その両方を持つことはあり得ないということです。 この保証はコンパイル時に強制され、目に見えるような実行時のコストは発生しません。 多くの場合、それら2つのポインタ型は低コストの参照をコードのセクション間で共有するには十分です。</p> <!--These pointers cannot be copied in such a way that they outlive the lifetime associated with them.--> <p>それらのポインタを関連付けられているライフタイムを超えて有効になるような方法でコピーすることはできません。</p> <!--## `*const T` and `*mut T`--> <h2 id='const-t-と-mut-t' class='section-header'><a href='#const-t-と-mut-t'><code>*const T</code> と <code>*mut T</code></a></h2> <!-- These are C-like raw pointers with no lifetime or ownership attached to them. They point to --> <!--some location in memory with no other restrictions. The only guarantee that these provide is that--> <!--they cannot be dereferenced except in code marked `unsafe`.--> <p>関連付けられたライフタイムや所有権を持たない、C的な生ポインタがあります。 それらはメモリのある場所を何の制約もなく指示します。 それらの提供する唯一の保証は、 <code>unsafe</code> であるとマークされたコードの外ではそれらが参照を外せないということです。</p> <!--These are useful when building safe, low cost abstractions like `Vec<T>`, but should be avoided in--> <!--safe code.--> <p>それらは <code>Vec&lt;T&gt;</code> のような安全で低コストな抽象を構築するときには便利ですが、安全なコードの中では避けるべきです。</p> <h2 id='rct' class='section-header'><a href='#rct'><code>Rc&lt;T&gt;</code></a></h2> <!--This is the first wrapper we will cover that has a runtime cost.--> <p>これは、本書でカバーする中では初めての、実行時にコストの発生するラッパです。</p> <!--[`Rc<T>`][rc] is a reference counted pointer. In other words, this lets us have multiple "owning"--> <!--pointers to the same data, and the data will be dropped (destructors will be run) when all pointers--> <!--are out of scope.--> <p><a href="../std/rc/struct.Rc.html"><code>Rc&lt;T&gt;</code></a> は参照カウンタを持つポインタです。 言い換えると、これを使えば、あるデータを「所有する」複数のポインタを持つことができるようになるということです。そして、全てのポインタがスコープから外れたとき、そのデータは削除されます(デストラクタが実行されます)。</p> <!--Internally, it contains a shared &ldquo;reference count&rdquo; (also called &ldquo;refcount&rdquo;),--> <!--which is incremented each time the `Rc` is cloned, and decremented each time one of the `Rc`s goes--> <!--out of scope. The main responsibility of `Rc<T>` is to ensure that destructors are called for shared--> <!--data.--> <p>内部的には、それは共有「参照カウント」(「refcount」とも呼ばれます)を持っています。それは、 <code>Rc</code> がクローンされる度に1増加し、 <code>Rc</code> がスコープから外れる度に1減少します。 <code>Rc&lt;T&gt;</code> の主な役割は、共有データのデストラクタが呼び出されることを保証することです。</p> <!--The internal data here is immutable, and if a cycle of references is created, the data will be--> <!--leaked. If we want data that doesn't leak when there are cycles, we need a garbage collector.--> <p>ここでの中身のデータはイミュータブルで、もし循環参照が起きてしまったら、そのデータはメモリリークを起こすでしょう。 もし循環してもメモリリークを起こさないデータを求めるのであれば、ガーベジコレクタが必要です。</p> <!--#### Guarantees--> <h4 id='保証' class='section-header'><a href='#保証'>保証</a></h4> <!--The main guarantee provided here is that the data will not be destroyed until all references to it--> <!--are out of scope.--> <p>ここで提供される主な保証は、それに対する全ての参照がスコープから外れるまではデータが破壊されないということです。</p> <!--This should be used when we wish to dynamically allocate and share some data (read-only) between--> <!--various portions of your program, where it is not certain which portion will finish using the pointer--> <!--last. It's a viable alternative to `&T` when `&T` is either impossible to statically check for--> <!--correctness, or creates extremely unergonomic code where the programmer does not wish to spend the--> <!--development cost of working with.--> <p>これは(読込専用の)あるデータを動的に割り当て、プログラムの様々な部分で共有したいときで、どの部分が最後にポインタを使い終わるのかがはっきりしないときに使われるべきです。 それは <code>&amp;T</code> が正しさを静的にチェックすることが不可能なとき、又はプログラマがそれを使うために開発コストを費やすことを望まないような極めて非エルゴノミックなコードを作っているときに、 <code>&amp;T</code> の有望な代替品です。</p> <!--This pointer is _not_ thread safe, and Rust will not let it be sent or shared with other threads.--> <!--This lets one avoid the cost of atomics in situations where they are unnecessary.--> <p>このポインタはスレッドセーフでは <em>ありません</em> 。Rustはそれを他のスレッドに対して送ったり共有したりはさせません。 これによって、それらが不要な状況でのアトミック性のためのコストを省くことができます。</p> <!--There is a sister smart pointer to this one, `Weak<T>`. This is a non-owning, but also non-borrowed,--> <!--smart pointer. It is also similar to `&T`, but it is not restricted in lifetime&mdash;a `Weak<T>`--> <!--can be held on to forever. However, it is possible that an attempt to access the inner data may fail--> <!--and return `None`, since this can outlive the owned `Rc`s. This is useful for cyclic--> <!--data structures and other things.--> <p>これの姉妹に当たるスマートポインタとして、 <code>Weak&lt;T&gt;</code> があります。 これは所有せず、借用もしないスマートポインタです。 それは <code>&amp;T</code> とも似ていますが、ライフタイムによる制約がありません。 <code>Weak&lt;T&gt;</code> は永遠に有効であり続けることができます。 しかし、これは所有する <code>Rc</code> のライフタイムを超えて有効である可能性があるため、中身のデータへのアクセスが失敗し、 <code>None</code> を返すという可能性があります。 これは循環するデータ構造やその他のものについて便利です。</p> <!--#### Cost--> <h4 id='コスト' class='section-header'><a href='#コスト'>コスト</a></h4> <!--As far as memory goes, `Rc<T>` is a single allocation, though it will allocate two extra words (i.e.--> <!--two `usize` values) as compared to a regular `Box<T>` (for "strong" and "weak" refcounts).--> <p>メモリに関する限り、 <code>Rc&lt;T&gt;</code> の割当ては1回です。ただし、普通の <code>Box&lt;T&gt;</code> と比べると (「強い」参照カウントと「弱い」参照カウントのために)、2ワード余分(つまり、2つの <code>usize</code> の値)に割り当てます。</p> <!--`Rc<T>` has the computational cost of incrementing/decrementing the refcount whenever it is cloned--> <!--or goes out of scope respectively. Note that a clone will not do a deep copy, rather it will simply--> <!--increment the inner reference count and return a copy of the `Rc<T>`.--> <p><code>Rc&lt;T&gt;</code> では、それをクローンしたりそれがスコープから外れたりする度に参照カウントを増減するための計算コストが掛かります。 クローンはディープコピーではなく、それが単に内部の参照カウントを1増加させ、 <code>Rc&lt;T&gt;</code> のコピーを返すだけだということに注意しましょう。</p> <!--# Cell types--> <h1 id='セル型' class='section-header'><a href='#セル型'>セル型</a></h1> <!--`Cell`s provide interior mutability. In other words, they contain data which can be manipulated even--> <!--if the type cannot be obtained in a mutable form (for example, when it is behind an `&`-ptr or--> <!--`Rc<T>`).--> <p><code>Cell</code> は内的ミュータビリティを提供します。 言い換えると、型がミュータブルな形式を持てないものであったとしても(例えば、それが <code>&amp;</code> ポインタや <code>Rc&lt;T&gt;</code> の参照先であるとき)、操作できるデータを持つということです。</p> <!--[The documentation for the `cell` module has a pretty good explanation for these][cell-mod].--> <p><a href="../std/cell/"><code>cell</code>モジュールのドキュメントには、それらについての非常によい説明があります</a> 。</p> <!--These types are _generally_ found in struct fields, but they may be found elsewhere too.--> <p>それらの型は <em>一般的には</em> 構造体のフィールドで見られますが、他の場所でも見られるかもしれません。</p> <h2 id='cellt' class='section-header'><a href='#cellt'><code>Cell&lt;T&gt;</code></a></h2> <!--[`Cell<T>`][cell] is a type that provides zero-cost interior mutability, but only for `Copy` types.--> <!--Since the compiler knows that all the data owned by the contained value is on the stack, there's--> <!--no worry of leaking any data behind references (or worse!) by simply replacing the data.--> <p><a href="../std/cell/struct.Cell.html"><code>Cell&lt;T&gt;</code></a> はゼロコストで内的ミュータビリティを提供するものですが、 <code>Copy</code> 型のためだけのものです。 コンパイラは含まれている値によって所有されている全てのデータがスタック上にあることを認識しています。そのため、単純にデータが置き換えられることによって参照先のデータがメモリリークを起こす(又はもっと悪いことも!)心配はありません。</p> <!--It is still possible to violate your own invariants using this wrapper, so be careful when using it.--> <!--If a field is wrapped in `Cell`, it's a nice indicator that the chunk of data is mutable and may not--> <!--stay the same between the time you first read it and when you intend to use it.--> <p>このラッパを使うことで、維持されている不変性に違反してしまう可能性もあるので、それを使うときには注意しましょう。 もしフィールドが <code>Cell</code> でラップされているならば、そのデータの塊はミュータブルで、最初にそれを読み込んだときとそれを使おうと思ったときで同じままだとは限らないということのよい目印になります。</p> <span class='rusttest'>fn main() { use std::cell::Cell; let x = Cell::new(1); let y = &amp;x; let z = &amp;x; x.set(2); y.set(3); z.set(4); println!(&quot;{}&quot;, x.get()); }</span><pre class='rust rust-example-rendered'> <span class='kw'>use</span> <span class='ident'>std</span>::<span class='ident'>cell</span>::<span class='ident'>Cell</span>; <span class='kw'>let</span> <span class='ident'>x</span> <span class='op'>=</span> <span class='ident'>Cell</span>::<span class='ident'>new</span>(<span class='number'>1</span>); <span class='kw'>let</span> <span class='ident'>y</span> <span class='op'>=</span> <span class='kw-2'>&amp;</span><span class='ident'>x</span>; <span class='kw'>let</span> <span class='ident'>z</span> <span class='op'>=</span> <span class='kw-2'>&amp;</span><span class='ident'>x</span>; <span class='ident'>x</span>.<span class='ident'>set</span>(<span class='number'>2</span>); <span class='ident'>y</span>.<span class='ident'>set</span>(<span class='number'>3</span>); <span class='ident'>z</span>.<span class='ident'>set</span>(<span class='number'>4</span>); <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;{}&quot;</span>, <span class='ident'>x</span>.<span class='ident'>get</span>());</pre> <!--Note that here we were able to mutate the same value from various immutable references.--> <p>ここでは同じ値を様々なイミュータブルな参照から変更できるということに注意しましょう。</p> <!--This has the same runtime cost as the following:--> <p>これには次のものと同じ実行時のコストが掛かります。</p> <span class='rusttest'>fn main() { let mut x = 1; let y = &amp;mut x; let z = &amp;mut x; x = 2; *y = 3; *z = 4; println!(&quot;{}&quot;, x); }</span><pre class='rust rust-example-rendered'> <span class='kw'>let</span> <span class='kw-2'>mut</span> <span class='ident'>x</span> <span class='op'>=</span> <span class='number'>1</span>; <span class='kw'>let</span> <span class='ident'>y</span> <span class='op'>=</span> <span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='ident'>x</span>; <span class='kw'>let</span> <span class='ident'>z</span> <span class='op'>=</span> <span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='ident'>x</span>; <span class='ident'>x</span> <span class='op'>=</span> <span class='number'>2</span>; <span class='op'>*</span><span class='ident'>y</span> <span class='op'>=</span> <span class='number'>3</span>; <span class='op'>*</span><span class='ident'>z</span> <span class='op'>=</span> <span class='number'>4</span>; <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;{}&quot;</span>, <span class='ident'>x</span>);</pre> <!--but it has the added benefit of actually compiling successfully.--> <p>しかし、それには実際に正常にコンパイルできるという追加の利点があります。</p> <!--#### Guarantees--> <h4 id='保証-1' class='section-header'><a href='#保証-1'>保証</a></h4> <!--This relaxes the &ldquo;no aliasing with mutability&rdquo; restriction in places where it's--> <!--unnecessary. However, this also relaxes the guarantees that the restriction provides; so if your--> <!--invariants depend on data stored within `Cell`, you should be careful.--> <p>これは「ミュータブルなエイリアスはない」という制約を、それが不要な場所において緩和します。 しかし、これはその制約が提供する保証をも緩和してしまいます。もし不変条件が <code>Cell</code> に保存されているデータに依存しているのであれば、注意すべきです。</p> <!--This is useful for mutating primitives and other `Copy` types when there is no easy way of--> <!--doing it in line with the static rules of `&` and `&mut`.--> <p>これは <code>&amp;</code> や <code>&amp;mut</code> の静的なルールの下では簡単な方法がない場合に、プリミティブやその他の <code>Copy</code> 型を変更するのに便利です。</p> <!--`Cell` does not let you obtain interior references to the data, which makes it safe to freely--> <!--mutate.--> <p><code>Cell</code> によって安全な方法で自由に変更できるようなデータへの内部の参照を得られるわけではありません。</p> <!--#### Cost--> <h4 id='コスト-1' class='section-header'><a href='#コスト-1'>コスト</a></h4> <!--There is no runtime cost to using `Cell<T>`, however if you are using it to wrap larger (`Copy`)--> <!--structs, it might be worthwhile to instead wrap individual fields in `Cell<T>` since each write is--> <!--otherwise a full copy of the struct.--> <p><code>Cell&lt;T&gt;</code> の使用に実行時のコストは掛かりません。ただし、もしそれを大きな( <code>Copy</code> の)構造体をラップするために使っているのであれば、代わりに個々のフィールドを <code>Cell&lt;T&gt;</code> でラップする方がよいかもしれません。そうしなければ、各書込みが構造体の完全コピーを発生させることになるからです。</p> <h2 id='refcellt' class='section-header'><a href='#refcellt'><code>RefCell&lt;T&gt;</code></a></h2> <!--[`RefCell<T>`][refcell] also provides interior mutability, but isn't restricted to `Copy` types.--> <p><a href="../std/cell/struct.RefCell.html"><code>RefCell&lt;T&gt;</code></a> もまた内的ミュータビリティを提供するものですが、 <code>Copy</code> 型に限定されません。</p> <!--Instead, it has a runtime cost. `RefCell<T>` enforces the read-write lock pattern at runtime (it's--> <!--like a single-threaded mutex), unlike `&T`/`&mut T` which do so at compile time. This is done by the--> <!--`borrow()` and `borrow_mut()` functions, which modify an internal reference count and return smart--> <!--pointers which can be dereferenced immutably and mutably respectively. The refcount is restored when--> <!--the smart pointers go out of scope. With this system, we can dynamically ensure that there are never--> <!--any other borrows active when a mutable borrow is active. If the programmer attempts to make such a--> <!--borrow, the thread will panic.--> <p>その代わり、それには実行時のコストが掛かります。 <code>RefCell&lt;T&gt;</code> は読み書きロックパターンを実行時に(シングルスレッドのミューテックスのように)強制します。この点が、それをコンパイル時に行う <code>&amp;T</code> や <code>&amp;mut T</code> とは異なります。 これは <code>borrow()</code> 関数と <code>borrow_mut()</code> 関数によって行われます。それらは内部の参照カウントを変更し、それぞれイミュータブル、ミュータブルに参照を外すことのできるスマートポインタを戻します。 参照カウントはスマートポインタがスコープから外れたときに元に戻されます。 このシステムによって、ミュータブルな借用が有効なときには決してその他の借用が有効にならないということを動的に保証することができます。 もしプログラマがそのような借用を作ろうとすれば、スレッドはパニックするでしょう。</p> <span class='rusttest'>fn main() { use std::cell::RefCell; let x = RefCell::new(vec![1,2,3,4]); { println!(&quot;{:?}&quot;, *x.borrow()) } { let mut my_ref = x.borrow_mut(); my_ref.push(1); } }</span><pre class='rust rust-example-rendered'> <span class='kw'>use</span> <span class='ident'>std</span>::<span class='ident'>cell</span>::<span class='ident'>RefCell</span>; <span class='kw'>let</span> <span class='ident'>x</span> <span class='op'>=</span> <span class='ident'>RefCell</span>::<span class='ident'>new</span>(<span class='macro'>vec</span><span class='macro'>!</span>[<span class='number'>1</span>,<span class='number'>2</span>,<span class='number'>3</span>,<span class='number'>4</span>]); { <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;{:?}&quot;</span>, <span class='op'>*</span><span class='ident'>x</span>.<span class='ident'>borrow</span>()) } { <span class='kw'>let</span> <span class='kw-2'>mut</span> <span class='ident'>my_ref</span> <span class='op'>=</span> <span class='ident'>x</span>.<span class='ident'>borrow_mut</span>(); <span class='ident'>my_ref</span>.<span class='ident'>push</span>(<span class='number'>1</span>); }</pre> <!--Similar to `Cell`, this is mainly useful for situations where it's hard or impossible to satisfy the--> <!--borrow checker. Generally we know that such mutations won't happen in a nested form, but it's good--> <!--to check.--> <p><code>Cell</code> と同様に、これは主に、借用チェッカを満足させることが困難、又は不可能な状況で便利です。 一般的に、そのような変更はネストした形式では発生しないと考えられますが、それをチェックすることはよいことです。</p> <!--For large, complicated programs, it becomes useful to put some things in `RefCell`s to make things--> <!-- simpler. For example, a lot of the maps in the `ctxt` struct in the Rust compiler internals --> <!--are inside this wrapper. These are only modified once (during creation, which is not right after--> <!--initialization) or a couple of times in well-separated places. However, since this struct is--> <!--pervasively used everywhere, juggling mutable and immutable pointers would be hard (perhaps--> <!--impossible) and probably form a soup of `&`-ptrs which would be hard to extend. On the other hand,--> <!--the `RefCell` provides a cheap (not zero-cost) way of safely accessing these. In the future, if--> <!--someone adds some code that attempts to modify the cell when it's already borrowed, it will cause a--> <!--(usually deterministic) panic which can be traced back to the offending borrow.--> <p>大きく複雑なプログラムにとって、物事を単純にするために何かを <code>RefCell</code> の中に入れることは便利です。 例えば、Rustコンパイラの内部の<code>ctxt</code>構造体にあるたくさんのマップはこのラッパの中にあります。 それらは(初期化の直後ではなく生成の過程で)一度だけ変更されるか、又はきれいに分離された場所で数回変更されます。 しかし、この構造体はあらゆる場所で全般的に使われているので、ミュータブルなポインタとイミュータブルなポインタとをジャグリング的に扱うのは難しく(あるいは不可能で)、おそらく拡張の困難な <code>&amp;</code> ポインタのスープになってしまいます。 一方、 <code>RefCell</code> はそれらにアクセスするための(ゼロコストではありませんが)低コストの方法です。 将来、もし誰かが既に借用されたセルを変更しようとするコードを追加すれば、それは(普通は確定的に)パニックを引き起こすでしょう。これは、その違反した借用まで遡り得ます。</p> <!--Similarly, in Servo's DOM there is a lot of mutation, most of which is local to a DOM type, but some--> <!--of which crisscrosses the DOM and modifies various things. Using `RefCell` and `Cell` to guard all--> <!--mutation lets us avoid worrying about mutability everywhere, and it simultaneously highlights the--> <!--places where mutation is _actually_ happening.--> <p>同様に、ServoのDOMではたくさんの変更が行われるようになっていて、そのほとんどはDOM型にローカルです。しかし、複数のDOMに縦横無尽にまたがり、様々なものを変更するものもあります。 全ての変更をガードするために <code>RefCell</code> と <code>Cell</code> を使うことで、あらゆる場所でのミュータビリティについて心配する必要がなくなり、それは同時に、変更が <em>実際に</em> 起こっている場所を強調してくれます。</p> <!--Note that `RefCell` should be avoided if a mostly simple solution is possible with `&` pointers.--> <p>もし <code>&amp;</code> ポインタを使ってもっと単純に解決できるのであれば、 <code>RefCell</code> は避けるべきであるということに注意しましょう。</p> <!--#### Guarantees--> <h4 id='保証-2' class='section-header'><a href='#保証-2'>保証</a></h4> <!--`RefCell` relaxes the _static_ restrictions preventing aliased mutation, and replaces them with--> <!--_dynamic_ ones. As such the guarantees have not changed.--> <p><code>RefCell</code> はミュータブルなエイリアスを作らせないという <em>静的な</em> 制約を緩和し、それを <em>動的な</em> 制約に置き換えます。 そのため、その保証は変わりません。</p> <!--#### Cost--> <h4 id='コスト-2' class='section-header'><a href='#コスト-2'>コスト</a></h4> <!--`RefCell` does not allocate, but it contains an additional "borrow state"--> <!--indicator (one word in size) along with the data.--> <p><code>RefCell</code> は割当てを行いませんが、データとともに(サイズ1ワードの)追加の「借用状態」の表示を持っています。</p> <!--At runtime each borrow causes a modification/check of the refcount.--> <p>実行時には、各借用が参照カウントの変更又はチェックを発生させます。</p> <!--# Synchronous types--> <h1 id='同期型' class='section-header'><a href='#同期型'>同期型</a></h1> <!--Many of the types above cannot be used in a threadsafe manner. Particularly, `Rc<T>` and--> <!--`RefCell<T>`, which both use non-atomic reference counts (_atomic_ reference counts are those which--> <!--can be incremented from multiple threads without causing a data race), cannot be used this way. This--> <!--makes them cheaper to use, but we need thread safe versions of these too. They exist, in the form of--> <!--`Arc<T>` and `Mutex<T>`/`RwLock<T>`--> <p>前に挙げた型の多くはスレッドセーフな方法で使うことができません。 特に <code>Rc&lt;T&gt;</code> と <code>RefCell&lt;T&gt;</code> は両方とも非アトミックな参照カウント( <em>アトミックな</em> 参照カウントとは、データ競合を発生させることなく複数のスレッドから増加させることができるもののことです)を使っていて、スレッドセーフな方法で使うことができません。 これによってそれらを低コストで使うことができるのですが、それらのスレッドセーフなバージョンも必要です。 それらは <code>Arc&lt;T&gt;</code> 、 <code>Mutex&lt;T&gt;</code> 、 <code>RwLock&lt;T&gt;</code> という形式で存在します。</p> <!--Note that the non-threadsafe types _cannot_ be sent between threads, and this is checked at compile--> <!--time.--> <p>非スレッドセーフな型はスレッド間で送ることが <em>できません</em> 。 これはコンパイル時にチェックされます。</p> <!--There are many useful wrappers for concurrent programming in the [sync][sync] module, but only the--> <!--major ones will be covered below.--> <p><a href="../std/sync/index.html">sync</a> モジュールには並行プログラミングのための便利なラッパがたくさんありますが、以下では有名なものだけをカバーします。</p> <h2 id='arct' class='section-header'><a href='#arct'><code>Arc&lt;T&gt;</code></a></h2> <!-- [`Arc<T>`][arc] is a version of `Rc<T>` that uses an atomic reference count (hence, "Arc"). --> <!--This can be sent freely between threads.--> <p><a href="../std/sync/struct.Arc.html"><code>Arc&lt;T&gt;</code></a> はアトミックな参照カウントを使う <code>Rc&lt;T&gt;</code> の別バージョンです(そのため、「Arc」なのです)。 これはスレッド間で自由に送ることができます。</p> <!--C++'s `shared_ptr` is similar to `Arc`, however in the case of C++ the inner data is always mutable.--> <!--For semantics similar to that from C++, we should use `Arc<Mutex<T>>`, `Arc<RwLock<T>>`, or--> <!--`Arc<UnsafeCell<T>>`[^4] (`UnsafeCell<T>` is a cell type that can be used to hold any data and has--> <!--no runtime cost, but accessing it requires `unsafe` blocks). The last one should only be used if we--> <!--are certain that the usage won't cause any memory unsafety. Remember that writing to a struct is not--> <!--an atomic operation, and many functions like `vec.push()` can reallocate internally and cause unsafe--> <!--behavior, so even monotonicity may not be enough to justify `UnsafeCell`.--> <p>C++の <code>shared_ptr</code> は <code>Arc</code> と似ていますが、C++の場合、中身のデータは常にミュータブルです。 C++と同じセマンティクスで使うためには、 <code>Arc&lt;Mutex&lt;T&gt;&gt;</code> 、 <code>Arc&lt;RwLock&lt;T&gt;&gt;</code> 、 <code>Arc&lt;UnsafeCell&lt;T&gt;&gt;</code> を使うべきです <sup id="fnref1"><a href="#fn1" rel="footnote">1</a></sup> ( <code>UnsafeCell&lt;T&gt;</code> はどんなデータでも持つことができ、実行時のコストも掛かりませんが、それにアクセスするためには <code>unsafe</code> ブロックが必要というセル型です)。 最後のものは、その使用がメモリをアンセーフにしないことを確信している場合にだけ使うべきです。 次のことを覚えましょう。構造体に書き込むのはアトミックな作業ではなく、<code>vec.push()</code>のような多くの関数は内部でメモリの再割当てを行い、アンセーフな挙動を引き起こす可能性があります。そのため単純な操作であるということだけでは <code>UnsafeCell</code> を正当化するには十分ではありません。</p> <!--[^4]: `Arc<UnsafeCell<T>>` actually won't compile since `UnsafeCell<T>` isn't `Send` or `Sync`, but we can wrap it in a type and implement `Send`/`Sync` for it manually to get `Arc<Wrapper<T>>` where `Wrapper` is `struct Wrapper<T>(UnsafeCell<T>)`.--> <!--#### Guarantees--> <h4 id='保証-3' class='section-header'><a href='#保証-3'>保証</a></h4> <!--Like `Rc`, this provides the (thread safe) guarantee that the destructor for the internal data will--> <!--be run when the last `Arc` goes out of scope (barring any cycles).--> <p><code>Rc</code> のように、これは最後の <code>Arc</code> がスコープから外れたときに(循環がなければ)中身のデータのためのデストラクタが実行されることを(スレッドセーフに)保証します。</p> <!--#### Cost--> <h4 id='コスト-3' class='section-header'><a href='#コスト-3'>コスト</a></h4> <!--This has the added cost of using atomics for changing the refcount (which will happen whenever it is--> <!--cloned or goes out of scope). When sharing data from an `Arc` in a single thread, it is preferable--> <!--to share `&` pointers whenever possible.--> <p>これには参照カウントの変更(これは、それがクローンされたりスコープから外れたりする度に発生します)にアトミック性を使うための追加のコストが掛かります。 シングルスレッドにおいて、データを <code>Arc</code> から共有するのであれば、可能な場合は <code>&amp;</code> ポインタを共有する方が適切です。</p> <!--## `Mutex<T>` and `RwLock<T>`--> <h2 id='mutext-と-rwlockt' class='section-header'><a href='#mutext-と-rwlockt'><code>Mutex&lt;T&gt;</code> と <code>RwLock&lt;T&gt;</code></a></h2> <!--[`Mutex<T>`][mutex] and [`RwLock<T>`][rwlock] provide mutual-exclusion via RAII guards (guards are--> <!--objects which maintain some state, like a lock, until their destructor is called). For both of--> <!--these, the mutex is opaque until we call `lock()` on it, at which point the thread will block--> <!--until a lock can be acquired, and then a guard will be returned. This guard can be used to access--> <!--the inner data (mutably), and the lock will be released when the guard goes out of scope.--> <p><a href="../std/sync/struct.Mutex.html"><code>Mutex&lt;T&gt;</code></a> と <a href="../std/sync/struct.RwLock.html"><code>RwLock&lt;T&gt;</code></a> はRAIIガード(ガードとは、ロックのようにそれらのデストラクタが呼び出されるまである状態を保持するオブジェクトのことです)による相互排他を提供します。 それらの両方とも、その <code>lock()</code> を呼び出すまでミューテックスは不透明です。その時点で、スレッドはロックが得られ、ガードが戻されるまでブロックします。 このガードを使うことで、中身のデータに(ミュータブルに)アクセスできるようになり、ロックはガードがスコープから外れたときに解放されます。</p> <span class='rusttest'>fn main() { { let guard = mutex.lock(); // guard dereferences mutably to the inner type // ガードがミュータブルに内部の型への参照を外す *guard += 1; // } // lock released when destructor runs } // デストラクタが実行されるときにロックは解除される }</span><pre class='rust rust-example-rendered'> { <span class='kw'>let</span> <span class='ident'>guard</span> <span class='op'>=</span> <span class='ident'>mutex</span>.<span class='ident'>lock</span>(); <span class='comment'>// ガードがミュータブルに内部の型への参照を外す</span> <span class='op'>*</span><span class='ident'>guard</span> <span class='op'>+=</span> <span class='number'>1</span>; } <span class='comment'>// デストラクタが実行されるときにロックは解除される</span></pre> <!--`RwLock` has the added benefit of being efficient for multiple reads. It is always safe to have--> <!--multiple readers to shared data as long as there are no writers; and `RwLock` lets readers acquire a--> <!--"read lock". Such locks can be acquired concurrently and are kept track of via a reference count.--> <!--Writers must obtain a "write lock" which can only be obtained when all readers have gone out of--> <!--scope.--> <p><code>RwLock</code>には複数の読込みを効率化するという追加の利点があります。 それはライタのない限り常に、共有されたデータに対する複数のリーダを安全に持つことができます。そして、<code>RwLock</code>によってリーダは「読込みロック」を取得できます。 このようなロックは並行に取得することができ、参照カウントによって追跡することができます。 ライタは「書込みロック」を取得する必要があります。「書込みロック」はすべてのリーダがスコープから外れたときにだけ取得できます。</p> <!--#### Guarantees--> <h4 id='保証-4' class='section-header'><a href='#保証-4'>保証</a></h4> <!--Both of these provide safe shared mutability across threads, however they are prone to deadlocks.--> <!--Some level of additional protocol safety can be obtained via the type system.--> <p>それらのどちらもスレッド間での安全で共有されたミュータビリティを提供しますが、それらはデッドロックしがちです。 型システムによって、ある程度の追加のプロトコルの安全性を得ることができます。</p> <!--#### Costs--> <h4 id='コスト-4' class='section-header'><a href='#コスト-4'>コスト</a></h4> <!--These use internal atomic-like types to maintain the locks, which are pretty costly (they can block--> <!--all memory reads across processors till they're done). Waiting on these locks can also be slow when--> <!--there's a lot of concurrent access happening.--> <p>それらはロックを保持するために内部でアトミック的な型を使います。それにはかなりコストが掛かります(それらは仕事が終わるまで、プロセッサ中のメモリ読込み全てをブロックする可能性があります)。 たくさんの並行なアクセスが起こる場合には、それらのロックを待つことが遅くなる可能性があります。</p> <!--# Composition--> <h1 id='合成' class='section-header'><a href='#合成'>合成</a></h1> <!--A common gripe when reading Rust code is with types like `Rc<RefCell<Vec<T>>>` (or even more--> <!--complicated compositions of such types). It's not always clear what the composition does, or why the--> <!--author chose one like this (and when one should be using such a composition in one's own code)--> <p>Rustのコードを読むときに一般的な悩みは、 <code>Rc&lt;RefCell&lt;Vec&lt;T&gt;&gt;&gt;</code> のような型(又はそのような型のもっと複雑な合成)です。 その合成が何をしているのか、なぜ作者はこんなものを選んだのか(そして、自分のコード内でいつこんな合成を使うべきなのか)ということは、常に明らかなわけではありません。</p> <!--Usually, it's a case of composing together the guarantees that you need, without paying for stuff--> <!--that is unnecessary.--> <p>普通、それは不要なコストを支払うことなく、必要とする保証を互いに組み合わせた場合です。</p> <!--For example, `Rc<RefCell<T>>` is one such composition. `Rc<T>` itself can't be dereferenced mutably;--> <!--because `Rc<T>` provides sharing and shared mutability can lead to unsafe behavior, so we put--> <!--`RefCell<T>` inside to get dynamically verified shared mutability. Now we have shared mutable data,--> <!--but it's shared in a way that there can only be one mutator (and no readers) or multiple readers.--> <p>例えば、 <code>Rc&lt;RefCell&lt;T&gt;&gt;</code> はそのような合成の1つです。 <code>Rc&lt;T&gt;</code> そのものはミュータブルに参照を外すことができません。 <code>Rc&lt;T&gt;</code> は共有を提供し、共有されたミュータビリティはアンセーフな挙動に繋がる可能性があります。そのため、動的に証明された共有されたミュータビリティを得るために、 <code>RefCell&lt;T&gt;</code> を中に入れます。 これで共有されたミュータブルなデータを持つことになりますが、それは(リーダはなしで)ライタが1つだけ、又はリーダが複数という方法で共有することになります。</p> <!--Now, we can take this a step further, and have `Rc<RefCell<Vec<T>>>` or `Rc<Vec<RefCell<T>>>`. These--> <!--are both shareable, mutable vectors, but they're not the same.--> <p>今度は、これをさらに次の段階に進めると、 <code>Rc&lt;RefCell&lt;Vec&lt;T&gt;&gt;&gt;</code> や <code>Rc&lt;Vec&lt;RefCell&lt;T&gt;&gt;&gt;</code> を持つことができます。 それらは両方とも共有できるミュータブルなベクタですが、同じではありません。</p> <!--With the former, the `RefCell<T>` is wrapping the `Vec<T>`, so the `Vec<T>` in its entirety is--> <!--mutable. At the same time, there can only be one mutable borrow of the whole `Vec` at a given time.--> <!--This means that your code cannot simultaneously work on different elements of the vector from--> <!--different `Rc` handles. However, we are able to push and pop from the `Vec<T>` at will. This is--> <!-- similar to a `&mut Vec<T>` with the borrow checking done at runtime. --> <p>1つ目について、 <code>RefCell&lt;T&gt;</code> は <code>Vec&lt;T&gt;</code> をラップしているので、その <code>Vec&lt;T&gt;</code> 全体がミュータブルです。 同時に、それらは特定の時間において <code>Vec</code> 全体の唯一のミュータブルな借用になり得ます。 これは、コードがそのベクタの別の要素について、別の <code>Rc</code> ハンドルから同時には操作できないということを意味します。 しかし、 <code>Vec&lt;T&gt;</code> に対するプッシュやポップは好きなように行うことができます。 これは借用チェックが実行時に行われるという点で <code>&amp;mut Vec&lt;T&gt;</code> と同様です。</p> <!--With the latter, the borrowing is of individual elements, but the overall vector is immutable. Thus,--> <!--we can independently borrow separate elements, but we cannot push or pop from the vector. This is--> <!-- similar to a `&mut [T]`[^3], but, again, the borrow checking is at runtime. --> <p>2つ目について、借用は個々の要素に対して行われますが、ベクタ全体がイミュータブルになります。 そのため、異なる要素を別々に借用することができますが、ベクタに対するプッシュやポップを行うことはできません。 これは <code>&amp;mut [T]</code><sup id="fnref2"><a href="#fn2" rel="footnote">2</a></sup> と同じですが、やはり借用チェックは実行時に行われます。</p> <!--In concurrent programs, we have a similar situation with `Arc<Mutex<T>>`, which provides shared--> <!--mutability and ownership.--> <p>並行プログラムでは、 <code>Arc&lt;Mutex&lt;T&gt;&gt;</code> と似た状況に置かれます。それは共有されたミュータビリティと所有権を提供します。</p> <!--When reading code that uses these, go in step by step and look at the guarantees/costs provided.--> <p>それらを使ったコードを読むときには、1行1行進み、提供される保証とコストを見ましょう。</p> <!--When choosing a composed type, we must do the reverse; figure out which guarantees we want, and at--> <!--which point of the composition we need them. For example, if there is a choice between--> <!--`Vec<RefCell<T>>` and `RefCell<Vec<T>>`, we should figure out the tradeoffs as done above and pick--> <!--one.--> <p>合成された型を選択するときには、その逆に考えなければなりません。必要とする保証が何であるか、必要とする合成がどの点にあるのかを理解しましょう。 例えば、もし <code>Vec&lt;RefCell&lt;T&gt;&gt;</code> と <code>RefCell&lt;Vec&lt;T&gt;&gt;</code> のどちらかを選ぶのであれば、前の方で行ったようにトレードオフを理解し、選ばなければなりません。</p> <!--[^3]: `&[T]` and `&mut [T]` are _slices_; they consist of a pointer and a length and can refer to a portion of a vector or array. `&mut [T]` can have its elements mutated, however its length cannot be touched.--> <p><code>&amp;mut [T]</code> ではその要素を変更できますが、その長さは変更することができません。</p> <div class="footnotes"> <hr> <ol> <li id="fn1"> <p><code>Arc&lt;UnsafeCell&lt;T&gt;&gt;</code> は <code>Send</code> や <code>Sync</code> ではないため、実際にはコンパイルできません。しかし、 <code>Arc&lt;Wrapper&lt;T&gt;&gt;</code> を得るために、手動でそれを <code>Send</code> と <code>Sync</code> を実装した型でラップすることができます。ここでの <code>Wrapper</code> は <code>struct Wrapper&lt;T&gt;(UnsafeCell&lt;T&gt;)</code> です。&nbsp;<a href="#fnref1" rev="footnote">&#8617;</a></p> </li> <li id="fn2"> <p><code>&amp;[T]</code> と <code>&amp;mut [T]</code> は <em>スライス</em> です。それらはポインタと長さを持ち、ベクタや配列の一部を参照することができます。&nbsp;<a href="#fnref2" rev="footnote">&#8617;</a></p> </li> </ol> </div> <script type="text/javascript"> window.playgroundUrl = "https://play.rust-lang.org"; </script> <script src='rustbook.js'></script> <script src='playpen.js'></script> </div></div> </body> </html> <|start_filename|>docs/1.9/nomicon/transmutes.html<|end_filename|> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="generator" content="rustdoc"> <title>Transmutes</title> <link rel="stylesheet" type="text/css" href="rustbook.css"> <meta name="robots" content="noindex"> </head> <body class="rustdoc"> <!--[if lte IE 8]> <div class="warning"> This old browser is unsupported and will most likely display funky things. </div> <![endif]--> <div id="nav"> <button id="toggle-nav"> <span class="sr-only">Toggle navigation</span> <span class="bar"></span> <span class="bar"></span> <span class="bar"></span> </button> </div> <div id='toc' class='mobile-hidden'> <ul class='chapter'> <li><a href='README.html'><b>1.</b> Introduction</a> </li> <li><a href='meet-safe-and-unsafe.html'><b>2.</b> Meet Safe and Unsafe</a> <ul class='section'> <li><a href='safe-unsafe-meaning.html'><b>2.1.</b> How Safe and Unsafe Interact</a> </li> <li><a href='working-with-unsafe.html'><b>2.2.</b> Working with Unsafe</a> </li> </ul> </li> <li><a href='data.html'><b>3.</b> Data Layout</a> <ul class='section'> <li><a href='repr-rust.html'><b>3.1.</b> repr(Rust)</a> </li> <li><a href='exotic-sizes.html'><b>3.2.</b> Exotically Sized Types</a> </li> <li><a href='other-reprs.html'><b>3.3.</b> Other reprs</a> </li> </ul> </li> <li><a href='ownership.html'><b>4.</b> Ownership</a> <ul class='section'> <li><a href='references.html'><b>4.1.</b> References</a> </li> <li><a href='lifetimes.html'><b>4.2.</b> Lifetimes</a> </li> <li><a href='lifetime-mismatch.html'><b>4.3.</b> Limits of Lifetimes</a> </li> <li><a href='lifetime-elision.html'><b>4.4.</b> Lifetime Elision</a> </li> <li><a href='unbounded-lifetimes.html'><b>4.5.</b> Unbounded Lifetimes</a> </li> <li><a href='hrtb.html'><b>4.6.</b> Higher-Rank Trait Bounds</a> </li> <li><a href='subtyping.html'><b>4.7.</b> Subtyping and Variance</a> </li> <li><a href='dropck.html'><b>4.8.</b> Drop Check</a> </li> <li><a href='phantom-data.html'><b>4.9.</b> PhantomData</a> </li> <li><a href='borrow-splitting.html'><b>4.10.</b> Splitting Borrows</a> </li> </ul> </li> <li><a href='conversions.html'><b>5.</b> Type Conversions</a> <ul class='section'> <li><a href='coercions.html'><b>5.1.</b> Coercions</a> </li> <li><a href='dot-operator.html'><b>5.2.</b> The Dot Operator</a> </li> <li><a href='casts.html'><b>5.3.</b> Casts</a> </li> <li><a class='active' href='transmutes.html'><b>5.4.</b> Transmutes</a> </li> </ul> </li> <li><a href='uninitialized.html'><b>6.</b> Uninitialized Memory</a> <ul class='section'> <li><a href='checked-uninit.html'><b>6.1.</b> Checked</a> </li> <li><a href='drop-flags.html'><b>6.2.</b> Drop Flags</a> </li> <li><a href='unchecked-uninit.html'><b>6.3.</b> Unchecked</a> </li> </ul> </li> <li><a href='obrm.html'><b>7.</b> Ownership Based Resource Management</a> <ul class='section'> <li><a href='constructors.html'><b>7.1.</b> Constructors</a> </li> <li><a href='destructors.html'><b>7.2.</b> Destructors</a> </li> <li><a href='leaking.html'><b>7.3.</b> Leaking</a> </li> </ul> </li> <li><a href='unwinding.html'><b>8.</b> Unwinding</a> <ul class='section'> <li><a href='exception-safety.html'><b>8.1.</b> Exception Safety</a> </li> <li><a href='poisoning.html'><b>8.2.</b> Poisoning</a> </li> </ul> </li> <li><a href='concurrency.html'><b>9.</b> Concurrency</a> <ul class='section'> <li><a href='races.html'><b>9.1.</b> Races</a> </li> <li><a href='send-and-sync.html'><b>9.2.</b> Send and Sync</a> </li> <li><a href='atomics.html'><b>9.3.</b> Atomics</a> </li> </ul> </li> <li><a href='vec.html'><b>10.</b> Implementing Vec</a> <ul class='section'> <li><a href='vec-layout.html'><b>10.1.</b> Layout</a> </li> <li><a href='vec-alloc.html'><b>10.2.</b> Allocating</a> </li> <li><a href='vec-push-pop.html'><b>10.3.</b> Push and Pop</a> </li> <li><a href='vec-dealloc.html'><b>10.4.</b> Deallocating</a> </li> <li><a href='vec-deref.html'><b>10.5.</b> Deref</a> </li> <li><a href='vec-insert-remove.html'><b>10.6.</b> Insert and Remove</a> </li> <li><a href='vec-into-iter.html'><b>10.7.</b> IntoIter</a> </li> <li><a href='vec-raw.html'><b>10.8.</b> RawVec</a> </li> <li><a href='vec-drain.html'><b>10.9.</b> Drain</a> </li> <li><a href='vec-zsts.html'><b>10.10.</b> Handling Zero-Sized Types</a> </li> <li><a href='vec-final.html'><b>10.11.</b> Final Code</a> </li> </ul> </li> <li><a href='arc-and-mutex.html'><b>11.</b> Implementing Arc and Mutex</a> </li> </ul> </div> <div id='page-wrapper'> <div id='page'> <blockquote class="header-caveat"> <p> <strong>注意: <a href="https://doc.rust-jp.rs/book-ja/">最新版のドキュメントをご覧ください。</a></strong>この第1版ドキュメントは古くなっており、最新情報が反映されていません。リンク先のドキュメントが現在の Rust の最新のドキュメントです。 </p> </blockquote> <h1 class="title">Transmutes</h1> <p>Get out of our way type system! We&#39;re going to reinterpret these bits or die trying! Even though this book is all about doing things that are unsafe, I really can&#39;t emphasize that you should deeply think about finding Another Way than the operations covered in this section. This is really, truly, the most horribly unsafe thing you can do in Rust. The railguards here are dental floss.</p> <p><code>mem::transmute&lt;T, U&gt;</code> takes a value of type <code>T</code> and reinterprets it to have type <code>U</code>. The only restriction is that the <code>T</code> and <code>U</code> are verified to have the same size. The ways to cause Undefined Behavior with this are mind boggling.</p> <ul> <li>First and foremost, creating an instance of <em>any</em> type with an invalid state is going to cause arbitrary chaos that can&#39;t really be predicted.</li> <li>Transmute has an overloaded return type. If you do not specify the return type it may produce a surprising type to satisfy inference.</li> <li>Making a primitive with an invalid value is UB</li> <li>Transmuting between non-repr(C) types is UB</li> <li>Transmuting an &amp; to &amp;mut is UB <ul> <li>Transmuting an &amp; to &amp;mut is <em>always</em> UB</li> <li>No you can&#39;t do it</li> <li>No you&#39;re not special</li> </ul></li> <li>Transmuting to a reference without an explicitly provided lifetime produces an <a href="unbounded-lifetimes.html">unbounded lifetime</a></li> </ul> <p><code>mem::transmute_copy&lt;T, U&gt;</code> somehow manages to be <em>even more</em> wildly unsafe than this. It copies <code>size_of&lt;U&gt;</code> bytes out of an <code>&amp;T</code> and interprets them as a <code>U</code>. The size check that <code>mem::transmute</code> has is gone (as it may be valid to copy out a prefix), though it is Undefined Behavior for <code>U</code> to be larger than <code>T</code>.</p> <p>Also of course you can get most of the functionality of these functions using pointer casts.</p> <script type="text/javascript"> window.playgroundUrl = "https://play.rust-lang.org"; </script> <script src='rustbook.js'></script> <script src='playpen.js'></script> </div></div> </body> </html> <|start_filename|>docs/1.9/nomicon/vec-drain.html<|end_filename|> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="generator" content="rustdoc"> <title>Drain</title> <link rel="stylesheet" type="text/css" href="rustbook.css"> <meta name="robots" content="noindex"> </head> <body class="rustdoc"> <!--[if lte IE 8]> <div class="warning"> This old browser is unsupported and will most likely display funky things. </div> <![endif]--> <div id="nav"> <button id="toggle-nav"> <span class="sr-only">Toggle navigation</span> <span class="bar"></span> <span class="bar"></span> <span class="bar"></span> </button> </div> <div id='toc' class='mobile-hidden'> <ul class='chapter'> <li><a href='README.html'><b>1.</b> Introduction</a> </li> <li><a href='meet-safe-and-unsafe.html'><b>2.</b> Meet Safe and Unsafe</a> <ul class='section'> <li><a href='safe-unsafe-meaning.html'><b>2.1.</b> How Safe and Unsafe Interact</a> </li> <li><a href='working-with-unsafe.html'><b>2.2.</b> Working with Unsafe</a> </li> </ul> </li> <li><a href='data.html'><b>3.</b> Data Layout</a> <ul class='section'> <li><a href='repr-rust.html'><b>3.1.</b> repr(Rust)</a> </li> <li><a href='exotic-sizes.html'><b>3.2.</b> Exotically Sized Types</a> </li> <li><a href='other-reprs.html'><b>3.3.</b> Other reprs</a> </li> </ul> </li> <li><a href='ownership.html'><b>4.</b> Ownership</a> <ul class='section'> <li><a href='references.html'><b>4.1.</b> References</a> </li> <li><a href='lifetimes.html'><b>4.2.</b> Lifetimes</a> </li> <li><a href='lifetime-mismatch.html'><b>4.3.</b> Limits of Lifetimes</a> </li> <li><a href='lifetime-elision.html'><b>4.4.</b> Lifetime Elision</a> </li> <li><a href='unbounded-lifetimes.html'><b>4.5.</b> Unbounded Lifetimes</a> </li> <li><a href='hrtb.html'><b>4.6.</b> Higher-Rank Trait Bounds</a> </li> <li><a href='subtyping.html'><b>4.7.</b> Subtyping and Variance</a> </li> <li><a href='dropck.html'><b>4.8.</b> Drop Check</a> </li> <li><a href='phantom-data.html'><b>4.9.</b> PhantomData</a> </li> <li><a href='borrow-splitting.html'><b>4.10.</b> Splitting Borrows</a> </li> </ul> </li> <li><a href='conversions.html'><b>5.</b> Type Conversions</a> <ul class='section'> <li><a href='coercions.html'><b>5.1.</b> Coercions</a> </li> <li><a href='dot-operator.html'><b>5.2.</b> The Dot Operator</a> </li> <li><a href='casts.html'><b>5.3.</b> Casts</a> </li> <li><a href='transmutes.html'><b>5.4.</b> Transmutes</a> </li> </ul> </li> <li><a href='uninitialized.html'><b>6.</b> Uninitialized Memory</a> <ul class='section'> <li><a href='checked-uninit.html'><b>6.1.</b> Checked</a> </li> <li><a href='drop-flags.html'><b>6.2.</b> Drop Flags</a> </li> <li><a href='unchecked-uninit.html'><b>6.3.</b> Unchecked</a> </li> </ul> </li> <li><a href='obrm.html'><b>7.</b> Ownership Based Resource Management</a> <ul class='section'> <li><a href='constructors.html'><b>7.1.</b> Constructors</a> </li> <li><a href='destructors.html'><b>7.2.</b> Destructors</a> </li> <li><a href='leaking.html'><b>7.3.</b> Leaking</a> </li> </ul> </li> <li><a href='unwinding.html'><b>8.</b> Unwinding</a> <ul class='section'> <li><a href='exception-safety.html'><b>8.1.</b> Exception Safety</a> </li> <li><a href='poisoning.html'><b>8.2.</b> Poisoning</a> </li> </ul> </li> <li><a href='concurrency.html'><b>9.</b> Concurrency</a> <ul class='section'> <li><a href='races.html'><b>9.1.</b> Races</a> </li> <li><a href='send-and-sync.html'><b>9.2.</b> Send and Sync</a> </li> <li><a href='atomics.html'><b>9.3.</b> Atomics</a> </li> </ul> </li> <li><a href='vec.html'><b>10.</b> Implementing Vec</a> <ul class='section'> <li><a href='vec-layout.html'><b>10.1.</b> Layout</a> </li> <li><a href='vec-alloc.html'><b>10.2.</b> Allocating</a> </li> <li><a href='vec-push-pop.html'><b>10.3.</b> Push and Pop</a> </li> <li><a href='vec-dealloc.html'><b>10.4.</b> Deallocating</a> </li> <li><a href='vec-deref.html'><b>10.5.</b> Deref</a> </li> <li><a href='vec-insert-remove.html'><b>10.6.</b> Insert and Remove</a> </li> <li><a href='vec-into-iter.html'><b>10.7.</b> IntoIter</a> </li> <li><a href='vec-raw.html'><b>10.8.</b> RawVec</a> </li> <li><a class='active' href='vec-drain.html'><b>10.9.</b> Drain</a> </li> <li><a href='vec-zsts.html'><b>10.10.</b> Handling Zero-Sized Types</a> </li> <li><a href='vec-final.html'><b>10.11.</b> Final Code</a> </li> </ul> </li> <li><a href='arc-and-mutex.html'><b>11.</b> Implementing Arc and Mutex</a> </li> </ul> </div> <div id='page-wrapper'> <div id='page'> <blockquote class="header-caveat"> <p> <strong>注意: <a href="https://doc.rust-jp.rs/book-ja/">最新版のドキュメントをご覧ください。</a></strong>この第1版ドキュメントは古くなっており、最新情報が反映されていません。リンク先のドキュメントが現在の Rust の最新のドキュメントです。 </p> </blockquote> <h1 class="title">Drain</h1> <p>Let&#39;s move on to Drain. Drain is largely the same as IntoIter, except that instead of consuming the Vec, it borrows the Vec and leaves its allocation untouched. For now we&#39;ll only implement the &quot;basic&quot; full-range version.</p> <span class='rusttest'>fn main() { use std::marker::PhantomData; struct Drain&lt;&#39;a, T: &#39;a&gt; { // Need to bound the lifetime here, so we do it with `&amp;&#39;a mut Vec&lt;T&gt;` // because that&#39;s semantically what we contain. We&#39;re &quot;just&quot; calling // `pop()` and `remove(0)`. vec: PhantomData&lt;&amp;&#39;a mut Vec&lt;T&gt;&gt; start: *const T, end: *const T, } impl&lt;&#39;a, T&gt; Iterator for Drain&lt;&#39;a, T&gt; { type Item = T; fn next(&amp;mut self) -&gt; Option&lt;T&gt; { if self.start == self.end { None }</span><pre class='rust rust-example-rendered'> <span class='kw'>use</span> <span class='ident'>std</span>::<span class='ident'>marker</span>::<span class='ident'>PhantomData</span>; <span class='kw'>struct</span> <span class='ident'>Drain</span><span class='op'>&lt;</span><span class='lifetime'>&#39;a</span>, <span class='ident'>T</span>: <span class='lifetime'>&#39;a</span><span class='op'>&gt;</span> { <span class='comment'>// Need to bound the lifetime here, so we do it with `&amp;&#39;a mut Vec&lt;T&gt;`</span> <span class='comment'>// because that&#39;s semantically what we contain. We&#39;re &quot;just&quot; calling</span> <span class='comment'>// `pop()` and `remove(0)`.</span> <span class='ident'>vec</span>: <span class='ident'>PhantomData</span><span class='op'>&lt;</span><span class='kw-2'>&amp;</span><span class='lifetime'>&#39;a</span> <span class='kw-2'>mut</span> <span class='ident'>Vec</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;&gt;</span> <span class='ident'>start</span>: <span class='op'>*</span><span class='kw'>const</span> <span class='ident'>T</span>, <span class='ident'>end</span>: <span class='op'>*</span><span class='kw'>const</span> <span class='ident'>T</span>, } <span class='kw'>impl</span><span class='op'>&lt;</span><span class='lifetime'>&#39;a</span>, <span class='ident'>T</span><span class='op'>&gt;</span> <span class='ident'>Iterator</span> <span class='kw'>for</span> <span class='ident'>Drain</span><span class='op'>&lt;</span><span class='lifetime'>&#39;a</span>, <span class='ident'>T</span><span class='op'>&gt;</span> { <span class='kw'>type</span> <span class='ident'>Item</span> <span class='op'>=</span> <span class='ident'>T</span>; <span class='kw'>fn</span> <span class='ident'>next</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>) <span class='op'>-&gt;</span> <span class='prelude-ty'>Option</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> { <span class='kw'>if</span> <span class='self'>self</span>.<span class='ident'>start</span> <span class='op'>==</span> <span class='self'>self</span>.<span class='ident'>end</span> { <span class='prelude-val'>None</span></pre> <p>-- wait, this is seeming familiar. Let&#39;s do some more compression. Both IntoIter and Drain have the exact same structure, let&#39;s just factor it out.</p> <span class='rusttest'>fn main() { struct RawValIter&lt;T&gt; { start: *const T, end: *const T, } impl&lt;T&gt; RawValIter&lt;T&gt; { // unsafe to construct because it has no associated lifetimes. // This is necessary to store a RawValIter in the same struct as // its actual allocation. OK since it&#39;s a private implementation // detail. unsafe fn new(slice: &amp;[T]) -&gt; Self { RawValIter { start: slice.as_ptr(), end: if slice.len() == 0 { // if `len = 0`, then this is not actually allocated memory. // Need to avoid offsetting because that will give wrong // information to LLVM via GEP. slice.as_ptr() } else { slice.as_ptr().offset(slice.len() as isize) } } } } // Iterator and DoubleEndedIterator impls identical to IntoIter. }</span><pre class='rust rust-example-rendered'> <span class='kw'>struct</span> <span class='ident'>RawValIter</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> { <span class='ident'>start</span>: <span class='op'>*</span><span class='kw'>const</span> <span class='ident'>T</span>, <span class='ident'>end</span>: <span class='op'>*</span><span class='kw'>const</span> <span class='ident'>T</span>, } <span class='kw'>impl</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> <span class='ident'>RawValIter</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> { <span class='comment'>// unsafe to construct because it has no associated lifetimes.</span> <span class='comment'>// This is necessary to store a RawValIter in the same struct as</span> <span class='comment'>// its actual allocation. OK since it&#39;s a private implementation</span> <span class='comment'>// detail.</span> <span class='kw'>unsafe</span> <span class='kw'>fn</span> <span class='ident'>new</span>(<span class='ident'>slice</span>: <span class='kw-2'>&amp;</span>[<span class='ident'>T</span>]) <span class='op'>-&gt;</span> <span class='self'>Self</span> { <span class='ident'>RawValIter</span> { <span class='ident'>start</span>: <span class='ident'>slice</span>.<span class='ident'>as_ptr</span>(), <span class='ident'>end</span>: <span class='kw'>if</span> <span class='ident'>slice</span>.<span class='ident'>len</span>() <span class='op'>==</span> <span class='number'>0</span> { <span class='comment'>// if `len = 0`, then this is not actually allocated memory.</span> <span class='comment'>// Need to avoid offsetting because that will give wrong</span> <span class='comment'>// information to LLVM via GEP.</span> <span class='ident'>slice</span>.<span class='ident'>as_ptr</span>() } <span class='kw'>else</span> { <span class='ident'>slice</span>.<span class='ident'>as_ptr</span>().<span class='ident'>offset</span>(<span class='ident'>slice</span>.<span class='ident'>len</span>() <span class='kw'>as</span> <span class='ident'>isize</span>) } } } } <span class='comment'>// Iterator and DoubleEndedIterator impls identical to IntoIter.</span></pre> <p>And IntoIter becomes the following:</p> <span class='rusttest'>fn main() { pub struct IntoIter&lt;T&gt; { _buf: RawVec&lt;T&gt;, // we don&#39;t actually care about this. Just need it to live. iter: RawValIter&lt;T&gt;, } impl&lt;T&gt; Iterator for IntoIter&lt;T&gt; { type Item = T; fn next(&amp;mut self) -&gt; Option&lt;T&gt; { self.iter.next() } fn size_hint(&amp;self) -&gt; (usize, Option&lt;usize&gt;) { self.iter.size_hint() } } impl&lt;T&gt; DoubleEndedIterator for IntoIter&lt;T&gt; { fn next_back(&amp;mut self) -&gt; Option&lt;T&gt; { self.iter.next_back() } } impl&lt;T&gt; Drop for IntoIter&lt;T&gt; { fn drop(&amp;mut self) { for _ in &amp;mut self.iter {} } } impl&lt;T&gt; Vec&lt;T&gt; { pub fn into_iter(self) -&gt; IntoIter&lt;T&gt; { unsafe { let iter = RawValIter::new(&amp;self); let buf = ptr::read(&amp;self.buf); mem::forget(self); IntoIter { iter: iter, _buf: buf, } } } } }</span><pre class='rust rust-example-rendered'> <span class='kw'>pub</span> <span class='kw'>struct</span> <span class='ident'>IntoIter</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> { <span class='ident'>_buf</span>: <span class='ident'>RawVec</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span>, <span class='comment'>// we don&#39;t actually care about this. Just need it to live.</span> <span class='ident'>iter</span>: <span class='ident'>RawValIter</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span>, } <span class='kw'>impl</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> <span class='ident'>Iterator</span> <span class='kw'>for</span> <span class='ident'>IntoIter</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> { <span class='kw'>type</span> <span class='ident'>Item</span> <span class='op'>=</span> <span class='ident'>T</span>; <span class='kw'>fn</span> <span class='ident'>next</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>) <span class='op'>-&gt;</span> <span class='prelude-ty'>Option</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> { <span class='self'>self</span>.<span class='ident'>iter</span>.<span class='ident'>next</span>() } <span class='kw'>fn</span> <span class='ident'>size_hint</span>(<span class='kw-2'>&amp;</span><span class='self'>self</span>) <span class='op'>-&gt;</span> (<span class='ident'>usize</span>, <span class='prelude-ty'>Option</span><span class='op'>&lt;</span><span class='ident'>usize</span><span class='op'>&gt;</span>) { <span class='self'>self</span>.<span class='ident'>iter</span>.<span class='ident'>size_hint</span>() } } <span class='kw'>impl</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> <span class='ident'>DoubleEndedIterator</span> <span class='kw'>for</span> <span class='ident'>IntoIter</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> { <span class='kw'>fn</span> <span class='ident'>next_back</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>) <span class='op'>-&gt;</span> <span class='prelude-ty'>Option</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> { <span class='self'>self</span>.<span class='ident'>iter</span>.<span class='ident'>next_back</span>() } } <span class='kw'>impl</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> <span class='ident'>Drop</span> <span class='kw'>for</span> <span class='ident'>IntoIter</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> { <span class='kw'>fn</span> <span class='ident'>drop</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>) { <span class='kw'>for</span> _ <span class='kw'>in</span> <span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>.<span class='ident'>iter</span> {} } } <span class='kw'>impl</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> <span class='ident'>Vec</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> { <span class='kw'>pub</span> <span class='kw'>fn</span> <span class='ident'>into_iter</span>(<span class='self'>self</span>) <span class='op'>-&gt;</span> <span class='ident'>IntoIter</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> { <span class='kw'>unsafe</span> { <span class='kw'>let</span> <span class='ident'>iter</span> <span class='op'>=</span> <span class='ident'>RawValIter</span>::<span class='ident'>new</span>(<span class='kw-2'>&amp;</span><span class='self'>self</span>); <span class='kw'>let</span> <span class='ident'>buf</span> <span class='op'>=</span> <span class='ident'>ptr</span>::<span class='ident'>read</span>(<span class='kw-2'>&amp;</span><span class='self'>self</span>.<span class='ident'>buf</span>); <span class='ident'>mem</span>::<span class='ident'>forget</span>(<span class='self'>self</span>); <span class='ident'>IntoIter</span> { <span class='ident'>iter</span>: <span class='ident'>iter</span>, <span class='ident'>_buf</span>: <span class='ident'>buf</span>, } } } }</pre> <p>Note that I&#39;ve left a few quirks in this design to make upgrading Drain to work with arbitrary subranges a bit easier. In particular we <em>could</em> have RawValIter drain itself on drop, but that won&#39;t work right for a more complex Drain. We also take a slice to simplify Drain initialization.</p> <p>Alright, now Drain is really easy:</p> <span class='rusttest'>fn main() { use std::marker::PhantomData; pub struct Drain&lt;&#39;a, T: &#39;a&gt; { vec: PhantomData&lt;&amp;&#39;a mut Vec&lt;T&gt;&gt;, iter: RawValIter&lt;T&gt;, } impl&lt;&#39;a, T&gt; Iterator for Drain&lt;&#39;a, T&gt; { type Item = T; fn next(&amp;mut self) -&gt; Option&lt;T&gt; { self.iter.next() } fn size_hint(&amp;self) -&gt; (usize, Option&lt;usize&gt;) { self.iter.size_hint() } } impl&lt;&#39;a, T&gt; DoubleEndedIterator for Drain&lt;&#39;a, T&gt; { fn next_back(&amp;mut self) -&gt; Option&lt;T&gt; { self.iter.next_back() } } impl&lt;&#39;a, T&gt; Drop for Drain&lt;&#39;a, T&gt; { fn drop(&amp;mut self) { for _ in &amp;mut self.iter {} } } impl&lt;T&gt; Vec&lt;T&gt; { pub fn drain(&amp;mut self) -&gt; Drain&lt;T&gt; { unsafe { let iter = RawValIter::new(&amp;self); // this is a mem::forget safety thing. If Drain is forgotten, we just // leak the whole Vec&#39;s contents. Also we need to do this *eventually* // anyway, so why not do it now? self.len = 0; Drain { iter: iter, vec: PhantomData, } } } } }</span><pre class='rust rust-example-rendered'> <span class='kw'>use</span> <span class='ident'>std</span>::<span class='ident'>marker</span>::<span class='ident'>PhantomData</span>; <span class='kw'>pub</span> <span class='kw'>struct</span> <span class='ident'>Drain</span><span class='op'>&lt;</span><span class='lifetime'>&#39;a</span>, <span class='ident'>T</span>: <span class='lifetime'>&#39;a</span><span class='op'>&gt;</span> { <span class='ident'>vec</span>: <span class='ident'>PhantomData</span><span class='op'>&lt;</span><span class='kw-2'>&amp;</span><span class='lifetime'>&#39;a</span> <span class='kw-2'>mut</span> <span class='ident'>Vec</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;&gt;</span>, <span class='ident'>iter</span>: <span class='ident'>RawValIter</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span>, } <span class='kw'>impl</span><span class='op'>&lt;</span><span class='lifetime'>&#39;a</span>, <span class='ident'>T</span><span class='op'>&gt;</span> <span class='ident'>Iterator</span> <span class='kw'>for</span> <span class='ident'>Drain</span><span class='op'>&lt;</span><span class='lifetime'>&#39;a</span>, <span class='ident'>T</span><span class='op'>&gt;</span> { <span class='kw'>type</span> <span class='ident'>Item</span> <span class='op'>=</span> <span class='ident'>T</span>; <span class='kw'>fn</span> <span class='ident'>next</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>) <span class='op'>-&gt;</span> <span class='prelude-ty'>Option</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> { <span class='self'>self</span>.<span class='ident'>iter</span>.<span class='ident'>next</span>() } <span class='kw'>fn</span> <span class='ident'>size_hint</span>(<span class='kw-2'>&amp;</span><span class='self'>self</span>) <span class='op'>-&gt;</span> (<span class='ident'>usize</span>, <span class='prelude-ty'>Option</span><span class='op'>&lt;</span><span class='ident'>usize</span><span class='op'>&gt;</span>) { <span class='self'>self</span>.<span class='ident'>iter</span>.<span class='ident'>size_hint</span>() } } <span class='kw'>impl</span><span class='op'>&lt;</span><span class='lifetime'>&#39;a</span>, <span class='ident'>T</span><span class='op'>&gt;</span> <span class='ident'>DoubleEndedIterator</span> <span class='kw'>for</span> <span class='ident'>Drain</span><span class='op'>&lt;</span><span class='lifetime'>&#39;a</span>, <span class='ident'>T</span><span class='op'>&gt;</span> { <span class='kw'>fn</span> <span class='ident'>next_back</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>) <span class='op'>-&gt;</span> <span class='prelude-ty'>Option</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> { <span class='self'>self</span>.<span class='ident'>iter</span>.<span class='ident'>next_back</span>() } } <span class='kw'>impl</span><span class='op'>&lt;</span><span class='lifetime'>&#39;a</span>, <span class='ident'>T</span><span class='op'>&gt;</span> <span class='ident'>Drop</span> <span class='kw'>for</span> <span class='ident'>Drain</span><span class='op'>&lt;</span><span class='lifetime'>&#39;a</span>, <span class='ident'>T</span><span class='op'>&gt;</span> { <span class='kw'>fn</span> <span class='ident'>drop</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>) { <span class='kw'>for</span> _ <span class='kw'>in</span> <span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>.<span class='ident'>iter</span> {} } } <span class='kw'>impl</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> <span class='ident'>Vec</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> { <span class='kw'>pub</span> <span class='kw'>fn</span> <span class='ident'>drain</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>) <span class='op'>-&gt;</span> <span class='ident'>Drain</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> { <span class='kw'>unsafe</span> { <span class='kw'>let</span> <span class='ident'>iter</span> <span class='op'>=</span> <span class='ident'>RawValIter</span>::<span class='ident'>new</span>(<span class='kw-2'>&amp;</span><span class='self'>self</span>); <span class='comment'>// this is a mem::forget safety thing. If Drain is forgotten, we just</span> <span class='comment'>// leak the whole Vec&#39;s contents. Also we need to do this *eventually*</span> <span class='comment'>// anyway, so why not do it now?</span> <span class='self'>self</span>.<span class='ident'>len</span> <span class='op'>=</span> <span class='number'>0</span>; <span class='ident'>Drain</span> { <span class='ident'>iter</span>: <span class='ident'>iter</span>, <span class='ident'>vec</span>: <span class='ident'>PhantomData</span>, } } } }</pre> <p>For more details on the <code>mem::forget</code> problem, see the <a href="leaking.html">section on leaks</a>.</p> <script type="text/javascript"> window.playgroundUrl = "https://play.rust-lang.org"; </script> <script src='rustbook.js'></script> <script src='playpen.js'></script> </div></div> </body> </html> <|start_filename|>docs/1.9/style/style/braces.html<|end_filename|> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="generator" content="rustdoc"> <title>Braces, semicolons, and commas [FIXME: needs RFC]</title> <link rel="stylesheet" type="text/css" href="../rustbook.css"> <meta name="robots" content="noindex"> </head> <body class="rustdoc"> <!--[if lte IE 8]> <div class="warning"> This old browser is unsupported and will most likely display funky things. </div> <![endif]--> <div id="nav"> <button id="toggle-nav"> <span class="sr-only">Toggle navigation</span> <span class="bar"></span> <span class="bar"></span> <span class="bar"></span> </button> </div> <div id='toc' class='mobile-hidden'> <ul class='chapter'> <li><a href='../README.html'><b>1.</b> Introduction</a> </li> <li><a href='../style/README.html'><b>2.</b> Style</a> <ul class='section'> <li><a href='../style/whitespace.html'><b>2.1.</b> Whitespace</a> </li> <li><a href='../style/comments.html'><b>2.2.</b> Comments</a> </li> <li><a class='active' href='../style/braces.html'><b>2.3.</b> Braces, semicolons, commas</a> </li> <li><a href='../style/naming/README.html'><b>2.4.</b> Naming</a> <ul class='section'> <li><a href='../style/naming/ownership.html'><b>2.4.1.</b> Ownership variants</a> </li> <li><a href='../style/naming/containers.html'><b>2.4.2.</b> Containers/wrappers</a> </li> <li><a href='../style/naming/conversions.html'><b>2.4.3.</b> Conversions</a> </li> <li><a href='../style/naming/iterators.html'><b>2.4.4.</b> Iterators</a> </li> </ul> </li> <li><a href='../style/imports.html'><b>2.5.</b> Imports</a> </li> <li><a href='../style/organization.html'><b>2.6.</b> Organization</a> </li> </ul> </li> <li><a href='../features/README.html'><b>3.</b> Guidelines by Rust feature</a> <ul class='section'> <li><a href='../features/let.html'><b>3.1.</b> Let binding</a> </li> <li><a href='../features/match.html'><b>3.2.</b> Pattern matching</a> </li> <li><a href='../features/loops.html'><b>3.3.</b> Loops</a> </li> <li><a href='../features/functions-and-methods/README.html'><b>3.4.</b> Functions and methods</a> <ul class='section'> <li><a href='../features/functions-and-methods/input.html'><b>3.4.1.</b> Input</a> </li> <li><a href='../features/functions-and-methods/output.html'><b>3.4.2.</b> Output</a> </li> <li><a href='../features/functions-and-methods/convenience.html'><b>3.4.3.</b> For convenience</a> </li> </ul> </li> <li><a href='../features/types/README.html'><b>3.5.</b> Types</a> <ul class='section'> <li><a href='../features/types/conversions.html'><b>3.5.1.</b> Conversions</a> </li> <li><a href='../features/types/newtype.html'><b>3.5.2.</b> The newtype pattern</a> </li> </ul> </li> <li><a href='../features/traits/README.html'><b>3.6.</b> Traits</a> <ul class='section'> <li><a href='../features/traits/generics.html'><b>3.6.1.</b> For generics</a> </li> <li><a href='../features/traits/objects.html'><b>3.6.2.</b> For objects</a> </li> <li><a href='../features/traits/overloading.html'><b>3.6.3.</b> For overloading</a> </li> <li><a href='../features/traits/extensions.html'><b>3.6.4.</b> For extensions</a> </li> <li><a href='../features/traits/reuse.html'><b>3.6.5.</b> For reuse</a> </li> <li><a href='../features/traits/common.html'><b>3.6.6.</b> Common traits</a> </li> </ul> </li> <li><a href='../features/modules.html'><b>3.7.</b> Modules</a> </li> <li><a href='../features/crates.html'><b>3.8.</b> Crates</a> </li> </ul> </li> <li><a href='../ownership/README.html'><b>4.</b> Ownership and resources</a> <ul class='section'> <li><a href='../ownership/constructors.html'><b>4.1.</b> Constructors</a> </li> <li><a href='../ownership/builders.html'><b>4.2.</b> Builders</a> </li> <li><a href='../ownership/destructors.html'><b>4.3.</b> Destructors</a> </li> <li><a href='../ownership/raii.html'><b>4.4.</b> RAII</a> </li> <li><a href='../ownership/cell-smart.html'><b>4.5.</b> Cells and smart pointers</a> </li> </ul> </li> <li><a href='../errors/README.html'><b>5.</b> Errors</a> <ul class='section'> <li><a href='../errors/signaling.html'><b>5.1.</b> Signaling</a> </li> <li><a href='../errors/handling.html'><b>5.2.</b> Handling</a> </li> <li><a href='../errors/propagation.html'><b>5.3.</b> Propagation</a> </li> <li><a href='../errors/ergonomics.html'><b>5.4.</b> Ergonomics</a> </li> </ul> </li> <li><a href='../safety/README.html'><b>6.</b> Safety and guarantees</a> <ul class='section'> <li><a href='../safety/unsafe.html'><b>6.1.</b> Using unsafe</a> </li> <li><a href='../safety/lib-guarantees.html'><b>6.2.</b> Library guarantees</a> </li> </ul> </li> <li><a href='../testing/README.html'><b>7.</b> Testing</a> <ul class='section'> <li><a href='../testing/unit.html'><b>7.1.</b> Unit testing</a> </li> </ul> </li> <li><a href='../platform.html'><b>8.</b> FFI, platform-specific code</a> </li> </ul> </div> <div id='page-wrapper'> <div id='page'> <blockquote class="header-caveat"> <p> <strong>注意: <a href="https://doc.rust-jp.rs/book-ja/">最新版のドキュメントをご覧ください。</a></strong>この第1版ドキュメントは古くなっており、最新情報が反映されていません。リンク先のドキュメントが現在の Rust の最新のドキュメントです。 </p> </blockquote> <h1 class="title">Braces, semicolons, and commas [FIXME: needs RFC]</h1> <h3 id='opening-braces-always-go-on-the-same-line' class='section-header'><a href='#opening-braces-always-go-on-the-same-line'>Opening braces always go on the same line.</a></h3> <span class='rusttest'>fn main() { fn foo() { ... } fn frobnicate(a: Bar, b: Bar, c: Bar, d: Bar) -&gt; Bar { ... } trait Bar { fn baz(&amp;self); } impl Bar for Baz { fn baz(&amp;self) { ... } } frob(|x| { x.transpose() }) }</span><pre class='rust rust-example-rendered'> <span class='kw'>fn</span> <span class='ident'>foo</span>() { ... } <span class='kw'>fn</span> <span class='ident'>frobnicate</span>(<span class='ident'>a</span>: <span class='ident'>Bar</span>, <span class='ident'>b</span>: <span class='ident'>Bar</span>, <span class='ident'>c</span>: <span class='ident'>Bar</span>, <span class='ident'>d</span>: <span class='ident'>Bar</span>) <span class='op'>-&gt;</span> <span class='ident'>Bar</span> { ... } <span class='kw'>trait</span> <span class='ident'>Bar</span> { <span class='kw'>fn</span> <span class='ident'>baz</span>(<span class='kw-2'>&amp;</span><span class='self'>self</span>); } <span class='kw'>impl</span> <span class='ident'>Bar</span> <span class='kw'>for</span> <span class='ident'>Baz</span> { <span class='kw'>fn</span> <span class='ident'>baz</span>(<span class='kw-2'>&amp;</span><span class='self'>self</span>) { ... } } <span class='ident'>frob</span>(<span class='op'>|</span><span class='ident'>x</span><span class='op'>|</span> { <span class='ident'>x</span>.<span class='ident'>transpose</span>() })</pre> <h3 id='match-arms-get-braces-except-for-single-line-expressions' class='section-header'><a href='#match-arms-get-braces-except-for-single-line-expressions'><code>match</code> arms get braces, except for single-line expressions.</a></h3> <span class='rusttest'>fn main() { match foo { bar =&gt; baz, quux =&gt; { do_something(); do_something_else() } } }</span><pre class='rust rust-example-rendered'> <span class='kw'>match</span> <span class='ident'>foo</span> { <span class='ident'>bar</span> <span class='op'>=&gt;</span> <span class='ident'>baz</span>, <span class='ident'>quux</span> <span class='op'>=&gt;</span> { <span class='ident'>do_something</span>(); <span class='ident'>do_something_else</span>() } }</pre> <h3 id='return-statements-get-semicolons' class='section-header'><a href='#return-statements-get-semicolons'><code>return</code> statements get semicolons.</a></h3> <span class='rusttest'>fn main() { fn foo() { do_something(); if condition() { return; } do_something_else(); } }</span><pre class='rust rust-example-rendered'> <span class='kw'>fn</span> <span class='ident'>foo</span>() { <span class='ident'>do_something</span>(); <span class='kw'>if</span> <span class='ident'>condition</span>() { <span class='kw'>return</span>; } <span class='ident'>do_something_else</span>(); }</pre> <h3 id='trailing-commas' class='section-header'><a href='#trailing-commas'>Trailing commas</a></h3> <blockquote> <p><strong>[FIXME]</strong> We should have a guideline for when to include trailing commas in <code>struct</code>s, <code>match</code>es, function calls, etc.</p> <p>One possible rule: a trailing comma should be included whenever the closing delimiter appears on a separate line:</p> </blockquote> <span class='rusttest'>fn main() { Foo { bar: 0, baz: 1 } Foo { bar: 0, baz: 1, } match a_thing { None =&gt; 0, Some(x) =&gt; 1, } }</span><pre class='rust rust-example-rendered'> <span class='ident'>Foo</span> { <span class='ident'>bar</span>: <span class='number'>0</span>, <span class='ident'>baz</span>: <span class='number'>1</span> } <span class='ident'>Foo</span> { <span class='ident'>bar</span>: <span class='number'>0</span>, <span class='ident'>baz</span>: <span class='number'>1</span>, } <span class='kw'>match</span> <span class='ident'>a_thing</span> { <span class='prelude-val'>None</span> <span class='op'>=&gt;</span> <span class='number'>0</span>, <span class='prelude-val'>Some</span>(<span class='ident'>x</span>) <span class='op'>=&gt;</span> <span class='number'>1</span>, }</pre> <script type="text/javascript"> window.playgroundUrl = "https://play.rust-lang.org"; </script> <script src='rustbook.js'></script> <script src='playpen.js'></script> </div></div> </body> </html> <|start_filename|>docs/1.9/book/compiler-plugins.html<|end_filename|> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="generator" content="rustdoc"> <title>コンパイラプラグイン</title> <link rel="stylesheet" type="text/css" href="rustbook.css"> <meta name="robots" content="noindex"> </head> <body class="rustdoc"> <!--[if lte IE 8]> <div class="warning"> This old browser is unsupported and will most likely display funky things. </div> <![endif]--> <div id="nav"> <button id="toggle-nav"> <span class="sr-only">Toggle navigation</span> <span class="bar"></span> <span class="bar"></span> <span class="bar"></span> </button> </div> <div id='toc' class='mobile-hidden'> <ul class='chapter'> <li><a href='README.html'><b>1.</b> Introduction</a> </li> <li><a href='getting-started.html'><b>2.</b> はじめる</a> </li> <li><a href='guessing-game.html'><b>3.</b> チュートリアル:数当てゲーム</a> </li> <li><a href='syntax-and-semantics.html'><b>4.</b> シンタックスとセマンティクス</a> <ul class='section'> <li><a href='variable-bindings.html'><b>4.1.</b> 変数束縛</a> </li> <li><a href='functions.html'><b>4.2.</b> 関数</a> </li> <li><a href='primitive-types.html'><b>4.3.</b> プリミティブ型</a> </li> <li><a href='comments.html'><b>4.4.</b> コメント</a> </li> <li><a href='if.html'><b>4.5.</b> if</a> </li> <li><a href='loops.html'><b>4.6.</b> ループ</a> </li> <li><a href='vectors.html'><b>4.7.</b> ベクタ</a> </li> <li><a href='ownership.html'><b>4.8.</b> 所有権</a> </li> <li><a href='references-and-borrowing.html'><b>4.9.</b> 参照と借用</a> </li> <li><a href='lifetimes.html'><b>4.10.</b> ライフタイム</a> </li> <li><a href='mutability.html'><b>4.11.</b> ミュータビリティ</a> </li> <li><a href='structs.html'><b>4.12.</b> 構造体</a> </li> <li><a href='enums.html'><b>4.13.</b> 列挙型</a> </li> <li><a href='match.html'><b>4.14.</b> マッチ</a> </li> <li><a href='patterns.html'><b>4.15.</b> パターン</a> </li> <li><a href='method-syntax.html'><b>4.16.</b> メソッド構文</a> </li> <li><a href='strings.html'><b>4.17.</b> 文字列</a> </li> <li><a href='generics.html'><b>4.18.</b> ジェネリクス</a> </li> <li><a href='traits.html'><b>4.19.</b> トレイト</a> </li> <li><a href='drop.html'><b>4.20.</b> Drop</a> </li> <li><a href='if-let.html'><b>4.21.</b> if let</a> </li> <li><a href='trait-objects.html'><b>4.22.</b> トレイトオブジェクト</a> </li> <li><a href='closures.html'><b>4.23.</b> クロージャ</a> </li> <li><a href='ufcs.html'><b>4.24.</b> 共通の関数呼出構文</a> </li> <li><a href='crates-and-modules.html'><b>4.25.</b> クレートとモジュール</a> </li> <li><a href='const-and-static.html'><b>4.26.</b> `const` と `static`</a> </li> <li><a href='attributes.html'><b>4.27.</b> アトリビュート</a> </li> <li><a href='type-aliases.html'><b>4.28.</b> `type` エイリアス</a> </li> <li><a href='casting-between-types.html'><b>4.29.</b> 型間のキャスト</a> </li> <li><a href='associated-types.html'><b>4.30.</b> 関連型</a> </li> <li><a href='unsized-types.html'><b>4.31.</b> サイズ不定型</a> </li> <li><a href='operators-and-overloading.html'><b>4.32.</b> 演算子とオーバーロード</a> </li> <li><a href='deref-coercions.html'><b>4.33.</b> Derefによる型強制</a> </li> <li><a href='macros.html'><b>4.34.</b> マクロ</a> </li> <li><a href='raw-pointers.html'><b>4.35.</b> 生ポインタ</a> </li> <li><a href='unsafe.html'><b>4.36.</b> `unsafe`</a> </li> </ul> </li> <li><a href='effective-rust.html'><b>5.</b> Effective Rust</a> <ul class='section'> <li><a href='the-stack-and-the-heap.html'><b>5.1.</b> スタックとヒープ</a> </li> <li><a href='testing.html'><b>5.2.</b> テスト</a> </li> <li><a href='conditional-compilation.html'><b>5.3.</b> 条件付きコンパイル</a> </li> <li><a href='documentation.html'><b>5.4.</b> ドキュメント</a> </li> <li><a href='iterators.html'><b>5.5.</b> イテレータ</a> </li> <li><a href='concurrency.html'><b>5.6.</b> 並行性</a> </li> <li><a href='error-handling.html'><b>5.7.</b> エラーハンドリング</a> </li> <li><a href='choosing-your-guarantees.html'><b>5.8.</b> 保証を選ぶ</a> </li> <li><a href='ffi.html'><b>5.9.</b> 他言語関数インターフェース</a> </li> <li><a href='borrow-and-asref.html'><b>5.10.</b> BorrowとAsRef</a> </li> <li><a href='release-channels.html'><b>5.11.</b> リリースチャネル</a> </li> <li><a href='using-rust-without-the-standard-library.html'><b>5.12.</b> 標準ライブラリ無しでRustを使う</a> </li> </ul> </li> <li><a href='nightly-rust.html'><b>6.</b> Nightly Rust</a> <ul class='section'> <li><a class='active' href='compiler-plugins.html'><b>6.1.</b> コンパイラプラグイン</a> </li> <li><a href='inline-assembly.html'><b>6.2.</b> インラインアセンブリ</a> </li> <li><a href='no-stdlib.html'><b>6.3.</b> No stdlib</a> </li> <li><a href='intrinsics.html'><b>6.4.</b> Intrinsic</a> </li> <li><a href='lang-items.html'><b>6.5.</b> 言語アイテム</a> </li> <li><a href='advanced-linking.html'><b>6.6.</b> 高度なリンキング</a> </li> <li><a href='benchmark-tests.html'><b>6.7.</b> ベンチマークテスト</a> </li> <li><a href='box-syntax-and-patterns.html'><b>6.8.</b> Box構文とパターン</a> </li> <li><a href='slice-patterns.html'><b>6.9.</b> スライスパターン</a> </li> <li><a href='associated-constants.html'><b>6.10.</b> 関連定数</a> </li> <li><a href='custom-allocators.html'><b>6.11.</b> カスタムアロケータ</a> </li> </ul> </li> <li><a href='glossary.html'><b>7.</b> 用語集</a> </li> <li><a href='syntax-index.html'><b>8.</b> 構文の索引</a> </li> <li><a href='bibliography.html'><b>9.</b> 関係書目</a> </li> </ul> </div> <div id='page-wrapper'> <div id='page'> <blockquote class="header-caveat"> <p> <strong>注意: <a href="https://doc.rust-jp.rs/book-ja/">最新版のドキュメントをご覧ください。</a></strong>この第1版ドキュメントは古くなっており、最新情報が反映されていません。リンク先のドキュメントが現在の Rust の最新のドキュメントです。 </p> </blockquote> <h1 class="title">コンパイラプラグイン</h1> <!-- % Compiler Plugins --> <!-- # Introduction --> <h1 id='イントロダクション' class='section-header'><a href='#イントロダクション'>イントロダクション</a></h1> <!-- `rustc` can load compiler plugins, which are user-provided libraries that --> <!-- extend the compiler's behavior with new syntax extensions, lint checks, etc. --> <p><code>rustc</code> はコンパイラプラグイン、ユーザの提供する構文拡張や構文チェックなどのコンパイラの振舞を拡張するライブラリをロード出来ます。</p> <!-- A plugin is a dynamic library crate with a designated *registrar* function that --> <!-- registers extensions with `rustc`. Other crates can load these extensions using --> <!-- the crate attribute `#![plugin(...)]`. See the --> <!-- `rustc_plugin` documentation for more about the --> <!-- mechanics of defining and loading a plugin. --> <p>プラグインとは <code>rustc</code> に拡張を登録するための、指定された <em>登録用</em> 関数を持った動的ライブラリのクレートです。 他のクレートはこれらのプラグインを <code>#![plugin(...)]</code> クレートアトリビュートでロード出来ます。 プラグインの定義、ロードの仕組みについて詳しくは <code>rustc_plugin</code> を参照して下さい。</p> <!-- If present, arguments passed as `#![plugin(foo(... args ...))]` are not --> <!-- interpreted by rustc itself. They are provided to the plugin through the --> <!-- `Registry`'s `args` method. --> <p><code>#![plugin(foo(... args ...))]</code> のように渡された引数があるなら、それらはrustc自身によっては解釈されません。 <code>Registry</code> の<code>args</code> メソッドを通じてプラグインに渡されます。</p> <!-- In the vast majority of cases, a plugin should *only* be used through --> <!-- `#![plugin]` and not through an `extern crate` item. Linking a plugin would --> <!-- pull in all of libsyntax and librustc as dependencies of your crate. This is --> <!-- generally unwanted unless you are building another plugin. The --> <!-- `plugin_as_library` lint checks these guidelines. --> <p>ほとんどの場合で、プラグインは <code>#![plugin]</code> を通じて <em>のみ</em> 使われるべきで、 <code>extern crate</code> を通じて使われるべきではありません。 プラグインをリンクするとlibsyntaxとlibrustcの全てをクレートの依存に引き込んでしまいます。 これは別のプラグインを作っているのでもない限り一般的には望まぬ挙動です。 <code>plugin_as_library</code> チェッカによってこのガイドラインは検査されます。</p> <!-- The usual practice is to put compiler plugins in their own crate, separate from --> <!-- any `macro_rules!` macros or ordinary Rust code meant to be used by consumers --> <!-- of a library. --> <p>普通の慣行ではコンパイラプラグインはそれ専用のクレートに置かれて、 <code>macro_rules!</code> マクロやコンシューマが使うライブラリのコードとは分けられます。</p> <!-- # Syntax extensions --> <h1 id='構文拡張' class='section-header'><a href='#構文拡張'>構文拡張</a></h1> <!-- Plugins can extend Rust's syntax in various ways. One kind of syntax extension --> <!-- is the procedural macro. These are invoked the same way as [ordinary --> <!-- macros](macros.html), but the expansion is performed by arbitrary Rust --> <!-- code that manipulates syntax trees at --> <!-- compile time. --> <p>プラグインはRustの構文を様々な方法で拡張出来ます。構文拡張の1つに手続的マクロがあります。 これらは<a href="macros.html">普通のマクロ</a>と同じように実行されますが展開は任意の構文木をコンパイル時に操作するRustのコードが行います。</p> <!-- Let's write a plugin --> <!-- [`roman_numerals.rs`](https://github.com/rust-lang/rust/tree/master/src/test/auxiliary/roman_numerals.rs) --> <!-- that implements Roman numeral integer literals. --> <p>ローマ数字リテラルを実装する<a href="https://github.com/rust-lang/rust/tree/master/src/test/auxiliary/roman_numerals.rs"><code>roman_numerals.rs</code></a>を書いてみましょう。</p> <span class='rusttest'>fn main() { #![crate_type=&quot;dylib&quot;] #![feature(plugin_registrar, rustc_private)] extern crate syntax; extern crate rustc; extern crate rustc_plugin; use syntax::codemap::Span; use syntax::parse::token; use syntax::ast::TokenTree; use syntax::ext::base::{ExtCtxt, MacResult, DummyResult, MacEager}; // use syntax::ext::build::AstBuilder; // trait for expr_usize use syntax::ext::build::AstBuilder; // expr_usizeのトレイト use rustc_plugin::Registry; fn expand_rn(cx: &amp;mut ExtCtxt, sp: Span, args: &amp;[TokenTree]) -&gt; Box&lt;MacResult + &#39;static&gt; { static NUMERALS: &amp;&#39;static [(&amp;&#39;static str, usize)] = &amp;[ (&quot;M&quot;, 1000), (&quot;CM&quot;, 900), (&quot;D&quot;, 500), (&quot;CD&quot;, 400), (&quot;C&quot;, 100), (&quot;XC&quot;, 90), (&quot;L&quot;, 50), (&quot;XL&quot;, 40), (&quot;X&quot;, 10), (&quot;IX&quot;, 9), (&quot;V&quot;, 5), (&quot;IV&quot;, 4), (&quot;I&quot;, 1)]; if args.len() != 1 { cx.span_err( sp, &amp;format!(&quot;argument should be a single identifier, but got {} arguments&quot;, args.len())); return DummyResult::any(sp); } let text = match args[0] { TokenTree::Token(_, token::Ident(s, _)) =&gt; s.to_string(), _ =&gt; { cx.span_err(sp, &quot;argument should be a single identifier&quot;); return DummyResult::any(sp); } }; let mut text = &amp;*text; let mut total = 0; while !text.is_empty() { match NUMERALS.iter().find(|&amp;&amp;(rn, _)| text.starts_with(rn)) { Some(&amp;(rn, val)) =&gt; { total += val; text = &amp;text[rn.len()..]; } None =&gt; { cx.span_err(sp, &quot;invalid Roman numeral&quot;); return DummyResult::any(sp); } } } MacEager::expr(cx.expr_usize(sp, total)) } #[plugin_registrar] pub fn plugin_registrar(reg: &amp;mut Registry) { reg.register_macro(&quot;rn&quot;, expand_rn); } }</span><pre class='rust rust-example-rendered'> <span class='attribute'>#<span class='op'>!</span>[<span class='ident'>crate_type</span><span class='op'>=</span><span class='string'>&quot;dylib&quot;</span>]</span> <span class='attribute'>#<span class='op'>!</span>[<span class='ident'>feature</span>(<span class='ident'>plugin_registrar</span>, <span class='ident'>rustc_private</span>)]</span> <span class='kw'>extern</span> <span class='kw'>crate</span> <span class='ident'>syntax</span>; <span class='kw'>extern</span> <span class='kw'>crate</span> <span class='ident'>rustc</span>; <span class='kw'>extern</span> <span class='kw'>crate</span> <span class='ident'>rustc_plugin</span>; <span class='kw'>use</span> <span class='ident'>syntax</span>::<span class='ident'>codemap</span>::<span class='ident'>Span</span>; <span class='kw'>use</span> <span class='ident'>syntax</span>::<span class='ident'>parse</span>::<span class='ident'>token</span>; <span class='kw'>use</span> <span class='ident'>syntax</span>::<span class='ident'>ast</span>::<span class='ident'>TokenTree</span>; <span class='kw'>use</span> <span class='ident'>syntax</span>::<span class='ident'>ext</span>::<span class='ident'>base</span>::{<span class='ident'>ExtCtxt</span>, <span class='ident'>MacResult</span>, <span class='ident'>DummyResult</span>, <span class='ident'>MacEager</span>}; <span class='kw'>use</span> <span class='ident'>syntax</span>::<span class='ident'>ext</span>::<span class='ident'>build</span>::<span class='ident'>AstBuilder</span>; <span class='comment'>// expr_usizeのトレイト</span> <span class='kw'>use</span> <span class='ident'>rustc_plugin</span>::<span class='ident'>Registry</span>; <span class='kw'>fn</span> <span class='ident'>expand_rn</span>(<span class='ident'>cx</span>: <span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='ident'>ExtCtxt</span>, <span class='ident'>sp</span>: <span class='ident'>Span</span>, <span class='ident'>args</span>: <span class='kw-2'>&amp;</span>[<span class='ident'>TokenTree</span>]) <span class='op'>-&gt;</span> <span class='ident'>Box</span><span class='op'>&lt;</span><span class='ident'>MacResult</span> <span class='op'>+</span> <span class='lifetime'>&#39;static</span><span class='op'>&gt;</span> { <span class='kw'>static</span> <span class='ident'>NUMERALS</span>: <span class='kw-2'>&amp;</span><span class='lifetime'>&#39;static</span> [(<span class='kw-2'>&amp;</span><span class='lifetime'>&#39;static</span> <span class='ident'>str</span>, <span class='ident'>usize</span>)] <span class='op'>=</span> <span class='kw-2'>&amp;</span>[ (<span class='string'>&quot;M&quot;</span>, <span class='number'>1000</span>), (<span class='string'>&quot;CM&quot;</span>, <span class='number'>900</span>), (<span class='string'>&quot;D&quot;</span>, <span class='number'>500</span>), (<span class='string'>&quot;CD&quot;</span>, <span class='number'>400</span>), (<span class='string'>&quot;C&quot;</span>, <span class='number'>100</span>), (<span class='string'>&quot;XC&quot;</span>, <span class='number'>90</span>), (<span class='string'>&quot;L&quot;</span>, <span class='number'>50</span>), (<span class='string'>&quot;XL&quot;</span>, <span class='number'>40</span>), (<span class='string'>&quot;X&quot;</span>, <span class='number'>10</span>), (<span class='string'>&quot;IX&quot;</span>, <span class='number'>9</span>), (<span class='string'>&quot;V&quot;</span>, <span class='number'>5</span>), (<span class='string'>&quot;IV&quot;</span>, <span class='number'>4</span>), (<span class='string'>&quot;I&quot;</span>, <span class='number'>1</span>)]; <span class='kw'>if</span> <span class='ident'>args</span>.<span class='ident'>len</span>() <span class='op'>!=</span> <span class='number'>1</span> { <span class='ident'>cx</span>.<span class='ident'>span_err</span>( <span class='ident'>sp</span>, <span class='kw-2'>&amp;</span><span class='macro'>format</span><span class='macro'>!</span>(<span class='string'>&quot;argument should be a single identifier, but got {} arguments&quot;</span>, <span class='ident'>args</span>.<span class='ident'>len</span>())); <span class='kw'>return</span> <span class='ident'>DummyResult</span>::<span class='ident'>any</span>(<span class='ident'>sp</span>); } <span class='kw'>let</span> <span class='ident'>text</span> <span class='op'>=</span> <span class='kw'>match</span> <span class='ident'>args</span>[<span class='number'>0</span>] { <span class='ident'>TokenTree</span>::<span class='ident'>Token</span>(_, <span class='ident'>token</span>::<span class='ident'>Ident</span>(<span class='ident'>s</span>, _)) <span class='op'>=&gt;</span> <span class='ident'>s</span>.<span class='ident'>to_string</span>(), _ <span class='op'>=&gt;</span> { <span class='ident'>cx</span>.<span class='ident'>span_err</span>(<span class='ident'>sp</span>, <span class='string'>&quot;argument should be a single identifier&quot;</span>); <span class='kw'>return</span> <span class='ident'>DummyResult</span>::<span class='ident'>any</span>(<span class='ident'>sp</span>); } }; <span class='kw'>let</span> <span class='kw-2'>mut</span> <span class='ident'>text</span> <span class='op'>=</span> <span class='kw-2'>&amp;</span><span class='op'>*</span><span class='ident'>text</span>; <span class='kw'>let</span> <span class='kw-2'>mut</span> <span class='ident'>total</span> <span class='op'>=</span> <span class='number'>0</span>; <span class='kw'>while</span> <span class='op'>!</span><span class='ident'>text</span>.<span class='ident'>is_empty</span>() { <span class='kw'>match</span> <span class='ident'>NUMERALS</span>.<span class='ident'>iter</span>().<span class='ident'>find</span>(<span class='op'>|</span><span class='op'>&amp;&amp;</span>(<span class='ident'>rn</span>, _)<span class='op'>|</span> <span class='ident'>text</span>.<span class='ident'>starts_with</span>(<span class='ident'>rn</span>)) { <span class='prelude-val'>Some</span>(<span class='kw-2'>&amp;</span>(<span class='ident'>rn</span>, <span class='ident'>val</span>)) <span class='op'>=&gt;</span> { <span class='ident'>total</span> <span class='op'>+=</span> <span class='ident'>val</span>; <span class='ident'>text</span> <span class='op'>=</span> <span class='kw-2'>&amp;</span><span class='ident'>text</span>[<span class='ident'>rn</span>.<span class='ident'>len</span>()..]; } <span class='prelude-val'>None</span> <span class='op'>=&gt;</span> { <span class='ident'>cx</span>.<span class='ident'>span_err</span>(<span class='ident'>sp</span>, <span class='string'>&quot;invalid Roman numeral&quot;</span>); <span class='kw'>return</span> <span class='ident'>DummyResult</span>::<span class='ident'>any</span>(<span class='ident'>sp</span>); } } } <span class='ident'>MacEager</span>::<span class='ident'>expr</span>(<span class='ident'>cx</span>.<span class='ident'>expr_usize</span>(<span class='ident'>sp</span>, <span class='ident'>total</span>)) } <span class='attribute'>#[<span class='ident'>plugin_registrar</span>]</span> <span class='kw'>pub</span> <span class='kw'>fn</span> <span class='ident'>plugin_registrar</span>(<span class='ident'>reg</span>: <span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='ident'>Registry</span>) { <span class='ident'>reg</span>.<span class='ident'>register_macro</span>(<span class='string'>&quot;rn&quot;</span>, <span class='ident'>expand_rn</span>); }</pre> <!-- Then we can use `rn!()` like any other macro: --> <p><code>rn!()</code> マクロを他の任意のマクロと同じように使えます。</p> <span class='rusttest'>#![feature(plugin)] #![plugin(roman_numerals)] fn main() { assert_eq!(rn!(MMXV), 2015); } </span><pre class='rust rust-example-rendered'> <span class='attribute'>#<span class='op'>!</span>[<span class='ident'>feature</span>(<span class='ident'>plugin</span>)]</span> <span class='attribute'>#<span class='op'>!</span>[<span class='ident'>plugin</span>(<span class='ident'>roman_numerals</span>)]</span> <span class='kw'>fn</span> <span class='ident'>main</span>() { <span class='macro'>assert_eq</span><span class='macro'>!</span>(<span class='macro'>rn</span><span class='macro'>!</span>(<span class='ident'>MMXV</span>), <span class='number'>2015</span>); }</pre> <!-- The advantages over a simple `fn(&str) -> u32` are: --> <p>単純な <code>fn(&amp;str) -&gt; u32</code> に対する利点は</p> <!-- * The (arbitrarily complex) conversion is done at compile time. --> <!-- * Input validation is also performed at compile time. --> <!-- * It can be extended to allow use in patterns, which effectively gives --> <!-- a way to define new literal syntax for any data type. --> <ul> <li>(任意に複雑な)変換がコンパイル時に行なわれる</li> <li>入力バリデーションもコンパイル時に行なわれる</li> <li>パターンで使えるように拡張出来るので、実質的に任意のデータ型に対して新たなリテラル構文を与えられる</li> </ul> <!-- In addition to procedural macros, you can define new --> <!-- [`derive`](../reference.html#derive)-like attributes and other kinds of --> <!-- extensions. See `Registry::register_syntax_extension` and the `SyntaxExtension` --> <!-- enum. For a more involved macro example, see --> <!-- [`regex_macros`](https://github.com/rust-lang/regex/blob/master/regex_macros/src/lib.rs). --> <p>手続き的マクロに加えて<a href="../reference.html#derive"><code>derive</code></a>ライクなアトリビュートや他の拡張を書けます。 <code>Registry::register_syntax_extension</code> や <code>SyntaxExtension</code> 列挙型を参照して下さい。 もっと複雑なマクロの例は<a href="https://github.com/rust-lang/regex/blob/master/regex_macros/src/lib.rs"><code>regex_macros</code></a>を参照して下さい。</p> <!-- ## Tips and tricks --> <h2 id='ヒントと小技' class='section-header'><a href='#ヒントと小技'>ヒントと小技</a></h2> <!-- Some of the [macro debugging tips](macros.html#debugging-macro-code) are applicable. --> <p><a href="macros.html#debugging-macro-code">マクロデバッグのヒント</a>のいくつかが使えます。</p> <!-- You can use `syntax::parse` to turn token trees into --> <!-- higher-level syntax elements like expressions: --> <p><code>syntax::parse</code>を使うことでトークン木を式などの高レベルな構文要素に変換出来ます。</p> <span class='rusttest'>fn main() { fn expand_foo(cx: &amp;mut ExtCtxt, sp: Span, args: &amp;[TokenTree]) -&gt; Box&lt;MacResult+&#39;static&gt; { let mut parser = cx.new_parser_from_tts(args); let expr: P&lt;Expr&gt; = parser.parse_expr(); }</span><pre class='rust rust-example-rendered'> <span class='kw'>fn</span> <span class='ident'>expand_foo</span>(<span class='ident'>cx</span>: <span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='ident'>ExtCtxt</span>, <span class='ident'>sp</span>: <span class='ident'>Span</span>, <span class='ident'>args</span>: <span class='kw-2'>&amp;</span>[<span class='ident'>TokenTree</span>]) <span class='op'>-&gt;</span> <span class='ident'>Box</span><span class='op'>&lt;</span><span class='ident'>MacResult</span><span class='op'>+</span><span class='lifetime'>&#39;static</span><span class='op'>&gt;</span> { <span class='kw'>let</span> <span class='kw-2'>mut</span> <span class='ident'>parser</span> <span class='op'>=</span> <span class='ident'>cx</span>.<span class='ident'>new_parser_from_tts</span>(<span class='ident'>args</span>); <span class='kw'>let</span> <span class='ident'>expr</span>: <span class='ident'>P</span><span class='op'>&lt;</span><span class='ident'>Expr</span><span class='op'>&gt;</span> <span class='op'>=</span> <span class='ident'>parser</span>.<span class='ident'>parse_expr</span>();</pre> <!-- Looking through [`libsyntax` parser --> <!-- code](https://github.com/rust-lang/rust/blob/master/src/libsyntax/parse/parser.rs) --> <!-- will give you a feel for how the parsing infrastructure works. --> <p><a href="https://github.com/rust-lang/rust/blob/master/src/libsyntax/parse/parser.rs"><code>libsyntax</code> のパーサのコード</a>を見るとパーサの基盤がどのように機能しているかを感られるでしょう。</p> <!-- Keep the `Span`s of everything you parse, for better error reporting. You can --> <!-- wrap `Spanned` around your custom data structures. --> <p>パースしたものの <code>Span</code> は良いエラー報告のために保持しておきましょう。 自分で作ったデータ構造に対しても <code>Spanned</code> でラップ出来ます。</p> <!-- Calling `ExtCtxt::span_fatal` will immediately abort compilation. It's better to --> <!-- instead call `ExtCtxt::span_err` and return `DummyResult` so that the compiler --> <!-- can continue and find further errors. --> <p><code>ExtCtxt::span_fatal</code> を呼ぶとコンパイルは即座に中断されます。 <code>ExtCtxt::span_err</code> を呼んで <code>DummyResult</code> を返せばコンパイラはさらなるエラーを発見できるのでその方が良いでしょう。</p> <!-- To print syntax fragments for debugging, you can use `span_note` together with --> <!-- `syntax::print::pprust::*_to_string`. --> <p>構文の断片を表示するには <code>span_note</code> と <code>syntax::print::pprust::*_to_string</code> を使えば出来ます。</p> <!-- The example above produced an integer literal using `AstBuilder::expr_usize`. --> <!-- As an alternative to the `AstBuilder` trait, `libsyntax` provides a set of --> <!-- quasiquote macros. They are undocumented and very rough around the edges. --> <!-- However, the implementation may be a good starting point for an improved --> <!-- quasiquote as an ordinary plugin library. --> <p>上記の例では <code>AstBuilder::expr_usize</code> を使って整数リテラルを作りました。 <code>AstBuilder</code> トレイトの代替として <code>libsyntax</code> は準クォートマクロを提供しています。 ドキュメントがない上に荒削りです。しかしながらその実装は改良版の普通のプラグインライブラリのとっかかりにはほど良いでしょう。</p> <!-- # Lint plugins --> <h1 id='構文チェックプラグイン' class='section-header'><a href='#構文チェックプラグイン'>構文チェックプラグイン</a></h1> <!-- Plugins can extend [Rust's lint --> <!-- infrastructure](../reference.html#lint-check-attributes) with additional checks for --> <!-- code style, safety, etc. Now let's write a plugin [`lint_plugin_test.rs`](https://github.com/rust-lang/rust/blob/master/src/test/auxiliary/lint_plugin_test.rs) --> <!-- that warns about any item named `lintme`. --> <p>プラグインによって<a href="../reference.html#lint-check-attributes">Rustの構文チェック基盤</a>を拡張してコーディングスタイル、安全性などを検査するようにできます。では<a href="https://github.com/rust-lang/rust/blob/master/src/test/auxiliary/lint_plugin_test.rs"><code>lint_plugin_test.rs</code></a>プラグインを書いてみましょう。 <code>lintme</code> という名前のアイテムについて警告を出すものです。</p> <span class='rusttest'>#![feature(plugin_registrar)] #![feature(box_syntax, rustc_private)] fn main() { extern crate syntax; // Load rustc as a plugin to get macros // macroを使うためにrustcをプラグインとして読み込む #[macro_use] extern crate rustc; extern crate rustc_plugin; use rustc::lint::{EarlyContext, LintContext, LintPass, EarlyLintPass, EarlyLintPassObject, LintArray}; use rustc_plugin::Registry; use syntax::ast; declare_lint!(TEST_LINT, Warn, &quot;Warn about items named &#39;lintme&#39;&quot;); struct Pass; impl LintPass for Pass { fn get_lints(&amp;self) -&gt; LintArray { lint_array!(TEST_LINT) } } impl EarlyLintPass for Pass { fn check_item(&amp;mut self, cx: &amp;EarlyContext, it: &amp;ast::Item) { if it.ident.name.as_str() == &quot;lintme&quot; { cx.span_lint(TEST_LINT, it.span, &quot;item is named &#39;lintme&#39;&quot;); } } } #[plugin_registrar] pub fn plugin_registrar(reg: &amp;mut Registry) { reg.register_early_lint_pass(box Pass as EarlyLintPassObject); } }</span><pre class='rust rust-example-rendered'> <span class='attribute'>#<span class='op'>!</span>[<span class='ident'>feature</span>(<span class='ident'>plugin_registrar</span>)]</span> <span class='attribute'>#<span class='op'>!</span>[<span class='ident'>feature</span>(<span class='ident'>box_syntax</span>, <span class='ident'>rustc_private</span>)]</span> <span class='kw'>extern</span> <span class='kw'>crate</span> <span class='ident'>syntax</span>; <span class='comment'>// macroを使うためにrustcをプラグインとして読み込む</span> <span class='attribute'>#[<span class='ident'>macro_use</span>]</span> <span class='kw'>extern</span> <span class='kw'>crate</span> <span class='ident'>rustc</span>; <span class='kw'>extern</span> <span class='kw'>crate</span> <span class='ident'>rustc_plugin</span>; <span class='kw'>use</span> <span class='ident'>rustc</span>::<span class='ident'>lint</span>::{<span class='ident'>EarlyContext</span>, <span class='ident'>LintContext</span>, <span class='ident'>LintPass</span>, <span class='ident'>EarlyLintPass</span>, <span class='ident'>EarlyLintPassObject</span>, <span class='ident'>LintArray</span>}; <span class='kw'>use</span> <span class='ident'>rustc_plugin</span>::<span class='ident'>Registry</span>; <span class='kw'>use</span> <span class='ident'>syntax</span>::<span class='ident'>ast</span>; <span class='macro'>declare_lint</span><span class='macro'>!</span>(<span class='ident'>TEST_LINT</span>, <span class='ident'>Warn</span>, <span class='string'>&quot;Warn about items named &#39;lintme&#39;&quot;</span>); <span class='kw'>struct</span> <span class='ident'>Pass</span>; <span class='kw'>impl</span> <span class='ident'>LintPass</span> <span class='kw'>for</span> <span class='ident'>Pass</span> { <span class='kw'>fn</span> <span class='ident'>get_lints</span>(<span class='kw-2'>&amp;</span><span class='self'>self</span>) <span class='op'>-&gt;</span> <span class='ident'>LintArray</span> { <span class='macro'>lint_array</span><span class='macro'>!</span>(<span class='ident'>TEST_LINT</span>) } } <span class='kw'>impl</span> <span class='ident'>EarlyLintPass</span> <span class='kw'>for</span> <span class='ident'>Pass</span> { <span class='kw'>fn</span> <span class='ident'>check_item</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>, <span class='ident'>cx</span>: <span class='kw-2'>&amp;</span><span class='ident'>EarlyContext</span>, <span class='ident'>it</span>: <span class='kw-2'>&amp;</span><span class='ident'>ast</span>::<span class='ident'>Item</span>) { <span class='kw'>if</span> <span class='ident'>it</span>.<span class='ident'>ident</span>.<span class='ident'>name</span>.<span class='ident'>as_str</span>() <span class='op'>==</span> <span class='string'>&quot;lintme&quot;</span> { <span class='ident'>cx</span>.<span class='ident'>span_lint</span>(<span class='ident'>TEST_LINT</span>, <span class='ident'>it</span>.<span class='ident'>span</span>, <span class='string'>&quot;item is named &#39;lintme&#39;&quot;</span>); } } } <span class='attribute'>#[<span class='ident'>plugin_registrar</span>]</span> <span class='kw'>pub</span> <span class='kw'>fn</span> <span class='ident'>plugin_registrar</span>(<span class='ident'>reg</span>: <span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='ident'>Registry</span>) { <span class='ident'>reg</span>.<span class='ident'>register_early_lint_pass</span>(<span class='kw'>box</span> <span class='ident'>Pass</span> <span class='kw'>as</span> <span class='ident'>EarlyLintPassObject</span>); }</pre> <!-- Then code like --> <p>そしたらこのようなコードは</p> <span class='rusttest'>fn main() { #![plugin(lint_plugin_test)] fn lintme() { } }</span><pre class='rust rust-example-rendered'> <span class='attribute'>#<span class='op'>!</span>[<span class='ident'>plugin</span>(<span class='ident'>lint_plugin_test</span>)]</span> <span class='kw'>fn</span> <span class='ident'>lintme</span>() { }</pre> <!-- will produce a compiler warning: --> <p>コンパイラの警告を発生させます。</p> <pre><code class="language-txt">foo.rs:4:1: 4:16 warning: item is named &#39;lintme&#39;, #[warn(test_lint)] on by default foo.rs:4 fn lintme() { } ^~~~~~~~~~~~~~~ </code></pre> <!-- The components of a lint plugin are: --> <p>構文チェックプラグインのコンポーネントは</p> <!-- * one or more `declare_lint!` invocations, which define static `Lint` structs; --> <ul> <li>1回以上の <code>declare_lint!</code> の実行。それによって <code>Lint</code> 構造体が定義されます。</li> </ul> <!-- * a struct holding any state needed by the lint pass (here, none); --> <ul> <li>構文チェックパスで必要となる状態を保持する構造体(ここでは何もない)</li> </ul> <!-- * a `LintPass` --> <!-- implementation defining how to check each syntax element. A single --> <!-- `LintPass` may call `span_lint` for several different `Lint`s, but should --> <!-- register them all through the `get_lints` method. --> <ul> <li>それぞれの構文要素をどうやってチェックするかを定めた <code>LintPass</code> の実装。 単一の <code>LintPass</code> は複数回 <code>span_lint</code> をいくつかの異なる <code>Lint</code> に対して呼ぶかもしれませんが、全て <code>get_lints</code>を通じて登録すべきです。</li> </ul> <!-- Lint passes are syntax traversals, but they run at a late stage of compilation --> <!-- where type information is available. `rustc`'s [built-in --> <!-- lints](https://github.com/rust-lang/rust/blob/master/src/librustc/lint/builtin.rs) --> <!-- mostly use the same infrastructure as lint plugins, and provide examples of how --> <!-- to access type information. --> <p>構文チェックパスは構文巡回ですが、型情報が得られる、コンパイルの終盤で走ります。 <code>rustc</code> の<a href="https://github.com/rust-lang/rust/blob/master/src/librustc/lint/builtin.rs">組み込み構文チェック</a>は殆どプラグインと同じ基盤を使っており、どうやって型情報にアクセスするかの例になっています。</p> <!-- Lints defined by plugins are controlled by the usual [attributes and compiler --> <!-- flags](../reference.html#lint-check-attributes), e.g. `#[allow(test_lint)]` or --> <!-- `-A test-lint`. These identifiers are derived from the first argument to --> <!-- `declare_lint!`, with appropriate case and punctuation conversion. --> <p>プラグインによって定義されたLintは普通の<a href="../reference.html#lint-check-attributes">アトリビュートとコンパイラフラグ</a>例えば <code>#[allow(test_lint)]</code> や <code>-A test-lint</code> によってコントロールされます。 これらの識別子は <code>declare_lint!</code> の第一引数に由来しており、適切な名前に変換されます。</p> <!-- You can run `rustc -W help foo.rs` to see a list of lints known to `rustc`, --> <!-- including those provided by plugins loaded by `foo.rs`. --> <p><code>rustc -W help foo.rs</code> を走らせることで <code>rustc</code> の知っている、及び <code>foo.rs</code> 内で定義されたコンパイラ構文チェックをロード出来ます。</p> <script type="text/javascript"> window.playgroundUrl = "https://play.rust-lang.org"; </script> <script src='rustbook.js'></script> <script src='playpen.js'></script> </div></div> </body> </html> <|start_filename|>docs/1.9/nomicon/data.html<|end_filename|> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="generator" content="rustdoc"> <title>Data Representation in Rust</title> <link rel="stylesheet" type="text/css" href="rustbook.css"> <meta name="robots" content="noindex"> </head> <body class="rustdoc"> <!--[if lte IE 8]> <div class="warning"> This old browser is unsupported and will most likely display funky things. </div> <![endif]--> <div id="nav"> <button id="toggle-nav"> <span class="sr-only">Toggle navigation</span> <span class="bar"></span> <span class="bar"></span> <span class="bar"></span> </button> </div> <div id='toc' class='mobile-hidden'> <ul class='chapter'> <li><a href='README.html'><b>1.</b> Introduction</a> </li> <li><a href='meet-safe-and-unsafe.html'><b>2.</b> Meet Safe and Unsafe</a> <ul class='section'> <li><a href='safe-unsafe-meaning.html'><b>2.1.</b> How Safe and Unsafe Interact</a> </li> <li><a href='working-with-unsafe.html'><b>2.2.</b> Working with Unsafe</a> </li> </ul> </li> <li><a class='active' href='data.html'><b>3.</b> Data Layout</a> <ul class='section'> <li><a href='repr-rust.html'><b>3.1.</b> repr(Rust)</a> </li> <li><a href='exotic-sizes.html'><b>3.2.</b> Exotically Sized Types</a> </li> <li><a href='other-reprs.html'><b>3.3.</b> Other reprs</a> </li> </ul> </li> <li><a href='ownership.html'><b>4.</b> Ownership</a> <ul class='section'> <li><a href='references.html'><b>4.1.</b> References</a> </li> <li><a href='lifetimes.html'><b>4.2.</b> Lifetimes</a> </li> <li><a href='lifetime-mismatch.html'><b>4.3.</b> Limits of Lifetimes</a> </li> <li><a href='lifetime-elision.html'><b>4.4.</b> Lifetime Elision</a> </li> <li><a href='unbounded-lifetimes.html'><b>4.5.</b> Unbounded Lifetimes</a> </li> <li><a href='hrtb.html'><b>4.6.</b> Higher-Rank Trait Bounds</a> </li> <li><a href='subtyping.html'><b>4.7.</b> Subtyping and Variance</a> </li> <li><a href='dropck.html'><b>4.8.</b> Drop Check</a> </li> <li><a href='phantom-data.html'><b>4.9.</b> PhantomData</a> </li> <li><a href='borrow-splitting.html'><b>4.10.</b> Splitting Borrows</a> </li> </ul> </li> <li><a href='conversions.html'><b>5.</b> Type Conversions</a> <ul class='section'> <li><a href='coercions.html'><b>5.1.</b> Coercions</a> </li> <li><a href='dot-operator.html'><b>5.2.</b> The Dot Operator</a> </li> <li><a href='casts.html'><b>5.3.</b> Casts</a> </li> <li><a href='transmutes.html'><b>5.4.</b> Transmutes</a> </li> </ul> </li> <li><a href='uninitialized.html'><b>6.</b> Uninitialized Memory</a> <ul class='section'> <li><a href='checked-uninit.html'><b>6.1.</b> Checked</a> </li> <li><a href='drop-flags.html'><b>6.2.</b> Drop Flags</a> </li> <li><a href='unchecked-uninit.html'><b>6.3.</b> Unchecked</a> </li> </ul> </li> <li><a href='obrm.html'><b>7.</b> Ownership Based Resource Management</a> <ul class='section'> <li><a href='constructors.html'><b>7.1.</b> Constructors</a> </li> <li><a href='destructors.html'><b>7.2.</b> Destructors</a> </li> <li><a href='leaking.html'><b>7.3.</b> Leaking</a> </li> </ul> </li> <li><a href='unwinding.html'><b>8.</b> Unwinding</a> <ul class='section'> <li><a href='exception-safety.html'><b>8.1.</b> Exception Safety</a> </li> <li><a href='poisoning.html'><b>8.2.</b> Poisoning</a> </li> </ul> </li> <li><a href='concurrency.html'><b>9.</b> Concurrency</a> <ul class='section'> <li><a href='races.html'><b>9.1.</b> Races</a> </li> <li><a href='send-and-sync.html'><b>9.2.</b> Send and Sync</a> </li> <li><a href='atomics.html'><b>9.3.</b> Atomics</a> </li> </ul> </li> <li><a href='vec.html'><b>10.</b> Implementing Vec</a> <ul class='section'> <li><a href='vec-layout.html'><b>10.1.</b> Layout</a> </li> <li><a href='vec-alloc.html'><b>10.2.</b> Allocating</a> </li> <li><a href='vec-push-pop.html'><b>10.3.</b> Push and Pop</a> </li> <li><a href='vec-dealloc.html'><b>10.4.</b> Deallocating</a> </li> <li><a href='vec-deref.html'><b>10.5.</b> Deref</a> </li> <li><a href='vec-insert-remove.html'><b>10.6.</b> Insert and Remove</a> </li> <li><a href='vec-into-iter.html'><b>10.7.</b> IntoIter</a> </li> <li><a href='vec-raw.html'><b>10.8.</b> RawVec</a> </li> <li><a href='vec-drain.html'><b>10.9.</b> Drain</a> </li> <li><a href='vec-zsts.html'><b>10.10.</b> Handling Zero-Sized Types</a> </li> <li><a href='vec-final.html'><b>10.11.</b> Final Code</a> </li> </ul> </li> <li><a href='arc-and-mutex.html'><b>11.</b> Implementing Arc and Mutex</a> </li> </ul> </div> <div id='page-wrapper'> <div id='page'> <blockquote class="header-caveat"> <p> <strong>注意: <a href="https://doc.rust-jp.rs/book-ja/">最新版のドキュメントをご覧ください。</a></strong>この第1版ドキュメントは古くなっており、最新情報が反映されていません。リンク先のドキュメントが現在の Rust の最新のドキュメントです。 </p> </blockquote> <h1 class="title">Data Representation in Rust</h1> <p>Low-level programming cares a lot about data layout. It&#39;s a big deal. It also pervasively influences the rest of the language, so we&#39;re going to start by digging into how data is represented in Rust.</p> <script type="text/javascript"> window.playgroundUrl = "https://play.rust-lang.org"; </script> <script src='rustbook.js'></script> <script src='playpen.js'></script> </div></div> </body> </html> <|start_filename|>docs/1.9/nomicon/vec-final.html<|end_filename|> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="generator" content="rustdoc"> <title>The Final Code</title> <link rel="stylesheet" type="text/css" href="rustbook.css"> <meta name="robots" content="noindex"> </head> <body class="rustdoc"> <!--[if lte IE 8]> <div class="warning"> This old browser is unsupported and will most likely display funky things. </div> <![endif]--> <div id="nav"> <button id="toggle-nav"> <span class="sr-only">Toggle navigation</span> <span class="bar"></span> <span class="bar"></span> <span class="bar"></span> </button> </div> <div id='toc' class='mobile-hidden'> <ul class='chapter'> <li><a href='README.html'><b>1.</b> Introduction</a> </li> <li><a href='meet-safe-and-unsafe.html'><b>2.</b> Meet Safe and Unsafe</a> <ul class='section'> <li><a href='safe-unsafe-meaning.html'><b>2.1.</b> How Safe and Unsafe Interact</a> </li> <li><a href='working-with-unsafe.html'><b>2.2.</b> Working with Unsafe</a> </li> </ul> </li> <li><a href='data.html'><b>3.</b> Data Layout</a> <ul class='section'> <li><a href='repr-rust.html'><b>3.1.</b> repr(Rust)</a> </li> <li><a href='exotic-sizes.html'><b>3.2.</b> Exotically Sized Types</a> </li> <li><a href='other-reprs.html'><b>3.3.</b> Other reprs</a> </li> </ul> </li> <li><a href='ownership.html'><b>4.</b> Ownership</a> <ul class='section'> <li><a href='references.html'><b>4.1.</b> References</a> </li> <li><a href='lifetimes.html'><b>4.2.</b> Lifetimes</a> </li> <li><a href='lifetime-mismatch.html'><b>4.3.</b> Limits of Lifetimes</a> </li> <li><a href='lifetime-elision.html'><b>4.4.</b> Lifetime Elision</a> </li> <li><a href='unbounded-lifetimes.html'><b>4.5.</b> Unbounded Lifetimes</a> </li> <li><a href='hrtb.html'><b>4.6.</b> Higher-Rank Trait Bounds</a> </li> <li><a href='subtyping.html'><b>4.7.</b> Subtyping and Variance</a> </li> <li><a href='dropck.html'><b>4.8.</b> Drop Check</a> </li> <li><a href='phantom-data.html'><b>4.9.</b> PhantomData</a> </li> <li><a href='borrow-splitting.html'><b>4.10.</b> Splitting Borrows</a> </li> </ul> </li> <li><a href='conversions.html'><b>5.</b> Type Conversions</a> <ul class='section'> <li><a href='coercions.html'><b>5.1.</b> Coercions</a> </li> <li><a href='dot-operator.html'><b>5.2.</b> The Dot Operator</a> </li> <li><a href='casts.html'><b>5.3.</b> Casts</a> </li> <li><a href='transmutes.html'><b>5.4.</b> Transmutes</a> </li> </ul> </li> <li><a href='uninitialized.html'><b>6.</b> Uninitialized Memory</a> <ul class='section'> <li><a href='checked-uninit.html'><b>6.1.</b> Checked</a> </li> <li><a href='drop-flags.html'><b>6.2.</b> Drop Flags</a> </li> <li><a href='unchecked-uninit.html'><b>6.3.</b> Unchecked</a> </li> </ul> </li> <li><a href='obrm.html'><b>7.</b> Ownership Based Resource Management</a> <ul class='section'> <li><a href='constructors.html'><b>7.1.</b> Constructors</a> </li> <li><a href='destructors.html'><b>7.2.</b> Destructors</a> </li> <li><a href='leaking.html'><b>7.3.</b> Leaking</a> </li> </ul> </li> <li><a href='unwinding.html'><b>8.</b> Unwinding</a> <ul class='section'> <li><a href='exception-safety.html'><b>8.1.</b> Exception Safety</a> </li> <li><a href='poisoning.html'><b>8.2.</b> Poisoning</a> </li> </ul> </li> <li><a href='concurrency.html'><b>9.</b> Concurrency</a> <ul class='section'> <li><a href='races.html'><b>9.1.</b> Races</a> </li> <li><a href='send-and-sync.html'><b>9.2.</b> Send and Sync</a> </li> <li><a href='atomics.html'><b>9.3.</b> Atomics</a> </li> </ul> </li> <li><a href='vec.html'><b>10.</b> Implementing Vec</a> <ul class='section'> <li><a href='vec-layout.html'><b>10.1.</b> Layout</a> </li> <li><a href='vec-alloc.html'><b>10.2.</b> Allocating</a> </li> <li><a href='vec-push-pop.html'><b>10.3.</b> Push and Pop</a> </li> <li><a href='vec-dealloc.html'><b>10.4.</b> Deallocating</a> </li> <li><a href='vec-deref.html'><b>10.5.</b> Deref</a> </li> <li><a href='vec-insert-remove.html'><b>10.6.</b> Insert and Remove</a> </li> <li><a href='vec-into-iter.html'><b>10.7.</b> IntoIter</a> </li> <li><a href='vec-raw.html'><b>10.8.</b> RawVec</a> </li> <li><a href='vec-drain.html'><b>10.9.</b> Drain</a> </li> <li><a href='vec-zsts.html'><b>10.10.</b> Handling Zero-Sized Types</a> </li> <li><a class='active' href='vec-final.html'><b>10.11.</b> Final Code</a> </li> </ul> </li> <li><a href='arc-and-mutex.html'><b>11.</b> Implementing Arc and Mutex</a> </li> </ul> </div> <div id='page-wrapper'> <div id='page'> <blockquote class="header-caveat"> <p> <strong>注意: <a href="https://doc.rust-jp.rs/book-ja/">最新版のドキュメントをご覧ください。</a></strong>この第1版ドキュメントは古くなっており、最新情報が反映されていません。リンク先のドキュメントが現在の Rust の最新のドキュメントです。 </p> </blockquote> <h1 class="title">The Final Code</h1> <span class='rusttest'>#![feature(unique)] #![feature(alloc, heap_api)] extern crate alloc; use std::ptr::{Unique, self}; use std::mem; use std::ops::{Deref, DerefMut}; use std::marker::PhantomData; use alloc::heap; struct RawVec&lt;T&gt; { ptr: Unique&lt;T&gt;, cap: usize, } impl&lt;T&gt; RawVec&lt;T&gt; { fn new() -&gt; Self { unsafe { // !0 is usize::MAX. This branch should be stripped at compile time. let cap = if mem::size_of::&lt;T&gt;() == 0 { !0 } else { 0 }; // heap::EMPTY doubles as &quot;unallocated&quot; and &quot;zero-sized allocation&quot; RawVec { ptr: Unique::new(heap::EMPTY as *mut T), cap: cap } } } fn grow(&amp;mut self) { unsafe { let elem_size = mem::size_of::&lt;T&gt;(); // since we set the capacity to usize::MAX when elem_size is // 0, getting to here necessarily means the Vec is overfull. assert!(elem_size != 0, &quot;capacity overflow&quot;); let align = mem::align_of::&lt;T&gt;(); let (new_cap, ptr) = if self.cap == 0 { let ptr = heap::allocate(elem_size, align); (1, ptr) } else { let new_cap = 2 * self.cap; let ptr = heap::reallocate(*self.ptr as *mut _, self.cap * elem_size, new_cap * elem_size, align); (new_cap, ptr) }; // If allocate or reallocate fail, we&#39;ll get `null` back if ptr.is_null() { oom() } self.ptr = Unique::new(ptr as *mut _); self.cap = new_cap; } } } impl&lt;T&gt; Drop for RawVec&lt;T&gt; { fn drop(&amp;mut self) { let elem_size = mem::size_of::&lt;T&gt;(); if self.cap != 0 &amp;&amp; elem_size != 0 { let align = mem::align_of::&lt;T&gt;(); let num_bytes = elem_size * self.cap; unsafe { heap::deallocate(*self.ptr as *mut _, num_bytes, align); } } } } pub struct Vec&lt;T&gt; { buf: RawVec&lt;T&gt;, len: usize, } impl&lt;T&gt; Vec&lt;T&gt; { fn ptr(&amp;self) -&gt; *mut T { *self.buf.ptr } fn cap(&amp;self) -&gt; usize { self.buf.cap } pub fn new() -&gt; Self { Vec { buf: RawVec::new(), len: 0 } } pub fn push(&amp;mut self, elem: T) { if self.len == self.cap() { self.buf.grow(); } unsafe { ptr::write(self.ptr().offset(self.len as isize), elem); } // Can&#39;t fail, we&#39;ll OOM first. self.len += 1; } pub fn pop(&amp;mut self) -&gt; Option&lt;T&gt; { if self.len == 0 { None } else { self.len -= 1; unsafe { Some(ptr::read(self.ptr().offset(self.len as isize))) } } } pub fn insert(&amp;mut self, index: usize, elem: T) { assert!(index &lt;= self.len, &quot;index out of bounds&quot;); if self.cap() == self.len { self.buf.grow(); } unsafe { if index &lt; self.len { ptr::copy(self.ptr().offset(index as isize), self.ptr().offset(index as isize + 1), self.len - index); } ptr::write(self.ptr().offset(index as isize), elem); self.len += 1; } } pub fn remove(&amp;mut self, index: usize) -&gt; T { assert!(index &lt; self.len, &quot;index out of bounds&quot;); unsafe { self.len -= 1; let result = ptr::read(self.ptr().offset(index as isize)); ptr::copy(self.ptr().offset(index as isize + 1), self.ptr().offset(index as isize), self.len - index); result } } pub fn into_iter(self) -&gt; IntoIter&lt;T&gt; { unsafe { let iter = RawValIter::new(&amp;self); let buf = ptr::read(&amp;self.buf); mem::forget(self); IntoIter { iter: iter, _buf: buf, } } } pub fn drain(&amp;mut self) -&gt; Drain&lt;T&gt; { unsafe { let iter = RawValIter::new(&amp;self); // this is a mem::forget safety thing. If Drain is forgotten, we just // leak the whole Vec&#39;s contents. Also we need to do this *eventually* // anyway, so why not do it now? self.len = 0; Drain { iter: iter, vec: PhantomData, } } } } impl&lt;T&gt; Drop for Vec&lt;T&gt; { fn drop(&amp;mut self) { while let Some(_) = self.pop() {} // allocation is handled by RawVec } } impl&lt;T&gt; Deref for Vec&lt;T&gt; { type Target = [T]; fn deref(&amp;self) -&gt; &amp;[T] { unsafe { ::std::slice::from_raw_parts(self.ptr(), self.len) } } } impl&lt;T&gt; DerefMut for Vec&lt;T&gt; { fn deref_mut(&amp;mut self) -&gt; &amp;mut [T] { unsafe { ::std::slice::from_raw_parts_mut(self.ptr(), self.len) } } } struct RawValIter&lt;T&gt; { start: *const T, end: *const T, } impl&lt;T&gt; RawValIter&lt;T&gt; { unsafe fn new(slice: &amp;[T]) -&gt; Self { RawValIter { start: slice.as_ptr(), end: if mem::size_of::&lt;T&gt;() == 0 { ((slice.as_ptr() as usize) + slice.len()) as *const _ } else if slice.len() == 0 { slice.as_ptr() } else { slice.as_ptr().offset(slice.len() as isize) } } } } impl&lt;T&gt; Iterator for RawValIter&lt;T&gt; { type Item = T; fn next(&amp;mut self) -&gt; Option&lt;T&gt; { if self.start == self.end { None } else { unsafe { let result = ptr::read(self.start); self.start = self.start.offset(1); Some(result) } } } fn size_hint(&amp;self) -&gt; (usize, Option&lt;usize&gt;) { let elem_size = mem::size_of::&lt;T&gt;(); let len = (self.end as usize - self.start as usize) / if elem_size == 0 { 1 } else { elem_size }; (len, Some(len)) } } impl&lt;T&gt; DoubleEndedIterator for RawValIter&lt;T&gt; { fn next_back(&amp;mut self) -&gt; Option&lt;T&gt; { if self.start == self.end { None } else { unsafe { self.end = self.end.offset(-1); Some(ptr::read(self.end)) } } } } pub struct IntoIter&lt;T&gt; { _buf: RawVec&lt;T&gt;, // we don&#39;t actually care about this. Just need it to live. iter: RawValIter&lt;T&gt;, } impl&lt;T&gt; Iterator for IntoIter&lt;T&gt; { type Item = T; fn next(&amp;mut self) -&gt; Option&lt;T&gt; { self.iter.next() } fn size_hint(&amp;self) -&gt; (usize, Option&lt;usize&gt;) { self.iter.size_hint() } } impl&lt;T&gt; DoubleEndedIterator for IntoIter&lt;T&gt; { fn next_back(&amp;mut self) -&gt; Option&lt;T&gt; { self.iter.next_back() } } impl&lt;T&gt; Drop for IntoIter&lt;T&gt; { fn drop(&amp;mut self) { for _ in &amp;mut *self {} } } pub struct Drain&lt;&#39;a, T: &#39;a&gt; { vec: PhantomData&lt;&amp;&#39;a mut Vec&lt;T&gt;&gt;, iter: RawValIter&lt;T&gt;, } impl&lt;&#39;a, T&gt; Iterator for Drain&lt;&#39;a, T&gt; { type Item = T; fn next(&amp;mut self) -&gt; Option&lt;T&gt; { self.iter.next_back() } fn size_hint(&amp;self) -&gt; (usize, Option&lt;usize&gt;) { self.iter.size_hint() } } impl&lt;&#39;a, T&gt; DoubleEndedIterator for Drain&lt;&#39;a, T&gt; { fn next_back(&amp;mut self) -&gt; Option&lt;T&gt; { self.iter.next_back() } } impl&lt;&#39;a, T&gt; Drop for Drain&lt;&#39;a, T&gt; { fn drop(&amp;mut self) { // pre-drain the iter for _ in &amp;mut self.iter {} } } /// Abort the process, we&#39;re out of memory! /// /// In practice this is probably dead code on most OSes fn oom() { ::std::process::exit(-9999); } fn main() {} </span><pre class='rust rust-example-rendered'> <span class='attribute'>#<span class='op'>!</span>[<span class='ident'>feature</span>(<span class='ident'>unique</span>)]</span> <span class='attribute'>#<span class='op'>!</span>[<span class='ident'>feature</span>(<span class='ident'>alloc</span>, <span class='ident'>heap_api</span>)]</span> <span class='kw'>extern</span> <span class='kw'>crate</span> <span class='ident'>alloc</span>; <span class='kw'>use</span> <span class='ident'>std</span>::<span class='ident'>ptr</span>::{<span class='ident'>Unique</span>, <span class='self'>self</span>}; <span class='kw'>use</span> <span class='ident'>std</span>::<span class='ident'>mem</span>; <span class='kw'>use</span> <span class='ident'>std</span>::<span class='ident'>ops</span>::{<span class='ident'>Deref</span>, <span class='ident'>DerefMut</span>}; <span class='kw'>use</span> <span class='ident'>std</span>::<span class='ident'>marker</span>::<span class='ident'>PhantomData</span>; <span class='kw'>use</span> <span class='ident'>alloc</span>::<span class='ident'>heap</span>; <span class='kw'>struct</span> <span class='ident'>RawVec</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> { <span class='ident'>ptr</span>: <span class='ident'>Unique</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span>, <span class='ident'>cap</span>: <span class='ident'>usize</span>, } <span class='kw'>impl</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> <span class='ident'>RawVec</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> { <span class='kw'>fn</span> <span class='ident'>new</span>() <span class='op'>-&gt;</span> <span class='self'>Self</span> { <span class='kw'>unsafe</span> { <span class='comment'>// !0 is usize::MAX. This branch should be stripped at compile time.</span> <span class='kw'>let</span> <span class='ident'>cap</span> <span class='op'>=</span> <span class='kw'>if</span> <span class='ident'>mem</span>::<span class='ident'>size_of</span>::<span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span>() <span class='op'>==</span> <span class='number'>0</span> { <span class='op'>!</span><span class='number'>0</span> } <span class='kw'>else</span> { <span class='number'>0</span> }; <span class='comment'>// heap::EMPTY doubles as &quot;unallocated&quot; and &quot;zero-sized allocation&quot;</span> <span class='ident'>RawVec</span> { <span class='ident'>ptr</span>: <span class='ident'>Unique</span>::<span class='ident'>new</span>(<span class='ident'>heap</span>::<span class='ident'>EMPTY</span> <span class='kw'>as</span> <span class='op'>*</span><span class='kw-2'>mut</span> <span class='ident'>T</span>), <span class='ident'>cap</span>: <span class='ident'>cap</span> } } } <span class='kw'>fn</span> <span class='ident'>grow</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>) { <span class='kw'>unsafe</span> { <span class='kw'>let</span> <span class='ident'>elem_size</span> <span class='op'>=</span> <span class='ident'>mem</span>::<span class='ident'>size_of</span>::<span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span>(); <span class='comment'>// since we set the capacity to usize::MAX when elem_size is</span> <span class='comment'>// 0, getting to here necessarily means the Vec is overfull.</span> <span class='macro'>assert</span><span class='macro'>!</span>(<span class='ident'>elem_size</span> <span class='op'>!=</span> <span class='number'>0</span>, <span class='string'>&quot;capacity overflow&quot;</span>); <span class='kw'>let</span> <span class='ident'>align</span> <span class='op'>=</span> <span class='ident'>mem</span>::<span class='ident'>align_of</span>::<span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span>(); <span class='kw'>let</span> (<span class='ident'>new_cap</span>, <span class='ident'>ptr</span>) <span class='op'>=</span> <span class='kw'>if</span> <span class='self'>self</span>.<span class='ident'>cap</span> <span class='op'>==</span> <span class='number'>0</span> { <span class='kw'>let</span> <span class='ident'>ptr</span> <span class='op'>=</span> <span class='ident'>heap</span>::<span class='ident'>allocate</span>(<span class='ident'>elem_size</span>, <span class='ident'>align</span>); (<span class='number'>1</span>, <span class='ident'>ptr</span>) } <span class='kw'>else</span> { <span class='kw'>let</span> <span class='ident'>new_cap</span> <span class='op'>=</span> <span class='number'>2</span> <span class='op'>*</span> <span class='self'>self</span>.<span class='ident'>cap</span>; <span class='kw'>let</span> <span class='ident'>ptr</span> <span class='op'>=</span> <span class='ident'>heap</span>::<span class='ident'>reallocate</span>(<span class='op'>*</span><span class='self'>self</span>.<span class='ident'>ptr</span> <span class='kw'>as</span> <span class='op'>*</span><span class='kw-2'>mut</span> _, <span class='self'>self</span>.<span class='ident'>cap</span> <span class='op'>*</span> <span class='ident'>elem_size</span>, <span class='ident'>new_cap</span> <span class='op'>*</span> <span class='ident'>elem_size</span>, <span class='ident'>align</span>); (<span class='ident'>new_cap</span>, <span class='ident'>ptr</span>) }; <span class='comment'>// If allocate or reallocate fail, we&#39;ll get `null` back</span> <span class='kw'>if</span> <span class='ident'>ptr</span>.<span class='ident'>is_null</span>() { <span class='ident'>oom</span>() } <span class='self'>self</span>.<span class='ident'>ptr</span> <span class='op'>=</span> <span class='ident'>Unique</span>::<span class='ident'>new</span>(<span class='ident'>ptr</span> <span class='kw'>as</span> <span class='op'>*</span><span class='kw-2'>mut</span> _); <span class='self'>self</span>.<span class='ident'>cap</span> <span class='op'>=</span> <span class='ident'>new_cap</span>; } } } <span class='kw'>impl</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> <span class='ident'>Drop</span> <span class='kw'>for</span> <span class='ident'>RawVec</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> { <span class='kw'>fn</span> <span class='ident'>drop</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>) { <span class='kw'>let</span> <span class='ident'>elem_size</span> <span class='op'>=</span> <span class='ident'>mem</span>::<span class='ident'>size_of</span>::<span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span>(); <span class='kw'>if</span> <span class='self'>self</span>.<span class='ident'>cap</span> <span class='op'>!=</span> <span class='number'>0</span> <span class='op'>&amp;&amp;</span> <span class='ident'>elem_size</span> <span class='op'>!=</span> <span class='number'>0</span> { <span class='kw'>let</span> <span class='ident'>align</span> <span class='op'>=</span> <span class='ident'>mem</span>::<span class='ident'>align_of</span>::<span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span>(); <span class='kw'>let</span> <span class='ident'>num_bytes</span> <span class='op'>=</span> <span class='ident'>elem_size</span> <span class='op'>*</span> <span class='self'>self</span>.<span class='ident'>cap</span>; <span class='kw'>unsafe</span> { <span class='ident'>heap</span>::<span class='ident'>deallocate</span>(<span class='op'>*</span><span class='self'>self</span>.<span class='ident'>ptr</span> <span class='kw'>as</span> <span class='op'>*</span><span class='kw-2'>mut</span> _, <span class='ident'>num_bytes</span>, <span class='ident'>align</span>); } } } } <span class='kw'>pub</span> <span class='kw'>struct</span> <span class='ident'>Vec</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> { <span class='ident'>buf</span>: <span class='ident'>RawVec</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span>, <span class='ident'>len</span>: <span class='ident'>usize</span>, } <span class='kw'>impl</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> <span class='ident'>Vec</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> { <span class='kw'>fn</span> <span class='ident'>ptr</span>(<span class='kw-2'>&amp;</span><span class='self'>self</span>) <span class='op'>-&gt;</span> <span class='op'>*</span><span class='kw-2'>mut</span> <span class='ident'>T</span> { <span class='op'>*</span><span class='self'>self</span>.<span class='ident'>buf</span>.<span class='ident'>ptr</span> } <span class='kw'>fn</span> <span class='ident'>cap</span>(<span class='kw-2'>&amp;</span><span class='self'>self</span>) <span class='op'>-&gt;</span> <span class='ident'>usize</span> { <span class='self'>self</span>.<span class='ident'>buf</span>.<span class='ident'>cap</span> } <span class='kw'>pub</span> <span class='kw'>fn</span> <span class='ident'>new</span>() <span class='op'>-&gt;</span> <span class='self'>Self</span> { <span class='ident'>Vec</span> { <span class='ident'>buf</span>: <span class='ident'>RawVec</span>::<span class='ident'>new</span>(), <span class='ident'>len</span>: <span class='number'>0</span> } } <span class='kw'>pub</span> <span class='kw'>fn</span> <span class='ident'>push</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>, <span class='ident'>elem</span>: <span class='ident'>T</span>) { <span class='kw'>if</span> <span class='self'>self</span>.<span class='ident'>len</span> <span class='op'>==</span> <span class='self'>self</span>.<span class='ident'>cap</span>() { <span class='self'>self</span>.<span class='ident'>buf</span>.<span class='ident'>grow</span>(); } <span class='kw'>unsafe</span> { <span class='ident'>ptr</span>::<span class='ident'>write</span>(<span class='self'>self</span>.<span class='ident'>ptr</span>().<span class='ident'>offset</span>(<span class='self'>self</span>.<span class='ident'>len</span> <span class='kw'>as</span> <span class='ident'>isize</span>), <span class='ident'>elem</span>); } <span class='comment'>// Can&#39;t fail, we&#39;ll OOM first.</span> <span class='self'>self</span>.<span class='ident'>len</span> <span class='op'>+=</span> <span class='number'>1</span>; } <span class='kw'>pub</span> <span class='kw'>fn</span> <span class='ident'>pop</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>) <span class='op'>-&gt;</span> <span class='prelude-ty'>Option</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> { <span class='kw'>if</span> <span class='self'>self</span>.<span class='ident'>len</span> <span class='op'>==</span> <span class='number'>0</span> { <span class='prelude-val'>None</span> } <span class='kw'>else</span> { <span class='self'>self</span>.<span class='ident'>len</span> <span class='op'>-=</span> <span class='number'>1</span>; <span class='kw'>unsafe</span> { <span class='prelude-val'>Some</span>(<span class='ident'>ptr</span>::<span class='ident'>read</span>(<span class='self'>self</span>.<span class='ident'>ptr</span>().<span class='ident'>offset</span>(<span class='self'>self</span>.<span class='ident'>len</span> <span class='kw'>as</span> <span class='ident'>isize</span>))) } } } <span class='kw'>pub</span> <span class='kw'>fn</span> <span class='ident'>insert</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>, <span class='ident'>index</span>: <span class='ident'>usize</span>, <span class='ident'>elem</span>: <span class='ident'>T</span>) { <span class='macro'>assert</span><span class='macro'>!</span>(<span class='ident'>index</span> <span class='op'>&lt;=</span> <span class='self'>self</span>.<span class='ident'>len</span>, <span class='string'>&quot;index out of bounds&quot;</span>); <span class='kw'>if</span> <span class='self'>self</span>.<span class='ident'>cap</span>() <span class='op'>==</span> <span class='self'>self</span>.<span class='ident'>len</span> { <span class='self'>self</span>.<span class='ident'>buf</span>.<span class='ident'>grow</span>(); } <span class='kw'>unsafe</span> { <span class='kw'>if</span> <span class='ident'>index</span> <span class='op'>&lt;</span> <span class='self'>self</span>.<span class='ident'>len</span> { <span class='ident'>ptr</span>::<span class='ident'>copy</span>(<span class='self'>self</span>.<span class='ident'>ptr</span>().<span class='ident'>offset</span>(<span class='ident'>index</span> <span class='kw'>as</span> <span class='ident'>isize</span>), <span class='self'>self</span>.<span class='ident'>ptr</span>().<span class='ident'>offset</span>(<span class='ident'>index</span> <span class='kw'>as</span> <span class='ident'>isize</span> <span class='op'>+</span> <span class='number'>1</span>), <span class='self'>self</span>.<span class='ident'>len</span> <span class='op'>-</span> <span class='ident'>index</span>); } <span class='ident'>ptr</span>::<span class='ident'>write</span>(<span class='self'>self</span>.<span class='ident'>ptr</span>().<span class='ident'>offset</span>(<span class='ident'>index</span> <span class='kw'>as</span> <span class='ident'>isize</span>), <span class='ident'>elem</span>); <span class='self'>self</span>.<span class='ident'>len</span> <span class='op'>+=</span> <span class='number'>1</span>; } } <span class='kw'>pub</span> <span class='kw'>fn</span> <span class='ident'>remove</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>, <span class='ident'>index</span>: <span class='ident'>usize</span>) <span class='op'>-&gt;</span> <span class='ident'>T</span> { <span class='macro'>assert</span><span class='macro'>!</span>(<span class='ident'>index</span> <span class='op'>&lt;</span> <span class='self'>self</span>.<span class='ident'>len</span>, <span class='string'>&quot;index out of bounds&quot;</span>); <span class='kw'>unsafe</span> { <span class='self'>self</span>.<span class='ident'>len</span> <span class='op'>-=</span> <span class='number'>1</span>; <span class='kw'>let</span> <span class='ident'>result</span> <span class='op'>=</span> <span class='ident'>ptr</span>::<span class='ident'>read</span>(<span class='self'>self</span>.<span class='ident'>ptr</span>().<span class='ident'>offset</span>(<span class='ident'>index</span> <span class='kw'>as</span> <span class='ident'>isize</span>)); <span class='ident'>ptr</span>::<span class='ident'>copy</span>(<span class='self'>self</span>.<span class='ident'>ptr</span>().<span class='ident'>offset</span>(<span class='ident'>index</span> <span class='kw'>as</span> <span class='ident'>isize</span> <span class='op'>+</span> <span class='number'>1</span>), <span class='self'>self</span>.<span class='ident'>ptr</span>().<span class='ident'>offset</span>(<span class='ident'>index</span> <span class='kw'>as</span> <span class='ident'>isize</span>), <span class='self'>self</span>.<span class='ident'>len</span> <span class='op'>-</span> <span class='ident'>index</span>); <span class='ident'>result</span> } } <span class='kw'>pub</span> <span class='kw'>fn</span> <span class='ident'>into_iter</span>(<span class='self'>self</span>) <span class='op'>-&gt;</span> <span class='ident'>IntoIter</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> { <span class='kw'>unsafe</span> { <span class='kw'>let</span> <span class='ident'>iter</span> <span class='op'>=</span> <span class='ident'>RawValIter</span>::<span class='ident'>new</span>(<span class='kw-2'>&amp;</span><span class='self'>self</span>); <span class='kw'>let</span> <span class='ident'>buf</span> <span class='op'>=</span> <span class='ident'>ptr</span>::<span class='ident'>read</span>(<span class='kw-2'>&amp;</span><span class='self'>self</span>.<span class='ident'>buf</span>); <span class='ident'>mem</span>::<span class='ident'>forget</span>(<span class='self'>self</span>); <span class='ident'>IntoIter</span> { <span class='ident'>iter</span>: <span class='ident'>iter</span>, <span class='ident'>_buf</span>: <span class='ident'>buf</span>, } } } <span class='kw'>pub</span> <span class='kw'>fn</span> <span class='ident'>drain</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>) <span class='op'>-&gt;</span> <span class='ident'>Drain</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> { <span class='kw'>unsafe</span> { <span class='kw'>let</span> <span class='ident'>iter</span> <span class='op'>=</span> <span class='ident'>RawValIter</span>::<span class='ident'>new</span>(<span class='kw-2'>&amp;</span><span class='self'>self</span>); <span class='comment'>// this is a mem::forget safety thing. If Drain is forgotten, we just</span> <span class='comment'>// leak the whole Vec&#39;s contents. Also we need to do this *eventually*</span> <span class='comment'>// anyway, so why not do it now?</span> <span class='self'>self</span>.<span class='ident'>len</span> <span class='op'>=</span> <span class='number'>0</span>; <span class='ident'>Drain</span> { <span class='ident'>iter</span>: <span class='ident'>iter</span>, <span class='ident'>vec</span>: <span class='ident'>PhantomData</span>, } } } } <span class='kw'>impl</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> <span class='ident'>Drop</span> <span class='kw'>for</span> <span class='ident'>Vec</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> { <span class='kw'>fn</span> <span class='ident'>drop</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>) { <span class='kw'>while</span> <span class='kw'>let</span> <span class='prelude-val'>Some</span>(_) <span class='op'>=</span> <span class='self'>self</span>.<span class='ident'>pop</span>() {} <span class='comment'>// allocation is handled by RawVec</span> } } <span class='kw'>impl</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> <span class='ident'>Deref</span> <span class='kw'>for</span> <span class='ident'>Vec</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> { <span class='kw'>type</span> <span class='ident'>Target</span> <span class='op'>=</span> [<span class='ident'>T</span>]; <span class='kw'>fn</span> <span class='ident'>deref</span>(<span class='kw-2'>&amp;</span><span class='self'>self</span>) <span class='op'>-&gt;</span> <span class='kw-2'>&amp;</span>[<span class='ident'>T</span>] { <span class='kw'>unsafe</span> { ::<span class='ident'>std</span>::<span class='ident'>slice</span>::<span class='ident'>from_raw_parts</span>(<span class='self'>self</span>.<span class='ident'>ptr</span>(), <span class='self'>self</span>.<span class='ident'>len</span>) } } } <span class='kw'>impl</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> <span class='ident'>DerefMut</span> <span class='kw'>for</span> <span class='ident'>Vec</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> { <span class='kw'>fn</span> <span class='ident'>deref_mut</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>) <span class='op'>-&gt;</span> <span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> [<span class='ident'>T</span>] { <span class='kw'>unsafe</span> { ::<span class='ident'>std</span>::<span class='ident'>slice</span>::<span class='ident'>from_raw_parts_mut</span>(<span class='self'>self</span>.<span class='ident'>ptr</span>(), <span class='self'>self</span>.<span class='ident'>len</span>) } } } <span class='kw'>struct</span> <span class='ident'>RawValIter</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> { <span class='ident'>start</span>: <span class='op'>*</span><span class='kw'>const</span> <span class='ident'>T</span>, <span class='ident'>end</span>: <span class='op'>*</span><span class='kw'>const</span> <span class='ident'>T</span>, } <span class='kw'>impl</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> <span class='ident'>RawValIter</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> { <span class='kw'>unsafe</span> <span class='kw'>fn</span> <span class='ident'>new</span>(<span class='ident'>slice</span>: <span class='kw-2'>&amp;</span>[<span class='ident'>T</span>]) <span class='op'>-&gt;</span> <span class='self'>Self</span> { <span class='ident'>RawValIter</span> { <span class='ident'>start</span>: <span class='ident'>slice</span>.<span class='ident'>as_ptr</span>(), <span class='ident'>end</span>: <span class='kw'>if</span> <span class='ident'>mem</span>::<span class='ident'>size_of</span>::<span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span>() <span class='op'>==</span> <span class='number'>0</span> { ((<span class='ident'>slice</span>.<span class='ident'>as_ptr</span>() <span class='kw'>as</span> <span class='ident'>usize</span>) <span class='op'>+</span> <span class='ident'>slice</span>.<span class='ident'>len</span>()) <span class='kw'>as</span> <span class='op'>*</span><span class='kw'>const</span> _ } <span class='kw'>else</span> <span class='kw'>if</span> <span class='ident'>slice</span>.<span class='ident'>len</span>() <span class='op'>==</span> <span class='number'>0</span> { <span class='ident'>slice</span>.<span class='ident'>as_ptr</span>() } <span class='kw'>else</span> { <span class='ident'>slice</span>.<span class='ident'>as_ptr</span>().<span class='ident'>offset</span>(<span class='ident'>slice</span>.<span class='ident'>len</span>() <span class='kw'>as</span> <span class='ident'>isize</span>) } } } } <span class='kw'>impl</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> <span class='ident'>Iterator</span> <span class='kw'>for</span> <span class='ident'>RawValIter</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> { <span class='kw'>type</span> <span class='ident'>Item</span> <span class='op'>=</span> <span class='ident'>T</span>; <span class='kw'>fn</span> <span class='ident'>next</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>) <span class='op'>-&gt;</span> <span class='prelude-ty'>Option</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> { <span class='kw'>if</span> <span class='self'>self</span>.<span class='ident'>start</span> <span class='op'>==</span> <span class='self'>self</span>.<span class='ident'>end</span> { <span class='prelude-val'>None</span> } <span class='kw'>else</span> { <span class='kw'>unsafe</span> { <span class='kw'>let</span> <span class='ident'>result</span> <span class='op'>=</span> <span class='ident'>ptr</span>::<span class='ident'>read</span>(<span class='self'>self</span>.<span class='ident'>start</span>); <span class='self'>self</span>.<span class='ident'>start</span> <span class='op'>=</span> <span class='self'>self</span>.<span class='ident'>start</span>.<span class='ident'>offset</span>(<span class='number'>1</span>); <span class='prelude-val'>Some</span>(<span class='ident'>result</span>) } } } <span class='kw'>fn</span> <span class='ident'>size_hint</span>(<span class='kw-2'>&amp;</span><span class='self'>self</span>) <span class='op'>-&gt;</span> (<span class='ident'>usize</span>, <span class='prelude-ty'>Option</span><span class='op'>&lt;</span><span class='ident'>usize</span><span class='op'>&gt;</span>) { <span class='kw'>let</span> <span class='ident'>elem_size</span> <span class='op'>=</span> <span class='ident'>mem</span>::<span class='ident'>size_of</span>::<span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span>(); <span class='kw'>let</span> <span class='ident'>len</span> <span class='op'>=</span> (<span class='self'>self</span>.<span class='ident'>end</span> <span class='kw'>as</span> <span class='ident'>usize</span> <span class='op'>-</span> <span class='self'>self</span>.<span class='ident'>start</span> <span class='kw'>as</span> <span class='ident'>usize</span>) <span class='op'>/</span> <span class='kw'>if</span> <span class='ident'>elem_size</span> <span class='op'>==</span> <span class='number'>0</span> { <span class='number'>1</span> } <span class='kw'>else</span> { <span class='ident'>elem_size</span> }; (<span class='ident'>len</span>, <span class='prelude-val'>Some</span>(<span class='ident'>len</span>)) } } <span class='kw'>impl</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> <span class='ident'>DoubleEndedIterator</span> <span class='kw'>for</span> <span class='ident'>RawValIter</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> { <span class='kw'>fn</span> <span class='ident'>next_back</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>) <span class='op'>-&gt;</span> <span class='prelude-ty'>Option</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> { <span class='kw'>if</span> <span class='self'>self</span>.<span class='ident'>start</span> <span class='op'>==</span> <span class='self'>self</span>.<span class='ident'>end</span> { <span class='prelude-val'>None</span> } <span class='kw'>else</span> { <span class='kw'>unsafe</span> { <span class='self'>self</span>.<span class='ident'>end</span> <span class='op'>=</span> <span class='self'>self</span>.<span class='ident'>end</span>.<span class='ident'>offset</span>(<span class='op'>-</span><span class='number'>1</span>); <span class='prelude-val'>Some</span>(<span class='ident'>ptr</span>::<span class='ident'>read</span>(<span class='self'>self</span>.<span class='ident'>end</span>)) } } } } <span class='kw'>pub</span> <span class='kw'>struct</span> <span class='ident'>IntoIter</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> { <span class='ident'>_buf</span>: <span class='ident'>RawVec</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span>, <span class='comment'>// we don&#39;t actually care about this. Just need it to live.</span> <span class='ident'>iter</span>: <span class='ident'>RawValIter</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span>, } <span class='kw'>impl</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> <span class='ident'>Iterator</span> <span class='kw'>for</span> <span class='ident'>IntoIter</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> { <span class='kw'>type</span> <span class='ident'>Item</span> <span class='op'>=</span> <span class='ident'>T</span>; <span class='kw'>fn</span> <span class='ident'>next</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>) <span class='op'>-&gt;</span> <span class='prelude-ty'>Option</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> { <span class='self'>self</span>.<span class='ident'>iter</span>.<span class='ident'>next</span>() } <span class='kw'>fn</span> <span class='ident'>size_hint</span>(<span class='kw-2'>&amp;</span><span class='self'>self</span>) <span class='op'>-&gt;</span> (<span class='ident'>usize</span>, <span class='prelude-ty'>Option</span><span class='op'>&lt;</span><span class='ident'>usize</span><span class='op'>&gt;</span>) { <span class='self'>self</span>.<span class='ident'>iter</span>.<span class='ident'>size_hint</span>() } } <span class='kw'>impl</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> <span class='ident'>DoubleEndedIterator</span> <span class='kw'>for</span> <span class='ident'>IntoIter</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> { <span class='kw'>fn</span> <span class='ident'>next_back</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>) <span class='op'>-&gt;</span> <span class='prelude-ty'>Option</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> { <span class='self'>self</span>.<span class='ident'>iter</span>.<span class='ident'>next_back</span>() } } <span class='kw'>impl</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> <span class='ident'>Drop</span> <span class='kw'>for</span> <span class='ident'>IntoIter</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> { <span class='kw'>fn</span> <span class='ident'>drop</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>) { <span class='kw'>for</span> _ <span class='kw'>in</span> <span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='op'>*</span><span class='self'>self</span> {} } } <span class='kw'>pub</span> <span class='kw'>struct</span> <span class='ident'>Drain</span><span class='op'>&lt;</span><span class='lifetime'>&#39;a</span>, <span class='ident'>T</span>: <span class='lifetime'>&#39;a</span><span class='op'>&gt;</span> { <span class='ident'>vec</span>: <span class='ident'>PhantomData</span><span class='op'>&lt;</span><span class='kw-2'>&amp;</span><span class='lifetime'>&#39;a</span> <span class='kw-2'>mut</span> <span class='ident'>Vec</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;&gt;</span>, <span class='ident'>iter</span>: <span class='ident'>RawValIter</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span>, } <span class='kw'>impl</span><span class='op'>&lt;</span><span class='lifetime'>&#39;a</span>, <span class='ident'>T</span><span class='op'>&gt;</span> <span class='ident'>Iterator</span> <span class='kw'>for</span> <span class='ident'>Drain</span><span class='op'>&lt;</span><span class='lifetime'>&#39;a</span>, <span class='ident'>T</span><span class='op'>&gt;</span> { <span class='kw'>type</span> <span class='ident'>Item</span> <span class='op'>=</span> <span class='ident'>T</span>; <span class='kw'>fn</span> <span class='ident'>next</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>) <span class='op'>-&gt;</span> <span class='prelude-ty'>Option</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> { <span class='self'>self</span>.<span class='ident'>iter</span>.<span class='ident'>next_back</span>() } <span class='kw'>fn</span> <span class='ident'>size_hint</span>(<span class='kw-2'>&amp;</span><span class='self'>self</span>) <span class='op'>-&gt;</span> (<span class='ident'>usize</span>, <span class='prelude-ty'>Option</span><span class='op'>&lt;</span><span class='ident'>usize</span><span class='op'>&gt;</span>) { <span class='self'>self</span>.<span class='ident'>iter</span>.<span class='ident'>size_hint</span>() } } <span class='kw'>impl</span><span class='op'>&lt;</span><span class='lifetime'>&#39;a</span>, <span class='ident'>T</span><span class='op'>&gt;</span> <span class='ident'>DoubleEndedIterator</span> <span class='kw'>for</span> <span class='ident'>Drain</span><span class='op'>&lt;</span><span class='lifetime'>&#39;a</span>, <span class='ident'>T</span><span class='op'>&gt;</span> { <span class='kw'>fn</span> <span class='ident'>next_back</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>) <span class='op'>-&gt;</span> <span class='prelude-ty'>Option</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> { <span class='self'>self</span>.<span class='ident'>iter</span>.<span class='ident'>next_back</span>() } } <span class='kw'>impl</span><span class='op'>&lt;</span><span class='lifetime'>&#39;a</span>, <span class='ident'>T</span><span class='op'>&gt;</span> <span class='ident'>Drop</span> <span class='kw'>for</span> <span class='ident'>Drain</span><span class='op'>&lt;</span><span class='lifetime'>&#39;a</span>, <span class='ident'>T</span><span class='op'>&gt;</span> { <span class='kw'>fn</span> <span class='ident'>drop</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>) { <span class='comment'>// pre-drain the iter</span> <span class='kw'>for</span> _ <span class='kw'>in</span> <span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>.<span class='ident'>iter</span> {} } } <span class='doccomment'>/// Abort the process, we&#39;re out of memory!</span> <span class='doccomment'>///</span> <span class='doccomment'>/// In practice this is probably dead code on most OSes</span> <span class='kw'>fn</span> <span class='ident'>oom</span>() { ::<span class='ident'>std</span>::<span class='ident'>process</span>::<span class='ident'>exit</span>(<span class='op'>-</span><span class='number'>9999</span>); } </pre> <script type="text/javascript"> window.playgroundUrl = "https://play.rust-lang.org"; </script> <script src='rustbook.js'></script> <script src='playpen.js'></script> </div></div> </body> </html> <|start_filename|>docs/1.6/book/benchmark-tests.html<|end_filename|> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="generator" content="rustdoc"> <title>ベンチマークテスト</title> <link rel="stylesheet" type="text/css" href="rustbook.css"> <meta name="robots" content="noindex"> </head> <body class="rustdoc"> <!--[if lte IE 8]> <div class="warning"> This old browser is unsupported and will most likely display funky things. </div> <![endif]--> <div id="nav"> <button id="toggle-nav"> <span class="sr-only">Toggle navigation</span> <span class="bar"></span> <span class="bar"></span> <span class="bar"></span> </button> </div> <div id='toc' class='mobile-hidden'> <ul class='chapter'> <li><a href='README.html'><b>1.</b> Introduction</a> </li> <li><a href='getting-started.html'><b>2.</b> はじめる</a> </li> <li><a href='learn-rust.html'><b>3.</b> Rustを学ぶ</a> <ul class='section'> <li><a href='guessing-game.html'><b>3.1.</b> 数当てゲーム</a> </li> <li><a href='dining-philosophers.html'><b>3.2.</b> 食事する哲学者</a> </li> <li><a href='rust-inside-other-languages.html'><b>3.3.</b> 他言語と共存する</a> </li> </ul> </li> <li><a href='syntax-and-semantics.html'><b>4.</b> シンタックスとセマンティクス</a> <ul class='section'> <li><a href='variable-bindings.html'><b>4.1.</b> 変数束縛</a> </li> <li><a href='functions.html'><b>4.2.</b> 関数</a> </li> <li><a href='primitive-types.html'><b>4.3.</b> プリミティブ型</a> </li> <li><a href='comments.html'><b>4.4.</b> コメント</a> </li> <li><a href='if.html'><b>4.5.</b> if</a> </li> <li><a href='loops.html'><b>4.6.</b> ループ</a> </li> <li><a href='ownership.html'><b>4.7.</b> 所有権</a> </li> <li><a href='references-and-borrowing.html'><b>4.8.</b> 参照と借用</a> </li> <li><a href='lifetimes.html'><b>4.9.</b> ライフタイム</a> </li> <li><a href='mutability.html'><b>4.10.</b> ミュータビリティ</a> </li> <li><a href='structs.html'><b>4.11.</b> 構造体</a> </li> <li><a href='enums.html'><b>4.12.</b> 列挙型</a> </li> <li><a href='match.html'><b>4.13.</b> マッチ</a> </li> <li><a href='patterns.html'><b>4.14.</b> パターン</a> </li> <li><a href='method-syntax.html'><b>4.15.</b> メソッド構文</a> </li> <li><a href='vectors.html'><b>4.16.</b> ベクタ</a> </li> <li><a href='strings.html'><b>4.17.</b> 文字列</a> </li> <li><a href='generics.html'><b>4.18.</b> ジェネリクス</a> </li> <li><a href='traits.html'><b>4.19.</b> トレイト</a> </li> <li><a href='drop.html'><b>4.20.</b> Drop</a> </li> <li><a href='if-let.html'><b>4.21.</b> if let</a> </li> <li><a href='trait-objects.html'><b>4.22.</b> トレイトオブジェクト</a> </li> <li><a href='closures.html'><b>4.23.</b> クロージャ</a> </li> <li><a href='ufcs.html'><b>4.24.</b> 共通の関数呼出構文</a> </li> <li><a href='crates-and-modules.html'><b>4.25.</b> クレートとモジュール</a> </li> <li><a href='const-and-static.html'><b>4.26.</b> `const` と `static`</a> </li> <li><a href='attributes.html'><b>4.27.</b> アトリビュート</a> </li> <li><a href='type-aliases.html'><b>4.28.</b> `type` エイリアス</a> </li> <li><a href='casting-between-types.html'><b>4.29.</b> 型間のキャスト</a> </li> <li><a href='associated-types.html'><b>4.30.</b> 関連型</a> </li> <li><a href='unsized-types.html'><b>4.31.</b> サイズ不定型</a> </li> <li><a href='operators-and-overloading.html'><b>4.32.</b> 演算子とオーバーロード</a> </li> <li><a href='deref-coercions.html'><b>4.33.</b> Derefによる型強制</a> </li> <li><a href='macros.html'><b>4.34.</b> マクロ</a> </li> <li><a href='raw-pointers.html'><b>4.35.</b> 生ポインタ</a> </li> <li><a href='unsafe.html'><b>4.36.</b> `unsafe`</a> </li> </ul> </li> <li><a href='effective-rust.html'><b>5.</b> Effective Rust</a> <ul class='section'> <li><a href='the-stack-and-the-heap.html'><b>5.1.</b> スタックとヒープ</a> </li> <li><a href='testing.html'><b>5.2.</b> テスト</a> </li> <li><a href='conditional-compilation.html'><b>5.3.</b> 条件付きコンパイル</a> </li> <li><a href='documentation.html'><b>5.4.</b> ドキュメント</a> </li> <li><a href='iterators.html'><b>5.5.</b> イテレータ</a> </li> <li><a href='concurrency.html'><b>5.6.</b> 並行性</a> </li> <li><a href='error-handling.html'><b>5.7.</b> エラーハンドリング</a> </li> <li><a href='choosing-your-guarantees.html'><b>5.8.</b> 保証を選ぶ</a> </li> <li><a href='ffi.html'><b>5.9.</b> 他言語関数インターフェース</a> </li> <li><a href='borrow-and-asref.html'><b>5.10.</b> BorrowとAsRef</a> </li> <li><a href='release-channels.html'><b>5.11.</b> リリースチャネル</a> </li> <li><a href='using-rust-without-the-standard-library.html'><b>5.12.</b> 標準ライブラリ無しでRustを使う</a> </li> </ul> </li> <li><a href='nightly-rust.html'><b>6.</b> Nightly Rust</a> <ul class='section'> <li><a href='compiler-plugins.html'><b>6.1.</b> コンパイラプラグイン</a> </li> <li><a href='inline-assembly.html'><b>6.2.</b> インラインアセンブリ</a> </li> <li><a href='no-stdlib.html'><b>6.3.</b> No stdlib</a> </li> <li><a href='intrinsics.html'><b>6.4.</b> Intrinsic</a> </li> <li><a href='lang-items.html'><b>6.5.</b> 言語アイテム</a> </li> <li><a href='advanced-linking.html'><b>6.6.</b> 高度なリンキング</a> </li> <li><a class='active' href='benchmark-tests.html'><b>6.7.</b> ベンチマークテスト</a> </li> <li><a href='box-syntax-and-patterns.html'><b>6.8.</b> Box構文とパターン</a> </li> <li><a href='slice-patterns.html'><b>6.9.</b> スライスパターン</a> </li> <li><a href='associated-constants.html'><b>6.10.</b> 関連定数</a> </li> <li><a href='custom-allocators.html'><b>6.11.</b> カスタムアロケータ</a> </li> </ul> </li> <li><a href='glossary.html'><b>7.</b> 用語集</a> </li> <li><a href='syntax-index.html'><b>8.</b> 構文の索引</a> </li> <li><a href='bibliography.html'><b>9.</b> 関係書目</a> </li> </ul> </div> <div id='page-wrapper'> <div id='page'> <blockquote class="header-caveat"> <p> <strong>注意: <a href="https://doc.rust-jp.rs/book-ja/">最新版のドキュメントをご覧ください。</a></strong>この第1版ドキュメントは古くなっており、最新情報が反映されていません。リンク先のドキュメントが現在の Rust の最新のドキュメントです。 </p> </blockquote> <h1 class="title">ベンチマークテスト</h1> <!-- % Benchmark tests --> <!-- Rust supports benchmark tests, which can test the performance of your --> <!-- code. Let's make our `src/lib.rs` look like this (comments elided): --> <p>Rustはコードのパフォーマンスをテストできるベンチマークテストをサポートしています。 早速、 <code>src/lib.rc</code> を以下のように作っていきましょう(コメントは省略しています):</p> <span class='rusttest'>#![feature(test)] fn main() { extern crate test; pub fn add_two(a: i32) -&gt; i32 { a + 2 } #[cfg(test)] mod tests { use super::*; use test::Bencher; #[test] fn it_works() { assert_eq!(4, add_two(2)); } #[bench] fn bench_add_two(b: &amp;mut Bencher) { b.iter(|| add_two(2)); } } }</span><pre class='rust rust-example-rendered'> <span class='attribute'>#<span class='op'>!</span>[<span class='ident'>feature</span>(<span class='ident'>test</span>)]</span> <span class='kw'>extern</span> <span class='kw'>crate</span> <span class='ident'>test</span>; <span class='kw'>pub</span> <span class='kw'>fn</span> <span class='ident'>add_two</span>(<span class='ident'>a</span>: <span class='ident'>i32</span>) <span class='op'>-&gt;</span> <span class='ident'>i32</span> { <span class='ident'>a</span> <span class='op'>+</span> <span class='number'>2</span> } <span class='attribute'>#[<span class='ident'>cfg</span>(<span class='ident'>test</span>)]</span> <span class='kw'>mod</span> <span class='ident'>tests</span> { <span class='kw'>use</span> <span class='kw'>super</span>::<span class='op'>*</span>; <span class='kw'>use</span> <span class='ident'>test</span>::<span class='ident'>Bencher</span>; <span class='attribute'>#[<span class='ident'>test</span>]</span> <span class='kw'>fn</span> <span class='ident'>it_works</span>() { <span class='macro'>assert_eq</span><span class='macro'>!</span>(<span class='number'>4</span>, <span class='ident'>add_two</span>(<span class='number'>2</span>)); } <span class='attribute'>#[<span class='ident'>bench</span>]</span> <span class='kw'>fn</span> <span class='ident'>bench_add_two</span>(<span class='ident'>b</span>: <span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='ident'>Bencher</span>) { <span class='ident'>b</span>.<span class='ident'>iter</span>(<span class='op'>||</span> <span class='ident'>add_two</span>(<span class='number'>2</span>)); } }</pre> <!-- Note the `test` feature gate, which enables this unstable feature. --> <p>不安定なベンチマークのフィーチャを有効にするため、 <code>test</code> フィーチャゲートを利用していることに注意して下さい。</p> <!-- We've imported the `test` crate, which contains our benchmarking support. --> <!-- We have a new function as well, with the `bench` attribute. Unlike regular --> <!-- tests, which take no arguments, benchmark tests take a `&mut Bencher`. This --> <!-- `Bencher` provides an `iter` method, which takes a closure. This closure --> <!-- contains the code we'd like to benchmark. --> <p>ベンチマークテストのサポートを含んだ <code>test</code> クレートをインポートしています。 また、 <code>bench</code> アトリビュートのついた新しい関数を定義しています。 引数を取らない通常のテストとは異なり、ベンチマークテストは <code>&amp;mut Bencher</code> を引数に取ります。 <code>Bencher</code> はベンチマークしたいコードを含んだクロージャを引数に取る <code>iter</code> メソッドを提供しています。</p> <!-- We can run benchmark tests with `cargo bench`: --> <p>ベンチマークテストは以下のように <code>cargo bench</code> のようにして実施できます:</p> <pre><code class="language-bash">$ cargo bench Compiling adder v0.0.1 (file:///home/steve/tmp/adder) Running target/release/adder-91b3e234d4ed382a running 2 tests test tests::it_works ... ignored test tests::bench_add_two ... bench: 1 ns/iter (+/- 0) test result: ok. 0 passed; 0 failed; 1 ignored; 1 measured </code></pre> <!-- Our non-benchmark test was ignored. You may have noticed that `cargo bench` --> <!-- takes a bit longer than `cargo test`. This is because Rust runs our benchmark --> <!-- a number of times, and then takes the average. Because we're doing so little --> <!-- work in this example, we have a `1 ns/iter (+/- 0)`, but this would show --> <!-- the variance if there was one. --> <p>ベンチマークでないテストは無視されます。 <code>cargo bench</code> が <code>cargo test</code> よりも時間がかかることにお気づきになったかもしれません。 これは、Rustがベンチマークをかなりの回数繰り返し実行し、その結果の平均を取るためです。 今回のコードでは非常に小さな処理しか行っていないために、 <code>1 ns/iter (+/- 0)</code> という結果を得ました、 しかし、この結果は変動することがあるでしょう。</p> <!-- Advice on writing benchmarks: --> <p>以下は、ベンチマークを書くときのアドバイスです:</p> <!-- * Move setup code outside the `iter` loop; only put the part you want to measure inside --> <!-- * Make the code do "the same thing" on each iteration; do not accumulate or change state --> <!-- * Make the outer function idempotent too; the benchmark runner is likely to run --> <!-- it many times --> <!-- * Make the inner `iter` loop short and fast so benchmark runs are fast and the --> <!-- calibrator can adjust the run-length at fine resolution --> <!-- * Make the code in the `iter` loop do something simple, to assist in pinpointing --> <!-- performance improvements (or regressions) --> <ul> <li>セットアップのコードを <code>iter</code> の外に移し、計測したい箇所のみを <code>iter</code> の中に書きましょう。</li> <li>それぞれの繰り返しでコードが「同じこと」をするようにし、集計をしたり状態を変更したりといったことはしないで下さい。</li> <li>利用している外部の関数についても冪等にしましょう、ベンチマークはその関数をおそらく何度も実行します。</li> <li>内側の <code>iter</code> ループを短く高速にしましょう、そうすることでベンチマークの実行は高速になり、キャリブレータは実行の長さをより良い精度で補正できるようになります。</li> <li>パフォーマンスの向上(または低下)をピンポイントで突き止められるように、<code>iter</code> ループ中のコードの処理を簡潔にしましょう。</li> </ul> <!-- ## Gotcha: optimizations --> <h2 id='注意点-最適化' class='section-header'><a href='#注意点-最適化'>注意点: 最適化</a></h2> <!-- There's another tricky part to writing benchmarks: benchmarks compiled with --> <!-- optimizations activated can be dramatically changed by the optimizer so that --> <!-- the benchmark is no longer benchmarking what one expects. For example, the --> <!-- compiler might recognize that some calculation has no external effects and --> <!-- remove it entirely. --> <p>ベンチマークを書くときに気をつけなければならないその他の点は: 最適化を有効にしてコンパイルしたベンチマークは劇的に最適化され、 もはや本来ベンチマークしたかったコードとは異なるという点です。 たとえば、コンパイラは幾つかの計算がなにも外部に影響を及ぼさないことを認識してそれらの計算を取り除くかもしれません。</p> <span class='rusttest'>#![feature(test)] fn main() { extern crate test; use test::Bencher; #[bench] fn bench_xor_1000_ints(b: &amp;mut Bencher) { b.iter(|| { (0..1000).fold(0, |old, new| old ^ new); }); } }</span><pre class='rust rust-example-rendered'> <span class='attribute'>#<span class='op'>!</span>[<span class='ident'>feature</span>(<span class='ident'>test</span>)]</span> <span class='kw'>extern</span> <span class='kw'>crate</span> <span class='ident'>test</span>; <span class='kw'>use</span> <span class='ident'>test</span>::<span class='ident'>Bencher</span>; <span class='attribute'>#[<span class='ident'>bench</span>]</span> <span class='kw'>fn</span> <span class='ident'>bench_xor_1000_ints</span>(<span class='ident'>b</span>: <span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='ident'>Bencher</span>) { <span class='ident'>b</span>.<span class='ident'>iter</span>(<span class='op'>||</span> { (<span class='number'>0</span>..<span class='number'>1000</span>).<span class='ident'>fold</span>(<span class='number'>0</span>, <span class='op'>|</span><span class='ident'>old</span>, <span class='ident'>new</span><span class='op'>|</span> <span class='ident'>old</span> <span class='op'>^</span> <span class='ident'>new</span>); }); }</pre> <!-- gives the following results --> <p>このベンチマークは以下の様な結果となります</p> <pre><code class="language-text">running 1 test test bench_xor_1000_ints ... bench: 0 ns/iter (+/- 0) test result: ok. 0 passed; 0 failed; 0 ignored; 1 measured </code></pre> <!-- The benchmarking runner offers two ways to avoid this. Either, the closure that --> <!-- the `iter` method receives can return an arbitrary value which forces the --> <!-- optimizer to consider the result used and ensures it cannot remove the --> <!-- computation entirely. This could be done for the example above by adjusting the --> <!-- `b.iter` call to --> <p>ベンチマークランナーはこの問題を避ける2つの手段を提供します。 <code>iter</code> メソッドが受け取るクロージャは任意の値を返すことができ、 オプティマイザに計算の結果が利用されていると考えさせ、その計算を取り除くことができないと保証することができます。 これは、上のコードにおいて <code>b.iter</code> の呼出を以下のようにすることで可能です:</p> <span class='rusttest'>fn main() { struct X; impl X { fn iter&lt;T, F&gt;(&amp;self, _: F) where F: FnMut() -&gt; T {} } let b = X; b.iter(|| { // note lack of `;` (could also use an explicit `return`). // `;` が無いことに注意して下さい (明示的な `return` を使うこともできます)。 (0..1000).fold(0, |old, new| old ^ new) }); }</span><pre class='rust rust-example-rendered'> <span class='ident'>b</span>.<span class='ident'>iter</span>(<span class='op'>||</span> { <span class='comment'>// `;` が無いことに注意して下さい (明示的な `return` を使うこともできます)。</span> (<span class='number'>0</span>..<span class='number'>1000</span>).<span class='ident'>fold</span>(<span class='number'>0</span>, <span class='op'>|</span><span class='ident'>old</span>, <span class='ident'>new</span><span class='op'>|</span> <span class='ident'>old</span> <span class='op'>^</span> <span class='ident'>new</span>) });</pre> <!-- Or, the other option is to call the generic `test::black_box` function, which --> <!-- is an opaque "black box" to the optimizer and so forces it to consider any --> <!-- argument as used. --> <p>もう一つの方法としては、ジェネリックな <code>test::black_box</code> 関数を呼び出すという手段が有ります、 <code>test::black_box</code> 関数はオプティマイザにとって不透明な「ブラックボックス」であり、 オプティマイザに引数のどれもが利用されていると考えさせることができます。</p> <span class='rusttest'>#![feature(test)] extern crate test; fn main() { struct X; impl X { fn iter&lt;T, F&gt;(&amp;self, _: F) where F: FnMut() -&gt; T {} } let b = X; b.iter(|| { let n = test::black_box(1000); (0..n).fold(0, |a, b| a ^ b) }) } </span><pre class='rust rust-example-rendered'> <span class='attribute'>#<span class='op'>!</span>[<span class='ident'>feature</span>(<span class='ident'>test</span>)]</span> <span class='kw'>extern</span> <span class='kw'>crate</span> <span class='ident'>test</span>; <span class='ident'>b</span>.<span class='ident'>iter</span>(<span class='op'>||</span> { <span class='kw'>let</span> <span class='ident'>n</span> <span class='op'>=</span> <span class='ident'>test</span>::<span class='ident'>black_box</span>(<span class='number'>1000</span>); (<span class='number'>0</span>..<span class='ident'>n</span>).<span class='ident'>fold</span>(<span class='number'>0</span>, <span class='op'>|</span><span class='ident'>a</span>, <span class='ident'>b</span><span class='op'>|</span> <span class='ident'>a</span> <span class='op'>^</span> <span class='ident'>b</span>) })</pre> <!-- Neither of these read or modify the value, and are very cheap for small values. --> <!-- Larger values can be passed indirectly to reduce overhead (e.g. --> <!-- `black_box(&huge_struct)`). --> <p>2つの手段のどちらも値を読んだり変更したりせず、小さな値に対して非常に低コストです。 大きな値は、オーバーヘッドを減らすために間接的に渡すことができます(例: <code>black_box(&amp;huge_struct)</code>)。</p> <!-- Performing either of the above changes gives the following benchmarking results --> <p>上記のどちらかの変更を施すことでベンチマークの結果は以下のようになります</p> <pre><code class="language-text">running 1 test test bench_xor_1000_ints ... bench: 131 ns/iter (+/- 3) test result: ok. 0 passed; 0 failed; 0 ignored; 1 measured </code></pre> <!-- However, the optimizer can still modify a testcase in an undesirable manner --> <!-- even when using either of the above. --> <p>しかしながら、上のどちらかの方法をとったとしても依然オプティマイザはテストケースを望まない形で変更する場合があります。</p> <script type="text/javascript"> window.playgroundUrl = "https://play.rust-lang.org"; </script> <script src='rustbook.js'></script> <script src='playpen.js'></script> </div></div> </body> </html> <|start_filename|>docs/1.9/book/unsized-types.html<|end_filename|> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="generator" content="rustdoc"> <title>サイズ不定型</title> <link rel="stylesheet" type="text/css" href="rustbook.css"> <meta name="robots" content="noindex"> </head> <body class="rustdoc"> <!--[if lte IE 8]> <div class="warning"> This old browser is unsupported and will most likely display funky things. </div> <![endif]--> <div id="nav"> <button id="toggle-nav"> <span class="sr-only">Toggle navigation</span> <span class="bar"></span> <span class="bar"></span> <span class="bar"></span> </button> </div> <div id='toc' class='mobile-hidden'> <ul class='chapter'> <li><a href='README.html'><b>1.</b> Introduction</a> </li> <li><a href='getting-started.html'><b>2.</b> はじめる</a> </li> <li><a href='guessing-game.html'><b>3.</b> チュートリアル:数当てゲーム</a> </li> <li><a href='syntax-and-semantics.html'><b>4.</b> シンタックスとセマンティクス</a> <ul class='section'> <li><a href='variable-bindings.html'><b>4.1.</b> 変数束縛</a> </li> <li><a href='functions.html'><b>4.2.</b> 関数</a> </li> <li><a href='primitive-types.html'><b>4.3.</b> プリミティブ型</a> </li> <li><a href='comments.html'><b>4.4.</b> コメント</a> </li> <li><a href='if.html'><b>4.5.</b> if</a> </li> <li><a href='loops.html'><b>4.6.</b> ループ</a> </li> <li><a href='vectors.html'><b>4.7.</b> ベクタ</a> </li> <li><a href='ownership.html'><b>4.8.</b> 所有権</a> </li> <li><a href='references-and-borrowing.html'><b>4.9.</b> 参照と借用</a> </li> <li><a href='lifetimes.html'><b>4.10.</b> ライフタイム</a> </li> <li><a href='mutability.html'><b>4.11.</b> ミュータビリティ</a> </li> <li><a href='structs.html'><b>4.12.</b> 構造体</a> </li> <li><a href='enums.html'><b>4.13.</b> 列挙型</a> </li> <li><a href='match.html'><b>4.14.</b> マッチ</a> </li> <li><a href='patterns.html'><b>4.15.</b> パターン</a> </li> <li><a href='method-syntax.html'><b>4.16.</b> メソッド構文</a> </li> <li><a href='strings.html'><b>4.17.</b> 文字列</a> </li> <li><a href='generics.html'><b>4.18.</b> ジェネリクス</a> </li> <li><a href='traits.html'><b>4.19.</b> トレイト</a> </li> <li><a href='drop.html'><b>4.20.</b> Drop</a> </li> <li><a href='if-let.html'><b>4.21.</b> if let</a> </li> <li><a href='trait-objects.html'><b>4.22.</b> トレイトオブジェクト</a> </li> <li><a href='closures.html'><b>4.23.</b> クロージャ</a> </li> <li><a href='ufcs.html'><b>4.24.</b> 共通の関数呼出構文</a> </li> <li><a href='crates-and-modules.html'><b>4.25.</b> クレートとモジュール</a> </li> <li><a href='const-and-static.html'><b>4.26.</b> `const` と `static`</a> </li> <li><a href='attributes.html'><b>4.27.</b> アトリビュート</a> </li> <li><a href='type-aliases.html'><b>4.28.</b> `type` エイリアス</a> </li> <li><a href='casting-between-types.html'><b>4.29.</b> 型間のキャスト</a> </li> <li><a href='associated-types.html'><b>4.30.</b> 関連型</a> </li> <li><a class='active' href='unsized-types.html'><b>4.31.</b> サイズ不定型</a> </li> <li><a href='operators-and-overloading.html'><b>4.32.</b> 演算子とオーバーロード</a> </li> <li><a href='deref-coercions.html'><b>4.33.</b> Derefによる型強制</a> </li> <li><a href='macros.html'><b>4.34.</b> マクロ</a> </li> <li><a href='raw-pointers.html'><b>4.35.</b> 生ポインタ</a> </li> <li><a href='unsafe.html'><b>4.36.</b> `unsafe`</a> </li> </ul> </li> <li><a href='effective-rust.html'><b>5.</b> Effective Rust</a> <ul class='section'> <li><a href='the-stack-and-the-heap.html'><b>5.1.</b> スタックとヒープ</a> </li> <li><a href='testing.html'><b>5.2.</b> テスト</a> </li> <li><a href='conditional-compilation.html'><b>5.3.</b> 条件付きコンパイル</a> </li> <li><a href='documentation.html'><b>5.4.</b> ドキュメント</a> </li> <li><a href='iterators.html'><b>5.5.</b> イテレータ</a> </li> <li><a href='concurrency.html'><b>5.6.</b> 並行性</a> </li> <li><a href='error-handling.html'><b>5.7.</b> エラーハンドリング</a> </li> <li><a href='choosing-your-guarantees.html'><b>5.8.</b> 保証を選ぶ</a> </li> <li><a href='ffi.html'><b>5.9.</b> 他言語関数インターフェース</a> </li> <li><a href='borrow-and-asref.html'><b>5.10.</b> BorrowとAsRef</a> </li> <li><a href='release-channels.html'><b>5.11.</b> リリースチャネル</a> </li> <li><a href='using-rust-without-the-standard-library.html'><b>5.12.</b> 標準ライブラリ無しでRustを使う</a> </li> </ul> </li> <li><a href='nightly-rust.html'><b>6.</b> Nightly Rust</a> <ul class='section'> <li><a href='compiler-plugins.html'><b>6.1.</b> コンパイラプラグイン</a> </li> <li><a href='inline-assembly.html'><b>6.2.</b> インラインアセンブリ</a> </li> <li><a href='no-stdlib.html'><b>6.3.</b> No stdlib</a> </li> <li><a href='intrinsics.html'><b>6.4.</b> Intrinsic</a> </li> <li><a href='lang-items.html'><b>6.5.</b> 言語アイテム</a> </li> <li><a href='advanced-linking.html'><b>6.6.</b> 高度なリンキング</a> </li> <li><a href='benchmark-tests.html'><b>6.7.</b> ベンチマークテスト</a> </li> <li><a href='box-syntax-and-patterns.html'><b>6.8.</b> Box構文とパターン</a> </li> <li><a href='slice-patterns.html'><b>6.9.</b> スライスパターン</a> </li> <li><a href='associated-constants.html'><b>6.10.</b> 関連定数</a> </li> <li><a href='custom-allocators.html'><b>6.11.</b> カスタムアロケータ</a> </li> </ul> </li> <li><a href='glossary.html'><b>7.</b> 用語集</a> </li> <li><a href='syntax-index.html'><b>8.</b> 構文の索引</a> </li> <li><a href='bibliography.html'><b>9.</b> 関係書目</a> </li> </ul> </div> <div id='page-wrapper'> <div id='page'> <blockquote class="header-caveat"> <p> <strong>注意: <a href="https://doc.rust-jp.rs/book-ja/">最新版のドキュメントをご覧ください。</a></strong>この第1版ドキュメントは古くなっており、最新情報が反映されていません。リンク先のドキュメントが現在の Rust の最新のドキュメントです。 </p> </blockquote> <h1 class="title">サイズ不定型</h1> <!-- % Unsized Types --> <!-- Most types have a particular size, in bytes, that is knowable at compile time. --> <!-- For example, an `i32` is thirty-two bits big, or four bytes. However, there are --> <!-- some types which are useful to express, but do not have a defined size. These are --> <!-- called ‘unsized’ or ‘dynamically sized’ types. One example is `[T]`. This type --> <!-- represents a certain number of `T` in sequence. But we don’t know how many --> <!-- there are, so the size is not known. --> <p>ほとんどの型はコンパイル時に知れる、バイト数で測った、サイズがあります。 たとえば、 <code>i32</code> 型は、32ビット(4バイト)というサイズです。 しかしながら、表現のためには便利であってもサイズが定まっていない型が存在します。 そのような型を 「サイズ不定」または「動的サイズ」型と呼びます。 一例を上げると <code>[T]</code> 型は 一定のサイズの<code>T</code> のシーケンスを意味していますが、その要素数については規定されていないため、サイズは不定となります。</p> <!-- Rust understands a few of these types, but they have some restrictions. There --> <!-- are three: --> <p>Rustはいくつかのそのような型を扱うことができますが、それらには以下の様な3つの制約が存在します:</p> <!-- 1. We can only manipulate an instance of an unsized type via a pointer. An -> <!-- `&[T]` works fine, but a `[T]` does not. --> <!-- 2. Variables and arguments cannot have dynamically sized types. --> <!-- 3. Only the last field in a `struct` may have a dynamically sized type; the --> <!-- other fields must not. Enum variants must not have dynamically sized types as --> <!-- data. --> <ol> <li>サイズ不定型はポインタを通してのみ操作できます。 たとえば、 <code>&amp;[T]</code> は大丈夫ですが、 <code>[T]</code> はそうではありません。</li> <li>変数や引数は動的なサイズを持つことはできません。</li> <li><code>struct</code> の最後のフィールドのみ、動的なサイズを持つことが許されます。 その他のフィールドはサイズが不定であってはなりません。 また、Enumのバリアントはデータとして動的なサイズの型を持つ事はできません。</li> </ol> <!-- So why bother? Well, because `[T]` can only be used behind a pointer, if we --> <!-- didn’t have language support for unsized types, it would be impossible to write --> <!-- this: --> <p>なぜこんなにややこしいのでしょうか? これは、<code>[T]</code> はポインタを通してのみ操作可能であるため、もし言語がサイズ不定型をサポートしていなかった場合、以下のようなコードを書くことは不可能となります:</p> <span class='rusttest'>fn main() { impl Foo for str { }</span><pre class='rust rust-example-rendered'> <span class='kw'>impl</span> <span class='ident'>Foo</span> <span class='kw'>for</span> <span class='ident'>str</span> {</pre> <!-- or --> <p>また、以下の様なコードも:</p> <span class='rusttest'>fn main() { impl&lt;T&gt; Foo for [T] { }</span><pre class='rust rust-example-rendered'> <span class='kw'>impl</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> <span class='ident'>Foo</span> <span class='kw'>for</span> [<span class='ident'>T</span>] {</pre> <!-- Instead, you would have to write: --> <p>このように書く代わりに、以下のように書くことになるでしょう:</p> <span class='rusttest'>fn main() { impl Foo for &amp;str { }</span><pre class='rust rust-example-rendered'> <span class='kw'>impl</span> <span class='ident'>Foo</span> <span class='kw'>for</span> <span class='kw-2'>&amp;</span><span class='ident'>str</span> {</pre> <!-- Meaning, this implementation would only work for [references][ref], and not --> <!-- other types of pointers. With the `impl for str`, all pointers, including (at --> <!-- some point, there are some bugs to fix first) user-defined custom smart --> <!-- pointers, can use this `impl`. --> <p>このように書いたとすると、このコードは <a href="references-and-borrowing.html">参照</a> に対してのみ動作するようになり、他のポインタ型に対しては動作しないことになります。 <code>impl for str</code> のように書くことで、すべてのポインタ、ユーザーの定義した独自のスマートポインタ(いくつかの点についてバグがあるので、それをまずは直さなくてはなりませんが)もこの <code>impl</code> を利用可能になります。</p> <h1 id='sized' class='section-header'><a href='#sized'>?Sized</a></h1> <!-- If you want to write a function that accepts a dynamically sized type, you --> <!-- can use the special bound, `?Sized`: --> <p>もし動的サイズ型を引数に取れるような関数を定義したい場合、特別な境界 <code>?Sized</code> を利用できます:</p> <span class='rusttest'>fn main() { struct Foo&lt;T: ?Sized&gt; { f: T, } }</span><pre class='rust rust-example-rendered'> <span class='kw'>struct</span> <span class='ident'>Foo</span><span class='op'>&lt;</span><span class='ident'>T</span>: ?<span class='ident'>Sized</span><span class='op'>&gt;</span> { <span class='ident'>f</span>: <span class='ident'>T</span>, }</pre> <!-- This `?`, read as “T may be `Sized`”, means that this bound is special: it --> <!-- lets us match more kinds, not less. It’s almost like every `T` implicitly has --> <!-- `T: Sized`, and the `?` undoes this default. --> <p><code>?</code> は 「Tは <code>Sized</code> かもしれない」と読みます。 これは <code>?</code> が特別な境界であり、より小さいカインドとマッチするのではなく、より大きいカインドとマッチする ことを意味しています。 これは、すべての <code>T</code> は暗黙的に <code>T : Sized</code> という制限がかけられていて、 <code>?</code> はその制限を解除するようなものです。</p> <script type="text/javascript"> window.playgroundUrl = "https://play.rust-lang.org"; </script> <script src='rustbook.js'></script> <script src='playpen.js'></script> </div></div> </body> </html> <|start_filename|>docs/1.9/book/documentation.html<|end_filename|> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="generator" content="rustdoc"> <title>ドキュメント</title> <link rel="stylesheet" type="text/css" href="rustbook.css"> <meta name="robots" content="noindex"> </head> <body class="rustdoc"> <!--[if lte IE 8]> <div class="warning"> This old browser is unsupported and will most likely display funky things. </div> <![endif]--> <div id="nav"> <button id="toggle-nav"> <span class="sr-only">Toggle navigation</span> <span class="bar"></span> <span class="bar"></span> <span class="bar"></span> </button> </div> <div id='toc' class='mobile-hidden'> <ul class='chapter'> <li><a href='README.html'><b>1.</b> Introduction</a> </li> <li><a href='getting-started.html'><b>2.</b> はじめる</a> </li> <li><a href='guessing-game.html'><b>3.</b> チュートリアル:数当てゲーム</a> </li> <li><a href='syntax-and-semantics.html'><b>4.</b> シンタックスとセマンティクス</a> <ul class='section'> <li><a href='variable-bindings.html'><b>4.1.</b> 変数束縛</a> </li> <li><a href='functions.html'><b>4.2.</b> 関数</a> </li> <li><a href='primitive-types.html'><b>4.3.</b> プリミティブ型</a> </li> <li><a href='comments.html'><b>4.4.</b> コメント</a> </li> <li><a href='if.html'><b>4.5.</b> if</a> </li> <li><a href='loops.html'><b>4.6.</b> ループ</a> </li> <li><a href='vectors.html'><b>4.7.</b> ベクタ</a> </li> <li><a href='ownership.html'><b>4.8.</b> 所有権</a> </li> <li><a href='references-and-borrowing.html'><b>4.9.</b> 参照と借用</a> </li> <li><a href='lifetimes.html'><b>4.10.</b> ライフタイム</a> </li> <li><a href='mutability.html'><b>4.11.</b> ミュータビリティ</a> </li> <li><a href='structs.html'><b>4.12.</b> 構造体</a> </li> <li><a href='enums.html'><b>4.13.</b> 列挙型</a> </li> <li><a href='match.html'><b>4.14.</b> マッチ</a> </li> <li><a href='patterns.html'><b>4.15.</b> パターン</a> </li> <li><a href='method-syntax.html'><b>4.16.</b> メソッド構文</a> </li> <li><a href='strings.html'><b>4.17.</b> 文字列</a> </li> <li><a href='generics.html'><b>4.18.</b> ジェネリクス</a> </li> <li><a href='traits.html'><b>4.19.</b> トレイト</a> </li> <li><a href='drop.html'><b>4.20.</b> Drop</a> </li> <li><a href='if-let.html'><b>4.21.</b> if let</a> </li> <li><a href='trait-objects.html'><b>4.22.</b> トレイトオブジェクト</a> </li> <li><a href='closures.html'><b>4.23.</b> クロージャ</a> </li> <li><a href='ufcs.html'><b>4.24.</b> 共通の関数呼出構文</a> </li> <li><a href='crates-and-modules.html'><b>4.25.</b> クレートとモジュール</a> </li> <li><a href='const-and-static.html'><b>4.26.</b> `const` と `static`</a> </li> <li><a href='attributes.html'><b>4.27.</b> アトリビュート</a> </li> <li><a href='type-aliases.html'><b>4.28.</b> `type` エイリアス</a> </li> <li><a href='casting-between-types.html'><b>4.29.</b> 型間のキャスト</a> </li> <li><a href='associated-types.html'><b>4.30.</b> 関連型</a> </li> <li><a href='unsized-types.html'><b>4.31.</b> サイズ不定型</a> </li> <li><a href='operators-and-overloading.html'><b>4.32.</b> 演算子とオーバーロード</a> </li> <li><a href='deref-coercions.html'><b>4.33.</b> Derefによる型強制</a> </li> <li><a href='macros.html'><b>4.34.</b> マクロ</a> </li> <li><a href='raw-pointers.html'><b>4.35.</b> 生ポインタ</a> </li> <li><a href='unsafe.html'><b>4.36.</b> `unsafe`</a> </li> </ul> </li> <li><a href='effective-rust.html'><b>5.</b> Effective Rust</a> <ul class='section'> <li><a href='the-stack-and-the-heap.html'><b>5.1.</b> スタックとヒープ</a> </li> <li><a href='testing.html'><b>5.2.</b> テスト</a> </li> <li><a href='conditional-compilation.html'><b>5.3.</b> 条件付きコンパイル</a> </li> <li><a class='active' href='documentation.html'><b>5.4.</b> ドキュメント</a> </li> <li><a href='iterators.html'><b>5.5.</b> イテレータ</a> </li> <li><a href='concurrency.html'><b>5.6.</b> 並行性</a> </li> <li><a href='error-handling.html'><b>5.7.</b> エラーハンドリング</a> </li> <li><a href='choosing-your-guarantees.html'><b>5.8.</b> 保証を選ぶ</a> </li> <li><a href='ffi.html'><b>5.9.</b> 他言語関数インターフェース</a> </li> <li><a href='borrow-and-asref.html'><b>5.10.</b> BorrowとAsRef</a> </li> <li><a href='release-channels.html'><b>5.11.</b> リリースチャネル</a> </li> <li><a href='using-rust-without-the-standard-library.html'><b>5.12.</b> 標準ライブラリ無しでRustを使う</a> </li> </ul> </li> <li><a href='nightly-rust.html'><b>6.</b> Nightly Rust</a> <ul class='section'> <li><a href='compiler-plugins.html'><b>6.1.</b> コンパイラプラグイン</a> </li> <li><a href='inline-assembly.html'><b>6.2.</b> インラインアセンブリ</a> </li> <li><a href='no-stdlib.html'><b>6.3.</b> No stdlib</a> </li> <li><a href='intrinsics.html'><b>6.4.</b> Intrinsic</a> </li> <li><a href='lang-items.html'><b>6.5.</b> 言語アイテム</a> </li> <li><a href='advanced-linking.html'><b>6.6.</b> 高度なリンキング</a> </li> <li><a href='benchmark-tests.html'><b>6.7.</b> ベンチマークテスト</a> </li> <li><a href='box-syntax-and-patterns.html'><b>6.8.</b> Box構文とパターン</a> </li> <li><a href='slice-patterns.html'><b>6.9.</b> スライスパターン</a> </li> <li><a href='associated-constants.html'><b>6.10.</b> 関連定数</a> </li> <li><a href='custom-allocators.html'><b>6.11.</b> カスタムアロケータ</a> </li> </ul> </li> <li><a href='glossary.html'><b>7.</b> 用語集</a> </li> <li><a href='syntax-index.html'><b>8.</b> 構文の索引</a> </li> <li><a href='bibliography.html'><b>9.</b> 関係書目</a> </li> </ul> </div> <div id='page-wrapper'> <div id='page'> <blockquote class="header-caveat"> <p> <strong>注意: <a href="https://doc.rust-jp.rs/book-ja/">最新版のドキュメントをご覧ください。</a></strong>この第1版ドキュメントは古くなっており、最新情報が反映されていません。リンク先のドキュメントが現在の Rust の最新のドキュメントです。 </p> </blockquote> <h1 class="title">ドキュメント</h1> <!-- % Documentation --> <!-- Documentation is an important part of any software project, and it's --> <!-- first-class in Rust. Let's talk about the tooling Rust gives you to --> <!-- document your project. --> <p>ドキュメントはどんなソフトウェアプロジェクトにとっても重要な部分であり、Rustにおいてはファーストクラスです。 プロジェクトのドキュメントを作成するために、Rustが提供するツールについて話しましょう。</p> <!-- ## About `rustdoc` --> <h2 id='rustdoc-について' class='section-header'><a href='#rustdoc-について'><code>rustdoc</code> について</a></h2> <!-- The Rust distribution includes a tool, `rustdoc`, that generates documentation. --> <!-- `rustdoc` is also used by Cargo through `cargo doc`. --> <p>Rustの配布物には <code>rustdoc</code> というドキュメントを生成するツールが含まれています。 <code>rustdoc</code> は <code>cargo doc</code> によってCargoでも使われます。</p> <!-- Documentation can be generated in two ways: from source code, and from --> <!-- standalone Markdown files. --> <p>ドキュメントは2通りの方法で生成することができます。ソースコードから、そして単体のMarkdownファイルからです。</p> <!-- ## Documenting source code --> <h2 id='ソースコードのドキュメントの作成' class='section-header'><a href='#ソースコードのドキュメントの作成'>ソースコードのドキュメントの作成</a></h2> <!-- The primary way of documenting a Rust project is through annotating the source --> <!-- code. You can use documentation comments for this purpose: --> <p>Rustのプロジェクトでドキュメントを書く1つ目の方法は、ソースコードに注釈を付けることで行います。 ドキュメンテーションコメントはこの目的のために使うことができます。</p> <span class='rusttest'>fn main() { /// Constructs a new `Rc&lt;T&gt;`. /// 新しい`Rc&lt;T&gt;`の生成 /// /// # Examples /// /// ``` /// use std::rc::Rc; /// /// let five = Rc::new(5); /// ``` pub fn new(value: T) -&gt; Rc&lt;T&gt; { // implementation goes here // 実装が続く } }</span><pre class='rust rust-example-rendered'> <span class='doccomment'>/// 新しい`Rc&lt;T&gt;`の生成</span> <span class='doccomment'>///</span> <span class='doccomment'>/// # Examples</span> <span class='doccomment'>///</span> <span class='doccomment'>/// ```</span> <span class='doccomment'>/// use std::rc::Rc;</span> <span class='doccomment'>///</span> <span class='doccomment'>/// let five = Rc::new(5);</span> <span class='doccomment'>/// ```</span> <span class='kw'>pub</span> <span class='kw'>fn</span> <span class='ident'>new</span>(<span class='ident'>value</span>: <span class='ident'>T</span>) <span class='op'>-&gt;</span> <span class='ident'>Rc</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> { <span class='comment'>// 実装が続く</span> }</pre> <!-- This code generates documentation that looks [like this][rc-new]. I've left the --> <!-- implementation out, with a regular comment in its place. --> <p>このコードは<a href="https://doc.rust-lang.org/nightly/std/rc/struct.Rc.html#method.new">このような</a>見た目のドキュメントを生成します。 実装についてはそこにある普通のコメントのとおり、省略しています。</p> <!-- The first thing to notice about this annotation is that it uses --> <!-- `///` instead of `//`. The triple slash --> <!-- indicates a documentation comment. --> <p>この注釈について注意すべき1つ目のことは、 <code>//</code> の代わりに <code>///</code> が使われていることです。 3連スラッシュはドキュメンテーションコメントを示します。</p> <!-- Documentation comments are written in Markdown. --> <p>ドキュメンテーションコメントはMarkdownで書きます。</p> <!-- Rust keeps track of these comments, and uses them when generating --> <!-- documentation. This is important when documenting things like enums: --> <p>Rustはそれらのコメントを把握し、ドキュメントを生成するときにそれらを使います。 このことは次のように列挙型のようなもののドキュメントを作成するときに重要です。</p> <span class='rusttest'>fn main() { /// The `Option` type. See [the module level documentation](index.html) for more. /// `Option`型。詳細は[モジュールレベルドキュメント](index.html)を参照 enum Option&lt;T&gt; { /// No value /// 値なし None, /// Some value `T` /// `T`型の何らかの値 Some(T), } }</span><pre class='rust rust-example-rendered'> <span class='doccomment'>/// `Option`型。詳細は[モジュールレベルドキュメント](index.html)を参照</span> <span class='kw'>enum</span> <span class='prelude-ty'>Option</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> { <span class='doccomment'>/// 値なし</span> <span class='prelude-val'>None</span>, <span class='doccomment'>/// `T`型の何らかの値</span> <span class='prelude-val'>Some</span>(<span class='ident'>T</span>), }</pre> <!-- The above works, but this does not: --> <p>上記の例は動きますが、これは動きません。</p> <span class='rusttest'>fn main() { /// The `Option` type. See [the module level documentation](index.html) for more. /// `Option`型。詳細は[モジュールレベルドキュメント](index.html)を参照 enum Option&lt;T&gt; { /// None, /// No value None, /// 値なし /// Some(T), /// Some value `T` Some(T), /// `T`型の何らかの値 } }</span><pre class='rust rust-example-rendered'> <span class='doccomment'>/// `Option`型。詳細は[モジュールレベルドキュメント](index.html)を参照</span> <span class='kw'>enum</span> <span class='prelude-ty'>Option</span><span class='op'>&lt;</span><span class='ident'>T</span><span class='op'>&gt;</span> { <span class='prelude-val'>None</span>, <span class='doccomment'>/// 値なし</span> <span class='prelude-val'>Some</span>(<span class='ident'>T</span>), <span class='doccomment'>/// `T`型の何らかの値</span> }</pre> <!-- You'll get an error: --> <p>次のようにエラーが発生します。</p> <pre><code class="language-text">hello.rs:4:1: 4:2 error: expected ident, found `}` hello.rs:4 } ^ </code></pre> <!-- This [unfortunate error](https://github.com/rust-lang/rust/issues/22547) is --> <!-- correct; documentation comments apply to the thing after them, and there's --> <!-- nothing after that last comment. --> <p>この <a href="https://github.com/rust-lang/rust/issues/22547">残念なエラー</a> は正しいのです。ドキュメンテーションコメントはそれらの後のものに適用されるところ、その最後のコメントの後には何もないからです。</p> <!-- ### Writing documentation comments --> <h3 id='ドキュメンテーションコメントの記述' class='section-header'><a href='#ドキュメンテーションコメントの記述'>ドキュメンテーションコメントの記述</a></h3> <!-- Anyway, let's cover each part of this comment in detail: --> <p>とりあえず、このコメントの各部分を詳細にカバーしましょう。</p> <span class='rusttest'>fn main() { /// Constructs a new `Rc&lt;T&gt;`. /// 新しい`Rc&lt;T&gt;`の生成 fn foo() {} }</span><pre class='rust rust-example-rendered'> <span class='doccomment'>/// 新しい`Rc&lt;T&gt;`の生成</span></pre> <!-- The first line of a documentation comment should be a short summary of its --> <!-- functionality. One sentence. Just the basics. High level. --> <p>ドキュメンテーションコメントの最初の行は、その機能の短いサマリにすべきです。 一文で。 基本だけを。 高レベルから。</p> <span class='rusttest'>fn main() { /// /// Other details about constructing `Rc&lt;T&gt;`s, maybe describing complicated /// semantics, maybe additional options, all kinds of stuff. /// `Rc&lt;T&gt;`の生成についてのその他の詳細。例えば、複雑なセマンティクスの説明、 /// 追加のオプションなどあらゆる種類のもの /// fn foo() {} }</span><pre class='rust rust-example-rendered'> <span class='doccomment'>///</span> <span class='doccomment'>/// `Rc&lt;T&gt;`の生成についてのその他の詳細。例えば、複雑なセマンティクスの説明、</span> <span class='doccomment'>/// 追加のオプションなどあらゆる種類のもの</span> <span class='doccomment'>///</span></pre> <!-- Our original example had just a summary line, but if we had more things to say, --> <!-- we could have added more explanation in a new paragraph. --> <p>この例にはサマリしかありませんが、もしもっと書くべきことがあれば、新しい段落にもっと多くの説明を追加することができます。</p> <!-- #### Special sections --> <h4 id='特別なセクション' class='section-header'><a href='#特別なセクション'>特別なセクション</a></h4> <!-- Next, are special sections. These are indicated with a header, `#`. There --> <!-- are four kinds of headers that are commonly used. They aren't special syntax, --> <!-- just convention, for now. --> <p>次は特別なセクションです。 それらには <code>#</code> が付いていて、ヘッダであることを示しています。 一般的には、4種類のヘッダが使われます。 今のところそれらは特別な構文ではなく、単なる慣習です。</p> <span class='rusttest'>fn main() { /// # Panics fn foo() {} }</span><pre class='rust rust-example-rendered'> <span class='doccomment'>/// # Panics</span></pre> <!-- Unrecoverable misuses of a function (i.e. programming errors) in Rust are --> <!-- usually indicated by panics, which kill the whole current thread at the very --> <!-- least. If your function has a non-trivial contract like this, that is --> <!-- detected/enforced by panics, documenting it is very important. --> <p>Rustにおいて、関数の回復不可能な誤用(つまり、プログラミングエラー)は普通、パニックによって表現されます。パニックは、少なくとも現在のスレッド全体の息の根を止めてしまいます。 もし関数にこのような、パニックによって検出されたり強制されたりするような自明でない取決めがあるときには、ドキュメントを作成することは非常に重要です。</p> <span class='rusttest'>fn main() { /// # Errors fn foo() {} }</span><pre class='rust rust-example-rendered'> <span class='doccomment'>/// # Errors</span></pre> <!-- If your function or method returns a `Result<T, E>`, then describing the --> <!-- conditions under which it returns `Err(E)` is a nice thing to do. This is --> <!-- slightly less important than `Panics`, because failure is encoded into the type --> <!-- system, but it's still a good thing to do. --> <p>もし関数やメソッドが <code>Result&lt;T, E&gt;</code> を戻すのであれば、それが <code>Err(E)</code> を戻したときの状況をドキュメントで説明するのはよいことです。 これは <code>Panics</code> のときに比べると重要性は少し下です。失敗は型システムによってコード化されますが、それでもまだそうすることはよいことだからです。</p> <span class='rusttest'>fn main() { /// # Safety fn foo() {} }</span><pre class='rust rust-example-rendered'> <span class='doccomment'>/// # Safety</span></pre> <!-- If your function is `unsafe`, you should explain which invariants the caller is --> <!-- responsible for upholding. --> <p>もし関数が <code>unsafe</code> であれば、呼出元が動作を続けるためにはどの不変条件について責任を持つべきなのかを説明すべきです。</p> <span class='rusttest'>fn main() { /// # Examples /// /// ``` /// use std::rc::Rc; /// /// let five = Rc::new(5); /// ``` fn foo() {} }</span><pre class='rust rust-example-rendered'> <span class='doccomment'>/// # Examples</span> <span class='doccomment'>///</span> <span class='doccomment'>/// ```</span> <span class='doccomment'>/// use std::rc::Rc;</span> <span class='doccomment'>///</span> <span class='doccomment'>/// let five = Rc::new(5);</span> <span class='doccomment'>/// ```</span></pre> <!-- Fourth, `Examples`. Include one or more examples of using your function or --> <!-- method, and your users will love you for it. These examples go inside of --> <!-- code block annotations, which we'll talk about in a moment, and can have --> <!-- more than one section: --> <p>4つ目は <code>Examples</code> です。 関数やメソッドの使い方の例を1つ以上含めてください。そうすればユーザから愛されることでしょう。 それらの例はコードブロック注釈内に入れます。コードブロック注釈についてはすぐ後で話しますが、それらは1つ以上のセクションを持つことができます。</p> <span class='rusttest'>fn main() { /// # Examples /// /// Simple `&amp;str` patterns: /// 単純な`&amp;str`パターン /// /// ``` /// let v: Vec&lt;&amp;str&gt; = &quot;Mary had a little lamb&quot;.split(&#39; &#39;).collect(); /// assert_eq!(v, vec![&quot;Mary&quot;, &quot;had&quot;, &quot;a&quot;, &quot;little&quot;, &quot;lamb&quot;]); /// ``` /// /// More complex patterns with a lambda: /// ラムダを使ったもっと複雑なパターン /// /// ``` /// let v: Vec&lt;&amp;str&gt; = &quot;abc1def2ghi&quot;.split(|c: char| c.is_numeric()).collect(); /// assert_eq!(v, vec![&quot;abc&quot;, &quot;def&quot;, &quot;ghi&quot;]); /// ``` fn foo() {} }</span><pre class='rust rust-example-rendered'> <span class='doccomment'>/// # Examples</span> <span class='doccomment'>///</span> <span class='doccomment'>/// 単純な`&amp;str`パターン</span> <span class='doccomment'>///</span> <span class='doccomment'>/// ```</span> <span class='doccomment'>/// let v: Vec&lt;&amp;str&gt; = &quot;Mary had a little lamb&quot;.split(&#39; &#39;).collect();</span> <span class='doccomment'>/// assert_eq!(v, vec![&quot;Mary&quot;, &quot;had&quot;, &quot;a&quot;, &quot;little&quot;, &quot;lamb&quot;]);</span> <span class='doccomment'>/// ```</span> <span class='doccomment'>///</span> <span class='doccomment'>/// ラムダを使ったもっと複雑なパターン</span> <span class='doccomment'>///</span> <span class='doccomment'>/// ```</span> <span class='doccomment'>/// let v: Vec&lt;&amp;str&gt; = &quot;abc1def2ghi&quot;.split(|c: char| c.is_numeric()).collect();</span> <span class='doccomment'>/// assert_eq!(v, vec![&quot;abc&quot;, &quot;def&quot;, &quot;ghi&quot;]);</span> <span class='doccomment'>/// ```</span></pre> <!-- Let's discuss the details of these code blocks. --> <p>それらのコードブロックの詳細について議論しましょう。</p> <!-- #### Code block annotations --> <h4 id='コードブロック注釈' class='section-header'><a href='#コードブロック注釈'>コードブロック注釈</a></h4> <!-- To write some Rust code in a comment, use the triple graves: --> <p>コメント内にRustのコードを書くためには、3連バッククオートを使います。</p> <span class='rusttest'>fn main() { /// ``` /// println!(&quot;Hello, world&quot;); /// ``` fn foo() {} }</span><pre class='rust rust-example-rendered'> <span class='doccomment'>/// ```</span> <span class='doccomment'>/// println!(&quot;Hello, world&quot;);</span> <span class='doccomment'>/// ```</span></pre> <!-- If you want something that's not Rust code, you can add an annotation: --> <p>もしRustのコードではないものを書きたいのであれば、注釈を追加することができます。</p> <span class='rusttest'>fn main() { /// ```c /// printf(&quot;Hello, world\n&quot;); /// ``` fn foo() {} }</span><pre class='rust rust-example-rendered'> <span class='doccomment'>/// ```c</span> <span class='doccomment'>/// printf(&quot;Hello, world\n&quot;);</span> <span class='doccomment'>/// ```</span></pre> <!-- This will highlight according to whatever language you're showing off. --> <!-- If you're only showing plain text, choose `text`. --> <p>これは、使われている言語が何であるかに応じてハイライトされます。 もし単なるプレーンテキストを書いているのであれば、 <code>text</code> を選択してください。</p> <!-- It's important to choose the correct annotation here, because `rustdoc` uses it --> <!-- in an interesting way: It can be used to actually test your examples in a --> <!-- library crate, so that they don't get out of date. If you have some C code but --> <!-- `rustdoc` thinks it's Rust because you left off the annotation, `rustdoc` will --> <!-- complain when trying to generate the documentation. --> <p>ここでは正しい注釈を選ぶことが重要です。なぜなら、 <code>rustdoc</code> はそれを興味深い方法で使うからです。それらが実際のコードと不整合を起こさないように、ライブラリクレート内で実際にあなたの例をテストするために使うのです。 もし例の中にCのコードが含まれているのに、あなたが注釈を付けるのを忘れてしまい、 <code>rustdoc</code> がそれをRustのコードだと考えてしまえば、 <code>rustdoc</code> はドキュメントを生成しようとするときに怒るでしょう。</p> <!-- ## Documentation as tests --> <h2 id='テストとしてのドキュメント' class='section-header'><a href='#テストとしてのドキュメント'>テストとしてのドキュメント</a></h2> <!-- Let's discuss our sample example documentation: --> <p>次のようなドキュメントにおける例について議論しましょう。</p> <span class='rusttest'>fn main() { /// ``` /// println!(&quot;Hello, world&quot;); /// ``` fn foo() {} }</span><pre class='rust rust-example-rendered'> <span class='doccomment'>/// ```</span> <span class='doccomment'>/// println!(&quot;Hello, world&quot;);</span> <span class='doccomment'>/// ```</span></pre> <!-- You'll notice that you don't need a `fn main()` or anything here. `rustdoc` will --> <!-- automatically add a `main()` wrapper around your code, using heuristics to attempt --> <!-- to put it in the right place. For example: --> <p><code>fn main()</code> とかがここでは不要だということに気が付くでしょう。 <code>rustdoc</code> は自動的に <code>main()</code> ラッパをコードの周りに、正しい場所へ配置するためのヒューリスティクスを使って追加します。 例えば、こうです。</p> <span class='rusttest'>fn main() { /// ``` /// use std::rc::Rc; /// /// let five = Rc::new(5); /// ``` fn foo() {} }</span><pre class='rust rust-example-rendered'> <span class='doccomment'>/// ```</span> <span class='doccomment'>/// use std::rc::Rc;</span> <span class='doccomment'>///</span> <span class='doccomment'>/// let five = Rc::new(5);</span> <span class='doccomment'>/// ```</span></pre> <!-- This will end up testing: --> <p>これが、テストのときには結局こうなります。</p> <span class='rusttest'>fn main() { use std::rc::Rc; let five = Rc::new(5); } </span><pre class='rust rust-example-rendered'> <span class='kw'>fn</span> <span class='ident'>main</span>() { <span class='kw'>use</span> <span class='ident'>std</span>::<span class='ident'>rc</span>::<span class='ident'>Rc</span>; <span class='kw'>let</span> <span class='ident'>five</span> <span class='op'>=</span> <span class='ident'>Rc</span>::<span class='ident'>new</span>(<span class='number'>5</span>); }</pre> <!-- Here's the full algorithm rustdoc uses to preprocess examples: --> <p>これがrustdocが例の前処理に使うアルゴリズムの全てです。</p> <!-- 1. Any leading `#![foo]` attributes are left intact as crate attributes. --> <!-- 2. Some common `allow` attributes are inserted, including --> <!-- `unused_variables`, `unused_assignments`, `unused_mut`, --> <!-- `unused_attributes`, and `dead_code`. Small examples often trigger --> <!-- these lints. --> <!-- 3. If the example does not contain `extern crate`, then `extern crate --> <!-- <mycrate>;` is inserted (note the lack of `#[macro_use]`). --> <!-- 4. Finally, if the example does not contain `fn main`, the remainder of the --> <!-- text is wrapped in `fn main() { your_code }`. --> <ol> <li>前の方にある全ての <code>#![foo]</code> アトリビュートは、そのままクレートのアトリビュートとして置いておく</li> <li><code>unused_variables</code> 、 <code>unused_assignments</code> 、 <code>unused_mut</code> 、 <code>unused_attributes</code> 、 <code>dead_code</code> などのいくつかの一般的な <code>allow</code> アトリビュートを追加する。 小さな例はしばしばこれらのリントに引っ掛かる</li> <li>もしその例が <code>extern crate</code> を含んでいなければ、 <code>extern crate &lt;mycrate&gt;;</code> を挿入する( <code>#[macro_use]</code> がないことに注意する)</li> <li>最後に、もし例が <code>fn main</code> を含んでいなければ、テキストの残りの部分を <code>fn main() { your_code }</code> で囲む</li> </ol> <!-- This generated `fn main` can be a problem! If you have `extern crate` or a `mod` --> <!-- statements in the example code that are referred to by `use` statements, they will --> <!-- fail to resolve unless you include at least `fn main() {}` to inhibit step 4. --> <!-- `#[macro_use] extern crate` also does not work except at the crate root, so when --> <!-- testing macros an explicit `main` is always required. It doesn't have to clutter --> <!-- up your docs, though -- keep reading! --> <p>こうして生成された <code>fn main</code> は問題になり得ます! もし <code>use</code> 文によって参照される例のコードに <code>extern crate</code> 文や <code>mod</code> 文が入っていれば、それらはステップ4を抑制するために少なくとも <code>fn main() {}</code> を含んでいない限り失敗します。 <code>#[macro_use] extern crate</code> も同様に、クレートのルート以外では動作しません。そのため、マクロのテストには明示的な <code>main</code> が常に必要なのです。 しかし、ドキュメントを散らかす必要はありません……続きを読みましょう!</p> <!-- Sometimes this algorithm isn't enough, though. For example, all of these code samples --> <!-- with `///` we've been talking about? The raw text: --> <p>しかし、これでは不十分なことがときどきあります。 例えば、今まで話してきた全ての <code>///</code> の付いたコード例はどうだったでしょうか。 生のテキストはこうなっています。</p> <pre><code class="language-text">/// 何らかのドキュメント # fn foo() {} </code></pre> <!-- looks different than the output: --> <p>それは出力とは違って見えます。</p> <span class='rusttest'>fn main() { /// Some documentation. /// 何らかのドキュメント fn foo() {} }</span><pre class='rust rust-example-rendered'> <span class='doccomment'>/// 何らかのドキュメント</span></pre> <!-- Yes, that's right: you can add lines that start with `# `, and they will --> <!-- be hidden from the output, but will be used when compiling your code. You --> <!-- can use this to your advantage. In this case, documentation comments need --> <!-- to apply to some kind of function, so if I want to show you just a --> <!-- documentation comment, I need to add a little function definition below --> <!-- it. At the same time, it's only there to satisfy the compiler, so hiding --> <!-- it makes the example more clear. You can use this technique to explain --> <!-- longer examples in detail, while still preserving the testability of your --> <!-- documentation. --> <p>そうです。正解です。 <code>#</code> で始まる行を追加することで、コードをコンパイルするときには使われるけれども、出力はされないというようにすることができます。 これは都合のよいように使うことができます。 この場合、ドキュメンテーションコメントそのものを見せたいので、ドキュメンテーションコメントを何らかの関数に適用する必要があります。そのため、その後に小さい関数定義を追加する必要があります。 同時に、それは単にコンパイラを満足させるためだけのものなので、それを隠すことで、例がすっきりするのです。 長い例を詳細に説明する一方、テスト可能性を維持するためにこのテクニックを使うことができます。</p> <!-- For example, imagine that we wanted to document this code: --> <p>例えば、このコードをドキュメントに書きたいとします。</p> <span class='rusttest'>fn main() { let x = 5; let y = 6; println!(&quot;{}&quot;, x + y); }</span><pre class='rust rust-example-rendered'> <span class='kw'>let</span> <span class='ident'>x</span> <span class='op'>=</span> <span class='number'>5</span>; <span class='kw'>let</span> <span class='ident'>y</span> <span class='op'>=</span> <span class='number'>6</span>; <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;{}&quot;</span>, <span class='ident'>x</span> <span class='op'>+</span> <span class='ident'>y</span>);</pre> <!-- We might want the documentation to end up looking like this: --> <p>最終的にはこのように見えるドキュメントが欲しいのかもしれません。</p> <!-- > First, we set `x` to five: --> <blockquote> <p>まず、<code>x</code>に5をセットする</p> <span class='rusttest'>fn main() { let x = 5; let y = 6; println!(&quot;{}&quot;, x + y); }</span><pre class='rust rust-example-rendered'> <span class='kw'>let</span> <span class='ident'>x</span> <span class='op'>=</span> <span class='number'>5</span>;</pre> <!-- > Next, we set `y` to six: --> <p>次に、<code>y</code>に6をセットする</p> <span class='rusttest'>fn main() { let x = 5; let y = 6; println!(&quot;{}&quot;, x + y); }</span><pre class='rust rust-example-rendered'> <span class='kw'>let</span> <span class='ident'>y</span> <span class='op'>=</span> <span class='number'>6</span>;</pre> <!-- > Finally, we print the sum of `x` and `y`: --> <p>最後に、<code>x</code>と<code>y</code>との合計を出力する</p> <span class='rusttest'>fn main() { let x = 5; let y = 6; println!(&quot;{}&quot;, x + y); }</span><pre class='rust rust-example-rendered'> <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;{}&quot;</span>, <span class='ident'>x</span> <span class='op'>+</span> <span class='ident'>y</span>);</pre> </blockquote> <!-- To keep each code block testable, we want the whole program in each block, but --> <!-- we don't want the reader to see every line every time. Here's what we put in --> <!-- our source code: --> <p>各コードブロックをテスト可能な状態にしておくために、各ブロックにはプログラム全体が必要です。しかし、読者には全ての行を毎回見せたくはありません。 ソースコードに挿入するものはこれです。</p> <pre><code class="language-text"> まず、`x`に5をセットする ```rust let x = 5; # let y = 6; # println!(&quot;{}&quot;, x + y); ``` 次に、`y`に6をセットする ```rust # let x = 5; let y = 6; # println!(&quot;{}&quot;, x + y); ``` 最後に、`x`と`y`との合計を出力する ```rust # let x = 5; # let y = 6; println!(&quot;{}&quot;, x + y); ``` </code></pre> <!-- By repeating all parts of the example, you can ensure that your example still --> <!-- compiles, while only showing the parts that are relevant to that part of your --> <!-- explanation. --> <p>例の全体を繰り返すことで、例がちゃんとコンパイルされることを保証する一方、説明に関係する部分だけを見せることができます。</p> <!-- ### Documenting macros --> <h3 id='マクロのドキュメントの作成' class='section-header'><a href='#マクロのドキュメントの作成'>マクロのドキュメントの作成</a></h3> <!-- Here’s an example of documenting a macro: --> <p>これはマクロのドキュメントの例です。</p> <span class='rusttest'>/// Panic with a given message unless an expression evaluates to true. /// 式がtrueと評価されない限り、与えられたメッセージとともにパニックする /// /// # Examples /// /// ``` /// # #[macro_use] extern crate foo; /// # fn main() { /// panic_unless!(1 + 1 == 2, “Math is broken.”); /// # } /// ``` /// /// ```should_panic /// # #[macro_use] extern crate foo; /// # fn main() { /// panic_unless!(true == false, “I’m broken.”); /// # } /// ``` #[macro_export] macro_rules! panic_unless { ($condition:expr, $($rest:expr),+) =&gt; ({ if ! $condition { panic!($($rest),+); } }); } fn main() {} </span><pre class='rust rust-example-rendered'> <span class='doccomment'>/// 式がtrueと評価されない限り、与えられたメッセージとともにパニックする</span> <span class='doccomment'>///</span> <span class='doccomment'>/// # Examples</span> <span class='doccomment'>///</span> <span class='doccomment'>/// ```</span> <span class='doccomment'>/// # #[macro_use] extern crate foo;</span> <span class='doccomment'>/// # fn main() {</span> <span class='doccomment'>/// panic_unless!(1 + 1 == 2, “Math is broken.”);</span> <span class='doccomment'>/// # }</span> <span class='doccomment'>/// ```</span> <span class='doccomment'>///</span> <span class='doccomment'>/// ```should_panic</span> <span class='doccomment'>/// # #[macro_use] extern crate foo;</span> <span class='doccomment'>/// # fn main() {</span> <span class='doccomment'>/// panic_unless!(true == false, “I’m broken.”);</span> <span class='doccomment'>/// # }</span> <span class='doccomment'>/// ```</span> <span class='attribute'>#[<span class='ident'>macro_export</span>]</span> <span class='macro'>macro_rules</span><span class='macro'>!</span> <span class='ident'>panic_unless</span> { (<span class='macro-nonterminal'>$</span><span class='macro-nonterminal'>condition</span>:<span class='ident'>expr</span>, $(<span class='macro-nonterminal'>$</span><span class='macro-nonterminal'>rest</span>:<span class='ident'>expr</span>),<span class='op'>+</span>) <span class='op'>=&gt;</span> ({ <span class='kw'>if</span> <span class='op'>!</span> <span class='macro-nonterminal'>$</span><span class='macro-nonterminal'>condition</span> { <span class='macro'>panic</span><span class='macro'>!</span>($(<span class='macro-nonterminal'>$</span><span class='macro-nonterminal'>rest</span>),<span class='op'>+</span>); } }); }</pre> <!-- You’ll note three things: we need to add our own `extern crate` line, so that --> <!-- we can add the `#[macro_use]` attribute. Second, we’ll need to add our own --> <!-- `main()` as well (for reasons discussed above). Finally, a judicious use of --> <!-- `#` to comment out those two things, so they don’t show up in the output. --> <p>3つのことに気が付くでしょう。 <code>#[macro_use]</code> アトリビュートを追加するために、自分で <code>extern crate</code> 行を追加しなければなりません。 2つ目に、 <code>main()</code> も自分で追加する必要があります(理由は前述しました)。 最後に、それらの2つが出力されないようにコメントアウトするという <code>#</code> の賢い使い方です。</p> <!-- Another case where the use of `#` is handy is when you want to ignore --> <!-- error handling. Lets say you want the following, --> <p><code>#</code> の使うと便利な場所のもう1つのケースは、エラーハンドリングを無視したいときです。 次のようにしたいとしましょう。</p> <span class='rusttest'>fn main() { /// use std::io; /// let mut input = String::new(); /// try!(io::stdin().read_line(&amp;mut input)); }</span><pre class='rust rust-example-rendered'> <span class='doccomment'>/// use std::io;</span> <span class='doccomment'>/// let mut input = String::new();</span> <span class='doccomment'>/// try!(io::stdin().read_line(&amp;mut input));</span></pre> <!-- The problem is that `try!` returns a `Result<T, E>` and test functions --> <!-- don't return anything so this will give a mismatched types error. --> <p>問題は <code>try!</code> が <code>Result&lt;T, E&gt;</code> を返すところ、テスト関数は何も返さないことで、これは型のミスマッチエラーを起こします。</p> <span class='rusttest'>fn main() { /// A doc test using try! /// try!を使ったドキュメンテーションテスト /// /// ``` /// use std::io; /// # fn foo() -&gt; io::Result&lt;()&gt; { /// let mut input = String::new(); /// try!(io::stdin().read_line(&amp;mut input)); /// # Ok(()) /// # } /// ``` fn foo() {} }</span><pre class='rust rust-example-rendered'> <span class='doccomment'>/// try!を使ったドキュメンテーションテスト</span> <span class='doccomment'>///</span> <span class='doccomment'>/// ```</span> <span class='doccomment'>/// use std::io;</span> <span class='doccomment'>/// # fn foo() -&gt; io::Result&lt;()&gt; {</span> <span class='doccomment'>/// let mut input = String::new();</span> <span class='doccomment'>/// try!(io::stdin().read_line(&amp;mut input));</span> <span class='doccomment'>/// # Ok(())</span> <span class='doccomment'>/// # }</span> <span class='doccomment'>/// ```</span></pre> <!-- You can get around this by wrapping the code in a function. This catches --> <!-- and swallows the `Result<T, E>` when running tests on the docs. This --> <!-- pattern appears regularly in the standard library. --> <p>これは関数内のコードをラッピングすることで回避できます。 これはドキュメント上のテストが実行されるときに <code>Result&lt;T, E&gt;</code> を捕まえて飲み込みます。 このパターンは標準ライブラリ内でよく現れます。</p> <!-- ### Running documentation tests --> <h3 id='ドキュメンテーションテストの実行' class='section-header'><a href='#ドキュメンテーションテストの実行'>ドキュメンテーションテストの実行</a></h3> <!-- To run the tests, either: --> <p>テストを実行するには、次のどちらかを使います。</p> <pre><code class="language-bash">$ rustdoc --test path/to/my/crate/root.rs # or $ cargo test </code></pre> <!-- That's right, `cargo test` tests embedded documentation too. **However, --> <!-- `cargo test` will not test binary crates, only library ones.** This is --> <!-- due to the way `rustdoc` works: it links against the library to be tested, --> <!-- but with a binary, there’s nothing to link to. --> <p>正解です。 <code>cargo test</code> は組み込まれたドキュメントもテストします。 <strong>しかし、<code>cargo test</code>がテストするのはライブラリクレートだけで、バイナリクレートはテストしません。</strong> これは <code>rustdoc</code> の動き方によるものです。それはテストするためにライブラリをリンクしますが、バイナリには何もリンクするものがないからです。</p> <!-- There are a few more annotations that are useful to help `rustdoc` do the right --> <!-- thing when testing your code: --> <p><code>rustdoc</code> がコードをテストするときに正しく動作するのを助けるために便利な注釈があと少しあります。</p> <span class='rusttest'>fn main() { /// ```ignore /// fn foo() { /// ``` fn foo() {} }</span><pre class='rust rust-example-rendered'> <span class='doccomment'>/// ```ignore</span> <span class='doccomment'>/// fn foo() {</span> <span class='doccomment'>/// ```</span></pre> <!-- The `ignore` directive tells Rust to ignore your code. This is almost never --> <!-- what you want, as it's the most generic. Instead, consider annotating it --> <!-- with `text` if it's not code, or using `#`s to get a working example that --> <!-- only shows the part you care about. --> <p><code>ignore</code> ディレクティブはRustにコードを無視するよう指示します。 これはあまりに汎用的なので、必要になることはほとんどありません。 もしそれがコードではなければ、代わりに <code>text</code> の注釈を付けること、又は問題となる部分だけが表示された、動作する例を作るために <code>#</code> を使うことを検討してください。</p> <span class='rusttest'>fn main() { /// ```should_panic /// assert!(false); /// ``` fn foo() {} }</span><pre class='rust rust-example-rendered'> <span class='doccomment'>/// ```should_panic</span> <span class='doccomment'>/// assert!(false);</span> <span class='doccomment'>/// ```</span></pre> <!-- `should_panic` tells `rustdoc` that the code should compile correctly, but --> <!-- not actually pass as a test. --> <p><code>should_panic</code> は、そのコードは正しくコンパイルされるべきではあるが、実際にテストとして成功する必要まではないということを <code>rustdoc</code> に教えます。</p> <span class='rusttest'>fn main() { /// ```no_run /// loop { /// println!(&quot;Hello, world&quot;); /// } /// ``` fn foo() {} }</span><pre class='rust rust-example-rendered'> <span class='doccomment'>/// ```no_run</span> <span class='doccomment'>/// loop {</span> <span class='doccomment'>/// println!(&quot;Hello, world&quot;);</span> <span class='doccomment'>/// }</span> <span class='doccomment'>/// ```</span></pre> <!-- The `no_run` attribute will compile your code, but not run it. This is --> <!-- important for examples such as "Here's how to start up a network service," --> <!-- which you would want to make sure compile, but might run in an infinite loop! --> <p><code>no_run</code> アトリビュートはコードをコンパイルしますが、実行はしません。 これは「これはネットワークサービスを開始する方法です」というような例や、コンパイルされることは保証したいけれども、無限ループになってしまうような例にとって重要です!</p> <!-- ### Documenting modules --> <h3 id='モジュールのドキュメントの作成' class='section-header'><a href='#モジュールのドキュメントの作成'>モジュールのドキュメントの作成</a></h3> <!-- Rust has another kind of doc comment, `//!`. This comment doesn't document the next item, but the enclosing item. In other words: --> <p>Rustには別の種類のドキュメンテーションコメント、 <code>//!</code> があります。 このコメントは次に続く要素のドキュメントではなく、それを囲っている要素のドキュメントです。 言い換えると、こうです。</p> <span class='rusttest'>fn main() { mod foo { //! This is documentation for the `foo` module. //! これは`foo`モジュールのドキュメントである //! //! # Examples // ... } }</span><pre class='rust rust-example-rendered'> <span class='kw'>mod</span> <span class='ident'>foo</span> { <span class='doccomment'>//! これは`foo`モジュールのドキュメントである</span> <span class='doccomment'>//!</span> <span class='doccomment'>//! # Examples</span> <span class='comment'>// ...</span> }</pre> <!-- This is where you'll see `//!` used most often: for module documentation. If --> <!-- you have a module in `foo.rs`, you'll often open its code and see this: --> <p><code>//!</code> を頻繁に見る場所がここ、モジュールドキュメントです。 もし <code>foo.rs</code> 内にモジュールを持っていれば、しばしばそのコードを開くとこれを見るでしょう。</p> <span class='rusttest'>fn main() { //! A module for using `foo`s. //! `foo`で使われるモジュール //! //! The `foo` module contains a lot of useful functionality blah blah blah //! `foo`モジュールに含まれているたくさんの便利な関数などなど }</span><pre class='rust rust-example-rendered'> <span class='doccomment'>//! `foo`で使われるモジュール</span> <span class='doccomment'>//!</span> <span class='doccomment'>//! `foo`モジュールに含まれているたくさんの便利な関数などなど</span></pre> <!-- ### Documentation comment style --> <h3 id='ドキュメンテーションコメントのスタイル' class='section-header'><a href='#ドキュメンテーションコメントのスタイル'>ドキュメンテーションコメントのスタイル</a></h3> <!-- Check out [RFC 505][rfc505] for full conventions around the style and format of --> <!-- documentation. --> <p>ドキュメントのスタイルや書式についての全ての慣習を知るには <a href="https://github.com/rust-lang/rfcs/blob/master/text/0505-api-comment-conventions.md">RFC 505</a> をチェックしてください。</p> <!-- ## Other documentation --> <h2 id='その他のドキュメント' class='section-header'><a href='#その他のドキュメント'>その他のドキュメント</a></h2> <!-- All of this behavior works in non-Rust source files too. Because comments --> <!-- are written in Markdown, they're often `.md` files. --> <p>ここにある振舞いは全て、Rust以外のソースコードファイルでも働きます。 コメントはMarkdownで書かれるので、しばしば <code>.md</code> ファイルになります。</p> <!-- When you write documentation in Markdown files, you don't need to prefix --> <!-- the documentation with comments. For example: --> <p>ドキュメントをMarkdownファイルに書くとき、ドキュメントにコメントのプレフィックスを付ける必要はありません。 例えば、こうする必要はありません。</p> <span class='rusttest'>fn main() { /// # Examples /// /// ``` /// use std::rc::Rc; /// /// let five = Rc::new(5); /// ``` fn foo() {} }</span><pre class='rust rust-example-rendered'> <span class='doccomment'>/// # Examples</span> <span class='doccomment'>///</span> <span class='doccomment'>/// ```</span> <span class='doccomment'>/// use std::rc::Rc;</span> <span class='doccomment'>///</span> <span class='doccomment'>/// let five = Rc::new(5);</span> <span class='doccomment'>/// ```</span></pre> <!-- is --> <p>これは、こうします。</p> <pre><code class="language-markdown"># Examples ``` use std::rc::Rc; let five = Rc::new(5); ``` </code></pre> <!-- when it's in a Markdown file. There is one wrinkle though: Markdown files need --> <!-- to have a title like this: --> <p>Markdownファイルの中ではこうします。 ただし、1つだけ新しいものがあります。Markdownファイルではこのように題名を付けなければなりません。</p> <pre><code class="language-markdown"># % The title % タイトル # This is the example documentation. これはサンプルのドキュメントです。 </code></pre> <!-- This `%` line needs to be the very first line of the file. --> <p>この <code>%</code> 行はそのファイルの一番先頭の行に書く必要があります。</p> <!-- ## `doc` attributes --> <h2 id='doc-アトリビュート' class='section-header'><a href='#doc-アトリビュート'><code>doc</code> アトリビュート</a></h2> <!-- At a deeper level, documentation comments are syntactic sugar for documentation --> <!-- attributes: --> <p>もっと深いレベルで言えは、ドキュメンテーションコメントはドキュメントアトリビュートの糖衣構文です。</p> <span class='rusttest'>fn main() { /// this fn foo() {} #[doc=&quot;this&quot;] fn bar() {} }</span><pre class='rust rust-example-rendered'> <span class='doccomment'>/// this</span> <span class='attribute'>#[<span class='ident'>doc</span><span class='op'>=</span><span class='string'>&quot;this&quot;</span>]</span></pre> <!-- are the same, as are these: --> <p>これらは同じもので、次のものも同じものです。</p> <span class='rusttest'>fn main() { //! this #![doc=&quot;this&quot;] }</span><pre class='rust rust-example-rendered'> <span class='doccomment'>//! this</span> <span class='attribute'>#<span class='op'>!</span>[<span class='ident'>doc</span><span class='op'>=</span><span class='string'>&quot;this&quot;</span>]</span></pre> <!-- You won't often see this attribute used for writing documentation, but it --> <!-- can be useful when changing some options, or when writing a macro. --> <p>このアトリビュートがドキュメントを書くために使われているのを見ることはそんなにないでしょう。しかし、これは何らかのオプションを変更したり、マクロを書いたりするときに便利です。</p> <!-- ### Re-exports --> <h3 id='再エクスポート' class='section-header'><a href='#再エクスポート'>再エクスポート</a></h3> <!-- `rustdoc` will show the documentation for a public re-export in both places: --> <p><code>rustdoc</code> はパブリックな再エクスポートがなされた場合に、両方の場所にドキュメントを表示します。</p> <span class='rusttest'>fn main() { extern crate foo; pub use foo::bar; }</span><pre class='rust rust-example-rendered'> <span class='kw'>extern</span> <span class='kw'>crate</span> <span class='ident'>foo</span>; <span class='kw'>pub</span> <span class='kw'>use</span> <span class='ident'>foo</span>::<span class='ident'>bar</span>;</pre> <!-- This will create documentation for `bar` both inside the documentation for the --> <!-- crate `foo`, as well as the documentation for your crate. It will use the same --> <!-- documentation in both places. --> <p>これは <code>bar</code> のドキュメントをクレートのドキュメントの中に生成するのと同様に、 <code>foo</code> クレートのドキュメントの中にも生成します。 同じドキュメントが両方の場所で使われます。</p> <!-- This behavior can be suppressed with `no_inline`: --> <p>この振舞いは <code>no_inline</code> で抑制することができます。</p> <span class='rusttest'>fn main() { extern crate foo; #[doc(no_inline)] pub use foo::bar; }</span><pre class='rust rust-example-rendered'> <span class='kw'>extern</span> <span class='kw'>crate</span> <span class='ident'>foo</span>; <span class='attribute'>#[<span class='ident'>doc</span>(<span class='ident'>no_inline</span>)]</span> <span class='kw'>pub</span> <span class='kw'>use</span> <span class='ident'>foo</span>::<span class='ident'>bar</span>;</pre> <!-- ## Missing documentation --> <h2 id='ドキュメントの不存在' class='section-header'><a href='#ドキュメントの不存在'>ドキュメントの不存在</a></h2> <!-- Sometimes you want to make sure that every single public thing in your project --> <!-- is documented, especially when you are working on a library. Rust allows you to --> <!-- to generate warnings or errors, when an item is missing documentation. --> <!-- To generate warnings you use `warn`: --> <p>ときどき、プロジェクト内の公開されている全てのものについて、ドキュメントが作成されていることを確認したいことがあります。これは特にライブラリについて作業をしているときにあります。 Rustでは、要素にドキュメントがないときに警告やエラーを生成することができます。 警告を生成するためには、 <code>warn</code> を使います。</p> <span class='rusttest'>fn main() { #![warn(missing_docs)] }</span><pre class='rust rust-example-rendered'> <span class='attribute'>#<span class='op'>!</span>[<span class='ident'>warn</span>(<span class='ident'>missing_docs</span>)]</span></pre> <!-- And to generate errors you use `deny`: --> <p>そしてエラーを生成するとき、 <code>deny</code> を使います。</p> <span class='rusttest'>fn main() { #![deny(missing_docs)] }</span><pre class='rust rust-example-rendered'> <span class='attribute'>#<span class='op'>!</span>[<span class='ident'>deny</span>(<span class='ident'>missing_docs</span>)]</span></pre> <!-- There are cases where you want to disable these warnings/errors to explicitly --> <!-- leave something undocumented. This is done by using `allow`: --> <p>何かを明示的にドキュメント化されていないままにするため、それらの警告やエラーを無効にしたい場合があります。 これは <code>allow</code> を使えば可能です。</p> <span class='rusttest'>fn main() { #[allow(missing_docs)] struct Undocumented; }</span><pre class='rust rust-example-rendered'> <span class='attribute'>#[<span class='ident'>allow</span>(<span class='ident'>missing_docs</span>)]</span> <span class='kw'>struct</span> <span class='ident'>Undocumented</span>;</pre> <!-- You might even want to hide items from the documentation completely: --> <p>ドキュメントから要素を完全に見えなくしたいこともあるかもしれません。</p> <span class='rusttest'>fn main() { #[doc(hidden)] struct Hidden; }</span><pre class='rust rust-example-rendered'> <span class='attribute'>#[<span class='ident'>doc</span>(<span class='ident'>hidden</span>)]</span> <span class='kw'>struct</span> <span class='ident'>Hidden</span>;</pre> <!-- ### Controlling HTML --> <h3 id='htmlの制御' class='section-header'><a href='#htmlの制御'>HTMLの制御</a></h3> <!-- You can control a few aspects of the HTML that `rustdoc` generates through the --> <!-- `#![doc]` version of the attribute: --> <p><code>rustdoc</code> の生成するHTMLのいくつかの外見は、 <code>#![doc]</code> アトリビュートを通じて制御することができます。</p> <span class='rusttest'>fn main() { #![doc(html_logo_url = &quot;https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png&quot;, html_favicon_url = &quot;https://www.rust-lang.org/favicon.ico&quot;, html_root_url = &quot;https://doc.rust-lang.org/&quot;)] }</span><pre class='rust rust-example-rendered'> <span class='attribute'>#<span class='op'>!</span>[<span class='ident'>doc</span>(<span class='ident'>html_logo_url</span> <span class='op'>=</span> <span class='string'>&quot;https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png&quot;</span>, <span class='ident'>html_favicon_url</span> <span class='op'>=</span> <span class='string'>&quot;https://www.rust-lang.org/favicon.ico&quot;</span>, <span class='ident'>html_root_url</span> <span class='op'>=</span> <span class='string'>&quot;https://doc.rust-lang.org/&quot;</span>)]</span></pre> <!-- This sets a few different options, with a logo, favicon, and a root URL. --> <p>これは、複数の異なったオプション、つまりロゴ、お気に入りアイコン、ルートのURLをセットします。</p> <!-- ### Configuring documentation tests --> <h3 id='ドキュメンテーションテストの設定' class='section-header'><a href='#ドキュメンテーションテストの設定'>ドキュメンテーションテストの設定</a></h3> <!-- You can also configure the way that `rustdoc` tests your documentation examples --> <!-- through the `#![doc(test(..))]` attribute. --> <p><code>rustdoc</code> がドキュメントの例をテストする方法は、 <code>#[doc(test(..))]</code> アトリビュートを通じて設定することができます。</p> <span class='rusttest'>fn main() { #![doc(test(attr(allow(unused_variables), deny(warnings))))] }</span><pre class='rust rust-example-rendered'> <span class='attribute'>#<span class='op'>!</span>[<span class='ident'>doc</span>(<span class='ident'>test</span>(<span class='ident'>attr</span>(<span class='ident'>allow</span>(<span class='ident'>unused_variables</span>), <span class='ident'>deny</span>(<span class='ident'>warnings</span>))))]</span></pre> <!-- This allows unused variables within the examples, but will fail the test for any --> <!-- other lint warning thrown. --> <p>これによって例の中の使われていない値は許されるようになりますが、その他の全てのリントの警告に対してテストは失敗するようになるでしょう。</p> <!-- ## Generation options --> <h2 id='生成オプション' class='section-header'><a href='#生成オプション'>生成オプション</a></h2> <!-- `rustdoc` also contains a few other options on the command line, for further customization: --> <p><code>rustdoc</code> はさらなるカスタマイズのために、その他にもコマンドラインのオプションをいくつか持っています。</p> <!-- - `--html-in-header FILE`: includes the contents of FILE at the end of the --> <!-- `<head>...</head>` section. --> <!-- - `--html-before-content FILE`: includes the contents of FILE directly after --> <!-- `<body>`, before the rendered content (including the search bar). --> <!-- - `--html-after-content FILE`: includes the contents of FILE after all the rendered content. --> <ul> <li><code>--html-in-header FILE</code> : FILEの内容を <code>&lt;head&gt;...&lt;/head&gt;</code> セクションの末尾に加える</li> <li><code>--html-before-content FILE</code> : FILEの内容を <code>&lt;body&gt;</code> の直後、レンダリングされた内容(検索バーを含む)の直前に加える</li> <li><code>--html-after-content FILE</code> : FILEの内容を全てのレンダリングされた内容の後に加える</li> </ul> <!-- ## Security note --> <h2 id='セキュリティ上の注意' class='section-header'><a href='#セキュリティ上の注意'>セキュリティ上の注意</a></h2> <!-- The Markdown in documentation comments is placed without processing into --> <!-- the final webpage. Be careful with literal HTML: --> <p>ドキュメンテーションコメント内のMarkdownは最終的なウェブページの中に無修正で挿入されます。 リテラルのHTMLには注意してください。</p> <span class='rusttest'>fn main() { /// &lt;script&gt;alert(document.cookie)&lt;/script&gt; fn foo() {} }</span><pre class='rust rust-example-rendered'> <span class='doccomment'>/// &lt;script&gt;alert(document.cookie)&lt;/script&gt;</span></pre> <script type="text/javascript"> window.playgroundUrl = "https://play.rust-lang.org"; </script> <script src='rustbook.js'></script> <script src='playpen.js'></script> </div></div> </body> </html> <|start_filename|>docs/1.6/book/crates-and-modules.html<|end_filename|> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="generator" content="rustdoc"> <title>クレートとモジュール</title> <link rel="stylesheet" type="text/css" href="rustbook.css"> <meta name="robots" content="noindex"> </head> <body class="rustdoc"> <!--[if lte IE 8]> <div class="warning"> This old browser is unsupported and will most likely display funky things. </div> <![endif]--> <div id="nav"> <button id="toggle-nav"> <span class="sr-only">Toggle navigation</span> <span class="bar"></span> <span class="bar"></span> <span class="bar"></span> </button> </div> <div id='toc' class='mobile-hidden'> <ul class='chapter'> <li><a href='README.html'><b>1.</b> Introduction</a> </li> <li><a href='getting-started.html'><b>2.</b> はじめる</a> </li> <li><a href='learn-rust.html'><b>3.</b> Rustを学ぶ</a> <ul class='section'> <li><a href='guessing-game.html'><b>3.1.</b> 数当てゲーム</a> </li> <li><a href='dining-philosophers.html'><b>3.2.</b> 食事する哲学者</a> </li> <li><a href='rust-inside-other-languages.html'><b>3.3.</b> 他言語と共存する</a> </li> </ul> </li> <li><a href='syntax-and-semantics.html'><b>4.</b> シンタックスとセマンティクス</a> <ul class='section'> <li><a href='variable-bindings.html'><b>4.1.</b> 変数束縛</a> </li> <li><a href='functions.html'><b>4.2.</b> 関数</a> </li> <li><a href='primitive-types.html'><b>4.3.</b> プリミティブ型</a> </li> <li><a href='comments.html'><b>4.4.</b> コメント</a> </li> <li><a href='if.html'><b>4.5.</b> if</a> </li> <li><a href='loops.html'><b>4.6.</b> ループ</a> </li> <li><a href='ownership.html'><b>4.7.</b> 所有権</a> </li> <li><a href='references-and-borrowing.html'><b>4.8.</b> 参照と借用</a> </li> <li><a href='lifetimes.html'><b>4.9.</b> ライフタイム</a> </li> <li><a href='mutability.html'><b>4.10.</b> ミュータビリティ</a> </li> <li><a href='structs.html'><b>4.11.</b> 構造体</a> </li> <li><a href='enums.html'><b>4.12.</b> 列挙型</a> </li> <li><a href='match.html'><b>4.13.</b> マッチ</a> </li> <li><a href='patterns.html'><b>4.14.</b> パターン</a> </li> <li><a href='method-syntax.html'><b>4.15.</b> メソッド構文</a> </li> <li><a href='vectors.html'><b>4.16.</b> ベクタ</a> </li> <li><a href='strings.html'><b>4.17.</b> 文字列</a> </li> <li><a href='generics.html'><b>4.18.</b> ジェネリクス</a> </li> <li><a href='traits.html'><b>4.19.</b> トレイト</a> </li> <li><a href='drop.html'><b>4.20.</b> Drop</a> </li> <li><a href='if-let.html'><b>4.21.</b> if let</a> </li> <li><a href='trait-objects.html'><b>4.22.</b> トレイトオブジェクト</a> </li> <li><a href='closures.html'><b>4.23.</b> クロージャ</a> </li> <li><a href='ufcs.html'><b>4.24.</b> 共通の関数呼出構文</a> </li> <li><a class='active' href='crates-and-modules.html'><b>4.25.</b> クレートとモジュール</a> </li> <li><a href='const-and-static.html'><b>4.26.</b> `const` と `static`</a> </li> <li><a href='attributes.html'><b>4.27.</b> アトリビュート</a> </li> <li><a href='type-aliases.html'><b>4.28.</b> `type` エイリアス</a> </li> <li><a href='casting-between-types.html'><b>4.29.</b> 型間のキャスト</a> </li> <li><a href='associated-types.html'><b>4.30.</b> 関連型</a> </li> <li><a href='unsized-types.html'><b>4.31.</b> サイズ不定型</a> </li> <li><a href='operators-and-overloading.html'><b>4.32.</b> 演算子とオーバーロード</a> </li> <li><a href='deref-coercions.html'><b>4.33.</b> Derefによる型強制</a> </li> <li><a href='macros.html'><b>4.34.</b> マクロ</a> </li> <li><a href='raw-pointers.html'><b>4.35.</b> 生ポインタ</a> </li> <li><a href='unsafe.html'><b>4.36.</b> `unsafe`</a> </li> </ul> </li> <li><a href='effective-rust.html'><b>5.</b> Effective Rust</a> <ul class='section'> <li><a href='the-stack-and-the-heap.html'><b>5.1.</b> スタックとヒープ</a> </li> <li><a href='testing.html'><b>5.2.</b> テスト</a> </li> <li><a href='conditional-compilation.html'><b>5.3.</b> 条件付きコンパイル</a> </li> <li><a href='documentation.html'><b>5.4.</b> ドキュメント</a> </li> <li><a href='iterators.html'><b>5.5.</b> イテレータ</a> </li> <li><a href='concurrency.html'><b>5.6.</b> 並行性</a> </li> <li><a href='error-handling.html'><b>5.7.</b> エラーハンドリング</a> </li> <li><a href='choosing-your-guarantees.html'><b>5.8.</b> 保証を選ぶ</a> </li> <li><a href='ffi.html'><b>5.9.</b> 他言語関数インターフェース</a> </li> <li><a href='borrow-and-asref.html'><b>5.10.</b> BorrowとAsRef</a> </li> <li><a href='release-channels.html'><b>5.11.</b> リリースチャネル</a> </li> <li><a href='using-rust-without-the-standard-library.html'><b>5.12.</b> 標準ライブラリ無しでRustを使う</a> </li> </ul> </li> <li><a href='nightly-rust.html'><b>6.</b> Nightly Rust</a> <ul class='section'> <li><a href='compiler-plugins.html'><b>6.1.</b> コンパイラプラグイン</a> </li> <li><a href='inline-assembly.html'><b>6.2.</b> インラインアセンブリ</a> </li> <li><a href='no-stdlib.html'><b>6.3.</b> No stdlib</a> </li> <li><a href='intrinsics.html'><b>6.4.</b> Intrinsic</a> </li> <li><a href='lang-items.html'><b>6.5.</b> 言語アイテム</a> </li> <li><a href='advanced-linking.html'><b>6.6.</b> 高度なリンキング</a> </li> <li><a href='benchmark-tests.html'><b>6.7.</b> ベンチマークテスト</a> </li> <li><a href='box-syntax-and-patterns.html'><b>6.8.</b> Box構文とパターン</a> </li> <li><a href='slice-patterns.html'><b>6.9.</b> スライスパターン</a> </li> <li><a href='associated-constants.html'><b>6.10.</b> 関連定数</a> </li> <li><a href='custom-allocators.html'><b>6.11.</b> カスタムアロケータ</a> </li> </ul> </li> <li><a href='glossary.html'><b>7.</b> 用語集</a> </li> <li><a href='syntax-index.html'><b>8.</b> 構文の索引</a> </li> <li><a href='bibliography.html'><b>9.</b> 関係書目</a> </li> </ul> </div> <div id='page-wrapper'> <div id='page'> <blockquote class="header-caveat"> <p> <strong>注意: <a href="https://doc.rust-jp.rs/book-ja/">最新版のドキュメントをご覧ください。</a></strong>この第1版ドキュメントは古くなっており、最新情報が反映されていません。リンク先のドキュメントが現在の Rust の最新のドキュメントです。 </p> </blockquote> <h1 class="title">クレートとモジュール</h1> <!-- % Crates and Modules --> <!-- When a project starts getting large, it’s considered good software engineering practice to split it up into a bunch of smaller pieces, and then fit them together. It’s also important to have a well-defined interface, so that some of your functionality is private, and some is public. To facilitate these kinds of things, Rust has a module system. --> <p>プロジェクトが大きくなり始めた際に、コードを小さなまとまりに分割しそれらでプロジェクトを組み立てるのはソフトウェア工学における優れた慣例だと考えられています。幾つかの機能をプライベートとし、また幾つかをパブリックとできるように、はっきりと定義されたインターフェースも重要となります。こういった事柄を容易にするため、Rustはモジュールシステムを有しています。</p> <!-- # Basic terminology: Crates and Modules --> <h1 id='基本的な用語-クレートとモジュール' class='section-header'><a href='#基本的な用語-クレートとモジュール'>基本的な用語: クレートとモジュール</a></h1> <!-- Rust has two distinct terms that relate to the module system: ‘crate’ and ‘module’. A crate is synonymous with a ‘library’ or ‘package’ in other languages. Hence “Cargo” as the name of Rust’s package management tool: you ship your crates to others with Cargo. Crates can produce an executable or a library, depending on the project. --> <p>Rustはモジュールシステムに関連する「クレート」(crate)と「モジュール」(module)という2つの用語を明確に区別しています。クレートは他の言語における「ライブラリ」や「パッケージ」と同じ意味です。このことからRustのパッケージマネジメントツールの名前を「Cargo」としています。(訳注: crateとは枠箱のことであり、cargoは船荷を指します)Cargoを使ってクレートを出荷し他のユーザに公開するわけです。クレートは実行形式かライブラリをプロジェクトに応じて作成できます。</p> <!-- Each crate has an implicit *root module* that contains the code for that crate. You can then define a tree of sub-modules under that root module. Modules allow you to partition your code within the crate itself. --> <p>各クレートは自身のコードが入っている <em>ルートモジュール</em> (root module)を暗黙的に持っています。そしてルートモジュール下にはサブモジュールの木が定義できます。モジュールによりクレート内でコードを分割できます。</p> <!-- As an example, let’s make a *phrases* crate, which will give us various phrases in different languages. To keep things simple, we’ll stick to ‘greetings’ and ‘farewells’ as two kinds of phrases, and use English and Japanese (日本語) as two languages for those phrases to be in. We’ll use this module layout: --> <p>例として、 <em>phrases</em> クレートを作ってみます。これに異なる言語で幾つかのフレーズを入れます。問題の単純さを保つために、2種類のフレーズ「greetings」と「farewells」のみとし、これらフレーズを表すための2つの言語として英語と日本語を使うことにします。モジュールのレイアウトは以下のようになります。</p> <pre><code class="language-text"> +-----------+ +---| greetings | | +-----------+ +---------+ | +---| english |---+ | +---------+ | +-----------+ | +---| farewells | +---------+ | +-----------+ | phrases |---+ +---------+ | +-----------+ | +---| greetings | | +----------+ | +-----------+ +---| japanese |--+ +----------+ | | +-----------+ +---| farewells | +-----------+ </code></pre> <!-- In this example, `phrases` is the name of our crate. All of the rest are modules. You can see that they form a tree, branching out from the crate *root*, which is the root of the tree: `phrases` itself. --> <p>この例において、 <code>phrases</code> がクレートの名前で、それ以外の全てはモジュールです。それらが木の形をしており、クレートの <em>ルート</em> から枝分かれしていることが分かります。そして木のルートは <code>phrases</code> それ自身です。</p> <!-- Now that we have a plan, let’s define these modules in code. To start, generate a new crate with Cargo: --> <p>ここまでで計画は立ちましたから、これらモジュールをコードで定義しましょう。始めるために、Cargoで新しいクレートを生成します。</p> <pre><code class="language-bash">$ cargo new phrases $ cd phrases </code></pre> <!-- If you remember, this generates a simple project for us: --> <p>聡明な読者ならご記憶かと思いますがCargoが単純なプロジェクトを生成してくれます。</p> <pre><code class="language-bash">$ tree . . ├── Cargo.toml └── src └── lib.rs 1 directory, 2 files </code></pre> <!-- `src/lib.rs` is our crate root, corresponding to the `phrases` in our diagram above. --> <p><code>src/lib.rs</code> はクレートのルートであり、先程の図における <code>phrases</code> に相当します。</p> <!-- # Defining Modules --> <h1 id='モジュールを定義する' class='section-header'><a href='#モジュールを定義する'>モジュールを定義する</a></h1> <!-- To define each of our modules, we use the `mod` keyword. Let’s make our `src/lib.rs` look like this: --> <p>それぞれのモジュールを定義するために、 <code>mod</code> キーワードを使います。 <code>src/lib.rs</code> を以下のようにしましょう。</p> <span class='rusttest'>fn main() { mod english { mod greetings { } mod farewells { } } mod japanese { mod greetings { } mod farewells { } } }</span><pre class='rust rust-example-rendered'> <span class='kw'>mod</span> <span class='ident'>english</span> { <span class='kw'>mod</span> <span class='ident'>greetings</span> { } <span class='kw'>mod</span> <span class='ident'>farewells</span> { } } <span class='kw'>mod</span> <span class='ident'>japanese</span> { <span class='kw'>mod</span> <span class='ident'>greetings</span> { } <span class='kw'>mod</span> <span class='ident'>farewells</span> { } }</pre> <!-- After the `mod` keyword, you give the name of the module. Module names follow the conventions for other Rust identifiers: `lower_snake_case`. The contents of each module are within curly braces (`{}`). --> <p><code>mod</code> キーワードの後、モジュールの名前を与えます。モジュール名はRustの他の識別子の慣例に従います。つまり <code>lower_snake_case</code> です。各モジュールの内容は波括弧( <code>{}</code> )の中に書きます。</p> <!-- Within a given `mod`, you can declare sub-`mod`s. We can refer to sub-modules with double-colon (`::`) notation: our four nested modules are `english::greetings`, `english::farewells`, `japanese::greetings`, and `japanese::farewells`. Because these sub-modules are namespaced under their parent module, the names don’t conflict: `english::greetings` and `japanese::greetings` are distinct, even though their names are both `greetings`. --> <p>与えられた <code>mod</code> 内で、サブ <code>mod</code> を定義することができます。サブモジュールは2重コロン( <code>::</code> )記法で参照できます。ネストされた4つのモジュールは <code>english::greetings</code> 、 <code>english::farewells</code> 、 <code>japanese::greetings</code> 、そして <code>japanese::farewells</code> です。これらサブモジュールは親モジュール配下の名前空間になるため、名前は競合しません。つまり <code>english::greetings</code> と <code>japanese::greetings</code> は例え両名が <code>greetings</code> であったとしても、明確に区別されます。</p> <!-- Because this crate does not have a `main()` function, and is called `lib.rs`, Cargo will build this crate as a library: --> <p>このクレートは <code>main()</code> 関数を持たず、 <code>lib.rs</code> と名付けられているため、Cargoはこのクレートをライブラリとしてビルドします。</p> <pre><code class="language-bash">$ cargo build Compiling phrases v0.0.1 (file:///home/you/projects/phrases) $ ls target/debug build deps examples libphrases-a7448e02a0468eaa.rlib native </code></pre> <!-- `libphrases-hash.rlib` is the compiled crate. Before we see how to use this crate from another crate, let’s break it up into multiple files. --> <p><code>libphrases-hash.rlib</code> はコンパイルされたクレートです。このクレートを他のクレートから使う方法を見る前に、複数のファイルに分割してみましょう。</p> <!-- # Multiple file crates --> <h1 id='複数のファイルによるクレート' class='section-header'><a href='#複数のファイルによるクレート'>複数のファイルによるクレート</a></h1> <!-- If each crate were just one file, these files would get very large. It’s often easier to split up crates into multiple files, and Rust supports this in two ways. --> <p>各クレートがただ1つのファイルからなるのであれば、これらファイルは非常に大きくなってしまうでしょう。クレートを複数のファイルに分けた方が楽になるため、Rustは2つの方法でこれをサポートしています。</p> <!-- Instead of declaring a module like this: --> <p>以下のようなモジュールを宣言する代わりに、</p> <span class='rusttest'>fn main() { mod english { // // contents of our module go here // モジュールの内容はここに } }</span><pre class='rust rust-example-rendered'> <span class='kw'>mod</span> <span class='ident'>english</span> { <span class='comment'>// モジュールの内容はここに</span> }</pre> <!-- We can instead declare our module like this: --> <p>以下のようなモジュールが宣言できます。</p> <span class='rusttest'>fn main() { mod english; }</span><pre class='rust rust-example-rendered'> <span class='kw'>mod</span> <span class='ident'>english</span>;</pre> <!-- If we do that, Rust will expect to find either a `english.rs` file, or a `english/mod.rs` file with the contents of our module. --> <p>こうすると、Rustは <code>english.rs</code> ファイルか、 <code>english/mod.rs</code> ファイルのどちらかにモジュールの内容があるだろうと予想します。</p> <!-- Note that in these files, you don’t need to re-declare the module: that’s already been done with the initial `mod` declaration. --> <p>それらのファイルの中でモジュールの再宣言を行う必要がないことに気をつけて下さい。先の <code>mod</code> 宣言にてそれは済んでいます。</p> <!-- Using these two techniques, we can break up our crate into two directories and seven files: --> <p>これら2つのテクニックを用いて、クレートを2つのディレクトリと7つのファイルに分解できます。</p> <pre><code class="language-bash">$ tree . . ├── Cargo.lock ├── Cargo.toml ├── src │   ├── english │   │   ├── farewells.rs │   │   ├── greetings.rs │   │   └── mod.rs │   ├── japanese │   │   ├── farewells.rs │   │   ├── greetings.rs │   │   └── mod.rs │   └── lib.rs └── target └── debug ├── build ├── deps ├── examples ├── libphrases-a7448e02a0468eaa.rlib └── native </code></pre> <!-- `src/lib.rs` is our crate root, and looks like this: --> <p><code>src/lib.rs</code> はクレートのルートで、以下のようになっています。</p> <span class='rusttest'>fn main() { mod english; mod japanese; }</span><pre class='rust rust-example-rendered'> <span class='kw'>mod</span> <span class='ident'>english</span>; <span class='kw'>mod</span> <span class='ident'>japanese</span>;</pre> <!-- These two declarations tell Rust to look for either `src/english.rs` and `src/japanese.rs`, or `src/english/mod.rs` and `src/japanese/mod.rs`, depending on our preference. In this case, because our modules have sub-modules, we’ve chosen the second. Both `src/english/mod.rs` and `src/japanese/mod.rs` look like this: --> <p>これら2つの宣言はRustへ書き手の好みに合わせて <code>src/english.rs</code> と <code>src/japanese.rs</code> 、または <code>src/english/mod.rs</code> と <code>src/japanese/mod.rs</code> のどちらかを見よと伝えています。今回の場合、サブモジュールがあるため私たちは後者を選択しました。 <code>src/english/mod.rs</code> と <code>src/japanese/mod.rs</code> は両方とも以下のようになっています。</p> <span class='rusttest'>fn main() { mod greetings; mod farewells; }</span><pre class='rust rust-example-rendered'> <span class='kw'>mod</span> <span class='ident'>greetings</span>; <span class='kw'>mod</span> <span class='ident'>farewells</span>;</pre> <!-- Again, these declarations tell Rust to look for either `src/english/greetings.rs` and `src/japanese/greetings.rs` or `src/english/farewells/mod.rs` and `src/japanese/farewells/mod.rs`. Because these sub-modules don’t have their own sub-modules, we’ve chosen to make them `src/english/greetings.rs` and `src/japanese/farewells.rs`. Whew! --> <p>繰り返すと、これら宣言はRustへ <code>src/english/greetings.rs</code> と <code>src/japanese/greetings.rs</code> 、または <code>src/english/farewells/mod.rs</code> と <code>src/japanese/farewells/mod.rs</code> のどちらかを見よと伝えています。これらサブモジュールは自身配下のサブモジュールを持たないため、私たちは <code>src/english/greetings.rs</code> と <code>src/japanese/farewells.rs</code> を選びました。ヒュー!</p> <!-- The contents of `src/english/greetings.rs` and `src/japanese/farewells.rs` are both empty at the moment. Let’s add some functions. --> <p><code>src/english/greetings.rs</code> と <code>src/japanese/farewells.rs</code> の中身は現在両方とも空です。幾つか関数を追加しましょう。</p> <!-- Put this in `src/english/greetings.rs`: --> <p><code>src/english/greetings.rs</code> に以下を入力します。</p> <span class='rusttest'>fn main() { fn hello() -&gt; String { &quot;Hello!&quot;.to_string() } }</span><pre class='rust rust-example-rendered'> <span class='kw'>fn</span> <span class='ident'>hello</span>() <span class='op'>-&gt;</span> <span class='ident'>String</span> { <span class='string'>&quot;Hello!&quot;</span>.<span class='ident'>to_string</span>() }</pre> <!-- Put this in `src/english/farewells.rs`: --> <p><code>src/english/farewells.rs</code> に以下を入力します。</p> <span class='rusttest'>fn main() { fn goodbye() -&gt; String { &quot;Goodbye.&quot;.to_string() } }</span><pre class='rust rust-example-rendered'> <span class='kw'>fn</span> <span class='ident'>goodbye</span>() <span class='op'>-&gt;</span> <span class='ident'>String</span> { <span class='string'>&quot;Goodbye.&quot;</span>.<span class='ident'>to_string</span>() }</pre> <!-- Put this in `src/japanese/greetings.rs`: --> <p><code>src/japanese/greetings.rs</code> に以下を入力します。</p> <span class='rusttest'>fn main() { fn hello() -&gt; String { &quot;こんにちは&quot;.to_string() } }</span><pre class='rust rust-example-rendered'> <span class='kw'>fn</span> <span class='ident'>hello</span>() <span class='op'>-&gt;</span> <span class='ident'>String</span> { <span class='string'>&quot;こんにちは&quot;</span>.<span class='ident'>to_string</span>() }</pre> <!-- Of course, you can copy and paste this from this web page, or just type something else. It’s not important that you actually put ‘konnichiwa’ to learn about the module system. --> <p>勿論、このwebページからコピー&amp;ペーストしたり、他の何かをタイプしても構いません。モジュールシステムを学ぶのに「konnichiwa」と入力するのは重要なことではありません。</p> <!-- Put this in `src/japanese/farewells.rs`: --> <p><code>src/japanese/farewells.rs</code> に以下を入力します。</p> <span class='rusttest'>fn main() { fn goodbye() -&gt; String { &quot;さようなら&quot;.to_string() } }</span><pre class='rust rust-example-rendered'> <span class='kw'>fn</span> <span class='ident'>goodbye</span>() <span class='op'>-&gt;</span> <span class='ident'>String</span> { <span class='string'>&quot;さようなら&quot;</span>.<span class='ident'>to_string</span>() }</pre> <!-- (This is ‘Sayōnara’, if you’re curious.) --> <p>(英語だと「Sayōnara」と表記するようです、御参考まで。)</p> <!-- Now that we have some functionality in our crate, let’s try to use it from another crate. --> <p>ここまででクレートに幾つかの機能が実装されました、それでは他のクレートから使ってみましょう。</p> <!-- # Importing External Crates --> <h1 id='外部クレートのインポート' class='section-header'><a href='#外部クレートのインポート'>外部クレートのインポート</a></h1> <!-- We have a library crate. Let’s make an executable crate that imports and uses our library. --> <p>前節でライブラリクレートができました。インポートしこのライブラリを用いた実行形式クレートを作成しましょう。</p> <!-- Make a `src/main.rs` and put this in it (it won’t quite compile yet): --> <p><code>src/main.rs</code> を作成し配置します。(このコンパイルはまだ通りません)</p> <span class='rusttest'>extern crate phrases; fn main() { println!(&quot;Hello in English: {}&quot;, phrases::english::greetings::hello()); println!(&quot;Goodbye in English: {}&quot;, phrases::english::farewells::goodbye()); println!(&quot;Hello in Japanese: {}&quot;, phrases::japanese::greetings::hello()); println!(&quot;Goodbye in Japanese: {}&quot;, phrases::japanese::farewells::goodbye()); } </span><pre class='rust rust-example-rendered'> <span class='kw'>extern</span> <span class='kw'>crate</span> <span class='ident'>phrases</span>; <span class='kw'>fn</span> <span class='ident'>main</span>() { <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;Hello in English: {}&quot;</span>, <span class='ident'>phrases</span>::<span class='ident'>english</span>::<span class='ident'>greetings</span>::<span class='ident'>hello</span>()); <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;Goodbye in English: {}&quot;</span>, <span class='ident'>phrases</span>::<span class='ident'>english</span>::<span class='ident'>farewells</span>::<span class='ident'>goodbye</span>()); <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;Hello in Japanese: {}&quot;</span>, <span class='ident'>phrases</span>::<span class='ident'>japanese</span>::<span class='ident'>greetings</span>::<span class='ident'>hello</span>()); <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;Goodbye in Japanese: {}&quot;</span>, <span class='ident'>phrases</span>::<span class='ident'>japanese</span>::<span class='ident'>farewells</span>::<span class='ident'>goodbye</span>()); }</pre> <!-- The `extern crate` declaration tells Rust that we need to compile and link to the `phrases` crate. We can then use `phrases` modules in this one. As we mentioned earlier, you can use double colons to refer to sub-modules and the functions inside of them. --> <p><code>extern crate</code> 宣言はRustにコンパイルして <code>phrases</code> クレートをリンクせよと伝えます。するとこのクレート内で <code>phrases</code> モジュールが使えます。先に述べていたように、2重コロンでサブモジュールとその中の関数を参照できます。</p> <!-- (Note: when importing a crate that has dashes in its name "like-this", which is not a valid Rust identifier, it will be converted by changing the dashes to underscores, so you would write `extern crate like_this;`.) --> <p>(注意: Rustの識別子として適切でない「like-this」のような、名前の中にダッシュが入ったクレートをインポートする場合、ダッシュがアンダースコアへ変換されるため <code>extern crate like_this;</code> と記述します。)</p> <!-- Also, Cargo assumes that `src/main.rs` is the crate root of a binary crate, rather than a library crate. Our package now has two crates: `src/lib.rs` and `src/main.rs`. This pattern is quite common for executable crates: most functionality is in a library crate, and the executable crate uses that library. This way, other programs can also use the library crate, and it’s also a nice separation of concerns. --> <p>また、Cargoは <code>src/main.rs</code> がライブラリクレートではなくバイナリクレートのルートだと仮定します。パッケージには今2つのクレートがあります。 <code>src/lib.rs</code> と <code>src/main.rs</code> です。ほとんどの機能をライブラリクレート内に置き、実行形式クレートから利用するのがよくあるパターンです。この方法なら他のプログラムがライブラリクレートを使うこともできますし、素敵な関心の分離(separation of concerns)にもなります。</p> <!-- This doesn’t quite work yet, though. We get four errors that look similar to this: --> <p>けれどこのままではまだ動作しません。以下に似た4つのエラーが発生します。</p> <pre><code class="language-bash">$ cargo build Compiling phrases v0.0.1 (file:///home/you/projects/phrases) src/main.rs:4:38: 4:72 error: function `hello` is private src/main.rs:4 println!(&quot;Hello in English: {}&quot;, phrases::english::greetings::hello()); ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ note: in expansion of format_args! &lt;std macros&gt;:2:25: 2:58 note: expansion site &lt;std macros&gt;:1:1: 2:62 note: in expansion of print! &lt;std macros&gt;:3:1: 3:54 note: expansion site &lt;std macros&gt;:1:1: 3:58 note: in expansion of println! phrases/src/main.rs:4:5: 4:76 note: expansion site </code></pre> <!-- By default, everything is private in Rust. Let’s talk about this in some more depth. --> <p>デフォルトでは、Rustにおける全てがプライベートです。それではもっと詳しく説明しましょう。</p> <!-- # Exporting a Public Interface --> <h1 id='パブリックなインターフェースのエクスポート' class='section-header'><a href='#パブリックなインターフェースのエクスポート'>パブリックなインターフェースのエクスポート</a></h1> <!-- Rust allows you to precisely control which aspects of your interface are public, and so private is the default. To make things public, you use the `pub` keyword. Let’s focus on the `english` module first, so let’s reduce our `src/main.rs` to just this: --> <p>Rustはインターフェースのパブリックである部分をきっちりと管理します。そのためプライベートがデフォルトです。パブリックにするためには <code>pub</code> キーワードを使います。まずは <code>english</code> モジュールに焦点を当てたいので、 <code>src/main.rs</code> をこれだけに減らしましょう。</p> <span class='rusttest'>extern crate phrases; fn main() { println!(&quot;Hello in English: {}&quot;, phrases::english::greetings::hello()); println!(&quot;Goodbye in English: {}&quot;, phrases::english::farewells::goodbye()); } </span><pre class='rust rust-example-rendered'> <span class='kw'>extern</span> <span class='kw'>crate</span> <span class='ident'>phrases</span>; <span class='kw'>fn</span> <span class='ident'>main</span>() { <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;Hello in English: {}&quot;</span>, <span class='ident'>phrases</span>::<span class='ident'>english</span>::<span class='ident'>greetings</span>::<span class='ident'>hello</span>()); <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;Goodbye in English: {}&quot;</span>, <span class='ident'>phrases</span>::<span class='ident'>english</span>::<span class='ident'>farewells</span>::<span class='ident'>goodbye</span>()); }</pre> <!-- In our `src/lib.rs`, let’s add `pub` to the `english` module declaration: --> <p><code>src/lib.rs</code> 内にて、 <code>english</code> モジュールの宣言に <code>pub</code> を加えましょう。</p> <span class='rusttest'>fn main() { pub mod english; mod japanese; }</span><pre class='rust rust-example-rendered'> <span class='kw'>pub</span> <span class='kw'>mod</span> <span class='ident'>english</span>; <span class='kw'>mod</span> <span class='ident'>japanese</span>;</pre> <!-- And in our `src/english/mod.rs`, let’s make both `pub`: --> <p>また <code>src/english/mod.rs</code> にて、両方とも <code>pub</code> にしましょう。</p> <span class='rusttest'>fn main() { pub mod greetings; pub mod farewells; }</span><pre class='rust rust-example-rendered'> <span class='kw'>pub</span> <span class='kw'>mod</span> <span class='ident'>greetings</span>; <span class='kw'>pub</span> <span class='kw'>mod</span> <span class='ident'>farewells</span>;</pre> <!-- In our `src/english/greetings.rs`, let’s add `pub` to our `fn` declaration: --> <p><code>src/english/greetings.rs</code> にて、 <code>fn</code> の宣言に <code>pub</code> を加えましょう。</p> <span class='rusttest'>fn main() { pub fn hello() -&gt; String { &quot;Hello!&quot;.to_string() } }</span><pre class='rust rust-example-rendered'> <span class='kw'>pub</span> <span class='kw'>fn</span> <span class='ident'>hello</span>() <span class='op'>-&gt;</span> <span class='ident'>String</span> { <span class='string'>&quot;Hello!&quot;</span>.<span class='ident'>to_string</span>() }</pre> <!-- And also in `src/english/farewells.rs`: --> <p>また <code>src/english/farewells.rs</code> にもです。</p> <span class='rusttest'>fn main() { pub fn goodbye() -&gt; String { &quot;Goodbye.&quot;.to_string() } }</span><pre class='rust rust-example-rendered'> <span class='kw'>pub</span> <span class='kw'>fn</span> <span class='ident'>goodbye</span>() <span class='op'>-&gt;</span> <span class='ident'>String</span> { <span class='string'>&quot;Goodbye.&quot;</span>.<span class='ident'>to_string</span>() }</pre> <!-- Now, our crate compiles, albeit with warnings about not using the `japanese` functions: --> <p>これでクレートはコンパイルできますが、 <code>japanese</code> 関数が使われていないという旨の警告が発生します。</p> <pre><code class="language-bash">$ cargo run Compiling phrases v0.0.1 (file:///home/you/projects/phrases) src/japanese/greetings.rs:1:1: 3:2 warning: function is never used: `hello`, #[warn(dead_code)] on by default src/japanese/greetings.rs:1 fn hello() -&gt; String { src/japanese/greetings.rs:2 &quot;こんにちは&quot;.to_string() src/japanese/greetings.rs:3 } src/japanese/farewells.rs:1:1: 3:2 warning: function is never used: `goodbye`, #[warn(dead_code)] on by default src/japanese/farewells.rs:1 fn goodbye() -&gt; String { src/japanese/farewells.rs:2 &quot;さようなら&quot;.to_string() src/japanese/farewells.rs:3 } Running `target/debug/phrases` Hello in English: Hello! Goodbye in English: Goodbye. </code></pre> <!-- `pub` also applies to `struct`s and their member fields. In keeping with Rust’s tendency toward safety, simply making a `struct` public won't automatically make its members public: you must mark the fields individually with `pub`. --> <p><code>pub</code> は <code>struct</code> や そのメンバのフィールドにも使えます。Rustの安全性に対する傾向に合わせ、単に <code>struct</code> をパブリックにしてもそのメンバまでは自動的にパブリックになりません。個々のフィールドに <code>pub</code> を付ける必要があります。</p> <!-- Now that our functions are public, we can use them. Great! However, typing out `phrases::english::greetings::hello()` is very long and repetitive. Rust has another keyword for importing names into the current scope, so that you can refer to them with shorter names. Let’s talk about `use`. --> <p>関数がパブリックになり、呼び出せるようになりました。素晴らしい!けれども <code>phrases::english::greetings::hello()</code> を打つのは非常に長くて退屈ですね。Rustにはもう1つ、現在のスコープに名前をインポートするキーワードがあるので、それを使えば短い名前で参照できます。では <code>use</code> について説明しましょう。</p> <!-- # Importing Modules with `use` --> <h1 id='use-でモジュールをインポートする' class='section-header'><a href='#use-でモジュールをインポートする'><code>use</code> でモジュールをインポートする</a></h1> <!-- Rust has a `use` keyword, which allows us to import names into our local scope. Let’s change our `src/main.rs` to look like this: --> <p>Rustには <code>use</code> キーワードがあり、ローカルスコープの中に名前をインポートできます。 <code>src/main.rs</code> を以下のように変えてみましょう。</p> <span class='rusttest'>extern crate phrases; use phrases::english::greetings; use phrases::english::farewells; fn main() { println!(&quot;Hello in English: {}&quot;, greetings::hello()); println!(&quot;Goodbye in English: {}&quot;, farewells::goodbye()); } </span><pre class='rust rust-example-rendered'> <span class='kw'>extern</span> <span class='kw'>crate</span> <span class='ident'>phrases</span>; <span class='kw'>use</span> <span class='ident'>phrases</span>::<span class='ident'>english</span>::<span class='ident'>greetings</span>; <span class='kw'>use</span> <span class='ident'>phrases</span>::<span class='ident'>english</span>::<span class='ident'>farewells</span>; <span class='kw'>fn</span> <span class='ident'>main</span>() { <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;Hello in English: {}&quot;</span>, <span class='ident'>greetings</span>::<span class='ident'>hello</span>()); <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;Goodbye in English: {}&quot;</span>, <span class='ident'>farewells</span>::<span class='ident'>goodbye</span>()); }</pre> <!-- The two `use` lines import each module into the local scope, so we can refer to the functions by a much shorter name. By convention, when importing functions, it’s considered best practice to import the module, rather than the function directly. In other words, you _can_ do this: --> <p>2つの <code>use</code> の行はローカルスコープの中に各モジュールをインポートしているため、とても短い名前で関数を参照できます。慣習では関数をインポートする場合、関数を直接インポートするよりもモジュール単位でするのがベストプラクティスだと考えられています。言い換えれば、こうすることも <em>できる</em> わけです。</p> <span class='rusttest'>extern crate phrases; use phrases::english::greetings::hello; use phrases::english::farewells::goodbye; fn main() { println!(&quot;Hello in English: {}&quot;, hello()); println!(&quot;Goodbye in English: {}&quot;, goodbye()); } </span><pre class='rust rust-example-rendered'> <span class='kw'>extern</span> <span class='kw'>crate</span> <span class='ident'>phrases</span>; <span class='kw'>use</span> <span class='ident'>phrases</span>::<span class='ident'>english</span>::<span class='ident'>greetings</span>::<span class='ident'>hello</span>; <span class='kw'>use</span> <span class='ident'>phrases</span>::<span class='ident'>english</span>::<span class='ident'>farewells</span>::<span class='ident'>goodbye</span>; <span class='kw'>fn</span> <span class='ident'>main</span>() { <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;Hello in English: {}&quot;</span>, <span class='ident'>hello</span>()); <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;Goodbye in English: {}&quot;</span>, <span class='ident'>goodbye</span>()); }</pre> <!-- But it is not idiomatic. This is significantly more likely to introduce a naming conflict. In our short program, it’s not a big deal, but as it grows, it becomes a problem. If we have conflicting names, Rust will give a compilation error. For example, if we made the `japanese` functions public, and tried to do this: --> <p>しかしこれは慣用的ではありません。名前の競合を引き起こす可能性が非常に高まるからです。この短いプログラムだと大したことではありませんが、長くなるにつれ問題になります。名前が競合するとコンパイルエラーになります。例えば、 <code>japanese</code> 関数をパブリックにして、以下を試してみます。</p> <span class='rusttest'>extern crate phrases; use phrases::english::greetings::hello; use phrases::japanese::greetings::hello; fn main() { println!(&quot;Hello in English: {}&quot;, hello()); println!(&quot;Hello in Japanese: {}&quot;, hello()); } </span><pre class='rust rust-example-rendered'> <span class='kw'>extern</span> <span class='kw'>crate</span> <span class='ident'>phrases</span>; <span class='kw'>use</span> <span class='ident'>phrases</span>::<span class='ident'>english</span>::<span class='ident'>greetings</span>::<span class='ident'>hello</span>; <span class='kw'>use</span> <span class='ident'>phrases</span>::<span class='ident'>japanese</span>::<span class='ident'>greetings</span>::<span class='ident'>hello</span>; <span class='kw'>fn</span> <span class='ident'>main</span>() { <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;Hello in English: {}&quot;</span>, <span class='ident'>hello</span>()); <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;Hello in Japanese: {}&quot;</span>, <span class='ident'>hello</span>()); }</pre> <!-- Rust will give us a compile-time error: --> <p>Rustはコンパイル時にエラーを起こします。</p> <pre><code class="language-text"> Compiling phrases v0.0.1 (file:///home/you/projects/phrases) src/main.rs:4:5: 4:40 error: a value named `hello` has already been imported in this module [E0252] src/main.rs:4 use phrases::japanese::greetings::hello; ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ error: aborting due to previous error Could not compile `phrases`. </code></pre> <!-- If we’re importing multiple names from the same module, we don’t have to type it out twice. Instead of this: --> <p>同じモジュールから複数の名前をインポートする場合、二度同じ文字を打つ必要はありません。以下の代わりに、</p> <span class='rusttest'>fn main() { use phrases::english::greetings; use phrases::english::farewells; }</span><pre class='rust rust-example-rendered'> <span class='kw'>use</span> <span class='ident'>phrases</span>::<span class='ident'>english</span>::<span class='ident'>greetings</span>; <span class='kw'>use</span> <span class='ident'>phrases</span>::<span class='ident'>english</span>::<span class='ident'>farewells</span>;</pre> <!-- We can use this shortcut: --> <p>このショートカットが使えます。</p> <span class='rusttest'>fn main() { use phrases::english::{greetings, farewells}; }</span><pre class='rust rust-example-rendered'> <span class='kw'>use</span> <span class='ident'>phrases</span>::<span class='ident'>english</span>::{<span class='ident'>greetings</span>, <span class='ident'>farewells</span>};</pre> <!-- ## Re-exporting with `pub use` --> <h2 id='pub-use-による再エクスポート' class='section-header'><a href='#pub-use-による再エクスポート'><code>pub use</code> による再エクスポート</a></h2> <!-- You don’t just use `use` to shorten identifiers. You can also use it inside of your crate to re-export a function inside another module. This allows you to present an external interface that may not directly map to your internal code organization. --> <p><code>use</code> は識別子を短くするためだけに用いるのではありません。他のモジュール内の関数を再エクスポートするためにクレートの中で使うこともできます。これを使って内部のコード構成そのままではない外部向けインターフェースを提供できます。</p> <!-- Let’s look at an example. Modify your `src/main.rs` to read like this: --> <p>例を見てみましょう。 <code>src/main.rs</code> を以下のように変更します。</p> <span class='rusttest'>extern crate phrases; use phrases::english::{greetings,farewells}; use phrases::japanese; fn main() { println!(&quot;Hello in English: {}&quot;, greetings::hello()); println!(&quot;Goodbye in English: {}&quot;, farewells::goodbye()); println!(&quot;Hello in Japanese: {}&quot;, japanese::hello()); println!(&quot;Goodbye in Japanese: {}&quot;, japanese::goodbye()); } </span><pre class='rust rust-example-rendered'> <span class='kw'>extern</span> <span class='kw'>crate</span> <span class='ident'>phrases</span>; <span class='kw'>use</span> <span class='ident'>phrases</span>::<span class='ident'>english</span>::{<span class='ident'>greetings</span>,<span class='ident'>farewells</span>}; <span class='kw'>use</span> <span class='ident'>phrases</span>::<span class='ident'>japanese</span>; <span class='kw'>fn</span> <span class='ident'>main</span>() { <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;Hello in English: {}&quot;</span>, <span class='ident'>greetings</span>::<span class='ident'>hello</span>()); <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;Goodbye in English: {}&quot;</span>, <span class='ident'>farewells</span>::<span class='ident'>goodbye</span>()); <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;Hello in Japanese: {}&quot;</span>, <span class='ident'>japanese</span>::<span class='ident'>hello</span>()); <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;Goodbye in Japanese: {}&quot;</span>, <span class='ident'>japanese</span>::<span class='ident'>goodbye</span>()); }</pre> <!-- Then, modify your `src/lib.rs` to make the `japanese` mod public: --> <p>そして、 <code>src/lib.rs</code> の <code>japanese</code> モジュールをパブリックに変更します。</p> <span class='rusttest'>fn main() { pub mod english; pub mod japanese; }</span><pre class='rust rust-example-rendered'> <span class='kw'>pub</span> <span class='kw'>mod</span> <span class='ident'>english</span>; <span class='kw'>pub</span> <span class='kw'>mod</span> <span class='ident'>japanese</span>;</pre> <!-- Next, make the two functions public, first in `src/japanese/greetings.rs`: --> <p>続いて、2つの関数をパブリックにします。始めに <code>src/japanese/greetings.rs</code> を、</p> <span class='rusttest'>fn main() { pub fn hello() -&gt; String { &quot;こんにちは&quot;.to_string() } }</span><pre class='rust rust-example-rendered'> <span class='kw'>pub</span> <span class='kw'>fn</span> <span class='ident'>hello</span>() <span class='op'>-&gt;</span> <span class='ident'>String</span> { <span class='string'>&quot;こんにちは&quot;</span>.<span class='ident'>to_string</span>() }</pre> <!-- And then in `src/japanese/farewells.rs`: --> <p>そして <code>src/japanese/farewells.rs</code> を、</p> <span class='rusttest'>fn main() { pub fn goodbye() -&gt; String { &quot;さようなら&quot;.to_string() } }</span><pre class='rust rust-example-rendered'> <span class='kw'>pub</span> <span class='kw'>fn</span> <span class='ident'>goodbye</span>() <span class='op'>-&gt;</span> <span class='ident'>String</span> { <span class='string'>&quot;さようなら&quot;</span>.<span class='ident'>to_string</span>() }</pre> <!-- Finally, modify your `src/japanese/mod.rs` to read like this: --> <p>最後に、 <code>src/japanese/mod.rs</code> を以下のように変更します。</p> <span class='rusttest'>fn main() { pub use self::greetings::hello; pub use self::farewells::goodbye; mod greetings; mod farewells; }</span><pre class='rust rust-example-rendered'> <span class='kw'>pub</span> <span class='kw'>use</span> <span class='self'>self</span>::<span class='ident'>greetings</span>::<span class='ident'>hello</span>; <span class='kw'>pub</span> <span class='kw'>use</span> <span class='self'>self</span>::<span class='ident'>farewells</span>::<span class='ident'>goodbye</span>; <span class='kw'>mod</span> <span class='ident'>greetings</span>; <span class='kw'>mod</span> <span class='ident'>farewells</span>;</pre> <!-- The `pub use` declaration brings the function into scope at this part of our module hierarchy. Because we’ve `pub use`d this inside of our `japanese` module, we now have a `phrases::japanese::hello()` function and a `phrases::japanese::goodbye()` function, even though the code for them lives in `phrases::japanese::greetings::hello()` and `phrases::japanese::farewells::goodbye()`. Our internal organization doesn’t define our external interface. --> <p><code>pub use</code> 宣言は関数をモジュール階層 <code>phrases::japanese</code> のスコープへ持ち込みます。<code>japanese</code> モジュールの中で <code>pub use</code> したため、 <code>phrases::japanese::greetings::hello()</code> と <code>phrases::japanese::farewells::goodbye()</code> にコードがあるのにも関わらず、 <code>phrases::japanese::hello()</code> 関数と <code>phrases::japanese::goodbye()</code> 関数が使えるようになります。内部の構成で外部向けのインターフェースが決まるわけではありません。</p> <!-- Here we have a `pub use` for each function we want to bring into the `japanese` scope. We could alternatively use the wildcard syntax to include everything from `greetings` into the current scope: `pub use self::greetings::*`. --> <p><code>pub use</code> によって各関数を <code>japanese</code> スコープの中に持ち込めるようになりました。 <code>greetings</code> から現在のスコープへ全てをインクルードする代わりに、 <code>pub use self::greetings::*</code> とすることでワイルドカード構文が使えます。</p> <!-- What about the `self`? Well, by default, `use` declarations are absolute paths, starting from your crate root. `self` makes that path relative to your current place in the hierarchy instead. There’s one more special form of `use`: you can `use super::` to reach one level up the tree from your current location. Some people like to think of `self` as `.` and `super` as `..`, from many shells’ display for the current directory and the parent directory. --> <p><code>self</code> とはなんでしょう? ええっと、デフォルトでは、 <code>use</code> 宣言はクレートのルートから始まる絶対パスです。 <code>self</code> は代わりに現在位置からの相対パスにします。 <code>use</code> にはもう1つ特別な形式があり、現在位置から1つ上へのアクセスに <code>use super::</code> が使えます。多くのシェルにおけるカレントディレクトリと親ディレクトリの表示になぞらえ、 <code>.</code> が <code>self</code> で、 <code>..</code> が <code>super</code> であるという考え方を好む人もそれなりにいます。</p> <!-- Outside of `use`, paths are relative: `foo::bar()` refers to a function inside of `foo` relative to where we are. If that’s prefixed with `::`, as in `::foo::bar()`, it refers to a different `foo`, an absolute path from your crate root. --> <p><code>use</code> でなければ、パスは相対です。<code>foo::bar()</code> は私達のいる場所から相対的に <code>foo</code> の内側の関数を参照します。 <code>::foo::bar()</code> のように <code>::</code> から始まるのであれば、クレートのルートからの絶対パスで、先程とは異なる <code>foo</code> を参照します。</p> <!-- This will build and run: --> <p>これはビルドして実行できます。</p> <pre><code class="language-bash">$ cargo run Compiling phrases v0.0.1 (file:///home/you/projects/phrases) Running `target/debug/phrases` Hello in English: Hello! Goodbye in English: Goodbye. Hello in Japanese: こんにちは Goodbye in Japanese: さようなら </code></pre> <!-- ## Complex imports --> <h2 id='複合的なインポート' class='section-header'><a href='#複合的なインポート'>複合的なインポート</a></h2> <!-- Rust offers several advanced options that can add compactness and convenience to your `extern crate` and `use` statements. Here is an example: --> <p><code>extern crate</code> 及び <code>use</code> 文に対し、Rustは簡潔さと利便性を付加できる上級者向けオプションを幾つか提供しています。以下が例になります。</p> <span class='rusttest'>extern crate phrases as sayings; use sayings::japanese::greetings as ja_greetings; use sayings::japanese::farewells::*; use sayings::english::{self, greetings as en_greetings, farewells as en_farewells}; fn main() { println!(&quot;Hello in English; {}&quot;, en_greetings::hello()); println!(&quot;And in Japanese: {}&quot;, ja_greetings::hello()); println!(&quot;Goodbye in English: {}&quot;, english::farewells::goodbye()); println!(&quot;Again: {}&quot;, en_farewells::goodbye()); println!(&quot;And in Japanese: {}&quot;, goodbye()); } </span><pre class='rust rust-example-rendered'> <span class='kw'>extern</span> <span class='kw'>crate</span> <span class='ident'>phrases</span> <span class='kw'>as</span> <span class='ident'>sayings</span>; <span class='kw'>use</span> <span class='ident'>sayings</span>::<span class='ident'>japanese</span>::<span class='ident'>greetings</span> <span class='kw'>as</span> <span class='ident'>ja_greetings</span>; <span class='kw'>use</span> <span class='ident'>sayings</span>::<span class='ident'>japanese</span>::<span class='ident'>farewells</span>::<span class='op'>*</span>; <span class='kw'>use</span> <span class='ident'>sayings</span>::<span class='ident'>english</span>::{<span class='self'>self</span>, <span class='ident'>greetings</span> <span class='kw'>as</span> <span class='ident'>en_greetings</span>, <span class='ident'>farewells</span> <span class='kw'>as</span> <span class='ident'>en_farewells</span>}; <span class='kw'>fn</span> <span class='ident'>main</span>() { <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;Hello in English; {}&quot;</span>, <span class='ident'>en_greetings</span>::<span class='ident'>hello</span>()); <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;And in Japanese: {}&quot;</span>, <span class='ident'>ja_greetings</span>::<span class='ident'>hello</span>()); <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;Goodbye in English: {}&quot;</span>, <span class='ident'>english</span>::<span class='ident'>farewells</span>::<span class='ident'>goodbye</span>()); <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;Again: {}&quot;</span>, <span class='ident'>en_farewells</span>::<span class='ident'>goodbye</span>()); <span class='macro'>println</span><span class='macro'>!</span>(<span class='string'>&quot;And in Japanese: {}&quot;</span>, <span class='ident'>goodbye</span>()); }</pre> <!-- What's going on here? --> <p>何が起きているでしょう?</p> <!-- First, both `extern crate` and `use` allow renaming the thing that is being imported. So the crate is still called "phrases", but here we will refer to it as "sayings". Similarly, the first `use` statement pulls in the `japanese::greetings` module from the crate, but makes it available as `ja_greetings` as opposed to simply `greetings`. This can help to avoid ambiguity when importing similarly-named items from different places. --> <p>第一に、インポートされているものを <code>extern crate</code> と <code>use</code> 双方でリネームしています。そのため 「phrases」という名前のクレートであっても、ここでは「sayings」として参照することになります。同様に、始めの <code>use</code> 文はクレートから <code>japanese::greetings</code> を引き出していますが、単純な <code>greetings</code> ではなく <code>ja_greetings</code> で利用できるようにしています。これは異なる場所から同じ名前のアイテムをインポートする際、曖昧さを回避するのに役立ちます。</p> <!-- The second `use` statement uses a star glob to bring in _all_ symbols from the `sayings::japanese::farewells` module. As you can see we can later refer to the Japanese `goodbye` function with no module qualifiers. This kind of glob should be used sparingly. --> <p>第二の <code>use</code> 文では <code>sayings::japanese::farewells</code> モジュールから <em>全ての</em> シンボルを持ってくるためにスターグロブを使っています。ご覧の通り、最後にモジュールの修飾無しで日本語の <code>goodbye</code> 関数を参照できています。なお、この類のグロブは慎重に使うべきです。</p> <!-- The third `use` statement bears more explanation. It's using "brace expansion" globbing to compress three `use` statements into one (this sort of syntax may be familiar if you've written Linux shell scripts before). The uncompressed form of this statement would be: --> <p>第三の <code>use</code> 文はもっと詳しい説明が必要です。これは3つの <code>use</code> 文を1つに圧縮するグロブ「中括弧展開」を用いています(以前にLinuxのシェルスクリプトを書いたことがあるなら、この類の構文は慣れていることでしょう)。この文を展開した形式は以下のようになります。</p> <span class='rusttest'>fn main() { use sayings::english; use sayings::english::greetings as en_greetings; use sayings::english::farewells as en_farewells; }</span><pre class='rust rust-example-rendered'> <span class='kw'>use</span> <span class='ident'>sayings</span>::<span class='ident'>english</span>; <span class='kw'>use</span> <span class='ident'>sayings</span>::<span class='ident'>english</span>::<span class='ident'>greetings</span> <span class='kw'>as</span> <span class='ident'>en_greetings</span>; <span class='kw'>use</span> <span class='ident'>sayings</span>::<span class='ident'>english</span>::<span class='ident'>farewells</span> <span class='kw'>as</span> <span class='ident'>en_farewells</span>;</pre> <!-- As you can see, the curly brackets compress `use` statements for several items under the same path, and in this context `self` just refers back to that path. Note: The curly brackets cannot be nested or mixed with star globbing. --> <p>ご覧の通り、波括弧は同一パス下にある幾つかのアイテムに対する <code>use</code> 文を圧縮します。また、この文脈における <code>self</code> はパスの1つ手前を参照するだけです。(訳注: <code>sayings::english::{self}</code> の <code>self</code> が指す1つ手前は <code>sayings::english</code> です)注意: 波括弧はネストできず、スターグロブと混ぜるとこともできません。</p> <script type="text/javascript"> window.playgroundUrl = "https://play.rust-lang.org"; </script> <script src='rustbook.js'></script> <script src='playpen.js'></script> </div></div> </body> </html> <|start_filename|>docs/1.9/book/casting-between-types.html<|end_filename|> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="generator" content="rustdoc"> <title>型間のキャスト</title> <link rel="stylesheet" type="text/css" href="rustbook.css"> <meta name="robots" content="noindex"> </head> <body class="rustdoc"> <!--[if lte IE 8]> <div class="warning"> This old browser is unsupported and will most likely display funky things. </div> <![endif]--> <div id="nav"> <button id="toggle-nav"> <span class="sr-only">Toggle navigation</span> <span class="bar"></span> <span class="bar"></span> <span class="bar"></span> </button> </div> <div id='toc' class='mobile-hidden'> <ul class='chapter'> <li><a href='README.html'><b>1.</b> Introduction</a> </li> <li><a href='getting-started.html'><b>2.</b> はじめる</a> </li> <li><a href='guessing-game.html'><b>3.</b> チュートリアル:数当てゲーム</a> </li> <li><a href='syntax-and-semantics.html'><b>4.</b> シンタックスとセマンティクス</a> <ul class='section'> <li><a href='variable-bindings.html'><b>4.1.</b> 変数束縛</a> </li> <li><a href='functions.html'><b>4.2.</b> 関数</a> </li> <li><a href='primitive-types.html'><b>4.3.</b> プリミティブ型</a> </li> <li><a href='comments.html'><b>4.4.</b> コメント</a> </li> <li><a href='if.html'><b>4.5.</b> if</a> </li> <li><a href='loops.html'><b>4.6.</b> ループ</a> </li> <li><a href='vectors.html'><b>4.7.</b> ベクタ</a> </li> <li><a href='ownership.html'><b>4.8.</b> 所有権</a> </li> <li><a href='references-and-borrowing.html'><b>4.9.</b> 参照と借用</a> </li> <li><a href='lifetimes.html'><b>4.10.</b> ライフタイム</a> </li> <li><a href='mutability.html'><b>4.11.</b> ミュータビリティ</a> </li> <li><a href='structs.html'><b>4.12.</b> 構造体</a> </li> <li><a href='enums.html'><b>4.13.</b> 列挙型</a> </li> <li><a href='match.html'><b>4.14.</b> マッチ</a> </li> <li><a href='patterns.html'><b>4.15.</b> パターン</a> </li> <li><a href='method-syntax.html'><b>4.16.</b> メソッド構文</a> </li> <li><a href='strings.html'><b>4.17.</b> 文字列</a> </li> <li><a href='generics.html'><b>4.18.</b> ジェネリクス</a> </li> <li><a href='traits.html'><b>4.19.</b> トレイト</a> </li> <li><a href='drop.html'><b>4.20.</b> Drop</a> </li> <li><a href='if-let.html'><b>4.21.</b> if let</a> </li> <li><a href='trait-objects.html'><b>4.22.</b> トレイトオブジェクト</a> </li> <li><a href='closures.html'><b>4.23.</b> クロージャ</a> </li> <li><a href='ufcs.html'><b>4.24.</b> 共通の関数呼出構文</a> </li> <li><a href='crates-and-modules.html'><b>4.25.</b> クレートとモジュール</a> </li> <li><a href='const-and-static.html'><b>4.26.</b> `const` と `static`</a> </li> <li><a href='attributes.html'><b>4.27.</b> アトリビュート</a> </li> <li><a href='type-aliases.html'><b>4.28.</b> `type` エイリアス</a> </li> <li><a class='active' href='casting-between-types.html'><b>4.29.</b> 型間のキャスト</a> </li> <li><a href='associated-types.html'><b>4.30.</b> 関連型</a> </li> <li><a href='unsized-types.html'><b>4.31.</b> サイズ不定型</a> </li> <li><a href='operators-and-overloading.html'><b>4.32.</b> 演算子とオーバーロード</a> </li> <li><a href='deref-coercions.html'><b>4.33.</b> Derefによる型強制</a> </li> <li><a href='macros.html'><b>4.34.</b> マクロ</a> </li> <li><a href='raw-pointers.html'><b>4.35.</b> 生ポインタ</a> </li> <li><a href='unsafe.html'><b>4.36.</b> `unsafe`</a> </li> </ul> </li> <li><a href='effective-rust.html'><b>5.</b> Effective Rust</a> <ul class='section'> <li><a href='the-stack-and-the-heap.html'><b>5.1.</b> スタックとヒープ</a> </li> <li><a href='testing.html'><b>5.2.</b> テスト</a> </li> <li><a href='conditional-compilation.html'><b>5.3.</b> 条件付きコンパイル</a> </li> <li><a href='documentation.html'><b>5.4.</b> ドキュメント</a> </li> <li><a href='iterators.html'><b>5.5.</b> イテレータ</a> </li> <li><a href='concurrency.html'><b>5.6.</b> 並行性</a> </li> <li><a href='error-handling.html'><b>5.7.</b> エラーハンドリング</a> </li> <li><a href='choosing-your-guarantees.html'><b>5.8.</b> 保証を選ぶ</a> </li> <li><a href='ffi.html'><b>5.9.</b> 他言語関数インターフェース</a> </li> <li><a href='borrow-and-asref.html'><b>5.10.</b> BorrowとAsRef</a> </li> <li><a href='release-channels.html'><b>5.11.</b> リリースチャネル</a> </li> <li><a href='using-rust-without-the-standard-library.html'><b>5.12.</b> 標準ライブラリ無しでRustを使う</a> </li> </ul> </li> <li><a href='nightly-rust.html'><b>6.</b> Nightly Rust</a> <ul class='section'> <li><a href='compiler-plugins.html'><b>6.1.</b> コンパイラプラグイン</a> </li> <li><a href='inline-assembly.html'><b>6.2.</b> インラインアセンブリ</a> </li> <li><a href='no-stdlib.html'><b>6.3.</b> No stdlib</a> </li> <li><a href='intrinsics.html'><b>6.4.</b> Intrinsic</a> </li> <li><a href='lang-items.html'><b>6.5.</b> 言語アイテム</a> </li> <li><a href='advanced-linking.html'><b>6.6.</b> 高度なリンキング</a> </li> <li><a href='benchmark-tests.html'><b>6.7.</b> ベンチマークテスト</a> </li> <li><a href='box-syntax-and-patterns.html'><b>6.8.</b> Box構文とパターン</a> </li> <li><a href='slice-patterns.html'><b>6.9.</b> スライスパターン</a> </li> <li><a href='associated-constants.html'><b>6.10.</b> 関連定数</a> </li> <li><a href='custom-allocators.html'><b>6.11.</b> カスタムアロケータ</a> </li> </ul> </li> <li><a href='glossary.html'><b>7.</b> 用語集</a> </li> <li><a href='syntax-index.html'><b>8.</b> 構文の索引</a> </li> <li><a href='bibliography.html'><b>9.</b> 関係書目</a> </li> </ul> </div> <div id='page-wrapper'> <div id='page'> <blockquote class="header-caveat"> <p> <strong>注意: <a href="https://doc.rust-jp.rs/book-ja/">最新版のドキュメントをご覧ください。</a></strong>この第1版ドキュメントは古くなっており、最新情報が反映されていません。リンク先のドキュメントが現在の Rust の最新のドキュメントです。 </p> </blockquote> <h1 class="title">型間のキャスト</h1> <!-- % Casting Between Types --> <!-- Rust, with its focus on safety, provides two different ways of casting different types between each other. The first, `as`, is for safe casts. In contrast, `transmute` allows for arbitrary casting, and is one of the most dangerous features of Rust! --> <p>Rustは安全性に焦点を合わせており、異なる型の間を互いにキャストするために二つの異なる方法を提供しています。 一つは <code>as</code> であり、これは安全なキャストに使われます。 逆に <code>transmute</code> は任意のキャストに使え、Rustにおける最も危険なフィーチャの一つです!</p> <!-- # Coercion --> <h1 id='型強制' class='section-header'><a href='#型強制'>型強制</a></h1> <!-- Coercion between types is implicit and has no syntax of its own, but can be spelled out with [`as`](#explicit-coercions). --> <p>型強制は暗黙に行われ、それ自体に構文はありませんが、<a href="#%E6%98%8E%E7%A4%BA%E7%9A%84%E5%9E%8B%E5%BC%B7%E5%88%B6"><code>as</code></a> で書くこともできます。</p> <!-- Coercion occurs in `let`, `const`, and `static` statements; in function call arguments; in field values in struct initialization; and in a function result. --> <p>型強制が現れるのは、 <code>let</code> ・ <code>const</code> ・ <code>static</code> 文、関数呼び出しの引数、構造体初期化の際のフィールド値、そして関数の結果です。</p> <!-- The most common case of coercion is removing mutability from a reference: --> <p>一番よくある型強制は、参照からミュータビリティを取り除くものです。</p> <!-- * `&mut T` to `&T` --> <ul> <li><code>&amp;mut T</code> から <code>&amp;T</code> へ</li> </ul> <!-- An analogous conversion is to remove mutability from a [raw pointer](raw-pointers.html): --> <p>似たような変換としては、 <a href="raw-pointers.html">生ポインタ</a> からミュータビリティを取り除くものがあります。</p> <!-- * `*mut T` to `*const T` --> <ul> <li><code>*mut T</code> から <code>*const T</code> へ</li> </ul> <!-- References can also be coerced to raw pointers: --> <p>参照も同様に、生ポインタへ型強制できます。</p> <!-- * `&T` to `*const T` --> <ul> <li><code>&amp;T</code> から <code>*const T</code> へ</li> </ul> <!-- * `&mut T` to `*mut T` --> <ul> <li><code>&amp;mut T</code> から <code>*mut T</code> へ</li> </ul> <!-- Custom coercions may be defined using [`Deref`](deref-coercions.html). --> <p><a href="deref-coercions.html"><code>Deref</code></a> によって、カスタマイズされた型強制が定義されることもあります。</p> <!-- Coercion is transitive. --> <p>型強制は推移的です。</p> <!-- # `as` --> <h1 id='as' class='section-header'><a href='#as'><code>as</code></a></h1> <!-- The `as` keyword does safe casting: --> <p><code>as</code> というキーワードは安全なキャストを行います。</p> <span class='rusttest'>fn main() { let x: i32 = 5; let y = x as i64; }</span><pre class='rust rust-example-rendered'> <span class='kw'>let</span> <span class='ident'>x</span>: <span class='ident'>i32</span> <span class='op'>=</span> <span class='number'>5</span>; <span class='kw'>let</span> <span class='ident'>y</span> <span class='op'>=</span> <span class='ident'>x</span> <span class='kw'>as</span> <span class='ident'>i64</span>;</pre> <!-- There are three major categories of safe cast: explicit coercions, casts between numeric types, and pointer casts. --> <p>安全なキャストは大きく三つに分類されます。 明示的型強制、数値型間のキャスト、そして、ポインタキャストです。</p> <!-- Casting is not transitive: even if `e as U1 as U2` is a valid expression, `e as U2` is not necessarily so (in fact it will only be valid if `U1` coerces to `U2`). --> <p>キャストは推移的ではありません。 <code>e as U1 as U2</code> が正しい式であったとしても、 <code>e as U2</code> が必ずしも正しいとは限らないのです。 (実際、この式が正しくなるのは、 <code>U1</code> が <code>U2</code> へ型強制されるときのみです。)</p> <!-- ## Explicit coercions --> <h2 id='明示的型強制' class='section-header'><a href='#明示的型強制'>明示的型強制</a></h2> <!-- A cast `e as U` is valid if `e` has type `T` and `T` *coerces* to `U`. --> <p><code>e as U</code> というキャストは、 <code>e</code> が型 <code>T</code> を持ち、かつ <code>T</code> が <code>U</code> に <em>型強制</em> されるとき、有効です。</p> <!-- ## Numeric casts --> <h2 id='数値キャスト' class='section-header'><a href='#数値キャスト'>数値キャスト</a></h2> <!-- A cast `e as U` is also valid in any of the following cases: --> <p><code>e as U</code> というキャストは、以下のどの場合でも有効です。</p> <!-- * `e` has type `T` and `T` and `U` are any numeric types; *numeric-cast* --> <!-- * `e` is a C-like enum (with no data attached to the variants), and `U` is an integer type; *enum-cast* --> <!-- * `e` has type `bool` or `char` and `U` is an integer type; *prim-int-cast* --> <!-- * `e` has type `u8` and `U` is `char`; *u8-char-cast* --> <ul> <li><code>e</code> が型 <code>T</code> を持ち、 <code>T</code> と <code>U</code> が数値型であるとき; <em>numeric-cast</em></li> <li><code>e</code> が C-likeな列挙型であり(つまり、ヴァリアントがデータを持っておらず)、 <code>U</code> が整数型であるとき; <em>enum-cast</em></li> <li><code>e</code> の型が <code>bool</code> か <code>char</code> であり、 <code>U</code> が整数型であるとき; <em>prim-int-cast</em></li> <li><code>e</code> が型 <code>u8</code> を持ち、 <code>U</code> が <code>char</code> であるとき; <em>u8-char-cast</em></li> </ul> <!-- For example --> <p>例えば、</p> <span class='rusttest'>fn main() { let one = true as u8; let at_sign = 64 as char; let two_hundred = -56i8 as u8; }</span><pre class='rust rust-example-rendered'> <span class='kw'>let</span> <span class='ident'>one</span> <span class='op'>=</span> <span class='boolvalue'>true</span> <span class='kw'>as</span> <span class='ident'>u8</span>; <span class='kw'>let</span> <span class='ident'>at_sign</span> <span class='op'>=</span> <span class='number'>64</span> <span class='kw'>as</span> <span class='ident'>char</span>; <span class='kw'>let</span> <span class='ident'>two_hundred</span> <span class='op'>=</span> <span class='op'>-</span><span class='number'>56i8</span> <span class='kw'>as</span> <span class='ident'>u8</span>;</pre> <!-- The semantics of numeric casts are: --> <p>数値キャストのセマンティクスは以下の通りです。</p> <!-- * Casting between two integers of the same size (e.g. i32 -> u32) is a no-op * Casting from a larger integer to a smaller integer (e.g. u32 -> u8) will truncate * Casting from a smaller integer to a larger integer (e.g. u8 -> u32) will * zero-extend if the source is unsigned * sign-extend if the source is signed * Casting from a float to an integer will round the float towards zero * **[NOTE: currently this will cause Undefined Behavior if the rounded value cannot be represented by the target integer type][float-int]**. This includes Inf and NaN. This is a bug and will be fixed. * Casting from an integer to float will produce the floating point representation of the integer, rounded if necessary (rounding strategy unspecified) * Casting from an f32 to an f64 is perfect and lossless * Casting from an f64 to an f32 will produce the closest possible value (rounding strategy unspecified) * **[NOTE: currently this will cause Undefined Behavior if the value is finite but larger or smaller than the largest or smallest finite value representable by f32][float-float]**. This is a bug and will be fixed. --> <ul> <li>サイズの同じ二つの整数間のキャスト (例えば、i32 -&gt; u32) は何も行いません</li> <li>サイズの大きい整数から小さい整数へのキャスト (例えば、u32 -&gt; u8) では切り捨てを行います</li> <li>サイズの小さい整数から大きい整数へのキャスト (例えば、u8 -&gt; u32) では、 <ul> <li>元の整数が符号無しならば、ゼロ拡張を行います</li> <li>元の整数が符号付きならば、符号拡張を行います</li> </ul></li> <li>浮動小数点数から整数へのキャストでは、0方向への丸めを行います <ul> <li><strong><a href="https://github.com/rust-lang/rust/issues/10184">注意: 現在、丸められた値がキャスト先の整数型で扱えない場合、このキャストは未定義動作を引き起こします。</a></strong> これには Inf や NaN も含まれます。 これはバグであり、修正される予定です。</li> </ul></li> <li>整数から浮動小数点数へのキャストでは、必要に応じて丸めが行われて、その整数を表す浮動小数点数がつくられます (丸め戦略は指定されていません)</li> <li>f32 から f64 へのキャストは完全で精度は落ちません</li> <li>f64 から f32 へのキャストでは、表現できる最も近い値がつくられます (丸め戦略は指定されていません) <ul> <li><strong><a href="https://github.com/rust-lang/rust/issues/15536">注意: 現在、値が有限でありながらf32 で表現できる最大(最小)の有限値より大きい(小さい)場合、このキャストは未定義動作を引き起こします。</a></strong> これはバグであり、修正される予定です。</li> </ul></li> </ul> <!-- ## Pointer casts --> <h2 id='ポインタキャスト' class='section-header'><a href='#ポインタキャスト'>ポインタキャスト</a></h2> <!-- Perhaps surprisingly, it is safe to cast [raw pointers](raw-pointers.html) to and from integers, and to cast between pointers to different types subject to some constraints. It is only unsafe to dereference the pointer: --> <p>驚くかもしれませんが、いくつかの制約のもとで、 <a href="raw-pointers.html">生ポインタ</a> と整数の間のキャストや、ポインタと他の型の間のキャストは安全です。 安全でないのはポインタの参照外しだけなのです。</p> <span class='rusttest'>fn main() { // let a = 300 as *const char; // a pointer to location 300 let a = 300 as *const char; // 300番地へのポインタ let b = a as u32; }</span><pre class='rust rust-example-rendered'> <span class='kw'>let</span> <span class='ident'>a</span> <span class='op'>=</span> <span class='number'>300</span> <span class='kw'>as</span> <span class='op'>*</span><span class='kw'>const</span> <span class='ident'>char</span>; <span class='comment'>// 300番地へのポインタ</span> <span class='kw'>let</span> <span class='ident'>b</span> <span class='op'>=</span> <span class='ident'>a</span> <span class='kw'>as</span> <span class='ident'>u32</span>;</pre> <!-- `e as U` is a valid pointer cast in any of the following cases: --> <p><code>e as U</code> が正しいポインタキャストであるのは、以下の場合です。</p> <!-- * `e` has type `*T`, `U` has type `*U_0`, and either `U_0: Sized` or `unsize_kind(T) == unsize_kind(U_0)`; a *ptr-ptr-cast* --> <ul> <li><code>e</code> が型 <code>*T</code> を持ち、 <code>U</code> が <code>*U_0</code> であり、 <code>U_0: Sized</code> または <code>unsize_kind(T) == unsize_kind(U_0)</code> である場合; <em>ptr-ptr-cast</em></li> </ul> <!-- * `e` has type `*T` and `U` is a numeric type, while `T: Sized`; *ptr-addr-cast* --> <ul> <li><code>e</code> が型 <code>*T</code> を持ち、 <code>U</code> が数値型で、 <code>T: Sized</code> である場合; <em>ptr-addr-cast</em></li> </ul> <!-- * `e` is an integer and `U` is `*U_0`, while `U_0: Sized`; *addr-ptr-cast* --> <ul> <li><code>e</code> が整数、<code>U</code> が <code>*U_0</code> であり、 <code>U_0: Sized</code> である場合; <em>addr-ptr-cast</em></li> </ul> <!-- * `e` has type `&[T; n]` and `U` is `*const T`; *array-ptr-cast* --> <ul> <li><code>e</code> が型 <code>&amp;[T; n]</code> を持ち、 <code>U</code> が <code>*const T</code> である場合; <em>array-ptr-cast</em></li> </ul> <!-- * `e` is a function pointer type and `U` has type `*T`, while `T: Sized`; *fptr-ptr-cast* --> <ul> <li><code>e</code> が関数ポインタ型であり、 <code>U</code> が <code>*T</code> であって、<code>T: Sized</code> の場合; <em>fptr-ptr-cast</em></li> </ul> <!-- * `e` is a function pointer type and `U` is an integer; *fptr-addr-cast* --> <ul> <li><code>e</code> が関数ポインタ型であり、 <code>U</code> が整数型である場合; <em>fptr-addr-cast</em></li> </ul> <h1 id='transmute' class='section-header'><a href='#transmute'><code>transmute</code></a></h1> <!-- `as` only allows safe casting, and will for example reject an attempt to cast four bytes into a `u32`: --> <p><code>as</code> は安全なキャストしか許さず、例えば4つのバイト値を <code>u32</code> へキャストすることはできません。</p> <span class='rusttest'>fn main() { let a = [0u8, 0u8, 0u8, 0u8]; // let b = a as u32; // four eights makes 32 let b = a as u32; // 4つの8で32になる }</span><pre class='rust rust-example-rendered'> <span class='kw'>let</span> <span class='ident'>a</span> <span class='op'>=</span> [<span class='number'>0u8</span>, <span class='number'>0u8</span>, <span class='number'>0u8</span>, <span class='number'>0u8</span>]; <span class='kw'>let</span> <span class='ident'>b</span> <span class='op'>=</span> <span class='ident'>a</span> <span class='kw'>as</span> <span class='ident'>u32</span>; <span class='comment'>// 4つの8で32になる</span></pre> <!-- This errors with: --> <p>これは以下のようなメッセージがでて、エラーになります。</p> <!-- ```text error: non-scalar cast: `[u8; 4]` as `u32` let b = a as u32; // four eights makes 32 ^~~~~~~~ ``` --> <pre><code class="language-text">error: non-scalar cast: `[u8; 4]` as `u32` let b = a as u32; // 4つの8で32になる ^~~~~~~~ </code></pre> <!-- This is a ‘non-scalar cast’ because we have multiple values here: the four elements of the array. These kinds of casts are very dangerous, because they make assumptions about the way that multiple underlying structures are implemented. For this, we need something more dangerous. --> <p>これは「non-scalar cast」であり、複数の値、つまり配列の4つの要素、があることが原因です。 この種類のキャストはとても危険です。 なぜなら、複数の裏に隠れた構造がどう実装されているかについて仮定をおいているからです。 そのためもっと危険なものが必要になります。</p> <!-- The `transmute` function is provided by a [compiler intrinsic][intrinsics], and what it does is very simple, but very scary. It tells Rust to treat a value of one type as though it were another type. It does this regardless of the typechecking system, and just completely trusts you. --> <p><code>transmute</code> 関数は <a href="intrinsics.html">コンパイラ intrinsic</a> によって提供されており、やることはとてもシンプルながら、とても恐ろしいです。 この関数は、Rustに対し、ある型の値を他の型であるかのように扱うように伝えます。 これは型検査システムに関係なく行われ、完全に使用者頼みです。</p> <!-- In our previous example, we know that an array of four `u8`s represents a `u32` properly, and so we want to do the cast. Using `transmute` instead of `as`, Rust lets us: --> <p>先ほどの例では、4つの <code>u8</code> からなる配列が ちゃんと <code>u32</code> を表していることを知った上で、キャストを行おうとしました。 これは、<code>as</code> の代わりに <code>transmute</code> を使うことで、次のように書けます。</p> <span class='rusttest'>fn main() { use std::mem; unsafe { let a = [0u8, 0u8, 0u8, 0u8]; let b = mem::transmute::&lt;[u8; 4], u32&gt;(a); } }</span><pre class='rust rust-example-rendered'> <span class='kw'>use</span> <span class='ident'>std</span>::<span class='ident'>mem</span>; <span class='kw'>unsafe</span> { <span class='kw'>let</span> <span class='ident'>a</span> <span class='op'>=</span> [<span class='number'>0u8</span>, <span class='number'>0u8</span>, <span class='number'>0u8</span>, <span class='number'>0u8</span>]; <span class='kw'>let</span> <span class='ident'>b</span> <span class='op'>=</span> <span class='ident'>mem</span>::<span class='ident'>transmute</span>::<span class='op'>&lt;</span>[<span class='ident'>u8</span>; <span class='number'>4</span>], <span class='ident'>u32</span><span class='op'>&gt;</span>(<span class='ident'>a</span>); }</pre> <!-- We have to wrap the operation in an `unsafe` block for this to compile successfully. Technically, only the `mem::transmute` call itself needs to be in the block, but it's nice in this case to enclose everything related, so you know where to look. In this case, the details about `a` are also important, and so they're in the block. You'll see code in either style, sometimes the context is too far away, and wrapping all of the code in `unsafe` isn't a great idea. --> <p>コンパイルを成功させるために、この操作は <code>unsafe</code> ブロックでくるんであります。 技術的には、 <code>mem::transmute</code> の呼び出しのみをブロックに入れればいいのですが、今回はどこを見ればよいかわかるよう、関連するもの全部を囲んでいます。 この例では <code>a</code> に関する詳細も重要であるため、ブロックにいれてあります。 ただ、文脈が離れすぎているときは、こう書かないこともあるでしょう。 そういうときは、コード全体を <code>unsafe</code> でくるむことは良い考えではないのです。</p> <!-- While `transmute` does very little checking, it will at least make sure that the types are the same size. This errors: --> <p><code>transmute</code> はほとんどチェックを行わないのですが、最低限、型同士が同じサイズかの確認はします。 そのため、次の例はエラーになります。</p> <span class='rusttest'>fn main() { use std::mem; unsafe { let a = [0u8, 0u8, 0u8, 0u8]; let b = mem::transmute::&lt;[u8; 4], u64&gt;(a); } }</span><pre class='rust rust-example-rendered'> <span class='kw'>use</span> <span class='ident'>std</span>::<span class='ident'>mem</span>; <span class='kw'>unsafe</span> { <span class='kw'>let</span> <span class='ident'>a</span> <span class='op'>=</span> [<span class='number'>0u8</span>, <span class='number'>0u8</span>, <span class='number'>0u8</span>, <span class='number'>0u8</span>]; <span class='kw'>let</span> <span class='ident'>b</span> <span class='op'>=</span> <span class='ident'>mem</span>::<span class='ident'>transmute</span>::<span class='op'>&lt;</span>[<span class='ident'>u8</span>; <span class='number'>4</span>], <span class='ident'>u64</span><span class='op'>&gt;</span>(<span class='ident'>a</span>); }</pre> <!-- with: --> <p>エラーメッセージはこうです。</p> <pre><code class="language-text">error: transmute called with differently sized types: [u8; 4] (32 bits) to u64 (64 bits) </code></pre> <!-- Other than that, you're on your own! --> <p>ただそれ以外に関しては、自己責任です!</p> <script type="text/javascript"> window.playgroundUrl = "https://play.rust-lang.org"; </script> <script src='rustbook.js'></script> <script src='playpen.js'></script> </div></div> </body> </html>
tnakagawa/the-rust-programming-language-ja
<|start_filename|>hdr_db/include/gcm-aes/c-file/gfvec.h<|end_filename|> /* Copyright (c) 2011, <NAME> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // --------------------------------------------------------------------- // gfvec class // --------------------------------------------------------------------- #ifndef _GFVEC_H #define _GFVEC_H #include <stdint.h> #include <stdio.h> #include <deque> #include <exception> #include <string> #include "gcm_dpi.h" // define for print message #define NO_TYPE 0 #define NULL_TYPE 1 #define INFO 2 #define DEBUG 3 #define WARNING 4 #define ERROR 5 class gfvec { public: uint8_t d[16]; gfvec () {}; gfvec (uint8_t c) { for (int i=0; i<16; i++) d[i]=c; }; gfvec (const gfvec &init); uint8_t operator[](unsigned index); gfvec operator+ (const gfvec &y); gfvec operator* (gfvec &y); void init (const uint8_t c) { for (int i=0; i<16; i++) d[i]=c; }; void copy (const uint8_t c[]) { for (int i=0; i<16; i++) d[i]=c[i]; }; uint8_t *ptr () { return d; }; void print (); void print (char *t) { printf(t); print(); } void rightshift (); void add (uint32_t amount); char ref_msg [5000]; }; #endif <|start_filename|>hdr_db/include/pcap/pcap_dump.h<|end_filename|> /*! \file pcap_dump.h * Defines the pcap_vpi data structures and function calls. Proper sequence of calls is * to first call pcap_open() to create a dumper, repeatedly call * pcap_add_pkt() to add packets to the dumper, then call * pcap_shutdown() when finished. */ /* Copyright (c) 2011, <NAME> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef PCAP_DUMP_H_ #define PCAP_DUMP_H_ #include <stdint.h> #include <pcap.h> #define PCAP_DUMP_READ 1 #define PCAP_DUMP_WRITE 0 #if defined(__cplusplus) extern "C" { #endif /*! Dumper context * * Contains the pcap context used to start up as well as the * dumper file containing packets. */ typedef struct { pcap_t *ctx; pcap_dumper_t *dump; } pcap_handle_t; /*! Packet information structure * * Contains the packet data and length, as well as the transmission * time of the packet */ typedef struct { /// packet length int length; /// packet data uint8_t *pdata; /// tx time in seconds uint32_t sec; /// tx time in microseconds uint32_t usec; } packet_info_t; char errbuf[PCAP_ERRBUF_SIZE]; /*! \brief Open up a dumper * \return pcap_handle_t structure containing context and dumper */ pcap_handle_t pcap_open (char *filename, int bufsize, int open_type); /*! \brief Add a packet to an active dumper */ void pcap_add_pkt (pcap_dumper_t *dump, packet_info_t *p); /*! \brief Get a packet to an active dumper */ void pcap_get_pkt (pcap_t *ctx, packet_info_t *p); /*! \brief Shut down a dumper and close the pcap file */ void pcap_shutdown (pcap_handle_t *h); #if defined(__cplusplus) } #endif #endif /*PCAP_DUMP_H_*/ <|start_filename|>hdr_db/include/gcm-aes/c-file/gcm_dpi.cpp<|end_filename|> /*Copyright (c) 2011, <NAME> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // --------------------------------------------------------------------- // GCM-AES DPI Calls // --------------------------------------------------------------------- #include <stdio.h> #include <svdpi.h> #include "gfvec.h" #include "gcm.h" #include "gcm_dpi.h" #define NO_TYPE 0 #define NULL_TYPE 1 #define INFO 2 #define DEBUG 3 #define WARNING 4 #define ERROR 5 char c_msg[5000]; svScope g_scope; void print_msg (int msg_type, char* msg, int msg_len) { if (msg_len > 0) { // Commenting out as xrun gives error // g_scope = svGetScopeFromName("$unit"); // svSetScope(g_scope); // ::print_c_msg (msg_type, msg); } } // function to encrypt/decrypt and auth extern "C" void gcm_crypt (svBitVec32 *t_key, // 128 bit Key svBitVec32 *t_sci, // 64 bit Sci uint32_t t_pn, // 32 bit Pn int auth_only, // 1 -> auth _only , no encrypt/decrypt int auth_st, // Auth Start int auth_sz, // Auth Size int enc, // 1 -> encrypt, 0 -> decrypt int enc_sz, // Encrypt/decrypt Size svOpenArrayHandle in_pkt, // Original Pkt (without auth tag) svOpenArrayHandle out_pkt, // Output Pkt (Encrypt/decrypt + Auth Tag) int *out_plen) // Output Pkt Len ` { uint8_t key[16]; uint64_t sci; uint32_t pn; int i, ii, j, shift, wc, auth_rg; gcm g_inst; gfvec k, ptxt, ctxt; svBitVec32 *in_pkt_ptr; svBitVec32 *out_pkt_ptr; in_pkt_ptr = (svBitVec32*) svGetArrayPtr(in_pkt); out_pkt_ptr = (svBitVec32*) svGetArrayPtr(out_pkt); // copy key j = 0; for (i = 0; i < 16; i++) { shift = (i%4) * 8; key[15 - i] = (uint8_t) ((t_key[j] >> shift) & 0xFF); if (shift == 24) j++; } // copy sci sci = ((uint64_t) t_sci[0]) | ((uint64_t) t_sci[1]) << 32; // copy pn pn = (uint32_t) t_pn; // Set key to use for encryption k.copy (key); g_inst.set_key (k); // Initialize engine with nonce values g_inst.packet_init (sci, pn); if (auth_only == 1) auth_rg = auth_st + auth_sz + enc_sz; else auth_rg = auth_st + auth_sz; // print_msg(INFO, c_msg, sprintf(c_msg, "auth_only %0d auth_st %0d auth_sz %0d auth_rg %0d enc %0d enc_sz %0d \n", // auth_only, auth_st, auth_sz, auth_rg, enc, enc_sz)); // authentication for (i = 0; i < auth_rg; i++) { if (i >= auth_st) g_inst.add_auth (in_pkt_ptr[i]); out_pkt_ptr[i] = in_pkt_ptr[i]; // print_msg(INFO, c_msg, sprintf(c_msg, "i %0d in_pkt_ptr %x out pkt_ptr %x AUTH_LOOP\n", // i, in_pkt_ptr[i], out_pkt_ptr[i])); } wc = 0; ii = auth_rg; // Encryption if (auth_only == 0) { for (i = 0; i < enc_sz; i++) { ptxt.d[wc] = in_pkt_ptr[auth_rg + i]; wc++; // if we've reached a full 16 count, encrypt/decrypt the word, then copy out of // gfvec into the out packet array. if (wc == 16) { if (enc) g_inst.encrypt (ptxt, ctxt, 16); else g_inst.decrypt (ptxt, ctxt, 16); for (j = 0; j < 16; j++) { out_pkt_ptr[j + ii] = ctxt.d[j]; // print_msg(INFO, c_msg, sprintf(c_msg, "i %0d j+ii %0d in_pkt_ptr %x out pkt_ptr %x ENC_LOOP\n", // j+ii, in_pkt_ptr[j+ii], out_pkt_ptr[j+ii])); } wc = 0; ii += 16; } } // check to see if anything is left over to encrypt/decrypt. If so, encrypt/decrypt with // the remainder amount and // copy the result into the packet. if (wc != 0) { if (enc) g_inst.encrypt (ptxt, ctxt, wc); else g_inst.decrypt (ptxt, ctxt, wc); for (j = 0; j < wc; j++) { out_pkt_ptr[j + ii] = ctxt.d[j]; // print_msg(INFO, c_msg, sprintf(c_msg, "i %0d in_pkt_ptr %x out pkt_ptr %x ENC_LOOP1 \n", // j+ii, in_pkt_ptr[j+ii], out_pkt_ptr[j+ii])); } ii += wc; } } // insert the auth tag g_inst.get_tag (ctxt); for (i = 0; i < 16; i++) { out_pkt_ptr[i + ii] = ctxt.d[i]; // print_msg(INFO, c_msg, sprintf(c_msg, "i %0d in_pkt_ptr %x out pkt_ptr %x \n", // i+ii, in_pkt_ptr[i+ii], out_pkt_ptr[i+ii])); } ii += 16; out_plen[0] = ii; } // h-key calculation needed by API calls extern "C" void aes_hkey (svBitVec32 *t_key, // 127:0 svBitVec32 *t_in, // 127 :0 svOpenArrayHandle t_out) { svBitVec32 *tmp_out; uint8_t key[16], in[16], out[16]; int i, j, shift; tmp_out = (svBitVec32*) svGetArrayPtr(t_out); aes_encrypt_ctx acx[1]; j = 0; for (i = 0; i < 16; i++) { shift = (i%4) * 8; key[15-i] = (uint8_t) ((t_key[j] >> shift) & 0xFF); in [15-i] = (uint8_t) ((t_in [j] >> shift) & 0xFF); if (shift == 24) j++; } aes_encrypt_key (key, 16, acx); aes_encrypt (in, out, acx); for (int i = 0; i < 16; i++) { tmp_out[15-i] = out[i]; //print_msg(INFO, c_msg, sprintf(c_msg, "i %0d key %x in %x out %x tmp_out %x \n", i, key[i], in[i], out[i], tmp_out[i])); } } <|start_filename|>hdr_db/include/gcm-aes/c-file/gcm.h<|end_filename|> /* Copyright (c) 2011, <NAME> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ //---------------------------------------------------------------------- // GCM Encryption and Decryption //---------------------------------------------------------------------- #ifndef _GCM_H #define _GCM_H #include <stdint.h> #include <stdio.h> #include "gfvec.h" #include "aes.h" #include "gcm_dpi.h" // define for print message #define NO_TYPE 0 #define NULL_TYPE 1 #define INFO 2 #define DEBUG 3 #define WARNING 4 #define ERROR 5 /*! \brief GCM encrypt/decrypt class * * Basic class to provide a GCM encrypt/decrypt engine, and associated * context. Emphasizes simplicity over speed. Requires the gfvec classes * for input and output, as these allow certain vector math to be performed * on 128-bit sequences. * * Engine needs to be initialized once per key with set_key(), and once * per packet with packet_init(). auth_finalize() is optional, and will * automatically be called at the first encrypt() call. * * Engine operation is by calling add_auth() once for each byte of the * authorized material, and encrypt() once for each 16-byte word of the * encrypted material. The size parameter allows the engine to be called * with less than 16 bytes on the last word. The engine will automatically * pad the remainder data with 0. * * Once auth and encrypt are complete, the result can be retrieved with * get_tag(). */ class gcm { private: aes_encrypt_ctx acx[1]; gfvec counter; gfvec h, eky0; gfvec xi; int auth_ind; gfvec auth_acc; bool auth_done; int alen, plen; public: bool debug; gcm () { debug = false; }; void set_key (gfvec &key); void packet_init (uint64_t sci, uint32_t pn); void add_auth (uint8_t adata); void auth_finalize(); void encrypt (gfvec &p, gfvec &c, int size); void decrypt (gfvec &c, gfvec &p, int size); void get_tag (gfvec &tag); char ref_msg [5000]; }; #endif <|start_filename|>hdr_db/include/gcm-aes/c-file/gfvec.cpp<|end_filename|> /* Copyright (c) 2011, <NAME> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // --------------------------------------------------------------------- // gfvec class // --------------------------------------------------------------------- #include "gfvec.h" // bit index operator // bit 0 is MSB, bit 127 is LSB (IBM numbering) uint8_t gfvec::operator[](unsigned index) { return (d[index/8] >> (7 - (index % 8))) & 0x01; } gfvec::gfvec (const gfvec &init) { for (int i=0; i<16; i++) d[i] = init.d[i]; } void gfvec::print () { for (int i=0; i<16; i++) print_msg(NO_TYPE, ref_msg, sprintf(ref_msg, "%02x", d[i])); print_msg(NO_TYPE, ref_msg, sprintf(ref_msg, "\n")); } void gfvec::add (uint32_t amount) { uint32_t tmp = 0; for (int i=0; i<4; i++) tmp += d[15-i] << (8*i); tmp += amount; for (int i=0; i<4; i++) d[15-i] = (tmp >> (8*i)) & 0xFF; } void gfvec::rightshift () { uint8_t carry, tmp; carry = 0; for (int i=0; i<16; i++) { tmp = (d[i] >> 1) | (carry << 7); carry = d[i] & 0x01; d[i] = tmp; } } gfvec gfvec::operator+ (const gfvec &y) { gfvec z; for (int i=0; i<16; i++) z.d[i] = d[i] ^ y.d[i]; return z; } gfvec gfvec::operator* (gfvec &y) { gfvec z(0),r(0); uint8_t tmp; gfvec v; for (int i=0; i<16; i++) v.d[i] = d[i]; r.d[0] = 0xE1; for (int i=0; i<128; i++) { if (y[i]) z = z + v; tmp = v[127]; v.rightshift(); if (tmp) v = v + r; } return z; } <|start_filename|>hdr_db/include/gcm-aes/c-file/gcm.cpp<|end_filename|> /*Copyright (c) 2011, <NAME> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ //---------------------------------------------------------------------- // GCM Encryption and Decryption //---------------------------------------------------------------------- #include "gcm.h" /*! \brief Set key to use for encryption */ void gcm::set_key (gfvec &key) { uint8_t zero[16]; for (int i=0; i<16; i++) zero[i] = 0; aes_encrypt_key (key.ptr(), 16, acx); aes_encrypt (zero, h.ptr(), acx); print_msg(INFO, ref_msg, sprintf(ref_msg, "GCM : Key = ")); key.print(); print_msg(INFO, ref_msg, sprintf(ref_msg, "GCM : H = ")); h.print(); } /*! \brief Initialize engine with nonce values * * Called once per packet, initializes the engine with the 96-bit * nonce of SCI and packet number, and initializes the internal * 32-bit word counter to 0. */ void gcm::packet_init (uint64_t sci, uint32_t pn) { for (int i=0; i<8; i++) counter.d[i] = sci >> (8*(7-i)); for (int i=0; i<4; i++) { counter.d[i+8] = pn >> (8*(3-i)); counter.d[i+12] = 0; } counter.add(1); aes_encrypt (counter.ptr(), eky0.ptr(), acx); print_msg(INFO, ref_msg, sprintf(ref_msg, "GCM : SCI = %llx\n", sci)); print_msg(INFO, ref_msg, sprintf(ref_msg, "GCM : PN = %x\n", pn)); #ifndef NO_REF_DEBUG print_msg(DEBUG, ref_msg, sprintf(ref_msg, "GCM : EK0 = ")); eky0.print(); #endif // initialize the authorization index/buf auth_ind = 0; xi.init(0); auth_acc.init(0); auth_done = false; // initialize length counters alen = 0; plen = 0; } /*! \brief Add single byte of authorized material */ void gcm::add_auth (uint8_t adata) { auth_acc.d[auth_ind++] = adata; if (auth_ind == 16) { #ifdef AUTH_DEBUG print_msg(DEBUG, ref_msg, sprintf(ref_msg, "GCM : RA_HASH_GH = ")); xi.print(); #endif xi = xi + auth_acc; #ifdef AUTH_DEBUG print_msg(DEBUG, ref_msg, sprintf(ref_msg, "GCM : RA_HASH_ACC = ")); auth_acc.print(); #endif xi = xi * h; auth_ind = 0; #ifdef AUTH_DEBUG print_msg(DEBUG, ref_msg, sprintf(ref_msg, "GCM : RA_HASH_MUL = ")); xi.print(); #endif } alen++; } /*! \brief Explict call to end auth region (optional) */ void gcm::auth_finalize() { if (auth_ind) { while (auth_ind < 16) auth_acc.d[auth_ind++] = 0; #ifdef AUTH_DEBUG print_msg(DEBUG, ref_msg, sprintf(ref_msg, "GCM : RA_HASH_GH = ")); xi.print(); #endif xi = xi + auth_acc; #ifdef AUTH_DEBUG print_msg(DEBUG, ref_msg, sprintf(ref_msg, "GCM : RA_HASH_ACC = ")); auth_acc.print(); #endif xi = xi * h; #ifdef AUTH_DEBUG print_msg(DEBUG, ref_msg, sprintf(ref_msg, "GCM : RA_HASH_MUL = ")); xi.print(); #endif } auth_done = true; } /*! \brief Encrypt a single word * * "p" refers to plaintext, and "c" to ciphertext (input and output, * respectively). Size is the number of bytes of valid data in the * p-vector, and should be 16 for all words except the last one. */ void gcm::encrypt (gfvec &p, gfvec &c, int size) { gfvec eki, cauth; if (!auth_done) auth_finalize(); counter.add (1); aes_encrypt (counter.ptr(), eki.ptr(), acx); #ifndef NO_REF_DEBUG print_msg(DEBUG, ref_msg, sprintf(ref_msg, "GCM : AES ctr = ")); counter.print(); print_msg(DEBUG, ref_msg, sprintf(ref_msg, "GCM : AES outi = ")); eki.print(); #endif c = p + eki; cauth = c; if (size != 16) for (int i=size; i<16; i++) cauth.d[i] = 0; #ifdef AUTH_DEBUG print_msg(DEBUG, ref_msg, sprintf(ref_msg, "GCM : RA_HASH_GH = ")); xi.print(); #endif xi = xi + cauth; #ifdef AUTH_DEBUG print_msg(DEBUG, ref_msg, sprintf(ref_msg, "GCM : RA_HASH_ACC = ")); cauth.print(); #endif xi = xi * h; #ifdef AUTH_DEBUG print_msg(DEBUG, ref_msg, sprintf(ref_msg, "GCM : RE_HASH_MUL = ")); xi.print(); #endif plen += size; } /*! \brief Decrypt a single word * * "c" refers to ciphertext, "p" to plaintext (input and output, * respectively). Size is number of valid bytes, as per encrypt. */ void gcm::decrypt (gfvec &c, gfvec &p, int size) { gfvec eki, cauth; if (!auth_done) auth_finalize(); counter.add (1); aes_encrypt (counter.ptr(), eki.ptr(), acx); p = c + eki; cauth = c; if (size != 16) for (int i=size; i<16; i++) cauth.d[i] = 0; #ifdef AUTH_DEBUG print_msg(DEBUG, ref_msg, sprintf(ref_msg, "GCM : RA_HASH_GH = ")); xi.print(); #endif xi = xi + cauth; #ifdef AUTH_DEBUG print_msg(DEBUG, ref_msg, sprintf(ref_msg, "GCM : RA_HASH_ACC = ")); cauth.print(); #endif xi = xi * h; #ifdef AUTH_DEBUG print_msg(DEBUG, ref_msg, sprintf(ref_msg, "GCM : RE_HASH_MUL = ")); xi.print(); #endif plen += size; } /*! \brief Retrieve the authorization tag * * */ void gcm::get_tag (gfvec &tag) { gfvec length(0); if (!auth_done) auth_finalize(); // convert values from bytes to bits and stuff values into // length vector plen *= 8; alen *= 8; for (int i=0; i<4; i++) { length.d[i+4] = alen >> (8*(3-i)); length.d[i+12] = plen >> (8*(3-i)); } // multiply length value into ghash // add E(K,Y0) to get final tag value #ifdef AUTH_DEBUG print_msg(DEBUG, ref_msg, sprintf(ref_msg, "GCM : RA_HASH_ACC = ")); length.print(); #endif xi = xi + length; xi = xi * h; #ifdef AUTH_DEBUG print_msg(DEBUG, ref_msg, sprintf(ref_msg, "GCM : RE_HASH_MUL = ")); xi.print(); #endif tag = xi + eky0; #ifdef AUTH_DEBUG print_msg(DEBUG, ref_msg, sprintf(ref_msg, "GCM : RE_HASH_FIN = ")); tag.print(); #endif } <|start_filename|>hdr_db/include/pcap/pcap_dpi.c<|end_filename|> /*! \file pcap_dpi.c * Contains the DPI routines used to allocate pcap dumpers, dump individual * packets to a dumpfile, and shutdown afterwards. Default has a maximum * of 32 open dumpfiles for a simulation. */ /* Copyright (c) 2011, <NAME> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <stdio.h> #include <svdpi.h> #include "pcap_dump.h" #include <assert.h> #define MAX_OPEN_PCAP 64 #define PCAP_BUFSIZE 2048 #if defined(__cplusplus) extern "C" { #endif pcap_handle_t pcap_handle[MAX_OPEN_PCAP]; static int pcap_used; /*! \brief Register VPI routines with the simulator */ void pv_register () { int i; pcap_used = 0; for (i = 0; i < MAX_OPEN_PCAP; i++) { pcap_handle[i].ctx = NULL; pcap_handle[i].dump = NULL; } } /*! \brief Create a new dumper (port) * * Usage: pv_open (phandle, filename, filetype) * * Creates a single dumper file. phandle must be a integer or 32-bit * reg, filename should be a string. Filetype should be 0 for writing * and 1 for reading. The index of the newly created dumper in phandle * should be passed to future calls of pv_dump_packet() , pv_get_packet * and pv_shutdown(). */ void pv_open(int *phandle, char *pcap_file, int file_type) { phandle[0] = pcap_used; assert (phandle[0] < MAX_OPEN_PCAP); pcap_handle[phandle[0]] = pcap_open (pcap_file, PCAP_BUFSIZE, file_type); pcap_used++; } /*! \brief Dump a packet to an active dumper * * Usage: pv_dump_packet (phandle, len, pkt, stime); * * Takes a packet residing in buffer pkt of length len and stores it in * the dumper referenced by phandle. The packet is stored using the * current simulation time as its time. */ void pv_dump_pkt(int phandle, int pkt_len, svOpenArrayHandle pkt, svBitVec32 *nstime) // simulation time in ns { svBitVec32 *pkt_ptr; packet_info_t p; uint64_t ns_time; int i; pkt_ptr = (svBitVec32*) svGetArrayPtr(pkt); p.pdata = (uint8_t *) malloc (pkt_len); ns_time = ((uint64_t) nstime[0]) | ((uint64_t) nstime[1]) << 32; for (i = 0; i < pkt_len; i++) { p.pdata[i] = (uint8_t) pkt_ptr[i]; } p.length = pkt_len; p.usec = ns_time / 1000LL; p.sec = p.usec / 1000LL; assert (phandle < MAX_OPEN_PCAP); pcap_add_pkt (pcap_handle[phandle].dump, &p); } /*! \brief Get a packet from an active dumper * * Usage: pv_get_packet (phandle, len, pkt, nstime); * * Takes a next packet residing in an active dumper and stores it in * an array. The packet is stored using the current simulation time as its time. */ void pv_get_pkt(int phandle, int *pkt_len, svOpenArrayHandle pkt, svBitVec32 *nstime) // simulation time in ns { svBitVec32 *pkt_ptr; packet_info_t p; uint64_t ns_time; int i; pkt_ptr = (svBitVec32*) svGetArrayPtr(pkt); pcap_get_pkt (pcap_handle[phandle].ctx, &p); if (p.pdata != NULL) { pkt_len[0] = p.length; ns_time = (uint64_t) (p.usec * 1000LL); for (i = 0; i < pkt_len[0]; i++) { pkt_ptr[i] = p.pdata[i]; } nstime[0] = ns_time & 0XFFFFFFFF; nstime[1] = (ns_time << 32) & 0XFFFFFFFF; } else { pkt_len[0] = 0; nstime[0] = 0; nstime[1] = 0; pkt_ptr[0] = 0; } } /*! \brief Shutdown a dumper after use * * Usage: pv_shutdown (handle) * * Shut down the dumper and close the file once simulation is complete. * Handle should be value passed by the original pv_open() call. */ void pv_shutdown(int phandle) { assert (phandle < MAX_OPEN_PCAP); assert (pcap_handle[phandle].ctx != NULL); assert (pcap_handle[phandle].dump != NULL); pcap_shutdown (&pcap_handle[phandle]); } #if defined(__cplusplus) } #endif <|start_filename|>hdr_db/include/pcap/pcap_dump.c<|end_filename|> /* Copyright (c) 2011, <NAME> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <stdio.h> #include <stdlib.h> #include "pcap_dump.h" #include <assert.h> void pcap_add_pkt (pcap_dumper_t *dump, packet_info_t *p) { struct pcap_pkthdr hdr; hdr.ts.tv_sec = p->sec; hdr.ts.tv_usec = p->usec; hdr.caplen = p->length; hdr.len = p->length; pcap_dump ((u_char *) dump, &hdr, p->pdata); } void pcap_get_pkt (pcap_t *ctx, packet_info_t *p) { struct pcap_pkthdr hdr; p->pdata = (uint8_t *) pcap_next (ctx, &hdr); if (p->pdata != NULL) { p->sec = hdr.ts.tv_sec; p->usec = hdr.ts.tv_usec; p->length = hdr.caplen; } } pcap_handle_t pcap_open (char *filename, int bufsize, int open_type) { pcap_handle_t h; h.ctx = NULL; h.dump = NULL; if (open_type == PCAP_DUMP_WRITE) { h.ctx = pcap_open_dead (DLT_EN10MB, bufsize); h.dump = pcap_dump_open (h.ctx, filename); } else { h.ctx = pcap_open_offline (filename, errbuf); h.dump = NULL; } return h; } void pcap_shutdown (pcap_handle_t *h) { if (h->dump != NULL) pcap_dump_close (h->dump); pcap_close (h->ctx); }
baohuachen/System-Verilog-Packet-Library
<|start_filename|>courses_app/src/components/CourseDetail/courseDetailStyle.js<|end_filename|> import {StyleSheet} from 'react-native'; const styles = StyleSheet.create({ coursesListContainer: { flex: 1, backgroundColor: '#FFFFFF', }, bgContainer: { width: '100%', height: '30%', }, illustrationImage: { flex: 1, position: 'relative', borderRadius: 10, width: '100%', }, illustrationBackgroundStyle: { resizeMode: 'cover', position: 'absolute', top: 0, }, backButton: { position: 'absolute', top: 16, left: 16, backgroundColor: '#eee', height: 32, width: 32, borderRadius: 5, display: 'flex', alignItems: 'center', justifyContent: 'center', }, coursesListContent: { top: '25%', height: '100%', width: '100%', position: 'absolute', backgroundColor: '#fff', borderTopLeftRadius: 50, borderTopRightRadius: 50, paddingTop: 30, }, coursesListTitle: { marginLeft: 30, fontWeight: 'bold', fontSize: 16, marginBottom: 15, }, scrollViewContent: { paddingTop: 15, flex: 1, }, coursesListWrapper: { paddingHorizontal: 16, paddingBottom: 100, }, singleCourse: { backgroundColor: '#fff', shadowColor: '#000', shadowOffset: { width: 0, height: 1, }, shadowOpacity: 0.18, shadowRadius: 1.0, elevation: 1, paddingVertical: 7, marginBottom: 30, borderRadius: 5, paddingHorizontal: 7, display: 'flex', flexDirection: 'row', overflow: 'hidden', }, courseImage: { height: 90, width: 90, marginRight: 10, }, courseBackgroundStyle: { resizeMode: 'cover', position: 'absolute', top: 0, borderRadius: 5, }, playButton: { height: 30, width: 30, backgroundColor: '#fff', borderRadius: 50, display: 'flex', alignItems: 'center', justifyContent: 'center', top: '30%', left: '30%', }, courseRightContainer: {display: 'flex', width: '100%'}, bookmarkIcon: { marginLeft: '63%', }, courseInfo: { fontWeight: 'bold', width: '69%', marginBottom: 'auto', fontSize: 14, }, progressBarContainer: { backgroundColor: '#EEEDF4', height: 10, width: '69%', borderRadius: 20, }, progressBarItem: { backgroundColor: '#D9864E', height: 10, borderRadius: 20, }, sectionScrollContainer: { paddingHorizontal: 16, paddingBottom: 60, }, }); export default styles; <|start_filename|>job_finder_app/src/components/index.js<|end_filename|> export * from './Category'; export * from './Job'; <|start_filename|>furniture_shop/src/screens/ProductDetail/index.js<|end_filename|> import React, {useContext} from 'react'; import { View, Text, Image, TouchableOpacity, ScrollView, TextInput, KeyboardAvoidingView, } from 'react-native'; import MaterialCommunityIcons from 'react-native-vector-icons/MaterialCommunityIcons'; import MaterialIcons from 'react-native-vector-icons/MaterialIcons'; import Entypo from 'react-native-vector-icons/Entypo'; import styles from './productDetailStyle'; import {AuthContext} from '../../context'; export function ProductDetail({route, navigation}) { const {state, dispatch} = useContext(AuthContext); const furniture = route?.params; const handleBackButton = () => { navigation?.goBack(); }; const handleNoInCart = (type) => { dispatch({ type: 'addToCart', payload: {furniture, type}, }); }; const getProductNoInCart = () => { let quantity = 0; let product = state?.cart?.find((item) => item.id === furniture.id); if (product) { quantity = product?.noInCart; } return quantity; }; return ( <KeyboardAvoidingView style={styles.productDetailContainer}> <View style={styles.productDetailContent}> <View style={styles.productDetailHeader}> <TouchableOpacity style={styles.productDetailCircleContainer} onPress={() => handleBackButton()}> <MaterialIcons name="arrow-back-ios" size={18} color="#333333" /> </TouchableOpacity> <TouchableOpacity style={styles.productDetailCircleContainer}> <MaterialCommunityIcons name="cart-outline" size={20} color="#333333" /> <Text style={styles.noInCartText}>{state?.cart?.length}</Text> </TouchableOpacity> </View> <ScrollView showsVerticalScrollIndicator={false}> <View style={styles.productDetailSection}> <Image source={{uri: furniture?.image}} style={styles.productImage} /> <View style={styles.productDetailRow}> <View> <Text numberOfLines={1} ellipsizeMode="tail" style={styles.productDetailName}> {furniture?.name} </Text> <Text numberOfLines={2} ellipsizeMode="tail" style={styles.productDetailType}> {furniture?.type} </Text> </View> <Text style={styles.productDetailPrice}>${furniture?.price}</Text> </View> <Text style={styles.productTitleText}>Quantity</Text> <View style={styles.productQuantityRow}> <TouchableOpacity onPress={() => handleNoInCart('subtract')}> <Entypo name="minus" size={23} color="#000" /> </TouchableOpacity> <Text style={styles.productQuantityValue}> {getProductNoInCart()} </Text> <TouchableOpacity onPress={() => handleNoInCart('add')}> <Entypo name="plus" size={23} color="#000" /> </TouchableOpacity> </View> <Text style={styles.productTitleText}>Description</Text> <Text style={styles.productDescription}> {furniture?.description} </Text> </View> </ScrollView> <TouchableOpacity style={styles.addToCartBtn} onPress={() => handleNoInCart('add')}> <Entypo name="plus" size={25} color="#fff" /> <Text style={styles.addToCartText}>Add to cart</Text> </TouchableOpacity> </View> </KeyboardAvoidingView> ); } <|start_filename|>music_app_ui/src/utils/navigationHelper.js<|end_filename|> export const getScreenParent = (route) => { let parent; let isDrawerStack = route === 'Discover' || route === 'LatestMusic' || route === 'TopMusic' || route === 'Spotlight' || route === 'Genres' || route === 'Playlists' || route === 'Browse' || route === 'Purchased' || route === 'RecentlyPlayed' || route === 'MyPlaylists' || route === 'Favourites' || route === 'GetCredit' || route === 'BecomeAnArtist' || route === 'Upload'; let isSingleStack = route === 'Login' || route === 'SignUp' || route === 'MySongs' || route === 'MyAlbums'; if (isDrawerStack) { parent = 'DrawerStack'; } else if (isSingleStack) { parent = 'SingleStack'; } return parent; }; <|start_filename|>job_finder_app/src/screens/JobDetail/index.js<|end_filename|> import React, {useContext, useState} from 'react'; import {View, Text, TouchableOpacity, Image, ScrollView} from 'react-native'; import AntDesign from 'react-native-vector-icons/AntDesign'; import FontAwesome from 'react-native-vector-icons/FontAwesome'; import MaterialIcons from 'react-native-vector-icons/MaterialIcons'; import styles from './jobDetailStyle.js'; import {AuthContext} from '../../context'; export function JobDetail({route, navigation}) { const job = route?.params?.job; const {state, dispatch} = useContext(AuthContext); const [data, setData] = useState({ jobInfo: `Our team is composed of people from different cultures, backgrounds, knowledge and skills mingled and working together to build the best platform from scratch which makes it very exciting.\nYou will be working on a fun, energetic and a once-in-a-lifetime environment that will enable you to achieve your best possible outcome in your career`, jobResponsibility: `\u25CF Plan, prototype, scope and develop backend components. Requirements can vary significantly with the client, particular creative execution and technical requirements, but ultimately you will be responsible for backend components with each project. \n\u25CF Learn, champion, and build upon Medusa, our backend framework, to continually improve functionality and maintain reusable modules. \n\u25CF Manage cloud infrastructure on GCP. Implement reliable auto-scaling solutions. Monitor server resources and usage. \n\u25CF Support live events and ensure servers are running smoothly, load tested, and optimized for expected traffic.`, }); const isBookmarked = () => { let value; let bookmarkedJobs = state?.bookmarks; value = bookmarkedJobs?.find( (bookmarkedJob) => bookmarkedJob.id === job.id, ); return value; }; const handleBackButton = () => { navigation?.goBack(); }; return ( <View style={styles.jobDetailContainer}> <View style={styles.jobDetailContent}> <View style={styles.jobDetailHeader}> <TouchableOpacity style={styles.jobDetailCircleContainer} onPress={() => handleBackButton()}> <AntDesign name="arrowleft" size={22} color="#333333" /> </TouchableOpacity> <TouchableOpacity style={styles.jobDetailCircleContainer}> {isBookmarked() ? ( <FontAwesome name="bookmark" color="#49AC5A" size={20} /> ) : ( <FontAwesome name="bookmark-o" color="#ccc" size={20} /> )} </TouchableOpacity> </View> <View style={styles.jobDetaiRow1}> <Image source={{uri: job?.company?.logo}} style={styles.jobImage} /> <Text style={styles.jobCompany} numberOfLines={1} ellipsizeMode="tail"> {job?.company?.name} </Text> <Text style={styles.jobRole} numberOfLines={1} ellipsizeMode="tail"> {job?.role} </Text> <View style={styles.flexRow}> <Text style={styles.jobSalary} numberOfLines={1} ellipsizeMode="tail"> {job?.salary} | </Text> <Text style={styles.jobLocation} numberOfLines={1} ellipsizeMode="tail"> {job?.location} </Text> </View> </View> <ScrollView showsVerticalScrollIndicator={false}> <View style={styles.jobDetailSection}> <Text style={styles.heading}>Job description</Text> <Text style={styles.jobInfoText}>{data?.jobInfo}</Text> <Text style={styles.heading}>Responsibilities</Text> <Text style={styles.jobInfoText}>{data?.jobResponsibility}</Text> </View> </ScrollView> <View style={styles.bottomWrapper}> <TouchableOpacity style={styles.applyHereBtn}> <Text style={styles.applyHereText}>Apply here</Text> <MaterialIcons name="double-arrow" color="#fff" size={20} /> </TouchableOpacity> </View> </View> </View> ); } <|start_filename|>furniture_shop/src/screens/index.js<|end_filename|> export * from './Home'; export * from './ProductDetail'; <|start_filename|>job_finder_app/src/screens/JobDetail/jobDetailStyle.js<|end_filename|> import {StyleSheet} from 'react-native'; const styles = StyleSheet.create({ jobDetailContainer: { flex: 1, backgroundColor: '#FFFFFF', }, jobDetailContent: { height: '100%', padding: 16, paddingBottom: 0, position: 'relative', }, jobDetailHeader: { display: 'flex', flexDirection: 'row', justifyContent: 'space-between', }, jobDetailCircleContainer: { backgroundColor: '#fafafa', height: 50, width: 50, borderRadius: 50, display: 'flex', alignItems: 'center', justifyContent: 'center', position: 'relative', }, jobDetaiRow1: { display: 'flex', alignItems: 'center', marginBottom: 50, }, jobImage: { height: 100, width: 100, resizeMode: 'contain', }, jobCompany: { opacity: 0.4, fontSize: 16, fontWeight: 'bold', }, jobRole: { fontWeight: 'bold', fontSize: 18, opacity: 0.8, }, flexRow: { display: 'flex', flexDirection: 'row', alignItems: 'center', }, jobSalary: { fontSize: 14, opacity: 0.4, fontWeight: 'bold', }, jobLocation: { fontSize: 14, marginLeft: 5, opacity: 0.4, fontWeight: 'bold', }, jobDetailSection:{ paddingBottom: 80 }, heading: { fontWeight: 'bold', fontSize: 15.5, opacity: 0.9, marginBottom: 10, }, jobInfoText: { lineHeight: 20, opacity: 0.6, fontSize: 14, marginBottom: 40, }, bottomWrapper: { position: 'absolute', bottom: 10, marginLeft: '5%', width: '100%', display: 'flex', alignItems: 'center', }, applyHereBtn: { backgroundColor: '#49AC5A', display: 'flex', flexDirection: 'row', paddingVertical: 15, paddingHorizontal: 30, borderRadius: 10, }, applyHereText: { color: '#fff', marginRight: 10, fontSize: 15, fontWeight: 'bold', }, }); export default styles; <|start_filename|>job_finder_app/src/navigators/Stack.js<|end_filename|> import React from 'react'; import {createStackNavigator} from '@react-navigation/stack'; import {createBottomTabNavigator} from '@react-navigation/bottom-tabs'; import Ionicons from 'react-native-vector-icons/Ionicons'; import Foundation from 'react-native-vector-icons/Foundation'; import MaterialCommunityIcons from 'react-native-vector-icons/MaterialCommunityIcons'; import { Home, JobDetail, Bookmarks, Settings, Notifications, Messages, } from '../screens'; const Stack = createStackNavigator(); const Tab = createBottomTabNavigator(); const TabStack = () => { return ( <Tab.Navigator initialRouteName="Home"> <Tab.Screen name="Home" component={Home} options={{ tabBarIcon: ({focused, tintColor}) => ( <Foundation name="home" color={focused ? '#49AC5A' : '#ccc'} size={24} /> ), tabBarLabel: () => { return null; }, }} /> <Tab.Screen name="Bookmarks" component={Bookmarks} options={{ tabBarIcon: ({focused, tintColor}) => ( <Ionicons name="ios-bookmarks" color={focused ? '#49AC5A' : '#ccc'} size={20} /> ), tabBarLabel: () => { return null; }, }} /> <Tab.Screen name="Messages" component={Messages} options={{ tabBarIcon: ({focused, tintColor}) => ( <MaterialCommunityIcons name="message-text" color={focused ? '#49AC5A' : '#ccc'} size={24} /> ), tabBarLabel: () => { return null; }, }} /> <Tab.Screen name="Notifications" component={Notifications} options={{ tabBarIcon: ({focused, tintColor}) => ( <Ionicons name="ios-notifications" color={focused ? '#49AC5A' : '#ccc'} size={24} /> ), tabBarLabel: () => { return null; }, }} /> <Tab.Screen name="Settings" component={Settings} options={{ tabBarIcon: ({focused, tintColor}) => ( <Ionicons name="settings-sharp" color={focused ? '#49AC5A' : '#ccc'} size={24} /> ), tabBarLabel: () => { return null; }, }} /> </Tab.Navigator> ); }; const NavStack = () => { return ( <Stack.Navigator initialRouteName="JobDetail"> <Stack.Screen name="JobDetail" component={JobDetail} options={{ headerShown: false, }} /> </Stack.Navigator> ); }; const AppStack = () => { return ( <Stack.Navigator initialRouteName="TabStack"> <Stack.Screen name="TabStack" component={TabStack} options={{headerShown: false}} /> <Stack.Screen name="NavStack" component={NavStack} options={{headerShown: false}} /> </Stack.Navigator> ); }; export default AppStack; <|start_filename|>job_finder_app/src/components/Job/index.js<|end_filename|> import React, {useContext} from 'react'; import {View, Text, Image, TouchableOpacity} from 'react-native'; import FontAwesome from 'react-native-vector-icons/FontAwesome'; import styles from './jobStyle.js'; import {AuthContext} from '../../context'; import {handleNestedNavigation} from '../../navigators/NavigatorHandler'; import {getScreenParent} from '../../utils/navigationHelper'; export function Job({job, navigation}) { const {state, dispatch} = useContext(AuthContext); const isBookmarked = () => { let value; let bookmarkedJobs = state?.bookmarks; value = bookmarkedJobs?.find( (bookmarkedJob) => bookmarkedJob.id === job.id, ); return value; }; const handleNavigation = (route, params) => { handleNestedNavigation(navigation, getScreenParent(route), route, params); }; return ( <TouchableOpacity style={styles.jobContainer} onPress={() => handleNavigation('JobDetail', {job})}> <Image source={{uri: job?.company?.logo}} style={styles.jobImage} /> <View style={styles.jobInfo}> <Text style={styles.jobCompany} numberOfLines={1} ellipsizeMode="tail"> {job?.company?.name} </Text> <Text style={styles.jobRole} numberOfLines={1} ellipsizeMode="tail"> {job?.role} </Text> <View style={styles.flexRow}> <Text style={styles.jobSalary} numberOfLines={1} ellipsizeMode="tail"> {job?.salary} | </Text> <Text style={styles.jobLocation} numberOfLines={1} ellipsizeMode="tail"> {job?.location} </Text> </View> </View> {isBookmarked() ? ( <FontAwesome name="bookmark" color="#ccc" size={20} /> ) : ( <FontAwesome name="bookmark-o" color="#ccc" size={20} /> )} </TouchableOpacity> ); } <|start_filename|>furniture_shop/src/components/NewProduct/index.js<|end_filename|> import React from 'react'; import {View, Text, Image, TouchableOpacity} from 'react-native'; import styles from './newProductStyle.js'; export function NewProduct({furniture, onNavigate}) { return ( <View style={styles.furnitureContainer}> <TouchableOpacity onPress={() => onNavigate('ProductDetail', furniture)} style={styles.furnitureImageWrapper}> <Image source={{uri: furniture?.image}} style={styles.furnitureImage} /> </TouchableOpacity> <Text numberOfLines={1} ellipsizeMode="tail" style={styles.furnitureName}> {furniture?.name} </Text> </View> ); } <|start_filename|>job_finder_app/src/components/Category/index.js<|end_filename|> import React from 'react'; import {Text, Image, TouchableOpacity} from 'react-native'; import styles from './categoryStyle.js'; export function Category({category}) { return ( <TouchableOpacity style={styles.categoryContainer}> <Image source={{uri: category?.image}} style={styles.categoryImage} /> <Text style={styles.categoryTitle} numberOfLines={1} ellipsizeMode="tail"> {category?.title} </Text> <Text style={styles.categoryNoOfJobs} numberOfLines={1} ellipsizeMode="tail"> {category?.noOfJobs} Jobs </Text> </TouchableOpacity> ); } <|start_filename|>job_finder_app/src/navigators/NavigatorHandler.js<|end_filename|> export const handleScreenNavigation = (navigation, route, params) => { navigation?.navigate(route, { params, }); }; export const handleScreenReplace = (navigation, route, params) => { navigation?.replace(route, { params, }); }; export const handleNestedNavigation = (navigation, parent, route, params) => { navigation?.navigate(parent, {screen: route, params}); }; export const handleNestedReplace = (navigation, parent, route, params) => { navigation?.replace(parent, {screen: route, params}); }; export const handleScreenBack = (navigation) => { navigation?.goBack(); }; export const handleRemoveScreen = (navigation) => { navigation?.pop(); }; <|start_filename|>job_finder_app/src/context/index.js<|end_filename|> import React, {createContext} from 'react'; export const AuthContext = createContext({}); <|start_filename|>courses_app/src/store/reducer/appReducer.js<|end_filename|> import initialState from '../state'; export const appReducer = (state = initialState, action) => { switch (action.type) { case 'addBookmark': { const courseDetail = action?.payload?.courseDetail; let courses = state?.courses; courses = courses.map((course) => { if (course.id === courseDetail.id) { let isBookmarked = course.isBookmarked ? false : true; course.isBookmarked = isBookmarked; } return course; }); return { ...state, courses, }; } default: return state; } }; <|start_filename|>courses_app/src/screens/Home/index.js<|end_filename|> import React, {useState, useContext} from 'react'; import { View, Text, TextInput, TouchableOpacity, ScrollView, ImageBackground, Image, } from 'react-native'; import shortid from 'shortid'; import Ionicons from 'react-native-vector-icons/Ionicons'; import MaterialIcons from 'react-native-vector-icons/MaterialIcons'; import styles from './homeStyle.js'; import FriesMenu from '../../assets/icons/FriesMenu.png'; import ProfilePhoto from '../../assets/photos/photo-1494790108377-be9c29b29330.jpg'; import {getIllustration, getBackground} from '../../utils'; import {AuthContext} from '../../context'; const categories = [ { id: 0, title: 'UX Design', number: 36, isTrendy: false, isBestRated: true, }, { id: 1, title: 'Photoshop', number: 22, isTrendy: true, isBestRated: true, }, { id: 2, title: 'Illustrator', number: 40, isTrendy: true, isBestRated: false, }, { id: 3, title: 'Development', number: 55, isTrendy: true, isBestRated: true, }, ]; export function Home({navigation}) { const {state, dispatch} = useContext(AuthContext); const [data, setData] = useState({ tabs: ['New', 'Trendy', 'Best rated'], activeTab: 'New', displayedCategories: categories, }); const handleTabPress = (tab, index) => { let {activeTab, displayedCategories} = data; activeTab = tab; if (index === 0) { displayedCategories = categories; } else if (index === 1) { displayedCategories = categories?.filter((category) => category.isTrendy); } else if (index === 2) { displayedCategories = categories?.filter( (category) => category.isBestRated, ); } setData({...data, activeTab, displayedCategories}); }; const handleNavigation = (route, params) => { navigation?.navigate('SingleStack', {screen: route, params}); }; const handleDrawer = () => { navigation?.openDrawer(); }; return ( <View style={styles.homeContainer}> <View style={styles.homeContent}> <TouchableOpacity style={styles.headerContainer} onPress={() => handleDrawer()}> <Image source={FriesMenu} /> <Image source={ProfilePhoto} style={styles.profilePhotoImage} /> </TouchableOpacity> <View style={styles.nameContainer}> <Text style={styles.nameText}>Hi</Text> <Text style={styles.usernameText}>{state?.username}</Text> </View> <Text style={styles.learnText}>Learn new Skills today!</Text> <View style={styles.searchContainer}> <Ionicons name="search" size={23} color="#808080" /> <TextInput placeholder="Search for a course" style={styles.searchInput} /> <TouchableOpacity style={styles.dropdownContainer}> <MaterialIcons name="keyboard-arrow-down" size={23} color="#808080" /> </TouchableOpacity> </View> <View style={styles.tabHeaderContainer}> {data?.tabs?.map((tab, index) => ( <TouchableOpacity key={shortid.generate()} style={styles.singleTab} onPress={() => handleTabPress(tab, index)}> <Text style={[ styles.tabText, data?.activeTab === tab ? styles.activeTabText : styles.inActiveTabText, ]}> {tab} </Text> {data?.activeTab === tab ? ( <View style={styles.activeTabBottom}></View> ) : null} </TouchableOpacity> ))} </View> <ScrollView style={styles.scrollViewContent} showsVerticalScrollIndicator={false}> <View style={styles.tabBodyContainer}> {data?.displayedCategories?.map((category, index) => ( <TouchableOpacity key={shortid.generate()} style={[ styles.categoryContainer, index % 2 ? styles.categoryLongHeight : styles.categoryShortHeight, getBackground(category?.id), ]} onPress={() => handleNavigation('CoursesList', category)}> <ImageBackground source={getIllustration(category?.id)} style={styles.illustrationImage} imageStyle={styles.backgroundStyle}> <View style={styles.transparentBg}> <Text style={styles.categoryTitletext}> {category?.title} </Text> <Text style={styles.categoryNumbertext}> {category?.number} </Text> </View> </ImageBackground> </TouchableOpacity> ))} </View> </ScrollView> </View> </View> ); } <|start_filename|>courses_app/src/components/index.js<|end_filename|> export * from './CourseDetail'; <|start_filename|>courses_app/src/screens/CoursesList/index.js<|end_filename|> import React, {useContext} from 'react'; import { View, Text, ImageBackground, TouchableOpacity, FlatList, } from 'react-native'; import MaterialIcons from 'react-native-vector-icons/MaterialIcons'; import shortid from 'shortid'; import styles from './coursesListStyle'; import {getIllustration, getBackground} from '../../utils'; import {AuthContext} from '../../context'; import {CourseDetail} from '../../components'; export function CoursesList({route, navigation}) { const course = route?.params; const {state, dispatch} = useContext(AuthContext); const handleBackButton = () => { navigation?.goBack(); }; const renderCourseList = ({item}) => { return <CourseDetail courseDetail={item} />; }; return ( <View style={styles.coursesListContainer}> <View style={[styles.bgContainer, getBackground(course?.id)]}> <ImageBackground source={getIllustration(course?.id)} style={styles.illustrationImage} imageStyle={styles.illustrationBackgroundStyle}> <TouchableOpacity style={styles.backButton} onPress={() => handleBackButton()}> <MaterialIcons name="keyboard-arrow-left" size={25} color="#000" /> </TouchableOpacity> </ImageBackground> </View> <View style={styles.coursesListContent}> <Text style={styles.coursesListTitle}> {course?.title} Courses List </Text> <FlatList data={state?.courses} keyExtractor={() => shortid.generate()} renderItem={renderCourseList} horizontal={false} showsVerticalScrollIndicator={false} contentContainerStyle={styles.sectionScrollContainer} /> </View> </View> ); } <|start_filename|>courses_app/src/store/state.js<|end_filename|> export default state = { username: 'Georgina', courses: [ { id: 0, title: 'User Experience Design Essentials - Adobe XD UI UX Design', noOfVideos: 15, isBookmarked: false, progress: 50, image: 'https://img-b.udemycdn.com/course/240x135/1452908_8741_3.jpg?secure=Ouz6FGhhMcvM-DxnZI7Ypw%3D%3D%2C1613718529', }, { id: 1, title: 'Visual Elements of User Interface Design', noOfVideos: 15, isBookmarked: true, progress: 2, image: 'https://d3njjcbhbojbot.cloudfront.net/api/utilities/v1/imageproxy/https://s3.amazonaws.com/coursera-course-photos/e6/8f0440758611e8bbc5cde522cfff09/visual_logo_03c.jpg?auto=format%2Ccompress&dpr=1&w=150&h=150&fit=fill&bg=FFF', }, { id: 2, title: 'The Complete App Design Course - UX, UI and Design Thinking', noOfVideos: 15, isBookmarked: false, progress: 35, image: 'https://img-a.udemycdn.com/course/240x135/1184844_3714.jpg?i6ftYwRPt0FNVa5r-SkRaxizOGD6WLcDVBiLVdT4XGiuNbMr5qDD_y1-nXrAbZhwj8-Q4B43IDH4AxHLkoVoY9oUkElAkVgqIgKk5lL7K_MkxqHiIh315Vi3GRw', }, { id: 3, title: 'UX Design & User Experience Design Course - Theory Only', noOfVideos: 15, isBookmarked: true, progress: 20, image: 'https://img-a.udemycdn.com/course/240x135/968750_196b_6.jpg?QBgvG-ZoSjOThkobl2t4WHS6OVfX3c9UU9AzAezj5i0DLzMybVxiFY23YXjHmB8cCTNHJTnyJgnQMB-rc7H582JgPVhvH9BddXaYKGjP-B1EQzQWs7aQK3BH7bU0', }, { id: 4, title: 'UX & Web Design Master Course: Strategy, Design, Development', noOfVideos: 15, isBookmarked: true, progress: 70, image: 'https://img-a.udemycdn.com/course/240x135/412738_4543.jpg?hNGPWazJ6nwA3l_-C8qUzWbmkLyJ4-ywLpAn7QM2wa6TYAxXkVezUH7viVADRLGIZ0eMgDPw5s2w7FbsXaiBQ3QDTnqRfyy0NNMjPn271BjWnClQe7acRON_Cw', }, { id: 5, title: 'Introduction to User Experience Principles and Processes', noOfVideos: 15, isBookmarked: true, progress: 90, image: 'https://d3njjcbhbojbot.cloudfront.net/api/utilities/v1/imageproxy/https://s3.amazonaws.com/coursera-course-photos/7d/3e5fa0cd6911e88090493dce122db5/ux_micromasters_course_1_1x1.png?auto=format%2Ccompress&dpr=1&w=150&h=150&fit=fill&bg=FFF', }, { id: 6, title: 'Introduction To UI/UX - UI/UX Design', video: 15, isBookmarked: true, progress: 35, image: 'https://d20vwa69zln1wj.cloudfront.net/d2f7a286386dd081444a3b1cf32d23e2/main/46c10942d92d31cb5f19979d1b75123d-20201215.jpg', }, { id: 7, title: 'UI/UX for Chatbot & Voice Interface AIs - UI/UX Design', video: 15, isBookmarked: true, progress: 84, image: 'https://d20vwa69zln1wj.cloudfront.net/d2f7a286386dd081444a3b1cf32d23e2/main/31a6922fd58ea57cd57a4b9aa31252fc-20201215.jpg', }, ], }; <|start_filename|>job_finder_app/src/store/reducer/appReducer.js<|end_filename|> import initialState from '../state'; export const appReducer = (state = initialState, action) => { switch (action.type) { case 'addBookmark': { const jobDetail = action?.payload?.jobDetail; let jobs = state?.jobs; jobs = jobs.map((job) => { if (job.id === jobDetail.id) { let isBookmarked = job.isBookmarked ? false : true; job.isBookmarked = isBookmarked; } return job; }); return { ...state, jobs, }; } default: return state; } }; <|start_filename|>job_finder_app/src/store/reducer/index.js<|end_filename|> import {appReducer} from './appReducer'; const reduceReducers = (...reducers) => (prevState, value, ...args) => reducers.reduce( (newState, reducer) => reducer(newState, value, ...args), prevState, ); export default reduceReducers(appReducer); <|start_filename|>music_app_ui/src/navigators/Stack.js<|end_filename|> import React from 'react'; import {Text} from 'react-native'; import {createDrawerNavigator} from '@react-navigation/drawer'; import {createStackNavigator} from '@react-navigation/stack'; import MaterialCommunityIcons from 'react-native-vector-icons/MaterialCommunityIcons'; import {Upload, Track} from '../screens'; const Stack = createStackNavigator(); const Drawer = createDrawerNavigator(); const DrawerStack = () => { return ( <Drawer.Navigator initialRouteName="Upload" drawerStyle={{backgroundColor: '#222225'}} drawerContentOptions={{ activeTintColor: '#e91e63', }}> <Drawer.Screen name="Upload" component={Upload} options={{ drawerLabel: ({focused, color}) => ( <Text style={{color: '#fff'}}>Upload</Text> ), drawerIcon: ({focused, size}) => ( <MaterialCommunityIcons name="transfer-up" size={20} color={focused ? '#fff' : '#ccc'} /> ), }} /> </Drawer.Navigator> ); }; const SingleStack = () => { return ( <Stack.Navigator> <Stack.Screen name="Track" component={Track} options={{headerShown: false}} /> </Stack.Navigator> ); }; function AppStack() { return ( <Stack.Navigator initialRouteName="DrawerStack"> <Stack.Screen name="DrawerStack" component={DrawerStack} options={{headerShown: false}} /> <Stack.Screen name="SingleStack" component={SingleStack} options={{headerShown: false}} /> </Stack.Navigator> ); } export default AppStack; <|start_filename|>job_finder_app/src/utils/navigationHelper.js<|end_filename|> export const getScreenParent = (route) => { let parent; let isNavStack = route === 'JobDetail'; let isTabStack = route === 'Home' || route === 'Bookmarks'; if (isNavStack) { parent = 'NavStack'; } else if (isTabStack) { parent = 'TabStack'; } return parent; }; <|start_filename|>music_app_ui/src/components/CustomText/index.js<|end_filename|> import React from 'react'; import {View, Text, StyleSheet} from 'react-native'; export function CustomText({type, text, size, style}) { return ( <Text style={[type === 1 ? styles.colorOne : styles.colorTwo, style]} numberOfLines={1} ellipsizeMode="tail"> {text} </Text> ); } const styles = StyleSheet.create({ colorOne: { color: '#c3c3c6', }, colorTwo: { color: '#8d8d8d', }, }); <|start_filename|>music_app_ui/src/components/NavDrawerHeader/index.js<|end_filename|> import React, {useContext} from 'react'; import {View, TouchableOpacity, Image, Text} from 'react-native'; import Ionicons from 'react-native-vector-icons/Ionicons'; import MaterialCommunityIcons from 'react-native-vector-icons/MaterialCommunityIcons'; import { Menu, MenuOptions, MenuOption, MenuTrigger, } from 'react-native-popup-menu'; import styles from './navDrawerHeaderStyle'; import NavIcon from '../../assets/menu-icon.png'; import Logo from '../../assets/logo.png'; import {getScreenParent} from '../../utils/navigationHelper'; import {navigateToNestedRoute} from '../../navigators/RootNavigation'; export function NavDrawerHeader({navigation}) { const handleToggleNavDrawer = () => { navigation?.openDrawer(); }; const handleNavigation = (route) => { navigateToNestedRoute(getScreenParent(route), route); }; return ( <View style={styles.navHeader}> <TouchableOpacity onPress={() => handleToggleNavDrawer()}> <Image source={NavIcon} style={styles.navIconImage} /> </TouchableOpacity> <View style={styles.logoContainer}> <Image source={Logo} style={styles.logoImage} /> </View> <View style={styles.controlIcons}> <Ionicons name="search" size={23} color="#ebebeb" /> <Menu> <MenuTrigger> <MaterialCommunityIcons name="account-circle" size={23} color="#ebebeb" style={{marginLeft: 15}} /> </MenuTrigger> <MenuOptions> <MenuOption> <Text style={styles.menuOptionText}>Login</Text> </MenuOption> <MenuOption> <Text style={styles.menuOptionText}>Sign Up</Text> </MenuOption> </MenuOptions> </Menu> </View> </View> ); } <|start_filename|>music_app_ui/src/screens/Upload/uploadStyle.js<|end_filename|> import {StyleSheet} from 'react-native'; const styles = StyleSheet.create({ uploadContainer: { flex: 1, backgroundColor: '#000', }, scrollViewContent: { height: '100%', padding: 16, }, uploadContent: { marginBottom: 50, padding: 16, }, layoutContent: { display: 'flex', }, uploadSingleSongText: { fontSize: 20, }, iconWrapper: { backgroundColor: '#00bcd4', height: 70, width: 70, borderRadius: 50, display: 'flex', justifyContent: 'center', alignItems: 'center', marginBottom: 40, }, singleCard: { display: 'flex', justifyContent: 'center', alignItems: 'center', backgroundColor: '#222225', height: 280, marginTop: 40, borderRadius: 5, }, }); export default styles; <|start_filename|>furniture_shop/src/screens/Home/homeStyle.js<|end_filename|> import {StyleSheet} from 'react-native'; const styles = StyleSheet.create({ homeContainer: { flex: 1, backgroundColor: '#fafafa', }, homeContent: { height: '100%', padding: 16, }, homeHeader: { display: 'flex', flexDirection: 'row', justifyContent: 'space-between', marginBottom: 40, }, homeHeaderCircleContainer: { backgroundColor: '#fff', height: 50, width: 50, borderRadius: 50, display: 'flex', alignItems: 'center', justifyContent: 'center', position: 'relative', }, noInCartText: { position: 'absolute', top: 2, right: 14, fontSize: 20, color: '#B48B49', fontWeight:"bold" }, nameContainer: { display: 'flex', flexDirection: 'row', marginBottom: 3, }, greetingText: { fontSize: 16, opacity: 0.4, fontWeight: 'bold', marginBottom: 5, }, chooseText: { fontWeight: 'bold', fontSize: 18, opacity: 0.8, marginBottom: 30, }, searchContainer: { height: 40, width: '100%', backgroundColor: '#FEFEFE', borderRadius: 20, display: 'flex', flexDirection: 'row', alignItems: 'center', borderWidth: 1, borderColor: '#FBFBFB', shadowColor: '#000', shadowOffset: { width: 0, height: 1, }, shadowOpacity: 0.18, shadowRadius: 1.0, elevation: 1, padding: 7, marginBottom: 20, }, searchInput: { width: '100%', height: 40, fontSize: 15, }, scrollViewContent: { paddingBottom: 40, paddingTop: 20, }, productsContainer: { display: 'flex', }, section: { display: 'flex', marginBottom: 50, }, sectionHeader: { display: 'flex', flexDirection: 'row', justifyContent: 'space-between', marginBottom: 20, }, sectionHeaderText: { color: '#000', textTransform: 'uppercase', fontWeight: 'bold', fontSize: 16, }, sectionHeaderLeft: { display: 'flex', flexDirection: 'row', alignItems: 'center', }, sectionHeaderLeftText: { color: '#a7a7a7', marginRight: 5, }, sectionScrollContainer: { display: 'flex', flexDirection: 'row', justifyContent: 'space-between', paddingVertical: 5, paddingHorizontal: 1, }, sectionContent: { paddingTop: 15, display: 'flex', flexDirection: 'row', width: '100%', }, }); export default styles; <|start_filename|>music_app_ui/src/components/index.js<|end_filename|> export * from './NavDrawerHeader'; export * from './CustomText'; <|start_filename|>furniture_shop/src/components/FeaturedProduct/featuredProductStyle.js<|end_filename|> import {StyleSheet, Dimensions} from 'react-native'; const styles = StyleSheet.create({ furnitureContainer: { backgroundColor: '#fff', borderRadius: 5, width: Dimensions.get('window').width / 2.5, padding: 10, shadowColor: '#000', shadowOffset: { width: 0, height: 0.5, }, shadowOpacity: 0, shadowRadius: 0.5, elevation: 2, marginRight: Dimensions.get('window').width / 10, display: 'flex', justifyContent: 'center', alignItems: 'center', }, furnitureImage: { height: 100, width: 100, marginBottom: 5, }, furnitureName: { width: '100%', fontWeight: 'bold', opacity: 0.8, }, furnitureType: { width: '100%', opacity: 0.5, marginBottom: 10, fontSize: 13, }, furnitureBottomRow: { display: 'flex', flexDirection: 'row', justifyContent: 'space-between', width: '100%', alignItems: 'center', }, furniturePrice: { opacity: 0.7, fontSize: 13 }, addToCartBtn: { backgroundColor: '#B48B49', padding: 5, borderRadius: 50, }, }); export default styles; <|start_filename|>music_app_ui/src/navigators/RootNavigation.js<|end_filename|> import {createRef} from 'react'; export const isReadyRef = createRef(); export const navigationRef = createRef(); export function navigate(parent, params) { navigationRef.current?.navigate(parent, params); } export function navigateToNestedRoute(parent, route, params) { navigationRef.current?.navigate(parent, {screen: route, params}); } export function goBack() { navigationRef.current?.goBack(); } <|start_filename|>music_app_ui/src/App.js<|end_filename|> import React from 'react'; import {SafeAreaView, StatusBar, StyleSheet} from 'react-native'; import {NavigationContainer} from '@react-navigation/native'; import {MenuProvider} from 'react-native-popup-menu'; import AppStack from './navigators/Stack'; import {navigationRef, isReadyRef} from './navigators/RootNavigation'; const App = () => { return ( <MenuProvider> <StatusBar barStyle="dark-content" /> <SafeAreaView style={styles.areaContainer}> <NavigationContainer ref={navigationRef}> <AppStack /> </NavigationContainer> </SafeAreaView> </MenuProvider> ); }; const styles = StyleSheet.create({ areaContainer: { flex: 1, }, }); export default App; <|start_filename|>job_finder_app/src/App.js<|end_filename|> import React, {useReducer} from 'react'; import {SafeAreaView, StyleSheet, StatusBar} from 'react-native'; import {NavigationContainer} from '@react-navigation/native'; import AppStack from './navigators/Stack'; import initialState from './store/state'; import reducer from './store/reducer'; import {AuthContext} from './context'; const App = () => { const [state, dispatch] = useReducer(reducer, initialState); return ( <AuthContext.Provider value={{ state, dispatch, }}> <StatusBar barStyle="dark-content" /> <SafeAreaView style={styles.areaContainer}> <NavigationContainer> <AppStack /> </NavigationContainer> </SafeAreaView> </AuthContext.Provider> ); }; const styles = StyleSheet.create({ areaContainer: { flex: 1, }, }); export default App; <|start_filename|>job_finder_app/src/screens/Home/index.js<|end_filename|> import React, {useState, useContext} from 'react'; import { View, Text, KeyboardAvoidingView, Image, TextInput, TouchableOpacity, ScrollView, FlatList, } from 'react-native'; import Ionicons from 'react-native-vector-icons/Ionicons'; import shortid from 'shortid'; import styles from './homeStyle.js'; import {AuthContext} from '../../context'; import {Category, Job} from '../../components'; export function Home({navigation}) { const {state, dispatch} = useContext(AuthContext); const [data, setData] = useState({ username: 'Shola', photo: 'https://images.pexels.com/photos/1987301/pexels-photo-1987301.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500', }); const renderCategory = ({item}) => { return <Category category={item} />; }; const renderJob = ({item}) => { return ( <Job job={item} navigation={navigation} /> ); }; return ( <KeyboardAvoidingView style={styles.homeContainer}> <View style={styles.homeContent}> <View style={styles.homeHeader}> <View> <Text style={styles.usernameText}>What's up {data?.username}</Text> <Text style={styles.findJobText}>Find your perfect job</Text> </View> <View style={styles.profilePicWrapper}> <Image source={{uri: data?.photo}} style={styles.profilePic} /> </View> </View> <View style={styles.searchContainer}> <TextInput placeholder="Search" style={styles.searchInput} /> <TouchableOpacity style={styles.searchButton}> <Ionicons name="shuffle" size={25} color="#fff" /> </TouchableOpacity> </View> {/* <FlatList style={styles.scrollViewContent} showsVerticalScrollIndicator={false}> */} <View style={styles.container}> <View style={styles.section}> <Text style={styles.heading}>Interesting categories</Text> <FlatList data={state?.categories} keyExtractor={(item, index) => shortid.generate()} renderItem={renderCategory} horizontal={true} contentContainerStyle={styles.sectionScrollContainer} showsHorizontalScrollIndicator={false} /> </View> <View style={styles.section}> <Text style={styles.heading}>Jobs for you</Text> <FlatList data={state?.jobs} keyExtractor={(item, index) => shortid.generate()} renderItem={renderJob} horizontal={false} contentContainerStyle={styles.sectionScrollContainer} showsHorizontalScrollIndicator={false} /> </View> </View> {/* </FlatList> */} </View> </KeyboardAvoidingView> ); } <|start_filename|>courses_app/src/screens/index.js<|end_filename|> export * from './Home'; export * from './CoursesList'; <|start_filename|>furniture_shop/src/screens/ProductDetail/productDetailStyle.js<|end_filename|> import {StyleSheet, Dimensions} from 'react-native'; const styles = StyleSheet.create({ productDetailContainer: { flex: 1, backgroundColor: '#fff', }, productDetailContent: { height: '100%', padding: 16, position: 'relative', }, productDetailHeader: { display: 'flex', flexDirection: 'row', justifyContent: 'space-between', marginBottom: 30, }, productDetailCircleContainer: { backgroundColor: '#fafafa', height: 50, width: 50, borderRadius: 50, display: 'flex', alignItems: 'center', justifyContent: 'center', position: 'relative', }, noInCartText: { position: 'absolute', top: 2, right: 14, fontSize: 20, color: '#B48B49', fontWeight: 'bold', zIndex: 10 }, productDetailSection: { paddingBottom: 50, }, addToCartBtn: { display: 'flex', alignItems: 'center', justifyContent: 'center', flexDirection: 'row', backgroundColor: '#AF8845', borderRadius: 30, paddingVertical: 10, position: 'absolute', bottom: 10, width: '100%', left: '5%', }, addToCartText: { color: '#fff', fontSize: 18, marginLeft: 10, }, productImage: { height: 220, width: '100%', resizeMode: 'contain', marginBottom: 30, }, productDetailRow: { display: 'flex', alignItems: 'center', justifyContent: 'space-between', flexDirection: 'row', marginBottom: 30, }, productDetailName: { width: '100%', fontWeight: 'bold', opacity: 0.8, fontSize: 18, }, productDetailType: { width: '100%', opacity: 0.5, marginBottom: 10, fontSize: 14, }, productDetailPrice: { opacity: 0.7, fontSize: 17, }, productTitleText: { fontSize: 15, marginBottom: 5, }, productQuantityRow: { display: 'flex', alignItems: 'center', flexDirection: 'row', marginBottom: 15, }, productQuantityValue: { fontSize: 18, borderColor: '#f4f4f4', borderWidth: 1, borderRadius: 15, textAlign: 'center', marginHorizontal: 5, paddingVertical: 6, paddingHorizontal: 18, display: 'flex', flexDirection: 'row', alignItems: 'center', }, productDescription: { opacity: 0.6, fontSize: 13, lineHeight: 18 }, }); export default styles; <|start_filename|>music_app_ui/src/screens/Upload/index.js<|end_filename|> import * as React from 'react'; import {View, TouchableOpacity, ScrollView} from 'react-native'; import MaterialIcons from 'react-native-vector-icons/MaterialIcons'; import styles from './uploadStyle.js'; import {CustomText} from '../../components'; import {NavDrawerHeader} from '../../components'; export function Upload({navigation}) { return ( <View style={styles.uploadContainer}> <NavDrawerHeader navigation={navigation} /> <ScrollView style={styles.scrollViewContent}> <View style={styles.layoutContent}> <TouchableOpacity style={styles.singleCard}> <View style={styles.iconWrapper}> <MaterialIcons name="music-note" color="#fff" size={30} /> </View> <CustomText type={1} text="Upload single song" style={styles.uploadSingleSongText} /> </TouchableOpacity> <TouchableOpacity style={styles.singleCard}> <View style={styles.iconWrapper}> <MaterialIcons name="library-music" color="#fff" size={30} /> </View> <CustomText type={1} text="Upload an album" style={styles.uploadSingleSongText} /> </TouchableOpacity> </View> </ScrollView> </View> ); } <|start_filename|>courses_app/src/components/CourseDetail/index.js<|end_filename|> import React, {useContext} from 'react'; import {View, Text, ImageBackground, TouchableOpacity} from 'react-native'; import MaterialIcons from 'react-native-vector-icons/MaterialIcons'; import styles from './courseDetailStyle'; import {AuthContext} from '../../context'; export function CourseDetail({courseDetail}) { const {state, dispatch} = useContext(AuthContext); const handleBookmark = () => { dispatch({ type: 'addBookmark', payload: {courseDetail}, }); }; return ( <View style={styles.singleCourse}> <ImageBackground source={{ uri: courseDetail?.image, }} style={styles.courseImage} imageStyle={styles.courseBackgroundStyle}> <TouchableOpacity style={styles.playButton}> <MaterialIcons name="play-arrow" size={25} color="#000" /> </TouchableOpacity> </ImageBackground> <View style={styles.courseRightContainer}> <TouchableOpacity onPress={() => handleBookmark()}> {courseDetail?.isBookmarked ? ( <MaterialIcons name="bookmark" size={20} color="#292929" style={styles.bookmarkIcon} /> ) : ( <MaterialIcons name="bookmark-border" size={20} color="#292929" style={styles.bookmarkIcon} /> )} </TouchableOpacity> <Text>{courseDetail?.noOfVideos} videos</Text> <Text numberOfLines={1} ellipsizeMode="tail" style={styles.courseInfo}> {courseDetail?.title} </Text> <View style={styles.progressBarContainer}> <View style={[ styles.progressBarItem, {width: `${courseDetail?.progress}%`}, ]}></View> </View> </View> </View> ); } <|start_filename|>furniture_shop/src/store/state.js<|end_filename|> export default state = { cart: [], featuredProducts: [ { id: 'A233334', name: 'Velvet Dining Side', price: 183.99, image: 'https://secure.img1-fg.wfcdn.com/im/56707838/resize-h700-w700%5Ecompr-r85/9261/92611790/Amsterdam+Velvet+Upholstered+Arm+Chair.jpg', description: 'This armchair - your daily dose of timeless elegance -Love being the hostess with the most? These chairs are some of the most stylish reasons to have yet another gathering or dinner party. Understated flair - It’s love at first sight with the task chair for many customers. And it’s easy to see why. Its smooth velvet upholstery makes the perfect accompaniment to good food and great company while its gorgeously gilded chrome legs lend just the right touch of opulence without being over the top. Frankly, it makes revamping or renovating your dining room/kitchen so effortless. ', quantity: 4, type: 'Chair', }, { id: 'B128765', name: 'Carone Tufted Velvet Upholstered Side Chair in Blue (Set of 4)', price: 559.99, image: 'https://secure.img1-fg.wfcdn.com/im/94703666/resize-h700-w700%5Ecompr-r85/1299/129943423/Carone+Tufted+Velvet+Upholstered+Side+Chair+in+Blue.jpg', description: 'Glamorous with subtle traditional elements, this upholstered dining chair is perfect for contemporary dining rooms. Each chair features a stainless steel base and classic nspired legs with a gleaming, shiny chrome finish. A channel-tufted backrest with a rolled top and plush velvet fabric adds a luxurious touch.', quantity: 3, type: 'Chair', }, { id: 'C095621', name: 'Schacht Upholstered Dining Chair (Set of 2)', price: 449.99, image: 'https://secure.img1-fg.wfcdn.com/im/43082320/resize-h700-w700%5Ecompr-r85/9592/95924905/Schacht+Upholstered+Dining+Chair.jpg', description: 'Includes: Two (2) Side Chairs. Upholstered in velvet fabric. Legs are made of stainless steel. Back frame is tufted. Medium firm seating. Seat Height 20. Seat Depth 18. Contemporary and Transitional Style. Fully assembled dimension 19"L x 25"D x 36"H.', quantity: 3, type: 'Dining set', }, ], newProducts: [ { id: 'A103765', name: '<NAME>', price: 173.99, image: 'https://secure.img1-fg.wfcdn.com/im/02789782/resize-h700-w700%5Ecompr-r85/7975/79758618/Gillett+Coffee+Table.jpg', description: 'The clean-lined contemporary design gets an industrial upgrade in this coffee table. Crafted of solid wood in a gently-distressed stain for a reclaimed look, this coffee table strikes a two-tiered rectangular silhouette on four black iron legs. The open lower shelf is perfect for stacking coffee table books or fanning out issues of your favorite magazines, while the tabletop provides a perfect platform for displaying trays of appetizers and drinks and your next get-together.', quantity: 4, type: 'Table', }, { id: 'E765432', name: 'Currahee 72" Double Bathroom Vanity Set', price: 1349.99, image: 'https://secure.img1-fg.wfcdn.com/im/97610588/resize-h700-w700%5Ecompr-r85/1367/136705443/Currahee+72%2522+Double+Bathroom+Vanity+Set.jpg', description: `Clean lines and plenty of drawer space make this classic double bathroom vanity the perfect piece for your bathroom or guest bath. It's 72" wide, the ideal size for sharing, and it's made from solid poplar wood in a neutral finish. The surface is crafted from stone in a carrara white color that complements your contemporary decor. And the two included undermount sinks with a rectangular silhouette are made from ceramic. Its six drawer fronts come with handles in a shiny finish, and they open up to reveal space for washcloths, toothpaste, and hair ties. And the four matching doors with sleek square knobs hide extra shelf space for hair dryers and bath towels. Plus, this bathroom vanity comes with a backsplash to help protect your walls.`, quantity: 4, type: 'Table', }, { id: 'N452178', name: '<NAME>', price: 697.57, image: 'https://secure.img1-fg.wfcdn.com/im/10139243/resize-h700-w700%5Ecompr-r85/3206/32067457/Priceville+Dining+Hutch.jpg', description: 'A great way to round out your living ensemble with much-needed storage, a china cabinet like this is a great option for storing everything from dining linens to wine. Crafted from a blend of solid and manufactured wood, this piece features four cabinets, three shelves, and three drawers on metal glides for abundant stowing space. A nine-bottle wine rack is included at the base of this piece, and the upper cabinets are glass-fronted for a classic look.', quantity: 4, type: 'Dining Set', }, { id: 'X986543', name: 'Folding Sleeper Chair Convertible Lazy Chair Soft Pillow 3 Position With Bench', price: 329.99, image: 'https://secure.img1-fg.wfcdn.com/im/47638865/resize-h700-w700%5Ecompr-r85/1261/126162033/Folding+Sleeper++Chair+Convertible+Lazy+Chair+Soft+Pillow+3+Position+With+Bench.jpg', description: 'This Is Our Brand New And Convertible Sleeper Chair, Which Is A Perfect Addition To Any Household That Wants Comfort And Convenience Without Giving Up A Ton Of Space. The Unique Folding Design Makes This Chair Easy To Transform. It Has Multiple Positions, Such As A Chair With Armrests or Chaise Lounge. Featuring Steel Construction, This Chair Can Retains Its Value Over The Long Term. A Pillow Comes As A Gift, Which You Can Use As A Pillow Or Cushion. You Can Put It In The Living Room, The Bedroom,balcony Or Even The Office.', quantity: 4, type: 'Chair', }, { id: 'D543098', name: 'Platform Bed', price: 131.99, image: 'https://secure.img1-fg.wfcdn.com/im/62947031/resize-h700-w700%5Ecompr-r85/6387/63873926/Platform+Bed.jpg', description: 'Every mattress needs a foundation, and every master suite needs a focal point – that’s where the bed frame comes in! This design’s streamlined silhouette pairs with natural wood grain patterning to bring you a look that pairs well with boho-chic ensembles and eclectic modern spaces alike. Crafted from solid wood and metal, this piece uses a support leg and slat system to cradle your mattress as you sleep, eliminating the need to use a box spring.', quantity: 4, type: 'Bed', }, ], }; <|start_filename|>courses_app/src/navigators/Stack.js<|end_filename|> import React from 'react'; import {createDrawerNavigator, DrawerItem} from '@react-navigation/drawer'; import {createStackNavigator} from '@react-navigation/stack'; import {Home, CoursesList} from '../screens'; const Stack = createStackNavigator(); const Drawer = createDrawerNavigator(); const DrawerStack = () => { return ( <Drawer.Navigator> <Drawer.Screen name="Home" component={Home} options={{headerShown: false}} /> </Drawer.Navigator> ); }; const SingleStack = () => { return ( <Stack.Navigator> <Stack.Screen name="CoursesList" component={CoursesList} options={{headerShown: false}} /> </Stack.Navigator> ); }; function AppStack() { return ( <Stack.Navigator initialRouteName="DrawerStack"> <Stack.Screen name="DrawerStack" component={DrawerStack} options={{headerShown: false}} /> <Stack.Screen name="SingleStack" component={SingleStack} options={{headerShown: false}} /> </Stack.Navigator> ); } export default AppStack; <|start_filename|>furniture_shop/src/store/reducer/appReducer.js<|end_filename|> import initialState from '../state'; export const appReducer = (state = initialState, action) => { switch (action.type) { case 'addToCart': { const {furniture, type} = action.payload; let cart = state?.cart; let isFound = cart?.some((item) => item.id === furniture.id); if (!isFound && type === 'add') { furniture.noInCart = 1; cart.push(furniture); } else { cart = cart.map((product) => { if (product.id === furniture.id) { if (type === 'add') { product.noInCart = product.noInCart + 1; } else if (type === 'subtract' && product.noInCart !== 0) { product.noInCart = product.noInCart - 1; } } return product; }); } return { ...state, cart, }; } default: return state; } }; <|start_filename|>job_finder_app/src/screens/Settings/index.js<|end_filename|> import React from 'react'; import {View, Text} from 'react-native'; export function Settings() { return ( <View> <Text>Settings</Text> </View> ); } <|start_filename|>job_finder_app/src/components/Job/jobStyle.js<|end_filename|> import {StyleSheet, Dimensions} from 'react-native'; const styles = StyleSheet.create({ jobContainer: { backgroundColor: '#fff', borderRadius: 5, display: 'flex', flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', shadowColor: '#000', shadowOffset: { width: 0, height: 0.5, }, shadowOpacity: 0, shadowRadius: 0.5, elevation: 2, paddingHorizontal: 10, paddingVertical: 5, marginBottom: 20, }, jobImage: { height: 80, width: '23%', resizeMode: 'contain', }, jobInfo: { width: '60%', }, flexRow: { display: 'flex', flexDirection: 'row', alignItems: 'center', }, jobCompany: { width: '100%', opacity: 0.5, fontSize: 13, fontWeight: 'bold', }, jobRole: { fontWeight: 'bold', fontSize: 14, width: '100%', opacity: 0.9, }, jobSalary: { fontSize: 13, }, jobLocation: { fontSize: 13, marginLeft: 5, }, }); export default styles; <|start_filename|>job_finder_app/src/screens/Home/homeStyle.js<|end_filename|> import {StyleSheet} from 'react-native'; const styles = StyleSheet.create({ homeContainer: { flex: 1, backgroundColor: '#fafafa', }, homeContent: { height: '100%', padding: 16, }, homeHeader: { display: 'flex', justifyContent: 'space-between', flexDirection: 'row', alignItems: 'center', marginBottom: 40, }, usernameText: { fontWeight: 'bold', opacity: 0.3, }, findJobText: {fontSize: 17, fontWeight: 'bold'}, profilePic: { height: 35, width: 35, borderRadius: 10, }, profilePicWrapper: { borderColor: '#CECECE', borderWidth: 1, borderRadius: 15, padding: 5, }, searchContainer: { height: 40, width: '100%', display: 'flex', flexDirection: 'row', marginBottom: 60, }, searchInput: { width: '85%', height: 40, fontSize: 15, backgroundColor: '#ececec', borderTopLeftRadius: 15, borderBottomLeftRadius: 15, paddingLeft: 15, paddingRight: 5, }, searchButton: { backgroundColor: '#31A854', width: '15%', display: 'flex', alignItems: 'center', justifyContent: 'center', borderTopRightRadius: 15, borderBottomRightRadius: 15, }, heading: { fontWeight: 'bold', fontSize: 15.5, opacity: 0.9, marginBottom: 10, }, scrollViewContent: { // paddingBottom: 40, }, container: { display: 'flex', }, section: { display: 'flex', marginBottom: 50, }, sectionScrollContainer: { paddingVertical: 1, paddingHorizontal: 1, }, }); export default styles; <|start_filename|>furniture_shop/src/components/index.js<|end_filename|> export * from './FeaturedProduct'; export * from './NewProduct'; <|start_filename|>music_app_ui/src/components/NavDrawerHeader/navDrawerHeaderStyle.js<|end_filename|> import {StyleSheet} from 'react-native'; const styles = StyleSheet.create({ navHeader: { backgroundColor: '#222225', height: 60, padding: 16, display: 'flex', flexDirection: 'row', alignItems: 'center', }, navIconImage: { height: 25, width: 25, resizeMode: 'cover', }, logoContainer: { width: 107, height: 37, position: 'relative', }, logoImage: { width: 120, height: 40, resizeMode: 'contain', zIndex: 1, }, controlIcons: { display: 'flex', flexDirection: 'row', marginLeft: 'auto', }, menuOptionText: { fontSize: 15, paddingLeft: 7, paddingBottom: 5, }, }); export default styles; <|start_filename|>furniture_shop/src/components/NewProduct/newProductStyle.js<|end_filename|> import {StyleSheet, Dimensions} from 'react-native'; const styles = StyleSheet.create({ furnitureContainer: { width: Dimensions.get('window').width / 2.8, display: 'flex', alignItems: 'center', justifyContent: 'center', paddingBottom: 7, marginRight: Dimensions.get('window').width / 20, height: 130, }, furnitureImageWrapper: { height: '80%', width: '100%', marginBottom: 5, }, furnitureImage: { height: '100%', width: '100%', borderRadius: 15, }, furnitureName: { width: '85%', fontWeight: 'bold', opacity: 0.6, textAlign: 'center', fontSize: 12, }, }); export default styles; <|start_filename|>courses_app/src/screens/Home/homeStyle.js<|end_filename|> import {StyleSheet} from 'react-native'; const styles = StyleSheet.create({ homeContainer: { flex: 1, backgroundColor: '#FFFFFF', }, homeContent: { height: '100%', padding: 16, }, headerContainer: { display: 'flex', flexDirection: 'row', justifyContent: 'space-between', marginBottom: 40, alignItems: 'center', }, profilePhotoImage: { height: 40, width: 40, borderRadius: 5, }, nameContainer: { display: 'flex', flexDirection: 'row', marginBottom: 3, }, nameText: { fontSize: 20, fontWeight: 'bold', }, usernameText: { fontSize: 20, fontWeight: 'bold', opacity: 0.7, marginLeft: 5, }, learnText: { fontSize: 16, marginBottom: 30, opacity: 0.6, }, searchContainer: { borderColor: '#ddd', borderWidth: 1, marginBottom: 30, borderRadius: 5, display: 'flex', flexDirection: 'row', alignItems: 'center', paddingHorizontal: 5, }, searchInput: { height: 40, fontSize: 15, marginLeft: 5, width: '80%', }, dropdownContainer: { borderLeftColor: '#ddd', borderLeftWidth: 1, height: 40, width: 40, display: 'flex', alignItems: 'center', justifyContent: 'center', }, tabHeaderContainer: { display: 'flex', flexDirection: 'row', marginBottom: 20, }, scrollViewContent:{ paddingTop: 10, paddingBottom: 40 }, singleTab: { marginRight: 20, display: 'flex', alignItems: 'center', }, tabText: { fontSize: 18, fontWeight: 'bold', }, activeTabText: { opacity: 0.9, }, inActiveTabText: { opacity: 0.3, }, activeTabBottom: { height: 10, width: 10, backgroundColor: '#B79069', borderRadius: 50, }, tabBodyContainer: { display: 'flex', flexDirection: 'row', flexWrap: 'wrap', justifyContent: 'space-between', }, categoryContainer: { width: '43%', borderRadius: 12, marginBottom: 30, }, categoryShortHeight: { height: 160, }, categoryLongHeight: { height: 200, }, categoryTitletext: { fontWeight: 'bold', fontSize: 16, opacity: 0.9, }, categoryNumbertext: { fontSize: 13, }, illustrationImage: { flex: 1, position: 'relative', borderRadius: 10, width: '100%', }, backgroundStyle: { resizeMode: 'cover', position: 'absolute', top: 55, }, transparentBg: { paddingTop: 10, paddingHorizontal: 10, }, bg0: { backgroundColor: '#FDAAB0', }, bg1: { backgroundColor: '#E296DE', }, bg2: { backgroundColor: '#9E7CF4', }, bg3: { backgroundColor: '#96D8CA', }, }); export default styles; <|start_filename|>music_app_ui/src/screens/index.js<|end_filename|> export * from './Upload'; export * from './Track'; <|start_filename|>courses_app/src/utils/index.js<|end_filename|> import UXImage from '../assets/illustrations/3647007.png'; import PSImage from '../assets/illustrations/4991639.png'; import DVImage from '../assets/illustrations/9814.png'; import IlImage from '../assets/illustrations/Wavy_Bus-35_Single-03.png'; export const getIllustration = (id) => { return id === 0 ? UXImage : id === 1 ? PSImage : id === 2 ? IlImage : DVImage; }; export const getBackground = (id) => { return id === 0 ? {backgroundColor: '#FDAAB0'} : id === 1 ? {backgroundColor: '#E296DE'} : id === 2 ? {backgroundColor: '#9E7CF4'} : {backgroundColor: '#96D8CA'}; }; <|start_filename|>furniture_shop/src/navigators/Stack.js<|end_filename|> import React from 'react'; import {createStackNavigator} from '@react-navigation/stack'; import {Home, ProductDetail} from '../screens'; const Stack = createStackNavigator(); function AppStack() { return ( <Stack.Navigator initialRouteName="Home"> <Stack.Screen name="Home" component={Home} options={{headerShown: false}} /> <Stack.Screen name="ProductDetail" component={ProductDetail} options={{headerShown: false}} /> </Stack.Navigator> ); } export default AppStack; <|start_filename|>furniture_shop/src/components/FeaturedProduct/index.js<|end_filename|> import React, {useContext} from 'react'; import {View, Text, Image, TouchableOpacity} from 'react-native'; import AntDesign from 'react-native-vector-icons/AntDesign'; import styles from './featuredProductStyle.js'; import {AuthContext} from '../../context'; export function FeaturedProduct({furniture, onNavigate}) { const {state, dispatch} = useContext(AuthContext); const handleNoInCart = (type) => { dispatch({ type: 'addToCart', payload: {furniture, type}, }); }; return ( <View style={styles.furnitureContainer}> <TouchableOpacity onPress={() => onNavigate('ProductDetail', furniture)}> <Image source={{uri: furniture?.image}} style={styles.furnitureImage} /> </TouchableOpacity> <Text numberOfLines={1} ellipsizeMode="tail" style={styles.furnitureName}> {furniture?.name} </Text> <Text numberOfLines={2} ellipsizeMode="tail" style={styles.furnitureType}> {furniture?.type} </Text> <View style={styles.furnitureBottomRow}> <Text style={styles.furniturePrice}>${furniture?.price}</Text> <TouchableOpacity style={styles.addToCartBtn} onPress={() => handleNoInCart('add')}> <AntDesign name="plus" size={20} color="#fff" /> </TouchableOpacity> </View> </View> ); } <|start_filename|>job_finder_app/src/components/Category/categoryStyle.js<|end_filename|> import {StyleSheet, Dimensions} from 'react-native'; const styles = StyleSheet.create({ categoryContainer: { backgroundColor: '#fff', borderRadius: 5, width: Dimensions.get('window').width / 2.5, padding: 10, paddingTop: 5, shadowColor: '#000', shadowOffset: { width: 0, height: 0.5, }, shadowOpacity: 0, shadowRadius: 0.5, elevation: 2, marginRight: Dimensions.get('window').width / 10, display: 'flex', justifyContent: 'center', alignItems: 'center', }, categoryImage: { height: 100, width: '100%', resizeMode: 'contain', marginBottom: 10, borderRadius: 5, }, categoryTitle: { fontWeight: 'bold', fontSize: 15, marginBottom: 5, }, categoryNoOfJobs: { opacity: 0.5, }, }); export default styles; <|start_filename|>music_app_ui/src/screens/Track/index.js<|end_filename|> import React from 'react'; import {View, Text, Button} from 'react-native'; import {CustomText} from '../../components'; export function Track() { return <Text>Hello</Text>; } <|start_filename|>job_finder_app/src/screens/index.js<|end_filename|> export * from './Home'; export * from './JobDetail'; export * from './Bookmarks'; export * from './Messages'; export * from './Notifications'; export * from './Settings'; <|start_filename|>job_finder_app/src/store/state.js<|end_filename|> export default state = { categories: [ { title: 'DevOps', noOfJobs: 120, image: 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcR020A6piMuQDzh0K3L-Se2x7m1IaPjK3waug&usqp=CAU', }, { title: 'Software Development', noOfJobs: 148, image: 'https://www.yourtrainingedge.com/wp-content/uploads/2019/07/artificial-intelligence-blur-close-up-546819.jpg', }, { title: 'UI/UX Design', noOfJobs: 195, image: 'https://www.dailyhostnews.com/wp-content/uploads/2020/12/post-featured-compressed-14-compressed-2100x1200.jpg', }, ], jobs: [ { id: 'A123', company: { name: 'Spotify', logo: 'https://1000logos.net/wp-content/uploads/2017/08/Spotify-Logo.png', }, role: 'Senior UI Designer', salary: '$50/hr', location: 'Remote', }, { id: 'B567', company: { name: 'Google', logo: 'https://i.pinimg.com/originals/00/ef/95/00ef95babba98ec1c4a326be11775602.png', }, role: 'Product Manager', salary: '$100/hr', location: 'Full time', }, { id: 'C789', company: { name: 'Coca-cola', logo: 'https://upload.wikimedia.org/wikipedia/commons/c/ce/Coca-Cola_logo.svg', }, role: 'React Developer', salary: '$50/hr', location: 'Remote', }, { id: 'D215', company: { name: 'Behance', logo: 'https://cdn.worldvectorlogo.com/logos/behance-1.svg', }, role: 'C# Developer', salary: '$100/hr', location: 'Full time', }, ], bookmarks: [ { id: 'A123', company: { name: 'Spotify', logo: 'https://1000logos.net/wp-content/uploads/2017/08/Spotify-Logo.png', }, role: 'UI Designer', salary: '$50/hr', location: 'Remote', }, ], }; <|start_filename|>furniture_shop/src/screens/Home/index.js<|end_filename|> import React, {useState, useContext} from 'react'; import { View, Text, TextInput, ScrollView, TouchableOpacity, FlatList, Image, } from 'react-native'; import Ionicons from 'react-native-vector-icons/Ionicons'; import MaterialCommunityIcons from 'react-native-vector-icons/MaterialCommunityIcons'; import shortid from 'shortid'; import HotDogMenu from '../../assets/icons/HotDogMenu.png'; import styles from './homeStyle.js'; import {FeaturedProduct, NewProduct} from '../../components'; import {AuthContext} from '../../context'; export function Home({navigation}) { const {state, dispatch} = useContext(AuthContext); const [data, setData] = useState({username: 'Kimberly'}); const handleNavigation = (route, params) => { navigation?.navigate(route, params); }; const renderFeaturedProducts = ({item}) => { return ( <FeaturedProduct furniture={item} onNavigate={(route, params) => handleNavigation(route, params)} /> ); }; const renderNewProducts = ({item}) => { return ( <NewProduct furniture={item} onNavigate={(route, params) => handleNavigation(route, params)} /> ); }; return ( <View style={styles.homeContainer}> <View style={styles.homeContent}> <View style={styles.homeHeader}> <TouchableOpacity style={styles.homeHeaderCircleContainer}> <Image source={HotDogMenu} /> </TouchableOpacity> <TouchableOpacity style={styles.homeHeaderCircleContainer}> <MaterialCommunityIcons name="cart-outline" size={20} color="#333333" /> <Text style={styles.noInCartText}>{state?.cart?.length}</Text> </TouchableOpacity> </View> <Text style={styles.greetingText}>Hello, {data?.username}</Text> <Text style={styles.chooseText}>Choose Your Furniture!</Text> <View style={styles.searchContainer}> <Ionicons name="search" size={20} color="#333333" /> <TextInput placeholder="Search" style={styles.searchInput} /> </View> <ScrollView style={styles.scrollViewContent} showsVerticalScrollIndicator={false}> <View style={styles.productsContainer}> <View style={styles.section}> <View style={styles.sectionHeader}> <Text style={styles.sectionHeaderText}>FEATURED PRODUCTS</Text> <TouchableOpacity style={styles.sectionHeaderLeft}> <Text style={styles.sectionHeaderLeftText}>See all</Text> <Ionicons name="arrow-forward-sharp" size={20} color="#D1D1D1" /> </TouchableOpacity> </View> <FlatList data={state?.featuredProducts} keyExtractor={(item, index) => shortid.generate()} renderItem={renderFeaturedProducts} horizontal={true} contentContainerStyle={styles.sectionScrollContainer} showsHorizontalScrollIndicator={false} /> </View> <View style={styles.section}> <View style={styles.sectionHeader}> <Text style={styles.sectionHeaderText}>NEW PRODUCTS</Text> </View> <View style={styles.sectionContent}> <FlatList data={state?.newProducts} keyExtractor={(item, index) => shortid.generate()} renderItem={renderNewProducts} horizontal={true} showsHorizontalScrollIndicator={false} /> </View> </View> </View> </ScrollView> </View> </View> ); }
Abhisek-Ray99/React-Native-UI-Templates
<|start_filename|>ExampleOBJC/OBJCExample/ViewController.h<|end_filename|> // // ViewController.h // OBJCExample // // Created by Aurelien on 28/05/2019. // Copyright © 2019 chronotruck. All rights reserved. // #import <UIKit/UIKit.h> #import "FlagPhoneNumber-Swift.h" @interface ViewController : UIViewController @end <|start_filename|>Sources/libPhoneNumber/NBGeneratedPhoneNumberMetaData.h<|end_filename|> /***** * Data Generated from GeneratePhoneNumberHeader.sh * Off of PhoneNumberMetaDataForTesting.json, PhoneNumberMetaData.json, and ShortNumberMetaData.json */ #include <zlib.h> // z_const is not defined in some versions of zlib, so define it here // in case it has not been defined. #if defined(ZLIB_CONST) && !defined(z_const) # define z_const const #else # define z_const #endif #if TESTING==1 z_const Bytef kPhoneNumberMetaData[] = { 0x1f, 0x8b, 0x08, 0x08, 0x5a, 0x2a, 0xbe, 0x5b, 0x00, 0x03, 0x50, 0x68, 0x6f, 0x6e, 0x65, 0x4e, 0x75, 0x6d, 0x62, 0x65, 0x72, 0x4d, 0x65, 0x74, 0x61, 0x44, 0x61, 0x74, 0x61, 0x46, 0x6f, 0x72, 0x54, 0x65, 0x73, 0x74, 0x69, 0x6e, 0x67, 0x2e, 0x6a, 0x73, 0x6f, 0x6e, 0x00, 0xed, 0x1d, 0x6b, 0x6f, 0xdb, 0x38, 0xf2, 0xaf, 0x04, 0x42, 0x3e, 0x44, 0x07, 0xfa, 0x4e, 0x7c, 0x8a, 0xec, 0x97, 0xa2, 0xcd, 0x76, 0xbb, 0xaf, 0xb4, 0x45, 0xd2, 0x00, 0x6d, 0xb5, 0xfa, 0x50, 0x5c, 0x8b, 0xc3, 0x01, 0x8b, 0xf6, 0x70, 0xe8, 0x02, 0x77, 0x28, 0xd3, 0xdf, 0xbe, 0x33, 0xa4, 0xa4, 0x58, 0xd2, 0x50, 0x96, 0xed, 0x36, 0x51, 0xea, 0x04, 0xad, 0x4d, 0xd9, 0x9a, 0x21, 0x29, 0xce, 0x7b, 0x86, 0xf4, 0xe7, 0xec, 0x9f, 0x1f, 0xff, 0xfc, 0xf0, 0xe9, 0xbf, 0xff, 0x3f, 0xfd, 0xf8, 0xee, 0xfd, 0xcb, 0x8f, 0xe7, 0xef, 0xff, 0xf5, 0xef, 0x8f, 0x1f, 0xb0, 0x7d, 0xf6, 0xf6, 0x3f, 0xd9, 0x83, 0xcf, 0x19, 0xcf, 0x1e, 0x54, 0xd9, 0xe5, 0x45, 0xc6, 0xb2, 0xc7, 0x8f, 0xf1, 0x05, 0x5b, 0xa7, 0x8f, 0xb2, 0x9a, 0x65, 0x52, 0xe2, 0x57, 0x3f, 0x9e, 0x87, 0xb6, 0xc1, 0xf6, 0x4f, 0x97, 0xa1, 0xed, 0xb0, 0xfd, 0xf3, 0x4b, 0x6c, 0x2b, 0x85, 0xed, 0xa7, 0x08, 0xf9, 0xf4, 0x69, 0xf8, 0x20, 0xdc, 0x78, 0xf1, 0x24, 0xb4, 0x2d, 0xb6, 0x5f, 0xfc, 0x16, 0xda, 0x01, 0xe8, 0x87, 0xf0, 0xb9, 0x16, 0xd8, 0x3e, 0x7b, 0x15, 0xda, 0x01, 0xc1, 0xa3, 0xd0, 0x89, 0xd6, 0xd8, 0x7e, 0x1c, 0xda, 0x26, 0x8c, 0xeb, 0xd1, 0x25, 0x8e, 0xe6, 0x14, 0x5f, 0xc2, 0xdd, 0x26, 0xdc, 0xfd, 0xec, 0x4d, 0x68, 0x87, 0xbb, 0x2f, 0x42, 0xaf, 0x36, 0xdc, 0xfd, 0xcb, 0x8b, 0xd0, 0x0e, 0xd8, 0x7f, 0x0d, 0x58, 0x6c, 0x18, 0xcd, 0xe9, 0x33, 0x6c, 0x8b, 0x38, 0xd6, 0x47, 0xcf, 0xc3, 0x85, 0x09, 0x77, 0x9d, 0x3f, 0x01, 0xd4, 0xaf, 0xc3, 0x4c, 0x84, 0x2b, 0xf0, 0x93, 0x97, 0x71, 0xea, 0x65, 0xbc, 0xf7, 0x2c, 0x5e, 0xc4, 0x71, 0xbd, 0x8e, 0x17, 0x01, 0xe5, 0xa3, 0x1f, 0x02, 0xfa, 0x22, 0xc0, 0x14, 0x05, 0x0f, 0x57, 0xb1, 0xe7, 0xe6, 0xca, 0x95, 0x71, 0x06, 0x4f, 0xe2, 0x85, 0x5b, 0xff, 0xca, 0x85, 0x07, 0x73, 0x09, 0xd3, 0xb8, 0x62, 0xed, 0xf2, 0xbc, 0xfc, 0x78, 0xf6, 0xfe, 0xd3, 0xdb, 0x77, 0x6f, 0x3f, 0xbd, 0xc5, 0x55, 0x89, 0x98, 0x3f, 0xfc, 0xf9, 0xc7, 0x1f, 0x2c, 0xbe, 0x86, 0x97, 0xec, 0xf7, 0xdf, 0xdf, 0x7d, 0xb6, 0x57, 0x19, 0xbb, 0xfe, 0x88, 0x7a, 0xa9, 0x6c, 0x5d, 0xaf, 0x83, 0xcd, 0x78, 0xa9, 0x56, 0x7c, 0x7f, 0x98, 0xd4, 0xf0, 0x32, 0x2e, 0xa4, 0xd2, 0xa6, 0xb4, 0xd9, 0xad, 0x0c, 0xeb, 0x9b, 0xc2, 0x84, 0x35, 0x65, 0xb0, 0x5c, 0x73, 0x40, 0x38, 0xab, 0x62, 0x1f, 0xd9, 0x09, 0x3e, 0x2a, 0x75, 0x95, 0xb7, 0xef, 0x40, 0x86, 0xc7, 0xfc, 0xe8, 0x58, 0x64, 0x80, 0x72, 0xb8, 0xea, 0xb3, 0xc7, 0xb2, 0x76, 0x7d, 0x43, 0xb3, 0xdf, 0xab, 0xc7, 0x8e, 0x65, 0x48, 0x32, 0x77, 0x9b, 0xc9, 0xdc, 0x7d, 0x25, 0x92, 0x25, 0xba, 0xea, 0x48, 0xd6, 0x7d, 0x87, 0x34, 0xbb, 0x07, 0x9d, 0x5b, 0x31, 0x1f, 0x6e, 0x8d, 0xd4, 0xf3, 0x14, 0xbd, 0x1f, 0x1d, 0xcb, 0x03, 0x23, 0xf9, 0xa8, 0x0a, 0x6e, 0x91, 0xe4, 0x6f, 0x0a, 0xe6, 0xce, 0xb3, 0x56, 0x24, 0x79, 0x58, 0xaf, 0x39, 0x20, 0xfc, 0x9e, 0xde, 0x69, 0x7a, 0x07, 0x4b, 0x29, 0x41, 0xee, 0x66, 0x33, 0xb9, 0x1b, 0x82, 0xa4, 0x08, 0xb0, 0x86, 0xa4, 0x16, 0x4e, 0x4f, 0x4b, 0x86, 0xc1, 0x65, 0x62, 0x60, 0xdb, 0x22, 0xd1, 0x6f, 0x5a, 0x95, 0x21, 0x82, 0xc3, 0x20, 0xe3, 0x27, 0x14, 0x19, 0x57, 0x7c, 0xe5, 0xea, 0x99, 0x46, 0xf9, 0x1d, 0x12, 0xdd, 0xdf, 0x05, 0x0c, 0x2e, 0x19, 0x48, 0x6f, 0x3e, 0x87, 0xa4, 0xf9, 0x52, 0xe8, 0x39, 0x33, 0x45, 0x91, 0x12, 0x72, 0xf0, 0x55, 0x27, 0xe7, 0xf6, 0x26, 0xe7, 0xb3, 0x49, 0x72, 0x2e, 0xe7, 0xf8, 0x98, 0xac, 0xd2, 0x6c, 0x28, 0xa0, 0xa7, 0x30, 0x64, 0xbc, 0x1d, 0xff, 0x08, 0xd9, 0xb7, 0x43, 0xb4, 0x38, 0xb2, 0xbc, 0x39, 0xf2, 0x3f, 0x43, 0x89, 0xae, 0x22, 0xf9, 0x67, 0x3d, 0x16, 0xe8, 0x5f, 0x2d, 0x86, 0xf8, 0x6f, 0xa6, 0x47, 0x7c, 0x34, 0xcf, 0x49, 0xea, 0x17, 0xbb, 0xca, 0xf2, 0x4c, 0x00, 0xdc, 0xc9, 0xc3, 0x07, 0x95, 0x30, 0x91, 0x6a, 0x3d, 0xfc, 0x8f, 0x17, 0x39, 0x62, 0xd4, 0x04, 0x0d, 0x0b, 0x21, 0x28, 0xab, 0x25, 0x73, 0x40, 0xf9, 0x32, 0x49, 0xf9, 0x4e, 0xc8, 0x7b, 0x5b, 0xa7, 0x47, 0xe5, 0xcf, 0x33, 0x26, 0x54, 0x47, 0xe5, 0x5f, 0x06, 0x74, 0xfe, 0x65, 0x2c, 0xfa, 0x7b, 0x21, 0x18, 0xd9, 0x98, 0xe8, 0x6b, 0xef, 0x07, 0x6c, 0xaa, 0x9f, 0x27, 0x94, 0x82, 0x34, 0x36, 0xb2, 0x86, 0x63, 0xbc, 0x98, 0x61, 0xb5, 0xb3, 0x92, 0x59, 0x86, 0xf7, 0x32, 0x3e, 0xd4, 0x6f, 0x1d, 0x75, 0x6b, 0x36, 0xe9, 0x1b, 0xf6, 0xd6, 0x6d, 0x0d, 0xe3, 0x00, 0x9d, 0x43, 0x54, 0x30, 0x26, 0xdf, 0xe1, 0xa5, 0xb0, 0x3a, 0x1a, 0x2b, 0x35, 0x3e, 0x5b, 0xa4, 0x82, 0x98, 0xb6, 0x48, 0x20, 0x19, 0x6a, 0xf0, 0x13, 0x44, 0xe1, 0x79, 0x91, 0xa7, 0x98, 0xd8, 0xa4, 0x86, 0xb3, 0x78, 0x66, 0x3b, 0xcf, 0x98, 0x4e, 0x68, 0x14, 0x10, 0x7f, 0x27, 0x9c, 0x7b, 0xa9, 0xa4, 0x97, 0x25, 0xd7, 0x39, 0xfc, 0x7b, 0x08, 0x77, 0xb9, 0x63, 0xde, 0x9b, 0xe4, 0x3a, 0xf3, 0x89, 0xab, 0xa4, 0x9f, 0xbc, 0x02, 0xe6, 0x63, 0x55, 0xc6, 0x43, 0xbc, 0xbc, 0x38, 0xe6, 0x9d, 0xb8, 0xeb, 0x47, 0x4e, 0x45, 0x1a, 0xb2, 0x2a, 0x04, 0x88, 0x5f, 0x5f, 0x09, 0x59, 0x8f, 0x71, 0xb8, 0x1c, 0xc6, 0x4a, 0x76, 0x2e, 0x8e, 0xb8, 0x06, 0xce, 0x5f, 0x1d, 0x2b, 0xc4, 0xe2, 0xa8, 0x01, 0xb8, 0x7c, 0x6a, 0x0c, 0x62, 0x0d, 0x1a, 0x9e, 0xc9, 0xfa, 0x38, 0xf2, 0x16, 0x57, 0x78, 0x3d, 0x3a, 0x3e, 0x3d, 0x1d, 0x4c, 0x6b, 0x28, 0x8d, 0xda, 0x69, 0xad, 0xba, 0x69, 0x55, 0xc6, 0x5e, 0x4f, 0xa7, 0x5e, 0xfe, 0xe3, 0x6c, 0x04, 0xe9, 0xd1, 0xda, 0xe3, 0x9c, 0xfb, 0x20, 0x07, 0xa0, 0xe3, 0x67, 0xb9, 0xef, 0xb3, 0x3b, 0x0c, 0x99, 0x7e, 0x99, 0x90, 0xe9, 0xba, 0xb4, 0x41, 0x5e, 0x2a, 0xc6, 0xd5, 0x0c, 0x83, 0x67, 0x2c, 0x7a, 0x61, 0x15, 0x1a, 0x14, 0x94, 0xb4, 0x14, 0x5d, 0xce, 0xa7, 0x87, 0x66, 0x80, 0x43, 0xa5, 0xc0, 0xd5, 0x2c, 0x70, 0x6e, 0xd3, 0xde, 0x12, 0x7e, 0x37, 0xf6, 0x12, 0xc6, 0xe2, 0x9a, 0xbb, 0xa2, 0x82, 0x1b, 0x4d, 0x9d, 0x44, 0xe4, 0x66, 0x21, 0x5a, 0xa0, 0xb4, 0xbe, 0xcc, 0x98, 0x09, 0xee, 0x2f, 0xaf, 0xb8, 0xa8, 0x93, 0x4e, 0x00, 0xde, 0xd0, 0x0a, 0x69, 0x32, 0x3f, 0x95, 0x30, 0x8e, 0x50, 0x2c, 0x20, 0x3f, 0x8d, 0xc4, 0x09, 0x4f, 0x0b, 0xa2, 0x06, 0xae, 0x12, 0x2b, 0x55, 0xf6, 0xb8, 0x71, 0x67, 0xa6, 0xba, 0x7b, 0x2c, 0xf9, 0xf8, 0x31, 0xc5, 0x92, 0x42, 0x99, 0x99, 0x9e, 0x37, 0x50, 0x1e, 0xab, 0xca, 0xcd, 0x83, 0x47, 0x94, 0x84, 0x9d, 0x11, 0x91, 0xcc, 0x80, 0xbf, 0x55, 0xea, 0x5d, 0x32, 0x4c, 0xa8, 0x94, 0x40, 0xc6, 0xe2, 0x7c, 0xd3, 0x62, 0x1d, 0x9e, 0x6f, 0xfd, 0x98, 0x74, 0x22, 0x82, 0x9c, 0x9f, 0xe5, 0x3c, 0x04, 0xea, 0x1e, 0x14, 0x30, 0x4c, 0x80, 0x67, 0x94, 0xa2, 0x88, 0x98, 0x6e, 0xa9, 0x0a, 0xe2, 0xbb, 0x80, 0xc1, 0x65, 0x64, 0x5a, 0xdf, 0xa7, 0x03, 0x52, 0x54, 0x7e, 0x41, 0x51, 0xf9, 0x89, 0x50, 0xc2, 0xdb, 0x93, 0xa2, 0xf0, 0xc6, 0xf8, 0xb2, 0xf4, 0xd6, 0xe6, 0x1e, 0xac, 0x87, 0x94, 0x23, 0x48, 0x92, 0xfe, 0x40, 0x30, 0x83, 0x10, 0x17, 0x60, 0xfa, 0x4a, 0xf8, 0x5f, 0x08, 0xb4, 0x7c, 0x4d, 0x1d, 0x42, 0xa3, 0x5e, 0x55, 0xc5, 0x4a, 0x28, 0x6c, 0x69, 0x68, 0x81, 0x69, 0xeb, 0xcb, 0x4a, 0x82, 0x55, 0x57, 0x7b, 0x07, 0xda, 0x55, 0xd7, 0xb9, 0x57, 0x00, 0x23, 0xd0, 0x4a, 0x83, 0x5b, 0xb8, 0x37, 0x0a, 0x46, 0x94, 0x7b, 0x0d, 0x58, 0x8c, 0x84, 0xd1, 0x15, 0x22, 0x8f, 0xba, 0x99, 0xb0, 0xdd, 0x94, 0x80, 0xdb, 0x66, 0xe9, 0x8d, 0x30, 0x3c, 0xa9, 0x4b, 0x2f, 0xb5, 0xf3, 0x0a, 0xde, 0xb5, 0x2e, 0xa7, 0xf0, 0xc2, 0xad, 0x01, 0xef, 0xc0, 0xe9, 0xee, 0x3d, 0xb2, 0x94, 0xdb, 0xdc, 0x19, 0x74, 0xe5, 0x30, 0x64, 0x16, 0xad, 0x40, 0x32, 0x5e, 0x96, 0x80, 0x59, 0x20, 0xc3, 0x5d, 0x5c, 0xeb, 0x94, 0xac, 0xa7, 0x57, 0xb2, 0x29, 0x2d, 0x73, 0x20, 0xec, 0xf6, 0x7a, 0x32, 0x5d, 0x41, 0xc4, 0x57, 0x87, 0x88, 0x92, 0xf9, 0x05, 0x2a, 0x36, 0xcb, 0x03, 0xcd, 0x2c, 0x9c, 0x62, 0x96, 0x0c, 0x83, 0x0b, 0xc6, 0x64, 0xa9, 0xb1, 0x32, 0x13, 0x63, 0x45, 0x3d, 0xed, 0x0c, 0x8c, 0xfc, 0xd0, 0x3b, 0xfc, 0x9b, 0x8e, 0xcd, 0xb6, 0x6e, 0x43, 0x70, 0x18, 0xf8, 0x2a, 0xba, 0x0b, 0xf6, 0x68, 0xe4, 0x6e, 0x88, 0xb1, 0x7b, 0xd2, 0x07, 0x19, 0x41, 0x10, 0x0e, 0x0d, 0xd1, 0xc9, 0x41, 0x39, 0x25, 0xa7, 0x8f, 0x48, 0xa7, 0x44, 0xec, 0xe3, 0x94, 0x4c, 0x80, 0xe3, 0x57, 0xad, 0x60, 0x1e, 0xe1, 0xba, 0xf7, 0x4d, 0xf6, 0xe0, 0x3c, 0x58, 0xc8, 0x99, 0xbe, 0xc9, 0x10, 0xfe, 0x30, 0xe8, 0xfc, 0x34, 0x59, 0x8e, 0x34, 0xdf, 0x3d, 0x21, 0xcb, 0x92, 0x68, 0xf7, 0x64, 0x8a, 0xce, 0xef, 0x53, 0xd5, 0xfb, 0xd0, 0xf9, 0x69, 0x1b, 0xdd, 0xba, 0xa7, 0x73, 0x8a, 0xce, 0x9f, 0x25, 0x2c, 0xa6, 0xb2, 0x6e, 0xa8, 0x95, 0x5f, 0x79, 0x0b, 0x9e, 0x03, 0x58, 0xe4, 0x8d, 0x25, 0x64, 0x98, 0xbb, 0xf2, 0x21, 0xa1, 0x56, 0xce, 0x63, 0x85, 0x51, 0x6e, 0x4f, 0x34, 0x98, 0x48, 0x4e, 0x70, 0xb4, 0xf1, 0xce, 0x31, 0x6f, 0x2e, 0x43, 0x20, 0x19, 0x7c, 0x1a, 0xf4, 0x5f, 0x74, 0x18, 0x15, 0x7a, 0x36, 0x65, 0x55, 0x70, 0x69, 0x40, 0x29, 0xe7, 0xc9, 0x9d, 0x05, 0xf2, 0xae, 0x54, 0x93, 0xde, 0x1c, 0x63, 0x3c, 0xcb, 0x98, 0x35, 0x9b, 0xcb, 0x3e, 0x22, 0x0c, 0x65, 0x16, 0x69, 0x66, 0x06, 0x86, 0x91, 0x84, 0xd5, 0x80, 0x0f, 0xc2, 0x7b, 0x34, 0xb9, 0x2a, 0x3e, 0xfc, 0x04, 0x13, 0x34, 0x85, 0x77, 0x7a, 0x2d, 0xcb, 0x75, 0x7c, 0x7a, 0x3a, 0x36, 0xd7, 0xda, 0x5e, 0x6c, 0xbf, 0x8f, 0x2e, 0x94, 0x7c, 0x58, 0x66, 0xd7, 0xab, 0x9b, 0x8d, 0x96, 0x4d, 0xa9, 0xa3, 0xfb, 0x78, 0xd9, 0x3e, 0x5c, 0xf7, 0xea, 0x5e, 0x1d, 0x4d, 0xd0, 0xf9, 0x0f, 0x64, 0xf9, 0xec, 0xfc, 0xfc, 0xa3, 0x62, 0x20, 0x94, 0xd8, 0x7a, 0x59, 0x09, 0xab, 0x04, 0x93, 0x03, 0xc2, 0x0f, 0x25, 0x58, 0x6a, 0x65, 0x1a, 0x89, 0xe4, 0x65, 0x55, 0x34, 0xf2, 0xc9, 0x57, 0xa0, 0x21, 0x6a, 0x0c, 0xa2, 0x55, 0x31, 0x85, 0xdc, 0xb8, 0xff, 0x79, 0xd0, 0x2c, 0x9c, 0x51, 0xba, 0x45, 0x26, 0xab, 0x0c, 0xc7, 0x3d, 0xf3, 0x13, 0x1d, 0x8b, 0x4f, 0x7c, 0x19, 0x65, 0x9b, 0x37, 0x55, 0x21, 0xea, 0xb6, 0x2d, 0xa3, 0x1b, 0x94, 0x13, 0x0a, 0x4c, 0x5f, 0x2b, 0xb0, 0x3e, 0x63, 0x53, 0xb5, 0x29, 0xc9, 0x38, 0xd7, 0x5a, 0x6c, 0x6c, 0x20, 0x1e, 0x46, 0xa1, 0xb2, 0x93, 0x8a, 0x4b, 0xdd, 0x64, 0x3b, 0x1b, 0x75, 0x4f, 0x0d, 0xcc, 0xa5, 0x30, 0x8e, 0xc6, 0xb5, 0x3c, 0x66, 0x04, 0x6a, 0x63, 0xca, 0xed, 0xa3, 0x02, 0x25, 0x1b, 0xa8, 0x27, 0x01, 0xc4, 0x84, 0xb4, 0xe4, 0x5d, 0x61, 0x7c, 0x85, 0x71, 0xd7, 0x40, 0x42, 0x89, 0x82, 0x8a, 0xae, 0x94, 0x01, 0xcd, 0xac, 0x88, 0xe7, 0x1f, 0xad, 0x2a, 0x55, 0x75, 0xe1, 0xb1, 0x14, 0xc1, 0x8d, 0x41, 0x03, 0xde, 0x6e, 0xfb, 0x88, 0x18, 0x28, 0x61, 0xd5, 0x28, 0x61, 0x24, 0x70, 0xa0, 0xe7, 0x55, 0xa0, 0x67, 0x2c, 0x34, 0xe4, 0x3d, 0x8a, 0x4e, 0xa3, 0xed, 0x66, 0x27, 0x58, 0xf9, 0xb5, 0x70, 0xaf, 0xa3, 0x6d, 0xf3, 0xbe, 0x66, 0x94, 0xef, 0xc5, 0xed, 0xac, 0x93, 0xa0, 0x92, 0xa5, 0x93, 0xc5, 0x6e, 0x0d, 0xf8, 0xa0, 0x8c, 0x83, 0x1f, 0xc9, 0x54, 0x9a, 0x9c, 0xb9, 0x77, 0x66, 0x18, 0x8c, 0x49, 0xc1, 0x65, 0xf7, 0x15, 0xa5, 0x7b, 0x0b, 0x1c, 0x58, 0x29, 0x26, 0xe5, 0x0e, 0x02, 0xa7, 0x5f, 0xf9, 0xb4, 0xf6, 0x3e, 0xae, 0x80, 0x92, 0x87, 0xc9, 0x04, 0x4f, 0xc9, 0x6a, 0x89, 0x94, 0x97, 0x39, 0x44, 0x12, 0xea, 0x96, 0x9a, 0xfa, 0xd1, 0x71, 0x06, 0xc0, 0x24, 0x2b, 0x46, 0x25, 0xa9, 0x95, 0x23, 0x4e, 0x0a, 0x59, 0x19, 0x2a, 0xaa, 0xd2, 0x9b, 0x81, 0xb2, 0x32, 0xa5, 0xe6, 0x47, 0x3a, 0x3e, 0x5d, 0x7f, 0x3a, 0x0f, 0x83, 0x03, 0xa7, 0x39, 0x5d, 0x97, 0xe5, 0x66, 0x62, 0xb1, 0x20, 0xff, 0x15, 0x26, 0x14, 0x83, 0x17, 0xbe, 0x12, 0x75, 0x3a, 0x2d, 0xa7, 0xe4, 0x2c, 0x8c, 0x65, 0x72, 0x66, 0x65, 0x31, 0x0f, 0x83, 0x36, 0x29, 0x0c, 0xda, 0xa4, 0x31, 0x84, 0xd3, 0x29, 0xd4, 0x8c, 0x7d, 0x10, 0x23, 0xe6, 0x9c, 0xaa, 0xa8, 0x6c, 0x0b, 0x99, 0x60, 0xd9, 0x51, 0x41, 0x96, 0xb6, 0x0e, 0x4a, 0xea, 0x04, 0x18, 0x34, 0xef, 0xeb, 0xb8, 0x51, 0x0d, 0x15, 0x51, 0x4b, 0xd5, 0xb0, 0xb8, 0x49, 0xa0, 0x98, 0x51, 0x89, 0xd5, 0x11, 0x60, 0x0a, 0x45, 0xaa, 0x3e, 0x72, 0x4d, 0x49, 0x57, 0xaa, 0x5c, 0x07, 0x1f, 0x8b, 0x99, 0xac, 0x4c, 0xae, 0x40, 0x69, 0xd2, 0x74, 0x75, 0x07, 0x85, 0xce, 0xd3, 0x9b, 0x8d, 0x12, 0xd3, 0x1c, 0xd0, 0x88, 0x9b, 0x85, 0x2b, 0xbf, 0x25, 0xc3, 0xe0, 0x42, 0x76, 0xbc, 0xbf, 0x1d, 0xfc, 0x4d, 0x53, 0xdd, 0xad, 0xd0, 0xf9, 0x4f, 0x64, 0x75, 0xb0, 0x4c, 0xb9, 0x99, 0x43, 0x2c, 0x5f, 0xe3, 0x00, 0x8e, 0x64, 0x67, 0x9d, 0xff, 0xbd, 0xf4, 0xd2, 0x8d, 0x1b, 0x23, 0x66, 0x58, 0x2d, 0x26, 0xbb, 0xc8, 0xae, 0xe9, 0x6b, 0xb2, 0x71, 0x98, 0xe2, 0xd0, 0x88, 0xf9, 0xe7, 0x97, 0x64, 0xca, 0xa3, 0x90, 0xcd, 0xe6, 0x25, 0x3d, 0x73, 0xf3, 0x12, 0xbd, 0x71, 0x29, 0x90, 0x29, 0xbd, 0xff, 0x29, 0x2b, 0xe6, 0xc7, 0x70, 0x64, 0x0c, 0xce, 0xce, 0xb7, 0x39, 0xa9, 0xd2, 0x7b, 0x8b, 0xbb, 0x6d, 0x9a, 0xca, 0x77, 0x2f, 0x3b, 0x83, 0x60, 0x88, 0x90, 0xae, 0x80, 0x87, 0x09, 0x0e, 0xd1, 0xe1, 0xe6, 0x0a, 0x11, 0xd1, 0xc4, 0x88, 0x90, 0x21, 0xd1, 0x39, 0x2c, 0xea, 0x9f, 0xc6, 0xb5, 0x3c, 0xa6, 0x01, 0xaa, 0x60, 0xd2, 0xcd, 0xd6, 0x00, 0x5b, 0xda, 0x7f, 0x45, 0x25, 0x4c, 0x9d, 0xda, 0x8a, 0xa2, 0xd6, 0x83, 0x1b, 0x23, 0x40, 0x2e, 0x5b, 0x83, 0x6d, 0xda, 0x50, 0xa3, 0xa0, 0x65, 0x12, 0x68, 0x98, 0xba, 0xb1, 0x59, 0x7d, 0x58, 0xfe, 0xe2, 0x2f, 0x2f, 0x28, 0x29, 0x50, 0x94, 0xb1, 0xd6, 0x2b, 0xec, 0x13, 0xec, 0x1c, 0x35, 0x39, 0x4b, 0x22, 0x8c, 0x63, 0xcf, 0xf5, 0xce, 0xb8, 0xe1, 0xe6, 0xaf, 0x54, 0x5b, 0x06, 0x98, 0x4a, 0xcc, 0x8f, 0x36, 0xb1, 0x6e, 0xaa, 0xa7, 0xb2, 0x04, 0xfe, 0xef, 0xf1, 0xeb, 0xf7, 0x58, 0x59, 0x83, 0x2b, 0xce, 0x6c, 0x28, 0x79, 0xf9, 0x16, 0x0e, 0x5e, 0x58, 0xd0, 0x44, 0xf4, 0x72, 0x18, 0xb7, 0xa1, 0x7d, 0xab, 0xc6, 0xb9, 0x9b, 0x85, 0x29, 0xed, 0x9d, 0x71, 0xce, 0xbd, 0x10, 0xc2, 0x4b, 0x09, 0x97, 0x98, 0xe9, 0x58, 0xfb, 0x20, 0xe7, 0xc4, 0x47, 0xd3, 0x7b, 0xfd, 0x52, 0xdd, 0x5c, 0x77, 0x81, 0x1b, 0xd4, 0xb1, 0x29, 0x9a, 0xb6, 0xe8, 0x5d, 0x14, 0xf1, 0x6a, 0x32, 0xa8, 0x4b, 0x6f, 0xe8, 0x8b, 0xfb, 0x7f, 0xa8, 0x6d, 0x84, 0xd4, 0x03, 0x58, 0x45, 0x31, 0x06, 0xc4, 0x9c, 0x9c, 0x0e, 0xdc, 0xf7, 0xb7, 0xa6, 0x4a, 0xb0, 0x41, 0xfb, 0x2d, 0x82, 0x64, 0x01, 0x79, 0x1c, 0x21, 0xbd, 0xdb, 0xad, 0xc7, 0x68, 0xea, 0x96, 0xa4, 0xdf, 0xaf, 0xa9, 0x2d, 0xdc, 0x65, 0x23, 0x94, 0xdc, 0x95, 0xb7, 0x09, 0x1f, 0x7e, 0x5a, 0xee, 0x8d, 0x53, 0x6d, 0xc2, 0x63, 0x32, 0x23, 0x6c, 0xbc, 0xf6, 0x1a, 0xc3, 0x0f, 0xb5, 0x37, 0xf0, 0xa6, 0xea, 0x1c, 0x49, 0x31, 0xe6, 0x19, 0xc0, 0xa0, 0xe8, 0xaa, 0x42, 0x0c, 0x23, 0x13, 0x4d, 0x89, 0x73, 0x10, 0x38, 0x46, 0x9d, 0x74, 0x7b, 0x08, 0x08, 0x99, 0xa0, 0xe3, 0x74, 0x2c, 0x8b, 0x34, 0x98, 0xd2, 0x89, 0x33, 0x2a, 0xcb, 0x35, 0xb4, 0x90, 0x4c, 0x71, 0x3d, 0x0b, 0xf2, 0x64, 0x96, 0x19, 0xbb, 0x15, 0x77, 0x11, 0x82, 0x99, 0x4e, 0x06, 0xcd, 0x74, 0x41, 0x6e, 0x91, 0xdc, 0x2a, 0xec, 0x96, 0xc6, 0x80, 0x84, 0xc4, 0xac, 0x40, 0xb3, 0x09, 0x93, 0xaa, 0x1c, 0xb3, 0xaa, 0xb6, 0x86, 0x05, 0x2f, 0xeb, 0xeb, 0x00, 0xf5, 0x70, 0x07, 0xb8, 0xc5, 0xd5, 0xc7, 0x72, 0x1d, 0x6f, 0x75, 0x73, 0xd7, 0xc3, 0xdd, 0xe4, 0xef, 0xf5, 0xa6, 0x5d, 0x2c, 0x0f, 0x2a, 0x3c, 0xc7, 0x72, 0x13, 0x5f, 0x19, 0x57, 0x3b, 0x20, 0x35, 0xa5, 0x6d, 0x9d, 0x7b, 0xac, 0x15, 0x42, 0x81, 0x4f, 0xdc, 0x81, 0xb1, 0x4b, 0xe5, 0xb5, 0xf3, 0x36, 0x6f, 0xef, 0xdb, 0x4a, 0xea, 0xf6, 0xbb, 0xaf, 0x38, 0x60, 0x85, 0xf5, 0xb7, 0x31, 0xce, 0x17, 0x68, 0x5d, 0xe1, 0x00, 0xe0, 0x89, 0x14, 0xf0, 0x48, 0x56, 0xcd, 0x96, 0x8c, 0x40, 0x22, 0xcd, 0x80, 0x46, 0x30, 0xe1, 0x33, 0xe4, 0x14, 0x55, 0x69, 0x53, 0xe7, 0x29, 0xe8, 0x29, 0x99, 0x98, 0x1c, 0xa3, 0x0c, 0x5b, 0x06, 0xc0, 0x7d, 0xd8, 0x4e, 0x1c, 0x13, 0x18, 0xd0, 0x28, 0xdd, 0x30, 0x8a, 0xa9, 0x87, 0x25, 0x27, 0x26, 0xb1, 0x49, 0x57, 0x46, 0x34, 0xcd, 0xce, 0x79, 0x49, 0x2f, 0xd8, 0x26, 0x62, 0x11, 0xf1, 0x0c, 0x96, 0x1a, 0x13, 0xff, 0x40, 0x89, 0x65, 0x8d, 0x37, 0x5c, 0x7f, 0x88, 0x84, 0xc2, 0x81, 0x52, 0x14, 0x48, 0x2a, 0x51, 0x71, 0x54, 0xc7, 0x5e, 0x3a, 0xaf, 0x40, 0x6c, 0xc1, 0xbd, 0x18, 0xe7, 0x86, 0xa5, 0xca, 0xe9, 0x24, 0xe7, 0xa6, 0xb9, 0x87, 0x4d, 0x3a, 0x5d, 0xe1, 0x1a, 0x74, 0x81, 0xd8, 0xdb, 0xee, 0x43, 0xcf, 0xcd, 0xe6, 0x75, 0x94, 0x6b, 0x12, 0x4f, 0x86, 0x81, 0x21, 0xc0, 0x27, 0xcd, 0x60, 0x2d, 0xca, 0xce, 0x62, 0xa5, 0x6d, 0xa8, 0x7a, 0xe3, 0x2b, 0x83, 0x48, 0xf0, 0x2a, 0xbf, 0xc6, 0x35, 0x39, 0xac, 0x75, 0x65, 0x29, 0x78, 0x98, 0x7e, 0xa4, 0x46, 0x11, 0xc8, 0x11, 0xf7, 0x0a, 0xc5, 0xf9, 0x22, 0x2f, 0x07, 0x41, 0x2d, 0xcc, 0x34, 0x52, 0x35, 0x42, 0x2a, 0x4d, 0x87, 0x10, 0x2b, 0x2b, 0xc2, 0x4c, 0x0d, 0x96, 0x58, 0xe0, 0x5e, 0xf2, 0x44, 0x6e, 0x78, 0x58, 0x9c, 0xbf, 0xea, 0x2a, 0xca, 0x4c, 0x9b, 0x41, 0x67, 0xeb, 0x57, 0x71, 0xb0, 0x61, 0xf0, 0x39, 0xf5, 0xcd, 0x16, 0xd3, 0xa0, 0x08, 0x7e, 0xb2, 0xef, 0x66, 0x82, 0xfd, 0x3e, 0xa7, 0x66, 0x7a, 0x50, 0x8e, 0xd5, 0x19, 0x59, 0xaa, 0xd6, 0xed, 0xa3, 0x99, 0x77, 0x34, 0x4c, 0x5b, 0xbb, 0x33, 0x4c, 0x4e, 0x77, 0xea, 0x95, 0x0a, 0x8c, 0x88, 0x64, 0xee, 0x6c, 0x8c, 0x88, 0xa7, 0x32, 0x83, 0xcd, 0xa6, 0x1e, 0xe2, 0xd8, 0x95, 0x6f, 0x53, 0x66, 0x93, 0x42, 0x91, 0xac, 0xab, 0x59, 0xba, 0x9b, 0x05, 0xeb, 0xcf, 0xb4, 0x68, 0xa3, 0x8f, 0xfd, 0x1d, 0x6a, 0x20, 0x56, 0x0b, 0x85, 0x72, 0xf5, 0xa4, 0x79, 0xfc, 0xc8, 0x70, 0x7c, 0xe2, 0xe8, 0x97, 0xcd, 0xd9, 0xa8, 0x0a, 0x84, 0x5f, 0x53, 0xf8, 0xc1, 0x8f, 0x3a, 0x4c, 0x3c, 0xc9, 0xe1, 0x09, 0x34, 0x52, 0x7a, 0xad, 0xbd, 0xe5, 0x1b, 0x10, 0xcd, 0x18, 0x8f, 0x40, 0x85, 0x12, 0x84, 0xf5, 0xf5, 0xb6, 0xcb, 0x20, 0xa7, 0xbc, 0x8d, 0x35, 0x65, 0x2e, 0xf0, 0xc2, 0x44, 0x47, 0x7c, 0xa4, 0x87, 0xd7, 0xfa, 0x2a, 0x94, 0xee, 0xb9, 0x8b, 0x41, 0xf6, 0x34, 0x83, 0xcf, 0x1b, 0xa7, 0x26, 0x85, 0x91, 0x1e, 0x3d, 0x85, 0x11, 0xc5, 0xa6, 0x2e, 0x5d, 0x6a, 0x1e, 0x41, 0x45, 0x0d, 0x7b, 0xab, 0xef, 0x97, 0x6e, 0x7a, 0xe9, 0x06, 0x8e, 0xfe, 0x60, 0xe5, 0x66, 0xae, 0x16, 0x81, 0x64, 0xe6, 0x62, 0xdd, 0x86, 0x3e, 0xb8, 0x15, 0x0d, 0xf4, 0xec, 0x0d, 0x7d, 0x6c, 0x9f, 0x6d, 0x9d, 0x44, 0x70, 0x6e, 0x41, 0x79, 0x97, 0x73, 0x8f, 0xb0, 0x4c, 0xb8, 0xb6, 0x42, 0x15, 0xce, 0x35, 0xd1, 0xf0, 0x60, 0x00, 0x88, 0x55, 0x19, 0x6c, 0xba, 0x32, 0x58, 0xe9, 0x78, 0x16, 0x1a, 0x18, 0x03, 0x22, 0x58, 0x05, 0x79, 0xca, 0x25, 0x0c, 0x48, 0x86, 0x51, 0x81, 0x71, 0xdd, 0x48, 0x30, 0x4e, 0x0b, 0xd1, 0x0e, 0xb9, 0x89, 0xbe, 0x83, 0xa3, 0xec, 0x79, 0x1b, 0xe2, 0xd7, 0x78, 0x85, 0x07, 0xb8, 0xc4, 0x0b, 0x13, 0xe6, 0xd8, 0xee, 0x5d, 0xcd, 0xc1, 0x9f, 0x68, 0x35, 0xb0, 0x69, 0x5c, 0xfb, 0x32, 0xd6, 0x2e, 0x8e, 0x46, 0x44, 0xea, 0x1d, 0xf2, 0x09, 0xb4, 0xc7, 0xea, 0xb0, 0x2d, 0x74, 0x20, 0x75, 0x38, 0xdb, 0x14, 0x9a, 0x84, 0x1e, 0x1c, 0xa3, 0x59, 0x9e, 0x26, 0x04, 0x3a, 0x64, 0x66, 0x97, 0x82, 0x92, 0xa4, 0x13, 0xd1, 0x06, 0xdf, 0x14, 0x86, 0x54, 0x4c, 0x99, 0xf0, 0xa1, 0x86, 0x79, 0x01, 0x3d, 0x46, 0x00, 0x5e, 0xcd, 0x5c, 0xff, 0x8d, 0xca, 0x2b, 0xa0, 0xe4, 0x3e, 0x4c, 0xeb, 0xf6, 0xc5, 0x6f, 0x0b, 0x38, 0xdf, 0x19, 0xa3, 0x6a, 0x1a, 0x63, 0xfa, 0xe8, 0x6c, 0x98, 0xe0, 0x0a, 0xa2, 0x70, 0x9b, 0x3a, 0x14, 0x41, 0x27, 0xce, 0x44, 0x98, 0x38, 0x19, 0xcb, 0xae, 0x9d, 0x23, 0x3c, 0x8e, 0x14, 0x51, 0x9d, 0x94, 0x77, 0x24, 0x13, 0x8f, 0xab, 0xc8, 0x94, 0xdd, 0xa7, 0xd4, 0x6b, 0x18, 0x2c, 0x21, 0x4a, 0x31, 0x1b, 0x7c, 0x07, 0xc7, 0x22, 0xe7, 0xf4, 0x11, 0xe8, 0xc2, 0x24, 0xab, 0x0d, 0x37, 0xb0, 0x08, 0xfe, 0x0a, 0x53, 0x52, 0x7f, 0x1a, 0xc1, 0xc3, 0x56, 0xa5, 0x01, 0x91, 0x1a, 0x60, 0x11, 0x87, 0xa1, 0x78, 0xaf, 0xca, 0xa4, 0xf2, 0x35, 0x8e, 0x8e, 0x29, 0xcf, 0x09, 0x03, 0x8f, 0xcb, 0x20, 0x79, 0xe0, 0x48, 0x01, 0xaf, 0xda, 0x00, 0x2f, 0x2a, 0xb0, 0x16, 0x8b, 0x95, 0x2c, 0xa7, 0xb4, 0xbf, 0xe5, 0x24, 0x8b, 0x2d, 0x8f, 0x61, 0xf0, 0x07, 0xb0, 0xe0, 0x51, 0x6f, 0xcb, 0x31, 0xdd, 0xa2, 0x13, 0x95, 0xcb, 0x37, 0xc0, 0x36, 0x48, 0x1d, 0xbe, 0x47, 0x09, 0xde, 0x66, 0x77, 0x86, 0x8f, 0x2e, 0x92, 0x7b, 0xa1, 0xbe, 0xce, 0x0f, 0xc0, 0xdc, 0x99, 0x1f, 0x58, 0x59, 0x32, 0x0c, 0xae, 0x12, 0x53, 0xb3, 0x7e, 0x0f, 0xe3, 0xf0, 0xce, 0x78, 0xbb, 0x20, 0xcb, 0x63, 0x2b, 0xde, 0x9d, 0x13, 0x3d, 0x6f, 0x03, 0xb9, 0xa5, 0x4f, 0x88, 0x96, 0x26, 0x79, 0xfc, 0xb9, 0x24, 0x5d, 0x98, 0x21, 0x02, 0x9b, 0xfe, 0xe5, 0x00, 0x3b, 0x07, 0x01, 0x7f, 0xb8, 0x4b, 0x08, 0x70, 0x3c, 0x13, 0x3e, 0x11, 0x06, 0xe4, 0xa9, 0x38, 0xe0, 0xf2, 0x19, 0xe3, 0x29, 0x78, 0x3f, 0x78, 0x32, 0x1c, 0x6a, 0xc1, 0x1a, 0x5e, 0x30, 0xcd, 0x30, 0x9c, 0x5e, 0x19, 0xfe, 0xa6, 0x4d, 0x2e, 0xea, 0xe7, 0xef, 0x42, 0x78, 0xde, 0x84, 0xf0, 0x06, 0x27, 0x6a, 0xa3, 0x86, 0x75, 0xf0, 0x44, 0x99, 0x44, 0x74, 0x61, 0xb6, 0xae, 0x7d, 0xc7, 0x78, 0xd5, 0x61, 0x99, 0x73, 0x2f, 0xc9, 0x13, 0x7f, 0x6c, 0x74, 0x0d, 0x67, 0x44, 0x4f, 0x14, 0x33, 0xa3, 0x70, 0x86, 0x8d, 0x51, 0x89, 0x14, 0xdf, 0xf5, 0x6b, 0x07, 0x29, 0x58, 0xaa, 0xb8, 0xc2, 0x6e, 0x28, 0xae, 0x88, 0x90, 0xbb, 0x72, 0xfb, 0xe2, 0x18, 0x6c, 0x27, 0xa6, 0x84, 0xc5, 0x64, 0xc2, 0x15, 0xf7, 0x85, 0xee, 0x09, 0x62, 0xbf, 0x24, 0xcf, 0x6b, 0xc4, 0x74, 0x77, 0xf7, 0xd3, 0x06, 0x57, 0x68, 0xe2, 0xc7, 0xfc, 0xed, 0x4c, 0x77, 0x86, 0x4c, 0x40, 0x6d, 0x89, 0x33, 0xf1, 0x8b, 0x07, 0xb1, 0x83, 0x9b, 0xc4, 0x8d, 0x9e, 0xce, 0xcc, 0x53, 0x18, 0x5b, 0x9c, 0xdb, 0xe4, 0xbc, 0x48, 0x98, 0xe5, 0xf1, 0xd1, 0xe5, 0xe0, 0x14, 0xc6, 0xec, 0xe8, 0xfd, 0xff, 0x3e, 0x7d, 0xf8, 0xfb, 0x51, 0xeb, 0xbe, 0xf4, 0x32, 0x5a, 0x9c, 0x4e, 0x8c, 0xf4, 0xf4, 0xd9, 0xa0, 0x9b, 0x2d, 0x73, 0x17, 0x23, 0xe8, 0x2d, 0x73, 0x31, 0x14, 0xfc, 0x0e, 0x8f, 0x85, 0x8f, 0x58, 0x6f, 0x43, 0x92, 0x74, 0xbf, 0xd5, 0xde, 0x9b, 0xd9, 0xe9, 0x3c, 0x81, 0xd9, 0x22, 0x94, 0x37, 0xe6, 0x0f, 0xc3, 0x85, 0x48, 0x69, 0x37, 0x63, 0x88, 0x42, 0x2a, 0x9a, 0xcd, 0x30, 0x76, 0xd0, 0xd5, 0x08, 0x93, 0xbc, 0xf2, 0x1d, 0xff, 0x58, 0xf2, 0x6e, 0x2c, 0xf9, 0x26, 0x63, 0xce, 0xd9, 0xc4, 0x51, 0x92, 0x2d, 0x63, 0xda, 0x2f, 0xbc, 0x15, 0x72, 0xd7, 0x51, 0x0a, 0x8c, 0xa4, 0x8f, 0xe2, 0xe6, 0x93, 0x9b, 0xac, 0xab, 0x36, 0xf8, 0x7e, 0x80, 0x47, 0x40, 0xbe, 0xa6, 0xf7, 0xcf, 0xec, 0x15, 0xdf, 0x73, 0x58, 0xd5, 0xa4, 0xe2, 0x0f, 0x4d, 0x90, 0x51, 0x3e, 0x67, 0x0a, 0x2a, 0xca, 0x27, 0x5d, 0x32, 0xb6, 0x27, 0xdd, 0xd7, 0x89, 0xed, 0x2d, 0x8e, 0xd2, 0x77, 0xe2, 0x0e, 0x58, 0xb4, 0x2d, 0x02, 0x78, 0xfb, 0x11, 0x65, 0xb7, 0x66, 0x1e, 0x16, 0xe1, 0xae, 0xc4, 0xdb, 0xae, 0xae, 0xfe, 0x02, 0x41, 0x47, 0x0f, 0x1a, 0x02, 0x81, 0x00, 0x00 }; z_const size_t kPhoneNumberMetaDataCompressedLength = sizeof(kPhoneNumberMetaData); z_const size_t kPhoneNumberMetaDataExpandedLength = 33026; #else // TESTING == 1 z_const Bytef kPhoneNumberMetaData[] = { 0x1f, 0x8b, 0x08, 0x08, 0x8b, 0x26, 0xbe, 0x5b, 0x00, 0x03, 0x50, 0x68, 0x6f, 0x6e, 0x65, 0x4e, 0x75, 0x6d, 0x62, 0x65, 0x72, 0x4d, 0x65, 0x74, 0x61, 0x44, 0x61, 0x74, 0x61, 0x2e, 0x6a, 0x73, 0x6f, 0x6e, 0x00, 0xec, 0xbd, 0x59, 0x8f, 0x1b, 0xc7, 0x96, 0x2e, 0xfa, 0x57, 0x0c, 0xc2, 0x0f, 0x45, 0x80, 0x04, 0x62, 0x1e, 0xfa, 0x45, 0xb0, 0x64, 0x5b, 0x96, 0x25, 0xd9, 0xde, 0x96, 0xec, 0xbd, 0x6d, 0x16, 0x1f, 0x1a, 0xb7, 0x1b, 0x17, 0x17, 0x38, 0xe8, 0x7d, 0x70, 0xd0, 0x07, 0xb8, 0x17, 0x3b, 0x75, 0x7e, 0xfb, 0x8d, 0x35, 0x44, 0xe4, 0x14, 0x91, 0x4c, 0x92, 0x55, 0xa5, 0x92, 0xab, 0x7a, 0x90, 0x8b, 0x64, 0xc6, 0x90, 0x99, 0x11, 0x2b, 0xd6, 0xf0, 0xad, 0x6f, 0xfd, 0x6b, 0xf3, 0x7f, 0xfd, 0xf3, 0x7f, 0xff, 0xd7, 0x7f, 0xff, 0xaf, 0xff, 0xef, 0xd5, 0x3f, 0xff, 0xe3, 0x3f, 0x3f, 0xfe, 0xf3, 0xd7, 0xff, 0xfc, 0xbf, 0xff, 0x9f, 0x7f, 0xfe, 0x17, 0xfc, 0xfd, 0xfe, 0xdf, 0xff, 0xe7, 0xe6, 0xdf, 0xfe, 0xb5, 0x91, 0x9b, 0x7f, 0x3b, 0x6c, 0x7e, 0xfb, 0xb0, 0xd9, 0x6d, 0xbe, 0x79, 0x0d, 0xff, 0xbc, 0x81, 0x7f, 0xe0, 0xe3, 0xcb, 0x97, 0xf0, 0xcf, 0x7b, 0xf8, 0x07, 0x3e, 0xbe, 0xfa, 0x26, 0xfd, 0xf3, 0x2d, 0x7c, 0xfc, 0xf6, 0xe7, 0xf4, 0xcf, 0xeb, 0x6f, 0xe1, 0x9f, 0xdf, 0xd2, 0x3f, 0x3f, 0xc2, 0x77, 0x6f, 0x7f, 0x82, 0x7f, 0xfe, 0x48, 0xff, 0xbc, 0x7b, 0x95, 0xfe, 0x79, 0xff, 0x0b, 0xfc, 0x03, 0xcd, 0x7e, 0xf9, 0x35, 0xfd, 0xf3, 0xe1, 0x1f, 0xe9, 0x9f, 0x8f, 0xf0, 0xc3, 0xc7, 0x8f, 0xe9, 0x9f, 0xdf, 0xe1, 0xaf, 0xdf, 0x61, 0xb4, 0xdf, 0xdf, 0x6c, 0x8e, 0xbb, 0x8d, 0x87, 0x29, 0xfc, 0x0a, 0x7d, 0xbd, 0xfd, 0x13, 0x3e, 0x2b, 0x01, 0x5f, 0x7c, 0xf7, 0x1a, 0xff, 0xc6, 0x1f, 0xff, 0xfc, 0x06, 0xfe, 0xd6, 0xf8, 0xfd, 0xeb, 0x5f, 0xf1, 0x6f, 0x9c, 0xf7, 0x4f, 0xef, 0xf0, 0x6f, 0x05, 0x7f, 0xbf, 0xfc, 0x0e, 0xff, 0xd6, 0xf0, 0xf7, 0xf7, 0x74, 0x8d, 0xc1, 0x7e, 0x3e, 0xe0, 0xdf, 0x0e, 0xfe, 0xfe, 0xe1, 0x37, 0xfc, 0x3b, 0xc2, 0xdf, 0x6f, 0x70, 0x2a, 0xd8, 0xb1, 0xc1, 0x8e, 0x7f, 0xfd, 0x19, 0xff, 0xc6, 0x8e, 0x5f, 0xfd, 0x80, 0x7f, 0x63, 0x67, 0xdf, 0x7c, 0xc4, 0xbf, 0xb1, 0xb3, 0xd7, 0xf0, 0x50, 0x5e, 0xc3, 0xd4, 0xdf, 0xc0, 0x6d, 0xff, 0x88, 0x63, 0x1a, 0x0b, 0x3f, 0x7d, 0xfb, 0x16, 0xff, 0xc6, 0x71, 0x3e, 0xd0, 0xf7, 0x38, 0xf7, 0x9f, 0xe0, 0x71, 0x7d, 0xf8, 0x11, 0xbf, 0x08, 0xf0, 0xc5, 0x2f, 0x38, 0x69, 0x83, 0x93, 0xf8, 0x16, 0x2f, 0xb4, 0x38, 0xe6, 0x2f, 0xf4, 0x37, 0xde, 0xcc, 0xfb, 0x7f, 0xe0, 0xdf, 0x38, 0xfe, 0x2b, 0x9c, 0xb4, 0xc5, 0xf1, 0xbf, 0xc1, 0x1b, 0xb3, 0x38, 0xe0, 0x4b, 0xfa, 0x1b, 0x07, 0x7c, 0x85, 0x7d, 0x5a, 0x1c, 0xf0, 0x15, 0xde, 0x87, 0xc5, 0xb1, 0x7e, 0xc7, 0x3e, 0x1d, 0xde, 0xdf, 0xfb, 0x3f, 0xf0, 0x6f, 0x1c, 0xeb, 0x1b, 0x78, 0xda, 0xaf, 0xe0, 0x3d, 0xbc, 0xc2, 0x91, 0x1c, 0x8e, 0xfa, 0xe6, 0x5b, 0xfc, 0x1b, 0x47, 0xfd, 0x05, 0x9f, 0x80, 0xc3, 0x51, 0x7f, 0xc2, 0xd7, 0xe2, 0x70, 0xd4, 0x0f, 0xf8, 0x5a, 0x1c, 0x8e, 0xfa, 0x11, 0xaf, 0x09, 0xd8, 0xe3, 0x8f, 0xbf, 0xe0, 0xdf, 0xd8, 0xcf, 0x5b, 0x9c, 0x59, 0xc0, 0xb6, 0xbf, 0xff, 0x84, 0x7f, 0xd3, 0x2c, 0xf1, 0xef, 0x88, 0xb3, 0xf9, 0x88, 0xd7, 0x44, 0x6c, 0xfb, 0x86, 0xbe, 0xc7, 0xb6, 0xbf, 0xe0, 0x63, 0x8c, 0xf4, 0xe4, 0xbf, 0xc7, 0xbf, 0xb1, 0x9f, 0x77, 0xf4, 0x3d, 0xce, 0xe1, 0xfd, 0x7b, 0xfc, 0x1b, 0xef, 0xf0, 0x0d, 0xf6, 0xa3, 0x24, 0x76, 0xf4, 0xe1, 0x03, 0x7d, 0xa0, 0x67, 0x08, 0x2b, 0xf6, 0xbb, 0x1f, 0xe8, 0x1b, 0xec, 0xef, 0x5b, 0x5a, 0x5e, 0x92, 0x26, 0xff, 0x13, 0x7d, 0xc0, 0x5e, 0xde, 0xe1, 0xb3, 0x51, 0xb4, 0xf2, 0x5e, 0xbf, 0xa7, 0x0f, 0xd4, 0x25, 0x5d, 0xa6, 0xa8, 0x4b, 0x1a, 0x4c, 0x61, 0x6f, 0xef, 0xdf, 0xd1, 0x07, 0x5a, 0x18, 0x7c, 0x19, 0xce, 0xef, 0xd5, 0x1b, 0xfa, 0x80, 0xe3, 0xbc, 0xfc, 0x9e, 0x3e, 0xd0, 0x62, 0xf8, 0x8e, 0x3e, 0xe0, 0xa0, 0x1f, 0x69, 0x85, 0x2b, 0x5c, 0x09, 0x2f, 0x71, 0x85, 0x28, 0x5a, 0xe3, 0xef, 0x7f, 0xa3, 0x0f, 0x38, 0x83, 0x77, 0x34, 0x28, 0xad, 0xf2, 0x0f, 0x34, 0x28, 0x2d, 0xf3, 0xd7, 0x74, 0x73, 0xb4, 0xce, 0x7f, 0xa2, 0xde, 0x34, 0xce, 0xe0, 0xe3, 0xb7, 0xf4, 0x81, 0x1e, 0x3b, 0xcd, 0x40, 0xd3, 0xea, 0xa0, 0x9b, 0xd3, 0x38, 0x83, 0x57, 0xbf, 0xd3, 0x07, 0x9c, 0xc1, 0x07, 0x5c, 0xe7, 0x8a, 0x36, 0xc3, 0xeb, 0xbf, 0xd1, 0x07, 0x9c, 0xc1, 0xeb, 0x6f, 0xe8, 0x03, 0xce, 0xe0, 0x15, 0x8d, 0x43, 0x7b, 0xe3, 0x15, 0x8d, 0x43, 0x9b, 0xe3, 0x9b, 0x9f, 0xe9, 0x03, 0xce, 0xe0, 0xf5, 0xdf, 0xe9, 0x03, 0xce, 0xe0, 0x0d, 0xff, 0x82, 0x33, 0xf8, 0xe6, 0x15, 0x7d, 0xc0, 0x19, 0x7c, 0xe0, 0x0f, 0x34, 0x03, 0xea, 0xcd, 0xd2, 0x76, 0xa4, 0x0e, 0x68, 0x6f, 0x7c, 0x47, 0x73, 0xa3, 0xcd, 0xf1, 0x81, 0x7a, 0xa3, 0xdd, 0xf1, 0x2d, 0x3d, 0x37, 0xda, 0x1e, 0x6f, 0xe9, 0xf1, 0xd2, 0xfe, 0xf8, 0x48, 0x6f, 0x9b, 0x36, 0xc8, 0x6f, 0x34, 0x6b, 0xda, 0x21, 0x2f, 0xe9, 0xfd, 0xd0, 0x16, 0x79, 0x4f, 0x97, 0xd1, 0x1e, 0xf9, 0x93, 0x9e, 0x0e, 0x6d, 0x92, 0xf7, 0xd4, 0x86, 0xf6, 0xc6, 0xaf, 0xdf, 0xa5, 0xd5, 0xf4, 0x07, 0x4d, 0x83, 0x76, 0xc8, 0x9f, 0x34, 0x41, 0xde, 0x22, 0xf4, 0x88, 0x68, 0x8f, 0xbc, 0xe7, 0x5f, 0x70, 0xe4, 0x77, 0xb4, 0x26, 0x1d, 0x8d, 0xcc, 0xbf, 0xd0, 0xbd, 0xf3, 0xc8, 0x78, 0xef, 0x6f, 0x69, 0x64, 0xda, 0x1c, 0x1f, 0x7e, 0x00, 0x59, 0x49, 0x5d, 0xd2, 0x16, 0xf9, 0x8e, 0x16, 0x41, 0xa4, 0x27, 0x48, 0xbd, 0xd0, 0x06, 0xf8, 0x9e, 0x9e, 0x46, 0xc4, 0x5e, 0x5e, 0x93, 0x40, 0xa4, 0x27, 0xf8, 0xfa, 0x0d, 0x7d, 0x20, 0xe9, 0xf2, 0x91, 0x3e, 0xe0, 0xcd, 0xbc, 0x23, 0x39, 0x48, 0x4f, 0xf0, 0x0d, 0x09, 0x4e, 0x7a, 0x82, 0x6f, 0x48, 0x5a, 0xd2, 0x13, 0xfc, 0x86, 0x7b, 0xc3, 0xfb, 0x78, 0xcf, 0x1d, 0xd0, 0x2a, 0xfa, 0x83, 0x3e, 0xd0, 0x0c, 0xf0, 0xcc, 0xf8, 0x07, 0x7d, 0x43, 0x8b, 0x19, 0x9f, 0x9c, 0xf6, 0x38, 0x8d, 0x77, 0xd4, 0xd0, 0xd3, 0x62, 0xfe, 0x9d, 0x3e, 0xe0, 0x34, 0xbe, 0xa3, 0x91, 0x3d, 0x6d, 0xa7, 0x6f, 0xe9, 0x03, 0x2d, 0xa5, 0xf7, 0xf4, 0x81, 0x04, 0x1d, 0x0d, 0xe6, 0x71, 0x1a, 0xdf, 0xf0, 0x65, 0x38, 0x8d, 0xf7, 0xaf, 0xe8, 0x03, 0x3d, 0x4e, 0x6a, 0x13, 0x70, 0xd0, 0xdf, 0xe8, 0xc4, 0x20, 0xd9, 0xf4, 0x2b, 0xdd, 0x14, 0x09, 0xa7, 0xf7, 0x34, 0x68, 0xc0, 0x41, 0xff, 0xf1, 0x96, 0x3e, 0xe0, 0x38, 0x3f, 0xd0, 0xa9, 0x41, 0xb2, 0xea, 0x03, 0x3d, 0xbc, 0x40, 0xaf, 0x8d, 0x7b, 0xc3, 0x9b, 0x7b, 0x4f, 0x82, 0x9e, 0x64, 0xc5, 0xab, 0x3f, 0xe9, 0x03, 0xc9, 0x0a, 0xfe, 0x05, 0xbb, 0x7e, 0x87, 0x1d, 0x58, 0x81, 0x97, 0x7d, 0xff, 0x96, 0x3e, 0xe0, 0x65, 0x2f, 0xff, 0xa4, 0x0f, 0x38, 0x9d, 0xd7, 0x1f, 0xe9, 0x03, 0xb6, 0xf9, 0xf0, 0x3b, 0x7d, 0xc0, 0x67, 0xf0, 0xc3, 0x4f, 0xf4, 0x01, 0xe7, 0xf6, 0x13, 0xf7, 0x46, 0x1b, 0x9a, 0x24, 0xbf, 0xc0, 0xb9, 0xfd, 0xf2, 0x0d, 0x7d, 0xa0, 0xb3, 0xe5, 0x3d, 0x7d, 0xc0, 0x89, 0xfe, 0x40, 0x5d, 0xd3, 0x92, 0x7a, 0x0d, 0x47, 0xf2, 0xcb, 0x77, 0x70, 0x2e, 0x7f, 0x4f, 0x5f, 0xd3, 0x5c, 0xe8, 0xb0, 0x20, 0xd9, 0xfb, 0xfa, 0x0f, 0xfa, 0x80, 0x73, 0xf9, 0xee, 0x15, 0x7d, 0x20, 0xf1, 0xc6, 0x6d, 0x70, 0x2e, 0xbf, 0xf0, 0x65, 0xb4, 0x2c, 0xfe, 0x46, 0x1f, 0x70, 0x2e, 0x1f, 0x68, 0x62, 0xb4, 0x30, 0x7f, 0xe3, 0xcb, 0x70, 0x2e, 0xaf, 0xfe, 0x0e, 0xc3, 0xe3, 0xb5, 0x8e, 0x96, 0xc5, 0xc7, 0x77, 0xf4, 0x01, 0x47, 0xfe, 0xe9, 0x7b, 0xfa, 0x80, 0x23, 0xbf, 0xfc, 0x89, 0x3e, 0xd0, 0xc6, 0xfa, 0x95, 0x3e, 0xd0, 0xc8, 0x74, 0xf8, 0xd0, 0x4a, 0xf8, 0xf8, 0x33, 0x7d, 0xa0, 0x91, 0x5f, 0xd2, 0x07, 0x3a, 0xf5, 0x7e, 0xa3, 0x0f, 0x38, 0xf2, 0xf7, 0x28, 0x20, 0x1c, 0x2d, 0x8b, 0x5f, 0xfe, 0x4e, 0x1f, 0xf0, 0xde, 0xff, 0x4e, 0x83, 0xd2, 0xb2, 0x78, 0xf5, 0x96, 0x3e, 0xe0, 0x0c, 0x7e, 0xa2, 0x0e, 0x68, 0x59, 0xfc, 0xfd, 0x03, 0x7d, 0xc0, 0x41, 0xdf, 0xbe, 0xa1, 0x0f, 0x24, 0xcd, 0x5f, 0xd1, 0x07, 0x92, 0xe6, 0xbf, 0xd3, 0x07, 0x1c, 0xf4, 0x17, 0xea, 0x9a, 0x8f, 0x3a, 0xea, 0x9a, 0x1e, 0xf8, 0xf7, 0xef, 0xe9, 0x03, 0xad, 0x45, 0x3a, 0x40, 0x69, 0x8d, 0x88, 0xb4, 0x3a, 0xf0, 0x53, 0x18, 0x7e, 0xa2, 0xad, 0xfc, 0x96, 0x4e, 0x57, 0xda, 0xbd, 0x3f, 0xbc, 0xa5, 0x0f, 0xb4, 0x6d, 0x7e, 0xa6, 0x0f, 0x38, 0xd5, 0xb7, 0xd4, 0x1f, 0x6d, 0xd8, 0x77, 0xb8, 0x30, 0x82, 0x1f, 0x75, 0xee, 0x47, 0x9d, 0xd3, 0x43, 0x79, 0xf9, 0x2d, 0x7d, 0x90, 0xa3, 0x9f, 0xd4, 0xe8, 0x93, 0x1e, 0x7d, 0xa2, 0xe7, 0xff, 0x77, 0xfa, 0x30, 0xec, 0x31, 0xb2, 0xaa, 0xf1, 0x3b, 0x7d, 0xa0, 0x2d, 0xff, 0x92, 0x3e, 0x60, 0x87, 0x3f, 0xfe, 0x4c, 0x1f, 0x68, 0xb9, 0xff, 0x41, 0x1f, 0x48, 0xf2, 0xfc, 0x8d, 0x3e, 0xd0, 0x8d, 0xfc, 0x9d, 0x3e, 0xd0, 0x56, 0xfc, 0x86, 0x3e, 0xe0, 0x33, 0xff, 0xe3, 0x3b, 0xfa, 0x80, 0xa3, 0xfe, 0x4c, 0x8a, 0x00, 0xdd, 0xe2, 0x2f, 0x1f, 0xe8, 0x03, 0x29, 0x38, 0x74, 0x19, 0xad, 0xae, 0x37, 0xef, 0xe8, 0x03, 0xad, 0xae, 0x1f, 0xe8, 0x03, 0x0e, 0xfa, 0x37, 0xea, 0x9a, 0xe5, 0xcc, 0x47, 0xfa, 0x40, 0xeb, 0x9a, 0x74, 0x12, 0x5a, 0x5d, 0x3f, 0xfd, 0x42, 0x1f, 0xe2, 0xf0, 0x56, 0xe9, 0x15, 0x7e, 0xfc, 0x91, 0x3e, 0x60, 0xdf, 0x1f, 0x69, 0x3e, 0xb4, 0x67, 0xbe, 0xf9, 0x93, 0x3e, 0xd0, 0x71, 0x48, 0xf3, 0xa1, 0x3d, 0xf3, 0xf6, 0x35, 0x7d, 0xa0, 0x6d, 0x92, 0x2e, 0xfb, 0xb4, 0xcb, 0x5a, 0xfa, 0xc7, 0x7f, 0xbe, 0xff, 0xcf, 0xff, 0xfe, 0xf7, 0xff, 0xf8, 0xf7, 0xff, 0xfe, 0x77, 0x50, 0xce, 0x69, 0x65, 0xfc, 0xd7, 0xff, 0xfe, 0x1f, 0xff, 0x63, 0x47, 0xff, 0xe2, 0x3f, 0x9b, 0xdb, 0xdb, 0xff, 0xf8, 0x57, 0xf8, 0xb4, 0xd9, 0xf5, 0x5f, 0xd5, 0xfe, 0x39, 0x84, 0xe3, 0x71, 0xd8, 0x6c, 0xc5, 0x3f, 0x87, 0xbd, 0xbc, 0xbe, 0x4d, 0x6b, 0x7a, 0x1b, 0x99, 0x34, 0x15, 0x0b, 0x5b, 0xf4, 0xb3, 0x4c, 0xeb, 0x5e, 0xdb, 0xe0, 0xa2, 0xd8, 0xa5, 0xd7, 0xb5, 0xa6, 0x89, 0xdc, 0x1d, 0x68, 0x8c, 0xcd, 0x0d, 0x3c, 0x2a, 0xf3, 0x69, 0x9b, 0xff, 0x9b, 0x64, 0xe4, 0xd7, 0xf2, 0xab, 0xaf, 0xd5, 0x26, 0x75, 0x39, 0x7d, 0xeb, 0xab, 0xe7, 0x32, 0xf8, 0xfc, 0x40, 0x77, 0x7f, 0xd5, 0x88, 0x45, 0xe4, 0x7d, 0x61, 0xcb, 0xfc, 0xa1, 0xda, 0x3c, 0xa6, 0xed, 0x94, 0x97, 0x79, 0x78, 0x5e, 0xe6, 0x97, 0x2c, 0x73, 0x5f, 0x95, 0xe6, 0x07, 0x6d, 0xf7, 0xfe, 0xb8, 0x72, 0xb1, 0xc7, 0x3b, 0x58, 0x50, 0x37, 0x2f, 0xfe, 0x2d, 0x8d, 0xe9, 0x60, 0xc8, 0xce, 0x1f, 0xdc, 0x3e, 0x1c, 0xb7, 0x30, 0xba, 0xaf, 0xac, 0x31, 0x2d, 0x78, 0x95, 0xfd, 0x05, 0x65, 0xf6, 0x15, 0x1b, 0xc0, 0xaf, 0x92, 0xf3, 0xd4, 0x6e, 0xb8, 0x07, 0x34, 0xef, 0x81, 0xc1, 0x7f, 0xf3, 0x5e, 0xf8, 0xea, 0x6b, 0xbd, 0xd9, 0x1d, 0x78, 0x31, 0x6c, 0x8e, 0x4f, 0x6d, 0x67, 0x54, 0x0f, 0x00, 0x29, 0xe0, 0x21, 0x49, 0x71, 0x7a, 0x5b, 0x48, 0xf5, 0xc8, 0x17, 0xce, 0x17, 0xd2, 0x66, 0xe1, 0x91, 0xa7, 0x9f, 0xf2, 0x89, 0x93, 0xcc, 0x9a, 0x7e, 0x2b, 0x5c, 0x72, 0x16, 0x28, 0x5e, 0xff, 0xb6, 0xff, 0xef, 0x64, 0x1f, 0xc8, 0x27, 0xb7, 0x05, 0xd0, 0xfc, 0x9a, 0x6d, 0x81, 0x83, 0x7b, 0xd0, 0xa3, 0x61, 0x61, 0xb8, 0x8d, 0xfb, 0x0b, 0xeb, 0xef, 0x57, 0x9c, 0x05, 0x41, 0xae, 0x6f, 0x37, 0xd8, 0x03, 0xe3, 0x83, 0x60, 0xbe, 0x01, 0xe0, 0x4d, 0x3c, 0xbd, 0x3d, 0xa0, 0xaa, 0x7b, 0x40, 0x6a, 0x5c, 0x94, 0xee, 0x53, 0xd2, 0x5c, 0x50, 0x7c, 0xec, 0xd2, 0xf3, 0x7a, 0xd1, 0xc9, 0x86, 0xd6, 0x32, 0xed, 0xdd, 0xef, 0xc2, 0x2e, 0xee, 0xa4, 0xd8, 0x49, 0xb9, 0xbb, 0x8b, 0x83, 0x62, 0xa3, 0xd3, 0x3c, 0xd2, 0xff, 0x29, 0x50, 0xa0, 0xb4, 0x07, 0xe5, 0x09, 0xfe, 0x32, 0xf0, 0x55, 0xe7, 0xf9, 0xb5, 0x6e, 0x49, 0xd7, 0xad, 0xa8, 0x54, 0x46, 0xc1, 0x46, 0xda, 0x8c, 0x67, 0x08, 0xf3, 0x7b, 0xe4, 0xeb, 0xfd, 0x0e, 0xd4, 0x4e, 0x99, 0xfe, 0x1f, 0x1e, 0x9e, 0x38, 0x08, 0x6d, 0xfc, 0xb1, 0x83, 0x37, 0x7b, 0x10, 0x52, 0xc7, 0x63, 0xa7, 0xd2, 0x57, 0xf6, 0xd8, 0x19, 0xf8, 0x68, 0x5d, 0x38, 0x76, 0xee, 0x20, 0x8c, 0x4d, 0x3f, 0xf8, 0x83, 0x70, 0xc7, 0x2e, 0x1c, 0xa4, 0x4d, 0x8a, 0x6a, 0x17, 0xd3, 0xa7, 0x10, 0x8f, 0xdb, 0xce, 0xe1, 0x39, 0xb5, 0x73, 0x9f, 0xb6, 0x1d, 0xf4, 0x68, 0x6c, 0x17, 0xf9, 0xc9, 0x0f, 0xfe, 0x53, 0x7d, 0xfe, 0xb1, 0x3f, 0xc7, 0xfa, 0x63, 0x2c, 0xa8, 0x8b, 0x76, 0xf1, 0xf0, 0x24, 0x2b, 0x56, 0x0d, 0x1c, 0x5f, 0xae, 0x4b, 0xef, 0x79, 0x53, 0x9e, 0xc0, 0xf8, 0x62, 0x35, 0x37, 0x85, 0x06, 0xc7, 0x5e, 0xb5, 0x89, 0x69, 0x6a, 0x8c, 0xfa, 0xa0, 0xf4, 0xb1, 0xd5, 0x4c, 0xef, 0x2a, 0x66, 0xd7, 0xda, 0xb1, 0xe6, 0x4d, 0xb4, 0x39, 0x58, 0x3f, 0x1b, 0x4c, 0xaf, 0x68, 0xd7, 0x1c, 0x6b, 0xd7, 0xd6, 0x01, 0x60, 0x75, 0xfc, 0x25, 0x44, 0x60, 0xba, 0xff, 0x00, 0x0f, 0xae, 0x69, 0x65, 0x99, 0x60, 0xb3, 0x9d, 0x35, 0xec, 0x41, 0x66, 0xb1, 0xa8, 0x6b, 0x62, 0xd1, 0xb2, 0xfc, 0x63, 0xa1, 0x98, 0xde, 0xc2, 0x8b, 0xd3, 0x3a, 0xc2, 0x9d, 0x08, 0xc0, 0xe7, 0x36, 0xf8, 0xf8, 0x41, 0x54, 0x1d, 0x05, 0xa9, 0x4b, 0x9d, 0x95, 0x42, 0xd0, 0x32, 0x9e, 0xbf, 0x5f, 0xf8, 0x0d, 0xdf, 0xef, 0x40, 0xde, 0xe8, 0x35, 0xa3, 0xca, 0x73, 0xcd, 0xc7, 0x34, 0x52, 0x6b, 0x77, 0x2e, 0x37, 0xfe, 0xea, 0x6b, 0xd3, 0x68, 0x6f, 0x4e, 0xee, 0x6e, 0xfb, 0x97, 0xd8, 0xa4, 0x6b, 0x5b, 0x97, 0x98, 0xc7, 0x6c, 0x43, 0xe2, 0x89, 0x24, 0x57, 0x18, 0xab, 0x5f, 0xd0, 0x32, 0xff, 0x4b, 0xb4, 0xc9, 0x7b, 0xee, 0x12, 0x53, 0x75, 0xba, 0x6d, 0x26, 0xc7, 0xd4, 0xa3, 0x58, 0xf8, 0xcd, 0x95, 0xb7, 0xe9, 0x2d, 0x76, 0x88, 0x59, 0x5d, 0xbb, 0xee, 0x29, 0x00, 0x56, 0x5d, 0xf7, 0xf1, 0x41, 0xec, 0xd3, 0x87, 0x6a, 0xd3, 0xba, 0xa5, 0xcd, 0x50, 0x73, 0x7c, 0xcc, 0xf7, 0x42, 0x2b, 0x3e, 0xbd, 0xaf, 0xf3, 0x57, 0xfc, 0xa2, 0xb4, 0x7f, 0x14, 0xcb, 0xfd, 0x61, 0x46, 0x4c, 0x0f, 0xf1, 0x9b, 0x57, 0xb5, 0xe5, 0x0e, 0xee, 0x73, 0x21, 0x6d, 0xb2, 0x42, 0xc0, 0xea, 0x3b, 0x18, 0x77, 0x6c, 0xd9, 0x1a, 0xd3, 0x6e, 0xed, 0xce, 0x4d, 0xd6, 0x99, 0x3b, 0xa8, 0xbd, 0x61, 0x9f, 0x8b, 0xae, 0xf9, 0x5c, 0x54, 0x48, 0x6b, 0x6d, 0xd4, 0xc7, 0xa4, 0x07, 0xd3, 0xb2, 0x73, 0x0c, 0xa8, 0x1c, 0x4b, 0x4d, 0x1f, 0xdd, 0xa2, 0x7d, 0xb0, 0xcd, 0x91, 0xde, 0xeb, 0x4e, 0x19, 0x0f, 0xbb, 0xe4, 0xd4, 0x3b, 0x9b, 0x76, 0xf0, 0x39, 0xd7, 0xfd, 0xa6, 0x5f, 0x76, 0x75, 0x35, 0xd3, 0x28, 0x21, 0xe5, 0xe8, 0x95, 0xbb, 0xbb, 0xd8, 0x05, 0xdf, 0x36, 0x76, 0x81, 0x44, 0x23, 0x9c, 0x63, 0x47, 0x60, 0xcb, 0xbb, 0x7d, 0x73, 0x72, 0xd3, 0xbe, 0x1d, 0xf8, 0x64, 0xa6, 0xb7, 0xe7, 0x43, 0xf3, 0xde, 0x3c, 0xe9, 0xcf, 0xd3, 0x7b, 0x1b, 0xed, 0xa5, 0x28, 0xc8, 0x4b, 0xd4, 0x1d, 0xb4, 0x6b, 0x76, 0xa4, 0x2b, 0x1d, 0xcd, 0x66, 0x22, 0x83, 0x38, 0x08, 0x75, 0x6c, 0x6d, 0xad, 0xf4, 0xb3, 0x98, 0xf9, 0x70, 0xc2, 0xf4, 0x6e, 0x64, 0xfb, 0x4d, 0xc5, 0x93, 0x77, 0xf3, 0x08, 0x37, 0xcd, 0xb7, 0x9b, 0x9d, 0xf6, 0x6e, 0xf5, 0xa6, 0x69, 0x69, 0x51, 0x43, 0x37, 0x09, 0xaf, 0x99, 0x05, 0x93, 0x63, 0xe4, 0x54, 0x59, 0x61, 0xda, 0x4c, 0x4c, 0x13, 0x77, 0x0f, 0xa6, 0x09, 0xbe, 0xfe, 0x95, 0x12, 0xff, 0x52, 0x6c, 0xc2, 0xd5, 0x7b, 0xf6, 0xbb, 0xd6, 0xc9, 0x65, 0x28, 0xd6, 0x0c, 0x8e, 0xb4, 0x3d, 0x7a, 0xd2, 0x78, 0xfb, 0xf2, 0x3d, 0xa9, 0x5d, 0x4c, 0xfb, 0x07, 0x0f, 0xa5, 0xd8, 0xf2, 0x57, 0x4c, 0xc7, 0x4c, 0xc7, 0xda, 0x6e, 0xc9, 0xc7, 0xba, 0xc9, 0xfd, 0xa5, 0xff, 0x06, 0xf6, 0xe4, 0xce, 0xf7, 0x84, 0xca, 0xd1, 0x85, 0xf1, 0xf3, 0xdb, 0x1d, 0xfc, 0xd4, 0xf0, 0x4e, 0x5b, 0xd3, 0xa4, 0xb9, 0x37, 0xdd, 0x29, 0x56, 0xd4, 0x9c, 0x29, 0xd3, 0x3d, 0x6e, 0x44, 0x16, 0x17, 0x83, 0x5b, 0x9f, 0x77, 0xc6, 0x5b, 0xdd, 0xba, 0xb1, 0xc6, 0xb7, 0x89, 0xa2, 0x88, 0x88, 0xea, 0x0e, 0x17, 0x62, 0xc5, 0x1c, 0x3c, 0x74, 0x62, 0xdb, 0x42, 0x4f, 0x64, 0xbf, 0xc1, 0x42, 0x27, 0xf7, 0xbc, 0xeb, 0xbf, 0x03, 0x35, 0x52, 0xd2, 0xae, 0xdf, 0x8c, 0x76, 0xfe, 0x66, 0x2e, 0x07, 0xaa, 0x7b, 0x1e, 0x9e, 0xeb, 0x68, 0x1f, 0x3b, 0xd1, 0x85, 0xc9, 0x56, 0xde, 0x4e, 0x1d, 0x89, 0x53, 0x57, 0xa0, 0x4a, 0x22, 0x3d, 0xe9, 0x5a, 0x79, 0x11, 0xa1, 0x23, 0xe5, 0x6b, 0xb9, 0x19, 0xcb, 0x03, 0xf5, 0xe9, 0x54, 0x3f, 0xb6, 0xde, 0x90, 0x1b, 0x34, 0x1d, 0x91, 0x30, 0xee, 0x23, 0x71, 0x72, 0xa4, 0xa7, 0x27, 0x0e, 0xaa, 0xbd, 0x66, 0xd2, 0xcf, 0xaa, 0xbe, 0x66, 0xae, 0x96, 0x29, 0xdf, 0x57, 0x83, 0x33, 0xea, 0x1c, 0xf0, 0xca, 0x7c, 0x37, 0x83, 0x4c, 0x4a, 0xb7, 0x93, 0xa4, 0x51, 0x48, 0x2f, 0x58, 0x1b, 0xf8, 0xcb, 0xa0, 0xf7, 0x7f, 0x6f, 0x8f, 0xdb, 0xd4, 0x7b, 0x6c, 0x4b, 0x8c, 0x12, 0x8d, 0x9e, 0x8d, 0x34, 0x1d, 0xc5, 0x93, 0xd2, 0x6e, 0xa8, 0xb7, 0x4e, 0x1d, 0x92, 0xe4, 0xeb, 0x74, 0xfa, 0x86, 0xe4, 0x5f, 0xad, 0x77, 0xff, 0x0c, 0x7d, 0x99, 0x88, 0x82, 0xef, 0x93, 0x28, 0xd0, 0xd7, 0x48, 0x82, 0x11, 0xf4, 0xeb, 0xcc, 0x9d, 0x8b, 0xeb, 0xac, 0xec, 0xde, 0x63, 0x3d, 0x0a, 0x73, 0x46, 0xf3, 0xcf, 0xb9, 0x87, 0x1f, 0x66, 0xc4, 0x23, 0xa6, 0xf4, 0xd5, 0xd5, 0x00, 0xe5, 0x42, 0x77, 0xb0, 0x78, 0x84, 0xa2, 0x32, 0x20, 0x44, 0x0b, 0x02, 0x36, 0xed, 0x59, 0x8a, 0xca, 0x26, 0x4e, 0xdd, 0x41, 0x0c, 0x2e, 0xfd, 0x3f, 0xec, 0x5b, 0x9d, 0x76, 0x72, 0x30, 0xdb, 0xce, 0xc2, 0x07, 0xd5, 0xb4, 0x8e, 0xa1, 0x95, 0x71, 0x33, 0x45, 0xba, 0xbe, 0x81, 0x79, 0x04, 0x67, 0x3a, 0xd8, 0xca, 0xf2, 0xa0, 0xf7, 0x10, 0x33, 0xc4, 0x00, 0xec, 0x41, 0x25, 0x13, 0xbc, 0x4b, 0xbf, 0x80, 0xfd, 0x90, 0xb5, 0x9a, 0xe5, 0x41, 0xcd, 0xba, 0x41, 0x61, 0x48, 0x21, 0x3a, 0xad, 0x3b, 0x63, 0x3a, 0x6b, 0x3b, 0xe7, 0x3a, 0xef, 0xbb, 0x10, 0x96, 0xc5, 0x52, 0xc8, 0x12, 0xb8, 0xa6, 0x32, 0x2c, 0x35, 0x8c, 0x8d, 0x86, 0x97, 0x2c, 0xb1, 0x8d, 0xa5, 0xb9, 0x2b, 0x80, 0x46, 0xf1, 0x1d, 0xac, 0x9b, 0xbe, 0xcd, 0x9a, 0xcb, 0x04, 0xe7, 0x81, 0x4f, 0x2e, 0x80, 0xc8, 0x5c, 0x7a, 0xb4, 0x61, 0xe1, 0x7d, 0x62, 0x86, 0x29, 0xa8, 0x12, 0x60, 0xa4, 0x6e, 0x46, 0x86, 0xea, 0xf8, 0xd3, 0xb4, 0xf1, 0x64, 0x0c, 0x71, 0x70, 0x71, 0x71, 0x12, 0xc2, 0xb5, 0x27, 0x51, 0xae, 0xda, 0x7c, 0x39, 0xbb, 0xf8, 0x4d, 0x73, 0x17, 0x9b, 0xbb, 0xdd, 0xc5, 0x86, 0xb6, 0x30, 0x2c, 0x99, 0x08, 0xbb, 0x69, 0x61, 0x17, 0x19, 0xe3, 0x66, 0x6a, 0x46, 0x6b, 0xeb, 0x22, 0x32, 0x42, 0xdb, 0xce, 0x78, 0xd7, 0xc1, 0xba, 0xd4, 0x07, 0xb0, 0xfa, 0x20, 0xa6, 0x9f, 0x8e, 0xfa, 0x2d, 0xee, 0x68, 0x15, 0x3b, 0xaf, 0x96, 0x76, 0xad, 0x49, 0x1d, 0x3c, 0xef, 0xda, 0xb3, 0x77, 0xed, 0xea, 0x59, 0x60, 0xe6, 0xf7, 0x75, 0x9b, 0xf3, 0xbc, 0x0d, 0x81, 0x99, 0x93, 0x5f, 0xce, 0x1e, 0x7c, 0xd7, 0xd8, 0x83, 0xa8, 0xbf, 0xee, 0x2d, 0x00, 0x56, 0xd8, 0x19, 0x06, 0x5b, 0xd1, 0xf3, 0x56, 0xb4, 0x9f, 0xba, 0x74, 0x41, 0x20, 0x33, 0x48, 0x7f, 0x2a, 0x5b, 0xb4, 0xe2, 0xeb, 0x9d, 0x0e, 0xcc, 0x36, 0xf5, 0x71, 0xee, 0xf2, 0xc5, 0x21, 0x75, 0x1a, 0x12, 0xfe, 0x90, 0xec, 0x74, 0xc3, 0xd5, 0x01, 0x96, 0xbb, 0x3d, 0xe6, 0x85, 0xb2, 0x45, 0x48, 0x12, 0x7c, 0xe5, 0xf7, 0x91, 0xbe, 0x2d, 0x93, 0x6c, 0xef, 0xb4, 0x96, 0x19, 0x8e, 0x56, 0xfe, 0xd4, 0x16, 0x81, 0xfe, 0xe1, 0xbc, 0xa5, 0xce, 0x7d, 0xfa, 0x8f, 0x6b, 0x6b, 0xd4, 0xce, 0xe5, 0x8d, 0x32, 0xec, 0x7b, 0x6a, 0x13, 0xb7, 0x9d, 0x2b, 0x9b, 0x9a, 0xdb, 0x6d, 0x3a, 0x25, 0xd8, 0xae, 0x92, 0xee, 0x3f, 0xfd, 0x5f, 0x75, 0xbb, 0x4e, 0xfd, 0xe2, 0x53, 0x47, 0x62, 0x10, 0x61, 0xb1, 0x8b, 0xf4, 0xfb, 0xa9, 0x2e, 0xfc, 0x40, 0x68, 0xd4, 0xee, 0xc4, 0xb3, 0xd0, 0x58, 0xf2, 0x20, 0x9e, 0xb1, 0x75, 0xdf, 0x6d, 0x76, 0xda, 0xda, 0x6b, 0x54, 0x73, 0x04, 0x0a, 0x0d, 0x8d, 0xf4, 0x20, 0xba, 0x58, 0x35, 0x96, 0x4f, 0x69, 0xda, 0x06, 0x17, 0xc1, 0x3a, 0x03, 0xbd, 0x82, 0x7f, 0xc7, 0x85, 0x8d, 0xcb, 0xb8, 0x33, 0x8b, 0xc6, 0xfa, 0x14, 0x72, 0x05, 0x2d, 0xfd, 0xe5, 0x9e, 0x01, 0x37, 0x30, 0x0e, 0xae, 0x13, 0x6c, 0x17, 0xb7, 0xfe, 0x2c, 0x72, 0xed, 0x7d, 0xcb, 0x51, 0x98, 0xce, 0x66, 0x0e, 0x71, 0xc1, 0x19, 0x2a, 0xd2, 0x21, 0xd4, 0xda, 0xd8, 0xd3, 0xae, 0x59, 0x5a, 0xcc, 0xa5, 0x16, 0x6a, 0xee, 0x60, 0x12, 0x24, 0x4d, 0x60, 0x8b, 0x76, 0x38, 0x9c, 0xfc, 0xe8, 0x1d, 0x04, 0x6b, 0x5c, 0x82, 0x0b, 0x00, 0x97, 0x4f, 0x92, 0x25, 0x16, 0x2d, 0xb6, 0xce, 0xe1, 0x4e, 0x44, 0x55, 0xc1, 0x27, 0x55, 0x41, 0xc3, 0xc1, 0xa8, 0xb6, 0x2d, 0xe7, 0x47, 0x86, 0xa8, 0xcf, 0xd7, 0x7c, 0x75, 0x3e, 0xe6, 0x20, 0xb5, 0x81, 0xb1, 0x2c, 0x1d, 0xb1, 0x49, 0xe9, 0x91, 0x60, 0x58, 0xb4, 0x7d, 0x02, 0xbe, 0xaa, 0x22, 0x84, 0x36, 0xf4, 0x27, 0xf4, 0xc8, 0x9f, 0xb1, 0x94, 0x4a, 0x8a, 0x74, 0x3b, 0x48, 0x11, 0xeb, 0xad, 0x82, 0x40, 0x8d, 0xa9, 0x3d, 0x96, 0xac, 0xb4, 0xba, 0x64, 0xf9, 0x6d, 0x9c, 0xc0, 0x37, 0x93, 0xf6, 0x53, 0x7a, 0xe4, 0x16, 0xde, 0x80, 0x39, 0x08, 0x94, 0xf1, 0x16, 0xfc, 0x33, 0xa8, 0xbe, 0x61, 0xe6, 0x10, 0xe9, 0x9d, 0xcd, 0xd3, 0xc4, 0x09, 0x85, 0x8f, 0x6c, 0x43, 0x4b, 0x6d, 0xa7, 0xbd, 0xb9, 0x44, 0x4a, 0xe5, 0xed, 0xeb, 0x26, 0x01, 0x81, 0xb4, 0x8e, 0xa0, 0xe7, 0x9b, 0xb4, 0x6f, 0xb7, 0xab, 0xa5, 0xc4, 0xb1, 0xd5, 0xa4, 0x31, 0x0a, 0xba, 0xcc, 0x07, 0xab, 0x63, 0x59, 0x2a, 0xa9, 0xb6, 0x68, 0x0b, 0xdc, 0xf6, 0xab, 0xa7, 0x27, 0x65, 0x7e, 0xae, 0xbb, 0x0e, 0xe3, 0x85, 0xb9, 0x0d, 0x1b, 0xb0, 0xfc, 0xc9, 0x73, 0xc8, 0x1e, 0x3d, 0xd4, 0x80, 0x6c, 0xde, 0xbb, 0xb5, 0xdd, 0xa1, 0x54, 0x43, 0xbf, 0x87, 0x3d, 0xd5, 0x8c, 0x75, 0x6c, 0xa2, 0xd2, 0x77, 0xa5, 0xdd, 0xff, 0x25, 0xda, 0xc0, 0xbb, 0xdc, 0x29, 0x63, 0xae, 0x8e, 0x03, 0xd6, 0x76, 0xc9, 0x13, 0xdb, 0x15, 0xbf, 0xb6, 0x02, 0xeb, 0xb2, 0x23, 0x1d, 0x1f, 0x70, 0xf0, 0x71, 0xa8, 0xb1, 0xaf, 0xd8, 0x2a, 0x18, 0x83, 0x3b, 0xb2, 0xfd, 0x30, 0x8d, 0x6b, 0x4b, 0xea, 0x04, 0xba, 0x57, 0xfc, 0xff, 0x88, 0x62, 0x25, 0xa7, 0x78, 0x12, 0x6f, 0x1e, 0x45, 0xbd, 0x4c, 0x1a, 0x1c, 0x9c, 0xc0, 0xc6, 0xd2, 0x11, 0xac, 0x0c, 0x1c, 0xcd, 0x1e, 0x4f, 0x1f, 0x38, 0x8b, 0x35, 0xfc, 0x9e, 0x36, 0x8e, 0x72, 0x78, 0x28, 0x63, 0x2f, 0x14, 0x56, 0x94, 0x07, 0x80, 0xb3, 0x20, 0x9a, 0x7f, 0x4f, 0x87, 0xba, 0x46, 0xc7, 0xbe, 0x41, 0x1b, 0x81, 0x7a, 0xdd, 0x13, 0xba, 0x9f, 0x8e, 0x5a, 0xb4, 0x51, 0xfc, 0x01, 0xaf, 0xc2, 0x5b, 0xed, 0x1c, 0x4f, 0xca, 0x38, 0x9e, 0x16, 0x44, 0xfb, 0xa0, 0x21, 0x66, 0x00, 0x6c, 0xbb, 0x20, 0xf0, 0xd0, 0xa1, 0xab, 0x94, 0x67, 0x25, 0x45, 0xd3, 0xa4, 0xfb, 0x63, 0x2a, 0x6d, 0x5a, 0x18, 0x06, 0x95, 0x8b, 0x2d, 0x4d, 0x52, 0xd3, 0xa1, 0xc6, 0x66, 0x50, 0xba, 0x11, 0x05, 0x1a, 0x23, 0x4d, 0x01, 0x0e, 0x64, 0x65, 0xf0, 0x5c, 0x93, 0x7b, 0x4d, 0x60, 0x6d, 0x50, 0x46, 0x0c, 0x69, 0x21, 0xd4, 0x6b, 0x48, 0x87, 0x1f, 0x34, 0x87, 0x5b, 0xd7, 0x98, 0x38, 0x8b, 0xfe, 0x8c, 0x74, 0x93, 0x21, 0x3f, 0xc2, 0xf4, 0xcc, 0xe8, 0x09, 0x46, 0x1e, 0x9d, 0x9e, 0x9b, 0x83, 0x94, 0x85, 0xd4, 0x1b, 0x25, 0xdd, 0xe2, 0xdc, 0xc9, 0x89, 0x95, 0x9e, 0x98, 0xc4, 0x7c, 0x07, 0xc5, 0x4f, 0x04, 0xee, 0x84, 0xfa, 0x10, 0x69, 0x1e, 0x74, 0x2f, 0x92, 0x9f, 0x3f, 0x98, 0x72, 0x34, 0x0b, 0x9c, 0x6a, 0x7a, 0x16, 0x0c, 0x46, 0xf2, 0x65, 0x7c, 0x48, 0x1f, 0x85, 0xc8, 0x06, 0x5d, 0x01, 0x33, 0xc1, 0x17, 0xe1, 0xe8, 0xae, 0xf6, 0x3c, 0x79, 0x03, 0x8f, 0xc4, 0x79, 0x91, 0xd7, 0x55, 0x4d, 0xd9, 0x91, 0x3d, 0xd8, 0x6d, 0xbc, 0xbe, 0x1a, 0x8b, 0xcb, 0x79, 0x4b, 0x42, 0x14, 0xdf, 0x8d, 0x94, 0xc5, 0x00, 0xf2, 0xfd, 0x7a, 0xc3, 0xc5, 0x06, 0xd3, 0x83, 0x45, 0x62, 0x22, 0x2d, 0x03, 0xd0, 0xfe, 0xc0, 0xdc, 0x48, 0xb7, 0xe9, 0xf1, 0xae, 0xf0, 0x5d, 0x39, 0x98, 0x3b, 0x5a, 0x03, 0xf0, 0x00, 0x34, 0xae, 0x19, 0x65, 0x28, 0x1f, 0x84, 0x5e, 0x85, 0x44, 0x85, 0x7f, 0x3b, 0x74, 0x8c, 0x74, 0xa4, 0x88, 0x94, 0x6f, 0xf0, 0xf4, 0x9f, 0x89, 0xf4, 0xfa, 0x9d, 0xd1, 0xed, 0xd5, 0xee, 0x8c, 0xf5, 0xbb, 0xda, 0xf1, 0x50, 0xc2, 0xc3, 0x7e, 0xfa, 0x90, 0xa6, 0x0a, 0x15, 0xa4, 0xb3, 0xb4, 0x63, 0xea, 0x10, 0xb7, 0x5b, 0xd3, 0xd1, 0x23, 0x3c, 0x0f, 0x7e, 0xdd, 0xec, 0x6c, 0x43, 0xab, 0x7b, 0x01, 0x4a, 0x7f, 0x92, 0x66, 0x59, 0xd6, 0x08, 0xf5, 0x02, 0x73, 0x7e, 0xae, 0x93, 0x35, 0xd0, 0xcb, 0x5a, 0x39, 0x73, 0xc0, 0x56, 0x59, 0xc6, 0xc0, 0x7a, 0xe9, 0x62, 0x2f, 0x62, 0xdc, 0xb1, 0x88, 0x17, 0x83, 0xea, 0xec, 0x8b, 0xa1, 0x98, 0xc1, 0x75, 0x0c, 0x2a, 0xb7, 0x06, 0xa1, 0xd0, 0xc7, 0x1b, 0x8a, 0xa0, 0x81, 0x7d, 0xfb, 0x02, 0x47, 0xea, 0x45, 0x4d, 0xe7, 0xd3, 0xec, 0x02, 0xa8, 0x99, 0x2f, 0xe6, 0x52, 0x67, 0x26, 0x72, 0xf6, 0x59, 0xe4, 0x28, 0x52, 0xb4, 0xa1, 0xbf, 0x2c, 0x74, 0xec, 0x01, 0x51, 0x0e, 0x2f, 0x8a, 0xf4, 0xf1, 0xf0, 0x10, 0x8e, 0xd8, 0x79, 0xea, 0xed, 0x05, 0x3c, 0x94, 0xfd, 0x40, 0x0a, 0xc9, 0x22, 0x7e, 0x20, 0x25, 0xc8, 0x63, 0x4f, 0x92, 0x75, 0xf5, 0x91, 0x24, 0x82, 0x1e, 0x92, 0x7d, 0xfd, 0x62, 0x9b, 0x77, 0x54, 0x16, 0x47, 0x03, 0x59, 0x24, 0xed, 0x40, 0x10, 0xc1, 0x1b, 0x9b, 0x0b, 0x21, 0x98, 0x4c, 0x91, 0x40, 0xc7, 0x81, 0xec, 0xc1, 0x5b, 0x7c, 0x51, 0x44, 0x0f, 0xdc, 0x07, 0xdd, 0x46, 0x11, 0x41, 0xe9, 0x5d, 0xd0, 0xd3, 0x0e, 0x7c, 0xcf, 0x59, 0x26, 0x6d, 0x5f, 0x48, 0x0b, 0x69, 0x2c, 0x9b, 0xf8, 0xf5, 0x18, 0xc8, 0x96, 0x95, 0x88, 0x03, 0xe3, 0x3e, 0x5a, 0x06, 0xfd, 0xfe, 0x6b, 0xb5, 0xcf, 0x09, 0x94, 0xa7, 0x9c, 0x01, 0x83, 0x36, 0x1c, 0x22, 0x24, 0x05, 0xbd, 0xa9, 0xdb, 0xaf, 0x6e, 0x30, 0x05, 0x30, 0x2d, 0x36, 0x88, 0xdb, 0xb4, 0x45, 0xaa, 0xa8, 0x5b, 0xf5, 0x55, 0x7a, 0xa4, 0x5f, 0xeb, 0x3d, 0xe5, 0x66, 0x24, 0xb1, 0x35, 0xbf, 0x9f, 0x58, 0x4f, 0xee, 0xa8, 0x77, 0x50, 0xac, 0x6d, 0x8a, 0x7e, 0xc3, 0x8e, 0x81, 0xcb, 0xe2, 0x69, 0xe9, 0x5c, 0x15, 0xce, 0xfb, 0x91, 0x70, 0xae, 0x08, 0xe6, 0x61, 0xdf, 0x7c, 0xc4, 0x6a, 0x5a, 0xee, 0x3a, 0x6f, 0xe5, 0xf2, 0x15, 0xed, 0xd3, 0x38, 0xdc, 0x9a, 0x70, 0x02, 0x5a, 0x3c, 0xe5, 0xe8, 0xb4, 0x87, 0x2d, 0x68, 0x0c, 0x8c, 0x43, 0x6d, 0xd2, 0x12, 0x34, 0xe5, 0x68, 0x77, 0xe4, 0xec, 0xa4, 0x8d, 0x84, 0x3b, 0x1a, 0x22, 0x23, 0x26, 0x6f, 0x0d, 0x3e, 0x11, 0xf1, 0xce, 0x03, 0x62, 0x76, 0x07, 0x33, 0xce, 0x4b, 0x58, 0x43, 0x38, 0x05, 0x82, 0x88, 0x69, 0xd9, 0x6f, 0x3f, 0xdf, 0xf4, 0xc1, 0x33, 0x01, 0x76, 0xb6, 0x34, 0x7c, 0x6e, 0x43, 0x27, 0xd7, 0xdf, 0x4d, 0x6b, 0xed, 0x98, 0x89, 0xe5, 0x5a, 0x5f, 0x3b, 0xd9, 0x70, 0x1e, 0x77, 0xd1, 0x58, 0xb8, 0xa0, 0xcf, 0xf3, 0x36, 0xec, 0x17, 0x2d, 0xed, 0x64, 0xb9, 0x0c, 0xe1, 0x9b, 0x77, 0x70, 0x1f, 0x2b, 0x33, 0x0d, 0xf1, 0x85, 0x2e, 0xca, 0xcf, 0x31, 0xf3, 0x7b, 0x59, 0x8f, 0x8b, 0xab, 0xa2, 0xb1, 0x24, 0x07, 0xab, 0x62, 0xb8, 0x1c, 0x5b, 0x0b, 0x0b, 0x9b, 0xe0, 0x1a, 0x24, 0xa7, 0x23, 0x0b, 0xd0, 0x09, 0x7e, 0xe4, 0xda, 0x13, 0xa5, 0x2d, 0xbe, 0xd9, 0xaa, 0x1d, 0x8a, 0xef, 0xb5, 0x82, 0x7b, 0xd2, 0xf4, 0x59, 0x70, 0x3f, 0x69, 0xc1, 0xbd, 0x56, 0x64, 0x4f, 0x56, 0xcd, 0x34, 0x31, 0xfc, 0x59, 0x58, 0x3f, 0x0b, 0xeb, 0x47, 0x23, 0xac, 0xef, 0xd0, 0xe5, 0xb6, 0x09, 0xb2, 0x65, 0x9f, 0xcf, 0x9d, 0x63, 0x53, 0xd3, 0xbe, 0xd9, 0x14, 0x7e, 0x6a, 0x5a, 0xe4, 0xd5, 0x79, 0xac, 0xbd, 0x8b, 0x23, 0x32, 0xec, 0x37, 0xc2, 0x6e, 0x3d, 0x9c, 0xc7, 0x05, 0x73, 0x35, 0xa4, 0x07, 0xc0, 0x6e, 0xb0, 0x02, 0x55, 0x0f, 0x87, 0x29, 0x91, 0xae, 0xd8, 0x86, 0xf7, 0x40, 0x33, 0x35, 0x0b, 0x50, 0xd3, 0x38, 0x95, 0x21, 0x78, 0x8d, 0x83, 0x11, 0x0f, 0xd6, 0xa3, 0x57, 0x84, 0xe9, 0xd1, 0x68, 0x38, 0x7a, 0xd1, 0x86, 0xf5, 0xa4, 0xb6, 0x5e, 0xeb, 0x67, 0x58, 0xcf, 0x7d, 0xc2, 0x7a, 0x3e, 0x3c, 0x30, 0xac, 0x27, 0xbd, 0xd3, 0x2f, 0x08, 0xd6, 0xf3, 0xb1, 0x4e, 0x38, 0x44, 0x9e, 0x57, 0x74, 0x96, 0xef, 0xa4, 0xfa, 0x44, 0xf2, 0x95, 0xbd, 0x35, 0xb8, 0x98, 0x77, 0x52, 0x7e, 0x62, 0xc7, 0x37, 0x61, 0xf1, 0xf5, 0x4e, 0x8a, 0x9c, 0x39, 0x73, 0xcc, 0x88, 0x8a, 0x2e, 0xd0, 0x5f, 0xee, 0x13, 0xb3, 0xd3, 0xec, 0xfc, 0xa7, 0x24, 0xb4, 0xa9, 0xff, 0x9c, 0xc0, 0xc2, 0x1f, 0xa9, 0x95, 0x85, 0x6b, 0xc1, 0xfb, 0x42, 0x5b, 0x86, 0x38, 0x8e, 0x56, 0xa0, 0x85, 0xcc, 0x6e, 0x9e, 0x85, 0xb3, 0x4b, 0xdb, 0x6f, 0x77, 0xd0, 0xd3, 0x18, 0x00, 0xcf, 0x56, 0x15, 0xaf, 0x6c, 0xf1, 0xa5, 0x91, 0x0f, 0xcd, 0x22, 0x92, 0x82, 0x4e, 0x0f, 0xe3, 0xb2, 0x33, 0x2e, 0x90, 0xcb, 0x07, 0x3d, 0x53, 0x70, 0x8a, 0xdb, 0xc0, 0xc7, 0x98, 0xa4, 0x1f, 0xc1, 0xe7, 0x84, 0xbe, 0x23, 0x73, 0xb0, 0xe4, 0xbd, 0x92, 0xda, 0x07, 0x3e, 0x83, 0xb0, 0xb1, 0x06, 0x6f, 0x16, 0x79, 0xbe, 0x14, 0xb7, 0x49, 0xbb, 0x58, 0x43, 0xef, 0x18, 0xe8, 0x08, 0xe4, 0x03, 0xe4, 0x63, 0x4a, 0x75, 0xf9, 0xa2, 0x03, 0xce, 0xc6, 0x80, 0xe6, 0x80, 0xdd, 0xa2, 0x7b, 0x29, 0xf5, 0xab, 0xe1, 0x5a, 0x90, 0x6e, 0x52, 0xe3, 0xb5, 0x86, 0xae, 0xa2, 0x47, 0x0b, 0x5e, 0x27, 0x64, 0x11, 0x62, 0x59, 0x54, 0x3a, 0x53, 0xec, 0xd1, 0x32, 0x1e, 0x2f, 0x22, 0xa6, 0x21, 0x59, 0x6e, 0x13, 0x7d, 0x8d, 0x78, 0xe6, 0x95, 0x97, 0xba, 0x94, 0x55, 0x3f, 0x17, 0x5b, 0xd3, 0xc7, 0xed, 0x50, 0x30, 0x82, 0x2b, 0x1f, 0x3d, 0x80, 0xe5, 0xcc, 0xf7, 0x8c, 0xd1, 0xe2, 0xd5, 0x54, 0x1b, 0xc6, 0x11, 0x4e, 0x79, 0x82, 0x97, 0x9a, 0xbf, 0xe3, 0xaa, 0xb3, 0xda, 0xd5, 0xfb, 0xec, 0xd3, 0x99, 0x86, 0x7d, 0x2e, 0xf5, 0x17, 0x59, 0x55, 0xa1, 0x7c, 0x89, 0x0c, 0x8e, 0xa8, 0xf7, 0x1e, 0xcf, 0xee, 0x1d, 0xa4, 0x3a, 0x1e, 0xc1, 0x1d, 0xc7, 0xa2, 0x30, 0x8e, 0x01, 0xdb, 0xe6, 0x05, 0xbd, 0x02, 0x5b, 0xcf, 0xca, 0xaa, 0x21, 0x3d, 0x0e, 0x8b, 0x0f, 0xe6, 0x62, 0xc1, 0xcd, 0x4e, 0x60, 0x70, 0x8f, 0x12, 0x04, 0x46, 0xd1, 0x56, 0x67, 0x67, 0xbe, 0x06, 0x51, 0xb0, 0x05, 0xbf, 0x68, 0x38, 0x2e, 0x3d, 0x79, 0x1f, 0x6a, 0x53, 0xae, 0xef, 0x5a, 0x92, 0x4c, 0x3b, 0x73, 0x76, 0xb6, 0x85, 0x94, 0x6e, 0x66, 0xfc, 0x4a, 0x37, 0x73, 0x39, 0xca, 0x0c, 0xfa, 0x4a, 0x52, 0x60, 0x9a, 0x62, 0x39, 0xb5, 0x6f, 0x21, 0xa8, 0x93, 0x2f, 0x9f, 0x80, 0x29, 0xd2, 0xba, 0xf6, 0x35, 0x3c, 0xc4, 0xa0, 0x49, 0x0d, 0x5e, 0x96, 0x73, 0xb1, 0x4e, 0xb6, 0x2e, 0x86, 0x0a, 0x88, 0xcd, 0x95, 0xad, 0xc7, 0xa3, 0xa6, 0x37, 0x31, 0x9a, 0x31, 0x68, 0x25, 0xb2, 0x33, 0x5b, 0xd7, 0x59, 0xd9, 0x8d, 0xb7, 0x26, 0x62, 0x92, 0x49, 0x58, 0xe0, 0xab, 0xec, 0x74, 0x12, 0x1d, 0x05, 0xb3, 0xb1, 0x84, 0xf7, 0x18, 0x3d, 0x12, 0xe9, 0xeb, 0xd7, 0x17, 0x02, 0xaf, 0x69, 0x36, 0x9c, 0x2a, 0x52, 0x14, 0xe5, 0x1a, 0x19, 0xf7, 0x10, 0x04, 0xd0, 0x24, 0xa1, 0x30, 0x9a, 0xe1, 0xb2, 0x7e, 0xcf, 0x91, 0x45, 0x92, 0x6e, 0x79, 0xb6, 0xe6, 0x58, 0xe4, 0x29, 0x08, 0xdf, 0x74, 0x1b, 0x4f, 0x14, 0xcc, 0xf6, 0x5b, 0x95, 0x45, 0x96, 0x96, 0x50, 0xfc, 0x44, 0x41, 0xf5, 0xbd, 0xf1, 0x45, 0xc5, 0xb6, 0x56, 0xac, 0x05, 0xb5, 0x0d, 0x37, 0xea, 0x2c, 0xbd, 0x55, 0xe7, 0x14, 0x38, 0x34, 0xa0, 0x2c, 0xd0, 0xdc, 0x09, 0x12, 0x9b, 0x6c, 0xf3, 0x29, 0xe3, 0x39, 0x4a, 0x5d, 0x40, 0x54, 0x61, 0x00, 0x6e, 0x13, 0x18, 0x1f, 0x96, 0xb8, 0x0e, 0x1c, 0xc2, 0x78, 0x35, 0xc7, 0x9f, 0x21, 0x19, 0x0e, 0x34, 0x06, 0xc6, 0x5a, 0x81, 0x4a, 0x40, 0x91, 0xef, 0xac, 0x35, 0xea, 0x4f, 0xd8, 0x0e, 0xcc, 0x45, 0x3e, 0x52, 0xd2, 0x92, 0xa4, 0x73, 0x86, 0x55, 0x98, 0xed, 0xb6, 0x05, 0x39, 0xde, 0x28, 0x59, 0x43, 0xfb, 0x02, 0xe6, 0x78, 0x1a, 0x02, 0x65, 0x05, 0xa8, 0x4c, 0x0b, 0xad, 0x78, 0xbc, 0x0f, 0x44, 0xdd, 0xa4, 0x01, 0x1d, 0x05, 0x76, 0xfa, 0x40, 0x39, 0x9c, 0xe6, 0x14, 0x6f, 0x16, 0xd2, 0x2f, 0xa1, 0xea, 0x4c, 0x63, 0x16, 0x13, 0xbd, 0x25, 0xe0, 0x23, 0xe5, 0x7b, 0x56, 0xcd, 0x7b, 0x92, 0xf5, 0x23, 0xce, 0xcf, 0xdf, 0x9b, 0xcc, 0x47, 0x9b, 0x22, 0xa4, 0xc1, 0x01, 0x72, 0x94, 0xdb, 0xd8, 0xc2, 0xfa, 0xe1, 0x16, 0x2a, 0xfd, 0xa2, 0x75, 0x9f, 0x67, 0x6a, 0x2c, 0x65, 0x34, 0xe6, 0xc3, 0xbe, 0x3a, 0x67, 0x5d, 0xed, 0x1b, 0x48, 0x12, 0xee, 0x22, 0x00, 0x8c, 0x98, 0x12, 0x78, 0x83, 0x16, 0xd1, 0x07, 0x72, 0x0b, 0x0b, 0x3f, 0xcf, 0xa7, 0xca, 0x24, 0x61, 0xab, 0xe7, 0x38, 0xef, 0xb1, 0x9d, 0x93, 0x7d, 0x97, 0x12, 0x1c, 0x11, 0xe0, 0x2e, 0x48, 0x92, 0x09, 0x18, 0x1d, 0xad, 0x3b, 0x82, 0x37, 0xc1, 0x20, 0x64, 0x6e, 0x9b, 0x6e, 0x2b, 0x8d, 0x96, 0xfe, 0x85, 0xe8, 0x21, 0x78, 0x1c, 0x9a, 0x87, 0x19, 0x30, 0xd6, 0x64, 0x83, 0xa4, 0xf7, 0xcd, 0xa2, 0x10, 0x3c, 0xc5, 0x3f, 0x46, 0x57, 0x9d, 0x02, 0x02, 0xb6, 0x31, 0xc7, 0xd2, 0x74, 0xa0, 0xf2, 0x55, 0xa2, 0x1b, 0xae, 0x01, 0x8e, 0x96, 0x6e, 0xe1, 0xe2, 0x92, 0xf6, 0x5c, 0xa1, 0x5c, 0xac, 0xb5, 0x3b, 0xe8, 0x10, 0xab, 0x1e, 0xe8, 0xca, 0x4c, 0xf1, 0x5a, 0xd0, 0x08, 0x70, 0xcf, 0x6b, 0x38, 0xa6, 0xe2, 0x76, 0x44, 0xd9, 0x96, 0x96, 0xff, 0xf6, 0x46, 0x4d, 0x9a, 0x63, 0xdb, 0x80, 0xed, 0x82, 0x18, 0xd1, 0x52, 0xca, 0x38, 0x3c, 0xab, 0x47, 0xd7, 0x47, 0xe6, 0x5f, 0x1c, 0x5f, 0x5b, 0x73, 0xf3, 0xf0, 0xe5, 0xce, 0x8f, 0xa9, 0x1c, 0xa4, 0x1e, 0x3b, 0x86, 0xd4, 0xfc, 0x7e, 0x34, 0x4a, 0xc0, 0x6a, 0x6a, 0xf5, 0x86, 0x55, 0x99, 0x5d, 0xcd, 0x37, 0x23, 0xe7, 0xc9, 0x47, 0xbd, 0x84, 0x4e, 0x9d, 0xc9, 0x4a, 0x77, 0x37, 0xcc, 0x3d, 0xda, 0xde, 0x98, 0x5d, 0x2f, 0x62, 0x92, 0x15, 0x96, 0x1f, 0xe2, 0x1c, 0x41, 0x32, 0xdd, 0x6f, 0x34, 0xee, 0xc5, 0x3b, 0xf5, 0xea, 0x63, 0xef, 0xef, 0x2d, 0x67, 0x92, 0x42, 0x6d, 0x80, 0x0f, 0xbb, 0x20, 0x9a, 0x38, 0xdd, 0x69, 0xc7, 0x33, 0xca, 0x85, 0x1b, 0x66, 0xbb, 0xa5, 0xc4, 0x88, 0xa6, 0x3f, 0xc7, 0xaa, 0x1a, 0x6c, 0x19, 0x1a, 0x47, 0x01, 0xc6, 0x16, 0x21, 0x9e, 0xc8, 0xcd, 0xa9, 0xd3, 0xda, 0x55, 0x0a, 0x8f, 0x38, 0x05, 0xda, 0x17, 0xa7, 0xac, 0xa0, 0x46, 0xa3, 0x19, 0x27, 0x05, 0xa8, 0xb2, 0x2d, 0x1e, 0x78, 0x0e, 0x76, 0x28, 0x98, 0x66, 0xa0, 0x1d, 0xb5, 0xc7, 0xe7, 0x74, 0xd2, 0xb3, 0x33, 0x4a, 0x66, 0xbe, 0xa1, 0x56, 0x83, 0x58, 0x6b, 0x70, 0x89, 0x4c, 0xbe, 0x54, 0x8e, 0xab, 0x80, 0x8a, 0x8b, 0x90, 0xed, 0x87, 0x40, 0x30, 0xf0, 0x0d, 0xad, 0x8c, 0x9d, 0x8a, 0xeb, 0x89, 0x8e, 0x4e, 0x66, 0x6d, 0xa3, 0xb4, 0xb5, 0xad, 0x2d, 0xfb, 0x30, 0x2b, 0xfe, 0xf3, 0xec, 0xb1, 0x7f, 0x2c, 0xe4, 0x7f, 0x0d, 0xd4, 0xbb, 0x02, 0x8e, 0x4f, 0xe7, 0xa0, 0xd8, 0x4e, 0x77, 0x1e, 0x38, 0x77, 0x6e, 0x28, 0xb7, 0x82, 0x1a, 0xd8, 0xfc, 0x83, 0x65, 0x79, 0xb3, 0x8e, 0x45, 0x6c, 0xd7, 0xd0, 0x44, 0x65, 0x40, 0x43, 0x20, 0x3b, 0x9d, 0x6a, 0xca, 0x51, 0xcd, 0xa5, 0xdd, 0xcb, 0xcd, 0xc9, 0xcd, 0x19, 0xd2, 0x53, 0xcb, 0x2c, 0x6b, 0xb4, 0xf0, 0x75, 0xed, 0xad, 0x39, 0xc5, 0xbc, 0x19, 0xab, 0xd3, 0x6b, 0xa9, 0x6e, 0x15, 0xae, 0x28, 0xe7, 0x8f, 0x9c, 0x75, 0x51, 0xed, 0xc9, 0x35, 0x94, 0xb5, 0xc7, 0x4e, 0x42, 0x08, 0x0b, 0x6d, 0xa7, 0x6d, 0x80, 0x2d, 0xdb, 0x45, 0x06, 0xb9, 0x1a, 0x4c, 0x88, 0xb9, 0x41, 0x60, 0x30, 0xd2, 0x3d, 0x77, 0x46, 0x26, 0x71, 0x8a, 0xec, 0xd8, 0xec, 0xcd, 0x17, 0x91, 0xe2, 0x4d, 0x4d, 0xe5, 0x6a, 0xee, 0x33, 0xb8, 0xab, 0x5d, 0x84, 0x3c, 0xcd, 0x7c, 0xaa, 0xa6, 0xc3, 0x1a, 0x1d, 0x39, 0xbd, 0xaa, 0x8e, 0xdf, 0x24, 0xab, 0x80, 0x28, 0xdc, 0x25, 0xba, 0x42, 0x0f, 0xac, 0xf0, 0x20, 0x7d, 0xf7, 0xb6, 0xc3, 0x64, 0x13, 0xb0, 0x6e, 0x8b, 0x03, 0xd4, 0x91, 0x67, 0x94, 0x4e, 0x03, 0xa6, 0x39, 0xee, 0x34, 0x9b, 0x58, 0x96, 0xac, 0xaa, 0xe2, 0x4f, 0x9d, 0x08, 0x6f, 0x29, 0xf2, 0x5a, 0x2d, 0x33, 0x81, 0x5c, 0x9b, 0xb2, 0x2d, 0x3c, 0x7a, 0x69, 0x2d, 0xab, 0x5c, 0xd0, 0x01, 0xf9, 0x66, 0xa1, 0x05, 0x24, 0x18, 0x89, 0xec, 0xe1, 0x4d, 0x1d, 0x5c, 0x3b, 0xb3, 0xf9, 0xfe, 0xeb, 0x53, 0x74, 0xae, 0x96, 0x48, 0x7f, 0xb6, 0x25, 0x12, 0x0b, 0x25, 0x46, 0x31, 0x03, 0xdf, 0x4e, 0xc0, 0x7c, 0x2b, 0xed, 0x6c, 0x56, 0x75, 0x20, 0xbe, 0xb1, 0x3e, 0x19, 0xb5, 0xc1, 0xdc, 0x82, 0xfa, 0xbf, 0x62, 0xec, 0x31, 0x3e, 0xe8, 0x74, 0x4a, 0xab, 0x4e, 0x22, 0xac, 0x50, 0x11, 0xe6, 0x50, 0x6b, 0x80, 0x19, 0x6a, 0x3a, 0xb5, 0x79, 0x12, 0x64, 0x4c, 0x1a, 0x4e, 0x5d, 0xed, 0x6c, 0x86, 0x3a, 0xb7, 0x4f, 0x76, 0x59, 0xd2, 0x30, 0x66, 0x73, 0xab, 0xcc, 0x2b, 0x0d, 0x61, 0x4d, 0x47, 0x02, 0xcc, 0xa0, 0x99, 0x0a, 0x78, 0x46, 0x48, 0x62, 0x43, 0x8d, 0x82, 0x4f, 0xb7, 0xd6, 0x58, 0xa6, 0xce, 0xfc, 0xb2, 0x09, 0xe1, 0xb6, 0x15, 0x2a, 0x0c, 0xf5, 0x16, 0xf4, 0x90, 0x5b, 0x56, 0x1f, 0xfd, 0x0a, 0xa9, 0xa4, 0x8f, 0x5d, 0x26, 0xfd, 0xb9, 0xd9, 0xc5, 0x78, 0x51, 0xe6, 0xd6, 0x34, 0x2d, 0x6a, 0x62, 0x03, 0x2c, 0x67, 0x69, 0xd6, 0x1b, 0x31, 0x55, 0x35, 0xc5, 0xd2, 0x5c, 0xb2, 0x01, 0x6a, 0x7f, 0x0e, 0x56, 0xd8, 0x60, 0x79, 0x9d, 0xb2, 0x11, 0xa7, 0x04, 0xfd, 0xd5, 0x81, 0xeb, 0x69, 0xb1, 0x67, 0x4e, 0x5e, 0x0f, 0x49, 0xac, 0x8e, 0xcb, 0x6c, 0x36, 0x4f, 0xe8, 0x31, 0xdc, 0xd5, 0x99, 0x74, 0xaf, 0xfb, 0xe1, 0x5a, 0xc9, 0xfd, 0xf2, 0x9b, 0x96, 0xbd, 0xa6, 0x33, 0xab, 0x2c, 0x80, 0x41, 0x48, 0x5c, 0xbe, 0x80, 0x00, 0x7a, 0xc3, 0x73, 0x36, 0xed, 0x9f, 0xe8, 0x02, 0x2a, 0x89, 0xae, 0x1c, 0xa8, 0x64, 0x0e, 0x3e, 0x04, 0x7a, 0x1b, 0x72, 0x7a, 0x27, 0xc1, 0x7c, 0xc8, 0x99, 0x22, 0x19, 0x60, 0x46, 0x81, 0x38, 0x4a, 0xce, 0x89, 0x08, 0xf7, 0x66, 0xf5, 0x03, 0x22, 0xe6, 0x86, 0x31, 0x2c, 0x99, 0x6f, 0xc0, 0x61, 0xb6, 0x36, 0xd2, 0xfb, 0xa5, 0x2e, 0xa8, 0x03, 0xcc, 0xdd, 0xcd, 0x7c, 0x00, 0xe8, 0x01, 0xe4, 0xae, 0xb7, 0x4d, 0x8f, 0x93, 0xae, 0xb1, 0x96, 0x85, 0xca, 0xdd, 0x38, 0x3e, 0xd3, 0x35, 0x3e, 0x26, 0xc1, 0xc1, 0x54, 0x72, 0xe0, 0x19, 0x83, 0x9e, 0xd4, 0xce, 0x4b, 0x08, 0x3e, 0xb6, 0x5d, 0x79, 0x4e, 0xd6, 0xd3, 0x78, 0x0f, 0xa2, 0x4d, 0x4f, 0x58, 0x8d, 0xde, 0x4c, 0xbd, 0xa4, 0x11, 0xa8, 0x09, 0xdd, 0x02, 0xa6, 0x60, 0x45, 0x1f, 0x21, 0xeb, 0x1b, 0xd5, 0x59, 0xd4, 0x18, 0x14, 0x1e, 0xb2, 0x00, 0x26, 0x2c, 0xde, 0x9d, 0x0e, 0xfe, 0x9a, 0x2c, 0xde, 0x8a, 0x7f, 0x2b, 0x03, 0x85, 0xf4, 0xbe, 0xe6, 0x87, 0x5b, 0xe7, 0x1c, 0x73, 0xbc, 0x12, 0x28, 0xb6, 0xba, 0xdc, 0xcb, 0xf4, 0xbf, 0xd5, 0x62, 0x08, 0x50, 0x81, 0x66, 0x44, 0x1a, 0x76, 0xb1, 0x94, 0xb9, 0x33, 0x19, 0xb5, 0xf1, 0xb8, 0xf6, 0xd1, 0x26, 0x18, 0x18, 0x99, 0x0d, 0x8e, 0x09, 0x3d, 0xe3, 0xb9, 0xc2, 0xb5, 0x72, 0xb5, 0xfc, 0x7a, 0xd9, 0xe2, 0x23, 0x32, 0xee, 0x4e, 0xf9, 0x88, 0x08, 0xbb, 0x74, 0x93, 0x33, 0xd1, 0x3d, 0x45, 0x43, 0x3a, 0x72, 0x3b, 0x0b, 0xca, 0xdb, 0xc9, 0x1c, 0x60, 0x28, 0xae, 0xd0, 0x4f, 0x25, 0xba, 0xec, 0x3f, 0xb2, 0x06, 0x63, 0xfa, 0x9a, 0x71, 0x02, 0x74, 0x69, 0x60, 0x70, 0x92, 0xef, 0xac, 0x27, 0xdf, 0x92, 0x44, 0x36, 0x40, 0xa7, 0x17, 0xe8, 0x87, 0x4c, 0x2d, 0x14, 0x4f, 0x53, 0x6f, 0xcf, 0xba, 0x14, 0xd9, 0x34, 0x39, 0x3a, 0x93, 0x13, 0x08, 0xd3, 0x3d, 0xa0, 0x2b, 0xde, 0x45, 0x02, 0x4b, 0x04, 0x8a, 0x4c, 0x59, 0x0a, 0x7e, 0x2f, 0x4f, 0x44, 0xd9, 0x95, 0x94, 0x69, 0xf7, 0x0a, 0x98, 0xea, 0xd2, 0x4c, 0xa2, 0x77, 0x0b, 0x6e, 0xb2, 0x8a, 0xa4, 0xaa, 0xce, 0xf3, 0xa2, 0x6d, 0x70, 0x0f, 0xec, 0x66, 0xc6, 0x69, 0xd9, 0x3a, 0x30, 0xf0, 0xc7, 0x25, 0x66, 0xb3, 0xb4, 0x25, 0x1e, 0x98, 0x3c, 0xc9, 0xb8, 0xab, 0x51, 0x56, 0x79, 0xa9, 0x46, 0x95, 0x54, 0x45, 0xcf, 0xdb, 0xca, 0x53, 0x0a, 0x2a, 0xe0, 0x3d, 0xe0, 0xa1, 0xa6, 0x2d, 0xe2, 0xb5, 0x5b, 0xdc, 0x18, 0x7a, 0xe1, 0xc1, 0x5c, 0x2d, 0x6a, 0xaa, 0xdc, 0xe3, 0x00, 0xdf, 0x61, 0x0a, 0xb8, 0xf8, 0x29, 0xef, 0x29, 0x94, 0x34, 0x60, 0xb4, 0x0f, 0x18, 0x49, 0xbb, 0x61, 0x0e, 0x2a, 0x02, 0x90, 0xca, 0xfa, 0x3d, 0x94, 0x70, 0xe9, 0x2a, 0xb6, 0xf2, 0x86, 0x37, 0x0b, 0xb7, 0xb9, 0xb1, 0x39, 0x12, 0x4b, 0xdc, 0x84, 0x62, 0xaf, 0x38, 0x37, 0x71, 0xaf, 0x98, 0x67, 0x74, 0xaf, 0x88, 0x42, 0x43, 0x22, 0x82, 0x09, 0x12, 0x0a, 0x1d, 0xa1, 0xa4, 0x01, 0xd0, 0x8b, 0x49, 0x89, 0x92, 0x52, 0xe9, 0x04, 0xe0, 0x9b, 0x50, 0xc3, 0x8a, 0x47, 0x82, 0x23, 0x29, 0xcc, 0xef, 0x45, 0x0d, 0x4d, 0x72, 0x0e, 0x1d, 0x41, 0x95, 0x2c, 0xd1, 0xa2, 0x40, 0x63, 0xb1, 0xe5, 0x5c, 0x45, 0xf4, 0xa5, 0x4b, 0x8a, 0x6b, 0xa8, 0x03, 0xe2, 0xb1, 0x20, 0x5d, 0x00, 0xb3, 0xf0, 0x2c, 0x67, 0x32, 0x4b, 0x0d, 0xb3, 0xf3, 0x98, 0xe2, 0x17, 0xf0, 0x24, 0x19, 0x58, 0xde, 0x04, 0x46, 0x50, 0x2f, 0x0e, 0x19, 0x90, 0xa6, 0x3e, 0x75, 0x22, 0xcb, 0x33, 0x51, 0xe2, 0x09, 0x20, 0x62, 0x03, 0xfb, 0x70, 0x14, 0x97, 0x60, 0x43, 0x73, 0x1f, 0x7f, 0x23, 0xb1, 0x07, 0xf9, 0x8f, 0x2a, 0x7b, 0x49, 0x14, 0x79, 0x63, 0x58, 0xb7, 0x49, 0xcd, 0x6d, 0x69, 0xdd, 0x19, 0xbe, 0x58, 0x4f, 0x2f, 0x56, 0x45, 0x80, 0x96, 0x91, 0x58, 0xfa, 0x0f, 0xae, 0x52, 0xa5, 0x1f, 0x0c, 0x3a, 0x5a, 0x3e, 0xd6, 0x19, 0x46, 0x96, 0x2f, 0x8c, 0x5b, 0x84, 0x59, 0xe7, 0xcf, 0xa1, 0xd6, 0x49, 0xfa, 0x5b, 0xe3, 0x50, 0x25, 0x62, 0x4e, 0x69, 0x9a, 0xe5, 0xf6, 0xe9, 0xd6, 0xd3, 0x96, 0xd0, 0x9a, 0x47, 0xc9, 0xf8, 0xbc, 0xf9, 0x8d, 0x12, 0x45, 0xef, 0x8b, 0xf2, 0xa0, 0xba, 0x5c, 0x5a, 0x93, 0x6f, 0x63, 0x70, 0xb3, 0x37, 0x5c, 0xd5, 0x10, 0x6a, 0x1a, 0x16, 0x2f, 0x0a, 0x36, 0x51, 0x85, 0x52, 0x9f, 0x1f, 0xb3, 0xca, 0xe3, 0x12, 0xe0, 0x3b, 0x67, 0xae, 0xf0, 0x90, 0x7b, 0xd6, 0x3d, 0xe1, 0x46, 0xb6, 0xa0, 0x85, 0xdb, 0x1c, 0x57, 0x1c, 0x3f, 0x8c, 0xac, 0x3e, 0xdb, 0x2d, 0xa7, 0xc2, 0x8e, 0x3b, 0xd2, 0xc3, 0x09, 0x1d, 0xb8, 0x4f, 0x7c, 0xc2, 0xfc, 0x70, 0xb1, 0xc8, 0x21, 0xf5, 0xa9, 0xf1, 0x26, 0x0d, 0xbd, 0xf6, 0xfe, 0x06, 0xc9, 0x4f, 0x06, 0x0f, 0x3a, 0x8d, 0x50, 0x26, 0xed, 0x87, 0x8f, 0x1f, 0x06, 0xed, 0x94, 0x4e, 0x87, 0xf4, 0x96, 0xbf, 0x8d, 0x93, 0xa9, 0xe4, 0x13, 0x11, 0x3e, 0x58, 0xdd, 0x3f, 0x3b, 0x7e, 0xe4, 0x78, 0x06, 0x40, 0x02, 0xb0, 0x29, 0xf1, 0xd3, 0x6e, 0x78, 0x8b, 0xa3, 0xf7, 0x3b, 0xbe, 0x25, 0x9b, 0xd7, 0x76, 0x6d, 0xd5, 0x25, 0xcb, 0x61, 0x74, 0xb5, 0x75, 0xb1, 0xbf, 0x7a, 0xb4, 0xfa, 0x0e, 0xe5, 0x79, 0x4f, 0x1e, 0xb0, 0xeb, 0x5f, 0xd9, 0xf4, 0xf9, 0xf2, 0x9d, 0xa8, 0xec, 0x42, 0x4c, 0x07, 0xe9, 0x76, 0xf0, 0x54, 0xd2, 0x67, 0x57, 0x9e, 0x07, 0xf7, 0x97, 0x6f, 0x38, 0x9b, 0x3e, 0xd3, 0xf7, 0xf8, 0x2f, 0xde, 0x43, 0x79, 0x69, 0x65, 0x56, 0xa5, 0xfe, 0xe1, 0xe1, 0x6d, 0xf5, 0x9f, 0xd3, 0x0a, 0x0e, 0x79, 0x12, 0x9a, 0x06, 0x3d, 0x20, 0x20, 0x32, 0x8f, 0x6c, 0xca, 0x97, 0xe5, 0xab, 0x9c, 0x61, 0x6c, 0x7c, 0xf9, 0x6a, 0x72, 0x6b, 0x45, 0x59, 0x63, 0xf9, 0x30, 0x7a, 0x34, 0x4c, 0x7d, 0x80, 0x4b, 0x13, 0x97, 0x5e, 0x3f, 0xdf, 0xf4, 0x20, 0x46, 0xb3, 0x1d, 0xed, 0xcd, 0xc1, 0x0f, 0xac, 0xac, 0x0d, 0x7e, 0x29, 0x4f, 0x3f, 0x3f, 0x21, 0x4f, 0x3e, 0x49, 0xa1, 0x40, 0xd8, 0x83, 0x2d, 0x8d, 0x12, 0x53, 0x1d, 0x71, 0x84, 0xfe, 0x5e, 0x54, 0xde, 0xb5, 0x3a, 0xc3, 0x48, 0x70, 0x50, 0xf4, 0x17, 0xc2, 0xd5, 0x28, 0xfc, 0x14, 0x2e, 0xa6, 0x17, 0x5b, 0x70, 0x23, 0x0a, 0x22, 0x9e, 0xa2, 0x1f, 0xd2, 0x53, 0x20, 0x20, 0x60, 0x16, 0x99, 0x91, 0x74, 0xbd, 0x23, 0xb1, 0x76, 0x24, 0xbd, 0x34, 0xb5, 0x0d, 0x18, 0x9f, 0xeb, 0xf0, 0xa1, 0xc1, 0xd0, 0x72, 0x3b, 0x7a, 0x97, 0x95, 0x93, 0xd4, 0x4b, 0x39, 0xd3, 0xd6, 0x9b, 0x81, 0x19, 0x49, 0x54, 0x44, 0x3c, 0x84, 0x46, 0xf5, 0xd8, 0x98, 0x2d, 0xa3, 0x6f, 0xe0, 0x4d, 0xc0, 0xe1, 0x4d, 0x1f, 0xb7, 0xcd, 0xea, 0xee, 0x25, 0x1a, 0x34, 0x8e, 0xdd, 0x54, 0x62, 0x36, 0x10, 0xae, 0x6d, 0xf5, 0xb2, 0x92, 0x02, 0xe1, 0x12, 0x0d, 0xe5, 0xa1, 0xda, 0x6c, 0x22, 0xee, 0xad, 0x83, 0xa1, 0x24, 0x78, 0x3c, 0x3e, 0x35, 0x62, 0x2d, 0x00, 0xd8, 0x84, 0x9e, 0x8c, 0xbc, 0x3b, 0xaa, 0x76, 0xbd, 0x13, 0x35, 0xa4, 0x2e, 0x3e, 0x01, 0x50, 0x61, 0x76, 0x21, 0x88, 0x73, 0x0d, 0x66, 0x45, 0x86, 0x29, 0x68, 0x34, 0xa3, 0x1c, 0x72, 0x75, 0x22, 0xa7, 0x7d, 0xe7, 0xc6, 0xd7, 0x1f, 0x90, 0x67, 0xa1, 0x82, 0xeb, 0xa4, 0xc5, 0x9b, 0x01, 0x2e, 0x93, 0x56, 0x92, 0x32, 0x94, 0x3a, 0xa2, 0xb6, 0x54, 0xcc, 0x57, 0xd0, 0xc1, 0x89, 0xa2, 0x38, 0x04, 0x45, 0xbe, 0x1e, 0xf8, 0x86, 0x77, 0xb8, 0x50, 0x88, 0x60, 0x54, 0xe0, 0xee, 0xb7, 0xc7, 0x4c, 0xb2, 0xa0, 0x11, 0x29, 0xa6, 0xc0, 0x53, 0xc4, 0x17, 0x33, 0x46, 0x4c, 0x71, 0xb2, 0x11, 0x7a, 0xa0, 0xb0, 0x3f, 0xd8, 0x74, 0xdb, 0x0c, 0x6f, 0xcb, 0x5f, 0x5a, 0xea, 0x91, 0xb4, 0x96, 0x4a, 0x12, 0xf3, 0xed, 0xd0, 0x27, 0x50, 0x70, 0xa2, 0xa3, 0x9b, 0x27, 0x57, 0x55, 0x78, 0x54, 0x86, 0xfc, 0xc3, 0x8c, 0x08, 0xcb, 0xaf, 0x5a, 0x09, 0xc4, 0x64, 0xfd, 0x58, 0x16, 0xfd, 0x78, 0x95, 0x77, 0xb1, 0x1e, 0x01, 0x12, 0x7b, 0x57, 0x7c, 0x89, 0xcc, 0xe1, 0xa7, 0x49, 0x13, 0x63, 0xc0, 0x3b, 0xb3, 0x3e, 0x48, 0xf2, 0x04, 0xe2, 0x46, 0x62, 0x6d, 0x97, 0x48, 0x3a, 0x24, 0xab, 0x95, 0x6d, 0xff, 0x60, 0x55, 0x50, 0xd5, 0x40, 0x8a, 0x16, 0xb4, 0xcf, 0x8c, 0x7f, 0x84, 0xbe, 0x59, 0x61, 0x0d, 0x87, 0x45, 0x66, 0x3f, 0xe3, 0x5b, 0x88, 0xb7, 0x49, 0xf0, 0xba, 0x3c, 0xb1, 0x05, 0x38, 0xc9, 0xd4, 0x8b, 0x39, 0x7b, 0x6a, 0x9e, 0xe8, 0xf5, 0x04, 0x32, 0x69, 0x68, 0x64, 0x86, 0x21, 0x73, 0x2b, 0xc2, 0xee, 0xb0, 0xe8, 0x21, 0x88, 0x8c, 0x20, 0xe5, 0x7c, 0x06, 0x79, 0x20, 0xb6, 0x12, 0xf8, 0x4c, 0x6a, 0x3d, 0x15, 0x4a, 0x66, 0xcf, 0xad, 0xa3, 0x14, 0xca, 0x3d, 0x57, 0x4e, 0xde, 0x6b, 0x72, 0x98, 0x70, 0x4e, 0x46, 0x4c, 0xc7, 0x31, 0x82, 0x1b, 0x9b, 0x86, 0x5c, 0x5c, 0x33, 0x73, 0x1f, 0x7c, 0x6c, 0x75, 0x00, 0xbf, 0xdd, 0x19, 0xa3, 0xe9, 0x65, 0x9e, 0xc9, 0xef, 0x36, 0x3b, 0xad, 0x2e, 0x70, 0x4c, 0x9e, 0x13, 0xb0, 0xc0, 0xe0, 0x3b, 0xfe, 0x4b, 0x4b, 0xf9, 0x3c, 0x37, 0x63, 0x23, 0x82, 0x53, 0x7c, 0x40, 0xa3, 0xfd, 0x70, 0x42, 0xd8, 0xad, 0x20, 0x1a, 0x3c, 0xd9, 0x76, 0x71, 0x5e, 0xe6, 0x51, 0x09, 0xcc, 0xb4, 0xc0, 0xf0, 0x01, 0xc1, 0x4e, 0x91, 0xb0, 0x63, 0x90, 0xa6, 0x46, 0xd9, 0xcc, 0x9b, 0xd3, 0x99, 0x40, 0xfe, 0x50, 0x8c, 0xf1, 0x2e, 0x50, 0x97, 0xfb, 0x20, 0x45, 0x75, 0xa5, 0x5f, 0x2d, 0x69, 0x1b, 0xf5, 0x51, 0xb2, 0x25, 0xbd, 0x46, 0xc4, 0x56, 0xdc, 0x0b, 0x20, 0x06, 0x4c, 0xc4, 0xac, 0x2c, 0xd8, 0xda, 0xd6, 0x11, 0xa2, 0xda, 0x15, 0xf2, 0x34, 0x83, 0x16, 0x0a, 0xd1, 0x05, 0xe5, 0x2b, 0xd0, 0xad, 0x90, 0x3d, 0xa2, 0xc5, 0x1d, 0x2a, 0xe0, 0x57, 0xe0, 0x51, 0x6d, 0xfb, 0x73, 0x84, 0x89, 0x15, 0x40, 0x1c, 0xca, 0x55, 0x66, 0x66, 0x62, 0x3b, 0xf6, 0x64, 0xdd, 0x94, 0x47, 0x1e, 0xd4, 0x7e, 0x38, 0xb1, 0xf4, 0xfd, 0x66, 0xa7, 0xd4, 0x85, 0x75, 0xd3, 0xce, 0x13, 0x24, 0xb8, 0xd4, 0x9e, 0x1a, 0x32, 0xef, 0x65, 0xb5, 0xc6, 0x49, 0x71, 0x02, 0x3a, 0x04, 0xfc, 0x64, 0xbf, 0x1f, 0xa2, 0x82, 0x1a, 0x3a, 0xc6, 0xb4, 0xff, 0x9e, 0x80, 0xdd, 0xec, 0xa6, 0x14, 0xec, 0xd4, 0xc7, 0x8e, 0x98, 0xed, 0xb8, 0xdc, 0x20, 0x9e, 0xbf, 0x94, 0x9a, 0xcf, 0x94, 0x65, 0xfb, 0x1c, 0x83, 0x64, 0xdc, 0x1f, 0x67, 0xe9, 0xe7, 0x12, 0x6c, 0x9a, 0x79, 0x01, 0xfd, 0x4d, 0xc9, 0x30, 0xcb, 0xda, 0xc5, 0xb6, 0xc0, 0x02, 0x9b, 0x49, 0x1b, 0x73, 0x43, 0xb1, 0x3a, 0xd3, 0xd4, 0x77, 0xc8, 0xc9, 0x86, 0xa8, 0x5b, 0x23, 0x7e, 0x34, 0x82, 0x55, 0xb3, 0xe5, 0x3d, 0x8c, 0x52, 0x44, 0x83, 0xd4, 0x84, 0xd9, 0xdf, 0x2e, 0xe4, 0x05, 0x98, 0xb0, 0x06, 0x54, 0xb7, 0x8a, 0x0f, 0x79, 0x49, 0xec, 0xe5, 0x42, 0x8e, 0x97, 0x45, 0x50, 0x2f, 0x59, 0xad, 0x40, 0xc8, 0xde, 0x9a, 0xb2, 0x5f, 0x31, 0xe5, 0x33, 0xc4, 0xc1, 0x6b, 0xc0, 0xf7, 0xc5, 0xcb, 0xcc, 0xc1, 0x15, 0x42, 0xa0, 0x62, 0x1f, 0xaa, 0xd3, 0xb9, 0x78, 0x0d, 0xab, 0xb2, 0x01, 0x01, 0x36, 0x3a, 0x67, 0x02, 0x7b, 0xc1, 0x00, 0xfe, 0x45, 0xb3, 0xac, 0x89, 0xff, 0x3f, 0xb3, 0xa3, 0x05, 0x95, 0x27, 0x9d, 0xf8, 0xe9, 0x81, 0xae, 0x9a, 0xc6, 0xbc, 0x75, 0xc4, 0xed, 0xb0, 0x12, 0xcf, 0xb2, 0xab, 0x8c, 0x8e, 0x61, 0x67, 0x53, 0xee, 0xa5, 0x22, 0x07, 0x56, 0x06, 0xb5, 0x2b, 0xaf, 0x26, 0xe9, 0x35, 0xb4, 0x81, 0xe1, 0xd8, 0x0f, 0x8f, 0x2b, 0x1c, 0xfd, 0x70, 0x42, 0xfe, 0x87, 0x46, 0x1c, 0xc8, 0x9d, 0x61, 0xbf, 0x56, 0xdc, 0x68, 0x37, 0xc4, 0x52, 0x91, 0x4d, 0x46, 0x54, 0x9d, 0x58, 0x00, 0x52, 0x6a, 0xf9, 0x41, 0xb2, 0x6c, 0x17, 0x82, 0xfc, 0xaf, 0x2c, 0xb8, 0x15, 0xd3, 0xb1, 0x10, 0x4c, 0x06, 0xd7, 0x0f, 0x8a, 0x54, 0x72, 0xea, 0xde, 0x20, 0x54, 0xd7, 0x43, 0xa8, 0xf9, 0x16, 0x63, 0xe1, 0x0b, 0xc0, 0x46, 0x5f, 0x4d, 0x41, 0xc8, 0xa0, 0x1d, 0x59, 0x2a, 0x71, 0x22, 0x8a, 0x51, 0xef, 0x99, 0x1b, 0x67, 0x6f, 0x72, 0x4a, 0x1d, 0x4e, 0x4b, 0x97, 0x58, 0x2f, 0x24, 0xb3, 0xb3, 0xf3, 0x45, 0xe7, 0xf4, 0x43, 0xce, 0xbb, 0xf0, 0x94, 0x67, 0xd8, 0x9e, 0x8b, 0x76, 0xd5, 0xb9, 0x84, 0xa6, 0x38, 0x0e, 0x55, 0x5d, 0x0f, 0xcf, 0x1c, 0x8f, 0x5a, 0xaa, 0xb1, 0x8b, 0x7e, 0xb3, 0x7a, 0xf3, 0x60, 0x9a, 0xe3, 0x99, 0x07, 0xd7, 0x2d, 0x61, 0xe9, 0xed, 0xa2, 0xd7, 0x97, 0xe9, 0x6f, 0x8d, 0x4a, 0xb6, 0x07, 0x8a, 0xc1, 0x05, 0x04, 0x98, 0xf4, 0x0f, 0xea, 0xc9, 0xa9, 0x6e, 0xad, 0xc2, 0x56, 0x07, 0xe5, 0x58, 0x45, 0x92, 0xeb, 0x8b, 0x4e, 0x4c, 0x34, 0x34, 0xd5, 0x5a, 0x44, 0x4a, 0xa9, 0xc6, 0x8e, 0x53, 0x31, 0x0d, 0x08, 0x3b, 0x28, 0x30, 0xdb, 0xaa, 0x5d, 0x72, 0x19, 0xf9, 0x68, 0xdd, 0xe7, 0xcb, 0x05, 0x7a, 0x74, 0x6d, 0xe0, 0x6d, 0xee, 0x94, 0xbd, 0x30, 0xd9, 0xe8, 0x4c, 0x43, 0x07, 0x4d, 0xe1, 0xd1, 0x6b, 0x7a, 0x72, 0x7b, 0xe7, 0xc7, 0xba, 0xd9, 0x93, 0x21, 0x0e, 0x97, 0x7a, 0x1b, 0x00, 0xbd, 0x2f, 0x34, 0xc2, 0x17, 0x88, 0x4a, 0xd8, 0x85, 0x85, 0x9a, 0x0a, 0x42, 0xc9, 0xfa, 0x56, 0x72, 0x64, 0x65, 0x88, 0x45, 0xa7, 0x2b, 0x38, 0x1d, 0xff, 0xfa, 0x3b, 0x68, 0x13, 0xac, 0x67, 0x54, 0x5c, 0xdd, 0x69, 0x6c, 0xbd, 0xcd, 0x09, 0x7b, 0xe9, 0xad, 0xee, 0x94, 0x8a, 0x0f, 0xb2, 0x87, 0x30, 0x1d, 0xfb, 0x71, 0xec, 0x9a, 0x4d, 0x90, 0xcd, 0x23, 0xbf, 0xc7, 0xea, 0x5e, 0xbd, 0x65, 0x5a, 0x35, 0xdc, 0x6c, 0x4c, 0xca, 0x5d, 0x5c, 0x70, 0x6a, 0x4d, 0x3b, 0x9c, 0x1a, 0xbc, 0x36, 0x72, 0xbd, 0x1c, 0xa6, 0xeb, 0x4f, 0xda, 0x61, 0xf0, 0xed, 0x04, 0xcd, 0xd8, 0x57, 0xc5, 0x19, 0xf6, 0xe2, 0x22, 0x2b, 0x98, 0xb0, 0x77, 0x24, 0x05, 0xf1, 0x19, 0x3e, 0x64, 0x17, 0x7c, 0x76, 0x2e, 0x8a, 0xcf, 0x99, 0x94, 0xfa, 0xe8, 0xda, 0xc0, 0x7b, 0xde, 0xa5, 0x67, 0xbc, 0xd2, 0xc4, 0xbe, 0x6e, 0x11, 0xdf, 0xd9, 0x16, 0x78, 0x98, 0x11, 0xe1, 0xe9, 0xb4, 0x2a, 0x7e, 0x19, 0x23, 0xef, 0x12, 0xbd, 0x9b, 0xba, 0xbb, 0xc9, 0xac, 0xff, 0x80, 0xf3, 0x71, 0x12, 0x40, 0x21, 0x1c, 0xe7, 0xeb, 0x7a, 0xe8, 0x0c, 0xba, 0xa8, 0x11, 0x40, 0x04, 0x79, 0x6a, 0x71, 0xdb, 0x05, 0x46, 0xc4, 0x54, 0x53, 0xb3, 0xaa, 0xd9, 0xa6, 0x34, 0x8b, 0xfa, 0x04, 0x0e, 0xda, 0xf7, 0x39, 0x66, 0x0b, 0xf4, 0x1e, 0xe9, 0x6a, 0xed, 0x1f, 0x03, 0xb2, 0x76, 0x11, 0x4c, 0xfb, 0x08, 0x91, 0xb3, 0x67, 0xec, 0xcb, 0xf7, 0x0f, 0x0c, 0x92, 0x4d, 0xef, 0xf4, 0xcb, 0xa1, 0x22, 0x7c, 0xf9, 0x53, 0xc3, 0x8f, 0xcd, 0xc5, 0x5d, 0xd6, 0x9c, 0x4b, 0x95, 0x54, 0xc8, 0x5c, 0xe2, 0x87, 0x3d, 0xc0, 0x10, 0x40, 0x06, 0x4e, 0x85, 0x0c, 0x07, 0xbb, 0x5d, 0x2a, 0x05, 0x5a, 0x05, 0x4a, 0x43, 0x9f, 0x0a, 0x11, 0xf3, 0x87, 0x42, 0xa4, 0xd4, 0x0e, 0xb6, 0x3d, 0xc7, 0x82, 0x46, 0x3b, 0xe0, 0xa7, 0xcd, 0xce, 0x5d, 0xea, 0x4b, 0x68, 0xf2, 0x31, 0xec, 0x9f, 0xa4, 0xef, 0xa0, 0x5a, 0x52, 0x2e, 0xc3, 0x60, 0x7d, 0x46, 0x64, 0x43, 0xbc, 0xa1, 0xa9, 0x89, 0x4d, 0xbb, 0xa6, 0x68, 0x4f, 0x63, 0x13, 0xa9, 0xc1, 0x71, 0x25, 0x01, 0xd4, 0x67, 0xb9, 0xfa, 0x21, 0xd1, 0x37, 0xa3, 0xb7, 0x50, 0x51, 0x3a, 0x4a, 0x44, 0xe0, 0x24, 0x46, 0xf4, 0x11, 0x43, 0xd9, 0xe9, 0x08, 0x44, 0x94, 0xcc, 0xd6, 0xcc, 0xfd, 0x98, 0x6c, 0x25, 0x05, 0x84, 0x26, 0xd2, 0xd5, 0xb6, 0x33, 0x0a, 0x81, 0xbb, 0xe0, 0x1d, 0x72, 0x80, 0x31, 0xb0, 0x4c, 0x80, 0x92, 0xf3, 0x5c, 0xa0, 0x3b, 0xa8, 0x10, 0x43, 0xdc, 0x70, 0x5c, 0x77, 0x26, 0xbb, 0x2d, 0x39, 0x20, 0xcc, 0x23, 0xb8, 0x3c, 0x53, 0xc3, 0x46, 0x21, 0x96, 0xd8, 0x5e, 0xa8, 0xfc, 0x5b, 0x8d, 0xad, 0xcc, 0x1f, 0x48, 0x46, 0x32, 0xd7, 0xc0, 0x80, 0xbe, 0x06, 0x05, 0xac, 0xd4, 0x53, 0x92, 0xbe, 0x69, 0x0e, 0xc1, 0x8f, 0x33, 0x24, 0xc9, 0x63, 0xe7, 0x6d, 0xb8, 0x4c, 0x1c, 0xfc, 0x0c, 0x8a, 0x2a, 0x1c, 0x89, 0xe2, 0x06, 0x0c, 0x20, 0xac, 0x7c, 0x33, 0xd1, 0x57, 0xcb, 0x0f, 0x2d, 0xd1, 0x80, 0x4b, 0x82, 0xc1, 0x82, 0x33, 0xc9, 0x80, 0x00, 0x15, 0xee, 0xe9, 0xeb, 0x57, 0xaf, 0xbe, 0x1a, 0x45, 0x20, 0xfa, 0xf7, 0xd8, 0xb3, 0x45, 0xc2, 0x77, 0x0b, 0x4d, 0x80, 0xc9, 0xa4, 0x45, 0xf6, 0xcd, 0xf1, 0x8a, 0x80, 0x71, 0x98, 0x49, 0x07, 0x4f, 0x4b, 0x34, 0xfd, 0xad, 0x99, 0xdf, 0x6b, 0x8e, 0xb2, 0x04, 0x18, 0xd6, 0xc4, 0xa0, 0x6b, 0xdc, 0x06, 0x32, 0x20, 0x68, 0xb2, 0x43, 0xf5, 0xd6, 0xd1, 0xdf, 0x5e, 0x70, 0xe4, 0x01, 0x49, 0xdb, 0x99, 0xb0, 0xa5, 0x89, 0x35, 0xf6, 0xd2, 0x36, 0x42, 0x0e, 0x12, 0xc3, 0xc5, 0x54, 0xe9, 0x09, 0x59, 0x7e, 0xa9, 0x58, 0x95, 0x74, 0xf0, 0x5d, 0x3c, 0x72, 0xa8, 0x1a, 0xd2, 0x58, 0x90, 0x49, 0xa1, 0xe3, 0x60, 0xb2, 0xb0, 0x54, 0xf6, 0xbb, 0x39, 0xa2, 0x26, 0xa8, 0xf1, 0xb3, 0x1e, 0xc0, 0x1b, 0xff, 0x6f, 0xb0, 0xf1, 0xd7, 0xbb, 0x79, 0xae, 0xdb, 0x03, 0xf4, 0x0a, 0xc0, 0xf8, 0x3a, 0x7e, 0x41, 0xea, 0x70, 0xab, 0x38, 0x66, 0xae, 0x69, 0xc6, 0x66, 0x6a, 0x8d, 0x4b, 0x44, 0x0d, 0xc0, 0x8e, 0x43, 0x90, 0x6b, 0x84, 0x24, 0x30, 0x4e, 0xb1, 0xc7, 0x1f, 0x38, 0x49, 0x61, 0x1d, 0xf8, 0x95, 0x18, 0x7a, 0xe7, 0x1b, 0x32, 0x6d, 0x0d, 0x44, 0x42, 0x63, 0xd0, 0x17, 0x4b, 0xb0, 0x51, 0xd9, 0x64, 0x26, 0x74, 0x05, 0x22, 0xec, 0x3d, 0xa5, 0x6c, 0x69, 0x4c, 0xa5, 0xdf, 0x96, 0x9c, 0x86, 0x2a, 0x26, 0x7f, 0xa1, 0xea, 0x62, 0x25, 0x82, 0x89, 0x4e, 0xf0, 0xf1, 0xd0, 0x5b, 0x00, 0x98, 0x96, 0xb2, 0xa1, 0x5c, 0x7d, 0xb1, 0x4c, 0x07, 0x0c, 0xef, 0xcc, 0x21, 0x3b, 0x9d, 0x18, 0xf4, 0x87, 0x54, 0x11, 0x83, 0xc6, 0xb5, 0x19, 0x46, 0x57, 0x07, 0xfc, 0x53, 0xe1, 0xd1, 0x46, 0xf5, 0x44, 0x57, 0x25, 0xf2, 0x6b, 0xf3, 0x51, 0x57, 0x24, 0x5f, 0xb2, 0x5b, 0x81, 0xf4, 0x08, 0xfb, 0x7b, 0xd1, 0xf4, 0x2a, 0xd7, 0xb9, 0x34, 0x9b, 0x5d, 0xde, 0x62, 0x25, 0x61, 0x3e, 0xd3, 0x5e, 0x94, 0x8c, 0x2f, 0xe2, 0xa4, 0x4e, 0x62, 0x55, 0x2f, 0x15, 0x30, 0x30, 0x42, 0x54, 0x72, 0xac, 0xef, 0x84, 0xb4, 0xf3, 0x0c, 0x69, 0x02, 0x15, 0x18, 0x2d, 0x6a, 0x11, 0xc8, 0xc7, 0x03, 0x7e, 0x7b, 0xc5, 0x89, 0x82, 0xc0, 0x76, 0x8c, 0x65, 0x18, 0x00, 0x16, 0x68, 0xbb, 0x18, 0x2b, 0x24, 0x51, 0x00, 0xe3, 0x3e, 0xd9, 0x0c, 0x4f, 0x7b, 0x7c, 0xc5, 0x9f, 0xb6, 0xa8, 0xa7, 0x80, 0x8e, 0x31, 0x98, 0xca, 0x52, 0xd4, 0x93, 0xd1, 0xf8, 0xf0, 0xfe, 0xb8, 0xee, 0x21, 0xf8, 0x1e, 0x3c, 0xfc, 0x58, 0xbe, 0xc3, 0xfc, 0x82, 0xfc, 0xbc, 0x87, 0x2c, 0x92, 0xb4, 0x63, 0x8b, 0xde, 0xb1, 0xab, 0x57, 0x4a, 0x62, 0x18, 0x06, 0x5e, 0xd9, 0x80, 0x81, 0x14, 0xf6, 0x6a, 0x62, 0xd2, 0x94, 0xca, 0xb2, 0x07, 0x7c, 0xb7, 0x62, 0xee, 0xe8, 0x1a, 0x99, 0xe0, 0xb4, 0xb6, 0xd3, 0xb6, 0xb6, 0xde, 0x36, 0x9e, 0x6a, 0x37, 0x50, 0xa6, 0xa6, 0xb7, 0x96, 0x89, 0x11, 0xa0, 0x5d, 0x41, 0xc8, 0xdc, 0x00, 0x75, 0x0b, 0x16, 0x12, 0x4f, 0xea, 0xd5, 0x4d, 0xbb, 0x90, 0xf9, 0x74, 0x3e, 0xb5, 0xfe, 0x62, 0xa3, 0xc3, 0xe3, 0x17, 0xf0, 0x4a, 0x1f, 0xe9, 0x73, 0xbb, 0xab, 0xd3, 0xb2, 0x17, 0x50, 0x9d, 0x19, 0x8a, 0xa4, 0xd5, 0xe6, 0xec, 0xe7, 0x3a, 0xba, 0x5b, 0xc5, 0x6d, 0x54, 0x32, 0x6e, 0xef, 0x94, 0x1f, 0x22, 0x67, 0xab, 0x42, 0xc2, 0x9f, 0xd2, 0xf9, 0x60, 0x33, 0xa5, 0xae, 0x2a, 0x28, 0x03, 0x58, 0x91, 0x06, 0x95, 0x1f, 0xc2, 0xcd, 0x64, 0x3a, 0x1a, 0xac, 0xb9, 0xe4, 0x64, 0xd2, 0x95, 0x15, 0x21, 0x7b, 0xa8, 0xe2, 0x2c, 0x16, 0x9e, 0xc0, 0xd4, 0x6c, 0x88, 0x7f, 0x02, 0x9a, 0x9c, 0x90, 0x1a, 0x98, 0xa4, 0x0d, 0x6e, 0x2f, 0xc6, 0x6b, 0x2a, 0x70, 0x98, 0x2e, 0xe4, 0xc5, 0xb7, 0x2b, 0x0c, 0xb7, 0x6f, 0xc3, 0x1e, 0x88, 0x35, 0x07, 0x31, 0xde, 0x96, 0x93, 0x7c, 0x21, 0xab, 0x86, 0x6f, 0x4b, 0xf6, 0x05, 0xa1, 0x89, 0x3e, 0x1c, 0xb3, 0x05, 0x3c, 0x3a, 0x11, 0x24, 0xb3, 0x5f, 0x70, 0xd4, 0x16, 0x84, 0x38, 0x38, 0xa7, 0xfb, 0x0a, 0xb0, 0x50, 0xf9, 0x07, 0x2a, 0xbe, 0x26, 0x9d, 0xc7, 0x51, 0x49, 0x0c, 0x8f, 0x64, 0x18, 0xa1, 0x97, 0x4e, 0x92, 0xf3, 0x07, 0x29, 0x83, 0x33, 0xdd, 0x6b, 0x5c, 0xbe, 0x43, 0x3b, 0xcb, 0xf8, 0x68, 0xde, 0xa1, 0xce, 0x94, 0xaa, 0xdd, 0xd5, 0xce, 0xf3, 0x93, 0xc3, 0x3d, 0x19, 0x7f, 0xfa, 0x43, 0x97, 0xf6, 0x49, 0xef, 0xf1, 0x2e, 0x48, 0x27, 0x94, 0x52, 0x76, 0xa0, 0xb2, 0xd7, 0xd3, 0x61, 0xf1, 0x2a, 0x26, 0xc7, 0xbb, 0x5a, 0x20, 0x35, 0xaa, 0xfc, 0x64, 0xf7, 0x47, 0x87, 0x1b, 0x69, 0xad, 0x8f, 0x7d, 0x57, 0xa3, 0xa5, 0x22, 0x57, 0x1f, 0x16, 0x8d, 0x4b, 0x1b, 0x2c, 0x97, 0xc0, 0x01, 0x99, 0xd4, 0x17, 0x86, 0x06, 0x47, 0x1c, 0x15, 0x5f, 0x36, 0x0b, 0x90, 0x8a, 0x4a, 0x9e, 0x9b, 0xaf, 0x0f, 0x28, 0x51, 0x34, 0x79, 0xdf, 0xae, 0xe0, 0xee, 0xab, 0x1e, 0xbd, 0xc7, 0x6d, 0x1c, 0x3f, 0x9c, 0xda, 0xfc, 0x11, 0x80, 0x7d, 0xf6, 0x01, 0xb0, 0x16, 0x32, 0xbd, 0xa4, 0x91, 0xfe, 0x03, 0xcb, 0xed, 0x14, 0x28, 0x99, 0x93, 0xfa, 0x68, 0xd5, 0x3c, 0x39, 0xef, 0x7e, 0x8b, 0xd2, 0x9c, 0x1c, 0xfc, 0x43, 0x98, 0x6e, 0x14, 0xab, 0x9d, 0x69, 0xbb, 0x8a, 0x01, 0xad, 0x6e, 0x88, 0xe6, 0xd8, 0x70, 0xe2, 0xa4, 0x42, 0x05, 0x41, 0x90, 0xe3, 0x4b, 0x73, 0x7a, 0x2b, 0x1f, 0xbb, 0x76, 0x08, 0xa5, 0x95, 0x9c, 0x7e, 0xe5, 0x20, 0x37, 0x9e, 0x6a, 0xb3, 0x13, 0x96, 0x73, 0x9f, 0x33, 0xa2, 0x01, 0x7f, 0x4b, 0xf9, 0x99, 0xc2, 0x30, 0x54, 0x6d, 0x4f, 0x75, 0x11, 0xf0, 0x32, 0x13, 0x33, 0x2f, 0x15, 0x1b, 0x5d, 0x50, 0x62, 0x9d, 0xd0, 0xbd, 0x6e, 0x31, 0x47, 0xcb, 0xcc, 0xc2, 0xd4, 0xb3, 0x23, 0xd0, 0x93, 0xa3, 0xc4, 0x95, 0xc9, 0x22, 0x6f, 0x7a, 0x4b, 0xe6, 0x78, 0x79, 0x3f, 0x72, 0x82, 0x13, 0x39, 0x6a, 0x43, 0xc6, 0x4a, 0x4e, 0xc5, 0x1d, 0x10, 0x43, 0x5d, 0x34, 0x4b, 0x0f, 0xd5, 0xe7, 0x8f, 0x5c, 0x7b, 0xaa, 0x1e, 0xc6, 0x8c, 0x73, 0xf6, 0x27, 0x7c, 0x40, 0xb0, 0x50, 0x77, 0xe9, 0xc5, 0xdf, 0x75, 0x44, 0xcf, 0xcd, 0xec, 0xd2, 0x81, 0x6d, 0x32, 0xbc, 0x36, 0x8a, 0xd6, 0x85, 0x6d, 0xc9, 0xe2, 0x9f, 0x9c, 0x34, 0xf9, 0xa3, 0xe9, 0x4b, 0x24, 0x3a, 0x22, 0xd2, 0xdb, 0xa2, 0x50, 0xd9, 0x63, 0x16, 0x38, 0xf7, 0x9a, 0x79, 0xa5, 0x30, 0xd3, 0x0b, 0xf3, 0x38, 0xc8, 0x8d, 0x48, 0x5a, 0x33, 0x12, 0x45, 0x60, 0x20, 0x3c, 0xd3, 0x22, 0x95, 0xe6, 0x25, 0xa3, 0x9d, 0xf2, 0xcf, 0x06, 0x14, 0x55, 0x96, 0x8b, 0x02, 0x9e, 0xc5, 0x3a, 0x45, 0x8e, 0xb5, 0x4a, 0x6a, 0x17, 0xf8, 0xeb, 0xed, 0x0d, 0x97, 0x8f, 0x3a, 0x76, 0xcc, 0xb2, 0x42, 0x2a, 0x47, 0x49, 0x41, 0x23, 0x26, 0x06, 0x45, 0x94, 0x4b, 0x68, 0x46, 0xc0, 0x97, 0x9e, 0x17, 0x0b, 0x71, 0xe5, 0xe0, 0x15, 0x84, 0xc9, 0x41, 0xc0, 0x59, 0x6f, 0x68, 0x80, 0x94, 0x52, 0xe3, 0x0e, 0xc4, 0x3e, 0x0b, 0xc7, 0x83, 0x2a, 0x4d, 0x88, 0xf2, 0xd3, 0x20, 0x2f, 0x1f, 0x2a, 0x3f, 0x42, 0x63, 0xaa, 0x69, 0x3b, 0xa5, 0xdf, 0x2a, 0x63, 0x45, 0x94, 0x23, 0x5d, 0x15, 0x99, 0xa6, 0x91, 0xe1, 0xbe, 0x2e, 0xaa, 0x21, 0xbd, 0xdf, 0x47, 0xba, 0x35, 0x2c, 0x23, 0x4c, 0x3c, 0xa0, 0xe6, 0x76, 0x21, 0x23, 0x55, 0x45, 0x93, 0x46, 0x99, 0x0f, 0x54, 0x01, 0xf5, 0xa0, 0xcf, 0x4b, 0x89, 0xe1, 0xab, 0xec, 0x99, 0xcd, 0xab, 0xf9, 0x0f, 0x75, 0xe2, 0x67, 0x08, 0xa3, 0x48, 0x31, 0x58, 0x51, 0x35, 0x09, 0xa8, 0xea, 0x5e, 0xd4, 0xcf, 0x24, 0x05, 0x95, 0x89, 0xcd, 0x07, 0x48, 0x49, 0xc1, 0xb5, 0x72, 0x40, 0x69, 0x6b, 0xed, 0x34, 0x28, 0x51, 0xe9, 0x76, 0x93, 0x98, 0x19, 0xe9, 0xad, 0x9b, 0xf0, 0x42, 0xe4, 0xc0, 0xe5, 0x26, 0xfc, 0x1f, 0x99, 0x25, 0xe4, 0xb9, 0x64, 0xc7, 0xfb, 0x52, 0xd2, 0x5a, 0x7a, 0x5c, 0x9a, 0x01, 0xbd, 0xdd, 0x68, 0xe1, 0x83, 0xb6, 0x0d, 0xd6, 0x0f, 0x1e, 0x78, 0xc9, 0xa0, 0xb2, 0x81, 0x08, 0x5c, 0x14, 0xa5, 0x55, 0xa0, 0xbd, 0x3e, 0xbc, 0x34, 0x4d, 0x39, 0x7c, 0x75, 0x51, 0x62, 0xfc, 0x60, 0x16, 0x37, 0x54, 0xeb, 0x16, 0x55, 0x7b, 0x62, 0x63, 0x23, 0x77, 0x82, 0x62, 0xff, 0xab, 0xeb, 0x53, 0xd3, 0xd3, 0xfe, 0xd8, 0x72, 0xb9, 0x1e, 0x6e, 0x02, 0x0b, 0x19, 0x39, 0x1f, 0xd8, 0x41, 0xa1, 0xcd, 0xa0, 0xf0, 0x1c, 0xd9, 0x09, 0x1a, 0x73, 0x7b, 0xda, 0xfd, 0x35, 0x6e, 0x62, 0x5a, 0x88, 0x79, 0xce, 0xaf, 0x4a, 0xd3, 0x90, 0x0e, 0x79, 0x6d, 0xb2, 0xf3, 0xdf, 0xc7, 0x32, 0x75, 0x8d, 0x2e, 0x60, 0x4d, 0xec, 0x37, 0xa0, 0xc7, 0x94, 0xa9, 0x53, 0x1b, 0x0e, 0x24, 0x40, 0xf0, 0x91, 0x2a, 0x71, 0xe6, 0x84, 0x27, 0x24, 0xd7, 0xc0, 0x04, 0x23, 0x62, 0xe5, 0x8c, 0x98, 0x7f, 0xbb, 0x6d, 0xf7, 0x5b, 0xb9, 0x85, 0x43, 0xa1, 0xf1, 0xda, 0xb6, 0x4e, 0xc7, 0x1c, 0x62, 0xc6, 0x08, 0x64, 0xa4, 0x4e, 0xc6, 0xf1, 0x69, 0x70, 0x5d, 0x34, 0x9d, 0x82, 0xb9, 0xb9, 0xaa, 0xb5, 0xcc, 0xee, 0xc8, 0x49, 0x19, 0x24, 0x0a, 0x67, 0x37, 0xaf, 0x2e, 0x0b, 0xa5, 0x92, 0xb9, 0x37, 0x6a, 0x7a, 0xd7, 0x07, 0xee, 0x40, 0x5e, 0x49, 0xd1, 0x14, 0x59, 0x20, 0x81, 0x58, 0x00, 0x7d, 0xa6, 0xa3, 0xb7, 0x55, 0xa5, 0x40, 0xd0, 0x2c, 0xc9, 0xf4, 0x5e, 0x8b, 0xbb, 0xf6, 0xd5, 0x00, 0x1c, 0x73, 0x13, 0xd2, 0x41, 0xe4, 0x08, 0xdb, 0x16, 0x8e, 0xf9, 0x1b, 0x3f, 0xfc, 0x55, 0x2d, 0xc1, 0x5f, 0x66, 0x05, 0xaf, 0xe7, 0xb5, 0xae, 0xe9, 0x64, 0xf4, 0x2d, 0xde, 0xc8, 0x4d, 0xa5, 0x6a, 0xf6, 0xac, 0x13, 0xbe, 0xf3, 0xea, 0xa1, 0x20, 0x38, 0x1e, 0x06, 0x7e, 0x8f, 0xd1, 0xa9, 0xf0, 0xd8, 0xad, 0xe9, 0xcb, 0x2c, 0xf0, 0x3f, 0x37, 0x3b, 0x2b, 0xe4, 0xdd, 0x28, 0xcf, 0x7d, 0xa0, 0x26, 0x4c, 0x95, 0xe7, 0x99, 0x3c, 0x19, 0x6d, 0xf4, 0xfd, 0x50, 0xb6, 0x8b, 0xa7, 0xa6, 0x1b, 0xbf, 0x6a, 0x92, 0xd1, 0xb3, 0x4f, 0x2c, 0x1b, 0xd8, 0x95, 0xda, 0x3f, 0xd3, 0x2e, 0xab, 0x5e, 0xfa, 0x0c, 0x02, 0x37, 0x48, 0x10, 0xe5, 0xba, 0x43, 0xb2, 0xb4, 0x23, 0x20, 0x54, 0x88, 0x62, 0xcc, 0x75, 0x46, 0x77, 0x8e, 0x9d, 0xdd, 0x42, 0xa7, 0xc3, 0x9b, 0xd8, 0x8d, 0x24, 0xe3, 0x58, 0x88, 0xe6, 0xd1, 0x01, 0x63, 0x7d, 0x44, 0x92, 0x17, 0x1f, 0x41, 0xbd, 0xce, 0x6a, 0x6d, 0xea, 0x56, 0x6a, 0xc0, 0xd7, 0x19, 0x9f, 0x89, 0x14, 0xb0, 0x2c, 0x0e, 0x24, 0x4d, 0xa7, 0x4d, 0xbf, 0x65, 0x92, 0x31, 0x77, 0xf4, 0x9d, 0x8c, 0x9d, 0xb2, 0x9d, 0xd7, 0x40, 0xad, 0x84, 0xb8, 0xba, 0x13, 0xee, 0x59, 0xb7, 0x1a, 0x69, 0xfe, 0x85, 0xde, 0xa2, 0x12, 0x66, 0xf5, 0x2d, 0x7e, 0xc9, 0x90, 0x77, 0xb6, 0x91, 0x5a, 0x5e, 0xfa, 0x2e, 0x09, 0xed, 0x0b, 0x49, 0xa3, 0xdd, 0x89, 0xdb, 0x70, 0x50, 0xe1, 0x25, 0x17, 0xfc, 0x81, 0xad, 0xb6, 0xca, 0x5f, 0x2f, 0xaf, 0x14, 0x23, 0x5f, 0xa0, 0x10, 0x7a, 0xd5, 0x2c, 0xdc, 0x6b, 0x73, 0xe1, 0x5e, 0x73, 0x49, 0xd5, 0xde, 0x76, 0x19, 0xb2, 0x9b, 0x61, 0x9d, 0x5e, 0x85, 0x79, 0xbf, 0x69, 0x27, 0x4a, 0x99, 0xd6, 0x43, 0xcc, 0xdf, 0xb3, 0x21, 0x01, 0xe4, 0xc1, 0x64, 0x20, 0x03, 0x17, 0xa1, 0x15, 0x69, 0x7f, 0xb2, 0x62, 0x2b, 0x3a, 0x67, 0x78, 0x93, 0x07, 0x28, 0x66, 0xe8, 0x02, 0x56, 0x6e, 0x8e, 0xc7, 0x40, 0xac, 0xb7, 0x40, 0x6b, 0x81, 0x5c, 0x61, 0x36, 0xb6, 0x8b, 0xf0, 0x86, 0x28, 0xdd, 0x5c, 0x6b, 0xb8, 0xab, 0x22, 0xbc, 0xd6, 0x3c, 0x17, 0xe1, 0xfd, 0xcb, 0x15, 0xe1, 0x4d, 0xfb, 0xe5, 0x8c, 0x22, 0xbc, 0xdb, 0x17, 0xe7, 0x16, 0xe0, 0x7d, 0x72, 0xf2, 0xa7, 0x41, 0x33, 0x3f, 0x80, 0x0a, 0x22, 0xb5, 0xe2, 0x6a, 0x33, 0x65, 0xb6, 0x6f, 0x54, 0x8e, 0x34, 0xb2, 0x53, 0xbe, 0x1e, 0xaf, 0x6b, 0xfa, 0x92, 0x68, 0xe3, 0x2b, 0x63, 0xfb, 0x6a, 0xae, 0xdb, 0xb2, 0xa7, 0x6f, 0xfb, 0x1c, 0x9c, 0xaa, 0xab, 0x3d, 0x56, 0xfb, 0xbd, 0xd7, 0x17, 0xf2, 0x98, 0xdb, 0xc0, 0xdb, 0xde, 0x29, 0xa3, 0xaf, 0x29, 0x61, 0xd3, 0x66, 0x22, 0x0a, 0x61, 0x19, 0xab, 0x34, 0xf1, 0xdf, 0xe3, 0x7a, 0x58, 0x47, 0x0e, 0x54, 0x29, 0x27, 0x7d, 0x29, 0xe1, 0xd1, 0x88, 0x21, 0xf2, 0x69, 0x99, 0x3b, 0x55, 0x92, 0x46, 0x3c, 0xdc, 0xfb, 0x9c, 0x21, 0xef, 0x9b, 0x15, 0x2f, 0xa6, 0xdd, 0xce, 0x38, 0x14, 0x96, 0xaa, 0x37, 0xa9, 0x5c, 0xb6, 0x7a, 0x12, 0x7f, 0x82, 0xc2, 0x0a, 0xbe, 0xd9, 0xaa, 0xf0, 0x8f, 0x5d, 0x7f, 0x04, 0xc1, 0x9d, 0xb5, 0xfc, 0x1f, 0xf0, 0xdb, 0x17, 0x80, 0xd1, 0x87, 0x37, 0xb8, 0x53, 0xfa, 0x61, 0xf8, 0x14, 0x9f, 0x60, 0x5e, 0xdd, 0xab, 0x2a, 0x9d, 0x22, 0x45, 0xde, 0xd1, 0x61, 0x17, 0x50, 0xf9, 0x4e, 0xda, 0xae, 0xba, 0x94, 0x2d, 0x21, 0x35, 0x85, 0x70, 0x55, 0x68, 0x96, 0x5f, 0xc9, 0xbe, 0xb8, 0x99, 0xd9, 0x28, 0x50, 0x8b, 0x69, 0x62, 0xe7, 0x85, 0xbb, 0xb3, 0x93, 0x6e, 0x53, 0x14, 0x5d, 0xb8, 0x59, 0x49, 0x9c, 0xf0, 0x4d, 0xdf, 0x61, 0xaf, 0xed, 0x3e, 0xf6, 0xcd, 0xf3, 0x1a, 0x8e, 0x3e, 0x75, 0x9d, 0xc7, 0x6d, 0xd5, 0xe6, 0x09, 0x42, 0x9e, 0x8a, 0x4c, 0x57, 0xe0, 0xbe, 0x42, 0xd5, 0x7d, 0x77, 0x0b, 0xce, 0xfc, 0x27, 0xb7, 0x41, 0xab, 0x54, 0x78, 0x18, 0x53, 0x96, 0x72, 0x50, 0xf1, 0x68, 0x85, 0xbf, 0x2e, 0xd9, 0xc5, 0xaa, 0x86, 0x63, 0x93, 0x90, 0x40, 0x43, 0x29, 0x2c, 0x98, 0x6d, 0x2a, 0x35, 0x16, 0xd1, 0x55, 0x44, 0x93, 0x87, 0x85, 0x30, 0x40, 0xef, 0x94, 0xcd, 0xd8, 0xa6, 0x5a, 0x65, 0x4c, 0xfa, 0x03, 0x46, 0x99, 0x5b, 0x9d, 0xf8, 0x6a, 0xad, 0xf2, 0x06, 0xd7, 0xe8, 0xfa, 0x6a, 0xe2, 0xd3, 0x0e, 0x22, 0x18, 0x9f, 0x4b, 0x35, 0x1b, 0x57, 0x11, 0xc3, 0x63, 0xdc, 0x7b, 0xa1, 0x7a, 0xa4, 0x59, 0xd5, 0x8b, 0x0f, 0xcd, 0x0e, 0x7c, 0x8d, 0x7a, 0xf5, 0xd2, 0xac, 0x58, 0x58, 0x44, 0x3b, 0x23, 0xef, 0xa2, 0x88, 0xe3, 0x89, 0x13, 0x14, 0xa0, 0x00, 0xa0, 0x6d, 0x5e, 0xac, 0xaa, 0x66, 0x8e, 0xbc, 0xd5, 0xcc, 0xa0, 0xcb, 0xb3, 0xfa, 0xea, 0x6b, 0xcb, 0x52, 0xa3, 0xa9, 0xfd, 0x6e, 0xfc, 0x89, 0x97, 0xe9, 0x9b, 0x2f, 0xf3, 0xce, 0xa4, 0xc9, 0xc6, 0xe6, 0xc2, 0x3a, 0xb5, 0x9d, 0x61, 0x9b, 0x3b, 0xa3, 0x3a, 0x81, 0x4d, 0x70, 0xb8, 0x47, 0x62, 0x6d, 0x5d, 0xb9, 0x5c, 0xbc, 0x65, 0x9a, 0x70, 0xa6, 0x48, 0xda, 0x54, 0x29, 0xfa, 0xc0, 0xc1, 0xd4, 0x9c, 0xde, 0xf4, 0xde, 0x1a, 0xa0, 0x3b, 0x41, 0x99, 0xab, 0x12, 0xa3, 0xf6, 0x9e, 0xcb, 0x47, 0x40, 0xe5, 0x2b, 0xf0, 0x6c, 0x61, 0x90, 0x98, 0x1c, 0x6b, 0xe0, 0xd9, 0x86, 0xab, 0xa8, 0xc4, 0x44, 0x12, 0x48, 0x98, 0x78, 0x6a, 0xa1, 0x1a, 0x17, 0x00, 0xf6, 0xc2, 0x42, 0x51, 0x59, 0xd5, 0x34, 0xa8, 0xa1, 0x0f, 0xce, 0xc8, 0xe1, 0x5a, 0x5b, 0x0e, 0x41, 0x72, 0xe8, 0x35, 0x33, 0x4b, 0x7e, 0xb2, 0x7a, 0x6d, 0xf0, 0x4b, 0xde, 0xf1, 0x5f, 0xa2, 0x0d, 0x2c, 0x90, 0x9d, 0x52, 0x0f, 0x81, 0xa2, 0xa5, 0x45, 0xf7, 0xe4, 0x8e, 0xfb, 0xb7, 0x0d, 0x5a, 0x98, 0x26, 0xa1, 0xdc, 0xb4, 0xa3, 0x0a, 0x6c, 0x8c, 0xc9, 0x24, 0x24, 0x20, 0xb4, 0x10, 0x10, 0x66, 0x8f, 0xed, 0xc2, 0x54, 0x95, 0x54, 0x71, 0xac, 0xb8, 0xd0, 0x52, 0x86, 0x2b, 0xd4, 0x66, 0x8f, 0x6e, 0xd9, 0x3e, 0xdc, 0xf6, 0x78, 0xbb, 0xd9, 0xb9, 0x70, 0xa1, 0xc2, 0x5d, 0xf1, 0x32, 0x0d, 0x43, 0xdc, 0x4f, 0x6b, 0x1f, 0xb4, 0xc8, 0xfb, 0xd2, 0x6a, 0xa3, 0x3a, 0x55, 0x99, 0xe4, 0x9e, 0x8b, 0xef, 0xe9, 0x4f, 0x6b, 0x93, 0xcb, 0xea, 0x99, 0xdd, 0x18, 0xe0, 0x89, 0x54, 0xbc, 0xd0, 0x70, 0xd5, 0x00, 0x0f, 0x25, 0xe3, 0x28, 0x75, 0x25, 0xb0, 0xf1, 0xba, 0xa5, 0xec, 0xea, 0x5c, 0xbc, 0x17, 0x7c, 0xee, 0x04, 0xe7, 0xbe, 0xe5, 0x8a, 0x00, 0x9a, 0xf9, 0x9b, 0x40, 0x73, 0x86, 0x3c, 0x6b, 0xaa, 0x46, 0x34, 0x49, 0x09, 0x05, 0x43, 0x07, 0x41, 0x53, 0x3d, 0x8c, 0xb4, 0x4e, 0x5d, 0xbb, 0x46, 0x25, 0x7e, 0x8c, 0x33, 0xaf, 0xa7, 0x8c, 0x37, 0x95, 0xf9, 0x0e, 0xde, 0x6a, 0x4b, 0xfd, 0x69, 0xe6, 0x8c, 0xdf, 0x05, 0x0c, 0xd2, 0x31, 0x38, 0x67, 0x57, 0xb1, 0x9f, 0x36, 0xae, 0x55, 0xea, 0xee, 0x6e, 0xc6, 0x46, 0x18, 0x6b, 0xf5, 0x96, 0x0b, 0xef, 0x5d, 0x25, 0x16, 0x04, 0x6c, 0x87, 0x8e, 0x30, 0x55, 0x18, 0xa6, 0xcc, 0xf5, 0xb8, 0x72, 0x7d, 0x29, 0xca, 0xf3, 0x87, 0xf4, 0x06, 0xac, 0x2e, 0x25, 0x99, 0x79, 0x5a, 0x82, 0xe6, 0x74, 0x52, 0x28, 0xc9, 0x4a, 0xa5, 0xa4, 0xb6, 0x31, 0xae, 0x40, 0x89, 0x2b, 0x89, 0xb1, 0x67, 0x5b, 0xff, 0xa8, 0x07, 0x1a, 0xce, 0x86, 0xc8, 0x8b, 0x6e, 0xb6, 0xe2, 0xb6, 0x95, 0x01, 0xe2, 0xa9, 0x99, 0xc5, 0xa1, 0x5b, 0xc1, 0x98, 0x53, 0x53, 0x31, 0x66, 0x94, 0xaf, 0xe3, 0xc2, 0x71, 0x00, 0x0f, 0xe4, 0x74, 0xf2, 0xca, 0x0d, 0x38, 0xaa, 0x42, 0xd0, 0xb7, 0x74, 0xd3, 0x66, 0xcb, 0x05, 0xe7, 0xc7, 0x8d, 0x61, 0x0f, 0x9c, 0x0c, 0x01, 0x00, 0x50, 0x0c, 0xfe, 0x9d, 0xe5, 0x01, 0x54, 0x92, 0x98, 0xf1, 0x15, 0xc9, 0xd8, 0x78, 0x41, 0x66, 0x94, 0x20, 0x5f, 0x92, 0xa6, 0xc9, 0x48, 0x7a, 0x5e, 0x05, 0x7f, 0xdd, 0x55, 0x70, 0x87, 0x07, 0xfa, 0xa2, 0xf8, 0x9c, 0x76, 0x73, 0x8d, 0xd8, 0xbc, 0x5a, 0x9d, 0x68, 0xb1, 0xa0, 0x72, 0x46, 0x03, 0x1e, 0x75, 0x61, 0x35, 0xf9, 0xfc, 0x2c, 0xe0, 0x8b, 0x8c, 0x71, 0x0a, 0xa1, 0x46, 0xb0, 0x1b, 0x16, 0x4e, 0xf4, 0x1a, 0xeb, 0xda, 0xb4, 0x37, 0x28, 0xdb, 0xd5, 0x76, 0x94, 0xb9, 0x2a, 0xe9, 0xda, 0xec, 0x6c, 0x6d, 0xfb, 0x96, 0xc2, 0x1d, 0x16, 0xb8, 0x79, 0xcc, 0x6d, 0xe0, 0xad, 0xef, 0x94, 0x7e, 0x08, 0x8a, 0x7a, 0x08, 0x03, 0x57, 0xfc, 0xd8, 0xab, 0xfb, 0x60, 0x3f, 0x15, 0xac, 0xc6, 0x27, 0xa7, 0xe9, 0x57, 0x89, 0x50, 0x29, 0x02, 0x45, 0xea, 0x8d, 0xc6, 0xcc, 0x58, 0xc5, 0xfa, 0x26, 0x2a, 0xaf, 0x58, 0xe8, 0x95, 0xea, 0x8a, 0xa2, 0xda, 0x93, 0x5d, 0x38, 0x04, 0xb9, 0xb0, 0x9c, 0x7c, 0x25, 0xc5, 0xa7, 0xfe, 0x77, 0x74, 0x92, 0x03, 0xba, 0xac, 0x4f, 0xd6, 0x8a, 0xa3, 0x8a, 0xa8, 0xdd, 0x42, 0x2c, 0x77, 0x3a, 0xf7, 0x41, 0xa6, 0x16, 0x38, 0xd5, 0x31, 0x87, 0x69, 0x2a, 0x12, 0x50, 0x39, 0x23, 0xf9, 0x08, 0xd5, 0xbd, 0x6d, 0x3e, 0x40, 0x3a, 0x9a, 0x49, 0x9a, 0x1c, 0xaa, 0xe4, 0x00, 0xe7, 0xa7, 0x62, 0xba, 0x70, 0xd8, 0x61, 0x0a, 0xaa, 0x2c, 0x79, 0x1a, 0x54, 0x42, 0x0c, 0x6a, 0x4d, 0x6b, 0x3a, 0x21, 0xfb, 0xca, 0xe3, 0x90, 0x61, 0x41, 0x5e, 0x7b, 0x95, 0x94, 0x3e, 0x49, 0xbc, 0x4e, 0x9c, 0x2b, 0x95, 0x13, 0x35, 0xb4, 0x84, 0x3a, 0x81, 0x70, 0x9e, 0x3a, 0x74, 0xa0, 0x45, 0xc9, 0xf0, 0x51, 0x0b, 0x75, 0xad, 0x63, 0xd8, 0x6e, 0x17, 0xe7, 0xc8, 0x36, 0x03, 0xbd, 0x05, 0xc4, 0x98, 0x69, 0xdb, 0x41, 0x71, 0xc2, 0x5b, 0x4a, 0x33, 0xa5, 0x94, 0xe5, 0x48, 0x60, 0x19, 0x2e, 0x96, 0x9e, 0x39, 0x25, 0xf0, 0x06, 0x30, 0xff, 0x03, 0x31, 0x6b, 0x54, 0xa8, 0x3a, 0x19, 0x1d, 0x98, 0x19, 0x4b, 0x2f, 0x0e, 0x04, 0x65, 0xc9, 0x9c, 0x25, 0xca, 0x0b, 0x48, 0xa0, 0xb7, 0xb9, 0xac, 0x35, 0x92, 0x59, 0x10, 0xbe, 0x2d, 0x0d, 0x13, 0x04, 0x33, 0x79, 0xec, 0x73, 0x22, 0xad, 0xa6, 0x2c, 0x38, 0xe4, 0xc4, 0xa3, 0x79, 0xa8, 0x4c, 0xd7, 0x21, 0x3b, 0x4e, 0xf7, 0x87, 0x4c, 0x1a, 0x43, 0xf5, 0x53, 0x0d, 0x0f, 0xb1, 0xa7, 0x31, 0xf6, 0x48, 0xe3, 0x85, 0x39, 0x3d, 0x74, 0x17, 0x54, 0x3d, 0x9b, 0x34, 0x0f, 0x1f, 0x3a, 0x09, 0x3f, 0xec, 0xb1, 0xec, 0x24, 0xa6, 0xf7, 0xeb, 0x6c, 0x27, 0x8d, 0x20, 0x77, 0xda, 0xf9, 0xd0, 0x67, 0xde, 0x65, 0xea, 0x1f, 0x8d, 0x5d, 0x4b, 0x5a, 0x69, 0x69, 0xb5, 0x72, 0x49, 0x1f, 0xe2, 0x58, 0xb2, 0xe4, 0x80, 0x59, 0x7c, 0xf4, 0xc8, 0xd1, 0x38, 0x15, 0xdc, 0x52, 0xd4, 0xe2, 0x2c, 0xb4, 0x20, 0xe7, 0xeb, 0x8f, 0xd8, 0xb0, 0x43, 0x46, 0x39, 0x98, 0x03, 0x63, 0x0e, 0x80, 0xd3, 0x34, 0x67, 0xfc, 0xf1, 0x67, 0xe7, 0xf8, 0x0f, 0xcf, 0x88, 0xc3, 0xec, 0xef, 0x01, 0xde, 0x52, 0xc1, 0x29, 0xce, 0x71, 0x90, 0xb0, 0xd3, 0x3a, 0x5a, 0xa4, 0x6e, 0x78, 0x97, 0x6b, 0xe0, 0x38, 0xb1, 0x7d, 0xb1, 0x90, 0x1a, 0xd1, 0x2c, 0x33, 0x3e, 0x0f, 0x62, 0x49, 0xf4, 0x0b, 0xb7, 0xbc, 0xc2, 0xd2, 0x85, 0xd3, 0x25, 0xe8, 0x4c, 0x9e, 0x48, 0x7a, 0x11, 0x45, 0xa3, 0xe9, 0x77, 0xe7, 0x60, 0x73, 0xa6, 0xcd, 0xc5, 0xb5, 0x6a, 0x70, 0x2b, 0x8c, 0x16, 0x7f, 0xbf, 0xe6, 0x24, 0xbd, 0x77, 0xcb, 0x5e, 0xe7, 0xbc, 0xf0, 0x07, 0x6b, 0x1e, 0xca, 0x50, 0xe5, 0xab, 0xb5, 0xcf, 0x6b, 0x3f, 0xaf, 0x79, 0x5c, 0xec, 0x72, 0xed, 0x4a, 0x67, 0x79, 0x37, 0x58, 0xeb, 0x72, 0xb8, 0xd8, 0xb1, 0x99, 0x0b, 0x79, 0x71, 0x4f, 0x17, 0x76, 0x4f, 0x99, 0x9e, 0x3d, 0xe2, 0xfd, 0xa2, 0x0e, 0xe7, 0x2e, 0xea, 0xe8, 0xf2, 0x3a, 0xae, 0x58, 0xb5, 0xf5, 0x57, 0x3a, 0xc9, 0x7a, 0x9d, 0x2e, 0xe4, 0x7b, 0x56, 0x11, 0x7e, 0xda, 0xec, 0x82, 0x2b, 0xc9, 0xb5, 0xf9, 0x08, 0x48, 0x1b, 0x86, 0x6a, 0x1f, 0xc3, 0xd6, 0x44, 0x0e, 0x6d, 0x5e, 0xf9, 0x00, 0xae, 0x9c, 0xc5, 0xd0, 0x6e, 0xd6, 0x35, 0xed, 0x06, 0xd8, 0xcb, 0x69, 0x6e, 0x24, 0xe0, 0x9d, 0xa7, 0x66, 0x43, 0xc5, 0xd6, 0x30, 0x53, 0x5b, 0x03, 0x57, 0x7d, 0x29, 0xe7, 0x8e, 0xc6, 0x81, 0x48, 0x6b, 0xc7, 0x36, 0xf3, 0xc9, 0xcb, 0xb5, 0x6c, 0x1a, 0xf0, 0x1a, 0x87, 0xc3, 0xf5, 0x20, 0x11, 0x2f, 0x3a, 0xf8, 0x86, 0xfe, 0x8c, 0x00, 0x30, 0xdd, 0x56, 0x7e, 0x29, 0x3f, 0x71, 0x74, 0x2d, 0x75, 0x3b, 0x65, 0x90, 0x1d, 0xde, 0xcf, 0x6c, 0x6c, 0x3c, 0x1c, 0x36, 0x3b, 0xfa, 0x2f, 0x1d, 0xed, 0x3c, 0x87, 0xc1, 0x37, 0xa3, 0x39, 0x9c, 0x18, 0x68, 0xd7, 0x2a, 0xc0, 0xa5, 0xf6, 0x63, 0xea, 0x37, 0x25, 0x27, 0xb6, 0xe3, 0x70, 0x6a, 0xd9, 0xae, 0x95, 0xb3, 0xe1, 0x76, 0x72, 0x60, 0x1f, 0xd2, 0xfb, 0x3e, 0x65, 0x83, 0x4a, 0x91, 0xe9, 0x1a, 0xf1, 0xc8, 0x00, 0xbb, 0xad, 0xf2, 0x0d, 0xae, 0x1f, 0xdc, 0x57, 0x33, 0xc3, 0x77, 0x5b, 0x2e, 0x5c, 0x9a, 0xcd, 0xc8, 0x4a, 0x6d, 0x4e, 0xa6, 0x72, 0x94, 0xaf, 0x3b, 0xc7, 0x51, 0x94, 0x95, 0x33, 0x1c, 0x8f, 0xc0, 0xfb, 0x3f, 0xc0, 0x41, 0xac, 0x35, 0xce, 0x6f, 0x3e, 0xb5, 0xeb, 0x02, 0x4d, 0xd7, 0x8e, 0xe9, 0xfd, 0xba, 0x63, 0x7a, 0x2c, 0xce, 0x56, 0x3f, 0xf2, 0xf6, 0xfb, 0x5f, 0xa9, 0xd0, 0xad, 0xd1, 0xe6, 0x0e, 0x3a, 0x1e, 0xc7, 0x0a, 0xdd, 0x44, 0x9b, 0x3b, 0x39, 0x5d, 0x73, 0x72, 0x85, 0x04, 0xe1, 0x21, 0xaf, 0x5b, 0xf8, 0x70, 0x07, 0xf7, 0x4e, 0x2a, 0x08, 0x1f, 0x9e, 0xce, 0x6d, 0x0b, 0x51, 0xf4, 0x6c, 0xf7, 0x4a, 0x11, 0x4e, 0x4b, 0xbf, 0x74, 0x11, 0x6e, 0x96, 0x20, 0xf8, 0x3f, 0x33, 0x49, 0x98, 0xdb, 0xc2, 0xe9, 0x3d, 0xe6, 0xcd, 0xb0, 0x94, 0xe9, 0x77, 0x27, 0xf2, 0xf6, 0x2f, 0x2f, 0x4b, 0x9f, 0xa5, 0xe3, 0xb3, 0x74, 0x7c, 0x96, 0x8e, 0x4f, 0x50, 0x3a, 0xde, 0x95, 0xfb, 0x07, 0xeb, 0x4b, 0x75, 0xd9, 0xc8, 0xdb, 0xd6, 0x8c, 0xab, 0x75, 0xee, 0xe2, 0x99, 0xb1, 0x77, 0xdd, 0xbc, 0xd6, 0xb6, 0x06, 0xc3, 0xa0, 0x55, 0x70, 0x04, 0x7d, 0x2f, 0x7a, 0x5b, 0xfc, 0x47, 0xca, 0x9c, 0x81, 0x8d, 0x2a, 0x66, 0xce, 0xac, 0xc8, 0x06, 0xf5, 0xb3, 0x98, 0x5e, 0x5a, 0x45, 0x59, 0xd6, 0x2a, 0x76, 0x30, 0x90, 0x0a, 0xa4, 0x07, 0x7b, 0x8a, 0x20, 0x8b, 0x10, 0x2b, 0x0a, 0x1f, 0x9b, 0x20, 0x4e, 0xad, 0x64, 0xdd, 0xe0, 0x9e, 0x5a, 0xdb, 0x0b, 0x46, 0xbb, 0x6c, 0x59, 0xed, 0x53, 0xfb, 0xbf, 0xa4, 0x01, 0x82, 0x48, 0xc9, 0x35, 0x83, 0xab, 0x3d, 0xc6, 0x75, 0x3d, 0xde, 0xab, 0x95, 0x78, 0x99, 0x65, 0x09, 0xd5, 0x3e, 0x3c, 0xd3, 0x74, 0x93, 0x60, 0x33, 0x47, 0xd3, 0x59, 0x60, 0xac, 0x40, 0xfa, 0xf5, 0x39, 0x14, 0x13, 0x98, 0x92, 0x51, 0xca, 0x42, 0x0b, 0xbc, 0x74, 0xa9, 0x12, 0x48, 0x39, 0x5e, 0x27, 0x75, 0x40, 0x28, 0x77, 0x75, 0xef, 0x89, 0x7b, 0x92, 0x92, 0x41, 0xf7, 0x70, 0x16, 0x1d, 0x70, 0x89, 0x31, 0xc7, 0xcb, 0xf8, 0x0a, 0x78, 0x1b, 0xb1, 0x43, 0xae, 0x97, 0x6d, 0xb9, 0x70, 0xc0, 0x78, 0xbc, 0xa8, 0x8b, 0x4c, 0xc6, 0x2f, 0x14, 0x9e, 0x95, 0x66, 0x72, 0x5b, 0x6d, 0xb9, 0x1f, 0x51, 0xd6, 0xe0, 0x51, 0x28, 0x4c, 0xa1, 0xa3, 0x09, 0xa0, 0x1c, 0x4d, 0xd6, 0x4b, 0x91, 0xe6, 0xd5, 0x60, 0xe5, 0x97, 0xff, 0x44, 0xc6, 0xc7, 0xc4, 0xca, 0x27, 0xf2, 0x39, 0x44, 0xe5, 0xe7, 0x11, 0xce, 0xad, 0x6a, 0x11, 0x54, 0xa0, 0x24, 0x33, 0x58, 0xf0, 0x6b, 0x3b, 0x43, 0x38, 0x57, 0xc2, 0x7a, 0xcc, 0x70, 0xc6, 0x1e, 0x1d, 0xcc, 0x15, 0xa7, 0xc2, 0x9f, 0x05, 0x0f, 0x73, 0x6e, 0x89, 0xa5, 0x09, 0xf4, 0xb7, 0xbc, 0x47, 0x4f, 0xab, 0x92, 0x1c, 0x99, 0xc4, 0xe2, 0x06, 0x69, 0x28, 0xec, 0x54, 0xb2, 0x42, 0x14, 0xf9, 0xad, 0xd1, 0x37, 0x49, 0xd7, 0x83, 0xfe, 0xb6, 0x84, 0x60, 0x0d, 0x7a, 0xc5, 0x24, 0x2e, 0x71, 0xc4, 0x56, 0x80, 0xf5, 0xb6, 0x1d, 0xb5, 0x6c, 0xc9, 0xf1, 0xcf, 0xc6, 0x7f, 0x26, 0xe1, 0x84, 0x74, 0x0c, 0x6b, 0xec, 0x18, 0x8a, 0x93, 0x94, 0xcb, 0xcc, 0x5c, 0x5d, 0xf5, 0x5f, 0x36, 0x68, 0x21, 0x5f, 0x41, 0x49, 0x06, 0x51, 0x4f, 0x52, 0x4b, 0x5b, 0xbc, 0xe4, 0xbc, 0x1b, 0x47, 0x7c, 0x65, 0xa0, 0xb9, 0x0b, 0xa6, 0xa4, 0x88, 0x71, 0x3b, 0xf7, 0xf5, 0xaf, 0xaa, 0x2a, 0x4f, 0xcc, 0x7b, 0xf4, 0xfa, 0xdb, 0xca, 0xe3, 0x92, 0xed, 0xd3, 0xcb, 0x5d, 0x70, 0xee, 0x8b, 0x59, 0x27, 0x4f, 0x2b, 0x10, 0xf9, 0x5b, 0xb3, 0x22, 0xe3, 0x80, 0x38, 0xda, 0xe4, 0xcc, 0xcd, 0x52, 0x4e, 0x66, 0x2d, 0xb5, 0x63, 0xba, 0x2b, 0xb3, 0x9b, 0xa2, 0x73, 0x15, 0x26, 0xdd, 0x64, 0x8b, 0x9e, 0xc2, 0x7f, 0xb9, 0x7f, 0xa5, 0x8f, 0xc5, 0xfa, 0x66, 0xd3, 0x48, 0xd9, 0xfe, 0x5a, 0xb0, 0x26, 0xf3, 0xa5, 0x5c, 0x33, 0x92, 0x2e, 0x45, 0xaa, 0xc7, 0x7a, 0xfd, 0x95, 0x1a, 0x74, 0x80, 0xa6, 0x38, 0x9f, 0x9a, 0x6d, 0x6d, 0x65, 0xbb, 0xa2, 0xe8, 0xdb, 0x43, 0xed, 0xe3, 0x47, 0xd7, 0x06, 0x96, 0xd1, 0xce, 0x6a, 0xac, 0x9b, 0x73, 0x66, 0xb2, 0x0d, 0xed, 0x4d, 0x78, 0x71, 0xa3, 0x7d, 0xee, 0x51, 0xed, 0x10, 0x6d, 0x70, 0x95, 0x99, 0xf9, 0x82, 0xb8, 0x12, 0x5c, 0xad, 0x55, 0x55, 0x41, 0xb1, 0x4f, 0x34, 0x3b, 0xfc, 0xf7, 0xd6, 0x8e, 0x6f, 0x1a, 0x61, 0xd3, 0x9e, 0x66, 0xb5, 0x0f, 0x28, 0xa3, 0x0e, 0x1d, 0x2d, 0x48, 0x9c, 0x0a, 0x2e, 0x13, 0x45, 0x55, 0xc2, 0x31, 0x9f, 0xee, 0x16, 0x43, 0xe7, 0x92, 0x0e, 0xee, 0x82, 0xc4, 0x6f, 0x68, 0x0f, 0xf5, 0xb2, 0x6d, 0x48, 0x39, 0x4f, 0xae, 0xa4, 0xd4, 0x4f, 0x18, 0x16, 0x70, 0x6a, 0x10, 0x42, 0x3c, 0x43, 0xf4, 0x07, 0xfb, 0xf3, 0x77, 0x00, 0x05, 0x85, 0xe5, 0xda, 0xe0, 0xf5, 0x0d, 0x7a, 0x22, 0xdf, 0x2c, 0x97, 0x67, 0x8d, 0x4f, 0x0f, 0xc3, 0xd3, 0xe2, 0x6f, 0xa7, 0x12, 0x88, 0x4e, 0xa0, 0xba, 0x5a, 0x96, 0xe9, 0xe5, 0x0c, 0xee, 0x91, 0x40, 0x41, 0xcc, 0x0e, 0xc5, 0x85, 0x0f, 0xa9, 0xbc, 0x09, 0x93, 0xb9, 0xf3, 0xa9, 0x0c, 0x84, 0xa7, 0xe8, 0xee, 0x04, 0xd2, 0xaf, 0x03, 0x11, 0xac, 0xb6, 0x36, 0x5a, 0x34, 0xd5, 0x02, 0x89, 0x30, 0x16, 0x45, 0xea, 0x15, 0x57, 0x98, 0xc5, 0xc8, 0x7a, 0x26, 0x58, 0x96, 0x0c, 0xa0, 0xe0, 0x2f, 0xdb, 0xbd, 0xdb, 0xcf, 0x59, 0x0c, 0x71, 0xe3, 0x04, 0xb2, 0x5a, 0xb5, 0x66, 0xe7, 0x2a, 0x2a, 0xed, 0x43, 0x12, 0xb3, 0xc3, 0xd2, 0x39, 0xab, 0x36, 0xe2, 0x2a, 0x46, 0x75, 0x6d, 0xb0, 0xae, 0x69, 0xe5, 0xe0, 0x6b, 0xfb, 0x4f, 0xe3, 0xc1, 0xb4, 0xf2, 0x6c, 0xd2, 0x3b, 0xb4, 0x4d, 0xe9, 0x6a, 0x29, 0x3d, 0x73, 0xa6, 0x0c, 0x49, 0xa8, 0x9c, 0x1b, 0xbf, 0xa0, 0x12, 0x8c, 0xaf, 0xfe, 0xf1, 0x79, 0x59, 0xd9, 0x64, 0xa7, 0x45, 0x67, 0x81, 0x7c, 0x4d, 0xfa, 0xcc, 0xca, 0x26, 0x88, 0xe2, 0x0c, 0xfe, 0x56, 0x12, 0x22, 0x32, 0x40, 0x83, 0x28, 0x89, 0x8e, 0x4d, 0xc4, 0xce, 0x69, 0x2e, 0xda, 0xa0, 0x3a, 0x95, 0x8c, 0x29, 0xe6, 0x5c, 0xb4, 0xae, 0x8b, 0x50, 0xfb, 0xc8, 0x64, 0xd9, 0x40, 0xe6, 0x35, 0xd1, 0xbb, 0xa5, 0x9e, 0x6d, 0x58, 0x66, 0x67, 0x9b, 0x97, 0xf8, 0x7b, 0x66, 0x67, 0x7b, 0x66, 0x67, 0x6b, 0xb3, 0xb3, 0xfd, 0xe3, 0x99, 0x9d, 0xed, 0x4e, 0xe5, 0x50, 0xb3, 0x7c, 0x83, 0x62, 0xc8, 0x19, 0x14, 0x95, 0x5b, 0x2d, 0x7d, 0xe6, 0x94, 0x4d, 0x6a, 0x81, 0x93, 0x4d, 0xd5, 0x99, 0x3f, 0xe1, 0x70, 0xf0, 0xed, 0xc8, 0x4c, 0x4e, 0x77, 0x9b, 0xb4, 0x62, 0xaf, 0x5a, 0x6d, 0x3d, 0x85, 0xec, 0x4b, 0x9a, 0x3b, 0xd1, 0xda, 0x3c, 0x39, 0xb1, 0x4a, 0x0d, 0x95, 0xfa, 0x2a, 0x28, 0xe6, 0xfa, 0x50, 0xb2, 0x4a, 0x43, 0xd5, 0x9e, 0xdc, 0x95, 0x14, 0x54, 0xf0, 0x06, 0x77, 0xda, 0x5e, 0x89, 0xbb, 0x9f, 0xd9, 0xb4, 0x18, 0x28, 0x7d, 0x24, 0x9a, 0x35, 0x92, 0xcc, 0x8a, 0xa5, 0x62, 0x5c, 0xde, 0x97, 0x25, 0x71, 0xf5, 0x86, 0x68, 0x91, 0xaa, 0xa3, 0x6f, 0x8a, 0x73, 0x36, 0x05, 0x6a, 0xd7, 0xff, 0x92, 0x00, 0x81, 0x5b, 0xe9, 0xf0, 0x1e, 0x00, 0xd8, 0x67, 0x37, 0x97, 0x53, 0xc6, 0xe9, 0xa9, 0x83, 0x28, 0x73, 0x5c, 0x21, 0xa4, 0x38, 0x9b, 0x2f, 0x67, 0x82, 0x49, 0xfd, 0x3b, 0x41, 0x45, 0x0d, 0xe9, 0x78, 0x56, 0x54, 0xcd, 0x84, 0x21, 0xa5, 0xdb, 0xe6, 0x43, 0x75, 0xa2, 0x56, 0xba, 0xe8, 0xee, 0x39, 0x62, 0xe8, 0x14, 0xc4, 0x82, 0xb1, 0x1d, 0x93, 0xc3, 0x5d, 0x41, 0x16, 0x83, 0x84, 0x3a, 0x4d, 0xf7, 0x7a, 0x35, 0xea, 0x3a, 0xe3, 0xce, 0x11, 0xb9, 0x5e, 0xd1, 0x12, 0x65, 0xdc, 0x89, 0xbb, 0x82, 0xe3, 0xa8, 0xf9, 0x64, 0xa2, 0x6c, 0x1f, 0x70, 0x7f, 0x6e, 0x76, 0x46, 0x89, 0xeb, 0x54, 0xf4, 0xc5, 0xca, 0x67, 0x84, 0xbf, 0x97, 0x60, 0xb0, 0xad, 0xa8, 0x6f, 0xd4, 0xce, 0xa5, 0x8b, 0xe0, 0x16, 0x69, 0xc1, 0x1e, 0xd6, 0xf5, 0xe0, 0x1e, 0x8b, 0x84, 0x89, 0x45, 0x3b, 0xe9, 0x2b, 0x08, 0x56, 0x5f, 0x9c, 0x6f, 0xa5, 0x94, 0x55, 0xe7, 0x82, 0xfd, 0x42, 0x2e, 0x03, 0xa0, 0x17, 0x10, 0xac, 0xed, 0x31, 0x15, 0xa5, 0xd2, 0xf1, 0x00, 0xcc, 0x0f, 0xcb, 0xe0, 0xdb, 0xef, 0x5a, 0x88, 0x08, 0x2c, 0xb3, 0x4e, 0x19, 0x37, 0xf2, 0x53, 0x0e, 0x50, 0x21, 0x80, 0xc7, 0x71, 0xce, 0x80, 0x04, 0xb5, 0x8f, 0x14, 0x66, 0x46, 0xea, 0x27, 0xa9, 0xf3, 0x09, 0x63, 0x98, 0x69, 0x9f, 0x91, 0x0a, 0x6d, 0x10, 0x12, 0xc5, 0x58, 0x00, 0x28, 0xba, 0x94, 0x0b, 0xa0, 0x92, 0x57, 0x14, 0xae, 0x37, 0x31, 0x27, 0x28, 0x78, 0x4e, 0x62, 0xc7, 0x22, 0xb0, 0xdc, 0xc6, 0x00, 0x66, 0x7f, 0x70, 0x49, 0xc1, 0xa7, 0x93, 0x3a, 0x2e, 0xf2, 0x75, 0x7a, 0x90, 0xf6, 0x63, 0xe1, 0x6f, 0x9d, 0xc9, 0x5e, 0x57, 0xd0, 0x6b, 0x98, 0x1d, 0x96, 0x2b, 0x1a, 0xe5, 0xff, 0xec, 0xa4, 0xde, 0x49, 0xb3, 0x93, 0x36, 0xbd, 0x41, 0x3d, 0x55, 0x37, 0xf8, 0x6e, 0x35, 0x39, 0xf7, 0xb9, 0x54, 0x07, 0x7c, 0x54, 0xfc, 0x12, 0x32, 0x3e, 0x2f, 0xcd, 0x3f, 0x7d, 0xcd, 0xb4, 0xf1, 0x7c, 0x99, 0xc2, 0xa9, 0x66, 0xe7, 0x7e, 0xff, 0xc8, 0xf6, 0x8c, 0xd9, 0xa7, 0xa8, 0x00, 0x25, 0x6c, 0x60, 0x0c, 0xeb, 0xc5, 0x16, 0xb3, 0x73, 0xd2, 0x39, 0x00, 0x79, 0x1d, 0xb9, 0x2d, 0x55, 0x4f, 0x57, 0x80, 0xfb, 0x21, 0xf6, 0x79, 0xda, 0x73, 0xe4, 0x93, 0xc4, 0x07, 0xa9, 0xa1, 0x82, 0x46, 0xee, 0xe4, 0x5f, 0x02, 0x5a, 0x43, 0x75, 0x5a, 0xc4, 0xaf, 0x6f, 0x79, 0x32, 0x92, 0x82, 0x92, 0xfd, 0x0d, 0xc5, 0x32, 0xcb, 0x6d, 0x11, 0xe4, 0x61, 0x10, 0x18, 0xe5, 0x9f, 0x45, 0x2e, 0xb0, 0xa5, 0x38, 0x6c, 0xca, 0x85, 0x06, 0xca, 0xc4, 0xe8, 0x1a, 0x92, 0xba, 0xa5, 0x4a, 0x28, 0x7e, 0x27, 0xfb, 0x1b, 0x2f, 0xd0, 0x18, 0x83, 0x45, 0xc9, 0x2b, 0x00, 0x96, 0x9a, 0x00, 0x3b, 0xf1, 0xb2, 0x76, 0xa6, 0x92, 0x35, 0x53, 0x6c, 0xb8, 0x5b, 0x8a, 0x22, 0x23, 0x02, 0x8f, 0x04, 0x38, 0xac, 0x30, 0x0c, 0xaf, 0x40, 0x26, 0x59, 0x2d, 0x45, 0xc7, 0xf6, 0x7b, 0x66, 0x38, 0x8d, 0x1a, 0xe3, 0x44, 0x8e, 0xb9, 0xc2, 0xdd, 0x2d, 0x85, 0x5d, 0x43, 0x14, 0xf3, 0xbe, 0x46, 0x37, 0x32, 0x35, 0xb6, 0xfc, 0xc1, 0x17, 0x18, 0x11, 0x94, 0x5d, 0xbe, 0xa1, 0x74, 0x93, 0xf2, 0x4d, 0x89, 0x00, 0x34, 0x0f, 0xb4, 0x93, 0x84, 0x07, 0xf8, 0xa0, 0x34, 0x06, 0xa1, 0x7b, 0x8a, 0x63, 0x2a, 0x75, 0x66, 0xa0, 0x5e, 0x9a, 0xe0, 0x55, 0x52, 0x7d, 0x53, 0xb2, 0x96, 0x81, 0x5a, 0x7b, 0x4b, 0xb3, 0x53, 0x50, 0xd0, 0x2b, 0x59, 0x38, 0x02, 0x27, 0xaa, 0xc7, 0xc5, 0x38, 0x21, 0x10, 0x77, 0x3b, 0x13, 0xcf, 0xe5, 0x4c, 0x93, 0xc3, 0x33, 0x6b, 0x06, 0xb4, 0xc3, 0x12, 0xae, 0x73, 0x6a, 0x33, 0x69, 0x87, 0xe7, 0xd2, 0x44, 0xf1, 0x95, 0x16, 0x35, 0x91, 0x5a, 0xb3, 0x61, 0xab, 0x29, 0xe4, 0xc5, 0xce, 0xaf, 0x1f, 0x1d, 0xa7, 0xfc, 0x6a, 0x06, 0x20, 0x15, 0xac, 0xe9, 0x6e, 0x44, 0x07, 0x09, 0xed, 0x27, 0xf8, 0xd7, 0xe6, 0xad, 0x55, 0x06, 0x8d, 0x32, 0x66, 0x14, 0x5c, 0xb1, 0x0a, 0x48, 0xcd, 0x40, 0x89, 0x04, 0xb7, 0xac, 0x41, 0x06, 0x41, 0x4a, 0xa1, 0x42, 0xa9, 0x0e, 0xc8, 0x4d, 0xf0, 0x9b, 0x20, 0x80, 0x13, 0x7d, 0x6f, 0x28, 0x37, 0x24, 0xc9, 0x01, 0x47, 0x52, 0x04, 0xb1, 0x36, 0xe3, 0xbe, 0x19, 0x49, 0x85, 0xa0, 0xb6, 0x80, 0xe5, 0xbe, 0xee, 0x62, 0x94, 0xea, 0xed, 0x96, 0x0a, 0x5b, 0xb3, 0xdb, 0x3d, 0x50, 0xdd, 0x2b, 0x1e, 0xc7, 0x81, 0xa0, 0x64, 0xec, 0x2e, 0x24, 0x80, 0x43, 0xb9, 0x71, 0x74, 0xfd, 0x50, 0xe1, 0x71, 0xaa, 0x01, 0xec, 0x70, 0xb6, 0xb8, 0x33, 0xa7, 0x20, 0x66, 0x00, 0x69, 0xf7, 0x1d, 0x6a, 0xfe, 0x19, 0x9b, 0x02, 0x3b, 0x23, 0xe5, 0x9e, 0xc1, 0x33, 0x05, 0x6d, 0x9f, 0x0f, 0x3d, 0x45, 0xd8, 0xe1, 0xac, 0xa0, 0x07, 0x8e, 0x2f, 0x25, 0x25, 0xcf, 0x58, 0x46, 0xd2, 0x2a, 0xdc, 0xf4, 0x48, 0xfc, 0xc4, 0x1c, 0x0b, 0x48, 0xf1, 0x82, 0x9c, 0x8e, 0xdc, 0x5a, 0x73, 0x1b, 0x9d, 0x3e, 0xe7, 0xa3, 0x81, 0x1e, 0xae, 0xe4, 0xc2, 0x6b, 0xb9, 0x35, 0x14, 0x2b, 0xe1, 0x76, 0x8e, 0x88, 0x22, 0x3d, 0x36, 0x0b, 0x38, 0x36, 0x9c, 0xf4, 0xb9, 0x7e, 0x09, 0xf7, 0x8a, 0x91, 0xed, 0x90, 0x67, 0x0e, 0x37, 0x87, 0xcc, 0x92, 0x9e, 0x48, 0x1e, 0xf2, 0xdc, 0x69, 0xea, 0xfb, 0x32, 0x8f, 0x8c, 0xe6, 0x2d, 0x31, 0xb4, 0x32, 0x77, 0x43, 0xf4, 0x10, 0x5c, 0xc5, 0x0c, 0x34, 0x22, 0x3c, 0x55, 0x14, 0x62, 0x85, 0x71, 0x1e, 0x7d, 0xff, 0x42, 0x52, 0x41, 0x43, 0x0f, 0xbf, 0x78, 0x9a, 0xa1, 0xeb, 0xa1, 0xcd, 0xca, 0x10, 0x76, 0x5a, 0x62, 0xfd, 0xb8, 0xe1, 0xf3, 0xa1, 0x17, 0xe7, 0x32, 0x40, 0x1a, 0x5a, 0x41, 0x63, 0xa4, 0x24, 0xa4, 0x51, 0xb6, 0xad, 0x77, 0x38, 0x5b, 0x41, 0x7a, 0xb8, 0x84, 0x24, 0x2b, 0x59, 0x63, 0x50, 0xd8, 0xa4, 0x45, 0x41, 0xf9, 0xe2, 0x99, 0x50, 0xab, 0x4b, 0xd6, 0xdc, 0x92, 0x39, 0x12, 0x3c, 0x1c, 0x65, 0x00, 0x20, 0xd3, 0x1e, 0x88, 0x7c, 0xe1, 0x2c, 0x60, 0x04, 0x59, 0xff, 0x05, 0xdc, 0x7d, 0x6c, 0x49, 0x97, 0x3e, 0xd5, 0x61, 0xba, 0x03, 0x64, 0xa8, 0x70, 0x3c, 0xca, 0xb0, 0x24, 0xc8, 0x82, 0x85, 0xc1, 0x83, 0x15, 0xfc, 0x9f, 0xca, 0x1d, 0x51, 0x07, 0xaa, 0x21, 0xd3, 0xc2, 0xa1, 0x2e, 0x07, 0x43, 0x79, 0x00, 0x53, 0x79, 0x1b, 0xd0, 0x44, 0xae, 0xdd, 0x9e, 0xcf, 0xcf, 0xba, 0x0d, 0xd0, 0xf6, 0xd5, 0x19, 0xea, 0x50, 0x8d, 0x39, 0xa4, 0xef, 0x6b, 0x82, 0x1d, 0x96, 0x22, 0xe6, 0x0d, 0x8c, 0xa4, 0x6f, 0x98, 0xbf, 0xa4, 0x72, 0x65, 0xb5, 0x17, 0xf6, 0x7c, 0x8d, 0x7b, 0xa9, 0x60, 0x05, 0xe9, 0xca, 0x4a, 0x17, 0x07, 0x8a, 0x60, 0x4d, 0x3a, 0xd8, 0x55, 0x26, 0x72, 0x83, 0x35, 0x8e, 0x81, 0xab, 0xd1, 0x0f, 0x41, 0x96, 0x33, 0xc5, 0x5f, 0xc2, 0x66, 0x37, 0x65, 0x6d, 0x77, 0x39, 0x3d, 0x58, 0xb6, 0x0e, 0x7d, 0xf2, 0xab, 0x8f, 0x0f, 0xfd, 0xb6, 0x36, 0x7d, 0xa7, 0xb6, 0x94, 0x0c, 0x19, 0x57, 0x83, 0x0b, 0x79, 0xc8, 0x9a, 0x5b, 0x55, 0x4f, 0x6c, 0xc3, 0xb1, 0xbd, 0x76, 0x92, 0x9b, 0x5c, 0xa8, 0x95, 0x3d, 0x29, 0xd6, 0xa2, 0xd6, 0x18, 0x23, 0xea, 0x5e, 0x5a, 0x67, 0xae, 0x02, 0xd4, 0xe5, 0x61, 0x1c, 0x48, 0x33, 0xea, 0xa4, 0xd4, 0x0c, 0x5c, 0x64, 0x49, 0x2a, 0x75, 0xa7, 0x52, 0x53, 0x1d, 0xe3, 0xb6, 0xd7, 0x3e, 0xb1, 0x0d, 0xe4, 0x48, 0x68, 0xf0, 0x98, 0x98, 0x23, 0x97, 0xa9, 0xd6, 0x1a, 0x51, 0x40, 0x83, 0x4b, 0x6b, 0x77, 0xe6, 0x7d, 0x5f, 0x1e, 0x62, 0xa4, 0x26, 0xc1, 0x0d, 0xa1, 0xb3, 0xe9, 0xdb, 0x1f, 0x1b, 0x56, 0x1e, 0x15, 0xb8, 0x69, 0x3a, 0xbc, 0xa6, 0xef, 0x60, 0xe6, 0x76, 0xa5, 0x54, 0x14, 0x12, 0xdf, 0xc6, 0xb6, 0xa3, 0x0a, 0x2a, 0x09, 0x5d, 0x21, 0x84, 0x9e, 0xba, 0x2b, 0x7d, 0xdb, 0xd3, 0x16, 0xb4, 0x14, 0x42, 0x6e, 0x2e, 0x53, 0xf4, 0xfe, 0x6a, 0x6d, 0xe0, 0x0d, 0xee, 0x94, 0xd5, 0x0f, 0xc3, 0x98, 0xff, 0x58, 0x1c, 0xb2, 0x0f, 0x33, 0x22, 0x3c, 0xdd, 0x16, 0x41, 0x67, 0x13, 0xfa, 0x7a, 0x6a, 0x67, 0x64, 0xe8, 0xf9, 0x2d, 0x92, 0x62, 0x48, 0xe5, 0x28, 0x44, 0x08, 0x09, 0x58, 0x4b, 0x31, 0x42, 0x5d, 0xe7, 0xcc, 0xbf, 0xdb, 0xde, 0xc2, 0x82, 0x27, 0xb5, 0x51, 0xe9, 0xad, 0xe9, 0xa7, 0xfa, 0x42, 0x38, 0xf3, 0xd3, 0x0b, 0xde, 0x99, 0x55, 0x04, 0xb7, 0xf2, 0xaa, 0xad, 0xf3, 0x78, 0x82, 0x19, 0x0f, 0xb7, 0x77, 0x9a, 0x2c, 0x5c, 0xb6, 0xe0, 0x0a, 0xbc, 0xf3, 0xa0, 0x95, 0xae, 0x8d, 0x61, 0x54, 0x6b, 0x50, 0xa6, 0x3e, 0x6e, 0xb8, 0x7e, 0x38, 0x94, 0x2e, 0xcc, 0xd6, 0x10, 0xe5, 0x4a, 0xb0, 0x6f, 0x27, 0x59, 0x3b, 0x82, 0xc2, 0xd0, 0x5e, 0x50, 0x96, 0x47, 0xc3, 0x01, 0x08, 0xbd, 0x19, 0x35, 0x43, 0xc9, 0xd0, 0xf0, 0xed, 0x91, 0xe1, 0x6c, 0x06, 0xef, 0x27, 0xa4, 0x90, 0x5a, 0xcc, 0xab, 0xd4, 0x92, 0x12, 0x30, 0x9d, 0xa4, 0x44, 0xcb, 0x85, 0xf1, 0x94, 0xb2, 0xeb, 0xc6, 0xfb, 0x92, 0xeb, 0x34, 0x2e, 0x15, 0x69, 0xbc, 0xa8, 0x3e, 0xe3, 0x19, 0x7b, 0xfc, 0xfd, 0xba, 0xd2, 0x8c, 0xd3, 0xd6, 0x97, 0xee, 0x19, 0x78, 0xa7, 0x5f, 0x0e, 0x10, 0xe8, 0xdb, 0x56, 0xea, 0xe3, 0x60, 0x9b, 0x5e, 0xbb, 0x45, 0xa9, 0xc4, 0x99, 0x39, 0xc6, 0xc1, 0x9b, 0xee, 0x54, 0xcc, 0x9b, 0x47, 0x30, 0x04, 0x17, 0x6c, 0x79, 0xc3, 0x30, 0x9a, 0xbd, 0x22, 0x26, 0x53, 0x45, 0xf5, 0xd2, 0xc9, 0xf9, 0xd2, 0x13, 0x19, 0x41, 0x1a, 0x14, 0x7e, 0xcf, 0x14, 0xef, 0x48, 0x6c, 0x44, 0x97, 0xa8, 0xcc, 0x15, 0x8c, 0xd5, 0xc8, 0x4b, 0x3c, 0x40, 0xa2, 0xdb, 0x7c, 0x5b, 0x20, 0x42, 0x9a, 0xad, 0xf9, 0xec, 0x5b, 0x2f, 0x11, 0x0c, 0x04, 0xda, 0x66, 0xba, 0x28, 0xb9, 0x2f, 0x1e, 0x97, 0x9c, 0x82, 0xbc, 0xcf, 0xb9, 0xd6, 0xe0, 0x3c, 0x21, 0xc0, 0x12, 0x88, 0x16, 0xf0, 0xd5, 0x70, 0x61, 0x01, 0xcc, 0x67, 0xf6, 0x84, 0x0f, 0x92, 0x36, 0xe4, 0xf1, 0x31, 0xb3, 0xdc, 0x73, 0xee, 0x27, 0x66, 0xa5, 0x65, 0xc2, 0x1d, 0x42, 0x33, 0x52, 0xcb, 0xe2, 0x5a, 0x02, 0xc7, 0x34, 0xfa, 0x27, 0x04, 0x31, 0xbb, 0xe2, 0x2c, 0x6c, 0x86, 0x14, 0xa9, 0x01, 0xc8, 0xb1, 0xa2, 0xfb, 0x07, 0x11, 0xd7, 0x97, 0x7f, 0x85, 0xa4, 0xa7, 0xd1, 0xbb, 0xb9, 0xb2, 0xbf, 0x67, 0x31, 0x75, 0x91, 0x98, 0xfa, 0xf9, 0x81, 0xc5, 0x14, 0xbf, 0xf7, 0x2f, 0x48, 0x54, 0x35, 0xa1, 0x11, 0xe8, 0xa2, 0x84, 0x03, 0x97, 0x76, 0x7e, 0x58, 0x2d, 0xae, 0xe6, 0xe4, 0x9e, 0x64, 0xc7, 0xe7, 0x4c, 0x6a, 0x66, 0x1e, 0x28, 0xe8, 0x7e, 0x21, 0x49, 0x48, 0x20, 0x12, 0x39, 0x3a, 0x19, 0xdb, 0x78, 0xb9, 0x3a, 0xb6, 0x88, 0xba, 0xb7, 0x07, 0xf4, 0x91, 0x52, 0xe8, 0x06, 0xfb, 0x42, 0xe1, 0x05, 0xbe, 0xe5, 0x5b, 0x62, 0xdb, 0x4b, 0x3f, 0xb7, 0x91, 0x11, 0xb6, 0x9a, 0x94, 0x73, 0xe7, 0xc8, 0x88, 0x20, 0x80, 0x61, 0x02, 0x0a, 0xbc, 0xb4, 0x6e, 0x32, 0x88, 0x15, 0x95, 0x6b, 0x10, 0xb2, 0xa4, 0x96, 0x3a, 0x59, 0x81, 0xf3, 0xb8, 0x68, 0x37, 0xc7, 0x90, 0xd3, 0xaa, 0xaa, 0x82, 0xa3, 0x9a, 0x2c, 0x19, 0x79, 0xa5, 0xed, 0x94, 0xbc, 0x93, 0x2a, 0x92, 0xcb, 0x86, 0x81, 0xe4, 0xdc, 0x9d, 0xd3, 0xd5, 0x6f, 0x96, 0xfb, 0xb1, 0xfb, 0x9a, 0x2f, 0x71, 0x14, 0x03, 0x5a, 0xd3, 0x4f, 0x5c, 0xf0, 0x01, 0x3e, 0xcc, 0x36, 0xff, 0x2c, 0x82, 0xe5, 0xbb, 0x7a, 0x89, 0xea, 0xbc, 0x81, 0x76, 0xec, 0xbc, 0xc3, 0x94, 0xf1, 0x92, 0x7d, 0xb3, 0x4e, 0xba, 0xb4, 0x39, 0x20, 0xa0, 0xb7, 0x6c, 0xbc, 0x2f, 0x16, 0x04, 0x98, 0x80, 0xcd, 0xe7, 0x5d, 0x71, 0x9e, 0x84, 0x8e, 0xc0, 0x35, 0x70, 0x04, 0xd7, 0x6c, 0xf6, 0xcf, 0xf6, 0xa2, 0x65, 0xa0, 0x17, 0x69, 0xd1, 0xae, 0xaa, 0x53, 0x77, 0x18, 0x56, 0xb0, 0xc8, 0xe5, 0xc9, 0x2c, 0x21, 0x90, 0xef, 0x85, 0x49, 0xff, 0xa1, 0xda, 0xd0, 0x1b, 0x0a, 0xb1, 0x99, 0x21, 0xac, 0x42, 0x6c, 0x64, 0x08, 0xa7, 0xf5, 0xb4, 0xb3, 0xf1, 0x12, 0xf1, 0xd1, 0xcc, 0x5b, 0xc8, 0x99, 0xbb, 0xca, 0x20, 0x89, 0xa3, 0x75, 0x47, 0xae, 0x14, 0xb2, 0x9c, 0x2d, 0xb8, 0x90, 0x01, 0x51, 0x0b, 0xad, 0xac, 0xa1, 0x40, 0x97, 0xc4, 0x39, 0xc3, 0x31, 0xaa, 0x16, 0x29, 0xc3, 0x42, 0xf2, 0xf1, 0xec, 0x16, 0x3e, 0xef, 0xd4, 0x9f, 0x86, 0x84, 0xab, 0xc2, 0xb9, 0x30, 0xfe, 0x06, 0xa0, 0x24, 0xc3, 0xc8, 0xd2, 0x1c, 0xa6, 0xd0, 0xfb, 0x99, 0xed, 0xb7, 0x02, 0x2d, 0xe5, 0x2b, 0x78, 0x7d, 0x50, 0x78, 0x74, 0x3a, 0x85, 0xd1, 0x0c, 0x32, 0xd8, 0x71, 0x9f, 0x16, 0x19, 0x8f, 0x99, 0x87, 0xbd, 0x26, 0x8b, 0xd8, 0x4b, 0xb9, 0x94, 0xad, 0xb4, 0xc9, 0xb0, 0xb9, 0x40, 0x41, 0x62, 0x36, 0x2d, 0x39, 0x18, 0x03, 0x18, 0x87, 0x5b, 0xe4, 0x3a, 0x4d, 0xf6, 0x19, 0xf3, 0xce, 0x10, 0xa4, 0x40, 0x64, 0x54, 0x92, 0xa5, 0xe0, 0x8b, 0x21, 0xe7, 0x90, 0xe5, 0xd2, 0xa5, 0xed, 0x8c, 0x91, 0xaa, 0xe2, 0x35, 0xcf, 0x5c, 0x0b, 0x08, 0xc3, 0xb9, 0x19, 0x14, 0x19, 0xc5, 0xb1, 0xd1, 0x82, 0x68, 0x67, 0xa3, 0xd4, 0x01, 0xdf, 0x30, 0x3d, 0x71, 0xfa, 0x65, 0x64, 0x38, 0xcf, 0xf2, 0xcc, 0x2e, 0x12, 0x84, 0xbe, 0xcf, 0x2a, 0x5b, 0x04, 0x90, 0x4f, 0xe5, 0xe0, 0x45, 0x66, 0x50, 0x5a, 0xa9, 0x3b, 0xed, 0xaf, 0xac, 0x62, 0x3a, 0x4b, 0x11, 0x73, 0xfd, 0xea, 0xb3, 0x7c, 0x1c, 0x1e, 0xcb, 0xba, 0x00, 0x22, 0x37, 0x84, 0x22, 0x50, 0x5d, 0x8c, 0x5d, 0xed, 0x7a, 0x75, 0xec, 0x57, 0x0e, 0x2e, 0x9b, 0xbe, 0x71, 0x6d, 0xfd, 0xe4, 0xbe, 0x26, 0xb2, 0xcd, 0xd4, 0x84, 0x13, 0x71, 0x0f, 0x5a, 0xe6, 0xbb, 0x13, 0x1d, 0x2d, 0x65, 0x98, 0x46, 0xff, 0x65, 0x01, 0x1f, 0xc0, 0x2f, 0x0d, 0x81, 0xa9, 0xda, 0xb1, 0xed, 0xe6, 0x3c, 0x9a, 0x38, 0xdd, 0x20, 0xee, 0xc1, 0x5f, 0x0d, 0x4b, 0xbc, 0x58, 0xd1, 0x95, 0x2d, 0x30, 0x13, 0x28, 0x9f, 0x4b, 0x5a, 0xb6, 0xea, 0x24, 0x1f, 0x24, 0xe9, 0x55, 0x2f, 0x3a, 0x82, 0xf0, 0x14, 0xea, 0x19, 0xa9, 0xd7, 0x13, 0xcf, 0x60, 0x6e, 0x5c, 0x55, 0x94, 0x49, 0x16, 0x96, 0x24, 0xb5, 0xc8, 0xaf, 0xcc, 0x1a, 0x27, 0x40, 0x9f, 0x14, 0x93, 0x47, 0xa8, 0x4f, 0xc8, 0x4f, 0x8e, 0x84, 0xdd, 0x03, 0x44, 0x3d, 0xc8, 0x70, 0x6c, 0xe0, 0xcc, 0x36, 0x77, 0x20, 0x48, 0x69, 0xcd, 0xd0, 0x62, 0xcd, 0xc6, 0x26, 0xce, 0x3e, 0xdd, 0x0a, 0xd2, 0x9c, 0x23, 0xb0, 0x86, 0x98, 0x2f, 0x00, 0xcf, 0xc4, 0x94, 0x82, 0x19, 0xc9, 0xc4, 0xa6, 0x2e, 0x5d, 0x83, 0x20, 0x1d, 0x40, 0x7b, 0x59, 0x85, 0x17, 0x59, 0x77, 0x1c, 0x20, 0x96, 0xdb, 0x51, 0xde, 0x2a, 0xb4, 0x11, 0x6c, 0xef, 0xf9, 0x63, 0x90, 0x90, 0x90, 0x66, 0x39, 0x5e, 0x5f, 0x51, 0x2e, 0x57, 0x12, 0xd4, 0xdc, 0x09, 0xc7, 0x4d, 0xb3, 0x8b, 0x47, 0xc6, 0x6f, 0x73, 0x86, 0x74, 0x85, 0x1a, 0xd1, 0xe2, 0x62, 0xc5, 0x74, 0x86, 0x71, 0xcc, 0xd5, 0x80, 0xda, 0x76, 0xe7, 0x8c, 0xe1, 0x02, 0x17, 0x39, 0x14, 0x09, 0xd0, 0xe4, 0xbf, 0x05, 0x47, 0x08, 0x98, 0x2b, 0x87, 0x21, 0xb1, 0xe7, 0x32, 0xa8, 0xbf, 0xa2, 0xd9, 0x61, 0xa4, 0x87, 0x3a, 0x1a, 0x00, 0x79, 0x9e, 0x96, 0x15, 0x5b, 0x2d, 0x1e, 0x5d, 0xca, 0x39, 0xae, 0xa9, 0x19, 0x3d, 0xf5, 0x86, 0xaa, 0x90, 0x81, 0x3e, 0xd5, 0x34, 0x49, 0x15, 0x42, 0x43, 0x63, 0x61, 0x9b, 0x33, 0xfb, 0xe3, 0xd0, 0xc1, 0x4d, 0x0e, 0x7b, 0xf6, 0xbf, 0x3b, 0x82, 0x06, 0x2a, 0xf8, 0x2f, 0xb8, 0xb7, 0xfd, 0x82, 0xbb, 0xcb, 0xd9, 0x7a, 0xf8, 0x39, 0x2c, 0x6c, 0xf1, 0x7a, 0x75, 0xd8, 0x10, 0x9b, 0x2d, 0x62, 0xb5, 0xc5, 0x43, 0xed, 0xe0, 0x8d, 0x8d, 0xca, 0xe4, 0xac, 0x9f, 0x9a, 0x76, 0x07, 0xbf, 0xe7, 0x1c, 0x42, 0x78, 0xd3, 0xbb, 0xa4, 0x1c, 0xaf, 0xdc, 0xc6, 0xd7, 0xad, 0xe4, 0xd1, 0x4a, 0xf8, 0x72, 0x7c, 0xc5, 0xdf, 0x55, 0x49, 0xe3, 0x0e, 0xd2, 0x37, 0x4b, 0x3f, 0x4f, 0x3b, 0xf2, 0x69, 0xe2, 0xb5, 0x32, 0x1b, 0x12, 0xc1, 0xb7, 0x01, 0x49, 0xbd, 0x8c, 0xc0, 0x00, 0x07, 0x04, 0x82, 0x72, 0x88, 0xb7, 0x6b, 0x97, 0x62, 0xd2, 0x5e, 0x68, 0xa7, 0xe6, 0x62, 0x76, 0x36, 0x0a, 0x51, 0xc6, 0x70, 0x7f, 0x6d, 0x28, 0xd4, 0x17, 0x01, 0xb1, 0x78, 0xb8, 0xa3, 0xed, 0xd7, 0xb4, 0x29, 0xe2, 0x25, 0x75, 0xcf, 0x97, 0x75, 0x61, 0xee, 0xe1, 0xe9, 0x1d, 0x27, 0x1f, 0x1a, 0x4a, 0xb0, 0x95, 0x5d, 0x4e, 0xdc, 0x59, 0x9d, 0x7c, 0x3a, 0xd7, 0x75, 0x03, 0xe7, 0xa9, 0x70, 0x4a, 0x92, 0xca, 0x29, 0x49, 0x5c, 0xaa, 0x34, 0x96, 0xfd, 0xc4, 0xde, 0xcd, 0x41, 0x5a, 0xcb, 0xe0, 0x6a, 0x53, 0x2e, 0xbd, 0x65, 0xfa, 0x07, 0x8c, 0xaf, 0x66, 0x0a, 0xf4, 0x1c, 0x36, 0x66, 0x6b, 0x9f, 0x59, 0xc4, 0xf3, 0xe5, 0x6e, 0x98, 0xa3, 0xc6, 0x23, 0x09, 0x0e, 0x48, 0xfb, 0xbe, 0x0f, 0xc2, 0xb9, 0xe3, 0x70, 0x92, 0xed, 0xb0, 0x5c, 0x11, 0x75, 0xdb, 0xe7, 0x96, 0xa5, 0x65, 0x53, 0x7a, 0xae, 0x25, 0x7e, 0xd6, 0x8f, 0x30, 0xba, 0xb1, 0xe2, 0x10, 0x31, 0xa1, 0x30, 0x42, 0xc2, 0x64, 0x5c, 0x14, 0x38, 0x78, 0xec, 0xa4, 0x48, 0x27, 0xa7, 0x8e, 0xec, 0x07, 0x68, 0x8f, 0xe3, 0x1a, 0x61, 0x27, 0xd2, 0x8b, 0x9a, 0x92, 0x49, 0xb4, 0x0e, 0x58, 0xa8, 0x0e, 0xb3, 0x10, 0xb2, 0xd5, 0x8d, 0x88, 0xed, 0x42, 0x71, 0x2d, 0x80, 0x86, 0x55, 0x5b, 0xf9, 0xe6, 0x69, 0xee, 0xaf, 0xac, 0xcb, 0x0e, 0x4b, 0x79, 0xa7, 0xcd, 0xbd, 0xa5, 0xb4, 0xb2, 0xce, 0x79, 0x55, 0xfc, 0x86, 0xb0, 0x01, 0x84, 0x23, 0xc8, 0x89, 0x0b, 0x9c, 0x3e, 0xb7, 0x7d, 0x24, 0xc8, 0xb1, 0x8d, 0x95, 0xad, 0x37, 0x64, 0x65, 0xff, 0x86, 0xae, 0x96, 0x3b, 0x1f, 0x5b, 0x99, 0xa7, 0xb2, 0x2b, 0x6c, 0x6d, 0xeb, 0x05, 0x4f, 0xdd, 0xd0, 0x96, 0x6c, 0x6d, 0x97, 0xe4, 0x25, 0x32, 0x7f, 0x99, 0x85, 0xdf, 0xa2, 0xd2, 0x9c, 0xd4, 0x56, 0x4a, 0xe3, 0x41, 0x34, 0xb3, 0x4e, 0x3f, 0x22, 0x73, 0xbe, 0xc5, 0x00, 0x4b, 0x7a, 0x57, 0x96, 0x80, 0x21, 0x40, 0x30, 0x41, 0xf8, 0x14, 0x02, 0x9d, 0x41, 0xac, 0x58, 0x91, 0xb7, 0x53, 0x2a, 0xba, 0x14, 0xc3, 0xd3, 0xc1, 0xe7, 0x72, 0x02, 0x0e, 0x23, 0xca, 0xc9, 0x6a, 0x8e, 0x04, 0x51, 0x03, 0x93, 0xfd, 0x40, 0xe8, 0x14, 0x24, 0xc0, 0x47, 0x4b, 0x1e, 0xc1, 0x13, 0xe8, 0x56, 0x22, 0x17, 0xa5, 0x0c, 0x69, 0x96, 0xd8, 0x32, 0x42, 0x79, 0xaf, 0xbd, 0xcf, 0xcc, 0xfc, 0x98, 0xec, 0x6a, 0x89, 0x74, 0x46, 0x62, 0x2f, 0x34, 0x63, 0x9c, 0x35, 0x0b, 0x2c, 0xa5, 0x30, 0xb7, 0xb3, 0xd3, 0x68, 0xf0, 0x1b, 0xc3, 0x99, 0x32, 0xce, 0xe5, 0x3a, 0x07, 0x96, 0x2f, 0xe6, 0xc4, 0x24, 0x4d, 0xb9, 0x9d, 0xe5, 0x42, 0x6b, 0x31, 0x51, 0x08, 0xaf, 0xd7, 0x94, 0xee, 0x44, 0x40, 0x16, 0x4c, 0xe9, 0x09, 0x62, 0xbb, 0x2d, 0xc9, 0x4c, 0x52, 0xe6, 0x4a, 0xd4, 0x34, 0x2a, 0x75, 0x27, 0x24, 0x01, 0xe4, 0xa0, 0x4b, 0x61, 0xb0, 0x43, 0xfc, 0xc9, 0x01, 0x32, 0x06, 0x86, 0xd8, 0x32, 0x0f, 0x36, 0xc9, 0x59, 0xfa, 0x39, 0xd2, 0xef, 0xf0, 0x7c, 0x60, 0x38, 0x2c, 0x39, 0x85, 0x97, 0xc1, 0xf3, 0x50, 0xc4, 0x01, 0x46, 0x77, 0x45, 0x0f, 0x02, 0xa6, 0xab, 0xb1, 0x19, 0xce, 0x77, 0x4f, 0x18, 0x1e, 0x27, 0xd2, 0x0c, 0x39, 0x87, 0xc8, 0x8f, 0x9f, 0x09, 0xfe, 0x17, 0x5a, 0x6b, 0xe8, 0x86, 0x9b, 0x53, 0x6b, 0x6c, 0xbc, 0xa5, 0x07, 0x83, 0x28, 0x3f, 0xe5, 0x71, 0x56, 0x69, 0x18, 0x98, 0x00, 0x60, 0x42, 0xb6, 0x30, 0x46, 0x29, 0xbc, 0x00, 0x34, 0x2f, 0xfc, 0xa4, 0x33, 0x68, 0x00, 0x56, 0x82, 0xa3, 0xc7, 0x08, 0xdf, 0xe1, 0x7d, 0x09, 0x7a, 0x88, 0x00, 0x8c, 0xf7, 0x28, 0xc9, 0x9b, 0xfe, 0x5c, 0x09, 0xff, 0x33, 0xf5, 0xab, 0xd2, 0xaa, 0x9e, 0x05, 0x00, 0x5b, 0xde, 0x92, 0x28, 0x3f, 0xab, 0x55, 0xf3, 0xe8, 0xda, 0x80, 0x70, 0xd9, 0x29, 0x7b, 0xb6, 0x92, 0x08, 0x6f, 0x6c, 0x90, 0x93, 0xb3, 0x50, 0x43, 0x46, 0xee, 0x87, 0xf9, 0x55, 0x8f, 0x41, 0x6c, 0x3f, 0xcc, 0x88, 0xe9, 0x8e, 0xbf, 0x7f, 0xd3, 0xf4, 0x9a, 0x66, 0x52, 0x6d, 0x14, 0x8e, 0xa6, 0x60, 0xd3, 0xc3, 0x30, 0x37, 0x7f, 0x17, 0x26, 0x34, 0x02, 0x2b, 0x22, 0x4e, 0xc3, 0x7c, 0xa2, 0x8a, 0x94, 0xa7, 0xca, 0xa1, 0xc4, 0x3d, 0x82, 0xde, 0xca, 0xc0, 0x9f, 0xf2, 0x09, 0xa2, 0x76, 0x8b, 0x85, 0x0d, 0x37, 0xd5, 0xb1, 0xe6, 0x03, 0x65, 0xa9, 0x25, 0x0a, 0x33, 0xc1, 0xbc, 0xd3, 0x3a, 0xcb, 0x57, 0x9b, 0x2d, 0x8d, 0x99, 0xa9, 0xab, 0x13, 0x6c, 0x51, 0x7c, 0xcd, 0x27, 0x07, 0x99, 0x60, 0x4c, 0xfd, 0x53, 0xed, 0xc9, 0xb5, 0x72, 0x9f, 0x1e, 0xfb, 0x46, 0x4e, 0x8b, 0x6d, 0xa7, 0x2d, 0x10, 0x7b, 0x8a, 0x2e, 0x12, 0x86, 0x32, 0x9d, 0x23, 0xf1, 0xc8, 0x27, 0x59, 0x87, 0x6e, 0xf4, 0xce, 0x40, 0x8d, 0x18, 0x1b, 0x89, 0x18, 0x32, 0x00, 0x6e, 0x12, 0x84, 0xfa, 0x12, 0x11, 0xd7, 0x66, 0xb2, 0xf3, 0xc7, 0x21, 0xe5, 0x89, 0x2b, 0x93, 0xa0, 0x67, 0xfa, 0x08, 0x69, 0xd4, 0x70, 0x12, 0x54, 0x32, 0x08, 0xbd, 0x1d, 0x2a, 0x8d, 0x18, 0x8c, 0x01, 0x76, 0xd8, 0x5a, 0xd6, 0x9e, 0x74, 0xd3, 0x4b, 0xd3, 0x57, 0x39, 0x50, 0x5d, 0xf5, 0xad, 0x9a, 0x59, 0x9e, 0x69, 0x4e, 0x96, 0x86, 0x07, 0x21, 0x28, 0xe7, 0xb7, 0xee, 0x53, 0x2d, 0x1d, 0xcc, 0x72, 0x9d, 0xfb, 0x5d, 0xd2, 0xe9, 0xbb, 0x10, 0x64, 0x72, 0xd6, 0x74, 0x03, 0xe1, 0x12, 0x26, 0x88, 0x03, 0x6c, 0x8d, 0x62, 0xbb, 0x6b, 0xf0, 0x4d, 0x21, 0x61, 0x90, 0x40, 0x7e, 0x1d, 0xfb, 0x74, 0x43, 0x07, 0xa5, 0x15, 0x1d, 0x91, 0x1c, 0xa8, 0x9e, 0x1e, 0x9b, 0xb8, 0x4d, 0x98, 0x99, 0x82, 0xd5, 0x54, 0x0a, 0x92, 0x04, 0xac, 0x80, 0x9a, 0x59, 0x37, 0xe8, 0x15, 0x4e, 0xdc, 0x2d, 0x22, 0xef, 0xda, 0x32, 0x13, 0xc0, 0xdb, 0xb2, 0x5d, 0x88, 0xf3, 0xe9, 0x59, 0x82, 0x15, 0x74, 0x40, 0xa4, 0x0a, 0x06, 0x19, 0x36, 0x74, 0xe6, 0xf0, 0xc2, 0x0e, 0xae, 0x9d, 0xd9, 0x5c, 0x16, 0xf5, 0x7c, 0x5e, 0x57, 0xcb, 0xe7, 0x56, 0xb2, 0x1f, 0xdc, 0x34, 0xc9, 0x1b, 0x94, 0x92, 0x19, 0x92, 0x68, 0xec, 0x7a, 0xea, 0xd6, 0x5a, 0xcd, 0x57, 0x0c, 0x66, 0x61, 0x5d, 0x9a, 0x00, 0x58, 0xf2, 0x82, 0x45, 0x12, 0x90, 0xcb, 0x68, 0xe9, 0x40, 0x68, 0xab, 0x3f, 0x2b, 0xa3, 0xff, 0x85, 0x26, 0xce, 0x58, 0x82, 0x5b, 0x53, 0x8e, 0xba, 0xa0, 0xe4, 0xee, 0x66, 0x44, 0xca, 0xd7, 0x38, 0x29, 0x26, 0xbd, 0x8b, 0x85, 0x18, 0x92, 0x58, 0x59, 0xfb, 0xe6, 0xd1, 0x09, 0xce, 0xcb, 0x84, 0xed, 0x8f, 0x9b, 0x5d, 0x7a, 0x9c, 0x50, 0xb4, 0x26, 0xbd, 0xbe, 0xce, 0xaa, 0xf9, 0x42, 0x1d, 0x3e, 0x9b, 0x45, 0x21, 0x3a, 0xab, 0x6b, 0x40, 0xc9, 0xfb, 0x66, 0x56, 0xc4, 0xf4, 0x74, 0x81, 0xae, 0xfb, 0x08, 0x51, 0xdf, 0xeb, 0x83, 0xbc, 0x7a, 0x07, 0xb7, 0xd2, 0x11, 0xfd, 0x6a, 0x85, 0x69, 0x8e, 0x71, 0x33, 0xcd, 0xc6, 0x1b, 0x5d, 0x21, 0x2d, 0x3c, 0x58, 0xd7, 0xbc, 0xbe, 0x42, 0xac, 0xfc, 0xe8, 0x16, 0xf3, 0xc3, 0x6d, 0x9a, 0xb7, 0x50, 0x26, 0x64, 0x3d, 0x91, 0xda, 0x75, 0xcb, 0xf1, 0x0b, 0x5c, 0xcc, 0xd5, 0xfc, 0x40, 0x28, 0xec, 0xb7, 0x3a, 0x40, 0x53, 0x47, 0x9a, 0x25, 0x8d, 0x97, 0x2c, 0xfb, 0x98, 0xc9, 0x3f, 0x6f, 0x17, 0xb8, 0x67, 0xb5, 0xaa, 0x51, 0x73, 0x56, 0xfb, 0xf2, 0x27, 0xfb, 0xb2, 0x95, 0xbe, 0x1e, 0xdd, 0xca, 0x7c, 0xb8, 0x1d, 0xf0, 0x3e, 0x1d, 0x1b, 0x39, 0x22, 0xb3, 0xa6, 0xd9, 0x8a, 0xf3, 0x02, 0xfd, 0x6c, 0x02, 0xe0, 0xa3, 0x58, 0xbd, 0x72, 0xb3, 0xe3, 0x6f, 0xd8, 0x31, 0x9f, 0xbf, 0x7e, 0x6a, 0x07, 0x43, 0x33, 0x89, 0x4f, 0xe5, 0xd8, 0xc7, 0x6a, 0x14, 0xe7, 0x34, 0x1a, 0x99, 0x1f, 0x38, 0x81, 0x8f, 0x00, 0x69, 0x19, 0xdb, 0xe9, 0xac, 0xad, 0xcd, 0x04, 0xd0, 0x21, 0x7a, 0x45, 0x36, 0x6f, 0xa0, 0x6a, 0xf3, 0x5a, 0x11, 0x8c, 0x20, 0x98, 0x0e, 0xb6, 0xb5, 0xed, 0x02, 0x26, 0x80, 0xcd, 0x82, 0x10, 0x14, 0x31, 0x32, 0x90, 0x03, 0x88, 0xee, 0x52, 0x48, 0xea, 0xc2, 0x3f, 0x98, 0x36, 0xa3, 0x46, 0xc4, 0x46, 0xc1, 0x89, 0xcf, 0x84, 0x01, 0xb8, 0x41, 0x32, 0x96, 0x3d, 0xd2, 0x10, 0x85, 0xe6, 0x33, 0x72, 0x05, 0x06, 0x90, 0xde, 0xfa, 0x4e, 0xc5, 0xd0, 0x2a, 0x44, 0xc5, 0x3c, 0xeb, 0x60, 0x8d, 0x08, 0x24, 0xa3, 0x5e, 0x4e, 0x5c, 0xe9, 0xcb, 0xca, 0x0f, 0x7a, 0x79, 0x92, 0xb5, 0xa1, 0xbe, 0x6f, 0x60, 0x07, 0x0a, 0x8d, 0xcc, 0xd9, 0xf1, 0x4e, 0xf4, 0xf8, 0xb6, 0x9c, 0xb4, 0x03, 0xe2, 0xcd, 0xd9, 0x72, 0xa0, 0x75, 0x4a, 0xa0, 0x19, 0x51, 0xc8, 0x23, 0x17, 0xa0, 0x32, 0x8d, 0xf8, 0x5f, 0xa0, 0x0a, 0xa1, 0xed, 0x48, 0x5e, 0x03, 0x2f, 0x93, 0x16, 0x4f, 0xbb, 0xca, 0x5b, 0x88, 0xf5, 0x48, 0x5e, 0x08, 0xa6, 0x39, 0x50, 0x30, 0x57, 0xb1, 0x4d, 0xaf, 0xf4, 0x7a, 0xf7, 0x0f, 0x01, 0x5e, 0xe6, 0x4e, 0x9f, 0x9d, 0x8a, 0x41, 0x09, 0xbc, 0xcd, 0x08, 0x5e, 0x3d, 0x92, 0xf7, 0xd5, 0xd7, 0x96, 0x7d, 0xc0, 0x75, 0x5a, 0xa6, 0x61, 0x63, 0x3d, 0x01, 0xc5, 0xc9, 0x99, 0xa3, 0x27, 0x9c, 0x35, 0x36, 0x62, 0x76, 0x71, 0xcc, 0xaf, 0x26, 0x29, 0x19, 0xf7, 0x71, 0x2b, 0xd7, 0xce, 0xed, 0x73, 0x8a, 0x11, 0xd8, 0x0b, 0x99, 0x77, 0xb4, 0xbe, 0x17, 0x7a, 0x7e, 0xf7, 0x6b, 0x25, 0xc9, 0xeb, 0x6f, 0x1a, 0xe7, 0x32, 0x3b, 0x5b, 0x32, 0x33, 0xc4, 0x1a, 0x6d, 0x77, 0x96, 0x64, 0x20, 0x64, 0xeb, 0x16, 0x84, 0x34, 0xf3, 0xb2, 0x16, 0x15, 0x26, 0x1a, 0x46, 0x07, 0x2f, 0xce, 0x63, 0x23, 0x9c, 0xa8, 0xd8, 0x81, 0x97, 0x3c, 0xf9, 0xbf, 0x44, 0x1b, 0x78, 0xa7, 0x3b, 0x65, 0x2e, 0xd3, 0x6a, 0xcf, 0xe3, 0x8c, 0xa9, 0xb1, 0x87, 0x9e, 0xbd, 0xf1, 0x9e, 0x9c, 0x93, 0xe4, 0xf5, 0xcb, 0xc6, 0xe9, 0xad, 0x8b, 0x12, 0x89, 0xa5, 0xbc, 0x33, 0x2a, 0xb6, 0x09, 0xd8, 0x9b, 0xef, 0x40, 0x46, 0xee, 0x13, 0x8f, 0x5d, 0x8d, 0xf3, 0x0c, 0x89, 0x25, 0x3c, 0xd2, 0x4c, 0x0a, 0x49, 0x18, 0x00, 0x80, 0xb6, 0x22, 0x00, 0xd6, 0xb8, 0x5c, 0x8c, 0x58, 0x65, 0x4a, 0xfd, 0x2e, 0xc3, 0x10, 0xd0, 0x4f, 0x4a, 0x09, 0xe6, 0x84, 0x3f, 0x48, 0x17, 0xb9, 0x4c, 0x64, 0x0d, 0xa9, 0xed, 0x1e, 0x01, 0x4f, 0x06, 0x00, 0xb4, 0x4a, 0x72, 0x2c, 0x5f, 0x66, 0xc0, 0x14, 0x84, 0xbc, 0x65, 0x56, 0xab, 0x1d, 0xf5, 0xca, 0xb3, 0x41, 0x2c, 0x54, 0xd2, 0x7c, 0x35, 0xb1, 0x8a, 0x52, 0x60, 0xda, 0x70, 0x78, 0x1b, 0x4b, 0x6b, 0x70, 0xc5, 0x1a, 0x1c, 0xc8, 0x33, 0xf9, 0x06, 0x91, 0x63, 0x60, 0xde, 0x41, 0xe1, 0xb1, 0x06, 0x9f, 0x6d, 0xbe, 0x18, 0x59, 0x2a, 0x90, 0xce, 0xf3, 0x00, 0x2c, 0x99, 0xe5, 0xe6, 0x3c, 0xb1, 0x53, 0x7b, 0xb6, 0x97, 0x01, 0xc6, 0xc0, 0x0c, 0xd7, 0xe4, 0xe7, 0x66, 0xe0, 0x96, 0x62, 0x52, 0x8d, 0x43, 0xe1, 0xde, 0x48, 0x5f, 0x39, 0xa6, 0xbc, 0x80, 0x3b, 0x72, 0xc4, 0x45, 0x1d, 0x7b, 0x96, 0x52, 0x22, 0xfe, 0xc0, 0xb8, 0x80, 0xe1, 0x19, 0x48, 0x62, 0xeb, 0x30, 0x3c, 0x27, 0x76, 0xa5, 0xe7, 0xe4, 0x32, 0xa6, 0x0a, 0xe1, 0x27, 0xcf, 0x7c, 0x1b, 0x96, 0x20, 0xc8, 0x0c, 0xe8, 0x62, 0x44, 0x02, 0xd6, 0x4b, 0xa7, 0xbe, 0x88, 0x18, 0x9b, 0xee, 0xde, 0x64, 0x52, 0xd6, 0x02, 0x45, 0xa0, 0x6a, 0x08, 0xd8, 0x37, 0x53, 0xd8, 0x13, 0x47, 0x6b, 0xc1, 0x34, 0x2b, 0x7a, 0x0a, 0x5c, 0x4d, 0x41, 0x28, 0xed, 0x98, 0x34, 0x40, 0x67, 0x3e, 0x0f, 0x93, 0x5f, 0x6a, 0xdf, 0x55, 0x99, 0x26, 0xdd, 0x58, 0xa6, 0xf6, 0x60, 0x86, 0x91, 0x7c, 0xdb, 0x99, 0x87, 0x84, 0x9f, 0x7c, 0x5e, 0x2a, 0x3e, 0x50, 0xb1, 0x41, 0x43, 0xdd, 0xd2, 0x53, 0xf4, 0x64, 0xa6, 0x89, 0x5c, 0xfc, 0x5a, 0x01, 0xad, 0x40, 0xa6, 0x43, 0x85, 0xe6, 0x7c, 0xd7, 0x8a, 0x16, 0x81, 0x2e, 0x9d, 0x9b, 0x43, 0x7e, 0x92, 0xf4, 0x72, 0x1d, 0x7a, 0x07, 0x0b, 0x21, 0x0b, 0x11, 0xd2, 0x52, 0xd1, 0x65, 0xc2, 0xcb, 0x6c, 0x67, 0x2b, 0x0e, 0x82, 0xa1, 0x2e, 0xe3, 0x5d, 0x28, 0xdd, 0xad, 0xb3, 0xc6, 0x32, 0x1f, 0x8a, 0x47, 0xe0, 0xc6, 0x2d, 0x33, 0xa4, 0x10, 0x39, 0xed, 0x3e, 0x53, 0xb5, 0xe6, 0xba, 0x6e, 0x86, 0xc0, 0x31, 0x36, 0x53, 0xbe, 0x12, 0x14, 0xc5, 0x97, 0xf5, 0x19, 0x0e, 0x60, 0xd3, 0x6d, 0x19, 0x72, 0xe2, 0x74, 0xa0, 0xf4, 0x17, 0x67, 0x30, 0xbf, 0x05, 0xdb, 0xa4, 0x3f, 0x89, 0x48, 0xc6, 0x21, 0x19, 0x30, 0x15, 0x84, 0xa3, 0x85, 0x08, 0x20, 0x0f, 0x34, 0x06, 0x05, 0xf5, 0xad, 0xe9, 0x8e, 0x78, 0x51, 0xc0, 0x56, 0x14, 0x90, 0x9b, 0x80, 0x68, 0x20, 0xc7, 0x55, 0x2b, 0x70, 0x06, 0xdb, 0x4e, 0x1a, 0xc1, 0xaf, 0xc5, 0x2a, 0xb8, 0x3b, 0xa9, 0x74, 0x46, 0x88, 0x28, 0x43, 0x0e, 0x23, 0x22, 0x6c, 0xc1, 0xfe, 0x94, 0x77, 0x39, 0xe0, 0xa1, 0xd2, 0x0b, 0xa7, 0x17, 0x1f, 0xdc, 0x96, 0x47, 0xca, 0x7c, 0x9a, 0xc0, 0x8f, 0x48, 0x2b, 0x5d, 0x45, 0x7b, 0xb0, 0xb0, 0xe0, 0xb4, 0xcd, 0x65, 0xed, 0x0c, 0x3e, 0x13, 0xd3, 0x39, 0x28, 0x59, 0x84, 0x25, 0x02, 0x0e, 0x02, 0x9f, 0x1a, 0xa2, 0xe6, 0x0d, 0x54, 0xb7, 0xca, 0x10, 0x21, 0xbc, 0xd2, 0xa1, 0x05, 0xd9, 0xaf, 0x2d, 0x84, 0xd5, 0x18, 0x7c, 0xe0, 0x56, 0xf0, 0xe3, 0xd5, 0xb0, 0xcc, 0x01, 0x96, 0xa2, 0xa0, 0xd8, 0x05, 0x3f, 0x63, 0xcf, 0x5e, 0xdd, 0x4e, 0x7b, 0x1c, 0x45, 0x51, 0xd4, 0x86, 0x52, 0x34, 0x42, 0xbe, 0x39, 0x8b, 0xd8, 0xa2, 0x8c, 0x92, 0x14, 0x34, 0x18, 0x02, 0xa5, 0x20, 0x1f, 0x4e, 0x91, 0xb8, 0xb0, 0x41, 0x13, 0x46, 0x87, 0x7f, 0x8b, 0x05, 0x18, 0x15, 0x24, 0xdc, 0x3c, 0xba, 0x6b, 0x34, 0x2e, 0x00, 0x83, 0xf5, 0xb9, 0xd2, 0xcd, 0x65, 0xa2, 0x7e, 0xe9, 0x5d, 0x08, 0x85, 0x3f, 0x99, 0x6d, 0x1f, 0xe9, 0xa2, 0xf7, 0x99, 0xc7, 0xa1, 0x5a, 0x3d, 0xaa, 0x51, 0x87, 0x64, 0x28, 0xac, 0xe7, 0xda, 0x93, 0xcf, 0xc1, 0x5b, 0x1e, 0x9b, 0x0b, 0x16, 0x98, 0xac, 0x1a, 0xaa, 0x4f, 0x39, 0x53, 0x90, 0xf1, 0x08, 0xf8, 0x44, 0xf3, 0x5a, 0xb2, 0x3d, 0x26, 0x94, 0x9e, 0xf7, 0x2d, 0xf1, 0x85, 0xec, 0xfb, 0xf0, 0x99, 0xcf, 0xcf, 0x09, 0x6f, 0xbe, 0xd0, 0xe4, 0x77, 0xb8, 0xfe, 0x78, 0x04, 0xde, 0xa5, 0xb4, 0xa5, 0xca, 0x48, 0xf4, 0x52, 0x20, 0xa0, 0x9d, 0x99, 0x8c, 0xd2, 0xdd, 0x97, 0x8a, 0x06, 0xcc, 0x18, 0x94, 0x51, 0xae, 0xb9, 0x4e, 0x79, 0xdf, 0x53, 0x3a, 0x17, 0x14, 0xac, 0x57, 0x3d, 0xe8, 0xb1, 0x1d, 0x08, 0x33, 0x55, 0x04, 0x40, 0x05, 0x8f, 0xc0, 0xb7, 0x03, 0xa8, 0xa4, 0x0e, 0xb7, 0x3d, 0x46, 0x42, 0x03, 0x87, 0x37, 0x17, 0xd3, 0xac, 0xe6, 0xe0, 0x5f, 0xda, 0x3d, 0x7c, 0x2b, 0x92, 0x1d, 0x4b, 0xe9, 0xea, 0x9c, 0x7b, 0x5b, 0x4f, 0xba, 0xaa, 0x93, 0xbe, 0xd7, 0x0a, 0xcd, 0x61, 0xb5, 0x2f, 0x43, 0x45, 0xe1, 0x70, 0x35, 0x97, 0x28, 0xac, 0x68, 0x4f, 0xd8, 0x54, 0x71, 0x1f, 0x95, 0xca, 0x69, 0x7e, 0x81, 0x99, 0x7e, 0xdd, 0x1c, 0xad, 0x6b, 0xf5, 0x60, 0x5d, 0xbb, 0x07, 0xd0, 0x6d, 0x76, 0xc6, 0xf4, 0xc6, 0xec, 0xe6, 0xab, 0xff, 0xb7, 0x40, 0x17, 0xda, 0xc6, 0xac, 0x1f, 0xfa, 0x53, 0x27, 0x3c, 0xcd, 0xbc, 0x0d, 0xe8, 0x00, 0x70, 0x10, 0xd8, 0x9b, 0x7e, 0x65, 0x1a, 0x7c, 0xe9, 0x83, 0x74, 0xd3, 0x46, 0x7c, 0x4e, 0x01, 0xf8, 0x02, 0x33, 0x04, 0x85, 0xbb, 0x3c, 0xb3, 0xab, 0xac, 0x6d, 0xd9, 0x01, 0xd9, 0x3b, 0x1e, 0xbc, 0x2d, 0xb2, 0x13, 0x5b, 0x80, 0x11, 0xb6, 0x92, 0x74, 0x16, 0x30, 0xeb, 0x2c, 0xdd, 0x53, 0x4c, 0xa2, 0xaf, 0x8b, 0x66, 0xcb, 0xf4, 0xd8, 0xf4, 0x9b, 0x8b, 0x5b, 0xcf, 0xc2, 0xbc, 0xd3, 0x31, 0xad, 0x14, 0x17, 0xd2, 0x35, 0x2e, 0x5f, 0xa4, 0x83, 0xd7, 0xfc, 0xb3, 0x4a, 0xbf, 0x63, 0xde, 0xda, 0x16, 0xb1, 0x80, 0xd1, 0xc3, 0xb5, 0xdb, 0x03, 0xd2, 0x91, 0xa7, 0x16, 0xbe, 0xf2, 0xc0, 0x46, 0xec, 0xfd, 0x76, 0x5a, 0xc2, 0xb9, 0x42, 0xae, 0x1d, 0x06, 0x8c, 0xd5, 0x53, 0x6a, 0x70, 0xda, 0x5b, 0xfc, 0x9f, 0xf2, 0xdf, 0xfe, 0x8f, 0x5a, 0x77, 0xc6, 0x6e, 0x6f, 0xd2, 0xcd, 0xdc, 0xc0, 0x8e, 0x98, 0xe5, 0xfa, 0x42, 0x20, 0x1c, 0xfe, 0x35, 0xfc, 0x1f, 0x97, 0xff, 0x6b, 0x4e, 0x98, 0xfe, 0xed, 0xd7, 0x86, 0x9b, 0x30, 0x33, 0x00, 0xc3, 0xa9, 0x53, 0x79, 0x28, 0x98, 0xbf, 0x75, 0xb2, 0xa3, 0x0a, 0xa8, 0xa6, 0x3c, 0x1c, 0x37, 0x7f, 0x38, 0x0b, 0x24, 0xd6, 0x9e, 0x15, 0x3f, 0x40, 0x56, 0x2b, 0x24, 0xa0, 0x20, 0x46, 0x27, 0xcc, 0xdc, 0x36, 0xac, 0x04, 0x63, 0xea, 0x37, 0xc0, 0x85, 0x64, 0x5a, 0x69, 0x7a, 0x81, 0x44, 0xd5, 0x3b, 0xd3, 0x94, 0x9c, 0x73, 0xcc, 0xcb, 0x25, 0x26, 0x13, 0x45, 0xa1, 0x04, 0xae, 0x2b, 0x6b, 0xb7, 0x4d, 0x89, 0x61, 0xdb, 0x12, 0xe3, 0x6a, 0x63, 0xea, 0xdb, 0x86, 0x03, 0xc3, 0xa4, 0xdd, 0x70, 0x87, 0x0c, 0x81, 0xa9, 0x3b, 0x56, 0x21, 0x35, 0xe5, 0xe6, 0xa7, 0xdd, 0xc8, 0x98, 0x6a, 0xd0, 0x51, 0x03, 0xd3, 0x7a, 0x82, 0x20, 0x09, 0xe9, 0x60, 0x23, 0xc8, 0x00, 0x59, 0x44, 0x88, 0xd6, 0x46, 0xbd, 0x2b, 0x74, 0x69, 0x52, 0x51, 0x80, 0x92, 0x71, 0x70, 0x5c, 0x6e, 0xcc, 0x86, 0xa4, 0xbf, 0x40, 0x89, 0x12, 0xd1, 0x45, 0xdd, 0x76, 0xaa, 0xa7, 0xf1, 0x95, 0x8b, 0xeb, 0x68, 0x38, 0x69, 0xae, 0x39, 0xf3, 0xda, 0x13, 0x01, 0x20, 0xdb, 0x59, 0x64, 0xbe, 0x05, 0xd6, 0x0a, 0x19, 0x0f, 0xae, 0x89, 0xe8, 0x4f, 0xc8, 0xa5, 0xe1, 0x0d, 0x7b, 0x59, 0x4e, 0x0e, 0xff, 0x4c, 0xaf, 0x77, 0x99, 0xdb, 0xe6, 0xdb, 0x07, 0xa6, 0xd7, 0x4b, 0xef, 0xf4, 0xcb, 0x49, 0x97, 0x7c, 0xdd, 0x2a, 0xf7, 0x05, 0x24, 0x9a, 0x39, 0xee, 0x0d, 0xbb, 0x68, 0xad, 0xbb, 0x32, 0x56, 0xb2, 0x27, 0x6f, 0x28, 0x43, 0xe0, 0x90, 0xeb, 0x50, 0x99, 0x6c, 0xb9, 0x7a, 0x36, 0x62, 0xcc, 0x4d, 0x61, 0xde, 0x53, 0x5c, 0x10, 0x84, 0x1d, 0x16, 0x6c, 0x03, 0x82, 0x41, 0x82, 0x69, 0x5c, 0x4b, 0xe9, 0xc2, 0xba, 0x46, 0x9c, 0x45, 0xb3, 0xaa, 0xcc, 0x88, 0x8a, 0x7e, 0x9b, 0xa3, 0x21, 0xf8, 0x18, 0x29, 0x3d, 0x01, 0xbd, 0x20, 0xb9, 0x7e, 0x2f, 0x7b, 0x1f, 0x92, 0x4a, 0x10, 0x9b, 0xf7, 0x9f, 0xa4, 0xb0, 0x5d, 0x2a, 0x0b, 0x7a, 0x46, 0xda, 0xd5, 0xbd, 0x2e, 0x94, 0x6b, 0x77, 0xb0, 0x17, 0xae, 0x79, 0x20, 0x0e, 0x1c, 0xe7, 0xb0, 0xa0, 0x76, 0x31, 0xda, 0x4b, 0x18, 0xf4, 0xce, 0xcb, 0x9c, 0xd2, 0xa6, 0xa5, 0x0c, 0x9e, 0xd5, 0x8f, 0x85, 0x97, 0xbb, 0xa2, 0x98, 0xe0, 0x9c, 0x59, 0xe5, 0x9e, 0xa0, 0xfe, 0x83, 0x27, 0xfd, 0x99, 0x44, 0xc2, 0xf7, 0x75, 0x3a, 0x01, 0x77, 0x8c, 0xad, 0xf0, 0xde, 0x5c, 0x08, 0x4c, 0xc4, 0x7f, 0xa4, 0x43, 0x9c, 0x19, 0x4e, 0x64, 0x26, 0xe9, 0x66, 0xff, 0x58, 0xf1, 0x78, 0x82, 0x53, 0x46, 0xa0, 0xa2, 0x6f, 0xda, 0x50, 0x83, 0xd4, 0x99, 0xac, 0xa1, 0x0d, 0x1c, 0x0f, 0xb2, 0x57, 0x26, 0xf6, 0x39, 0x07, 0xa1, 0xdd, 0x51, 0x6a, 0x50, 0x83, 0x2d, 0x3c, 0xe6, 0x6d, 0x78, 0xaf, 0x6d, 0xe0, 0xcd, 0xef, 0xd2, 0xd3, 0xbd, 0xff, 0xbd, 0x6b, 0xdd, 0x13, 0x4d, 0x95, 0x79, 0xdd, 0x22, 0x18, 0x92, 0x26, 0x60, 0x81, 0xcd, 0x1e, 0xee, 0x92, 0x5d, 0xac, 0x1c, 0xa5, 0xb8, 0xa1, 0x92, 0x8c, 0xe9, 0x79, 0xbe, 0x58, 0x1f, 0xb0, 0x98, 0x11, 0x0c, 0xa4, 0x51, 0x0e, 0xa5, 0xe8, 0x61, 0x95, 0xbd, 0x36, 0x5d, 0xa1, 0x6a, 0x95, 0x0d, 0x2b, 0xbd, 0x81, 0x9a, 0xed, 0x03, 0x9e, 0xdb, 0x41, 0x47, 0xb4, 0x06, 0x20, 0x1b, 0xce, 0x2f, 0xa0, 0xaf, 0x7d, 0xa8, 0x51, 0xbe, 0x7e, 0x16, 0xa7, 0x13, 0xda, 0xa6, 0xcf, 0x3e, 0xa7, 0x05, 0x9f, 0xd3, 0xeb, 0xb1, 0xcf, 0x69, 0x51, 0x18, 0x54, 0x37, 0xc6, 0x03, 0x1a, 0xde, 0x77, 0x26, 0x0a, 0x1e, 0x83, 0xed, 0x5d, 0xe5, 0xf3, 0x41, 0x05, 0x9a, 0xcb, 0x7b, 0xea, 0x4f, 0x45, 0x25, 0x5f, 0x91, 0xa5, 0x51, 0xe7, 0xdb, 0xd2, 0xbc, 0xc5, 0x90, 0xf2, 0x8b, 0x94, 0x7c, 0xf0, 0x51, 0x3b, 0x7f, 0xe4, 0x80, 0x81, 0xcb, 0x11, 0x25, 0xc1, 0x79, 0xc5, 0x64, 0xe4, 0x96, 0xef, 0x74, 0x1f, 0x58, 0x28, 0xdf, 0xe5, 0x12, 0x1c, 0x3a, 0xc7, 0xea, 0x06, 0xbf, 0xb1, 0x65, 0x0c, 0xfa, 0x7d, 0xf9, 0x2e, 0xf0, 0x77, 0x6a, 0xf0, 0x1d, 0x6e, 0x53, 0x15, 0x8e, 0xa2, 0xf3, 0x8b, 0x1e, 0x6c, 0x2d, 0xaa, 0xde, 0xff, 0xca, 0xad, 0xd2, 0x20, 0x90, 0x19, 0x12, 0x7a, 0x86, 0x35, 0x61, 0xb8, 0xbc, 0x30, 0x44, 0xe5, 0x16, 0xac, 0x0a, 0x55, 0xdd, 0xa8, 0x0d, 0xce, 0xed, 0x3a, 0xcd, 0xf5, 0x1d, 0xd2, 0x24, 0x3e, 0xe6, 0x36, 0xb0, 0x70, 0x77, 0xea, 0x7c, 0xcc, 0xd5, 0x3a, 0xc7, 0x22, 0x2e, 0xfe, 0x65, 0x85, 0x7f, 0xe2, 0xfb, 0x0d, 0xf7, 0xa7, 0xa3, 0xb7, 0x5f, 0xf7, 0x6c, 0xf3, 0x7d, 0x2e, 0x4d, 0xa3, 0x99, 0x94, 0x4b, 0x24, 0x7b, 0xb8, 0xf2, 0x55, 0x93, 0xc6, 0xfe, 0xc4, 0x6d, 0x20, 0xe8, 0x01, 0x7d, 0x3a, 0x68, 0xb5, 0x53, 0x48, 0x15, 0x36, 0x14, 0xe4, 0xc2, 0x16, 0xba, 0x55, 0xa4, 0x1b, 0xf4, 0x0c, 0x43, 0x26, 0xfc, 0x43, 0x13, 0x42, 0xaf, 0x9a, 0x24, 0xa8, 0xe9, 0xa4, 0xe0, 0xa8, 0xe0, 0xd2, 0x84, 0x37, 0xf6, 0x99, 0x16, 0x69, 0xbc, 0x19, 0x31, 0x51, 0x76, 0x7d, 0x1a, 0x4a, 0x55, 0x9d, 0x9f, 0xec, 0x28, 0xf5, 0xe4, 0x30, 0x45, 0xef, 0x5a, 0xfa, 0x7a, 0x04, 0x55, 0x2f, 0x47, 0x59, 0x1b, 0x16, 0xe6, 0xb4, 0xd3, 0x8a, 0x17, 0x2a, 0xf5, 0xa3, 0x09, 0x98, 0x80, 0x64, 0x62, 0xe8, 0xf3, 0x06, 0x7a, 0x09, 0x1f, 0x07, 0x8c, 0xf3, 0x8d, 0x34, 0x49, 0x81, 0x51, 0x8f, 0xca, 0xf6, 0x26, 0xc0, 0xbd, 0xe9, 0x59, 0x87, 0xab, 0x90, 0x7b, 0x55, 0x85, 0xdc, 0xb7, 0x2e, 0x0f, 0x5f, 0x98, 0xa5, 0xbc, 0xd1, 0x87, 0x36, 0x9d, 0xc0, 0x46, 0x87, 0x8c, 0xa5, 0x4f, 0x6f, 0x78, 0xa7, 0x62, 0xbc, 0xb3, 0x3a, 0x8a, 0xd3, 0x28, 0x66, 0x59, 0x27, 0x4f, 0x6e, 0xeb, 0xd4, 0xd3, 0xbc, 0x16, 0x9c, 0xfd, 0xd3, 0x8e, 0x2a, 0x6a, 0x9c, 0x21, 0x85, 0x35, 0x1f, 0x60, 0x44, 0xab, 0x03, 0xf8, 0x2b, 0xc4, 0xa4, 0x65, 0x72, 0x32, 0xd2, 0x35, 0xad, 0x21, 0x65, 0xd3, 0x71, 0x55, 0x5c, 0x4a, 0xc4, 0x46, 0x16, 0x1a, 0xd0, 0x06, 0xb1, 0x66, 0x36, 0x62, 0xef, 0xc2, 0x96, 0x2d, 0x4b, 0x36, 0xba, 0xab, 0xfc, 0xdf, 0xce, 0xd5, 0x72, 0x22, 0x15, 0x92, 0xe2, 0x34, 0x1d, 0xd2, 0x77, 0x05, 0x79, 0xff, 0x4b, 0xb4, 0x81, 0x15, 0xb1, 0x53, 0xea, 0xca, 0x13, 0x69, 0x96, 0x46, 0xbc, 0x7f, 0x82, 0x5b, 0xeb, 0xa7, 0xc6, 0xa9, 0xa4, 0x05, 0x82, 0xd0, 0x70, 0xb1, 0x2b, 0xb5, 0xba, 0x88, 0xef, 0x8c, 0x3d, 0x44, 0x0b, 0x86, 0x43, 0x60, 0xbc, 0xce, 0x30, 0xba, 0x13, 0x21, 0x87, 0xc8, 0x59, 0x85, 0x10, 0x57, 0xc0, 0xa6, 0x4a, 0x2c, 0x98, 0xee, 0x17, 0x9c, 0xac, 0xc9, 0x4a, 0x3b, 0x0d, 0x49, 0xc7, 0x52, 0xd4, 0x9c, 0x5f, 0x5c, 0xf3, 0xc6, 0xb8, 0xfb, 0xaa, 0x14, 0xf4, 0x98, 0xdb, 0x6c, 0xd2, 0x2b, 0x6c, 0xba, 0x42, 0xaa, 0x35, 0x62, 0x22, 0x2f, 0x8e, 0xb4, 0xcb, 0x2e, 0x24, 0xbd, 0x3b, 0x0b, 0x61, 0xae, 0xaf, 0xa3, 0xbe, 0x73, 0x4f, 0xaf, 0xac, 0xf0, 0xeb, 0x5f, 0x5a, 0xd4, 0x9a, 0x31, 0xed, 0xdc, 0xa2, 0xef, 0x5d, 0x14, 0x61, 0x11, 0x0c, 0x98, 0x76, 0x81, 0x0a, 0x13, 0x2a, 0x82, 0x25, 0x38, 0x04, 0xa5, 0x4b, 0x26, 0xa6, 0x43, 0xe6, 0x34, 0x8c, 0xb9, 0xe8, 0x0c, 0xf5, 0x25, 0xbc, 0xba, 0x47, 0x80, 0x69, 0x60, 0xe4, 0xe0, 0xb2, 0xea, 0x99, 0xc6, 0xaa, 0xa6, 0x7b, 0xba, 0x78, 0x33, 0x28, 0x7c, 0x41, 0x36, 0x21, 0xb9, 0x81, 0x90, 0xc1, 0xad, 0x1d, 0x86, 0x11, 0xe2, 0x0b, 0x53, 0x2e, 0xef, 0xb5, 0x0d, 0xac, 0x92, 0x5d, 0x7a, 0xc6, 0x5f, 0x4c, 0x18, 0xe6, 0x6e, 0x40, 0x4f, 0x0f, 0xb7, 0x09, 0xff, 0xd6, 0xd8, 0x84, 0x4a, 0x29, 0xc0, 0xf5, 0x21, 0x55, 0xa2, 0xb5, 0x44, 0x29, 0xbf, 0xbd, 0x62, 0x4f, 0x66, 0x66, 0x44, 0xe8, 0xf0, 0x40, 0x89, 0x0f, 0xbc, 0xff, 0xe0, 0x0b, 0x60, 0x8e, 0xc6, 0xa4, 0xe8, 0xf4, 0x72, 0x4a, 0x39, 0xc0, 0xfa, 0x11, 0xaa, 0xb5, 0x88, 0xf5, 0xf4, 0x6a, 0x98, 0xb2, 0x45, 0xfc, 0x42, 0xdb, 0x6d, 0xae, 0xd4, 0x42, 0xd5, 0xef, 0x9e, 0x86, 0xed, 0x0c, 0x7a, 0xd8, 0x78, 0xb2, 0x65, 0xfc, 0x42, 0x10, 0x0e, 0xb0, 0x18, 0x76, 0xca, 0x5c, 0xa9, 0x93, 0x2e, 0x50, 0xc4, 0x92, 0xd3, 0xb2, 0x7e, 0x4c, 0x4e, 0x40, 0x8c, 0x87, 0xa7, 0x68, 0x24, 0x56, 0x33, 0xae, 0xd1, 0xc8, 0x73, 0xe4, 0xf2, 0x3b, 0x78, 0xde, 0x85, 0x6b, 0xd2, 0xaf, 0x67, 0xa1, 0x2f, 0xc5, 0xc0, 0xa2, 0xde, 0x4b, 0x29, 0x39, 0x17, 0xe7, 0xa0, 0x1d, 0x93, 0x9d, 0x71, 0x62, 0x88, 0xa5, 0xec, 0x15, 0xe2, 0x1b, 0xa5, 0xc2, 0x14, 0xc8, 0x1a, 0x8d, 0x71, 0x0e, 0x06, 0x27, 0x49, 0x4c, 0x0f, 0x39, 0x68, 0x74, 0xb1, 0x68, 0x6c, 0xaa, 0xa9, 0x09, 0xe6, 0x7a, 0x31, 0x8b, 0x6a, 0xe4, 0xcc, 0xdb, 0x21, 0xac, 0x89, 0x68, 0xd5, 0x68, 0x08, 0xa4, 0x1b, 0xb5, 0xb9, 0xca, 0x70, 0xa0, 0x06, 0x36, 0x93, 0xb1, 0x52, 0x14, 0x11, 0x47, 0x37, 0x85, 0x98, 0xd6, 0x10, 0x5d, 0xad, 0xe5, 0xb4, 0x19, 0xd7, 0x5f, 0xe8, 0xf0, 0x4a, 0x47, 0x87, 0xbc, 0xb1, 0xc3, 0xdb, 0xe1, 0x74, 0x10, 0x60, 0x86, 0x0b, 0x3c, 0x82, 0x1f, 0xdd, 0x0b, 0x75, 0xef, 0x46, 0x8f, 0x80, 0xf3, 0x5f, 0xc0, 0x3c, 0x8e, 0xcc, 0x9b, 0xc0, 0x44, 0xa7, 0x83, 0x66, 0x90, 0xa7, 0x42, 0xf3, 0x8b, 0xd4, 0x64, 0x21, 0x7c, 0xd2, 0xca, 0x72, 0x87, 0x7b, 0x28, 0x75, 0x8d, 0x6f, 0xdb, 0xcc, 0xbe, 0x1b, 0x37, 0x4c, 0xeb, 0xae, 0x38, 0xe1, 0x4f, 0x94, 0x7a, 0x99, 0x8a, 0x2e, 0xa0, 0xb1, 0x68, 0x47, 0x7d, 0xeb, 0xd5, 0x20, 0x36, 0x5c, 0xf6, 0x39, 0x3d, 0x2a, 0xa9, 0x3a, 0x65, 0x9b, 0x73, 0x2d, 0x25, 0x4d, 0xa7, 0x1d, 0xac, 0x8a, 0xe2, 0x5e, 0x2a, 0xc3, 0x20, 0xd3, 0xfd, 0x42, 0x11, 0xb6, 0x02, 0xcc, 0x2f, 0xbb, 0x59, 0x19, 0xa9, 0xd3, 0xe8, 0x7d, 0x85, 0xe0, 0x57, 0x20, 0x8c, 0x0f, 0xed, 0x6a, 0x58, 0xee, 0xa9, 0x7b, 0x97, 0x9b, 0x8c, 0xd7, 0x1c, 0xe4, 0xed, 0x13, 0xb4, 0x57, 0x15, 0x98, 0x9a, 0x91, 0xf1, 0x1d, 0xa0, 0xcc, 0xca, 0x22, 0xbe, 0x36, 0x59, 0x8a, 0x73, 0xb4, 0xc7, 0xd4, 0x3c, 0xc7, 0x82, 0xea, 0xad, 0x25, 0x5f, 0xad, 0x8c, 0x37, 0xed, 0x41, 0x86, 0x5c, 0xe3, 0xa4, 0x4a, 0x84, 0x41, 0xe9, 0x0b, 0x49, 0x51, 0x19, 0x15, 0xc9, 0x98, 0x91, 0xea, 0x6d, 0x24, 0x52, 0x3f, 0xc4, 0x5a, 0x17, 0x71, 0x5d, 0x17, 0xf7, 0xba, 0x1e, 0x2e, 0xdb, 0xbd, 0x1f, 0x81, 0x2e, 0xec, 0xc2, 0xba, 0x77, 0x95, 0x6d, 0x3b, 0xc8, 0x21, 0xaf, 0xef, 0xba, 0x85, 0x94, 0x9b, 0x27, 0xb7, 0x01, 0x7f, 0x6b, 0xa9, 0x1f, 0x7d, 0x86, 0x83, 0xf3, 0xf2, 0xea, 0x2c, 0x87, 0xd4, 0x07, 0xdb, 0x02, 0x00, 0xe0, 0x07, 0x90, 0x0b, 0x14, 0x19, 0xc4, 0x1c, 0x06, 0xa8, 0x22, 0xa3, 0x5c, 0x4e, 0x97, 0x16, 0x9d, 0x75, 0xa5, 0x42, 0x26, 0x65, 0x12, 0xe7, 0x64, 0x68, 0xba, 0x12, 0xf3, 0x33, 0x03, 0x69, 0x00, 0xfa, 0x50, 0x52, 0x82, 0x8b, 0x55, 0x0f, 0x1a, 0x4c, 0xc0, 0x94, 0x3a, 0x5b, 0xaa, 0x2e, 0x1d, 0x44, 0xd2, 0x46, 0x3c, 0x56, 0x35, 0xc7, 0x34, 0x53, 0x2c, 0x2f, 0x68, 0x7c, 0xba, 0xca, 0x97, 0x8c, 0xe3, 0x03, 0xe7, 0x66, 0x07, 0xa8, 0x89, 0x18, 0x38, 0x33, 0x97, 0xec, 0x77, 0x77, 0xf0, 0xa4, 0x47, 0x28, 0x24, 0x7d, 0x3f, 0x30, 0x38, 0x1a, 0x9c, 0x7e, 0x6d, 0x9b, 0xde, 0x4b, 0x3d, 0x2f, 0x4b, 0x49, 0x4f, 0xe8, 0xf9, 0xe1, 0x9c, 0xf1, 0x70, 0x9e, 0x93, 0x3e, 0x2e, 0x13, 0xaa, 0xbf, 0xad, 0x4b, 0xfa, 0x90, 0x57, 0x0a, 0xad, 0xf2, 0x42, 0xbf, 0xa0, 0x8c, 0x8f, 0xbf, 0x57, 0xe3, 0x72, 0x26, 0x73, 0x5c, 0x75, 0x6b, 0x41, 0xde, 0x7e, 0x16, 0x36, 0x30, 0x46, 0xb7, 0x5e, 0x69, 0xfa, 0x49, 0xcd, 0xcb, 0xd4, 0x4e, 0x3b, 0xc0, 0x54, 0x77, 0x14, 0xba, 0x07, 0x4b, 0xa8, 0xc0, 0xa6, 0x5d, 0x11, 0xad, 0xad, 0xc0, 0xaa, 0xfe, 0xea, 0x21, 0x01, 0xd3, 0x44, 0x99, 0x99, 0xca, 0xd3, 0xf0, 0xfc, 0xbe, 0x77, 0x49, 0xc9, 0xbb, 0xd3, 0xa8, 0x9b, 0xb9, 0x20, 0x63, 0x02, 0x56, 0xd8, 0x93, 0xd3, 0x2f, 0xfe, 0x68, 0x33, 0x6f, 0xd3, 0xb9, 0x62, 0x28, 0x23, 0x8a, 0x16, 0x7a, 0x17, 0x9c, 0xa2, 0x4c, 0x7f, 0x21, 0x42, 0x2b, 0x14, 0x3d, 0xdb, 0x86, 0x15, 0xb0, 0x23, 0x06, 0xba, 0x5d, 0xce, 0x4c, 0x24, 0x2e, 0x11, 0x76, 0x3e, 0xd8, 0xc3, 0x98, 0x2d, 0x45, 0x31, 0x0b, 0x05, 0xa1, 0x39, 0x15, 0x5d, 0x0a, 0xe6, 0x38, 0xd5, 0x65, 0xc1, 0x2b, 0x8e, 0x94, 0xcf, 0xbd, 0xe5, 0x6a, 0x2c, 0x7e, 0x09, 0x54, 0x52, 0x0d, 0x0c, 0xb4, 0x36, 0xb1, 0x6b, 0xfa, 0x35, 0x43, 0xcc, 0x0f, 0xa3, 0x3e, 0x4e, 0xa8, 0x35, 0x84, 0xc7, 0xd6, 0x0a, 0xe0, 0xc3, 0x6f, 0x9f, 0x8d, 0xe1, 0x71, 0x75, 0x1b, 0x58, 0x31, 0x3b, 0x1b, 0xd1, 0x1a, 0x58, 0xca, 0x4e, 0x3c, 0x6f, 0xbb, 0x12, 0xb1, 0xc6, 0xd3, 0xdb, 0x7e, 0x3f, 0x54, 0x69, 0xb3, 0x0b, 0x27, 0xd3, 0x2d, 0xe7, 0x15, 0x30, 0xab, 0x3f, 0xa7, 0x58, 0x0c, 0xff, 0x85, 0x07, 0xf9, 0x02, 0xfe, 0xb7, 0x63, 0xf4, 0x75, 0x2e, 0x6c, 0x6a, 0xdc, 0xda, 0xa0, 0xc0, 0xa0, 0x52, 0x49, 0x05, 0x69, 0xae, 0x30, 0x09, 0x51, 0x33, 0xbc, 0xb1, 0x20, 0xa7, 0x63, 0x0e, 0x14, 0xa0, 0x34, 0xd0, 0x2c, 0x2d, 0xa4, 0x25, 0x7e, 0x24, 0xd2, 0x67, 0x69, 0x6b, 0xba, 0x9e, 0xa5, 0x07, 0x38, 0x80, 0x48, 0x8a, 0xd0, 0xc6, 0x35, 0xa5, 0x82, 0xb4, 0x65, 0xf7, 0x15, 0x55, 0xb2, 0x43, 0x54, 0xd8, 0x02, 0x13, 0xeb, 0x0a, 0x73, 0x1e, 0x06, 0xc8, 0xd5, 0xf1, 0xc0, 0x27, 0x26, 0x98, 0x95, 0xa8, 0xe8, 0xe3, 0x37, 0xc4, 0x24, 0x11, 0x7b, 0x8a, 0x28, 0x47, 0x7c, 0x4c, 0x03, 0x8e, 0x14, 0x9a, 0x3f, 0xa7, 0x6a, 0x09, 0xe6, 0xc7, 0xe1, 0x89, 0x46, 0xa2, 0x57, 0xb1, 0x4c, 0x83, 0x42, 0x5c, 0x53, 0xb6, 0x50, 0x12, 0x31, 0xc3, 0x3f, 0xba, 0x74, 0x07, 0x45, 0xfb, 0x32, 0x94, 0xbb, 0xf3, 0x82, 0xdd, 0xb8, 0xc1, 0x40, 0x3e, 0xd9, 0xa8, 0x5f, 0xc9, 0x04, 0x49, 0x07, 0x6d, 0xfb, 0xd2, 0x83, 0x84, 0x10, 0x1a, 0xf6, 0x99, 0x2b, 0x07, 0x62, 0x8e, 0xda, 0x42, 0xb5, 0xa6, 0x55, 0xee, 0x8f, 0x55, 0xb9, 0xa0, 0xc3, 0x0e, 0x66, 0x8a, 0x91, 0x10, 0xf9, 0x89, 0xed, 0xb3, 0xfb, 0x92, 0x8a, 0x49, 0x48, 0xaa, 0x28, 0x5f, 0x11, 0x77, 0xd5, 0x04, 0x85, 0xbc, 0x1c, 0xef, 0xc2, 0x2f, 0x82, 0xc6, 0x09, 0x55, 0xfd, 0xe2, 0x6d, 0xc1, 0xcf, 0x4e, 0xbb, 0xc2, 0x9b, 0x63, 0xf8, 0x68, 0x01, 0xf8, 0x7d, 0x5e, 0xe3, 0xf0, 0x12, 0x45, 0xfb, 0x89, 0x56, 0x53, 0x84, 0x2e, 0x85, 0x51, 0x83, 0x0c, 0xd8, 0x05, 0x8b, 0x02, 0xf5, 0x86, 0x49, 0x9e, 0x04, 0xae, 0x2e, 0xe4, 0x59, 0x7b, 0x71, 0x45, 0x41, 0x03, 0x35, 0xe5, 0x1a, 0x89, 0x18, 0xaf, 0x4d, 0xff, 0xce, 0x80, 0x11, 0x4b, 0x6e, 0x9a, 0x2e, 0xb0, 0x27, 0x7d, 0xb8, 0xf4, 0xb9, 0xfa, 0xdf, 0x99, 0x2a, 0x56, 0x38, 0x05, 0xc8, 0xa8, 0x37, 0xe5, 0x70, 0x70, 0x9d, 0x3c, 0x1b, 0xb3, 0xbc, 0x24, 0xef, 0x75, 0xcd, 0xd8, 0x02, 0x2a, 0x05, 0x87, 0xd5, 0xdd, 0x90, 0x55, 0x25, 0xa6, 0xcd, 0xea, 0xb8, 0x60, 0x1e, 0x18, 0xe6, 0x21, 0x13, 0x12, 0x49, 0xca, 0xde, 0xf6, 0x25, 0x90, 0x42, 0x9d, 0xe4, 0xd5, 0x81, 0xa9, 0x3f, 0x11, 0xf9, 0xd6, 0xf1, 0x0a, 0x83, 0x49, 0x20, 0x94, 0x99, 0x9d, 0x73, 0x35, 0x08, 0x3d, 0x50, 0x8a, 0x71, 0x22, 0x9f, 0x33, 0x99, 0xfe, 0x18, 0x88, 0x41, 0x55, 0x05, 0xc5, 0x89, 0xe2, 0x34, 0x96, 0x91, 0xe1, 0xae, 0x7b, 0x12, 0x27, 0x8a, 0xe6, 0x30, 0x89, 0x92, 0xcd, 0xf2, 0x02, 0x65, 0x28, 0xf3, 0x8c, 0x51, 0xaf, 0xe0, 0x1f, 0x58, 0x32, 0xdf, 0x7d, 0x6b, 0x7d, 0xde, 0xd9, 0x01, 0x49, 0xf8, 0xab, 0xb2, 0x18, 0xb8, 0x64, 0x0a, 0x6c, 0x1d, 0xc8, 0x4a, 0x0a, 0x71, 0x01, 0x6c, 0x25, 0x5d, 0x15, 0x6c, 0x75, 0xf5, 0x49, 0x5a, 0x45, 0x9c, 0x41, 0xea, 0xd0, 0xbe, 0x19, 0x4d, 0x99, 0x76, 0x55, 0x4b, 0x21, 0xc8, 0xdc, 0x89, 0x91, 0x4a, 0xac, 0x02, 0x03, 0x36, 0xc3, 0x3b, 0xe1, 0x44, 0xc1, 0x68, 0x5a, 0x52, 0x3d, 0xb9, 0x54, 0xb8, 0x66, 0x78, 0x34, 0x14, 0x7c, 0x1a, 0x50, 0x2a, 0x92, 0x73, 0xc8, 0x23, 0xd9, 0xa1, 0x25, 0x45, 0x57, 0xef, 0x33, 0x45, 0x20, 0xe2, 0x5f, 0x2c, 0x02, 0xd8, 0x32, 0xa9, 0x60, 0xe8, 0xa4, 0xa3, 0xe4, 0x63, 0x4b, 0xac, 0xe4, 0xe0, 0xd5, 0xc1, 0x6c, 0x27, 0x83, 0xf9, 0x47, 0x54, 0x1d, 0x96, 0xa9, 0x0a, 0xa4, 0x87, 0x65, 0x6e, 0xb8, 0x5e, 0x23, 0xf8, 0x93, 0x98, 0x92, 0x91, 0x99, 0x00, 0xd9, 0x8b, 0xe4, 0x0e, 0xe5, 0x24, 0x56, 0xec, 0x9e, 0xd2, 0x86, 0x17, 0xa1, 0x8f, 0x94, 0x6d, 0x68, 0x0b, 0xab, 0x00, 0x93, 0x89, 0xb5, 0x95, 0xe8, 0xaa, 0xef, 0xe6, 0xb0, 0xf4, 0xb0, 0x37, 0x9f, 0xb7, 0x8c, 0xf9, 0xa3, 0x6b, 0x03, 0x2b, 0x76, 0x67, 0xc5, 0x85, 0x30, 0xb8, 0xa9, 0xbc, 0xde, 0x97, 0x9a, 0x35, 0xfe, 0x29, 0xaa, 0xd1, 0xed, 0x20, 0x3d, 0x2a, 0x9d, 0xb7, 0x9c, 0x6b, 0x9f, 0xeb, 0x2e, 0x79, 0xc8, 0x4e, 0x44, 0x3f, 0x05, 0x96, 0xd0, 0x92, 0xac, 0x34, 0xc3, 0xf7, 0x8e, 0xbe, 0x5e, 0xa1, 0x37, 0xd7, 0x6b, 0xee, 0xe5, 0x3a, 0x5a, 0x7d, 0xea, 0x61, 0x09, 0x90, 0x8b, 0xcc, 0x59, 0x89, 0xbb, 0x9d, 0xe1, 0x30, 0xbb, 0xda, 0x56, 0xa9, 0x2a, 0x46, 0x94, 0x24, 0x99, 0x1a, 0x54, 0x5c, 0x52, 0x82, 0x62, 0xed, 0x52, 0xe5, 0x5a, 0x60, 0x9f, 0x58, 0x81, 0xcd, 0x7a, 0x8f, 0x95, 0x8c, 0x20, 0x97, 0x3b, 0xf5, 0xa9, 0x99, 0xa1, 0x14, 0xeb, 0xba, 0xf5, 0xec, 0x26, 0x83, 0xc8, 0xc1, 0xb2, 0x6b, 0xab, 0x00, 0x92, 0x28, 0xa3, 0xbe, 0x44, 0x9a, 0x5a, 0xd2, 0x74, 0xcb, 0x2d, 0xb4, 0xdd, 0xd3, 0x72, 0x76, 0x84, 0x54, 0x78, 0x14, 0x2f, 0x59, 0xb1, 0x1b, 0x0f, 0xde, 0xf5, 0x96, 0x26, 0xec, 0xcd, 0x9d, 0xea, 0x7d, 0x10, 0x14, 0x0f, 0x67, 0xf3, 0x90, 0xc8, 0xed, 0x34, 0x56, 0x36, 0x8f, 0x91, 0x4d, 0x53, 0x10, 0x73, 0xce, 0xf7, 0x44, 0xc7, 0xda, 0xd5, 0x72, 0x18, 0xf7, 0xb5, 0x1c, 0xc6, 0xb8, 0xaa, 0x71, 0x9c, 0x37, 0x24, 0x7b, 0x67, 0x8c, 0xf4, 0xdb, 0xcd, 0xe7, 0x8c, 0x97, 0x55, 0xe6, 0xcd, 0x56, 0xcf, 0xe9, 0x69, 0xbb, 0x1a, 0x23, 0x35, 0x2d, 0xd3, 0xd3, 0xa3, 0xd3, 0x75, 0xcb, 0xed, 0x17, 0x74, 0xda, 0x71, 0xeb, 0xc7, 0x20, 0x78, 0xb1, 0x40, 0x03, 0x40, 0xb3, 0x5f, 0x74, 0xbe, 0x09, 0xb2, 0xdf, 0xb8, 0x1a, 0x42, 0x9b, 0xb6, 0xe8, 0xd5, 0x02, 0xb9, 0x8a, 0x1b, 0x00, 0x2f, 0x4f, 0xb8, 0x4e, 0x1b, 0x23, 0x85, 0x9b, 0x2c, 0x67, 0x82, 0xf6, 0x2f, 0x94, 0xd2, 0x03, 0xe8, 0x80, 0xd6, 0xb3, 0x1c, 0x34, 0xe6, 0xb0, 0xad, 0x2a, 0x29, 0xba, 0xce, 0xdc, 0x12, 0x5a, 0xd7, 0x87, 0x6a, 0x52, 0xe8, 0x25, 0xef, 0xec, 0xa1, 0xda, 0xe0, 0x79, 0x01, 0xfb, 0x85, 0x08, 0x8d, 0x49, 0xf1, 0x1b, 0x21, 0xaa, 0xab, 0x27, 0x43, 0x88, 0xa5, 0xb8, 0xcb, 0x0f, 0x88, 0x07, 0xb8, 0xa3, 0x84, 0xb4, 0xaa, 0x08, 0x32, 0x4f, 0x10, 0x68, 0xf8, 0x43, 0x35, 0xd2, 0x4f, 0x95, 0xbe, 0x38, 0xee, 0x55, 0x00, 0xad, 0xab, 0xb0, 0x36, 0x0d, 0x9e, 0xb3, 0xc2, 0x62, 0x16, 0x89, 0xcd, 0xda, 0x0f, 0x03, 0xd0, 0x4c, 0x13, 0xcd, 0x56, 0x69, 0x47, 0x3c, 0xd9, 0x58, 0x49, 0x3e, 0xdb, 0x06, 0x2a, 0x3b, 0xf1, 0xaa, 0x22, 0xa5, 0xae, 0xb8, 0xd4, 0x27, 0x02, 0xa5, 0x93, 0x8e, 0x82, 0x38, 0x18, 0x9a, 0x70, 0x35, 0x55, 0xad, 0x65, 0x39, 0x2b, 0x62, 0x63, 0xc2, 0x71, 0xc1, 0x7f, 0x75, 0xfa, 0xd4, 0xde, 0xc4, 0xac, 0x84, 0xd4, 0x63, 0xce, 0x77, 0x78, 0xee, 0x5f, 0xbb, 0x7d, 0x95, 0x6c, 0x3e, 0x2b, 0xd9, 0x7a, 0x56, 0xb0, 0xb8, 0x76, 0xda, 0x65, 0x55, 0xc3, 0x8d, 0x75, 0x8d, 0x0a, 0x1b, 0xdd, 0x44, 0xd9, 0x58, 0x04, 0xe4, 0xa4, 0xcb, 0xbe, 0x96, 0xdb, 0xc1, 0xb1, 0x59, 0xf5, 0xe7, 0xd4, 0x75, 0x0d, 0xaa, 0xe0, 0x42, 0xed, 0xef, 0x9c, 0x02, 0x61, 0x69, 0x55, 0xcc, 0xb6, 0xcb, 0xd4, 0xbf, 0xd1, 0x94, 0xf8, 0x94, 0x98, 0x5b, 0x7b, 0xca, 0xd7, 0x4a, 0x80, 0x37, 0x2d, 0x46, 0x53, 0xf6, 0x3b, 0x04, 0x12, 0xce, 0x99, 0x76, 0xa9, 0xaf, 0xfa, 0x04, 0xb5, 0x96, 0xbb, 0x82, 0x57, 0x58, 0x21, 0x1c, 0x72, 0x65, 0xef, 0x9d, 0x94, 0x3b, 0xa9, 0x8e, 0xe8, 0x74, 0xad, 0xe1, 0x92, 0xe1, 0xff, 0x0d, 0xbd, 0xc6, 0xce, 0x72, 0x59, 0xe4, 0x4f, 0xc8, 0x76, 0xe4, 0xb1, 0xc2, 0x30, 0x65, 0x7f, 0xed, 0x72, 0x48, 0x9e, 0xbe, 0xcc, 0x41, 0x03, 0xc2, 0x20, 0x1b, 0x72, 0xac, 0x07, 0x02, 0x21, 0xbb, 0xc2, 0xd2, 0x8f, 0x0e, 0x44, 0x42, 0x2e, 0x77, 0x9c, 0x11, 0xce, 0xf8, 0x63, 0xc7, 0x88, 0x67, 0xca, 0xe3, 0xc3, 0x02, 0x08, 0xcc, 0xc3, 0x08, 0xbe, 0x38, 0xa2, 0xc4, 0x37, 0xec, 0x7d, 0xc2, 0x83, 0x4b, 0x22, 0x61, 0x8f, 0x2f, 0xc1, 0x44, 0x47, 0x3d, 0x51, 0xc4, 0x01, 0x3a, 0xd3, 0x64, 0x71, 0x79, 0xa6, 0xf5, 0x47, 0xe2, 0x5f, 0xa4, 0xf8, 0x09, 0x84, 0x48, 0x66, 0x5c, 0xf3, 0xa0, 0x96, 0x83, 0xb2, 0x3c, 0x9b, 0x1c, 0xc9, 0x90, 0x7c, 0x48, 0x22, 0x06, 0xdb, 0x65, 0x02, 0x7e, 0xc6, 0x39, 0xc7, 0x17, 0x1d, 0x73, 0x56, 0xd0, 0x0d, 0x70, 0x0b, 0x97, 0xeb, 0x2f, 0x28, 0xb4, 0xcc, 0x8e, 0xb9, 0x10, 0x60, 0xa1, 0x98, 0x1c, 0x79, 0xf5, 0x72, 0x19, 0x04, 0x80, 0xa2, 0xe0, 0x1d, 0xc1, 0xaf, 0x58, 0x75, 0xc0, 0xd3, 0xb8, 0x34, 0x27, 0xc7, 0x19, 0xbd, 0x70, 0x0b, 0x96, 0x9d, 0x4d, 0x1a, 0x32, 0x35, 0xe8, 0xe8, 0xae, 0x16, 0x78, 0x57, 0x32, 0x50, 0xfd, 0xc7, 0xb9, 0x39, 0x46, 0x8b, 0xa0, 0xba, 0x02, 0x72, 0x98, 0x16, 0xa1, 0x4a, 0x92, 0x80, 0xdb, 0x40, 0x97, 0x43, 0x8f, 0x00, 0x8e, 0x09, 0x81, 0x5e, 0x24, 0x1b, 0xd9, 0xaf, 0x8a, 0x65, 0xcc, 0x81, 0x9b, 0x0b, 0x19, 0xde, 0xe1, 0xd5, 0x47, 0x7c, 0x51, 0xda, 0x75, 0x51, 0xe6, 0x67, 0x8c, 0xb0, 0x29, 0x38, 0xe2, 0x8f, 0x71, 0x8b, 0x2b, 0xc3, 0xa7, 0xab, 0x7c, 0x59, 0xe4, 0x11, 0x90, 0x55, 0xe8, 0x1c, 0xc5, 0x17, 0x85, 0x8e, 0x5b, 0xa0, 0xc8, 0x63, 0xce, 0x5d, 0x19, 0x69, 0x61, 0x20, 0x62, 0x07, 0x89, 0x09, 0x34, 0x0f, 0x22, 0xa1, 0x34, 0x07, 0xb2, 0x63, 0x5b, 0xc0, 0x93, 0x47, 0x7a, 0x33, 0xf8, 0x25, 0x12, 0xf5, 0x42, 0xc8, 0x25, 0xfd, 0x88, 0x78, 0x78, 0x19, 0x69, 0x32, 0xd8, 0x21, 0x54, 0x6d, 0x40, 0xcf, 0x2e, 0x16, 0x14, 0x8b, 0xf0, 0x66, 0x15, 0xce, 0x8d, 0x87, 0x83, 0x2c, 0x35, 0x72, 0xd4, 0xc2, 0x44, 0xfd, 0x96, 0x21, 0xea, 0x34, 0x72, 0x9a, 0x07, 0x4c, 0xd2, 0xe4, 0x1e, 0x91, 0x12, 0x58, 0xe1, 0x9d, 0xe1, 0x0f, 0x1e, 0xbd, 0xc4, 0x31, 0xbf, 0x1c, 0x20, 0x4b, 0xcb, 0xab, 0x8c, 0x36, 0x4c, 0xda, 0xb9, 0xb5, 0xf8, 0x42, 0xab, 0x6a, 0x00, 0x6f, 0xd8, 0x89, 0xcb, 0xc1, 0xfb, 0xb2, 0x0f, 0x33, 0xed, 0x4b, 0xd5, 0xad, 0xd0, 0xa8, 0x0c, 0xdd, 0x2f, 0x83, 0xa9, 0x95, 0x1f, 0xdb, 0x6a, 0x6f, 0xac, 0xf5, 0x54, 0xa1, 0x49, 0x33, 0xed, 0x2e, 0xcc, 0x9a, 0x2e, 0xee, 0xf5, 0x5c, 0x05, 0x91, 0xbb, 0x73, 0x8a, 0xab, 0x47, 0xc3, 0xbb, 0x02, 0x71, 0x22, 0x08, 0x15, 0x26, 0x41, 0x49, 0x86, 0xd2, 0x84, 0x97, 0xf1, 0x04, 0xc1, 0x56, 0x1c, 0x83, 0xc7, 0x29, 0x43, 0x02, 0xf6, 0x3f, 0x9d, 0x9a, 0x62, 0x7e, 0x6c, 0xea, 0x76, 0x63, 0x41, 0xb2, 0x09, 0xb3, 0x42, 0x38, 0x3e, 0x68, 0x2c, 0x97, 0x40, 0x9b, 0x76, 0x35, 0x66, 0x42, 0xdf, 0x4d, 0x7d, 0x05, 0xfb, 0xaf, 0xd5, 0x9e, 0x6d, 0xd7, 0xbc, 0x1a, 0x4f, 0xb0, 0xa9, 0x17, 0x77, 0x63, 0x89, 0x28, 0xad, 0xea, 0x23, 0xa9, 0x0f, 0x36, 0x13, 0xa2, 0x57, 0x1c, 0x15, 0x16, 0xb4, 0x91, 0xf4, 0xaf, 0x98, 0x55, 0x98, 0x4b, 0x4b, 0x9a, 0x01, 0xf8, 0xd3, 0x07, 0x91, 0x7e, 0x59, 0x60, 0x5d, 0xb7, 0x54, 0xaa, 0xbe, 0xce, 0xbb, 0x3e, 0xb8, 0xdc, 0x9c, 0xe6, 0x76, 0xaf, 0x11, 0xcc, 0x17, 0x56, 0xf8, 0x15, 0xc1, 0xaa, 0x20, 0x0e, 0xc3, 0x02, 0x75, 0xf7, 0x40, 0xf0, 0xe4, 0x5b, 0x55, 0xd6, 0xa6, 0xbd, 0xcc, 0xb6, 0xa5, 0xec, 0x0f, 0xf3, 0x85, 0x6e, 0x70, 0x88, 0xaa, 0x1f, 0xef, 0x4e, 0x48, 0xe4, 0xde, 0x54, 0x89, 0x9d, 0x93, 0xf0, 0x0e, 0x7d, 0x25, 0xac, 0x12, 0x4c, 0x0e, 0xfc, 0xc9, 0x15, 0x47, 0x6d, 0xef, 0xda, 0x5d, 0x59, 0xa3, 0x2e, 0x53, 0x4e, 0xce, 0x4f, 0x3a, 0x99, 0x95, 0x97, 0x2e, 0x67, 0x63, 0x11, 0xea, 0x42, 0x0f, 0x86, 0xca, 0x99, 0x84, 0x59, 0xf7, 0x50, 0x86, 0xbf, 0xe8, 0xf8, 0x38, 0xe4, 0x6b, 0x2d, 0x6b, 0x67, 0x9e, 0x7f, 0x1d, 0x61, 0x39, 0x80, 0x72, 0x91, 0xea, 0xb3, 0xb0, 0x97, 0x31, 0x5d, 0x20, 0xb3, 0x3a, 0xd7, 0x33, 0x75, 0xf8, 0x4f, 0x45, 0xd7, 0x2b, 0x89, 0x54, 0x7c, 0x89, 0x2f, 0x13, 0xc1, 0xea, 0x5a, 0x3d, 0x91, 0x23, 0x1c, 0x7a, 0xdc, 0x36, 0x0e, 0x9b, 0x88, 0xf2, 0xf5, 0x41, 0xf7, 0xb4, 0x9a, 0x95, 0x78, 0x3c, 0xc7, 0x74, 0xe6, 0xc2, 0x6d, 0xfe, 0xbc, 0x90, 0x13, 0x4f, 0xe5, 0x11, 0xfa, 0xd3, 0xac, 0x4a, 0x23, 0x69, 0xd7, 0xa0, 0x07, 0xe4, 0x02, 0xfe, 0x40, 0xd6, 0xbd, 0xc9, 0x95, 0x45, 0x8d, 0x27, 0x30, 0xf2, 0x71, 0xe3, 0xbf, 0xc8, 0xd3, 0x1b, 0x96, 0xac, 0x55, 0xab, 0xd6, 0xf5, 0x1c, 0x0e, 0x49, 0xc9, 0x59, 0x98, 0x60, 0xf5, 0x1e, 0x2b, 0x3c, 0x99, 0xcd, 0x2e, 0xfc, 0x2a, 0x8c, 0x05, 0xd6, 0x6d, 0xaa, 0x1e, 0xa6, 0xde, 0x35, 0x4d, 0xbf, 0xb4, 0xcd, 0x76, 0xda, 0x9e, 0x4d, 0x79, 0x27, 0xa7, 0x87, 0x47, 0xcb, 0xf6, 0xab, 0x9c, 0x62, 0xe5, 0x08, 0x9c, 0x9e, 0x61, 0xac, 0x4d, 0xfb, 0xce, 0x06, 0x54, 0x64, 0xd9, 0xa7, 0x50, 0x4e, 0x8f, 0xc5, 0x23, 0x71, 0x0a, 0xf0, 0x3c, 0x20, 0xec, 0x0f, 0xb7, 0x52, 0xad, 0xad, 0x09, 0xa7, 0xf2, 0xc6, 0x4c, 0xa8, 0x9e, 0x9d, 0x32, 0x9c, 0xf4, 0xf8, 0xca, 0x6a, 0xcb, 0xf5, 0x76, 0xaf, 0xa1, 0x6a, 0x68, 0xb0, 0x67, 0xd7, 0x76, 0x34, 0xef, 0xc6, 0x3b, 0x50, 0x5d, 0xdb, 0x87, 0x77, 0xe5, 0xa0, 0x32, 0xd5, 0x83, 0x8a, 0x3a, 0xb1, 0xf3, 0x5e, 0xfc, 0xe0, 0xec, 0x6e, 0xb1, 0x8c, 0xd7, 0xce, 0xd7, 0xe1, 0x63, 0x6f, 0x37, 0x05, 0xf5, 0xdb, 0x82, 0x7c, 0x04, 0x03, 0x82, 0x4b, 0xd9, 0xe4, 0xcf, 0x62, 0x9b, 0x55, 0x82, 0x3b, 0x3f, 0x37, 0x97, 0x37, 0xf3, 0xc9, 0xa3, 0x33, 0xbd, 0xfb, 0xe6, 0x71, 0x29, 0x43, 0x63, 0x13, 0xd7, 0x67, 0x92, 0x1f, 0x7c, 0x53, 0x43, 0xb6, 0x55, 0xe8, 0x16, 0x4c, 0x09, 0xf6, 0x75, 0x95, 0xf8, 0x8d, 0xe5, 0x3e, 0x83, 0x03, 0x35, 0xa8, 0x6b, 0xc9, 0x38, 0x1d, 0xb9, 0x10, 0xcf, 0x70, 0xc1, 0x4f, 0xfc, 0x04, 0x73, 0x5f, 0xa2, 0x65, 0x84, 0x97, 0x42, 0xff, 0x83, 0x09, 0x71, 0xc1, 0x93, 0x57, 0x37, 0x3d, 0xb2, 0x07, 0x62, 0x1a, 0xd5, 0xe4, 0x0a, 0x67, 0xd0, 0x65, 0xf6, 0x6c, 0xd0, 0xd1, 0x29, 0xd1, 0x79, 0x89, 0x99, 0xc1, 0x0a, 0x13, 0x9c, 0x0d, 0x95, 0xa5, 0xe4, 0xa2, 0x8b, 0xee, 0x50, 0xc0, 0x32, 0x90, 0x5a, 0xd8, 0x27, 0xbc, 0x10, 0xb8, 0x86, 0xcb, 0x56, 0xb7, 0x39, 0x1a, 0x1b, 0x94, 0xad, 0x93, 0x03, 0x01, 0xac, 0x5d, 0x42, 0x85, 0xb0, 0x1a, 0xa5, 0x98, 0x89, 0xb7, 0x5a, 0x05, 0xae, 0x15, 0x0e, 0x9d, 0x1f, 0x34, 0x70, 0xb0, 0x4a, 0xe4, 0x78, 0xe0, 0x9a, 0x88, 0xc9, 0xde, 0x96, 0xc9, 0x9c, 0x54, 0x9c, 0xde, 0xb5, 0x10, 0x14, 0x95, 0x51, 0xc6, 0x7a, 0x3c, 0xa7, 0x32, 0xce, 0xc2, 0x51, 0x24, 0xeb, 0x67, 0xd1, 0x5d, 0xd8, 0x65, 0x84, 0xd4, 0x0a, 0xec, 0x80, 0xd6, 0xec, 0x30, 0xc9, 0xec, 0xbe, 0x04, 0xad, 0x72, 0x9c, 0xd8, 0x46, 0x0a, 0x14, 0x14, 0xa2, 0xcb, 0x61, 0x1f, 0xad, 0x21, 0xbd, 0x08, 0x69, 0x98, 0xb7, 0xe0, 0x88, 0xb6, 0xbe, 0xa7, 0x36, 0xac, 0x53, 0x79, 0xb7, 0xcf, 0xc4, 0x77, 0x9b, 0x5d, 0xf4, 0xd9, 0xee, 0xcb, 0x88, 0xd3, 0xb3, 0xaa, 0x70, 0xf3, 0x6a, 0xaf, 0x8a, 0xd7, 0xde, 0x36, 0x2a, 0xb1, 0x8c, 0x59, 0x64, 0xd3, 0x56, 0x22, 0x9b, 0x95, 0xf6, 0xb6, 0x16, 0xd7, 0x4c, 0xdb, 0x8e, 0x1a, 0x60, 0x30, 0xff, 0xb4, 0x84, 0x4f, 0xd7, 0x0f, 0x71, 0x77, 0xe9, 0x68, 0x3f, 0x64, 0x3d, 0xb2, 0x85, 0xbb, 0xa3, 0x29, 0xec, 0xb9, 0xfd, 0x81, 0x41, 0x25, 0x7d, 0x17, 0xb0, 0xde, 0xa7, 0x0d, 0xf0, 0x52, 0x05, 0x05, 0xbb, 0xe0, 0xe7, 0xf1, 0xe5, 0xad, 0x93, 0xa4, 0xbf, 0xd5, 0x74, 0x0d, 0xb6, 0x14, 0x62, 0xdc, 0x52, 0xaa, 0x3a, 0x51, 0xcc, 0xb0, 0x25, 0xe6, 0x50, 0xa5, 0x2b, 0x47, 0x2d, 0x6d, 0x8c, 0xe3, 0x24, 0xee, 0x3c, 0x45, 0x1b, 0xd1, 0xec, 0x8c, 0x71, 0x7c, 0xb9, 0x3c, 0xf5, 0x4c, 0xf7, 0xf8, 0x4c, 0xf3, 0x33, 0xb1, 0xf7, 0x91, 0x8b, 0xba, 0xb4, 0x33, 0x4f, 0x1e, 0x4d, 0x70, 0x4b, 0x6d, 0x55, 0x37, 0xd6, 0xa4, 0x43, 0xdb, 0x90, 0x83, 0x1b, 0xc4, 0x33, 0x63, 0x57, 0x4d, 0x66, 0xb6, 0x68, 0x18, 0x0a, 0x31, 0x0e, 0x01, 0x1e, 0xf8, 0x9c, 0x80, 0x2d, 0x56, 0x25, 0x57, 0x84, 0xfd, 0xef, 0x94, 0xe9, 0xc8, 0x3f, 0xcc, 0x00, 0x4a, 0x2a, 0x5d, 0x73, 0xbb, 0x9e, 0xc6, 0xa6, 0x5e, 0x39, 0x20, 0xf5, 0x7b, 0xb0, 0x5c, 0x9c, 0xb3, 0x5a, 0x38, 0x20, 0x5d, 0xe0, 0x67, 0xa9, 0xe4, 0xd4, 0x63, 0xad, 0x70, 0x80, 0xb1, 0x49, 0xc3, 0x02, 0x5d, 0x41, 0x21, 0x6f, 0x3e, 0x74, 0x3f, 0x00, 0x88, 0xd7, 0x45, 0x4e, 0x54, 0x19, 0x22, 0x32, 0xf5, 0x83, 0x05, 0x89, 0x01, 0xf9, 0x06, 0x73, 0x29, 0xfc, 0xda, 0x2a, 0x0d, 0xa0, 0x54, 0x8c, 0xc8, 0x4e, 0x0c, 0xe9, 0x9f, 0x50, 0xf4, 0xb0, 0xd5, 0x4d, 0x14, 0x78, 0x8b, 0x21, 0x4e, 0x03, 0xde, 0xb9, 0x04, 0x40, 0xd2, 0x99, 0x4d, 0x52, 0x7d, 0x5c, 0x67, 0x1d, 0xde, 0x13, 0xf8, 0x44, 0xf9, 0xaf, 0xd6, 0xd9, 0x15, 0x8c, 0xad, 0xf7, 0x79, 0x3e, 0x5d, 0xc4, 0x3a, 0x96, 0x7f, 0x5a, 0x3a, 0x57, 0xd2, 0xfa, 0x5f, 0xb7, 0x09, 0x57, 0xb7, 0x1e, 0x05, 0x8c, 0x10, 0xb8, 0x49, 0x2f, 0x99, 0x1c, 0x07, 0x96, 0x2a, 0xb7, 0x56, 0x1e, 0x3a, 0x5c, 0x4a, 0x1f, 0x3a, 0x78, 0xb9, 0xb7, 0x99, 0x43, 0x1e, 0xa2, 0x2c, 0xb6, 0xf9, 0x8c, 0xec, 0xe0, 0x19, 0x5d, 0x35, 0x6f, 0x78, 0xc4, 0x2d, 0x7e, 0x46, 0x21, 0xa0, 0x1e, 0x1d, 0xee, 0x7c, 0xb1, 0xb3, 0x7d, 0x54, 0xe9, 0xb6, 0x4d, 0x7f, 0x32, 0x1d, 0x62, 0xa8, 0x32, 0xee, 0xa4, 0xae, 0x62, 0xd6, 0x40, 0x0e, 0x48, 0xac, 0xf4, 0x4c, 0x79, 0xb7, 0x08, 0x60, 0x05, 0x18, 0xaa, 0xd8, 0x62, 0x48, 0x9a, 0x5d, 0x16, 0xec, 0xa4, 0x57, 0x5c, 0x32, 0x87, 0x82, 0x3a, 0xc4, 0x20, 0x03, 0x5a, 0x1f, 0x6c, 0x4e, 0x24, 0x8f, 0x71, 0x58, 0x8f, 0x07, 0x93, 0x9c, 0xad, 0x1f, 0xc4, 0x44, 0xc8, 0x9f, 0x83, 0x81, 0xe6, 0x8c, 0x05, 0xcf, 0x31, 0x0c, 0xa8, 0x86, 0x4e, 0x0d, 0x81, 0x61, 0x15, 0x93, 0xae, 0xa5, 0xa5, 0x6a, 0xdc, 0x32, 0xa7, 0x04, 0x28, 0x97, 0x03, 0x51, 0x94, 0x9a, 0x8d, 0xc3, 0x84, 0x0c, 0xa2, 0x85, 0x30, 0x50, 0xc0, 0x20, 0x0c, 0xf3, 0xe8, 0x80, 0x6b, 0x16, 0xf9, 0x67, 0x0c, 0x15, 0x08, 0xb3, 0x14, 0xb6, 0xa1, 0x00, 0x98, 0x1a, 0xe6, 0xc1, 0xe4, 0xb8, 0x0d, 0x72, 0xd9, 0x60, 0x31, 0x21, 0x24, 0xb1, 0x21, 0x07, 0x06, 0x40, 0xbf, 0xc9, 0xcd, 0x0b, 0x7f, 0x28, 0x05, 0xe1, 0xf9, 0x90, 0xbb, 0x2a, 0x94, 0x96, 0x19, 0x71, 0x9e, 0xb4, 0x45, 0xa8, 0x4e, 0x6b, 0xd3, 0xb7, 0xd6, 0x23, 0x2f, 0x4e, 0x61, 0xd4, 0x11, 0x1c, 0xaa, 0x50, 0x30, 0x29, 0x62, 0xea, 0xd1, 0x88, 0x13, 0x36, 0xc4, 0xa4, 0x03, 0xc3, 0x24, 0x91, 0x22, 0x31, 0x23, 0x1d, 0x33, 0x25, 0x1c, 0x26, 0xf8, 0xd0, 0xa5, 0x8a, 0xa2, 0x5c, 0x9a, 0xaa, 0xa4, 0x62, 0x7d, 0x6d, 0x7c, 0x08, 0x51, 0x6e, 0xfb, 0x77, 0xe4, 0xf0, 0x1d, 0x95, 0xd7, 0xa4, 0x39, 0x6c, 0xa6, 0x09, 0x6b, 0x6c, 0x0a, 0x0c, 0x1e, 0xf3, 0x6c, 0x28, 0xa9, 0x1d, 0x0d, 0x7f, 0x4b, 0x0f, 0x43, 0x67, 0x3e, 0x69, 0xc5, 0xf0, 0x7a, 0xc5, 0xa1, 0x15, 0xc3, 0xf5, 0xbf, 0xd3, 0xb3, 0x0a, 0xa5, 0xc8, 0x9a, 0x85, 0xf2, 0x6c, 0xa4, 0xe3, 0x2b, 0xca, 0xe8, 0xc0, 0x38, 0xde, 0xde, 0x33, 0x44, 0xc1, 0xf8, 0x8c, 0xd5, 0x2f, 0x60, 0xfe, 0x64, 0x2d, 0x48, 0xcc, 0x7f, 0x57, 0x19, 0x84, 0x49, 0x51, 0x34, 0x0c, 0xa7, 0xe5, 0xbe, 0x88, 0x39, 0x14, 0xe2, 0x69, 0x3e, 0xa3, 0x1d, 0x10, 0x71, 0x9f, 0x5f, 0xab, 0xa4, 0xf2, 0xe2, 0xea, 0x60, 0xf3, 0xac, 0x72, 0xf9, 0x75, 0x43, 0xec, 0xbd, 0x40, 0x45, 0xe4, 0x35, 0x34, 0x24, 0x6a, 0xc2, 0x03, 0xe6, 0x17, 0x6c, 0x39, 0x4d, 0x00, 0x58, 0x9c, 0xb8, 0xfc, 0x3a, 0xf0, 0x66, 0x07, 0x7e, 0x11, 0x44, 0x6a, 0x64, 0xb8, 0xba, 0xbc, 0x71, 0x84, 0xb6, 0x30, 0x34, 0x3e, 0xae, 0x43, 0x65, 0x0a, 0x93, 0x12, 0xd0, 0x1d, 0xe1, 0x14, 0x88, 0xc2, 0x5e, 0xd3, 0x95, 0x26, 0xcf, 0x1d, 0xd4, 0x44, 0x26, 0x71, 0xee, 0x90, 0xd2, 0x9e, 0xea, 0xa1, 0x73, 0x0c, 0x32, 0xe4, 0x1e, 0x38, 0x44, 0xaa, 0xf2, 0x6b, 0x02, 0x80, 0xb9, 0xef, 0x33, 0xb5, 0x10, 0x02, 0x42, 0x3a, 0x38, 0x0c, 0xc3, 0xdc, 0x4c, 0x7b, 0x5a, 0xe6, 0x10, 0xd6, 0x43, 0xf8, 0x87, 0xa1, 0x50, 0x23, 0x2e, 0x2d, 0x5a, 0xaf, 0x94, 0x11, 0xa6, 0xca, 0x0b, 0xd6, 0x40, 0xea, 0x52, 0xa2, 0xa6, 0x2e, 0x30, 0xb2, 0x84, 0x59, 0xad, 0x10, 0x79, 0xa4, 0x86, 0x9c, 0x4a, 0xa5, 0xc6, 0x06, 0x60, 0xeb, 0x45, 0xce, 0x35, 0xdb, 0x0e, 0x96, 0x59, 0xbd, 0x3c, 0xb4, 0x14, 0x04, 0xd6, 0x9a, 0x6a, 0x34, 0x55, 0x34, 0x28, 0x42, 0xe2, 0x6e, 0x4a, 0xdd, 0x6b, 0x98, 0x18, 0x4c, 0xda, 0x25, 0xf1, 0x43, 0xd5, 0x00, 0x54, 0x12, 0x3f, 0x94, 0x1d, 0xe2, 0x32, 0x5e, 0x58, 0x59, 0x86, 0xf3, 0xe7, 0xa5, 0xd5, 0xe7, 0x75, 0xe9, 0x9c, 0xec, 0x31, 0xb0, 0x4c, 0xf9, 0x0e, 0x4a, 0x39, 0x6d, 0x37, 0x4c, 0x3c, 0x2a, 0x3b, 0x1f, 0x3e, 0x64, 0xe2, 0xef, 0xa4, 0x69, 0x76, 0xd9, 0xd0, 0x83, 0xc8, 0x13, 0x4e, 0x85, 0x0f, 0x08, 0x3e, 0x10, 0x64, 0xc4, 0xf4, 0x92, 0xdb, 0x92, 0xbb, 0x04, 0x34, 0xb4, 0xbe, 0xa0, 0x7c, 0x61, 0x63, 0xa7, 0xc6, 0x39, 0xbd, 0x2c, 0x70, 0xba, 0x59, 0xce, 0x4a, 0xc3, 0x4c, 0x80, 0x80, 0x75, 0xc1, 0x29, 0xb7, 0x25, 0x2b, 0x48, 0xa5, 0x34, 0x77, 0x4e, 0x84, 0x91, 0x24, 0xd4, 0x42, 0xc9, 0x91, 0x81, 0x02, 0xa6, 0xf8, 0x73, 0x97, 0xb5, 0x2a, 0xac, 0xdb, 0x5d, 0x86, 0xa2, 0x52, 0x66, 0xf9, 0x93, 0x94, 0x39, 0x71, 0x45, 0xba, 0x7c, 0x93, 0x60, 0xa5, 0xe7, 0xd1, 0x4d, 0xbe, 0xa5, 0x32, 0xb0, 0xb4, 0xe5, 0x3a, 0xcd, 0x03, 0x19, 0xba, 0xba, 0xe3, 0x9c, 0x8b, 0x40, 0x89, 0x46, 0x3e, 0x4f, 0x23, 0x97, 0x20, 0xe7, 0x2c, 0x1d, 0xbe, 0x35, 0x5a, 0x46, 0x3c, 0x9d, 0xca, 0xdd, 0x70, 0xfd, 0x78, 0xba, 0xd6, 0xb7, 0xae, 0xe2, 0x07, 0x87, 0xd5, 0x20, 0x78, 0x38, 0x9d, 0xc7, 0xa3, 0xfb, 0xda, 0x3b, 0xfe, 0xc1, 0x8f, 0xa7, 0xc3, 0xdb, 0x1c, 0x8a, 0xb7, 0x4c, 0x9f, 0xed, 0xf0, 0xe1, 0xd0, 0x43, 0x2d, 0x0b, 0x40, 0xe6, 0x9b, 0xde, 0xe2, 0x59, 0x94, 0xaf, 0x9c, 0x0c, 0x95, 0xcd, 0x34, 0x4e, 0x3d, 0xe4, 0x0c, 0x3b, 0x43, 0xf6, 0x32, 0x89, 0x23, 0xee, 0x84, 0x76, 0xe2, 0x9e, 0xe4, 0x68, 0xcf, 0x33, 0xde, 0x2f, 0x9b, 0xbd, 0xe1, 0x46, 0xfb, 0xd2, 0x86, 0x9e, 0xa3, 0x2a, 0x0f, 0x92, 0x79, 0xc7, 0xb6, 0x08, 0xe6, 0xa0, 0xaf, 0xd8, 0x0b, 0xa3, 0x5d, 0x79, 0x2a, 0xc6, 0x96, 0xfb, 0x1e, 0x94, 0x91, 0x57, 0x39, 0x1f, 0xb2, 0x5c, 0xa7, 0xf2, 0xd3, 0x2b, 0x30, 0x15, 0x58, 0xec, 0xfc, 0x98, 0xfb, 0xf5, 0x1b, 0x6a, 0x2f, 0x04, 0x57, 0x4c, 0x1c, 0xfc, 0x02, 0x57, 0x6a, 0xa9, 0xf9, 0xf5, 0xa9, 0x3e, 0xf5, 0x91, 0xd2, 0x54, 0xa8, 0x5f, 0xc1, 0xcb, 0xaa, 0x6f, 0x32, 0xe2, 0x55, 0x1f, 0xb5, 0x33, 0x34, 0x86, 0xbc, 0x19, 0x65, 0x67, 0x62, 0x9b, 0xe1, 0x84, 0xf2, 0xf2, 0xe0, 0x25, 0x59, 0xfb, 0x09, 0x77, 0x60, 0xfd, 0x07, 0x55, 0x22, 0x23, 0x70, 0xeb, 0x9c, 0x63, 0x38, 0x1c, 0x4b, 0x56, 0xdb, 0xa9, 0xea, 0xb7, 0x66, 0x79, 0x7e, 0x39, 0xa0, 0xa4, 0xf3, 0x15, 0x2c, 0xc1, 0x17, 0x47, 0xd2, 0xd5, 0x6f, 0x79, 0x84, 0xe1, 0x97, 0x39, 0x4d, 0xd7, 0xd3, 0xdb, 0xf6, 0x65, 0x15, 0xe7, 0x08, 0x1c, 0x48, 0xa2, 0x24, 0x6b, 0xea, 0x73, 0xcb, 0x7b, 0xab, 0x7f, 0x1a, 0x8d, 0x91, 0x69, 0x0f, 0x9b, 0x59, 0x07, 0x9c, 0x11, 0x37, 0xbd, 0x1d, 0x35, 0xbd, 0x70, 0x9b, 0xf3, 0xa4, 0x9b, 0x06, 0x5a, 0x41, 0x56, 0xcc, 0x8a, 0xc7, 0x8d, 0x0f, 0x0b, 0x54, 0x83, 0x59, 0x09, 0xc5, 0x3a, 0x31, 0xd9, 0x2a, 0xef, 0xa8, 0xf0, 0x1b, 0x0e, 0x93, 0x2c, 0x63, 0xd2, 0xf4, 0xe3, 0xa7, 0x6d, 0x25, 0xf2, 0x25, 0x5b, 0xe4, 0xa4, 0x32, 0x20, 0xc6, 0x84, 0x5a, 0xd6, 0xda, 0x39, 0xd9, 0x98, 0xa6, 0x9e, 0x05, 0xa6, 0x5c, 0x93, 0x60, 0x10, 0x7e, 0x4b, 0x9d, 0xcc, 0x32, 0x25, 0x1e, 0x94, 0x6f, 0x0c, 0x0c, 0x8d, 0x5d, 0x94, 0x97, 0x10, 0x05, 0xe7, 0xb8, 0x3f, 0x96, 0x40, 0x75, 0xe0, 0xe1, 0x49, 0xff, 0x3a, 0xfe, 0x8f, 0xe4, 0xf0, 0x00, 0xb5, 0x93, 0xe3, 0xd0, 0x83, 0xad, 0x47, 0x8c, 0x38, 0x3f, 0x13, 0x9c, 0xc6, 0xa8, 0x12, 0x0b, 0xcd, 0xea, 0x9c, 0xb0, 0x9c, 0xab, 0x27, 0x7b, 0xca, 0x25, 0x5c, 0xf5, 0x32, 0x62, 0x7a, 0x75, 0x9f, 0xad, 0x29, 0xf8, 0xd8, 0xea, 0x72, 0xaa, 0xe6, 0x86, 0x32, 0x58, 0xc8, 0x8d, 0x48, 0xca, 0x04, 0x68, 0x12, 0x45, 0x91, 0x18, 0x6b, 0x11, 0x3a, 0x6b, 0x11, 0xa8, 0x15, 0x6c, 0x87, 0x4a, 0x04, 0x66, 0x91, 0x0e, 0xf3, 0xd0, 0xfd, 0xc8, 0x5a, 0x20, 0x04, 0xd3, 0x78, 0x8a, 0xfe, 0x98, 0x95, 0x83, 0x5e, 0x33, 0xa0, 0xb9, 0x15, 0x95, 0xa0, 0xc8, 0x78, 0xfe, 0x41, 0x0f, 0x7e, 0xe1, 0x52, 0xa4, 0xac, 0xa0, 0x81, 0x4d, 0x50, 0x7e, 0xb2, 0xfc, 0x08, 0x58, 0x63, 0x93, 0xb6, 0xff, 0xc9, 0x95, 0xad, 0xd8, 0xf5, 0xe7, 0xcd, 0x50, 0xae, 0xa3, 0x61, 0x13, 0xfa, 0x3c, 0x56, 0x7c, 0xc4, 0x43, 0xb9, 0x3e, 0x11, 0xd5, 0x24, 0xa4, 0xcb, 0xef, 0x23, 0x91, 0x0c, 0x8f, 0xa2, 0xb7, 0x0b, 0xd0, 0x32, 0xa1, 0x2f, 0xba, 0x91, 0x92, 0xdf, 0xeb, 0xb1, 0x68, 0xb5, 0xe4, 0x36, 0x18, 0x18, 0x18, 0x09, 0xc3, 0x0e, 0xcd, 0x99, 0xfc, 0x3b, 0x3f, 0xc5, 0x50, 0xfa, 0x44, 0x69, 0x36, 0x16, 0x57, 0xf0, 0xfe, 0xb2, 0x86, 0x6c, 0xfc, 0x30, 0x3d, 0x97, 0x9f, 0x00, 0x25, 0x0e, 0xb7, 0x57, 0x42, 0x7c, 0x80, 0xa5, 0x20, 0x2a, 0xeb, 0xc0, 0x8f, 0x17, 0x42, 0xbe, 0x29, 0x17, 0x73, 0x7a, 0xe8, 0x54, 0x29, 0xcc, 0x5a, 0x59, 0x31, 0x6f, 0xfb, 0xc7, 0x3e, 0xd1, 0x04, 0x7b, 0x35, 0x70, 0xa0, 0x03, 0x8e, 0x14, 0x40, 0x52, 0x00, 0xb2, 0xf6, 0x87, 0x99, 0xb1, 0xbd, 0x16, 0x88, 0x89, 0xab, 0x79, 0x34, 0x5e, 0xb1, 0xca, 0x64, 0x9d, 0x04, 0x28, 0xcb, 0x78, 0x2d, 0x0d, 0xd4, 0xbe, 0xb9, 0xce, 0xb7, 0xc5, 0x15, 0x5b, 0x56, 0xd8, 0x0a, 0x55, 0x6e, 0xa4, 0xa8, 0x8d, 0x97, 0x35, 0xdf, 0xa7, 0xe6, 0x25, 0x54, 0x9e, 0x8e, 0x1b, 0x5e, 0x3f, 0x50, 0xaf, 0x8a, 0x46, 0x35, 0x52, 0xa7, 0x1a, 0xba, 0xd2, 0x40, 0x51, 0xea, 0x97, 0x0d, 0xdd, 0xab, 0x9c, 0xed, 0x1d, 0x96, 0x31, 0x7c, 0x4b, 0xa1, 0xb0, 0x6d, 0x6c, 0xc7, 0xdb, 0x69, 0xa8, 0x09, 0x2d, 0xa8, 0x41, 0x79, 0x6f, 0x8d, 0xae, 0xad, 0xa8, 0x3e, 0xbd, 0x52, 0x31, 0xd1, 0x78, 0x70, 0xcb, 0xcd, 0x7e, 0x5b, 0xdc, 0x7d, 0x95, 0x9e, 0x5a, 0x1b, 0xb1, 0x72, 0xe9, 0x40, 0xc1, 0xe0, 0xfd, 0x38, 0xd2, 0x2b, 0x1a, 0x4a, 0x45, 0xaf, 0x4e, 0xd4, 0x74, 0x89, 0xaa, 0x22, 0x31, 0x50, 0x21, 0x46, 0xfa, 0x43, 0x0e, 0xb6, 0x54, 0x0f, 0x96, 0xd3, 0x54, 0xb4, 0x35, 0xa7, 0x16, 0xd3, 0x01, 0x0a, 0xe2, 0x52, 0x5a, 0x1c, 0xe0, 0x34, 0x6b, 0xed, 0x2a, 0x77, 0x18, 0xb2, 0x91, 0x48, 0xb6, 0xdf, 0xc1, 0xf9, 0xf5, 0x05, 0x3b, 0xc2, 0x94, 0xea, 0x7d, 0x61, 0xa7, 0x1d, 0x61, 0x69, 0x4f, 0x4a, 0xb8, 0x80, 0x29, 0xa2, 0xef, 0xdf, 0x15, 0xb6, 0xf8, 0x3a, 0xd7, 0x61, 0x20, 0x30, 0xc5, 0x07, 0xc5, 0x45, 0x7e, 0x6d, 0x5b, 0xc2, 0x2f, 0xad, 0x5a, 0x8b, 0x7a, 0xb2, 0x26, 0xab, 0x58, 0xc4, 0xa4, 0xce, 0x5e, 0xbb, 0xee, 0x8c, 0x58, 0x52, 0xb9, 0x4c, 0x1f, 0x9c, 0x6b, 0x75, 0xe0, 0x30, 0xbc, 0xe7, 0xc4, 0xaa, 0x7e, 0xcc, 0x94, 0xb9, 0x24, 0x29, 0xd3, 0x1b, 0x52, 0xa9, 0x57, 0x4d, 0x63, 0x09, 0xb5, 0x74, 0x56, 0x4f, 0x8b, 0xf8, 0xa7, 0xe0, 0x36, 0xa4, 0x67, 0xaf, 0xea, 0x69, 0x0d, 0xc3, 0x09, 0xb0, 0x10, 0x93, 0x8c, 0x18, 0x74, 0x77, 0xe7, 0x41, 0xc6, 0x05, 0xeb, 0x26, 0xab, 0x30, 0x33, 0x03, 0x87, 0x1c, 0x10, 0xdc, 0xa8, 0x37, 0x5f, 0x92, 0xd0, 0x9c, 0x5a, 0x37, 0xa6, 0x6d, 0x92, 0x18, 0x11, 0xb5, 0xb0, 0xca, 0x89, 0xb9, 0xf5, 0x75, 0x75, 0x44, 0xe3, 0xe7, 0x5a, 0x44, 0xa3, 0xc5, 0xf6, 0x38, 0xed, 0x64, 0x56, 0x7a, 0xd8, 0xb7, 0x2c, 0x48, 0xed, 0x45, 0x94, 0xb3, 0x94, 0x52, 0x1d, 0x9a, 0xd7, 0x7f, 0x69, 0x65, 0x09, 0xef, 0xd9, 0x1e, 0xfc, 0x19, 0xb8, 0x1e, 0xdd, 0x9d, 0x72, 0x3d, 0xea, 0xa7, 0x96, 0x2a, 0xfa, 0xa6, 0x55, 0x1f, 0x46, 0x62, 0x29, 0x47, 0xd8, 0x9a, 0x2f, 0x10, 0x3f, 0x73, 0x7b, 0x6e, 0xd4, 0xae, 0x1a, 0xac, 0x1b, 0x51, 0x5a, 0x50, 0x61, 0x08, 0x8d, 0xe4, 0xc6, 0x9e, 0x58, 0x2d, 0x50, 0x2d, 0x10, 0x98, 0xae, 0x25, 0x80, 0x0b, 0x19, 0xf7, 0xdc, 0xf5, 0xbc, 0x16, 0x1e, 0x79, 0x20, 0x6f, 0x5b, 0x51, 0xe6, 0x58, 0xed, 0xec, 0x41, 0xd3, 0x47, 0x1e, 0x73, 0x1b, 0x58, 0x24, 0xbb, 0xe8, 0xd6, 0x86, 0xd1, 0xcf, 0xcc, 0xf8, 0x9c, 0xd1, 0x4b, 0xb8, 0xd5, 0xf4, 0x12, 0xae, 0x02, 0x68, 0xf2, 0x0d, 0x8d, 0x66, 0x0a, 0x36, 0x7d, 0x54, 0x24, 0x0b, 0x0f, 0xb7, 0xdd, 0xab, 0xec, 0x36, 0xc5, 0xaf, 0x8e, 0x89, 0x12, 0x19, 0xf7, 0xb2, 0x96, 0xb8, 0x06, 0xb7, 0x7a, 0xd2, 0xb2, 0x6a, 0x61, 0xb2, 0x1b, 0x0a, 0x17, 0x22, 0x8f, 0x19, 0x12, 0x55, 0xa1, 0x12, 0x6c, 0x6c, 0x28, 0x96, 0x86, 0xc5, 0x4a, 0xc0, 0xa8, 0x14, 0x3b, 0xd2, 0xb1, 0x09, 0x6a, 0x09, 0x61, 0xcd, 0xa4, 0xbf, 0xdf, 0x10, 0xfa, 0x34, 0xa0, 0xc8, 0xc0, 0x4b, 0x72, 0x38, 0xe0, 0x05, 0xe3, 0x1c, 0xc0, 0xd4, 0x22, 0xc6, 0x74, 0x91, 0x0c, 0x5d, 0x26, 0x4d, 0xcb, 0xbe, 0x61, 0x82, 0x3d, 0xa2, 0x25, 0x21, 0x3b, 0xc3, 0x3c, 0x7c, 0x55, 0x7e, 0x87, 0xaa, 0x9b, 0x94, 0x6e, 0xb2, 0x76, 0x6f, 0x31, 0x9b, 0xc7, 0x48, 0xb6, 0xc5, 0xc3, 0x19, 0xc3, 0x61, 0x0a, 0x5d, 0xb0, 0x9c, 0xc8, 0xda, 0xc5, 0x3f, 0xb3, 0x4f, 0x63, 0x74, 0x35, 0x59, 0x08, 0x02, 0x8d, 0x85, 0x1c, 0xbe, 0xd3, 0xc8, 0x0f, 0x06, 0x56, 0x81, 0x02, 0xb3, 0x24, 0x14, 0x4a, 0xc6, 0x2a, 0x9b, 0xc2, 0x3a, 0x37, 0xf4, 0xa3, 0x13, 0x2a, 0xd7, 0x82, 0x64, 0x62, 0xd4, 0x2d, 0xdd, 0x30, 0xfd, 0x54, 0xa3, 0x23, 0xc1, 0x47, 0x02, 0x3b, 0x60, 0x17, 0xc3, 0x25, 0x5e, 0xe4, 0xd3, 0x26, 0x3b, 0xee, 0x9d, 0x3a, 0x86, 0x5d, 0xb5, 0xac, 0x91, 0x85, 0x36, 0xfd, 0xb5, 0xc8, 0x88, 0xe3, 0xea, 0x57, 0xcd, 0x8c, 0x81, 0x45, 0x36, 0x9d, 0x3b, 0x37, 0x00, 0xd2, 0x9a, 0x8d, 0x46, 0x4a, 0xaa, 0xa9, 0x14, 0x8d, 0x31, 0xa2, 0xb5, 0x54, 0xa7, 0x9d, 0x5e, 0xbc, 0x44, 0xaf, 0x16, 0x82, 0x1f, 0x5a, 0x15, 0x65, 0x11, 0x4f, 0x7c, 0xc8, 0x5c, 0xb4, 0x97, 0xf1, 0xc2, 0xdf, 0x10, 0x40, 0x4e, 0x16, 0x9a, 0x5a, 0x14, 0x02, 0x58, 0x49, 0xcb, 0x33, 0x97, 0x1e, 0x61, 0x24, 0x08, 0x6b, 0x8e, 0x32, 0x11, 0x09, 0xaa, 0x43, 0x4e, 0x38, 0xe7, 0xc4, 0x2e, 0x0b, 0x7e, 0x45, 0x02, 0x10, 0x80, 0x23, 0x08, 0x71, 0x18, 0x58, 0x5e, 0x92, 0x00, 0x11, 0x42, 0x13, 0xd4, 0x04, 0x5d, 0x89, 0x21, 0xb3, 0xaf, 0xe4, 0xf0, 0x03, 0x91, 0x02, 0x6e, 0xbb, 0xe0, 0x21, 0x26, 0xde, 0xc4, 0xf9, 0x65, 0x8a, 0x9a, 0xd1, 0x2d, 0xcd, 0x6f, 0x48, 0x87, 0x03, 0xc7, 0x42, 0x61, 0x36, 0x0c, 0x23, 0xc9, 0x49, 0xe5, 0xec, 0x8f, 0xce, 0xbe, 0x6d, 0x49, 0x5e, 0x66, 0x84, 0xd1, 0xb3, 0xdf, 0x19, 0x33, 0x54, 0x30, 0xc3, 0xdb, 0x95, 0x08, 0x20, 0x3a, 0x51, 0xd2, 0x45, 0x58, 0x63, 0xcc, 0xf5, 0xe1, 0x54, 0x60, 0x33, 0x2b, 0x28, 0x0e, 0x8b, 0x1e, 0xd7, 0xcc, 0x9b, 0x6b, 0x73, 0x35, 0x0c, 0xb5, 0x58, 0x70, 0x42, 0xca, 0x6a, 0xad, 0xf7, 0x85, 0x62, 0xef, 0xa7, 0x9f, 0x41, 0x6c, 0x52, 0xd1, 0x47, 0x31, 0x67, 0x10, 0xf3, 0x9f, 0x49, 0x26, 0x9a, 0xd8, 0x9a, 0xa5, 0x21, 0x3a, 0xb6, 0xd9, 0x2c, 0x61, 0x2f, 0xec, 0xb4, 0x45, 0xd5, 0x0e, 0xed, 0x77, 0xb4, 0xd8, 0x25, 0x5a, 0xe5, 0x62, 0xdb, 0x25, 0xeb, 0xf4, 0x0a, 0xce, 0xd8, 0x29, 0x01, 0xac, 0xd9, 0xcf, 0xab, 0x63, 0x9d, 0xe6, 0x79, 0x7d, 0x2c, 0x26, 0x59, 0xce, 0x61, 0xaf, 0x2f, 0xa1, 0x58, 0x7d, 0xbc, 0x4d, 0x91, 0xe9, 0x80, 0xf2, 0x3d, 0xfd, 0x97, 0xe3, 0x19, 0xe8, 0x55, 0x8c, 0x16, 0xeb, 0xad, 0x34, 0xd7, 0x75, 0xa8, 0x8e, 0x01, 0xef, 0xb0, 0xca, 0x90, 0xc5, 0x7e, 0x98, 0x9b, 0x9e, 0xdb, 0x1b, 0xa5, 0x47, 0xc9, 0x88, 0xe5, 0xa8, 0x49, 0x20, 0x13, 0x8f, 0x73, 0x4e, 0x02, 0xa4, 0x79, 0x66, 0xdc, 0x33, 0x37, 0x4d, 0x47, 0xd7, 0x8b, 0x55, 0x8a, 0x60, 0x2b, 0xf9, 0x5f, 0xdc, 0x14, 0x5c, 0x1f, 0x09, 0x05, 0x94, 0xb2, 0xca, 0x1f, 0xb9, 0x2c, 0x9f, 0x44, 0x8f, 0xb0, 0xe1, 0x52, 0x7c, 0x2e, 0x93, 0x04, 0x1d, 0x89, 0x14, 0xe4, 0x96, 0x21, 0x52, 0x7d, 0x53, 0x55, 0xaa, 0x05, 0x82, 0xf3, 0xd6, 0x04, 0xae, 0x09, 0x88, 0x35, 0x71, 0x62, 0xae, 0x50, 0x98, 0xdd, 0xf6, 0xfd, 0x78, 0x9a, 0x1d, 0xd9, 0x40, 0x51, 0x94, 0x0b, 0x12, 0xd2, 0xd5, 0xe0, 0xd6, 0x95, 0x39, 0xea, 0x32, 0x1c, 0x85, 0x52, 0x83, 0x4a, 0xd1, 0x40, 0x14, 0x67, 0xc4, 0x9e, 0x9a, 0xab, 0x19, 0x06, 0x2c, 0xfd, 0x96, 0x23, 0x80, 0x83, 0xb6, 0x8a, 0x18, 0x48, 0x88, 0x12, 0x29, 0xf3, 0x7c, 0x10, 0x52, 0x0c, 0x91, 0x86, 0x8e, 0xeb, 0x14, 0xf6, 0x61, 0x9b, 0xbe, 0xb1, 0xde, 0xb3, 0xb0, 0x47, 0xd0, 0x1b, 0xcb, 0x47, 0x2e, 0x6a, 0x18, 0xa7, 0x77, 0xc5, 0xbf, 0x20, 0xe9, 0x44, 0x26, 0x13, 0x61, 0xb0, 0x1d, 0xa1, 0xeb, 0xdc, 0x20, 0x3c, 0x33, 0x90, 0xe0, 0x43, 0xda, 0x6f, 0xc4, 0xa2, 0x91, 0x48, 0x95, 0x55, 0x16, 0x46, 0xa1, 0x1a, 0x40, 0x6c, 0xcd, 0x4e, 0x3d, 0x9c, 0x6c, 0xc9, 0xaf, 0xd6, 0x4b, 0x0c, 0x32, 0x1b, 0x5d, 0x57, 0x59, 0x5b, 0xcc, 0x11, 0xd9, 0x59, 0x98, 0xd4, 0x69, 0xdd, 0x06, 0x97, 0x57, 0x33, 0x8d, 0x5c, 0xed, 0x74, 0x86, 0xfe, 0x82, 0x0f, 0x28, 0xee, 0xa0, 0x4a, 0xcf, 0x01, 0xf1, 0xbd, 0xec, 0xdf, 0xc0, 0x83, 0x18, 0x2b, 0x1e, 0xc1, 0x06, 0x31, 0x18, 0x94, 0xeb, 0xf0, 0xa4, 0xa2, 0xa3, 0x75, 0x90, 0x5e, 0x50, 0x80, 0xd6, 0x21, 0x42, 0x58, 0x2a, 0xe3, 0xa2, 0xd2, 0xff, 0x55, 0xa6, 0x57, 0x4d, 0x99, 0x70, 0xbb, 0x6a, 0x4a, 0x55, 0x60, 0x00, 0x5a, 0x36, 0x22, 0x20, 0x06, 0xb1, 0x80, 0xaa, 0xaf, 0x65, 0x0a, 0xce, 0x6f, 0x1c, 0xee, 0xd6, 0x13, 0x61, 0x4e, 0x6c, 0x67, 0x31, 0xfb, 0x3a, 0x23, 0xd1, 0x7c, 0x8e, 0xab, 0xc0, 0xe5, 0xc3, 0x3e, 0x58, 0xfb, 0xfe, 0x98, 0x8e, 0x9b, 0x2b, 0xe9, 0xde, 0x80, 0x27, 0x74, 0x74, 0xb0, 0x08, 0x28, 0x9b, 0xd5, 0x3c, 0x58, 0xe6, 0x57, 0x4b, 0x8e, 0x32, 0xb2, 0x86, 0x82, 0x8e, 0x6a, 0x88, 0xb1, 0x49, 0x4f, 0x50, 0x59, 0x4b, 0xf9, 0x5b, 0xcb, 0xd7, 0xe1, 0x12, 0x29, 0xef, 0x7d, 0x3b, 0x23, 0x30, 0xef, 0xe3, 0x07, 0xd3, 0xf1, 0xd1, 0x6a, 0xa4, 0x8a, 0xe4, 0x19, 0x1e, 0x8c, 0x34, 0xdc, 0xae, 0xc6, 0x83, 0xde, 0x20, 0x53, 0x0f, 0xd1, 0x4c, 0xaf, 0x9c, 0x73, 0x74, 0xcc, 0xed, 0x00, 0x7c, 0x52, 0x9d, 0x3d, 0x79, 0x08, 0x57, 0x4c, 0x08, 0xde, 0x2d, 0x18, 0x05, 0x8e, 0x10, 0x33, 0xd7, 0x61, 0xe1, 0x99, 0x2f, 0x4d, 0x61, 0xfc, 0x58, 0x5b, 0x7d, 0xb4, 0x7b, 0x98, 0x11, 0xce, 0x4f, 0x0d, 0x33, 0x5b, 0xbf, 0xef, 0xf3, 0x4b, 0x04, 0x8a, 0xeb, 0x54, 0x8f, 0x79, 0xa9, 0x70, 0xd8, 0xad, 0x2b, 0x0d, 0x8b, 0x4b, 0x8b, 0x3b, 0x55, 0x55, 0x8e, 0xb5, 0xad, 0xd3, 0x0e, 0xfd, 0xb1, 0x4a, 0xa5, 0x71, 0x83, 0x09, 0xba, 0xf7, 0x93, 0x6c, 0x95, 0xfa, 0x25, 0x5b, 0x69, 0x21, 0xdf, 0x2a, 0x5d, 0xd3, 0xf2, 0xce, 0xd4, 0xf2, 0xad, 0x2c, 0xaa, 0x6a, 0x04, 0x01, 0x10, 0x07, 0x64, 0xeb, 0x8a, 0x3e, 0x53, 0xe5, 0x2b, 0xfc, 0x2d, 0x62, 0x5c, 0x66, 0x21, 0xe3, 0x33, 0x72, 0xd2, 0xe7, 0xcc, 0x90, 0x80, 0x4e, 0xa1, 0x67, 0x6d, 0x51, 0x6b, 0x00, 0x36, 0xcb, 0x76, 0x79, 0x07, 0x21, 0x7c, 0x52, 0xaf, 0x1b, 0xe9, 0x58, 0x52, 0x09, 0x97, 0x9e, 0x22, 0x74, 0xe8, 0x1c, 0x84, 0xdc, 0x3b, 0x19, 0xa4, 0xe8, 0xb0, 0x44, 0xa0, 0xf0, 0xa0, 0x93, 0xb5, 0xcd, 0x9c, 0x34, 0x6a, 0xba, 0xb6, 0x56, 0x28, 0x98, 0x0d, 0xd0, 0xfc, 0xff, 0xc9, 0x8e, 0x34, 0xaa, 0x73, 0x11, 0x32, 0xb4, 0x34, 0x9b, 0x96, 0x46, 0x02, 0xbb, 0x13, 0x80, 0x24, 0x84, 0x10, 0xed, 0xc2, 0x43, 0xc1, 0x18, 0x2f, 0xea, 0x05, 0x7e, 0x21, 0x6b, 0xaf, 0xd5, 0x8c, 0x7e, 0xbd, 0x22, 0x6b, 0x2b, 0xad, 0xc1, 0x2b, 0xb3, 0xb6, 0x36, 0x9e, 0x21, 0x7a, 0xc8, 0xb9, 0x75, 0x40, 0x2d, 0xca, 0x60, 0x2a, 0x0f, 0x66, 0x48, 0xb0, 0x5d, 0xaa, 0xa9, 0xec, 0x1a, 0xd1, 0xbf, 0xea, 0x05, 0x76, 0x0f, 0xef, 0x4c, 0x8f, 0xbf, 0xbc, 0x6a, 0x87, 0xcd, 0x13, 0xbd, 0x6a, 0xcb, 0x89, 0x42, 0xa5, 0x86, 0xb3, 0xbe, 0x56, 0xbd, 0x48, 0xf2, 0x80, 0xaa, 0x0e, 0xd6, 0x54, 0x5e, 0x35, 0x0f, 0x95, 0x02, 0xf6, 0x63, 0x2b, 0x41, 0x73, 0x50, 0x59, 0xf4, 0xda, 0xaa, 0xa2, 0x01, 0xdf, 0x28, 0x25, 0x47, 0x30, 0xaf, 0xdd, 0x1e, 0x1d, 0xc7, 0x0a, 0x73, 0x66, 0x9c, 0xce, 0x55, 0x33, 0x40, 0x67, 0xf6, 0x8c, 0xa8, 0xd3, 0x19, 0xe1, 0x47, 0x69, 0x06, 0x58, 0x0f, 0x25, 0x5b, 0x0a, 0x8c, 0x39, 0xb1, 0xe8, 0x39, 0xc1, 0xe2, 0xde, 0xa6, 0x60, 0xf9, 0x44, 0xce, 0x80, 0x41, 0x35, 0x9a, 0x9d, 0x33, 0x94, 0xb5, 0x62, 0xb2, 0x12, 0x5e, 0x4a, 0x0c, 0xc1, 0x30, 0x99, 0x27, 0x86, 0xf4, 0x69, 0x85, 0x33, 0x5b, 0x28, 0xfa, 0xe2, 0x9d, 0x55, 0x7a, 0x9a, 0x6f, 0x42, 0x37, 0x5f, 0xbf, 0x6f, 0x4c, 0xf7, 0x61, 0x95, 0x5f, 0x9b, 0x92, 0x1b, 0x40, 0x8f, 0x83, 0xc0, 0x66, 0x6a, 0x54, 0x19, 0x88, 0x2b, 0x2a, 0x15, 0x14, 0xd4, 0x11, 0x83, 0x78, 0x54, 0x7e, 0x85, 0x59, 0x0c, 0x46, 0x64, 0x81, 0xe0, 0x97, 0x46, 0x88, 0xaa, 0xf5, 0x4b, 0xd5, 0x1a, 0xd2, 0x6c, 0xd4, 0xdc, 0x65, 0xd4, 0x98, 0xf9, 0xcd, 0x73, 0x35, 0xcf, 0xf3, 0x67, 0x01, 0x9b, 0x69, 0x55, 0x35, 0xcf, 0xb6, 0xf0, 0x5b, 0x3d, 0x56, 0x79, 0xa7, 0x5f, 0x4e, 0x41, 0xcf, 0x1f, 0xab, 0xd8, 0x8c, 0x9b, 0xbe, 0xc8, 0x20, 0x32, 0x7c, 0xf2, 0xc9, 0xde, 0x69, 0xd5, 0x59, 0xbd, 0x1d, 0x8a, 0x9f, 0x15, 0x7e, 0xe9, 0x79, 0x65, 0x81, 0x1b, 0xa2, 0xaf, 0x74, 0xec, 0x95, 0xcc, 0xa9, 0x69, 0x62, 0x50, 0x73, 0xd7, 0x93, 0x33, 0x97, 0x92, 0x0c, 0xc9, 0x5e, 0xc7, 0x68, 0x76, 0xf6, 0x68, 0x7a, 0x96, 0x18, 0x28, 0x99, 0x04, 0x01, 0xc2, 0xf6, 0x84, 0xa0, 0x2b, 0xe5, 0x5b, 0x24, 0x03, 0x76, 0x51, 0xc1, 0x02, 0x44, 0xad, 0xe2, 0x46, 0x2e, 0x72, 0xc5, 0x18, 0x4b, 0x15, 0x81, 0x04, 0x0d, 0xa8, 0x6f, 0xa9, 0x72, 0x0c, 0x80, 0xe9, 0x30, 0x6d, 0x0f, 0x47, 0x74, 0x10, 0x3f, 0x4f, 0xc7, 0x43, 0x86, 0x01, 0x6b, 0x84, 0x48, 0xf2, 0x8f, 0xd9, 0xa9, 0x6a, 0x22, 0x8f, 0x44, 0xd0, 0x60, 0x89, 0x8e, 0x10, 0x63, 0x73, 0xa2, 0xdf, 0x50, 0x3a, 0xf0, 0x5d, 0x5b, 0xe0, 0x57, 0xce, 0x3b, 0x3a, 0x33, 0x97, 0x11, 0x66, 0x50, 0x12, 0xf5, 0x33, 0x5c, 0xe4, 0x08, 0x22, 0x7b, 0xec, 0xa1, 0xce, 0x25, 0x37, 0x52, 0xb0, 0xc8, 0xcd, 0x2e, 0x07, 0x55, 0x70, 0xae, 0xf2, 0x48, 0xc2, 0x55, 0x61, 0x1d, 0x19, 0x7e, 0xb0, 0xd4, 0x1c, 0x28, 0x2f, 0xc9, 0x4b, 0x9e, 0x8f, 0x6c, 0x9b, 0x73, 0x09, 0x35, 0x23, 0xc4, 0xf7, 0x04, 0x30, 0x4c, 0xb7, 0x47, 0x98, 0x70, 0x86, 0xa8, 0xc6, 0x34, 0x5f, 0x48, 0xaf, 0x5a, 0xf2, 0x14, 0xab, 0x8a, 0xe7, 0x77, 0x1a, 0xe8, 0x43, 0x75, 0xd2, 0x12, 0x72, 0xb9, 0x23, 0x8f, 0x1d, 0x43, 0xe0, 0x03, 0xd5, 0xa7, 0xb3, 0x1c, 0x2d, 0x58, 0xc8, 0xe4, 0x5f, 0x43, 0xc8, 0x15, 0x4e, 0x16, 0x4d, 0x5b, 0x9c, 0x66, 0x14, 0x0b, 0x1e, 0xea, 0x15, 0xed, 0x83, 0x6d, 0x0e, 0x5f, 0x2b, 0x3d, 0x3b, 0x7b, 0x4a, 0x4d, 0xa0, 0xd6, 0x2a, 0x3a, 0xb2, 0x33, 0xa4, 0xe3, 0xcf, 0x00, 0x45, 0x50, 0x17, 0xc4, 0xef, 0x4e, 0x19, 0x7b, 0x80, 0x9d, 0x04, 0xa7, 0x9c, 0x3f, 0x4d, 0xa8, 0x39, 0xb1, 0xe8, 0x0f, 0x55, 0x5a, 0x96, 0x32, 0x64, 0xdb, 0x92, 0x85, 0x2d, 0x47, 0x74, 0x28, 0x4b, 0x21, 0xc3, 0x09, 0x0d, 0xe5, 0x12, 0x72, 0x61, 0xe3, 0x61, 0x5f, 0xe2, 0x49, 0xd5, 0x5e, 0x8e, 0xc6, 0xb9, 0x7a, 0x2d, 0xe1, 0xeb, 0x0e, 0x93, 0xe9, 0xd1, 0x0f, 0x41, 0xed, 0xa5, 0x6d, 0x11, 0x42, 0x25, 0xf6, 0x74, 0x17, 0xe5, 0xbb, 0x7e, 0xfc, 0xa5, 0xea, 0x0e, 0x17, 0xc5, 0x41, 0xe9, 0x76, 0xd2, 0x00, 0x1d, 0x41, 0xc9, 0x6a, 0x23, 0x6f, 0x78, 0x92, 0x6c, 0xf9, 0x92, 0x33, 0x6c, 0xda, 0x09, 0x45, 0x41, 0xea, 0x7a, 0x27, 0xed, 0x4e, 0xa6, 0x31, 0x6a, 0x44, 0x05, 0x04, 0x9d, 0xa6, 0xa4, 0x69, 0xf0, 0xf3, 0x62, 0xec, 0x4c, 0xb3, 0x57, 0x1a, 0x53, 0x7e, 0xa1, 0x4e, 0xa3, 0x62, 0x76, 0x66, 0x0a, 0xf0, 0x51, 0x82, 0x33, 0xa3, 0x79, 0x51, 0x18, 0x73, 0x49, 0x47, 0xc7, 0x10, 0xdf, 0xdb, 0x9c, 0x42, 0x4b, 0x45, 0xe0, 0x59, 0x03, 0xcc, 0x99, 0xdf, 0xe4, 0x62, 0xb6, 0xfc, 0x7b, 0xc8, 0x1a, 0x22, 0x63, 0xba, 0x55, 0xef, 0xbd, 0xce, 0x49, 0x75, 0x50, 0x16, 0x3e, 0x0b, 0xef, 0x3e, 0xab, 0x40, 0xe5, 0xec, 0x63, 0xf2, 0xed, 0x76, 0xec, 0x1a, 0x2d, 0x31, 0x39, 0x2a, 0x1d, 0x49, 0xba, 0x24, 0x8c, 0x93, 0xb3, 0x86, 0x23, 0x4f, 0xb2, 0x69, 0x5b, 0xe9, 0xaa, 0xbb, 0x70, 0x46, 0xcb, 0x0f, 0xef, 0xaa, 0x7f, 0x85, 0xd5, 0xb0, 0x7f, 0xbd, 0x08, 0xe4, 0xcc, 0x75, 0x89, 0xaf, 0x9a, 0xd4, 0x05, 0xed, 0x93, 0x5a, 0x47, 0xe7, 0x43, 0x7a, 0x83, 0x9f, 0xd2, 0xb6, 0x61, 0x3f, 0x3e, 0xf9, 0x7c, 0xcb, 0x02, 0x4e, 0xcf, 0x20, 0x28, 0x22, 0xf8, 0xe6, 0xd5, 0x81, 0x59, 0xb2, 0x4a, 0x30, 0x49, 0x32, 0x1f, 0x31, 0xdb, 0x96, 0xfb, 0x57, 0xaa, 0x7a, 0xfa, 0x5e, 0x8c, 0x4d, 0xa9, 0x1f, 0xd7, 0x9c, 0x1a, 0x17, 0x6d, 0xce, 0x76, 0x9e, 0x9f, 0x5b, 0x55, 0x21, 0xc1, 0x2e, 0xbf, 0x06, 0xbb, 0xf0, 0x1a, 0x60, 0x6f, 0xee, 0x02, 0x6a, 0xb7, 0x67, 0xc3, 0x2f, 0x1a, 0x65, 0xca, 0x84, 0xf0, 0xd0, 0x93, 0xf0, 0xf9, 0x3f, 0xe5, 0xbf, 0x54, 0x4a, 0x67, 0x5d, 0xb8, 0xb1, 0x67, 0x80, 0xc2, 0xf7, 0x0a, 0xfc, 0x17, 0x31, 0x6e, 0x97, 0xf9, 0x08, 0x5b, 0x44, 0x5b, 0x98, 0x57, 0xe1, 0xd2, 0x3e, 0xa1, 0x38, 0xbd, 0x75, 0x44, 0xef, 0x40, 0x20, 0x27, 0x8d, 0x41, 0x1c, 0x13, 0x89, 0xe4, 0xdb, 0xbb, 0x2e, 0xfa, 0xb4, 0xfd, 0x8c, 0xc3, 0x4d, 0xa6, 0x91, 0xf3, 0x1b, 0x38, 0x2d, 0x25, 0x1a, 0xb4, 0xb0, 0x99, 0x0c, 0x30, 0x99, 0xc0, 0xf6, 0x77, 0x85, 0xd9, 0x30, 0x6d, 0x45, 0x54, 0xc5, 0xd2, 0xee, 0x35, 0xe4, 0xb2, 0xf6, 0x39, 0x4d, 0xc5, 0xa2, 0x7f, 0x36, 0xad, 0x69, 0xec, 0x9e, 0xd9, 0x31, 0x4d, 0xda, 0x9e, 0x80, 0xa5, 0x42, 0x55, 0x4e, 0x53, 0xf4, 0xcb, 0x84, 0x3c, 0xa9, 0x2d, 0x4e, 0x07, 0x18, 0x22, 0xc2, 0x71, 0x30, 0xa9, 0x08, 0xb3, 0x0a, 0x34, 0x2d, 0x70, 0x56, 0x1d, 0xd0, 0x89, 0xe6, 0xa0, 0x6c, 0x25, 0xcc, 0x0f, 0x19, 0x33, 0x9d, 0x76, 0x79, 0x92, 0xe9, 0x06, 0x84, 0x22, 0xba, 0x58, 0xe4, 0xd2, 0x73, 0x71, 0xfb, 0x60, 0xd3, 0x4d, 0x76, 0xab, 0xcf, 0xd5, 0x44, 0xea, 0xb3, 0xce, 0x24, 0x14, 0xd3, 0xd9, 0x67, 0xa3, 0x79, 0xf1, 0x2e, 0x16, 0x51, 0x37, 0xd3, 0x2c, 0x85, 0xf1, 0x32, 0xe0, 0xc8, 0x9f, 0x25, 0x89, 0xee, 0xb3, 0x57, 0x21, 0x90, 0x68, 0x8f, 0x1c, 0x44, 0xa4, 0x94, 0x1a, 0xd0, 0x7e, 0xf7, 0x9c, 0x46, 0xaa, 0xf7, 0x96, 0x61, 0x22, 0x74, 0x9b, 0x90, 0x6a, 0x15, 0x28, 0x57, 0x46, 0x33, 0x25, 0x21, 0x57, 0xef, 0x14, 0x7d, 0x39, 0x15, 0xa9, 0xf9, 0xa9, 0x2a, 0xcc, 0x6d, 0xd1, 0x87, 0xac, 0x78, 0x67, 0x52, 0x12, 0x41, 0xaa, 0x38, 0x2e, 0x27, 0x5a, 0x87, 0x16, 0x9f, 0xb0, 0xe4, 0x5a, 0xa0, 0xc0, 0x7f, 0xc8, 0xfa, 0x36, 0x0d, 0x73, 0x60, 0x28, 0x9e, 0xa1, 0xd9, 0xf6, 0x1e, 0x05, 0xe4, 0xaa, 0x4f, 0x23, 0xe0, 0x11, 0x60, 0x28, 0xb2, 0x99, 0xa9, 0x12, 0x0d, 0x13, 0x97, 0x08, 0x69, 0xca, 0xe9, 0xa1, 0x0e, 0x86, 0xef, 0x2b, 0xd0, 0xc9, 0x41, 0x14, 0x2c, 0x64, 0x7c, 0x64, 0x95, 0xde, 0xfa, 0x7c, 0x90, 0x58, 0x66, 0x5f, 0xc1, 0xb3, 0x89, 0x4e, 0x14, 0x7d, 0x14, 0x5c, 0xf6, 0xce, 0xd1, 0xb1, 0x23, 0xa8, 0x96, 0x3b, 0x06, 0x64, 0xf9, 0x24, 0x33, 0xbe, 0x3c, 0x13, 0x9c, 0x2f, 0x00, 0x64, 0xf2, 0x22, 0xcc, 0x6f, 0x82, 0x3a, 0x73, 0x54, 0x08, 0xd9, 0x1e, 0xcb, 0xaa, 0x59, 0x7e, 0x35, 0x37, 0x44, 0xb8, 0x90, 0x39, 0x5b, 0x34, 0x26, 0x2e, 0x4e, 0x5f, 0x12, 0x5d, 0xe4, 0x02, 0x91, 0x4c, 0xa6, 0x29, 0xfa, 0x90, 0x89, 0x58, 0x72, 0xfe, 0x1f, 0x3f, 0x26, 0x83, 0x19, 0x8d, 0xdb, 0x41, 0x5d, 0x3d, 0x1e, 0x37, 0x87, 0x82, 0x95, 0xe1, 0x00, 0xb0, 0x62, 0x40, 0x4f, 0xef, 0xa8, 0x91, 0x92, 0x29, 0x5b, 0x38, 0x07, 0x52, 0xf5, 0x1a, 0x41, 0x60, 0x1a, 0xdc, 0xed, 0xfc, 0xdd, 0x63, 0xaf, 0x36, 0xb2, 0x6a, 0x01, 0x49, 0x5d, 0xdb, 0x8b, 0xd7, 0x01, 0xf4, 0x85, 0x7f, 0x1d, 0x02, 0x77, 0xb8, 0x5d, 0xbd, 0x2a, 0xe8, 0x29, 0xb0, 0x71, 0xe7, 0xf2, 0x32, 0x30, 0x3e, 0xf4, 0x4e, 0x39, 0x4e, 0xc8, 0x53, 0x18, 0x7e, 0x35, 0x59, 0x89, 0x29, 0x1c, 0x03, 0xa0, 0x33, 0xd1, 0xed, 0x7a, 0xd2, 0x98, 0x02, 0x3f, 0xcc, 0xc9, 0xb2, 0xc2, 0x6b, 0x87, 0xcc, 0x3a, 0xa5, 0xfc, 0x10, 0xf5, 0xc8, 0xd6, 0xed, 0xdd, 0x2f, 0x3b, 0x7c, 0x94, 0x94, 0x11, 0xa6, 0x28, 0xeb, 0x10, 0x5e, 0xc1, 0xf6, 0x79, 0x21, 0xfe, 0x05, 0x16, 0x22, 0x7c, 0x14, 0x1d, 0x45, 0xc0, 0xa8, 0x66, 0x2f, 0xde, 0x1c, 0x94, 0x29, 0x99, 0x2f, 0x4f, 0xd6, 0x84, 0xd9, 0xf7, 0x41, 0x85, 0x48, 0x96, 0x97, 0x2a, 0xde, 0x10, 0xd1, 0x41, 0x65, 0xe9, 0xe9, 0xa8, 0x17, 0x76, 0x71, 0x70, 0x56, 0x39, 0x7f, 0x31, 0x58, 0x42, 0x11, 0xd7, 0xc2, 0x7d, 0x2d, 0x67, 0x7c, 0x29, 0x82, 0xd5, 0x7e, 0x2c, 0x22, 0x1d, 0xa8, 0xcc, 0xc9, 0xf3, 0x02, 0x7f, 0x12, 0x0b, 0x1c, 0x35, 0x35, 0xf0, 0xf4, 0x39, 0xb1, 0x7d, 0x5e, 0xe8, 0x0d, 0x8d, 0x70, 0x81, 0xea, 0x35, 0x6b, 0x84, 0xac, 0xe7, 0xd1, 0xb1, 0x44, 0xae, 0x57, 0x43, 0x69, 0xd2, 0x3a, 0x62, 0x0a, 0x70, 0x56, 0xdf, 0x68, 0x4d, 0x19, 0xa4, 0xb5, 0xc3, 0x24, 0xe6, 0x1c, 0xb0, 0x82, 0x3a, 0x49, 0xf4, 0xfe, 0x15, 0x32, 0x02, 0xc0, 0x0a, 0xe5, 0x84, 0xdf, 0x81, 0xf9, 0x4d, 0x8b, 0x21, 0x6a, 0xdc, 0x92, 0xc3, 0x41, 0xe1, 0x57, 0x02, 0xdc, 0x52, 0x49, 0x03, 0xe4, 0x7d, 0x18, 0xcf, 0xc1, 0x0f, 0x16, 0xbb, 0xc0, 0x0b, 0xe1, 0x3a, 0xdc, 0xa0, 0xd7, 0x4f, 0x08, 0xce, 0xc5, 0x53, 0x93, 0x82, 0x9d, 0x87, 0xd6, 0xd7, 0x67, 0x98, 0xd9, 0x85, 0xaa, 0x3e, 0xd5, 0x28, 0x33, 0x47, 0x8f, 0x0c, 0x61, 0x60, 0x39, 0x61, 0xc6, 0x3b, 0xa2, 0xea, 0xba, 0x90, 0x0c, 0x8a, 0xa8, 0xcf, 0xf0, 0x0f, 0x0e, 0x28, 0x9b, 0x21, 0x4d, 0x9c, 0x96, 0x84, 0xa0, 0x68, 0xa5, 0x6c, 0x4d, 0xf2, 0xf4, 0xea, 0x63, 0xd1, 0x05, 0x4f, 0x4a, 0x65, 0x9c, 0xb8, 0x69, 0xf9, 0x1e, 0xa7, 0x49, 0xd8, 0x3d, 0x22, 0xa8, 0xef, 0x10, 0x2c, 0xef, 0x13, 0xe6, 0xf5, 0xbc, 0x51, 0xb5, 0x88, 0x4e, 0x6d, 0xc4, 0xda, 0x78, 0xe1, 0x14, 0xf2, 0xa7, 0xc6, 0x9a, 0x4d, 0x72, 0x62, 0x6d, 0x69, 0x81, 0xda, 0x7d, 0x2e, 0x60, 0xb2, 0x26, 0x79, 0x1a, 0x2b, 0x1a, 0xd9, 0x99, 0x17, 0x79, 0x45, 0x23, 0x97, 0xff, 0x5b, 0x6a, 0x12, 0x8d, 0x1b, 0x1d, 0xeb, 0x00, 0xec, 0x67, 0x2f, 0xc7, 0xb3, 0x97, 0xe3, 0xd9, 0xcb, 0xf1, 0xec, 0xe5, 0x78, 0xd6, 0xbd, 0xbf, 0x04, 0xdd, 0xfb, 0xd9, 0xcb, 0xf1, 0xbc, 0x10, 0x1f, 0xc5, 0x42, 0xac, 0x1b, 0x81, 0xcf, 0x5e, 0x8e, 0xe7, 0x05, 0xfe, 0x97, 0x5e, 0xe0, 0x37, 0xcf, 0x5e, 0x8e, 0x67, 0x2f, 0xc7, 0xb3, 0x97, 0xe3, 0x09, 0x79, 0x39, 0xae, 0x70, 0x57, 0x5c, 0xe2, 0x79, 0x18, 0xc3, 0x28, 0x54, 0xb3, 0xea, 0x8d, 0x5a, 0x40, 0x50, 0x54, 0xc1, 0x51, 0x9b, 0xeb, 0xf1, 0x2c, 0x8c, 0x5c, 0x99, 0x20, 0x3d, 0x7c, 0x13, 0x9e, 0x62, 0x7d, 0x0b, 0x9e, 0x72, 0x2d, 0x7c, 0xeb, 0x6d, 0x2b, 0x01, 0x09, 0x56, 0x08, 0x24, 0x4a, 0xc3, 0x9c, 0x5e, 0x74, 0x78, 0x64, 0xdc, 0x8e, 0x73, 0x0b, 0xdc, 0xa0, 0x92, 0x6d, 0x95, 0x35, 0x6a, 0x3a, 0xa4, 0xaf, 0x27, 0x60, 0xd2, 0xab, 0xc1, 0xba, 0xbd, 0xa5, 0xd8, 0x00, 0x7e, 0x42, 0xe2, 0x46, 0x02, 0xbe, 0x74, 0x07, 0x95, 0x0b, 0xef, 0xee, 0x72, 0x2d, 0xde, 0x9c, 0xb3, 0x89, 0x57, 0x66, 0x66, 0x7a, 0xfa, 0x99, 0xcf, 0xeb, 0x9e, 0x49, 0x1d, 0xbe, 0x26, 0x9e, 0x9a, 0xf4, 0x5f, 0x37, 0x70, 0xee, 0xcc, 0x57, 0x83, 0xaa, 0x00, 0x30, 0x71, 0xe6, 0x53, 0x10, 0x66, 0x6b, 0x41, 0x79, 0x59, 0xe3, 0x43, 0x99, 0x23, 0x50, 0xc5, 0xa1, 0xcf, 0xc2, 0xaa, 0xa6, 0x01, 0x03, 0x38, 0xbf, 0xd2, 0xd1, 0xfc, 0x09, 0x02, 0x58, 0xbf, 0xb0, 0xac, 0x37, 0x40, 0xa9, 0xb5, 0x9e, 0x1e, 0x39, 0x01, 0x0d, 0x2c, 0xce, 0x9d, 0x22, 0xba, 0x84, 0x0a, 0x80, 0x49, 0xd8, 0x6e, 0x75, 0x45, 0xf7, 0x09, 0xaa, 0x13, 0x0b, 0xb9, 0x9e, 0x10, 0x53, 0x13, 0xd8, 0x69, 0xa5, 0x78, 0x79, 0xd5, 0xf9, 0x57, 0xe3, 0xce, 0x0a, 0xf7, 0x58, 0x4e, 0xfc, 0x5e, 0xdf, 0xc0, 0xd5, 0xd2, 0xe5, 0x75, 0x2b, 0x55, 0x89, 0xea, 0xdf, 0xdc, 0xf6, 0x09, 0xd2, 0x50, 0x3a, 0x5b, 0x88, 0xd5, 0xb2, 0xa4, 0x59, 0x12, 0x9c, 0x55, 0x2e, 0xb2, 0x1a, 0x6c, 0xae, 0x08, 0x43, 0x54, 0x04, 0x9e, 0x0d, 0x02, 0x85, 0xa8, 0x77, 0x43, 0xba, 0x9b, 0x28, 0xf4, 0x05, 0xe9, 0x7b, 0x7b, 0x20, 0xfa, 0x6e, 0x94, 0xda, 0x36, 0x5f, 0x4b, 0x09, 0x07, 0x91, 0xbf, 0x76, 0xf9, 0x52, 0xd2, 0xce, 0xe9, 0x4b, 0x5f, 0xae, 0x75, 0x81, 0xf8, 0x0b, 0x22, 0x36, 0xe1, 0x42, 0x16, 0xa4, 0x1a, 0x60, 0x49, 0x28, 0xcc, 0x63, 0xc2, 0x46, 0x9c, 0x43, 0x15, 0x89, 0xd5, 0x1e, 0xad, 0x82, 0xdb, 0x05, 0x08, 0xaf, 0x6e, 0xc8, 0x95, 0xc6, 0x53, 0xe0, 0x5a, 0x2c, 0x40, 0x98, 0x85, 0x92, 0x6f, 0x9b, 0x53, 0x26, 0x86, 0x95, 0x35, 0xe8, 0x6f, 0x6b, 0xd3, 0xfc, 0x92, 0x99, 0xb2, 0x94, 0x93, 0xb7, 0xaa, 0xce, 0xf5, 0xd2, 0x1b, 0xdc, 0x34, 0xaa, 0x2a, 0x3c, 0x3a, 0xb1, 0x73, 0x99, 0xa8, 0x7a, 0xbd, 0xd9, 0xc5, 0xe8, 0x2e, 0x61, 0xba, 0x3a, 0x4d, 0xca, 0x02, 0x86, 0x24, 0x2c, 0x56, 0x0d, 0x44, 0xd0, 0x27, 0x62, 0x48, 0x13, 0xc2, 0x2b, 0xdc, 0x0b, 0xa8, 0xf3, 0x1d, 0xa8, 0x54, 0xea, 0x1a, 0x29, 0x56, 0x9b, 0x47, 0xae, 0x39, 0xfd, 0x44, 0x05, 0xd9, 0x0f, 0xcd, 0x9a, 0xcd, 0xf1, 0x53, 0x5f, 0x29, 0x27, 0xe9, 0x09, 0x57, 0x11, 0x76, 0x92, 0x01, 0x43, 0x38, 0x75, 0x26, 0x42, 0x51, 0xcc, 0x56, 0x8f, 0x75, 0xc2, 0x2c, 0x52, 0xf4, 0xe5, 0xfa, 0xeb, 0x1c, 0x07, 0x82, 0x1d, 0x0c, 0xf2, 0xe4, 0x05, 0x4b, 0x8e, 0x4e, 0x69, 0xb4, 0xbe, 0x15, 0x38, 0x0c, 0x03, 0x9f, 0x83, 0xb4, 0x44, 0x2a, 0xfa, 0x8e, 0x9e, 0x57, 0xd6, 0x6c, 0x12, 0x7b, 0xde, 0x14, 0x5a, 0x19, 0x9d, 0xeb, 0x67, 0x41, 0x58, 0x00, 0xfa, 0xc6, 0xe2, 0xab, 0x0c, 0xb2, 0x37, 0x81, 0xcc, 0x79, 0x59, 0x32, 0x27, 0xf1, 0x66, 0x4c, 0xd8, 0xf2, 0xfd, 0x60, 0xe4, 0x05, 0xee, 0x26, 0xfd, 0xc1, 0xaa, 0xda, 0xa8, 0xf6, 0x14, 0x5c, 0xc9, 0xf2, 0x29, 0x7f, 0x2d, 0xdd, 0xa0, 0x2f, 0xba, 0x22, 0x4c, 0xa6, 0x92, 0x6f, 0x15, 0x45, 0x2d, 0x97, 0x8b, 0xa6, 0x62, 0xc4, 0x54, 0xe6, 0x5a, 0xec, 0x4b, 0x05, 0xa4, 0xa6, 0x9e, 0x54, 0x2f, 0x75, 0x3d, 0x63, 0xf7, 0x08, 0x68, 0x02, 0xc0, 0xeb, 0xc7, 0xdc, 0xb2, 0xd8, 0xe6, 0x11, 0x6a, 0x94, 0x90, 0x9e, 0x97, 0x80, 0x8d, 0xa3, 0x2e, 0x97, 0x7a, 0x8c, 0xf7, 0x56, 0xe6, 0xf9, 0x9e, 0x45, 0xe4, 0x0f, 0x9b, 0x5d, 0xb0, 0x96, 0x92, 0x43, 0x90, 0x9d, 0xea, 0x42, 0x4a, 0xc0, 0x45, 0xe2, 0x8c, 0xf4, 0x03, 0x1d, 0xbe, 0x28, 0xef, 0x2a, 0x25, 0x98, 0x41, 0x1b, 0x6b, 0x15, 0x35, 0x1e, 0xf4, 0x83, 0x97, 0x81, 0x5b, 0x81, 0xae, 0x7f, 0x24, 0xb4, 0x58, 0x0f, 0x27, 0xf0, 0xde, 0xb4, 0x34, 0x37, 0x2e, 0xfa, 0xed, 0xfa, 0x9a, 0x7a, 0x5c, 0x4c, 0x12, 0xb6, 0x36, 0x25, 0xa2, 0x58, 0xd1, 0x22, 0xd0, 0x99, 0x8e, 0x56, 0xa5, 0x31, 0x85, 0x48, 0xea, 0x40, 0x6d, 0xb3, 0xc8, 0x65, 0x07, 0xb2, 0x8f, 0x3a, 0x85, 0xb1, 0x1c, 0xa6, 0x0c, 0x53, 0xc2, 0xb0, 0x54, 0x28, 0x07, 0x95, 0x3a, 0x50, 0xc9, 0x90, 0x74, 0xa5, 0xe0, 0xb2, 0x01, 0x8a, 0xf9, 0x69, 0xd3, 0xc9, 0x29, 0x44, 0xb7, 0xd0, 0x06, 0x8b, 0x65, 0xa4, 0x4b, 0x90, 0x98, 0x0a, 0x52, 0xfc, 0x9b, 0x0c, 0x40, 0xba, 0x42, 0x77, 0x77, 0xc3, 0xd9, 0xaa, 0x82, 0x08, 0x50, 0x89, 0x07, 0xb5, 0x57, 0x0b, 0xf3, 0xd7, 0xac, 0x90, 0x51, 0x4d, 0x40, 0x69, 0x96, 0x46, 0xf1, 0x2b, 0x92, 0x25, 0x1f, 0xdd, 0x0e, 0xbf, 0x9a, 0xa0, 0x81, 0x6b, 0xd2, 0x15, 0xce, 0x56, 0xa9, 0xc8, 0x65, 0xae, 0x98, 0x4a, 0x56, 0xd5, 0xde, 0x47, 0x7a, 0x50, 0xb3, 0x6a, 0xd6, 0x81, 0x97, 0xf0, 0xce, 0x85, 0x3a, 0x63, 0xf9, 0xe3, 0xad, 0x47, 0xfc, 0x70, 0x3b, 0xbc, 0x4a, 0x23, 0x01, 0x1e, 0xcf, 0xd0, 0xca, 0xb7, 0x9f, 0xf6, 0x34, 0x27, 0xfe, 0x36, 0x4b, 0x75, 0x3f, 0xab, 0x0c, 0x2f, 0xb0, 0xf7, 0x5a, 0x46, 0x07, 0x13, 0xcb, 0xde, 0x01, 0xc3, 0x40, 0x68, 0x0d, 0x91, 0xe9, 0x28, 0x1f, 0xf7, 0x2e, 0x81, 0x97, 0xb5, 0x53, 0xee, 0x42, 0x2a, 0xaf, 0xa9, 0xb3, 0x59, 0xcd, 0x0d, 0x0c, 0x7c, 0xeb, 0x4f, 0xee, 0x8c, 0x6b, 0xd5, 0xd2, 0xbe, 0x4b, 0x22, 0x15, 0x17, 0x73, 0x7c, 0x21, 0x76, 0x00, 0x6d, 0xd2, 0x42, 0xa1, 0xb3, 0xc1, 0xe5, 0x8a, 0x74, 0x5e, 0x2c, 0x10, 0x80, 0xb8, 0xa8, 0xb4, 0x5b, 0x49, 0x00, 0x82, 0x23, 0x59, 0x8c, 0xab, 0x39, 0x42, 0xf6, 0x60, 0x68, 0xa9, 0x73, 0xc8, 0x77, 0xeb, 0x1d, 0x05, 0xa5, 0x96, 0xc6, 0x02, 0xa2, 0x94, 0x28, 0xfd, 0x8a, 0xb1, 0x6e, 0x9e, 0xc9, 0x46, 0x2e, 0xd9, 0xc5, 0x3f, 0x3d, 0x34, 0xd9, 0x88, 0x8b, 0x5f, 0x0e, 0xd9, 0xc8, 0xdb, 0x6a, 0x26, 0x39, 0x85, 0x22, 0x64, 0x44, 0xc3, 0x88, 0x8a, 0x4e, 0xdb, 0xf5, 0xd9, 0xe2, 0x0d, 0x3b, 0x3b, 0x47, 0x02, 0xda, 0x3c, 0x0c, 0xaa, 0x6a, 0x09, 0x56, 0x3b, 0x93, 0x11, 0x8b, 0x02, 0x37, 0xa4, 0x44, 0xfa, 0xb9, 0xda, 0xd7, 0xa3, 0xb7, 0xd7, 0x1e, 0xee, 0x6c, 0x83, 0x2c, 0x65, 0x2b, 0x90, 0x14, 0x39, 0xc6, 0x6b, 0xbd, 0x67, 0xab, 0xea, 0x5e, 0xdc, 0x9e, 0x26, 0xa8, 0x50, 0xeb, 0x62, 0xa2, 0x73, 0xcb, 0xf1, 0xfe, 0x3c, 0x64, 0x1b, 0x2e, 0x5f, 0x98, 0xab, 0x91, 0xf7, 0xf5, 0x78, 0x8b, 0x0b, 0x24, 0x17, 0xeb, 0x6c, 0x08, 0xf9, 0xd9, 0x06, 0xf9, 0x5c, 0x5b, 0xbd, 0x5a, 0x18, 0x03, 0x05, 0x73, 0x5f, 0x75, 0x7a, 0x67, 0xa8, 0x5e, 0x15, 0x7a, 0xb8, 0xe0, 0x41, 0xf3, 0xa6, 0x25, 0x89, 0x80, 0xfc, 0x11, 0xe0, 0x6d, 0xa2, 0x9a, 0xf6, 0x22, 0x13, 0x2a, 0xa3, 0xe3, 0x29, 0xd3, 0x88, 0xe5, 0xb3, 0xbb, 0x43, 0xbf, 0xd4, 0x2d, 0xa3, 0xc7, 0x57, 0x58, 0xa5, 0x6e, 0x37, 0x67, 0x9a, 0x48, 0x8f, 0x4a, 0xcf, 0x25, 0xc9, 0x80, 0xe7, 0x82, 0xe6, 0xa6, 0xa9, 0xde, 0xde, 0xc1, 0x20, 0x61, 0x84, 0x21, 0xd2, 0x06, 0x72, 0xdc, 0x49, 0xba, 0x2f, 0x3d, 0xf0, 0x18, 0xb6, 0xc2, 0x90, 0x35, 0x57, 0x7f, 0x3f, 0xad, 0xea, 0x54, 0x64, 0xae, 0xd1, 0xd7, 0xf4, 0x44, 0x6e, 0xd0, 0x52, 0x12, 0x33, 0x73, 0xa9, 0x12, 0x52, 0xbc, 0x61, 0xda, 0x06, 0x34, 0x5a, 0x43, 0xe7, 0x02, 0x99, 0xb3, 0x31, 0x90, 0x3f, 0x2d, 0xbd, 0x8d, 0x2e, 0x14, 0x2e, 0x86, 0xfa, 0x61, 0xdf, 0xe0, 0xb6, 0x1d, 0x3c, 0xd0, 0x29, 0x53, 0xc2, 0xe2, 0xf1, 0xeb, 0xc4, 0x0a, 0xe6, 0x8a, 0x4b, 0x24, 0x55, 0x3a, 0xd8, 0x71, 0xed, 0xec, 0x6a, 0x35, 0x9d, 0x9b, 0xfc, 0x0a, 0x73, 0xee, 0x64, 0xdf, 0x84, 0x18, 0xf8, 0x25, 0x92, 0x86, 0xb4, 0x17, 0x76, 0x41, 0x31, 0xaa, 0x00, 0xaa, 0x3e, 0x46, 0x2e, 0x8b, 0x99, 0x16, 0x90, 0x45, 0x00, 0x8f, 0x67, 0x8d, 0xc5, 0x77, 0x1a, 0x95, 0x2d, 0xac, 0x6b, 0x88, 0xd8, 0xb8, 0x89, 0xa4, 0xbc, 0x41, 0xc2, 0x39, 0xa2, 0xb8, 0xb5, 0x2c, 0xad, 0xe6, 0x64, 0xe2, 0x75, 0x9f, 0xda, 0x30, 0x15, 0x83, 0x73, 0x16, 0x5a, 0x2b, 0xb9, 0x08, 0x54, 0xf8, 0xf7, 0xd5, 0xab, 0x7d, 0x33, 0x16, 0x31, 0xe9, 0x52, 0x12, 0xe6, 0xab, 0x54, 0xc8, 0xcd, 0x64, 0xbc, 0x02, 0x29, 0x04, 0x33, 0xd6, 0x8f, 0xa3, 0x6e, 0x03, 0xb5, 0x0c, 0x19, 0x70, 0x1d, 0xc7, 0xab, 0x04, 0xfe, 0x82, 0xb5, 0x69, 0x72, 0xc9, 0x47, 0xd2, 0x44, 0xd3, 0x93, 0xf1, 0x84, 0xf1, 0xc9, 0x55, 0xf8, 0x1a, 0xb3, 0x1b, 0x96, 0xf9, 0x90, 0xec, 0x7a, 0x46, 0x85, 0x2c, 0xff, 0x3d, 0xfe, 0x60, 0x4e, 0xdc, 0x6d, 0x8b, 0x84, 0x77, 0x88, 0x92, 0x91, 0x03, 0x57, 0x64, 0x6b, 0x5a, 0xa7, 0xd1, 0x36, 0xbc, 0x41, 0x06, 0x20, 0x97, 0x93, 0x7d, 0x2d, 0xcc, 0x4a, 0x96, 0x22, 0xac, 0x0b, 0xaf, 0xfa, 0xac, 0x99, 0x2f, 0xa0, 0x73, 0x6c, 0x7a, 0x71, 0x6b, 0xbb, 0xb1, 0xcd, 0x6e, 0xec, 0xc9, 0x3e, 0xec, 0xc9, 0xe3, 0x59, 0x08, 0x8d, 0x94, 0x25, 0x5a, 0xf0, 0x7f, 0xc2, 0xe9, 0xe5, 0xd2, 0x78, 0x96, 0xc3, 0x4e, 0xc1, 0x2d, 0xba, 0xe1, 0x4d, 0xac, 0xd3, 0xba, 0x8d, 0xdb, 0xf1, 0xa7, 0xb5, 0xa3, 0x2c, 0xd7, 0xd2, 0x2a, 0x55, 0x41, 0x99, 0x76, 0x25, 0xf2, 0x7f, 0x2a, 0xbd, 0x1f, 0x9f, 0xf7, 0xf9, 0xf3, 0x3e, 0xff, 0x2b, 0xed, 0xf3, 0x89, 0xb2, 0x63, 0x17, 0xb4, 0x1c, 0xdb, 0xac, 0x78, 0xb0, 0x8c, 0xe9, 0x6b, 0x2b, 0x3b, 0x2b, 0x0d, 0xce, 0xb6, 0x72, 0x73, 0x62, 0xc5, 0x8b, 0xc1, 0x72, 0xf7, 0xa2, 0xb9, 0xe2, 0x9b, 0x31, 0x41, 0x6b, 0xcc, 0xbd, 0xb0, 0xbb, 0xbd, 0xfd, 0x7b, 0x8b, 0x9f, 0x3c, 0x00, 0xa5, 0x9b, 0x1b, 0xf1, 0xb7, 0xad, 0xd0, 0xac, 0xfd, 0x2c, 0xde, 0xa3, 0x18, 0x5b, 0xcd, 0xfe, 0x36, 0x43, 0xfa, 0xbb, 0xce, 0xec, 0x68, 0xc6, 0x30, 0xf7, 0x32, 0xb1, 0x55, 0x52, 0x22, 0xc0, 0x2d, 0x97, 0x27, 0xd2, 0xa5, 0xfc, 0x48, 0x3b, 0xbe, 0x5d, 0x2d, 0x5c, 0x39, 0x57, 0x76, 0x2d, 0x59, 0x15, 0xc0, 0xbc, 0x89, 0xd1, 0x19, 0x2a, 0x22, 0x45, 0x69, 0x18, 0xe8, 0x7a, 0xc8, 0xa0, 0x1f, 0x65, 0x73, 0x81, 0xf9, 0x3c, 0xab, 0xbe, 0x00, 0x53, 0x81, 0x0e, 0x61, 0x8b, 0x74, 0x39, 0xf3, 0x01, 0x53, 0x2d, 0xf8, 0x11, 0x14, 0xe8, 0x20, 0x5c, 0x26, 0x78, 0x13, 0x44, 0xa5, 0x19, 0x4b, 0x97, 0x11, 0x8b, 0x67, 0x63, 0x71, 0x27, 0xec, 0x1a, 0x54, 0xbe, 0x9c, 0x67, 0x20, 0x38, 0x33, 0x2f, 0x8f, 0x02, 0x35, 0xf8, 0x24, 0xe1, 0xe5, 0x85, 0x2a, 0x66, 0xc5, 0x02, 0x93, 0xb9, 0x5d, 0xc3, 0x4f, 0x29, 0x43, 0xcb, 0x89, 0x2f, 0xc3, 0xc9, 0xf2, 0x4d, 0x97, 0xe8, 0xe0, 0x8f, 0xae, 0x0d, 0xac, 0xfc, 0x5d, 0x74, 0xf6, 0x32, 0x8f, 0xbb, 0x99, 0x9d, 0xb6, 0xa5, 0xfe, 0x1c, 0x96, 0x28, 0x63, 0x04, 0x1c, 0x01, 0xc5, 0x70, 0xad, 0xa7, 0x55, 0xae, 0x5a, 0xf9, 0xdd, 0xd3, 0x1a, 0x76, 0x88, 0x01, 0x7a, 0x62, 0xae, 0xfa, 0x3f, 0x5a, 0x45, 0xe4, 0x8c, 0xed, 0xee, 0xd0, 0x5d, 0x9f, 0xba, 0xcb, 0xee, 0x7a, 0x85, 0xb2, 0xc7, 0x80, 0x58, 0x86, 0x8f, 0xba, 0xd3, 0x01, 0x6a, 0x5a, 0xe2, 0x56, 0x33, 0x88, 0xfd, 0x43, 0xed, 0x06, 0x95, 0x1c, 0xef, 0x8b, 0xbc, 0x96, 0x48, 0xec, 0xab, 0x2c, 0x96, 0x4a, 0xe2, 0x32, 0x93, 0xd2, 0x60, 0x05, 0x39, 0xbb, 0xe4, 0x9a, 0x81, 0xa1, 0x95, 0x9a, 0xd5, 0x0d, 0xab, 0xee, 0x30, 0x9e, 0xa6, 0x56, 0x1c, 0x20, 0x47, 0x8c, 0x97, 0x43, 0x52, 0x60, 0x9a, 0x96, 0xa1, 0x69, 0x59, 0xd1, 0x79, 0x07, 0x99, 0x0c, 0x91, 0xf3, 0x8f, 0xe9, 0x1a, 0x54, 0x2e, 0x28, 0xc9, 0x68, 0x71, 0x3a, 0x5a, 0xe9, 0xfb, 0xe6, 0x1e, 0xaf, 0x56, 0x39, 0x1a, 0x87, 0x03, 0xba, 0x74, 0x4d, 0xf4, 0xae, 0x35, 0xcf, 0x78, 0xad, 0x57, 0xfe, 0xb1, 0xc4, 0x06, 0xfe, 0xb8, 0x36, 0x36, 0x00, 0xaf, 0x2c, 0x50, 0x51, 0xba, 0xc6, 0x0b, 0x4d, 0xbf, 0x72, 0xb0, 0xb3, 0x7c, 0xf5, 0x05, 0x85, 0x07, 0xfe, 0x6c, 0x89, 0x00, 0xed, 0x14, 0xd6, 0x8f, 0xf2, 0x03, 0x9f, 0x1f, 0xeb, 0x6c, 0x17, 0x14, 0xc6, 0xdc, 0x60, 0x7f, 0xd4, 0x18, 0x37, 0x7b, 0x2e, 0xd4, 0x57, 0x0a, 0x1b, 0x10, 0xcd, 0x37, 0xe0, 0x81, 0xf5, 0xb6, 0x93, 0x93, 0x5f, 0xf0, 0xc4, 0x8e, 0xdb, 0x6e, 0xa0, 0xd7, 0xe0, 0x67, 0xd0, 0x2d, 0x15, 0x1f, 0xf8, 0xbc, 0x47, 0x33, 0xbf, 0x36, 0xfc, 0x6c, 0x46, 0xb8, 0x17, 0xd6, 0x18, 0x2c, 0xd3, 0xd0, 0xda, 0xbe, 0xad, 0xcc, 0x79, 0x64, 0x9e, 0xda, 0x51, 0x8a, 0x1b, 0xc5, 0xd0, 0xe1, 0x7a, 0x90, 0x49, 0xe0, 0x32, 0xc2, 0xcb, 0x89, 0x4a, 0xd6, 0x17, 0x30, 0x8d, 0x71, 0xb9, 0x35, 0x2a, 0x31, 0xaa, 0xe0, 0xa4, 0xf3, 0xf4, 0x73, 0x66, 0x1b, 0x16, 0x81, 0x64, 0xb0, 0x34, 0xcf, 0x08, 0xf5, 0x0f, 0xe3, 0x60, 0x0c, 0x24, 0xa7, 0xe5, 0x94, 0xbd, 0xc1, 0xd0, 0x3a, 0x66, 0x1c, 0x35, 0x8f, 0xa7, 0xfa, 0xdb, 0xb3, 0xe3, 0xa7, 0x24, 0x15, 0xd9, 0x84, 0xf0, 0x0c, 0x25, 0x23, 0xaa, 0x27, 0xf7, 0x67, 0xa8, 0xa1, 0x67, 0xbc, 0x63, 0xec, 0x6b, 0x4a, 0x28, 0xdf, 0xd3, 0xe4, 0x4e, 0xde, 0x08, 0xc3, 0xac, 0xf3, 0xf8, 0x9c, 0x08, 0x19, 0x17, 0x0a, 0xfa, 0xfa, 0xbe, 0x3a, 0xda, 0xc4, 0x9b, 0xc7, 0xaa, 0x1b, 0x95, 0xfb, 0x34, 0x9e, 0x48, 0x7e, 0x0d, 0x6a, 0x9c, 0x96, 0x3c, 0x6c, 0xad, 0x93, 0x06, 0x90, 0x0e, 0x42, 0x88, 0x18, 0xe3, 0xac, 0x5a, 0x8c, 0x68, 0xb2, 0xc1, 0x16, 0x9c, 0xe0, 0xb4, 0xfa, 0x0b, 0x17, 0x42, 0xac, 0xb7, 0x89, 0xd5, 0x36, 0x17, 0xc9, 0xbe, 0x20, 0x42, 0x7b, 0x9c, 0x50, 0x9f, 0x9b, 0xb7, 0xb2, 0xf9, 0x0c, 0xac, 0xec, 0xdb, 0xc0, 0xe6, 0xdd, 0xf9, 0xd4, 0x11, 0x12, 0xd1, 0x8e, 0x94, 0xf1, 0xf2, 0x69, 0x13, 0xfe, 0x8f, 0xac, 0xc4, 0x7a, 0xee, 0x4a, 0xd2, 0x0c, 0xe6, 0xfa, 0x79, 0xe4, 0xd7, 0xbb, 0x6f, 0x1a, 0xf2, 0x8b, 0x96, 0xeb, 0x30, 0x7e, 0x41, 0x19, 0x84, 0xb8, 0xb2, 0xe5, 0x79, 0xcc, 0xd8, 0xc7, 0x79, 0x85, 0x26, 0xc4, 0x14, 0x43, 0x95, 0x6b, 0xb4, 0x6e, 0x6f, 0x11, 0x4c, 0x0b, 0x39, 0xcd, 0x84, 0x29, 0x96, 0x40, 0x2a, 0x20, 0x31, 0x3d, 0xd8, 0x85, 0x36, 0xfc, 0x5f, 0x41, 0xee, 0x41, 0x70, 0xaa, 0x06, 0x13, 0x9e, 0xa5, 0x73, 0xe1, 0x88, 0x4a, 0x07, 0x14, 0x25, 0x8a, 0x13, 0xaf, 0xfd, 0x81, 0x73, 0x6d, 0xb3, 0xc2, 0xdb, 0x1c, 0x4a, 0x28, 0xfd, 0x25, 0xe2, 0x5b, 0x1f, 0xcc, 0x32, 0x49, 0x0b, 0x69, 0x17, 0xec, 0xd9, 0xa9, 0x06, 0x4a, 0xd4, 0x3d, 0x8c, 0x55, 0x98, 0xbf, 0xaa, 0x24, 0x62, 0x1e, 0xb8, 0xe4, 0xce, 0x29, 0x0f, 0x2b, 0xaf, 0x36, 0x5c, 0x5a, 0x98, 0x02, 0x3e, 0xef, 0x4a, 0x4f, 0xe6, 0xa2, 0x96, 0xe6, 0xa2, 0x87, 0x39, 0x9d, 0x77, 0x2b, 0x14, 0xee, 0xf5, 0x45, 0x5d, 0x2d, 0x30, 0x5e, 0x56, 0x01, 0x7a, 0x39, 0xa5, 0x91, 0x12, 0x24, 0xdb, 0x3a, 0xe9, 0xb4, 0xd7, 0xb9, 0xeb, 0x85, 0x5d, 0x1e, 0x12, 0xeb, 0x66, 0xdf, 0x0e, 0xc2, 0xc7, 0xb7, 0x39, 0x3f, 0x08, 0x0b, 0xc3, 0xc2, 0x27, 0xa7, 0x10, 0x83, 0x8b, 0xdc, 0x0a, 0x98, 0xc0, 0xbf, 0xe0, 0x8b, 0xaa, 0x6c, 0xde, 0x4a, 0x22, 0x01, 0x28, 0x6e, 0x00, 0xb7, 0x2d, 0x63, 0x11, 0xec, 0x93, 0xf9, 0x88, 0xd0, 0xd7, 0x41, 0x9c, 0x3f, 0xe0, 0xe6, 0x59, 0x3a, 0xbf, 0xef, 0x0c, 0x18, 0x14, 0x33, 0xf2, 0xb4, 0x0e, 0x41, 0xaa, 0xdc, 0xd6, 0xac, 0xac, 0xc7, 0x42, 0x55, 0x91, 0xd3, 0xcd, 0xef, 0x59, 0x6a, 0xbc, 0x04, 0x7f, 0x86, 0xbc, 0xba, 0x94, 0x47, 0x25, 0x3b, 0x09, 0xc2, 0xf0, 0x03, 0xce, 0x06, 0xf0, 0x9b, 0xcd, 0x96, 0x4b, 0x5e, 0x5b, 0x97, 0xa2, 0x2a, 0x0e, 0x54, 0xb9, 0xe3, 0x89, 0x49, 0x80, 0x57, 0xa7, 0x01, 0x8a, 0xde, 0x86, 0xab, 0xbd, 0x1e, 0xa9, 0x8f, 0x1b, 0xaa, 0x7a, 0xa7, 0xb1, 0x68, 0x1b, 0xc5, 0x6d, 0x98, 0x95, 0x84, 0x6b, 0x07, 0x79, 0xfc, 0x23, 0x99, 0x3c, 0xa1, 0xb9, 0xf3, 0x53, 0x37, 0x46, 0x8b, 0xa9, 0xb7, 0xb5, 0x2e, 0x01, 0x68, 0x48, 0x15, 0x28, 0xb7, 0x52, 0x07, 0x53, 0x40, 0x91, 0x30, 0xa6, 0x29, 0x66, 0x0f, 0xa6, 0x5f, 0x74, 0x50, 0xfa, 0xc1, 0x90, 0x31, 0x20, 0x69, 0x5e, 0xd9, 0x2c, 0x91, 0x0b, 0x92, 0x28, 0x8d, 0xa1, 0xc2, 0xcc, 0xfb, 0x5b, 0x9f, 0xcf, 0x33, 0xa2, 0xf1, 0x32, 0xa9, 0xf2, 0xea, 0x81, 0x11, 0x8d, 0xe9, 0x9d, 0x7e, 0x39, 0x2e, 0x8b, 0x77, 0xad, 0x24, 0x1a, 0x36, 0x6a, 0x39, 0x11, 0x38, 0xfb, 0xf2, 0xe3, 0xea, 0xa2, 0x69, 0xbe, 0x55, 0x34, 0x4d, 0x48, 0xa8, 0x0f, 0x96, 0xab, 0x95, 0x39, 0xa2, 0xf2, 0x63, 0x92, 0x45, 0xe2, 0x4b, 0x44, 0x16, 0x23, 0x4f, 0x65, 0x18, 0x99, 0x18, 0xc7, 0x2d, 0x1d, 0xe7, 0xb5, 0xf8, 0xc9, 0x74, 0xf3, 0x94, 0x5a, 0x91, 0xb1, 0xa3, 0x04, 0x36, 0x91, 0xcb, 0x43, 0x0a, 0x48, 0x62, 0xa4, 0x0a, 0x6c, 0xe8, 0x5a, 0xd0, 0x31, 0x1f, 0xe5, 0x74, 0x5c, 0xe8, 0x9c, 0xe0, 0x67, 0x54, 0x67, 0x5d, 0xbb, 0x76, 0x58, 0x06, 0xff, 0xcc, 0x6c, 0x63, 0x8c, 0x7b, 0x20, 0x37, 0x61, 0xe4, 0x83, 0x84, 0xfe, 0x53, 0xdf, 0xab, 0xe9, 0x7f, 0x16, 0x6f, 0x24, 0xe6, 0xfe, 0x80, 0x1b, 0x4a, 0xb2, 0xdb, 0x97, 0xcc, 0x25, 0xe7, 0x90, 0x8e, 0xa2, 0xd9, 0x7d, 0x3c, 0xdd, 0xfd, 0xbd, 0xae, 0xd5, 0xcb, 0xb6, 0xef, 0x9b, 0xcd, 0xce, 0x28, 0x5d, 0x57, 0x0a, 0xd2, 0x7b, 0xa3, 0x15, 0x95, 0xa4, 0xaf, 0x73, 0x73, 0x90, 0xda, 0xb9, 0x39, 0x06, 0x94, 0xb5, 0xba, 0xb6, 0x46, 0x4c, 0xdf, 0x10, 0x83, 0x70, 0xc3, 0x66, 0x2e, 0x6e, 0x6f, 0xfc, 0x70, 0xb0, 0x39, 0x20, 0xc3, 0x45, 0xff, 0x48, 0x94, 0x85, 0x4d, 0xf0, 0x68, 0x10, 0x87, 0x2e, 0xf8, 0xf6, 0xda, 0xf4, 0x42, 0x05, 0x39, 0x5f, 0x3c, 0xd5, 0x59, 0xc0, 0xcd, 0xc1, 0x71, 0x0d, 0x3b, 0xa6, 0x3b, 0x50, 0xb6, 0x4e, 0x7b, 0xe7, 0x44, 0x1f, 0x66, 0x09, 0x04, 0x80, 0x9a, 0x83, 0xb7, 0xff, 0xb6, 0xa5, 0x5e, 0x48, 0x26, 0x09, 0x80, 0xc3, 0x57, 0xae, 0x55, 0x2d, 0x62, 0x45, 0xb3, 0xe0, 0x12, 0x5c, 0x6c, 0x46, 0x80, 0x37, 0x3f, 0x7a, 0xcd, 0x31, 0xad, 0x8e, 0x3d, 0x13, 0x54, 0x98, 0x51, 0x12, 0xb5, 0x9a, 0xb4, 0x48, 0x64, 0x85, 0xbe, 0x3b, 0x26, 0xf2, 0x64, 0xae, 0x32, 0xb9, 0x1d, 0xf6, 0xd3, 0xb4, 0x3b, 0x56, 0x29, 0x1f, 0xe8, 0xd7, 0xdb, 0x67, 0xfa, 0x98, 0x05, 0xaf, 0xe0, 0x23, 0xcf, 0x0b, 0x7a, 0x38, 0x41, 0xf1, 0x36, 0x59, 0x0f, 0x6b, 0x6b, 0x44, 0x9f, 0xcb, 0x6e, 0x20, 0xd1, 0x43, 0x74, 0x1e, 0x07, 0xd5, 0xa0, 0xac, 0xdf, 0x13, 0xf5, 0x0e, 0xb4, 0x20, 0xd4, 0x10, 0x1e, 0x46, 0xe5, 0x58, 0xb3, 0x0a, 0xc8, 0xce, 0x82, 0xec, 0x69, 0xc4, 0x9a, 0xca, 0xeb, 0x7d, 0x06, 0x55, 0x4d, 0x83, 0xde, 0x48, 0x1a, 0x22, 0xfd, 0x4f, 0x5b, 0x73, 0x58, 0x97, 0x4c, 0x7f, 0x93, 0xab, 0xc9, 0xa6, 0x63, 0xa6, 0x4c, 0x38, 0x75, 0x9d, 0x2c, 0x11, 0x6b, 0xa9, 0xda, 0x1e, 0x52, 0x37, 0xb3, 0xda, 0xd0, 0xcc, 0xd8, 0xf0, 0x55, 0x8e, 0xac, 0x99, 0xa6, 0x74, 0xc9, 0x4b, 0xdd, 0x68, 0x2a, 0x0e, 0xab, 0x88, 0x7c, 0x60, 0x49, 0xde, 0xa6, 0x2b, 0xc5, 0x2c, 0x88, 0xfb, 0xf8, 0x99, 0x96, 0xd2, 0x6a, 0xda, 0x29, 0x7d, 0x2f, 0xde, 0x01, 0xd3, 0x62, 0x2c, 0x39, 0x6d, 0xf4, 0xaf, 0xcc, 0xc1, 0xa8, 0x57, 0x17, 0xf5, 0xe1, 0x89, 0x92, 0x2e, 0xbd, 0xfb, 0xd0, 0x96, 0x0c, 0x2e, 0xbb, 0x0d, 0xc2, 0x19, 0x15, 0x9a, 0xeb, 0xc9, 0x53, 0x0b, 0x49, 0x0b, 0xe3, 0xeb, 0x0f, 0xd6, 0x35, 0x0f, 0x5a, 0x5b, 0xaf, 0xd4, 0x88, 0xe4, 0x68, 0xdc, 0xac, 0x9a, 0xab, 0xc8, 0xe6, 0xf3, 0x5f, 0xf0, 0x78, 0x86, 0xd7, 0xb7, 0x53, 0xae, 0x9e, 0xb6, 0x5e, 0x6d, 0x36, 0xdc, 0x1a, 0x15, 0x88, 0x32, 0x43, 0x86, 0xdc, 0xd3, 0xcb, 0xef, 0x7d, 0xf7, 0xb1, 0xc9, 0x61, 0x61, 0xd8, 0xe3, 0x6d, 0x15, 0x6a, 0xd0, 0x62, 0x75, 0x94, 0x6d, 0x7e, 0x78, 0x81, 0x7d, 0x48, 0xcc, 0xb6, 0x12, 0x59, 0xe5, 0x52, 0x9f, 0x27, 0xab, 0xaf, 0x4e, 0x96, 0xbb, 0x6b, 0x6d, 0x0f, 0xd7, 0x0a, 0x09, 0x37, 0xcb, 0x4f, 0x97, 0xf2, 0xd5, 0x13, 0xc3, 0x96, 0xac, 0x71, 0xa8, 0xda, 0x9d, 0xcc, 0xba, 0x36, 0xff, 0x4d, 0xbd, 0x35, 0x87, 0x86, 0xeb, 0xe3, 0x85, 0x5a, 0x0b, 0xdf, 0x9e, 0xa1, 0xaf, 0x8e, 0x71, 0xc6, 0xfe, 0xf8, 0xb8, 0xd9, 0x69, 0x2f, 0xf8, 0xa8, 0x1a, 0xc7, 0x92, 0x81, 0x12, 0xb2, 0x7d, 0x5a, 0x31, 0xd5, 0x40, 0x95, 0xde, 0x4f, 0x7b, 0x74, 0x40, 0x4a, 0xe0, 0x76, 0xb7, 0xe4, 0xfd, 0x64, 0xf2, 0xd6, 0x9b, 0xb0, 0x87, 0xea, 0xd4, 0xd4, 0x97, 0x1c, 0x84, 0xc3, 0x72, 0x4a, 0x99, 0xaa, 0xc3, 0xf4, 0x60, 0x5d, 0x84, 0x63, 0x01, 0x76, 0x80, 0x33, 0x86, 0x60, 0x7e, 0xa1, 0x73, 0x8b, 0xfd, 0xe6, 0x00, 0xcf, 0x72, 0x70, 0x6c, 0xe0, 0x14, 0x4f, 0x4f, 0xe1, 0xab, 0xaf, 0xe5, 0xbc, 0x27, 0xbb, 0xbd, 0x51, 0xcb, 0x66, 0xb2, 0x55, 0x04, 0x46, 0xa9, 0xcc, 0xe7, 0x31, 0x48, 0x8a, 0xb4, 0x56, 0x18, 0x34, 0xdb, 0x58, 0x49, 0x85, 0x51, 0xe2, 0x6a, 0x51, 0xf1, 0x5b, 0x35, 0xd6, 0xa6, 0x7a, 0x06, 0x51, 0xbd, 0x93, 0xa2, 0xa4, 0x5b, 0x9a, 0x9c, 0x66, 0xa7, 0x76, 0xf1, 0x13, 0x93, 0x91, 0x96, 0x58, 0x9c, 0xdc, 0x05, 0xe6, 0x1a, 0x45, 0xe8, 0xf8, 0x96, 0xf8, 0x46, 0x57, 0x10, 0x83, 0x99, 0x1d, 0x64, 0xf8, 0xf9, 0x3e, 0xf5, 0x70, 0x7a, 0xf0, 0x16, 0x67, 0x2e, 0x0e, 0xcb, 0x80, 0xf5, 0xc1, 0x74, 0x98, 0xf3, 0x1b, 0x96, 0x19, 0x90, 0x80, 0xe7, 0x1c, 0x51, 0xf4, 0x6d, 0x93, 0xdb, 0xbc, 0x44, 0x0c, 0x09, 0x29, 0x23, 0x88, 0xfe, 0x46, 0x21, 0xdd, 0xf5, 0x6d, 0x66, 0xc6, 0x92, 0x55, 0x54, 0xbd, 0xf2, 0xd5, 0xa3, 0x9a, 0x00, 0x48, 0x0e, 0x0a, 0x4f, 0x23, 0x2b, 0xb7, 0xb4, 0xc8, 0x19, 0x2e, 0x91, 0x8e, 0xbd, 0x89, 0x5e, 0xd8, 0x38, 0x15, 0xd6, 0xf3, 0x09, 0x2e, 0x0a, 0xba, 0x25, 0xf1, 0x1c, 0x01, 0xc1, 0x63, 0x97, 0x68, 0x51, 0x4f, 0xf7, 0x11, 0x84, 0x6c, 0xcf, 0x41, 0x9e, 0x6c, 0x7f, 0xd1, 0xba, 0x57, 0x99, 0x0b, 0x0c, 0x2c, 0x1e, 0x26, 0xb7, 0xa7, 0x37, 0xb3, 0x48, 0x5a, 0x3b, 0x9a, 0xc7, 0x78, 0x35, 0xf1, 0x22, 0xdf, 0x69, 0xab, 0xea, 0x84, 0x38, 0x37, 0x92, 0x61, 0xf6, 0xe0, 0xb0, 0xa5, 0x48, 0x82, 0x45, 0xb6, 0x76, 0x06, 0xa0, 0x2b, 0xc8, 0x4c, 0xc8, 0x39, 0x0b, 0xb0, 0x54, 0x56, 0xe6, 0x15, 0x4e, 0x15, 0x11, 0xe0, 0x74, 0xf7, 0xcc, 0xd0, 0x95, 0xee, 0x6a, 0xb8, 0x34, 0x99, 0x9f, 0x90, 0x7a, 0xf9, 0xfa, 0xd5, 0xab, 0xaf, 0x9a, 0x9a, 0xff, 0x92, 0x97, 0xf1, 0x4e, 0x07, 0xa8, 0xd8, 0x24, 0xe2, 0xec, 0x29, 0xde, 0xd0, 0xab, 0x53, 0x55, 0xa0, 0x05, 0xee, 0x60, 0x0d, 0xc0, 0x5c, 0x83, 0xa5, 0x6c, 0xce, 0x7f, 0x02, 0x27, 0x50, 0x1c, 0x17, 0x74, 0xb6, 0x30, 0xe7, 0xaf, 0xbe, 0xb6, 0x77, 0x39, 0x6d, 0xb9, 0xab, 0x26, 0xb8, 0x61, 0xf7, 0x52, 0x21, 0xc5, 0x3a, 0xe8, 0x55, 0x20, 0xd0, 0xf4, 0xe0, 0xc5, 0x86, 0xe9, 0x5b, 0x65, 0x69, 0x96, 0xb9, 0xf9, 0xd7, 0xbc, 0xea, 0xa9, 0xc7, 0x7a, 0xfe, 0xaa, 0x21, 0x11, 0x87, 0xa8, 0xbb, 0x58, 0x8e, 0xac, 0xeb, 0x70, 0xc1, 0x93, 0x3d, 0xeb, 0xe0, 0x31, 0x9c, 0xb2, 0x0f, 0x33, 0x22, 0xc8, 0x9f, 0xdf, 0x9b, 0x86, 0xa9, 0x23, 0xb8, 0x5b, 0xbc, 0x58, 0x11, 0x6f, 0xab, 0xd0, 0xba, 0x7a, 0x6c, 0xb5, 0x8d, 0xd8, 0x96, 0xca, 0xdd, 0x3a, 0xc9, 0x42, 0xdd, 0x84, 0x8d, 0xcd, 0x06, 0xb1, 0x61, 0xf3, 0xca, 0xe6, 0x08, 0x77, 0x86, 0x71, 0x59, 0xdd, 0x06, 0xde, 0x55, 0xd2, 0xb2, 0xe5, 0x65, 0x56, 0xe8, 0x0a, 0x38, 0x07, 0x68, 0x0c, 0x10, 0x83, 0x94, 0x4f, 0xcf, 0x2a, 0x6d, 0xa5, 0xb2, 0x94, 0x7c, 0xba, 0xce, 0x5f, 0x15, 0x73, 0xe1, 0xb0, 0x0a, 0x98, 0x31, 0x80, 0xca, 0x36, 0x18, 0x47, 0x81, 0x15, 0x04, 0x08, 0xee, 0x76, 0xd7, 0x65, 0xe5, 0xaf, 0x08, 0xa0, 0xc4, 0x4c, 0xb1, 0x51, 0xed, 0x28, 0x3e, 0x47, 0x4f, 0x26, 0x9b, 0xe9, 0x8f, 0xcd, 0x4e, 0xc9, 0x70, 0xae, 0x77, 0x95, 0x69, 0x9f, 0x8b, 0xc9, 0x3a, 0xa8, 0x46, 0x39, 0x60, 0x85, 0x7e, 0x9a, 0x4e, 0xce, 0xf7, 0x55, 0x34, 0xf5, 0x21, 0x07, 0xf5, 0x56, 0x58, 0x5b, 0x53, 0x5b, 0x23, 0x27, 0x7e, 0x61, 0x22, 0x27, 0xe7, 0x1b, 0x28, 0x2e, 0xdc, 0xa3, 0x19, 0xd7, 0x66, 0xa8, 0x78, 0x50, 0x60, 0xfa, 0xfa, 0x6d, 0xb1, 0x07, 0xe9, 0xf8, 0x82, 0xf4, 0xe7, 0x5c, 0x81, 0x90, 0xcb, 0x0e, 0x91, 0x35, 0x86, 0x29, 0x63, 0x82, 0x8b, 0x13, 0xe9, 0x65, 0x9a, 0x77, 0xab, 0xea, 0xe7, 0xc3, 0x0d, 0x91, 0x8c, 0x8e, 0xc8, 0x7e, 0xf6, 0xca, 0x50, 0xc9, 0x28, 0xce, 0x56, 0x70, 0xbc, 0xd7, 0x1d, 0xd5, 0x66, 0x94, 0x39, 0x33, 0xb6, 0x6a, 0x81, 0x35, 0x7d, 0xaf, 0xad, 0x7d, 0x1d, 0x5a, 0x19, 0x0a, 0xed, 0x04, 0x85, 0xbb, 0xcb, 0x4f, 0xb8, 0xa4, 0xcd, 0xc6, 0x46, 0x65, 0x32, 0xaa, 0xb3, 0x9a, 0x0c, 0x9b, 0x7e, 0xcf, 0xfc, 0x8f, 0xb0, 0xa4, 0xd2, 0x2e, 0x55, 0xd7, 0x04, 0x39, 0xdd, 0x78, 0x87, 0xe2, 0x92, 0xa2, 0xf5, 0x74, 0xa4, 0x92, 0x03, 0xa0, 0xc8, 0xa6, 0x97, 0x53, 0x8f, 0x6b, 0x4c, 0x29, 0xdc, 0x47, 0xbd, 0x00, 0xb9, 0x6e, 0x2c, 0xf5, 0xb9, 0xe2, 0xb6, 0x0b, 0x31, 0xfd, 0xda, 0xaf, 0x5a, 0x24, 0xdf, 0x05, 0x38, 0x4f, 0xbf, 0x2e, 0x29, 0x17, 0x30, 0xf0, 0x57, 0xdc, 0xa4, 0x3a, 0x72, 0x25, 0x15, 0x1f, 0x47, 0x86, 0x04, 0x9b, 0x7a, 0x8b, 0x0a, 0xde, 0xa3, 0x62, 0x91, 0xb1, 0x3a, 0x6f, 0x97, 0xe3, 0x38, 0x13, 0xb9, 0x76, 0x27, 0x04, 0x5a, 0xf2, 0x0b, 0x13, 0x67, 0x2d, 0xa4, 0x27, 0x79, 0xab, 0x07, 0x79, 0xe5, 0xb8, 0xf3, 0xfd, 0xfa, 0xe0, 0x4d, 0x2d, 0xde, 0x9a, 0xda, 0x63, 0x6d, 0x33, 0xc3, 0xce, 0xad, 0xb6, 0x3f, 0x38, 0xae, 0x40, 0x3d, 0x67, 0x30, 0xf7, 0x70, 0x86, 0xe0, 0xf5, 0x34, 0xb7, 0x9c, 0xa6, 0x1f, 0x17, 0xf0, 0xdb, 0xae, 0xae, 0x2b, 0xac, 0x51, 0x9f, 0x17, 0xe6, 0xf4, 0x50, 0x02, 0xe6, 0x5e, 0xdb, 0xc0, 0xa2, 0x48, 0x3a, 0xb8, 0xbf, 0x44, 0x20, 0x2d, 0x58, 0xf6, 0xf3, 0xed, 0x09, 0xb5, 0xd0, 0x5a, 0xb5, 0xbe, 0xdb, 0x2a, 0xbc, 0x59, 0x16, 0x0c, 0xba, 0x3a, 0x22, 0xef, 0xef, 0x51, 0x93, 0x65, 0x1f, 0x44, 0xcb, 0x03, 0xe1, 0xee, 0x8f, 0x66, 0x2f, 0xf8, 0x96, 0xd7, 0x71, 0xb6, 0xbb, 0x3e, 0x97, 0xb8, 0xf8, 0xf6, 0x74, 0x5d, 0x1d, 0xe4, 0xad, 0xbf, 0x22, 0xae, 0x45, 0x66, 0x04, 0x69, 0x3f, 0x32, 0x53, 0xbd, 0x53, 0xad, 0x49, 0x8d, 0x3c, 0x18, 0x7e, 0x61, 0x5b, 0x73, 0x26, 0xfb, 0x34, 0x2c, 0x04, 0x38, 0x51, 0xa7, 0x32, 0xe8, 0x95, 0x20, 0xa0, 0x92, 0x7c, 0x9b, 0x10, 0x1f, 0x41, 0xad, 0x85, 0xab, 0x6a, 0xb7, 0x25, 0x86, 0x92, 0xf5, 0x18, 0xd5, 0xd9, 0x31, 0x31, 0x01, 0xd5, 0xab, 0x4f, 0x3b, 0x87, 0xaf, 0x8c, 0x85, 0x5d, 0x22, 0x23, 0x36, 0x3a, 0x17, 0x37, 0xab, 0x46, 0x11, 0x7b, 0xc5, 0x0d, 0x56, 0x42, 0x92, 0x11, 0x0d, 0x04, 0xe7, 0x6a, 0x17, 0x6d, 0xcb, 0xd7, 0xa9, 0xba, 0x7a, 0x91, 0xc1, 0x15, 0xce, 0x33, 0xb4, 0x4e, 0x4e, 0x28, 0x0f, 0x53, 0x62, 0x8b, 0xc7, 0x56, 0x27, 0x2b, 0xbd, 0x51, 0xdd, 0x7e, 0xd9, 0xfa, 0xae, 0x82, 0x4f, 0xef, 0x5b, 0x35, 0xf8, 0xb0, 0x6c, 0x6a, 0x51, 0xf7, 0xb1, 0x12, 0xdf, 0x19, 0xe9, 0xa0, 0xc7, 0x7a, 0x2e, 0xa8, 0x20, 0xd3, 0x84, 0x2d, 0x17, 0x75, 0xa4, 0x92, 0xb9, 0xfa, 0x80, 0x95, 0xa1, 0x28, 0x81, 0x9b, 0x1c, 0xa9, 0x1e, 0x02, 0x01, 0x0a, 0xfe, 0x9b, 0xeb, 0xed, 0xc9, 0x23, 0x7d, 0xa6, 0x6a, 0x55, 0x6e, 0x49, 0x00, 0xe8, 0x0c, 0xd8, 0x1e, 0x4b, 0x99, 0xf9, 0x94, 0x88, 0xfd, 0xe8, 0x96, 0xb2, 0x39, 0x38, 0x01, 0xde, 0x21, 0x65, 0x15, 0x49, 0xb1, 0x41, 0x34, 0xb4, 0xa5, 0xc5, 0x3b, 0xef, 0x94, 0x4a, 0x6a, 0xc1, 0x89, 0x30, 0x0e, 0xdf, 0x30, 0xe1, 0xe1, 0x97, 0xb4, 0x9e, 0x24, 0x2f, 0xd2, 0xff, 0x09, 0x35, 0x17, 0x5e, 0x11, 0x0d, 0x39, 0x69, 0x1d, 0x85, 0xba, 0xa0, 0x4e, 0x68, 0x5b, 0x77, 0x32, 0x56, 0xc2, 0xff, 0x3e, 0x06, 0x3d, 0x65, 0xe3, 0x91, 0x19, 0xb2, 0x5d, 0x20, 0xd0, 0x07, 0x29, 0x82, 0x0f, 0x95, 0x2a, 0x0a, 0x69, 0x71, 0xee, 0x74, 0xb8, 0xc8, 0x2a, 0x5a, 0x53, 0xaf, 0x05, 0x0d, 0x6b, 0xe6, 0x89, 0xc3, 0xfa, 0xc5, 0x8f, 0x4b, 0x00, 0x78, 0x5f, 0x98, 0x5a, 0xeb, 0x25, 0x0d, 0x94, 0x07, 0x69, 0x3c, 0x7b, 0x6c, 0x57, 0x8b, 0x84, 0xef, 0x1b, 0x22, 0xc1, 0x46, 0xd1, 0xb9, 0xb2, 0x7a, 0x57, 0x08, 0x82, 0x99, 0x9b, 0x23, 0x72, 0x95, 0x0d, 0xac, 0x5b, 0x2b, 0xcd, 0x51, 0x77, 0x90, 0x30, 0x72, 0xc0, 0xfa, 0x62, 0x94, 0xfd, 0x05, 0xde, 0xf8, 0x8c, 0x56, 0xaf, 0x5b, 0xcd, 0x82, 0x82, 0xc1, 0xd3, 0x50, 0x70, 0xe4, 0x0c, 0x73, 0xd8, 0xb8, 0x92, 0xac, 0xd6, 0x48, 0x86, 0xaf, 0x5d, 0xc8, 0x30, 0x71, 0xe9, 0xa4, 0xfd, 0x12, 0x8a, 0x30, 0x3c, 0x9c, 0xde, 0xff, 0xfd, 0x66, 0x97, 0x9e, 0xf1, 0xca, 0x2d, 0x77, 0xdd, 0x62, 0xbf, 0xb3, 0xad, 0xf2, 0x30, 0x23, 0xc2, 0xd3, 0xa9, 0xd6, 0x94, 0x64, 0x2a, 0x90, 0x75, 0x8e, 0xbf, 0xb9, 0x43, 0x9b, 0x48, 0x0b, 0x48, 0x68, 0x01, 0x0f, 0x0a, 0xd7, 0x45, 0x04, 0xa0, 0x58, 0x2e, 0x77, 0xa4, 0xf8, 0x1c, 0xf6, 0x65, 0x61, 0x1f, 0x34, 0x61, 0x81, 0xc1, 0x1f, 0x98, 0x03, 0x58, 0xb9, 0x4e, 0x6d, 0x1b, 0x15, 0x2d, 0x2a, 0xd4, 0xce, 0x34, 0xb1, 0x19, 0xcb, 0x13, 0x9c, 0xb2, 0xb1, 0xe9, 0x66, 0xd7, 0xf5, 0x50, 0xd5, 0xa3, 0x5b, 0xcf, 0x57, 0x83, 0x21, 0x4e, 0x02, 0x4e, 0x31, 0x05, 0x20, 0xad, 0x8b, 0x9d, 0x3a, 0x3f, 0xc1, 0x99, 0x17, 0x4e, 0x9d, 0x1b, 0xa1, 0x6e, 0x2e, 0x0f, 0x9d, 0x62, 0x8f, 0xe1, 0x94, 0x7a, 0xb8, 0xad, 0x57, 0xad, 0x82, 0x98, 0xf3, 0x19, 0xb9, 0xd8, 0xaa, 0x21, 0xd0, 0xbe, 0x56, 0x71, 0x2d, 0x0b, 0x7d, 0x2d, 0x80, 0x65, 0x3c, 0x21, 0xe5, 0x94, 0x6d, 0xef, 0x24, 0x53, 0x3b, 0x84, 0xd8, 0x72, 0x4d, 0x26, 0xaa, 0xd9, 0x5a, 0x98, 0x45, 0x9a, 0x50, 0x66, 0x71, 0x6c, 0x24, 0x38, 0xda, 0xbf, 0xfe, 0xe1, 0xb3, 0x71, 0xda, 0x36, 0xcf, 0xdf, 0xf2, 0x00, 0xe0, 0x05, 0xef, 0x5c, 0x54, 0x6b, 0x13, 0x7a, 0xab, 0x3e, 0x70, 0x33, 0x8d, 0x52, 0x61, 0xa5, 0xe5, 0x27, 0xb6, 0x51, 0xaa, 0x99, 0x75, 0x07, 0x4a, 0xc6, 0x5d, 0x19, 0xda, 0xad, 0x17, 0x1b, 0x29, 0xee, 0x7e, 0x9d, 0x01, 0x7f, 0x7b, 0xa6, 0xb9, 0xe2, 0xdc, 0x79, 0x45, 0xce, 0x7f, 0x09, 0xf0, 0xd4, 0x00, 0xd8, 0x3e, 0x7d, 0x44, 0x00, 0x19, 0x06, 0xaf, 0x34, 0x58, 0x2e, 0x99, 0x6c, 0x6c, 0xf0, 0x03, 0x5d, 0x6b, 0x09, 0x26, 0x0e, 0x67, 0x1d, 0x32, 0x5c, 0x79, 0x22, 0xef, 0xa1, 0x84, 0x7c, 0xb7, 0x64, 0xeb, 0xa8, 0x4a, 0xd1, 0x74, 0xba, 0x8b, 0xf9, 0x1d, 0xf8, 0x6c, 0x87, 0xed, 0x4b, 0x79, 0x50, 0x3c, 0xe8, 0x38, 0x0d, 0x58, 0xc2, 0x19, 0xaa, 0x17, 0x8f, 0x50, 0x5f, 0x77, 0x19, 0x9f, 0xef, 0x01, 0xb2, 0x7d, 0xd5, 0xf4, 0x46, 0x7a, 0x7c, 0xd5, 0x03, 0x84, 0xfa, 0xb3, 0x2c, 0x38, 0xa3, 0x65, 0x53, 0xf2, 0xe1, 0xa1, 0x1b, 0x69, 0xf1, 0x25, 0x8b, 0x2d, 0x9e, 0xcd, 0x0f, 0x74, 0x41, 0x45, 0x14, 0xa8, 0x1b, 0xb6, 0x86, 0x12, 0x08, 0xaf, 0xab, 0x34, 0xff, 0xff, 0xdb, 0xfb, 0x96, 0xe6, 0x58, 0x96, 0xe3, 0xbc, 0xbf, 0x72, 0x02, 0xbe, 0x8b, 0x33, 0x11, 0x03, 0xb9, 0xeb, 0x5d, 0xb5, 0x3a, 0x61, 0xcb, 0x94, 0x44, 0x4b, 0x94, 0x28, 0x5e, 0x8a, 0xa4, 0x38, 0xc0, 0xd2, 0x0b, 0x6d, 0xe4, 0x8d, 0x16, 0x8e, 0x50, 0x5f, 0xfd, 0x76, 0x57, 0x3e, 0xaa, 0xba, 0xa7, 0x3b, 0xb3, 0xa7, 0x67, 0x06, 0xc0, 0x01, 0x88, 0xa3, 0x30, 0x7d, 0x0f, 0x80, 0xae, 0x47, 0x57, 0xd7, 0x23, 0x2b, 0xf3, 0xcb, 0xef, 0x0b, 0x6d, 0x0a, 0x1c, 0x44, 0x47, 0xb0, 0x70, 0xf6, 0x86, 0xcf, 0x9a, 0xd5, 0xf3, 0x9b, 0x7f, 0x50, 0x5d, 0xbe, 0x13, 0xfc, 0xf7, 0x1e, 0x7f, 0x2f, 0x66, 0xb8, 0xb5, 0x24, 0x41, 0x60, 0xfb, 0x80, 0x9d, 0x82, 0x6e, 0x71, 0xe0, 0xf2, 0x39, 0xf9, 0x86, 0x42, 0x3d, 0x34, 0x27, 0x11, 0x92, 0xf4, 0x21, 0x83, 0x6d, 0x99, 0x42, 0xda, 0x5b, 0x36, 0xef, 0xfa, 0xa8, 0xc6, 0x46, 0x53, 0x19, 0x4d, 0x42, 0x43, 0x9a, 0x94, 0x38, 0x40, 0xac, 0x37, 0x26, 0x86, 0x5d, 0xff, 0x82, 0xd1, 0xf6, 0xcb, 0x3e, 0xa0, 0xa0, 0x78, 0x6b, 0xb5, 0xc5, 0x2d, 0x6f, 0x09, 0xaf, 0x3a, 0x05, 0xde, 0x6e, 0x07, 0xf8, 0x87, 0x6a, 0x0a, 0xb7, 0xb4, 0xfe, 0x3d, 0xc5, 0x6e, 0x0f, 0x1d, 0xa1, 0x16, 0xd1, 0x32, 0x78, 0xd4, 0xf6, 0x0e, 0x8c, 0xd3, 0xa4, 0x31, 0x79, 0x3c, 0xff, 0x5f, 0xa0, 0x95, 0x17, 0x5c, 0x7a, 0xd3, 0xd4, 0xf8, 0x4e, 0xeb, 0x59, 0x94, 0xdf, 0xc4, 0x14, 0x14, 0x72, 0xc5, 0xf6, 0x63, 0x05, 0x74, 0x85, 0x48, 0xbf, 0x12, 0x50, 0xff, 0x65, 0x91, 0x81, 0x10, 0x21, 0xdb, 0x80, 0x93, 0x62, 0x0f, 0xa3, 0xdd, 0x19, 0xb8, 0x9a, 0x01, 0xc3, 0x8f, 0xa7, 0xb0, 0xd8, 0x0c, 0x4c, 0xbb, 0x0b, 0x93, 0x6e, 0x36, 0xdd, 0x72, 0x71, 0xcd, 0x3f, 0x21, 0x26, 0x06, 0x7c, 0xbf, 0xc8, 0xe5, 0x81, 0x96, 0x02, 0x2a, 0x18, 0x92, 0x00, 0x39, 0xc6, 0x9c, 0x90, 0xf3, 0x63, 0xda, 0x0d, 0x88, 0x44, 0x14, 0x9d, 0xbc, 0x03, 0x2f, 0x68, 0x9e, 0x22, 0xc8, 0x51, 0x02, 0x4f, 0x78, 0x76, 0x1b, 0xa1, 0x76, 0x39, 0x6c, 0x67, 0x8c, 0xd7, 0xa8, 0x2d, 0xf0, 0x3f, 0xa2, 0xe5, 0x7f, 0x50, 0x64, 0xce, 0x4f, 0x75, 0x84, 0x06, 0x94, 0x77, 0xc7, 0x08, 0x1a, 0xdf, 0xed, 0x3c, 0x77, 0x47, 0x60, 0x18, 0x38, 0xb5, 0x51, 0x82, 0x47, 0x7d, 0xb7, 0x9d, 0xd0, 0xba, 0x81, 0x1f, 0xf3, 0x70, 0xf8, 0xc6, 0xd4, 0xac, 0x98, 0xdf, 0x7b, 0xa8, 0xaf, 0xe0, 0x22, 0xfd, 0xad, 0xbe, 0xd5, 0xb7, 0x31, 0xc4, 0x6f, 0x07, 0x52, 0x4b, 0x40, 0x39, 0x76, 0x74, 0x83, 0x23, 0x6f, 0x37, 0x3f, 0xd0, 0xbc, 0x5a, 0x63, 0xa7, 0x8d, 0xa6, 0x51, 0x22, 0xe8, 0x34, 0xd4, 0xd6, 0xdb, 0x4a, 0xd4, 0x56, 0xb3, 0xb9, 0xe0, 0x59, 0xf3, 0x6d, 0x6a, 0x09, 0xa1, 0x4b, 0x87, 0x11, 0x21, 0x17, 0x9c, 0x7e, 0xd4, 0xc8, 0x4f, 0x17, 0xdd, 0xcd, 0xfc, 0x0e, 0x69, 0x5e, 0x6f, 0x99, 0x82, 0x7f, 0xeb, 0xce, 0x11, 0x17, 0x0b, 0x54, 0x6c, 0xda, 0xab, 0x8e, 0x10, 0x9d, 0xa7, 0x0e, 0x46, 0x60, 0x7a, 0xa5, 0xf7, 0x73, 0x5c, 0x75, 0x9c, 0x57, 0xdd, 0xc6, 0xad, 0x97, 0x00, 0xd1, 0x2d, 0x14, 0x70, 0xf7, 0x1d, 0xe8, 0xc4, 0x3d, 0x8d, 0xdc, 0x3a, 0x5e, 0x00, 0x0b, 0x42, 0x5d, 0xea, 0xdc, 0x08, 0x38, 0x37, 0x80, 0x62, 0x72, 0xf2, 0x97, 0x00, 0x3a, 0x11, 0xb9, 0x5a, 0x87, 0x3a, 0x06, 0xbd, 0xa3, 0x64, 0x1b, 0xa2, 0x18, 0xf3, 0xec, 0x2b, 0x51, 0x37, 0x0c, 0x3f, 0x7d, 0x5a, 0xbc, 0x24, 0x70, 0xe5, 0x93, 0x01, 0xd9, 0x58, 0x66, 0xe5, 0x41, 0x80, 0x61, 0x5b, 0xcd, 0x6c, 0x3e, 0xd2, 0xfa, 0xd3, 0xd8, 0xbd, 0x89, 0xf6, 0xb6, 0x4d, 0xf9, 0xe1, 0x40, 0x4c, 0x86, 0xf8, 0x67, 0x9c, 0x2e, 0x53, 0xfd, 0x58, 0xbc, 0x2f, 0x59, 0x64, 0xbc, 0x0c, 0xcd, 0x65, 0x34, 0xd9, 0xb1, 0x92, 0xc8, 0xb3, 0x94, 0x1f, 0xcf, 0x0b, 0x53, 0x5a, 0x95, 0x69, 0x42, 0x32, 0x8d, 0x4d, 0x54, 0x94, 0x89, 0x72, 0xf9, 0xd4, 0x8c, 0x4d, 0x5d, 0xba, 0x03, 0xd3, 0x70, 0x32, 0xa3, 0xd6, 0xc0, 0xa1, 0xbd, 0x26, 0x9d, 0xdb, 0x4f, 0xc8, 0x03, 0xda, 0x78, 0x75, 0x27, 0xcf, 0x57, 0xad, 0x80, 0x87, 0xa4, 0x55, 0x0a, 0x5a, 0x14, 0x81, 0x88, 0x7c, 0x22, 0x2f, 0xb6, 0xc6, 0xb5, 0x33, 0x3e, 0x35, 0x8d, 0x6b, 0x47, 0x37, 0x91, 0xe7, 0xbe, 0xe2, 0x48, 0xa9, 0x91, 0xc7, 0xaf, 0x51, 0xf3, 0x10, 0x0b, 0x39, 0x36, 0xcd, 0x51, 0x6a, 0x3c, 0xeb, 0x87, 0xbc, 0x15, 0xef, 0x2d, 0x92, 0x14, 0xda, 0x2c, 0xad, 0x65, 0x71, 0x05, 0x20, 0xc4, 0x7e, 0xf7, 0xda, 0x4b, 0xe3, 0x4e, 0xf1, 0x9d, 0x55, 0xc2, 0xcc, 0x47, 0x62, 0x18, 0x7d, 0xe0, 0xc9, 0xec, 0x80, 0xee, 0x2b, 0xd6, 0x2f, 0x64, 0xe1, 0xff, 0xd7, 0x8c, 0x23, 0x53, 0x1f, 0x13, 0xe5, 0x41, 0xe0, 0x14, 0x3a, 0x96, 0x70, 0x7f, 0xda, 0xbf, 0x10, 0xd9, 0x31, 0xb8, 0x97, 0x4b, 0xc9, 0xff, 0x56, 0x96, 0x91, 0x99, 0xdd, 0x34, 0xc2, 0x96, 0x66, 0xa3, 0x1e, 0x73, 0x36, 0x71, 0xbc, 0x40, 0x19, 0xb0, 0x11, 0xaf, 0x96, 0x99, 0x4a, 0x17, 0x85, 0xf4, 0x38, 0x96, 0x5c, 0xbc, 0x2c, 0x2e, 0x55, 0xc7, 0xb8, 0x2a, 0x59, 0x08, 0x24, 0x08, 0xeb, 0xf8, 0x44, 0x84, 0xd9, 0x1e, 0x16, 0x26, 0x27, 0xb0, 0xac, 0xeb, 0x6b, 0x82, 0xd9, 0xfa, 0xf0, 0x41, 0x8d, 0x6e, 0x5a, 0xfc, 0x14, 0x60, 0x93, 0x2b, 0x5b, 0x5c, 0xdb, 0xf4, 0x54, 0xa2, 0x62, 0x89, 0x85, 0x69, 0x67, 0x1d, 0xa2, 0x19, 0x57, 0xdc, 0x27, 0xbd, 0xba, 0x89, 0x3a, 0xd3, 0x90, 0xd6, 0x04, 0x43, 0x05, 0xba, 0x83, 0xa0, 0x73, 0x19, 0x26, 0x62, 0xd7, 0x3d, 0xd1, 0x7d, 0x4d, 0xda, 0x16, 0xaa, 0x6d, 0xbb, 0x2c, 0xa5, 0x51, 0x3d, 0xe2, 0x29, 0xf4, 0x6d, 0xa4, 0x2b, 0x96, 0x6b, 0x34, 0xbe, 0x74, 0x06, 0x7a, 0xb2, 0x47, 0xfa, 0xcf, 0x01, 0x69, 0xe2, 0x7b, 0xba, 0xa1, 0x6d, 0x34, 0xfa, 0xb0, 0xbf, 0x87, 0xa8, 0x63, 0x52, 0x82, 0x80, 0xca, 0xeb, 0x27, 0x9a, 0x80, 0x40, 0xc4, 0xe3, 0xa9, 0x1f, 0xbf, 0x44, 0xe4, 0x08, 0xe8, 0xd5, 0x9e, 0x9f, 0xaa, 0x1d, 0x07, 0x59, 0xca, 0x1b, 0xfd, 0x4b, 0x84, 0xff, 0x9d, 0xf9, 0xcc, 0xea, 0x58, 0x3d, 0xea, 0x83, 0x9f, 0x82, 0x32, 0x26, 0x30, 0xf5, 0x8e, 0x25, 0x21, 0x99, 0x84, 0xb9, 0x2a, 0x2a, 0x42, 0x93, 0xf3, 0x7c, 0xd3, 0x14, 0x76, 0xbd, 0xfa, 0x98, 0xb0, 0x55, 0xc3, 0xaf, 0x6d, 0x2f, 0x1e, 0x8e, 0x8b, 0x5c, 0x7b, 0xfc, 0x33, 0xce, 0x4b, 0xb9, 0xe8, 0x7c, 0x23, 0x59, 0x42, 0x84, 0x68, 0x76, 0xdb, 0x44, 0xf9, 0x80, 0xf0, 0xb7, 0xc5, 0xaf, 0xa0, 0x59, 0xe5, 0x10, 0xd0, 0xc8, 0x31, 0x42, 0x4b, 0xa3, 0x17, 0x7b, 0xd2, 0x4b, 0x1d, 0x6f, 0xea, 0xcb, 0xc9, 0xbf, 0x37, 0x50, 0xc3, 0xdb, 0xed, 0x7b, 0xff, 0xa4, 0xe1, 0x9a, 0x72, 0xb5, 0x13, 0x27, 0xde, 0xba, 0x1b, 0xfd, 0x55, 0xb9, 0x63, 0x47, 0xd0, 0xb4, 0x37, 0x63, 0xfb, 0xf9, 0xa9, 0x25, 0xb2, 0x8b, 0xae, 0xea, 0x2c, 0xfa, 0xa2, 0x58, 0x47, 0x63, 0x46, 0x90, 0x83, 0x3b, 0x94, 0x7d, 0x26, 0xbc, 0x3d, 0x71, 0x7c, 0xa0, 0xe5, 0x0a, 0xcf, 0x10, 0x94, 0x7f, 0x83, 0xae, 0xf2, 0xcd, 0xbd, 0xbe, 0xef, 0xb9, 0x0c, 0x4c, 0x84, 0x63, 0x0e, 0x37, 0xfa, 0xa3, 0x54, 0x4a, 0x9b, 0x4f, 0xc8, 0x68, 0xf3, 0x9b, 0xdf, 0x5e, 0x26, 0x84, 0xae, 0x3f, 0xc5, 0x04, 0x99, 0xb4, 0xf7, 0x71, 0x42, 0x47, 0xa2, 0xad, 0x44, 0x53, 0x12, 0x29, 0x1a, 0x43, 0xac, 0xf7, 0x76, 0x72, 0x52, 0x80, 0xf0, 0x94, 0x75, 0x7c, 0x3b, 0xaf, 0x37, 0x90, 0x5c, 0x6d, 0xd2, 0xcc, 0x28, 0x41, 0x67, 0x81, 0x2f, 0x00, 0x2e, 0x8d, 0xb0, 0xa4, 0xa2, 0x47, 0x39, 0x43, 0x5b, 0x6f, 0x89, 0xf5, 0x21, 0xcc, 0xe7, 0xce, 0x98, 0x13, 0x95, 0xc7, 0x92, 0xd5, 0x00, 0x31, 0x34, 0xbe, 0x3b, 0x17, 0xf1, 0xc3, 0x74, 0xf4, 0x07, 0xc5, 0xf4, 0x6d, 0x9b, 0xc7, 0x6f, 0xf7, 0x51, 0x4c, 0x9b, 0x3b, 0xd7, 0x73, 0xff, 0xa0, 0x1f, 0x87, 0x5f, 0xfa, 0x37, 0xff, 0xac, 0xa2, 0x04, 0xe3, 0xbd, 0x28, 0xc1, 0xc6, 0xdf, 0x9c, 0x98, 0xbf, 0x39, 0x51, 0x26, 0xc0, 0x10, 0xba, 0x40, 0x13, 0xea, 0xb9, 0x34, 0x47, 0x0e, 0xa4, 0x99, 0xa1, 0x5c, 0x03, 0xdc, 0x83, 0x37, 0x90, 0x83, 0xd1, 0x09, 0x50, 0x3f, 0x42, 0x0e, 0x72, 0x76, 0x63, 0x4b, 0x4a, 0xea, 0x4e, 0x27, 0xce, 0x9b, 0x4b, 0x56, 0x47, 0x24, 0xc6, 0x12, 0xed, 0x0f, 0x08, 0xe1, 0x7c, 0xd1, 0xfc, 0x33, 0x40, 0x08, 0xaf, 0xd6, 0x88, 0x59, 0x5c, 0xe1, 0xf7, 0xc4, 0x63, 0xe3, 0x67, 0x35, 0x6e, 0x75, 0xfe, 0x55, 0x72, 0xaf, 0x3e, 0xdd, 0xc7, 0xb2, 0x08, 0x67, 0x5a, 0x80, 0x2c, 0x90, 0x11, 0x91, 0x3b, 0x80, 0x62, 0x42, 0xa5, 0x5b, 0xcd, 0xae, 0x75, 0x41, 0x3c, 0x25, 0xb0, 0x37, 0x67, 0xf1, 0xa2, 0xfd, 0xc4, 0x8d, 0x57, 0x03, 0x2a, 0xde, 0xdd, 0x3a, 0xb8, 0x6d, 0xed, 0x00, 0x17, 0xaa, 0x95, 0x69, 0x92, 0xc4, 0x62, 0x77, 0xc4, 0x35, 0x21, 0x69, 0xf7, 0xd3, 0x19, 0xb1, 0x1a, 0x3f, 0xe9, 0xb9, 0x1d, 0xcb, 0xa2, 0x26, 0x18, 0x49, 0x89, 0xde, 0x97, 0x2b, 0xf4, 0x1c, 0x05, 0x23, 0x11, 0x6a, 0x30, 0xfa, 0x7d, 0xcd, 0x93, 0x32, 0xa6, 0x00, 0x60, 0x12, 0x6b, 0xc2, 0x68, 0xd9, 0x66, 0x6d, 0x3b, 0x21, 0xbe, 0x3f, 0x6c, 0xc2, 0xdb, 0x96, 0xe8, 0xcf, 0x6f, 0x2c, 0x3b, 0x52, 0xbf, 0xe9, 0x07, 0x32, 0x0b, 0x35, 0xde, 0x53, 0x0a, 0xab, 0xa6, 0xb2, 0x38, 0x9e, 0xea, 0x09, 0xc3, 0xc8, 0xa1, 0x1d, 0x60, 0x5d, 0x49, 0xbf, 0x1d, 0x53, 0xab, 0x4c, 0x17, 0x34, 0x37, 0xc4, 0x73, 0x00, 0x42, 0x7f, 0x89, 0x9b, 0xda, 0x20, 0x09, 0x97, 0x72, 0x3f, 0xa0, 0xb3, 0x88, 0xb3, 0xaf, 0xa6, 0xe7, 0xa9, 0xf7, 0xf7, 0xd0, 0xc3, 0x9e, 0x24, 0x7a, 0xee, 0x40, 0x3a, 0xb4, 0x20, 0x3a, 0x09, 0x3d, 0x40, 0xa4, 0x08, 0x9f, 0xcb, 0x58, 0xd2, 0x01, 0x63, 0x8e, 0xdd, 0x11, 0x24, 0x0a, 0x07, 0x57, 0xa3, 0x51, 0x68, 0x19, 0xa8, 0x87, 0x1b, 0xea, 0x5f, 0xe3, 0x1e, 0x96, 0x70, 0xc7, 0x81, 0xc7, 0x01, 0xfe, 0x07, 0x64, 0xa2, 0x0e, 0x59, 0x3f, 0x00, 0x16, 0x31, 0x62, 0xb6, 0xfd, 0x60, 0x58, 0x5f, 0x11, 0x46, 0x06, 0x3d, 0x8b, 0x80, 0x21, 0x64, 0x2a, 0x76, 0x29, 0x4a, 0x59, 0x57, 0x89, 0x83, 0x86, 0xbe, 0x13, 0x75, 0x06, 0xcc, 0x09, 0x6d, 0x08, 0xe0, 0x6f, 0x1d, 0x32, 0x0c, 0x74, 0xac, 0xe1, 0xa5, 0xe9, 0x8a, 0x5d, 0x50, 0xf5, 0xbe, 0x40, 0xf2, 0x2d, 0x69, 0x3d, 0x83, 0xbf, 0xcd, 0x25, 0x8e, 0x6f, 0x5e, 0xf6, 0x67, 0x9f, 0x56, 0x67, 0x80, 0x0c, 0x43, 0x4f, 0x46, 0xbe, 0x7b, 0xd5, 0x8a, 0x14, 0xa4, 0x6c, 0x50, 0x22, 0x3c, 0xf7, 0x8a, 0xfb, 0x9c, 0x28, 0xf6, 0xc7, 0xa4, 0x7d, 0xcd, 0x93, 0x69, 0xe8, 0x76, 0x17, 0x39, 0xbb, 0x9b, 0x50, 0xc1, 0x20, 0x0f, 0xc4, 0xb9, 0x2c, 0xf6, 0x44, 0x19, 0xa1, 0x30, 0xb3, 0x3d, 0x92, 0x39, 0xf8, 0x64, 0x98, 0xcd, 0x94, 0x59, 0x45, 0x8d, 0x47, 0x9d, 0xdd, 0x2d, 0xfd, 0xa0, 0xe0, 0x3d, 0x82, 0x60, 0x85, 0xe5, 0x62, 0x4f, 0x61, 0x06, 0xbf, 0xc0, 0x88, 0x00, 0xd2, 0x91, 0x7a, 0xfe, 0x6d, 0x62, 0x6e, 0xbf, 0x34, 0x6b, 0x11, 0xee, 0x84, 0xd3, 0x9f, 0xc9, 0xcb, 0x53, 0x10, 0xac, 0xb8, 0xb5, 0xcb, 0x04, 0x1b, 0xf6, 0x10, 0x7d, 0x82, 0x2c, 0xc8, 0xd6, 0xba, 0x5f, 0xc5, 0xd0, 0x57, 0x19, 0x3b, 0xaa, 0xc1, 0xec, 0x04, 0xa6, 0xd1, 0xef, 0x24, 0x0f, 0xf4, 0x80, 0x00, 0x96, 0x61, 0xca, 0x81, 0x15, 0x97, 0xb8, 0xc0, 0x28, 0x9a, 0x78, 0x9a, 0x1e, 0xad, 0x83, 0xe4, 0x34, 0x84, 0x11, 0x61, 0xf6, 0x30, 0x18, 0x30, 0x6b, 0x3e, 0xd0, 0x59, 0x6d, 0x83, 0x6d, 0x9b, 0xc3, 0x2c, 0xef, 0x66, 0xc6, 0xa2, 0xab, 0x6d, 0x03, 0xf4, 0xc8, 0x1c, 0x5e, 0x18, 0xce, 0xc2, 0xe9, 0xe7, 0xcf, 0x87, 0x4f, 0x67, 0x49, 0x6b, 0x84, 0x8a, 0x75, 0xae, 0xe2, 0xaa, 0x08, 0x73, 0x82, 0x17, 0x10, 0x0c, 0x85, 0x93, 0xed, 0x0a, 0xc5, 0xd0, 0x15, 0xc0, 0xe6, 0x2b, 0x71, 0x0e, 0x0f, 0x24, 0xb8, 0x8d, 0x99, 0x9d, 0xb0, 0x42, 0xd1, 0x75, 0x03, 0xe4, 0x57, 0x83, 0xf5, 0x94, 0x41, 0x30, 0xf4, 0xd4, 0x01, 0xfc, 0xd5, 0xd6, 0x0e, 0x11, 0xd3, 0xe5, 0x85, 0x05, 0x5b, 0x50, 0x04, 0x1c, 0x1e, 0xea, 0xbc, 0x13, 0xc7, 0x56, 0x01, 0xe5, 0xd2, 0x0b, 0xc8, 0xe3, 0x94, 0x2e, 0x2e, 0xbb, 0x9d, 0xa2, 0xdc, 0xf3, 0x1a, 0x56, 0xc3, 0x52, 0xf4, 0x2a, 0xca, 0xbe, 0x2a, 0xde, 0x6a, 0xf1, 0xef, 0x2e, 0x03, 0x93, 0xeb, 0x58, 0x62, 0x5f, 0xe8, 0xa6, 0x6c, 0xaf, 0xf0, 0xd5, 0x02, 0x97, 0x16, 0x6a, 0xcb, 0x09, 0xea, 0x40, 0xc1, 0x3a, 0x4f, 0x31, 0x39, 0xab, 0x7d, 0xcc, 0x4b, 0xea, 0x60, 0x42, 0x08, 0x3a, 0xbf, 0x1b, 0x5d, 0xd0, 0x07, 0x7f, 0x1a, 0xc2, 0xb3, 0x6a, 0x35, 0x79, 0xe5, 0x00, 0xb9, 0x7b, 0x17, 0xf8, 0xa3, 0xb4, 0x0b, 0x30, 0x9b, 0x28, 0xc3, 0x51, 0x11, 0x8c, 0x4a, 0x21, 0xce, 0x67, 0x73, 0xc6, 0xe3, 0xbc, 0x27, 0x40, 0x24, 0xca, 0x0d, 0x36, 0x21, 0x4e, 0x33, 0xb3, 0xf0, 0xa5, 0x93, 0x4f, 0xe6, 0x8c, 0xc3, 0x88, 0xad, 0xc1, 0xd5, 0x3c, 0x27, 0x95, 0x56, 0x2f, 0xae, 0x45, 0x5a, 0x44, 0xef, 0x5d, 0x56, 0xe7, 0xee, 0x83, 0xda, 0x68, 0xbb, 0x8a, 0x33, 0x12, 0x0b, 0x56, 0xe1, 0xe9, 0x70, 0xb4, 0xf1, 0x05, 0x30, 0x7d, 0x6b, 0x78, 0xdd, 0x49, 0x57, 0xf0, 0xbd, 0x4c, 0x7e, 0xac, 0x80, 0x32, 0xae, 0x73, 0x37, 0x9b, 0xa4, 0xf6, 0xe0, 0xb2, 0x2a, 0xd0, 0x67, 0x85, 0x9f, 0xfd, 0x49, 0xcb, 0x34, 0x40, 0x3c, 0x43, 0x53, 0xfc, 0xfe, 0xcf, 0xb2, 0xc7, 0xb7, 0x06, 0xaa, 0x04, 0xca, 0xf5, 0x02, 0x68, 0xa1, 0x42, 0xe3, 0xfc, 0xcf, 0x24, 0x38, 0x46, 0xb6, 0x82, 0x01, 0xc6, 0x98, 0x4e, 0x25, 0xc5, 0x78, 0x76, 0x92, 0x22, 0x40, 0x23, 0x3f, 0x52, 0xb8, 0xd5, 0xb0, 0x56, 0xe9, 0x89, 0x38, 0x67, 0x1c, 0xdf, 0xe9, 0x91, 0xa8, 0xc2, 0xfa, 0x90, 0x09, 0xd5, 0x8b, 0x25, 0x32, 0x29, 0x83, 0x07, 0xbe, 0xb6, 0x18, 0x2c, 0xfb, 0x48, 0x0f, 0x3e, 0x46, 0x7e, 0xf0, 0xe4, 0xd2, 0x33, 0x3d, 0x9b, 0xa9, 0x59, 0x34, 0x1a, 0x88, 0x4d, 0x9f, 0xae, 0x35, 0xb0, 0xf1, 0xb4, 0xeb, 0x4f, 0xe4, 0x3d, 0x8d, 0xb3, 0x26, 0x3d, 0x57, 0x02, 0x6e, 0x77, 0x87, 0x1d, 0x8c, 0xa4, 0x4a, 0xd8, 0xba, 0x80, 0x1a, 0xaa, 0x31, 0xf5, 0x98, 0x17, 0xb3, 0x59, 0xa1, 0xef, 0x80, 0x8a, 0xda, 0x5e, 0x03, 0x0b, 0x9a, 0x1b, 0xd4, 0xc9, 0xae, 0x2d, 0xc2, 0xeb, 0xe5, 0xaf, 0x2c, 0x7f, 0x18, 0x33, 0x0f, 0x4c, 0x9c, 0x89, 0xc8, 0x60, 0x63, 0xb1, 0xb5, 0xe5, 0x68, 0x5c, 0xea, 0xaf, 0x52, 0x23, 0x3b, 0x37, 0x60, 0xcb, 0xb5, 0x56, 0x3c, 0x51, 0x94, 0x52, 0x48, 0x0e, 0x49, 0x7f, 0xe1, 0x25, 0x50, 0x94, 0x81, 0xab, 0xb0, 0xd4, 0x7e, 0x4b, 0xe2, 0x94, 0xb3, 0xe9, 0x45, 0xc5, 0x36, 0xf2, 0xa7, 0xae, 0x3e, 0xb8, 0x21, 0x7f, 0x92, 0xf2, 0xd1, 0x3f, 0xda, 0xe7, 0x7e, 0xfc, 0x4b, 0xff, 0xdc, 0x82, 0x6a, 0x84, 0xd1, 0x3e, 0xf8, 0x8a, 0x05, 0x8b, 0x0c, 0xb5, 0x2e, 0x25, 0xf8, 0x3d, 0xed, 0xe4, 0x7a, 0x91, 0x56, 0xab, 0x70, 0x3b, 0xab, 0x08, 0x7a, 0x15, 0xe1, 0x85, 0xad, 0x75, 0xd8, 0x7c, 0x8f, 0x28, 0xb9, 0x01, 0xe1, 0x71, 0x38, 0x8f, 0xcf, 0xbd, 0xd5, 0x03, 0x7e, 0xaa, 0xc1, 0x83, 0xe8, 0x10, 0x9e, 0x5a, 0x66, 0xc0, 0x63, 0xcb, 0xfc, 0x74, 0xce, 0x1b, 0xd5, 0x6f, 0xcd, 0x8e, 0x02, 0x24, 0x97, 0x10, 0xf4, 0x6d, 0x59, 0xe2, 0x89, 0x67, 0x44, 0x75, 0xa0, 0x9d, 0xe6, 0x35, 0x11, 0x7e, 0x39, 0xce, 0x33, 0xa7, 0x09, 0x3e, 0xd0, 0x02, 0x1e, 0xf8, 0x1a, 0x36, 0xd0, 0x62, 0xdb, 0x68, 0xcb, 0x1c, 0x36, 0x7b, 0x3e, 0x78, 0x7f, 0x76, 0xcc, 0x9b, 0xf9, 0xc6, 0xc2, 0xc0, 0x4c, 0xa9, 0x4e, 0xfd, 0x15, 0xa4, 0x1a, 0xb7, 0x5e, 0xa5, 0x5d, 0x28, 0xe9, 0x4d, 0x96, 0x6d, 0x3e, 0xff, 0xa5, 0x7f, 0x80, 0x85, 0x99, 0xb5, 0x18, 0xff, 0x9d, 0x63, 0x2e, 0x54, 0x72, 0xd5, 0x90, 0x7f, 0x0f, 0xf3, 0xe8, 0xfb, 0x18, 0x64, 0x9a, 0x02, 0x00, 0x5f, 0xa5, 0xbe, 0x91, 0x7a, 0xfb, 0xa9, 0x79, 0x37, 0xee, 0xcc, 0x08, 0x60, 0x9f, 0x8d, 0xc5, 0x8c, 0x10, 0x46, 0xf1, 0xc0, 0x19, 0x47, 0x30, 0x1e, 0x9b, 0xf0, 0x0c, 0x81, 0x0f, 0xf4, 0x98, 0x19, 0x6d, 0x43, 0xf4, 0xe1, 0xed, 0x44, 0xca, 0x18, 0x8d, 0x45, 0x6f, 0xd2, 0x94, 0x45, 0x66, 0xd9, 0x11, 0x3b, 0x27, 0x28, 0xc4, 0x6f, 0x39, 0x9d, 0xb6, 0x96, 0x93, 0xc9, 0xd0, 0xeb, 0xd4, 0x11, 0x3d, 0xc8, 0x62, 0xdd, 0x64, 0x5c, 0xe0, 0x89, 0x98, 0xf8, 0xa0, 0x76, 0x7c, 0x2a, 0x93, 0xcc, 0x15, 0x1c, 0x91, 0x20, 0xe2, 0x89, 0x0e, 0xe1, 0x38, 0x07, 0x04, 0xa5, 0x36, 0xdf, 0xc7, 0x1c, 0x30, 0xb0, 0x12, 0xa6, 0xf3, 0xb8, 0x45, 0xb7, 0xe0, 0x1d, 0xdd, 0x63, 0x7b, 0x47, 0xf2, 0x43, 0x71, 0xa1, 0x88, 0x88, 0xde, 0x96, 0x46, 0xe9, 0x9f, 0x99, 0x0e, 0x91, 0x84, 0x83, 0x02, 0xb1, 0x21, 0x42, 0x56, 0x63, 0xa0, 0x8e, 0x12, 0x67, 0x07, 0x65, 0xb6, 0xda, 0x99, 0xd4, 0x0c, 0xd0, 0xc1, 0x1b, 0xe0, 0x4e, 0xeb, 0x7c, 0xab, 0xce, 0x53, 0xf6, 0xeb, 0x16, 0x51, 0x86, 0xb3, 0x2e, 0x43, 0xe0, 0xb3, 0x3c, 0x2c, 0x3e, 0x9e, 0xf8, 0xe5, 0x4c, 0x8b, 0xad, 0xd9, 0xee, 0x94, 0xf7, 0x7d, 0x0c, 0x4c, 0x6c, 0x8b, 0x9f, 0xe2, 0x4a, 0x98, 0x20, 0x89, 0x46, 0x12, 0xbb, 0xcb, 0x09, 0xc1, 0x15, 0xce, 0x78, 0x2a, 0x0e, 0x64, 0xf2, 0x3b, 0xf0, 0x02, 0x4e, 0x6a, 0x62, 0xbf, 0x34, 0x46, 0x90, 0x30, 0xfb, 0xcd, 0x00, 0x99, 0x9b, 0x85, 0x96, 0x39, 0xc7, 0xd7, 0x98, 0x74, 0x04, 0xca, 0x9f, 0x15, 0x1c, 0x22, 0x3b, 0xe4, 0x09, 0xa9, 0x15, 0x1a, 0x69, 0x63, 0xef, 0xe6, 0x53, 0x07, 0x54, 0x1b, 0xae, 0x21, 0x31, 0x86, 0x7a, 0xe6, 0xbc, 0xd7, 0xd3, 0xd7, 0x38, 0x5a, 0x7c, 0x3e, 0x68, 0x42, 0xfa, 0x5f, 0x35, 0x92, 0x40, 0xcc, 0x51, 0xcd, 0xf9, 0x37, 0xdd, 0x42, 0xd8, 0x36, 0x10, 0x4c, 0xdc, 0xa8, 0x23, 0xee, 0xaa, 0xe3, 0x55, 0x37, 0xa0, 0xb3, 0xbe, 0x06, 0xcf, 0xd8, 0xb9, 0xa1, 0x05, 0x75, 0x5c, 0x9f, 0xdd, 0xe1, 0xd9, 0xc0, 0x8c, 0x31, 0x34, 0x95, 0x71, 0x65, 0x6f, 0x79, 0x62, 0x6b, 0x5d, 0x51, 0x88, 0x53, 0x90, 0x7a, 0x58, 0xdd, 0xb5, 0x8e, 0x71, 0x2f, 0x29, 0xdd, 0x74, 0x5e, 0x7a, 0x34, 0xb7, 0x35, 0x6f, 0xe0, 0x94, 0x3d, 0x97, 0xa4, 0x7b, 0xbd, 0x93, 0x0f, 0xab, 0x47, 0xe1, 0x4a, 0xdf, 0xcb, 0x80, 0x0e, 0xdd, 0xda, 0x99, 0x71, 0x5c, 0x97, 0x35, 0x70, 0x7e, 0xe2, 0x16, 0xc7, 0xbb, 0xd1, 0xba, 0x2e, 0x3c, 0x36, 0xc1, 0xca, 0xae, 0x8b, 0x41, 0x4c, 0x85, 0xa9, 0xb5, 0x3d, 0xfe, 0xe4, 0x1e, 0xf9, 0xc4, 0xe3, 0x67, 0x1f, 0x8e, 0xfd, 0x9f, 0xc3, 0xd9, 0xe9, 0x69, 0x2e, 0xbd, 0x8e, 0x11, 0x92, 0x69, 0x4c, 0x38, 0xf9, 0xcb, 0x23, 0x48, 0x4f, 0x7d, 0x52, 0x07, 0xc7, 0x9f, 0xb5, 0x3c, 0x13, 0x3c, 0xbb, 0xae, 0x38, 0x42, 0x05, 0x6c, 0x03, 0x5e, 0xf1, 0x26, 0xae, 0xa5, 0x67, 0xd4, 0x8b, 0x45, 0xab, 0xbd, 0x38, 0x3d, 0xc9, 0xc4, 0x08, 0x5b, 0xc4, 0x2a, 0xde, 0x88, 0x67, 0x8d, 0x7a, 0xa5, 0x12, 0xef, 0x66, 0x8a, 0x40, 0xe2, 0x16, 0xc1, 0xc9, 0xa6, 0xc2, 0xe2, 0x5b, 0x6d, 0x53, 0xaf, 0x5a, 0x06, 0x26, 0xc0, 0xd1, 0x86, 0xfc, 0x42, 0x62, 0x55, 0x42, 0x76, 0xaf, 0x1d, 0xe9, 0x63, 0x5d, 0x0a, 0x4f, 0xac, 0xbd, 0x9e, 0xf9, 0x9d, 0xc4, 0x26, 0xde, 0x6c, 0x31, 0xfe, 0xa3, 0x2c, 0xcc, 0xc3, 0xa9, 0xa3, 0x49, 0x92, 0x16, 0xbd, 0xbc, 0x10, 0x23, 0xa7, 0xbb, 0xe3, 0x8e, 0xdd, 0xd0, 0x4b, 0x26, 0x11, 0x55, 0x83, 0x49, 0x63, 0x40, 0x78, 0x42, 0x2c, 0x48, 0x45, 0xe2, 0xe8, 0x77, 0xa0, 0xdd, 0xe3, 0xc8, 0x34, 0x73, 0x1e, 0x2c, 0x3a, 0x3e, 0x04, 0x0d, 0xea, 0x92, 0x92, 0x1f, 0x29, 0x8d, 0x94, 0xad, 0xe7, 0x0d, 0x92, 0x9f, 0x91, 0x1d, 0x05, 0xd5, 0x50, 0x3e, 0x6a, 0x68, 0x35, 0x59, 0xdc, 0xcd, 0xcf, 0xff, 0x18, 0xf9, 0x8f, 0x08, 0xf1, 0x71, 0x79, 0xf4, 0x76, 0xf6, 0xc7, 0x34, 0xd5, 0x4e, 0xd4, 0x14, 0x8e, 0x90, 0x56, 0xf1, 0xd4, 0x7b, 0x71, 0xc6, 0xce, 0xc1, 0x6c, 0xb9, 0xac, 0x13, 0x63, 0x5c, 0x62, 0xcb, 0x15, 0x18, 0x36, 0xa8, 0x52, 0xb0, 0x95, 0x6c, 0xe8, 0xb8, 0x7b, 0x67, 0xe7, 0x96, 0xb8, 0x45, 0x6d, 0xa2, 0x6a, 0x6b, 0x91, 0x29, 0x0f, 0xb8, 0x2b, 0x50, 0x1a, 0xe6, 0x0b, 0x62, 0xc4, 0xdc, 0xed, 0x46, 0x5c, 0x8a, 0x4e, 0x29, 0x6c, 0x64, 0x2b, 0x26, 0x6b, 0xac, 0x20, 0xb0, 0x8e, 0x1a, 0x44, 0x03, 0x18, 0xfa, 0x90, 0xd8, 0xaf, 0x7b, 0x83, 0xcc, 0xbe, 0xad, 0xeb, 0xa2, 0x37, 0x69, 0xbb, 0x7c, 0xda, 0x10, 0x66, 0x4d, 0xef, 0x68, 0xef, 0x43, 0xff, 0x99, 0xe3, 0x49, 0x9b, 0xe3, 0x46, 0x66, 0x73, 0x6c, 0x58, 0x22, 0x58, 0x45, 0x47, 0x1b, 0xfd, 0xeb, 0xd0, 0xfa, 0x67, 0xc1, 0xd2, 0xd9, 0xbb, 0x13, 0xc6, 0x5b, 0x83, 0x2f, 0x78, 0xd7, 0xbb, 0x39, 0x78, 0xf4, 0x22, 0x9a, 0x40, 0x1f, 0x70, 0x33, 0x15, 0x65, 0x81, 0x66, 0x79, 0xae, 0xbb, 0xb8, 0x9e, 0x04, 0x24, 0x18, 0xdc, 0x8e, 0x3b, 0x35, 0x37, 0x72, 0xb8, 0x81, 0x7f, 0x5b, 0x67, 0x10, 0x91, 0xb2, 0x6b, 0x30, 0xd1, 0x88, 0x89, 0x2b, 0x66, 0x92, 0x64, 0xac, 0x14, 0x22, 0xc3, 0x31, 0x5e, 0x88, 0x6a, 0xf5, 0xc1, 0x45, 0xad, 0x09, 0x17, 0x63, 0x32, 0xe6, 0xfe, 0x26, 0x5e, 0xb5, 0x0c, 0x7c, 0xd8, 0x63, 0xcc, 0xe9, 0xc5, 0x72, 0x0c, 0x70, 0xb9, 0xfc, 0xd5, 0x4f, 0xf6, 0xaf, 0xba, 0xd3, 0xb0, 0xe5, 0x6b, 0x3d, 0xf2, 0x99, 0xe0, 0xdf, 0x0b, 0x4a, 0xe2, 0xed, 0x16, 0x8f, 0x28, 0xab, 0x51, 0xcf, 0xc4, 0xbc, 0x9f, 0x67, 0x43, 0x01, 0x3b, 0xdb, 0x81, 0x44, 0x71, 0x28, 0xae, 0xe5, 0x31, 0x08, 0x83, 0x64, 0x58, 0x86, 0xb8, 0x58, 0x13, 0x07, 0xb7, 0x88, 0xb5, 0xca, 0x23, 0xf3, 0xd5, 0xec, 0x19, 0x74, 0x4c, 0x25, 0x44, 0x4c, 0xc3, 0xa2, 0xdb, 0xe2, 0x4d, 0x54, 0xd6, 0x5d, 0x5d, 0x68, 0x1e, 0x1d, 0x54, 0x5b, 0x49, 0x7e, 0x0f, 0x45, 0xd6, 0xbe, 0x25, 0x05, 0x1b, 0xa9, 0xc0, 0x90, 0xe5, 0x02, 0x45, 0x2d, 0x50, 0xa4, 0x02, 0xef, 0x70, 0xbd, 0xfd, 0x0a, 0x72, 0x7a, 0x5e, 0x6e, 0xbd, 0xe9, 0x10, 0x85, 0xa1, 0x8c, 0x68, 0x6a, 0xce, 0xaf, 0x0a, 0x43, 0xbe, 0x74, 0xbe, 0x0d, 0x9f, 0xef, 0x9e, 0x20, 0x2a, 0x5c, 0xd4, 0xd5, 0xb4, 0xff, 0x58, 0x5b, 0x73, 0xa4, 0xb1, 0x25, 0x3d, 0xc4, 0x11, 0x2c, 0xf3, 0x3c, 0xba, 0x72, 0x40, 0x53, 0xd7, 0x6e, 0xf3, 0xb0, 0x0d, 0x31, 0x0e, 0x65, 0x6d, 0x55, 0x2d, 0x6b, 0x77, 0x8d, 0xaf, 0x56, 0x3c, 0x77, 0xf2, 0x12, 0xdc, 0x25, 0x56, 0xf2, 0xee, 0x96, 0xc6, 0xdb, 0x2d, 0xc1, 0xbf, 0xa9, 0x47, 0x5e, 0xba, 0x33, 0xad, 0x6e, 0x81, 0xf8, 0x35, 0xa2, 0x94, 0xdc, 0x82, 0xa7, 0xc5, 0x7d, 0xba, 0xa5, 0x25, 0x2b, 0x64, 0x30, 0xf5, 0x38, 0x60, 0x78, 0xdc, 0x2f, 0x93, 0xb0, 0x12, 0xb2, 0x4f, 0x75, 0xea, 0xa9, 0x11, 0x11, 0x09, 0x69, 0x3f, 0x44, 0x38, 0x1f, 0x11, 0x14, 0x74, 0x34, 0xb6, 0x56, 0x7b, 0xac, 0x27, 0x5c, 0x9d, 0xf2, 0xc7, 0xa5, 0xc9, 0xd9, 0xb8, 0x74, 0x22, 0x70, 0x99, 0x52, 0xfc, 0xc4, 0x09, 0xfc, 0xd9, 0x23, 0x5f, 0x94, 0xe0, 0x2e, 0x4b, 0x21, 0x0f, 0x30, 0x5d, 0xac, 0x6b, 0x90, 0x62, 0xe2, 0x1d, 0x4d, 0x40, 0x45, 0xdc, 0x43, 0x88, 0x7c, 0xf8, 0x91, 0xc4, 0xae, 0x4f, 0x74, 0xcc, 0x42, 0x14, 0x08, 0x4e, 0x5a, 0x3e, 0x8c, 0xf9, 0x46, 0x8c, 0x8d, 0x1c, 0xe9, 0xd9, 0x54, 0x2f, 0xec, 0x46, 0xc7, 0x2c, 0xe6, 0x01, 0x75, 0x61, 0x1f, 0x16, 0xef, 0x2a, 0xbe, 0x1c, 0x6f, 0x3a, 0x89, 0x89, 0xd9, 0xd0, 0xf5, 0x3e, 0xf8, 0x91, 0xe0, 0x23, 0x93, 0x5d, 0x0c, 0x5e, 0xf9, 0x82, 0x39, 0x1c, 0x75, 0x67, 0x4a, 0x94, 0x7b, 0x81, 0xae, 0x8a, 0xcc, 0xa0, 0x15, 0x12, 0x6a, 0xc5, 0xe1, 0xc9, 0x27, 0x0e, 0x55, 0x21, 0xe6, 0x85, 0x29, 0x38, 0x33, 0xf9, 0x1f, 0x23, 0xb6, 0xd5, 0xe2, 0x67, 0x20, 0xe2, 0x09, 0xee, 0x7e, 0xfa, 0xe3, 0xa1, 0xf3, 0x90, 0x26, 0x4a, 0xd8, 0x47, 0xff, 0xe7, 0xe8, 0x32, 0xe3, 0x6a, 0x3c, 0xb7, 0x11, 0x33, 0xe7, 0x76, 0x44, 0xe9, 0x71, 0x24, 0xcb, 0xa0, 0x5f, 0x80, 0xdf, 0x06, 0x13, 0x3c, 0x60, 0x14, 0x7d, 0xc3, 0xb3, 0x10, 0x53, 0x29, 0xf7, 0xa7, 0xe4, 0xd3, 0xa4, 0x41, 0xec, 0x5a, 0x03, 0xf4, 0x14, 0x90, 0x69, 0x58, 0x0c, 0xf3, 0x64, 0x7a, 0x03, 0xba, 0x75, 0x70, 0x49, 0xce, 0xfa, 0xb0, 0x18, 0xeb, 0xf3, 0x1c, 0x1d, 0x06, 0x6f, 0x2b, 0x7e, 0x62, 0x7a, 0x3f, 0x43, 0xb4, 0xd3, 0xc0, 0x67, 0x02, 0x2d, 0x4e, 0x95, 0xa2, 0xe9, 0x74, 0x22, 0x15, 0xe6, 0xda, 0x85, 0x61, 0x22, 0xcc, 0xf5, 0xf4, 0x81, 0x29, 0x29, 0x6d, 0x96, 0x2d, 0x32, 0x05, 0x46, 0x86, 0x9e, 0x42, 0xd6, 0x62, 0x60, 0x64, 0xa8, 0xb5, 0x50, 0x14, 0x46, 0x15, 0x61, 0xdc, 0xcb, 0x30, 0x05, 0xc5, 0x54, 0x2b, 0x2b, 0x0f, 0xa2, 0xab, 0x36, 0x8b, 0xf4, 0x94, 0xe4, 0x04, 0x33, 0x46, 0x71, 0x7b, 0xa4, 0x50, 0xe0, 0x7f, 0x8b, 0xf0, 0xcb, 0xd9, 0xfa, 0x7a, 0xdf, 0xdb, 0xfc, 0x6d, 0x47, 0x03, 0x48, 0xb7, 0x38, 0xf4, 0x76, 0x94, 0x17, 0xe7, 0xa1, 0x24, 0x5f, 0xfd, 0x62, 0xcf, 0x11, 0xd8, 0x10, 0x25, 0x37, 0x86, 0x3d, 0x4a, 0x5c, 0xf6, 0x8f, 0xec, 0x4c, 0x9b, 0x44, 0x00, 0x10, 0xa6, 0x95, 0xaf, 0x81, 0xc7, 0x0a, 0x1d, 0x05, 0xfe, 0x19, 0x9c, 0x94, 0x7d, 0xd6, 0x09, 0xc1, 0xad, 0x34, 0xc5, 0xa2, 0x44, 0x62, 0xb2, 0xd6, 0xc9, 0x44, 0xc1, 0xa7, 0xad, 0xf2, 0x4d, 0xf4, 0x39, 0x08, 0xa4, 0x94, 0x5a, 0xf9, 0x94, 0x2f, 0xf1, 0x68, 0xa6, 0xf7, 0xe5, 0xaa, 0xa9, 0xa3, 0xba, 0xb5, 0xe6, 0x92, 0x86, 0xf7, 0x5a, 0x2c, 0xb9, 0xbb, 0x8f, 0xe4, 0x5f, 0x6b, 0x90, 0x0f, 0x48, 0xd5, 0x39, 0x75, 0x31, 0x0c, 0xa7, 0x32, 0xdc, 0x2f, 0x2b, 0x5e, 0x5d, 0x4d, 0x35, 0x6f, 0xaa, 0xac, 0x12, 0x85, 0xce, 0x1b, 0x76, 0xe0, 0x24, 0x0a, 0x6a, 0xe1, 0x36, 0x18, 0xdb, 0xed, 0x76, 0x40, 0x9a, 0x6b, 0xb8, 0x66, 0xe2, 0x21, 0x0c, 0x34, 0xdf, 0x09, 0x21, 0x1e, 0x04, 0x3a, 0x08, 0x2c, 0x6b, 0x9f, 0x90, 0x69, 0xa9, 0xc7, 0xd9, 0x74, 0xe7, 0xa6, 0xdc, 0x0b, 0xc3, 0x5b, 0xa2, 0x18, 0x8d, 0xce, 0x7f, 0xb1, 0xb2, 0x70, 0x30, 0x1f, 0x8e, 0x61, 0x08, 0x2f, 0x9b, 0x35, 0x6b, 0x70, 0x1a, 0x7d, 0x3a, 0x6b, 0x57, 0x15, 0xc6, 0xe8, 0x96, 0xec, 0x13, 0x73, 0x79, 0x77, 0x7a, 0x78, 0x84, 0x49, 0x80, 0x11, 0x73, 0x62, 0x5f, 0xd0, 0x70, 0xe4, 0x95, 0x57, 0xad, 0x43, 0xd3, 0x36, 0xd5, 0x8b, 0x6b, 0xb0, 0xee, 0x9c, 0x47, 0x85, 0x89, 0xba, 0x07, 0xac, 0x98, 0x3d, 0xdf, 0x00, 0xf4, 0x97, 0x75, 0x7a, 0x0c, 0x41, 0xad, 0x40, 0x5e, 0x87, 0x80, 0x49, 0x04, 0x80, 0x6e, 0xe9, 0xb9, 0x91, 0xb3, 0x6f, 0x19, 0x9c, 0x00, 0x06, 0x2d, 0xb0, 0xec, 0x97, 0x13, 0xa1, 0x81, 0x1d, 0x57, 0x1b, 0x5b, 0x16, 0xaf, 0x83, 0xca, 0x2c, 0x9e, 0x1c, 0x9e, 0x6d, 0x33, 0xdf, 0x9e, 0x69, 0x6d, 0x13, 0xde, 0x2b, 0xc1, 0x05, 0x16, 0x16, 0x71, 0x20, 0x44, 0x35, 0xa4, 0x59, 0x37, 0xb4, 0x16, 0x3c, 0xce, 0x0c, 0x87, 0xa6, 0xcc, 0x10, 0xcd, 0x84, 0xda, 0x43, 0xf8, 0x36, 0x77, 0xbe, 0x43, 0xb0, 0xd0, 0xc1, 0x95, 0x9e, 0xa6, 0xf4, 0x1f, 0x11, 0x2f, 0x23, 0x6e, 0xb0, 0xab, 0x00, 0x1f, 0xb4, 0xa4, 0x4a, 0x23, 0xcd, 0x54, 0xe2, 0xb7, 0x2a, 0x69, 0x7b, 0xc9, 0x71, 0x23, 0xa8, 0xb4, 0xb4, 0xe8, 0xa5, 0x6f, 0x07, 0xc2, 0xd0, 0x91, 0x75, 0x03, 0xc4, 0xba, 0xca, 0x10, 0x77, 0xd6, 0xf5, 0x56, 0x3b, 0x0f, 0xfa, 0x04, 0xc3, 0x58, 0x8c, 0x1e, 0x94, 0x0b, 0xda, 0x77, 0x80, 0x15, 0x74, 0x74, 0x57, 0x0b, 0xe7, 0x9d, 0x99, 0x01, 0xc7, 0xe5, 0xc5, 0xdc, 0x6b, 0xa1, 0x72, 0x18, 0xd1, 0x95, 0xea, 0xb3, 0x60, 0x69, 0xec, 0x8b, 0x2a, 0x19, 0x3a, 0xa7, 0x2c, 0xad, 0x1b, 0x3a, 0xb6, 0x18, 0xf5, 0x07, 0xb3, 0x1f, 0x4e, 0x2e, 0x98, 0xd6, 0x74, 0xdb, 0xbd, 0x35, 0xf8, 0x84, 0xb7, 0xb0, 0x0d, 0x42, 0xf2, 0x7c, 0xfe, 0x42, 0x3c, 0x97, 0xb7, 0x5f, 0x69, 0x31, 0x08, 0x73, 0x35, 0x7b, 0x39, 0x83, 0xf2, 0xc7, 0xb0, 0x5d, 0x1a, 0xb6, 0xf9, 0x7e, 0x11, 0xd5, 0x9d, 0x24, 0x6a, 0x3b, 0x89, 0x78, 0x0e, 0xd5, 0x89, 0x3c, 0xcc, 0xb7, 0xf2, 0xba, 0x39, 0xc6, 0xa6, 0x03, 0x31, 0xed, 0xd7, 0x60, 0xc0, 0x95, 0xb9, 0xee, 0x02, 0x8d, 0x26, 0x6c, 0xf4, 0xcf, 0xfd, 0x46, 0xcd, 0x43, 0x4b, 0x29, 0x6c, 0xf8, 0xdb, 0x69, 0xdb, 0xc5, 0x47, 0x39, 0x33, 0x9b, 0xb6, 0x54, 0xd0, 0x5c, 0xab, 0x7f, 0xd8, 0xca, 0xb9, 0xed, 0x67, 0xd0, 0x12, 0x11, 0xf8, 0x9d, 0xbb, 0x0c, 0xff, 0xd5, 0x65, 0xee, 0xa0, 0x7b, 0xf6, 0x6c, 0x5b, 0xc1, 0x63, 0x54, 0xfd, 0x02, 0xd7, 0x58, 0x02, 0x1a, 0xdf, 0xf0, 0xd0, 0xef, 0xf9, 0x57, 0x18, 0xd8, 0x41, 0xa4, 0xd0, 0x68, 0xd9, 0x37, 0x86, 0xce, 0x3f, 0xca, 0x17, 0x0a, 0x8d, 0x47, 0x03, 0x07, 0xa4, 0x89, 0x67, 0x69, 0x27, 0xa2, 0xec, 0x2d, 0x58, 0xb7, 0xe5, 0x19, 0xda, 0x5c, 0xdb, 0xb8, 0x18, 0xe9, 0xf1, 0x43, 0xdc, 0x49, 0x70, 0xa1, 0xb9, 0xd7, 0x27, 0x4a, 0xb7, 0xcd, 0x2a, 0x2c, 0xe4, 0xb1, 0xa8, 0x55, 0x08, 0x32, 0x80, 0xeb, 0x2a, 0x0c, 0x0b, 0x50, 0x3f, 0xe2, 0x2c, 0x9c, 0x31, 0x77, 0x88, 0x5a, 0x1d, 0x86, 0xbc, 0x2b, 0xdb, 0x55, 0x66, 0x9d, 0xa8, 0x2e, 0xef, 0xe9, 0x52, 0x68, 0xc2, 0x29, 0x72, 0x1d, 0x41, 0xa9, 0x03, 0x66, 0xdc, 0xd1, 0xdf, 0x10, 0x55, 0x6a, 0x14, 0x27, 0xbb, 0x74, 0x29, 0x16, 0xc1, 0x24, 0x16, 0xb8, 0xe9, 0xdb, 0xe8, 0x4e, 0xa6, 0x39, 0x2c, 0x74, 0xdf, 0xdd, 0xc0, 0xdc, 0x5e, 0xf4, 0x2c, 0x9a, 0xc8, 0x4e, 0xba, 0xdc, 0xe0, 0xed, 0x03, 0xf9, 0x1a, 0x0d, 0xed, 0x30, 0xfc, 0x0e, 0xda, 0x84, 0x68, 0x57, 0x42, 0x79, 0xbb, 0xce, 0x0d, 0xa4, 0xae, 0x5d, 0x42, 0xc5, 0x0f, 0x09, 0x5f, 0x52, 0x64, 0x56, 0xc6, 0xb8, 0xe7, 0xb9, 0x83, 0x7c, 0x07, 0x7a, 0x4d, 0xcf, 0xc3, 0x30, 0x4d, 0x1c, 0x6b, 0xc4, 0x54, 0x40, 0x02, 0xe1, 0x47, 0xce, 0x75, 0xa8, 0x2b, 0x81, 0x7e, 0x82, 0x78, 0x31, 0xc2, 0x92, 0x49, 0x73, 0x0a, 0xff, 0x96, 0xf8, 0xa7, 0x48, 0xd9, 0x85, 0xf4, 0x03, 0x32, 0xe0, 0xb4, 0x1f, 0x32, 0xee, 0x3f, 0xfd, 0x47, 0x4e, 0x74, 0xc4, 0x1f, 0x74, 0x3f, 0x37, 0xe1, 0xea, 0x87, 0xc5, 0x80, 0x48, 0xbd, 0x47, 0x86, 0x56, 0xa2, 0xfd, 0x48, 0x24, 0xdf, 0x94, 0x29, 0x69, 0x84, 0x69, 0xad, 0xe4, 0xa4, 0xbe, 0xec, 0x3f, 0x24, 0xf9, 0xc5, 0xdb, 0xf9, 0x01, 0x7e, 0x0b, 0xfa, 0x0c, 0xe9, 0x5a, 0xdb, 0xdb, 0x9c, 0x5b, 0x43, 0x4c, 0xab, 0x61, 0x58, 0x6b, 0x77, 0xcb, 0x80, 0x8a, 0xcb, 0x22, 0xec, 0x05, 0xcf, 0xe4, 0x23, 0xe5, 0x9c, 0x55, 0x9e, 0x58, 0x92, 0x66, 0x8c, 0x64, 0x8d, 0x71, 0x65, 0x3c, 0x45, 0xcc, 0x6c, 0x8a, 0xb4, 0x4c, 0xba, 0x4f, 0xe6, 0x92, 0xd0, 0xb8, 0x61, 0x3d, 0xb2, 0x3c, 0xa2, 0xad, 0xa4, 0x83, 0xad, 0x96, 0x95, 0x4a, 0x5c, 0x38, 0xb5, 0x9e, 0x8d, 0x1a, 0x1e, 0xea, 0xdf, 0x25, 0x8a, 0xba, 0x80, 0x61, 0x15, 0xad, 0x50, 0x08, 0x9f, 0x40, 0x08, 0xfb, 0x8a, 0xa5, 0xf9, 0x3b, 0x88, 0x57, 0xfb, 0xdb, 0x5c, 0x74, 0x0a, 0x43, 0x15, 0x1a, 0xc8, 0x9f, 0xce, 0x41, 0xa7, 0x12, 0xdb, 0x79, 0x04, 0x1d, 0xe6, 0x0d, 0xfb, 0x6f, 0x59, 0xa5, 0x5f, 0xeb, 0x1d, 0x91, 0x02, 0xb1, 0x68, 0x2b, 0x00, 0x0a, 0xf8, 0xec, 0xe0, 0xf1, 0x4b, 0xc3, 0x2f, 0xe7, 0xbe, 0x24, 0x44, 0xeb, 0x33, 0x67, 0xbf, 0xac, 0xe3, 0x3b, 0xb1, 0xb6, 0xbd, 0xbb, 0x32, 0xf0, 0x5d, 0x8f, 0x31, 0xdf, 0xa8, 0xea, 0xa1, 0x2c, 0x90, 0xcf, 0x07, 0x83, 0x12, 0x73, 0x97, 0x4e, 0xb6, 0xa5, 0x4b, 0x94, 0x5f, 0x7a, 0xfa, 0x2c, 0xa0, 0x33, 0x20, 0x62, 0x33, 0xe4, 0x86, 0xb7, 0xa5, 0xeb, 0xa0, 0xe4, 0xa2, 0x5c, 0xb6, 0xd6, 0xd3, 0x83, 0xa5, 0xe4, 0x60, 0xc8, 0x3b, 0xc0, 0x34, 0x5b, 0xce, 0x09, 0x45, 0xe5, 0xca, 0xf0, 0xd8, 0xd3, 0x5f, 0x67, 0x28, 0x0b, 0xeb, 0x87, 0x52, 0xb4, 0xd5, 0xe2, 0x24, 0xd7, 0x4a, 0x16, 0x1a, 0x25, 0x37, 0x84, 0x9d, 0x52, 0x42, 0xc8, 0xe7, 0x8e, 0x52, 0xb6, 0xfc, 0x6a, 0x32, 0x65, 0x85, 0x35, 0x72, 0x18, 0x29, 0x30, 0xa4, 0x11, 0xa5, 0x72, 0x87, 0x56, 0xd7, 0x56, 0x66, 0xc1, 0xd2, 0xe3, 0xab, 0x8e, 0xe4, 0x44, 0x4c, 0xb1, 0x4a, 0xd9, 0xbd, 0xdf, 0x6b, 0x9b, 0xd4, 0x1c, 0x88, 0xb4, 0xc7, 0x6d, 0x7e, 0xc5, 0x5a, 0xfd, 0x73, 0x5d, 0xab, 0xbe, 0x73, 0xb9, 0x45, 0x73, 0x50, 0xcd, 0x4d, 0x99, 0xca, 0xed, 0x52, 0xfe, 0x61, 0x9d, 0x18, 0x63, 0xc3, 0x6e, 0x34, 0x59, 0xa6, 0x82, 0xd7, 0xa6, 0x9d, 0xb9, 0x06, 0xeb, 0x9c, 0x2b, 0x59, 0x03, 0x52, 0xc8, 0x52, 0x58, 0x87, 0xbf, 0x2d, 0x93, 0xc4, 0x14, 0xa2, 0x45, 0x99, 0x52, 0xc6, 0x0f, 0xa8, 0xf2, 0x22, 0x24, 0x31, 0x4c, 0x72, 0x65, 0xe8, 0xcb, 0x56, 0xfc, 0xa6, 0x16, 0x67, 0xed, 0x3e, 0x22, 0xab, 0xf5, 0x1b, 0x15, 0xc5, 0x5f, 0xbb, 0x07, 0x1c, 0x80, 0x6f, 0x34, 0x8c, 0xc9, 0xd7, 0x1b, 0xf2, 0x78, 0xee, 0xfb, 0x15, 0x28, 0x72, 0x61, 0xff, 0x88, 0xfa, 0x94, 0xb6, 0x51, 0x9d, 0xd1, 0x1f, 0x6f, 0x07, 0xfd, 0x27, 0x4d, 0x48, 0xfb, 0x64, 0x27, 0x0d, 0xf9, 0x00, 0xfc, 0x35, 0xc3, 0x00, 0x6e, 0xca, 0x6f, 0xbb, 0xed, 0xee, 0xa3, 0x90, 0x11, 0xda, 0x99, 0xdf, 0x45, 0xcf, 0x9e, 0x93, 0xc6, 0x75, 0xbd, 0xe3, 0x12, 0x75, 0x10, 0x4b, 0xef, 0xda, 0xc6, 0x28, 0x60, 0x3a, 0x3a, 0xe5, 0x69, 0x4b, 0xc0, 0x4c, 0xd4, 0xc3, 0x15, 0x1a, 0xd9, 0xf3, 0xca, 0x1a, 0x99, 0x75, 0xd1, 0x95, 0x1f, 0xca, 0x0e, 0x37, 0xe1, 0xab, 0xce, 0x97, 0x9b, 0xf6, 0xbf, 0x7f, 0x02, 0x9d, 0xdb, 0x78, 0x63, 0x86, 0xa8, 0xa8, 0xde, 0x4a, 0xea, 0x27, 0x79, 0x95, 0x12, 0xba, 0xbc, 0x68, 0xf3, 0xa3, 0x76, 0xf9, 0x9c, 0x16, 0xc4, 0x4f, 0xef, 0x86, 0xce, 0xf2, 0xcd, 0x56, 0xf0, 0x6f, 0xc5, 0x94, 0x51, 0x66, 0xb3, 0xc0, 0x93, 0x24, 0x6e, 0xf8, 0xbe, 0x85, 0x65, 0xab, 0xa0, 0xc2, 0x9f, 0x30, 0x16, 0x0e, 0x51, 0xf4, 0xd1, 0x02, 0x59, 0x18, 0xa7, 0x5a, 0xa2, 0xc3, 0x2d, 0x35, 0x94, 0x0b, 0x22, 0x1e, 0x43, 0x66, 0x8a, 0x0d, 0xe4, 0xfb, 0x72, 0xa5, 0x47, 0xe7, 0xd1, 0x8d, 0x3a, 0x41, 0x08, 0x38, 0xed, 0xd2, 0x35, 0x30, 0x66, 0x7c, 0x9c, 0x22, 0xf4, 0xb9, 0x3f, 0x66, 0x00, 0x86, 0x30, 0x22, 0xff, 0x4a, 0x20, 0xa5, 0x04, 0x24, 0x53, 0x81, 0xd0, 0x7e, 0x00, 0x5c, 0x2b, 0x85, 0xe6, 0x87, 0xd8, 0x43, 0xf7, 0xc3, 0x40, 0x99, 0x59, 0x08, 0xd9, 0x7c, 0x62, 0xf0, 0x22, 0xd9, 0x61, 0x1c, 0x81, 0x31, 0xec, 0x44, 0x24, 0xf0, 0x4e, 0x88, 0xcf, 0xf5, 0x68, 0x28, 0x07, 0x46, 0xa5, 0x0d, 0x85, 0x5a, 0xb3, 0x94, 0x29, 0x7a, 0x1a, 0x1c, 0x21, 0x79, 0xe8, 0x15, 0xc9, 0xc0, 0x43, 0x40, 0x0f, 0x39, 0xf0, 0xb0, 0xef, 0x74, 0x60, 0x0f, 0x8c, 0x8f, 0x2c, 0xb5, 0x3c, 0xd2, 0x94, 0x3d, 0x31, 0xe5, 0x88, 0x65, 0x18, 0x66, 0xc0, 0x4c, 0x54, 0x7c, 0xd7, 0x89, 0x09, 0x05, 0x9d, 0xb7, 0xc8, 0x1c, 0xce, 0x48, 0x84, 0x46, 0x33, 0x43, 0x83, 0x35, 0x56, 0xd3, 0x20, 0x00, 0x90, 0x28, 0xb5, 0xa6, 0x1f, 0x1b, 0x9e, 0x14, 0x9b, 0xa6, 0x62, 0xa5, 0x6f, 0x7a, 0x72, 0x26, 0xcc, 0x2e, 0x8e, 0xe0, 0x7a, 0xe6, 0xc7, 0x67, 0x33, 0x5a, 0x83, 0xbd, 0x8f, 0x2b, 0xc8, 0x07, 0x67, 0xf8, 0xe6, 0x8e, 0xff, 0x4c, 0x48, 0x3b, 0xb3, 0x95, 0x06, 0x2b, 0x99, 0x9b, 0x1b, 0xa0, 0xa5, 0x3d, 0x2c, 0xe1, 0x5f, 0x49, 0xff, 0xd6, 0xa2, 0x00, 0x5d, 0xac, 0x5f, 0x0e, 0xd0, 0x57, 0x90, 0x19, 0x4a, 0x03, 0x3a, 0x40, 0x7e, 0xb2, 0xbe, 0x63, 0xc7, 0x8b, 0x0d, 0xbc, 0xbf, 0xed, 0xb7, 0xae, 0xf0, 0x63, 0x18, 0x6e, 0x4c, 0xbf, 0xd1, 0x48, 0x84, 0x79, 0x73, 0xb8, 0xb4, 0xb1, 0x3e, 0xf6, 0x50, 0xf1, 0x27, 0xdb, 0x55, 0xc5, 0xf4, 0x37, 0xdc, 0x55, 0x7d, 0x5f, 0x70, 0xbb, 0x63, 0x1a, 0x32, 0x41, 0xd1, 0x57, 0x26, 0x11, 0xf5, 0x14, 0x16, 0x25, 0xf1, 0x68, 0x96, 0x14, 0xa0, 0x9b, 0x80, 0x8f, 0x04, 0xd4, 0xf7, 0x7a, 0x3c, 0x54, 0xcc, 0x16, 0x57, 0x82, 0x10, 0x4f, 0x88, 0x1b, 0x10, 0xac, 0x92, 0x6b, 0x00, 0x42, 0xb7, 0x47, 0x3f, 0x87, 0xa0, 0x97, 0xdf, 0xa5, 0x30, 0xa0, 0x67, 0xac, 0x37, 0x21, 0x89, 0xed, 0xf2, 0x27, 0x0a, 0xcf, 0x2b, 0x55, 0xc8, 0xd1, 0xad, 0x1b, 0x97, 0xec, 0xaf, 0xea, 0x92, 0x35, 0xf5, 0xeb, 0x10, 0xfb, 0x24, 0xe0, 0x02, 0x00, 0x01, 0x0a, 0xba, 0xa2, 0x1c, 0xaa, 0x78, 0xf8, 0xf2, 0x3f, 0xfe, 0xfd, 0xff, 0xfc, 0xbf, 0xff, 0xfb, 0xa5, 0xdf, 0x1b, 0x77, 0xc7, 0x2b, 0xa6, 0xec, 0x1d, 0x48, 0x8e, 0xfb, 0x09, 0x39, 0xfe, 0xa6, 0xd0, 0xe8, 0xe3, 0x8c, 0xbf, 0x67, 0x69, 0x70, 0x79, 0xe2, 0xe1, 0xb4, 0x98, 0xce, 0xba, 0x2e, 0x3c, 0xdf, 0x2e, 0x16, 0x59, 0x40, 0x79, 0x90, 0x0a, 0x9c, 0x85, 0x33, 0xf4, 0xbb, 0x68, 0xf9, 0x94, 0x61, 0x8c, 0xdf, 0xca, 0x29, 0x7a, 0xbe, 0x61, 0x3b, 0xd0, 0x36, 0xd9, 0x95, 0xaa, 0xb7, 0x32, 0xc9, 0x08, 0x5d, 0x52, 0x9e, 0x4f, 0xbe, 0x6b, 0xc0, 0x7b, 0x3d, 0x9a, 0x31, 0x78, 0x49, 0xb2, 0x39, 0x37, 0x57, 0x91, 0x98, 0x94, 0x91, 0x3e, 0x9f, 0x4c, 0xfc, 0x15, 0x8b, 0x1b, 0x72, 0xf1, 0x72, 0x79, 0x83, 0x74, 0x58, 0x8f, 0xd6, 0x68, 0xe6, 0x6b, 0x8d, 0x78, 0x53, 0x92, 0xcb, 0x63, 0x61, 0xff, 0x0a, 0x87, 0xf6, 0x03, 0x6a, 0xd9, 0xec, 0x71, 0x00, 0xc4, 0xef, 0xb5, 0xee, 0xc4, 0xfc, 0x3d, 0x4a, 0x16, 0x68, 0x48, 0xfd, 0x09, 0xc8, 0x44, 0xb4, 0xfe, 0x8f, 0x4d, 0x4a, 0x27, 0xfa, 0xbd, 0x42, 0x79, 0x32, 0x89, 0x37, 0xa6, 0x66, 0xd1, 0x99, 0x6e, 0x49, 0xbe, 0x0b, 0x93, 0xb2, 0xb8, 0x6e, 0x26, 0x18, 0x4e, 0x94, 0x2c, 0x45, 0x87, 0x11, 0x70, 0xdb, 0x8c, 0x00, 0xa1, 0x69, 0x80, 0xe5, 0xd2, 0xb2, 0x09, 0xb4, 0x05, 0x2d, 0xb9, 0x49, 0x04, 0xd3, 0x82, 0x5b, 0xe9, 0x19, 0x5c, 0xa1, 0x36, 0x63, 0x9e, 0x36, 0x92, 0x0c, 0x44, 0xd6, 0x97, 0x15, 0x71, 0x75, 0xde, 0xca, 0x38, 0xf8, 0x70, 0xb6, 0xf5, 0xd2, 0xaf, 0x3e, 0xa0, 0x84, 0x2e, 0x62, 0xbd, 0xe3, 0x86, 0x12, 0xaf, 0x65, 0x2a, 0x8e, 0xe5, 0xab, 0xc2, 0xe4, 0x3b, 0xc6, 0x14, 0x10, 0xa7, 0x47, 0x82, 0x6a, 0x9b, 0x7b, 0xc4, 0x4e, 0xe1, 0x8f, 0x9e, 0xa2, 0xc0, 0xfc, 0xd7, 0x36, 0xed, 0xf4, 0x87, 0x58, 0x9a, 0xf1, 0x9f, 0xce, 0x78, 0xff, 0xbb, 0x8d, 0x7c, 0x21, 0xdc, 0x2c, 0x8f, 0x75, 0xe5, 0xdb, 0x9e, 0xbf, 0xe0, 0x7f, 0x69, 0x29, 0xb4, 0x98, 0x0e, 0x40, 0x66, 0xf2, 0xd8, 0xc3, 0x48, 0xbb, 0x8e, 0x68, 0x0c, 0x11, 0xf5, 0xbc, 0xa7, 0x67, 0x40, 0x40, 0xae, 0x02, 0x37, 0xd4, 0xc8, 0xd7, 0x73, 0x51, 0x11, 0xc7, 0x34, 0xea, 0x9e, 0xa2, 0x47, 0xa1, 0x21, 0x95, 0x60, 0x53, 0x62, 0x28, 0x08, 0x5e, 0x70, 0x11, 0x66, 0xd2, 0xa4, 0x88, 0x32, 0x5d, 0x81, 0x39, 0xae, 0xe4, 0x6d, 0xff, 0xf6, 0xab, 0x99, 0x2a, 0x5d, 0x0f, 0x5a, 0x77, 0xc5, 0x5e, 0xc2, 0xfd, 0xda, 0xa0, 0x83, 0xe7, 0xdc, 0x41, 0x41, 0xbe, 0x0e, 0xdb, 0x99, 0x60, 0x1d, 0xf3, 0x63, 0xf9, 0x16, 0xee, 0x02, 0xf7, 0x48, 0x24, 0x86, 0x58, 0x5c, 0x41, 0x0e, 0x69, 0x29, 0x51, 0x51, 0x90, 0xc8, 0x78, 0x75, 0xa0, 0xd3, 0x20, 0xc2, 0xeb, 0xd7, 0xcc, 0xa2, 0x3d, 0x05, 0x54, 0x50, 0x5b, 0xe8, 0x19, 0x4f, 0xab, 0x8b, 0x4c, 0xff, 0x28, 0x1f, 0x66, 0x2f, 0xda, 0x5d, 0x06, 0xa6, 0xfa, 0x31, 0xba, 0x6b, 0x11, 0x50, 0xf6, 0x12, 0xc4, 0xdd, 0x4a, 0xe6, 0xbe, 0x15, 0xaf, 0x06, 0xe2, 0xa3, 0x67, 0x7b, 0xd2, 0xd2, 0xf1, 0x8b, 0x7c, 0xca, 0x6e, 0x74, 0x65, 0xf4, 0x91, 0xb3, 0xb3, 0x29, 0x2d, 0xf4, 0xe4, 0xc2, 0x73, 0x81, 0x09, 0x05, 0x81, 0xb0, 0xc8, 0xe9, 0xd8, 0x76, 0xf4, 0xfe, 0x50, 0x0f, 0x4f, 0x8b, 0x8e, 0xa7, 0x88, 0x64, 0x82, 0xc0, 0x9f, 0xf6, 0xc0, 0x52, 0x6c, 0x6e, 0xa8, 0x35, 0xa5, 0x5a, 0x15, 0xd3, 0xd2, 0xc1, 0x36, 0xee, 0x02, 0xd2, 0x1e, 0xfb, 0x31, 0xd4, 0x5f, 0xba, 0x12, 0xe9, 0x0f, 0x76, 0x8c, 0x0e, 0x58, 0x79, 0xeb, 0xcc, 0x84, 0x09, 0x0a, 0x19, 0xee, 0x2d, 0xe7, 0xdb, 0x9a, 0xda, 0x4a, 0xc4, 0x66, 0xc0, 0xa7, 0xc5, 0x4d, 0xd9, 0x4e, 0x73, 0x6c, 0x11, 0x48, 0x58, 0xa7, 0xb0, 0xf6, 0xb2, 0x41, 0xde, 0x80, 0x9d, 0xe7, 0xb6, 0x13, 0x78, 0x42, 0x03, 0xe6, 0x9a, 0x3b, 0xe8, 0xb9, 0x8f, 0x85, 0xff, 0x50, 0x70, 0x9d, 0xd5, 0xb7, 0x08, 0xf1, 0x80, 0x7f, 0xf6, 0xe2, 0xc5, 0xce, 0x3d, 0x0a, 0xc4, 0xac, 0x42, 0xbe, 0xae, 0x7b, 0xcc, 0x17, 0x2f, 0x77, 0x1b, 0x3c, 0x63, 0x66, 0x2c, 0x02, 0x89, 0x6a, 0x6e, 0x59, 0xaf, 0x1b, 0x49, 0x11, 0x19, 0x99, 0x5b, 0xf3, 0x82, 0xb4, 0xb5, 0x97, 0x34, 0xc7, 0xed, 0xc4, 0x8a, 0xc6, 0x7b, 0x3e, 0xaf, 0xe6, 0x73, 0x1d, 0x5a, 0x7f, 0xaf, 0x1d, 0x5a, 0x75, 0x1e, 0x9e, 0x2c, 0x5f, 0xec, 0x31, 0xb5, 0x8e, 0xc0, 0x86, 0xe4, 0x39, 0x9f, 0x8e, 0xb3, 0xc9, 0xb5, 0x8d, 0xde, 0x6d, 0x72, 0xdf, 0x72, 0x6a, 0x2c, 0x7a, 0x98, 0x69, 0x07, 0x3e, 0xcc, 0x38, 0x1f, 0x1a, 0x80, 0x1c, 0x82, 0x7c, 0x85, 0x4a, 0x30, 0x1f, 0x37, 0xe5, 0xaa, 0xf6, 0x67, 0x4f, 0xb6, 0x01, 0x7d, 0xe0, 0x60, 0xbc, 0x82, 0x02, 0x6a, 0x76, 0x2c, 0x6a, 0x3e, 0x30, 0x58, 0x7b, 0x76, 0xd2, 0x3c, 0x26, 0x9c, 0x86, 0x05, 0x42, 0x49, 0x0c, 0x0f, 0xf4, 0x34, 0xbe, 0x59, 0xa6, 0x00, 0x11, 0x40, 0xa1, 0x2b, 0x1d, 0x58, 0x1b, 0x8b, 0x99, 0x4b, 0x26, 0x37, 0x15, 0x15, 0x07, 0x07, 0x13, 0x1f, 0xac, 0x9e, 0xc4, 0x4c, 0x30, 0x44, 0x00, 0x06, 0x39, 0x86, 0x0f, 0xf0, 0x0f, 0x10, 0xa4, 0x88, 0xc3, 0x09, 0x85, 0xf7, 0x12, 0x72, 0x55, 0x3e, 0xb3, 0xda, 0x88, 0x6d, 0x62, 0x23, 0x96, 0x92, 0x15, 0xfc, 0x09, 0xc5, 0x3f, 0xe1, 0x84, 0x76, 0xa4, 0xba, 0xc6, 0x8f, 0x11, 0x01, 0x3a, 0x67, 0xfa, 0xf1, 0xe9, 0x5d, 0x9f, 0x20, 0x5e, 0x76, 0xa4, 0x57, 0x9f, 0xba, 0x87, 0x0c, 0x1a, 0x40, 0xc5, 0x60, 0xa3, 0x36, 0x86, 0xfd, 0xcc, 0x96, 0x28, 0xbb, 0x71, 0x0c, 0x57, 0x57, 0x0f, 0x8a, 0x99, 0x18, 0xdf, 0xe3, 0x1a, 0x81, 0xd8, 0xcb, 0x12, 0x05, 0x49, 0xbc, 0x7a, 0xf2, 0x3a, 0xe5, 0xc4, 0x54, 0xb8, 0x17, 0x6e, 0xf6, 0xfd, 0x7d, 0x87, 0x90, 0x28, 0x28, 0xb4, 0xa8, 0x4e, 0x53, 0x6b, 0x07, 0x0f, 0xff, 0xf7, 0x32, 0xf8, 0x90, 0xba, 0x74, 0x8f, 0xc5, 0x5e, 0x4d, 0xee, 0x0d, 0x38, 0x84, 0xc5, 0xbe, 0xba, 0xbe, 0xc5, 0xd3, 0x53, 0xc2, 0x9e, 0xbc, 0xe1, 0xad, 0x33, 0xcd, 0xe1, 0x26, 0x7a, 0x0c, 0x00, 0x32, 0x74, 0xf6, 0x38, 0x13, 0x89, 0x04, 0x96, 0x34, 0xb8, 0x62, 0xc1, 0x5d, 0x3a, 0x68, 0xe2, 0x32, 0xef, 0xae, 0x1e, 0xf4, 0x1e, 0x96, 0x49, 0xa8, 0xab, 0x0f, 0x83, 0x37, 0xc4, 0x0d, 0x1c, 0x68, 0x79, 0x02, 0x41, 0xcd, 0x03, 0x67, 0x0a, 0x5d, 0x7a, 0x0e, 0xa6, 0xb4, 0xda, 0x87, 0x90, 0x37, 0x46, 0x87, 0x57, 0x9f, 0x54, 0xce, 0x9d, 0x8d, 0xd3, 0x8a, 0x08, 0x49, 0x03, 0xd4, 0x18, 0xb3, 0x96, 0xf6, 0x58, 0x1f, 0x6d, 0x37, 0x0d, 0xb3, 0x69, 0xe3, 0x71, 0x75, 0xc1, 0x3b, 0x4a, 0x8a, 0xae, 0xe5, 0xf6, 0x7e, 0xfb, 0x5e, 0x76, 0xfb, 0x03, 0xee, 0xfb, 0xcc, 0xf4, 0x91, 0xcd, 0x15, 0x8f, 0x5e, 0xf5, 0xec, 0xfc, 0x2d, 0xdf, 0x83, 0xa5, 0xd1, 0x45, 0xa6, 0xf1, 0x83, 0x69, 0xa7, 0x57, 0xf3, 0x1d, 0xc5, 0x46, 0xf8, 0x33, 0xe5, 0xa0, 0xb7, 0xcf, 0xda, 0xce, 0x35, 0x56, 0x96, 0xc5, 0x6f, 0x4c, 0x27, 0x5c, 0xd3, 0xdd, 0xf2, 0xcf, 0x44, 0xcb, 0xdc, 0xa4, 0x0e, 0xe0, 0xcb, 0xef, 0x3c, 0xf0, 0xcc, 0x58, 0xcd, 0x11, 0xfd, 0xb8, 0x03, 0x46, 0x21, 0x98, 0x41, 0xda, 0xce, 0x6b, 0xeb, 0xdf, 0x4c, 0xb6, 0x21, 0x67, 0xe1, 0x8e, 0xf6, 0x12, 0x56, 0x94, 0xc8, 0x67, 0xd0, 0x33, 0x90, 0xce, 0x25, 0x3d, 0xe3, 0xea, 0x42, 0xbe, 0xe3, 0xa6, 0x2f, 0x01, 0x9b, 0xbe, 0x92, 0x1a, 0x5a, 0xe6, 0x51, 0x2c, 0xac, 0x30, 0x46, 0x94, 0x02, 0x24, 0x3f, 0x7e, 0x6a, 0x20, 0x80, 0xd8, 0xb3, 0x1f, 0x61, 0xdd, 0x51, 0x44, 0x86, 0xf8, 0xa5, 0x0a, 0x32, 0x5d, 0x1e, 0xb8, 0x3b, 0xd5, 0x0e, 0x32, 0xa5, 0xaf, 0xaf, 0xf5, 0x09, 0x26, 0x99, 0x08, 0xa2, 0xd4, 0x28, 0x2c, 0x03, 0x86, 0x6a, 0x44, 0x4c, 0xcd, 0xc7, 0xb8, 0x7d, 0x2e, 0xcf, 0x5b, 0x9a, 0x64, 0xe1, 0x9a, 0x90, 0xe0, 0xcd, 0x04, 0xfa, 0x0f, 0x09, 0x92, 0x2a, 0x9d, 0xe7, 0x14, 0x5b, 0xb1, 0xa2, 0x5d, 0x58, 0xce, 0x16, 0x1c, 0x94, 0x7b, 0xf2, 0x4a, 0xea, 0xa7, 0x0f, 0xae, 0xa8, 0x76, 0x95, 0xaa, 0xb8, 0x0a, 0x33, 0xf4, 0xe8, 0xef, 0xc4, 0x52, 0xb9, 0xc5, 0x79, 0x6f, 0x4e, 0x48, 0xf2, 0xb6, 0xa2, 0x0d, 0x68, 0x27, 0x1f, 0x3e, 0x54, 0x2e, 0x85, 0x10, 0x64, 0xcd, 0xd2, 0x17, 0x99, 0xd4, 0x1a, 0x9f, 0x41, 0xef, 0x82, 0x40, 0x15, 0xb5, 0x7e, 0x9d, 0x1d, 0x32, 0xa9, 0x11, 0xdd, 0x0a, 0x67, 0x33, 0x9e, 0x69, 0xef, 0x06, 0x9e, 0xf3, 0xa7, 0x41, 0x87, 0x9d, 0x09, 0x72, 0xaa, 0x92, 0x8c, 0xaa, 0x27, 0x3f, 0x58, 0x60, 0x96, 0x60, 0x4b, 0xd1, 0xfb, 0x2b, 0xc6, 0x42, 0x00, 0x9d, 0x46, 0x8a, 0xab, 0x88, 0x88, 0xd3, 0xe8, 0x27, 0x24, 0xcd, 0xcb, 0x1d, 0x37, 0x79, 0xf0, 0xfa, 0x92, 0xf1, 0xca, 0xe2, 0xbd, 0x7b, 0x7f, 0x16, 0xf1, 0xa6, 0x20, 0xe0, 0xb7, 0x33, 0xee, 0x22, 0xf0, 0x07, 0x7a, 0xf2, 0xb4, 0x87, 0x41, 0x8f, 0x81, 0xe2, 0x3d, 0x67, 0xcd, 0xe1, 0xe4, 0x49, 0x12, 0x81, 0xc0, 0x6b, 0x6a, 0xe9, 0x1f, 0x99, 0x5d, 0xb3, 0x32, 0xf0, 0x05, 0x8f, 0x61, 0xc8, 0xf7, 0x10, 0x9e, 0xe8, 0x31, 0xcb, 0x93, 0x9f, 0x91, 0x5e, 0xbc, 0x07, 0xa3, 0xec, 0x6d, 0x5a, 0x84, 0x61, 0xd5, 0xb2, 0x1e, 0x4f, 0x1c, 0x9b, 0xc4, 0x20, 0x5e, 0x4e, 0x7b, 0x41, 0x47, 0x5a, 0xbe, 0x4a, 0xad, 0x62, 0x2c, 0xae, 0xcc, 0x1d, 0x26, 0xc2, 0x99, 0x9b, 0x93, 0x70, 0xfc, 0x53, 0xc5, 0x6f, 0x51, 0x27, 0x6b, 0xa6, 0x02, 0xd8, 0xd3, 0xa3, 0x07, 0x23, 0x92, 0xea, 0xfa, 0x76, 0x0b, 0xd5, 0xe4, 0x68, 0x2d, 0xac, 0xbc, 0x0f, 0x9b, 0x05, 0x8b, 0x52, 0xf0, 0x96, 0x09, 0xf3, 0x10, 0xa8, 0xef, 0x4c, 0xcd, 0x89, 0x6f, 0xb0, 0xaf, 0xfb, 0xe1, 0xde, 0x5e, 0xc0, 0x1c, 0x3a, 0x02, 0x13, 0x11, 0xde, 0x83, 0xce, 0xa5, 0x52, 0xcf, 0x7e, 0x32, 0x77, 0xae, 0x8f, 0xfe, 0x41, 0xe1, 0xab, 0x3f, 0x7c, 0x9c, 0x25, 0xf6, 0xb3, 0xb2, 0xc4, 0x1a, 0x10, 0x2f, 0x1c, 0x78, 0x9d, 0xd5, 0xb3, 0xbc, 0x2e, 0x3a, 0xbb, 0x17, 0x34, 0xbd, 0x95, 0x1f, 0x66, 0xe1, 0xa2, 0xe5, 0x51, 0x89, 0xd1, 0xdb, 0x13, 0xa6, 0x75, 0x03, 0xdb, 0x18, 0xa4, 0xb2, 0x8e, 0xa5, 0x5e, 0x54, 0xd9, 0x95, 0x21, 0x0b, 0x61, 0x59, 0x05, 0xdb, 0xb7, 0x6c, 0x27, 0x9c, 0xa2, 0xea, 0x92, 0x7d, 0x08, 0xa5, 0xec, 0xb0, 0xc4, 0xcd, 0x86, 0x2d, 0x6f, 0x64, 0x63, 0xfe, 0x25, 0x88, 0x08, 0x1e, 0x4c, 0xda, 0x68, 0x37, 0x7d, 0x7f, 0xb5, 0x40, 0x98, 0x35, 0xc7, 0x92, 0xae, 0x97, 0xee, 0xc3, 0x29, 0x74, 0xc0, 0xd4, 0x28, 0x89, 0x80, 0x7b, 0x12, 0xa8, 0x85, 0x99, 0xb6, 0xf6, 0x2d, 0xb5, 0x4f, 0x7a, 0xc9, 0xe2, 0xc5, 0xe7, 0x04, 0xf7, 0xe0, 0x9c, 0xab, 0x54, 0x2f, 0x4d, 0x8f, 0xa1, 0xe4, 0x5e, 0xe7, 0x2c, 0xfd, 0x7c, 0x47, 0xef, 0xef, 0xd5, 0x1c, 0xa8, 0x26, 0xbf, 0x49, 0x02, 0x54, 0x7b, 0xce, 0x5d, 0x59, 0x05, 0x8f, 0x40, 0x41, 0x10, 0x01, 0x6c, 0x0a, 0xee, 0x60, 0xb4, 0x86, 0x7e, 0x5b, 0x88, 0x67, 0xba, 0xae, 0x5d, 0xfa, 0xdc, 0x86, 0x78, 0x99, 0x09, 0x69, 0x75, 0xda, 0xb1, 0x2f, 0x28, 0x36, 0xab, 0xc1, 0xe7, 0x41, 0xcf, 0x87, 0x52, 0x2a, 0x01, 0xb6, 0x23, 0xbb, 0x75, 0xd2, 0x8a, 0x99, 0xa0, 0x5f, 0x59, 0x4b, 0xf3, 0x64, 0xc8, 0x7f, 0xc4, 0x18, 0x9a, 0x31, 0xf1, 0x6f, 0x1f, 0x51, 0xf7, 0xf5, 0x84, 0xb4, 0xdb, 0xe8, 0x81, 0x4a, 0x1b, 0x6a, 0xaf, 0x29, 0xca, 0x8d, 0x64, 0x48, 0xc3, 0x64, 0x59, 0x5d, 0x13, 0xd2, 0xc6, 0xfe, 0x99, 0x15, 0x45, 0x8e, 0x9c, 0x51, 0x1d, 0x8c, 0xa1, 0x51, 0x0a, 0xf3, 0x91, 0x17, 0x8b, 0xba, 0x0d, 0xfd, 0xf4, 0xe9, 0x92, 0x06, 0x53, 0xea, 0xe8, 0x82, 0x79, 0x19, 0x4d, 0x3d, 0x29, 0x93, 0xb2, 0xce, 0xa8, 0xeb, 0x6f, 0xc7, 0xa8, 0xc4, 0xf6, 0x6e, 0x32, 0xa4, 0x1e, 0x90, 0x64, 0x9c, 0xb9, 0xcf, 0x4c, 0xd2, 0x3f, 0x63, 0x1a, 0x52, 0xff, 0x16, 0x62, 0xeb, 0x0f, 0x1b, 0x8a, 0xb3, 0x20, 0x38, 0x6b, 0x86, 0x81, 0xc2, 0xd2, 0x0f, 0xbf, 0xfd, 0xa3, 0xba, 0xd4, 0x39, 0x52, 0x8a, 0xab, 0xdd, 0x87, 0xba, 0x68, 0xf2, 0x58, 0xed, 0xc2, 0x3b, 0x68, 0x46, 0x60, 0xe5, 0x57, 0xdb, 0x35, 0xa5, 0x43, 0xaf, 0x30, 0x10, 0x36, 0x01, 0xf8, 0x47, 0x12, 0xb3, 0x05, 0x5b, 0xf0, 0x51, 0xb7, 0xec, 0x23, 0x30, 0x17, 0x13, 0xd3, 0xbd, 0xa3, 0xe1, 0x0b, 0x28, 0x88, 0x8d, 0x5e, 0x3c, 0xd8, 0x24, 0x25, 0x20, 0x22, 0x93, 0x8c, 0xa5, 0x09, 0x3e, 0xd4, 0x0e, 0xe0, 0x10, 0x67, 0x92, 0x0c, 0xd6, 0x6a, 0x8a, 0x92, 0x58, 0xce, 0x2d, 0x9f, 0xf5, 0x2f, 0xa2, 0x0c, 0x4c, 0x94, 0x63, 0xcc, 0x70, 0xea, 0x1b, 0x5c, 0x6b, 0x57, 0x2f, 0x62, 0x0d, 0xc3, 0x67, 0xdf, 0xcf, 0x02, 0x7c, 0x9b, 0x16, 0x61, 0x30, 0x35, 0xc9, 0xf6, 0xc6, 0xd2, 0xfb, 0xc4, 0x02, 0xb1, 0x13, 0xc0, 0x6d, 0x16, 0x30, 0xdf, 0x85, 0xbf, 0x23, 0xaf, 0xbc, 0xa8, 0x69, 0x03, 0x70, 0x22, 0x03, 0x6e, 0x3a, 0x3e, 0x76, 0x81, 0x78, 0x91, 0x9c, 0x73, 0x88, 0xf4, 0x81, 0xff, 0x34, 0x92, 0xaf, 0x63, 0xea, 0xe8, 0x01, 0x8b, 0xe0, 0x7a, 0x22, 0x73, 0xa2, 0x64, 0xfc, 0xc0, 0xc9, 0x89, 0x26, 0x03, 0xe3, 0x58, 0x4c, 0x0c, 0x7d, 0x83, 0x18, 0x7b, 0x53, 0xc4, 0xcc, 0x23, 0x99, 0xf8, 0x0e, 0x2f, 0x7f, 0x08, 0x19, 0x1a, 0x63, 0x5d, 0xde, 0x06, 0x2b, 0x40, 0xad, 0x09, 0x8e, 0xd4, 0xf8, 0xf6, 0xce, 0x75, 0xcd, 0x71, 0xa0, 0xc6, 0x91, 0x1b, 0xab, 0x6e, 0x0e, 0x89, 0xc8, 0x10, 0x5b, 0xbc, 0xc6, 0xa4, 0xae, 0x66, 0xc9, 0xca, 0x58, 0x63, 0x0a, 0x48, 0x20, 0x86, 0x7c, 0x91, 0x21, 0x77, 0x6d, 0x8e, 0x2d, 0x23, 0xe1, 0x6c, 0xb7, 0x6a, 0xa3, 0xb5, 0xa2, 0xbf, 0x04, 0xe3, 0x21, 0x18, 0x64, 0x2a, 0x2e, 0x4d, 0xad, 0xb7, 0x11, 0xa2, 0x05, 0xdd, 0x16, 0x29, 0xd1, 0x48, 0x88, 0x85, 0x77, 0xbe, 0xca, 0xef, 0xf6, 0xa0, 0xd6, 0xfb, 0x09, 0x7e, 0x18, 0x6d, 0x53, 0xcd, 0x49, 0x02, 0x37, 0x14, 0x5e, 0x13, 0xc7, 0x50, 0xc2, 0x3d, 0x6e, 0xb4, 0xb0, 0xdc, 0x5a, 0x56, 0xf3, 0x9c, 0xa3, 0xbb, 0x8f, 0x34, 0xcf, 0xc1, 0x24, 0xd4, 0x22, 0xbb, 0x7b, 0xd4, 0x2b, 0xef, 0x6a, 0x60, 0xaa, 0x78, 0x99, 0x95, 0x04, 0x2b, 0xfd, 0x02, 0xb7, 0xc3, 0xa2, 0xc8, 0x35, 0xd4, 0x18, 0x02, 0xc6, 0x2d, 0xc1, 0x88, 0xc3, 0xa7, 0xd1, 0x59, 0x96, 0x57, 0x43, 0xfb, 0x98, 0x9f, 0x7b, 0xa3, 0x7b, 0xa0, 0x75, 0x92, 0xf1, 0x35, 0xaf, 0xe3, 0xdd, 0x38, 0x38, 0x79, 0xfc, 0xf5, 0xe0, 0x83, 0x1d, 0x5e, 0x28, 0xf8, 0x50, 0xdf, 0xfa, 0x9f, 0xb5, 0x5c, 0x75, 0xd8, 0x70, 0x01, 0x7c, 0xdd, 0x75, 0x68, 0xd0, 0x64, 0xb9, 0xc2, 0xfc, 0x5a, 0xe7, 0x48, 0x41, 0xca, 0xb6, 0xb6, 0x5d, 0x79, 0x29, 0xbc, 0xb1, 0xac, 0xe1, 0xd4, 0x98, 0x42, 0x65, 0x73, 0x7f, 0x0f, 0x5b, 0xc5, 0x7d, 0xa9, 0xce, 0xef, 0x79, 0xef, 0xdb, 0x5d, 0x06, 0xbe, 0xf9, 0xb1, 0xbc, 0x30, 0x13, 0x9c, 0x25, 0x22, 0xfd, 0xbc, 0x97, 0x16, 0xc2, 0x69, 0xec, 0xad, 0x67, 0xd7, 0xf3, 0x68, 0x74, 0x3b, 0x5b, 0xc9, 0xb9, 0x79, 0xb1, 0x65, 0xb8, 0xbb, 0xcc, 0xbd, 0x4b, 0xf0, 0x77, 0x5a, 0x62, 0xb3, 0x8d, 0x23, 0xeb, 0x8c, 0xdf, 0xec, 0xea, 0x88, 0x2a, 0xe0, 0xae, 0xfe, 0xc9, 0x44, 0xe1, 0xa6, 0x12, 0x11, 0x43, 0xf9, 0x34, 0x89, 0x4c, 0xe0, 0x79, 0x1a, 0x99, 0x11, 0x81, 0x89, 0x18, 0x08, 0xcb, 0xe8, 0x1a, 0x9d, 0x03, 0x31, 0x4d, 0x44, 0xa4, 0x68, 0x60, 0x1a, 0x86, 0x44, 0x7c, 0xaa, 0x0e, 0x75, 0x19, 0x20, 0x83, 0xa7, 0x6c, 0xd1, 0x12, 0x74, 0x0e, 0x98, 0xe5, 0x62, 0xd5, 0xd6, 0x7a, 0x9e, 0x6d, 0x81, 0x67, 0x25, 0xe0, 0x20, 0x72, 0x69, 0x2b, 0x24, 0x51, 0x8c, 0xdc, 0x16, 0x73, 0x28, 0x50, 0x46, 0x85, 0x81, 0xbc, 0x89, 0xec, 0x21, 0x3d, 0x58, 0xad, 0xc8, 0x88, 0xce, 0x90, 0xd7, 0x5d, 0xba, 0xbf, 0x03, 0xdd, 0xcf, 0x78, 0x35, 0xb0, 0x51, 0x89, 0xa4, 0x6f, 0x44, 0xd4, 0x6d, 0xcc, 0x2f, 0x72, 0x2a, 0x1a, 0x9c, 0x69, 0x20, 0xfa, 0x9e, 0x3f, 0x4e, 0x58, 0xe2, 0x77, 0x1a, 0xf1, 0x3a, 0xfa, 0xc7, 0xd0, 0x6f, 0x08, 0xf7, 0xf8, 0xe9, 0x66, 0xb4, 0x5f, 0xe4, 0x73, 0x05, 0x07, 0x82, 0xc2, 0x98, 0x46, 0x36, 0x87, 0x5a, 0xc3, 0x5c, 0x2c, 0xe4, 0x9f, 0xa4, 0x3f, 0x80, 0xee, 0xa7, 0x79, 0xea, 0xca, 0x24, 0xf5, 0xff, 0x89, 0x40, 0x2e, 0x71, 0x4d, 0x24, 0x3a, 0xcd, 0x21, 0xb0, 0xde, 0x90, 0xe4, 0x03, 0x8a, 0x9f, 0x94, 0x82, 0xae, 0x40, 0x33, 0x67, 0x60, 0x19, 0x36, 0xbc, 0x7f, 0xc6, 0x0e, 0x7b, 0x60, 0x3f, 0x77, 0x02, 0x90, 0x40, 0xad, 0xc4, 0xe9, 0x9c, 0x54, 0x32, 0x7d, 0xdd, 0x75, 0xe0, 0xa3, 0xcb, 0x15, 0xbc, 0xf2, 0x2a, 0x06, 0x9a, 0xf5, 0x59, 0xfc, 0xe2, 0xe1, 0xcb, 0xbf, 0xfd, 0xfb, 0x7f, 0xec, 0xe1, 0x1d, 0x50, 0x22, 0x17, 0x44, 0x2f, 0x57, 0xea, 0x14, 0xb9, 0x48, 0xc8, 0xb6, 0x80, 0xfe, 0x02, 0xbf, 0xf2, 0x91, 0xff, 0x01, 0xd3, 0xec, 0x56, 0x0b, 0x1e, 0x66, 0xf1, 0xe5, 0xc6, 0x75, 0x27, 0x68, 0x7a, 0x77, 0x46, 0xb8, 0x4b, 0xaa, 0x9d, 0x99, 0x24, 0xdb, 0xe3, 0x25, 0xa0, 0x38, 0xbf, 0x13, 0xc3, 0xa1, 0xd5, 0x18, 0x62, 0xfd, 0x52, 0xd0, 0x7c, 0x63, 0x36, 0x26, 0x66, 0x6d, 0xfa, 0xcf, 0x70, 0x34, 0xc3, 0x2f, 0x04, 0x19, 0x6d, 0xcc, 0x40, 0xf5, 0xd6, 0x50, 0x66, 0xaa, 0x4f, 0x87, 0x03, 0xa1, 0x2a, 0x91, 0x7b, 0x93, 0x57, 0xa7, 0x83, 0x7f, 0x17, 0xbe, 0x62, 0xe4, 0x5f, 0x50, 0xee, 0x62, 0xdf, 0xf6, 0x95, 0x8e, 0x8b, 0x04, 0x12, 0x45, 0xb2, 0x98, 0x7a, 0x43, 0x09, 0x94, 0xc4, 0x5c, 0x88, 0x7b, 0x8d, 0x6d, 0x60, 0x59, 0x22, 0x80, 0x2f, 0x1c, 0x84, 0xa9, 0xbb, 0x29, 0x5a, 0x1a, 0xf8, 0x78, 0xd7, 0xb0, 0x6c, 0xcc, 0x53, 0x44, 0x24, 0x4f, 0xcf, 0x16, 0xf2, 0x51, 0xd1, 0x0f, 0x54, 0xe0, 0x40, 0x5b, 0x96, 0x13, 0x19, 0x32, 0xcd, 0x20, 0x04, 0x6c, 0xd7, 0x2f, 0xb1, 0xf2, 0xba, 0xc4, 0x29, 0x57, 0x1b, 0x47, 0x47, 0xa7, 0x26, 0x7d, 0x88, 0x22, 0x9a, 0x51, 0x54, 0x62, 0x9a, 0x0d, 0xff, 0x46, 0xda, 0xc6, 0x6a, 0x40, 0x61, 0x4b, 0x44, 0x71, 0xf5, 0x34, 0x71, 0x0b, 0x6f, 0x72, 0x7b, 0xbe, 0x73, 0x9f, 0x31, 0x4c, 0xf4, 0xa3, 0xcb, 0x57, 0x4b, 0x34, 0xb5, 0x83, 0xb6, 0x6f, 0x81, 0x75, 0x1c, 0xd7, 0x79, 0x13, 0x08, 0x2a, 0x74, 0xe5, 0x20, 0xc9, 0x45, 0x82, 0x5f, 0xe4, 0xa9, 0xeb, 0x2a, 0xc3, 0xda, 0x39, 0x87, 0x6d, 0x9e, 0x4d, 0x50, 0x9a, 0x98, 0x34, 0x79, 0xa7, 0xa9, 0xc8, 0x34, 0xa0, 0x02, 0x97, 0x7c, 0xec, 0x35, 0xc7, 0x65, 0x42, 0x87, 0xc0, 0xd0, 0xd9, 0x72, 0xb6, 0x26, 0xcd, 0xa9, 0xc5, 0xcb, 0x9c, 0xb2, 0xe4, 0x51, 0x49, 0xe0, 0xf3, 0x51, 0x5e, 0x1f, 0xff, 0x26, 0x15, 0x19, 0x66, 0x99, 0x8a, 0x42, 0xa9, 0xe1, 0x65, 0x6c, 0xbd, 0x97, 0xdb, 0x7c, 0x81, 0x3d, 0x8e, 0xb7, 0xb2, 0xfa, 0x89, 0xa4, 0xf8, 0xd3, 0xb0, 0x1d, 0x7f, 0xba, 0x66, 0xd3, 0x15, 0xe9, 0xbc, 0x01, 0x68, 0xdf, 0x05, 0xa5, 0xf7, 0x40, 0xbb, 0x56, 0x8b, 0x96, 0xee, 0x4e, 0xe0, 0x75, 0xf6, 0x9c, 0x07, 0xd0, 0x32, 0x3d, 0xea, 0x55, 0x29, 0xa0, 0x73, 0x2e, 0xd0, 0xed, 0x08, 0x31, 0xe6, 0x44, 0x94, 0x67, 0x50, 0x58, 0x2f, 0x20, 0xf8, 0x1f, 0x50, 0xd8, 0x89, 0x9c, 0x79, 0x81, 0x11, 0xab, 0x34, 0xf9, 0x60, 0x53, 0x3a, 0x30, 0xe9, 0x9b, 0x99, 0xc4, 0xf2, 0x1c, 0x99, 0x91, 0xe8, 0x99, 0x26, 0x25, 0x9f, 0xd0, 0x82, 0xd9, 0x8f, 0x89, 0x83, 0xd9, 0x78, 0xd0, 0xea, 0x69, 0xdf, 0x6e, 0x50, 0x6c, 0xc8, 0xa2, 0x0c, 0xc4, 0x14, 0xad, 0x2e, 0x42, 0xb8, 0xda, 0xab, 0xbe, 0x9a, 0x29, 0x31, 0x7c, 0x5d, 0xcc, 0xe9, 0xc0, 0x99, 0x3c, 0x14, 0xb1, 0xd8, 0x4d, 0x93, 0x2c, 0x13, 0xc9, 0xb2, 0xdc, 0x8e, 0xac, 0xef, 0x79, 0xc5, 0x0e, 0xf7, 0x2f, 0x0f, 0xc7, 0x84, 0x97, 0x44, 0xf0, 0x6c, 0x9e, 0x6d, 0x70, 0xed, 0xa7, 0x87, 0xfc, 0x5f, 0x66, 0x93, 0x6c, 0x62, 0x79, 0x43, 0x7b, 0xfc, 0xc9, 0x3e, 0x76, 0x29, 0xb2, 0x44, 0x9b, 0xc3, 0x4f, 0x0d, 0x46, 0x66, 0x66, 0x3b, 0x8b, 0x5b, 0xca, 0xf1, 0x6c, 0xa0, 0xa8, 0x6b, 0x8d, 0x8f, 0x7c, 0xe7, 0x73, 0x9e, 0x77, 0x9c, 0xfc, 0xe5, 0x2b, 0xf8, 0x53, 0x57, 0x15, 0xa7, 0x7d, 0xc6, 0x60, 0x12, 0xea, 0x78, 0x9e, 0xed, 0xe2, 0xef, 0xb3, 0x7b, 0x37, 0x7c, 0xe5, 0x97, 0x11, 0x10, 0x7a, 0x9b, 0xfd, 0x15, 0xe6, 0xa4, 0x16, 0x6a, 0x1f, 0x62, 0x35, 0xba, 0xba, 0xb2, 0x28, 0x67, 0x41, 0x2a, 0xf7, 0xa7, 0x65, 0xdd, 0x62, 0xea, 0x4d, 0xad, 0x10, 0xd2, 0x85, 0x27, 0xdf, 0x95, 0xe8, 0x81, 0x0a, 0x32, 0x9a, 0x04, 0x73, 0x61, 0xd4, 0x2d, 0x20, 0xd9, 0x7d, 0xf7, 0xbf, 0xbb, 0x6f, 0xa1, 0x6a, 0x05, 0xbb, 0x6e, 0xa0, 0xaf, 0x3a, 0x11, 0x6e, 0xdb, 0x91, 0xfe, 0xf8, 0x70, 0xac, 0x43, 0xfe, 0x42, 0x28, 0x71, 0xdd, 0x75, 0xa4, 0xc6, 0x70, 0x36, 0x72, 0x44, 0x6e, 0x00, 0xce, 0xbc, 0xbb, 0x1b, 0xe3, 0x9b, 0x2d, 0xe3, 0x9f, 0x37, 0x42, 0x36, 0x78, 0xe6, 0xb7, 0x4b, 0xc2, 0x58, 0xec, 0x6e, 0xc7, 0xb1, 0x8c, 0x96, 0x35, 0x0d, 0x87, 0x6b, 0x89, 0xee, 0x80, 0x38, 0x70, 0x29, 0x11, 0x11, 0x29, 0x72, 0x22, 0x25, 0x71, 0x26, 0xd6, 0x63, 0xbb, 0xc8, 0x89, 0xb9, 0x4c, 0x5e, 0x13, 0x80, 0xb3, 0x8d, 0x48, 0xa1, 0xd3, 0x64, 0x81, 0x1b, 0x39, 0x6e, 0x09, 0x10, 0x5e, 0x95, 0x19, 0x77, 0xc1, 0x1a, 0x99, 0xd7, 0xb0, 0x16, 0xd2, 0xb5, 0x41, 0xdd, 0x14, 0xac, 0x24, 0xaa, 0xb7, 0xda, 0x55, 0xac, 0xbe, 0xab, 0x58, 0x2d, 0x30, 0xfd, 0x66, 0x3b, 0xc4, 0xcf, 0x10, 0x17, 0x8a, 0xf1, 0x6a, 0xf1, 0xae, 0xa7, 0xcb, 0x24, 0x28, 0x86, 0xf0, 0x13, 0xc2, 0xe5, 0x24, 0xec, 0x28, 0x1d, 0xd6, 0xc5, 0xca, 0x19, 0x8a, 0x77, 0x11, 0x1c, 0x2e, 0x76, 0x95, 0x6e, 0xbf, 0x83, 0x2f, 0x25, 0x4f, 0x60, 0xdb, 0xa9, 0xd8, 0x2a, 0xb5, 0x5a, 0x88, 0xc2, 0x67, 0x63, 0xde, 0xd5, 0x4e, 0x04, 0x1d, 0x52, 0xa7, 0xba, 0x31, 0x2f, 0x77, 0x75, 0xfa, 0xf9, 0x7f, 0xea, 0x44, 0xe7, 0x91, 0xd5, 0x76, 0x27, 0xa7, 0xf5, 0x3e, 0x91, 0x52, 0x91, 0x05, 0x9b, 0x78, 0xab, 0xf8, 0xfa, 0x4f, 0x99, 0xf3, 0x24, 0xea, 0x4b, 0x51, 0x27, 0xc7, 0x3b, 0x8f, 0x24, 0xe2, 0xe2, 0x31, 0xcf, 0xec, 0xac, 0x8d, 0x75, 0x0b, 0x3e, 0x8f, 0xb4, 0x7f, 0x76, 0xc0, 0xaf, 0x6f, 0x1e, 0xab, 0xc2, 0x99, 0xc4, 0x1c, 0x17, 0x72, 0x4c, 0xb4, 0x05, 0x1d, 0x38, 0xb1, 0xb4, 0x79, 0xc0, 0x08, 0x19, 0x93, 0x80, 0x93, 0xcb, 0x28, 0x93, 0x87, 0x0e, 0x63, 0x5f, 0x99, 0x59, 0x5e, 0xb4, 0x1e, 0x26, 0x6f, 0x85, 0x38, 0x9c, 0x39, 0xb9, 0x46, 0x04, 0x23, 0xc1, 0xff, 0x2f, 0xbc, 0xd4, 0xab, 0x6e, 0x14, 0xf7, 0x4e, 0xcf, 0xc0, 0xe1, 0x5d, 0xf1, 0xd5, 0x82, 0x91, 0x5e, 0x0d, 0xa6, 0xda, 0x31, 0xa2, 0xb0, 0x20, 0xdc, 0x75, 0x6f, 0x47, 0xf0, 0x86, 0xa5, 0xef, 0x63, 0xf6, 0xbd, 0x2f, 0x7d, 0xeb, 0x1d, 0x1f, 0xfa, 0xb3, 0xe1, 0x08, 0x7f, 0xfe, 0x6b, 0xdd, 0x16, 0x61, 0xa2, 0xae, 0xa7, 0x4e, 0xe2, 0x39, 0x96, 0x64, 0x88, 0xaf, 0x7e, 0xe0, 0xfb, 0xc5, 0x0e, 0x85, 0xb4, 0xe5, 0x7e, 0x40, 0x54, 0x0a, 0x2a, 0x4a, 0xbc, 0xae, 0xa5, 0xb4, 0x4e, 0x2c, 0xb5, 0x27, 0xc6, 0x12, 0xcb, 0x49, 0x3d, 0xc1, 0x08, 0xc9, 0xa8, 0xd0, 0x49, 0x6d, 0x92, 0xc2, 0xdf, 0x10, 0xc0, 0xfc, 0x61, 0xd6, 0x1c, 0x00, 0x90, 0xfd, 0xec, 0x1b, 0xc8, 0x71, 0xf8, 0xce, 0x4b, 0x0c, 0x1f, 0xf6, 0x68, 0x31, 0x29, 0x9e, 0x9c, 0xf9, 0xcf, 0xa3, 0x19, 0xbe, 0x6d, 0xa9, 0x77, 0xef, 0x91, 0x59, 0x92, 0x42, 0x3f, 0x3e, 0x7e, 0x3a, 0xf0, 0xed, 0xcf, 0xff, 0x4b, 0x0e, 0xf3, 0x34, 0x3a, 0xaf, 0xab, 0x61, 0x1e, 0x60, 0xa6, 0x93, 0x0a, 0x27, 0xd0, 0x7e, 0x6c, 0x99, 0xe1, 0x60, 0x2a, 0xcb, 0xf0, 0x74, 0x43, 0xfb, 0x5c, 0x41, 0x36, 0xc9, 0x96, 0x02, 0x27, 0xc6, 0x18, 0x8c, 0x58, 0xc7, 0x7b, 0x9e, 0xfd, 0xaf, 0x5a, 0x06, 0x3e, 0x67, 0x5d, 0x2a, 0xe5, 0x9e, 0x8b, 0xb5, 0x66, 0x94, 0x72, 0x25, 0xef, 0xc5, 0xb0, 0x7c, 0xbb, 0x15, 0xa2, 0x6a, 0x3d, 0xd8, 0x9e, 0x43, 0x85, 0xe0, 0x85, 0x33, 0x31, 0xeb, 0x8c, 0xff, 0x6e, 0x39, 0x44, 0x09, 0x7f, 0xea, 0x29, 0x45, 0x48, 0x99, 0x97, 0xf6, 0xe3, 0x34, 0xa6, 0x18, 0xa1, 0x15, 0x56, 0xdb, 0x80, 0x8e, 0xf7, 0x56, 0xaf, 0x61, 0xbc, 0x42, 0x47, 0xab, 0xb3, 0x34, 0x0e, 0x63, 0xc4, 0xc1, 0x6c, 0xb0, 0x2c, 0x12, 0x43, 0x2e, 0x7a, 0x8e, 0xfd, 0x74, 0x94, 0x38, 0xcb, 0xf1, 0x48, 0xf5, 0x34, 0x49, 0x9e, 0x48, 0x3e, 0xfd, 0xfa, 0x2f, 0xd6, 0xf2, 0x41, 0x06, 0x5a, 0xf0, 0xfb, 0x17, 0x24, 0xbe, 0x78, 0x9e, 0x55, 0x86, 0xb1, 0x2a, 0x88, 0x22, 0xcc, 0x2b, 0x23, 0x5c, 0xf4, 0xc8, 0xd7, 0x79, 0xe8, 0x11, 0xd6, 0x1c, 0x1a, 0x62, 0x8b, 0x01, 0x5b, 0x58, 0x1f, 0x88, 0xc8, 0x4c, 0xd5, 0x11, 0xc3, 0x91, 0xf5, 0xe7, 0xf5, 0x21, 0x1e, 0x8c, 0x05, 0x79, 0x0c, 0xbc, 0x6d, 0x40, 0x6e, 0x8d, 0xd2, 0x74, 0x78, 0x22, 0x8b, 0x08, 0x21, 0x94, 0xaa, 0xb0, 0xbd, 0x34, 0xab, 0x35, 0x70, 0x9f, 0x60, 0x38, 0x4c, 0x78, 0x26, 0x8a, 0x3c, 0x8b, 0xcf, 0x91, 0xd5, 0xe5, 0x19, 0x5d, 0x16, 0x01, 0xae, 0x42, 0xf2, 0x3e, 0xc6, 0x9d, 0x59, 0x5c, 0x66, 0xaa, 0x8f, 0xc5, 0x71, 0xdc, 0xa2, 0x8b, 0x18, 0x6d, 0xb1, 0x5c, 0x19, 0xc4, 0xa4, 0x03, 0x09, 0x23, 0x3d, 0x32, 0x13, 0x09, 0xc9, 0x7f, 0xb7, 0xb7, 0xb7, 0x3e, 0xf5, 0x1d, 0x70, 0xde, 0xd5, 0xdc, 0x62, 0x7a, 0x33, 0x65, 0x33, 0x8a, 0x4e, 0xc5, 0x36, 0x14, 0xd8, 0x6b, 0xb8, 0x93, 0x12, 0x0b, 0x2f, 0x7f, 0x7c, 0xc7, 0x36, 0x23, 0xcb, 0x30, 0x91, 0x42, 0x0f, 0x0b, 0x0b, 0x4d, 0xf5, 0x4b, 0xb7, 0x34, 0x01, 0xdc, 0x28, 0xb0, 0x1c, 0x21, 0x87, 0xca, 0x46, 0xa2, 0xf1, 0x3e, 0xa6, 0x1e, 0xbb, 0x03, 0x6b, 0xfc, 0x20, 0xac, 0x8e, 0x65, 0xc8, 0xdc, 0x17, 0x5e, 0x10, 0x2c, 0xfb, 0x03, 0xbc, 0x2f, 0xfe, 0xd0, 0x57, 0x8a, 0x13, 0xd3, 0x21, 0x8a, 0xec, 0x7b, 0x69, 0xcb, 0x6f, 0xf9, 0xc2, 0xa8, 0x08, 0x45, 0x5b, 0x26, 0xb3, 0x32, 0x39, 0xe0, 0x8d, 0xc2, 0xe0, 0x18, 0xb5, 0x2e, 0x0c, 0x67, 0x4a, 0x32, 0xe7, 0xf2, 0x6a, 0x38, 0xc3, 0x6c, 0x59, 0x0b, 0xd5, 0x88, 0x9c, 0xc8, 0x37, 0x73, 0x14, 0xd6, 0x4d, 0xee, 0xe8, 0xaf, 0xf6, 0xb6, 0xe0, 0x9e, 0x26, 0xe4, 0x21, 0xcf, 0x82, 0x44, 0xcd, 0xb6, 0xaa, 0x3b, 0x17, 0x6e, 0x29, 0xe8, 0xb5, 0xa3, 0xc0, 0xa0, 0x25, 0x39, 0x1b, 0xb8, 0x38, 0x97, 0x41, 0xc1, 0xec, 0xd7, 0x05, 0x40, 0xfc, 0xf8, 0xa2, 0xee, 0xd0, 0xd9, 0xb7, 0x5d, 0x17, 0xce, 0x33, 0xf6, 0xa0, 0xe5, 0xbf, 0xce, 0x7a, 0xc8, 0xde, 0xe2, 0x2c, 0x06, 0xe9, 0xe7, 0x2f, 0x78, 0x56, 0x81, 0x5e, 0x11, 0x6e, 0x47, 0xc4, 0xc5, 0x8e, 0xff, 0xa2, 0x78, 0xe8, 0xfc, 0xb5, 0x81, 0x79, 0x8e, 0xdf, 0x7c, 0x1b, 0xa9, 0xa4, 0xb9, 0xb9, 0x17, 0xed, 0x01, 0x0d, 0xf8, 0x33, 0x6d, 0xdc, 0x16, 0x83, 0xc5, 0x6d, 0x7b, 0x3e, 0xe0, 0x1e, 0xe0, 0x99, 0x8f, 0xad, 0x76, 0xa2, 0xfd, 0x91, 0x79, 0xba, 0x89, 0x03, 0xae, 0x91, 0x13, 0xd1, 0xf6, 0x73, 0x60, 0xb9, 0x7a, 0x4c, 0x7a, 0x24, 0xb5, 0xb4, 0xb6, 0x85, 0x08, 0xa3, 0x7c, 0xd6, 0x5b, 0x65, 0x80, 0xbf, 0x7b, 0x27, 0x93, 0x34, 0x47, 0xf5, 0x01, 0x4d, 0x42, 0x0d, 0x49, 0x2d, 0xc7, 0xa1, 0x3c, 0xa1, 0x90, 0x1d, 0x2e, 0x8f, 0x8b, 0x15, 0x66, 0xc0, 0x62, 0xda, 0x6b, 0x54, 0x5c, 0x67, 0x7d, 0xa6, 0x32, 0xfb, 0x66, 0xd3, 0xc5, 0x41, 0xf8, 0xf2, 0x53, 0xc0, 0xbe, 0x05, 0x64, 0xd3, 0x1e, 0x63, 0x22, 0x1f, 0xfb, 0xcc, 0xb5, 0xb8, 0x7b, 0x13, 0xf8, 0x72, 0xf5, 0x26, 0x70, 0x71, 0xf9, 0x7f, 0x11, 0x97, 0xff, 0x55, 0x0b, 0xff, 0xcb, 0x62, 0xe1, 0xdf, 0xb0, 0xe4, 0xbf, 0xdc, 0xb1, 0xe4, 0xaf, 0x5b, 0xec, 0x5f, 0xbe, 0xdb, 0x62, 0xdf, 0xbb, 0xcc, 0xbf, 0x7c, 0x9f, 0x65, 0x7e, 0xcd, 0x02, 0xff, 0xb2, 0x58, 0xe0, 0x97, 0x97, 0xf6, 0x2c, 0x4c, 0x7f, 0xf6, 0xbc, 0xbe, 0xaa, 0xbf, 0x9c, 0xad, 0xea, 0xab, 0xd7, 0xf3, 0x17, 0x69, 0x3d, 0xdf, 0xb6, 0x92, 0xbf, 0x5c, 0x5c, 0xc9, 0x4b, 0x7b, 0xc3, 0x4f, 0xa0, 0x4d, 0xd1, 0xe0, 0xf0, 0x5a, 0xa4, 0xf9, 0x9d, 0x5c, 0xe9, 0x10, 0x70, 0xb7, 0x78, 0x4b, 0xbe, 0x96, 0x49, 0x6e, 0x36, 0x3f, 0x81, 0x85, 0xe6, 0xf5, 0xc1, 0x0d, 0x0b, 0xec, 0x21, 0x55, 0x26, 0x88, 0x06, 0x7d, 0x44, 0x6a, 0x9e, 0x31, 0x0d, 0xa0, 0x28, 0x39, 0x63, 0x08, 0xdd, 0x2f, 0xfa, 0x87, 0x88, 0xcf, 0xa5, 0xd5, 0x3a, 0x63, 0x22, 0x15, 0x3c, 0x62, 0xb2, 0x96, 0xdf, 0xca, 0x7b, 0x92, 0x09, 0x88, 0x55, 0xa6, 0x8c, 0x69, 0x39, 0x65, 0x64, 0x5f, 0x6d, 0x26, 0x8f, 0xf9, 0xa0, 0x87, 0x2b, 0x8d, 0x1a, 0xaf, 0x5c, 0xbf, 0x9e, 0x29, 0x1b, 0xf5, 0x28, 0xb6, 0xf7, 0xb2, 0x92, 0x57, 0x9d, 0x57, 0xf3, 0xce, 0xba, 0x16, 0x18, 0x90, 0x06, 0xcf, 0x69, 0x83, 0x07, 0x13, 0xe7, 0x18, 0x03, 0x86, 0x06, 0x08, 0xde, 0x79, 0x7d, 0x78, 0x40, 0x4d, 0x53, 0x8b, 0x4c, 0xff, 0xb2, 0x66, 0xa8, 0xdc, 0x21, 0xdd, 0xa0, 0x25, 0xc3, 0x6d, 0xc5, 0x49, 0xf3, 0xa6, 0x02, 0xa8, 0xe2, 0x46, 0x4d, 0xef, 0x45, 0x9b, 0x01, 0x90, 0x99, 0xea, 0x7c, 0x83, 0xbf, 0xa9, 0xf3, 0xed, 0xae, 0x2e, 0xc0, 0x24, 0xd0, 0x14, 0x86, 0x4e, 0x96, 0x1c, 0x21, 0x63, 0xde, 0x1b, 0x72, 0xf0, 0xc7, 0x65, 0x88, 0x90, 0x51, 0xc1, 0x81, 0x03, 0x9a, 0xd5, 0xa8, 0x68, 0xf1, 0x41, 0x69, 0xb6, 0x3d, 0x58, 0x6b, 0xc2, 0x92, 0xbe, 0xe7, 0xc4, 0xee, 0x18, 0x91, 0xce, 0x72, 0x95, 0x77, 0xfa, 0x81, 0xc2, 0x79, 0x37, 0x4d, 0x13, 0x4a, 0x4c, 0x94, 0x07, 0x2f, 0x5a, 0x63, 0x85, 0x00, 0xe0, 0xdf, 0x3d, 0x1c, 0x6d, 0x19, 0x76, 0x27, 0xad, 0xde, 0x37, 0xa5, 0x0d, 0x24, 0x66, 0x05, 0x48, 0x8e, 0xf9, 0x30, 0x2e, 0xd3, 0x5f, 0x2b, 0x34, 0xdb, 0x5d, 0xdd, 0xb2, 0xe5, 0x7b, 0xc4, 0x5f, 0xc8, 0xa1, 0xe5, 0x25, 0x7f, 0xcc, 0xb2, 0xf6, 0x70, 0x94, 0xd4, 0x2d, 0x1a, 0x2c, 0x08, 0x24, 0x41, 0xba, 0xdc, 0x86, 0x27, 0x60, 0x10, 0xfd, 0x37, 0xa1, 0xec, 0xcd, 0xf5, 0x1a, 0xb9, 0x42, 0xf8, 0x1f, 0x94, 0xaf, 0x5a, 0x7e, 0x1a, 0xba, 0x42, 0x99, 0x9d, 0x04, 0x7b, 0x80, 0xf6, 0x2b, 0x29, 0x78, 0x22, 0xe2, 0x99, 0x30, 0xd2, 0xb1, 0x6c, 0xb0, 0x58, 0xa9, 0x07, 0xc9, 0x79, 0xf4, 0x4f, 0x1d, 0xa2, 0x9e, 0x7c, 0xba, 0xf6, 0x89, 0xad, 0x40, 0x84, 0xd3, 0x88, 0x97, 0x96, 0x7b, 0x50, 0x4d, 0x58, 0x59, 0x74, 0xe3, 0xcd, 0xb3, 0x49, 0x17, 0xe3, 0x1c, 0x0a, 0x31, 0x46, 0x6c, 0x00, 0xad, 0x8a, 0x22, 0x0c, 0x02, 0xb3, 0xef, 0xe8, 0xf2, 0xd5, 0xce, 0xac, 0xeb, 0x2e, 0x10, 0x08, 0xa6, 0x07, 0xed, 0x46, 0x9e, 0x63, 0x81, 0xa6, 0x5e, 0x52, 0x15, 0x96, 0x3a, 0x7d, 0xc1, 0xa5, 0x28, 0x24, 0xcf, 0xb0, 0x36, 0xbd, 0x46, 0xe0, 0x5b, 0x91, 0x33, 0x36, 0x40, 0xfe, 0x53, 0xa3, 0xcd, 0xe0, 0x3f, 0x0b, 0x05, 0x09, 0x09, 0xab, 0x81, 0x10, 0xfa, 0xc0, 0xbf, 0x2b, 0x14, 0xd1, 0xdb, 0xed, 0x5c, 0xff, 0x5b, 0x83, 0x25, 0xa3, 0x20, 0x92, 0x6f, 0x4a, 0xa0, 0xa9, 0xf0, 0x81, 0xbb, 0x1f, 0x4c, 0xb4, 0x5c, 0x90, 0xa9, 0xa8, 0x57, 0x2d, 0x89, 0x91, 0x53, 0xd8, 0xf6, 0x60, 0x86, 0x04, 0x9a, 0x7c, 0x70, 0x61, 0xee, 0xa2, 0xe3, 0x22, 0xa7, 0xc5, 0xbe, 0x8d, 0x86, 0xf7, 0xb6, 0x3b, 0x64, 0xbc, 0x2d, 0x4c, 0x3b, 0xb5, 0x0a, 0xbb, 0xa7, 0x0a, 0x33, 0xcc, 0xc2, 0x31, 0xac, 0x41, 0xa5, 0x22, 0x96, 0xea, 0xd3, 0x76, 0x65, 0xb2, 0xac, 0xaa, 0xcc, 0xba, 0x40, 0x51, 0xde, 0xd3, 0xa5, 0x80, 0x8e, 0x07, 0xb5, 0x0e, 0x09, 0x6f, 0x99, 0x79, 0x3e, 0x1d, 0x7d, 0x7a, 0x23, 0x43, 0xe1, 0xc5, 0x96, 0xdb, 0x03, 0xf3, 0x92, 0x8c, 0x19, 0xe3, 0x8b, 0xf8, 0x35, 0xd0, 0x57, 0x83, 0xf0, 0xca, 0x31, 0xf0, 0xfe, 0xa1, 0x7d, 0x92, 0x46, 0x15, 0x27, 0xf6, 0xa7, 0x7e, 0xb0, 0x8d, 0x1c, 0x75, 0xb8, 0x96, 0x8a, 0x43, 0x09, 0x63, 0x29, 0x4a, 0xa0, 0xb1, 0x2e, 0x09, 0xd4, 0x87, 0xaa, 0x9c, 0x40, 0x9b, 0x49, 0x8b, 0x00, 0x7f, 0xb8, 0x26, 0xc8, 0x2a, 0x24, 0x0f, 0x60, 0xf6, 0x7b, 0x9c, 0xf8, 0xc6, 0xea, 0x7e, 0x0d, 0x79, 0xf0, 0x48, 0xd4, 0x29, 0x68, 0x05, 0xdb, 0xd9, 0x1f, 0x0f, 0xe6, 0x14, 0x53, 0x93, 0x4f, 0x9b, 0x7e, 0x6d, 0xe2, 0x86, 0xa5, 0x2e, 0xe7, 0x3b, 0xf1, 0x37, 0x68, 0x4d, 0xb6, 0xa4, 0xbf, 0x16, 0xed, 0x23, 0xe9, 0x4d, 0x26, 0xc9, 0xef, 0xe8, 0x3e, 0x85, 0xce, 0xf3, 0x4d, 0xf2, 0x15, 0xc8, 0x2f, 0x3b, 0x57, 0x2a, 0xbe, 0x23, 0x7b, 0x1e, 0x25, 0x46, 0xb5, 0x6b, 0x5c, 0x0e, 0xaf, 0x94, 0xff, 0x80, 0x49, 0xb7, 0x83, 0x6d, 0x21, 0x53, 0x8c, 0x19, 0xeb, 0xc6, 0x48, 0x2c, 0x5a, 0x37, 0x60, 0xd6, 0x1e, 0xbd, 0xbd, 0x3a, 0xbd, 0x74, 0xe5, 0x2b, 0x94, 0xc0, 0xbe, 0x56, 0x49, 0x73, 0x5f, 0xf9, 0x91, 0x05, 0xfd, 0x8c, 0xd9, 0x8c, 0x7c, 0x38, 0xce, 0x7f, 0x3a, 0x89, 0xd0, 0x68, 0xe5, 0xce, 0x8f, 0x8e, 0xca, 0xa1, 0x3c, 0xc0, 0xd7, 0x54, 0x42, 0x59, 0x2b, 0x83, 0xe7, 0xcc, 0xa8, 0xfa, 0xef, 0x67, 0xb2, 0x50, 0xfb, 0x52, 0xfe, 0x97, 0x86, 0xd9, 0x59, 0x1d, 0xf8, 0x26, 0x37, 0x67, 0xff, 0xc7, 0xbc, 0x99, 0xc9, 0x81, 0x6f, 0xa9, 0x6d, 0x7b, 0xf0, 0xb7, 0x25, 0x5e, 0x54, 0x65, 0x01, 0x62, 0x5c, 0x62, 0x1c, 0x48, 0x45, 0x14, 0x96, 0x4b, 0x68, 0xa9, 0xe6, 0xbc, 0x67, 0xb4, 0x75, 0x3f, 0xb4, 0x9f, 0x87, 0x43, 0x57, 0x28, 0xaf, 0x9f, 0x62, 0x37, 0x68, 0x71, 0xb5, 0xaf, 0x95, 0xa8, 0x2d, 0xa7, 0x22, 0xfa, 0x18, 0x5f, 0x82, 0x4e, 0xe0, 0x67, 0x51, 0x79, 0x89, 0x12, 0xe8, 0x03, 0xbd, 0x14, 0x10, 0xe1, 0x13, 0x0d, 0xc8, 0xae, 0x5c, 0xaf, 0xe7, 0xb5, 0xda, 0x07, 0x64, 0x7e, 0x3c, 0x5b, 0x54, 0x5c, 0xe9, 0x3b, 0xb6, 0xc8, 0xd7, 0x64, 0xed, 0xca, 0x66, 0xe0, 0x63, 0x40, 0x38, 0x02, 0x30, 0x8f, 0x05, 0x81, 0x25, 0x1c, 0x7b, 0x68, 0x92, 0x20, 0xc8, 0xdc, 0x4f, 0x0a, 0xc8, 0xa8, 0x1b, 0xb3, 0xd1, 0x7b, 0xc0, 0x75, 0x7e, 0xc7, 0x2b, 0xd5, 0xbb, 0x2b, 0x03, 0xf3, 0xe1, 0x68, 0xdd, 0x4d, 0xe4, 0x41, 0x6d, 0xf9, 0x9f, 0x5d, 0x79, 0xf8, 0xef, 0xef, 0x47, 0xaf, 0xed, 0x6d, 0x5a, 0x84, 0x91, 0x14, 0x35, 0x73, 0x60, 0xdf, 0x08, 0xbe, 0x8c, 0xa7, 0x30, 0xb1, 0xe6, 0xed, 0x4b, 0xa1, 0x24, 0x19, 0xd1, 0xa5, 0x41, 0x58, 0xeb, 0xc2, 0xd0, 0x42, 0xbd, 0x71, 0xa0, 0x25, 0xd8, 0x2f, 0x1b, 0xd2, 0xfa, 0x82, 0xa7, 0x73, 0x8e, 0x2e, 0xad, 0x72, 0x98, 0xd6, 0x35, 0x47, 0x90, 0x97, 0x53, 0xcf, 0xd5, 0xfa, 0x7f, 0x66, 0xe9, 0x82, 0x7b, 0x09, 0xf5, 0xcf, 0x84, 0x1c, 0xe4, 0xea, 0x05, 0x4c, 0x62, 0xe5, 0x79, 0x81, 0x66, 0x6f, 0xea, 0x2a, 0x78, 0x92, 0xf4, 0xae, 0x06, 0x30, 0xc9, 0x8c, 0x19, 0x56, 0x5d, 0x85, 0x79, 0x71, 0x74, 0x49, 0x96, 0x12, 0x9b, 0x18, 0x1f, 0xe8, 0xfa, 0x0f, 0x1f, 0xec, 0xa7, 0x33, 0x11, 0x90, 0xdb, 0x73, 0x2e, 0x71, 0xc6, 0xcd, 0xc3, 0x06, 0x50, 0xb9, 0xb0, 0x62, 0x4f, 0xd0, 0x2a, 0xb7, 0xbd, 0x8c, 0x32, 0xc4, 0xde, 0xab, 0x2f, 0x24, 0x4f, 0xc6, 0xa1, 0x88, 0xe7, 0xd7, 0xec, 0x17, 0x24, 0x61, 0xef, 0xec, 0x19, 0x95, 0x5d, 0xf5, 0xed, 0x73, 0xec, 0x37, 0xff, 0xa8, 0x9d, 0xe4, 0xae, 0x1b, 0x27, 0x63, 0x71, 0xce, 0xed, 0xa6, 0xe7, 0x5c, 0xda, 0x27, 0x8e, 0x0d, 0x1f, 0x86, 0x81, 0xe7, 0x6a, 0xf7, 0xd8, 0x6c, 0x11, 0x49, 0x4a, 0xc2, 0xd3, 0xa0, 0x96, 0x8e, 0x37, 0xa0, 0x68, 0x8c, 0xee, 0x5a, 0x1d, 0x8c, 0xc8, 0x61, 0x83, 0x1a, 0x97, 0x03, 0x6b, 0x0a, 0x8e, 0xd6, 0x6c, 0xf1, 0xea, 0x25, 0x95, 0x19, 0x62, 0xc7, 0x15, 0x69, 0xe9, 0x82, 0x38, 0xcd, 0xf0, 0xbf, 0x92, 0x1f, 0x42, 0x96, 0x14, 0xa8, 0xd7, 0x65, 0xc0, 0x8f, 0xe8, 0x3b, 0xc0, 0x0b, 0x72, 0xff, 0x35, 0xaa, 0x10, 0x57, 0x2c, 0x41, 0x5a, 0x9f, 0x5a, 0xf2, 0xee, 0xd6, 0xe7, 0x7c, 0xc0, 0xbf, 0xf2, 0x9d, 0x1f, 0xa6, 0xc7, 0xd1, 0xda, 0x17, 0xd2, 0x36, 0xd8, 0x5e, 0xd0, 0x2e, 0xad, 0xe3, 0x93, 0x57, 0x41, 0x69, 0xf2, 0x3b, 0x89, 0x54, 0xbe, 0xdd, 0xda, 0x15, 0xc9, 0x04, 0x4f, 0xae, 0xd1, 0xac, 0x13, 0x6c, 0xdd, 0xc6, 0x34, 0x17, 0x5b, 0x9f, 0xf8, 0xc8, 0x0b, 0x2f, 0x36, 0x40, 0x99, 0x7b, 0x35, 0x87, 0x69, 0xd9, 0xb6, 0x2e, 0x8a, 0x0a, 0x15, 0x98, 0xa3, 0xfd, 0x05, 0x51, 0xd1, 0x89, 0xb5, 0x54, 0x28, 0xaf, 0x2d, 0x3f, 0x7f, 0x7b, 0xe2, 0xf4, 0xca, 0x44, 0xff, 0x0c, 0x48, 0x42, 0x98, 0x51, 0xff, 0x56, 0x97, 0xf2, 0x13, 0x1c, 0x71, 0xa2, 0xac, 0xbc, 0xc1, 0x1c, 0x15, 0x70, 0xef, 0x20, 0xae, 0x3b, 0x03, 0x36, 0x29, 0x34, 0x26, 0x90, 0xda, 0x6c, 0x67, 0x05, 0x19, 0x09, 0x94, 0xf1, 0x8d, 0x7f, 0x4a, 0x67, 0x8e, 0x98, 0xf6, 0x02, 0x07, 0xba, 0x00, 0xf0, 0x33, 0x04, 0xcc, 0x06, 0xbe, 0x9c, 0xae, 0x27, 0xbc, 0x41, 0x64, 0xb8, 0x0f, 0x5e, 0xfd, 0xaa, 0xd3, 0xea, 0x3d, 0x97, 0x81, 0x39, 0x7b, 0xb4, 0xe1, 0xa6, 0x9b, 0x42, 0xb3, 0x37, 0x28, 0x60, 0xb3, 0x46, 0x53, 0x89, 0x56, 0xc9, 0x89, 0xee, 0x79, 0x3c, 0x25, 0xc5, 0x12, 0x4b, 0xd9, 0x72, 0x3f, 0x92, 0xd3, 0x44, 0x76, 0x5b, 0x2c, 0x70, 0x1c, 0x34, 0x83, 0xb5, 0x87, 0xc3, 0x52, 0x13, 0xdd, 0x84, 0x7a, 0xf8, 0x35, 0xea, 0x24, 0x80, 0x1c, 0x95, 0xd2, 0x44, 0xb2, 0x2f, 0x80, 0x40, 0xd6, 0xee, 0x0d, 0x9c, 0xe2, 0x34, 0xb9, 0x81, 0x2d, 0xc1, 0x83, 0x83, 0x3d, 0x95, 0x76, 0x79, 0x7d, 0x2f, 0xb8, 0x8d, 0xb7, 0xdb, 0x0d, 0x55, 0x51, 0x45, 0x4c, 0x9a, 0x88, 0xf9, 0xcc, 0x85, 0xb9, 0x6f, 0xa7, 0x13, 0xfd, 0x07, 0x90, 0x7b, 0xe1, 0x28, 0x7f, 0x06, 0x36, 0x9c, 0x5a, 0x33, 0x9e, 0xaa, 0x10, 0x33, 0x0c, 0x59, 0xdf, 0xcc, 0x88, 0x44, 0x75, 0x9d, 0x1e, 0x97, 0x10, 0x24, 0x49, 0xca, 0xb1, 0x98, 0xcb, 0xa3, 0xef, 0x2e, 0x7e, 0xbd, 0x1d, 0xfe, 0x25, 0xd2, 0x88, 0x9f, 0xdd, 0x97, 0xa2, 0x36, 0x9e, 0x21, 0xae, 0x02, 0x45, 0x91, 0xe7, 0xc1, 0x31, 0x94, 0xfd, 0x51, 0x9a, 0x4d, 0xd1, 0xe5, 0xc7, 0xae, 0x09, 0x40, 0xb2, 0xbf, 0xf0, 0x85, 0x2f, 0x49, 0x2b, 0xaf, 0x49, 0xb5, 0x82, 0x2a, 0x3e, 0xb0, 0x68, 0x26, 0x3e, 0xe6, 0xcf, 0x97, 0xb3, 0xaa, 0x50, 0x93, 0xde, 0x9e, 0xb3, 0xaa, 0x92, 0xaf, 0x19, 0x99, 0x7b, 0x0d, 0x2d, 0x08, 0x4b, 0x1a, 0x6c, 0x69, 0x23, 0x3d, 0x35, 0xa5, 0x1f, 0x5e, 0xbf, 0x59, 0x19, 0xf8, 0x72, 0xc7, 0xba, 0xab, 0xdd, 0x43, 0x19, 0xbe, 0xe1, 0xbc, 0x37, 0x9f, 0x96, 0x85, 0x49, 0x93, 0x28, 0xb4, 0x76, 0x72, 0xd4, 0xed, 0x38, 0xbf, 0x96, 0xa7, 0x97, 0xb5, 0xda, 0xc1, 0xd2, 0x1c, 0xe8, 0x72, 0xa4, 0x72, 0x20, 0xa7, 0x78, 0x43, 0x33, 0x1f, 0x5a, 0x8e, 0xe9, 0xd3, 0x46, 0x1c, 0xbf, 0xe4, 0x8f, 0xc0, 0x16, 0xfb, 0x76, 0x2b, 0xe5, 0xf7, 0xe0, 0x1f, 0x2f, 0x2f, 0xaa, 0x8b, 0x71, 0xb2, 0x9f, 0x4f, 0x5c, 0xec, 0xe7, 0x3f, 0xc8, 0xa0, 0x81, 0xd8, 0xb4, 0x5b, 0x98, 0x62, 0x90, 0x86, 0x8b, 0x91, 0xfc, 0x75, 0xdc, 0xbe, 0xed, 0x88, 0xab, 0xe5, 0x35, 0xc4, 0xdd, 0x22, 0xdb, 0x90, 0x1a, 0x04, 0xda, 0x03, 0xc2, 0x39, 0x45, 0x5d, 0x56, 0x26, 0x49, 0x61, 0x66, 0x55, 0x56, 0x66, 0xeb, 0x6d, 0x64, 0x85, 0x99, 0xf5, 0x0b, 0x95, 0x5d, 0x95, 0x95, 0x5d, 0x95, 0xbd, 0xc3, 0x55, 0xf6, 0x07, 0x50, 0xab, 0x77, 0x2f, 0xbb, 0xca, 0xb6, 0x51, 0xf3, 0x0b, 0x4d, 0xae, 0xf5, 0xb5, 0x71, 0x56, 0xad, 0x02, 0xcc, 0xef, 0x0e, 0xe7, 0xcf, 0xb4, 0x8e, 0xff, 0xb4, 0x41, 0x34, 0x18, 0xba, 0x36, 0x27, 0xab, 0x61, 0x8e, 0xc9, 0x9a, 0xb0, 0x37, 0xe4, 0x25, 0xb2, 0x0d, 0x42, 0x05, 0x08, 0xb1, 0x43, 0x58, 0x67, 0x3e, 0x59, 0x47, 0x69, 0xfe, 0x2d, 0x19, 0x5f, 0xba, 0x5f, 0x40, 0x19, 0x6f, 0xf7, 0x69, 0xd8, 0x73, 0xfd, 0x06, 0xe9, 0x6c, 0x2c, 0xdd, 0x06, 0x07, 0x20, 0x59, 0x66, 0xa2, 0x02, 0xff, 0xb8, 0x71, 0x31, 0x84, 0xc2, 0x76, 0xd8, 0xd7, 0x10, 0xa3, 0x0b, 0x48, 0x6a, 0x3e, 0x84, 0x9d, 0x6a, 0xf3, 0x75, 0x77, 0x90, 0x65, 0x70, 0xea, 0x00, 0x6f, 0x16, 0x2c, 0x4a, 0xc1, 0x5b, 0x26, 0x17, 0xf2, 0x2f, 0xd6, 0xbe, 0xa3, 0x9e, 0x2d, 0xbf, 0xc1, 0xbe, 0xee, 0x87, 0x61, 0x10, 0x85, 0x8b, 0xaf, 0xd8, 0x19, 0xfe, 0xf4, 0x00, 0xc0, 0xfb, 0xc1, 0x00, 0x3a, 0xe6, 0x2c, 0x32, 0x76, 0xfe, 0xd3, 0xb2, 0xf4, 0xad, 0x4b, 0x03, 0xbe, 0xe9, 0x07, 0x02, 0xf8, 0x8b, 0x92, 0x9d, 0xe0, 0xe8, 0x98, 0xb3, 0x9f, 0x04, 0xed, 0x1c, 0x5b, 0xd6, 0x4a, 0x72, 0x93, 0xb2, 0x9f, 0x96, 0xfd, 0xc4, 0xdf, 0x88, 0x7f, 0x03, 0x10, 0x1e, 0x75, 0x05, 0xa2, 0xe3, 0x96, 0x7e, 0x8d, 0x98, 0x0f, 0xa6, 0x19, 0x31, 0xcc, 0xc9, 0x77, 0xc0, 0xf4, 0xd2, 0xc6, 0x70, 0x7e, 0x1d, 0x11, 0x28, 0xf5, 0x68, 0xdd, 0x97, 0x42, 0xe6, 0x34, 0xc0, 0x8b, 0x72, 0x4b, 0xbc, 0x19, 0x6c, 0x4b, 0xbd, 0x91, 0xd7, 0x82, 0xa7, 0x04, 0xc3, 0xf3, 0xe0, 0xec, 0x0f, 0xc7, 0x6e, 0x5b, 0x62, 0xff, 0x0a, 0x14, 0x9f, 0xee, 0x25, 0xb8, 0x8a, 0x44, 0x3d, 0x4a, 0x33, 0x03, 0x82, 0x51, 0x1d, 0x33, 0x7e, 0xee, 0x22, 0x56, 0xb3, 0xaa, 0xa4, 0x2c, 0x2b, 0xf8, 0x5c, 0x87, 0xee, 0x9f, 0x35, 0x68, 0x49, 0x3d, 0x1f, 0x30, 0x34, 0xd4, 0x34, 0xa8, 0xf8, 0xdc, 0x7d, 0xda, 0x0f, 0x88, 0x5f, 0x47, 0x84, 0x50, 0x7d, 0xaa, 0x41, 0x76, 0x45, 0xf3, 0x99, 0xf8, 0xf4, 0xb6, 0xa1, 0xde, 0xe9, 0x14, 0xb7, 0xb2, 0x98, 0xe3, 0x0e, 0x03, 0x7a, 0xd8, 0x10, 0x66, 0x1c, 0x24, 0xbb, 0x79, 0x9d, 0x6b, 0xb3, 0x45, 0xd8, 0xfd, 0x9d, 0xa9, 0x75, 0xcf, 0x06, 0x4b, 0xed, 0xa7, 0x28, 0x4d, 0x9b, 0x79, 0x52, 0x1c, 0x6d, 0x94, 0x71, 0x25, 0x62, 0xab, 0x7b, 0x0c, 0xe1, 0x01, 0x26, 0xd2, 0xd2, 0x12, 0x0e, 0xf2, 0xc3, 0xe5, 0x15, 0x6c, 0xdf, 0xad, 0x6f, 0xbe, 0x9a, 0xb9, 0xdf, 0x69, 0x35, 0xfe, 0x5e, 0xe4, 0xda, 0xce, 0x8a, 0x43, 0x65, 0x59, 0x89, 0x5f, 0xda, 0x85, 0x9a, 0x23, 0x26, 0x97, 0x52, 0x7e, 0x78, 0x61, 0x6e, 0x3f, 0xd6, 0xea, 0x67, 0x7a, 0xc3, 0xe4, 0x50, 0xfe, 0x66, 0x1f, 0xc7, 0x74, 0xfc, 0xbd, 0xc6, 0xd2, 0x3a, 0xbb, 0xc5, 0x45, 0x5f, 0xda, 0x89, 0xb2, 0xc7, 0x7c, 0x14, 0x2f, 0x70, 0x11, 0x01, 0x8b, 0x09, 0xbc, 0xf4, 0x2d, 0xc8, 0x1f, 0x86, 0x0d, 0xd9, 0x4f, 0x5f, 0x92, 0x51, 0x40, 0xc1, 0x72, 0xd5, 0x60, 0x82, 0x3a, 0x12, 0x42, 0xf7, 0x48, 0xf9, 0x45, 0x46, 0x28, 0xea, 0xb4, 0xb3, 0x04, 0x36, 0x2a, 0xb0, 0x7b, 0xcc, 0x12, 0xec, 0x86, 0xa8, 0xd2, 0xb8, 0x75, 0x66, 0x5f, 0xe3, 0xb7, 0xdf, 0xe7, 0xa4, 0x0b, 0xd1, 0xae, 0xfb, 0xdc, 0x5d, 0x37, 0xa9, 0x57, 0xbd, 0xcf, 0xd1, 0x67, 0x6b, 0x49, 0x6b, 0xea, 0x77, 0x5d, 0x9d, 0xd8, 0xd3, 0xd0, 0xc2, 0x7c, 0x7c, 0xdb, 0x8b, 0x5e, 0xed, 0xd1, 0x07, 0x5a, 0xad, 0x22, 0x3d, 0x2c, 0x5f, 0x85, 0x22, 0xe7, 0x42, 0xa6, 0xfd, 0x98, 0xfd, 0x65, 0x7c, 0x81, 0x60, 0x83, 0x20, 0x31, 0x3e, 0x52, 0x8a, 0x5d, 0xbd, 0x55, 0x35, 0x6a, 0x46, 0x19, 0xb9, 0x1f, 0x06, 0x39, 0x28, 0x0e, 0xb7, 0xb1, 0x7a, 0x37, 0x84, 0x1c, 0xdc, 0xb4, 0x9d, 0x0a, 0x19, 0xdd, 0x87, 0x10, 0xa6, 0x7b, 0xbb, 0x03, 0x0b, 0x38, 0x63, 0x1d, 0x70, 0x96, 0x0c, 0xa3, 0x89, 0x1b, 0x1f, 0x51, 0xa6, 0x55, 0xbe, 0x12, 0x85, 0x8b, 0xe0, 0xb2, 0xcf, 0xe6, 0xbd, 0xfc, 0xbd, 0x48, 0x27, 0x74, 0xb2, 0x49, 0xcd, 0x6c, 0xbb, 0xb8, 0x74, 0x10, 0x59, 0x02, 0x2a, 0xba, 0x40, 0x77, 0xe0, 0xe0, 0xb8, 0x01, 0xe2, 0x23, 0x38, 0x10, 0x10, 0x79, 0xc6, 0x8b, 0x72, 0x23, 0x76, 0x27, 0x68, 0x3b, 0x26, 0xc8, 0xdd, 0x25, 0xd2, 0xd1, 0xb8, 0xe9, 0xd8, 0x60, 0x69, 0xb6, 0x1f, 0x2b, 0x88, 0x57, 0xd0, 0xdf, 0x02, 0xe6, 0xf5, 0xc6, 0x2b, 0xd1, 0x95, 0xcb, 0xe7, 0x33, 0xae, 0x1e, 0x8d, 0x4e, 0x87, 0x55, 0xa8, 0xbf, 0x61, 0xa6, 0x6f, 0x42, 0x62, 0xdb, 0x89, 0xcb, 0x78, 0x9f, 0xdf, 0x71, 0x4d, 0xeb, 0xfa, 0x95, 0x24, 0xe7, 0x61, 0x59, 0x11, 0x51, 0x1d, 0x82, 0xc1, 0x00, 0xc9, 0x13, 0x89, 0xdf, 0x61, 0x83, 0xd3, 0x7c, 0x57, 0x80, 0x0f, 0x3a, 0xee, 0x11, 0xd1, 0xb7, 0x60, 0x5f, 0x96, 0x35, 0x52, 0xf6, 0xe8, 0x09, 0x99, 0x0d, 0x40, 0xba, 0x91, 0x93, 0x76, 0x57, 0xef, 0x6d, 0x36, 0xbc, 0x16, 0x46, 0xce, 0xd5, 0x5d, 0xd6, 0xf1, 0x56, 0x2b, 0xf3, 0x21, 0x36, 0xb4, 0xed, 0x7e, 0x0d, 0xdc, 0xc2, 0x33, 0xe9, 0x48, 0xa2, 0x42, 0x44, 0x35, 0x79, 0x0f, 0x3d, 0x88, 0x90, 0x8e, 0xbb, 0x2f, 0x7d, 0x55, 0x72, 0x56, 0xd6, 0x09, 0x81, 0x29, 0x0d, 0x17, 0x13, 0x6f, 0x15, 0x3f, 0xa5, 0xf9, 0x74, 0x7b, 0x82, 0x46, 0xd4, 0x01, 0x0e, 0xfa, 0x66, 0x97, 0xc2, 0xbd, 0x62, 0xe7, 0x56, 0x00, 0x01, 0x08, 0x77, 0x14, 0x25, 0x7f, 0x1c, 0xc6, 0xe9, 0x18, 0x14, 0x8c, 0xf4, 0x82, 0x8e, 0xa5, 0x54, 0x09, 0x85, 0x19, 0x80, 0x79, 0x68, 0x4c, 0x96, 0xc8, 0xc9, 0x7d, 0xbd, 0xd0, 0xf8, 0x31, 0xa7, 0x83, 0xba, 0x49, 0x88, 0x9a, 0xdd, 0xd4, 0x0b, 0xa5, 0x07, 0xde, 0x9c, 0x80, 0x62, 0x1d, 0x78, 0x71, 0x30, 0xef, 0x14, 0xdf, 0x8c, 0xc9, 0xc1, 0xe7, 0x00, 0x73, 0xf1, 0xac, 0x36, 0x3f, 0x30, 0x68, 0xf3, 0x32, 0x30, 0x73, 0x8e, 0xa5, 0xd8, 0x1b, 0xf4, 0x50, 0xeb, 0x45, 0xfe, 0x5c, 0x2b, 0x54, 0x40, 0x78, 0xf7, 0xec, 0x7a, 0xff, 0x5c, 0xaf, 0x21, 0x06, 0x00, 0xc4, 0x67, 0x4c, 0x18, 0x73, 0x69, 0x54, 0xdf, 0x38, 0xdc, 0x2e, 0x6d, 0x2c, 0xfe, 0x64, 0x7c, 0xfd, 0xfe, 0x27, 0x48, 0x94, 0x26, 0x3e, 0x54, 0xb8, 0xeb, 0x90, 0x9c, 0x79, 0x20, 0xf9, 0x67, 0xb1, 0x05, 0xe7, 0x4c, 0x62, 0xad, 0x31, 0x8d, 0xa7, 0xb4, 0x3e, 0x52, 0x7f, 0x03, 0x0f, 0xf2, 0x7f, 0x86, 0xf6, 0xdf, 0x41, 0xab, 0x75, 0xb6, 0x23, 0x69, 0x1d, 0x76, 0x14, 0x7c, 0xa1, 0x54, 0x2e, 0x40, 0x2b, 0xc3, 0xa2, 0xf9, 0xda, 0x94, 0xd8, 0x47, 0x48, 0xec, 0x82, 0x28, 0xda, 0x61, 0xd9, 0xf3, 0xcf, 0xb5, 0x85, 0x69, 0x7c, 0x26, 0x3e, 0xe9, 0x1c, 0xf5, 0xcb, 0xba, 0xfc, 0x11, 0x59, 0xd1, 0x04, 0x1b, 0x86, 0x10, 0xc8, 0x27, 0xe6, 0x9d, 0xc5, 0xaf, 0x2f, 0x92, 0x7d, 0x39, 0x33, 0x98, 0xc5, 0x55, 0x20, 0x61, 0x59, 0xbd, 0x48, 0xb2, 0xe5, 0x03, 0xe9, 0x0d, 0xbd, 0xf2, 0x76, 0xf2, 0xf7, 0xd5, 0xa4, 0x78, 0x5b, 0x77, 0xef, 0xc7, 0x9a, 0xe5, 0x1b, 0xc4, 0x0f, 0x94, 0x56, 0x96, 0xba, 0x15, 0x0f, 0x48, 0xbc, 0xdd, 0x58, 0x55, 0x89, 0x08, 0xd0, 0x92, 0x3e, 0xb9, 0xa3, 0x2c, 0x51, 0x8f, 0x99, 0x6b, 0xfa, 0x3d, 0xd8, 0x5c, 0x4c, 0x8e, 0x78, 0x20, 0x3e, 0x37, 0x35, 0x48, 0x96, 0x64, 0xb2, 0xa2, 0x73, 0x87, 0xad, 0x4e, 0x3d, 0x25, 0x84, 0xd8, 0x56, 0xb0, 0x03, 0xb5, 0xb4, 0xc4, 0x7f, 0xf7, 0x02, 0xb9, 0x1d, 0x1c, 0x13, 0x14, 0x97, 0xfd, 0x0b, 0xb6, 0x08, 0xf3, 0xe2, 0x18, 0xd3, 0xfe, 0x75, 0xb3, 0x0f, 0xe0, 0xfa, 0xe8, 0x91, 0x3a, 0x7c, 0xc5, 0xb0, 0xae, 0xc4, 0x1d, 0xd3, 0xa7, 0x33, 0x9b, 0x45, 0xb2, 0x88, 0x0e, 0x5a, 0xbd, 0xc1, 0x11, 0xc5, 0x18, 0x1d, 0xbe, 0x32, 0x13, 0x31, 0x95, 0x25, 0x07, 0xb1, 0x27, 0x03, 0x35, 0x73, 0x64, 0x84, 0x7e, 0x43, 0x89, 0xdb, 0x9e, 0x7e, 0x06, 0x43, 0x3a, 0x77, 0x69, 0x1d, 0x03, 0x40, 0x9e, 0x40, 0x7f, 0x09, 0x44, 0x38, 0x16, 0x11, 0x0a, 0x87, 0x6a, 0x3d, 0xea, 0x3a, 0x36, 0x4a, 0x68, 0x60, 0x9b, 0x4c, 0x3b, 0xfe, 0xb0, 0x8a, 0xcf, 0x96, 0xe3, 0x6f, 0xc0, 0x2a, 0x76, 0xdb, 0x56, 0xb1, 0xb2, 0x1a, 0x77, 0x78, 0xb0, 0x1e, 0x7f, 0x72, 0x8f, 0x2c, 0x5f, 0x80, 0xb7, 0xe4, 0xaf, 0xf9, 0xcb, 0x39, 0x3d, 0xe6, 0xbc, 0xdc, 0x22, 0x21, 0x13, 0xd9, 0x2f, 0xe1, 0x79, 0x99, 0xce, 0x69, 0x47, 0x9b, 0x1d, 0x0a, 0xd4, 0x9a, 0xfd, 0x5c, 0x6b, 0x5e, 0x24, 0x6c, 0x40, 0x97, 0x99, 0xce, 0xac, 0xb6, 0x63, 0xd9, 0x63, 0xb0, 0x13, 0x19, 0x1a, 0xd2, 0x53, 0x4f, 0xec, 0x18, 0xb3, 0xb1, 0xba, 0xa0, 0xe6, 0x83, 0x1b, 0x06, 0x49, 0xdf, 0x92, 0x71, 0xbc, 0x96, 0x6f, 0xee, 0xbe, 0xb3, 0xad, 0xe1, 0xae, 0x82, 0x51, 0x43, 0x33, 0x1a, 0x4a, 0xbd, 0x76, 0x81, 0x9e, 0x01, 0x56, 0x08, 0x8f, 0x28, 0xa4, 0xc8, 0x1c, 0x6d, 0xc8, 0x05, 0xa1, 0x87, 0x78, 0xad, 0x42, 0xcc, 0x50, 0x7b, 0xa4, 0x15, 0xc9, 0xcc, 0x21, 0xb1, 0xe2, 0x72, 0x50, 0xe3, 0xac, 0x59, 0x6e, 0x03, 0x1c, 0x06, 0x1b, 0xcd, 0x18, 0xa9, 0x99, 0x57, 0x5e, 0xf0, 0xc0, 0xd3, 0x60, 0xe2, 0xcb, 0xf0, 0x34, 0x48, 0x62, 0x9a, 0x34, 0xbd, 0x3e, 0xdd, 0x01, 0x2b, 0x32, 0x2c, 0xd0, 0xfc, 0x1e, 0x32, 0xb0, 0xbc, 0xd5, 0x89, 0x3d, 0x8c, 0xdd, 0xf8, 0xe5, 0x0c, 0xe3, 0xa5, 0x84, 0xc4, 0x0e, 0x40, 0x8f, 0xe8, 0x29, 0xea, 0xc7, 0x70, 0x6e, 0xe6, 0x2f, 0xb6, 0x38, 0xa0, 0xd4, 0x9b, 0x27, 0x6c, 0x79, 0xd0, 0x05, 0xaa, 0xed, 0x1e, 0x81, 0xea, 0x44, 0x7e, 0x08, 0xe0, 0x33, 0xd9, 0xcc, 0x3d, 0x4e, 0xa8, 0xf0, 0xb9, 0x69, 0xdd, 0x36, 0xd4, 0x95, 0xc8, 0x22, 0x0a, 0x98, 0x05, 0x6b, 0x5f, 0xda, 0xbe, 0x7d, 0x77, 0x65, 0x60, 0xca, 0x54, 0x4b, 0xf8, 0xfe, 0x95, 0xb8, 0x48, 0x3f, 0x26, 0x2d, 0x45, 0xe3, 0xf9, 0x9b, 0x5f, 0x4a, 0x28, 0xee, 0x22, 0xd4, 0xf4, 0x71, 0x37, 0xe4, 0x22, 0xce, 0x28, 0x9c, 0x3e, 0xdd, 0xfa, 0xde, 0xe2, 0x0c, 0x58, 0xa6, 0xa1, 0x40, 0x7a, 0x99, 0xdf, 0x89, 0x8d, 0x48, 0x72, 0x24, 0x8a, 0x61, 0xed, 0xa0, 0x35, 0x5a, 0x37, 0x8d, 0x0c, 0x74, 0xe3, 0x80, 0x71, 0x80, 0x60, 0x6f, 0xfd, 0x1d, 0xfc, 0x2b, 0x26, 0xfc, 0xe5, 0x0c, 0x03, 0x0f, 0xcf, 0x8d, 0x44, 0xef, 0xd0, 0x1e, 0x4f, 0xa0, 0xf8, 0x48, 0xff, 0x2e, 0xec, 0xa8, 0x06, 0xde, 0x35, 0x2c, 0x88, 0x10, 0xfa, 0xd4, 0xab, 0xf6, 0xd0, 0xd6, 0x41, 0x0d, 0x48, 0xb5, 0x10, 0xd7, 0x52, 0x37, 0x67, 0xd9, 0xf9, 0xc0, 0x7b, 0x1e, 0xf3, 0xe0, 0x9b, 0xd3, 0x50, 0x5b, 0x02, 0xa6, 0x0c, 0xe7, 0x1b, 0x41, 0x3e, 0x38, 0xea, 0xc7, 0x02, 0x6a, 0xe6, 0xe4, 0x9e, 0xfa, 0x65, 0x8c, 0x26, 0xea, 0x84, 0x4e, 0x8d, 0xea, 0x75, 0x11, 0x0b, 0x5b, 0xb5, 0x9c, 0x75, 0xd5, 0x0f, 0x55, 0xac, 0x66, 0x3d, 0xf2, 0x19, 0xbc, 0x11, 0x79, 0x0b, 0x86, 0xa6, 0xc9, 0x45, 0xbe, 0x44, 0x54, 0xec, 0x21, 0x14, 0xbc, 0x44, 0x19, 0x8a, 0x34, 0x44, 0x5d, 0x27, 0xbb, 0x3e, 0x68, 0xd7, 0xc0, 0xb5, 0xdb, 0x3b, 0x01, 0x33, 0xfc, 0xd8, 0xfc, 0x59, 0xf7, 0xa5, 0x68, 0x5f, 0x88, 0x64, 0x03, 0x68, 0x81, 0xb4, 0x4c, 0xc8, 0x97, 0xed, 0x7b, 0x3c, 0x63, 0xe2, 0xcf, 0xa7, 0x56, 0x8c, 0xbc, 0x75, 0xed, 0x6a, 0x27, 0xb0, 0xdb, 0x39, 0x16, 0x9e, 0x84, 0x5d, 0x1d, 0x70, 0x57, 0xdd, 0x6b, 0xdf, 0x76, 0x30, 0xe3, 0x69, 0xc6, 0x12, 0xbb, 0xaa, 0xc5, 0x7b, 0x4f, 0x45, 0x8d, 0x6a, 0x1c, 0xd5, 0x47, 0x2e, 0x3a, 0xbe, 0x41, 0x88, 0x45, 0x9b, 0x78, 0x61, 0x63, 0x0d, 0x8a, 0x1b, 0x1c, 0xb4, 0xa8, 0x4c, 0xa0, 0xd5, 0x3e, 0xb4, 0x98, 0x88, 0xbd, 0xe4, 0x98, 0x83, 0xba, 0xae, 0xea, 0x43, 0x66, 0xf9, 0x52, 0x37, 0xee, 0xaf, 0x5a, 0x2a, 0xfb, 0x3a, 0xc9, 0xef, 0x66, 0x68, 0x68, 0x8e, 0x99, 0xb7, 0xd6, 0x7a, 0xab, 0x60, 0x32, 0xf2, 0x03, 0xaa, 0x77, 0x34, 0x9a, 0x73, 0x98, 0x30, 0xa0, 0xa1, 0x4b, 0x7e, 0x44, 0xd0, 0x12, 0xe3, 0x90, 0x22, 0x91, 0x02, 0x1d, 0xc6, 0x0c, 0x18, 0x46, 0xaf, 0xe3, 0xd4, 0x6a, 0x13, 0xd6, 0xee, 0x45, 0x74, 0xf6, 0xee, 0x44, 0xcc, 0x5d, 0x80, 0xdd, 0x9a, 0xf3, 0xe6, 0xdd, 0xd7, 0x26, 0xf1, 0x4b, 0x7d, 0x2a, 0xcf, 0x9d, 0x8a, 0x1c, 0x80, 0xa5, 0xb1, 0x49, 0x00, 0x41, 0xf9, 0x6a, 0xe3, 0x65, 0x14, 0x53, 0x39, 0x20, 0x49, 0x95, 0x56, 0x6c, 0xb3, 0xcb, 0xe5, 0x07, 0x08, 0xf5, 0x35, 0x93, 0x0a, 0xeb, 0xe4, 0x7e, 0x5b, 0xac, 0x69, 0xfd, 0xa6, 0xdf, 0x19, 0x6b, 0x0a, 0x5d, 0x88, 0xa6, 0x6c, 0x4c, 0xba, 0xfa, 0x57, 0x75, 0xd2, 0xc1, 0x98, 0x89, 0x09, 0xfc, 0xc8, 0xb5, 0x9f, 0xfa, 0x7e, 0xb0, 0x5f, 0x85, 0x63, 0x1d, 0x2b, 0xb3, 0x93, 0xee, 0xe1, 0x1d, 0x57, 0x22, 0xd6, 0x04, 0xd2, 0xbb, 0xc2, 0xfe, 0xfa, 0xb3, 0x9a, 0x56, 0x9d, 0x79, 0xd5, 0xef, 0xf3, 0x9e, 0xcb, 0xc0, 0x67, 0x3e, 0xc6, 0xbc, 0x1f, 0x42, 0xf7, 0x02, 0xab, 0xe3, 0xe6, 0xd2, 0xdf, 0xe5, 0xde, 0xf1, 0x47, 0xf5, 0xde, 0x81, 0xa2, 0x34, 0x93, 0x0f, 0x8e, 0x54, 0x30, 0xba, 0xd2, 0x96, 0xdd, 0x7d, 0xff, 0x50, 0xd1, 0x70, 0x94, 0xe8, 0x17, 0xba, 0xe0, 0x05, 0xdd, 0x69, 0x50, 0x54, 0x80, 0x51, 0x72, 0x6c, 0xbe, 0x7b, 0x7a, 0xb2, 0x74, 0xcf, 0x46, 0xb3, 0xeb, 0x43, 0xef, 0x11, 0x12, 0x2a, 0x42, 0x65, 0xa9, 0x97, 0x4a, 0xdd, 0x51, 0x5f, 0x7f, 0x68, 0x47, 0xa1, 0xc3, 0x73, 0x2d, 0x02, 0xe3, 0x7d, 0xff, 0xe3, 0x86, 0x6b, 0x4f, 0x06, 0xde, 0xad, 0x99, 0xef, 0x51, 0x13, 0x53, 0xb5, 0xe7, 0x77, 0x61, 0xed, 0x40, 0x24, 0xa7, 0xf5, 0xfe, 0x76, 0x8d, 0x0c, 0x3b, 0x90, 0x5c, 0x08, 0xb0, 0xca, 0xf7, 0xf7, 0xd3, 0x3d, 0x97, 0x4e, 0x64, 0x89, 0x7c, 0x09, 0x9d, 0x8b, 0x52, 0xd4, 0xe1, 0x50, 0x45, 0x2d, 0xd6, 0xe1, 0x42, 0x81, 0x74, 0x6b, 0x22, 0xcf, 0x15, 0xee, 0x6b, 0x30, 0x9f, 0x8f, 0x19, 0x45, 0xba, 0xd0, 0x56, 0x01, 0xd6, 0x04, 0xb0, 0x56, 0xca, 0x81, 0x2e, 0x1d, 0x0f, 0xff, 0xad, 0x01, 0x71, 0x36, 0xee, 0x1c, 0x76, 0xd8, 0x04, 0xa1, 0xd8, 0x41, 0x00, 0xe4, 0xd5, 0x96, 0xf2, 0xf3, 0x70, 0x11, 0xc9, 0x37, 0xf0, 0x87, 0x19, 0xc3, 0x40, 0x7c, 0xa4, 0xe0, 0x3a, 0x1b, 0x1a, 0x25, 0xe4, 0xba, 0x52, 0x08, 0x72, 0x4d, 0xe0, 0x3e, 0x0d, 0x14, 0xd4, 0x15, 0xea, 0x80, 0x71, 0x95, 0x6f, 0xe5, 0x8a, 0xee, 0xfd, 0x3e, 0x2f, 0x6b, 0x59, 0x97, 0x4c, 0xc3, 0x25, 0xfa, 0x90, 0x34, 0xe9, 0x74, 0xbc, 0x07, 0xd7, 0xcd, 0xc3, 0x34, 0xc4, 0x1b, 0x96, 0xd7, 0x6b, 0x68, 0x0f, 0xc3, 0x34, 0xd4, 0x32, 0x9c, 0x4f, 0xb6, 0x31, 0x44, 0xfb, 0xce, 0x10, 0xbd, 0x0b, 0x46, 0xb8, 0x34, 0x2e, 0xec, 0xc6, 0x86, 0x63, 0xad, 0x6c, 0x0f, 0xe3, 0x55, 0x00, 0xcd, 0xf6, 0x74, 0xc2, 0x69, 0xa8, 0xba, 0x20, 0xa2, 0xa2, 0x19, 0x04, 0x73, 0x75, 0x83, 0x32, 0x5a, 0xe1, 0xa8, 0x2e, 0xea, 0x05, 0xaf, 0x68, 0xac, 0xd6, 0x80, 0x4e, 0x1c, 0x30, 0x4c, 0xbb, 0x21, 0x35, 0xec, 0xc5, 0xc2, 0x37, 0x4d, 0x16, 0x6f, 0xd4, 0x3b, 0xe8, 0x2c, 0x0e, 0x0c, 0xdf, 0xf5, 0x68, 0x03, 0xe6, 0xb4, 0x20, 0x67, 0xcb, 0xbd, 0x04, 0x03, 0xd2, 0x62, 0xf6, 0x77, 0xc8, 0xcc, 0x68, 0x12, 0x3b, 0x4b, 0x97, 0x86, 0x46, 0xfe, 0xf3, 0x4a, 0xeb, 0x17, 0x1d, 0x5f, 0xe8, 0x30, 0xf1, 0xcf, 0xed, 0xab, 0x92, 0x56, 0x67, 0xfb, 0xb8, 0xdf, 0xc7, 0xfa, 0xf9, 0x17, 0x31, 0xf5, 0xf9, 0xd4, 0x8e, 0xce, 0x5d, 0x94, 0x8f, 0xb2, 0xf5, 0xcf, 0x19, 0x9b, 0x14, 0x2e, 0x71, 0x24, 0xa6, 0x07, 0xc9, 0x9c, 0x00, 0x47, 0xa8, 0x96, 0xd5, 0xc6, 0xd2, 0x73, 0x92, 0x6e, 0x28, 0x35, 0xa6, 0x35, 0x54, 0xea, 0x71, 0x52, 0x2b, 0x76, 0x91, 0xa4, 0x22, 0x91, 0x17, 0x96, 0xc5, 0xbc, 0xd4, 0x56, 0x8a, 0xb6, 0xc0, 0xaf, 0x66, 0xa0, 0xa7, 0x5b, 0xb6, 0xd7, 0xd5, 0xf9, 0x3a, 0x77, 0xcf, 0x77, 0xd2, 0xfd, 0x44, 0x5d, 0xd2, 0xb0, 0x65, 0x5a, 0xcd, 0x06, 0x03, 0xe6, 0xc4, 0xd1, 0xe5, 0x6d, 0x47, 0xe5, 0xc3, 0xf0, 0x5f, 0x02, 0x8a, 0x77, 0x1f, 0xe8, 0xf6, 0xe4, 0xf2, 0x73, 0x21, 0x93, 0x16, 0x9c, 0xed, 0x98, 0x9c, 0x98, 0x13, 0x01, 0x54, 0x06, 0x72, 0xbb, 0x3b, 0x48, 0xfa, 0xed, 0xdf, 0x93, 0x3f, 0x25, 0xaa, 0x69, 0x6d, 0x15, 0x8d, 0x34, 0xe7, 0x10, 0x3b, 0x5e, 0x7f, 0x99, 0x94, 0x6a, 0xd6, 0x56, 0x86, 0xeb, 0x4a, 0x77, 0x97, 0x2d, 0x83, 0xf3, 0x79, 0x0d, 0x35, 0x1f, 0x2c, 0xb6, 0x8f, 0xd3, 0x3a, 0x3d, 0x5b, 0x24, 0x80, 0x7e, 0x26, 0xb7, 0x17, 0xb8, 0x42, 0x80, 0x1c, 0x70, 0x3c, 0xd5, 0xd9, 0x01, 0xd8, 0x1b, 0xfc, 0x4b, 0x46, 0x63, 0x19, 0x78, 0xa1, 0x1b, 0x8e, 0x97, 0x88, 0xd9, 0x6d, 0xb7, 0x8d, 0x7a, 0x24, 0x01, 0x94, 0x1f, 0x6a, 0x8d, 0xed, 0x2f, 0x87, 0x9b, 0x5b, 0x12, 0x5f, 0xfa, 0x79, 0xfe, 0xaa, 0x0b, 0xbd, 0xd2, 0x79, 0xc7, 0x20, 0x85, 0xd4, 0x4c, 0xf8, 0x22, 0xe8, 0xd6, 0x73, 0xeb, 0x2b, 0x7e, 0x08, 0x34, 0xe3, 0x22, 0x44, 0x2e, 0x01, 0x5e, 0x30, 0x75, 0xb2, 0x3f, 0xe5, 0x70, 0xcf, 0x83, 0x34, 0x52, 0x3c, 0x7b, 0xe9, 0xb1, 0xde, 0x6f, 0xda, 0x1f, 0xa0, 0xe7, 0x7d, 0x04, 0xf0, 0x69, 0x74, 0x59, 0x9f, 0x8f, 0x11, 0xee, 0xa1, 0xf4, 0x8c, 0xad, 0xa3, 0xb4, 0xaf, 0x63, 0x8b, 0x42, 0x9b, 0xdd, 0xa4, 0x67, 0xa9, 0xa3, 0x0e, 0xe0, 0xe0, 0x00, 0x91, 0xba, 0xb2, 0xcb, 0xef, 0xc9, 0x0a, 0x7c, 0xbb, 0xa3, 0x44, 0x4c, 0xc5, 0x6c, 0x00, 0x14, 0x48, 0x44, 0xae, 0xc6, 0x79, 0x97, 0x4c, 0xaa, 0x46, 0xbf, 0xaa, 0x0e, 0xb2, 0xf7, 0x88, 0xc1, 0xab, 0x1e, 0x44, 0x62, 0xbb, 0x1a, 0xa4, 0x25, 0xab, 0xa9, 0x2b, 0xbe, 0x3d, 0x35, 0x94, 0x0b, 0x01, 0x59, 0xea, 0xfd, 0x38, 0x4e, 0x3d, 0x20, 0x05, 0xc2, 0x76, 0x77, 0x46, 0xe7, 0x25, 0xa1, 0x6e, 0x5c, 0x7b, 0x3c, 0x4c, 0x37, 0x48, 0x5c, 0x4a, 0x76, 0x7e, 0x9f, 0x44, 0xf1, 0x49, 0xaf, 0x1d, 0x93, 0x5d, 0x80, 0x5a, 0x80, 0x78, 0x49, 0xef, 0x92, 0x78, 0xde, 0x4d, 0x97, 0xf2, 0x91, 0xf4, 0xe8, 0x89, 0x79, 0x2b, 0x0e, 0x87, 0xda, 0xad, 0x27, 0x86, 0xf0, 0x4c, 0xc8, 0x73, 0x59, 0xf9, 0x40, 0x36, 0x7e, 0x33, 0x24, 0x67, 0x6d, 0x29, 0x84, 0xaa, 0xc7, 0x5b, 0x2f, 0xb6, 0x95, 0xb3, 0xfa, 0xde, 0x11, 0x7f, 0x30, 0x41, 0xab, 0xe9, 0x1a, 0xd9, 0x74, 0x4d, 0x57, 0x9b, 0xae, 0x6d, 0xa3, 0x5c, 0xa0, 0xe8, 0xe0, 0x4a, 0x8b, 0xc7, 0x01, 0x5e, 0x2e, 0x20, 0x21, 0x03, 0x3d, 0x2b, 0xec, 0x60, 0x79, 0x98, 0xa6, 0xa9, 0xa3, 0xc8, 0x47, 0xe8, 0xdb, 0x95, 0xf0, 0xf4, 0x66, 0x9e, 0xdb, 0x42, 0xc0, 0xc0, 0xf1, 0x9e, 0x47, 0xc9, 0xfd, 0x2d, 0xb5, 0x78, 0x5d, 0x45, 0xbd, 0xae, 0x7b, 0x71, 0x8b, 0x87, 0x7b, 0x3c, 0x74, 0xcf, 0xfa, 0x4f, 0xba, 0x63, 0xc9, 0x74, 0xe7, 0xcd, 0xef, 0x56, 0x6e, 0x8c, 0x82, 0xb5, 0x10, 0x58, 0x57, 0x96, 0x68, 0xa1, 0x22, 0x0b, 0x20, 0xdd, 0x40, 0x07, 0x0b, 0x62, 0x86, 0x3c, 0xea, 0x43, 0x04, 0x3c, 0xdb, 0xf0, 0x1b, 0x42, 0x12, 0x32, 0xc4, 0xc2, 0x6c, 0x44, 0x44, 0x91, 0x71, 0xcf, 0x53, 0xa8, 0x2a, 0xa4, 0x45, 0x5d, 0xf5, 0xb4, 0x21, 0xf5, 0x03, 0x4b, 0xec, 0x96, 0x1e, 0xf3, 0xd3, 0x03, 0x86, 0x5f, 0xe2, 0x04, 0x50, 0x89, 0x3c, 0xdb, 0x06, 0x14, 0x37, 0x68, 0x55, 0x80, 0x35, 0x58, 0x2b, 0x71, 0x84, 0xea, 0x1f, 0x30, 0x91, 0xc8, 0x63, 0xf6, 0x53, 0xad, 0x02, 0x64, 0x31, 0x1c, 0xf5, 0x04, 0xbb, 0x9b, 0xe1, 0xda, 0xc2, 0x56, 0xd6, 0x59, 0x4f, 0xd0, 0x77, 0x39, 0xda, 0x01, 0x55, 0x1c, 0xf9, 0x8d, 0x0c, 0xf6, 0x01, 0x21, 0xc6, 0x06, 0x32, 0x6e, 0x10, 0x2c, 0x83, 0xed, 0xb4, 0xde, 0xc4, 0xd5, 0xe8, 0xf8, 0x36, 0x3c, 0x78, 0xec, 0x22, 0xaf, 0xcb, 0x60, 0x22, 0x9d, 0xa9, 0x89, 0x66, 0x37, 0x0d, 0x4d, 0x46, 0x0e, 0x4f, 0xfb, 0x3c, 0x85, 0xe2, 0xc8, 0x40, 0x31, 0xa7, 0x36, 0x2a, 0x9e, 0x32, 0xf7, 0xeb, 0xbb, 0x26, 0xec, 0x8e, 0xc3, 0x31, 0xf1, 0x54, 0x4b, 0xed, 0x30, 0x0f, 0x30, 0x42, 0x24, 0xea, 0x08, 0x63, 0x87, 0x32, 0xd7, 0x15, 0xf3, 0x3c, 0x44, 0x09, 0xdf, 0x06, 0x87, 0x17, 0x6d, 0x3d, 0x44, 0x72, 0x40, 0x87, 0xc8, 0x67, 0x15, 0xb1, 0x0e, 0xaa, 0x0b, 0x70, 0xd8, 0x24, 0x4d, 0x63, 0x48, 0xf0, 0x67, 0xfe, 0x95, 0xf8, 0x7b, 0xd7, 0xe1, 0x89, 0x29, 0xd3, 0x00, 0xa5, 0x42, 0x9f, 0xc9, 0x47, 0xea, 0x0c, 0xd1, 0xda, 0xc0, 0x20, 0x43, 0x38, 0xf4, 0xb0, 0x1d, 0x2c, 0xb3, 0xf5, 0x90, 0x08, 0x61, 0x19, 0x3b, 0xa1, 0xe9, 0xf8, 0x63, 0x26, 0xfe, 0x98, 0x89, 0xef, 0x73, 0x26, 0xfe, 0x88, 0x6b, 0xdf, 0x66, 0xb2, 0xfc, 0xbc, 0x2f, 0xae, 0x6d, 0xb6, 0xb3, 0x78, 0x1e, 0x7f, 0xb2, 0xab, 0xde, 0xed, 0x82, 0xe7, 0xb0, 0x72, 0x23, 0x6a, 0xa7, 0xac, 0xca, 0x3f, 0x6f, 0x83, 0x94, 0x66, 0x8d, 0x43, 0xf9, 0x1b, 0xcf, 0x78, 0xf3, 0x22, 0x26, 0x45, 0xb5, 0x89, 0xb7, 0x27, 0x4c, 0xfd, 0xfb, 0xc4, 0xae, 0x7c, 0xb7, 0x5d, 0x21, 0x92, 0xf8, 0x52, 0x48, 0xb1, 0xc9, 0x35, 0x80, 0xf8, 0x22, 0x99, 0x64, 0x24, 0x76, 0xb6, 0x2f, 0x90, 0xb8, 0xbc, 0x00, 0x71, 0x28, 0xd2, 0x23, 0x5f, 0x8d, 0xba, 0x4e, 0xeb, 0x8b, 0x09, 0xcc, 0x9a, 0x42, 0x4a, 0xdc, 0x66, 0x62, 0x4f, 0xf1, 0x62, 0x35, 0x6b, 0xf7, 0x78, 0x50, 0x39, 0xc3, 0x44, 0x6a, 0xfc, 0x65, 0x27, 0x86, 0x1e, 0x4a, 0x94, 0x83, 0xfd, 0x17, 0xab, 0xb8, 0x65, 0x82, 0xbc, 0x6a, 0x19, 0x98, 0x10, 0xc7, 0x50, 0x32, 0xc5, 0xe4, 0x4c, 0xf3, 0x93, 0x8d, 0x43, 0x8b, 0xc9, 0x7d, 0xf9, 0xb7, 0x7f, 0xff, 0x8f, 0xbf, 0xfa, 0xb2, 0x0c, 0xcc, 0x29, 0xac, 0x50, 0x2a, 0xe5, 0xfd, 0x4a, 0x85, 0x6d, 0x4f, 0x9c, 0x4b, 0x71, 0x89, 0x29, 0x1e, 0xbc, 0xe6, 0x27, 0x7f, 0x5f, 0x81, 0xae, 0xb7, 0x69, 0x11, 0xbe, 0xa3, 0x18, 0xd4, 0x3a, 0x35, 0x55, 0xc7, 0x9d, 0xde, 0x72, 0xc1, 0x4a, 0x8b, 0x2d, 0xd9, 0x8f, 0x32, 0xf7, 0x7c, 0xcf, 0x31, 0x80, 0xc3, 0x99, 0xce, 0xfb, 0xe8, 0x7b, 0xfa, 0x1f, 0x98, 0x02, 0x64, 0xf9, 0x78, 0xd3, 0xf3, 0xfa, 0x1c, 0x12, 0xe8, 0x80, 0x59, 0x60, 0x91, 0xe2, 0x7e, 0x8c, 0x0d, 0x05, 0x40, 0xd8, 0x01, 0x86, 0xd9, 0xc1, 0xb1, 0x3e, 0x96, 0x96, 0x34, 0x88, 0x7e, 0xcc, 0x6a, 0x1d, 0x01, 0xd3, 0x37, 0x1b, 0x32, 0x5f, 0x81, 0x0b, 0xc3, 0xf7, 0x14, 0x41, 0x04, 0xbb, 0x83, 0x8f, 0x2c, 0xa2, 0x47, 0x9d, 0xb3, 0x0e, 0x11, 0x3d, 0xfb, 0xc4, 0x3a, 0x8f, 0xd4, 0xe9, 0xba, 0x77, 0x26, 0x66, 0x67, 0x84, 0x1e, 0x93, 0x61, 0xe1, 0x5b, 0x86, 0xe2, 0x13, 0x65, 0x4f, 0x84, 0xc4, 0xe9, 0x13, 0x2e, 0x50, 0x67, 0x0d, 0xd2, 0x0b, 0x45, 0xc3, 0x89, 0x8b, 0xfc, 0x18, 0xd9, 0x84, 0xe0, 0xc7, 0x4f, 0xcd, 0xe7, 0x89, 0x99, 0x8b, 0x86, 0xba, 0x65, 0xc0, 0xfb, 0x49, 0xc6, 0x5b, 0x1b, 0xb0, 0x90, 0x7a, 0x9c, 0xa1, 0xbf, 0x1e, 0x3d, 0x7f, 0xd0, 0xf3, 0x1b, 0x63, 0x2c, 0xc3, 0x4e, 0xfb, 0xa5, 0x7f, 0xa0, 0xfa, 0xbf, 0x92, 0xd1, 0xe6, 0x85, 0x57, 0x23, 0x17, 0xd2, 0x88, 0xf8, 0xcd, 0xfa, 0x16, 0x08, 0xbd, 0x65, 0x4f, 0xce, 0x33, 0x19, 0x8c, 0xc4, 0x8f, 0x19, 0xea, 0xd8, 0xe1, 0xbd, 0x9f, 0x09, 0xd6, 0x4d, 0x1b, 0x3b, 0x4c, 0x5f, 0x42, 0x49, 0x58, 0x97, 0x66, 0xee, 0xdd, 0x38, 0x29, 0x76, 0x82, 0x81, 0xd9, 0x7c, 0x50, 0x28, 0x6c, 0x80, 0xfa, 0xb1, 0x34, 0xf0, 0xe0, 0xd2, 0xb6, 0x08, 0x50, 0xc7, 0x0e, 0x90, 0x90, 0x67, 0x7f, 0x3a, 0x72, 0x7f, 0x0d, 0x89, 0x06, 0xa1, 0x51, 0x0b, 0x16, 0x69, 0x86, 0xc8, 0x6b, 0xb0, 0xe4, 0x53, 0x3a, 0xb1, 0x3a, 0x28, 0x0c, 0x7f, 0x88, 0x63, 0x76, 0x07, 0x7e, 0x01, 0xa2, 0x9f, 0x36, 0xf4, 0x16, 0x0e, 0x7e, 0x06, 0x8b, 0xd1, 0xd3, 0x14, 0xc3, 0x8f, 0x96, 0xd0, 0x02, 0x46, 0xe6, 0x8c, 0x13, 0x76, 0x1e, 0x79, 0x53, 0x08, 0x42, 0x99, 0xb8, 0x6d, 0xeb, 0x91, 0x45, 0x0d, 0x0b, 0x07, 0x8e, 0xbb, 0xd2, 0x14, 0x0a, 0x5f, 0x49, 0x6f, 0x8f, 0x8c, 0x71, 0x72, 0xb2, 0xc2, 0xfc, 0x83, 0x56, 0xc1, 0xe4, 0x87, 0x16, 0xd9, 0x98, 0xa5, 0x99, 0x3b, 0x24, 0x1c, 0xbf, 0xd2, 0xdf, 0x0a, 0xe4, 0x54, 0x6b, 0x6f, 0x78, 0xa4, 0x0c, 0x19, 0xb0, 0x78, 0x3b, 0x60, 0xa5, 0x17, 0x1a, 0x01, 0xb0, 0x9b, 0xeb, 0xe4, 0x65, 0x00, 0xe7, 0xd3, 0x19, 0xe0, 0xa5, 0x37, 0x09, 0xde, 0x3c, 0x64, 0xc4, 0xa7, 0x9a, 0xe8, 0x5e, 0xe0, 0x11, 0x5e, 0x0f, 0x8d, 0x00, 0x5e, 0x26, 0x19, 0x82, 0xab, 0x8e, 0x85, 0xaa, 0xb2, 0xed, 0x15, 0xe1, 0xe5, 0xc7, 0x12, 0x78, 0xa6, 0xd3, 0x6b, 0x46, 0x4a, 0xb4, 0x1b, 0x43, 0xc2, 0xce, 0xb7, 0xb7, 0xa8, 0x9d, 0x4e, 0x48, 0x76, 0x83, 0x63, 0x8a, 0xc3, 0xe2, 0xfb, 0x78, 0x46, 0x30, 0x28, 0xb9, 0x96, 0xaf, 0x24, 0xd2, 0x0c, 0xc8, 0x7e, 0x53, 0x9f, 0x64, 0xfb, 0xdc, 0x40, 0xd8, 0xac, 0x9a, 0xa0, 0xf8, 0xb1, 0x27, 0xb7, 0x66, 0x38, 0xe1, 0x7a, 0x29, 0x7d, 0xe4, 0x11, 0xef, 0xdd, 0x3e, 0x2c, 0xdc, 0x13, 0xf0, 0xce, 0x11, 0x51, 0xd8, 0x70, 0x48, 0xb8, 0x44, 0xd0, 0x9f, 0x8d, 0x05, 0x7c, 0x7b, 0x8f, 0x82, 0x9b, 0x47, 0xe0, 0x5b, 0x4e, 0xa2, 0x05, 0x88, 0x2b, 0x8d, 0x05, 0x35, 0xa0, 0x2d, 0x78, 0xf7, 0x36, 0x99, 0xe7, 0xef, 0x35, 0x30, 0x5a, 0x0a, 0x56, 0x06, 0xbd, 0x1d, 0x4c, 0x69, 0xf0, 0x90, 0x47, 0xfc, 0x94, 0x78, 0x81, 0x82, 0x2a, 0x71, 0x78, 0x0a, 0x7d, 0x4d, 0xfc, 0x98, 0x70, 0x29, 0x23, 0x55, 0x2b, 0x06, 0xe7, 0x72, 0x7b, 0xc6, 0xe2, 0x10, 0x63, 0xfd, 0xb6, 0x87, 0x36, 0xfc, 0x01, 0xf7, 0x11, 0x92, 0x6d, 0xae, 0xb3, 0x98, 0x3c, 0xfc, 0x74, 0x05, 0x1b, 0x68, 0x7f, 0xe1, 0x39, 0x0b, 0x8b, 0x31, 0xb5, 0x39, 0x8b, 0x1a, 0xe5, 0x68, 0x76, 0x9d, 0x68, 0xc2, 0xf2, 0x6c, 0x8a, 0xfd, 0x23, 0x1a, 0xbe, 0x78, 0x5a, 0x9c, 0x42, 0x0e, 0x97, 0x12, 0xd0, 0x03, 0xe1, 0x4e, 0x06, 0x63, 0xca, 0x1c, 0x35, 0xe8, 0x36, 0x9e, 0xae, 0x7d, 0xd4, 0x14, 0xeb, 0x23, 0xc0, 0x9e, 0x4a, 0xd7, 0x9b, 0x44, 0xdf, 0x92, 0x76, 0x22, 0xca, 0xc5, 0x76, 0x3c, 0x19, 0x3d, 0x43, 0xca, 0xea, 0xdc, 0x80, 0x5b, 0xa8, 0xe5, 0xee, 0xc3, 0x05, 0x0d, 0x43, 0x10, 0x34, 0x2d, 0xc8, 0xe9, 0x5b, 0xc7, 0xcb, 0xe2, 0xb7, 0xcd, 0x09, 0xfb, 0xdc, 0x76, 0x33, 0x10, 0x02, 0x6f, 0x87, 0x80, 0x16, 0xe0, 0x2c, 0xb2, 0x1b, 0xf8, 0xdd, 0x59, 0x47, 0x6f, 0x67, 0x85, 0xfd, 0x19, 0x32, 0xb1, 0xf3, 0x2d, 0xfc, 0x44, 0x7c, 0xc2, 0x5f, 0x93, 0x85, 0x11, 0x19, 0xd0, 0x44, 0xf9, 0xd5, 0x9f, 0xca, 0x4c, 0xfa, 0x83, 0x08, 0x2a, 0xe0, 0xb0, 0xfa, 0xd7, 0x49, 0xee, 0x0a, 0x0f, 0xb8, 0xcc, 0xbe, 0xd6, 0x91, 0x9d, 0xe4, 0xf8, 0xf3, 0xb7, 0xba, 0x88, 0x3a, 0xe6, 0x72, 0x68, 0x82, 0xd8, 0x5f, 0xa7, 0x5c, 0xce, 0x8b, 0x86, 0x16, 0x6b, 0x63, 0x1f, 0xcd, 0xb0, 0x96, 0xde, 0x1a, 0xea, 0xc1, 0x8f, 0x89, 0xc6, 0x46, 0x22, 0x02, 0xa2, 0x3f, 0x4b, 0x44, 0x9e, 0xb8, 0xf1, 0x42, 0x57, 0x5d, 0xbf, 0x28, 0xe5, 0x5f, 0x66, 0x40, 0x4d, 0x19, 0xcc, 0x20, 0x66, 0x94, 0xc8, 0x1d, 0xcb, 0xc3, 0xec, 0x38, 0x72, 0x6a, 0x32, 0xa9, 0x0c, 0x84, 0x8c, 0x92, 0x12, 0x38, 0xd4, 0x97, 0x53, 0xc6, 0xb3, 0x0d, 0xfc, 0x16, 0x88, 0x8f, 0x6b, 0xb4, 0x66, 0xb8, 0x1f, 0xe2, 0x16, 0x85, 0xea, 0xb9, 0xb4, 0x35, 0xa3, 0xfd, 0x47, 0x9b, 0xf4, 0x4c, 0x78, 0xe2, 0xd0, 0xb3, 0xd0, 0x0b, 0x47, 0xde, 0x3d, 0x5f, 0x64, 0x25, 0x30, 0x41, 0x11, 0xbb, 0x27, 0xc2, 0x60, 0x33, 0x65, 0x2a, 0x75, 0x04, 0x2c, 0x1c, 0x90, 0xfa, 0x8b, 0xfb, 0xbc, 0xeb, 0xc5, 0xe1, 0x6d, 0x13, 0x9d, 0x54, 0x45, 0x17, 0xa9, 0x49, 0x59, 0xc0, 0x99, 0x9c, 0x84, 0x3e, 0x86, 0xa0, 0x05, 0xf9, 0x42, 0x90, 0xa2, 0x7c, 0x8c, 0xc4, 0xfc, 0x03, 0xe0, 0x28, 0xf6, 0x0b, 0x0d, 0xde, 0xb7, 0xce, 0x67, 0x53, 0xf7, 0x61, 0x31, 0xc0, 0x5a, 0x4e, 0xfd, 0xb2, 0x9e, 0x5b, 0x41, 0xaf, 0x77, 0x6f, 0x17, 0x3b, 0x88, 0xeb, 0x53, 0xf6, 0x77, 0x67, 0x27, 0x25, 0x9c, 0x6b, 0xb6, 0xda, 0x59, 0xee, 0x6b, 0x4f, 0x09, 0x4a, 0x64, 0x14, 0x80, 0xeb, 0xfa, 0xb1, 0xf9, 0xa7, 0xab, 0x85, 0x1c, 0x28, 0x9e, 0x86, 0xd9, 0xd8, 0x43, 0xb7, 0x57, 0xeb, 0xc9, 0x9e, 0x28, 0x44, 0x5c, 0xaa, 0x9d, 0x1c, 0xeb, 0x73, 0xb5, 0x4e, 0x5d, 0x4c, 0x2c, 0x7b, 0x1b, 0x57, 0xca, 0xc8, 0xd4, 0x41, 0xb9, 0x6f, 0xd8, 0x38, 0xa1, 0x5a, 0x02, 0xc6, 0x06, 0x73, 0x19, 0xcb, 0xac, 0x7d, 0xb6, 0x76, 0xf8, 0x5e, 0xb0, 0xd5, 0xb0, 0x77, 0x1b, 0xd4, 0xec, 0x3f, 0x1c, 0xb3, 0x77, 0x3b, 0x66, 0xff, 0xf0, 0xd6, 0xe4, 0xf6, 0xf5, 0x9b, 0x7e, 0x1c, 0x72, 0xfb, 0x3f, 0xfc, 0x6a, 0x0b, 0x0a, 0xc2, 0x69, 0xca, 0xa4, 0x27, 0x48, 0x22, 0xa1, 0x77, 0xad, 0xeb, 0x76, 0x5f, 0x02, 0x57, 0x00, 0x31, 0x3f, 0x8e, 0xb0, 0x73, 0x70, 0x8a, 0xa1, 0xe7, 0xbb, 0x60, 0x41, 0x2e, 0xa6, 0x03, 0xe2, 0xce, 0x8d, 0x0e, 0x0b, 0xe4, 0x94, 0x5f, 0x11, 0x7d, 0xb8, 0xca, 0xe0, 0xc4, 0x6b, 0x11, 0xba, 0x5b, 0xea, 0x24, 0x6c, 0xd9, 0xd6, 0x0a, 0x84, 0x76, 0x13, 0x6d, 0x78, 0x21, 0xa5, 0x7a, 0xb5, 0xc6, 0x54, 0x9b, 0x5f, 0x29, 0xf3, 0xaa, 0xb3, 0xe5, 0xb6, 0x05, 0xf4, 0xab, 0x87, 0x63, 0xc8, 0xf7, 0x24, 0x43, 0xa7, 0x55, 0x70, 0x83, 0xd2, 0x86, 0x1f, 0x7e, 0xfa, 0xeb, 0xbf, 0xfe, 0x84, 0x36, 0xb7, 0x86, 0xbe, 0xb2, 0xf5, 0xe4, 0x7c, 0xc1, 0x14, 0x5f, 0x8b, 0x07, 0x15, 0x5e, 0x6b, 0x4b, 0x23, 0x1b, 0x43, 0x93, 0xb0, 0x5e, 0x88, 0x81, 0x9e, 0x17, 0x4e, 0x49, 0x00, 0x26, 0x22, 0xc2, 0xb7, 0xdd, 0x55, 0x7d, 0x89, 0x78, 0xaa, 0x75, 0x1f, 0xf4, 0x6a, 0xd5, 0xd5, 0xa3, 0xd2, 0xea, 0xd9, 0x8a, 0x72, 0x0f, 0x1a, 0xb0, 0xcb, 0x51, 0x86, 0x3b, 0xf8, 0x2d, 0x80, 0xbb, 0xd7, 0x79, 0x3e, 0xc6, 0x89, 0xec, 0x08, 0x7f, 0x59, 0xea, 0xba, 0xf7, 0x78, 0x61, 0x7e, 0x9e, 0xf7, 0xa9, 0xa5, 0x46, 0x68, 0x7d, 0x72, 0xeb, 0x60, 0x83, 0xdc, 0xa7, 0x1f, 0xa7, 0xe8, 0x6d, 0x9b, 0xc0, 0xdf, 0xbe, 0xf1, 0x29, 0x6a, 0x3f, 0xd4, 0x29, 0xfa, 0x6b, 0xfd, 0x14, 0x75, 0x60, 0x0e, 0x03, 0xdd, 0x51, 0x5f, 0xd9, 0x77, 0xad, 0x6a, 0xe7, 0x87, 0x86, 0x15, 0x31, 0xe0, 0xc2, 0x23, 0x80, 0x80, 0x07, 0xb1, 0x0b, 0xd2, 0x5e, 0x02, 0xc7, 0x56, 0x27, 0x17, 0x4c, 0xb4, 0xc6, 0xc8, 0x2b, 0xe8, 0xc0, 0x01, 0x19, 0xd8, 0x93, 0x16, 0xc1, 0x81, 0xe6, 0x48, 0x29, 0x06, 0x30, 0x0e, 0xec, 0x26, 0x33, 0x8d, 0xb4, 0x6a, 0xb4, 0x89, 0x9d, 0x5f, 0x19, 0x0c, 0xfa, 0x92, 0x55, 0x1b, 0xb6, 0xf6, 0x28, 0xfa, 0x9d, 0xb2, 0x51, 0x1f, 0xbb, 0xf7, 0x3f, 0xf6, 0x8e, 0xdb, 0xf6, 0x8e, 0x5f, 0xef, 0x85, 0x46, 0xbc, 0xc4, 0xc6, 0x51, 0x3f, 0xe8, 0x07, 0xda, 0x38, 0x64, 0x5e, 0x42, 0x0a, 0xd9, 0x81, 0xff, 0xea, 0x44, 0x40, 0x75, 0x76, 0x60, 0x7d, 0x25, 0xca, 0x22, 0x74, 0xbb, 0xf5, 0xdc, 0xe2, 0xdb, 0x13, 0x9b, 0x09, 0x71, 0xe6, 0x18, 0x7c, 0x84, 0x99, 0x15, 0x23, 0x06, 0x61, 0xd8, 0xbd, 0xdd, 0xc5, 0x3f, 0x32, 0x63, 0x8f, 0x5a, 0xbc, 0x84, 0x71, 0x5e, 0x8f, 0x18, 0xa6, 0x40, 0x01, 0x9e, 0x82, 0xf9, 0x8b, 0x69, 0x23, 0x8b, 0xc7, 0x9a, 0xdd, 0xbc, 0x43, 0x5f, 0x67, 0x7c, 0xaa, 0x9c, 0x04, 0x98, 0x4f, 0xc8, 0xdb, 0x54, 0xad, 0x03, 0xc7, 0x31, 0xa6, 0x46, 0xbc, 0xc6, 0xd7, 0x6d, 0xd8, 0x0d, 0xba, 0xf6, 0x09, 0x1a, 0x37, 0x10, 0x12, 0xa1, 0xd8, 0x43, 0x3c, 0x51, 0x92, 0x40, 0xc1, 0x07, 0x0e, 0x4c, 0x1f, 0xcf, 0xb9, 0x8d, 0xa5, 0xe5, 0x25, 0x6c, 0xc8, 0x07, 0x88, 0x39, 0xd1, 0xeb, 0xf1, 0x6c, 0x12, 0x24, 0x5e, 0x74, 0x56, 0x2a, 0x22, 0x24, 0xe2, 0x97, 0x69, 0x42, 0x24, 0x4a, 0x4d, 0xb2, 0x14, 0x89, 0x54, 0xd3, 0xab, 0xce, 0xfe, 0x65, 0x68, 0x3c, 0xc1, 0x07, 0xd2, 0x92, 0xed, 0x1f, 0x4a, 0xb1, 0x8a, 0xec, 0x2b, 0x2c, 0x83, 0x63, 0xf6, 0xf7, 0x5c, 0x31, 0x96, 0xc8, 0x07, 0x93, 0x9e, 0xcb, 0x4a, 0xb8, 0x58, 0x44, 0x5c, 0x2c, 0x90, 0xd6, 0x79, 0xd8, 0x2c, 0xd5, 0xdb, 0x3b, 0x2e, 0xca, 0xc5, 0xed, 0xd6, 0x3a, 0x14, 0xe4, 0xb8, 0xc0, 0xa4, 0x9b, 0x06, 0xd2, 0x98, 0xed, 0x83, 0xdb, 0xd0, 0x90, 0x0b, 0xc1, 0x8c, 0x0d, 0x5a, 0xa6, 0x79, 0x2d, 0x1b, 0x99, 0x99, 0x88, 0x62, 0xd8, 0x35, 0x76, 0x7a, 0x82, 0x75, 0xbd, 0x64, 0x5f, 0xa8, 0xc3, 0x2d, 0xea, 0x58, 0x77, 0xc4, 0x5e, 0xf5, 0x22, 0x82, 0xa0, 0xcc, 0x6b, 0x0b, 0x57, 0xa3, 0xe7, 0x13, 0x67, 0xda, 0x18, 0x0b, 0xd9, 0x76, 0xdf, 0xf6, 0xd2, 0xb0, 0x88, 0xdc, 0xed, 0xcb, 0xca, 0xc6, 0xdc, 0xf3, 0x4e, 0x25, 0xdb, 0xc5, 0xc0, 0x92, 0x3a, 0xf7, 0x59, 0x73, 0xbd, 0x77, 0x9f, 0x4b, 0xff, 0xb2, 0xe5, 0x16, 0x72, 0xa8, 0xc3, 0xb1, 0xb8, 0xa7, 0x8e, 0xf0, 0xc5, 0xf3, 0x5d, 0xcc, 0x9d, 0x14, 0x5b, 0xa5, 0xfd, 0x3e, 0xf7, 0x8c, 0xa0, 0x59, 0x40, 0x98, 0xfc, 0xab, 0x3e, 0x9f, 0x9a, 0xe6, 0xbc, 0x18, 0xd5, 0x40, 0x26, 0x8c, 0xb3, 0x41, 0x11, 0xe8, 0x6a, 0x88, 0x13, 0xad, 0x65, 0x13, 0x42, 0xf4, 0xf6, 0x11, 0x6f, 0xc6, 0x78, 0x1a, 0xf4, 0xcc, 0x23, 0x85, 0x6e, 0xee, 0x55, 0x58, 0xe7, 0xff, 0x22, 0xca, 0xc0, 0xcc, 0x39, 0xd6, 0xa3, 0xf2, 0x65, 0x39, 0xed, 0xc3, 0xfb, 0x51, 0x7c, 0xa3, 0xac, 0xd2, 0x01, 0xb2, 0x96, 0x87, 0xbe, 0x38, 0x65, 0x9a, 0x67, 0xe2, 0x78, 0xbe, 0x77, 0x29, 0xfe, 0xf1, 0x6f, 0xb4, 0x98, 0x8b, 0x0f, 0x90, 0xa0, 0x9e, 0xc7, 0x64, 0x09, 0x32, 0xb3, 0x73, 0xe7, 0x89, 0xc2, 0x62, 0xe0, 0x7a, 0xf4, 0x29, 0xaf, 0x28, 0x8e, 0x86, 0xde, 0x01, 0xd8, 0x15, 0xae, 0x2a, 0xfe, 0xee, 0xa6, 0xee, 0x9b, 0x2d, 0x91, 0xfa, 0x45, 0x8f, 0x31, 0x9b, 0x17, 0x93, 0x4a, 0x5c, 0x9e, 0xdf, 0xe0, 0xe5, 0x7e, 0x27, 0xab, 0xe5, 0xbe, 0x16, 0x1f, 0xe0, 0x48, 0x51, 0x19, 0xc3, 0x3d, 0x4f, 0x2a, 0x18, 0x51, 0x31, 0x3d, 0x0c, 0xcf, 0xaa, 0x47, 0x06, 0x94, 0xcd, 0xc0, 0x0c, 0xcd, 0xaf, 0xc8, 0xbc, 0xd3, 0x7b, 0x2e, 0x50, 0x98, 0x07, 0x2a, 0x32, 0x43, 0xe1, 0xb9, 0x41, 0x97, 0x8c, 0x4e, 0x62, 0x20, 0x72, 0xa8, 0xed, 0x39, 0x94, 0x00, 0x43, 0x84, 0x97, 0x2a, 0x44, 0x31, 0xe1, 0xbd, 0x8a, 0xb7, 0x45, 0x3d, 0x85, 0x54, 0x90, 0x5f, 0x11, 0x7a, 0xba, 0x41, 0x32, 0x4d, 0xd7, 0x92, 0xf3, 0x38, 0xfd, 0x3b, 0x5f, 0x42, 0xb7, 0x2d, 0xbb, 0x9f, 0x61, 0xd9, 0x05, 0xe9, 0x4a, 0x71, 0x71, 0xd5, 0x35, 0x63, 0xbf, 0xf3, 0x4a, 0x6b, 0x54, 0xd2, 0xee, 0xb8, 0x48, 0xfd, 0x5c, 0xb1, 0x48, 0x2b, 0xf7, 0x8e, 0x4f, 0x27, 0xc3, 0xf2, 0x27, 0x51, 0xfa, 0xeb, 0x6b, 0x47, 0x40, 0x23, 0xb9, 0x1a, 0xa2, 0xeb, 0x16, 0xc1, 0xc7, 0x1d, 0xc2, 0x48, 0x6b, 0xd6, 0x33, 0x34, 0x2d, 0x31, 0xab, 0xaa, 0x1c, 0x18, 0xde, 0x84, 0xb0, 0x43, 0x46, 0x32, 0xca, 0xd9, 0x18, 0x4d, 0x9c, 0x68, 0x11, 0x4b, 0x84, 0x95, 0xa9, 0x97, 0xf2, 0xce, 0xae, 0xf3, 0x1e, 0xd6, 0xc9, 0x17, 0x1b, 0x8a, 0x48, 0x42, 0xde, 0xc4, 0xb2, 0x7c, 0xd1, 0xcb, 0x97, 0x1d, 0xe5, 0xdf, 0xdf, 0xe2, 0xac, 0xb3, 0xe1, 0xe8, 0xb2, 0xbb, 0xc5, 0x05, 0xb0, 0x4b, 0x88, 0xe1, 0x12, 0x51, 0x51, 0x58, 0x67, 0x4e, 0xdc, 0xcc, 0x6c, 0x54, 0xa7, 0xd5, 0xe7, 0x4c, 0xba, 0xf8, 0x57, 0x0d, 0x4c, 0x60, 0x26, 0x6a, 0xc6, 0x04, 0x3e, 0x4d, 0x3d, 0x05, 0x6a, 0x59, 0x33, 0x7a, 0x2e, 0x9f, 0x45, 0xa3, 0x15, 0xa1, 0x63, 0xb8, 0x37, 0x58, 0x48, 0xc2, 0x3c, 0x00, 0xf4, 0x18, 0xb3, 0x31, 0x01, 0xc6, 0x1e, 0x32, 0xcb, 0x16, 0xe7, 0xae, 0x5b, 0x1c, 0x21, 0x71, 0x15, 0x49, 0x87, 0x00, 0x40, 0x94, 0x75, 0xd5, 0x06, 0xc9, 0x4d, 0x09, 0xd7, 0xea, 0x75, 0x2f, 0x12, 0x41, 0xa7, 0x35, 0x97, 0x67, 0x92, 0x1d, 0x87, 0xef, 0x7c, 0x2d, 0xbe, 0xd9, 0x9a, 0xaf, 0xd3, 0xe5, 0x58, 0x62, 0xba, 0x76, 0xcd, 0xe3, 0xf4, 0xb9, 0x2c, 0x27, 0x4c, 0xda, 0xd2, 0xed, 0x63, 0x0b, 0x24, 0x81, 0xfb, 0xf6, 0x0e, 0xfe, 0xc4, 0x9f, 0x74, 0x41, 0x6b, 0x4c, 0xe4, 0x14, 0x83, 0x8b, 0xee, 0x50, 0x66, 0x2e, 0xaa, 0xeb, 0x81, 0x8b, 0x0f, 0x36, 0x52, 0x0e, 0x74, 0xec, 0x69, 0x07, 0xf1, 0x89, 0x79, 0x53, 0x75, 0x16, 0xe1, 0x5a, 0x28, 0x4a, 0xf7, 0xd1, 0xe8, 0x0a, 0xe3, 0x0c, 0x12, 0x45, 0x34, 0x20, 0xa1, 0xfc, 0x64, 0x19, 0x55, 0x54, 0x2f, 0xed, 0x4c, 0x35, 0x34, 0x80, 0xcf, 0xdf, 0x3f, 0xb6, 0x60, 0x85, 0xd4, 0x44, 0xad, 0x4a, 0x3c, 0xfb, 0xf3, 0x06, 0x06, 0xe8, 0x63, 0xc0, 0x79, 0x6e, 0x5b, 0xa9, 0xbf, 0x7f, 0x38, 0xda, 0x68, 0x77, 0xae, 0xd4, 0xfb, 0xe6, 0x79, 0xff, 0xc6, 0x75, 0x7a, 0x7d, 0x9c, 0x40, 0xde, 0x9f, 0x65, 0x76, 0xbe, 0x19, 0xf8, 0x3c, 0x93, 0xfb, 0x7f, 0x47, 0xdc, 0x9f, 0x2e, 0x9b, 0xa2, 0x0d, 0x6b, 0x88, 0xc0, 0x06, 0x48, 0xf9, 0x81, 0x6f, 0x0c, 0xe1, 0xed, 0x90, 0x70, 0x44, 0xb9, 0x6b, 0x44, 0x25, 0x90, 0xf5, 0x18, 0x9c, 0x1c, 0x82, 0x13, 0xda, 0x89, 0x1c, 0x64, 0x6b, 0xb4, 0xaf, 0x48, 0x5d, 0xd3, 0xce, 0xef, 0x8c, 0x09, 0x8f, 0xb4, 0xef, 0xca, 0x19, 0xda, 0x1a, 0x82, 0xee, 0xf2, 0xe2, 0xb9, 0xd0, 0xaf, 0xcc, 0xe1, 0xc0, 0xd2, 0x28, 0x9e, 0x74, 0xc2, 0xcd, 0xb8, 0x8b, 0xc8, 0x38, 0xea, 0x14, 0x82, 0x71, 0x07, 0xf5, 0xef, 0x2d, 0x73, 0xf2, 0x21, 0x27, 0x75, 0x1c, 0x92, 0x36, 0x0e, 0x30, 0xc1, 0x8e, 0xf6, 0xea, 0xb3, 0xf2, 0xec, 0x8c, 0x3b, 0x2e, 0xdc, 0xaa, 0xf4, 0x1d, 0xb7, 0x89, 0x8c, 0x7a, 0xd0, 0xe9, 0xb8, 0x3e, 0x1a, 0xb7, 0xca, 0x5f, 0x36, 0x93, 0xeb, 0xf8, 0xee, 0x6b, 0x5a, 0x3c, 0xda, 0x5f, 0x91, 0x00, 0xf4, 0xb6, 0x6f, 0x1a, 0x8d, 0x3e, 0x91, 0x8c, 0x32, 0x91, 0xee, 0xde, 0x74, 0x44, 0x25, 0x53, 0x3e, 0x9e, 0x0d, 0x65, 0x19, 0x3e, 0x5d, 0x4f, 0xe0, 0x26, 0xd0, 0xb7, 0x19, 0xcc, 0x3f, 0x56, 0x2f, 0xca, 0x3a, 0x0d, 0xe8, 0xba, 0xae, 0x82, 0xc1, 0x1b, 0x6d, 0x05, 0x94, 0x96, 0xa7, 0x71, 0x37, 0xd7, 0xe7, 0x2d, 0x9f, 0xf1, 0xdd, 0x95, 0x81, 0x4f, 0x5c, 0x4f, 0xde, 0x9b, 0xa4, 0x88, 0x04, 0xfe, 0xdc, 0x86, 0xbe, 0x3d, 0xa7, 0x97, 0x34, 0x9d, 0xb9, 0x7b, 0x83, 0x72, 0xd7, 0x3c, 0x92, 0x11, 0xbd, 0x20, 0xfd, 0x9e, 0x25, 0xdb, 0xa5, 0x25, 0xcb, 0x81, 0x74, 0x85, 0x86, 0xa9, 0x78, 0x69, 0x63, 0x18, 0x3e, 0x29, 0x67, 0xc1, 0x9f, 0x45, 0x7d, 0x03, 0xe2, 0x16, 0x9c, 0x12, 0x48, 0xe3, 0x31, 0xff, 0x42, 0xe4, 0x46, 0xbe, 0xff, 0xa6, 0x0e, 0xfd, 0x78, 0x72, 0x3d, 0x3f, 0xef, 0xd4, 0x85, 0x0a, 0x20, 0x29, 0xcf, 0x75, 0x61, 0xe3, 0x11, 0xe9, 0x8a, 0x9a, 0xeb, 0x6a, 0xc4, 0xe4, 0xfe, 0xd8, 0xb8, 0x70, 0x11, 0x6a, 0x14, 0x35, 0x36, 0x8f, 0x65, 0x97, 0xbb, 0x8d, 0x72, 0x44, 0x94, 0x62, 0x3d, 0x5b, 0x04, 0x87, 0x1b, 0x58, 0xe3, 0x96, 0x48, 0xa5, 0x90, 0xeb, 0x14, 0x4d, 0xfb, 0xda, 0x06, 0xe8, 0xf4, 0x40, 0x8e, 0x3b, 0x53, 0x0e, 0xd4, 0xd5, 0x3b, 0x16, 0xf8, 0x23, 0x41, 0xfd, 0x3c, 0x3e, 0x17, 0x6c, 0x68, 0x1c, 0x9e, 0x48, 0xb8, 0x0a, 0x79, 0xf0, 0x70, 0x15, 0x7b, 0x6e, 0xe0, 0x1e, 0x48, 0xf2, 0xb5, 0xb9, 0xfe, 0xd6, 0x35, 0xe7, 0xf8, 0xd8, 0xda, 0x84, 0x4a, 0xb0, 0x0e, 0x9e, 0xd3, 0x98, 0xc6, 0xcd, 0x4c, 0xe6, 0x98, 0x6b, 0x96, 0x08, 0x1e, 0x44, 0x17, 0x83, 0xd3, 0x30, 0x31, 0xca, 0x52, 0xdd, 0x0d, 0x44, 0x78, 0x02, 0x52, 0x85, 0xf6, 0x97, 0x92, 0x99, 0x56, 0x2b, 0x8f, 0x26, 0x41, 0x36, 0x7e, 0x66, 0x02, 0x01, 0xbc, 0x65, 0x04, 0x4e, 0xd1, 0xce, 0x98, 0x13, 0x0c, 0xcf, 0x06, 0xd0, 0x72, 0xc6, 0xa7, 0x10, 0xb1, 0x98, 0xa9, 0x9e, 0xd1, 0xa5, 0xfa, 0xf1, 0xb0, 0x2c, 0xa6, 0xc3, 0x97, 0x8c, 0x4d, 0x52, 0x6e, 0xd3, 0xa1, 0xe7, 0xee, 0xb5, 0x44, 0x09, 0x64, 0xd4, 0xb2, 0x98, 0x2e, 0x5d, 0x8d, 0x3d, 0x83, 0xed, 0x00, 0x57, 0x03, 0x40, 0x23, 0x21, 0xe9, 0x08, 0x72, 0xac, 0x6d, 0x69, 0x86, 0x19, 0x3b, 0x45, 0x1c, 0x37, 0x85, 0x81, 0x20, 0xce, 0x35, 0x6f, 0xf9, 0xd9, 0xf0, 0x7b, 0x48, 0xd7, 0x2e, 0x16, 0xea, 0x9a, 0x49, 0x2c, 0x91, 0xba, 0xde, 0x00, 0xe4, 0x10, 0xfc, 0x5b, 0x62, 0xea, 0x35, 0xe8, 0x3c, 0x1b, 0xeb, 0x6d, 0x0f, 0xde, 0xcc, 0xb6, 0x31, 0x9d, 0x61, 0xad, 0xf0, 0x23, 0x41, 0x3f, 0x21, 0x9f, 0x9c, 0x06, 0xac, 0x87, 0x56, 0x5a, 0xfe, 0x3e, 0xbf, 0x12, 0xa6, 0x6a, 0x03, 0x05, 0xb4, 0xe7, 0xf3, 0x68, 0xe4, 0xc3, 0x2a, 0xc0, 0xaf, 0x32, 0x42, 0xbb, 0x6c, 0xc8, 0x96, 0xdb, 0x88, 0xa4, 0x99, 0xd1, 0x14, 0x34, 0xf8, 0xb3, 0xe2, 0x7c, 0x07, 0x3a, 0x05, 0x9e, 0xfe, 0x0c, 0xc5, 0x59, 0x1e, 0x0b, 0xc6, 0xad, 0x02, 0x23, 0x34, 0x75, 0xc5, 0xb9, 0x8a, 0xe8, 0x51, 0xba, 0x26, 0x36, 0xd2, 0x79, 0x32, 0x7c, 0x09, 0x16, 0x90, 0xa3, 0xf7, 0xaa, 0xa9, 0xa9, 0xb8, 0x79, 0xa4, 0x20, 0x0c, 0x65, 0xce, 0x52, 0x06, 0xfa, 0xd0, 0x00, 0x0d, 0xdb, 0x81, 0x99, 0x8f, 0x45, 0xa0, 0x73, 0x6e, 0x13, 0x7d, 0x25, 0xf2, 0x07, 0xe0, 0x69, 0x05, 0xbc, 0x2c, 0xa0, 0x4d, 0x4f, 0x2e, 0xea, 0xb8, 0x45, 0xd2, 0x42, 0x5a, 0x1b, 0x4b, 0x94, 0xa5, 0x59, 0xf7, 0xc7, 0x7a, 0x16, 0xde, 0xe5, 0x23, 0x4e, 0x73, 0xae, 0x2c, 0xe6, 0x88, 0xb6, 0xec, 0x0c, 0xc0, 0x89, 0x89, 0xb9, 0x7c, 0x91, 0x98, 0x2f, 0x90, 0x4c, 0x0f, 0x38, 0xdf, 0x0e, 0x48, 0xbe, 0xb9, 0xdc, 0xcd, 0x56, 0x5b, 0x59, 0xb1, 0xbc, 0x7f, 0x5d, 0xb5, 0x79, 0x09, 0x7c, 0xcf, 0xf5, 0x8f, 0x4b, 0xeb, 0x7b, 0x7d, 0x22, 0x7b, 0x5e, 0x02, 0xb2, 0x67, 0xeb, 0x92, 0x09, 0x9d, 0x84, 0xa3, 0x39, 0xee, 0xf3, 0x88, 0xe5, 0x28, 0xf3, 0xfe, 0x83, 0xd7, 0xb5, 0x6f, 0x97, 0x7c, 0xe3, 0x58, 0xd2, 0x98, 0xa2, 0x7f, 0x06, 0x86, 0x98, 0x76, 0x64, 0x1c, 0xc8, 0x4c, 0x50, 0x56, 0xda, 0x85, 0x06, 0xf8, 0x79, 0xda, 0x5f, 0x81, 0x3f, 0x02, 0x97, 0x21, 0xf2, 0x83, 0x9f, 0x6f, 0xa9, 0x60, 0x60, 0x64, 0xd8, 0x4f, 0x01, 0x1a, 0xca, 0x5b, 0xaa, 0x30, 0x9a, 0xe2, 0x6d, 0x44, 0x18, 0xcf, 0x2b, 0xf6, 0x5b, 0xe1, 0xdd, 0xf1, 0x28, 0x9d, 0x11, 0x0f, 0x2c, 0xdf, 0x9c, 0xa8, 0xa4, 0xa0, 0x6a, 0x8b, 0x6f, 0x04, 0x89, 0xa1, 0xb1, 0x10, 0x43, 0x0b, 0x62, 0x53, 0xa3, 0x3c, 0xa0, 0x6b, 0x2e, 0x03, 0xd1, 0xd7, 0x69, 0xdd, 0x33, 0xec, 0xaa, 0xa2, 0xd6, 0xcb, 0xf3, 0x79, 0xe9, 0x45, 0xc7, 0xa6, 0xdd, 0x17, 0xe6, 0x78, 0x40, 0x1c, 0x47, 0xfd, 0x31, 0x3b, 0x61, 0x82, 0xcc, 0x2b, 0x5a, 0xc0, 0x18, 0xb3, 0xd0, 0x7f, 0xf2, 0x0c, 0x4a, 0x80, 0x9e, 0xfc, 0x29, 0x2d, 0xbc, 0x5f, 0x7e, 0xf9, 0xff, 0x18, 0x24, 0x4a, 0x30, 0xfd, 0xd0, 0x04, 0x00 }; z_const size_t kPhoneNumberMetaDataCompressedLength = sizeof(kPhoneNumberMetaData); z_const size_t kPhoneNumberMetaDataExpandedLength = 315645; #endif // TESTING #if SHORT_NUMBER_SUPPORT z_const Bytef kShortNumberMetaData[] = { 0x1f, 0x8b, 0x08, 0x08, 0x5a, 0x2a, 0xbe, 0x5b, 0x00, 0x03, 0x53, 0x68, 0x6f, 0x72, 0x74, 0x4e, 0x75, 0x6d, 0x62, 0x65, 0x72, 0x4d, 0x65, 0x74, 0x61, 0x44, 0x61, 0x74, 0x61, 0x2e, 0x6a, 0x73, 0x6f, 0x6e, 0x00, 0xed, 0x7d, 0x5d, 0x6f, 0xe4, 0x3a, 0x92, 0xe5, 0x7f, 0xf1, 0x93, 0x13, 0xb0, 0x01, 0xf1, 0x53, 0x52, 0xbf, 0x18, 0x6d, 0x57, 0x95, 0xeb, 0xcb, 0xbe, 0xbe, 0x65, 0x57, 0xdd, 0xdb, 0x57, 0x9d, 0x0f, 0x8d, 0xed, 0xc6, 0x62, 0x81, 0x41, 0xf7, 0x62, 0x31, 0xf3, 0xb0, 0x68, 0xd6, 0x7f, 0x1f, 0x9e, 0x20, 0xa5, 0xcc, 0x54, 0x06, 0x95, 0x4a, 0x5b, 0xa6, 0xcd, 0xaa, 0xd9, 0x9d, 0xf1, 0xdc, 0x52, 0x8a, 0x1f, 0xa2, 0x42, 0xc1, 0x60, 0xc4, 0x89, 0x13, 0xff, 0x3e, 0xf9, 0x5f, 0xff, 0xfa, 0xaf, 0x7f, 0xfe, 0xe7, 0xff, 0xfb, 0xff, 0x57, 0xff, 0xfa, 0xfb, 0x3f, 0x1e, 0xfe, 0xf5, 0xe5, 0x1f, 0xff, 0xfb, 0xff, 0xfc, 0xeb, 0x9f, 0xf8, 0xef, 0x9b, 0xbf, 0xfd, 0xdf, 0x93, 0x3f, 0xfd, 0xfb, 0xa4, 0x3a, 0xf9, 0x53, 0x77, 0xf2, 0xe7, 0xab, 0x93, 0xb3, 0x93, 0x3f, 0xbf, 0xc1, 0x9f, 0xb7, 0xf8, 0xf3, 0x0e, 0x7f, 0xae, 0xf1, 0xe7, 0x03, 0xfe, 0x7c, 0xc6, 0x9f, 0x1b, 0xfc, 0xf9, 0x05, 0x7f, 0xbe, 0xe0, 0xcf, 0x3d, 0xfe, 0x3c, 0xe0, 0xcf, 0x57, 0xfc, 0xf9, 0x0d, 0x7f, 0x7e, 0xc7, 0x9f, 0x3f, 0xfc, 0x9f, 0xcb, 0x3f, 0xe3, 0xcf, 0x25, 0xfe, 0xa0, 0xd3, 0x4b, 0x74, 0x7a, 0x89, 0x4e, 0x2f, 0xd1, 0xe9, 0xe5, 0x7b, 0xfc, 0x41, 0xcf, 0x97, 0x1f, 0xf1, 0x07, 0xdd, 0x5f, 0xa2, 0xfb, 0xcb, 0x5b, 0xfc, 0xc1, 0x18, 0x97, 0xbf, 0xe2, 0x0f, 0x06, 0xba, 0xc4, 0x40, 0x97, 0x18, 0xe8, 0x12, 0x63, 0x5c, 0xfe, 0x05, 0x7f, 0x30, 0xc6, 0x15, 0xc6, 0xb8, 0xc2, 0xc4, 0xaf, 0x30, 0xc6, 0x15, 0xba, 0xbf, 0x42, 0xf7, 0x57, 0xe8, 0xfe, 0x0a, 0xdd, 0x5f, 0x7d, 0xc2, 0x1f, 0x74, 0x7f, 0x85, 0xee, 0xaf, 0xd0, 0xfd, 0x15, 0xba, 0xbf, 0x42, 0xcf, 0x57, 0x98, 0xf8, 0xd5, 0x37, 0xfc, 0x41, 0xcf, 0x57, 0x98, 0xfd, 0x15, 0xba, 0xbf, 0x42, 0xf7, 0x6f, 0x30, 0xe7, 0x37, 0x98, 0xdf, 0x1b, 0xf4, 0xf2, 0x06, 0x1d, 0xbc, 0x41, 0xdb, 0x37, 0xf8, 0xf5, 0x2d, 0xc6, 0x7d, 0x8b, 0x5b, 0xde, 0x62, 0xc8, 0xb7, 0x18, 0xf2, 0x2d, 0x3a, 0x7d, 0x8b, 0xe9, 0xbe, 0xc5, 0x74, 0xdf, 0x61, 0x06, 0xef, 0xd0, 0xc1, 0x3b, 0x74, 0xf0, 0x0e, 0x1d, 0xbc, 0x43, 0x07, 0xef, 0x70, 0xdf, 0x35, 0x66, 0x7f, 0x8d, 0x15, 0xba, 0xc6, 0xec, 0xaf, 0xd1, 0xd5, 0x35, 0x1e, 0xe1, 0x1a, 0xfd, 0x5d, 0xa3, 0xbf, 0x6b, 0x74, 0x70, 0x8d, 0xd9, 0x5f, 0xa3, 0xed, 0x35, 0x66, 0x7f, 0x7d, 0x87, 0x3f, 0xd4, 0x01, 0xc6, 0xb8, 0xc6, 0x23, 0x5c, 0x63, 0xf6, 0xd7, 0x98, 0xf8, 0x7b, 0x0c, 0xf4, 0x1e, 0xf7, 0xbd, 0xc7, 0x2d, 0xef, 0x71, 0xcb, 0x7b, 0xdc, 0xf2, 0x01, 0x63, 0x7c, 0xc0, 0x18, 0x1f, 0xd0, 0xdf, 0x07, 0xf4, 0xf7, 0x01, 0xf7, 0x7d, 0xc0, 0x3a, 0x7f, 0xc0, 0xcd, 0x1f, 0x30, 0xf1, 0x0f, 0x68, 0xf1, 0x11, 0xf7, 0x7d, 0xc4, 0x2d, 0x1f, 0x31, 0xdd, 0x8f, 0x18, 0xf2, 0x13, 0xae, 0x7d, 0xc2, 0xd4, 0x3e, 0x61, 0x6a, 0x9f, 0x30, 0xb5, 0x4f, 0xb8, 0xe5, 0x13, 0x7a, 0xf9, 0x44, 0xb7, 0xa0, 0x97, 0x4f, 0x98, 0xcb, 0x27, 0xcc, 0xe5, 0x13, 0x96, 0xe9, 0x33, 0x9e, 0xf2, 0x33, 0x9e, 0xf2, 0x33, 0x16, 0xec, 0x33, 0x9a, 0x7d, 0xc6, 0x24, 0x3f, 0xe3, 0xe6, 0xcf, 0x18, 0xf2, 0x33, 0x86, 0xfc, 0x8c, 0x49, 0x7e, 0xc6, 0xab, 0xf8, 0x8c, 0xb6, 0x37, 0x68, 0x76, 0x83, 0x16, 0x37, 0x98, 0xf8, 0x0d, 0x06, 0xbf, 0xc1, 0xe2, 0xdc, 0x60, 0x06, 0x37, 0x98, 0xc1, 0x0d, 0x7a, 0xb9, 0xc1, 0xc3, 0xdc, 0x60, 0x1a, 0x37, 0x98, 0xc6, 0x0d, 0xa6, 0x7b, 0x83, 0xb9, 0xdc, 0xe0, 0xb1, 0x6e, 0x30, 0xc6, 0x0d, 0xc6, 0xb8, 0xc1, 0x18, 0x37, 0x18, 0xe3, 0x06, 0x63, 0xdc, 0x60, 0x92, 0x37, 0x78, 0xdd, 0x37, 0x34, 0x1a, 0x66, 0x7a, 0x8b, 0x21, 0x6f, 0x31, 0xe4, 0x2d, 0x46, 0xbb, 0xc5, 0x68, 0xb7, 0x18, 0xed, 0x16, 0x73, 0xbe, 0xc5, 0x40, 0xb7, 0xe8, 0xfe, 0x16, 0xdd, 0xdf, 0xa2, 0xe7, 0x5b, 0xf4, 0x77, 0x8b, 0xb6, 0xbf, 0x60, 0x06, 0x77, 0xe8, 0xe0, 0x0e, 0x6d, 0xef, 0xd0, 0xf6, 0x0e, 0x6d, 0xef, 0x30, 0xd3, 0x3b, 0xcc, 0xf4, 0x0e, 0x1d, 0xdc, 0xd1, 0x7d, 0x68, 0x7b, 0x87, 0x59, 0xdd, 0x61, 0x56, 0x77, 0x98, 0xcb, 0x1d, 0xa6, 0xf1, 0x2b, 0x3a, 0xf8, 0x82, 0x0e, 0xbe, 0x60, 0xa0, 0x2f, 0xb8, 0xe5, 0x0b, 0xc6, 0xf8, 0x82, 0x5b, 0xee, 0xf1, 0xeb, 0x3d, 0x56, 0xf2, 0x1e, 0x93, 0xbc, 0xc7, 0xba, 0xdc, 0xe3, 0xe6, 0x7b, 0x0c, 0x74, 0x8f, 0x81, 0xee, 0x31, 0xd3, 0x7b, 0x08, 0xdc, 0x3d, 0x86, 0xbc, 0xc7, 0x90, 0xf7, 0x18, 0xf2, 0x1e, 0x8b, 0x73, 0x8f, 0x4e, 0xef, 0x31, 0xf8, 0x3d, 0xc6, 0xbd, 0xc7, 0x42, 0xdc, 0x63, 0x0d, 0xee, 0x31, 0xf8, 0x3d, 0x9e, 0xe3, 0x01, 0x3d, 0x3f, 0xa0, 0xe7, 0x07, 0x74, 0xfa, 0x80, 0x4e, 0x1f, 0xd0, 0xdf, 0x03, 0xba, 0x7a, 0x40, 0x57, 0x0f, 0xe8, 0xea, 0x01, 0x5d, 0x3d, 0xa0, 0xab, 0x07, 0x74, 0xf5, 0x80, 0xae, 0x1e, 0x30, 0xc9, 0x07, 0xf4, 0xf2, 0x15, 0x33, 0xfd, 0x8a, 0x0e, 0xbe, 0xe2, 0x11, 0xbe, 0xa2, 0xfb, 0xaf, 0xf8, 0xe1, 0x1b, 0x7e, 0xf8, 0x86, 0x31, 0xbe, 0x61, 0xe2, 0xdf, 0x70, 0xcb, 0x37, 0xcc, 0xf9, 0x1b, 0x3a, 0xfd, 0x86, 0x47, 0xfd, 0x0d, 0x4b, 0xf7, 0x1b, 0x9a, 0xfd, 0x8e, 0x47, 0xf8, 0x0b, 0xee, 0xfb, 0x0b, 0xc6, 0xf8, 0x03, 0x6d, 0xff, 0xc0, 0x0c, 0xfe, 0xf8, 0xed, 0x64, 0xfd, 0xfd, 0xac, 0x57, 0x6a, 0x0f, 0xff, 0xba, 0xf9, 0xc7, 0x7f, 0xfe, 0xed, 0xef, 0x7f, 0xfb, 0xcf, 0xbf, 0x41, 0x97, 0x79, 0x35, 0xf6, 0xa7, 0xee, 0x9f, 0xff, 0xf5, 0x1f, 0xff, 0x71, 0x16, 0xfe, 0xd2, 0x9f, 0x93, 0xf6, 0xaf, 0x7f, 0xfd, 0xbb, 0xff, 0x9f, 0x93, 0xb3, 0xcd, 0x35, 0xee, 0x4f, 0xa7, 0xd6, 0xeb, 0xed, 0x7f, 0x4e, 0xdf, 0x3d, 0x6e, 0x7c, 0x2e, 0x7c, 0xeb, 0xc7, 0xb4, 0x19, 0x5d, 0x24, 0x55, 0x7c, 0x54, 0x37, 0xb3, 0x87, 0xdb, 0x5e, 0x12, 0x21, 0xf6, 0x46, 0xa1, 0x8b, 0xeb, 0xa3, 0xee, 0xcd, 0xba, 0x46, 0x8f, 0x68, 0xb8, 0xa6, 0x4d, 0x8d, 0x11, 0x09, 0x51, 0x96, 0x48, 0xbc, 0xc9, 0x20, 0x12, 0x42, 0x74, 0x95, 0xb4, 0xcd, 0x7a, 0xff, 0x5d, 0x0b, 0x21, 0x39, 0xb9, 0x38, 0xd4, 0xa0, 0x04, 0xe1, 0x78, 0xcb, 0x09, 0x47, 0x27, 0x74, 0xbb, 0xf6, 0xd2, 0xf1, 0x6f, 0x79, 0xa6, 0xbe, 0x1f, 0x16, 0x91, 0x33, 0xfd, 0x3a, 0x84, 0xe4, 0x6d, 0x16, 0x21, 0x91, 0xae, 0x6d, 0xbb, 0xba, 0x69, 0x13, 0xaf, 0x9d, 0xfd, 0x78, 0xc6, 0x3d, 0x68, 0x6d, 0x3a, 0x61, 0xd7, 0xd3, 0x3d, 0xbd, 0x9c, 0x00, 0x9d, 0xc4, 0xf9, 0xed, 0xcf, 0xcb, 0xff, 0xb0, 0xa3, 0x0b, 0x3b, 0x1d, 0xc4, 0xe8, 0x5d, 0x42, 0x8c, 0xd6, 0x41, 0xcd, 0x9c, 0x5e, 0xfc, 0x89, 0xc4, 0xe9, 0xfb, 0xea, 0x62, 0x86, 0x38, 0x99, 0xd7, 0x21, 0x4e, 0xef, 0x72, 0x88, 0x93, 0x5f, 0x99, 0x4a, 0x3a, 0xd1, 0xae, 0x38, 0x19, 0x68, 0x67, 0x48, 0xd3, 0xd0, 0x81, 0xd3, 0x95, 0xff, 0xff, 0x7c, 0x37, 0x4f, 0x16, 0xa5, 0x93, 0x44, 0xe7, 0x7b, 0x97, 0x3b, 0xc3, 0xca, 0xd3, 0x11, 0xad, 0xd7, 0x74, 0xf0, 0x62, 0xc5, 0xa9, 0x5d, 0x97, 0xb5, 0x6b, 0x5d, 0xe7, 0x30, 0x64, 0xbc, 0x00, 0x08, 0xe1, 0x35, 0x09, 0x23, 0x41, 0x09, 0x7b, 0x46, 0xd4, 0xd6, 0x1d, 0x6e, 0xf6, 0x54, 0x89, 0xf1, 0xa3, 0x30, 0xc2, 0xe8, 0x2f, 0xf2, 0x33, 0x4a, 0xdc, 0xbb, 0xa6, 0x13, 0x78, 0xf9, 0x36, 0xed, 0x87, 0x9f, 0xc6, 0xa6, 0x5d, 0xf0, 0xc5, 0x7f, 0xe6, 0xd5, 0x80, 0x89, 0xb6, 0x89, 0x99, 0x65, 0x9b, 0x9c, 0x99, 0x33, 0x9b, 0x92, 0x01, 0x52, 0x9f, 0x0a, 0x3d, 0x3a, 0x2d, 0x9c, 0xb0, 0xe8, 0x57, 0x7d, 0x67, 0x75, 0xb1, 0xad, 0xaa, 0x6a, 0x57, 0x1d, 0x53, 0xb7, 0xdb, 0x9d, 0x19, 0x34, 0xd7, 0xfb, 0x93, 0x3a, 0x31, 0x95, 0x90, 0x8a, 0xd7, 0x92, 0xdb, 0x32, 0xf2, 0x39, 0xd3, 0x86, 0xe3, 0x0d, 0x10, 0xd9, 0xd5, 0xe7, 0xed, 0x9a, 0x7b, 0x50, 0x39, 0x73, 0xd3, 0x11, 0x61, 0x4f, 0x77, 0x16, 0x1b, 0x50, 0x55, 0x39, 0xda, 0x88, 0xac, 0xf3, 0x3a, 0x45, 0xaa, 0xd5, 0xca, 0x35, 0x71, 0xbf, 0xf7, 0x23, 0x49, 0x3f, 0x92, 0xeb, 0x54, 0x30, 0x29, 0x9d, 0xc5, 0x2a, 0xb9, 0xa6, 0xed, 0x84, 0x5c, 0xaf, 0x5c, 0x72, 0xc9, 0x30, 0x8f, 0x05, 0x44, 0x71, 0x77, 0xd9, 0xd9, 0x8b, 0x89, 0x47, 0x54, 0x22, 0x3d, 0x39, 0xe3, 0xbb, 0xd0, 0x23, 0x61, 0x88, 0x3b, 0xd7, 0x4d, 0xc2, 0x10, 0x6a, 0xa2, 0xcc, 0x32, 0xdd, 0xb1, 0x32, 0xfb, 0x3a, 0xb4, 0xd6, 0x4d, 0x0e, 0x89, 0xac, 0xbc, 0x28, 0x28, 0xce, 0x06, 0xae, 0xe6, 0x58, 0xd3, 0x41, 0xce, 0x82, 0xf1, 0xe3, 0x9a, 0x4e, 0x9c, 0xd7, 0x61, 0xa5, 0x99, 0xd7, 0xd6, 0xd4, 0x8b, 0xe8, 0xb7, 0xbc, 0xa6, 0xd0, 0x2f, 0x3f, 0xc0, 0xe9, 0xfd, 0x97, 0x3c, 0xa7, 0x77, 0xa9, 0x0c, 0x7b, 0x94, 0x52, 0x89, 0xc3, 0xfb, 0xd4, 0xfd, 0x25, 0x9c, 0xdd, 0xbf, 0xb0, 0xba, 0xa6, 0x12, 0xaa, 0x09, 0xa7, 0x77, 0x31, 0x47, 0xdb, 0xf8, 0x23, 0xfe, 0x94, 0xbe, 0xf1, 0xfd, 0x45, 0x57, 0xc0, 0x77, 0x52, 0xf1, 0x5d, 0x05, 0x75, 0xee, 0x2f, 0x5c, 0x38, 0xd1, 0x55, 0xe7, 0x52, 0xfb, 0x7f, 0x5d, 0xb0, 0x1b, 0xe6, 0xee, 0x39, 0xd1, 0x0f, 0xb3, 0x94, 0x34, 0x7d, 0xc9, 0xa3, 0x94, 0x2a, 0x51, 0xfb, 0x03, 0x3a, 0x67, 0x26, 0x89, 0x4a, 0x1c, 0x56, 0x4c, 0xc3, 0x9e, 0xe8, 0x57, 0x49, 0x19, 0xaf, 0x95, 0xb0, 0x5e, 0xf2, 0xdc, 0x5b, 0x1a, 0x92, 0xec, 0x0d, 0x7f, 0x60, 0x53, 0xaa, 0x96, 0x7e, 0x27, 0x54, 0xaa, 0x49, 0x8c, 0x23, 0x97, 0x50, 0x57, 0x34, 0x00, 0xa3, 0x0c, 0xc7, 0x97, 0x79, 0x75, 0xb5, 0x99, 0xe3, 0x7e, 0x17, 0xf8, 0x6d, 0xd7, 0x19, 0xd0, 0xef, 0x82, 0xf7, 0xac, 0x64, 0xea, 0xb6, 0x64, 0x77, 0xc0, 0xfd, 0x4b, 0x5a, 0xf0, 0x07, 0xc5, 0x2d, 0xec, 0x7f, 0xaf, 0xd0, 0x53, 0x7d, 0xf4, 0x86, 0xf7, 0x30, 0xb1, 0xe1, 0x45, 0xc1, 0x51, 0xf3, 0x04, 0x67, 0xc2, 0xec, 0x17, 0xc1, 0x6c, 0xed, 0x2a, 0xbb, 0xa6, 0xaf, 0x54, 0xd4, 0x64, 0xb6, 0xce, 0x32, 0xfc, 0xed, 0x52, 0x12, 0xf5, 0x90, 0xc9, 0xde, 0x87, 0xa9, 0x2d, 0xbd, 0xb6, 0x71, 0x5a, 0xb3, 0x4f, 0x38, 0xc7, 0xcc, 0x8a, 0x16, 0xbf, 0x74, 0xfc, 0xc2, 0x79, 0x3b, 0x7f, 0x7a, 0x84, 0x32, 0x76, 0xd4, 0xaf, 0xfc, 0x8e, 0x7a, 0x2e, 0xa3, 0x51, 0x79, 0x56, 0xcf, 0x3e, 0x72, 0x9e, 0xd5, 0x67, 0xcd, 0xe4, 0xb1, 0x53, 0x9a, 0xa6, 0x69, 0x8c, 0x33, 0xc6, 0xac, 0x5c, 0xad, 0x98, 0x73, 0xca, 0xe8, 0x22, 0x75, 0x5c, 0x8f, 0x0f, 0x38, 0xe8, 0x08, 0x67, 0x58, 0xed, 0xb4, 0xb1, 0x2b, 0xd7, 0x86, 0x23, 0x0b, 0xf7, 0x12, 0xbc, 0x1a, 0x18, 0x1d, 0x7c, 0xf6, 0x8f, 0xc6, 0x51, 0x30, 0xbf, 0x66, 0x10, 0xcc, 0xed, 0x33, 0xa3, 0x7c, 0xac, 0x58, 0x6e, 0x77, 0x42, 0x72, 0xe9, 0xa4, 0x6b, 0x3b, 0x6d, 0xfd, 0xc9, 0x12, 0xab, 0xe2, 0x2d, 0x3c, 0x3a, 0x73, 0xea, 0x3e, 0x96, 0x11, 0x8e, 0x74, 0x7e, 0x21, 0xbf, 0xbb, 0x86, 0xa4, 0x19, 0xd6, 0x52, 0xb0, 0x67, 0xbc, 0x08, 0xfb, 0x57, 0x11, 0x17, 0xf0, 0xcc, 0xe2, 0xe4, 0x2a, 0x8d, 0xab, 0xb1, 0xb6, 0xca, 0xd9, 0x7a, 0x8e, 0x58, 0x87, 0xaf, 0x24, 0x1a, 0x4b, 0x52, 0xfb, 0xf7, 0x17, 0x3b, 0xb1, 0xf5, 0x7e, 0x6b, 0xff, 0xc3, 0xde, 0xdb, 0x1d, 0x3b, 0x14, 0x46, 0x62, 0xc2, 0x4c, 0xc1, 0x5f, 0x1e, 0xbd, 0xd2, 0x9a, 0xfd, 0x7c, 0x87, 0xc7, 0x9a, 0x25, 0x18, 0x51, 0x78, 0xd7, 0x84, 0x6a, 0xf9, 0x21, 0x3c, 0xb1, 0xbf, 0x65, 0xb1, 0x19, 0xab, 0xa9, 0x0d, 0x98, 0x55, 0x02, 0xbe, 0x49, 0x8d, 0xcf, 0xb6, 0x04, 0x6f, 0xdc, 0xef, 0xbc, 0x28, 0xd4, 0x25, 0x1b, 0x75, 0xbf, 0xe7, 0x09, 0x19, 0x3e, 0x21, 0x54, 0x58, 0x1b, 0x6c, 0xdf, 0x29, 0x97, 0x46, 0x39, 0x5b, 0xeb, 0x1f, 0x07, 0x1c, 0x63, 0x25, 0x05, 0x9a, 0xff, 0xc8, 0x15, 0x19, 0x24, 0xcf, 0x58, 0x62, 0x7f, 0x9c, 0x73, 0x08, 0xdd, 0xed, 0x84, 0x9c, 0x64, 0xae, 0x69, 0x76, 0xed, 0xd9, 0x4d, 0x77, 0xcb, 0xb8, 0xc6, 0x12, 0x03, 0xe0, 0xa7, 0x71, 0xe4, 0x78, 0x7f, 0xc2, 0x47, 0x76, 0xb0, 0x26, 0xa0, 0x65, 0xe2, 0xbc, 0xb0, 0x50, 0x84, 0xa0, 0x8f, 0x0a, 0x64, 0x3d, 0x1b, 0x00, 0x3e, 0xfa, 0xfc, 0x22, 0x06, 0xdf, 0xbc, 0xe6, 0x5c, 0x60, 0xf2, 0x88, 0x23, 0xc1, 0xf8, 0x40, 0x80, 0x1d, 0x61, 0x2b, 0x06, 0x20, 0xce, 0x28, 0x0a, 0x10, 0x3d, 0x21, 0xfe, 0xa7, 0x8e, 0x9c, 0x20, 0x16, 0x56, 0xb5, 0x6f, 0xd2, 0xd5, 0xcd, 0x7a, 0x73, 0x5b, 0xa7, 0xce, 0x4d, 0xef, 0x6d, 0xaa, 0xd3, 0xc1, 0x18, 0x59, 0x88, 0xd2, 0xbb, 0xbc, 0x64, 0x95, 0x9e, 0x3c, 0xb7, 0x4d, 0x61, 0x06, 0x14, 0x90, 0xcc, 0xcf, 0x2e, 0x8f, 0x70, 0xc8, 0xb6, 0x6b, 0xce, 0x14, 0x92, 0xbc, 0x05, 0x15, 0x57, 0x32, 0xdd, 0xa2, 0x04, 0x19, 0x61, 0xe1, 0x79, 0x9d, 0x30, 0x75, 0xbb, 0x50, 0xc8, 0xc8, 0xeb, 0x76, 0xce, 0xac, 0xdb, 0xbd, 0xd8, 0x2d, 0xe5, 0x9e, 0xbd, 0xcc, 0x02, 0xd5, 0x8b, 0xea, 0x44, 0x02, 0x42, 0xe5, 0xcd, 0xe7, 0xb6, 0x65, 0xcc, 0xe7, 0x76, 0x2e, 0x7c, 0x86, 0xdc, 0xda, 0xe7, 0xaa, 0x5d, 0x3b, 0x83, 0x7f, 0xe2, 0xc4, 0xd8, 0x09, 0xaf, 0x18, 0x57, 0xce, 0x9e, 0xf6, 0x26, 0xad, 0xab, 0xfd, 0x2d, 0x7a, 0xed, 0x1a, 0x8c, 0xda, 0xfa, 0x9f, 0xbc, 0x9e, 0xb3, 0x08, 0x6c, 0xd2, 0x39, 0x53, 0x28, 0x0d, 0xbf, 0x6e, 0xe5, 0xb5, 0xd7, 0xca, 0xa9, 0x78, 0x0a, 0xbc, 0x70, 0x8a, 0x02, 0x9e, 0x5e, 0xa9, 0xe1, 0x40, 0xaa, 0xfb, 0xbe, 0x45, 0x1f, 0x1a, 0x35, 0x21, 0x34, 0x8a, 0x27, 0xa8, 0x1b, 0xeb, 0x10, 0x25, 0x26, 0x5c, 0x86, 0x69, 0x35, 0x0f, 0xcc, 0x10, 0xd5, 0x02, 0xa1, 0x89, 0xa0, 0xb8, 0x05, 0xdc, 0xd0, 0x6a, 0xbd, 0x3d, 0xb2, 0x1f, 0x96, 0x59, 0xc5, 0xd1, 0xd5, 0x6d, 0x23, 0xac, 0x9b, 0xb8, 0x2f, 0xd1, 0x3a, 0xee, 0xd9, 0x09, 0xd4, 0xe1, 0xf9, 0xae, 0x83, 0x78, 0xeb, 0x44, 0x31, 0xeb, 0x4c, 0xa1, 0x0f, 0x04, 0xfa, 0xab, 0x4e, 0x9a, 0xf3, 0x26, 0x6c, 0x53, 0x95, 0xeb, 0x83, 0xfd, 0x74, 0xc6, 0x87, 0xa1, 0x5d, 0xfb, 0x1d, 0x4b, 0xa8, 0xb8, 0x6d, 0x4d, 0xec, 0xf7, 0xbc, 0x07, 0xc6, 0xf7, 0xa0, 0x74, 0x78, 0xf9, 0x55, 0xed, 0xd0, 0x8f, 0x16, 0xda, 0xf9, 0xae, 0x2a, 0x7f, 0xd5, 0xbf, 0xe8, 0xf8, 0x39, 0x73, 0xfd, 0xd6, 0x72, 0x74, 0x18, 0xd0, 0xdc, 0x77, 0x95, 0x05, 0xdd, 0x18, 0xbe, 0x2b, 0x91, 0xb2, 0x39, 0xe7, 0xba, 0x0a, 0xf1, 0x6d, 0xc6, 0x85, 0xee, 0x2a, 0xe9, 0x37, 0xfd, 0x01, 0x25, 0x20, 0xea, 0x55, 0x6f, 0x0d, 0x68, 0xc4, 0x44, 0xfc, 0xaa, 0x51, 0x18, 0x29, 0x7c, 0x06, 0x6a, 0xf3, 0x83, 0xa2, 0x0b, 0x7a, 0x73, 0x41, 0x7b, 0x31, 0xa5, 0x6b, 0x86, 0xac, 0x8c, 0xca, 0x1b, 0x11, 0x86, 0x22, 0x29, 0xd6, 0x7a, 0xd9, 0x5d, 0xd1, 0x10, 0xf8, 0x28, 0xfd, 0xbd, 0xca, 0xfa, 0xaf, 0x4e, 0xe0, 0xa3, 0xab, 0xc3, 0x64, 0x28, 0xfa, 0x22, 0x6b, 0xfa, 0x5e, 0xc9, 0x4f, 0x69, 0x0d, 0x3e, 0x68, 0x58, 0x2a, 0x4d, 0x8b, 0xd7, 0xde, 0x29, 0x7c, 0xd3, 0x5d, 0x8c, 0x6d, 0x25, 0xde, 0xfe, 0x8b, 0x42, 0x32, 0x27, 0xe7, 0x26, 0xeb, 0xa6, 0xe6, 0xbe, 0x33, 0x16, 0x96, 0x29, 0xe6, 0x98, 0x1d, 0xf2, 0x75, 0x98, 0x1d, 0x59, 0x30, 0x98, 0xb0, 0x41, 0x39, 0xbf, 0x07, 0xeb, 0x22, 0x99, 0xb8, 0xb9, 0x04, 0x6b, 0x83, 0x45, 0x56, 0x3e, 0x53, 0x74, 0x05, 0x9f, 0xbb, 0xc8, 0x1b, 0x53, 0xb9, 0xcc, 0x01, 0xb9, 0x8c, 0x18, 0x2a, 0xaf, 0x8e, 0x2c, 0x8e, 0x3d, 0x4b, 0xc5, 0x54, 0xc2, 0x72, 0xad, 0x0e, 0xf5, 0x5b, 0x86, 0x9c, 0xbd, 0x4f, 0x60, 0x13, 0x9a, 0x85, 0x63, 0xc0, 0x27, 0xc1, 0xc3, 0x01, 0xad, 0xdf, 0x88, 0x55, 0x4a, 0x3f, 0x56, 0x35, 0x07, 0xc0, 0xdb, 0xb1, 0x5f, 0x06, 0x57, 0x14, 0xd7, 0xbe, 0xd5, 0x73, 0x00, 0x7c, 0xc8, 0xea, 0x7c, 0x76, 0xe1, 0x83, 0xef, 0xfd, 0xd1, 0xe6, 0x6e, 0x58, 0xa9, 0xf0, 0x94, 0xfd, 0xee, 0x4c, 0x11, 0x12, 0xe4, 0x24, 0xd0, 0xbe, 0x6f, 0x04, 0x40, 0x54, 0x7e, 0xef, 0xf6, 0x0b, 0x62, 0xb1, 0x27, 0xfa, 0x7f, 0x99, 0x7e, 0x61, 0xc8, 0x3a, 0xdd, 0x5a, 0x28, 0x7f, 0x53, 0x25, 0x75, 0xc3, 0x02, 0x09, 0x31, 0x9f, 0xa7, 0xdb, 0xaa, 0x55, 0xb7, 0x99, 0x2f, 0xdc, 0x42, 0xde, 0x02, 0x68, 0x46, 0x31, 0x8f, 0x70, 0x23, 0xfd, 0x78, 0x18, 0xce, 0x70, 0x7c, 0x1f, 0x6b, 0x4a, 0xd4, 0x65, 0xcd, 0x55, 0x7b, 0xbe, 0x4c, 0x96, 0xcc, 0x89, 0xe5, 0x4e, 0xb0, 0x96, 0x09, 0xfb, 0x2f, 0xa2, 0x22, 0x73, 0x40, 0x91, 0x09, 0x5d, 0x55, 0xb3, 0xe8, 0xaa, 0x7a, 0xa6, 0x66, 0x84, 0x58, 0xc6, 0x13, 0x12, 0x39, 0x8b, 0x0c, 0xec, 0x39, 0xbf, 0x28, 0xc1, 0x5e, 0xaf, 0xbc, 0xbd, 0xee, 0xda, 0x1a, 0xc6, 0x5b, 0x27, 0x9b, 0x75, 0xe3, 0x5a, 0xd6, 0xab, 0xb9, 0xc4, 0xbe, 0x7c, 0xb2, 0x33, 0xa8, 0x1f, 0xb0, 0x49, 0x8c, 0xc6, 0xbd, 0xb1, 0xbd, 0x67, 0xab, 0x7d, 0x2f, 0x6c, 0xeb, 0x76, 0x8c, 0x2f, 0x0e, 0xb2, 0xf7, 0x71, 0x22, 0xea, 0xf2, 0x74, 0xc9, 0xab, 0xb7, 0x3c, 0x6e, 0x5c, 0x04, 0x9a, 0x39, 0x98, 0x2c, 0x22, 0x83, 0x1f, 0xf3, 0xc8, 0x20, 0x6f, 0xab, 0xcd, 0x16, 0x41, 0xb4, 0xc7, 0xb1, 0x3e, 0x78, 0x2c, 0xab, 0x15, 0x39, 0x01, 0xd2, 0xcb, 0xb5, 0x8c, 0xb4, 0x09, 0xc9, 0xd9, 0xe7, 0xb3, 0x7c, 0xb2, 0x73, 0xc7, 0x5b, 0x13, 0xe5, 0x40, 0xe1, 0x47, 0x83, 0x2c, 0x68, 0x79, 0x06, 0xf5, 0xe6, 0xaf, 0x71, 0xf2, 0x92, 0xba, 0xb3, 0x04, 0x63, 0x2d, 0x01, 0x5a, 0x2f, 0xcd, 0x47, 0x9d, 0x03, 0xad, 0x7e, 0x54, 0x80, 0x1f, 0x79, 0x56, 0x05, 0x44, 0xf6, 0x2f, 0x6f, 0xcb, 0x4f, 0xb0, 0x02, 0x71, 0xca, 0xf3, 0xbf, 0x7c, 0x6f, 0x14, 0xb3, 0x98, 0xf1, 0xb6, 0xe5, 0x93, 0xac, 0xa6, 0xef, 0x2f, 0x41, 0x35, 0xb0, 0xe9, 0x07, 0x65, 0x27, 0xf6, 0x5e, 0x66, 0x4a, 0x47, 0xa8, 0x12, 0x99, 0xdd, 0x7b, 0x66, 0x5e, 0xb2, 0x75, 0x3a, 0xa5, 0xb7, 0x2a, 0x08, 0xd1, 0x7b, 0xf9, 0xeb, 0x8f, 0xb1, 0xbd, 0xfc, 0x9a, 0x07, 0x2b, 0x94, 0xc8, 0x05, 0x48, 0x50, 0x50, 0xc4, 0xd8, 0x45, 0x0a, 0x43, 0xb6, 0x88, 0xc3, 0x68, 0xc1, 0x9d, 0x86, 0x4f, 0x59, 0x11, 0x52, 0x9f, 0xdb, 0xfe, 0x2c, 0xbd, 0x50, 0x56, 0xa7, 0x3f, 0xe6, 0x77, 0xc1, 0xd9, 0x14, 0xa2, 0x08, 0xa6, 0x76, 0x8d, 0x6c, 0x38, 0x9f, 0x5a, 0x33, 0x3a, 0xb5, 0x9d, 0x2d, 0x76, 0xca, 0xc9, 0x92, 0xa9, 0x12, 0x13, 0x3a, 0x1b, 0x72, 0xc6, 0x20, 0xa2, 0xc7, 0x0b, 0x42, 0x3b, 0x47, 0xed, 0x0c, 0xd1, 0x50, 0xb9, 0x0e, 0x61, 0x4c, 0x80, 0x35, 0xea, 0x96, 0x72, 0x56, 0x80, 0x93, 0x75, 0x8a, 0xde, 0x15, 0x34, 0x53, 0x27, 0xce, 0x95, 0xc1, 0xf9, 0xc8, 0x20, 0x56, 0x6a, 0x1b, 0x9c, 0xd2, 0x05, 0x62, 0xa8, 0x0d, 0xb1, 0x87, 0x90, 0xff, 0xa8, 0x41, 0x86, 0x67, 0xc8, 0x7f, 0x69, 0x63, 0x0c, 0x88, 0xb2, 0x86, 0x14, 0xc2, 0x70, 0x17, 0x38, 0x59, 0x09, 0x6d, 0xd0, 0x69, 0x25, 0x54, 0xed, 0x2f, 0xe8, 0x4e, 0x21, 0x46, 0x73, 0x11, 0x1b, 0xd1, 0xc1, 0x5f, 0xd8, 0x35, 0x82, 0xaf, 0xe1, 0x86, 0xa6, 0xa3, 0x00, 0x1e, 0x6d, 0xab, 0xed, 0x7a, 0x85, 0x28, 0x6c, 0x08, 0xe9, 0xc9, 0x0e, 0x93, 0x69, 0xc3, 0xac, 0xe1, 0x94, 0x32, 0x98, 0x91, 0x0a, 0x49, 0xa6, 0x7e, 0xae, 0x92, 0xfe, 0x6d, 0x42, 0x3c, 0x96, 0x62, 0x53, 0x8d, 0xef, 0x1a, 0x69, 0x38, 0x08, 0xeb, 0xa2, 0x65, 0x88, 0x4a, 0x05, 0xbc, 0x6f, 0xe5, 0x9a, 0xba, 0xf1, 0x07, 0x7d, 0xd3, 0x9a, 0xf6, 0x22, 0x06, 0xa1, 0xbc, 0x6e, 0xbb, 0x70, 0x5e, 0x2f, 0xfb, 0x1e, 0x5d, 0x94, 0x25, 0x80, 0x72, 0x8d, 0x09, 0xcf, 0x15, 0x70, 0xd7, 0x4e, 0x54, 0xfe, 0xff, 0xa5, 0x5e, 0x81, 0x6d, 0xc6, 0xb1, 0xc3, 0xca, 0xbf, 0xb8, 0xda, 0x8f, 0xc7, 0x45, 0x74, 0x46, 0x97, 0xe3, 0xf6, 0xb9, 0xd3, 0xdc, 0x08, 0x87, 0xc8, 0x4f, 0xc3, 0xcd, 0x30, 0xce, 0x8e, 0x8f, 0x15, 0x35, 0x63, 0x89, 0x3f, 0x63, 0xbd, 0x65, 0x07, 0x57, 0x24, 0x2c, 0xc3, 0xfe, 0x02, 0xcc, 0x19, 0x35, 0x7e, 0xc2, 0x6b, 0x22, 0xb8, 0x2b, 0xdf, 0xfe, 0xcc, 0x93, 0x1e, 0x84, 0x5d, 0x73, 0xf6, 0xf9, 0x63, 0xfa, 0xf6, 0x12, 0xac, 0x4f, 0x36, 0x17, 0xa8, 0x70, 0xeb, 0x33, 0x4b, 0xd6, 0x8f, 0xa0, 0xbd, 0x80, 0xb3, 0x07, 0xe6, 0xe4, 0xbe, 0x43, 0x47, 0xdb, 0x09, 0xeb, 0xf3, 0x25, 0x13, 0x64, 0x8f, 0xb6, 0x3e, 0x0f, 0x64, 0x30, 0x14, 0x29, 0x43, 0x39, 0xd2, 0x19, 0x92, 0xdc, 0x54, 0xf3, 0x80, 0x55, 0x4a, 0x48, 0x95, 0xe6, 0xb7, 0x5a, 0x26, 0x3a, 0x44, 0x83, 0x30, 0x02, 0x3a, 0xbe, 0xcc, 0xc7, 0x82, 0x8e, 0x69, 0xbd, 0x26, 0xde, 0xd5, 0xe2, 0x33, 0xf1, 0xc1, 0x1d, 0xfb, 0xec, 0x82, 0x73, 0x10, 0xb9, 0x9e, 0x3e, 0xca, 0x54, 0xe0, 0x6f, 0x68, 0x09, 0xac, 0xa3, 0xbd, 0x02, 0x52, 0x06, 0xd6, 0xa5, 0x0c, 0x96, 0x20, 0xac, 0xbb, 0xba, 0xa3, 0x4c, 0x6a, 0x6f, 0x06, 0x06, 0x2b, 0xd0, 0xff, 0xa3, 0xe8, 0x28, 0x39, 0x9b, 0x14, 0x11, 0x0d, 0x9f, 0xc3, 0xea, 0x28, 0xe4, 0xd4, 0xbf, 0x02, 0xa9, 0xca, 0x91, 0x0f, 0xd1, 0x86, 0xd3, 0x03, 0x87, 0x27, 0x49, 0x99, 0x3f, 0x87, 0x5a, 0x14, 0x20, 0x21, 0x57, 0x6c, 0x76, 0xc3, 0x1e, 0x52, 0x92, 0x87, 0x4c, 0xce, 0xdb, 0xd1, 0xce, 0xec, 0x44, 0xa2, 0xaa, 0x4c, 0x61, 0xab, 0x77, 0x3a, 0x59, 0x48, 0x8e, 0xae, 0xb2, 0x24, 0x3d, 0xa4, 0x3c, 0x2c, 0xb3, 0xd2, 0xec, 0xe3, 0x69, 0x3b, 0x64, 0x53, 0x1a, 0x64, 0x2c, 0x48, 0x9c, 0x6d, 0x03, 0xa2, 0x76, 0x73, 0x55, 0xc5, 0xf7, 0x80, 0x7f, 0x39, 0x9c, 0x88, 0x7a, 0xc8, 0x85, 0x00, 0x2c, 0x94, 0xa5, 0x7a, 0x50, 0xda, 0x2c, 0xb0, 0x23, 0x02, 0x42, 0x6f, 0x6b, 0x16, 0x11, 0x3f, 0x2b, 0x3a, 0x8d, 0x93, 0x72, 0x44, 0x35, 0xd0, 0xdc, 0x13, 0x0f, 0xc2, 0x7c, 0x52, 0xca, 0xff, 0xb8, 0x3b, 0x40, 0x94, 0xac, 0x35, 0x71, 0x94, 0xf3, 0x68, 0xa0, 0xb2, 0x3c, 0x80, 0x57, 0x39, 0x88, 0x89, 0x03, 0x0e, 0x2c, 0x91, 0x31, 0x98, 0x4a, 0x81, 0x4e, 0xdf, 0x5f, 0x82, 0x8e, 0x4b, 0x64, 0x40, 0x94, 0x7c, 0xca, 0xbb, 0xca, 0x95, 0x05, 0x21, 0x3a, 0xa5, 0xbd, 0x2d, 0x54, 0xd7, 0xae, 0x61, 0x9d, 0x9b, 0xb3, 0xce, 0x7b, 0x9b, 0x7e, 0xbc, 0xcd, 0x1e, 0xba, 0x4a, 0x1d, 0xfe, 0xc2, 0xe5, 0xc2, 0x48, 0xb4, 0xae, 0x92, 0x38, 0xe8, 0xb2, 0x12, 0x4f, 0xaf, 0x72, 0x51, 0xd2, 0x46, 0xe4, 0x8b, 0xe4, 0x3c, 0x79, 0xc2, 0x5f, 0x4e, 0x86, 0x22, 0x3a, 0x3d, 0xd1, 0xb0, 0x14, 0x90, 0xf4, 0xd5, 0x14, 0x48, 0xfa, 0xf1, 0x7b, 0xd5, 0x98, 0x13, 0x6b, 0x73, 0x71, 0x21, 0xe9, 0xc8, 0x82, 0x7d, 0x9e, 0x00, 0x55, 0xf1, 0xae, 0x24, 0x21, 0xed, 0x44, 0x8b, 0x12, 0xc4, 0x81, 0xc7, 0x32, 0x8b, 0xf3, 0x85, 0x23, 0x56, 0x7d, 0xa2, 0xb1, 0xd3, 0x70, 0xde, 0x4b, 0x1e, 0xcf, 0xc8, 0xd0, 0x90, 0xf2, 0xbc, 0x21, 0x42, 0x9b, 0x0d, 0x09, 0xa7, 0xd1, 0xca, 0x35, 0x8a, 0x95, 0x3f, 0xff, 0x53, 0x3a, 0x18, 0xb0, 0x2d, 0x5d, 0x39, 0xc0, 0xcd, 0x41, 0x87, 0x48, 0xe8, 0x90, 0xa7, 0x71, 0x15, 0x55, 0x7d, 0x5e, 0x71, 0x4f, 0x5b, 0x17, 0xfa, 0x34, 0x23, 0xa8, 0xbd, 0xa6, 0x68, 0x91, 0x37, 0xbd, 0x29, 0x41, 0x48, 0x9b, 0x75, 0x0c, 0x66, 0x54, 0x94, 0x00, 0x08, 0xc0, 0x69, 0x13, 0xf9, 0xb5, 0x3b, 0x20, 0xd7, 0x01, 0xcd, 0xaf, 0x11, 0x39, 0x6a, 0x28, 0x5d, 0x69, 0x2b, 0x61, 0x88, 0xcd, 0xd2, 0x3c, 0x11, 0xba, 0x1e, 0x47, 0x7c, 0x7c, 0x77, 0x71, 0x50, 0xb3, 0xa6, 0x4c, 0xc0, 0x55, 0x48, 0x44, 0xa3, 0xfc, 0x67, 0x2e, 0x66, 0xb4, 0xff, 0xba, 0x47, 0x2f, 0x1b, 0xe9, 0x50, 0x5e, 0x58, 0x9c, 0xe2, 0x08, 0x62, 0x8c, 0xda, 0x63, 0x99, 0x61, 0xcd, 0xfe, 0xe9, 0xe7, 0x60, 0x26, 0x11, 0x99, 0xde, 0xae, 0x12, 0xd0, 0x68, 0x5d, 0x1e, 0xab, 0xc3, 0x55, 0x16, 0x5c, 0x74, 0xc8, 0x5d, 0x13, 0x21, 0xf1, 0x9d, 0xdf, 0x25, 0x67, 0x06, 0x6a, 0xb7, 0xbb, 0xf1, 0x5f, 0x8b, 0xe6, 0x5c, 0x99, 0x4b, 0xe0, 0x44, 0x4e, 0xf8, 0xbe, 0xc7, 0x57, 0x13, 0x7c, 0x0e, 0xb3, 0xdb, 0xae, 0xa9, 0x58, 0x55, 0xf1, 0x71, 0x40, 0x14, 0xdc, 0x7a, 0x76, 0x29, 0x6a, 0xdb, 0xce, 0x26, 0xdc, 0xea, 0x2c, 0x38, 0xf5, 0xc0, 0xfd, 0x25, 0xec, 0xc1, 0x09, 0x2a, 0xf0, 0x29, 0xb5, 0xb5, 0x27, 0x20, 0xd3, 0x49, 0xf2, 0x52, 0x28, 0xa7, 0x95, 0x66, 0x4e, 0xd2, 0xe3, 0xab, 0x63, 0x18, 0x7c, 0xd8, 0x71, 0x6c, 0xe5, 0xa4, 0x10, 0x01, 0x36, 0xa1, 0x1c, 0x1d, 0xa7, 0x2a, 0x00, 0x19, 0x04, 0x10, 0x08, 0xa2, 0x76, 0xc6, 0xdf, 0xd0, 0x88, 0x26, 0x30, 0xef, 0xb7, 0xae, 0xa9, 0xfa, 0x44, 0x58, 0x6f, 0x50, 0x7b, 0x8b, 0x99, 0x92, 0x5c, 0x15, 0x9d, 0xbf, 0x70, 0x00, 0x93, 0x31, 0x19, 0x16, 0xc8, 0x15, 0xa2, 0xe9, 0x77, 0x42, 0x49, 0xba, 0x24, 0x5b, 0x4a, 0x7d, 0xf0, 0x1f, 0xbd, 0xb5, 0x26, 0x6c, 0x61, 0x42, 0xfb, 0x1e, 0xfc, 0x16, 0xaf, 0xac, 0xb1, 0x21, 0x36, 0xef, 0x77, 0x2c, 0x43, 0xc9, 0x0a, 0xc6, 0xe8, 0x90, 0x31, 0x5b, 0x55, 0xda, 0x4f, 0xc3, 0x68, 0xfa, 0x87, 0xb5, 0xf4, 0x63, 0xdb, 0xe7, 0xcd, 0x56, 0x35, 0xb6, 0x44, 0x25, 0xfc, 0x3c, 0xc2, 0x20, 0xfe, 0x9f, 0xd6, 0x22, 0x15, 0xcd, 0xff, 0xdf, 0x90, 0x9f, 0x5e, 0x37, 0x61, 0x2f, 0xf4, 0x8f, 0x88, 0xe4, 0x0e, 0xec, 0xa6, 0x8d, 0xf4, 0x13, 0x45, 0xfa, 0x7d, 0xbc, 0x0e, 0xe4, 0x01, 0x36, 0x22, 0xc5, 0x02, 0x00, 0xa4, 0x1c, 0xa5, 0x82, 0xf3, 0x66, 0x46, 0x16, 0x58, 0xb7, 0x0a, 0xe1, 0x09, 0x1e, 0xa6, 0x31, 0xa6, 0xdd, 0x4b, 0xda, 0x18, 0xf6, 0x02, 0xaf, 0x1c, 0x69, 0xf4, 0x3d, 0xec, 0xc4, 0x52, 0xf0, 0x42, 0x5d, 0xc4, 0xd7, 0x7f, 0x11, 0xde, 0x7f, 0x0f, 0x98, 0x40, 0x22, 0x01, 0x58, 0x52, 0x6a, 0xff, 0x73, 0x0d, 0xc4, 0x49, 0x52, 0x24, 0x68, 0x41, 0x9d, 0x17, 0x8c, 0xd5, 0x91, 0x92, 0xa1, 0xea, 0xb4, 0x70, 0xc0, 0xf4, 0x90, 0xce, 0x82, 0x26, 0xf0, 0xe5, 0x64, 0x84, 0x76, 0x2e, 0x07, 0x8c, 0x8c, 0x4c, 0x8a, 0x8a, 0x50, 0xa3, 0xe0, 0xe0, 0x89, 0xbf, 0xd7, 0x7f, 0x59, 0x4a, 0x31, 0x3c, 0x7a, 0xe3, 0xab, 0x4f, 0xcb, 0x51, 0xd9, 0x1e, 0x34, 0x10, 0x3b, 0x50, 0xd2, 0x78, 0x07, 0x40, 0x11, 0xb1, 0x1e, 0x27, 0x53, 0x0c, 0x8d, 0xa9, 0xeb, 0x7d, 0xf9, 0x5e, 0x53, 0xe1, 0x45, 0x56, 0x75, 0xf5, 0xbc, 0x37, 0x33, 0x4c, 0x24, 0xe2, 0x68, 0x7e, 0x1d, 0xdb, 0x5b, 0x16, 0x46, 0xf8, 0x0b, 0xd1, 0x25, 0x92, 0xc7, 0x76, 0x3f, 0xcd, 0xad, 0x00, 0x18, 0xd3, 0xde, 0x11, 0xdf, 0x3b, 0xdb, 0xc9, 0x02, 0xac, 0xca, 0x6c, 0xdf, 0xe3, 0xab, 0xbc, 0x51, 0x34, 0xbf, 0xed, 0x9a, 0x4a, 0x76, 0xce, 0xc2, 0x2f, 0x9c, 0xcd, 0x4c, 0xdb, 0x9e, 0x38, 0x85, 0xe6, 0x95, 0xa4, 0x1c, 0x80, 0xfd, 0x68, 0x27, 0x03, 0xc0, 0xc8, 0xdb, 0xda, 0x73, 0x29, 0x62, 0xaa, 0xfe, 0x2c, 0xd9, 0x77, 0xe6, 0xda, 0x81, 0x4a, 0x94, 0xef, 0x77, 0x8c, 0xf4, 0xeb, 0x7b, 0x98, 0x6a, 0xd7, 0x1a, 0x63, 0x77, 0x59, 0x79, 0xcc, 0xf8, 0x6c, 0x7f, 0xdc, 0x7a, 0x3f, 0xd2, 0xd8, 0x4a, 0x81, 0xfe, 0x9b, 0x92, 0x3d, 0xf2, 0x59, 0x50, 0xff, 0xc1, 0x7f, 0xd1, 0x92, 0x23, 0xdd, 0xef, 0xca, 0x7e, 0xaf, 0x7d, 0x8a, 0x13, 0xc3, 0x12, 0xbe, 0xd5, 0xb6, 0x11, 0xdf, 0x0a, 0x40, 0x2b, 0xc8, 0x54, 0x74, 0xa7, 0x91, 0xef, 0x6e, 0x3a, 0x65, 0x01, 0x8c, 0x00, 0x84, 0x16, 0x9b, 0x74, 0x2c, 0x81, 0x61, 0xb4, 0x7a, 0xae, 0x68, 0xd0, 0xc9, 0xe4, 0x10, 0xc7, 0xf8, 0xee, 0x8f, 0xea, 0x63, 0x4d, 0xe5, 0x8a, 0x59, 0x91, 0x04, 0x0c, 0xb8, 0x3c, 0x4f, 0x43, 0x16, 0x5c, 0xf8, 0x93, 0xe3, 0xdc, 0x55, 0xb0, 0xf1, 0xbc, 0x91, 0x48, 0x3c, 0x81, 0x96, 0x4c, 0xd6, 0xa8, 0x51, 0x23, 0xa4, 0x5b, 0xc2, 0xe0, 0x04, 0xdf, 0xb2, 0x05, 0x34, 0x87, 0x90, 0x39, 0x75, 0x1b, 0x40, 0xd5, 0xc1, 0xc2, 0x95, 0xbd, 0x37, 0x8d, 0x18, 0xc8, 0xbd, 0x61, 0x69, 0x82, 0xf5, 0x2a, 0x61, 0xce, 0x0d, 0x66, 0xb1, 0x25, 0xef, 0x1b, 0xb1, 0x64, 0x11, 0xb9, 0x8f, 0x09, 0xcc, 0x3e, 0xde, 0xee, 0x6c, 0x55, 0xa0, 0xf0, 0x01, 0x6e, 0x9c, 0xf0, 0xdd, 0x92, 0xb0, 0xe9, 0x60, 0x05, 0x80, 0x6d, 0x5a, 0xa3, 0xbb, 0xc6, 0x98, 0x60, 0xbd, 0x02, 0xa9, 0x5c, 0x39, 0x0d, 0x8a, 0x20, 0x91, 0x04, 0x61, 0x57, 0x2f, 0x4a, 0x1e, 0x78, 0x92, 0x9a, 0x2d, 0x63, 0xd8, 0x36, 0x63, 0x6e, 0xe7, 0xf0, 0x25, 0xb0, 0x1c, 0xe5, 0xcb, 0x32, 0xb8, 0xe4, 0xfd, 0x1a, 0x72, 0xb0, 0x8d, 0x8b, 0xaa, 0x83, 0x05, 0xcf, 0xc9, 0xc3, 0x3e, 0x0d, 0x1e, 0xff, 0x35, 0x50, 0x07, 0x24, 0xff, 0x56, 0xf8, 0x83, 0x0c, 0x85, 0x48, 0x39, 0xed, 0xae, 0x5f, 0x32, 0x37, 0x6b, 0x6e, 0xc3, 0x35, 0xd5, 0x7d, 0x2f, 0x1e, 0xcf, 0x88, 0xda, 0xf5, 0xcf, 0x2f, 0x3b, 0xc8, 0x4f, 0x91, 0x9c, 0xec, 0x28, 0x1e, 0xc8, 0x38, 0x7d, 0x7f, 0x09, 0xa2, 0xf1, 0x63, 0xb0, 0xbe, 0x5f, 0x65, 0x61, 0x7d, 0xff, 0xb1, 0x33, 0xf6, 0xae, 0x78, 0xd6, 0xf7, 0xe2, 0xa0, 0x5b, 0x39, 0x88, 0xde, 0x7f, 0x42, 0xe8, 0xd6, 0x14, 0x26, 0xfe, 0x07, 0xa0, 0x93, 0xbb, 0xca, 0x85, 0x97, 0xa7, 0xaa, 0xe2, 0x4b, 0x13, 0xc9, 0x25, 0x7b, 0x2c, 0x43, 0xb6, 0x58, 0x70, 0xfc, 0xa2, 0xc4, 0xee, 0xa7, 0x1b, 0xe6, 0x72, 0xb8, 0xa6, 0xa5, 0xca, 0x2c, 0x5d, 0xb9, 0xea, 0x08, 0x80, 0xac, 0xb0, 0xab, 0x90, 0x02, 0xbb, 0x80, 0x88, 0xf5, 0x6c, 0x6c, 0x84, 0x5d, 0x90, 0xfd, 0xe1, 0x9b, 0xb8, 0x8e, 0x43, 0x65, 0x1d, 0x1d, 0xef, 0x88, 0x43, 0xa6, 0xc4, 0xd0, 0x22, 0xcd, 0xa6, 0x08, 0x49, 0x7c, 0xc3, 0xd2, 0x15, 0x2f, 0xaf, 0xe5, 0x0e, 0xf0, 0x0e, 0x3f, 0x87, 0x08, 0xbe, 0xc9, 0xc2, 0x2a, 0x8c, 0x6c, 0x44, 0xd6, 0x9d, 0x3f, 0xab, 0x06, 0x4a, 0x08, 0xad, 0x99, 0xf5, 0x5e, 0xe9, 0xb1, 0xa1, 0xd2, 0x00, 0x2b, 0x5f, 0x0b, 0xc0, 0xe9, 0xb3, 0x08, 0x17, 0x4b, 0xf0, 0x56, 0x10, 0x11, 0xd7, 0x9b, 0x2c, 0x5c, 0x6e, 0x3f, 0x11, 0x47, 0xef, 0x1b, 0x16, 0x06, 0xb3, 0xa3, 0x6e, 0x4e, 0x97, 0x64, 0x46, 0x1f, 0xed, 0x83, 0x79, 0xf7, 0xc0, 0x37, 0x39, 0xf0, 0x32, 0x08, 0x46, 0xb3, 0x75, 0x4e, 0x8e, 0xd9, 0xfa, 0xe0, 0x03, 0x6d, 0x76, 0x95, 0x10, 0x59, 0x59, 0x4d, 0x0c, 0xd6, 0x23, 0xe3, 0x1a, 0xd8, 0xe7, 0xc6, 0x29, 0xe0, 0x3e, 0x80, 0x0a, 0x68, 0x04, 0xaf, 0x9a, 0x0a, 0xb1, 0xc0, 0xde, 0xf0, 0x91, 0x6b, 0x55, 0x98, 0x1b, 0xe0, 0x4d, 0x8e, 0x98, 0xb5, 0x52, 0x2a, 0xc0, 0x38, 0x04, 0x6f, 0xef, 0x84, 0x84, 0xe7, 0x47, 0x36, 0x2b, 0x41, 0x56, 0x12, 0x31, 0xc3, 0xd2, 0x64, 0x25, 0x0f, 0x37, 0xd8, 0x91, 0x2e, 0xa3, 0xa9, 0x50, 0x4e, 0x19, 0xd2, 0x91, 0xa8, 0xfe, 0xd6, 0xd7, 0x0e, 0x2c, 0x27, 0xd7, 0xf9, 0x4d, 0x96, 0x33, 0x1b, 0x20, 0x5f, 0xac, 0x01, 0xb3, 0xb3, 0x24, 0xec, 0x6e, 0x45, 0x68, 0xb1, 0x9a, 0xa3, 0x14, 0x5a, 0x84, 0x9d, 0x96, 0xed, 0xb9, 0x1e, 0x53, 0x15, 0x71, 0x33, 0x9b, 0xdb, 0xd2, 0x8b, 0xcb, 0x5b, 0x3e, 0x5f, 0xb4, 0x34, 0x65, 0xf2, 0x36, 0x47, 0xbe, 0x68, 0xcf, 0xb6, 0x10, 0x2a, 0xfc, 0x1d, 0x5d, 0x7f, 0x74, 0x4e, 0xcb, 0x02, 0x14, 0xcc, 0xdb, 0xe4, 0x11, 0x7d, 0xc1, 0xfc, 0x9c, 0x9e, 0x19, 0x6d, 0xd7, 0xcb, 0x46, 0x21, 0x6e, 0xe3, 0x40, 0x84, 0x45, 0xa8, 0x48, 0xa1, 0xfb, 0x08, 0x37, 0x80, 0x93, 0x60, 0x8d, 0xd6, 0xad, 0xec, 0x8b, 0xd6, 0x78, 0xa3, 0x50, 0x8b, 0x0a, 0x05, 0x97, 0x62, 0xc1, 0x1a, 0x14, 0xc0, 0x41, 0x3d, 0x1a, 0xad, 0x63, 0xb1, 0x1a, 0x7f, 0x41, 0xc8, 0x3a, 0x94, 0xa5, 0x39, 0x25, 0xce, 0xf1, 0x06, 0x91, 0xf5, 0x88, 0xa0, 0x0c, 0x95, 0xa6, 0x84, 0x9e, 0x28, 0x55, 0xce, 0xa4, 0x02, 0x35, 0x04, 0x65, 0x94, 0x1a, 0xac, 0x19, 0x04, 0xbd, 0x3c, 0x1d, 0x78, 0xde, 0xce, 0xb5, 0xa5, 0x4a, 0x3d, 0x88, 0xd8, 0xdb, 0x18, 0xdf, 0x0f, 0x95, 0xae, 0x42, 0x0d, 0x8a, 0x50, 0xdf, 0x8a, 0x2e, 0x98, 0x4e, 0x22, 0x26, 0xdf, 0x29, 0x80, 0x4f, 0x62, 0xe4, 0xde, 0x5f, 0x26, 0x09, 0xd2, 0x30, 0xb0, 0x1d, 0xe1, 0x48, 0x0d, 0x8d, 0x54, 0xaf, 0x37, 0x30, 0x55, 0x5a, 0x34, 0xe0, 0x64, 0x89, 0x2f, 0x4e, 0x75, 0x8a, 0xa8, 0xdc, 0x71, 0x01, 0xba, 0xaa, 0xe7, 0xd7, 0x0e, 0x10, 0xda, 0xcd, 0x35, 0xd8, 0xcf, 0x4d, 0x4c, 0xd1, 0x41, 0xb2, 0x8c, 0xee, 0x94, 0x8e, 0x00, 0x01, 0x15, 0x96, 0xc1, 0x50, 0x16, 0x0d, 0x16, 0x39, 0x42, 0x5a, 0x23, 0xda, 0x40, 0x0f, 0xc0, 0x02, 0x3f, 0x64, 0x78, 0x38, 0x9a, 0x5d, 0xe5, 0x80, 0x19, 0xc0, 0x02, 0x98, 0xf0, 0x33, 0x71, 0xcc, 0xc5, 0x0a, 0xe9, 0x01, 0x51, 0x43, 0x15, 0x0a, 0x01, 0xb1, 0x0d, 0x8f, 0x2d, 0x00, 0x4a, 0x70, 0x80, 0xe1, 0x82, 0x02, 0x6d, 0x33, 0x95, 0x01, 0x2f, 0x8b, 0x3c, 0x21, 0x2a, 0x93, 0x10, 0x2a, 0x23, 0x18, 0x60, 0x45, 0x15, 0x80, 0xdf, 0x35, 0xea, 0x1c, 0xd9, 0x28, 0x35, 0x04, 0x5f, 0x10, 0xf4, 0x9b, 0x41, 0xd1, 0x80, 0xd0, 0xbd, 0xec, 0xa8, 0x00, 0x22, 0xb1, 0xe4, 0x91, 0xc4, 0xc8, 0x50, 0xb8, 0x88, 0xde, 0x43, 0xc8, 0x54, 0xa2, 0x29, 0xb6, 0x43, 0xb5, 0xc4, 0x55, 0x0f, 0x86, 0x30, 0x86, 0xf2, 0x90, 0x9a, 0x7e, 0x64, 0x0c, 0xe0, 0x2c, 0x32, 0x92, 0xea, 0xcd, 0x9a, 0x2b, 0x7a, 0x72, 0xac, 0xf9, 0x6a, 0xa8, 0x8e, 0x8d, 0x64, 0x27, 0x3f, 0xa6, 0x1e, 0x26, 0x41, 0xb5, 0x91, 0x64, 0xe5, 0x7a, 0xf9, 0x03, 0xc1, 0x79, 0x0d, 0x04, 0x07, 0xc1, 0x37, 0x9a, 0xb0, 0x4e, 0x38, 0xd6, 0x10, 0x61, 0x1e, 0xf5, 0x15, 0x07, 0x6c, 0xeb, 0x78, 0xf8, 0x41, 0x8a, 0x1f, 0x41, 0x3f, 0xfc, 0x22, 0x12, 0x2d, 0x8b, 0x1c, 0x56, 0x64, 0x78, 0xfb, 0xb6, 0x25, 0x7a, 0x42, 0x1b, 0x2b, 0xa7, 0x49, 0x65, 0x09, 0xcc, 0x91, 0x38, 0x1f, 0x35, 0xa3, 0x63, 0x59, 0x22, 0x25, 0xed, 0xed, 0xeb, 0x77, 0x5e, 0x6d, 0xd4, 0x46, 0xe0, 0x51, 0xdc, 0x56, 0x1d, 0xb4, 0x78, 0xc0, 0x13, 0xfe, 0x35, 0x14, 0x9c, 0x6b, 0xd6, 0xab, 0xe1, 0x73, 0xf3, 0x5f, 0xd0, 0x50, 0x16, 0x13, 0x5f, 0x1c, 0xbd, 0xaf, 0xf0, 0x85, 0x9c, 0xdb, 0xad, 0x5f, 0x6a, 0xfa, 0x81, 0x04, 0x53, 0x9c, 0xeb, 0xc0, 0x77, 0x19, 0x7f, 0xaa, 0x40, 0x95, 0x13, 0xe4, 0x14, 0x2f, 0x75, 0xfb, 0x27, 0x7c, 0xf2, 0xab, 0x28, 0x60, 0x66, 0x1d, 0x72, 0xdd, 0xce, 0x37, 0x37, 0x0c, 0x92, 0x40, 0x15, 0xb3, 0xb6, 0xa6, 0x71, 0xde, 0x67, 0xc4, 0xe1, 0x79, 0x50, 0xca, 0x53, 0x34, 0xdb, 0xad, 0xda, 0xd8, 0x6a, 0xa7, 0x09, 0x68, 0x1a, 0x5f, 0x9b, 0x7b, 0x2e, 0x6a, 0x45, 0x90, 0x5d, 0x34, 0xeb, 0x41, 0x1b, 0x42, 0x3d, 0xe3, 0x83, 0xa4, 0xbc, 0x3f, 0x61, 0xad, 0x17, 0xcf, 0x2d, 0x35, 0xe7, 0xd5, 0x39, 0x4c, 0xab, 0x15, 0x61, 0x8f, 0x36, 0xba, 0x0d, 0x5a, 0xec, 0x9c, 0xf4, 0x1a, 0x2a, 0x99, 0xf5, 0x8a, 0xcd, 0x90, 0x0a, 0xd3, 0xbd, 0x56, 0x83, 0x2f, 0x20, 0x96, 0xdb, 0xd3, 0xaa, 0xd7, 0x1c, 0xaa, 0x23, 0x1d, 0x86, 0x42, 0xa9, 0x7a, 0xa3, 0xae, 0xfa, 0x42, 0x67, 0x75, 0xd4, 0x30, 0xa6, 0xd7, 0x4f, 0x44, 0xb4, 0x49, 0xac, 0x48, 0x4d, 0x60, 0xb5, 0x8c, 0x1a, 0x2a, 0xaa, 0xa7, 0xbe, 0xcf, 0x4a, 0x45, 0x79, 0x00, 0x88, 0x2a, 0x80, 0xf3, 0xa9, 0xa4, 0x20, 0xa5, 0xf5, 0x57, 0xbd, 0x4e, 0xea, 0x54, 0x60, 0xcd, 0x94, 0x76, 0xd0, 0x3c, 0x01, 0x4c, 0xe8, 0x15, 0xa9, 0xdf, 0x8a, 0x7a, 0x35, 0x13, 0xb6, 0xa1, 0xf8, 0xbd, 0x6f, 0xd4, 0x0b, 0x40, 0x89, 0x7d, 0x19, 0x3d, 0x68, 0x40, 0x13, 0x67, 0x83, 0x86, 0x51, 0x67, 0x80, 0x2f, 0xd2, 0xb5, 0x5b, 0x0a, 0x82, 0x18, 0x37, 0x01, 0xa0, 0x21, 0x21, 0x81, 0xe2, 0x23, 0x0d, 0xd9, 0x56, 0x21, 0xa8, 0xe0, 0xd5, 0x83, 0x64, 0xe5, 0x44, 0x99, 0x64, 0xee, 0xe1, 0x5b, 0x36, 0x4d, 0x1b, 0xcb, 0x5c, 0x2e, 0x4a, 0xf5, 0x6d, 0xae, 0xfa, 0x55, 0x7e, 0xf3, 0xc1, 0x06, 0x9b, 0x48, 0xf0, 0x9f, 0xa7, 0xd9, 0x42, 0x1f, 0x9d, 0xed, 0xeb, 0xd2, 0xa1, 0x3b, 0xa7, 0xb4, 0x66, 0x33, 0x97, 0x97, 0x80, 0xdd, 0x9d, 0x24, 0x3a, 0xdf, 0xbb, 0xcc, 0x23, 0x4f, 0x8f, 0x69, 0x0d, 0xf9, 0x62, 0xf3, 0xbe, 0x45, 0x69, 0x27, 0xd6, 0xb7, 0xb9, 0x12, 0xb7, 0x3b, 0x58, 0x2a, 0xfe, 0xab, 0x66, 0x5e, 0xbe, 0x49, 0x9d, 0x3f, 0x0e, 0xb4, 0x29, 0xe1, 0xe4, 0x91, 0xa2, 0xb4, 0xde, 0xd5, 0x42, 0x45, 0x41, 0x32, 0xdf, 0x66, 0x23, 0xae, 0x26, 0x60, 0xf1, 0x3a, 0xee, 0x1e, 0x12, 0x45, 0x58, 0x29, 0xaf, 0x7e, 0xd8, 0x92, 0x81, 0xb6, 0xac, 0x50, 0x45, 0xa3, 0x8e, 0x17, 0x5b, 0xbf, 0x53, 0xe0, 0xf8, 0x93, 0xe0, 0xba, 0x49, 0xe6, 0x4a, 0x53, 0xe6, 0xdd, 0x42, 0xc3, 0x2c, 0xc0, 0x7f, 0x93, 0x45, 0x32, 0x59, 0x5a, 0xe5, 0x08, 0xcd, 0x5e, 0xec, 0x64, 0x4c, 0xeb, 0x87, 0x63, 0x0b, 0xc1, 0xbf, 0x9b, 0xfe, 0xa8, 0x61, 0xdd, 0x40, 0x67, 0xe1, 0x8d, 0xc0, 0x58, 0xad, 0x0a, 0x85, 0xe0, 0x23, 0x51, 0x34, 0x8f, 0x08, 0x18, 0x43, 0xd3, 0x53, 0xdc, 0x16, 0x91, 0xd8, 0x22, 0xc0, 0x0f, 0xc4, 0x99, 0x8e, 0x15, 0xe6, 0x87, 0x7f, 0x06, 0xc3, 0xb3, 0x47, 0x24, 0x6c, 0xce, 0x22, 0xf1, 0x6c, 0x0a, 0xc2, 0xa4, 0xd5, 0x36, 0x89, 0x9b, 0xaa, 0x07, 0xca, 0xb3, 0xfd, 0x89, 0x81, 0x9a, 0x6d, 0x00, 0xce, 0x6d, 0x7f, 0x25, 0x39, 0x28, 0x9f, 0xab, 0xc0, 0x75, 0x99, 0x84, 0x89, 0xed, 0x2c, 0x17, 0xb7, 0xe9, 0x45, 0xcb, 0x16, 0xc7, 0xc7, 0x58, 0x47, 0x8d, 0xce, 0x6a, 0x55, 0x64, 0xd0, 0x94, 0xfd, 0xe1, 0xd0, 0x5b, 0x8e, 0x38, 0xf9, 0xf5, 0x39, 0x89, 0x6e, 0x1f, 0x50, 0xb4, 0xa1, 0x13, 0xd9, 0xac, 0x33, 0x99, 0xb7, 0xb0, 0x63, 0xfb, 0x9f, 0x60, 0x20, 0xd6, 0xc3, 0xbf, 0x00, 0xea, 0x8f, 0x47, 0x04, 0xf9, 0x7d, 0x63, 0xb2, 0x06, 0x11, 0x70, 0xdb, 0xaf, 0xcb, 0x6c, 0xca, 0xfc, 0x55, 0xfd, 0xed, 0x6a, 0xfb, 0x72, 0xdd, 0x76, 0x9b, 0x7f, 0xb0, 0xef, 0x73, 0xeb, 0x06, 0xe6, 0xb3, 0xad, 0xc6, 0x5c, 0x08, 0xb4, 0x32, 0xa8, 0x12, 0x1c, 0xea, 0x88, 0x37, 0x55, 0xbf, 0x1c, 0x52, 0xa4, 0x44, 0x54, 0x0a, 0xf0, 0xf4, 0x8d, 0x44, 0x94, 0x13, 0xd0, 0xad, 0x05, 0xa2, 0xd5, 0x41, 0x22, 0xad, 0x1c, 0x2e, 0x72, 0xd6, 0x11, 0xab, 0xba, 0x50, 0x43, 0xaf, 0x3d, 0x28, 0x99, 0xdb, 0xd3, 0xe9, 0x29, 0xd5, 0xdf, 0xb2, 0xcc, 0xd9, 0xc5, 0x31, 0x8b, 0xbe, 0xcd, 0x41, 0x96, 0x1d, 0xe2, 0x6f, 0x17, 0x8e, 0xac, 0xd9, 0x16, 0x41, 0x09, 0x36, 0x10, 0x97, 0xe4, 0x18, 0x9d, 0xd9, 0xb6, 0x80, 0x1d, 0xe3, 0x5d, 0x82, 0xcd, 0xa5, 0x1e, 0x9d, 0xa8, 0x16, 0xc8, 0x35, 0x65, 0xd4, 0x7d, 0xea, 0xfa, 0x62, 0x58, 0x83, 0x77, 0x79, 0x2a, 0x5f, 0x3e, 0x56, 0x53, 0x8b, 0xa8, 0x72, 0x49, 0xd7, 0xd6, 0x26, 0x9a, 0x90, 0x89, 0x4a, 0x83, 0x85, 0x40, 0x08, 0xde, 0xf1, 0xe5, 0x2b, 0x2b, 0xf2, 0x86, 0x3d, 0x12, 0xce, 0x82, 0x6c, 0xf8, 0xd7, 0x71, 0x5a, 0x7f, 0x97, 0x03, 0xfa, 0xd4, 0x12, 0xce, 0x8d, 0x8f, 0xcd, 0x1c, 0x94, 0xa9, 0xb0, 0xfb, 0x63, 0x0b, 0x6a, 0xe0, 0xe5, 0x1b, 0x36, 0x7b, 0x71, 0x8e, 0x93, 0xbb, 0x34, 0xeb, 0x76, 0x85, 0xec, 0x3e, 0xaa, 0x9c, 0x52, 0x6d, 0xca, 0x7a, 0xc0, 0xbf, 0xad, 0xbd, 0x0c, 0x3a, 0x0c, 0xce, 0xa6, 0xe2, 0xbf, 0x6c, 0x16, 0xdd, 0x91, 0xfc, 0x8f, 0xef, 0x58, 0x44, 0x55, 0x71, 0xf1, 0xc4, 0x77, 0x79, 0xb8, 0x85, 0x12, 0xc5, 0xa5, 0x39, 0x8d, 0xd5, 0xe7, 0xb4, 0x73, 0x6d, 0x8a, 0x81, 0xf7, 0xbe, 0x3b, 0x00, 0x73, 0x2a, 0xf1, 0x04, 0xff, 0x2e, 0x0b, 0xe6, 0x49, 0x56, 0x52, 0x8a, 0xa3, 0x62, 0xce, 0x87, 0x9b, 0x94, 0x20, 0x30, 0x2c, 0xd6, 0xa9, 0x3c, 0x3a, 0xd9, 0x77, 0x99, 0x0a, 0x21, 0x3e, 0x11, 0x7b, 0xe9, 0xdb, 0x37, 0x54, 0x70, 0x4c, 0x12, 0xab, 0xa0, 0xab, 0xa9, 0x34, 0x78, 0xd3, 0xc5, 0xe0, 0x54, 0xc9, 0x2e, 0x9a, 0x77, 0x09, 0xe7, 0xe1, 0x79, 0x4f, 0x0e, 0x34, 0xc3, 0x41, 0x43, 0xe4, 0x40, 0x87, 0xcb, 0xe1, 0xe1, 0x7f, 0x6b, 0x27, 0x54, 0x1f, 0xe2, 0xd7, 0x14, 0xab, 0xb6, 0x4d, 0x7f, 0x62, 0xa6, 0x82, 0x6d, 0x88, 0x6c, 0x49, 0xa9, 0xfb, 0x58, 0x7c, 0xcf, 0xa0, 0xa9, 0x6a, 0x04, 0xcd, 0x6b, 0xcd, 0x39, 0xcf, 0xab, 0x31, 0x5f, 0xe1, 0x30, 0x99, 0x9d, 0xef, 0xde, 0x5a, 0x6b, 0xe0, 0x0e, 0x68, 0xd6, 0xa9, 0xc3, 0xb5, 0x96, 0x63, 0x8c, 0x31, 0x17, 0xf3, 0x7d, 0x97, 0xcb, 0x35, 0xd9, 0x91, 0x5b, 0x21, 0x59, 0xc0, 0x64, 0xf4, 0x06, 0x52, 0xc2, 0x3b, 0xf0, 0xc6, 0x9c, 0xc6, 0xb2, 0x74, 0x7b, 0x31, 0xe0, 0xdd, 0xe5, 0x77, 0x5d, 0x88, 0xd7, 0x0f, 0x2c, 0x60, 0x08, 0xda, 0x03, 0xb1, 0xe1, 0x2d, 0xb2, 0x4d, 0x86, 0x4d, 0x88, 0xe1, 0x09, 0x6f, 0xd5, 0x29, 0x1d, 0xdc, 0x58, 0xd1, 0xf3, 0x12, 0x70, 0xc9, 0x52, 0x3a, 0x5d, 0x0d, 0xd7, 0x3b, 0xc0, 0x3e, 0x92, 0x4e, 0xb7, 0x7d, 0xb7, 0x88, 0x20, 0x9b, 0x51, 0xbb, 0x10, 0xdd, 0xf1, 0x03, 0x58, 0x1a, 0x09, 0x0c, 0x5f, 0x5e, 0x79, 0x57, 0x24, 0x1b, 0x56, 0x5b, 0xc4, 0xf3, 0x6b, 0x50, 0x4f, 0x6e, 0x4f, 0xc6, 0xcf, 0x82, 0xa6, 0xc0, 0x0d, 0x24, 0xf7, 0x78, 0x66, 0xc7, 0x8e, 0x13, 0xd1, 0x80, 0xe1, 0x8c, 0x7b, 0xf4, 0xd1, 0x18, 0xe9, 0x63, 0x11, 0x7a, 0x48, 0x88, 0xe3, 0xde, 0xfb, 0xa1, 0xa3, 0xbb, 0x86, 0xab, 0xb0, 0x5f, 0x1f, 0x8e, 0x85, 0x01, 0xb2, 0x3f, 0xea, 0x31, 0x18, 0x95, 0xd7, 0x6c, 0x69, 0x0e, 0x71, 0x64, 0xe0, 0x51, 0xbe, 0x92, 0xbd, 0xe0, 0x3a, 0x4b, 0xed, 0x0d, 0x38, 0x07, 0x51, 0x4b, 0x30, 0xc8, 0x32, 0xcf, 0x78, 0x0b, 0x48, 0x60, 0xe2, 0x6b, 0x9a, 0xd9, 0xb6, 0x00, 0xc5, 0x7f, 0x7d, 0x99, 0x50, 0xfc, 0x03, 0x10, 0x63, 0xb9, 0x42, 0xa8, 0x66, 0xe3, 0x8a, 0xaf, 0x11, 0x82, 0xf7, 0x6b, 0x58, 0xf5, 0x28, 0x30, 0xff, 0x45, 0x3b, 0xdd, 0x10, 0x7f, 0x2c, 0x5b, 0xe9, 0x6d, 0x1f, 0x51, 0xf6, 0x78, 0x09, 0xbb, 0xcc, 0x05, 0xad, 0x66, 0x4f, 0x23, 0xf3, 0x99, 0xa3, 0xa9, 0x2e, 0xe8, 0x80, 0xba, 0x18, 0xb4, 0x35, 0xa9, 0x0b, 0x4a, 0x37, 0xdb, 0x28, 0x6d, 0x19, 0xee, 0x52, 0x00, 0x97, 0x01, 0x23, 0x16, 0x90, 0x17, 0xa4, 0xa0, 0x02, 0x7e, 0x23, 0xd8, 0x2b, 0x51, 0x39, 0x13, 0xce, 0x07, 0x2f, 0x60, 0x85, 0x37, 0x80, 0x7f, 0xb5, 0x1b, 0xf0, 0x44, 0x15, 0xfe, 0xac, 0x2e, 0xfc, 0x1e, 0x0d, 0xcd, 0x77, 0x1a, 0x18, 0x1a, 0xfd, 0x88, 0x11, 0xdd, 0x01, 0xa0, 0xa0, 0x75, 0x3a, 0xb2, 0x3a, 0x4a, 0xe3, 0x9a, 0x15, 0x5c, 0xe4, 0x42, 0xad, 0xd5, 0x40, 0x2f, 0x89, 0x92, 0x59, 0x84, 0x09, 0xd1, 0x9a, 0x68, 0xa1, 0x0c, 0x4d, 0x04, 0x8f, 0x60, 0xaa, 0xdd, 0x8d, 0xa2, 0x77, 0xb6, 0xfb, 0xff, 0x6e, 0xdd, 0xb0, 0x07, 0xf5, 0xff, 0xd1, 0x44, 0x0f, 0x7d, 0x60, 0x6d, 0x4c, 0x64, 0x70, 0x9a, 0x25, 0xc8, 0x85, 0xc9, 0xe7, 0xe5, 0x27, 0x67, 0x6a, 0x11, 0xa5, 0x93, 0x5d, 0x0e, 0x45, 0xcf, 0x1e, 0x05, 0xd5, 0xb5, 0x15, 0xe7, 0x38, 0xf4, 0x5d, 0xa4, 0x61, 0x63, 0x3b, 0x63, 0x62, 0xc0, 0xd0, 0x3f, 0x96, 0x58, 0x91, 0x71, 0x13, 0x9f, 0xb8, 0xe9, 0xcd, 0x1e, 0x2e, 0x11, 0x13, 0xfb, 0xdf, 0x88, 0x09, 0xb6, 0xdf, 0x0c, 0xd8, 0x1a, 0x26, 0x65, 0x51, 0x17, 0x5f, 0xe7, 0xa8, 0x59, 0x72, 0xcc, 0x61, 0xf1, 0xf9, 0x4e, 0x89, 0xcb, 0xf1, 0x63, 0x5c, 0xb3, 0xc0, 0x63, 0x20, 0x47, 0x0b, 0x46, 0x21, 0x5d, 0xe7, 0x00, 0x56, 0x56, 0x51, 0xa1, 0x4a, 0x62, 0x02, 0x8b, 0x09, 0xbd, 0x50, 0xa5, 0x72, 0x8e, 0xcd, 0x9d, 0xf6, 0x76, 0x26, 0xba, 0x4c, 0x57, 0x33, 0x5d, 0x8c, 0x18, 0x6f, 0xa6, 0x43, 0x72, 0x7f, 0xde, 0x47, 0xba, 0x33, 0xaf, 0x93, 0xe5, 0x6c, 0x0e, 0x9b, 0x9b, 0xaf, 0x43, 0xbe, 0xb2, 0xd4, 0xb1, 0xa1, 0xa3, 0xd4, 0x6c, 0x30, 0xd2, 0xd4, 0xdd, 0x25, 0x18, 0x94, 0x09, 0x30, 0xe4, 0x72, 0xc6, 0x64, 0x5e, 0x09, 0xc9, 0x53, 0xcb, 0x26, 0x61, 0x2c, 0xce, 0xab, 0x70, 0x1b, 0x8d, 0xc5, 0x2d, 0x5b, 0x71, 0xdb, 0x9d, 0x22, 0x47, 0xc6, 0xa0, 0xd9, 0xd8, 0x7c, 0x15, 0x6c, 0x3e, 0xde, 0x4a, 0x35, 0xa5, 0x88, 0x5b, 0xa2, 0x26, 0x8e, 0x36, 0xcd, 0x52, 0x8c, 0xfc, 0x79, 0xe5, 0x2d, 0x0b, 0x48, 0xb2, 0x8d, 0xb4, 0xf3, 0x8f, 0x97, 0xb9, 0xd8, 0x43, 0xe0, 0x50, 0x85, 0x59, 0xaf, 0x5d, 0xa3, 0x56, 0x00, 0x79, 0xa7, 0xc3, 0x36, 0x8b, 0xec, 0x6d, 0xdb, 0x83, 0xed, 0x0f, 0x64, 0xc6, 0x08, 0xda, 0x84, 0xe5, 0xfd, 0xe8, 0xae, 0x20, 0x72, 0x09, 0x70, 0x42, 0xf4, 0x6e, 0x2d, 0x77, 0x5e, 0xae, 0x36, 0xe7, 0xe5, 0xf1, 0x47, 0x4c, 0xc8, 0xfe, 0x16, 0xa0, 0x45, 0x64, 0x56, 0xd0, 0x37, 0x9d, 0xf4, 0x45, 0xcd, 0xa8, 0xd3, 0xd4, 0x84, 0xec, 0xa1, 0x54, 0x17, 0xcd, 0xd8, 0xe8, 0xd1, 0x9c, 0xe4, 0x66, 0x2b, 0x5b, 0x23, 0xa1, 0xba, 0xda, 0x27, 0x51, 0x08, 0xc5, 0x73, 0xb4, 0x4c, 0x53, 0xb9, 0x6c, 0x81, 0xcc, 0x86, 0xb5, 0x27, 0x6b, 0x7a, 0x45, 0xb5, 0x14, 0x68, 0xf9, 0x2b, 0xa9, 0x74, 0xdb, 0xbf, 0x80, 0xde, 0x5b, 0xb8, 0xc1, 0x9c, 0x09, 0x90, 0xd3, 0xf6, 0x10, 0xc7, 0xef, 0xb1, 0xc6, 0x13, 0x20, 0x5e, 0xfd, 0x1d, 0x58, 0x76, 0xe8, 0xa9, 0xd9, 0x39, 0x74, 0x06, 0xe9, 0x0c, 0xc9, 0x17, 0x6d, 0x0e, 0x55, 0x68, 0xda, 0x85, 0x2c, 0x2a, 0x87, 0xb2, 0x0d, 0xdb, 0x32, 0x14, 0x13, 0x26, 0xd8, 0xfa, 0x8d, 0x7b, 0x5e, 0x53, 0xee, 0xbb, 0x9a, 0xfb, 0x59, 0xe3, 0x2b, 0x62, 0x0b, 0xa9, 0x94, 0xc5, 0xfa, 0x79, 0x9d, 0xa5, 0x46, 0xc8, 0x11, 0x44, 0x7e, 0x65, 0x93, 0xf8, 0x5d, 0xb3, 0xf1, 0xef, 0xe2, 0xf2, 0x1c, 0xae, 0x73, 0x95, 0xa6, 0x98, 0x2a, 0x67, 0x78, 0x74, 0x83, 0x12, 0xe4, 0x83, 0xad, 0x40, 0xa1, 0x13, 0x21, 0xa5, 0x71, 0x27, 0xaf, 0xc4, 0xbe, 0xcb, 0x50, 0x6d, 0xe2, 0xd1, 0xef, 0x62, 0xfa, 0xfc, 0xff, 0xcc, 0xce, 0x89, 0xa3, 0xa7, 0x03, 0x89, 0xb8, 0x2b, 0xdd, 0x01, 0x71, 0xf7, 0x92, 0x0e, 0x08, 0xb6, 0x46, 0xdb, 0xe4, 0xdd, 0x25, 0x68, 0x09, 0x16, 0xca, 0xf0, 0x43, 0x90, 0x24, 0x5e, 0xe7, 0xc2, 0x1c, 0xc0, 0x3c, 0xf6, 0xb6, 0xb1, 0x7d, 0x22, 0x17, 0xec, 0xc8, 0xca, 0xde, 0x89, 0x5d, 0xad, 0x26, 0xbb, 0x2f, 0x43, 0xd2, 0xd8, 0xdc, 0x86, 0x4d, 0xcd, 0xd1, 0xb2, 0x1c, 0x0f, 0x39, 0x32, 0x1c, 0xe8, 0xfd, 0x07, 0xf6, 0x07, 0xfe, 0xd0, 0x33, 0xb7, 0xe4, 0x68, 0x45, 0x39, 0x3b, 0xae, 0x4f, 0xb4, 0xc1, 0x61, 0x2a, 0xe5, 0x56, 0x5f, 0x02, 0xfd, 0x99, 0xd9, 0xad, 0xce, 0x56, 0xd6, 0x28, 0x2c, 0x86, 0x97, 0xa3, 0x98, 0xc6, 0xeb, 0x88, 0xe1, 0x1d, 0xb7, 0x46, 0x8f, 0x54, 0x35, 0x6c, 0x21, 0x84, 0xc2, 0x4e, 0xcb, 0x79, 0xaa, 0x20, 0x74, 0x2a, 0x71, 0xca, 0xe1, 0x93, 0x72, 0xa7, 0xef, 0x2f, 0x41, 0x34, 0x58, 0xea, 0xfb, 0xae, 0x12, 0x05, 0x16, 0xa4, 0xba, 0xce, 0x41, 0x73, 0xdf, 0x86, 0x58, 0x2c, 0xaf, 0x0d, 0xd8, 0xcf, 0x66, 0x1c, 0xda, 0x05, 0x58, 0xa3, 0x16, 0x80, 0x80, 0x04, 0x82, 0x1a, 0x14, 0x81, 0x72, 0xe0, 0xc9, 0x02, 0x44, 0xe5, 0x34, 0x16, 0x7d, 0x47, 0x4d, 0x76, 0xf0, 0xb4, 0x84, 0xf8, 0xaf, 0x06, 0xdf, 0x4a, 0x47, 0xcc, 0xe7, 0x2e, 0x39, 0x81, 0xca, 0x77, 0xb0, 0x04, 0xa6, 0x80, 0xaf, 0xc1, 0x3d, 0xab, 0x4e, 0xf6, 0xfc, 0xb6, 0x5e, 0xf4, 0xde, 0x4f, 0xa5, 0xb3, 0x78, 0xc9, 0xb3, 0xb3, 0x1d, 0xe1, 0x67, 0xf5, 0xab, 0x90, 0xbf, 0xf7, 0x79, 0x48, 0x80, 0x11, 0xed, 0x43, 0x71, 0xbe, 0xa7, 0x04, 0xfc, 0x02, 0x30, 0x9a, 0x28, 0x66, 0xfe, 0x5d, 0x01, 0x8b, 0x2b, 0x7b, 0xc3, 0xb3, 0x42, 0xd6, 0xb4, 0x1d, 0x12, 0x7f, 0x9b, 0x4e, 0x80, 0x0e, 0x18, 0xe5, 0x79, 0x65, 0xcf, 0xea, 0xb4, 0xd5, 0xcc, 0x34, 0x43, 0x9b, 0xa6, 0x1b, 0xfa, 0x53, 0x3d, 0xf7, 0x92, 0xa0, 0xfa, 0x6a, 0x9b, 0x41, 0x44, 0x1b, 0xfe, 0x9b, 0xdc, 0xd7, 0xfd, 0x3c, 0x42, 0x33, 0x67, 0x7b, 0x90, 0x71, 0x9f, 0x7c, 0x4f, 0x26, 0x9a, 0x3c, 0x1f, 0x70, 0xc4, 0x1d, 0xd5, 0x6a, 0x13, 0x8d, 0x24, 0x64, 0x04, 0xf1, 0x07, 0x11, 0xe7, 0x18, 0xb8, 0xa4, 0x9a, 0x81, 0xbc, 0xc5, 0x54, 0x61, 0xc6, 0x3d, 0x69, 0x19, 0x6a, 0x5c, 0xd9, 0x15, 0x3a, 0xc5, 0x8c, 0x24, 0xdc, 0xea, 0x48, 0x13, 0x6b, 0xe0, 0x7e, 0xa7, 0x0e, 0x5b, 0xb5, 0xea, 0x07, 0x46, 0x74, 0x64, 0x35, 0xb9, 0xba, 0xcb, 0x20, 0xc5, 0xf0, 0xd8, 0x0d, 0x05, 0x51, 0xfd, 0xc4, 0x4c, 0x95, 0x40, 0xff, 0x57, 0x4d, 0x33, 0x0f, 0x08, 0xd6, 0xb6, 0x8c, 0xdf, 0x76, 0x74, 0x31, 0x52, 0x52, 0xbe, 0x4f, 0x94, 0x61, 0x2d, 0x19, 0xe6, 0xf3, 0x3e, 0x4b, 0x09, 0x56, 0x36, 0xce, 0x3d, 0x2f, 0xd8, 0xd9, 0x26, 0x4f, 0x17, 0xcb, 0x05, 0x36, 0x73, 0x9d, 0x2e, 0xde, 0x27, 0x52, 0x3d, 0xda, 0xa5, 0x33, 0x3d, 0x86, 0xe0, 0xa5, 0x6a, 0x79, 0x62, 0x9d, 0x7d, 0x47, 0xc9, 0x7e, 0xbe, 0x86, 0xe8, 0xe3, 0x55, 0x5c, 0xfb, 0x66, 0xe4, 0x88, 0xe0, 0xf2, 0x34, 0xde, 0x67, 0xa3, 0x90, 0x91, 0x43, 0x30, 0xad, 0x45, 0xa2, 0xeb, 0x61, 0xbf, 0xc9, 0x44, 0xba, 0xc6, 0xec, 0xe0, 0x24, 0xd6, 0x36, 0x52, 0x99, 0x81, 0xbb, 0xb2, 0x21, 0x2e, 0xb3, 0xf4, 0xf0, 0x0b, 0x68, 0x3f, 0x8c, 0xc8, 0x74, 0x3e, 0xbe, 0xcc, 0xcb, 0xea, 0x31, 0xad, 0x21, 0xab, 0x53, 0x1e, 0x96, 0x52, 0x95, 0x5d, 0x16, 0x47, 0x8b, 0xe8, 0x34, 0x7f, 0xaa, 0x69, 0x66, 0xe8, 0x3b, 0x6a, 0x9c, 0xc6, 0x29, 0x3e, 0x7b, 0x28, 0xe0, 0xa0, 0x18, 0x1d, 0xab, 0xf2, 0x32, 0x94, 0x2a, 0xdd, 0xae, 0x0e, 0xb6, 0xf1, 0x72, 0x66, 0x75, 0x0f, 0xbf, 0xcf, 0x52, 0xc0, 0xf4, 0x34, 0x94, 0x20, 0xad, 0x67, 0xe6, 0xa4, 0x4d, 0xd6, 0x31, 0xad, 0xd7, 0x13, 0x0e, 0xe2, 0x92, 0x5d, 0xc3, 0x1f, 0x58, 0x18, 0x7e, 0x07, 0xde, 0xda, 0x72, 0x35, 0xd7, 0x87, 0x1c, 0xb8, 0x7c, 0x11, 0xea, 0x97, 0x70, 0xe6, 0xfb, 0x11, 0x99, 0xba, 0xa1, 0x0b, 0xaf, 0xc2, 0xfa, 0x7d, 0xb2, 0x16, 0x1a, 0xd0, 0x96, 0xb6, 0x69, 0xb8, 0xed, 0x67, 0x91, 0x9d, 0x71, 0x72, 0x08, 0xfa, 0xf1, 0xb0, 0x62, 0xdb, 0xbb, 0x6d, 0xa2, 0x35, 0xc4, 0x8c, 0x07, 0xfd, 0x0b, 0xb3, 0x64, 0xea, 0xd6, 0x53, 0x42, 0x5d, 0x27, 0xa6, 0xa7, 0x34, 0xe3, 0xda, 0x1b, 0x55, 0xcd, 0xb0, 0xe0, 0x3e, 0xe4, 0x61, 0x57, 0x7e, 0x6a, 0xbe, 0xd6, 0x6c, 0x93, 0xad, 0xed, 0xff, 0x03, 0x38, 0x32, 0xb5, 0xa1, 0x12, 0x4b, 0x8d, 0x3e, 0x5a, 0x50, 0x91, 0x5c, 0x4d, 0xc1, 0xad, 0xe6, 0x6e, 0x5b, 0x29, 0x38, 0xa4, 0xe3, 0xf8, 0x72, 0xc2, 0x76, 0x1b, 0xa0, 0x63, 0x81, 0xca, 0x79, 0x33, 0x75, 0xb4, 0x67, 0xb4, 0x35, 0xdb, 0x2f, 0xa4, 0x36, 0x09, 0xfd, 0x2a, 0x2d, 0x68, 0xf6, 0x21, 0x0b, 0x00, 0x2c, 0xe2, 0xbb, 0xe5, 0x93, 0x77, 0xdc, 0xe0, 0x33, 0x02, 0x4b, 0x3e, 0x32, 0xcd, 0x44, 0x74, 0x21, 0x05, 0xff, 0x0e, 0xd2, 0xfb, 0xfc, 0x19, 0x62, 0xe0, 0xc8, 0xe3, 0x9c, 0x80, 0x4b, 0x80, 0xc2, 0x4f, 0x44, 0xc5, 0xf3, 0xf2, 0x8e, 0x2f, 0x27, 0x84, 0xf0, 0x88, 0xd6, 0x10, 0x35, 0x9e, 0x52, 0x25, 0xd2, 0x85, 0xff, 0x75, 0x51, 0x26, 0xb1, 0xbc, 0x92, 0x97, 0x03, 0x64, 0xf6, 0x04, 0x7c, 0x78, 0x90, 0xa2, 0x2d, 0xdb, 0x9a, 0xbc, 0x85, 0x96, 0x92, 0x26, 0xfd, 0x06, 0x99, 0x4c, 0x3b, 0x78, 0xc9, 0xb4, 0xe9, 0x93, 0xdd, 0x29, 0xee, 0x4f, 0xaf, 0xb1, 0xa3, 0xec, 0xe4, 0x5e, 0xca, 0x12, 0x3e, 0x39, 0x69, 0xea, 0x1e, 0x13, 0xde, 0x1c, 0xe1, 0x0a, 0x3f, 0x6b, 0xce, 0xda, 0xf4, 0x76, 0xdc, 0x6f, 0xec, 0xae, 0x26, 0x26, 0x75, 0xf6, 0x63, 0x30, 0xf3, 0xc8, 0x30, 0x04, 0x20, 0x81, 0xeb, 0x81, 0x29, 0x1f, 0xbe, 0x57, 0x2b, 0xac, 0xf0, 0x7f, 0xf8, 0xbd, 0xde, 0x8c, 0x8a, 0xe4, 0xf8, 0x99, 0x72, 0xa2, 0x99, 0xc5, 0x9b, 0xd7, 0x2b, 0x45, 0xe2, 0xc6, 0x70, 0xb2, 0x6d, 0x56, 0x4e, 0x5a, 0x96, 0xc7, 0xaf, 0xda, 0x73, 0xc2, 0x1e, 0x52, 0x90, 0x3a, 0x54, 0x07, 0xf1, 0x06, 0x24, 0x51, 0xdf, 0x8b, 0xca, 0x59, 0xd7, 0xd5, 0x1b, 0xfa, 0x50, 0xdb, 0x29, 0x8d, 0x0a, 0x13, 0x75, 0xd4, 0xa0, 0x81, 0x76, 0xbf, 0xba, 0x70, 0x9a, 0xd2, 0x70, 0xc0, 0x3e, 0xde, 0xd2, 0x75, 0x2a, 0x8a, 0xd0, 0xd3, 0xd3, 0x13, 0xb9, 0xd9, 0x68, 0xc1, 0x83, 0x63, 0x5c, 0xb8, 0x36, 0x16, 0x6d, 0xc1, 0xd9, 0x27, 0x60, 0xc4, 0xad, 0x72, 0xa1, 0xac, 0x46, 0xe8, 0xd3, 0x44, 0x0b, 0xa3, 0x0a, 0xf5, 0x51, 0x1c, 0x95, 0xba, 0x88, 0x45, 0x15, 0xa4, 0x1a, 0x20, 0xe6, 0x3d, 0xaf, 0x3e, 0x18, 0x56, 0xc5, 0xfa, 0x02, 0x34, 0x18, 0xb0, 0x49, 0x29, 0x66, 0x15, 0x5f, 0x71, 0xe0, 0x16, 0x6d, 0xe3, 0xfa, 0x29, 0x14, 0x64, 0xa0, 0x15, 0x34, 0x7e, 0x24, 0x1d, 0xf4, 0xff, 0x05, 0x88, 0xff, 0x6d, 0x2c, 0x8b, 0x42, 0xb3, 0x08, 0x8b, 0x1b, 0x96, 0xa3, 0xff, 0x5f, 0x72, 0x17, 0x7e, 0xdf, 0x3a, 0xc8, 0xd0, 0x93, 0x0e, 0xff, 0xf0, 0xeb, 0xe1, 0x9f, 0x09, 0xdd, 0x86, 0x3b, 0xcf, 0xa2, 0xe1, 0x50, 0x0d, 0x91, 0x89, 0x8d, 0x28, 0xfb, 0x8d, 0xa7, 0xee, 0x69, 0x72, 0xcd, 0xf7, 0xd5, 0x40, 0x0e, 0x27, 0xc3, 0xce, 0xa4, 0x34, 0xea, 0xba, 0x9c, 0x07, 0xd6, 0x1d, 0x20, 0xd5, 0x6b, 0xe1, 0x45, 0x5f, 0x34, 0xae, 0xb5, 0x9d, 0xee, 0x0b, 0x88, 0x54, 0x43, 0x1a, 0x14, 0xfc, 0x43, 0xd8, 0xdf, 0x8c, 0x88, 0xf1, 0x0e, 0xd4, 0x54, 0x19, 0xe6, 0x20, 0x86, 0xf1, 0x3b, 0x15, 0x93, 0x84, 0xe2, 0xda, 0xc7, 0xd9, 0xd3, 0x5d, 0x7d, 0x8e, 0x3a, 0xc1, 0x4c, 0x6c, 0x7f, 0x99, 0xde, 0xc6, 0x66, 0x1a, 0xd6, 0x5a, 0x57, 0x77, 0xe1, 0x1b, 0x77, 0x4d, 0xd3, 0x84, 0x55, 0x05, 0xac, 0x09, 0x8b, 0xb8, 0xda, 0x2e, 0x3c, 0x23, 0xd6, 0x55, 0xe0, 0x8b, 0x10, 0x43, 0x65, 0x62, 0x74, 0x2f, 0x94, 0xf0, 0x92, 0x16, 0x5f, 0x20, 0xfd, 0x64, 0x8c, 0x0a, 0xfd, 0xd6, 0xb1, 0x96, 0x4c, 0xa5, 0x51, 0x3d, 0x45, 0x87, 0xf7, 0x22, 0xe3, 0x02, 0x5e, 0x80, 0x19, 0x4f, 0x0d, 0xff, 0x90, 0x61, 0xea, 0xfd, 0xac, 0x2f, 0xe2, 0x3c, 0x9d, 0xd5, 0x5b, 0xcf, 0xe4, 0xdf, 0x49, 0xdb, 0xae, 0x68, 0xee, 0x64, 0x99, 0xca, 0xa1, 0x2a, 0x84, 0x8d, 0x2f, 0x1d, 0xcd, 0x28, 0x5b, 0x1f, 0x99, 0x61, 0xbb, 0x2d, 0x29, 0x75, 0x9f, 0xb2, 0x4f, 0x7c, 0xe7, 0x21, 0xe0, 0x12, 0x6c, 0x5d, 0xa8, 0xcc, 0x61, 0xd5, 0x6a, 0x2c, 0xbb, 0x0d, 0xb3, 0xf0, 0xcf, 0x85, 0x6f, 0x44, 0x2b, 0x92, 0xf9, 0x61, 0x93, 0xa5, 0x8f, 0x46, 0xd4, 0xdb, 0x3b, 0x43, 0x27, 0x11, 0x3f, 0x35, 0x75, 0x1f, 0xc4, 0xf1, 0xbf, 0xd1, 0x40, 0x20, 0x16, 0xa0, 0x95, 0x3d, 0x45, 0xa5, 0x1d, 0x8d, 0x0c, 0x95, 0xfe, 0x6b, 0x20, 0x2e, 0xe2, 0x66, 0x78, 0xfe, 0x26, 0x86, 0x63, 0x88, 0x03, 0x2e, 0x14, 0x1c, 0xa7, 0xe0, 0xcc, 0x69, 0x5f, 0xa4, 0x06, 0x53, 0xd5, 0x74, 0x6b, 0xa8, 0x9a, 0x01, 0xd5, 0xe9, 0x5f, 0x17, 0xb5, 0x5e, 0x91, 0x04, 0x4c, 0x68, 0xd3, 0x66, 0x6c, 0x82, 0xe3, 0x09, 0x88, 0xfb, 0x20, 0x04, 0xb4, 0xe0, 0x6e, 0x0d, 0x7d, 0x98, 0xda, 0x8b, 0x05, 0x67, 0x09, 0x87, 0x5f, 0x46, 0xbe, 0xee, 0x9a, 0x4b, 0xcf, 0x88, 0xf1, 0xe4, 0x6d, 0xa5, 0x1c, 0xf4, 0x00, 0x8a, 0x80, 0x84, 0x87, 0x37, 0xa8, 0x01, 0x54, 0xf7, 0xc7, 0x06, 0x34, 0x80, 0x66, 0xa9, 0xf0, 0xe0, 0x54, 0x94, 0x08, 0x9f, 0x3c, 0xf4, 0x38, 0x2d, 0x34, 0xfd, 0xe6, 0x35, 0x3a, 0xe7, 0x4e, 0x31, 0x6a, 0x7c, 0x7c, 0xdb, 0xda, 0x83, 0x52, 0x4a, 0x52, 0xb5, 0x7e, 0xdd, 0x08, 0x5e, 0x10, 0x86, 0x63, 0x57, 0x62, 0x7f, 0xf8, 0x89, 0xc5, 0x11, 0x5a, 0x31, 0x84, 0x09, 0x61, 0x0e, 0xd8, 0x5d, 0x7f, 0x4d, 0x38, 0x81, 0xeb, 0x22, 0x33, 0xfc, 0xfc, 0xe3, 0x64, 0xdb, 0x1e, 0x51, 0x2e, 0xc6, 0x24, 0xf2, 0xd8, 0xe7, 0x16, 0xd7, 0xd8, 0xee, 0xc6, 0x69, 0xad, 0xa4, 0xd7, 0xbe, 0xc2, 0xeb, 0xdf, 0xb6, 0xdd, 0x8d, 0x6e, 0x86, 0x16, 0xb8, 0x61, 0x09, 0xf7, 0xf0, 0xac, 0x71, 0xb6, 0xbb, 0x48, 0x25, 0xfa, 0x3d, 0xae, 0x23, 0x88, 0x1d, 0x1f, 0x27, 0xf3, 0xdf, 0xe5, 0x92, 0xce, 0x15, 0xbf, 0xc7, 0x51, 0x77, 0xdc, 0x0b, 0x52, 0x7b, 0x2f, 0x68, 0x11, 0xf9, 0xcb, 0x57, 0x53, 0x81, 0x8a, 0xa5, 0x4b, 0x93, 0xa8, 0xe9, 0x37, 0x8f, 0x49, 0xa1, 0xb5, 0xbd, 0x29, 0x00, 0x84, 0x03, 0xd5, 0x88, 0xa3, 0x7d, 0xaf, 0xa1, 0x6d, 0xde, 0x04, 0xc2, 0xeb, 0xbe, 0xee, 0x5a, 0x45, 0xb6, 0x57, 0x60, 0x9e, 0xb1, 0xa4, 0x7a, 0x1a, 0xf0, 0x83, 0x89, 0xde, 0x0c, 0x13, 0x84, 0x34, 0xa0, 0x9a, 0x48, 0x64, 0xf7, 0x80, 0x14, 0x9d, 0xba, 0x0c, 0xb9, 0x79, 0x82, 0xec, 0x1d, 0xd8, 0x69, 0x43, 0x69, 0x36, 0x50, 0x7d, 0x51, 0xd9, 0x36, 0x14, 0xcd, 0x92, 0x04, 0x9d, 0x70, 0x5e, 0x03, 0xc2, 0xec, 0xf0, 0x4a, 0xd6, 0xc4, 0xe2, 0x55, 0x7e, 0x07, 0xb5, 0xb4, 0x8d, 0x79, 0xd5, 0x18, 0x71, 0x11, 0x0a, 0xe5, 0x97, 0xa8, 0xb4, 0x11, 0x46, 0xa9, 0xa9, 0x32, 0x1d, 0xf6, 0xac, 0x86, 0x08, 0xcc, 0xda, 0xc8, 0x3c, 0x0c, 0x2a, 0xb3, 0x0d, 0x50, 0xba, 0xab, 0x54, 0xa8, 0x12, 0x47, 0x83, 0x61, 0xe6, 0x54, 0xa7, 0x4c, 0xd2, 0xf3, 0xa0, 0xe7, 0xbe, 0x42, 0xaf, 0xff, 0x3f, 0x6d, 0xe5, 0xbc, 0xf2, 0x6e, 0x67, 0x79, 0xc9, 0xc1, 0x30, 0xe6, 0x17, 0xd2, 0xf7, 0xec, 0xb7, 0xcd, 0x55, 0x2a, 0x9e, 0xea, 0xef, 0x18, 0xa7, 0x79, 0x9e, 0x8d, 0x3d, 0x48, 0xd4, 0x43, 0xbf, 0xd1, 0x6e, 0x4f, 0x83, 0x3d, 0x27, 0x8e, 0xf3, 0x67, 0x59, 0xf6, 0x33, 0x7f, 0x9b, 0xef, 0x80, 0x6b, 0x3f, 0xbe, 0xde, 0x05, 0x4a, 0xf9, 0x0f, 0x6c, 0x39, 0x89, 0xe7, 0x2b, 0x4b, 0x5e, 0x0b, 0xce, 0x65, 0x3c, 0xba, 0xda, 0xe9, 0xa5, 0x3e, 0xcf, 0x1c, 0xc5, 0x1c, 0x9e, 0xc0, 0x0d, 0xde, 0xdb, 0x28, 0x72, 0x0b, 0xa1, 0x23, 0xbd, 0xb0, 0x5b, 0x40, 0xfa, 0xf5, 0x69, 0x5f, 0x63, 0x50, 0x9b, 0x60, 0xab, 0x51, 0x0d, 0x33, 0x58, 0xec, 0xf1, 0x97, 0x1a, 0x59, 0xb4, 0xa1, 0x58, 0x5c, 0xac, 0xdf, 0xb6, 0xa6, 0xfb, 0xc1, 0x36, 0x46, 0x55, 0x3b, 0x50, 0x16, 0xf1, 0xd9, 0x62, 0xd7, 0x71, 0x7e, 0x9a, 0xad, 0x2d, 0xaf, 0xb5, 0xd8, 0x7b, 0xa3, 0xec, 0xf3, 0x6b, 0xbf, 0x19, 0x26, 0xa6, 0xe9, 0x7f, 0x1a, 0xf7, 0x01, 0x89, 0x3d, 0x90, 0x28, 0xb0, 0x04, 0x4e, 0x6e, 0x17, 0x72, 0xc1, 0xba, 0x2f, 0x44, 0x33, 0xa6, 0x24, 0x1c, 0x3b, 0x04, 0x02, 0x8c, 0x81, 0x94, 0xa1, 0xae, 0x7b, 0xea, 0x4f, 0xb8, 0x05, 0xcc, 0x2a, 0xa9, 0x36, 0x84, 0x34, 0x7a, 0xac, 0x35, 0xf6, 0x26, 0x1a, 0x65, 0x3b, 0x53, 0xe8, 0x5b, 0xa2, 0xda, 0xe6, 0x53, 0x1c, 0xa5, 0xfd, 0x69, 0x25, 0x68, 0x65, 0x94, 0x4c, 0x6c, 0xda, 0xbd, 0x72, 0xab, 0x51, 0x0d, 0x06, 0x47, 0x01, 0xd6, 0xac, 0x91, 0xc1, 0xb7, 0x2f, 0xe8, 0x9c, 0x63, 0xfa, 0x6f, 0x81, 0x4a, 0xfb, 0x85, 0xd3, 0x56, 0xa8, 0xbb, 0xaa, 0x1d, 0xaa, 0x4d, 0xf9, 0xad, 0x03, 0x25, 0x55, 0xc1, 0xb5, 0xd9, 0x9e, 0xf6, 0x15, 0xf4, 0x4e, 0x77, 0xe8, 0x4e, 0xc9, 0x1f, 0xbb, 0xa2, 0xd3, 0xa2, 0xb3, 0xad, 0x8d, 0x1f, 0x98, 0x54, 0xfe, 0x7b, 0xeb, 0x89, 0x51, 0xc1, 0xaa, 0xd9, 0xfb, 0x25, 0xfa, 0x56, 0x78, 0x75, 0xa7, 0x7d, 0xb1, 0xd4, 0xce, 0x6c, 0x7c, 0xba, 0x5b, 0xee, 0xfb, 0x4a, 0x1b, 0x22, 0x65, 0xc3, 0xe5, 0x57, 0x47, 0x5c, 0x7b, 0xa2, 0xbb, 0x50, 0xcb, 0xb0, 0xf7, 0x08, 0x30, 0x66, 0xdb, 0xde, 0xd1, 0x25, 0x0a, 0x9d, 0xff, 0xdc, 0x3e, 0x26, 0xa2, 0x62, 0x72, 0xd7, 0xe9, 0xbb, 0xe0, 0x26, 0xf1, 0xfc, 0xab, 0xb3, 0xf5, 0x20, 0x1f, 0x5f, 0x34, 0x1e, 0x36, 0x1f, 0xa1, 0xda, 0x27, 0x7f, 0x6d, 0x48, 0x0a, 0x55, 0x2c, 0x10, 0xea, 0xc5, 0x52, 0x36, 0x3d, 0x95, 0x05, 0x84, 0xbb, 0x1e, 0x6c, 0xbc, 0x50, 0xa1, 0x51, 0x99, 0x0b, 0xa0, 0xa9, 0x9b, 0xe8, 0x46, 0x83, 0x0d, 0x04, 0x2f, 0x89, 0x4e, 0x50, 0x96, 0xbc, 0xac, 0xdb, 0x78, 0x6e, 0x43, 0x48, 0x66, 0x22, 0x1c, 0x51, 0x18, 0xff, 0xff, 0xc7, 0x2c, 0x19, 0xee, 0x30, 0xbb, 0x81, 0xee, 0x4d, 0x9d, 0x1d, 0x26, 0x82, 0xff, 0xa8, 0xe5, 0x67, 0x9f, 0xb3, 0x94, 0xf8, 0x72, 0xbc, 0x7d, 0x1f, 0x59, 0x0e, 0xf7, 0x8d, 0x48, 0x94, 0x08, 0x14, 0xf9, 0x98, 0x85, 0xcf, 0xfd, 0x34, 0x62, 0x2e, 0x83, 0x27, 0xfc, 0xf1, 0x47, 0x4c, 0x52, 0x56, 0x2d, 0x55, 0x1e, 0x97, 0xc4, 0xea, 0x72, 0x2e, 0xf5, 0x79, 0x3d, 0x54, 0x8e, 0x6e, 0x71, 0x94, 0x13, 0xde, 0xa2, 0xe2, 0x79, 0x51, 0x16, 0x91, 0xa6, 0x61, 0xa0, 0xc4, 0x28, 0x2d, 0x7e, 0x3c, 0x1c, 0x1c, 0x7d, 0x54, 0x37, 0x90, 0xc1, 0x64, 0x1a, 0x7d, 0x41, 0x3a, 0x29, 0x4b, 0x26, 0xbd, 0x00, 0xf1, 0x10, 0x27, 0x05, 0x3c, 0x55, 0xf4, 0xe4, 0xed, 0x05, 0xec, 0x57, 0x9f, 0x12, 0x96, 0xd4, 0xf9, 0x52, 0x9e, 0xd7, 0xe1, 0x3c, 0x69, 0xc9, 0x74, 0x8e, 0x56, 0x33, 0x82, 0x60, 0x54, 0xca, 0x1d, 0x16, 0xb7, 0x6c, 0x9d, 0x25, 0xa7, 0x3d, 0x6b, 0xa7, 0x9a, 0x71, 0xc6, 0x14, 0x84, 0x3c, 0x75, 0x54, 0xf1, 0x3f, 0xcd, 0xc0, 0x1b, 0x7d, 0xca, 0x65, 0x5f, 0x81, 0xf4, 0xfd, 0x89, 0x36, 0x16, 0x99, 0xf9, 0x35, 0x65, 0xd5, 0x50, 0x49, 0xc5, 0x1d, 0x68, 0x87, 0xd4, 0x54, 0xe7, 0x7a, 0xe3, 0x6a, 0x0a, 0x9c, 0x6d, 0x2a, 0x10, 0x33, 0x93, 0x19, 0x66, 0xe2, 0x31, 0x22, 0x9c, 0x3e, 0x06, 0xd5, 0x47, 0x0c, 0xd2, 0x54, 0x92, 0xdd, 0x74, 0x9b, 0x4a, 0x01, 0x6e, 0xf3, 0x2a, 0x10, 0x5f, 0x54, 0x66, 0x38, 0xa7, 0xc4, 0x10, 0x58, 0x38, 0xc7, 0x6c, 0x40, 0x24, 0x4e, 0x20, 0x26, 0x41, 0xe1, 0x81, 0x2a, 0x74, 0x1b, 0xdc, 0xa7, 0xe8, 0x1b, 0x40, 0xf9, 0x3e, 0xe8, 0x1c, 0x0e, 0x2b, 0x75, 0xe8, 0xa3, 0xed, 0x8f, 0x29, 0x90, 0x0a, 0x1c, 0xe5, 0xbc, 0x1c, 0xd4, 0xa1, 0x5d, 0xdf, 0x20, 0x78, 0x0e, 0xce, 0x87, 0x8c, 0xa1, 0x96, 0x1c, 0x07, 0xa4, 0xfc, 0x06, 0xdf, 0x14, 0x0f, 0xbd, 0x5d, 0x2a, 0xfd, 0x47, 0x87, 0x1a, 0xe7, 0x3b, 0xeb, 0x28, 0xe2, 0x22, 0x4a, 0xd8, 0xab, 0xb6, 0x1b, 0x96, 0xe7, 0xb9, 0x56, 0xc0, 0x3f, 0xb5, 0xdb, 0x5a, 0x05, 0xb8, 0x4e, 0x0e, 0x48, 0x7e, 0x4a, 0x8a, 0xf0, 0x34, 0x9b, 0xe7, 0xf0, 0x9f, 0x5f, 0x8c, 0x98, 0x25, 0xde, 0x77, 0xcc, 0xb5, 0x27, 0xa8, 0xe3, 0xd4, 0xa0, 0xf8, 0x9d, 0x6c, 0x9c, 0x4f, 0x09, 0x4e, 0x50, 0x3d, 0x84, 0x05, 0xe7, 0x68, 0x91, 0x57, 0xb1, 0xcd, 0x7c, 0xca, 0xc2, 0x07, 0x5a, 0x25, 0x12, 0x44, 0x45, 0x35, 0x23, 0x43, 0x35, 0xb6, 0xa6, 0x97, 0xc4, 0x77, 0xb1, 0x0c, 0x7c, 0x9f, 0x39, 0x94, 0x8f, 0xae, 0xf2, 0x2e, 0xb4, 0xf9, 0x6d, 0x21, 0x3a, 0x29, 0x7e, 0x4f, 0x5b, 0xb0, 0x7d, 0xfc, 0x29, 0x0b, 0xc9, 0xa7, 0xe8, 0x82, 0xd7, 0xca, 0x72, 0xa7, 0x8f, 0x91, 0xf7, 0x3a, 0x95, 0x07, 0x52, 0x07, 0x14, 0x35, 0xbe, 0xf6, 0x64, 0x3f, 0x85, 0x25, 0x83, 0x7c, 0x4a, 0xd5, 0x16, 0x2d, 0x30, 0x5f, 0xfe, 0x53, 0x16, 0xce, 0xcd, 0x36, 0xe4, 0x96, 0x21, 0xab, 0x16, 0x7c, 0x97, 0x8c, 0x14, 0xec, 0x67, 0xaa, 0x32, 0xdd, 0x0c, 0xf6, 0x0a, 0x02, 0x6e, 0x88, 0xd1, 0x49, 0xf2, 0x82, 0x62, 0x0f, 0xa1, 0x01, 0x02, 0x06, 0x63, 0x62, 0x94, 0x7d, 0x3e, 0xcc, 0x8a, 0xcb, 0x55, 0xaf, 0x16, 0x8c, 0x9b, 0x3e, 0xd2, 0x6c, 0x4e, 0x12, 0x19, 0x1e, 0x94, 0xac, 0xd7, 0x41, 0x4b, 0xf6, 0x29, 0x8b, 0x83, 0xa7, 0xe3, 0x89, 0x37, 0x78, 0xfa, 0xc2, 0x89, 0x9b, 0x4b, 0x38, 0x48, 0xf1, 0x08, 0x51, 0x55, 0x98, 0xe3, 0xef, 0x53, 0x0e, 0x68, 0xa7, 0xf2, 0x87, 0x8f, 0x3e, 0xd0, 0x9d, 0x08, 0x2c, 0xb3, 0x15, 0x1d, 0x67, 0x35, 0x2b, 0x41, 0x56, 0x58, 0x6f, 0x0c, 0xc0, 0x04, 0x65, 0xc9, 0x4a, 0x16, 0x87, 0x4c, 0x70, 0x02, 0x0a, 0xd0, 0x30, 0x88, 0x64, 0xfe, 0xcc, 0x23, 0x9b, 0x95, 0x20, 0x2b, 0x49, 0xb2, 0xc3, 0xc5, 0x9c, 0x33, 0xc4, 0x65, 0x23, 0x1b, 0x07, 0xd0, 0x61, 0xc3, 0xe7, 0x9f, 0x70, 0x00, 0xeb, 0x45, 0x44, 0x28, 0x0b, 0x54, 0x49, 0xf0, 0x64, 0x21, 0xc7, 0xa6, 0xd5, 0xac, 0xe1, 0xcf, 0xd9, 0xb8, 0x5e, 0x82, 0x53, 0x06, 0x57, 0x00, 0xdf, 0xa1, 0x6c, 0x44, 0x45, 0xe1, 0x30, 0x04, 0x81, 0x61, 0x54, 0x03, 0x3e, 0x1c, 0x8c, 0x1f, 0x01, 0x12, 0x14, 0x7f, 0xce, 0x6e, 0xd7, 0xf0, 0x08, 0x35, 0xa7, 0xa1, 0x1c, 0xa0, 0x7c, 0xb6, 0x04, 0xd8, 0xc4, 0xac, 0x31, 0xa8, 0xc6, 0x44, 0xce, 0x69, 0x22, 0x2c, 0xa1, 0x09, 0x53, 0x81, 0xf0, 0x49, 0xe2, 0xcb, 0xd2, 0x9a, 0x6d, 0x54, 0x5d, 0x91, 0x87, 0xbb, 0x3c, 0x34, 0x67, 0x8f, 0x06, 0xf0, 0x0c, 0x7e, 0xa6, 0x54, 0x32, 0x6c, 0xbd, 0xc4, 0x91, 0x2e, 0xd1, 0xf9, 0xde, 0x65, 0xf6, 0x48, 0x77, 0x8c, 0x04, 0xb1, 0xec, 0x67, 0x65, 0x71, 0x25, 0x7e, 0xca, 0xc3, 0x7a, 0xf6, 0xb3, 0x70, 0x25, 0x7e, 0xfa, 0x83, 0x57, 0x2a, 0xaa, 0x48, 0x5e, 0x56, 0xff, 0x34, 0xcf, 0x2f, 0x1c, 0x7d, 0xba, 0x8d, 0x7a, 0x3a, 0xa9, 0x83, 0x00, 0xe8, 0x48, 0xa0, 0x56, 0x64, 0x70, 0x2b, 0xf3, 0x4e, 0xc8, 0x45, 0xb6, 0xb1, 0xa9, 0x11, 0xd4, 0x5e, 0x42, 0x68, 0x02, 0x20, 0xfe, 0x88, 0x4e, 0xbc, 0x8c, 0x7d, 0x4e, 0xd6, 0xdc, 0x2d, 0x47, 0xed, 0x7c, 0xce, 0x52, 0x69, 0xb7, 0xa5, 0x62, 0x29, 0x9c, 0xcf, 0x88, 0x0f, 0x99, 0x4e, 0xdf, 0x5f, 0x80, 0xfa, 0xf9, 0x9c, 0xa8, 0xa8, 0x5b, 0xd8, 0x51, 0xff, 0x73, 0x96, 0x2a, 0xb9, 0x11, 0x70, 0x5a, 0xb9, 0xda, 0xa4, 0x52, 0x82, 0x27, 0x4f, 0x70, 0x87, 0x5b, 0x96, 0x20, 0x31, 0x57, 0xe5, 0xdb, 0x30, 0xfe, 0x19, 0x9e, 0x5f, 0x5c, 0x26, 0xdd, 0x3b, 0x09, 0x53, 0xe6, 0x60, 0x93, 0x12, 0x04, 0x84, 0x0d, 0x59, 0x88, 0xe2, 0xc2, 0x15, 0x9f, 0xb3, 0x95, 0x08, 0xeb, 0x24, 0xbc, 0x16, 0x9a, 0x3d, 0xc4, 0x1e, 0x97, 0xe6, 0x40, 0xfd, 0x50, 0x66, 0x2c, 0x20, 0xc9, 0xa8, 0xaf, 0xed, 0x35, 0x8e, 0x6b, 0x28, 0xb9, 0x87, 0x07, 0x4e, 0x17, 0x52, 0x39, 0xf1, 0x33, 0x4b, 0xde, 0x5b, 0x98, 0x09, 0x93, 0x87, 0xaf, 0x17, 0x19, 0xe4, 0x09, 0x46, 0x2a, 0xd6, 0x15, 0x4d, 0x2d, 0x90, 0x4b, 0x9f, 0x6a, 0x51, 0x82, 0x78, 0xf0, 0xe9, 0x8f, 0x4a, 0x37, 0x05, 0xc6, 0x49, 0x3f, 0xe7, 0x70, 0x24, 0x2a, 0x63, 0xd2, 0x88, 0x63, 0xf6, 0xdb, 0x19, 0xb7, 0xc6, 0x29, 0x84, 0xfc, 0x7f, 0x38, 0x92, 0xb4, 0x28, 0x1d, 0xfd, 0x8c, 0x08, 0xe6, 0xbd, 0xc1, 0x18, 0x6f, 0xcd, 0xde, 0xf1, 0x27, 0x15, 0x7f, 0x7f, 0x44, 0x47, 0x90, 0xb1, 0xa9, 0x4c, 0xbe, 0x52, 0x54, 0x50, 0x9e, 0x7c, 0xbd, 0x4e, 0xfa, 0xcd, 0x67, 0xbe, 0x75, 0x3c, 0x7d, 0x7f, 0x09, 0xea, 0x87, 0x4f, 0x99, 0x0b, 0xb9, 0x51, 0x3b, 0xf9, 0x3b, 0x6a, 0x5e, 0xfe, 0x0e, 0x38, 0x8b, 0x5f, 0x5b, 0x3d, 0xa7, 0xcf, 0x39, 0xf2, 0xe1, 0x42, 0x2d, 0xfa, 0x0b, 0x27, 0xe5, 0x85, 0x53, 0xea, 0x62, 0xc3, 0xad, 0x32, 0xd7, 0xd9, 0x93, 0xa0, 0x29, 0x9e, 0xec, 0xf7, 0xf4, 0x47, 0x24, 0xf5, 0xfc, 0x9c, 0xa4, 0x91, 0x7d, 0x05, 0x4c, 0x8b, 0x8f, 0x17, 0xc2, 0x2c, 0xac, 0xb1, 0x48, 0xca, 0x7c, 0x12, 0xa5, 0xe7, 0x69, 0x20, 0x3a, 0xda, 0x49, 0xc2, 0xdc, 0x70, 0x2a, 0x02, 0x74, 0x1b, 0xa1, 0xb1, 0xea, 0xaf, 0x49, 0x02, 0x3b, 0xb9, 0x48, 0x31, 0xa8, 0x2c, 0xa2, 0xf6, 0x2d, 0xa1, 0xfe, 0xfa, 0xa4, 0xdc, 0x65, 0x58, 0xda, 0x9f, 0x44, 0xed, 0x29, 0x44, 0x13, 0xf6, 0xfd, 0x81, 0x59, 0xaa, 0x99, 0x62, 0x0f, 0xf4, 0x77, 0xa7, 0xfc, 0xb1, 0xdb, 0xd2, 0xf8, 0x2d, 0x87, 0x4a, 0x8c, 0x5a, 0x8a, 0x78, 0x62, 0x1f, 0x4f, 0xd4, 0xde, 0x3b, 0xbb, 0x7b, 0xf1, 0xac, 0x40, 0x51, 0x35, 0x12, 0x50, 0xbc, 0xb2, 0x50, 0x22, 0xda, 0x59, 0xa4, 0xc1, 0xd7, 0xfe, 0x9a, 0x44, 0x89, 0xc5, 0x35, 0x4b, 0xad, 0x3d, 0x26, 0x6e, 0x00, 0xc7, 0x3d, 0xbb, 0x96, 0xfb, 0xa9, 0xea, 0x3b, 0xcd, 0x6c, 0x32, 0x5b, 0xdb, 0x9a, 0xbd, 0x0c, 0xf5, 0x27, 0x09, 0x2a, 0x1b, 0x7f, 0x2b, 0xcc, 0x84, 0xcb, 0x11, 0x7f, 0x23, 0xc7, 0x36, 0x2b, 0x6c, 0x2d, 0x5f, 0x98, 0x6a, 0xfa, 0xfe, 0x02, 0x74, 0xd8, 0xcd, 0x54, 0x8c, 0xa4, 0x9c, 0x72, 0xce, 0x37, 0x59, 0xc2, 0x24, 0xd0, 0x1f, 0xc8, 0xb4, 0xe1, 0x2b, 0x65, 0x98, 0x94, 0x0b, 0xfc, 0x40, 0x9b, 0x12, 0xa4, 0x84, 0x75, 0x7e, 0x97, 0x27, 0x25, 0x39, 0xfc, 0xdf, 0x31, 0xe8, 0x41, 0x05, 0x7a, 0x93, 0x86, 0x74, 0xaa, 0x95, 0x16, 0x07, 0x1a, 0x96, 0x20, 0x2c, 0x09, 0x5a, 0xfd, 0xd7, 0x42, 0x77, 0xfe, 0x78, 0xf1, 0xc9, 0x43, 0xad, 0x2f, 0x41, 0xdd, 0x27, 0xce, 0x9f, 0x6c, 0x89, 0xb3, 0x67, 0xbb, 0x60, 0x8d, 0x13, 0x0f, 0x24, 0x28, 0xae, 0x74, 0xb4, 0x0a, 0x2d, 0x48, 0xb3, 0x82, 0x65, 0xd8, 0xb3, 0x8e, 0x6a, 0xe2, 0x0a, 0x14, 0x81, 0xd0, 0x13, 0x74, 0x8d, 0xe9, 0x49, 0xd1, 0x8a, 0x97, 0x21, 0x9b, 0x6c, 0xae, 0xec, 0x62, 0xa7, 0xc3, 0xe7, 0x7f, 0xec, 0x6d, 0x71, 0xcc, 0x92, 0x02, 0x1b, 0xf4, 0x92, 0x24, 0x62, 0x8f, 0xa7, 0x04, 0x6a, 0xc0, 0xaa, 0xd3, 0x27, 0x9c, 0x9e, 0x46, 0x4e, 0x73, 0x53, 0xf7, 0xb4, 0xe6, 0xce, 0x0e, 0xfc, 0x23, 0x03, 0x9f, 0x91, 0x1e, 0x08, 0x7e, 0xcc, 0x00, 0x31, 0x44, 0x10, 0x19, 0x9c, 0x3c, 0xc4, 0xdd, 0x5f, 0xf7, 0xac, 0xb9, 0x5d, 0xd5, 0xc4, 0xe4, 0x5a, 0x22, 0x6f, 0x6b, 0x22, 0x7d, 0xbf, 0x62, 0x8f, 0x38, 0x55, 0x29, 0x01, 0xc5, 0x9b, 0x77, 0x85, 0x27, 0xa8, 0xf8, 0x07, 0xc8, 0x20, 0xa0, 0xb4, 0x5f, 0x32, 0xef, 0xb9, 0xe1, 0x33, 0x54, 0x26, 0xee, 0x2e, 0x41, 0x26, 0xd8, 0x24, 0xdd, 0xf2, 0x0c, 0xb1, 0x2c, 0x09, 0xba, 0xe2, 0x22, 0x91, 0x8f, 0x94, 0xc8, 0x5e, 0x9a, 0xbe, 0xbf, 0x04, 0xe9, 0x60, 0xf3, 0x70, 0xcb, 0xc2, 0xa8, 0xdc, 0xe4, 0x48, 0xbb, 0xfd, 0x79, 0x70, 0xb6, 0x37, 0x3f, 0x00, 0x80, 0xe0, 0x26, 0x0b, 0x80, 0xa0, 0x67, 0x2a, 0x9a, 0x30, 0x74, 0xd2, 0xe7, 0xb6, 0x03, 0xcd, 0x4a, 0x10, 0x14, 0xb6, 0xde, 0x4f, 0x27, 0x14, 0xa8, 0x77, 0xff, 0x1a, 0x89, 0xef, 0xe7, 0xba, 0xb3, 0x93, 0x07, 0x37, 0x65, 0x24, 0x78, 0xcf, 0x23, 0xd1, 0x28, 0x1c, 0xad, 0x35, 0xd1, 0x7d, 0x4a, 0xc0, 0x80, 0x40, 0xed, 0x4e, 0x04, 0x73, 0x0c, 0xc8, 0x17, 0xed, 0x18, 0xcf, 0xf4, 0xce, 0xab, 0x90, 0x12, 0x45, 0x8e, 0x29, 0x83, 0xc7, 0xc8, 0xd3, 0xbe, 0x4e, 0x83, 0x24, 0x3e, 0x0f, 0x7d, 0x0e, 0x96, 0x95, 0x96, 0x18, 0xce, 0xc3, 0x48, 0x32, 0x39, 0xd2, 0x08, 0x09, 0xc0, 0xfb, 0xc0, 0x6f, 0xb2, 0x54, 0x15, 0x4a, 0x99, 0x2b, 0xbb, 0xe9, 0x19, 0x32, 0x65, 0x74, 0x87, 0x63, 0xe0, 0xa6, 0x7e, 0x50, 0xac, 0x64, 0x41, 0x4e, 0x70, 0x4b, 0x5c, 0xc9, 0x7e, 0xc1, 0x56, 0xd1, 0xe5, 0x10, 0x16, 0x2e, 0x66, 0x1d, 0x29, 0xe3, 0x4c, 0x3d, 0xf0, 0x67, 0xae, 0x86, 0xf2, 0x00, 0x30, 0xd1, 0xc3, 0xeb, 0x03, 0x6b, 0x92, 0x33, 0x2d, 0xb1, 0xf4, 0x13, 0x8b, 0x33, 0xad, 0xae, 0x0e, 0x3f, 0x49, 0x62, 0xd0, 0x34, 0x86, 0x56, 0x9a, 0xca, 0x19, 0xf1, 0xab, 0x4d, 0xc5, 0xa7, 0x46, 0x80, 0x71, 0xf4, 0xae, 0x95, 0xf2, 0xe3, 0x1b, 0x74, 0x08, 0x23, 0xbf, 0xaa, 0x04, 0xdf, 0xbe, 0xe6, 0x01, 0xe4, 0x3b, 0xfd, 0xe1, 0xa9, 0x2a, 0xff, 0x3c, 0xdb, 0x8f, 0x30, 0x3d, 0x2b, 0x85, 0xfb, 0x0f, 0x26, 0xc0, 0x50, 0xcf, 0x3d, 0x97, 0x2b, 0x4d, 0x9a, 0x9e, 0x5d, 0xf6, 0x07, 0xe7, 0xb8, 0xe2, 0x03, 0x81, 0xa7, 0x1b, 0x4f, 0xb6, 0x7f, 0x5e, 0xff, 0xa0, 0x2c, 0x7e, 0xfd, 0x26, 0x99, 0xa1, 0x5e, 0x90, 0xee, 0xce, 0x92, 0xa4, 0x9e, 0xaa, 0x1a, 0xcd, 0xba, 0xec, 0x93, 0xf7, 0x96, 0xa0, 0xa5, 0xd9, 0x14, 0xf5, 0xc2, 0x44, 0x22, 0x4b, 0xe9, 0x21, 0xaa, 0xc1, 0xc3, 0x12, 0x54, 0xf0, 0xfb, 0xf8, 0xf4, 0xfd, 0x25, 0x88, 0x06, 0xcb, 0x51, 0x59, 0x98, 0xf1, 0x9f, 0x83, 0x93, 0x32, 0xc9, 0xe6, 0xc6, 0x19, 0xff, 0xe9, 0x7b, 0x4b, 0x10, 0x09, 0x96, 0xa4, 0xa0, 0x30, 0x91, 0xc8, 0xc1, 0x50, 0xf0, 0x13, 0x9d, 0x07, 0xd9, 0x3a, 0x3d, 0xe5, 0x39, 0x90, 0x72, 0xd5, 0xe7, 0x99, 0x8a, 0xe4, 0x25, 0x03, 0xbe, 0x87, 0x1a, 0x95, 0x20, 0x27, 0x49, 0xce, 0x8a, 0x52, 0x9c, 0xcf, 0x59, 0x68, 0x29, 0x7e, 0x22, 0x76, 0xa4, 0x1b, 0x16, 0x07, 0x5e, 0xd8, 0x66, 0x92, 0x03, 0x07, 0xfe, 0xb3, 0x26, 0xc0, 0xdd, 0xb0, 0x68, 0xf0, 0x9d, 0x92, 0x3f, 0xff, 0x9e, 0x59, 0xc0, 0x77, 0x32, 0xf2, 0xbf, 0x1f, 0xd4, 0xce, 0x8b, 0x02, 0xc8, 0x53, 0x1f, 0xe5, 0xd1, 0xd4, 0x21, 0x69, 0x58, 0x77, 0xc9, 0xde, 0x49, 0x16, 0xd5, 0xdd, 0x97, 0x88, 0x2e, 0x8d, 0x2e, 0xe2, 0x26, 0x13, 0x9a, 0x5b, 0x07, 0x42, 0x48, 0xc3, 0xe5, 0xb8, 0x1d, 0x51, 0x21, 0x1a, 0x15, 0x4f, 0x9b, 0x9e, 0xc5, 0xb9, 0xe5, 0xb4, 0xbd, 0xef, 0xad, 0x14, 0xbb, 0x86, 0xc7, 0x6c, 0x97, 0xc8, 0x72, 0x7c, 0x93, 0x03, 0x85, 0x2d, 0x82, 0x77, 0x5e, 0x50, 0x79, 0x53, 0xde, 0x3b, 0x72, 0x58, 0x8a, 0x02, 0xa1, 0xa8, 0xea, 0xd1, 0x1e, 0x90, 0x4b, 0xa8, 0x25, 0xd7, 0x3b, 0x97, 0xed, 0x36, 0x65, 0x35, 0xe7, 0x24, 0x5e, 0x00, 0x4c, 0x7b, 0x42, 0x9f, 0x03, 0x87, 0xd3, 0xd6, 0x87, 0x13, 0xff, 0x8e, 0x11, 0xb0, 0x14, 0x5b, 0x56, 0xc9, 0xb5, 0x42, 0x6e, 0xb2, 0xd0, 0x65, 0xb5, 0x2d, 0xb4, 0x55, 0xcd, 0x26, 0xf1, 0xb6, 0xed, 0x1c, 0x2e, 0x64, 0xdf, 0x43, 0x43, 0x54, 0x31, 0x93, 0xfd, 0x2c, 0x40, 0x9c, 0x35, 0xe6, 0x9c, 0x49, 0x5c, 0xe6, 0xe3, 0x06, 0xc7, 0xb4, 0x86, 0x44, 0xfd, 0xce, 0xa7, 0x99, 0x98, 0x17, 0x2d, 0xad, 0x8b, 0xba, 0xc4, 0x46, 0xa1, 0x02, 0x36, 0xc3, 0x38, 0x3d, 0xbe, 0x9a, 0x8a, 0xa1, 0xfd, 0x9e, 0x23, 0x8f, 0x84, 0x08, 0xfa, 0x2b, 0x83, 0x92, 0xa2, 0x54, 0xf4, 0x9d, 0xf3, 0xdf, 0x54, 0xa3, 0xf9, 0x26, 0x93, 0xe9, 0x3a, 0x49, 0x45, 0x45, 0x55, 0xac, 0x70, 0x0d, 0x1a, 0x1c, 0x2a, 0xe3, 0x4e, 0xdd, 0xd7, 0x54, 0xc5, 0x01, 0xe3, 0x10, 0x22, 0x6d, 0xe5, 0x36, 0x6b, 0x94, 0x18, 0x56, 0x95, 0x82, 0x9b, 0x64, 0x33, 0x48, 0x3a, 0xa1, 0xca, 0xb4, 0xbf, 0xb2, 0xe4, 0x92, 0x3c, 0xbd, 0x38, 0x5b, 0xc4, 0x49, 0xea, 0x06, 0x15, 0x02, 0x6d, 0x8c, 0x27, 0xc6, 0x2c, 0x26, 0xe0, 0x1d, 0x43, 0x19, 0x36, 0xa4, 0x30, 0xc9, 0x98, 0xd6, 0x69, 0x10, 0x79, 0x54, 0x88, 0x75, 0x53, 0xe4, 0xb6, 0x42, 0x5d, 0xf8, 0x50, 0x8a, 0xb7, 0xa5, 0x9d, 0x57, 0x9c, 0xc7, 0x37, 0x46, 0x08, 0x60, 0x8b, 0xc2, 0x83, 0x21, 0x28, 0x1a, 0xee, 0xa4, 0x12, 0x17, 0x82, 0x6a, 0x9a, 0x3b, 0x6d, 0x74, 0x88, 0x5d, 0x86, 0xa2, 0xf1, 0xa8, 0xc5, 0x8e, 0xb2, 0xb8, 0xed, 0x45, 0xa8, 0x0e, 0x4f, 0xc8, 0x80, 0xcd, 0x7e, 0xde, 0xdf, 0x18, 0x2a, 0x86, 0x8a, 0xe6, 0xc2, 0x49, 0xff, 0x15, 0x10, 0x69, 0x66, 0xbb, 0x41, 0x7f, 0xa2, 0x72, 0x9c, 0x0e, 0x75, 0xec, 0x6d, 0xe3, 0x6a, 0x81, 0xba, 0x27, 0xa0, 0xd4, 0x5c, 0xf9, 0x49, 0x76, 0x52, 0xd9, 0x7a, 0x53, 0x2d, 0xa4, 0x05, 0xf4, 0xd8, 0xa6, 0x2c, 0xd7, 0x97, 0xfb, 0x68, 0x4e, 0x76, 0x27, 0xca, 0xc4, 0x73, 0xf7, 0x4e, 0x9e, 0x51, 0x8d, 0xb3, 0x8c, 0x77, 0xe5, 0xf1, 0xc3, 0xdc, 0xe4, 0xe2, 0xba, 0x13, 0x1d, 0x6a, 0xb1, 0x60, 0x23, 0xe7, 0x81, 0x35, 0x33, 0xbf, 0x22, 0x80, 0x1d, 0x86, 0x22, 0x38, 0x07, 0xfa, 0x2c, 0x06, 0x1b, 0x7c, 0xcb, 0xa6, 0x6d, 0x6d, 0x72, 0x2c, 0x8a, 0x52, 0xc7, 0xb7, 0x59, 0x92, 0xb7, 0x2a, 0xc1, 0x16, 0x9f, 0x1b, 0x5f, 0xe6, 0x4d, 0x36, 0x52, 0xc7, 0xfe, 0x4e, 0x37, 0x94, 0xf1, 0x01, 0x46, 0xa6, 0xbf, 0xc0, 0xe6, 0xd2, 0xb6, 0x6a, 0x91, 0xb2, 0x73, 0x59, 0xa4, 0x89, 0x4d, 0xef, 0xea, 0x84, 0xea, 0xf5, 0xfa, 0x0c, 0xf5, 0x44, 0xc8, 0xaf, 0xb4, 0xdb, 0xae, 0x2f, 0xa0, 0xde, 0xc5, 0xe2, 0x56, 0xa8, 0xe2, 0x07, 0xa0, 0xbe, 0xb2, 0x4a, 0x38, 0x53, 0x73, 0x14, 0xb7, 0x63, 0x35, 0xba, 0x1c, 0x65, 0xf5, 0x6d, 0x96, 0x3c, 0x30, 0xbf, 0xb7, 0xb2, 0xfe, 0xfe, 0x5d, 0xb0, 0x4f, 0x12, 0xbb, 0x55, 0x05, 0x24, 0x95, 0x0d, 0xa5, 0xed, 0xfd, 0x5e, 0xe8, 0xf7, 0xf4, 0x60, 0x78, 0x52, 0x05, 0x31, 0x09, 0xeb, 0x13, 0x55, 0x8b, 0x69, 0x67, 0x06, 0x86, 0xeb, 0x9c, 0x30, 0x5c, 0xb4, 0x9e, 0x5d, 0x04, 0xed, 0x25, 0x56, 0x75, 0x64, 0xc8, 0xc3, 0x40, 0xa6, 0x4e, 0xf6, 0x6f, 0x37, 0x76, 0xff, 0xd8, 0x95, 0x5b, 0x38, 0x53, 0xe5, 0xed, 0x54, 0x2c, 0x3e, 0xbc, 0x38, 0xd1, 0xc8, 0xf3, 0x7f, 0xa6, 0xdb, 0xb2, 0x98, 0x25, 0x8b, 0x87, 0xc2, 0x91, 0xae, 0x96, 0x6a, 0xe4, 0xed, 0x88, 0x3f, 0x8f, 0xe0, 0x84, 0x9b, 0xa5, 0xd9, 0x13, 0xca, 0xc0, 0x46, 0x4e, 0x55, 0x80, 0xa5, 0x37, 0xea, 0x74, 0xa8, 0x54, 0x47, 0x85, 0xac, 0x9c, 0x31, 0x17, 0x28, 0x97, 0xed, 0x45, 0xc9, 0x1b, 0xa4, 0x52, 0x3a, 0x14, 0x7b, 0x30, 0xc8, 0xa7, 0xa7, 0x61, 0x61, 0x3f, 0x3e, 0x93, 0x07, 0x7a, 0xce, 0xd4, 0xfc, 0xcc, 0x76, 0x67, 0xc5, 0x4f, 0x67, 0xac, 0x73, 0x9e, 0x28, 0xbb, 0x6c, 0x0a, 0x4f, 0x59, 0x31, 0xb3, 0xdb, 0x1c, 0x59, 0x3c, 0x31, 0x00, 0x16, 0xc8, 0x17, 0x8e, 0x0d, 0x9b, 0x4d, 0xb7, 0x2a, 0x61, 0xff, 0x9d, 0x2a, 0xbd, 0x57, 0xa8, 0xcb, 0xf0, 0x36, 0x4b, 0x8a, 0x4f, 0x0a, 0xcc, 0xc9, 0x7e, 0x46, 0x63, 0x57, 0xa1, 0xae, 0x6a, 0xce, 0x0f, 0xb7, 0x08, 0x18, 0xf4, 0x24, 0xd1, 0xf9, 0xde, 0xe5, 0x54, 0xb9, 0xb4, 0xf9, 0xad, 0x21, 0x40, 0x89, 0x72, 0x69, 0x52, 0x47, 0xcc, 0xf3, 0x53, 0x4f, 0x98, 0x27, 0xb5, 0xaa, 0x99, 0x32, 0x5e, 0xe3, 0xab, 0x63, 0x8e, 0x93, 0xc7, 0x4b, 0x4f, 0x3e, 0x12, 0x52, 0xd8, 0x50, 0x7e, 0xbf, 0x48, 0x1c, 0x32, 0x9b, 0x19, 0xa2, 0xb4, 0xe9, 0x86, 0xfc, 0x22, 0xf8, 0xaf, 0xaa, 0xba, 0x40, 0xc6, 0x34, 0xb6, 0x1c, 0x01, 0xe6, 0xf2, 0xa6, 0x6e, 0x9c, 0xc5, 0x7f, 0x11, 0x74, 0x5e, 0x78, 0x43, 0x18, 0xb5, 0x49, 0x6b, 0x8e, 0x86, 0x4f, 0x94, 0x92, 0x8b, 0x78, 0x9b, 0xca, 0x18, 0xd1, 0xbb, 0xa1, 0x8e, 0x2d, 0xed, 0x35, 0x4b, 0x7f, 0xe9, 0x19, 0xe1, 0xff, 0x60, 0x17, 0xbf, 0x10, 0x02, 0xe0, 0x36, 0x4b, 0xea, 0x07, 0xdc, 0x87, 0x4f, 0x2a, 0x97, 0xbe, 0x0d, 0x04, 0x18, 0xaf, 0x57, 0xef, 0x31, 0x44, 0x7d, 0x5b, 0x6f, 0x26, 0xc1, 0x58, 0x42, 0x02, 0x0e, 0xca, 0xde, 0x44, 0xa7, 0x9e, 0x8e, 0xc9, 0xd5, 0x43, 0xa9, 0x60, 0xca, 0xaf, 0x0e, 0xbe, 0x3a, 0xdc, 0x0f, 0x70, 0x01, 0x3f, 0xbf, 0x46, 0x2d, 0x12, 0xae, 0x93, 0x61, 0x76, 0x5c, 0x38, 0x70, 0x14, 0x74, 0x64, 0x09, 0x2f, 0xe3, 0x1c, 0x39, 0x1d, 0xca, 0xd2, 0x5c, 0xde, 0xb2, 0xf0, 0x69, 0xf1, 0x8c, 0x82, 0x1c, 0xf4, 0x86, 0xa8, 0xd7, 0x78, 0x23, 0xac, 0x00, 0x8f, 0x0b, 0x80, 0x2e, 0x26, 0xc0, 0x39, 0x60, 0xd6, 0xb3, 0x89, 0xbb, 0xa6, 0xe9, 0xe4, 0x7c, 0x1f, 0xa8, 0x8f, 0xba, 0xb3, 0x58, 0x54, 0xae, 0x09, 0x5e, 0x71, 0xdd, 0x83, 0x2d, 0x11, 0x6c, 0xa9, 0x41, 0xd8, 0xe5, 0x95, 0x6e, 0xc9, 0x38, 0x97, 0x5b, 0x16, 0xb1, 0x5d, 0x56, 0x7e, 0xc7, 0x6d, 0xae, 0x9a, 0x72, 0x21, 0x65, 0x23, 0xcd, 0x8f, 0x99, 0x3e, 0xc3, 0x1e, 0x68, 0x56, 0x82, 0xa0, 0x24, 0xf1, 0xb9, 0x05, 0x09, 0x4a, 0xa6, 0xca, 0x71, 0x70, 0x36, 0x72, 0xaf, 0x9a, 0xaf, 0x6d, 0x12, 0x12, 0x24, 0xe1, 0x9f, 0x94, 0xca, 0xb5, 0xbc, 0x90, 0x14, 0x12, 0xb5, 0xbd, 0xe5, 0x51, 0x73, 0x55, 0x69, 0x65, 0x4e, 0x6e, 0x73, 0xe0, 0xe5, 0x8e, 0x49, 0x0b, 0xaa, 0xbc, 0x84, 0x18, 0xaf, 0x42, 0x2a, 0x91, 0x0e, 0xf1, 0x3e, 0xdd, 0x04, 0xf2, 0xe7, 0x04, 0x06, 0x32, 0xc0, 0x8a, 0xed, 0x31, 0x42, 0xc1, 0xc6, 0x21, 0xc9, 0x77, 0x3a, 0x33, 0x6c, 0xb4, 0x28, 0x8c, 0xa4, 0x12, 0x8c, 0x1b, 0xae, 0x4a, 0x9d, 0xbb, 0xb6, 0x85, 0x22, 0x4b, 0x1c, 0x92, 0xb7, 0xc0, 0x67, 0x50, 0xc5, 0xfb, 0x47, 0xd8, 0x18, 0xdc, 0xda, 0x9f, 0xf5, 0x04, 0xe0, 0x21, 0x6a, 0x5d, 0xbb, 0x16, 0x96, 0x36, 0x8a, 0x69, 0x47, 0x3c, 0x5c, 0xe0, 0x38, 0x82, 0x9d, 0xee, 0x2d, 0x3e, 0x27, 0x6d, 0xd8, 0x9e, 0x6a, 0xcd, 0xab, 0x9e, 0x97, 0x74, 0x69, 0x0d, 0x0f, 0xb5, 0xe0, 0x13, 0xe9, 0xaa, 0xf5, 0xe7, 0x5d, 0x2f, 0x97, 0xbf, 0xb0, 0xd9, 0xce, 0x6d, 0x22, 0xcc, 0x3e, 0x9e, 0xef, 0xeb, 0x88, 0x8d, 0xff, 0x92, 0x23, 0xdb, 0xb9, 0x4d, 0xa9, 0x9c, 0x54, 0x06, 0x63, 0xfa, 0xee, 0x02, 0xf6, 0xb0, 0xbb, 0xa9, 0x48, 0x77, 0x39, 0x5b, 0xd8, 0x5d, 0x8e, 0x18, 0xf7, 0x31, 0x69, 0x8c, 0xa2, 0xea, 0x88, 0x09, 0x99, 0x3f, 0xc3, 0x97, 0x92, 0xf4, 0x7c, 0x97, 0xe4, 0xf3, 0x2b, 0x48, 0x34, 0x72, 0xf1, 0xf8, 0x55, 0xc6, 0x09, 0x90, 0x60, 0xb0, 0xc8, 0x97, 0x64, 0x32, 0xe3, 0xc1, 0x56, 0x25, 0x88, 0x49, 0xe9, 0x54, 0x7a, 0x77, 0x2f, 0x4a, 0xa5, 0xc7, 0xcb, 0xc6, 0xd4, 0xdd, 0x25, 0xc8, 0x04, 0x1f, 0x74, 0x0b, 0xc5, 0x4b, 0xbc, 0x05, 0x63, 0x67, 0xb3, 0x81, 0x9e, 0xd5, 0xaf, 0x43, 0x46, 0x72, 0x44, 0xdc, 0x02, 0x69, 0x3e, 0x56, 0x89, 0xb1, 0xda, 0x67, 0x04, 0xcf, 0x4f, 0x86, 0xa4, 0xb4, 0x80, 0xa0, 0x8e, 0xb8, 0x3c, 0xdb, 0x33, 0xb0, 0x32, 0x5a, 0xe6, 0x65, 0xc9, 0x65, 0x7b, 0x9a, 0x7e, 0x8e, 0x1d, 0xd6, 0xff, 0x36, 0xf2, 0x65, 0x0e, 0xf2, 0x00, 0x01, 0x63, 0xd9, 0xf8, 0xca, 0xb3, 0x5c, 0x72, 0x10, 0xf2, 0xa1, 0xf4, 0x48, 0x9d, 0x32, 0x46, 0x52, 0x74, 0x8d, 0x53, 0x4d, 0x4a, 0xb1, 0x5f, 0x92, 0xf4, 0x7c, 0x0b, 0xa0, 0xee, 0xf2, 0x8a, 0x49, 0x36, 0x92, 0x3e, 0x9c, 0x3f, 0xe5, 0x85, 0x33, 0xc0, 0xbc, 0xd9, 0x63, 0xa9, 0xfa, 0x66, 0x36, 0x2e, 0x41, 0x74, 0x12, 0xe1, 0xd7, 0x71, 0x9e, 0xd9, 0xd9, 0xcc, 0x9c, 0xeb, 0xd7, 0xc7, 0xb7, 0x7e, 0x97, 0x2d, 0xce, 0x9a, 0xca, 0x16, 0x5b, 0x82, 0x6f, 0x3d, 0x5e, 0x6b, 0x09, 0xfa, 0xba, 0xda, 0x50, 0x53, 0x13, 0x84, 0xb8, 0xe9, 0xf4, 0x39, 0x94, 0x18, 0xd1, 0xc5, 0x15, 0x2d, 0x8d, 0xac, 0xf7, 0x06, 0xf4, 0x82, 0x47, 0xe2, 0x97, 0xe4, 0x6b, 0xd1, 0x67, 0x59, 0x88, 0xeb, 0x9e, 0xc2, 0xef, 0x18, 0x30, 0x9d, 0x4a, 0x54, 0x0c, 0x30, 0x67, 0x09, 0x52, 0x91, 0x13, 0xbe, 0xeb, 0xf1, 0xd5, 0xa7, 0x16, 0x27, 0xba, 0x63, 0x23, 0x59, 0x65, 0x61, 0x24, 0xef, 0x72, 0x44, 0xb2, 0x7e, 0x1e, 0x92, 0xaa, 0xbb, 0xe7, 0x29, 0x39, 0xea, 0xcd, 0x75, 0x26, 0x57, 0x15, 0x17, 0x17, 0x92, 0x82, 0x2c, 0x55, 0x46, 0xab, 0x54, 0x3c, 0xb3, 0x4a, 0xc6, 0x33, 0x43, 0x13, 0x30, 0xb2, 0x22, 0x11, 0x95, 0x23, 0x99, 0x29, 0x86, 0x00, 0xf3, 0x2e, 0x33, 0xc9, 0x8c, 0x10, 0x79, 0xb1, 0x65, 0x77, 0x79, 0xd8, 0x65, 0x50, 0x8a, 0xf1, 0xb1, 0xe6, 0x4e, 0xa8, 0xf2, 0x48, 0x9b, 0xcf, 0xf6, 0x32, 0x15, 0x6d, 0xbd, 0xb0, 0xa4, 0x0d, 0x85, 0xed, 0x41, 0x39, 0x38, 0x1a, 0x7e, 0xa2, 0x3d, 0x28, 0x91, 0xf1, 0x5e, 0x9a, 0xf7, 0x26, 0x4b, 0xaa, 0xbb, 0x6c, 0xa6, 0x8a, 0xa0, 0xef, 0xdf, 0xdf, 0x97, 0x95, 0x4a, 0x78, 0x6f, 0x4a, 0x29, 0x00, 0xfb, 0x6b, 0x22, 0x36, 0x29, 0x8b, 0x4c, 0xc3, 0xfd, 0x35, 0x4b, 0x88, 0xf2, 0xd1, 0x8c, 0x08, 0xc4, 0x18, 0x24, 0x2b, 0x94, 0x5a, 0xa0, 0x9c, 0x86, 0xd5, 0xa6, 0x22, 0xd4, 0x7e, 0x8f, 0xb2, 0x2a, 0x65, 0xeb, 0xf9, 0x32, 0x15, 0xc1, 0x2c, 0x87, 0x90, 0xf5, 0x4b, 0xc6, 0x62, 0x64, 0x3f, 0x25, 0x21, 0xeb, 0x17, 0x16, 0x9f, 0xde, 0x85, 0x5a, 0xd3, 0xcf, 0x9a, 0x6b, 0xf1, 0x78, 0x2b, 0xf8, 0x24, 0x7a, 0xc6, 0x04, 0x9c, 0x60, 0x0a, 0x4e, 0x30, 0x25, 0x01, 0x14, 0xd2, 0x7d, 0x05, 0x6a, 0xd7, 0x74, 0xba, 0x49, 0x97, 0xa3, 0x6e, 0x1a, 0xbd, 0x53, 0x80, 0xb9, 0x1b, 0x4f, 0x37, 0xca, 0x5e, 0x1e, 0x38, 0xfb, 0xa3, 0x19, 0x19, 0xf7, 0xfd, 0x83, 0x54, 0x75, 0x7a, 0x6b, 0x4d, 0xb6, 0x17, 0x85, 0xfc, 0x82, 0x52, 0x20, 0x17, 0x43, 0x82, 0x62, 0x48, 0x40, 0x6e, 0x77, 0x56, 0xea, 0xb5, 0x19, 0xda, 0xf4, 0x9a, 0xf1, 0x00, 0x61, 0x92, 0xab, 0xd4, 0x2c, 0xf7, 0x5f, 0x67, 0x90, 0x6c, 0xf6, 0xb4, 0xdf, 0x73, 0x59, 0x2c, 0x53, 0x45, 0xfd, 0xf9, 0xd7, 0x63, 0x5b, 0x1e, 0xb3, 0xf8, 0x01, 0x86, 0xaa, 0x43, 0x87, 0xc5, 0x32, 0x51, 0x1a, 0x5d, 0x0c, 0xfc, 0x99, 0xa8, 0xed, 0x33, 0xd9, 0x5b, 0x19, 0x2a, 0x32, 0x05, 0x77, 0x5e, 0x17, 0xb7, 0x9b, 0xe6, 0x00, 0x3c, 0x87, 0x7a, 0xae, 0x2e, 0x38, 0x88, 0xc4, 0xb1, 0x99, 0x14, 0x15, 0xd9, 0xf0, 0x43, 0x6b, 0x5d, 0x7a, 0x42, 0xc5, 0x17, 0xd6, 0x05, 0x50, 0x16, 0x92, 0xec, 0x4b, 0x16, 0x9a, 0xc6, 0xd4, 0x46, 0xc8, 0xfa, 0x8a, 0x92, 0xf7, 0x16, 0x20, 0x12, 0xf7, 0x07, 0x48, 0x96, 0x96, 0x29, 0x64, 0x0d, 0x12, 0xa1, 0x56, 0xd5, 0xfe, 0x1c, 0xc3, 0xd2, 0x63, 0xd8, 0x3d, 0xb4, 0xf9, 0xd9, 0x52, 0xbe, 0xc6, 0xfb, 0x2c, 0xbc, 0x4b, 0xd8, 0xa7, 0x22, 0xbd, 0x39, 0xc8, 0xb7, 0x38, 0x9e, 0x86, 0xb9, 0x84, 0x78, 0x22, 0x90, 0x08, 0x79, 0x43, 0x8a, 0x2c, 0x28, 0x2d, 0xaa, 0x50, 0xac, 0xba, 0x0a, 0xfc, 0xb4, 0xe1, 0x1f, 0x6d, 0xeb, 0x24, 0x52, 0x67, 0x91, 0xe4, 0xda, 0xf6, 0x15, 0xb9, 0xc0, 0xfa, 0x25, 0x60, 0x53, 0x29, 0xfc, 0x97, 0xae, 0xe0, 0x08, 0x6f, 0x3a, 0x73, 0x4e, 0x64, 0x60, 0x94, 0xe1, 0xca, 0x32, 0x38, 0x8d, 0xa2, 0x68, 0xe0, 0x8a, 0xe5, 0x08, 0x03, 0x46, 0x57, 0xc7, 0x59, 0xf0, 0x61, 0xee, 0x48, 0x03, 0x17, 0x15, 0xd5, 0xd1, 0x46, 0x5a, 0x3e, 0xcb, 0x6c, 0x37, 0x66, 0xd3, 0x3d, 0x7b, 0x62, 0x6c, 0xed, 0xfe, 0x32, 0xe1, 0xa0, 0x88, 0x40, 0xfd, 0x72, 0x54, 0x9b, 0x7f, 0x92, 0xe7, 0x97, 0xd5, 0x63, 0x52, 0x80, 0x7a, 0x1a, 0xc6, 0x90, 0x19, 0x0d, 0xd2, 0x99, 0x4e, 0x99, 0x35, 0x81, 0xda, 0x3a, 0xdd, 0xae, 0x29, 0xa0, 0xef, 0x6c, 0x07, 0xd1, 0x72, 0x75, 0x87, 0xf5, 0x06, 0x2b, 0x28, 0x71, 0x34, 0x49, 0x8b, 0xaa, 0x79, 0xb5, 0x6b, 0x94, 0x89, 0xe4, 0x88, 0x62, 0x2d, 0x1c, 0x51, 0xd3, 0x04, 0x2e, 0x13, 0x47, 0x4c, 0x8b, 0x2c, 0xe0, 0xb6, 0x90, 0xcc, 0xb3, 0xfb, 0x04, 0xa3, 0x58, 0xbb, 0x08, 0x1b, 0x45, 0x5e, 0xc9, 0xcb, 0x41, 0x16, 0xf6, 0x44, 0xa2, 0xd0, 0x98, 0x9e, 0x0f, 0x3c, 0x9c, 0x0c, 0x55, 0xd0, 0x15, 0x95, 0xc2, 0xd4, 0x21, 0xf0, 0x87, 0xfc, 0xe8, 0x2e, 0x30, 0xd5, 0x8a, 0x20, 0x8f, 0x42, 0x52, 0x41, 0xcc, 0x86, 0xd8, 0x2a, 0x82, 0x9e, 0xb4, 0x83, 0x3f, 0xad, 0x68, 0xc1, 0x7b, 0x53, 0x7e, 0x24, 0xc7, 0x3f, 0xc3, 0x0b, 0x4a, 0x1c, 0x9f, 0x43, 0x94, 0xba, 0xb7, 0x04, 0x91, 0x48, 0x12, 0xc8, 0x6d, 0xd2, 0xd5, 0x96, 0x31, 0xe5, 0x1e, 0x8f, 0x91, 0x03, 0xeb, 0x8b, 0x08, 0x46, 0x4c, 0x2d, 0xd3, 0xdd, 0x34, 0x63, 0x42, 0x9a, 0xf1, 0x84, 0xa2, 0x00, 0x65, 0x71, 0xc6, 0xc2, 0xb0, 0xab, 0x58, 0x8a, 0x8d, 0x3d, 0xb7, 0xd8, 0x19, 0x4f, 0xaa, 0x19, 0x23, 0xc9, 0x00, 0x31, 0x29, 0xa7, 0x7b, 0x28, 0xf8, 0x16, 0x61, 0x49, 0x60, 0x7c, 0x10, 0x52, 0xad, 0x88, 0x5b, 0x1b, 0xcc, 0xda, 0x1b, 0x5e, 0x88, 0x0d, 0x2d, 0x09, 0x95, 0xb7, 0x5d, 0xb9, 0x40, 0x93, 0xd8, 0xbf, 0xd3, 0xef, 0x91, 0xe4, 0x04, 0x25, 0x80, 0x15, 0x38, 0x79, 0xfc, 0xee, 0xaa, 0x03, 0xe8, 0xbc, 0x22, 0x45, 0xa8, 0x41, 0x97, 0x18, 0x4a, 0x06, 0xd7, 0x68, 0x81, 0x2a, 0x17, 0x04, 0x0f, 0x25, 0x3e, 0xc5, 0xb6, 0xa7, 0x60, 0x8c, 0x78, 0x3e, 0x76, 0x40, 0x79, 0x3e, 0x78, 0xed, 0x0c, 0x6c, 0xbb, 0xc4, 0x11, 0xd8, 0x3f, 0xde, 0x02, 0x70, 0xac, 0xb9, 0x0f, 0xb3, 0xfd, 0x10, 0xdc, 0xf9, 0x4b, 0xca, 0x19, 0x4e, 0xcb, 0xb8, 0x22, 0xfb, 0xad, 0x6b, 0x89, 0xf0, 0xdc, 0x8e, 0x0c, 0x86, 0xaf, 0x2c, 0xc1, 0x61, 0xf6, 0xa2, 0x24, 0xf5, 0xc7, 0xa9, 0x97, 0xed, 0x2f, 0x28, 0x47, 0x2e, 0x45, 0xdb, 0x7a, 0x93, 0xf1, 0xf1, 0xb5, 0x59, 0x22, 0x3b, 0xb8, 0xed, 0x25, 0x10, 0xda, 0x83, 0x08, 0xa8, 0xa2, 0x9c, 0x56, 0x01, 0x54, 0x8a, 0xc8, 0xc7, 0x60, 0x75, 0xf9, 0xef, 0xa8, 0x06, 0x09, 0x62, 0x1b, 0x4f, 0x3d, 0x8c, 0xb4, 0xaa, 0x97, 0xf5, 0x25, 0xd3, 0xfc, 0x18, 0xb1, 0x1b, 0x5f, 0xee, 0xc5, 0x6e, 0x2a, 0xc9, 0xa2, 0x30, 0x43, 0x33, 0x47, 0xa2, 0xc5, 0x64, 0xa5, 0xb1, 0x23, 0x4a, 0x02, 0xa9, 0xef, 0x6e, 0xaa, 0x2b, 0xaf, 0x23, 0x74, 0x21, 0xd6, 0x01, 0x4b, 0x9d, 0xf7, 0xc3, 0x55, 0x2d, 0xbb, 0xcf, 0x42, 0xa8, 0x47, 0x18, 0xf7, 0xa7, 0xe1, 0xca, 0xd4, 0xfa, 0x47, 0xab, 0x5d, 0x76, 0xff, 0xb1, 0x7c, 0xcf, 0xb2, 0x7f, 0x86, 0x2c, 0xe2, 0x93, 0x66, 0x0c, 0xe3, 0x33, 0xc0, 0xa6, 0xee, 0x2f, 0x41, 0x34, 0xd2, 0xe9, 0x5f, 0x2f, 0x7f, 0x26, 0x79, 0xbc, 0xb0, 0x64, 0x4b, 0x05, 0xeb, 0x49, 0xd0, 0x13, 0xea, 0x81, 0xfd, 0x8e, 0xe6, 0x84, 0xe6, 0xa3, 0xa3, 0xae, 0x0f, 0xca, 0xfb, 0xcd, 0x8e, 0xc6, 0x81, 0x0f, 0x2f, 0xee, 0x07, 0x25, 0x0b, 0x1d, 0x9f, 0x38, 0x56, 0xd9, 0x92, 0x2b, 0x94, 0xdd, 0xe7, 0xc8, 0x15, 0x23, 0xee, 0x56, 0x18, 0x3c, 0x4f, 0xc0, 0xb0, 0xc5, 0x0e, 0x9c, 0xe5, 0x8b, 0x80, 0x2d, 0xc3, 0x1c, 0x95, 0xe8, 0x7c, 0xef, 0x32, 0x4f, 0x3e, 0x7c, 0x4c, 0x6b, 0xc8, 0x13, 0x9b, 0xfa, 0x55, 0xd8, 0xfe, 0x96, 0x25, 0xdb, 0x4b, 0x74, 0x38, 0xbb, 0xb3, 0x1e, 0x82, 0xc4, 0xfe, 0x36, 0x75, 0x7f, 0x09, 0xaa, 0xe6, 0x36, 0x11, 0x7f, 0x5a, 0x10, 0xda, 0x73, 0x22, 0x8c, 0x30, 0x81, 0xce, 0xd6, 0xab, 0xef, 0x55, 0x6a, 0xbf, 0x93, 0x95, 0x3f, 0x2b, 0x8f, 0x12, 0xd7, 0x62, 0xb7, 0x63, 0x27, 0x0b, 0x05, 0xe8, 0x10, 0xc6, 0xb1, 0x11, 0xcc, 0xc4, 0xf7, 0x27, 0xf7, 0x4e, 0xa4, 0xbc, 0x33, 0xee, 0x36, 0x87, 0x68, 0x25, 0x6b, 0x8b, 0xef, 0xac, 0x65, 0x72, 0x0f, 0xec, 0xbc, 0xf2, 0xa7, 0x35, 0xec, 0x15, 0x3f, 0x9e, 0x7e, 0xe3, 0xda, 0x82, 0x3b, 0x81, 0x6a, 0x26, 0x0d, 0xb4, 0xc1, 0x61, 0x85, 0x40, 0x30, 0x3e, 0xb1, 0x46, 0xe3, 0x2c, 0xc4, 0xb0, 0xba, 0xde, 0xa2, 0x9f, 0x58, 0xd5, 0x3d, 0x76, 0xdf, 0xfd, 0x77, 0x24, 0x36, 0x73, 0x63, 0x83, 0xb1, 0xbb, 0x05, 0x56, 0x58, 0x76, 0x60, 0x49, 0x2f, 0x37, 0x39, 0x0b, 0x9d, 0xf0, 0x71, 0xf1, 0x18, 0x4c, 0x53, 0x5e, 0x34, 0x35, 0x07, 0x62, 0x32, 0x16, 0xd9, 0xe0, 0x01, 0xda, 0xfe, 0x47, 0x4e, 0xe5, 0x51, 0xb9, 0x90, 0x4d, 0xad, 0x39, 0xce, 0x0f, 0xb4, 0x40, 0x66, 0xeb, 0x71, 0xeb, 0xf6, 0x48, 0xd5, 0x97, 0x24, 0x68, 0x2d, 0xcc, 0x2b, 0x95, 0x87, 0xa4, 0xd5, 0x70, 0xbb, 0x9c, 0x39, 0x6c, 0x51, 0xa5, 0x17, 0xb4, 0x24, 0x1f, 0xd4, 0x54, 0x52, 0x63, 0x29, 0x2a, 0x25, 0x4f, 0xe2, 0xe2, 0x4f, 0x83, 0x3d, 0xe3, 0xeb, 0x94, 0xeb, 0xa2, 0xcf, 0x68, 0x39, 0x0a, 0x96, 0x27, 0xf3, 0xd0, 0xd8, 0x4f, 0x66, 0xbb, 0x25, 0x8a, 0x8f, 0xeb, 0xa9, 0x3c, 0xb6, 0xa7, 0x9e, 0xca, 0x68, 0x80, 0xfd, 0xce, 0xf7, 0x2e, 0xa7, 0x4a, 0xc2, 0xcc, 0x6f, 0x0d, 0x01, 0x62, 0xab, 0x46, 0x17, 0x06, 0x84, 0xc8, 0x51, 0x1f, 0xba, 0x15, 0xdc, 0x69, 0x5e, 0xf0, 0x40, 0x88, 0xf4, 0xbd, 0x25, 0xe8, 0x14, 0x36, 0xa5, 0xb5, 0xb0, 0x6d, 0x26, 0x4f, 0xe9, 0xe6, 0x9f, 0xce, 0x11, 0xcd, 0x92, 0x82, 0x17, 0xa6, 0x2d, 0x72, 0x10, 0x82, 0xff, 0x3c, 0xb0, 0xa9, 0x07, 0x16, 0xc2, 0x59, 0x96, 0x48, 0x3c, 0x64, 0xc1, 0x6e, 0x4e, 0x85, 0xd4, 0x27, 0x0b, 0x17, 0x4e, 0x34, 0x29, 0x41, 0x40, 0x58, 0xa8, 0x65, 0x41, 0xa4, 0xba, 0x0f, 0x39, 0x70, 0x96, 0x69, 0xcf, 0x1c, 0x9b, 0x91, 0x97, 0xbe, 0xb9, 0x04, 0x89, 0x60, 0x31, 0x60, 0xe5, 0xf9, 0x3c, 0x1e, 0xb2, 0xd4, 0xae, 0x0c, 0x25, 0xee, 0x9b, 0x00, 0xc7, 0xe6, 0xf9, 0xb5, 0xc5, 0x7e, 0xf5, 0x65, 0xb6, 0x9f, 0xca, 0x2b, 0x13, 0x6f, 0x83, 0x1c, 0xec, 0xac, 0x0c, 0x29, 0x62, 0x21, 0x5d, 0x8b, 0x48, 0xd1, 0x4e, 0x16, 0x11, 0x6a, 0x57, 0x50, 0xed, 0x3b, 0xa4, 0x04, 0xc1, 0xef, 0x08, 0x96, 0x73, 0x4a, 0x07, 0xd2, 0x76, 0xbd, 0x72, 0x28, 0x8b, 0x8d, 0xab, 0xcd, 0x8a, 0x82, 0xc3, 0x20, 0xcf, 0x42, 0xfe, 0x12, 0xe5, 0x66, 0x74, 0x02, 0x77, 0x34, 0x6c, 0xc9, 0x6c, 0x61, 0xed, 0x6e, 0x24, 0x90, 0xcd, 0x06, 0x12, 0x2a, 0x80, 0x53, 0xa5, 0x9f, 0x41, 0xd3, 0xc6, 0xe1, 0xaa, 0xd6, 0x19, 0xcb, 0x62, 0x5d, 0x4c, 0xb5, 0xdf, 0xe7, 0x9e, 0xd4, 0x66, 0x21, 0xea, 0x45, 0xa6, 0x80, 0x6d, 0xb1, 0x04, 0x3c, 0x61, 0x65, 0xcb, 0x33, 0xbe, 0x6c, 0x58, 0xc8, 0xe2, 0x7f, 0x2a, 0xaa, 0xd5, 0x7c, 0xae, 0x4c, 0xa8, 0xd6, 0x4c, 0x98, 0x56, 0x54, 0x1f, 0xa4, 0xfc, 0x2c, 0x42, 0xf2, 0x22, 0xdc, 0x6e, 0xba, 0x4a, 0x87, 0x44, 0x9a, 0x2a, 0x24, 0x71, 0xd5, 0xa1, 0x42, 0x21, 0x42, 0xf4, 0x94, 0xc4, 0x14, 0xd2, 0xb7, 0x90, 0x57, 0x36, 0x5a, 0x4f, 0x45, 0xbc, 0x03, 0xbe, 0xef, 0x58, 0x70, 0x1e, 0xc8, 0x58, 0x03, 0xce, 0x57, 0xdf, 0x97, 0xf6, 0x83, 0xd6, 0x6a, 0xe5, 0x74, 0x5d, 0x87, 0x75, 0x47, 0x7c, 0x03, 0xb9, 0x12, 0x84, 0x08, 0x47, 0xce, 0x3d, 0xa0, 0xc6, 0x7e, 0x4c, 0x61, 0xeb, 0x98, 0x2e, 0x61, 0x6c, 0x13, 0x12, 0x78, 0xa4, 0x26, 0x1c, 0x40, 0x8b, 0x1e, 0x0d, 0x8d, 0x64, 0xfb, 0x67, 0x6b, 0xd7, 0x51, 0xa8, 0x74, 0xa7, 0xce, 0xed, 0x56, 0xb6, 0x45, 0x25, 0x4d, 0x9f, 0x00, 0x44, 0xd5, 0x41, 0xd1, 0x58, 0x13, 0x36, 0x13, 0xe5, 0x40, 0x45, 0xeb, 0x6f, 0x91, 0xa1, 0x74, 0x5d, 0x70, 0x7c, 0x4f, 0xae, 0x2d, 0x2b, 0xce, 0x0a, 0x8b, 0x49, 0x4b, 0x19, 0x17, 0x12, 0x0f, 0x1a, 0x96, 0x31, 0xae, 0xa2, 0xdd, 0x5f, 0xc6, 0x00, 0x68, 0xc0, 0x42, 0x86, 0x27, 0x32, 0x75, 0x7a, 0xe1, 0x90, 0x2e, 0x12, 0x85, 0x34, 0x00, 0xb1, 0xc3, 0x72, 0x35, 0x61, 0xb5, 0x74, 0x3d, 0x5a, 0x2f, 0x63, 0x67, 0xad, 0x56, 0x85, 0xa5, 0x32, 0x71, 0xa9, 0x2c, 0x69, 0xaf, 0xca, 0xd4, 0x4d, 0xbf, 0x54, 0xd4, 0x50, 0xd3, 0xda, 0xed, 0x2e, 0x15, 0x8f, 0x07, 0xd3, 0x07, 0xbe, 0x3b, 0xa1, 0xbb, 0x04, 0xcb, 0xab, 0x6e, 0xf8, 0xaf, 0xeb, 0x91, 0x0a, 0xec, 0x07, 0x00, 0x7c, 0x3d, 0x64, 0x01, 0x7c, 0x3d, 0x2e, 0xf5, 0x7c, 0x5e, 0xb3, 0x12, 0x76, 0x3a, 0x16, 0x89, 0x53, 0x98, 0xa0, 0xe4, 0x21, 0x69, 0x4e, 0x13, 0x16, 0xa6, 0x77, 0x1b, 0x6c, 0x36, 0x94, 0x5e, 0x22, 0xa1, 0x7e, 0xa0, 0x5d, 0x40, 0x99, 0x51, 0x25, 0x4a, 0x99, 0x94, 0x22, 0x33, 0x2c, 0xda, 0xa6, 0x2a, 0xe8, 0xd4, 0x95, 0x03, 0x6a, 0x13, 0xd4, 0xc3, 0xfe, 0x6b, 0xae, 0x58, 0xa0, 0xcd, 0xe4, 0xdd, 0x25, 0xc8, 0x04, 0x0b, 0xb3, 0x29, 0x4c, 0x8f, 0x64, 0x81, 0xc9, 0xb4, 0x74, 0x48, 0xe2, 0x4c, 0x2b, 0xfe, 0x3c, 0x3e, 0x7d, 0x7f, 0x09, 0xa2, 0xc1, 0x42, 0x56, 0x0a, 0xf3, 0xe2, 0xe5, 0x40, 0xab, 0x44, 0x97, 0x5c, 0xc8, 0xc2, 0x7f, 0x84, 0x2f, 0xef, 0x60, 0xc3, 0x12, 0x84, 0x85, 0xc5, 0xac, 0xf4, 0x09, 0x65, 0x0b, 0xe4, 0xf0, 0x9d, 0x88, 0xfe, 0x8c, 0x26, 0x64, 0x38, 0xa0, 0x68, 0x3a, 0x40, 0xc4, 0xc3, 0x89, 0xc0, 0x1e, 0x0d, 0x5e, 0x04, 0x6e, 0x83, 0x6e, 0x76, 0x11, 0x59, 0x6a, 0x29, 0xe1, 0xca, 0x82, 0x6f, 0x09, 0x05, 0x8f, 0xc0, 0xe7, 0x66, 0x9e, 0x8a, 0x55, 0x8f, 0x15, 0xd1, 0x1b, 0x00, 0xd5, 0x65, 0x58, 0x47, 0x45, 0x69, 0x7f, 0xf4, 0x5f, 0xf5, 0x85, 0xc3, 0x11, 0xd0, 0x3a, 0x6b, 0x56, 0x54, 0x1e, 0x1d, 0x47, 0x4d, 0xbf, 0xaa, 0x22, 0x1c, 0xde, 0x3a, 0x7f, 0x0c, 0xc3, 0x5a, 0x57, 0xf5, 0xe0, 0xd8, 0xc0, 0xb4, 0xac, 0xf3, 0x3f, 0xd0, 0x41, 0xad, 0x0d, 0x99, 0xb6, 0xe4, 0xe8, 0x08, 0x18, 0x03, 0x67, 0xbd, 0x58, 0x9b, 0x98, 0x4c, 0x5b, 0xf9, 0xd7, 0x23, 0x6d, 0x13, 0x0a, 0xaf, 0xd7, 0x48, 0xcd, 0xa1, 0x6e, 0xfd, 0xa1, 0x0c, 0x07, 0x3e, 0xb9, 0xc2, 0x4b, 0xd4, 0x6b, 0x1d, 0x60, 0xf2, 0x91, 0xcb, 0x4e, 0x55, 0xae, 0x69, 0x57, 0xe1, 0x60, 0x59, 0x85, 0x82, 0x72, 0xb5, 0xbf, 0x53, 0x19, 0x45, 0xdd, 0x54, 0xd6, 0xf9, 0x3b, 0xac, 0xf6, 0x3d, 0x55, 0xd2, 0xd9, 0x5a, 0xbb, 0x5a, 0x7b, 0x19, 0x30, 0x22, 0x24, 0x98, 0x75, 0x38, 0x28, 0xda, 0x6a, 0x15, 0x9e, 0x06, 0xed, 0xa5, 0x21, 0xf9, 0x01, 0x40, 0xb3, 0x5e, 0xcb, 0xd0, 0x6f, 0xa0, 0x3b, 0xc0, 0xf1, 0x0e, 0xbc, 0x30, 0xaa, 0xa5, 0x59, 0x69, 0xd0, 0x69, 0xf8, 0xe7, 0x11, 0x10, 0x29, 0x19, 0x66, 0x2a, 0xb4, 0x71, 0xb2, 0xad, 0x1c, 0x1d, 0x68, 0xe3, 0x24, 0x6b, 0x6f, 0x17, 0x36, 0xf8, 0x78, 0x69, 0x35, 0xec, 0x5a, 0xa0, 0xec, 0x73, 0x58, 0x1c, 0xa9, 0x6c, 0xa8, 0x63, 0xea, 0x65, 0xb6, 0x05, 0x63, 0x0c, 0x9d, 0x44, 0x2d, 0x56, 0xa9, 0xf1, 0xbd, 0x60, 0x89, 0xac, 0x3f, 0xb1, 0xe3, 0x6c, 0x2a, 0x1b, 0x5a, 0xf3, 0xc6, 0xa0, 0x8b, 0x90, 0x3f, 0x2c, 0x4c, 0x8b, 0xc1, 0xe6, 0x1c, 0x51, 0x4e, 0x64, 0x63, 0x2a, 0x67, 0xb4, 0x64, 0x80, 0xd7, 0xe3, 0xab, 0xe3, 0x93, 0xed, 0xa3, 0x55, 0x03, 0xc9, 0x14, 0x2d, 0x5f, 0x3d, 0x92, 0x1a, 0x3d, 0x48, 0xcc, 0x9e, 0xa4, 0x40, 0x44, 0x88, 0xbb, 0xf0, 0x7f, 0x04, 0xe3, 0x19, 0x04, 0x63, 0xef, 0x5d, 0x93, 0x37, 0x13, 0xba, 0x99, 0xc5, 0x88, 0x15, 0xb6, 0x91, 0xe7, 0xc0, 0x88, 0x21, 0xb5, 0x39, 0x95, 0x54, 0xcd, 0x06, 0x69, 0xa7, 0x6e, 0x2f, 0x61, 0xd3, 0xe6, 0x91, 0x62, 0xa5, 0x11, 0x95, 0x3f, 0xbc, 0x28, 0x38, 0x2c, 0x89, 0x2c, 0xfd, 0xfe, 0x8c, 0x80, 0xb0, 0x2c, 0xd2, 0xf1, 0x03, 0xd0, 0x1a, 0x3e, 0xe4, 0xa1, 0x35, 0xf4, 0xdb, 0x1b, 0xef, 0x1d, 0xe6, 0xeb, 0xaa, 0x4c, 0xdf, 0x5f, 0x82, 0x68, 0xb0, 0x98, 0x1f, 0xbf, 0x4d, 0x97, 0x8c, 0x31, 0x7d, 0xc8, 0x01, 0x02, 0x12, 0x81, 0xf0, 0x8d, 0xc5, 0xf7, 0xec, 0xd1, 0x35, 0xb2, 0x76, 0x57, 0xe8, 0x40, 0x5b, 0x0d, 0x02, 0xe8, 0x54, 0x37, 0x0b, 0x20, 0x4e, 0x2d, 0x9b, 0xc9, 0xb7, 0x77, 0x39, 0x81, 0x38, 0x3d, 0xa2, 0xb5, 0x97, 0xa7, 0xaf, 0x09, 0xba, 0xcc, 0x66, 0x59, 0x92, 0xa5, 0x17, 0x26, 0x52, 0xf8, 0x9a, 0x85, 0x34, 0x73, 0x46, 0x84, 0xe3, 0xb0, 0x90, 0x45, 0xb3, 0x18, 0xf1, 0x39, 0x98, 0xca, 0x3d, 0xe7, 0xfa, 0x44, 0xad, 0xc2, 0x90, 0x95, 0x87, 0x9b, 0x3a, 0x59, 0x53, 0x7e, 0x54, 0xa0, 0x65, 0x42, 0x02, 0x34, 0xee, 0x73, 0x7d, 0x1f, 0x43, 0x67, 0xb0, 0xac, 0xab, 0xaa, 0x6f, 0xf7, 0x4c, 0xb1, 0x18, 0x22, 0x18, 0x17, 0x4d, 0x1c, 0x6c, 0x35, 0x35, 0x5a, 0xb3, 0x5f, 0x90, 0xf7, 0x69, 0x5a, 0xf2, 0x2b, 0x8b, 0x69, 0x29, 0xcb, 0xee, 0xfe, 0x9a, 0x87, 0xcd, 0xe8, 0x67, 0x41, 0x46, 0x7e, 0x4d, 0x10, 0xd6, 0x2f, 0xc9, 0x26, 0x67, 0x39, 0xab, 0xd3, 0x32, 0x7b, 0xcb, 0x8e, 0x0f, 0x01, 0x67, 0x5b, 0xd9, 0x54, 0xce, 0xc8, 0xaa, 0xa5, 0xb3, 0xa7, 0xd6, 0xad, 0xb3, 0x56, 0xc5, 0x43, 0xb6, 0x54, 0xba, 0x72, 0xaa, 0x6e, 0xac, 0x3f, 0xfe, 0x5a, 0x1d, 0xb8, 0xd4, 0x94, 0x3f, 0xf6, 0x1a, 0x1d, 0x4f, 0xd1, 0xe4, 0x0f, 0xb0, 0xd6, 0x6f, 0x4c, 0xfe, 0xfc, 0xae, 0x94, 0x31, 0xe1, 0x8c, 0x6b, 0x6a, 0xa7, 0x64, 0xed, 0x8f, 0xb6, 0xc6, 0x1f, 0xcd, 0x03, 0xbd, 0x98, 0xd7, 0x18, 0x75, 0xbd, 0x0a, 0x47, 0x67, 0xd9, 0x6a, 0xed, 0x74, 0xd3, 0x4a, 0x67, 0x5a, 0x54, 0x02, 0x22, 0x00, 0x81, 0x6f, 0xa2, 0xe9, 0xb0, 0xdc, 0xaa, 0xfe, 0x1c, 0x4c, 0x6e, 0x82, 0xc6, 0x55, 0x4d, 0x1d, 0xa7, 0x03, 0xac, 0x43, 0xe5, 0x8f, 0xcc, 0x56, 0x4b, 0x1b, 0x9c, 0x0a, 0xd6, 0x4f, 0xd1, 0xb5, 0x56, 0xd8, 0x70, 0x4e, 0x36, 0xb2, 0xad, 0x83, 0xa6, 0xf2, 0x13, 0x6f, 0x94, 0x09, 0x28, 0x00, 0x3f, 0x9e, 0xb3, 0x3d, 0x47, 0x9b, 0x6d, 0xfc, 0x93, 0xb6, 0x2c, 0x6a, 0x46, 0x62, 0x2d, 0xf8, 0x6d, 0x6e, 0xfb, 0xe3, 0xc8, 0xc6, 0xd6, 0xff, 0xe8, 0xcc, 0x94, 0x0d, 0x4d, 0x45, 0x00, 0x5b, 0xac, 0x5d, 0x17, 0xb2, 0x57, 0xc9, 0x57, 0x67, 0x00, 0x1d, 0x69, 0xa8, 0x86, 0xc4, 0x39, 0x31, 0x80, 0x89, 0xa0, 0xa7, 0x15, 0x5f, 0x4e, 0x7d, 0xef, 0xe8, 0x42, 0x62, 0xa3, 0x14, 0x18, 0xe5, 0xa4, 0x5f, 0x32, 0xe7, 0x45, 0x43, 0xfb, 0x55, 0x27, 0xf7, 0x85, 0xb1, 0x92, 0x58, 0xfe, 0xa2, 0x37, 0x45, 0x54, 0xa2, 0x72, 0xd2, 0x5a, 0xe3, 0x6a, 0x5d, 0x69, 0x2f, 0x33, 0x94, 0x32, 0x63, 0x6c, 0xe5, 0xff, 0x27, 0xee, 0x28, 0xfe, 0x3f, 0xa4, 0xb4, 0x70, 0xb4, 0x48, 0x6d, 0x5d, 0xed, 0xdb, 0x87, 0x97, 0x56, 0xd5, 0x95, 0x70, 0xaa, 0xf1, 0xdd, 0x69, 0x6b, 0xe3, 0xdb, 0xf6, 0xff, 0xf4, 0x22, 0xa6, 0x1b, 0xe1, 0x6f, 0xf4, 0x8d, 0xfc, 0xeb, 0x6d, 0xbd, 0x3c, 0x70, 0x59, 0x9f, 0x68, 0xb8, 0xfb, 0x26, 0xf7, 0xb2, 0x82, 0xbb, 0xc8, 0xcf, 0x87, 0xcd, 0x4a, 0x29, 0x60, 0x94, 0x3a, 0x09, 0x6c, 0x09, 0xb7, 0xea, 0xf4, 0xfb, 0xd8, 0xcd, 0xc2, 0x93, 0x14, 0x0e, 0xdd, 0x6a, 0xb6, 0x02, 0xbc, 0xf4, 0x8f, 0x6e, 0xf7, 0x67, 0x06, 0x2d, 0x31, 0x55, 0x40, 0xac, 0x2c, 0x3c, 0xe4, 0xd7, 0x17, 0x2f, 0x22, 0x36, 0xeb, 0x13, 0xa9, 0x3a, 0xc2, 0x8a, 0x81, 0x84, 0x0a, 0x58, 0x22, 0x30, 0xe1, 0x2a, 0xc2, 0x6d, 0xd5, 0xd0, 0x38, 0x7c, 0xa9, 0xb1, 0x4a, 0x8f, 0x21, 0x55, 0xfe, 0x66, 0x0e, 0x81, 0xbb, 0x7b, 0x75, 0x31, 0x17, 0xec, 0xdc, 0x86, 0x10, 0x28, 0xfe, 0xbc, 0x56, 0xe9, 0x4d, 0x89, 0xe5, 0xd3, 0xa3, 0xca, 0xff, 0x80, 0x5a, 0xe1, 0x75, 0x9c, 0xda, 0xbe, 0xe6, 0x38, 0xb5, 0x55, 0xc1, 0xa8, 0x06, 0xac, 0x2d, 0xfc, 0x35, 0x9c, 0x03, 0xb6, 0xda, 0x15, 0xb6, 0x44, 0xe9, 0x14, 0xae, 0x2f, 0xa7, 0x0d, 0x7b, 0x5e, 0xaa, 0x16, 0x39, 0xc9, 0xf1, 0x7d, 0xef, 0x5d, 0x4e, 0x9c, 0xe4, 0x8e, 0x68, 0xed, 0x25, 0xed, 0x1b, 0x7b, 0x92, 0x2b, 0xcb, 0x69, 0xf4, 0x2d, 0x4f, 0x71, 0x83, 0x4e, 0x1e, 0x4b, 0xe9, 0x32, 0xd9, 0xa0, 0x00, 0xeb, 0xf7, 0xdb, 0x0f, 0x90, 0x17, 0xf4, 0xed, 0x7f, 0xf2, 0x82, 0x9e, 0x51, 0x40, 0x12, 0x7c, 0xdb, 0x85, 0x05, 0x24, 0xbe, 0x65, 0xac, 0x68, 0x88, 0x60, 0x2b, 0x6f, 0x9f, 0xd4, 0x49, 0x38, 0xfd, 0xe1, 0x66, 0x25, 0xc8, 0xca, 0x0f, 0xe0, 0x5d, 0xf9, 0x96, 0xc5, 0xbb, 0xf2, 0xb3, 0x2a, 0x13, 0x96, 0x9e, 0xb7, 0x30, 0x01, 0xc9, 0xc1, 0xbd, 0xfb, 0xf3, 0x54, 0xe6, 0xfe, 0xf6, 0x03, 0xa0, 0x5d, 0xbf, 0x65, 0x41, 0xbb, 0x8a, 0x4e, 0x69, 0x1e, 0x36, 0x9f, 0xe4, 0x1b, 0x9c, 0xb8, 0xbf, 0x04, 0xd1, 0x60, 0x2b, 0x40, 0x16, 0x26, 0x1a, 0x39, 0x6a, 0x3f, 0xfe, 0x3c, 0x44, 0x4a, 0xbf, 0xbd, 0x2b, 0x3c, 0x4b, 0xdd, 0x3f, 0x40, 0x06, 0x79, 0xa0, 0xf2, 0xd8, 0xcc, 0x6b, 0xe6, 0x4b, 0x6a, 0x4f, 0xdd, 0x5d, 0x82, 0x4c, 0x4c, 0x55, 0x1c, 0x2e, 0x47, 0x53, 0xfc, 0x96, 0x23, 0x72, 0x31, 0xd4, 0x6e, 0xd4, 0xe7, 0x36, 0x51, 0xbd, 0x51, 0x27, 0x8f, 0x28, 0x84, 0x72, 0x80, 0x1f, 0x76, 0x00, 0x3e, 0x86, 0x9e, 0x52, 0x75, 0x20, 0x17, 0xe0, 0xeb, 0x3b, 0x11, 0x61, 0x3c, 0x46, 0x3a, 0x25, 0x67, 0x0c, 0x1d, 0x21, 0x36, 0xbf, 0x27, 0xd9, 0xda, 0xcb, 0x91, 0x99, 0xdf, 0x33, 0x72, 0xb3, 0xb7, 0x54, 0x1f, 0xe9, 0xb8, 0xbc, 0xce, 0xc3, 0xcd, 0x0a, 0xd0, 0x2f, 0x7f, 0x61, 0x3d, 0x20, 0x65, 0x09, 0xca, 0x5f, 0xb2, 0xb8, 0x3f, 0xda, 0x4e, 0x68, 0xb6, 0x04, 0x52, 0x8a, 0x47, 0xe0, 0x40, 0x83, 0x12, 0x84, 0x63, 0x8a, 0xec, 0xb3, 0x9c, 0x12, 0xe5, 0x7f, 0xc9, 0xc2, 0xf7, 0x19, 0x34, 0x02, 0x9b, 0x33, 0xc3, 0x5b, 0x26, 0x13, 0x0d, 0x4a, 0xd1, 0x1e, 0x7f, 0x24, 0x70, 0x74, 0x4a, 0xbf, 0x60, 0x25, 0xb5, 0x13, 0x4d, 0xd8, 0x10, 0xdd, 0x20, 0x01, 0x83, 0x59, 0x5d, 0x2d, 0xfc, 0xf5, 0x83, 0x58, 0x8b, 0x3f, 0xb2, 0x81, 0xe7, 0x22, 0x62, 0xc2, 0xdb, 0x1b, 0x04, 0x53, 0xe1, 0x51, 0x74, 0xd5, 0x7e, 0x6d, 0x6d, 0xbe, 0x50, 0xe1, 0x5e, 0x8f, 0xa0, 0xae, 0xf0, 0x7f, 0x83, 0x81, 0x53, 0xd7, 0x94, 0x68, 0x22, 0x15, 0x80, 0x19, 0xfe, 0x00, 0x5d, 0xa3, 0xee, 0x6f, 0x4d, 0xb4, 0x17, 0xd2, 0x1b, 0x3e, 0x2b, 0xd7, 0xc5, 0x57, 0xc7, 0xd5, 0xd3, 0x0b, 0x93, 0xd8, 0x5d, 0x6b, 0x15, 0x90, 0x32, 0xc4, 0xc0, 0x41, 0xd8, 0x09, 0x0b, 0x90, 0x85, 0x1f, 0xaf, 0x11, 0x00, 0xca, 0x00, 0xa9, 0x23, 0x6d, 0xdb, 0x12, 0x24, 0x03, 0xff, 0xb7, 0xd5, 0x81, 0x90, 0xa6, 0xae, 0x8d, 0x70, 0x4d, 0xa3, 0x6a, 0xee, 0x05, 0xe1, 0xc7, 0xbd, 0x17, 0xb4, 0x7b, 0xce, 0xe3, 0x3c, 0xc9, 0x73, 0x82, 0xef, 0x53, 0xcf, 0xc7, 0x8e, 0x0b, 0x29, 0x67, 0xf3, 0xd8, 0x8b, 0xb3, 0xc1, 0xff, 0xc8, 0x91, 0xcd, 0x4e, 0x62, 0x47, 0x45, 0xfb, 0x84, 0x4a, 0x56, 0x50, 0x67, 0xde, 0xcb, 0xcc, 0x76, 0x25, 0xe8, 0x44, 0x36, 0x8d, 0x81, 0x1e, 0x6b, 0x51, 0xac, 0x3a, 0x1d, 0x77, 0x0c, 0xb1, 0x79, 0x3a, 0xcb, 0xe9, 0xb9, 0xd6, 0x4e, 0x43, 0xf0, 0x54, 0xea, 0x3b, 0x50, 0x15, 0x53, 0x53, 0x60, 0x5f, 0x9c, 0x72, 0xa4, 0x3a, 0x6c, 0xc4, 0x42, 0x9d, 0x9b, 0xa4, 0x5c, 0xb0, 0xdf, 0xda, 0x38, 0x96, 0xad, 0x51, 0x37, 0x22, 0x3e, 0xb3, 0xdb, 0x5e, 0x3b, 0x30, 0xfc, 0x10, 0x7f, 0xcf, 0xd4, 0x10, 0x0b, 0x01, 0x83, 0x35, 0x33, 0x72, 0x82, 0x21, 0xe8, 0xe0, 0x53, 0xcd, 0x96, 0xc9, 0xef, 0xdf, 0xff, 0x1b, 0x82, 0xe6, 0x89, 0x5e, 0x2a, 0x50, 0x02, 0x00 }; z_const size_t kShortNumberMetaDataCompressedLength = sizeof(kShortNumberMetaData); z_const size_t kShortNumberMetaDataExpandedLength = 151594; #endif // SHORT_NUMBER_SUPPORT
bungkhus/FlagPhoneNumber
<|start_filename|>src/MIDebugEngine/Natvis.Impl/VisualizationCache.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Microsoft.MIDebugEngine.Natvis { public class VisualizationCache { private struct VisualizerKey : IEquatable<VisualizerKey>, IComparable<VisualizerKey> { private string _name; private int _threadId; private int _level; public VisualizerKey(IVariableInformation variable) { _name = variable.FullName(); _threadId = variable.Client.Id; _level = (int)variable.ThreadContext.Level; } public VisualizerKey(string name, int threadId, int level) { _name = name; _threadId = threadId; _level = level; } public int CompareTo(VisualizerKey other) { int res = string.Compare(_name, other._name, StringComparison.Ordinal); if (res == 0) { res = _threadId - other._threadId; if (res == 0) { res = _level - other._level; } } return res; } public bool Equals(VisualizerKey other) { return CompareTo(other) == 0; } public override bool Equals(object obj) { return Equals((VisualizerKey)obj); } public override int GetHashCode() { return base.GetHashCode(); } } private Dictionary<VisualizerKey, VisualizerWrapper> _cache; internal VisualizationCache() { _cache = new Dictionary<VisualizerKey, VisualizerWrapper>(); } internal void Add(IVariableInformation var) { if (var is VisualizerWrapper) { lock (_cache) { VisualizerKey key = new VisualizerKey(var); if (!_cache.ContainsKey(key)) _cache.Add(key, (var as VisualizerWrapper)); } } } internal IVariableInformation Lookup(IVariableInformation var) { if (var is VisualizerWrapper) { lock (_cache) { VisualizerWrapper result = null; _cache.TryGetValue(new VisualizerKey(var), out result); return result; } } return null; } /// <summary> /// Check how this variable should be visualized on refresh /// </summary> /// <param name="var">the variable to display</param> /// <returns> /// 1. var if var is not a VisualizationWrapper /// 2. null if a VisualizedView that is not in the cache already /// 2. Lookup(var) if in the cache /// </returns> internal IVariableInformation VisualizeOnRefresh(IVariableInformation var) { if (var is VisualizerWrapper) { lock (_cache) { VisualizerWrapper result = null; if (_cache.TryGetValue(new VisualizerKey(var), out result)) { return result; } return null; } } return var; } internal void Flush() { lock (_cache) { _cache.Clear(); } } } } <|start_filename|>test/DebuggerTesting/Attribution/TestSettingsProviderAttribute.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using DebuggerTesting.TestFramework; namespace DebuggerTesting.Attribution { /// <summary> /// Attribute used to specify which class is used from providing test settings. /// </summary> [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false, Inherited = false)] public sealed class TestSettingsProviderAttribute : Attribute { #region Constructor public TestSettingsProviderAttribute(Type providerType) { Parameter.AssertIfNotOfType<ITestSettingsProvider>(providerType, nameof(providerType)); this.ProviderType = providerType; } #endregion #region Properties public Type ProviderType { get; private set; } #endregion } } <|start_filename|>test/CppTests/debuggees/kitchensink/src/calling.cpp<|end_filename|> #include "calling.h" Calling::Calling() : Feature("Calling") { } // Averages a variable number of doubles. Pass the count into argCount double average(int argCount, ...) { va_list args; va_start(args, argCount); double total = 0; for (int i = 0; i < argCount; i++) { total += va_arg(args, double); } va_end(args); return total / argCount; } void recursiveCall(int count) { if (count <= 0) return; recursiveCall(count - 1); } void c() { } void b() { c(); } void a() { b(); } void Calling::CoreRun() { this->Log("Calling recursive function."); recursiveCall(30); a(); this->Log("Calling variable arg function."); double ave = average(10, 1.0, 3.0, 4.5, 11.0, -30.0, 17.4, 2.1, -4.0, 0.0, 12.1); this->Log("Average ", ave); } <|start_filename|>src/OpenDebugAD7/AD7Impl/AD7Port.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.VisualStudio.Debugger.Interop; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace OpenDebugAD7.AD7Impl { internal sealed class AD7Port : IDebugPort2, IDebugDefaultPort2 { private readonly Dictionary<AD_PROCESS_ID, AD7Process> _processMap = new Dictionary<AD_PROCESS_ID, AD7Process>(); private readonly IDebugPortNotify2 _portNotify; internal AD7Port(IDebugPortNotify2 portNotify) { _portNotify = portNotify; } public int GetPortName(out string pbstrName) { throw new NotImplementedException(); } public int GetPortId(out Guid pguidPort) { throw new NotImplementedException(); } public int GetPortRequest(out IDebugPortRequest2 ppRequest) { throw new NotImplementedException(); } public int GetPortSupplier(out IDebugPortSupplier2 ppSupplier) { throw new NotImplementedException(); } public int GetProcess(AD_PROCESS_ID processId, out IDebugProcess2 ppProcess) { AD7Process process; lock (_processMap) { if (!_processMap.TryGetValue(processId, out process)) { process = new AD7Process(this, processId); _processMap.Add(processId, process); } } ppProcess = process; return HRConstants.S_OK; } public int EnumProcesses(out IEnumDebugProcesses2 ppEnum) { throw new NotImplementedException(); } public bool RemoveProcess(IDebugProcess2 process) { var ad7Process = process as AD7Process; if (ad7Process == null) { throw new ArgumentOutOfRangeException(nameof(process)); } lock (_processMap) { return _processMap.Remove(ad7Process.PhysicalProcessId); } } public int GetPortNotify(out IDebugPortNotify2 portNotify) { portNotify = _portNotify; return HRConstants.S_OK; } public int GetServer(out IDebugCoreServer3 ppServer) { throw new NotImplementedException(); } public int QueryIsLocal() { throw new NotImplementedException(); } } } <|start_filename|>src/DebugEngineHost/HostRunInTerminal.cs<|end_filename|> using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Microsoft.DebugEngineHost { /// <summary> /// Provides ability to launch in a VS Code protocol supported terminal /// </summary> public static class HostRunInTerminal { public static bool IsRunInTerminalAvailable() { return false; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "cwd")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")] public static void RunInTerminal(string title, string workingDirectory, bool useExternalConsole, IReadOnlyList<string> commandArgs, IReadOnlyDictionary<string, string> environmentVariables, Action<int?> success, Action<string> failure) { throw new NotImplementedException(); } } } <|start_filename|>test/DebuggerTesting/OpenDebug/RunnerException.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Globalization; using System.Runtime.Serialization; namespace DebuggerTesting.OpenDebug { /// <summary> /// Provides a serializable exception for errors that occur when running /// the debug adapter runner. /// </summary> #if !CORECLR [Serializable] #endif public class RunnerException : Exception { // Required for serialization public RunnerException() { } // Required for serialization public RunnerException(string message) : base(message) { } public RunnerException(string messageFormat, params object[] messageArgs) : base(string.Format(CultureInfo.CurrentCulture, messageFormat, messageArgs)) { } public RunnerException(string message, Exception innerException) : base(message, innerException) { } public RunnerException(Exception innerException, string messageFormat, params object[] messageArgs) : base(string.Format(CultureInfo.CurrentCulture, messageFormat, messageArgs), innerException) { } #if !CORECLR // Required for serialization protected RunnerException(SerializationInfo info, StreamingContext context) : base(info, context) { } #endif } } <|start_filename|>test/DebuggerTesting/OpenDebug/Commands/InitializeCommand.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using DebuggerTesting.OpenDebug.Commands.Responses; using Newtonsoft.Json; namespace DebuggerTesting.OpenDebug.Commands { #region InitializeCommandArgs public sealed class InitializeCommandArgs : JsonValue { public string adapterID; public bool linesStartAt1; public bool columnsStartAt1; public string pathFormat; } #endregion public sealed class InitializeResponseValue : CommandResponseValue { public sealed class Body { [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public bool? supportsConfigurationDoneRequest; [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public bool? supportsFunctionBreakpoints; [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public bool? supportsConditionalBreakpoints; [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public bool? supportsEvaluateForHovers; [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public bool? supportsSetVariable; } public Body body = new Body(); } internal class InitializeResponse : CommandResponse<InitializeResponseValue> { public InitializeResponse(string commandName) : base(commandName) { } } /// <summary> /// Required initialization information passed to the debugger. /// </summary> public class InitializeCommand : CommandWithResponse<InitializeCommandArgs, InitializeResponseValue> { public InitializeCommand(string adapterId) : base("initialize") { this.Args.adapterID = adapterId; this.Args.linesStartAt1 = true; this.Args.columnsStartAt1 = true; this.Args.pathFormat = "path"; } } } <|start_filename|>test/Android/SwitchFramesInCallStack/SwitchFramesInCallStack/SwitchFramesInCallStack.NativeActivity/Source2.cpp<|end_filename|> #include "Header1.h" #include "Header2.h" int* func6(func4 f4, func5 f5) { f4(); int ret = f5(1, 2); return &ret; } void func7() { int x = 0; return; } int func8(int x, int y) { return x + y; } <|start_filename|>src/DebugEngineHost.VSCode/HostWaitDialog.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; namespace Microsoft.DebugEngineHost { /// <summary> /// This is a nop implementation of HostWaitDialog. For now at least, /// there is no way to put up the dialog in VS Code, so do nothing. /// </summary> public sealed class HostWaitDialog : IDisposable { public HostWaitDialog(string format, string caption) { } public void ShowWaitDialog(string item) { } public void EndWaitDialog() { } public void Dispose() { EndWaitDialog(); } } } <|start_filename|>src/MIDebugEngine/Engine.Impl/SourceLine.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Diagnostics; using MICore; namespace Microsoft.MIDebugEngine { public class SourceLineMap : Dictionary<ulong, SourceLine> { public SourceLineMap(int capacity) : base(capacity) { } public void Add(ulong addr, uint line) { base.Add(addr, new SourceLine(line, addr)); } public void Replace(ulong addr, uint line) { base[addr] = new SourceLine(line, addr); } } public struct SourceLine { public uint Line { get; private set; } public ulong AddrStart { get; private set; } public SourceLine(uint line, ulong addr) { Line = line; AddrStart = addr; } public bool EndOfFunction { get { return Line == 0; } } } internal class SourceLineCache { private Dictionary<string, SourceLineMap> _mapFileToLinenums; private DebuggedProcess _process; public SourceLineCache(DebuggedProcess process) { _process = process; _mapFileToLinenums = new Dictionary<string, SourceLineMap>(); } public void Clear() { lock (_mapFileToLinenums) { this._mapFileToLinenums.Clear(); } } internal async Task<SourceLineMap> GetLinesForFile(string file) { string fileKey = file; lock (_mapFileToLinenums) { if (_mapFileToLinenums.ContainsKey(fileKey)) { return _mapFileToLinenums[fileKey]; } } SourceLineMap linesMap = null; linesMap = await LinesForFile(fileKey); lock (_mapFileToLinenums) { if (_mapFileToLinenums.ContainsKey(fileKey)) { return _mapFileToLinenums[fileKey]; } if (linesMap != null) { _mapFileToLinenums.Add(fileKey, linesMap); } else { _mapFileToLinenums.Add(fileKey, new SourceLineMap(0)); // empty list to prevent requerying. Release this list on dynamic library loading } return _mapFileToLinenums[fileKey]; } } private async Task<SourceLineMap> LinesForFile(string file) { string cmd = "-symbol-list-lines " + _process.EnsureProperPathSeparators(file); Results results = await _process.CmdAsync(cmd, ResultClass.None); if (results.ResultClass != ResultClass.done) { return null; } ValueListValue lines = results.Find<ValueListValue>("lines"); SourceLineMap linesMap = new SourceLineMap(lines.Content.Length); for (int i = 0; i < lines.Content.Length; ++i) { ulong addr = lines.Content[i].FindAddr("pc"); uint line = lines.Content[i].FindUint("line"); if (linesMap.ContainsKey(addr)) { // It is actually fairly common for an address to map to more than one line. For instance, // in debug builds destructors can have an entry to line 0 as well as one to the correct line. // Release builds with inlining will hit this very often. // Unforunately, without more context, it is impossible to know which line is the "right" line. // For the inline case, any line will be acceptable. For the destructor case, we should prefer // a non-zero line. if (linesMap[addr].Line == 0) { linesMap.Replace(addr, line); } } else { linesMap.Add(addr, line); } } return linesMap; } internal void OnLibraryLoad() { lock (_mapFileToLinenums) { List<string> toDelete = new List<string>(); foreach (var l in _mapFileToLinenums) { if (l.Value.Count == 0) { toDelete.Add(l.Key); } } foreach (var file in toDelete) { _mapFileToLinenums.Remove(file); // requery for line numbers next time they are asked for } } } } } <|start_filename|>src/SSHDebugPS/Docker/DockerPort.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information.using System; using Microsoft.VisualStudio.Shell; namespace Microsoft.SSHDebugPS.Docker { internal class DockerPort : AD7Port { public DockerPort(AD7PortSupplier portSupplier, string name, bool isInAddPort) : base(portSupplier, name, isInAddPort) { } protected override Connection GetConnectionInternal() { ThreadHelper.ThrowIfNotOnUIThread(); return ConnectionManager.GetDockerConnection(Name, supportSSHConnections: true); } } } <|start_filename|>test/CppTests/debuggees/sharedlib/src/mylib_base.h<|end_filename|> #include <string> using namespace std; class myBase { public: virtual int DisplayAge(int age) = 0; virtual string DisplayName(string firstName, string lastName) = 0; }; <|start_filename|>src/DebugEngineHost/HostMarshal.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.VisualStudio.Debugger.Interop; using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; using System.Diagnostics; namespace Microsoft.DebugEngineHost { /// <summary> /// This class provides marshalling helper methods to a debug engine. /// /// When run in Visual Studio, these methods deal with COM marshalling. /// /// When run in Visual Studio code, these methods are stubs to allow the AD7 API to function without COM. /// </summary> public static class HostMarshal { /// <summary> /// Registers the specified code context if it isn't already registered and returns an IntPtr that can be /// used by the host to get back to the object. /// </summary> /// <param name="codeContext">Object to register</param> /// <returns>In VS, the IntPtr to a native COM object which can be returned to VS. In VS Code, an identifier /// that allows VS Code to get back to the object.</returns> public static IntPtr RegisterCodeContext(IDebugCodeContext2 codeContext) { if (!Host.IsOnMainThread()) { Debug.Fail("Operation should be on main thread."); throw new MethodAccessException("COM Operation must occur on main thread."); } return Marshal.GetComInterfaceForObject(codeContext, typeof(IDebugCodeContext2)); } /// <summary> /// Obtains a document position interface given the specified IntPtr of the document position. /// </summary> /// <param name="documentPositionId">In VS, the IUnknown pointer to QI for a document position. In VS Code, /// the identifier for the document position</param> /// <returns>Document position object</returns> public static IDebugDocumentPosition2 GetDocumentPositionForIntPtr(IntPtr documentPositionId) { // TODO: It looks like the MIEngine currently leaks the native document position. Fix that. if (!Host.IsOnMainThread()) { Debug.Fail("Operation should be on main thread."); throw new MethodAccessException("COM Operation must occur on main thread."); } return (IDebugDocumentPosition2)Marshal.GetObjectForIUnknown(documentPositionId); } /// <summary> /// Obtains a function position interface given the specified IntPtr of the location. /// </summary> /// <param name="locationId">In VS, the IUnknown pointer to QI for a function position. In VS Code, /// the identifier for the function position</param> /// <returns>Function position object</returns> public static IDebugFunctionPosition2 GetDebugFunctionPositionForIntPtr(IntPtr locationId) { // TODO: It looks like the MIEngine currently leaks the native document position. Fix that. if (!Host.IsOnMainThread()) { Debug.Fail("Operation should be on main thread."); throw new MethodAccessException("COM Operation must occur on main thread."); } return (IDebugFunctionPosition2)Marshal.GetObjectForIUnknown(locationId); } /// <summary> /// Obtain the string expression from the bpLocation union for a BPLT_DATA_STRING breakpoint. /// </summary> /// <param name="stringId"></param> /// <returns></returns> public static string GetDataBreakpointStringForIntPtr(IntPtr stringId) { if (!Host.IsOnMainThread()) { Debug.Fail("Operation should be on main thread."); throw new MethodAccessException("COM Operation must occur on main thread."); } return (string)Marshal.PtrToStringBSTR(stringId); } /// <summary> /// Return the string form of the address of a bound data breakpoint /// </summary> /// <param name="address">address string</param> /// <returns>IntPtr to a BSTR which can be returned to VS.</returns> public static IntPtr GetIntPtrForDataBreakpointAddress(string address) { if (!Host.IsOnMainThread()) { Debug.Fail("Operation should be on main thread."); throw new MethodAccessException("COM Operation must occur on main thread."); } return Marshal.StringToBSTR(address); } /// <summary> /// Obtains a code context interface given the specified IntPtr of the location. /// </summary> /// <param name="contextId">In VS, the IUnknown pointer to QI for a code context. In VS Code, /// the identifier for the code context</param> /// <returns>code context object</returns> public static IDebugCodeContext2 GetDebugCodeContextForIntPtr(IntPtr contextId) { // TODO: It looks like the MIEngine currently leaks the code context. Fix that. if (!Host.IsOnMainThread()) { Debug.Fail("Operation should be on main thread."); throw new MethodAccessException("COM Operation must occur on main thread."); } return (IDebugCodeContext2)Marshal.GetObjectForIUnknown(contextId); } /// <summary> /// Obtains an event callback interface that can be used to send events on any threads /// </summary> /// <param name="ad7Callback">The underlying event call back which was obtained from the port</param> /// <returns>In VS, a thread-safe wrapper on top of the underlying SDM event callback which allows /// sending events on any thread. In VS Code, this just returns the provided ad7Callback. </returns> public static IDebugEventCallback2 GetThreadSafeEventCallback(IDebugEventCallback2 ad7Callback) { return new VSImpl.VSEventCallbackWrapper(ad7Callback); } public static int Release(IntPtr unknownId) { return Marshal.Release(unknownId); } } } <|start_filename|>src/MIDebugEngine/AD7.Impl/EngineConstants.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Text; namespace Microsoft.MIDebugEngine { static public class EngineConstants { /// <summary> /// This is the engine GUID of the engine. It needs to be changed here and in the registration /// when creating a new engine. /// </summary> public static readonly Guid EngineId = new Guid("{ea6637c6-17df-45b5-a183-0951c54243bc}"); public static readonly Guid GdbEngine = new Guid("{91744D97-430F-42C1-9779-A5813EBD6AB2}"); public static readonly Guid LldbEngine = new Guid("{5D630903-189D-4837-9785-699B05BEC2A9}"); } } <|start_filename|>src/IOSDebugLauncher/IOSLaunchOptions.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml; using MICore; using System.Runtime.InteropServices; using System.IO; using System.Globalization; using System.Diagnostics; namespace IOSDebugLauncher { public enum IOSDebugTarget { Device, Simulator, } internal class IOSLaunchOptions { public IOSLaunchOptions(string exePath, MICore.Xml.LaunchOptions.IOSLaunchOptions xmlOptions) { if (string.IsNullOrEmpty(exePath)) throw new ArgumentNullException(nameof(exePath)); if (xmlOptions == null) throw new ArgumentNullException(nameof(xmlOptions)); this.ExePath = exePath; this.RemoteMachineName = LaunchOptions.RequireAttribute(xmlOptions.RemoteMachineName, "RemoteMachineName"); this.PackageId = LaunchOptions.RequireAttribute(xmlOptions.PackageId, "PackageId"); this.VcRemotePort = LaunchOptions.RequirePortAttribute(xmlOptions.vcremotePort, "vcremotePort"); Debug.Assert((uint)IOSDebugTarget.Device == (uint)MICore.Xml.LaunchOptions.IOSLaunchOptionsIOSDebugTarget.Device); Debug.Assert((uint)IOSDebugTarget.Simulator == (uint)MICore.Xml.LaunchOptions.IOSLaunchOptionsIOSDebugTarget.Simulator); this.IOSDebugTarget = (IOSDebugTarget)xmlOptions.IOSDebugTarget; this.TargetArchitecture = LaunchOptions.ConvertTargetArchitectureAttribute(xmlOptions.TargetArchitecture); this.AdditionalSOLibSearchPath = xmlOptions.AdditionalSOLibSearchPath; this.Secure = (xmlOptions.Secure == MICore.Xml.LaunchOptions.IOSLaunchOptionsSecure.True); this.DeviceUdid = xmlOptions.DeviceUdid ?? string.Empty; } public string ExePath { get; private set; } public string RemoteMachineName { get; private set; } public string PackageId { get; private set; } public int VcRemotePort { get; private set; } public IOSDebugTarget IOSDebugTarget { get; private set; } public string DeviceUdid { get; private set; } public TargetArchitecture TargetArchitecture { get; private set; } public string AdditionalSOLibSearchPath { get; private set; } public bool Secure { get; private set; } } } <|start_filename|>test/CppTests/debuggees/kitchensink/src/nonterminating.cpp<|end_filename|> #include "nonterminating.h" NonTerminating::NonTerminating() : Feature("NonTerminating") { } void ThreadLoop(NonTerminating* t) { t->Log("Starting thread in NonTerminating"); while (!t->shouldExit) { this_thread::sleep_for(chrono::milliseconds(10)); } t->Log("Ending NonTerminating thread"); } void NonTerminating::CoreRun() { // Threading introduces timining differences when debugging. // Add background thread for common attach scenarios. thread backgroundThread(ThreadLoop, this); this->Log("Starting infinite loop."); bool shouldExitLocal = false; while (!(this->shouldExit || shouldExitLocal)) { this->DoSleep(); } this->shouldExit = true; this->Log("Exited infinite loop."); backgroundThread.join(); } void NonTerminating::DoSleep() { this_thread::sleep_for(chrono::milliseconds(30)); } <|start_filename|>test/CppTests/debuggees/optimization/src/source.cpp<|end_filename|> #include <iostream> #include <string> #include "mylib_base.h" #include "foo.h" #include "..//..//..//sharedlib//src//global.h" #include "..//..//..//sharedlib//src//sharedlib.h" using namespace std; typedef myBase* p_create(); typedef void p_destroy(myBase*); p_create* create; p_destroy* destroy; LIBRARY_HANDLE pHandle; void OpenMyLibrary() { string platform = STRINGIFY(DEBUGGEE_PLATFORM); create = NULL; destroy = NULL; string dllName = "mylib.dll"; string soName = "./mylib.so"; string libraryName = (platform.compare("WINDOWS") == 0) ? dllName : soName; pHandle = OpenLibrary(libraryName); if (!pHandle) { LogLibraryError("OpenLibrary"); return; } create = (p_create*)GetLibraryFunction(pHandle, "Create"); if (!create) { LogLibraryError("Get Create"); } destroy = (p_destroy*)GetLibraryFunction(pHandle, "Destroy"); if (!destroy) { LogLibraryError("Get Destroy"); } } void CloseMyLibrary() { create = NULL; destroy = NULL; if (pHandle != NULL) { bool closed = CloseLibrary(pHandle); if (!closed) { LogLibraryError("CloseLibarary"); } } } int main() { Foo * pFoo = new Foo(); cout << "default sum: " << pFoo->Sum() << endl; pFoo = new Foo(10); cout << " new sum:" << pFoo->Sum() << endl; if (pFoo) { delete pFoo; pFoo = NULL; } cout << "Start testing" << endl; string firstName = "Richard"; string lastName = "Zeng"; OpenMyLibrary(); myBase* myclass = create(); int age = myclass->DisplayAge(30); myclass->DisplayName(firstName, lastName); destroy(myclass); CloseMyLibrary(); cout << "Finish testing" << endl; return 0; } <|start_filename|>src/JDbg/Utils.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; namespace JDbg { /// <summary> /// Utilities for converting Big-Endian to Little-Endian /// </summary> public static class Utils { public static UInt32 UInt32FromBigEndianBytes(byte[] bytes) { Debug.Assert(bytes.Length == 4); int networkOder = BitConverter.ToInt32(bytes, 0); return (uint)IPAddress.NetworkToHostOrder(networkOder); } public static byte[] BigEndianBytesFromUInt32(UInt32 num) { int networkOrder = IPAddress.HostToNetworkOrder((int)num); return BitConverter.GetBytes(networkOrder); } public static ushort UInt16FromBigEndianBytes(byte[] bytes) { Debug.Assert(bytes.Length == 2); Int16 networkOrder = BitConverter.ToInt16(bytes, 0); return (UInt16)IPAddress.NetworkToHostOrder(networkOrder); } /// <summary> /// This method returns a ulong for a variable length array of big endian bytes. /// </summary> /// <param name="bytes">Big endian bytes to convert</param> /// <returns></returns> public static ulong ULongFromBigEndiantBytes(byte[] bytes) { Debug.Assert(bytes.Length <= 8); byte[] ulongBytes = { 0, 0, 0, 0, 0, 0, 0, 0 }; for (int i = 0; i < bytes.Length && i < 8; i++) { ulongBytes[bytes.Length - 1 - i] = bytes[i]; } return BitConverter.ToUInt64(ulongBytes, 0); } } } <|start_filename|>src/DebugEngineHost.VSCode/HostLoader.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; namespace Microsoft.DebugEngineHost { public static class HostLoader { public static object VsCoCreateManagedObject(HostConfigurationStore configStore, Guid clsid) { throw new NotImplementedException(); } } } <|start_filename|>src/tools/MakePIAPortableTool/MakePIAPortableTool.cs<|end_filename|> using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Text; using System.Text.RegularExpressions; namespace MakePIAPortable { class Program { #if DEBUG // Set this to a valid number to break the processing when we get to it public const int BreakLine = -1; #endif const string System_Runtime = "System.Runtime"; const string System_Runtime_InteropServices = "System.Runtime.InteropServices"; const string System_Threading = "System.Threading"; static List<Tuple<string, string>> s_contractAssemblies = new List<Tuple<string, string>> { new Tuple<string, string>(System_Runtime, "4:0:20:0"), new Tuple<string, string>(System_Runtime_InteropServices, "4:0:20:0"), new Tuple<string, string>(System_Threading, "4:0:20:0") }; static Dictionary<string, string> s_typeToContractAssemblyMap = new Dictionary<string, string> { // System.Runtime { "System.Byte", System_Runtime }, { "System.Decimal", System_Runtime }, { "System.Enum", System_Runtime }, { "System.FlagsAttribute", System_Runtime }, { "System.Guid", System_Runtime }, { "System.Object", System_Runtime }, { "System.Type", System_Runtime }, { "System.ValueType", System_Runtime }, { "System.Collections.Generic.IEnumerable", System_Runtime }, { "System.Reflection.DefaultMemberAttribute", System_Runtime }, { "System.Reflection.AssemblyDelaySignAttribute", System_Runtime}, { "System.Runtime.CompilerServices.CompilationRelaxationsAttribute", System_Runtime }, { "System.Runtime.CompilerServices.RuntimeCompatibilityAttribute", System_Runtime }, { "System.Diagnostics.DebuggableAttribute", System_Runtime }, { "System.Reflection.AssemblyTitleAttribute", System_Runtime }, { "System.Runtime.Versioning.TargetFrameworkAttribute", System_Runtime }, { "System.Reflection.AssemblyCompanyAttribute", System_Runtime }, { "System.Reflection.AssemblyConfigurationAttribute", System_Runtime }, { "System.Reflection.AssemblyCopyrightAttribute", System_Runtime }, { "System.Reflection.AssemblyFileVersionAttribute", System_Runtime }, { "System.Reflection.AssemblyInformationalVersionAttribute", System_Runtime }, { "System.Reflection.AssemblyProductAttribute", System_Runtime }, { "System.Runtime.CompilerServices.CompilerGeneratedAttribute", System_Runtime }, { "System.MulticastDelegate", System_Runtime }, { "System.IAsyncResult", System_Runtime }, { "System.AsyncCallback", System_Runtime }, { "System.IDisposable", System_Runtime }, { "System.Runtime.CompilerServices.RuntimeHelpers", System_Runtime }, { "System.Array", System_Runtime }, { "System.RuntimeFieldHandle", System_Runtime }, { "System.Threading.Monitor", System_Threading }, { "System.GC", System_Runtime }, { "System.Exception", System_Runtime }, { "System.Collections.IEnumerable", System_Runtime }, { "System.Collections.IEnumerator", System_Runtime }, { "System.DateTime", System_Runtime }, { "System.ObsoleteAttribute", System_Runtime }, { "System.Attribute", System_Runtime }, // System.Runtime.InteropServices { "System.Runtime.InteropServices.ClassInterfaceAttribute", System_Runtime_InteropServices }, { "System.Runtime.InteropServices.ClassInterfaceType", System_Runtime_InteropServices }, { "System.Runtime.InteropServices.CoClassAttribute", System_Runtime_InteropServices }, { "System.Runtime.InteropServices.ComInterfaceType", System_Runtime_InteropServices }, { "System.Runtime.InteropServices.DispIdAttribute", System_Runtime_InteropServices }, { "System.Runtime.InteropServices.GuidAttribute", System_Runtime_InteropServices}, { "System.Runtime.InteropServices.InterfaceTypeAttribute", System_Runtime_InteropServices }, { "System.Runtime.InteropServices.ComVisibleAttribute", System_Runtime_InteropServices }, { "System.Runtime.InteropServices.ComSourceInterfacesAttribute", System_Runtime_InteropServices }, { "System.Runtime.InteropServices.ComEventInterfaceAttribute", System_Runtime_InteropServices }, { "System.Runtime.InteropServices.ComTypes.IConnectionPointContainer", System_Runtime_InteropServices }, { "System.Runtime.InteropServices.ComTypes.IConnectionPoint", System_Runtime_InteropServices }, { "System.Runtime.InteropServices.Marshal", System_Runtime_InteropServices }, { "System.Runtime.InteropServices.InAttribute", System_Runtime_InteropServices }, { "System.Runtime.InteropServices.ComTypes.ITypeLib", System_Runtime_InteropServices }, { "System.Runtime.InteropServices.TypeIdentifierAttribute", System_Runtime_InteropServices }, }; static int Main(string[] args) { if (args.Length != 2) { Console.WriteLine("ERROR: unexpected syntax to MakePIAPortable.exe. Expected: MakePIAPortable.exe <input-il-file> <output-il-file>"); return -1; } string inputFile = args[0]; string outputFile = args[1]; if (!File.Exists(inputFile)) { Console.WriteLine("ERROR: Input file '{0}' does not exist.", inputFile); return -1; } try { return TransformIL(inputFile, outputFile); } catch (Exception e) { Console.WriteLine("ERROR: {0} while processing input file '{1}'. {2}", e.GetType(), inputFile, e.Message); return -1; } } private static int TransformIL(string inputFilePath, string outputFile) { bool isInterface = false; Regex mscorlibType = new Regex(@"\[mscorlib\][A-Za-z][A-Za-z\.]+"); Regex paramCustomAttributeRegex = new Regex(@"^ *.param \[[0-9]+\]$"); HashSet<string> emittedUnknownTypes = new HashSet<string>(); using (InputFile inputFile = new InputFile(inputFilePath)) using (StreamWriter output = new StreamWriter(File.OpenWrite(outputFile))) { while (true) { string inputLine = inputFile.ReadLine(); if (inputLine == null) break; if (isInterface) { if (inputLine.Contains(" internalcall")) { inputLine = inputLine.Replace(" internalcall", ""); } if (inputLine.Contains(" runtime ")) { inputLine = inputLine.Replace(" runtime ", " "); } } if (inputLine == ".assembly extern mscorlib") { if (!IsAssemblyReferenceBody(inputFile)) { Error.Emit(Error.Code.BadMscorlibReference, inputFile, "Unexpected text near '.assembly extern mscorlib'. Unable to transform."); return -1; } foreach (var assembly in s_contractAssemblies) { output.Write(".assembly extern "); output.WriteLine(assembly.Item1); output.WriteLine("{"); output.WriteLine(" .publickeytoken = (<KEY> )"); output.Write(" .ver "); output.WriteLine(assembly.Item2); output.WriteLine("}"); } continue; } else if (inputLine == ".assembly extern stdole") { if (!IsAssemblyReferenceBody(inputFile)) { Error.Emit(Error.Code.BadStdoleReference, inputFile, "Unexpected text near '.assembly extern stdole'. Unable to transform."); return -1; } // Drop the stdole reference on the floor. It wasn't actually used. continue; } else if (inputLine.StartsWith(" .publickey = (00 24 00 00 04 80 00 00 94 00 00 00 06 02 00 00", StringComparison.Ordinal)) { output.WriteLine(" .custom instance void [System.Runtime]System.Reflection.AssemblyDelaySignAttribute::.ctor(bool)"); output.WriteLine(" = { bool(true)}"); output.WriteLine(" .custom instance void [System.Runtime]System.Reflection.AssemblySignatureKeyAttribute::.ctor(string, string)"); output.WriteLine(" = {string('002400000c800000140100000602000000240000525341310008000001000100613399aff18ef1a2c2514a273a42d9042b72321f1757102df9ebada69923e2738406c21e5b801552ab8d200a65a235e001ac9adc25f2d811eb09496a4c6a59d4619589c69f5baf0c4179a47311d92555cd006acc8b5959f2bd6e10e360c34537a1d266da8085856583c85d81da7f3ec01ed9564c58d93d713cd0172c8e23a10f0239b80c96b07736f5d8b022542a4e74251a5f432824318b3539a5a087f8e53d2f135f9ca47f3bb2e10aff0af0849504fb7cea3ff192dc8de0edad64c68efde34c56d302ad55fd6e80f302d5efcdeae953658d3452561b5f36c542efdbdd9f888538d374cef106acf7d93a4445c3c73cd911f0571aaf3d54da12b11ddec375b3')"); output.WriteLine(" string('a5a866e1ee186f807668209f3b11236ace5e21f117803a3143abb126dd035d7d2f876b6938aaf2ee3414d5420d753621400db44a49c486ce134300a2106adb6bdb433590fef8ad5c43cba82290dc49530effd86523d9483c00f458af46890036b0e2c61d077d7fbac467a506eba29e467a87198b053c749aa2a4d2840c784e6d')}"); // fall through to outputting the input line } else if (inputLine.Contains("[mscorlib]")) { if (IsIgnoredCustomAttributeLine(inputLine)) { SkipCustomAttribute(inputLine, inputFile); continue; } StringBuilder lineBuilder = new StringBuilder(); Match match = mscorlibType.Match(inputLine); int nextStartPos = 0; while (match.Success) { lineBuilder.Append(inputLine, nextStartPos, match.Index - nextStartPos); nextStartPos = match.Index + match.Length; string typeName = match.Value.Substring("[mscorlib]".Length); string assemblyName; if (!s_typeToContractAssemblyMap.TryGetValue(typeName, out assemblyName)) { if (!emittedUnknownTypes.Contains(typeName)) { emittedUnknownTypes.Add(typeName); Error.Emit(Error.Code.UnknownType, inputFile, "Unknown type '{0}'. Unable to map to contract assembly.", typeName); } assemblyName = "unknown_assembly"; } lineBuilder.Append('['); lineBuilder.Append(assemblyName); lineBuilder.Append(']'); lineBuilder.Append(typeName); match = match.NextMatch(); } lineBuilder.Append(inputLine, nextStartPos, inputLine.Length - nextStartPos); output.WriteLine(lineBuilder); continue; } else if (paramCustomAttributeRegex.IsMatch(inputLine)) { string customAttributeLine = inputFile.TestNextLine(IsIgnoredCustomAttributeLine); if (customAttributeLine != null) { SkipCustomAttribute(customAttributeLine, inputFile); inputFile.SkipBlankLines(); // The '.param' directive contains an integer with the custom attribute index. We currently don't have code to rewrite that index, so // error out if we detect we need such code. If we need to implement this in the future, we could do so by getting a bunch of lines, rewriting them // and then unreading them (InputFile.UnreadLine) string[] problemLines = inputFile.TestNextLines( l1 => paramCustomAttributeRegex.IsMatch(l1), l2 => !IsIgnoredCustomAttributeLine(l2)); if (problemLines != null) { Error.Emit(Error.Code.UnsupportedCustomAttribute, inputFile, "Non-ignored custom attribute found after ignored custom attribute. This is not currently supported by this script."); } continue; } } else if (inputLine.StartsWith("// Metadata version: v", StringComparison.Ordinal)) { // This line doesn't hurt, but it is slightly confusing since this isn't the metadata version we will use, so strip it. continue; } // Remove 'import' from the interfaces else if (inputLine.StartsWith(".class ", StringComparison.Ordinal)) { // Remove '_EventProvider' classes from MS.VS.Interop since they // use ArrayList which is not in netstandard 1.3 if (inputLine.Contains("_EventProvider")) { inputLine = ""; SkipClass(inputFile); } else { isInterface = inputLine.Contains(" interface"); if (inputLine.Contains(" import ")) { inputLine = inputLine.Replace(" import ", " "); } } } output.WriteLine(inputLine); } } return Error.HasError ? 1 : 0; } private static bool IsAssemblyReferenceBody(InputFile inputFile) { return inputFile.TestNextLines( (x) => x == "{", (x) => true, (x) => true, (x) => x == "}" ) != null; } private static bool IsIgnoredCustomAttributeLine(string line) { return line.Contains(".custom instance void [mscorlib]System.Runtime.InteropServices.ComAliasNameAttribute::.ctor(") || line.Contains(".custom instance void [mscorlib]System.Runtime.InteropServices.ComConversionLossAttribute::.ctor()") || line.Contains(".custom instance void [mscorlib]System.Runtime.InteropServices.TypeLibTypeAttribute::.ctor(") || line.Contains(".custom instance void [mscorlib]System.Runtime.CompilerServices.IsReadOnlyAttribute::.ctor(") || line.Contains(".custom instance void System.Runtime.CompilerServices.IsReadOnlyAttribute::.ctor()") || line.Contains(".custom instance void [mscorlib]System.Runtime.InteropServices.TypeLibFuncAttribute::.ctor(") || line.Contains(".custom instance void [mscorlib]System.Runtime.InteropServices.TypeLibFuncAttribute::.ctor(") || line.Contains(".custom instance void [mscorlib]System.Resources.SatelliteContractVersionAttribute::.ctor(") || line.Contains(".custom instance void [mscorlib]System.Runtime.CompilerServices.DateTimeConstantAttribute::.ctor("); } private static void SkipClass(InputFile inputFile) { int startLineNumber = inputFile.LineNumber; // Find first open brace for class. while (true) { string nextLine = inputFile.ReadLine(); if (nextLine == null) { Error.Emit(Error.Code.BadCustomAttribute, inputFile, "Unexpected end-of-file while looking for start of class brace starting on line {0}", startLineNumber); return; } if (nextLine.IndexOf('{') >= 0) break; } int braceCount = 1; // Look for end class brace. while (true) { string nextLine = inputFile.ReadLine(); if (nextLine == null) { Error.Emit(Error.Code.BadCustomAttribute, inputFile, "Unexpected end-of-file while looking for end of class starting on line {0}", startLineNumber); return; } // Count for '{' within inner methods. if (nextLine.IndexOf('{') >= 0) braceCount++; // Decrease count for '{' seen. if (nextLine.IndexOf('}') >= 0) braceCount--; // If we met the name number of '}' as '{', we finished reading the class lines. if (braceCount == 0) break; } } private static void SkipCustomAttribute(string firstLine, InputFile inputFile) { // Handle cases where the custom attribute ends on the same line, but with trailing comments. // E.g. // .custom instance void [mscorlib]System.Runtime.InteropServices.ComAliasNameAttribute::.ctor(string) = ( 01 00 08 4F 4C 45 2E 42 4F 4F 4C 00 00 ) // ...OLE.BOOL.. int startOfCommentIndex = firstLine.IndexOf("//", StringComparison.Ordinal); if (startOfCommentIndex != -1) { firstLine = firstLine.Substring(0, startOfCommentIndex); } // This is a single line attribute, no need to search for the end of it. if (firstLine.TrimEnd(' ', '\t').EndsWith(")", StringComparison.Ordinal)) return; int startLineNumber = inputFile.LineNumber; while (true) { string nextLine = inputFile.ReadLine(); if (nextLine == null) { Error.Emit(Error.Code.BadCustomAttribute, inputFile, "Unexpected end-of-file while looking for end of custom attribute starting on line {0}", startLineNumber); return; } if (nextLine.IndexOf(')') >= 0) break; } } } static class Error { static public bool HasError { get; private set; } public enum Code { BadMscorlibReference = 1, UnknownType = 2, BadCustomAttribute = 3, UnsupportedCustomAttribute = 4, BadStdoleReference = 5 } public static void Emit(Code code, InputFile inputFile, string message) { HasError = true; Console.WriteLine("{0}({1}) : error MIP{2:000} : {3}", inputFile.FilePath, inputFile.LineNumber, (int)code, message); } public static void Emit(Code code, InputFile inputFile, string formatString, params object[] args) { Emit(code, inputFile, string.Format(CultureInfo.InvariantCulture, formatString, args)); } } class InputFile : IDisposable { public readonly string FilePath; public int LineNumber { get; private set; } StreamReader _input; readonly LinkedList<string> _peekedLines = new LinkedList<string>(); public InputFile(string filePath) { this.FilePath = filePath; _input = File.OpenText(filePath); } public string ReadLine() { this.LineNumber++; #if DEBUG if (this.LineNumber == Program.BreakLine) { Debugger.Break(); } #endif return InternalGetLine(); } /// <summary> /// Return a line the the input file. This is pushed as a stack. /// </summary> /// <param name="lineToReturn">Line to push</param> public void UnreadLine(string lineToReturn) { this.LineNumber--; InternalUngetLine(lineToReturn); } /// <summary> /// Test if the next line matches a predicate. If so, the line is returned and the current line number is increased. /// </summary> /// <param name="isMatch">Function to test if the next line matches. Returns true if it is a match</param> /// <returns>null if the next line is the end of file, or the line didn't match, otherwise the line</returns> public string TestNextLine(Func<string, bool> isMatch) { string nextLine = InternalGetLine(); if (nextLine == null) { return null; } if (isMatch(nextLine)) { LineNumber++; return nextLine; } else { InternalUngetLine(nextLine); return null; } } /// <summary> /// Test if the next lines matches a predicate. If so, the lines are returned and the current line number is increased. /// </summary> /// <param name="isMatchArray">Array of functions used to test if the next lines match. Each function returns true if that line matches.</param> /// <returns>null if the end of file is reached, or the lines didn't match, otherwise the array of lines</returns> public string[] TestNextLines(params Func<string, bool>[] isMatchArray) { string[] nextLines = new string[isMatchArray.Length]; for (int c = 0; c < isMatchArray.Length; c++) { string nextLine = InternalGetLine(); nextLines[c] = nextLine; if (nextLine == null || !isMatchArray[c](nextLine)) { // Put back the lines that we obtained for (int j = c; j >= 0; j--) { InternalUngetLine(nextLines[j]); } return null; } } LineNumber += nextLines.Length; return nextLines; } private string InternalGetLine() { if (_peekedLines.Count != 0) { string lineToReturn = _peekedLines.First.Value; _peekedLines.RemoveFirst(); return lineToReturn; } return _input.ReadLine(); } private void InternalUngetLine(string lineToReturn) { if (lineToReturn != null) { _peekedLines.AddFirst(lineToReturn); } } public void Dispose() { _input.Close(); } public void SkipBlankLines() { while (TestNextLine(x => string.IsNullOrWhiteSpace(x)) != null) { } } } } <|start_filename|>src/SSHDebugPS/Utilities/VSMessageBoxHelper.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using ThreadingTasks = System.Threading.Tasks; namespace Microsoft.SSHDebugPS.Utilities { internal class VSMessageBoxHelper { /// <summary> /// Switches to main thread and shows a VS message box. /// </summary> public static void PostUIMessage(string title, string message, OLEMSGICON icon, OLEMSGBUTTON button, OLEMSGDEFBUTTON defaultButton) { _ = ThreadingTasks.Task.Run(async () => await PostMessageInternalAsync(title, message, icon, button, defaultButton)); } public static void PostErrorMessage(string title, string message) { PostUIMessage( title, message, OLEMSGICON.OLEMSGICON_CRITICAL, OLEMSGBUTTON.OLEMSGBUTTON_OK, OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST); } private static async ThreadingTasks.Task PostMessageInternalAsync(string title, string message, OLEMSGICON icon, OLEMSGBUTTON button, OLEMSGDEFBUTTON defaultButton) { await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); VsShellUtilities.ShowMessageBox(ServiceProvider.GlobalProvider, message, title, icon, button, defaultButton); } } } <|start_filename|>src/MICore/ExceptionHelper.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.DebugEngineHost; using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MICore { public static class ExceptionHelper { /// <summary> /// Exception filter function used to report exceptions to telemetry. This **ALWAYS** returns 'true'. /// </summary> /// <param name="currentException">The current exception which is about to be caught.</param> /// <param name="logger">For logging messages</param> /// <param name="reportOnlyCorrupting">If true, only corrupting exceptions are reported</param> /// <returns>true</returns> public static bool BeforeCatch(Exception currentException, Logger logger, bool reportOnlyCorrupting) { if (reportOnlyCorrupting && !IsCorruptingException(currentException)) { return true; // ignore non-corrupting exceptions } try { HostTelemetry.ReportCurrentException(currentException, "Microsoft.MIDebugEngine"); logger?.WriteLine("EXCEPTION: " + currentException.GetType()); logger?.WriteTextBlock("EXCEPTION: ", currentException.StackTrace); } catch { // If anything goes wrong, ignore it. We want to report the original exception, not a telemetry problem } return true; } public static bool IsCorruptingException(Exception exception) { if (exception is NullReferenceException) return true; if (exception is ArgumentNullException) return true; if (exception is ArithmeticException) return true; if (exception is ArrayTypeMismatchException) return true; if (exception is DivideByZeroException) return true; if (exception is IndexOutOfRangeException) return true; if (exception is InvalidCastException) return true; if (exception is System.Runtime.InteropServices.SEHException) return true; return false; } } } <|start_filename|>src/SSHDebugPS/WSL/WSLConnection.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.VisualStudio.Debugger.Interop.UnixPortSupplier; using System.Collections.Generic; using System; using System.Text; using System.Threading; using SysProcess = System.Diagnostics.Process; using System.Threading.Tasks; namespace Microsoft.SSHDebugPS.WSL { internal class WSLConnection : PipeConnection { public WSLConnection(string distribution) : base(outerConnection:null, name: distribution) { } /// <inheritdoc/> public override int ExecuteCommand(string commandText, int timeout, out string commandOutput, out string errorMessage) { using (var cancellationTokenSource = new CancellationTokenSource()) { Task<ProcessResult> task = LocalProcessAsyncRunner.ExecuteProcessAsync(WSLCommandLine.GetExecStartInfo(this.Name, commandText), cancellationTokenSource.Token); #pragma warning disable VSTHRD002 // Avoid problematic synchronous waits if (!task.Wait(timeout)) { cancellationTokenSource.Cancel(); throw new TimeoutException(); } ProcessResult result = task.Result; #pragma warning restore VSTHRD002 // Avoid problematic synchronous waits commandOutput = string.Join("\n", result.StdOut); errorMessage = string.Join("\n", result.StdErr); return result.ExitCode; } } /// <inheritdoc/> public override void BeginExecuteAsyncCommand(string commandText, bool runInShell, IDebugUnixShellCommandCallback callback, out IDebugUnixShellAsyncCommand asyncCommand) { if (IsClosed) { throw new ObjectDisposedException(nameof(WSLConnection)); } string args = WSLCommandLine.GetExecCommandLineArgs(this.Name, commandText); ICommandRunner commandRunner = LocalCommandRunner.CreateInstance(handleRawOutput: runInShell == false, WSLCommandLine.ExePath, args); asyncCommand = new PipeAsyncCommand(commandRunner, callback); } /// <inheritdoc/> public override void CopyFile(string sourcePath, string destinationPath) { bool IsFullyQualifiedWindowsLocalPath(string path) { if (path == null) return false; if (path.Length < 3) return false; char driveLetter = sourcePath[0]; bool isDriveLetter = (driveLetter >= 'a' && driveLetter <= 'z') || (driveLetter >= 'A' && driveLetter <= 'Z'); if (!isDriveLetter) { return false; } if (sourcePath[1] != ':') { return false; } char slash = sourcePath[2]; if (slash != '\\' && slash != '/') { return false; } return true; } if (!IsFullyQualifiedWindowsLocalPath(sourcePath)) { throw new ArgumentOutOfRangeException(nameof(sourcePath)); } StringBuilder commandBuilder = new StringBuilder(); commandBuilder.Append("cp /mnt/"); commandBuilder.Append(char.ToLowerInvariant(sourcePath[0])); // Append all the other characters of the path with special handling for backslash and space for (int c = 2; c < sourcePath.Length; c++) { char ch = sourcePath[c]; switch (ch) { case '\\': commandBuilder.Append('/'); break; case ' ': commandBuilder.Append(@"\ "); break; default: commandBuilder.Append(ch); break; } } commandBuilder.Append(' '); commandBuilder.Append(destinationPath); this.ExecuteCommand(commandBuilder.ToString(), Timeout.Infinite); } /// <inheritdoc/> public override bool IsLinux() { return true; } /// <inheritdoc/> public override bool IsOSX() { return false; } } } <|start_filename|>test/CppTests/debuggees/sourcemap/src/manager/manager.h<|end_filename|> #include <vector> class Manager { public: Manager(); void AddInt(int value); int RemoveInt(); int Size(); int Sum(); private: std::vector<int> items; }; <|start_filename|>src/SSHDebugPS/AD7/AD7Program.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.VisualStudio.Debugger.Interop; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Microsoft.SSHDebugPS { [DebuggerDisplay("Program for process:{_process._processId}")] internal class AD7Program : IDebugProgram2 { private readonly AD7Process _process; private readonly Guid _engineId; private readonly Lazy<Guid> _uniqueId = new Lazy<Guid>(() => Guid.NewGuid(), LazyThreadSafetyMode.ExecutionAndPublication); internal AD7Program(AD7Process process, Guid engineId) { _process = process; _engineId = engineId; } int IDebugProgram2.Attach(IDebugEventCallback2 pCallback) { return HR.S_FALSE; // indicate that the attach happens through the engine rather than the port supplier } int IDebugProgram2.CanDetach() { throw new NotImplementedException(); } int IDebugProgram2.CauseBreak() { throw new NotImplementedException(); } int IDebugProgram2.Continue(IDebugThread2 pThread) { throw new NotImplementedException(); } int IDebugProgram2.Detach() { throw new NotImplementedException(); } int IDebugProgram2.EnumCodeContexts(IDebugDocumentPosition2 pDocPos, out IEnumDebugCodeContexts2 ppEnum) { throw new NotImplementedException(); } int IDebugProgram2.EnumCodePaths(string pszHint, IDebugCodeContext2 pStart, IDebugStackFrame2 pFrame, int fSource, out IEnumCodePaths2 ppEnum, out IDebugCodeContext2 ppSafety) { throw new NotImplementedException(); } int IDebugProgram2.EnumModules(out IEnumDebugModules2 ppEnum) { throw new NotImplementedException(); } int IDebugProgram2.EnumThreads(out IEnumDebugThreads2 ppEnum) { throw new NotImplementedException(); } int IDebugProgram2.Execute() { throw new NotImplementedException(); } int IDebugProgram2.GetDebugProperty(out IDebugProperty2 ppProperty) { throw new NotImplementedException(); } int IDebugProgram2.GetDisassemblyStream(enum_DISASSEMBLY_STREAM_SCOPE dwScope, IDebugCodeContext2 pCodeContext, out IDebugDisassemblyStream2 ppDisassemblyStream) { throw new NotImplementedException(); } int IDebugProgram2.GetENCUpdate(out object ppUpdate) { throw new NotImplementedException(); } int IDebugProgram2.GetEngineInfo(out string engineName, out Guid guidEngine) { // TODO: Do we need a real engine name? engineName = "<PS-Engine>"; guidEngine = _engineId; return HR.S_OK; } int IDebugProgram2.GetMemoryBytes(out IDebugMemoryBytes2 ppMemoryBytes) { throw new NotImplementedException(); } int IDebugProgram2.GetName(out string pbstrName) { throw new NotImplementedException(); } int IDebugProgram2.GetProcess(out IDebugProcess2 process) { process = _process; return HR.S_OK; } int IDebugProgram2.GetProgramId(out Guid guidProgramId) { guidProgramId = _uniqueId.Value; return HR.S_OK; } int IDebugProgram2.Step(IDebugThread2 pThread, enum_STEPKIND sk, enum_STEPUNIT Step) { throw new NotImplementedException(); } int IDebugProgram2.Terminate() { throw new NotImplementedException(); } int IDebugProgram2.WriteDump(enum_DUMPTYPE DUMPTYPE, string pszDumpUrl) { throw new NotImplementedException(); } } } <|start_filename|>eng/Scripts/CI-Build.cmd<|end_filename|> @echo off setlocal if "%~1"=="/?" goto Help if "%~1"=="-?" goto Help if "%~1"=="-h" goto Help @SET Args= %* @SET Args=%Args: /= -% powershell -NoProfile -ExecutionPolicy bypass -File %~dp0CI-Build.ps1 %Args% @exit /B %ERRORLEVEL% goto :EOF :Help call powershell -NoProfile -ExecutionPolicy ByPass -Command "get-help %~dp0CI-Build.ps1 -detailed" <|start_filename|>test/RegisterMIEngine.cmd<|end_filename|> @echo off setlocal set _GlassDir=%~dp0..\Microsoft.VisualStudio.Glass\ REM Determine the registry root first, as it is used in the help output if not exist "%_GlassDir%glass2.exe.regroot" echo ERROR: %_GlassDir%glass2.exe.regroot not found.&exit /b -1 set RegistryRoot= for /f "delims=" %%l in (%_GlassDir%glass2.exe.regroot) do call :ProcessRegRootLine %%l if "%RegistryRoot%"=="" echo ERROR: Incorrect format in %_GlassDir%glass2.exe.regroot&exit /b -1 if "%RegistryRoot%"=="ERROR" echo ERROR: Incorrect format in %_GlassDir%glass2.exe.regroot&exit /b -1 if "%~1"=="-?" goto help if "%~1"=="/?" goto help if NOT "%~1"=="" goto help if /i "%PROCESSOR_ARCHITECTURE%"=="amd64" call %SystemRoot%\SysWow64\cmd.exe /C "%~dpf0" %* & goto eof if /i NOT "%PROCESSOR_ARCHITECTURE%"=="x86" echo ERROR: Unsupported processor - script should only be run on an x86 or x64 OS & exit /b -1 set ERROR= if exist %tmp%\MIEngine.reg del %tmp%\MIEngine.reg call %_GlassDir%GlassRegGen.exe %~dp0MIEngine.regdef %RegistryRoot% %tmp%\MIEngine.reg if NOT "%ERRORLEVEL%"=="0" set ERROR=1& goto Done call reg.exe import %tmp%\MIEngine.reg if NOT "%ERRORLEVEL%"=="0" set ERROR=1 :Done if "%Error%"=="" echo RegisterMIEngine.cmd completed successfully.&echo.& goto eof echo RegisterMIEngine.cmd FAILED.&echo.&exit /b -1 goto eof :ProcessRegRootLine set line=%1 if "%line%"=="" goto eof if "%line:~0,1%"=="#" goto eof if NOT "%RegistryRoot%"=="" set RegistryRoot=ERROR& goto eof set RegistryRoot=%line% goto eof :Help echo RegisterMIEngine.cmd echo. echo This script is used to register glass2.exe for use with the Concord debug echo engine. It must be run on a computer with Visual Studio 11.0 is already echo installed. echo. echo Registry keys are written under HKLM\%RegistryRoot%. Delete echo this key to uninstall. echo. echo This script must be run as an administrator. echo. :eof <|start_filename|>src/MICore/DebuggerDisposedException.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; namespace MICore { /// <summary> /// Exception thrown to specify the debugger is disposed. /// </summary> public class DebuggerDisposedException : ObjectDisposedException { /// <summary> /// Command where the abort happened. /// </summary> public string AbortedCommand { get; private set; } /// <summary> /// Constructor for the DebuggerDisposedException which takes message, innerException and aborted command. /// </summary> public DebuggerDisposedException(string message, Exception innerException, string abortedCommand = null) : base(message, innerException) { AbortedCommand = abortedCommand; } /// <summary> /// Constructor for the DebuggerDisposedException which takes message and aborted command. /// </summary> public DebuggerDisposedException(string message, string abortedCommand = null) : this(message, null, abortedCommand) { } } } <|start_filename|>test/CppTests/debuggees/kitchensink/src/expression.cpp<|end_filename|> #include <string> #include <vector> #include "expression.h" using namespace std; int accumulate(int x) { if (x <= 1) return 1; return x + accumulate(x - 1); } extern "C" void func() { bool isCalled = true; double d = 10.10; accumulate(3); } void Expression::checkPrimitiveTypes() { bool mybool = true; char mychar = 'A'; int myint = 100; float myfloat = 299.0f; double mydouble = 321.00; wchar_t mywchar = 'z'; this->checkArrayAndPointers(); } void Expression::checkArrayAndPointers() { int arr[] = { 0,1,2,3,4 }; int *pArr = arr; this->checkClassOnStackAndHeap(); } void Expression::checkClassOnStackAndHeap() { Test::Student student; student.name = "John"; student.age = 10; Test::Student* pStu = new Test::Student(); pStu->name = "Bob"; pStu->age = 9; delete pStu; pStu = nullptr; this->checkSpecialValues(); } void Expression::checkSpecialValues() { char mynull = '\0'; double mydouble = 1.0, zero = 0.0; mydouble /= zero; this->checkPrettyPrinting(); } void Expression::checkPrettyPrinting() { string str = "hello, world"; vector<int> vec; for (int i = 0; i < 5; i++) { vec.push_back(i); } this->checkCallStack(&func); } void Expression::checkCallStack(void(*callback)()) { float _f = 1.0f; callback(); } void Expression::CoreRun() { this->checkPrimitiveTypes(); } Expression::Expression() : Feature("Expression") { } int Test::max(int x, int y) { if ((x - y) >= 0) return x; else return y; } double Test::max(double x, double y) { if ((x - y) >= 0) return x; else return y; } <|start_filename|>src/SSHDebugPS/MIEngineLauncher.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Diagnostics; using System.Runtime.InteropServices; using MICore; using MICore.Xml.LaunchOptions; using Microsoft.DebugEngineHost; using Microsoft.SSHDebugPS.SSH; namespace Microsoft.SSHDebugPS { /// <summary> /// Implementation of the MIEngine's IPlatformAppLauncher interface used to connect the SSH port supplier to the MIEngine /// for launch scenarios. /// /// Note that in these scenarios the SSH port supplier doesn't actually operate as a true port supplier -- we are still /// using the default port supplier as far as AD7 is concerned, and the SSH port supplier is just acting as a transport. /// </summary> [ComVisible(true)] [Guid("7E3052B2-FB42-4E38-B22C-1FD281BD4413")] sealed public class MIEngineLauncher : IPlatformAppLauncher { private SSHLaunchOptions _launchOptions; void IDisposable.Dispose() { } void IPlatformAppLauncher.Initialize(HostConfigurationStore configStore, IDeviceAppLauncherEventCallback eventCallback) { } void IPlatformAppLauncher.OnResume() { } void IPlatformAppLauncher.SetLaunchOptions(string exePath, string args, string dir, object launcherXmlOptions, TargetEngine targetEngine) { // NOTE: exePath/args/dir can all be ignored, as LaunchOptions.GetInstance will use those values if they aren't specified in the XML. _launchOptions = (SSHLaunchOptions)launcherXmlOptions; } void IPlatformAppLauncher.SetupForDebugging(out LaunchOptions debuggerLaunchOptions) { if (_launchOptions == null) { Debug.Fail("Why is SetupForDebugging being called before ParseLaunchOptions?"); throw new InvalidOperationException(); } string targetMachineName = LaunchOptions.RequireAttribute(_launchOptions.TargetMachine, "TargetMachine"); var port = new SSHPort(new SSHPortSupplier(), targetMachineName, isInAddPort: false); // NOTE: this may put up a dialog and/or throw an AD7ConnectCanceledException port.EnsureConnected(); debuggerLaunchOptions = new UnixShellPortLaunchOptions(_launchOptions.StartRemoteDebuggerCommand, port, LaunchOptions.ConvertMIModeAttribute(_launchOptions.MIMode), _launchOptions); } void IPlatformAppLauncher.Terminate() { } } } <|start_filename|>src/SSHDebugPS/UI/ContainerInstance.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using System.Threading.Tasks; namespace Microsoft.SSHDebugPS.Docker { public interface IContainerInstance : IEquatable<IContainerInstance> { string Id { get; } string Name { get; } } public abstract class ContainerInstance : IContainerInstance { public abstract string Id { get; set; } public abstract string Name { get; set; } #region IEquatable public static bool operator ==(ContainerInstance left, ContainerInstance right) { if (left is null || right is null) { return ReferenceEquals(left, right); } return left.Equals(right); } public static bool operator !=(ContainerInstance left, ContainerInstance right) { return !(left == right); } public bool Equals(IContainerInstance instance) { if (!ReferenceEquals(null, instance) && instance is ContainerInstance container) { return this.EqualsInternal(container); } return false; } public override bool Equals(object obj) { if (obj is IContainerInstance instance) { return this.Equals(instance); } return false; } public override int GetHashCode() { return GetHashCodeInternal(); } #endregion #region Helper Methods protected abstract bool EqualsInternal(ContainerInstance instance); protected abstract int GetHashCodeInternal(); #endregion } } <|start_filename|>test/DebuggerTesting/Compilation/GppStyleCompiler.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using DebuggerTesting.Utilities; namespace DebuggerTesting.Compilation { internal abstract class GppStyleCompiler : CompilerBase { #region Constructor public GppStyleCompiler(ILoggingComponent logger, ICompilerSettings settings) : base(logger, settings, PlatformUtilities.IsWindows) { } #endregion #region Methods protected override bool CompileCore( CompilerOutputType outputType, SupportedArchitecture architecture, IEnumerable<string> libraries, IEnumerable<string> sourceFilePaths, string targetFilePath, CompilerOption options, IDictionary<string, string> defineConstants) { ArgumentBuilder builder = new ArgumentBuilder("-", String.Empty); if (options.HasFlag(CompilerOption.GenerateSymbols)) { builder.AppendNamedArgument("g", null); } if (options.HasFlag(CompilerOption.OptimizeLevel1)) { builder.AppendNamedArgument("O1", null); } else if (options.HasFlag(CompilerOption.OptimizeLevel2)) { builder.AppendNamedArgument("O2", null); } else if (options.HasFlag(CompilerOption.OptimizeLevel3)) { builder.AppendNamedArgument("O3", null); } else { builder.AppendNamedArgument("O0", null); } // Enable pthreads if (options.HasFlag(CompilerOption.SupportThreading)) { builder.AppendNamedArgument("pthread", null); } // Just use C++ 11 builder.AppendNamedArgument("std", "c++11", "="); switch (outputType) { case CompilerOutputType.SharedLibrary: builder.AppendNamedArgument("shared", null); builder.AppendNamedArgument("fpic", null); break; case CompilerOutputType.ObjectFile: builder.AppendNamedArgument("c", null); builder.AppendNamedArgument("fpic", null); break; case CompilerOutputType.Unspecified: // Treat Unspecified as Executable, since executable is the default case CompilerOutputType.Executable: // Compiling an executable does not have a command line option, it's the default break; default: throw new ArgumentOutOfRangeException(nameof(outputType), "Unhandled output type: " + outputType); } switch (architecture) { case SupportedArchitecture.x64: builder.AppendNamedArgument("m", "64"); DefineConstant(builder, "DEBUGGEE_ARCH", "64"); break; case SupportedArchitecture.x86: builder.AppendNamedArgument("m", "32"); DefineConstant(builder, "DEBUGGEE_ARCH", "32"); break; case SupportedArchitecture.arm: builder.AppendNamedArgument("m", "arm"); DefineConstant(builder, "DEBUGGEE_ARCH", "ARM"); break; default: throw new ArgumentOutOfRangeException(nameof(architecture), "Unhandled target architecture: " + architecture); } // Define a constant for the platform name. DefineConstant(builder, "DEBUGGEE_PLATFORM", GetPlatformName()); this.SetAdditionalArguments(builder); builder.AppendNamedArgument("o", targetFilePath); foreach (string sourceFilePath in sourceFilePaths) { builder.AppendArgument(sourceFilePath); } foreach (string library in libraries) { builder.AppendNamedArgument("l", library); } foreach (var defineConstant in defineConstants) { DefineConstant(builder, defineConstant.Key, defineConstant.Value); } return 0 == this.RunCompiler(builder.ToString(), targetFilePath); } protected static void DefineConstant(ArgumentBuilder builder, string name, string value = null) { string constant = name; if (value != null) constant += "=" + ArgumentBuilder.MakeQuotedIfRequired(value); builder.AppendNamedArgument("D", constant); } /// <summary> /// Add any compiler specific aguments to the command line /// </summary> protected virtual void SetAdditionalArguments(ArgumentBuilder builder) { } #endregion } } <|start_filename|>src/JDbg/JDbg.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace JDbg { /// <summary> /// JDbg exposes debugging commands that can be used against a JVM at a higher level than JDWP. /// </summary> public class JDbg { private string _hostname; private int _port; private JdwpCommand.IDSizes _idSizes; private VersionCommand.Reply _version; private List<AllClassesWithGenericCommand.ClassData> _classes; private Jdwp _jdwp; private JDbg(string hostname, int port) { _hostname = hostname; _port = port; } /// <summary> /// Attach an instance of JDbg to a VM listening on hostname:port /// </summary> /// <param name="hostname"></param> /// <param name="port"></param> /// <returns></returns> public static JDbg Attach(string hostname, int port) { JDbg jdbg = new JDbg(hostname, port); jdbg._jdwp = Jdwp.Attach(hostname, port); return jdbg; } /// <summary> /// Attach an instance of JDbg to a VM listening on localhost:port /// </summary> /// <param name="port"></param> /// <returns></returns> public static JDbg Attach(int port) { return Attach("localhost", port); } /// <summary> /// Runs multiple commands to initialize java debugging /// </summary> /// <returns></returns> public async Task Inititalize() { _idSizes = await IDSizes(); _jdwp.SetIDSizes(_idSizes); _version = await Version(); _classes = await AllClassesWithGeneric(); } /// <summary> /// Get the sizes of various field from the JVM /// </summary> /// <returns></returns> private async Task<JdwpCommand.IDSizes> IDSizes() { IDSizesCommand command = new IDSizesCommand(); await _jdwp.SendCommandAsync(command); var reply = command.GetReply(); return reply; } /// <summary> /// Get the version string of the VM /// </summary> /// <returns></returns> private async Task<VersionCommand.Reply> Version() { VersionCommand command = new VersionCommand(); await _jdwp.SendCommandAsync(command); var reply = command.GetReply(); return reply; } /// <summary> /// Get the names of All classes in the JVM with Generics /// </summary> /// <returns></returns> private async Task<List<AllClassesWithGenericCommand.ClassData>> AllClassesWithGeneric() { AllClassesWithGenericCommand command = new AllClassesWithGenericCommand(); await _jdwp.SendCommandAsync(command); return command.GetClassData(); } /// <summary> /// Sends the dispose command to the VM, which is equivalent to detach. /// </summary> /// <returns></returns> private async Task Detach() { DisposeCommand command = new DisposeCommand(); await _jdwp.SendCommandAsync(command); } public void Close() { ThreadPool.QueueUserWorkItem(async (state) => { if (_jdwp != null) { try { await Detach(); } catch (Exception) { //If we hit exceptions here, catch and do nothing since we're already tearing down and there's nothing we can do anyways. } _jdwp.Close(); } }); } } } <|start_filename|>test/CppTests/debuggees/kitchensink/src/calling.h<|end_filename|> #pragma once #include "global.h" #include <iostream> #include <vector> #include <string> #include <stdarg.h> #include "feature.h" using namespace std; class Calling : public Feature { public: Calling(); virtual void CoreRun(); }; <|start_filename|>src/AndroidDebugLauncher/RunAsOutputParser.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Globalization; using System.Linq; namespace AndroidDebugLauncher { internal static class RunAsOutputParser { /// <summary> /// Handle run-as errors. We will get into this code path if the supplied package name is wrong. /// </summary> /// <param name="commandOutput">Output of the run-as command executed through adb shell. /// Example "run-as: Package 'com.bogus.hellojni' is unknown"</param> /// <param name="packageName">Package name used as the first argument to run-as</param> public static void ThrowIfRunAsErrors(string commandOutput, string packageName) { IEnumerable<string> allLines = commandOutput.GetLines(); string runAsLine = allLines.FirstOrDefault(line => line.StartsWith("run-as:", StringComparison.Ordinal)); if (runAsLine != null) { string errorMessage = runAsLine.Substring("run-as:".Length).Trim(); if (errorMessage.Length > 0) { if (!char.IsPunctuation(errorMessage[errorMessage.Length - 1])) { errorMessage = string.Concat(errorMessage, "."); } Telemetry.LaunchFailureCode telemetryCode = Telemetry.LaunchFailureCode.RunAsFailure; if (errorMessage == string.Format(CultureInfo.InvariantCulture, "Package '{0}' is unknown.", packageName)) { telemetryCode = Telemetry.LaunchFailureCode.RunAsPackageUnknown; errorMessage = string.Concat(errorMessage, "\r\n\r\n", LauncherResources.Error_RunAsUnknownPackage); } else if (errorMessage == string.Format(CultureInfo.InvariantCulture, "Package '{0}' is not debuggable.", packageName)) { telemetryCode = Telemetry.LaunchFailureCode.RunAsPackageNotDebuggable; errorMessage = string.Concat(errorMessage, "\r\n\r\n", LauncherResources.Error_RunAsNonDebuggablePackage); } throw new LauncherException(telemetryCode, string.Format(CultureInfo.CurrentCulture, LauncherResources.Error_ShellCommandFailed, "run-as", errorMessage)); } } } } } <|start_filename|>src/SSHDebugTests/SSHConnectionStringTests.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Globalization; using System.Security; using Microsoft.SSHDebugPS; using Microsoft.SSHDebugPS.Utilities; using Xunit; namespace SSHDebugTests { public class SSHConnectionStringTests { internal struct ConnectionStringTestItem { internal string rawConnectionString; internal string expectedUsername; internal string expectedPassword; internal string expectedHostname; internal int expectedPort; } [Fact] public void IPv6ConnectionStrings() { List<ConnectionStringTestItem> ipv6TestStrings = new List<ConnectionStringTestItem>(); ipv6TestStrings.Add( new ConnectionStringTestItem() { // valid rawConnectionString = "testuser@[1:2:3:4:5:6:7:8]:24", expectedUsername = "testuser", expectedPassword = <PASSWORD>, expectedHostname = "[1:2:3:4:5:6:7:8]", expectedPort = 24 }); ipv6TestStrings.Add( new ConnectionStringTestItem() { // valid with no port rawConnectionString = "testuser@[1:2:3:4:5:6:7:8]", expectedUsername = "testuser", expectedPassword = <PASSWORD>, expectedHostname = "[1:2:3:4:5:6:7:8]", expectedPort = ConnectionManager.DefaultSSHPort }); ipv6TestStrings.Add( new ConnectionStringTestItem() { // valid with username:password rawConnectionString = "test:user@[fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b:7:8]", expectedUsername = "test", expectedPassword = "<PASSWORD>", expectedHostname = "[fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b:7:8]", expectedPort = ConnectionManager.DefaultSSHPort }); ipv6TestStrings.Add( new ConnectionStringTestItem() { // Valid with large port rawConnectionString = "[fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b]:12345", expectedUsername = StringResources.UserName_PlaceHolder, expectedPassword = <PASSWORD>, expectedHostname = "[1:2:3:4:5:6:7:8]", expectedPort = 12345 }); ipv6TestStrings.Add( new ConnectionStringTestItem() { // Invalid format rawConnectionString = "testuser@:8", expectedUsername = StringResources.UserName_PlaceHolder, expectedPassword = <PASSWORD>, expectedHostname = StringResources.HostName_PlaceHolder, expectedPort = ConnectionManager.DefaultSSHPort }); ipv6TestStrings.Add( new ConnectionStringTestItem() { // Invalid string (just port) rawConnectionString = ":8", expectedUsername = StringResources.UserName_PlaceHolder, expectedPassword = null, expectedHostname = StringResources.HostName_PlaceHolder, expectedPort = ConnectionManager.DefaultSSHPort }); ipv6TestStrings.Add( new ConnectionStringTestItem() { // Empty String rawConnectionString = string.Empty, expectedUsername = StringResources.UserName_PlaceHolder, expectedPassword = <PASSWORD>, expectedHostname = StringResources.HostName_PlaceHolder, expectedPort = ConnectionManager.DefaultSSHPort }); ipv6TestStrings.Add( new ConnectionStringTestItem() { // Invalid port rawConnectionString = "[1:2:3:4:5:6:7:8]:123456", expectedUsername = StringResources.UserName_PlaceHolder, expectedPassword = <PASSWORD>, expectedHostname = StringResources.HostName_PlaceHolder, expectedPort = ConnectionManager.DefaultSSHPort }); foreach (var connection in ipv6TestStrings) { ParseConnectionAndValidate(connection); } } [Fact] public void Ipv4ConnectionStrings() { List<ConnectionStringTestItem> ipv4TestStrings = new List<ConnectionStringTestItem>(); ipv4TestStrings.Add( new ConnectionStringTestItem() { // valid no username rawConnectionString = "192.168.1.1:156", expectedUsername = StringResources.UserName_PlaceHolder, expectedPassword = <PASSWORD>, expectedHostname = "192.168.1.1", expectedPort = 156 }); ipv4TestStrings.Add( new ConnectionStringTestItem() { // valid username with port rawConnectionString = "[email protected]:65354", expectedUsername = "customUser", expectedPassword = <PASSWORD>, expectedHostname = "192.168.1.1", expectedPort = 65354 }); ipv4TestStrings.Add( new ConnectionStringTestItem() { // valid no username, Large port rawConnectionString = "192.168.1.1:" + (ushort.MaxValue).ToString("d", CultureInfo.InvariantCulture), expectedUsername = StringResources.UserName_PlaceHolder, expectedPassword = <PASSWORD>, expectedHostname = "192.168.1.1", expectedPort = ushort.MaxValue }); ipv4TestStrings.Add( new ConnectionStringTestItem() { // valid username no port rawConnectionString = "[email protected]", expectedUsername = "user", expectedPassword = <PASSWORD>, expectedHostname = "10.10.10.10", expectedPort = ConnectionManager.DefaultSSHPort }); ipv4TestStrings.Add( new ConnectionStringTestItem() { // valid username no port with password rawConnectionString = "user:[email protected]", expectedUsername = "user", expectedPassword = "<PASSWORD>", expectedHostname = "10.10.10.10", expectedPort = ConnectionManager.DefaultSSHPort }); ipv4TestStrings.Add( new ConnectionStringTestItem() { // Invalid port rawConnectionString = "192.168.1.1:123456", expectedUsername = StringResources.UserName_PlaceHolder, expectedPassword = null, expectedHostname = StringResources.HostName_PlaceHolder, expectedPort = ConnectionManager.DefaultSSHPort }); ipv4TestStrings.Add( new ConnectionStringTestItem() { // Invalid address rawConnectionString = "1%92.168.1.1:23", expectedUsername = StringResources.UserName_PlaceHolder, expectedPassword = null, expectedHostname = StringResources.HostName_PlaceHolder, expectedPort = ConnectionManager.DefaultSSHPort }); foreach (var connection in ipv4TestStrings) { ParseConnectionAndValidate(connection); } } private const string _comparisonErrorStringFormat = "{0} - Expected:'{1}' Actual:'{2}'"; private void ParseConnectionAndValidate(ConnectionStringTestItem item) { string username; string hostname; int port; ConnectionManager.ParseSSHConnectionString(item.rawConnectionString, out username, out SecureString password, out hostname, out port); Assert.True(item.expectedUsername.Equals(username, StringComparison.Ordinal), _comparisonErrorStringFormat.FormatInvariantWithArgs("UserName", item.expectedUsername, username)); Assert.True(item.expectedHostname.Equals(hostname, StringComparison.Ordinal), _comparisonErrorStringFormat.FormatInvariantWithArgs("Hostname", item.expectedHostname, hostname)); Assert.True(item.expectedPort == port, _comparisonErrorStringFormat.FormatInvariantWithArgs("Port", item.expectedPort, port)); if (item.expectedPassword == null) { Assert.True(password == null); } else { string passwordString = StringFromSecureString(password); Assert.True(item.expectedPassword.Equals(passwordString, StringComparison.Ordinal), _comparisonErrorStringFormat.FormatInvariantWithArgs("Password", item.expectedPassword, passwordString)); } } private static string StringFromSecureString(SecureString secString) { if (secString == null) { return null; } IntPtr bstr = System.Runtime.InteropServices.Marshal.SecureStringToBSTR(secString); string value = System.Runtime.InteropServices.Marshal.PtrToStringBSTR(bstr); System.Runtime.InteropServices.Marshal.FreeBSTR(bstr); return value; } } } <|start_filename|>test/DebuggerTesting/OpenDebug/Commands/EvaluateCommand.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using DebuggerTesting.OpenDebug.Commands.Responses; using Newtonsoft.Json; namespace DebuggerTesting.OpenDebug.Commands { public enum EvaluateContext { Unset = 0, None, DataTip, Watch, } #region EvaluateCommandArgs public sealed class EvaluateCommandArgs : JsonValue { public string expression; [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public int? frameId; [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public string context; } #endregion /// <summary> /// Evaluates an expression /// </summary> public class EvaluateCommand : CommandWithResponse<EvaluateCommandArgs, EvaluateResponseValue> { public EvaluateCommand(string expression, int frameId, EvaluateContext context = EvaluateContext.None) : base("evaluate") { Parameter.ThrowIfIsInvalid(context, EvaluateContext.Unset, nameof(context)); this.Args.expression = expression; this.Args.frameId = frameId; this.Args.context = ContextToName(context); } private static string ContextToName(EvaluateContext context) { switch (context) { case EvaluateContext.None: return null; case EvaluateContext.DataTip: return "hover"; case EvaluateContext.Watch: return "watch"; default: throw new ArgumentOutOfRangeException(nameof(context)); } } public string ActualResult { get; private set; } public override void ProcessActualResponse(IActualResponse response) { base.ProcessActualResponse(response); this.ActualResult = this.ActualResponse?.body?.result; } public override string ToString() { return "{0} ({1})".FormatInvariantWithArgs(base.ToString(), this.Args.expression); } } } <|start_filename|>src/DebugEngineHost.VSCode/HostTelemetry.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; namespace Microsoft.DebugEngineHost { /// <summary> /// Static class providing telemetry reporting services to debug engines. Telemetry /// reports go to Microsoft, and so in general this functionality should not be used /// by non-Microsoft implemented debug engines. /// </summary> public static class HostTelemetry { // NOTE: These are from Microsoft.VisualStudio.Debugger.Engine (src\debugger\concord\Dispatcher\Managed\WatsonErrorReport.cs) private const string TelemetryNonFatalWatsonEventName = @"VS/Diagnostics/Debugger/NonFatalError"; private const string TelemetryNonFatalErrorImplementationName = @"VS.Diagnostics.Debugger.NonFatalError.ImplementationName"; private const string TelemetryNonFatalErrorExceptionTypeName = @"VS.Diagnostics.Debugger.NonFatalError.ExceptionType"; private const string TelemetryNonFatalErrorExceptionStackName = @"VS.Diagnostics.Debugger.NonFatalError.ExceptionStack"; private const string TelemetryNonFatalErrorExceptionHResult = @"VS.Diagnostics.Debugger.NonFatalError.HResult"; // Common telemetry constants private const string TelemetryImplementationName = @"VS.Diagnostics.Debugger.ImplementationName"; private const string TelemetryEngineVersion = @"VS.Diagnostics.Debugger.EngineVersion"; private const string TelemetryHostVersion = @"VS.Diagnostics.Debugger.HostVersion"; private const string TelemetryAdapterId = @"VS.Diagnostics.Debugger.AdapterId"; private static Action<string, KeyValuePair<string, object>[]> s_telemetryCallback; private static string s_engineName; private static string s_engineVersion; private static string s_hostVersion; private static string s_adapterId; public static void InitializeTelemetry(Action<string, KeyValuePair<string, object>[]> telemetryCallback, TypeInfo engineType, string adapterId) { Debug.Assert(telemetryCallback != null && engineType != null, "Bogus arguments to InitializeTelemetry"); s_telemetryCallback = telemetryCallback; s_engineName = engineType.Namespace; s_engineVersion = GetVersionAttributeValue(engineType); s_hostVersion = GetVersionAttributeValue(typeof(HostTelemetry).GetTypeInfo()); s_adapterId = adapterId; } /// <summary> /// Reports a telemetry event to Microsoft. /// </summary> /// <param name="eventName">Name of the event. This should generally start with the /// prefix 'VS/Diagnostics/Debugger/'</param> /// <param name="eventProperties">0 or more properties of the event. Property names /// should generally start with the prefix 'VS.Diagnostics.Debugger.'</param> [Conditional("LAB")] public static void SendEvent(string eventName, params KeyValuePair<string, object>[] eventProperties) { #if LAB if (s_telemetryCallback != null) { s_telemetryCallback(eventName, eventProperties); } #endif } /// <summary> /// Reports the current exception to Microsoft's telemetry service. /// </summary> /// <param name="currentException">Exception object to report.</param> /// <param name="engineName">[Optional] Name of the engine reporting the exception. Ex:Microsoft.MIEngine. /// In OpenDebugAD7, this is optional.</param> public static void ReportCurrentException(Exception currentException, string engineName) { try { // Report the inner-most exception while (currentException.InnerException != null) { currentException = currentException.InnerException; } if (s_hostVersion == null) { // InitializeTelemetry not called yet return; } if (engineName == null) { engineName = s_engineName; } SendEvent(TelemetryNonFatalWatsonEventName, new KeyValuePair<string, object>(TelemetryNonFatalErrorImplementationName, engineName), new KeyValuePair<string, object>(TelemetryNonFatalErrorExceptionTypeName, currentException.GetType().FullName), new KeyValuePair<string, object>(TelemetryNonFatalErrorExceptionStackName, currentException.StackTrace), new KeyValuePair<string, object>(TelemetryNonFatalErrorExceptionHResult, currentException.HResult), new KeyValuePair<string, object>(TelemetryEngineVersion, s_engineVersion), new KeyValuePair<string, object>(TelemetryAdapterId, s_adapterId), new KeyValuePair<string, object>(TelemetryHostVersion, s_hostVersion) ); } catch { // We are already reporting an exception. If something goes wrong, nothing to be done. } } private static string GetVersionAttributeValue(TypeInfo engineType) { var attribute = engineType.Assembly.GetCustomAttribute(typeof(System.Reflection.AssemblyFileVersionAttribute)) as AssemblyFileVersionAttribute; if (attribute == null) return string.Empty; return attribute.Version; } } } <|start_filename|>test/Android/Eval/Eval/Eval.NativeActivity/main.cpp<|end_filename|> /* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #define LOGI(...) ((void)__android_log_print(ANDROID_LOG_INFO, "AndroidProject1.NativeActivity", __VA_ARGS__)) #define LOGW(...) ((void)__android_log_print(ANDROID_LOG_WARN, "AndroidProject1.NativeActivity", __VA_ARGS__)) /** * This is the main entry point of a native application that is using * android_native_app_glue. It runs in its own thread, with its own * event loop for receiving input events and doing other things. */ void android_main(struct android_app* state) { int i = 0xDEADBEEF; i += 0; // bp here } <|start_filename|>src/DebugEngineHost.VSCode/VSCode/AssemblyResolver.cs<|end_filename|> // // Copyright (c) Microsoft. All rights reserved. // // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Reflection; using System.Runtime.Loader; namespace Microsoft.DebugEngineHost.VSCode { internal static class AssemblyResolver { static readonly HashSet<string> s_unresolvedNames = new HashSet<string>(); public static void Initialize() { AssemblyLoadContext.Default.Resolving += OnAssemblyResolve; } private static Assembly OnAssemblyResolve(AssemblyLoadContext loadContext, AssemblyName assemblyName) { Assembly asm = InnerResolveHandler(assemblyName); return asm; } private static Assembly InnerResolveHandler(AssemblyName assemblyName) { string assemblyFileName = string.Concat(assemblyName.Name, ".dll"); if (assemblyName.CultureInfo != null && !assemblyName.CultureInfo.Equals(CultureInfo.InvariantCulture)) { //Prepend the culture directory (e.g. ja\Microsoft.VisualStudio.Test.resources.dll) assemblyFileName = Path.Combine(assemblyName.CultureInfo.Name, assemblyFileName); } // This name was unresolved last time. No need to check for it again lock (s_unresolvedNames) { if (s_unresolvedNames.Contains(assemblyFileName)) { return null; } } Assembly asm = AssemblyLoadContext.Default.LoadFromAssemblyPath(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, assemblyFileName)); if (asm == null) { lock (s_unresolvedNames) { s_unresolvedNames.Add(assemblyFileName); } } return asm; } } } <|start_filename|>test/CppTests/TestBase.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using DebugAdapterRunner; using DebuggerTesting; using DebuggerTesting.OpenDebug; using DebuggerTesting.OpenDebug.CrossPlatCpp; using System; using System.Collections.Generic; using Xunit.Abstractions; namespace CppTests { public abstract class TestBase : ILoggingComponent { #region ILoggingComponent Members public ITestOutputHelper OutputHelper { get; } #endregion protected TestBase(ITestOutputHelper outputHelper) { this.OutputHelper = outputHelper; } protected IDebuggerRunner CreateDebugAdapterRunner(ITestSettings settings) { return DebuggerRunner.Create(this, settings, GetCallbackHandlers()); } protected virtual IEnumerable<Tuple<string, CallbackRequestHandler>> GetCallbackHandlers() { return null; } } } <|start_filename|>test/DebuggerTesting/TestFramework/ITestSettingsProvider.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using System.Reflection; namespace DebuggerTesting.TestFramework { /// <summary> /// Interface use for providing test settings based on reflection of a test method. /// </summary> public interface ITestSettingsProvider { #region Methods /// <summary> /// Gets the test settings associated with the test method. /// </summary> IEnumerable<ITestSettings> GetSettings(MethodInfo testMethod); #endregion } } <|start_filename|>test/DebuggerTesting/OpenDebug/Commands/ReadMemoryCommand.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using DebuggerTesting.OpenDebug.Commands.Responses; using Newtonsoft.Json; using System; namespace DebuggerTesting.OpenDebug.Commands { public sealed class ReadMemoryArgs : JsonValue { public string memoryReference; [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public int? offset; public int count; } public class ReadMemoryCommand : CommandWithResponse<ReadMemoryArgs, ReadMemoryResponseValue> { public ReadMemoryCommand(string reference, int? offset, int count) : base("readMemory") { this.Args.memoryReference = reference; this.Args.offset = offset; this.Args.count = count; } } } <|start_filename|>src/SSHDebugPS/UI/ContainerPickerDialogWindow.xaml.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.ComponentModel; using System.Diagnostics; using System.Windows; using System.Windows.Automation; using System.Windows.Automation.Provider; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Input; using Microsoft.SSHDebugPS.Docker; using Microsoft.SSHDebugPS.UI; using Microsoft.SSHDebugPS.Utilities; using Microsoft.VisualStudio.PlatformUI; namespace Microsoft.SSHDebugPS.UI { /// <summary> /// Interaction logic for DockerContainerPickerWindow.xaml /// </summary> public partial class ContainerPickerDialogWindow : DialogWindow { public ContainerPickerDialogWindow(bool supportSSHConnections) { InitializeComponent(); _model = new ContainerPickerViewModel(supportSSHConnections); this.DataContext = _model; this.Loaded += OnWindowLoaded; } private void OnWindowLoaded(object sender, RoutedEventArgs e) { bool listItemFocused = false; try { if (ContainerListBox != null && ContainerListBox.HasItems) { if (ContainerListBox.SelectedItem == null) { ContainerListBox.SelectedIndex = 0; } ((ListBoxItem)ContainerListBox.ItemContainerGenerator.ContainerFromItem(ContainerListBox.SelectedItem)).Focus(); listItemFocused = true; } } catch (Exception ex) { // Ignore if focus was failed to be set Debug.Fail(ex.ToString()); } if (!listItemFocused) { //Focus the combo box ConnectionTypeComboBox.Focus(); } e.Handled = true; } #region Properties public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged(string name) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name)); } public string SelectedContainerConnectionString { get { return _model.SelectedContainerConnectionString; } } #endregion #region Event Handlers private void ListBox_GotKeyboardFocus(object sender, RoutedEventArgs e) { ListBoxItem item = e.OriginalSource as ListBoxItem; if (item != null && !item.IsSelected) { item.IsSelected = true; } } private void ContainerListBox_GotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e) { ListBoxItem item = e.OriginalSource as ListBoxItem; if (item != null && !item.IsSelected) { item.IsSelected = true; } } private void ContainerListBox_PreviewKeyDown(object sender, KeyEventArgs e) { if (sender is ListBox list) { if (list.SelectedItem is DockerContainerViewModel viewModel) { switch (e.Key) { case Key.Right: viewModel.IsExpanded = true; e.Handled = true; break; case Key.Left: viewModel.IsExpanded = false; e.Handled = true; break; case Key.Space: viewModel.IsExpanded = !viewModel.IsExpanded; e.Handled = true; break; } } } } #endregion #region Private Variables private ContainerPickerViewModel _model; #endregion } } <|start_filename|>src/MICoreUnitTests/MIResultsTests.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using MICore; using Xunit; namespace MICoreUnitTests { public class MIResultsTests { [Fact] public void TestParseCStringNull() { string miString = null; //input = <null> Assert.Throws<ArgumentNullException>(delegate { MIResults r = new MIResults(null); r.ParseCString(miString); }); } [Fact] public void TestParseCStringEmpty() { MIResults r = new MIResults(null); string miString = ""; // input = <empty> string result = r.ParseCString(miString); Assert.Equal(String.Empty, result); miString = "\"\""; // input = "" result = r.ParseCString(miString); Assert.Equal(String.Empty, result); } [Fact] public void TestParseCString() { MIResults r = new MIResults(null); string miString = "\"hello\""; //input = "hello" string result = r.ParseCString(miString); Assert.Equal("hello", result); miString = "\"\\tHello\\n\""; //input = "\tHello\n" result = r.ParseCString(miString); Assert.Equal("\tHello\n", result); miString = "\" \""; //input = <four spaces> result = r.ParseCString(miString); Assert.Equal(" ", result); miString = " \"Hello\" "; //input = <leading spaces>"Hello"<trailing spaces> result = r.ParseCString(miString); Assert.Equal("Hello", result); miString = "\"\"\"\"\"\""; //input = """""" result = r.ParseCString(miString); Assert.Equal("\"\"", result); } [Fact] public void TestParseResultListConstValues() { MIResults r = new MIResults(null); string miString = @"name=""value"""; // name="value" Results results = r.ParseResultList(miString); Assert.Single(results.Content); Assert.Equal("name", results.Content[0].Name); Assert.True(results.Content[0].Value is ConstValue); Assert.Equal("value", (results.Content[0].Value as ConstValue).Content); Assert.Equal("value", results.FindString("name")); miString = @"name1=""value1"",name2=""value2"""; // name1="value1",name2="value2" results = r.ParseResultList(miString); Assert.Equal(2, results.Content.Length); Assert.Equal("name1", results.Content[0].Name); Assert.Equal("name2", results.Content[1].Name); Assert.True(results.Content[0].Value is ConstValue); Assert.True(results.Content[1].Value is ConstValue); Assert.Equal("value1", (results.Content[0].Value as ConstValue).Content); Assert.Equal("value2", (results.Content[1].Value as ConstValue).Content); Assert.Equal("value1", results.FindString("name1")); Assert.Equal("value2", results.FindString("name2")); } } } <|start_filename|>src/DebugEngineHost.VSCode/HostLogger.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; namespace Microsoft.DebugEngineHost { public sealed class HostLogger { public delegate void OutputCallback(string outputMessage); private static HostLogger s_instance; private static readonly object s_lock = new object(); /// <summary>[Optional] VSCode-only host logger instance.</summary> public static HostLogger Instance { get { return s_instance; } } /// <summary>[Optional] VSCode-only method for obtaining the current host logger instance.</summary> public static void EnableHostLogging() { if (s_instance == null) { lock (s_lock) { if (s_instance == null) { s_instance = new HostLogger(); } } } } private string _logFilePath = null; private System.IO.StreamWriter _logFile = null; /// <summary>Callback for logging text to the desired output stream.</summary> public Action<string> LogCallback { get; set; } = null; /// <summary>The path to the log file.</summary> public string LogFilePath { get { return _logFilePath; } set { _logFile?.Dispose(); _logFilePath = value; if (!String.IsNullOrEmpty(_logFilePath)) { _logFile = System.IO.File.CreateText(_logFilePath); } } } private HostLogger() { } public void WriteLine(string line) { lock (s_lock) { _logFile?.WriteLine(line); _logFile?.Flush(); LogCallback?.Invoke(line); } } public void Flush() { } public void Close() { } /// <summary> /// Get a logger after the user has explicitly configured a log file/callback /// </summary> /// <param name="logFileName"></param> /// <param name="callback"></param> /// <returns>The host logger object</returns> public static HostLogger GetLoggerFromCmd(string logFileName, HostLogger.OutputCallback callback) { throw new NotImplementedException(); } } } <|start_filename|>src/OpenDebugAD7/MILaunchOptions.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Text; using Microsoft.DebugEngineHost; using Microsoft.DebugEngineHost.VSCode; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Serialization; using OpenDebug; namespace OpenDebugAD7 { ///<summary>Generates launch options for launching the mi engine.</summary> internal static class MILaunchOptions { /// <summary> /// Returns the path to lldb-mi which is installed when the extension is installed /// </summary> /// <returns>Path to lldb-mi or null if it doesn't exist</returns> internal static string GetLLDBMIPath() { string exePath = null; string directory = EngineConfiguration.GetAdapterDirectory(); DirectoryInfo dir = new DirectoryInfo(directory); // Remove /bin from the path to get to the debugAdapter folder string debugAdapterPath = dir.Parent?.FullName; if (!String.IsNullOrEmpty(debugAdapterPath)) { // Path for lldb-mi 10.x and if it exists use it. exePath = Path.Combine(debugAdapterPath, "lldb-mi", "bin", "lldb-mi"); if (!File.Exists(exePath)) { // Fall back to using path for lldb-mi 3.8 exePath = Path.Combine(debugAdapterPath, "lldb", "bin", "lldb-mi"); if (!File.Exists(exePath)) { // Neither exist return null; } } } return exePath; } } } <|start_filename|>test/DebuggerTesting/Utilities/UnixNativeMethods.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Runtime.InteropServices; namespace DebuggerTesting.Utilities { internal class UnixNativeMethods { private const string Libc = "libc"; [DllImport(Libc, EntryPoint = "kill", SetLastError = true)] internal static extern int Kill(int pid, int mode); [DllImport(Libc, EntryPoint = "mkfifo", SetLastError = true)] internal static extern int MkFifo(byte[] name, int mode); [DllImport(Libc, EntryPoint = "geteuid", SetLastError = true)] internal static extern uint GetEUid(); [DllImport(Libc, EntryPoint = "getpgid", SetLastError = true)] internal static extern int GetPGid(int pid); } } <|start_filename|>src/OpenDebugAD7/SessionConfiguration.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace OpenDebugAD7 { /// <summary> /// Class to hold configuration for a single debug session, such as Just My Code or Require Exact Source settings /// </summary> internal class SessionConfiguration { public bool RequireExactSource { get; set; } = true; public bool JustMyCode { get; set; } = true; public bool StopAtEntrypoint { get; set; } = false; public bool EnableStepFiltering { get; set; } = true; } } <|start_filename|>test/DebuggerTesting/OpenDebug/Commands/SetFunctionBreakpointsCommand.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Linq; using DebuggerTesting.OpenDebug.Commands.Responses; using Newtonsoft.Json; namespace DebuggerTesting.OpenDebug.Commands { #region SetBreakpointsCommandArgs public sealed class SetFunctionBreakpointsCommandArgs : JsonValue { public sealed class FunctionBreakpoint { public FunctionBreakpoint(string name, string condition = null) { this.name = name; this.condition = condition; } public string name; [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public string condition; } public FunctionBreakpoint[] breakpoints; } #endregion #region FunctionBreakpoints public sealed class FunctionBreakpoints { private List<SetFunctionBreakpointsCommandArgs.FunctionBreakpoint> breakpoints; public FunctionBreakpoints() { this.breakpoints = new List<SetFunctionBreakpointsCommandArgs.FunctionBreakpoint>(); } public FunctionBreakpoints(params string[] functions) : this() { foreach (string function in functions) { this.Add(function); } } public FunctionBreakpoints Add(string function, string condition = null) { this.breakpoints.Add(new SetFunctionBreakpointsCommandArgs.FunctionBreakpoint(function, condition)); return this; } public FunctionBreakpoints Remove(string function) { this.breakpoints.RemoveAll(bp => String.Equals(bp.name, function, StringComparison.Ordinal)); return this; } internal IList<SetFunctionBreakpointsCommandArgs.FunctionBreakpoint> Breakpoints { get { return this.breakpoints; } } } #endregion public class SetFunctionBreakpointsCommand : CommandWithResponse<SetFunctionBreakpointsCommandArgs, SetBreakpointsResponseValue> { public SetFunctionBreakpointsCommand() : base("setFunctionBreakpoints") { } public SetFunctionBreakpointsCommand(FunctionBreakpoints breakpoints) : this() { this.Args.breakpoints = breakpoints.Breakpoints.ToArray(); } public override string ToString() { return "{0} ({1})".FormatInvariantWithArgs(base.ToString(), String.Join(", ", this.Args.breakpoints.Select(bp => bp.name))); } } } <|start_filename|>test/DebugAdapterRunner/DebugAdapterRunner.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Newtonsoft.Json; using OpenDebug; using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Text; using System.Threading; namespace DebugAdapterRunner { /// <summary> /// Delegate for a callback request handler. For example, handler for `runInTerminal` /// </summary> /// <param name="runner">The runner instance</param> /// <param name="dispatcherRequest">The dispatcher request</param> public delegate void CallbackRequestHandler(DebugAdapterRunner runner, DispatcherRequest dispatcherRequest); public enum TraceDebugAdapterMode { None = 0, Console = 1, Memory = 2, } public class DebugAdapterRunner { // Whether the tool will dump requests and responses between the debug adapter and itself private TraceDebugAdapterMode _traceDebugAdapterOutput = TraceDebugAdapterMode.None; private volatile int _seq; private bool _hasAsserted; private string _assertionFileName; private readonly Action<string> _errorLogger; // The timeout for getting a response from the debug adapter public int ResponseTimeout; // Reference to debug adapter process public Process DebugAdapter; // The current thread id which is automatically updated when the tool receives a stopped event public int CurrentThreadId; // Keep a trace of the debug adapter output if requested private StringBuilder _debugAdapterOutput = new StringBuilder(); private IDictionary<string, CallbackRequestHandler> _callbackHandlers = new Dictionary<string, CallbackRequestHandler>(); // Current list of responses received from the debug adapter public List<string> Responses { get; private set; } public string DebugAdapterOutput { get { return _debugAdapterOutput.ToString(); } } public void AppendLineToDebugAdapterOutput(string line) { if (_traceDebugAdapterOutput == TraceDebugAdapterMode.Memory) { _debugAdapterOutput.AppendLine(line); } } public DebugAdapterRunner( string adapterPath, TraceDebugAdapterMode traceDebugAdapterOutput = TraceDebugAdapterMode.None, bool engineLogging = false, string engineLogPath = null, bool pauseForDebugger = false, bool isVsDbg = false, bool isNative = true, int responseTimeout = 5000, Action<string> errorLogger = null, bool redirectVSAssert = false, IEnumerable<KeyValuePair<string, string>> additionalEnvironmentVariables = null) { this._errorLogger = errorLogger; List<string> adapterArgs = new List<string>(); if (isVsDbg) { adapterArgs.Add("--interpreter=vscode"); } else { if (traceDebugAdapterOutput != TraceDebugAdapterMode.None) { adapterArgs.Add("--trace=response"); } } if (pauseForDebugger) { adapterArgs.Add("--pauseForDebugger"); } if (!string.IsNullOrEmpty(engineLogPath)) { adapterArgs.Add("--engineLogging=" + engineLogPath); } else if (engineLogging) { adapterArgs.Add("--engineLogging"); } StartDebugAdapter(adapterPath, string.Join(" ", adapterArgs), traceDebugAdapterOutput, pauseForDebugger, redirectVSAssert, responseTimeout, additionalEnvironmentVariables); } public DebugAdapterRunner( string adapterPath, string adapterArgs, TraceDebugAdapterMode traceDebugAdapterOutput, bool pauseForDebugger, bool redirectVSAssert, int responseTimeout, Action<string> errorLogger, IEnumerable<KeyValuePair<string, string>> additionalEnvironmentVariables) { _errorLogger = errorLogger; StartDebugAdapter(adapterPath, adapterArgs, traceDebugAdapterOutput, pauseForDebugger, redirectVSAssert, responseTimeout, additionalEnvironmentVariables); } private void StartDebugAdapter( string adapterPath, string adapterArgs, TraceDebugAdapterMode traceDebugAdapterOutput, bool pauseForDebugger, bool redirectVSAssert, int responseTimeout, IEnumerable<KeyValuePair<string, string>> additionalEnvironmentVariables) { // If pauseForDebugger is enabled, we might be debugging the adapter for a while. ResponseTimeout = pauseForDebugger ? 1000 * 60 * 60 * 24 : responseTimeout; _traceDebugAdapterOutput = traceDebugAdapterOutput; EventWaitHandle debugAdapterStarted = new EventWaitHandle(false, EventResetMode.AutoReset); Responses = new List<string>(); ProcessStartInfo startInfo = new ProcessStartInfo(adapterPath, adapterArgs); startInfo.UseShellExecute = false; startInfo.CreateNoWindow = true; startInfo.RedirectStandardInput = true; startInfo.RedirectStandardOutput = true; startInfo.RedirectStandardError = true; if (redirectVSAssert) { _assertionFileName = Path.Combine(Path.GetTempPath(), string.Format(CultureInfo.InvariantCulture, "vsassert.{0}.txt", Guid.NewGuid())); startInfo.Environment["VSASSERT"] = _assertionFileName; } if (additionalEnvironmentVariables != null) { foreach (KeyValuePair<string, string> pair in additionalEnvironmentVariables) { startInfo.Environment[pair.Key] = pair.Value; } } DebugAdapter = Process.Start(startInfo); DebugAdapter.ErrorDataReceived += (o, a) => { if (pauseForDebugger) { debugAdapterStarted.Set(); } string message = a.Data ?? string.Empty; if (message.StartsWith("ASSERT FAILED", StringComparison.Ordinal)) { _hasAsserted = true; } LogErrorLine(message); }; DebugAdapter.BeginErrorReadLine(); if (pauseForDebugger) { Console.WriteLine(string.Format(CultureInfo.InvariantCulture, "Attach a debugger to PID {0}", DebugAdapter.Id)); debugAdapterStarted.WaitOne(); } } private void LogErrorLine(string message) { try { if (Debugger.IsAttached) { Debug.WriteLine(message); } if (_errorLogger != null) { _errorLogger(message); } else if (_traceDebugAdapterOutput == TraceDebugAdapterMode.Console) { Console.WriteLine(message); } if (_traceDebugAdapterOutput != TraceDebugAdapterMode.None) { AppendLineToDebugAdapterOutput(message); } } catch { } } /// <summary> /// Returns the sequence number for the next message /// </summary> /// <returns>Sequence number</returns> public int GetNextSequenceNumber() { return Interlocked.Increment(ref _seq); } public string SerializeMessage(DispatcherMessage message) { string serialized = JsonConvert.SerializeObject(message); byte[] bytes = Encoding.UTF8.GetBytes(serialized); return string.Format(CultureInfo.InvariantCulture, "{0}{1}{2}{3}", DAPConstants.ContentLength, bytes.Length, DAPConstants.TwoCrLf, serialized); } public void Run(Command command) { try { command.Run(this); } catch (DARException darException) { throw new DARException(string.Format(CultureInfo.InvariantCulture, "Test command execution failed...\nFailure = {0}\n\nCommand = {1}\n\nFull output = {2}", darException.Message, JsonConvert.SerializeObject(command), DebugAdapterOutput)); } if (this.HasAsserted()) { throw new DARException(string.Format(CultureInfo.InvariantCulture, "Debug adapter has asserted wher running command. See test log for details. Command: {0}", JsonConvert.SerializeObject(command))); } } public bool HasAsserted() { if (_hasAsserted) return true; if (_assertionFileName != null && File.Exists(_assertionFileName)) { _hasAsserted = true; try { foreach (var line in File.ReadAllLines(_assertionFileName)) { LogErrorLine(line); } } catch { } return true; } return false; } public void AddCallbackRequestHandler(string commandName, CallbackRequestHandler handler) { this._callbackHandlers.Add(commandName, handler); } internal void HandleCallbackRequest(string receivedMessage) { DispatcherRequest dispatcherRequest = JsonConvert.DeserializeObject<DispatcherRequest>(receivedMessage); if (_callbackHandlers.TryGetValue(dispatcherRequest.command, out CallbackRequestHandler handler)) { handler(this, dispatcherRequest); } else { string errorMessage = String.Format(CultureInfo.CurrentCulture, "Received unhandled callback command '{0}'", dispatcherRequest.command); throw new DARException(errorMessage); } } } } <|start_filename|>test/CppTests/Tests/DebuggeeHelpers.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.IO; using DebuggerTesting; using DebuggerTesting.Compilation; using Xunit; namespace CppTests.Tests { internal static class DebuggeeHelper { private static object s_lock = new object(); public static IDebuggee OpenAndCompile(ILoggingComponent logger, ICompilerSettings settings, int moniker, string name, string outputname, Action<IDebuggee> addSourceFiles) { Assert.NotNull(addSourceFiles); lock (s_lock) { IDebuggee debuggee = Debuggee.Create(logger, settings, name, moniker, outputname); addSourceFiles(debuggee); debuggee.Compile(); return debuggee; } } public static IDebuggee Open(ILoggingComponent logger, ICompilerSettings settings, int moniker, string name, string outputname) { lock (s_lock) { IDebuggee debuggee = Debuggee.Open(logger, settings, name, moniker, outputname); Assert.True(File.Exists(debuggee.OutputPath), "The debuggee was not compiled. Missing " + debuggee.OutputPath); return debuggee; } } } } <|start_filename|>tools/Setup.cmd<|end_filename|> @echo off setlocal enabledelayedexpansion where dotnet >nul 2>nul if NOT "%ERRORLEVEL%"=="0" ( echo dotnet needs to be installed. https://dotnet.microsoft.com/download/dotnet-core exit /b -1 ) dotnet script -v >nul 2>nul if NOT "%ERRORLEVEL%"=="0" ( echo dotnet script needs to be installed. Run 'dotnet tool install -g dotnet-script'. echo More Information: https://github.com/filipw/dotnet-script#net-core-global-tool exit /b -1 ) dotnet script %~dp0\Setup.csx %* exit /b %ERRORLEVEL% <|start_filename|>test/DebuggerTesting/Utilities/Parameter.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Diagnostics; using System.Globalization; using System.Reflection; namespace DebuggerTesting { [DebuggerStepThrough] public static class Parameter { #region NotOfType /// <summary> /// Throws ArgumentException if the value is not of the specified type. /// </summary> public static void ThrowIfNotOfType<T>(object value, string paramName, bool allowNull = false) { AssertIfNotOfType<T>(value, paramName, allowNull); if (IsNotOfType<T>(value, allowNull)) throw new ArgumentException(string.Empty, paramName); } /// <summary> /// Assert if the value is not of the specified type. /// </summary> [DebuggerHidden] [Conditional("DEBUG")] public static void AssertIfNotOfType<T>(object value, string paramName, bool allowNull = false) { if (IsNotOfType<T>(value, allowNull)) ParameterAssert("Parameter {0} not of type {1}", paramName, typeof(T).Name); } public static void AssertIfNotOfType<T>(Type type, string paramName) { Parameter.AssertIfNull(type, paramName); if (!typeof(T).GetTypeInfo().IsAssignableFrom(type.GetTypeInfo())) ParameterAssert("Parameter {0} does not implement {1}", paramName, typeof(T).Name); } private static bool IsNotOfType<T>(object value, bool allowNull) { return (null == value && !allowNull) || (null != value && !(value is T)); } #endregion #region NullOrWhiteSpace /// <summary> /// Throws ArgumentNullException if the value is null or is white space. /// </summary> public static void ThrowIfNullOrWhiteSpace(string value, string paramName) { AssertIfNullOrWhiteSpace(value, paramName); if (IsNullOrWhiteSpace(value)) throw new ArgumentNullException(paramName); } /// <summary> /// Assert if the value is null or is white space. /// </summary> [DebuggerHidden] [Conditional("DEBUG")] public static void AssertIfNullOrWhiteSpace(string value, string paramName) { if (IsNullOrWhiteSpace(value)) ParameterAssert("Parameter {0} is null or white space.", paramName); } private static bool IsNullOrWhiteSpace(string value) { return String.IsNullOrWhiteSpace(value); } #endregion #region Null /// <summary> /// Throws ArgumentNullException if the value is null. /// </summary> public static void ThrowIfNull<T>(T value, string paramName) where T : class { AssertIfNull(value, paramName); if (IsNull(value)) throw new ArgumentNullException(paramName); } /// <summary> /// Assert if the value is null. /// </summary> [DebuggerHidden] [Conditional("DEBUG")] public static void AssertIfNull<T>(T value, string paramName) where T : class { if (IsNull(value)) ParameterAssert("Parameter {0} is null.", paramName); } private static bool IsNull<T>(T value) where T : class { return null == value; } #endregion #region IsInvalid /// <summary> /// Throws ArgumentNullException if the value matches an invalid value. /// </summary> public static void ThrowIfIsInvalid<T>(T value, T invalidValue, string paramName) where T : struct { AssertIfIsInvalid(value, invalidValue, paramName); if (IsInvalid(value, invalidValue)) throw new ArgumentNullException(paramName); } /// <summary> /// Assert if the value matches an invalid value. /// </summary> [DebuggerHidden] [Conditional("DEBUG")] public static void AssertIfIsInvalid<T>(T value, T invalidValue, string paramName) where T : struct { if (IsInvalid(value, invalidValue)) ParameterAssert("Parameter {0} is invalid value.", paramName); } private static bool IsInvalid<T>(T value, T invalidValue) { return object.Equals(value, invalidValue); } #endregion #region OutOfRange /// <summary> /// Throw ArgumentOutOfRangeException if value is not between minValue and maxValue inclusively. /// </summary> public static void ThrowIfOutOfRange(int value, int minValue, int maxValue, string paramName) { AssertIfOutOfRange(value, minValue, maxValue, paramName); if (IsOutOfRange(value, minValue, maxValue)) throw new ArgumentOutOfRangeException(paramName); } /// <summary> /// Assert if value is not between minValue and maxValue inclusively. /// </summary> [DebuggerHidden] [Conditional("DEBUG")] public static void AssertIfOutOfRange(int value, int minValue, int maxValue, string paramName) { if (IsOutOfRange(value, minValue, maxValue)) ParameterAssert("Parameter {0} is out of range. Should be between {1} and {2}.", paramName, minValue, maxValue); } private static bool IsOutOfRange(int value, int minValue, int maxValue) { return value < minValue || value > maxValue; } #endregion #region NotPositive /// <summary> /// Throws ArgumentOutOfRangeException if the value is not a negative or zero. /// </summary> public static void ThrowIfNegativeOrZero(int value, string paramName) { AssertIfNegativeOrZero(value, paramName); if (IsNegativeOrZero(value)) throw new ArgumentOutOfRangeException(paramName); } /// <summary> /// Assert if the value is not a negative or zero. /// </summary> [DebuggerHidden] [Conditional("DEBUG")] public static void AssertIfNegativeOrZero(int value, string paramName) { if (IsNegativeOrZero(value)) ParameterAssert("Parameter Error: Parameter {0} is not positive.", paramName); } private static bool IsNegativeOrZero(int value) { return value <= 0; } #endregion #region ParameterAssert [DebuggerHidden] [Conditional("DEBUG")] private static void ParameterAssert(string format, params object[] parameters) { string message = "Parameter Error: "; if (!string.IsNullOrEmpty(format)) message += string.Format(CultureInfo.InvariantCulture, format, parameters); Debug.WriteLine(message); Debug.Fail(message); } #endregion } } <|start_filename|>src/AndroidDebugLauncher/INDKFilePath.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace AndroidDebugLauncher { public interface INDKFilePath { string PartialFilePath { get; } string TryResolve(string ndkRoot); string GetSearchPathDescription(string ndkRoot); } } <|start_filename|>src/OpenDebugAD7/Document.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Security.Cryptography; using System.IO; using Microsoft.DebugEngineHost; using System.Globalization; using OpenDebugAD7.AD7Impl; namespace OpenDebugAD7 { internal class Document { public string Path { get; private set; } protected Document(string path) { Path = path; } public static Document GetOrCreate(string path) { Document document; if (!s_documentCache.TryGetValue(path, out document)) { document = new Document(path); s_documentCache.Add(path, document); } return document; } private static Dictionary<string, Document> s_documentCache = new Dictionary<string, Document>(); } } <|start_filename|>test/DebugAdapterRunner/DebugAdapterCommand.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; using Newtonsoft.Json; using OpenDebug; namespace DebugAdapterRunner { /// <summary>Represents a command that is sent to the debug adapter</summary> public class DebugAdapterCommand : Command { public dynamic args; private const int REQUEST_BYTES = 4096; public DebugAdapterCommand(string cmd, dynamic args, IEnumerable<DebugAdapterResponse> expectedResponses = null) { this.Name = cmd; this.args = args; if (expectedResponses == null) { this.ExpectedResponses.Add(new DebugAdapterResponse(new { success = true, command = cmd })); } else { this.ExpectedResponses.AddRange(expectedResponses); } } private string CreateDispatcherRequest(DebugAdapterRunner runner) { DispatcherRequest request = new DispatcherRequest(runner.GetNextSequenceNumber(), this.Name, this.args); return runner.SerializeMessage(request); } private void VerifyValueOfBuffer(byte[] buffer, string expectedValue) { string actualValue = Encoding.UTF8.GetString(buffer); if (actualValue != expectedValue) { string errorMessage = string.Format(CultureInfo.CurrentCulture, "Unexpected response from debug adapter. Was expecting {0} but got {1}", expectedValue, actualValue); throw new DARException(errorMessage); } } private string GetMessage(Stream stdout, int timeout, Process debugAdapter, DebugAdapterRunner runner) { // Read header of message byte[] header = ReadBlockFromStream(stdout, debugAdapter, DAPConstants.ContentLength.Length, timeout); VerifyValueOfBuffer(header, DAPConstants.ContentLength); // Read the length (in bytes) of the json message int messageLengthBytes = 0; int nextByte = -1; while (true) { nextByte = stdout.ReadByte(); if (nextByte >= '0' && nextByte <= '9') { messageLengthBytes = messageLengthBytes * 10 + nextByte - '0'; } else { break; } } // Read and verify TWO_CRLF byte[] twoCRLF = new byte[DAPConstants.TwoCrLf.Length]; twoCRLF[0] = (byte)nextByte; // Read one less byte because we have the first byte and copy into twoCRLF byte array byte[] oneMinustwoCRLF = ReadBlockFromStream(stdout, debugAdapter, DAPConstants.TwoCrLf.Length - 1, timeout); Array.Copy(oneMinustwoCRLF, 0, twoCRLF, 1, oneMinustwoCRLF.Length); VerifyValueOfBuffer(twoCRLF, DAPConstants.TwoCrLf); // Read the message contents byte[] messageBuffer = ReadBlockFromStream(stdout, debugAdapter, messageLengthBytes, timeout); return Encoding.UTF8.GetString(messageBuffer, 0, messageLengthBytes); } private byte[] ReadBlockFromStream(Stream stream, Process debugAdapter, int length, int timeout) { int bytesRead = 0; byte[] messageBuffer = new byte[length]; while (bytesRead < length) { // Read as many bytes as we need or as many bytes as we can fit int requestedReadBytes = Math.Min(length - bytesRead, DebugAdapterCommand.REQUEST_BYTES); Task<int> readMessageTask = stream.ReadAsync(messageBuffer, bytesRead, requestedReadBytes); if (!readMessageTask.Wait(timeout)) { if (bytesRead == 0) { throw new TimeoutException("Timeout waiting for message from Debug Adapter"); } else { throw new DARException(String.Format(CultureInfo.InvariantCulture, "Timeout reading expected bytes. Expected:{0} Actual:{1} Timeout:{2}", length, bytesRead, timeout)); } } if (debugAdapter.HasExited && readMessageTask.Result == 0) { throw new DARException(String.Format(CultureInfo.InvariantCulture, "The debugger process has exited without sending all expected bytes. Expected: {0} Actual:{1}", length, bytesRead)); } bytesRead += readMessageTask.Result; if (length > bytesRead) { // Give the process some time to fill the stdout buffer again Thread.Sleep(10); } } return messageBuffer; } private struct ResponsePair { /// <summary> /// Boolean to indicate if this response has a match. /// </summary> public bool FoundMatch { get; set; } /// <summary> /// The response /// </summary> public object Response { get; set; } } public override void Run(DebugAdapterRunner runner) { // Send the request string request = CreateDispatcherRequest(runner); // VSCode doesn't send /n at the end. If this is writeline, then concord hangs runner.DebugAdapter.StandardInput.Write(request); // Process + validate responses List<ResponsePair> responseList = new List<ResponsePair>(); int currentExpectedResponseIndex = 0; int previousExpectedResponseIndex = 0; // Loop until we have received as many expected responses as expected while (currentExpectedResponseIndex < this.ExpectedResponses.Count) { // Check if previous messages contained the expected response if (previousExpectedResponseIndex != currentExpectedResponseIndex) { DebugAdapterResponse expected = this.ExpectedResponses[currentExpectedResponseIndex]; // Only search responses in history list if we can ignore the response order. if (expected.IgnoreResponseOrder) { for (int i = 0; i < responseList.Count; i++) { ResponsePair responsePair = responseList[i]; // Make sure we have not seen this response and check to see if it the response we are expecting. if (!responsePair.FoundMatch && Utils.CompareObjects(expected.Response, responsePair.Response, expected.IgnoreOrder)) { expected.Match = responsePair.Response; responsePair.FoundMatch = true; break; } } // We found an expected response from a previous response. // Continue to next expectedResponse. if (expected.Match != null) { currentExpectedResponseIndex++; continue; } } } previousExpectedResponseIndex = currentExpectedResponseIndex; string receivedMessage = null; Exception getMessageExeception = null; try { receivedMessage = this.GetMessage( runner.DebugAdapter.StandardOutput.BaseStream, runner.ResponseTimeout, runner.DebugAdapter, runner); } catch (Exception e) { getMessageExeception = e; } if (getMessageExeception != null) { if (!runner.DebugAdapter.HasExited) { // If it hasn't exited yet, wait a little bit longer to make sure it isn't just about to exit try { runner.DebugAdapter.WaitForExit(500); } catch { } } string messageStart; if (runner.DebugAdapter.HasExited) { if (runner.HasAsserted()) { messageStart = string.Format(CultureInfo.CurrentCulture, "The debugger process has asserted and exited with code '{0}' without sending all expected responses. See test log for assert details.", runner.DebugAdapter.ExitCode); } else { messageStart = string.Format(CultureInfo.CurrentCulture, "The debugger process has exited with code '{0}' without sending all expected responses.", runner.DebugAdapter.ExitCode); } } else if (getMessageExeception is TimeoutException) { if (runner.HasAsserted()) { messageStart = "The debugger process has asserted. See test log for assert details."; } else { messageStart = "Expected response not found before timeout."; } } else { messageStart = "Exception while reading message from debug adpter. " + getMessageExeception.Message; } string expectedResponseText = string.Empty; for (int i = 0; i < ExpectedResponses.Count; i++) { string status; if (i < currentExpectedResponseIndex) status = "Found"; else if (i == currentExpectedResponseIndex) status = "Not Found"; else status = "Not searched yet"; expectedResponseText += string.Format(CultureInfo.CurrentCulture, "{0}. {1}: {2}\n", (i + 1), status, JsonConvert.SerializeObject(ExpectedResponses[i].Response)); } string actualResponseText = string.Empty; for (int i = 0; i < responseList.Count; i++) { actualResponseText += string.Format(CultureInfo.CurrentCulture, "{0}. {1}\n", (i + 1), JsonConvert.SerializeObject(responseList[i])); } string errorMessage = string.Format(CultureInfo.CurrentCulture, "{0}\nExpected =\n{1}\nActual Responses =\n{2}", messageStart, expectedResponseText, actualResponseText); throw new DARException(errorMessage); } try { DispatcherMessage dispatcherMessage = JsonConvert.DeserializeObject<DispatcherMessage>(receivedMessage); if (dispatcherMessage.type == "event") { DispatcherEvent dispatcherEvent = JsonConvert.DeserializeObject<DispatcherEvent>(receivedMessage); if (dispatcherEvent.eventType == "stopped") { runner.CurrentThreadId = dispatcherEvent.body.threadId; } var expected = this.ExpectedResponses[currentExpectedResponseIndex]; if (Utils.CompareObjects(expected.Response, dispatcherEvent, expected.IgnoreOrder)) { expected.Match = dispatcherEvent; currentExpectedResponseIndex++; } responseList.Add(new ResponsePair() { FoundMatch = expected.Match != null, Response = dispatcherEvent }); } else if (dispatcherMessage.type == "response") { DispatcherResponse dispatcherResponse = JsonConvert.DeserializeObject<DispatcherResponse>(receivedMessage); var expected = this.ExpectedResponses[currentExpectedResponseIndex]; if (Utils.CompareObjects(expected.Response, dispatcherResponse, expected.IgnoreOrder)) { expected.Match = dispatcherResponse; currentExpectedResponseIndex++; } responseList.Add(new ResponsePair() { FoundMatch = expected.Match != null, Response = dispatcherResponse }); } else if (dispatcherMessage.type == "request") { runner.HandleCallbackRequest(receivedMessage); } else { throw new DARException(String.Format(CultureInfo.CurrentCulture, "Unknown Dispatcher Message type: '{0}'", dispatcherMessage.type)); } } catch (JsonReaderException) { runner.AppendLineToDebugAdapterOutput("Response could not be parsed as json. This was the response:"); runner.AppendLineToDebugAdapterOutput(receivedMessage); throw; } } } } } <|start_filename|>src/DebugEngineHost/HostConfigurationStore.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.Win32; using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Microsoft.DebugEngineHost { public sealed class HostConfigurationStore { private const string DebuggerSectionName = "Debugger"; private const string LaunchersSectionName = "MILaunchers"; private string _engineId; private string _registryRoot; private RegistryKey _configKey; public HostConfigurationStore(string registryRoot) { if (string.IsNullOrEmpty(registryRoot)) throw new ArgumentNullException(nameof(registryRoot)); _registryRoot = registryRoot; _configKey = Registry.LocalMachine.OpenSubKey(registryRoot); if (_configKey == null) { throw new HostConfigurationException(registryRoot); } } /// <summary> /// Sets the Guid of the engine being hosted. This should only be set once for each HostConfigurationStore instance. /// </summary> /// <param name="value">The new engine GUID to set</param> public void SetEngineGuid(Guid value) { if (_engineId != null) { throw new InvalidOperationException(); } _engineId = value.ToString("B", CultureInfo.InvariantCulture); } // TODO: This should be removed. It is here only to make the Android launcher work for now public string RegistryRoot { get { return _registryRoot; } } public object GetEngineMetric(string metric) { if (_engineId == null) { throw new InvalidOperationException(); } return GetOptionalValue(@"AD7Metrics\Engine\" + _engineId, metric); } public void GetExceptionCategorySettings(Guid categoryId, out HostConfigurationSection categoryConfigSection, out string categoryName) { string subKeyName = @"AD7Metrics\Exception\" + categoryId.ToString("B", CultureInfo.InvariantCulture); RegistryKey categoryKey = _configKey.OpenSubKey(subKeyName); if (categoryKey == null) { throw new HostConfigurationException("$RegRoot$\\" + subKeyName); } categoryConfigSection = new HostConfigurationSection(categoryKey); categoryName = categoryKey.GetSubKeyNames().Single(); } /// <summary> /// Checks if logging is enabled, and if so returns a logger object. /// </summary> /// <param name="enableLoggingSettingName">[Optional] In VS, the name of the settings key to check if logging is enabled. If not specified, this will check 'Logging' in the AD7 Metrics.</param> /// <param name="logFileName">[Required] name of the log file to open if logging is enabled.</param> /// <returns>If no error then logging object. If file cannot be openened then throw an exception. Otherwise return an empty logger - the user can explictly reconfigure it later</returns> public HostLogger GetLogger(string enableLoggingSettingName, string logFileName) { if (string.IsNullOrEmpty(logFileName)) { throw new ArgumentNullException(nameof(logFileName)); } object enableLoggingValue; if (!string.IsNullOrEmpty(enableLoggingSettingName)) { enableLoggingValue = GetOptionalValue(DebuggerSectionName, enableLoggingSettingName); } else { enableLoggingValue = GetEngineMetric("EnableLogging"); } if (enableLoggingValue == null || !(enableLoggingValue is int) || ((int)enableLoggingValue) == 0) { return null; } return new HostLogger(HostLogger.GetStreamForName(logFileName, throwInUseError:false)); } public T GetDebuggerConfigurationSetting<T>(string settingName, T defaultValue) { return GetDebuggerConfigurationSetting(DebuggerSectionName, settingName, defaultValue); } public object GetCustomLauncher(string launcherTypeName) { string guidstr = GetDebuggerConfigurationSetting(LaunchersSectionName, launcherTypeName, Guid.Empty.ToString()); Guid clsidLauncher = new Guid(guidstr); if (clsidLauncher == Guid.Empty) { return null; } return HostLoader.VsCoCreateManagedObject(this, clsidLauncher); } private T GetDebuggerConfigurationSetting<T>(string sectionName, string settingName, T defaultValue) { object valueObj = GetOptionalValue(sectionName, settingName); if (valueObj == null) { return defaultValue; } T result; try { result = (T)valueObj; } catch (InvalidCastException) { Debug.Fail(string.Format(CultureInfo.CurrentCulture, "Failed to convert {0} to {1}", valueObj, typeof(T).Name)); result = defaultValue; } return result; } private object GetOptionalValue(string section, string valueName) { using (RegistryKey key = _configKey.OpenSubKey(section)) { if (key == null) { return null; } return key.GetValue(valueName); } } } } <|start_filename|>test/CppTests/debuggees/MacOSApp/src/Shared/main.cpp<|end_filename|> // // main.cpp // TestApp // // Created by <NAME> on 8/31/21. // #include "main.hpp" int main(int argc, char **argv) { int i = 0; printf("Hello from XCodeBuild\n"); i = i + 1; printf("Goodbye from XCodeBuild"); return 0; } <|start_filename|>test/Android/FunctionBreakPoints/FunctionBreakPoints/FunctionBreakPoints.NativeActivity/Header1.h<|end_filename|> #pragma once void Func(); int Func1(); void Func2(); class MyClass { public: int Func(); }; <|start_filename|>test/DebuggerTesting/OpenDebug/Commands/Responses/Source.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Newtonsoft.Json; namespace DebuggerTesting.OpenDebug.Commands.Responses { /// <summary> /// This data is used in multiple command args and responses /// </summary> public sealed class Source { [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public string name; [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public string path; [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public int? sourceReference; } } <|start_filename|>test/CppTests/debuggees/optimization/src/mylib_base.h<|end_filename|> #include <string> using namespace std; class myBase { public: virtual int DisplayAge(int age)=0; virtual string DisplayName(string firstName, string lastName)=0; }; <|start_filename|>test/Android/MultiThreadingCallStack/MultiThreadingCallStack/MultiThreadingCallStack.NativeActivity/Header1.h<|end_filename|> #pragma once void func(); void func1(); void func2(int x); void func3(int x, int y); void func4(); void func5(); <|start_filename|>test/CppTests/debuggees/exception/src/exception.cpp<|end_filename|> #include "exception.h" int myException::RaisedUnhandledException(int myvar) { int result = 10; int temp = -1; temp++; myvar = result / temp; result = EvalFunc(myvar, myvar); result++; return result; } int myException::RaisedHandledException(int a) { int global = 100; int result = 0; try { global++; RecursiveFunc(global); if (result == 0) { throw newException(global); } else { result = global / result; } } catch (newException ex) { result = a + global; int errorCode = ex.code; global++; } return result; } int myException::EvalFunc(int var1, int var2) { int result = var1 + var2; return result; } int myException::RecursiveFunc(int a) { if (a == 0) { return 1; } else { return RecursiveFunc(a - 1); } } void myException::RaisedThrowNewException() { throw newException(200); } void myException::RaisedReThrowException() { int var = 100; try { try { var = var - 100; if (var == 0) { RaisedThrowNewException(); } } catch (newException ex1) { int errorCode = ex1.code; var = EvalFunc(errorCode, errorCode); throw newException(var); } } catch (newException ex2) { int errorCode = ex2.code; var = 0; } } newException::newException(int c) { code = c; } newException::~newException() { code = 0; } <|start_filename|>test/CppTests/OpenDebug/CrossPlatCpp/InspectorValueExtensions.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using DebuggerTesting; using DebuggerTesting.OpenDebug.Commands; using DebuggerTesting.OpenDebug.Extensions; using System; using System.Globalization; using System.Text; using Xunit; namespace DebuggerTesting.OpenDebug.CrossPlatCpp { /// <summary> /// Provides helpers to give value types that are returned in different formats by different debugggers /// </summary> internal static class InspectorValueExtensions { #region Double public static void AssertValueAsDouble(this IVariableInspector valueInspector, double expectedValue) { AssertDoubleValue(valueInspector.DebuggerRunner.DebuggerSettings, valueInspector.Value, expectedValue); } public static void AssertEvaluateAsDouble(this IFrameInspector frameInspector, string expression, EvaluateContext context, double expectedValue) { string actualValue = frameInspector.Evaluate(expression, context); AssertDoubleValue(frameInspector.DebuggerRunner.DebuggerSettings, actualValue, expectedValue); } private static void AssertDoubleValue(IDebuggerSettings debuggerSettings, string actualValue, double expectedValue) { Assert.StartsWith(InspectorValueExtensions.GetDoubleValue(debuggerSettings, expectedValue), actualValue, StringComparison.Ordinal); } private static string GetDoubleValue(IDebuggerSettings debuggerSettings, double value) { if (double.IsPositiveInfinity(value)) { switch (debuggerSettings.DebuggerType) { case SupportedDebugger.Gdb_Gnu: case SupportedDebugger.Gdb_Cygwin: case SupportedDebugger.Gdb_MinGW: case SupportedDebugger.VsDbg: return "inf"; case SupportedDebugger.Lldb: return "+Inf"; default: Assert.True(false, "Debugger type doesn't have a specification for double value"); return null; } } switch (debuggerSettings.DebuggerType) { case SupportedDebugger.Gdb_Gnu: case SupportedDebugger.Gdb_Cygwin: case SupportedDebugger.Gdb_MinGW: case SupportedDebugger.Lldb: //10.1 //0 return value.ToString("R", CultureInfo.InvariantCulture); case SupportedDebugger.VsDbg: //10.100000000000000 //0.00000000000000000 return value.ToString("G10", CultureInfo.InvariantCulture); default: Assert.True(false, "Debugger type doesn't have a specification for double value"); return null; } } #endregion #region Float public static void AssertValueAsFloat(this IVariableInspector valueInspector, float expectedValue) { AssertFloatValue(valueInspector.DebuggerRunner.DebuggerSettings, valueInspector.Value, expectedValue); } public static void AssertEvaluateAsFloat(this IFrameInspector frameInspector, string expression, EvaluateContext context, float expectedValue) { string actualValue = frameInspector.Evaluate(expression, context); AssertFloatValue(frameInspector.DebuggerRunner.DebuggerSettings, actualValue, expectedValue); } private static void AssertFloatValue(IDebuggerSettings debuggerSettings, string actualValue, float expectedValue) { Assert.StartsWith(InspectorValueExtensions.GetFloatValue(debuggerSettings, expectedValue), actualValue, StringComparison.Ordinal); } private static string GetFloatValue(IDebuggerSettings debuggerSettings, float value) { if (float.IsPositiveInfinity(value)) { switch (debuggerSettings.DebuggerType) { case SupportedDebugger.Gdb_Gnu: case SupportedDebugger.Gdb_Cygwin: case SupportedDebugger.Gdb_MinGW: case SupportedDebugger.VsDbg: return "inf"; case SupportedDebugger.Lldb: return "+Inf"; default: Assert.True(false, "Debugger type doesn't have a specification for float value"); return null; } } switch (debuggerSettings.DebuggerType) { case SupportedDebugger.Gdb_Gnu: case SupportedDebugger.Gdb_Cygwin: case SupportedDebugger.Gdb_MinGW: case SupportedDebugger.Lldb: return value.ToString("R", CultureInfo.InvariantCulture); case SupportedDebugger.VsDbg: return value.ToString("G5", CultureInfo.InvariantCulture); default: Assert.True(false, "Debugger type doesn't have a specification for float value"); return null; } } #endregion #region Char public static void AssertValueAsChar(this IVariableInspector valueInspector, char expectedValue) { AssertCharValue(valueInspector.DebuggerRunner.DebuggerSettings, valueInspector.Value, expectedValue); } public static void AssertEvaluateAsChar(this IFrameInspector frameInspector, string expression, EvaluateContext context, char expectedValue) { string actualValue = frameInspector.Evaluate(expression, context); AssertCharValue(frameInspector.DebuggerRunner.DebuggerSettings, actualValue, expectedValue); } private static void AssertCharValue(IDebuggerSettings debuggerSettings, string actualValue, char expectedValue) { Assert.Equal(InspectorValueExtensions.GetCharValue(debuggerSettings, expectedValue), actualValue); } private static string GetCharValue(IDebuggerSettings debuggerSettings, char value) { // Non-printable chars if (value < ' ') { switch (debuggerSettings.DebuggerType) { case SupportedDebugger.Gdb_Gnu: case SupportedDebugger.Gdb_Cygwin: case SupportedDebugger.Gdb_MinGW: // 0 '\000' return @"{0} '\{0:D3}'".FormatInvariantWithArgs((int)value); case SupportedDebugger.Lldb: case SupportedDebugger.VsDbg: // 0 '\0' return @"{0} '\{0}'".FormatInvariantWithArgs((int)value); default: Assert.True(false, "Debugger type doesn't have a specification for char value"); return null; } } // Printable chars switch (debuggerSettings.DebuggerType) { case SupportedDebugger.Gdb_Gnu: case SupportedDebugger.Gdb_Cygwin: case SupportedDebugger.Gdb_MinGW: return EscapeIfNeeded(c => c == '\'', value); case SupportedDebugger.VsDbg: return EscapeIfNeeded(c => c == '"', value); case SupportedDebugger.Lldb: return "{0} '{1}'".FormatInvariantWithArgs((int)value, value); default: Assert.True(false, "Debugger type doesn't have a specification for char value"); return null; } } private static string EscapeIfNeeded(Func<char, bool> shouldEscape, char value) { string valueAsString = shouldEscape(value) ? "\\{0}".FormatInvariantWithArgs(value) : "{0}".FormatInvariantWithArgs(value); return "{0} '{1}'".FormatInvariantWithArgs((int)value, valueAsString); } #endregion #region WChar public static void AssertValueAsWChar(this IVariableInspector valueInspector, char expectedValue) { AssertWCharValue(valueInspector.DebuggerRunner.DebuggerSettings, valueInspector.Value, expectedValue); } public static void AssertEvaluateAsWChar(this IFrameInspector frameInspector, string expression, EvaluateContext context, char expectedValue) { string actualValue = frameInspector.Evaluate(expression, context); AssertWCharValue(frameInspector.DebuggerRunner.DebuggerSettings, actualValue, expectedValue); } private static void AssertWCharValue(IDebuggerSettings debuggerSettings, string actualValue, char expectedValue) { Assert.Equal(InspectorValueExtensions.GetWCharValue(debuggerSettings, expectedValue), actualValue); } private static string GetWCharValue(IDebuggerSettings debuggerSettings, char value) { switch (debuggerSettings.DebuggerType) { case SupportedDebugger.Gdb_Gnu: case SupportedDebugger.Gdb_Cygwin: case SupportedDebugger.Gdb_MinGW: return "{0} L'{1}'".FormatInvariantWithArgs((int)value, value); case SupportedDebugger.Lldb: return "L'{0}'".FormatInvariantWithArgs(value); case SupportedDebugger.VsDbg: return "{0} '{1}'".FormatInvariantWithArgs((int)value, value); default: Assert.True(false, "Debugger type doesn't have a specification for wchar value"); return null; } } #endregion #region Undefined Variable public static void AssertEvaluateAsError(this IFrameInspector frameInspector, string variableName, EvaluateContext context) { string actualErrorMessage = frameInspector.Evaluate(variableName, context); string expectedErrorMessage = GetUndefinedError(frameInspector.DebuggerRunner.DebuggerSettings, variableName); Assert.Contains(expectedErrorMessage, actualErrorMessage, StringComparison.OrdinalIgnoreCase); } private static string GetUndefinedError(IDebuggerSettings debuggerSettings, string variableName) { switch (debuggerSettings.DebuggerType) { case SupportedDebugger.Gdb_Gnu: case SupportedDebugger.Gdb_Cygwin: case SupportedDebugger.Gdb_MinGW: return "-var-create: unable to create variable object"; case SupportedDebugger.Lldb: return "error: error: use of undeclared identifier '{0}'".FormatInvariantWithArgs(variableName); case SupportedDebugger.VsDbg: return @"identifier ""{0}"" is undefined".FormatInvariantWithArgs(variableName); default: Assert.True(false, "This debugger type doesn't have a error message test."); return null; } } #endregion #region Vector public static void AssertValueAsVector(this IVariableInspector valueInspector, int vectorCount) { AssertVectorValue(valueInspector.DebuggerRunner.DebuggerSettings, valueInspector.Value, vectorCount); } public static void AssertEvaluateAsVector(this IFrameInspector frameInspector, string expression, EvaluateContext context, int vectorCount) { string actualValue = frameInspector.Evaluate(expression, context); AssertVectorValue(frameInspector.DebuggerRunner.DebuggerSettings, actualValue, vectorCount); } private static void AssertVectorValue(IDebuggerSettings debuggerSettings, string actualValue, int vectorCount) { Assert.Equal(InspectorValueExtensions.GetVectorValue(debuggerSettings, vectorCount), actualValue); } private static string GetVectorValue(IDebuggerSettings debuggerSettings, int vectorCount) { switch (debuggerSettings.DebuggerType) { case SupportedDebugger.Gdb_Gnu: case SupportedDebugger.Gdb_Cygwin: case SupportedDebugger.Gdb_MinGW: return "{...}"; case SupportedDebugger.VsDbg: return "{{ size={0} }}".FormatInvariantWithArgs(vectorCount); case SupportedDebugger.Lldb: return "size={0}".FormatInvariantWithArgs(vectorCount); default: Assert.True(false, "This debugger type doesn't have a vector format."); return null; } } #endregion #region Object public static void AssertValueAsObject(this IVariableInspector valueInspector, params string[] expectedObjectProperties) { AssertObjectValue(valueInspector.DebuggerRunner.DebuggerSettings, valueInspector.Value, expectedObjectProperties); } public static void AssertEvaluateAsObject(this IFrameInspector frameInspector, string expression, EvaluateContext context, params string[] expectedObjectProperties) { string actualValue = frameInspector.Evaluate(expression, context); AssertObjectValue(frameInspector.DebuggerRunner.DebuggerSettings, actualValue, expectedObjectProperties); } private static void AssertObjectValue(IDebuggerSettings debuggerSettings, string actualValue, params string[] expectedObjectProperties) { Assert.Equal(InspectorValueExtensions.GetObjectValue(debuggerSettings, expectedObjectProperties), actualValue); } private static string GetObjectValue(IDebuggerSettings debuggerSettings, params string[] properties) { if (properties.Length % 2 != 0) { throw new ArgumentException("Missing a property!"); } switch (debuggerSettings.DebuggerType) { case SupportedDebugger.Gdb_Gnu: case SupportedDebugger.Gdb_Cygwin: case SupportedDebugger.Gdb_MinGW: case SupportedDebugger.Lldb: return "{...}"; case SupportedDebugger.VsDbg: StringBuilder sb = new StringBuilder("{"); for (int i = 0; i < properties.Length; i += 2) { string name = properties[i]; string value = properties[i + 1]; sb.Append(name); sb.Append("="); sb.Append(value); sb.Append(" "); } sb.Append("}"); return sb.ToString(); default: Assert.True(false, "This debugger type doesn't have an object format."); return null; } } #endregion #region IntArray public static void AssertValueAsIntArray(this IVariableInspector valueInspector, params int[] expectedValue) { AssertIntArrayValue(valueInspector.DebuggerRunner.DebuggerSettings, valueInspector.Value, expectedValue); } public static void AssertEvaluateAsIntArray(this IFrameInspector frameInspector, string expression, EvaluateContext context, params int[] expectedValue) { string actualValue = frameInspector.Evaluate(expression, context); AssertIntArrayValue(frameInspector.DebuggerRunner.DebuggerSettings, actualValue, expectedValue); } private static void AssertIntArrayValue(IDebuggerSettings debuggerSettings, string actualValue, params int[] expectedValue) { Assert.Contains(GetIntArray(debuggerSettings, expectedValue), actualValue, StringComparison.Ordinal); } private static string GetIntArray(IDebuggerSettings debuggerSettings, params int[] value) { switch (debuggerSettings.DebuggerType) { case SupportedDebugger.Gdb_Gnu: case SupportedDebugger.Gdb_Cygwin: case SupportedDebugger.Gdb_MinGW: case SupportedDebugger.Lldb: return "[{0}]".FormatInvariantWithArgs(value.Length); case SupportedDebugger.VsDbg: StringBuilder sb = new StringBuilder("{"); for (int i = 0; i < value.Length; i++) { if (i != 0) sb.Append(", "); sb.Append(value[i]); } sb.Append("}"); return sb.ToString(); default: Assert.True(false, "This debugger type doesn't have an object format."); return null; } } #endregion #region String / char* /// <summary> /// This method has only been used for const char* so far. /// If required to work with other string-like types, please test it and /// expand this method to support those types. /// </summary> /// <param name="frameInspector"></param> /// <param name="expression"></param> /// <param name="context"></param> /// <param name="expectedValue"></param> public static void AssertEvaluateAsString( this IFrameInspector frameInspector, string expression, EvaluateContext context, string expectedValue) { if (expectedValue == null) { AssertEvaluateAsNull(frameInspector, expression, context); return; } for (int i = 0; i <= expectedValue.Length; i++) { string actualValue = frameInspector.Evaluate( string.Format(CultureInfo.InvariantCulture, "{0}[{1}]", expression, i), context); char expectedChar; ; if (i == expectedValue.Length) { expectedChar = '\0'; } else { expectedChar = expectedValue[i]; } AssertCharValue(frameInspector.DebuggerRunner.DebuggerSettings, actualValue, expectedChar); } } #endregion #region Pointer /// <summary> /// Checks whether a pointer value is null. /// This function will return incorrect results if not called with an expression of type pointer. /// </summary> /// <param name="frameInspector"></param> /// <param name="expression"></param> /// <param name="context"></param> public static void AssertEvaluateAsNull( this IFrameInspector frameInspector, string expression, EvaluateContext context) { string actualValue = frameInspector.Evaluate( string.Format(CultureInfo.InvariantCulture, "{0}==0", expression), context); Assert.Equal("true", actualValue); } #endregion } } <|start_filename|>test/DebuggerTesting/Utilities/UDebug.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Text.RegularExpressions; namespace DebuggerTesting { public enum DebugUIResult { Unset = 0, Debug, Ignore, IgnoreAll, EndProcess, } public interface IDebugFailUI { DebugUIResult ShowFailure(string message, string callLocation, string exception, string callStack); } public static class UDebug { [Conditional("DEBUG")] [DebuggerHidden] public static void Assert(bool condition, string format, params string[] parameters) { if (!condition) UDebug.Fail(format, parameters); } [Conditional("DEBUG")] [DebuggerHidden] public static void AssertNotNull<T>(T value, string format, params string[] parameters) where T : class { if (value == null) UDebug.Fail(format, parameters); } [Conditional("DEBUG")] [DebuggerHidden] public static void AssertNotNullOrEmpty(string value, string format, params string[] parameters) { if (string.IsNullOrEmpty(value)) UDebug.Fail(format, parameters); } [Conditional("DEBUG")] [DebuggerHidden] public static void AssertService<T>(T service) where T : class { if (service == null) UDebug.Fail("Service {0} could not be loaded.", typeof(T).Name); } [Conditional("DEBUG")] [DebuggerHidden] public static void Fail(string format, params object[] parameters) { UDebug.Fail(null, format, parameters); } [Conditional("DEBUG")] [DebuggerHidden] public static void Fail(Exception ex) { UDebug.Fail(ex, string.Empty); } [Conditional("DEBUG")] [DebuggerHidden] public static void Fail(string message) { UDebug.Fail((Exception)null, message); } private static bool? showFailUI; private static bool? ShowFailUI { get { return showFailUI; } set { // Only allow the value to be set once. if (null == showFailUI) showFailUI = value; } } [DebuggerHidden] [Conditional("DEBUG")] public static void Fail(Exception ex, string format, params string[] parameters) { #if DEBUG string message = null; string exception = null; string callStack = null; if (!string.IsNullOrEmpty(format)) message = string.Format(CultureInfo.InvariantCulture, format, parameters); if (ex != null) { exception = ExceptionToString(ex, 0, false); callStack = ExceptionToCallStack(ex); } FailInternal(message, exception, callStack); #endif } [DebuggerHidden] [Conditional("DEBUG")] private static void FailInternal(string message, string exception = null, string callStack = null) { #if DEBUG if (callStack == null) { callStack = GetCurrentCallStack(); } string callLocation = GetFirstUserFrame(); if (false != ShowFailUI) { message = message ?? string.Empty; message = "Failure: " + message; // Are we logging to a file? string logFile = Environment.GetEnvironmentVariable("vsassert"); if (string.IsNullOrEmpty(logFile)) { ShowFailureInternal(message, callLocation, exception, callStack); } else { using (StreamWriter file = File.AppendText(logFile)) { file.WriteLine(message); } } } else throw new Exception(message); #endif } #if DEBUG private static HashSet<string> IgnoreTable = new HashSet<string>(); /// <summary> /// A way to override default Debug Fail UI /// </summary> public static IDebugFailUI DebugFailUI { get; set; } [DebuggerStepThrough] [DebuggerHidden] private static void ShowFailureInternal(string message, string callLocation, string exception, string callStack) { if (IgnoreTable.Contains(callLocation)) return; message = message ?? string.Empty; if (DebugFailUI == null) DebugFailUI = new DefaultDebugFailUI(); DebugUIResult result = DebugUIResult.Ignore; try { result = DebugFailUI.ShowFailure(message, callLocation, exception, callStack); } catch (InvalidOperationException) { } switch (result) { case DebugUIResult.Debug: if (!Debugger.IsAttached) { Debugger.Launch(); } Debugger.Break(); break; case DebugUIResult.EndProcess: // Kill the process Process.GetCurrentProcess().Kill(); break; case DebugUIResult.IgnoreAll: if (!string.IsNullOrWhiteSpace(callLocation)) IgnoreTable.Add(callLocation); break; } } [DebuggerHidden] private static string ExceptionToCallStack(Exception ex) { return ExceptionToCallStack(ex, 0); } [DebuggerHidden] private static string ExceptionToCallStack(Exception ex, int depth = 0) { StringBuilder sb = new StringBuilder(); // Runtime Invoke may put the callstack information in the Data dictionary. if (ex.Data.Contains("CustomStackTrace")) { string stackTrace = ex.Data["CustomStackTrace"] as string; if (!string.IsNullOrEmpty(stackTrace)) { sb.Append(ex.GetType().Name); // Name of the exception type sb.AppendLine(" Call Stack (from thread): "); foreach (var line in stackTrace.Split(new string[] { " at " }, StringSplitOptions.RemoveEmptyEntries)) { string trimLine = line.Trim(); if (!string.IsNullOrEmpty(trimLine)) { sb.Append(" "); sb.AppendLine(trimLine); } } } } // The stack trace of where the exception was raised (not where the assert was raised) if (!string.IsNullOrEmpty(ex.StackTrace)) { sb.Append(ex.GetType().Name); // Name of the exception type sb.AppendLine(" Call Stack: "); foreach (var line in ex.StackTrace.Split(new string[] { " at " }, StringSplitOptions.RemoveEmptyEntries)) { string trimLine = line.Trim(); if (!string.IsNullOrEmpty(trimLine)) { sb.AppendLine(trimLine); } } } // Provide more information on common exceptions DetailedExceptionHelper(sb, ex, depth, string.Empty); // The inner exceptions if (ex.InnerException != null) { string innerCallStack = ExceptionToCallStack(ex.InnerException, depth + 1); if (!string.IsNullOrEmpty(innerCallStack)) { sb.AppendLine(); sb.Append(innerCallStack); } } return sb.ToString(); } #endif //DEBUG [DebuggerHidden] public static string ExceptionToString(Exception ex) { return ExceptionToString(ex, 0, true); } /// <summary> /// Converts an exception to a string that contains more useful /// information than the default ex.ToString() /// </summary> [DebuggerHidden] private static string ExceptionToString(Exception ex, int depth, bool showCallStack) { if (ex == null) return string.Empty; string padding = new string(' ', depth * 4); StringBuilder sb = new StringBuilder(); sb.Append(padding); sb.Append(ex.GetType().Name); // Name of the exception type sb.Append(": "); // The message string message = AddPadding(ex.Message, padding); if (!string.IsNullOrEmpty(message)) { sb.AppendLine(message); } else { sb.AppendLine(); } if (showCallStack) { // The stack trace of where the exception was raised (not where the assert was raised) if (!string.IsNullOrEmpty(ex.StackTrace)) { sb.AppendLine(); foreach (var line in ex.StackTrace.Split(new string[] { " at " }, StringSplitOptions.RemoveEmptyEntries)) { string trimLine = line.Trim(); if (!string.IsNullOrEmpty(trimLine)) { sb.AppendLine(trimLine); } } } } // Provide more information on common exceptions DetailedExceptionHelper(sb, ex, depth, padding); // The inner exceptions if (ex.InnerException != null) { sb.Append(padding); sb.AppendLine("Inner Exception: "); sb.Append(ExceptionToString(ex.InnerException, depth + 1, showCallStack: false)); } return sb.ToString(); } // Provide more information on common exceptions private static void DetailedExceptionHelper(StringBuilder sb, Exception ex, int depth, string padding) { // Reflection type loads occur a lot in this code, so give more info // on why they failed if (ex is ReflectionTypeLoadException) { foreach (var exLoader in (ex as ReflectionTypeLoadException).LoaderExceptions.Take(5)) { sb.AppendLine(); sb.Append(padding); sb.AppendLine("Loader exception: "); sb.Append(ExceptionToString(exLoader, depth + 1, showCallStack: false)); } } else if (ex is FileNotFoundException) { FileNotFoundException exception = (FileNotFoundException)ex; bool hasFileName = !String.IsNullOrEmpty(exception.FileName); bool hasFusionLog = false; #if !CORECLR hasFusionLog = !String.IsNullOrEmpty(exception.FusionLog); #endif if (hasFileName || hasFusionLog) { sb.AppendLine(); if (hasFileName) { sb.Append(padding); sb.Append("File: "); sb.AppendLine(exception.FileName); } #if !CORECLR if (hasFusionLog) { sb.Append(padding); sb.Append("Fusion log: "); sb.AppendLine(exception.FusionLog); } #endif } } else if (ex is AggregateException) { AggregateException exception = (AggregateException)ex; if (exception.InnerExceptions != null) { foreach (var exInner in exception.InnerExceptions.Take(5)) { sb.AppendLine(); sb.Append(padding); sb.AppendLine("Aggregate exception: "); sb.Append(ExceptionToString(exInner, depth + 1, showCallStack: false)); } } } } // Add padding before new lines to make indents consistent private static string AddPadding(string message, string padding) { message = message.Trim(); // Change tabs to spaces message = Regex.Replace(message, "\t", " "); // Handle any kind of new line that is spewed out of an exception // Change everything to '\n' first, then back to NewLine (AKA \r\n, AKA CRLF) message = Regex.Replace(message, Environment.NewLine, "\n"); message = Regex.Replace(message, "\r", "\n"); message = Regex.Replace(message, "\n", Environment.NewLine + padding); return message; } #if DEBUG static readonly private Type[] ClassesToIgnore = { typeof(UDebug), typeof(Parameter), typeof(DefaultDebugFailUI), typeof(Environment) }; [DebuggerHidden] private static string GetFirstUserFrame() { return GetCurrentCallStack(justFirstLine: true); } [DebuggerHidden] private static string GetCurrentCallStack() { return GetCurrentCallStack(justFirstLine: false); } [DebuggerHidden] private static string GetCurrentCallStack(bool justFirstLine) { // Use the Environment.StackTrace API to get the stack trace. IEnumerable<string> frames = Environment.StackTrace.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries); foreach (Type ignoreType in ClassesToIgnore) { frames = frames.Where(x => x.IndexOf(ignoreType.FullName, StringComparison.OrdinalIgnoreCase) < 0); } // Remove " at " part of string frames = frames.Select(x => x.Substring(6).Trim()); if (justFirstLine) return frames.FirstOrDefault() ?? string.Empty; return string.Join(Environment.NewLine, frames) ?? string.Empty; } #endif } #if DEBUG /// <summary> /// Implements the Debug Fail UI for the UDebug class /// </summary> internal class DefaultDebugFailUI : IDebugFailUI { DebugUIResult IDebugFailUI.ShowFailure(string message, string callLocation, string exception, string callStack) { Debug.Fail(exception + ": " + message, callStack); return DebugUIResult.Ignore; } } #endif //DEBUG } <|start_filename|>src/MIDebugPackage/Guids.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // MUST match guids.h using System; namespace Microsoft.MIDebugPackage { internal static class GuidList { public const string guidMIDebugPackagePkgString = "7a28ceda-da3e-4172-b19a-bb9c810046a6"; public const string guidMIDebugPackageCmdSetString = "eb4e4965-e07f-46d0-afcc-aa4dd43a5336"; public static readonly Guid guidMIDebugPackageCmdSet = new Guid(guidMIDebugPackageCmdSetString); }; } <|start_filename|>test/CppTests/Tests/MemoryTests.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Threading; using DebuggerTesting; using DebuggerTesting.Compilation; using DebuggerTesting.OpenDebug; using DebuggerTesting.OpenDebug.Commands; using DebuggerTesting.OpenDebug.CrossPlatCpp; using DebuggerTesting.OpenDebug.Events; using DebuggerTesting.OpenDebug.Extensions; using DebuggerTesting.Ordering; using DebuggerTesting.Utilities; using Xunit; using Xunit.Abstractions; namespace CppTests.Tests { [TestCaseOrderer(DependencyTestOrderer.TypeName, DependencyTestOrderer.AssemblyName)] public class MemoryTests : TestBase { #region Constructor public MemoryTests(ITestOutputHelper outputHelper) : base(outputHelper) { } #endregion #region Methods [Theory] [RequiresTestSettings] public void CompileKitchenSinkForBreakpointTests(ITestSettings settings) { this.TestPurpose("Compiles the kitchen sink debuggee."); this.WriteSettings(settings); IDebuggee debuggee = SinkHelper.OpenAndCompile(this, settings.CompilerSettings, DebuggeeMonikers.KitchenSink.Breakpoint); } [Theory] [DependsOnTest(nameof(CompileKitchenSinkForBreakpointTests))] [RequiresTestSettings] public void InstructionBreakpointsBasic(ITestSettings settings) { this.TestPurpose("Tests basic operation of instruction breakpoints"); this.WriteSettings(settings); IDebuggee debuggee = SinkHelper.Open(this, settings.CompilerSettings, DebuggeeMonikers.KitchenSink.Breakpoint); using (IDebuggerRunner runner = CreateDebugAdapterRunner(settings)) { this.Comment("Configure launch"); runner.Launch(settings.DebuggerSettings, debuggee, "-fCalling"); SourceBreakpoints mainBreakpoints = debuggee.Breakpoints(SinkHelper.Main, 33); this.Comment("Set initial breakpoints"); runner.SetBreakpoints(mainBreakpoints); this.Comment("Launch and run until first breakpoint"); runner.Expects.HitBreakpointEvent(SinkHelper.Main, 33) .AfterConfigurationDone(); string ip = string.Empty; this.Comment("Inspect the stack and try evaluation."); using (IThreadInspector inspector = runner.GetThreadInspector()) { this.Comment("Get the stack trace"); IFrameInspector mainFrame = inspector.Stack.First(); inspector.AssertStackFrameNames(true, "main.*"); this.WriteLine("Main frame: {0}", mainFrame); ip = mainFrame?.InstructionPointerReference; } Assert.False(string.IsNullOrEmpty(ip)); // Send Disassemble Request to get the current instruction and next one. this.WriteLine("Disassemble to get current and next instruction."); IEnumerable<IDisassemblyInstruction> instructions = runner.Disassemble(ip, 2); // Validate that we got two instructions. Assert.Equal(2, instructions.Count()); // Get the next instruction's address string nextIPAddress = instructions.Last().Address; Assert.False(string.IsNullOrEmpty(nextIPAddress)); // Set an instruction breakpoint this.Comment("Set Instruction Breakpoint"); InstructionBreakpoints instruction = new InstructionBreakpoints(new string[] { nextIPAddress }); runner.SetInstructionBreakpoints(instruction); // Expect it to be hit. runner.Expects.HitInstructionBreakpointEvent(nextIPAddress).AfterContinue(); // Get the Stack Trace to validate the current frame's ipReference is the one set from the InstructionBp using (IThreadInspector inspector = runner.GetThreadInspector()) { this.Comment("Get the instruction bp's stack trace"); IFrameInspector mainFrame = inspector.Stack.First(); ip = mainFrame?.InstructionPointerReference; Assert.False(string.IsNullOrEmpty(ip)); Assert.Equal(nextIPAddress, ip); } this.Comment("Continue until end"); runner.Expects.ExitedEvent() .TerminatedEvent() .AfterContinue(); runner.DisconnectAndVerify(); } } #endregion } } <|start_filename|>src/AndroidDebugLauncher/RegistryRoot.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace AndroidDebugLauncher { internal static class RegistryRoot { private static string s_value; static public string Value { get { if (s_value == null) { Debug.Fail("RegistryRoot.Value queried before it is set"); throw new InvalidOperationException(); } return s_value; } } internal static void Set(string registryRoot) { // Initialize the registry root the first time this is called. Subsequent calls are a no-op. Interlocked.CompareExchange<string>(ref s_value, registryRoot, null); Debug.Assert(s_value == registryRoot); } } } <|start_filename|>test/CppTests/Tests/ExecutionTests.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Linq; using DebuggerTesting; using DebuggerTesting.Compilation; using DebuggerTesting.OpenDebug; using DebuggerTesting.OpenDebug.Commands; using DebuggerTesting.OpenDebug.CrossPlatCpp; using DebuggerTesting.OpenDebug.Events; using DebuggerTesting.OpenDebug.Extensions; using DebuggerTesting.Ordering; using Xunit; using Xunit.Abstractions; namespace CppTests.Tests { [TestCaseOrderer(DependencyTestOrderer.TypeName, DependencyTestOrderer.AssemblyName)] public class ExecutionTests : TestBase { #region Constructor public ExecutionTests(ITestOutputHelper outputHelper) : base(outputHelper) { } #endregion [Theory] [RequiresTestSettings] public void CompileKitchenSinkForExecution(ITestSettings settings) { this.TestPurpose("Compiles the kitchen sink debuggee for execution tests."); this.WriteSettings(settings); IDebuggee debuggee = SinkHelper.OpenAndCompile(this, settings.CompilerSettings, DebuggeeMonikers.KitchenSink.Execution); } [Theory] [DependsOnTest(nameof(CompileKitchenSinkForExecution))] [RequiresTestSettings] public void ExecutionStepBasic(ITestSettings settings) { this.TestPurpose("Verify basic step in/over/out should work during debugging"); this.WriteSettings(settings); this.Comment("Open the kitchen sink debuggee for execution tests."); IDebuggee debuggee = SinkHelper.Open(this, settings.CompilerSettings, DebuggeeMonikers.KitchenSink.Execution); using (IDebuggerRunner runner = CreateDebugAdapterRunner(settings)) { this.Comment("Configure launch"); runner.Launch(settings.DebuggerSettings, debuggee, "-fCalling"); this.Comment("Set initial source breakpoints"); SourceBreakpoints bps = debuggee.Breakpoints(SinkHelper.Main, 21, 33); runner.SetBreakpoints(bps); this.Comment("Launch and run until hit the first entry"); runner.Expects.HitBreakpointEvent(SinkHelper.Main, 21).AfterConfigurationDone(); this.Comment("Step over the function"); runner.Expects.HitStepEvent(SinkHelper.Main, 23).AfterStepOver(); this.Comment("Continue to hit the second entry"); runner.Expects.HitBreakpointEvent(SinkHelper.Main, 33).AfterContinue(); this.Comment("Step in the function"); runner.ExpectStepAndStepToTarget(SinkHelper.Feature, startLine: 19, targetLine: 20).AfterStepIn(); this.Comment("Step over the function"); runner.Expects.HitStepEvent(SinkHelper.Feature, 21).AfterStepOver(); runner.Expects.HitStepEvent(SinkHelper.Feature, 22).AfterStepOver(); this.Comment("Step in the function"); runner.ExpectStepAndStepToTarget(SinkHelper.Calling, startLine: 47, targetLine: 48).AfterStepIn(); this.Comment("Step out the function"); runner.ExpectStepAndStepToTarget(SinkHelper.Feature, startLine: 22, targetLine: 23).AfterStepOut(); this.Comment("Continue running at the end of application"); runner.Expects.ExitedEvent() .TerminatedEvent() .AfterContinue(); this.Comment("Verify debugger and debuggee closed"); runner.DisconnectAndVerify(); } } [Theory] [DependsOnTest(nameof(CompileKitchenSinkForExecution))] [RequiresTestSettings] public void ExecutionStepRecursiveCall(ITestSettings settings) { this.TestPurpose("Verify steps should work when debugging recursive call"); this.WriteSettings(settings); this.Comment("Open the kitchen sink debuggee for execution tests."); IDebuggee debuggee = SinkHelper.Open(this, settings.CompilerSettings, DebuggeeMonikers.KitchenSink.Execution); using (IDebuggerRunner runner = CreateDebugAdapterRunner(settings)) { this.Comment("Configure launch"); runner.Launch(settings.DebuggerSettings, debuggee, "-fCalling"); this.Comment("Set initial function breakpoints"); FunctionBreakpoints funcBp = new FunctionBreakpoints("Calling::CoreRun()"); runner.SetFunctionBreakpoints(funcBp); this.Comment("Launch and run until hit function breakpoint in the entry of calling"); runner.ExpectBreakpointAndStepToTarget(SinkHelper.Calling, startLine: 47, targetLine: 48).AfterConfigurationDone(); this.Comment("Step over to go to the entry of recursive call"); runner.Expects.HitStepEvent(SinkHelper.Calling, 49).AfterStepOver(); this.Comment("Step in the recursive call"); runner.ExpectStepAndStepToTarget(SinkHelper.Calling, startLine: 25, targetLine: 26).AfterStepIn(); using (IThreadInspector threadInspector = runner.GetThreadInspector()) { this.Comment("Set count = 2"); IFrameInspector currentFrame = threadInspector.Stack.First(); currentFrame.GetVariable("count").Value = "2"; this.Comment("Verify there is only one 'recursiveCall' frames"); threadInspector.AssertStackFrameNames(true, "recursiveCall.*", "Calling::CoreRun.*", "Feature::Run.*", "main.*"); } this.Comment("Step over and then step in the recursive call once again"); runner.Expects.HitStepEvent(SinkHelper.Calling, 29).AfterStepOver(); runner.ExpectStepAndStepToTarget(SinkHelper.Calling, startLine: 25, targetLine: 26).AfterStepIn(); using (IThreadInspector threadInspector = runner.GetThreadInspector()) { this.Comment("Verify there are two 'recursiveCall' frames"); threadInspector.AssertStackFrameNames(true, "recursiveCall.*", "recursiveCall.*", "Calling::CoreRun.*", "Feature::Run.*", "main.*"); this.Comment("Set a source breakpoint in recursive call"); SourceBreakpoints srcBp = debuggee.Breakpoints(SinkHelper.Calling, 26); runner.SetBreakpoints(srcBp); } this.Comment("Step over the recursive call and hit the source breakpoint"); runner.Expects.HitStepEvent(SinkHelper.Calling, 29).AfterStepOver(); runner.Expects.HitBreakpointEvent(SinkHelper.Calling, 26).AfterStepOver(); using (IThreadInspector threadInspector = runner.GetThreadInspector()) { this.Comment("Verify there are three 'recursiveCall' frames"); threadInspector.AssertStackFrameNames(true, "recursiveCall.*", "recursiveCall.*", "recursiveCall.*", "Calling::CoreRun.*", "Feature::Run.*", "main.*"); } this.Comment("Try to step out twice from recursive call"); runner.ExpectStepAndStepToTarget(SinkHelper.Calling, 29, 30).AfterStepOut(); runner.ExpectStepAndStepToTarget(SinkHelper.Calling, 29, 30).AfterStepOut(); using (IThreadInspector threadInspector = runner.GetThreadInspector()) { this.Comment("Verify 'recursiveCall' return back only one frame"); threadInspector.AssertStackFrameNames(true, "recursiveCall.*", "Calling::CoreRun.*", "Feature::Run.*", "main.*"); } this.Comment("Step over from recursive call"); runner.ExpectStepAndStepToTarget(SinkHelper.Calling, 49, 50).AfterStepOver(); using (IThreadInspector threadInspector = runner.GetThreadInspector()) { this.Comment("Verify there is not 'recursiveCall' frame"); threadInspector.AssertStackFrameNames(true, "Calling::CoreRun.*", "Feature::Run.*", "main.*"); } this.Comment("Verify stop debugging"); runner.DisconnectAndVerify(); } } [Theory] [DependsOnTest(nameof(CompileKitchenSinkForExecution))] [RequiresTestSettings] // TODO: Re-enable for VsDbg and Gdb_Gnu [UnsupportedDebugger(SupportedDebugger.Gdb_Cygwin | SupportedDebugger.Gdb_MinGW | SupportedDebugger.Gdb_Gnu | SupportedDebugger.Lldb | SupportedDebugger.VsDbg, SupportedArchitecture.x86 | SupportedArchitecture.x64)] public void ExecutionAsyncBreak(ITestSettings settings) { this.TestPurpose("Verify break all should work run function"); this.WriteSettings(settings); this.Comment("Open the kitchen sink debuggee for execution tests."); IDebuggee debuggee = SinkHelper.Open(this, settings.CompilerSettings, DebuggeeMonikers.KitchenSink.Execution); using (IDebuggerRunner runner = CreateDebugAdapterRunner(settings)) { this.Comment("Configure launch"); runner.Launch(settings.DebuggerSettings, debuggee, "-fNonTerminating", "-fCalling"); this.Comment("Try to break all"); StoppedEvent breakAllEvent = new StoppedEvent(StoppedReason.Pause); runner.Expects.Event(breakAllEvent).AfterAsyncBreak(); this.WriteLine("Break all stopped on:"); this.WriteLine(breakAllEvent.ActualEvent.ToString()); this.Comment("Set a breakpoint while breaking code"); runner.SetBreakpoints(debuggee.Breakpoints(SinkHelper.NonTerminating, 28)); this.Comment("Start running after the async break and then hit the breakpoint"); runner.Expects.HitBreakpointEvent(SinkHelper.NonTerminating, 28).AfterContinue(); this.Comment("Evaluate the shouldExit member to true to stop the infinite loop."); using (IThreadInspector threadInspector = runner.GetThreadInspector()) { IFrameInspector firstFrame = threadInspector.Stack.First(); this.WriteLine(firstFrame.ToString()); firstFrame.GetVariable("shouldExit").Value = "true"; } this.Comment("Continue running at the end of application"); runner.Expects.ExitedEvent().TerminatedEvent().AfterContinue(); this.Comment("Verify debugger and debuggee closed"); runner.DisconnectAndVerify(); } } } } <|start_filename|>test/DebuggerTesting/SupportedDebugger.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; namespace DebuggerTesting { [Flags] public enum SupportedDebugger { Gdb_Gnu = 0x1, Gdb_Cygwin = 0x2, Gdb_MinGW = 0x4, Lldb = 0x8, VsDbg = 0x10, } } <|start_filename|>src/OpenDebugAD7/Telemetry/TelemetryHelper.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; namespace OpenDebugAD7 { internal static class TelemetryHelper { /// <summary> /// Ensures event name is properly prefixed. /// </summary> /// <param name="eventName">Name of the event</param> /// <returns>properly prefixed eventname</returns> public static string EnsureEventNamePrefix(string eventNamePrefix, string eventName) { if (!eventName.StartsWith(eventNamePrefix, StringComparison.OrdinalIgnoreCase)) { return String.Concat(eventNamePrefix, eventName); } return eventName; } /// <summary> /// Ensures Property names in the dictionary are properly prefixed. If not, it will convert the eventname and append it as the prefix /// </summary> /// <param name="eventName">Name of the telemetry event</param> /// <param name="properties">Dictionary of telemetry properties</param> /// <returns>prefixed properties array</returns> public static Dictionary<string, object> EnsurePropertyPrefix(string propertyNamePrefix, IDictionary<string, object> properties) { Debug.Assert(properties != null, "properties dictionary should not be null"); if (properties == null) return null; Dictionary<string, object> prefixedProperties = new Dictionary<string, object>(properties.Count); foreach (var item in properties) { string key = item.Key; if (!key.StartsWith(propertyNamePrefix, StringComparison.OrdinalIgnoreCase)) key = String.Concat(propertyNamePrefix, key); prefixedProperties[key] = item.Value; } return prefixedProperties; } /// <summary> /// Merges items from target into destination. if there are duplicate keys, target wins. /// </summary> public static void Merge(this Dictionary<string, object> destination, Dictionary<string, object> target) { if (target == null) { return; } if (destination == null) { destination = new Dictionary<string, object>(target); return; } foreach (var item in target) { destination[item.Key] = item.Value; } } } } <|start_filename|>src/MICore/LaunchCommand.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml; using System.Collections.ObjectModel; namespace MICore { /// <summary> /// A {command, description, ignore failure} tuple for a launch/setup command. These are either read from an XML launch options blob, or returned from a launcher. /// </summary> public class LaunchCommand { public readonly string CommandText; public readonly string Description; public readonly bool IgnoreFailures; public readonly bool IsMICommand; public /*OPTIONAL*/ Action<string> FailureHandler { get; private set; } public /*OPTIONAL*/ Func<string, Task> SuccessHandler { get; private set; } public /*Optional*/ Func<Results, Task> SuccessResultsHandler { get; private set; } public LaunchCommand(string commandText, string description = null, bool ignoreFailures = false, Action<string> failureHandler = null, Func<string, Task> successHandler = null, Func<Results, Task> successResultsHandler = null) { if (commandText == null) throw new ArgumentNullException(nameof(commandText)); commandText = commandText.Trim(); if (commandText.Length == 0) throw new ArgumentOutOfRangeException(nameof(commandText)); this.IsMICommand = commandText[0] == '-'; this.CommandText = commandText; this.Description = description; if (string.IsNullOrWhiteSpace(description)) this.Description = this.CommandText; this.IgnoreFailures = ignoreFailures; this.FailureHandler = failureHandler; this.SuccessHandler = successHandler; this.SuccessResultsHandler = successResultsHandler; } public static ReadOnlyCollection<LaunchCommand> CreateCollection(List<Json.LaunchOptions.SetupCommand> source) { IList<LaunchCommand> commands = source?.Select(x => new LaunchCommand(x.Text, x.Description, x.IgnoreFailures.GetValueOrDefault(false))).ToList(); if(commands == null) { commands = new List<LaunchCommand>(0); } return new ReadOnlyCollection<LaunchCommand>(commands); } public static ReadOnlyCollection<LaunchCommand> CreateCollection(Xml.LaunchOptions.Command[] source) { LaunchCommand[] commandArray = source?.Select(x => new LaunchCommand(x.Value, x.Description, x.IgnoreFailures)).ToArray(); if (commandArray == null) { commandArray = new LaunchCommand[0]; } return new ReadOnlyCollection<LaunchCommand>(commandArray); } } } <|start_filename|>src/DebugEngineHost.VSCode/VSCode/ExceptionSettings.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.VisualStudio.Debugger.Interop; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Globalization; using System.Linq; namespace Microsoft.DebugEngineHost.VSCode { sealed public class ExceptionSettings { public enum TriggerState { unhandled = enum_EXCEPTION_STATE.EXCEPTION_STOP_SECOND_CHANCE, userUnhandled = enum_EXCEPTION_STATE.EXCEPTION_STOP_USER_UNCAUGHT, thrown = enum_EXCEPTION_STATE.EXCEPTION_STOP_FIRST_CHANCE | enum_EXCEPTION_STATE.EXCEPTION_STOP_USER_FIRST_CHANCE, all = enum_EXCEPTION_STATE.EXCEPTION_STOP_FIRST_CHANCE | enum_EXCEPTION_STATE.EXCEPTION_STOP_USER_FIRST_CHANCE | enum_EXCEPTION_STATE.EXCEPTION_STOP_USER_UNCAUGHT | enum_EXCEPTION_STATE.EXCEPTION_STOP_SECOND_CHANCE }; sealed public class CategoryConfiguration { [JsonRequired] public string Name; [JsonRequired] public Guid Id; public Dictionary<string, TriggerState> DefaultTriggers = new Dictionary<string, TriggerState>(); } private IList<CategoryConfiguration> _categories = new List<CategoryConfiguration>(); private IList<ExceptionBreakpointFilter> _exceptionFilters = new List<ExceptionBreakpointFilter>(); public IList<CategoryConfiguration> Categories { get { return _categories; } } /// <summary> /// /*OPTIONAL*/ Set of exception breakpoints that appears in VS Code /// </summary> public IList<ExceptionBreakpointFilter> ExceptionBreakpointFilters { get { return _exceptionFilters; } } internal ExceptionSettings() { } #if DEBUG internal void ValidateExceptionFilters() { foreach (ExceptionBreakpointFilter filter in _exceptionFilters) { // Make sure that the category GUID was listed in the config file. if (!_categories.Where(c => c.Id == filter.categoryId).Any()) { Debug.Fail(string.Format(CultureInfo.InvariantCulture, "Missing category '{0}' from configuration file.", filter.categoryId)); } } } #endif internal void MakeReadOnly() { #if DEBUG ValidateExceptionFilters(); #endif _categories = new ReadOnlyCollection<CategoryConfiguration>(_categories); _exceptionFilters = new ReadOnlyCollection<ExceptionBreakpointFilter>(_exceptionFilters); } } } <|start_filename|>src/MIDebugEngine/Engine.Impl/EngineTelemetry.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using MICore; using Microsoft.DebugEngineHost; using System.Diagnostics; using System.Linq; using System.Globalization; namespace Microsoft.MIDebugEngine { internal class EngineTelemetry { private const string Event_DebuggerAborted = @"VS/Diagnostics/Debugger/MIEngine/DebuggerAborted"; private const string Property_DebuggerName = @"VS.Diagnostics.Debugger.MIEngine.DebuggerName"; private const string Property_LastSentCommandName = @"VS.Diagnostics.Debugger.MIEngine.LastSentCommandName"; private const string Property_DebuggerExitCode = @"VS.Diagnostics.Debugger.MIEngine.DebuggerExitCode"; private const string Windows_Runtime_Environment = @"VS/Diagnostics/Debugger/MIEngine/WindowsRuntime"; private const string Property_Windows_Runtime_Environment = @"VS.Diagnostics.Debugger.MIEngine.WindowsRuntime"; private const string Value_Windows_Runtime_Environment_Cygwin = "Cygwin"; private const string Value_Windows_Runtime_Environment_MinGW = "MinGW"; public bool DecodeTelemetryEvent(Results results, out string eventName, out KeyValuePair<string, object>[] properties) { properties = null; // NOTE: the message event is an MI Extension from clrdbg, though we could use in it the future for other debuggers eventName = results.TryFindString("event-name"); if (string.IsNullOrEmpty(eventName) || !char.IsLetter(eventName[0]) || !eventName.Contains('/')) { Debug.Fail("Bogus telemetry event. 'Event-name' property is missing or invalid."); return false; } TupleValue tuple; if (!results.TryFind("properties", out tuple)) { Debug.Fail("Bogus message event, missing 'properties' property"); return false; } List<KeyValuePair<string, object>> propertyList = new List<KeyValuePair<string, object>>(tuple.Content.Count); foreach (NamedResultValue pair in tuple.Content) { ConstValue resultValue = pair.Value as ConstValue; if (resultValue == null) continue; string content = resultValue.Content; if (string.IsNullOrEmpty(content)) continue; object value = content; int numericValue; if (content.Length >= 3 && content.StartsWith("0x", StringComparison.OrdinalIgnoreCase) && int.TryParse(content.Substring(2), NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture, out numericValue)) { value = numericValue; } else if (int.TryParse(content, NumberStyles.None, CultureInfo.InvariantCulture, out numericValue)) { value = numericValue; } if (value != null) { propertyList.Add(new KeyValuePair<string, object>(pair.Name, value)); } } properties = propertyList.ToArray(); return true; } public void SendDebuggerAborted(MICommandFactory commandFactory, string lastSentCommandName, /*OPTIONAL*/ string debuggerExitCode) { List<KeyValuePair<string, object>> eventProperties = new List<KeyValuePair<string, object>>(); eventProperties.Add(new KeyValuePair<string, object>(Property_DebuggerName, commandFactory.Name)); eventProperties.Add(new KeyValuePair<string, object>(Property_LastSentCommandName, lastSentCommandName)); if (!string.IsNullOrEmpty(debuggerExitCode)) { eventProperties.Add(new KeyValuePair<string, object>(Property_DebuggerExitCode, debuggerExitCode)); } HostTelemetry.SendEvent(Event_DebuggerAborted, eventProperties.ToArray()); } public enum WindowsRuntimeEnvironment { Cygwin, MinGW } public void SendWindowsRuntimeEnvironment(WindowsRuntimeEnvironment environment) { string envValue; if (environment == WindowsRuntimeEnvironment.Cygwin) { envValue = Value_Windows_Runtime_Environment_Cygwin; } else { envValue = Value_Windows_Runtime_Environment_MinGW; } HostTelemetry.SendEvent( Windows_Runtime_Environment, new KeyValuePair<string, object>(Property_Windows_Runtime_Environment, envValue)); } } } <|start_filename|>test/CppTests/Tests/MacOSAppTests.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Threading; using DebuggerTesting; using DebuggerTesting.Compilation; using DebuggerTesting.OpenDebug; using DebuggerTesting.OpenDebug.Commands; using DebuggerTesting.OpenDebug.CrossPlatCpp; using DebuggerTesting.OpenDebug.Events; using DebuggerTesting.OpenDebug.Extensions; using DebuggerTesting.Ordering; using DebuggerTesting.Utilities; using Xunit; using Xunit.Abstractions; namespace CppTests.Tests { [TestCaseOrderer(DependencyTestOrderer.TypeName, DependencyTestOrderer.AssemblyName)] public class MacOSAppTests : TestBase { #region Constructor public MacOSAppTests(ITestOutputHelper outputHelper) : base(outputHelper) { } #endregion #region Methods [Theory] [RequiresTestSettings] [SupportedCompiler(SupportedCompiler.XCodeBuild, SupportedArchitecture.x64)] public void CompileMacOSAppForTests(ITestSettings settings) { this.TestPurpose("Compile MacOSApp debuggee for tests."); this.WriteSettings(settings); IDebuggee debuggee = Debuggee.Create(this, settings.CompilerSettings, "MacOSApp", 1, "TestApp.app", CompilerOutputType.MacOSApp); debuggee.AddSourceFiles("TestApp.xcodeproj"); debuggee.Compile(); } [Theory] [DependsOnTest(nameof(CompileMacOSAppForTests))] [RequiresTestSettings] [SupportedCompiler(SupportedCompiler.XCodeBuild, SupportedArchitecture.x64)] public void MacOSAppBasic(ITestSettings settings) { IDebuggee debuggee = Debuggee.Open(this, settings.CompilerSettings, "MacOSApp", 1, "TestApp.app", CompilerOutputType.MacOSApp); using (IDebuggerRunner runner = CreateDebugAdapterRunner(settings)) { this.Comment("Configure launch."); runner.Launch(settings.DebuggerSettings, debuggee, null); SourceBreakpoints mainBreakpoints = debuggee.Breakpoints(SinkHelper.Main, 14); runner.SetBreakpoints(mainBreakpoints); this.Comment("Launch and run until first breakpoint"); runner.Expects.HitBreakpointEvent(SinkHelper.Main, 14) .AfterConfigurationDone(); this.Comment("Continue until end"); runner.Expects.ExitedEvent() .TerminatedEvent() .AfterContinue(); runner.DisconnectAndVerify(); } } #endregion } } <|start_filename|>test/DebuggerTesting/OpenDebug/Commands/AsyncBreakCommand.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace DebuggerTesting.OpenDebug.Commands { /// <summary> /// Causes the debugger to break into code /// </summary> public class AsyncBreakCommand : Command<ThreadCommandArgs> { public AsyncBreakCommand() : base("pause") { this.Args.threadId = 0; } } } <|start_filename|>test/Android/BreakPointEnableAndDisable/BreakPointEnableAndDisable/BreakPointEnableAndDisable.NativeActivity/Header1.h<|end_filename|> #pragma once void func(); void func1(); class MyClass { public: void Func(); }; <|start_filename|>test/CppTests/debuggees/kitchensink/src/main.cpp<|end_filename|> // NOTE THAT CHANGING THE LINE NUMBERS FOR EXISTING SOURCE CODE WILL REQUIRE CHANGING OTHER TESTS // SEE https://devdiv.visualstudio.com/DevDiv/_git/OpenDebugAD7/pullrequest/37021 for an example #include "main.h" #include "arguments.h" #include "nonterminating.h" #include "calling.h" #include "threading.h" #include "expression.h" #include "environment.h" using namespace std; int main(int argc, char *argv[]) { cout << "KitchenSink for Business! (" << STRINGIFY(DEBUGGEE_COMPILER) << "/" << ARCH << " Edition)" << endl; Arguments argumentsFeature; argumentsFeature.argc = argc; argumentsFeature.argv = argv; argumentsFeature.Run(); if (argumentsFeature.runNonTerminating == true) { // This feature just runs in an infinite loop. NonTerminating nonTerminatingFeature; nonTerminatingFeature.Run(); } if (argumentsFeature.runCalling == true) { Calling callingFeature; callingFeature.Run(); } if (argumentsFeature.runThreading == true) { Threading threadingFeature; threadingFeature.Run(); } if (argumentsFeature.runExpression == true) { Expression expressionFeature; expressionFeature.Run(); } if (argumentsFeature.runEnvironment == true) { Environment environmentFeature;; environmentFeature.Run(); } cout << "Goodbye.\n"; return 0; } <|start_filename|>src/SSHDebugPS/SSH/SSHUnixAsyncCommand.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Diagnostics; using System.Globalization; using System.Threading; using liblinux; using liblinux.Shell; using Microsoft.VisualStudio.Debugger.Interop.UnixPortSupplier; namespace Microsoft.SSHDebugPS.SSH { internal class SSHUnixAsyncCommand : IDebugUnixShellAsyncCommand { private readonly object _lock = new object(); private readonly IDebugUnixShellCommandCallback _callback; private IRemoteSystem _remoteSystem; private IStreamableCommand _command; public SSHUnixAsyncCommand(IRemoteSystem remoteSystem, IDebugUnixShellCommandCallback callback) { _remoteSystem = remoteSystem; _callback = callback; } internal void Start(string commandText) { _command = _remoteSystem.CreateStreamableCommand(commandText); _remoteSystem.StartCommand(_command, Timeout.InfiniteTimeSpan); _command.Finished += (sender, e) => _callback.OnExit(((NonHostedCommand)sender).ExitCode.ToString(CultureInfo.InvariantCulture)); _command.OutputReceived += (sender, e) => _callback.OnOutputLine(e.Output); _command.RedirectErrorOutputToOutput = true; _command.BeginOutputRead(); } void IDebugUnixShellAsyncCommand.Write(string text) { lock (_lock) { if (_command != null) { _command.Write(text); } } } void IDebugUnixShellAsyncCommand.WriteLine(string text) { lock (_lock) { if (_command != null) { _command.Write(text + "\n"); } } } void IDebugUnixShellAsyncCommand.Abort() { Close(); } private void Close() { lock (_lock) { if (_command != null) { _command.Dispose(); _command = null; } } } } } <|start_filename|>src/OpenDebugAD7/Properties/AssemblyInfo.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Reflection; using System.Runtime.CompilerServices; // Information about this assembly is defined by the following attributes. // Change them to the values specific to your project. [assembly: AssemblyTitle("OpenDebugAD7")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] <|start_filename|>test/CppTests/Properties/AssemblyInfo.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Reflection; using System.Runtime.InteropServices; using CppTests; using DebuggerTesting.Attribution; using Xunit; // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("ae286353-4fc0-4fb3-bf6a-2677252b96b2")] // Turn off parallel threads, xunit didn't seem to be handling this correctly [assembly: CollectionBehavior(DisableTestParallelization = true)] // This is located by the test settings resolver and specifies the settings provider for C++ tests [assembly: TestSettingsProvider(typeof(CppTestSettingsProvider))] <|start_filename|>test/DebuggerTesting/OpenDebug/Commands/ConfigurationDoneCommand.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; namespace DebuggerTesting.OpenDebug.Commands { /// <summary> /// Command used to start the debuggee after initial breakpoint and configuration /// commands have been issued. /// </summary> public class ConfigurationDoneCommand : Command<object> { public ConfigurationDoneCommand() : base("configurationDone") { this.Timeout = TimeSpan.FromSeconds(10); } } } <|start_filename|>test/DebuggerTesting/ITestSettings.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace DebuggerTesting { /// <summary> /// Interface describing the settings that are passed into a theory test. /// </summary> public interface ITestSettings { #region Properties string Name { get; } ICompilerSettings CompilerSettings { get; } IDebuggerSettings DebuggerSettings { get; } #endregion } } <|start_filename|>src/DebugEngineHost.VSCode/VSCode/ExceptionBreakpointFilter.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.VisualStudio.Debugger.Interop; using Newtonsoft.Json; using System; using System.Diagnostics; namespace Microsoft.DebugEngineHost.VSCode { /// <summary> /// Represents a breakpoint that appears in VS Code to enable or disable stopping on /// a set of exceptions. /// </summary> sealed public class ExceptionBreakpointFilter { private string _filter; /// <summary> /// The label for the button that will appear in the UI /// </summary> [JsonRequired] public string label { get; set; } /// <summary> /// The identifier for this filter. /// </summary> [JsonRequired] public string filter { get { return _filter; } set { _filter = value; } } [JsonRequired] public bool supportsCondition { get; set; } [JsonRequired] public string conditionDescription { get; set; } [JsonRequired] public Guid categoryId { get; set; } /// <summary> /// The default state for the button /// </summary> public bool @default { get; set; } [JsonIgnore] public enum_EXCEPTION_STATE State { get; set; } = enum_EXCEPTION_STATE.EXCEPTION_STOP_SECOND_CHANCE | enum_EXCEPTION_STATE.EXCEPTION_STOP_FIRST_CHANCE | enum_EXCEPTION_STATE.EXCEPTION_STOP_USER_FIRST_CHANCE; } } <|start_filename|>test/Android/EvalComplexExpression/EvalComplexExpression/EvalComplexExpression.NativeActivity/Source1.cpp<|end_filename|> #include "Header1.h" #include <string> using namespace std; void Func(int x) { int _x = x; _x++; return; } int Func(int x, double y) { int _y = (int)y; return x + y; } void Func() { int x = 0; double dx = 1.50; string str = "hello, world"; x = 1; return; } <|start_filename|>test/DebuggerTesting/Attribution/UnsupportedDebuggerAttribute.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; namespace DebuggerTesting { /// <summary> /// Attribute used by xUnit theory test for specifying which debuggers will not be used by the test. /// </summary> [AttributeUsage(AttributeTargets.Method, AllowMultiple = true, Inherited = false)] public class UnsupportedDebuggerAttribute : DebuggerAttribute { #region Constructor public UnsupportedDebuggerAttribute(SupportedDebugger debugger, SupportedArchitecture architecture) : base(debugger, architecture) { } #endregion } } <|start_filename|>src/SSHDebugTests/LineBufferTests.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.SSHDebugPS; using System.Collections.Generic; using System.Linq; using Xunit; namespace SSHDebugTests { public class LineBufferTests { [Fact] public void LineBuffer_FullLine() { var lineBuffer = new LineBuffer(); Verify(lineBuffer, "hello\n", new string[] { "hello" }); } [Fact] public void LineBuffer_FullLineWithCR() { var lineBuffer = new LineBuffer(); Verify(lineBuffer, "hello\r\n", new string[] { "hello" }); } [Fact] public void LineBuffer_TwoParts() { var lineBuffer = new LineBuffer(); Verify(lineBuffer, "hello", new string[] { }); Verify(lineBuffer, "\n", new string[] { "hello" }); } [Fact] public void LineBuffer_MultiLine() { var lineBuffer = new LineBuffer(); Verify(lineBuffer, "hello\nworld\n!\n", new string[] { "hello", "world", "!" }); } [Fact] public void LineBuffer_SplitLine1() { var lineBuffer = new LineBuffer(); Verify(lineBuffer, "hello\nmore text", new string[] { "hello" }); Verify(lineBuffer, "comes now\n", new string[] { "more textcomes now" }); } [Fact] public void LineBuffer_SplitLine2() { var lineBuffer = new LineBuffer(); Verify(lineBuffer, "hello\nworld\nmore text", new string[] { "hello", "world" }); Verify(lineBuffer, "comes now\n", new string[] { "more textcomes now" }); } [Fact] public void LineBuffer_EmptyLine() { var lineBuffer = new LineBuffer(); Verify(lineBuffer, "hello", new string[] { }); Verify(lineBuffer, "\n\nworld\n", new string[] { "hello", "", "world" }); } [Fact] public void LineBuffer_EmptyLineCR() { var lineBuffer = new LineBuffer(); Verify(lineBuffer, "hello", new string[] { }); Verify(lineBuffer, "\r\n\nworld\r\n", new string[] { "hello", "", "world" }); } [Fact] public void LineBuffer_CharByChar() { var lineBuffer = new LineBuffer(); Verify(lineBuffer, "a", new string[] { }); Verify(lineBuffer, "b", new string[] { }); Verify(lineBuffer, "c", new string[] { }); Verify(lineBuffer, "d", new string[] { }); Verify(lineBuffer, "e", new string[] { }); Verify(lineBuffer, "\n", new string[] { "abcde" }); } private void Verify(LineBuffer lineBuffer, string textToAdd, string[] expectedOutput) { IEnumerable<string> result; lineBuffer.ProcessText(textToAdd, out result); string[] r = result.ToArray(); Assert.Equal<int>(expectedOutput.Length, r.Length); for (int i = 0; i < expectedOutput.Length; i++) { Assert.Equal(expectedOutput[i], r[i]); } } } } <|start_filename|>src/MICore/SetMIDebugLogging.cmd<|end_filename|> @echo off setlocal if /i "%~1"=="" goto Help if /i "%~1"=="-?" goto Help if /i "%~1"=="/?" goto Help set LoggingValue= set Exp=0 set ServerLogging= set VSRootDir= set MIEngineRelativeDir=Common7\IDE\CommonExtensions\Microsoft\MDD\Debugger set MIEngineRelativePath=%MIEngineRelativeDir%\Microsoft.MIDebugEngine.dll :ArgLoop if /i "%~1"=="on" set LoggingValue=1& goto ArgLoopCondition if /i "%~1"=="off" set LoggingValue=0& goto ArgLoopCondition if /i "%~1"=="/VSRootDir" goto SetVSRoot if /i "%~1"=="-VSRootDir" goto SetVSRoot if /i "%~1"=="-serverlogging" goto SetServerLogging if /i "%~1"=="/serverlogging" goto SetServerLogging echo ERROR: Unknown argument '%~1'& exit /b -1 :SetVSRoot shift if "%~1"=="" echo ERROR: Expected version number. set VSRootDir=%~1 if not exist "%VSRootDir%" echo ERROR: '/VSRootDir' value '%VSRootDir%' does not exist & exit /b -1 if not exist "%VSRootDir%\%MIEngineRelativePath%" echo ERROR: '/VSRootDir' value '%VSRootDir%' does not contain MIEngine (%VSRootDir%\%MIEngineRelativePath%) & exit /b -1 goto ArgLoopCondition :SetServerLogging REM Documentation on GDBServer command line arguments: http://www.sourceware.org/gdb/onlinedocs/gdb/Server.html set ServerLogging=--debug if /i "%~2"=="full" shift & set ServerLogging=--debug --remote-debug goto ArgLoopCondition :ArgLoopCondition shift if NOT "%~1"=="" goto :ArgLoop if "%LoggingValue%"=="" echo ERROR: 'on' or 'off' must be specified.& exit /b -1 if /i NOT "%LoggingValue%"=="1" if NOT "%ServerLogging%"=="" echo ERROR: '/serverlogging' can only be used with 'on'& exit /b -1 set SetLoggingError= if NOT "%VSRootDir%"=="" call :SetLogging "%VSRootDir%" & goto Done REM If '/VSRootDir' is NOT specified, try ALL the default locations set ProgRoot=%ProgramFiles(x86)% if "%ProgRoot%"=="" set ProgRoot=%ProgramFiles% set VSVersionFound= set MIEngineFound= call :TryVSPath "%ProgRoot%\Microsoft Visual Studio 14.0" call :TryVSPaths "%ProgRoot%\Microsoft Visual Studio\2017\*" if "%VSVersionFound%"=="" echo ERROR: Visual Studio 2015+ is not installed, or not installed to the default location. Use '/VSRootDir' to specify the directory. & exit /b -1 if "%MIEngineFound%"=="" echo ERROR: The found version(s) of Visual Studio do not have the MIEngine installed. & exit /b -1 goto Done :Done echo. if NOT "%SetLoggingError%"=="" exit /b -1 echo SetMIDebugLogging.cmd succeeded. Restart Visual Studio to take effect. if "%LoggingValue%"=="1" echo Logging will be saved to %TMP%\Microsoft.MIDebug.log. exit /b 0 :TryVSPaths for /d %%d in (%1) do call :TryVSPath "%%d" goto :EOF :TryVSPath REM Arg1: path to VS Root if NOT "%SetLoggingError%"=="" goto :EOF if not exist "%~1" goto :EOF set VSVersionFound=1 if not exist "%~1\%MIEngineRelativePath%" goto :EOF set MIEngineFound=1 goto SetLogging :SetLogging REM Arg1: path to VS Root set PkgDefFile=%~1\%MIEngineRelativeDir%\logging.pkgdef if NOT exist "%PkgDefFile%" goto SetLogging_NoPkgDef del "%PkgDefFile%" if NOT exist "%PkgDefFile%" goto SetLogging_NoPkgDef echo ERROR: Failed to remove "%PkgDefFile%". Ensure this script is run as an administrator. set SetLoggingError=1 goto :EOF :SetLogging_NoPkgDef if "%LoggingValue%"=="0" goto UpdateConfiguration :EnableLogging echo [$RootKey$\Debugger]> "%PkgDefFile%" if exist "%PkgDefFile%" goto EnableLogging_PkgDefCreated echo ERROR: Failed to create "%PkgDefFile%". Ensure this script is run as an administrator. set SetLoggingError=1 goto :EOF :EnableLogging_PkgDefCreated echo "EnableMIDebugLogger"=dword:00000001>> "%PkgDefFile%" if NOT "%ServerLogging%"=="" echo "GDBServerLoggingArguments"="%ServerLogging%">> "%PkgDefFile%" :UpdateConfiguration echo Setting logging for %1 call "%~1\Common7\IDE\devenv.com" /updateconfiguration if "%ERRORLEVEL%"=="0" goto :EOF echo ERROR: '"%~1\Common7\IDE\devenv.com" /updateconfiguration' failed with error %ERRORLEVEL%. set SetLoggingError=1 goto :EOF :Help echo SetMIDebugLogging.cmd ^<on^|off^> [/serverlogging [full]] [/VSRootDir ^<value^>] echo. echo SetMIDebugLogging.cmd is used to enable/disable logging for the Microsoft echo MI debug engine. echo. echo Logging will be saved to %TMP%\Microsoft.MIDebug.log. echo. echo /serverlogging [full] Enables logging from gdbserver. This option is only echo supported when enabling logging ('on'). 'full' logging will echo turn on packet logging in addition to normal logging. echo. echo /VSRootDir ^<value^> sets the path to the root of Visual Studio echo (ex: C:\Program Files (x86)\Microsoft Visual Studio 14.0). If not echo specified, the default install directories for all versions of VS echo 2015+ will be used. echo. :eof <|start_filename|>test/CppTests/debuggees/kitchensink/src/arguments.cpp<|end_filename|> #include "arguments.h" Arguments::Arguments() : Feature("Arguments") { } void Arguments::CoreRun() { this->Log("Parsing Arguments."); if (this->argc > 1) { this->Log("Count: ", this->argc - 1); for (int i = 0; i < this->argc - 1; i++) { char* arg = this->argv[i + 1]; std::string argStr(arg); this->Log("Arg ", i + 1, ": ", argStr); if (argStr.compare("-fCalling") == 0) { this->runCalling = true; } if (argStr.compare("-fThreading") == 0) { this->runThreading = true; } if (argStr.compare("-fNonTerminating") == 0) { this->runNonTerminating = true; } if (argStr.compare("-fExpression") == 0) { this->runExpression = true; } if (argStr.compare("-fEnvironment") == 0) { this->runEnvironment = true; } } } } <|start_filename|>src/SSHDebugPS/LocalProcessAsyncRunner.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; using SysProcess = System.Diagnostics.Process; namespace Microsoft.SSHDebugPS { readonly struct ProcessResult { public int ExitCode { get; } public IList<string> StdOut { get; } public IList<string> StdErr { get; } public ProcessResult(int exitCode, IList<string> stdOut, IList<string> stdErr) { this.ExitCode = exitCode; this.StdOut = stdOut; this.StdErr = stdErr; } }; internal static class LocalProcessAsyncRunner { public static Task<ProcessResult> ExecuteProcessAsync(ProcessStartInfo startInfo, CancellationToken cancellationToken) { bool isComplete = false; var taskCompletionSource = new TaskCompletionSource<ProcessResult>(); CancellationTokenRegistration cancellationTokenRegistration = new CancellationTokenRegistration(); List<string> stdOut = new List<string>(); List<string> stdError = new List<string>(); SysProcess process = null; void Process_Exited(object sender, EventArgs e) { // Briefly take this lock to make sure that we had a chance to finish initialization, and to guard 'isComplete' lock (taskCompletionSource) { if (isComplete) { return; // already canceled } isComplete = true; } cancellationTokenRegistration.Dispose(); process.Exited -= Process_Exited; // Wait for any output handlers to flush process.WaitForExit(); int exitCode = process.ExitCode; process.Close(); taskCompletionSource.SetResult(new ProcessResult(exitCode, stdOut, stdError)); } void OnCancel() { // Briefly take this lock to make sure that we had a chance to finish initialization, and to guard 'isComplete' lock (taskCompletionSource) { if (isComplete) { return; // process already exited } isComplete = true; } taskCompletionSource.SetCanceled(); process.Exited -= Process_Exited; try { process.Kill(); } catch (Exception) { } process.Close(); } lock (taskCompletionSource) { cancellationTokenRegistration = cancellationToken.Register(OnCancel); process = new SysProcess(); process.StartInfo = startInfo; process.EnableRaisingEvents = true; process.Exited += Process_Exited; process.OutputDataReceived += (sender, e) => { if (e.Data == null) { return; // ignore end-of-stream } stdOut.Add(e.Data); }; process.ErrorDataReceived += (sender, e) => { if (e.Data == null) { return; // ignore end-of-stream } stdError.Add(e.Data); }; process.Start(); process.BeginOutputReadLine(); process.BeginErrorReadLine(); } return taskCompletionSource.Task; } } } <|start_filename|>test/DebuggerTesting/Utilities/XmlHelper.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Xml; using System.Xml.Linq; namespace DebuggerTesting.Utilities { public static class XmlHelper { #if CORECLR [SuppressMessage("Microsoft.Security.Xml", "CA3053:UseXmlSecureResolver", Justification = "XmlResolver property does not exist in CoreCLR.")] #endif public static XmlReader CreateXmlReader(string uri) { XmlReaderSettings settings = new XmlReaderSettings(); settings.ConformanceLevel = ConformanceLevel.Document; settings.DtdProcessing = DtdProcessing.Prohibit; #if !CORECLR settings.XmlResolver = null; #endif return XmlReader.Create(uri, settings); } public static string GetAttributeValue(this XElement element, string attributeName) { return element.Attribute(attributeName)?.Value; } public static TEnum GetAttributeEnum<TEnum>(this XElement element, string attributeName) where TEnum : struct { string attributeValue = GetAttributeValue(element, attributeName); TEnum value; if (!Enum.TryParse(attributeValue, true, out value)) throw new ArgumentOutOfRangeException(nameof(attributeValue), "Unhandled " + typeof(TEnum).Name + " value " + attributeValue); return value; } public static bool? GetAttributeValueAsBool(this XElement element, string attributeName) { string value = element.GetAttributeValue(attributeName); if (string.IsNullOrEmpty(value)) return null; return bool.Parse(value); } public static double? GetAttributeValueAsDouble(this XElement element, string attributeName) { string value = element.GetAttributeValue(attributeName); if (string.IsNullOrEmpty(value)) return null; return double.Parse(value, CultureInfo.InvariantCulture); } } } <|start_filename|>src/AndroidDebugLauncher/LauncherResources.Designer.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> //------------------------------------------------------------------------------ namespace AndroidDebugLauncher { using System; /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class LauncherResources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal LauncherResources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("AndroidDebugLauncher.LauncherResources", typeof(LauncherResources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// <summary> /// Looks up a localized string similar to The current Android NDK root is set to an NDK for platform &apos;Windows 64-bit&apos;. Platform &apos;Windows 64-bit&apos; NDKs do not support x86 debugging. Specify a 32-bit NDK for platform &apos;Windows 32-bit&apos; instead. This can be obtained from developer.android.com.. /// </summary> internal static string Error_64BitNDKNotSupportedForX86 { get { return ResourceManager.GetString("Error_64BitNDKNotSupportedForX86", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The Android command &apos;{0}&apos; failed to execute.. /// </summary> internal static string Error_AdbShellFailure { get { return ResourceManager.GetString("Error_AdbShellFailure", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Incompatible device CPU architecture detected. The debugger is configured for {0} debugging. But the configured device/emulator &apos;{1}&apos; is using {2} ABI.. /// </summary> internal static string Error_BadDeviceAbi { get { return ResourceManager.GetString("Error_BadDeviceAbi", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Unable to connect to the device/emulator through the Android Debug Bridge (adb). If the problem continues, try restarting the device/emulator or resetting adb.. /// </summary> internal static string Error_DeviceNotResponding { get { return ResourceManager.GetString("Error_DeviceNotResponding", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The target device or emulator is offline.. /// </summary> internal static string Error_DeviceOffline { get { return ResourceManager.GetString("Error_DeviceOffline", resourceCulture); } } /// <summary> /// Looks up a localized string similar to {0} file &apos;{1}&apos;, could not be found in the expected location of &apos;{2}&apos;. Ensure that a compatible {0} is installed.. /// </summary> internal static string Error_ExternalFileNotFound { get { return ResourceManager.GetString("Error_ExternalFileNotFound", resourceCulture); } } /// <summary> /// Looks up a localized string similar to GDBServer failed to start or attach to the target application.. /// </summary> internal static string Error_GDBServerFailed { get { return ResourceManager.GetString("Error_GDBServerFailed", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Required Android SDK file, adb.exe, could not be found under the specified Android SDK root &apos;{0}&apos;.. /// </summary> internal static string Error_InvalidAndroidSDK { get { return ResourceManager.GetString("Error_InvalidAndroidSDK", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The format of AndroidLaunchOptions attribute &apos;{0}&apos; is invalid.. /// </summary> internal static string Error_InvalidAttribute { get { return ResourceManager.GetString("Error_InvalidAttribute", resourceCulture); } } /// <summary> /// Looks up a localized string similar to AndroidLaunchOptions attribute &apos;{0}&apos; has an invalid value &apos;{1}&apos;. Directory does not exist or is not rooted.. /// </summary> internal static string Error_InvalidDirectoryAttribute { get { return ResourceManager.GetString("Error_InvalidDirectoryAttribute", resourceCulture); } } /// <summary> /// Looks up a localized string similar to A required Visual Studio registry value could not be found. Ensure that support for multi-device C++ development is enabled in Visual Studio setup. /// ///Registry key: {0} ///Value name: {1}. /// </summary> internal static string Error_MDDRegValueNotFound { get { return ResourceManager.GetString("Error_MDDRegValueNotFound", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Required AndroidLaunchOptions attribute &apos;{0}&apos; is missing.. /// </summary> internal static string Error_MissingAttribute { get { return ResourceManager.GetString("Error_MissingAttribute", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Multiple application processes were found for package &apos;{0}&apos;. Debugging multi-process packages is not currently supported. If the package is not expected to have multiple processes, try restarting the device or emulator.. /// </summary> internal static string Error_MulltipleApplicationProcesses { get { return ResourceManager.GetString("Error_MulltipleApplicationProcesses", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Non-debuggable application installed on the target device. Required file &apos;{0}&apos; could not be found on the device. Please reinstall the debuggable version.. /// </summary> internal static string Error_NoGdbServer { get { return ResourceManager.GetString("Error_NoGdbServer", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The package &apos;{0}&apos; did not start on the device or emulator.. /// </summary> internal static string Error_PackageDidNotStart { get { return ResourceManager.GetString("Error_PackageDidNotStart", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Cannot Attach. The package &apos;{0}&apos; is not running on the device or emulator.. /// </summary> internal static string Error_PackageIsNotRunning { get { return ResourceManager.GetString("Error_PackageIsNotRunning", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Non-debuggable application installed on the target device. Please reinstall the debuggable version.. /// </summary> internal static string Error_RunAsNonDebuggablePackage { get { return ResourceManager.GetString("Error_RunAsNonDebuggablePackage", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Troubleshooting steps: ///- Try launching the app from the app list. If the app is not in the app list, or cannot be started, this may indicate a problem with the app deployment. ///- Make sure that you have installed all updates available for your device. ///- Install the latest firmware or flash the device using the latest available image. This can be helpful even if you are already on the latest version of Android as the over-the-air Android upgrade process may corrupt file permissions needed for native debugg [rest of string was truncated]&quot;;. /// </summary> internal static string Error_RunAsUnknownPackage { get { return ResourceManager.GetString("Error_RunAsUnknownPackage", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Unexpected results from running the Android command &apos;{0}&apos;.. /// </summary> internal static string Error_ShellCommandBadResults { get { return ResourceManager.GetString("Error_ShellCommandBadResults", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Android command &apos;{0}&apos; failed. {1}. /// </summary> internal static string Error_ShellCommandFailed { get { return ResourceManager.GetString("Error_ShellCommandFailed", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The Visual Studio C++ Android debugger requires that the target emulator/device be running Android API level 17 (version 4.2) or newer, but the target emulator/device is running API level {0}. Please update your emulator/device.. /// </summary> internal static string Error_UnsupportedAPILevel { get { return ResourceManager.GetString("Error_UnsupportedAPILevel", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Java Development Kit. /// </summary> internal static string ProductName_JDK { get { return ResourceManager.GetString("ProductName_JDK", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Android NDK. /// </summary> internal static string ProductName_NDK { get { return ResourceManager.GetString("ProductName_NDK", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Android SDK. /// </summary> internal static string ProductName_SDK { get { return ResourceManager.GetString("ProductName_SDK", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Connecting to the Android device or emulator.. /// </summary> internal static string Step_ConnectToDevice { get { return ResourceManager.GetString("Step_ConnectToDevice", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Downloading files from the device or emulator.. /// </summary> internal static string Step_DownloadingFiles { get { return ResourceManager.GetString("Step_DownloadingFiles", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Getting the Android application Process ID.. /// </summary> internal static string Step_GettingAppProcessId { get { return ResourceManager.GetString("Step_GettingAppProcessId", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Inspecting properties of the device or emulator.. /// </summary> internal static string Step_InspectingDevice { get { return ResourceManager.GetString("Step_InspectingDevice", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Setting up the debugger connection to the device or emulator.. /// </summary> internal static string Step_PortForwarding { get { return ResourceManager.GetString("Step_PortForwarding", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Resolving paths to external dependencies.. /// </summary> internal static string Step_ResolveInstallPaths { get { return ResourceManager.GetString("Step_ResolveInstallPaths", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Starting the GDBServer process on the Android device or emulator.. /// </summary> internal static string Step_StartGDBServer { get { return ResourceManager.GetString("Step_StartGDBServer", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Starting the Android application.. /// </summary> internal static string Step_StartingApp { get { return ResourceManager.GetString("Step_StartingApp", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Waiting for the device or emulator to come online.. /// </summary> internal static string Step_WaitingForDeviceToComeOnline { get { return ResourceManager.GetString("Step_WaitingForDeviceToComeOnline", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Target architecture &apos;{0}&apos; is not supported.. /// </summary> internal static string UnsupportedTargetArchitecture { get { return ResourceManager.GetString("UnsupportedTargetArchitecture", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Setting up Android debugging.. /// </summary> internal static string WaitDialogText { get { return ResourceManager.GetString("WaitDialogText", resourceCulture); } } /// <summary> /// Looks up a localized string similar to C++ debugging can be unreliable in ARM emulators. Functionality such as stepping and breakpoints might not work as expected.. /// </summary> internal static string Warning_ArmEmulator { get { return ResourceManager.GetString("Warning_ArmEmulator", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Failed to connect to and resume the Android Java Virtual Machine.. /// </summary> internal static string Warning_JDbgResumeFailure { get { return ResourceManager.GetString("Warning_JDbgResumeFailure", resourceCulture); } } /// <summary> /// Looks up a localized string similar to This may be because a Java debugger, such as Eclipse, is already connected. Resume the Java debugger or close it.. /// </summary> internal static string Warning_JdbgVMUnavailable { get { return ResourceManager.GetString("Warning_JdbgVMUnavailable", resourceCulture); } } } } <|start_filename|>test/DebuggerTesting/OpenDebug/Commands/Command.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using DebugAdapterRunner; using DebuggerTesting.OpenDebug.Commands.Responses; using Newtonsoft.Json; using DarCommand = DebugAdapterRunner.Command; using DarRunner = DebugAdapterRunner.DebugAdapterRunner; namespace DebuggerTesting.OpenDebug.Commands { /// <summary> /// Base class for all Debug Adapter commands. Commands are issued and expect a response. /// </summary> /// <typeparam name="T">The class containing arguments to the command</typeparam> public abstract class Command<T> : DarCommand, ICommand where T : new() { public Command(string name) { Parameter.ThrowIfNull(name, nameof(name)); base.Name = name; this.Name = name; this.Args = new T(); this.SetExpectedResponse(success: true); this.Timeout = TimeSpan.Zero; } /// <summary> /// Call to set the expected success response of the command /// </summary> private void SetExpectedResponse(bool success) { this.ExpectedResponse = new CommandResponse(this.Name, success); } #region ICommand public new string Name { get; private set; } object ICommand.DynamicArgs { get { return Args; } } IResponse ICommand.ExpectedResponse { get { return this.ExpectedResponse; } } public virtual void ProcessActualResponse(IActualResponse response) { Parameter.ThrowIfNull(response, nameof(response)); CommandResponseValue commandResponse = response.Convert<CommandResponseValue>(); Parameter.ThrowIfNull(commandResponse, nameof(commandResponse)); this.Success = commandResponse.success; this.Message = commandResponse.message; } #endregion /// <summary> /// Arguments to the command. /// </summary> public T Args { get; protected set; } #region Response Handling protected IResponse ExpectedResponse { get; set; } public bool ExpectsSuccess { get { throw new NotImplementedException(); } set { this.SetExpectedResponse(success: value); } } public bool Success { get; private set; } public string Message { get; private set; } #endregion public TimeSpan Timeout { get; set; } #region Running public override void Run(DarRunner darRunner) { this.Run(darRunner, null); } public void Run(IDebuggerRunner runner, params IEvent[] expectedEvents) { Parameter.ThrowIfNull(runner, nameof(runner)); if (runner.ErrorEncountered) { runner.WriteLine("Previous error. Skipping command '{0}'.", this.Name); return; } try { this.Run(runner.DarRunner, runner, expectedEvents); } catch (Exception) { runner.ErrorEncountered = true; throw; } } /// <summary> /// Runs a command against the debugger. /// </summary> /// <param name="command">The command to run.</param> /// <param name="expectedEvents">[OPTIONAL] If the command causes an event to occur, pass the expected event(s)</param> private void Run(DarRunner darRunner, ILoggingComponent log, params IEvent[] expectedEvents) { Parameter.ThrowIfNull(darRunner, nameof(darRunner)); log?.WriteLine("Running command {0}", this.ToString()); log?.WriteLine("Command '{0}' expecting response: {1}", this.Name, this.ExpectedResponse.ToString()); DebugAdapterResponse darCommandResponse = GetDarResponse(this.ExpectedResponse); DebugAdapterCommand darCommand = new DebugAdapterCommand( this.Name, this.Args, new[] { darCommandResponse }); List<Tuple<DebugAdapterResponse, IEvent>> darEventMap = new List<Tuple<DebugAdapterResponse, IEvent>>(expectedEvents.Length); // Add additional expected events to match if requested if (expectedEvents != null && expectedEvents.Length > 0) { if (expectedEvents.Length > 1) log?.WriteLine("Command '{0}' expecting {1} events:", this.Name, expectedEvents.Length); foreach (var expectedEvent in expectedEvents) { DebugAdapterResponse darEventResponse = GetDarResponse(expectedEvent); darCommand.ExpectedResponses.Add(darEventResponse); darEventMap.Add(Tuple.Create(darEventResponse, expectedEvent)); // Debug info for expected response string eventMessage = expectedEvents.Length > 1 ? " - {1}" : "Command '{0}' expecting event: {1}"; log?.WriteLine(eventMessage, this.Name, expectedEvent.ToString()); } } // Allow the command to override the timeout int overrideTimeout = Convert.ToInt32(this.Timeout.TotalMilliseconds); int savedTimeout = darRunner.ResponseTimeout; try { if (overrideTimeout > 0) { darRunner.ResponseTimeout = overrideTimeout; log?.WriteLine("Command '{0}' timeout set to {1:n0} seconds.", this.Name, this.Timeout.TotalSeconds); } darCommand.Run(darRunner); // Allow the command to retrieve properties from the actual matched response. string responseJson = JsonConvert.SerializeObject(darCommandResponse.Match); if (!string.IsNullOrWhiteSpace(responseJson)) { this.ProcessActualResponse(new ActualResponse(responseJson)); } // Allow the events to retrieve properties from the actual event. foreach (var darEvent in darEventMap) { string eventJson = JsonConvert.SerializeObject(darEvent.Item1.Match); darEvent.Item2.ProcessActualResponse(new ActualResponse(eventJson)); } } catch (Exception ex) { // Add information to the log when the exception occurs log?.WriteLine("ERROR: Running command '{0}'. Exception thrown.", this.Name); log?.WriteLine(UDebug.ExceptionToString(ex)); // The DARException is not serializable, create a new exception if (ex is DARException) throw new RunnerException(ex.Message); else throw; } finally { if (overrideTimeout > 0) darRunner.ResponseTimeout = savedTimeout; } } // Create a DAR Response from an expected response private static DebugAdapterResponse GetDarResponse(IResponse response) { return new DebugAdapterResponse(response.DynamicResponse, response.IgnoreOrder, response.IgnoreResponseOrder); } #region ActualResponse /// <summary> /// Provides a way to get the command to interperet the actual result /// that comes back from the Debug Adapter. /// </summary> private class ActualResponse : IActualResponse { private string responseJson; public ActualResponse(string responseJson) { this.responseJson = responseJson; } public R Convert<R>() { try { return JsonConvert.DeserializeObject<R>(responseJson); } catch (JsonReaderException ex) { throw new FormatException("Malformed JSON: " + responseJson, ex); } } } #endregion #endregion public override string ToString() { return this.Name; } } public abstract class CommandWithResponse<T, R> : Command<T>, ICommandWithResponse<R> where T : new() where R : new() { public CommandWithResponse(string name) : base(name) { } public R ActualResponse { get; protected set; } public override void ProcessActualResponse(IActualResponse response) { base.ProcessActualResponse(response); this.ActualResponse = response.Convert<R>(); } public new R Run(IDebuggerRunner runner, params IEvent[] expectedEvents) { base.Run(runner, expectedEvents); return this.ActualResponse; } } } <|start_filename|>test/DebuggerTesting/Attribution/DebuggerSettings.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Linq; using DebuggerTesting.Utilities; namespace DebuggerTesting { internal sealed class DebuggerSettings : IDebuggerSettings { #region Constructor public DebuggerSettings( string debuggerName, SupportedDebugger debuggerType, string debuggerPath, string debuggerAdapterPath, string miMode, SupportedArchitecture debuggeeArchitecture, IDictionary<string, string> debuggerProperties) { this.DebuggeeArchitecture = debuggeeArchitecture; this.DebuggerName = debuggerName; this.DebuggerType = debuggerType; this.DebuggerPath = debuggerPath; this.DebuggerAdapterPath = debuggerAdapterPath; if (!string.IsNullOrWhiteSpace(miMode)) this.MIMode = miMode; this.Properties = debuggerProperties ?? new Dictionary<string, string>(StringComparer.Ordinal); } #endregion #region Methods public static bool operator ==(DebuggerSettings left, DebuggerSettings right) { if (Object.ReferenceEquals(left, null)) return Object.ReferenceEquals(right, null); return left.Equals(right); } public static bool operator !=(DebuggerSettings left, DebuggerSettings right) { if (Object.ReferenceEquals(left, null)) return !Object.ReferenceEquals(right, null); return !left.Equals(right); } public override bool Equals(object obj) { return this.Equals(obj as DebuggerSettings); } public bool Equals(DebuggerSettings obj) { if (Object.ReferenceEquals(obj, null)) return false; if (this.DebuggeeArchitecture != obj.DebuggeeArchitecture) return false; if (!String.Equals(this.DebuggerName, obj.DebuggerName, StringComparison.Ordinal)) return false; if (this.DebuggerType != obj.DebuggerType) return false; if (!String.Equals(this.DebuggerPath, obj.DebuggerPath, StringComparison.Ordinal)) return false; if (!String.Equals(this.MIMode, obj.MIMode, StringComparison.Ordinal)) return false; if (!Enumerable.SequenceEqual(this.Properties.Keys, obj.Properties.Keys, StringComparer.Ordinal)) return false; if (!Enumerable.SequenceEqual(this.Properties.Values, obj.Properties.Values, StringComparer.Ordinal)) return false; return true; } public override int GetHashCode() { return HashUtilities.CombineHashCodes( this.DebuggeeArchitecture.GetHashCode(), this.DebuggerName?.GetHashCode() ?? 0, this.DebuggerType.GetHashCode(), this.DebuggerPath?.GetHashCode() ?? 0, this.MIMode?.GetHashCode() ?? 0); } public override string ToString() { return "Debugger - Name: {0} Type: {1} ({2}) Path: {3} MIMode: {4}".FormatInvariantWithArgs(this.DebuggerName, this.DebuggerType, this.DebuggeeArchitecture, this.DebuggerPath, this.MIMode); } #endregion #region Properties public SupportedArchitecture DebuggeeArchitecture { get; private set; } public string DebuggerName { get; private set; } public SupportedDebugger DebuggerType { get; private set; } public string DebuggerPath { get; private set; } public string DebuggerAdapterPath { get; private set; } public string MIMode { get; private set; } public IDictionary<string, string> Properties { get; private set; } #endregion } } <|start_filename|>src/SSHDebugPS/VSOperationWaiter.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Threading.Tasks; using Microsoft.VisualStudio.Threading; using Microsoft.VisualStudio.Shell; using Task = System.Threading.Tasks.Task; using System.Threading; namespace Microsoft.SSHDebugPS.VS { internal static class VSOperationWaiter { /// <summary> /// Executes the specified action on a background thread, showing a wait dialog if it is available /// </summary> /// <param name="actionName">[Required] description of the action to show in the wait dialog</param> /// <param name="action">[Required] action to run</param> /// <param name="throwOnCancel">If specified, an OperationCanceledException is thrown if the operation is canceled</param> /// <returns>True if the operation succeed and wasn't canceled</returns> /// <exception cref="OperationCanceledException">Wait was canceled and 'throwOnCancel' is true</exception> public static bool Wait(string actionName, bool throwOnCancel, Action<CancellationToken> action) { try { ThreadHelper.JoinableTaskFactory.Run( actionName, async (progress, cancellationToken) => { await Task.Run(() => action(cancellationToken), cancellationToken); } ); } catch (OperationCanceledException) { if (throwOnCancel) throw; else return false; } return true; } } } <|start_filename|>src/DebugEngineHost/VSImpl/VsWaitDialog.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio; using System.Globalization; namespace Microsoft.DebugEngineHost.VSImpl { internal class VSWaitDialog { private readonly IVsThreadedWaitDialog2 _waitDialog; private const int m_delayShowDialogTimeInSeconds = 2; private bool _started; private string _format; private string _caption; public VSWaitDialog(string format, string caption) { _format = format; _caption = caption; var waitDialogFactory = (IVsThreadedWaitDialogFactory)Package.GetGlobalService(typeof(SVsThreadedWaitDialogFactory)); if (waitDialogFactory == null) { return; // normal case in glass } IVsThreadedWaitDialog2 waitDialog; int hr = waitDialogFactory.CreateInstance(out waitDialog); if (hr != VSConstants.S_OK) return; _waitDialog = waitDialog; _started = false; } public void ShowWaitDialog(string item) { if (_waitDialog == null) { return; } lock (_waitDialog) { string message = String.Format(CultureInfo.CurrentCulture, _format, item); int hr; if (!_started) { hr = _waitDialog.StartWaitDialog( _caption, message, "", "", message, m_delayShowDialogTimeInSeconds, /*fIsCancelable*/ false, /*fShowMarqueeProgress*/ true ); } else { bool canceled; hr = _waitDialog.UpdateProgress(message, "", message, 0, 0, /*fDisableCancel*/true, out canceled); } if (hr != VSConstants.S_OK) return; _started = true; } } public void EndWaitDialog() { if (_waitDialog == null) { return; } lock (_waitDialog) { int canceled; if (!_started) return; int hr = _waitDialog.EndWaitDialog(out canceled); if (hr != VSConstants.S_OK) return; _started = false; } } } } <|start_filename|>test/DebuggerTesting/Utilities/Windows/WindowsProcessNativeMethods.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Globalization; using System.Runtime.InteropServices; namespace DebuggerTesting.Utilities.Windows { /// <summary> /// P/Invoke APIs to get process information /// </summary> internal static class WindowsProcessNativeMethods { #region CreateToolhelp32Snapshot [Flags] private enum SnapshotFlags : uint { Inherit = 0x80000000, All = (HeapList | Process | Thread | Module | Module32), HeapList = 0x00000001, Process = 0x00000002, Thread = 0x00000004, Module = 0x00000008, Module32 = 0x00000010, } [DllImport("kernel32.dll", SetLastError = true)] private static extern IntPtr CreateToolhelp32Snapshot([In] SnapshotFlags flags, [In] uint processId); #endregion #region Process32 [StructLayout(LayoutKind.Sequential)] private struct ProcessEntry32 { public ProcessEntry32(uint? size) : this() { this.size = size ?? (uint)PlatformUtilities.MarshalSizeOf<ProcessEntry32>(); } const int MAX_PATH = 260; public uint size; public uint unused; public uint processId; public UIntPtr defaultHeapId; public uint moduleId; public uint cntThreads; public uint parentProcessId; public int pcPriClassBase; public uint flags; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = MAX_PATH)] public string exeFile; } private const int ERROR_NO_MORE_FILES = 18; [DllImport("kernel32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool Process32First([In] IntPtr snapshot, [In, Out] ref ProcessEntry32 processEntry); [DllImport("kernel32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool Process32Next([In] IntPtr snapshot, [In, Out] ref ProcessEntry32 processEntry); private static ProcessEntry32 Process32First(IntPtr snapshot) { ProcessEntry32 processEntry = new ProcessEntry32(size: null); if (!Process32First(snapshot, ref processEntry)) { int error = Marshal.GetLastWin32Error(); if (error != ERROR_NO_MORE_FILES) throw new InvalidOperationException("Win32 Error 0x" + error.ToString("X8", CultureInfo.InvariantCulture)); } return processEntry; } #endregion #region CloseHandle [DllImport("kernel32", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool CloseHandle([In] IntPtr handle); #endregion /// <summary> /// Gets the parent process id /// </summary> public static int? GetParentProcessId(int processId) { IntPtr snapshot = IntPtr.Zero; try { snapshot = CreateToolhelp32Snapshot(SnapshotFlags.Process, 0); ProcessEntry32 processEntry = Process32First(snapshot); do { if (processEntry.processId == processId) return (int)processEntry.parentProcessId; } while (Process32Next(snapshot, ref processEntry)); } catch (Exception) { } finally { if (snapshot != IntPtr.Zero) CloseHandle(snapshot); } return null; } } } <|start_filename|>src/OpenDebugAD7/AD7Impl/AD7DocumentPosition.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Globalization; using Microsoft.DebugEngineHost; using Microsoft.VisualStudio.Debugger.Interop; namespace OpenDebugAD7.AD7Impl { internal sealed class AD7DocumentPosition : IDebugDocumentPosition2, IDebugDocumentPosition110 { public string Path { get { return _document?.Path; } } public int Line { get; private set; } private SessionConfiguration _config; private Document _document; public AD7DocumentPosition(SessionConfiguration config, string path, int line) { _config = config; _document = Document.GetOrCreate(path); Line = line; } public int GetFileName(out string pbstrFileName) { pbstrFileName = Path; return 0; } public int GetDocument(out IDebugDocument2 ppDoc) { throw new NotImplementedException(); } public int IsPositionInDocument(IDebugDocument2 pDoc) { throw new NotImplementedException(); } public int GetRange(TEXT_POSITION[] pBegPosition, TEXT_POSITION[] pEndPosition) { pBegPosition[0].dwLine = (uint)Line; pBegPosition[0].dwColumn = 0; pEndPosition[0].dwLine = (uint)Line; pEndPosition[0].dwColumn = 0; return 0; } public int GetChecksum(ref Guid guidAlgorithm, CHECKSUM_DATA[] checksumData) { checksumData[0].ByteCount = 0; checksumData[0].pBytes = IntPtr.Zero; return HRConstants.E_NOTIMPL; } public int IsChecksumEnabled(out int fChecksumEnabled) { fChecksumEnabled = 0; if (_config.RequireExactSource) { // TODO: see comment in GetChecksum fChecksumEnabled = 0; } return HRConstants.S_OK; } public int GetLanguage(out Guid pguidLanguage) { throw new NotImplementedException(); } public int GetText(out string pbstrText) { throw new NotImplementedException(); } } internal class ChecksumNormalizationException : Exception { public ChecksumNormalizationException(string message) : base(message) { } } internal class AD7FunctionPosition : IDebugFunctionPosition2 { public string Name { get; private set; } public AD7FunctionPosition(string name) { Name = name; } public int GetFunctionName(out string pbstrFunctionName) { pbstrFunctionName = Name; return HRConstants.S_OK; } public int GetOffset(TEXT_POSITION[] pPosition) { return HRConstants.E_NOTIMPL; } } } <|start_filename|>test/DebuggerTesting/OpenDebug/Commands/Responses/DisassembleResponseValue.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Newtonsoft.Json; namespace DebuggerTesting.OpenDebug.Commands.Responses { public sealed class DisassembleResponseValue : CommandResponseValue { public sealed class Body { public sealed class DisassembledInstruction { public string address; [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public string instructionBytes; public string instruction; [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public string symbol; [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public Source location; [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public int? line; [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public int? column; [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public int? endLine; [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public int? endColumn; } public DisassembledInstruction[] instructions; } public Body body = new Body(); } } <|start_filename|>src/MICore/InvalidLaunchOptionsException.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Globalization; namespace MICore { public class InvalidLaunchOptionsException : Exception { internal InvalidLaunchOptionsException(string problemDescription) : base(string.Format(CultureInfo.CurrentCulture, MICoreResources.Error_InvalidLaunchOptions, problemDescription)) { } } } <|start_filename|>src/SSHDebugPS/Utilities/TelemetryHelper.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.SSHDebugPS.Utilities { internal static class TelemetryHelper { public const string Event_DockerPSParseFailure = @"VS/Diagnostics/Debugger/SSHDebugPS/DockerPSParseFailure"; public const string Event_ProcFSError = @"VS/Diagnostics/Debugger/SSHDebugPS/ProcFSError"; public static readonly string Property_ExceptionName = "vs.diagnostics.debugger.ExceptionName"; } } <|start_filename|>test/CppTests/debuggees/sharedlib/src/sharedlib.h<|end_filename|> #pragma once #include <iostream> #include <string> using namespace std; #ifdef WIN32_SHARED_LIBRARY // *********** Win32 Shared Library Implementation ************* #include <windows.h> typedef HINSTANCE LIBRARY_HANDLE; LIBRARY_HANDLE OpenLibrary(string libraryName) { return LoadLibraryA(libraryName.c_str()); } bool CloseLibrary(LIBRARY_HANDLE library) { return FreeLibrary(library) == TRUE; } void* GetLibraryFunction(LIBRARY_HANDLE library, string functionName) { return (void*)GetProcAddress(library, functionName.c_str()); } void LogLibraryError(string location) { cout << "Error in " << location << ": " << GetLastError() << endl; } #else // *********** POSIX Shared Library Implementation ************* #include <dlfcn.h> typedef void* LIBRARY_HANDLE; LIBRARY_HANDLE OpenLibrary(string libraryName) { return dlopen(libraryName.c_str(), RTLD_LAZY); } bool CloseLibrary(LIBRARY_HANDLE library) { return dlclose(library) == 0; } void* GetLibraryFunction(LIBRARY_HANDLE library, string functionName) { return dlsym(library, functionName.c_str()); } void LogLibraryError(string location) { cout << "Error in " << location << ": " << dlerror() << endl; } #endif <|start_filename|>test/DebuggerTesting/OpenDebug/Extensions/FrameInspector.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using System.Text; using DebuggerTesting.OpenDebug.Commands; using DebuggerTesting.OpenDebug.Commands.Responses; using DebuggerTesting.Utilities; namespace DebuggerTesting.OpenDebug.Extensions { internal class FrameInspector : DisposableObject, IFrameInspector { private int? variablesReference; private Dictionary<string, IVariableInspector> variables; private string name; private int id; private string sourceName; private string sourcePath; private int? line; private int? column; private int? sourceReference; private string instructionPointerReference; #region Constructor/Dispose public FrameInspector(IDebuggerRunner runner, string name, int id, string sourceName, string sourcePath, int? sourceReference, int? line, int? column, string instructionPointerReference) { Parameter.ThrowIfNull(runner, nameof(runner)); this.DebuggerRunner = runner; this.name = name; this.id = id; this.sourceName = sourceName; this.sourcePath = sourcePath; this.sourceReference = sourceReference; this.line = line; this.column = column; this.instructionPointerReference = instructionPointerReference; } protected override void Dispose(bool isDisposing) { if (isDisposing) { DisposableHelper.SafeDisposeAll(this.variables?.Values); this.variables = null; this.DebuggerRunner = null; } base.Dispose(IsDisposed); } #endregion #region Frame Info public IDebuggerRunner DebuggerRunner { get; private set; } public string Name { get { this.VerifyNotDisposed(); return this.name; } } public int Id { get { this.VerifyNotDisposed(); return this.id; } } public string SourceName { get { this.VerifyNotDisposed(); return this.sourceName; } } public string SourcePath { get { this.VerifyNotDisposed(); return this.sourcePath; } } public int? SourceReference { get { this.VerifyNotDisposed(); return this.sourceReference; } } public int? Line { get { this.VerifyNotDisposed(); return this.line; } } public int? Column { get { this.VerifyNotDisposed(); return this.column; } } public string InstructionPointerReference { get { this.VerifyNotDisposed(); return this.instructionPointerReference; } } #endregion /// <summary> /// Gets the local variables on this frame. /// </summary> public IDictionary<string, IVariableInspector> Variables { get { this.VerifyNotDisposed(); if (this.variables == null) { // Ensure the scope has been created if (this.variablesReference == null) { ScopesCommand scopesCommand = new ScopesCommand(this.Id); this.DebuggerRunner.RunCommand(scopesCommand); this.variablesReference = scopesCommand.VariablesReference; } if (this.variablesReference == null || this.variablesReference == 0) return null; // Get the variables this.variables = VariableInspector.GetChildVariables(this.DebuggerRunner, this.variablesReference.Value); } return this.variables; } } /// <summary> /// Evaluates an expression on this frame. /// WARNING: if an expression has side effects, you will need to Refresh the IInspector and /// get the stack information to get up to date info. /// </summary> public string Evaluate(string expression, EvaluateContext context = EvaluateContext.None) { this.VerifyNotDisposed(); EvaluateResponseValue response = this.DebuggerRunner.RunCommand(new EvaluateCommand(expression, this.Id, context)); return response.body.result; } public string GetSourceContent() { this.VerifyNotDisposed(); if (this.sourceReference == null) return null; return this.DebuggerRunner.RunCommand(new SourceCommand(this.sourceReference.Value))?.body?.content; } public override string ToString() { StringBuilder sb = new StringBuilder(this.Name); sb.Append(" ("); sb.Append(this.Id); sb.Append(")"); if (this.SourceName != null) { sb.Append(" ["); sb.Append(this.SourceName); if (this.Line != null) { sb.Append(":"); sb.Append(this.Line.Value); } sb.Append("]"); } return sb.ToString(); } } } <|start_filename|>test/CppTests/Tests/SinkHelper.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.IO; using DebuggerTesting; using DebuggerTesting.Compilation; using Xunit; namespace CppTests.Tests { /// <summary> /// Helpers to use the kitchen sink debuggee /// </summary> internal static class SinkHelper { public const string Main = "main.cpp"; public const string Arguments = "arguments.cpp"; public const string Calling = "calling.cpp"; public const string Feature = "feature.cpp"; public const string Threading = "threading.cpp"; public const string NonTerminating = "nonterminating.cpp"; public const string Expression = "expression.cpp"; public const string Environment = "environment.cpp"; private const string Name = "kitchensink"; private const string OutputName = "sink"; public static IDebuggee Open(ILoggingComponent logger, ICompilerSettings settings, int moniker) { return DebuggeeHelper.Open(logger, settings, moniker, SinkHelper.Name, SinkHelper.OutputName); } public static IDebuggee OpenAndCompile(ILoggingComponent logger, ICompilerSettings settings, int moniker) { return DebuggeeHelper.OpenAndCompile(logger, settings, moniker, SinkHelper.Name, SinkHelper.OutputName, SinkHelper.AddSourceFiles); } private static void AddSourceFiles(IDebuggee debuggee) { // Add a source files, specify type, compile debuggee.AddSourceFiles( SinkHelper.Main, SinkHelper.Arguments, SinkHelper.Calling, SinkHelper.Environment, SinkHelper.Feature, SinkHelper.Threading, SinkHelper.NonTerminating, SinkHelper.Expression); debuggee.CompilerOptions |= CompilerOption.SupportThreading; } } } <|start_filename|>src/SSHDebugPS/UI/ViewModels/ContainerPickerViewModel.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.IO; using System.Linq; using System.Windows.Threading; using liblinux.Persistence; using Microsoft.SSHDebugPS.Docker; using Microsoft.SSHDebugPS.SSH; using Microsoft.SSHDebugPS.Utilities; using System.Globalization; using Microsoft.VisualStudio.Shell; namespace Microsoft.SSHDebugPS.UI { public class ContainerPickerViewModel : INotifyPropertyChanged { private Lazy<bool> _sshAvailable; public ContainerPickerViewModel(bool supportSSHConnections) { ThreadHelper.ThrowIfNotOnUIThread(); SupportSSHConnections = supportSSHConnections; InitializeConnections(); ContainerInstances = new ObservableCollection<IContainerViewModel>(); // SSH is only available if we have Linux containers. _sshAvailable = new Lazy<bool>(() => SupportSSHConnections && IsLibLinuxAvailable()); AddSSHConnectionCommand = new ContainerUICommand( AddSSHConnection, (parameter /*unused parameter*/) => { return _sshAvailable.Value; }, UIResources.AddNewSSHConnectionLabel, UIResources.AddNewSSHConnectionToolTip); OKCommand = new ContainerUICommand( (dialogObject) => { ContainerPickerDialogWindow dialog = dialogObject as ContainerPickerDialogWindow; dialog.DialogResult = ComputeContainerConnectionString(); dialog.Close(); }, (parameter /*unused*/) => { return SelectedContainerInstance != null; }, UIResources.OKLabel, UIResources.OKLabel ); CancelCommand = new ContainerUICommand( (dialogObject) => { ContainerPickerDialogWindow dialog = dialogObject as ContainerPickerDialogWindow; dialog.Close(); }, UIResources.CancelLabel, UIResources.CancelLabel ); RefreshCommand = new ContainerUICommand( (parameter /*unused*/) => { RefreshContainersList(); }, (parameter /*unused*/) => { return IsRefreshEnabled; }, UIResources.RefreshHyperlink, UIResources.RefreshToolTip); PropertyChanged += ContainerPickerViewModel_PropertyChanged; SelectedConnection = SupportedConnections.First(item => item is LocalConnectionViewModel) ?? SupportedConnections.First(); } private void InitializeConnections() { List<IConnectionViewModel> connections = new List<IConnectionViewModel>(); connections.Add(new LocalConnectionViewModel()); if (SupportSSHConnections) // we currently only support SSH for Linux Containers { connections.AddRange(SSHHelper.GetAvailableSSHConnectionInfos().Select(item => new SSHConnectionViewModel(item))); } SupportedConnections = new ObservableCollection<IConnectionViewModel>(connections); OnPropertyChanged(nameof(SupportedConnections)); } internal void RefreshContainersList() { ThreadHelper.ThrowIfNotOnUIThread(); IsRefreshEnabled = false; // Clear everything before retreiving the container list ContainerInstances?.Clear(); UpdateStatusMessage(string.Empty, false); // Set the status ContainersFoundText = UIResources.QueryingForContainersMessage; // Tell the dispatcher to run the Refresh task with a lower priority than Render. // This is so that the UI does any necessary updating before the refresh task has completed. // Render = 7 // Loaded = 6 - Operations are processed when layout and render has finished but just before items at input priority are serviced. // https://docs.microsoft.com/en-us/dotnet/api/system.windows.threading.dispatcherpriority #pragma warning disable VSTHRD001 // Avoid legacy thread switching APIs _ = Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Input, (Action)(() => { RefreshContainersListInternal(); })); #pragma warning restore VSTHRD001 // Avoid legacy thread switching APIs } private bool ComputeContainerConnectionString() { if (SelectedContainerInstance != null) { string remoteConnectionString = string.Empty; string containerId; if (SelectedConnection.Connection == null) { SelectedContainerInstance.GetResult(out containerId); } else { SelectedContainerInstance.GetResult(out containerId); remoteConnectionString = SelectedConnection.Connection.Name; } SelectedContainerConnectionString = DockerConnection.CreateConnectionString(containerId, remoteConnectionString, Hostname); return true; } return false; } // The formatted string for the ConnectionType dialog public string SelectedContainerConnectionString { get; private set; } private const string unknownOS = "Unknown"; private void RefreshContainersListInternal() { int totalContainers = 0; try { IContainerViewModel selectedContainer = SelectedContainerInstance; SelectedContainerInstance = null; IEnumerable<DockerContainerInstance> containers; if (SelectedConnection is LocalConnectionViewModel) { containers = DockerHelper.GetLocalDockerContainers(Hostname, out totalContainers); } else { ContainersFoundText = UIResources.SSHConnectingStatusText; var connection = SelectedConnection.Connection; if (connection == null) { UpdateStatusMessage(UIResources.SSHConnectionFailedStatusText, isError: true); return; } containers = DockerHelper.GetRemoteDockerContainers(connection, Hostname, out totalContainers); } if (containers.Any()) { string serverOS; if (DockerHelper.TryGetServerOS(Hostname, out serverOS)) { bool lcow; bool getLCOW = DockerHelper.TryGetLCOW(Hostname, out lcow); TextInfo textInfo = new CultureInfo("en-US", false).TextInfo; serverOS = textInfo.ToTitleCase(serverOS); /* Note: LCOW is the abbreviation for Linux Containers on Windows * * In LCOW, both Linux and Windows containers can run simultaneously in a Docker (Windows) Engine. * Thus, the container platform must be queried directly. * Otherwise, the container platform must match that of the server engine. */ if (lcow && serverOS.Contains("Windows")) { foreach (DockerContainerInstance container in containers) { string containerPlatform = string.Empty; if (DockerHelper.TryGetContainerPlatform(Hostname, container.Name, out containerPlatform)) { container.Platform = textInfo.ToTitleCase(containerPlatform); } else { container.Platform = unknownOS; } } } else { foreach (DockerContainerInstance container in containers) { container.Platform = serverOS; } } } else { foreach (DockerContainerInstance container in containers) { container.Platform = unknownOS; } } } ContainerInstances = new ObservableCollection<IContainerViewModel>(containers.Select(item => new DockerContainerViewModel(item)).ToList()); OnPropertyChanged(nameof(ContainerInstances)); if (ContainerInstances.Count > 0) { if (selectedContainer != null) { var found = ContainerInstances.FirstOrDefault(c => selectedContainer.Equals(c)); if (found != null) { SelectedContainerInstance = found; return; } } SelectedContainerInstance = ContainerInstances[0]; } } catch (Exception ex) { UpdateStatusMessage(UIResources.ErrorStatusTextFormat.FormatCurrentCultureWithArgs(ex.Message), isError: true); return; } finally { if (ContainerInstances.Count > 0) { if (ContainerInstances.Count < totalContainers) { UpdateStatusMessage(UIResources.ContainersNotAllParsedStatusText.FormatCurrentCultureWithArgs(totalContainers - ContainerInstances.Count), isError: false); ContainersFoundText = UIResources.ContainersNotAllParsedText.FormatCurrentCultureWithArgs(ContainerInstances.Count, totalContainers); } else { ContainersFoundText = UIResources.ContainersFoundStatusText.FormatCurrentCultureWithArgs(ContainerInstances.Count); } } else { ContainersFoundText = UIResources.NoContainersFound; } IsRefreshEnabled = true; } } private static void AddSSHConnection(object parameter) { ThreadHelper.ThrowIfNotOnUIThread(); if (parameter is ContainerPickerViewModel vm && vm.AddSSHConnectionCommand.CanExecute(parameter)) { SSHConnection connection = ConnectionManager.GetSSHConnection(string.Empty) as SSHConnection; if (connection != null) { SSHConnectionViewModel sshConnection = new SSHConnectionViewModel(connection); vm.SupportedConnections.Add(sshConnection); vm.SelectedConnection = sshConnection; } } else { Debug.Fail("Unable to call AddSSHConnection"); } } private bool IsLibLinuxAvailable() { ThreadHelper.ThrowIfNotOnUIThread(); try { return SSHPortSupplier.IsLibLinuxAvailable(); } catch (FileNotFoundException) { return false; } } // Default is to Support SSH Connections private bool _supportSSHConnections = true; public bool SupportSSHConnections { get { return _supportSSHConnections; } private set { _supportSSHConnections = value; OnPropertyChanged(nameof(SupportSSHConnections)); } } #region Commands public IContainerUICommand AddSSHConnectionCommand { get; } public IContainerUICommand OKCommand { get; } public IContainerUICommand CancelCommand { get; } public IContainerUICommand RefreshCommand { get; } #endregion #region Event, EventHandlers and Properties public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged(string name) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name)); } private void ContainerPickerViewModel_PropertyChanged(object sender, PropertyChangedEventArgs e) { ThreadHelper.ThrowIfNotOnUIThread(); if (string.Equals(e.PropertyName, nameof(SelectedConnection), StringComparison.Ordinal)) { RefreshContainersList(); } } private string _hostname; public string Hostname { get => _hostname; set { if (!string.Equals(_hostname, value, StringComparison.Ordinal)) { _hostname = value; // If the user is updating the hostname, clear the container list and the selected container list. SelectedContainerInstance = null; ContainerInstances?.Clear(); OnPropertyChanged(nameof(Hostname)); } } } private string _containersFoundText; public string ContainersFoundText { get => _containersFoundText; set { _containersFoundText = value; OnPropertyChanged(nameof(ContainersFoundText)); } } public void UpdateStatusMessage(string statusMessage, bool isError) { // If the message is updated to empty, we want to clear the StatusIsError value. if (string.IsNullOrEmpty(statusMessage)) { if (!string.IsNullOrEmpty(_statusMessage)) { _statusMessage = statusMessage; OnPropertyChanged(nameof(StatusMessage)); } if (_statusIsError != false) { _statusIsError = false; OnPropertyChanged(nameof(StatusIsError)); } return; } if (!string.Equals(_statusMessage, statusMessage, StringComparison.Ordinal)) { _statusMessage = statusMessage; OnPropertyChanged(nameof(StatusMessage)); if (_statusIsError != isError) { _statusIsError = isError; OnPropertyChanged(nameof(StatusIsError)); } return; } } private string _statusMessage; public string StatusMessage { get => _statusMessage; } private bool _statusIsError; public bool StatusIsError { get => _statusIsError; } public ObservableCollection<IConnectionViewModel> SupportedConnections { get; private set; } public ObservableCollection<IContainerViewModel> ContainerInstances { get; private set; } private bool _isRefreshEnabled = true; public bool IsRefreshEnabled { get => _isRefreshEnabled; set { if (_isRefreshEnabled != value) { _isRefreshEnabled = value; OnPropertyChanged(nameof(IsRefreshEnabled)); } RefreshCommand.NotifyCanExecuteChanged(); } } private IContainerViewModel _selectedContainerInstance; public IContainerViewModel SelectedContainerInstance { get => _selectedContainerInstance; set { // checking cases that they are not equal if (!object.Equals(_selectedContainerInstance, value)) { _selectedContainerInstance = value; OnPropertyChanged(nameof(SelectedContainerInstance)); } // Update the status of the OK button OKCommand.NotifyCanExecuteChanged(); } } private IConnectionViewModel _selectedConnection; public IConnectionViewModel SelectedConnection { get => _selectedConnection; set { if ((_selectedConnection != null && _selectedConnection != value) || (_selectedConnection == null && value != null)) { _selectedConnection = value; OnPropertyChanged(nameof(SelectedConnection)); } } } #endregion } } <|start_filename|>test/CppTests/debuggees/kitchensink/src/feature.h<|end_filename|> #pragma once #include "global.h" #include <iostream> #include <vector> #include <string> using namespace std; class Feature { public: Feature(string name); virtual ~Feature() {} string GetName(); void Run(); void Log(); // These logging function seem to need to be inline, I'm guessing it is // because the signatures are created on demand. template <typename T> void Log(const T& t) { cout << t << endl; } template <typename First, typename... Rest> void Log(const First& first, const Rest&... rest) { // Logs the first item, then recurse cout << first; this->Log(rest...); } virtual void CoreRun() = 0; private: string _name; }; <|start_filename|>test/CppTests/debuggees/optimization/src/foo.h<|end_filename|> #pragma once #include <vector> using std::vector; /* Author : <NAME> Date : 2016-7-24 Desc : Encapsuate a class for suming of collection */ class Foo { public: Foo(); Foo(int num); int Sum(); private: bool Validate(int number); void FillContainer(); int number; vector<int> m_collection; }; <|start_filename|>test/DebuggerTesting/ICompilerSettings.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; namespace DebuggerTesting { /// <summary> /// Interface describing the settings used to compile a debuggee. /// </summary> public interface ICompilerSettings { #region Properties string CompilerName { get; } SupportedCompiler CompilerType { get; } string CompilerPath { get; } SupportedArchitecture DebuggeeArchitecture { get; } IDictionary<string, string> Properties { get; } #endregion } } <|start_filename|>test/CppTests/debuggees/sharedlib/src/global.h<|end_filename|> #pragma once #define STRINGIFY2( x) #x #define STRINGIFY(x) STRINGIFY2(x) #ifdef _MINGW #define WIN32_SHARED_LIBRARY #endif #ifdef _WIN32 #define WIN32_SHARED_LIBRARY #endif <|start_filename|>src/SSHDebugPS/VsOutputWindowWrapper.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Threading; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; namespace Microsoft.SSHDebugPS { internal static class VsOutputWindowWrapper { private static Lazy<IVsOutputWindow> outputWindowLazy = new Lazy<IVsOutputWindow>(() => { IVsOutputWindow outputWindow = null; try { ThreadHelper.ThrowIfNotOnUIThread(); outputWindow = Package.GetGlobalService(typeof(SVsOutputWindow)) as IVsOutputWindow; } catch (Exception) { Debug.Fail("Could not get OutputWindow service."); } return outputWindow; }, LazyThreadSafetyMode.PublicationOnly); private static Lazy<IVsUIShell> shellLazy = new Lazy<IVsUIShell>(() => { IVsUIShell shell = null; try { ThreadHelper.ThrowIfNotOnUIThread(); shell = Package.GetGlobalService(typeof(SVsUIShell)) as IVsUIShell; } catch (Exception) { Debug.Fail("Could not get VSShell service."); } return shell; // Use "PublicationOnly", because the implementation of GetService does its own locking }, LazyThreadSafetyMode.PublicationOnly); private class PaneInfo { public PaneInfo(Guid paneId) { this.paneId = paneId; this.Shown = false; } internal Guid paneId; internal bool Shown { get; set; } } private const string DefaultOutputPane = "Debug"; private static Dictionary<string, PaneInfo> panes = new Dictionary<string, PaneInfo>() { // The 'Debug' pane exists by default { DefaultOutputPane, new PaneInfo(VSConstants.GUID_OutWindowDebugPane) } }; /// <summary> /// Writes text directly to the VS Output window. /// </summary> public static void Write(string message, string pane = DefaultOutputPane) { ThreadHelper.JoinableTaskFactory.RunAsync(async delegate { await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); try { // Get the Output window IVsOutputWindow outputWindow = outputWindowLazy.Value; if (outputWindow == null) { return; } // Get the pane guid PaneInfo paneInfo; if (!panes.TryGetValue(pane, out paneInfo)) { // Pane didn't exist, create it paneInfo = new PaneInfo(Guid.NewGuid()); panes.Add(pane, paneInfo); } // Get the pane IVsOutputWindowPane outputPane; if (outputWindow.GetPane(ref paneInfo.paneId, out outputPane) != VSConstants.S_OK) { // Failed to get the pane - might need to create it first outputWindow.CreatePane(ref paneInfo.paneId, pane, fInitVisible: 1, fClearWithSolution: 1); outputWindow.GetPane(ref paneInfo.paneId, out outputPane); } // The first time we output text to a pane, ensure it's visible if (!paneInfo.Shown) { paneInfo.Shown = true; // Switch to the pane of the Output window outputPane.Activate(); // Show the output window IVsUIShell shell = shellLazy.Value; if (shell != null) { object inputVariant = null; shell.PostExecCommand(VSConstants.GUID_VSStandardCommandSet97, (uint)VSConstants.VSStd97CmdID.OutputWindow, 0, ref inputVariant); } } // Output the text outputPane.OutputString(message); } catch (Exception) { Debug.Fail("Failed to write to output pane."); } }).FileAndForget("VS/Diagnostics/Debugger/SSHDebugPS/VsOutputWindowWrapper/Write"); } /// <summary> /// Writes text directly to the VS Output window, appending a newline. /// </summary> public static void WriteLine(string message, string pane = DefaultOutputPane) { Write(string.Concat(message, Environment.NewLine), pane); } } } <|start_filename|>src/MICore/ProcessMonitor.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Threading; namespace MICore { public class ProcessMonitor : IDisposable { private readonly TimeSpan _EXIT_POLL_DELTA = TimeSpan.FromMilliseconds(200); private int _processId; private Timer _exitMonitorTimer; public ProcessMonitor(int processId) { if (!PlatformUtilities.IsLinux() && !PlatformUtilities.IsOSX()) { throw new NotImplementedException(); } _processId = processId; } public void Start() { _exitMonitorTimer = new Timer(MonitorForExit, null, TimeSpan.FromMilliseconds(0), _EXIT_POLL_DELTA); } public event EventHandler ProcessExited; private bool HasExited() { return !UnixUtilities.IsProcessRunning(_processId); } private void MonitorForExit(object o) { if (HasExited()) { _exitMonitorTimer.Dispose(); ProcessExited?.Invoke(this, null); } } public void Dispose() { _exitMonitorTimer?.Dispose(); GC.SuppressFinalize(this); } } } <|start_filename|>src/MICore/IncludeExcludeList.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Text.RegularExpressions; namespace MICore.SymbolLocator { public class IncludeExcludeList { static readonly char[] WildCardCharacters = new char[] { '*', '?' }; Lazy<List<Regex>> _wildcardEntries; Lazy<HashSet<string>> _qualifiedEntries; public bool IsEmpty { get { return !_wildcardEntries.IsValueCreated && !_qualifiedEntries.IsValueCreated; } } public IncludeExcludeList() { Clear(); } public void Add(string entry) { if (string.IsNullOrEmpty(entry)) return; if (entry.IndexOfAny(WildCardCharacters) >= 0) { // Entry is a wild card. Convert to a Regex. StringBuilder regexStringBuilder = new StringBuilder(); regexStringBuilder.Append('^'); regexStringBuilder.Append(Regex.Escape(entry)); regexStringBuilder.Append('$'); regexStringBuilder.Replace("\\*", ".*"); regexStringBuilder.Replace("\\?", "."); _wildcardEntries.Value.Add(new Regex(regexStringBuilder.ToString(), RegexOptions.CultureInvariant)); } else { _qualifiedEntries.Value.Add(entry); } } public bool Contains(string moduleName) { if (!_qualifiedEntries.IsValueCreated && !_wildcardEntries.IsValueCreated) { // the list is empty return false; } if (_qualifiedEntries.IsValueCreated) { if (_qualifiedEntries.Value.Contains(moduleName)) { return true; } // To handle entries without extension, try removing the extension from the module name and matching that string moduleNameWithoutExtension = Path.GetFileNameWithoutExtension(moduleName); if (_qualifiedEntries.Value.Contains(moduleNameWithoutExtension)) { return true; } } if (_wildcardEntries.IsValueCreated) { foreach (Regex regex in _wildcardEntries.Value) { if (regex.IsMatch(moduleName)) { return true; } } } return false; } public void Clear() { if (_wildcardEntries == null || _wildcardEntries.IsValueCreated) { _wildcardEntries = new Lazy<List<Regex>>(() => new List<Regex>()); } if (_qualifiedEntries == null || _qualifiedEntries.IsValueCreated) { _qualifiedEntries = new Lazy<HashSet<string>>(() => new HashSet<string>(StringComparer.Ordinal)); } } public void SetTo(IEnumerable<string> items) { Clear(); foreach (string item in items) { Add(item); } } } } <|start_filename|>test/DebugAdapterRunner/Utils.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Newtonsoft.Json.Linq; using System.Linq; using System.Text.RegularExpressions; namespace DebugAdapterRunner { internal class Utils { /// <summary>Returns whether the given array matches the pattern specified in the 'expected' array</summary> /// <returns>True if matching, false otherwise</returns> /// <remarks>The 'expected' array contains a list of elements that are searched in the actual array /// The actual array can have more elements. Whether the order of elements matters is up to /// the 'ignoreOrder' flag</remarks> private static bool CompareArrays(JArray expected, JArray actual, bool ignoreOrder) { return ignoreOrder ? CompareArraysUnordered(expected, actual) : CompareArraysInOrder(expected, actual); } /// <summary>Returns whether the given array contains each of the patterns specified in the 'expected' array in order.</summary> /// <returns>True if matching, false otherwise</returns> /// <remarks>The 'expected' array contains a list of elements that are searched in the actual array /// The actual array can have more elements. The order of elements in the 'actual' array must /// match the order found in the expected array</remarks> private static bool CompareArraysInOrder(JArray expected, JArray actual) { int currentExpectedIndex = 0; int currentActualIndex = 0; JToken[] expectedChildren = expected.Children().ToArray(); JToken[] actualChildren = actual.Children().ToArray(); while (currentExpectedIndex < expectedChildren.Length) { JToken expectedMember = expectedChildren[currentExpectedIndex]; bool foundMatching = false; while (currentActualIndex < actualChildren.Length) { JToken actualMember = actualChildren[currentActualIndex]; if (!CompareObjects(expectedMember.Value<object>(), actualMember.Value<object>(), ignoreOrder: false)) { currentActualIndex++; } else { foundMatching = true; break; } } if (!foundMatching) { return false; } currentActualIndex++; currentExpectedIndex++; } return true; } /// <summary>Returns whether the given array contains each of the patterns specified in the 'expected' array.</summary> /// <returns>True if matching, false otherwise</returns> /// <remarks>The 'expected' array contains a list of elements that are searched in the actual array. /// The actual array can have more elements, and the order of elements in the 'actual' array does not /// need to match the order found in the expected array. If there are multiple identical expected responses, /// there must be at least that many identical actual responses.</remarks> private static bool CompareArraysUnordered(JArray expected, JArray actual) { JArray actualCopy = new JArray(actual); foreach (JToken expectedMember in expected) { JToken foundMember = null; foreach (JToken actualMember in actualCopy) { if (CompareObjects(expectedMember.Value<object>(), actualMember.Value<object>(), ignoreOrder: true)) { foundMember = actualMember; break; } } if (foundMember != null) { // Don't compare against this item again. actualCopy.Remove(foundMember); } else { return false; } } return true; } private static bool CompareSimpleValues(object expected, object actual) { return Regex.IsMatch(actual.ToString(), expected.ToString(), RegexOptions.IgnoreCase); } /// <summary>Returns whether a given object matches the pattern specified by a given 'expected' object</summary> /// <returns>True, if matching, false otherwise</returns> /// <remarks> /// - 'expected' object fields should specify a regex pattern to be matched in the target object /// - Only the fields specified in the 'expected' object are matched (i.e. the target object can have more fields) /// - Fields that are arrays are matched by searching the target array for the elements specified in the array field of the 'expected' object /// - Arrays are searched in order by default. To ignore the order, specify 'ignoreOrder = true' /// </remarks> public static bool CompareObjects(object expected, object actual, bool ignoreOrder = false) { JObject expectedObject = JObject.FromObject(expected); JObject actualObject = JObject.FromObject(actual); foreach (JToken expectedToken in expectedObject.Children()) { JProperty property = expectedToken as JProperty; JToken actualToken = actualObject.Property(property.Name); if (actualToken == null || !(actualToken is JProperty)) // Property not found return false; JProperty actualProperty = actualToken as JProperty; if (property.Value is JArray) { if (!(actualProperty.Value is JArray)) return false; if (!CompareArrays(property.Value as JArray, actualProperty.Value as JArray, ignoreOrder)) return false; } else if (property.Value.HasValues) { if (!actualProperty.Value.HasValues) return false; if (!CompareObjects(property.Value.Value<object>(), actualProperty.Value.Value<object>(), ignoreOrder)) return false; } else if (!property.Value.HasValues && property.Value is JObject && actualProperty.Value is JObject) { // If property.Value is an empty object, we want to ignore actualProperty.Value's values as long as they are both JObject } else { if (!CompareSimpleValues(property.Value.Value<object>(), actualProperty.Value.Value<object>())) return false; } } return true; } } } <|start_filename|>test/DebuggerTesting/OpenDebug/Events/ExitedEvent.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Newtonsoft.Json; namespace DebuggerTesting.OpenDebug.Events { #region ExitedEventValue public sealed class ExitedEventValue : EventValue { public sealed class Body { [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public int? exitCode; } public Body body = new Body(); } #endregion /// <summary> /// Event that fires when the process exits /// </summary> public class ExitedEvent : Event<ExitedEventValue> { public ExitedEvent(int? exitCode = null) : base("exited") { this.ExpectedResponse.body.exitCode = exitCode; } public int ActualExitCode { get; private set; } public override void ProcessActualResponse(IActualResponse response) { base.ProcessActualResponse(response); this.ActualExitCode = this.ActualEvent?.body?.exitCode ?? -1; } public override string ToString() { return "{0} ({1})".FormatInvariantWithArgs(base.ToString(), this.ExpectedResponse.body.exitCode); } } } <|start_filename|>test/CppTests/OpenDebug/CrossPlatCpp/LaunchCommand.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.IO; using DebuggerTesting.OpenDebug.Commands; using DebuggerTesting.Utilities; using Newtonsoft.Json; namespace DebuggerTesting.OpenDebug.CrossPlatCpp { #region LaunchCommandArgs public sealed class CppLaunchCommandArgs : LaunchCommandArgs { public string launchOptionType; public string miDebuggerPath; public string targetArchitecture; [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public string symbolSearchPath; [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public string coreDumpPath; [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public int? processId; [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public bool? externalConsole; [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public string MIMode; } #endregion public class LaunchCommand : LaunchCommand<CppLaunchCommandArgs> { /// <summary> /// Launches a new process and attaches to it /// </summary> /// <param name="program">The full path to the program to launch</param> /// <param name="architecture">The architecture of the program</param> /// <param name="args">[OPTIONAL] Args to pass to the program</param> public LaunchCommand(IDebuggerSettings settings, string program, bool isAttach = false, params string[] args) { this.Timeout = TimeSpan.FromSeconds(15); this.Args.name = CreateName(settings); this.Args.program = program; this.Args.args = args ?? new string[] { }; this.Args.request = "launch"; this.Args.cwd = Path.GetDirectoryName(program); this.Args.environment = new EnvironmentEntry[] { }; this.Args.launchOptionType = "Local"; this.Args.symbolSearchPath = String.Empty; this.Args.sourceFileMap = new Dictionary<string, string>(); if (settings.DebuggerType == SupportedDebugger.VsDbg) { this.Args.type = "cppvsdbg"; } else { this.Args.type = "cppdbg"; this.Args.miDebuggerPath = settings.DebuggerPath; this.Args.targetArchitecture = settings.DebuggeeArchitecture.ToArchitectureString(); this.Args.MIMode = settings.MIMode; } } /// <summary> /// Launch a core dump /// </summary> /// <param name="settings"></param> /// <param name="program"></param> /// <param name="coreDumpPath"></param> public LaunchCommand(IDebuggerSettings settings, string program, string coreDumpPath) : this(settings, program) { this.Args.coreDumpPath = coreDumpPath; } private string CreateName(IDebuggerSettings settings) { string debuggerName = Enum.GetName(typeof(SupportedDebugger), settings.DebuggerType); return "C++ ({0})".FormatInvariantWithArgs(debuggerName); } public override string ToString() { return "{0} ({1})".FormatInvariantWithArgs(base.ToString(), this.Args.program); } } } <|start_filename|>test/Android/MultiThreadingCallStack/MultiThreadingCallStack/MultiThreadingCallStack.NativeActivity/Source1.cpp<|end_filename|> #include "Header1.h" #include <thread> void *func1(void *) { func2(1); } void func2(int x) { func3(2, 3); return; } void func3(int x, int y) { int z = x + y; } void func4() { func5(); return; } void func5() { int x = 0; return; } void func() { func4(); // Start a new thread pthread_t pt1; pthread_create(&pt1, NULL, func1, 0); pthread_join(pt1, NULL); return; } <|start_filename|>src/DebugEngineHost/HostConfigurationSection.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.Win32; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Microsoft.DebugEngineHost { public sealed class HostConfigurationSection : IDisposable { private readonly RegistryKey _key; internal HostConfigurationSection(RegistryKey key) { _key = key; } public void Dispose() { _key.Close(); } /// <summary> /// Obtains the value of the specified valueName /// </summary> /// <param name="valueName">Name of the value to obtain</param> /// <returns>[Optional] null if the value doesn't exist, otherwise the value</returns> public object GetValue(string valueName) { return _key.GetValue(valueName); } /// <summary> /// Enumerates the names of all the values defined in this section /// </summary> /// <returns>Enumerator of strings</returns> public IEnumerable<string> GetValueNames() { return _key.GetValueNames(); } } } <|start_filename|>test/DebuggerTesting/Attribution/CompilerSettings.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Linq; using DebuggerTesting.Utilities; namespace DebuggerTesting { internal sealed class CompilerSettings : ICompilerSettings { #region Constructor public CompilerSettings( string compilerName, SupportedCompiler compilerType, string compilerPath, SupportedArchitecture debuggeeArchitecture, IDictionary<string, string> compilerProperties) { this.CompilerName = compilerName; this.CompilerType = compilerType; this.CompilerPath = compilerPath; this.DebuggeeArchitecture = debuggeeArchitecture; this.Properties = compilerProperties ?? new Dictionary<string, string>(StringComparer.Ordinal); } #endregion #region Methods public static bool operator ==(CompilerSettings left, CompilerSettings right) { if (Object.ReferenceEquals(left, null)) return Object.ReferenceEquals(right, null); return left.Equals(right); } public static bool operator !=(CompilerSettings left, CompilerSettings right) { if (Object.ReferenceEquals(left, null)) return !Object.ReferenceEquals(right, null); return !left.Equals(right); } public override bool Equals(object obj) { return this.Equals(obj as CompilerSettings); } public bool Equals(CompilerSettings obj) { if (Object.ReferenceEquals(obj, null)) return false; if (!String.Equals(this.CompilerName, obj.CompilerName, StringComparison.Ordinal)) return false; if (this.CompilerType != obj.CompilerType) return false; if (!String.Equals(this.CompilerPath, obj.CompilerPath, StringComparison.Ordinal)) return false; if (this.DebuggeeArchitecture != obj.DebuggeeArchitecture) return false; if (!Enumerable.SequenceEqual(this.Properties.Keys, obj.Properties.Keys, StringComparer.Ordinal)) return false; if (!Enumerable.SequenceEqual(this.Properties.Values, obj.Properties.Values, StringComparer.Ordinal)) return false; return true; } public override int GetHashCode() { return HashUtilities.CombineHashCodes( this.CompilerName?.GetHashCode() ?? 0, this.CompilerType.GetHashCode(), this.CompilerPath?.GetHashCode() ?? 0, this.DebuggeeArchitecture.GetHashCode()); } public override string ToString() { return "Compiler - Name: {0} Type: {1} ({2}) Path: {3}".FormatInvariantWithArgs(this.CompilerName, this.CompilerType, this.DebuggeeArchitecture, this.CompilerPath); } #endregion #region Properties public string CompilerName { get; private set; } public SupportedCompiler CompilerType { get; private set; } public string CompilerPath { get; private set; } public SupportedArchitecture DebuggeeArchitecture { get; private set; } public IDictionary<string,string> Properties { get; private set; } #endregion } } <|start_filename|>test/CppTests/debuggees/sourcemap/src/writer/writer.cpp<|end_filename|> #include <iostream> #include "writer.h" Writer::Writer() { } void Writer::Write(const std::string msg) { std::cout << msg << std::endl; } void Writer::WriteLine(const std::string msg) { this->Write(msg); std::cout << std::endl; } void Writer::Write(const int number) { std::cout << number; } void Writer::WriteLine(const int number) { std::cout << "Writing number: " << number << std::endl; } <|start_filename|>src/SSHDebugPS/UI/Controls/ContainerListBox.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Windows.Automation.Peers; using System.Windows.Controls; namespace Microsoft.SSHDebugPS.UI { public class ContainerListBox : ListBox { protected override AutomationPeer OnCreateAutomationPeer() { return new ContainerListBoxAutomationPeer(this); } } } <|start_filename|>src/OpenDebugAD7/Telemetry/DebuggerTelemetry.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using Microsoft.VisualStudio.Shared.VSCodeDebugProtocol.Messages; using OpenDebug; namespace OpenDebugAD7 { internal sealed class DebuggerTelemetry { private static DebuggerTelemetry s_telemetryInstance; private Action<DebugEvent> _callback; // Telemetry Prefixes private const string EventNamePrefix = @"VS/Diagnostics/Debugger/"; private const string PropertyNamePrefix = @"VS.Diagnostics.Debugger."; // Debug Completed Telemetry event constants public const string TelemetryDebugCompletedEventName = "DebugCompleted"; public const string TelemetryBreakCounter = TelemetryDebugCompletedEventName + ".BreakCounter"; // Debug Event Names public const string TelemetryLaunchEventName = "Launch"; public const string TelemetryAttachEventName = "Attach"; public const string TelemetryEvaluateEventName = "Evaluate"; public const string TelemetryPauseEventName = "Pause"; public const string TelemetryTracepointEventName = "Tracepoint"; // Common telemetry properties public const string TelemetryErrorType = "ErrorType"; public const string TelemetryErrorCode = "ErrorCode"; public const string TelemetryMessage = "Message"; public const string TelemetryDuration = "Duration"; public const string TelemetryIsError = "IsError"; // Common property names and values private const string TelemetryImplementationName = "ImplementationName"; private const string TelemetryEngineVersion = "EngineVersion"; private const string TelemetryHostVersion = "HostVersion"; private const string TelemetryAdapterId = "AdapterId"; private string _engineName; private string _engineVersion; private string _hostVersion; private string _adapterId; // Specific telemetry properties public const string TelemetryIsCoreDump = TelemetryLaunchEventName + ".IsCoreDump"; public const string TelemetryIsNoDebug = TelemetryLaunchEventName + ".IsNoDebug"; public const string TelemetryUsesDebugServer = TelemetryLaunchEventName + ".UsesDebugServer"; public const string TelemetryExecuteInConsole = TelemetryEvaluateEventName + ".ExecuteInConsole"; public const string TelemetryVisualizerFileUsed = "VisualizerFileUsed"; public const string TelemetrySourceFileMappings = "SourceFileMappings"; public const string TelemetryMIMode = "MIMode"; public const string TelemetryFrameworkVersion = "FrameworkVersion"; public const string TelemetryStackFrameId = TelemetryExecuteInConsole + ".StackFrameId"; private DebuggerTelemetry(Action<DebugEvent> callback, TypeInfo engineType, TypeInfo hostType, string adapterId) { Debug.Assert(_engineName == null && _engineVersion == null, "InitializeTelemetry called more than once?"); _callback = callback; _engineName = engineType.Namespace; _engineVersion = GetVersionAttributeValue(engineType); _hostVersion = GetVersionAttributeValue(hostType); _adapterId = adapterId; } #region Public Static Methods public static void InitializeTelemetry(Action<DebugEvent> telemetryCallback, TypeInfo engineType, TypeInfo hostType, string adapterId) { Debug.Assert(telemetryCallback != null, "InitializeTelemetry called with incorrect values."); s_telemetryInstance = new DebuggerTelemetry(telemetryCallback, engineType, hostType, adapterId); } /// <summary> /// Report an error with a message. /// </summary> /// <param name="eventName">Name of the event</param> /// <param name="message">Error message</param> /// <param name="eventProperties">[Optional] Other event properties</param> public static void ReportError(string eventName, string message, Dictionary<string, object> eventProperties = null) { DebuggerTelemetry.s_telemetryInstance.ReportErrorInternal(eventName, null, message, eventProperties); } /// <summary> /// Report an error with error code /// </summary> /// <param name="eventName">Name of the event</param> /// <param name="errorCode">Error code</param> /// <param name="eventProperties">[Optional] Other event properties</param> public static void ReportError(string eventName, int errorCode, Dictionary<string, object> eventProperties = null) { DebuggerTelemetry.s_telemetryInstance?.ReportErrorInternal(eventName, errorCode, String.Empty, eventProperties); } /// <summary> /// Report an error with error code and message. /// </summary> /// <param name="eventName">Name of the event</param> /// <param name="errorCode">Error code</param> /// <param name="message">Error message</param> /// <param name="eventProperties">[Optional] Other event properties</param> public static void ReportError(string eventName, int errorCode, string message, Dictionary<string, object> eventProperties = null) { DebuggerTelemetry.s_telemetryInstance?.ReportErrorInternal(eventName, errorCode, message, eventProperties); } /// <summary>Reports expression evaluation duration</summary> /// <param name="isError">Whether evaluation resulted in an error result</param> /// <param name="duration">Time it took to evaluate</param> public static void ReportEvaluation(bool isError, TimeSpan duration, Dictionary<string, object> eventProperties = null) { Dictionary<string, object> properties = new Dictionary<string, object>(); properties[String.Concat(TelemetryEvaluateEventName, ".", TelemetryDuration)] = Math.Round(duration.TotalMilliseconds, MidpointRounding.AwayFromZero); properties[String.Concat(TelemetryEvaluateEventName, ".", TelemetryIsError)] = isError; properties.Merge(eventProperties); DebuggerTelemetry.s_telemetryInstance?.ReportEventInternal(TelemetryEvaluateEventName, properties); } /// <summary> /// Report an event /// </summary> /// <param name="eventName">Name of the event</param> /// <param name="eventProperties">[Optional] Other event properties</param> public static void ReportEvent(string eventName, Dictionary<string, object> eventProperties = null) { DebuggerTelemetry.s_telemetryInstance?.ReportEventInternal(eventName, String.Empty, eventProperties); } /// <summary> /// Report an event with a message /// </summary> /// <param name="eventName">Name of the event</param> /// <param name="message">Message</param> /// <param name="eventProperties">[Optional] Other event properties</param> public static void ReportEvent(string eventName, string message, Dictionary<string, object> eventProperties = null) { DebuggerTelemetry.s_telemetryInstance?.ReportEventInternal(eventName, message, eventProperties); } /// <summary>Reports a time measurement to Microsoft's telemetry service</summary> /// <param name="eventName">The name of the event</param> /// <param name="duration">Duration of the event</param> public static void ReportTimedEvent(string eventName, TimeSpan duration, Dictionary<string, object> eventProperties = null) { Dictionary<string, object> properties = new Dictionary<string, object>(); properties[String.Concat(eventName, ".", TelemetryDuration)] = (uint)duration.TotalMilliseconds; properties.Merge(eventProperties); DebuggerTelemetry.s_telemetryInstance?.ReportEventInternal(eventName, properties); } #endregion private void ReportErrorInternal(string eventName, int? errorCode, string message, Dictionary<string, object> eventProperties) { Dictionary<string, object> properties = new Dictionary<string, object>(); if (errorCode.HasValue) properties[String.Concat(eventName, ".", TelemetryErrorCode)] = errorCode.Value; if (!String.IsNullOrWhiteSpace(message)) properties[String.Concat(eventName, ".", TelemetryMessage)] = message; properties[String.Concat(eventName, ".", TelemetryIsError)] = true; properties.Merge(eventProperties); this.SendTelemetryEvent(eventName, properties); } private void ReportEventInternal(string eventName, Dictionary<string, object> eventProperties = null) { this.ReportEventInternal(eventName, String.Empty, eventProperties); } private void ReportEventInternal(string eventName, string message, Dictionary<string, object> eventProperties = null) { Dictionary<string, object> properties = new Dictionary<string, object>(); if (!String.IsNullOrWhiteSpace(message)) { properties[String.Concat(eventName, ".", TelemetryMessage)] = message; } properties.Merge(eventProperties); this.SendTelemetryEvent(eventName, properties); } /// <summary> /// Send the telemetry event. This method will ensure the proper prefixes are in place and apply a default set of properties to the event /// </summary> /// <param name="eventName">Name of the Event</param> /// <param name="eventProperties">Properties related to the event</param> public void SendTelemetryEvent(string eventName, Dictionary<string, object> eventProperties) { Dictionary<string, object> properties = new Dictionary<string, object>(); // Add base telemetry properties properties[TelemetryImplementationName] = _engineName; properties[TelemetryEngineVersion] = _engineVersion; properties[TelemetryHostVersion] = _hostVersion; properties[TelemetryAdapterId] = _adapterId; properties.Merge(eventProperties); this.SendTelemetryEventBase(TelemetryHelper.EnsureEventNamePrefix(EventNamePrefix, eventName), TelemetryHelper.EnsurePropertyPrefix(PropertyNamePrefix, properties)); } private void SendTelemetryEventBase(string eventName, params KeyValuePair<string, object>[] eventProperties) { Dictionary<string, object> properties = null; if (eventProperties != null) { properties = new Dictionary<string, object>(); foreach (var item in eventProperties) { if (properties.ContainsKey(item.Key)) continue; properties.Add(item.Key, item.Value); } } this.SendTelemetryEventBase(eventName, properties); } /// <summary> /// Only log telemetry if it is a LAB Build. LAB builds will be the official shipped builds. This prevents logging of telemetry for private builds /// </summary> [Conditional("LAB")] private void SendTelemetryEventBase(string eventName, Dictionary<string, object> properties) { #if LAB this._callback?.Invoke(new OutputEvent() { Category = OutputEvent.CategoryValue.Telemetry, Output = eventName, Data = properties }); #endif } #region private Static Methods private static string GetVersionAttributeValue(TypeInfo engineType) { var attribute = engineType.Assembly.GetCustomAttribute(typeof(System.Reflection.AssemblyFileVersionAttribute)) as AssemblyFileVersionAttribute; if (attribute == null) return string.Empty; return attribute.Version; } #endregion } } <|start_filename|>src/DebugEngineHost.VSCode/HostConfigurationStore.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.DebugEngineHost.VSCode; using System; using System.Globalization; using System.IO; using System.Linq; namespace Microsoft.DebugEngineHost { public sealed class HostConfigurationStore { private readonly EngineConfiguration _config; public HostConfigurationStore(string adapterId) { _config = EngineConfiguration.TryGet(adapterId); if (_config == null) { throw new ArgumentOutOfRangeException(nameof(adapterId)); } } public void SetEngineGuid(Guid value) { // nothing to do } public string RegistryRoot { get { throw new NotImplementedException(); } } public object GetCustomLauncher(string launcherTypeName) { throw new NotImplementedException(); } public object GetEngineMetric(string metric) { if (string.CompareOrdinal("GlobalVisualizersDirectory", metric) == 0) { string openDebugPath = EngineConfiguration.GetAdapterDirectory(); return Path.Combine(openDebugPath, "Visualizers"); } return null; } public void GetExceptionCategorySettings(Guid categoryId, out HostConfigurationSection categoryConfigSection, out string categoryName) { var category = _config.ExceptionSettings.Categories.FirstOrDefault((x) => x.Id == categoryId); if (category == null) { throw new InvalidDataException(string.Format(CultureInfo.CurrentCulture, HostResources.Error_ExceptionCategoryMissing, categoryId)); } categoryName = category.Name; categoryConfigSection = new HostConfigurationSection(category.DefaultTriggers); } /// <summary> /// Checks if logging is enabled, and if so returns a logger object. /// /// In VS, this is wired up to read from the registry and return a logger which writes a log file to %TMP%\log-file-name. /// In VS Code, this will check if the '--engineLogging' switch is enabled, and if so return a logger that wil write to the logger output. /// </summary> /// <param name="enableLoggingSettingName">[Optional] In VS, the name of the settings key to check if logging is enabled. If not specified, this will check 'EnableLogging' in the AD7 Metrics.</param> /// <param name="logFileName">[Required] name of the log file to open if logging is enabled. This is ignored for VSCode.</param> /// <returns>[Optional] If logging is enabled, the logging object.</returns> public HostLogger GetLogger(string enableLoggingSettingName, string logFileName) { return HostLogger.Instance; } /// <summary> /// Read the debugger setting /// </summary> public T GetDebuggerConfigurationSetting<T>(string settingName, T defaultValue) { // TODO: check the configuration store for these? return defaultValue; } } } <|start_filename|>test/CppTests/Tests/ThreadingTests.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using System.Globalization; using System.Linq; using DebuggerTesting; using DebuggerTesting.Compilation; using DebuggerTesting.OpenDebug; using DebuggerTesting.OpenDebug.CrossPlatCpp; using DebuggerTesting.OpenDebug.Events; using DebuggerTesting.OpenDebug.Extensions; using DebuggerTesting.Ordering; using Xunit; using Xunit.Abstractions; namespace CppTests.Tests { [TestCaseOrderer(DependencyTestOrderer.TypeName, DependencyTestOrderer.AssemblyName)] public class ThreadingTests : TestBase { #region Constructor public ThreadingTests(ITestOutputHelper outputHelper) : base(outputHelper) { } #endregion [Theory] [RequiresTestSettings] public void CompileKitchenSinkForThreading(ITestSettings settings) { this.TestPurpose("Compiles the kitchen sink debuggee for threading."); this.WriteSettings(settings); IDebuggee debuggee = SinkHelper.OpenAndCompile(this, settings.CompilerSettings, DebuggeeMonikers.KitchenSink.Threading); } [Theory] [DependsOnTest(nameof(CompileKitchenSinkForThreading))] [RequiresTestSettings] [UnsupportedDebugger(SupportedDebugger.Gdb_MinGW | SupportedDebugger.Gdb_Gnu, SupportedArchitecture.x86)] // TODO: Re-enable for vsdbg [UnsupportedDebugger(SupportedDebugger.VsDbg, SupportedArchitecture.x64)] public void ThreadingBasic(ITestSettings settings) { this.TestPurpose("Test basic multithreading scenario."); this.WriteSettings(settings); IDebuggee debuggee = SinkHelper.Open(this, settings.CompilerSettings, DebuggeeMonikers.KitchenSink.Threading); using (IDebuggerRunner runner = CreateDebugAdapterRunner(settings)) { this.Comment("Launching debuggee. Run until multiple threads are running."); runner.Launch(settings.DebuggerSettings, debuggee, "-fThreading"); runner.SetBreakpoints(debuggee.Breakpoints(SinkHelper.Threading, 37)); runner.Expects.HitBreakpointEvent() .AfterConfigurationDone(); IEnumerable<IThreadInfo> threads = runner.GetThreads(); List<string> loopCounts = new List<string>(); this.Comment("Inspect threads and find 'loopCount' variable on each worker thread."); this.WriteLine("Threads:"); foreach (var threadInfo in threads) { IThreadInspector threadInspector = threadInfo.GetThreadInspector(); // Don't look at main thread, just workers if (threadInspector.ThreadId == runner.StoppedThreadId) continue; this.Comment("Thread '{0}', Id: {1}".FormatInvariantWithArgs(threadInfo.Name, threadInspector.ThreadId)); IFrameInspector threadLoopFrame = threadInspector.Stack.FirstOrDefault(s => s.Name.Contains("ThreadLoop")); // Fail the test if the ThreadLoop frame could not be found if (threadLoopFrame == null) { this.WriteLine("This thread's stack did not contain a frame with 'ThreadLoop'"); this.WriteLine("Stack Trace:"); foreach (var frame in threadInspector.Stack) { this.WriteLine(frame.Name); } continue; } string variables = threadLoopFrame.Variables.ToReadableString(); this.WriteLine("Variables in 'ThreadLoop' frame:"); this.WriteLine(variables); // Put the different loopCounts in a list, so they can be verified order agnostic string loopCountValue = threadLoopFrame.GetVariable("loopCount").Value; this.WriteLine("loopCount = {0}", loopCountValue); loopCounts.Add(loopCountValue); } //Verify all the worker threads were observed Assert.True(loopCounts.Contains("0"), "Could not find thread with loop count 0"); Assert.True(loopCounts.Contains("1"), "Could not find thread with loop count 1"); Assert.True(loopCounts.Contains("2"), "Could not find thread with loop count 2"); Assert.True(loopCounts.Contains("3"), "Could not find thread with loop count 3"); Assert.True(4 == loopCounts.Count, "Expected to find 4 threads, but found " + loopCounts.Count.ToString(CultureInfo.InvariantCulture)); this.Comment("Run to end."); runner.Expects.TerminatedEvent().AfterContinue(); runner.DisconnectAndVerify(); } } [Theory] [DependsOnTest(nameof(CompileKitchenSinkForThreading))] [RequiresTestSettings] public void ThreadingBreakpoint(ITestSettings settings) { this.TestPurpose("Test breakpoint on multiple threads."); this.WriteSettings(settings); IDebuggee debuggee = SinkHelper.Open(this, settings.CompilerSettings, DebuggeeMonikers.KitchenSink.Threading); using (IDebuggerRunner runner = CreateDebugAdapterRunner(settings)) { this.Comment("Launching debuggee. Set breakpoint in worker thread code."); runner.Launch(settings.DebuggerSettings, true, debuggee, "-fThreading"); runner.SetBreakpoints(debuggee.Breakpoints(SinkHelper.Threading, 16)); // Turned on stop at entry, so should stop before anything is executed. // On Concord, this is a reason of "entry" versus "step" when it is hit. if (settings.DebuggerSettings.DebuggerType == SupportedDebugger.VsDbg) { runner.Expects.HitEntryEvent().AfterConfigurationDone(); } else { runner.Expects.HitStepEvent() .AfterConfigurationDone(); } // Since there are 4 worker threads, expect to hit the // breakpoint 4 times, once on each thread. for (int i = 1; i <= 4; i++) { StoppedEvent breakpointEvent = new StoppedEvent(StoppedReason.Breakpoint, SinkHelper.Threading, 16); this.Comment("Run until breakpoint #{0}.", i); runner.Expects.Event(breakpointEvent).AfterContinue(); this.WriteLine("Stopped on thread: {0}", breakpointEvent.ThreadId); this.WriteLine("Ensure stopped thread exists in ThreadList"); IEnumerable<IThreadInfo> threadInfo = runner.GetThreads(); Assert.True(threadInfo.Any(thread => thread.Id == breakpointEvent.ThreadId), string.Format(CultureInfo.CurrentCulture, "ThreadId {0} should exist in ThreadList", breakpointEvent.ThreadId)); } this.Comment("Run to end."); runner.Expects.TerminatedEvent().AfterContinue(); runner.DisconnectAndVerify(); } } } } <|start_filename|>test/DebuggerTesting/Utilities/DisposableHelper.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections; using System.Collections.Generic; using System.Linq; namespace DebuggerTesting.Utilities { public static class DisposableHelper { /// <summary> /// Calls dispose on the object if it implements IDisposable. /// Ignores a null object. /// </summary> public static void SafeDispose(object o) { SafeDispose(o as IDisposable); } /// <summary> /// Calls dispose on the object. /// Ignores a null object. /// </summary> public static void SafeDispose(this IDisposable o) { o?.Dispose(); } /// <summary> /// Calls dispose on all the objects in the collection that implement IDisposable. /// Ignores any null values. /// </summary> public static void SafeDisposeAll(IEnumerable objects) { SafeDisposeAll(objects?.OfType<IDisposable>()); } /// <summary> /// Calls dispose on all the objects in the collection. /// Ignores any null values. /// </summary> public static void SafeDisposeAll(this IEnumerable<IDisposable> objects) { if (objects == null) return; foreach (IDisposable o in objects) SafeDispose(o); } } } <|start_filename|>src/SSHDebugPS/WSL/WSLPortSupplier.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Runtime.InteropServices; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Debugger.Interop; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; namespace Microsoft.SSHDebugPS.WSL { [ComVisible(true)] [Guid("B8587A49-00BD-4DEE-94B9-6EBF49003E04")] internal class WSLPortSupplier : AD7PortSupplier { private readonly Guid _Id = new Guid("267B1341-AC92-44DC-94DF-2EE4205DD17E"); protected override Guid Id { get { return _Id; } } protected override string Name { get { return StringResources.WSL_PSName; } } protected override string Description { get { return StringResources.WSL_PSDescription; } } IEnumerable<string> _distros; public WSLPortSupplier() : base() { } public override int CanAddPort() { // Indicate that ports cannot be added return HR.S_FALSE; } public override int CanPersistPorts() { // Opt-out of the SDM remembering ports return HR.S_OK; } public override int EnumPorts(out IEnumDebugPorts2 ppEnum) { ThreadHelper.ThrowIfNotOnUIThread(); if (_distros == null) { IVsUIShell shell = Package.GetGlobalService(typeof(SVsUIShell)) as IVsUIShell; try { WSLCommandLine.EnsureInitialized(); _distros = WSLCommandLine.GetInstalledDistros(); } catch (Exception ex) { shell.SetErrorInfo(ex.HResult, ex.Message, 0, null, null); shell.ReportErrorInfo(ex.HResult); ppEnum = null; return VSConstants.E_ABORT; } } WSLPort[] ports = _distros.Select(name => new WSLPort(this, name, isInAddPort: false)).ToArray(); ppEnum = new AD7PortEnum(ports); return HR.S_OK; } public override int EnumPersistedPorts(BSTR_ARRAY portNames, out IEnumDebugPorts2 portEnum) { // This should never be called since CanPersistPorts returns S_OK Debug.Fail("Why is EnumPersistedPorts called?"); throw new NotImplementedException(); } public override int AddPort(IDebugPortRequest2 request, out IDebugPort2 port) { // This should never be called Debug.Fail("Why is AddPort called?"); throw new NotImplementedException(); } } } <|start_filename|>src/MICore/Logger.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Globalization; using Microsoft.DebugEngineHost; namespace MICore { /// <summary> /// Class which implements logging. The logging is control by a registry key. If enabled, logging goes to %TMP%\Microsoft.MIDebug.log /// </summary> public class Logger { private static bool s_isInitialized; private static bool s_isEnabled; private static DateTime s_initTime; // NOTE: We never clean this up private static HostLogger s_logger; private static int s_count; private int _id; public class LogInfo { public string logFile; public HostLogger.OutputCallback logToOutput; public bool enabled; }; private static LogInfo s_cmdLogInfo = new LogInfo(); public static LogInfo CmdLogInfo { get { return s_cmdLogInfo; } } private Logger() { _id = Interlocked.Increment(ref s_count); } public static Logger EnsureInitialized(HostConfigurationStore configStore) { Logger res = new Logger(); if (!s_isInitialized) { s_isInitialized = true; s_initTime = DateTime.Now; LoadMIDebugLogger(configStore); res.WriteLine("Initialized log at: " + s_initTime.ToString(CultureInfo.InvariantCulture)); } #if DEBUG if (System.Diagnostics.Debugger.IsAttached) { s_isEnabled = true; } #endif return res; } public static void LoadMIDebugLogger(HostConfigurationStore configStore) { if (s_logger == null) { if (CmdLogInfo.enabled) { // command configured log file s_logger = HostLogger.GetLoggerFromCmd(CmdLogInfo.logFile, CmdLogInfo.logToOutput); } else { // use default logging s_logger = configStore.GetLogger("EnableMIDebugLogger", "Microsoft.MIDebug.log"); } if (s_logger != null) { s_isEnabled = true; } } } public static void Reset() { HostLogger logger; if (CmdLogInfo.enabled) { logger = HostLogger.GetLoggerFromCmd(CmdLogInfo.logFile, CmdLogInfo.logToOutput); logger = Interlocked.Exchange(ref s_logger, logger); logger?.Close(); if (s_logger != null) { s_isEnabled = true; } } } /// <summary> /// If logging is enabled, writes a line of text to the log /// </summary> /// <param name="line">[Required] line to write</param> public void WriteLine(string line) { if (s_isEnabled) { WriteLineImpl(line); } } /// <summary> /// If logging is enabled, writes a line of text to the log /// </summary> /// <param name="format">[Required] format string</param> /// <param name="args">arguments to use in the format string</param> public void WriteLine(string format, params object[] args) { if (s_isEnabled) { WriteLineImpl(format, args); } } /// <summary> /// If logging is enabled, writes a block of text which may contain newlines to the log /// </summary> /// <param name="prefix">[Optional] Prefix to put on the front of each line</param> /// <param name="textBlock">Block of text to write</param> public void WriteTextBlock(string prefix, string textBlock) { if (s_isEnabled) { WriteTextBlockImpl(prefix, textBlock); } } /// <summary> /// If logging is enabled, flushes the log to disk /// </summary> public void Flush() { if (s_isEnabled) { FlushImpl(); } } public static bool IsEnabled { get { return s_isEnabled; } } [MethodImpl(MethodImplOptions.NoInlining)] // Disable inlining since logging is off by default, and we want to allow the public method to be inlined private void WriteLineImpl(string line) { string fullLine = String.Format(CultureInfo.CurrentCulture, "{2}: ({0}) {1}", (int)(DateTime.Now - s_initTime).TotalMilliseconds, line, _id); s_logger?.WriteLine(fullLine); #if DEBUG Debug.WriteLine("MS_MIDebug: " + fullLine); #endif } [MethodImpl(MethodImplOptions.NoInlining)] // Disable inlining since logging is off by default, and we want to allow the public method to be inlined private static void FlushImpl() { s_logger?.Flush(); } [MethodImpl(MethodImplOptions.NoInlining)] // Disable inlining since logging is off by default, and we want to allow the public method to be inlined private void WriteLineImpl(string format, object[] args) { WriteLineImpl(string.Format(CultureInfo.CurrentCulture, format, args)); } [MethodImpl(MethodImplOptions.NoInlining)] // Disable inlining since logging is off by default, and we want to allow the public method to be inlined private void WriteTextBlockImpl(string prefix, string textBlock) { using (var reader = new StringReader(textBlock)) { while (true) { var line = reader.ReadLine(); if (line == null) break; if (!string.IsNullOrEmpty(prefix)) WriteLineImpl(prefix + line); else WriteLineImpl(line); } } } } } <|start_filename|>src/OpenDebugAD7/AD7Impl/AD7Program.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.VisualStudio.Debugger.Interop; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace OpenDebugAD7.AD7Impl { internal sealed class AD7Program : IDebugProgram2 { private readonly Guid _id = Guid.NewGuid(); private readonly IDebugProcess2 _process; internal AD7Program(IDebugProcess2 process) { _process = process; } public int Attach(IDebugEventCallback2 pCallback) { throw new NotImplementedException(); } public int CanDetach() { throw new NotImplementedException(); } public int CauseBreak() { throw new NotImplementedException(); } public int Continue(IDebugThread2 pThread) { throw new NotImplementedException(); } public int Detach() { throw new NotImplementedException(); } public int EnumCodeContexts(IDebugDocumentPosition2 pDocPos, out IEnumDebugCodeContexts2 ppEnum) { throw new NotImplementedException(); } public int EnumCodePaths(string pszHint, IDebugCodeContext2 pStart, IDebugStackFrame2 pFrame, int fSource, out IEnumCodePaths2 ppEnum, out IDebugCodeContext2 ppSafety) { throw new NotImplementedException(); } public int EnumModules(out IEnumDebugModules2 ppEnum) { throw new NotImplementedException(); } public int EnumThreads(out IEnumDebugThreads2 ppEnum) { throw new NotImplementedException(); } public int Execute() { throw new NotImplementedException(); } public int GetDebugProperty(out IDebugProperty2 ppProperty) { throw new NotImplementedException(); } public int GetDisassemblyStream(enum_DISASSEMBLY_STREAM_SCOPE dwScope, IDebugCodeContext2 pCodeContext, out IDebugDisassemblyStream2 ppDisassemblyStream) { throw new NotImplementedException(); } public int GetENCUpdate(out object ppUpdate) { throw new NotImplementedException(); } public int GetEngineInfo(out string pbstrEngine, out Guid pguidEngine) { throw new NotImplementedException(); } public int GetMemoryBytes(out IDebugMemoryBytes2 ppMemoryBytes) { throw new NotImplementedException(); } public int GetName(out string pbstrName) { throw new NotImplementedException(); } public int GetProcess(out IDebugProcess2 process) { process = _process; return HRConstants.S_OK; } public int GetProgramId(out Guid guidProgramId) { guidProgramId = _id; return HRConstants.S_OK; } public int Step(IDebugThread2 pThread, enum_STEPKIND sk, enum_STEPUNIT Step) { throw new NotImplementedException(); } public int Terminate() { throw new NotImplementedException(); } public int WriteDump(enum_DUMPTYPE DUMPTYPE, string pszDumpUrl) { throw new NotImplementedException(); } } } <|start_filename|>src/JDbg/ReplyPacketParser.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace JDbg { /// <summary> /// Wrapper for JDWP reply packets. Automatically parses reply headers and exposes several /// helpful utilities for decoding reply payloads. /// </summary> internal class ReplyPacketParser { private BinaryReader _packetReader; private JdwpCommand.IDSizes _IDSizes; public uint Size { get; private set; } public uint Id { get; private set; } public UInt16 ErrorCode { get; private set; } public bool Succeeded { get; private set; } /// <summary> /// Construct a new ReplyPacketParser from the raw bytes of the reply packet. After the ReplyPacketParser is constrcuted, /// the header has already been decoded, the position of the underlying byte stream is at the beginning of the payload. /// Use the methods on this class to read bytes from the payload as structured data. /// </summary> /// <param name="replyBytes"></param> public ReplyPacketParser(byte[] replyBytes, JdwpCommand.IDSizes idSizes) { _packetReader = new BinaryReader(new MemoryStream(replyBytes)); _IDSizes = idSizes; Size = this.ReadUInt32(); Id = this.ReadUInt32(); this.ReadByte(); //flags byte ErrorCode = this.ReadUInt16(); if (ErrorCode == 0) { Succeeded = true; } else { Succeeded = false; } } /// <summary> /// Reads the next four bytes in the payload as a UInt32 /// </summary> /// <returns></returns> public UInt32 ReadUInt32() { byte[] bytes = _packetReader.ReadBytes(4); return Utils.UInt32FromBigEndianBytes(bytes); } /// <summary> /// Reads the next two bytes in the payload as a UInt16 /// </summary> /// <returns></returns> public UInt16 ReadUInt16() { byte[] bytes = _packetReader.ReadBytes(2); return Utils.UInt16FromBigEndianBytes(bytes); } /// <summary> /// Reads the next byte from the payload /// </summary> /// <returns></returns> public byte ReadByte() { return _packetReader.ReadByte(); } /// <summary> /// Reads the next bytes of the payload as a string. /// </summary> /// <returns></returns> public string ReadString() { UInt32 size = ReadUInt32(); byte[] stringBytes = _packetReader.ReadBytes((int)size); return Encoding.UTF8.GetString(stringBytes); } /// <summary> /// Reads the next bytes of the payload os a ReferenceTypeID /// </summary> /// <returns></returns> public ulong ReadReferenceTypeID() { byte[] bytes = _packetReader.ReadBytes(_IDSizes.ReferenceTypeIDSize); return Utils.ULongFromBigEndiantBytes(bytes); } } } <|start_filename|>test/Android/Stepping/Stepping/Stepping.NativeActivity/Source1.cpp<|end_filename|> #include "Header1.h" #include "Header2.h" void func1() { func2(); func2(); return; } void func2() { int x = 0; int y = 1; func3(); return; } <|start_filename|>test/CppTests/CppTestSettingsProvider.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Reflection; using System.Threading; using DebuggerTesting; using DebuggerTesting.Settings; using DebuggerTesting.TestFramework; namespace CppTests { public sealed class CppTestSettingsProvider : ITestSettingsProvider { #region ITestSettingsProvider Member IEnumerable<ITestSettings> ITestSettingsProvider.GetSettings(MethodInfo testMethod) { return this.settingsLazy.Value; } #endregion #region Methods private static IEnumerable<ITestSettings> GetSettings() { return TestSettingsHelper.LoadSettingsFromConfig(PathSettings.TestConfigurationFilePath); } #endregion #region Fields private Lazy<IEnumerable<ITestSettings>> settingsLazy = new Lazy<IEnumerable<ITestSettings>>( CppTestSettingsProvider.GetSettings, LazyThreadSafetyMode.ExecutionAndPublication); #endregion } } <|start_filename|>test/DebuggerTesting/OpenDebug/Commands/LaunchCommand.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using Newtonsoft.Json; namespace DebuggerTesting.OpenDebug.Commands { public abstract class LaunchCommandArgs : JsonValue { public string name; public string type; public string request; public string program; public string[] args; public bool stopAtEntry; public string cwd; public EnvironmentEntry[] environment; public bool noDebug; public IDictionary<string, string> sourceFileMap; } public abstract class LaunchCommand<T> : Command<T> where T : LaunchCommandArgs, new() { public LaunchCommand() : base("launch") { } public bool StopAtEntry { get { return this.Args.stopAtEntry; } set { this.Args.stopAtEntry = value; } } public EnvironmentEntry[] Environment { get { return this.Args.environment; } set { this.Args.environment = value; } } public IDictionary<string, string> SourceFileMap { get { return this.Args.sourceFileMap; } set { this.Args.sourceFileMap = value; } } } public class EnvironmentEntry : JsonValue { [JsonProperty(PropertyName = "name")] public string Name { get; set; } [JsonProperty(PropertyName = "value")] public string Value { get; set; } } } <|start_filename|>test/CppTests/debuggees/sourcemap/src/main.cpp<|end_filename|> #ifdef _WIN32 #include "writer\writer.h" #include "manager\manager.h" #else #include "writer/writer.h" #include "manager/manager.h" #endif int main(int argv, char** argc) { Writer writer; writer.Write("Hello World"); Manager mgr; for (int i = 90; i > 0; i -= 10) { mgr.AddInt(i); } writer.Write("Mgr has "); writer.Write(mgr.Size()); writer.WriteLine(" items."); writer.Write("The sum of Mgr is: "); writer.WriteLine(mgr.Sum()); writer.Write("Removing "); writer.Write(mgr.RemoveInt()); writer.Write(". The sum is now: "); writer.Write(mgr.Sum()); return 0; } <|start_filename|>test/CppTests/Tests/AutoCompleteTests.cs<|end_filename|> // // Copyright (c) Microsoft. All rights reserved. // // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.IO; using System.Linq; using DebuggerTesting; using DebuggerTesting.Compilation; using DebuggerTesting.OpenDebug; using DebuggerTesting.OpenDebug.Commands; using DebuggerTesting.OpenDebug.CrossPlatCpp; using DebuggerTesting.OpenDebug.Events; using DebuggerTesting.OpenDebug.Extensions; using DebuggerTesting.Ordering; using DebuggerTesting.Settings; using DebuggerTesting.Utilities; using Xunit; using Xunit.Abstractions; namespace CppTests.Tests { [TestCaseOrderer(DependencyTestOrderer.TypeName, DependencyTestOrderer.AssemblyName)] public class AutoCompleteTests : TestBase { #region Constructor public AutoCompleteTests(ITestOutputHelper outputHelper) : base(outputHelper) { } #endregion #region Methods private const string HelloName = "hello"; private const string HelloSourceName = "hello.cpp"; [Theory] [RequiresTestSettings] public void CompileHelloDebuggee(ITestSettings settings) { this.TestPurpose("Create and compile the 'hello' debuggee"); this.WriteSettings(settings); IDebuggee debuggee = Debuggee.Create(this, settings.CompilerSettings, HelloName, DebuggeeMonikers.HelloWorld.Sample); debuggee.AddSourceFiles(HelloSourceName); debuggee.Compile(); } [Theory] [DependsOnTest(nameof(CompileHelloDebuggee))] [RequiresTestSettings] [UnsupportedDebugger(SupportedDebugger.Lldb | SupportedDebugger.VsDbg, SupportedArchitecture.x64 | SupportedArchitecture.x86)] public void TestAutoComplete(ITestSettings settings) { this.TestPurpose("This test checks a bunch of commands and events."); this.WriteSettings(settings); IDebuggee debuggee = Debuggee.Open(this, settings.CompilerSettings, HelloName, DebuggeeMonikers.HelloWorld.Sample); using (IDebuggerRunner runner = CreateDebugAdapterRunner(settings)) { this.Comment("Launch the debuggee"); runner.Launch(settings.DebuggerSettings, debuggee); SourceBreakpoints callingBreakpoints = new SourceBreakpoints(debuggee, HelloSourceName); callingBreakpoints.Add(9); runner.SetBreakpoints(callingBreakpoints); runner.Expects.HitBreakpointEvent(HelloSourceName, 9) .AfterConfigurationDone(); // Test completion with -exec string[] completions = runner.CompletionsRequest("-exec break"); Assert.Collection(completions, elem1 => Assert.Equal("-exec break", elem1), elem2 => Assert.Equal("-exec break-range", elem2) ); // Test completion with ` completions = runner.CompletionsRequest("`pw"); Assert.Collection(completions, elem1 => Assert.Equal("`pwd", elem1) ); // Test completions without -exec or ` completions = runner.CompletionsRequest("pw"); Assert.Empty(completions); runner.Expects.ExitedEvent(0).TerminatedEvent().AfterContinue(); runner.DisconnectAndVerify(); } } #endregion } } <|start_filename|>test/DebuggerTesting/SupportedCompiler.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; namespace DebuggerTesting { [Flags] public enum SupportedCompiler { ClangPlusPlus = 0x1, GPlusPlus = 0x2, VisualCPlusPlus = 0x4, XCodeBuild = 0x8 } } <|start_filename|>test/Android/SwitchFramesInCallStack/SwitchFramesInCallStack/SwitchFramesInCallStack.NativeActivity/Header1.h<|end_filename|> #pragma once void func1(); int func2(int x, int y); bool func3(int *x, int *y); <|start_filename|>test/DebuggerTesting/TestFramework/TestSettingsDataDiscoverer.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Xunit.Abstractions; using Xunit.Sdk; namespace DebuggerTesting.TestFramework { /// <summary> /// Custom data discovered for xUnit theory tests that overrides the default behavior of data discovery. /// </summary> public class TestSettingsDataDiscoverer : DataDiscoverer { #region Methods public override bool SupportsDiscoveryEnumeration(IAttributeInfo dataAttribute, IMethodInfo testMethod) { // Return false to force xUnit to enumerate the test data during the execution phase of the test // rather than during the discovery phase. This is required because test data that is enuemrated // during the discovery phase must be serializable, but xUnit cannot serialize arbitrary complex // objects such as the ITestSettings implementation. return false; } #endregion } } <|start_filename|>src/MICore/UnixUtilities.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Text; namespace MICore { public static class UnixUtilities { internal const string SudoPath = "/usr/bin/sudo"; // Mono seems to stop responding when the is a large response unless we specify a larger buffer here internal const int StreamBufferSize = 1024 * 4; private const string PKExecPath = "/usr/bin/pkexec"; // Linux specific private const string PtraceScopePath = "/proc/sys/kernel/yama/ptrace_scope"; // OS X specific private const string CodeSignPath = "/usr/bin/codesign"; /// <summary> /// Launch a new terminal, spin up a new bash shell, cd to the working dir, execute a tty command to get the shell tty and store it. /// Start the debugger in mi mode setting the tty to the terminal defined earlier and redirect stdin/stdout /// to the correct pipes. After the debugger exits, cleanup the FIFOs. This is done using the trap command to add a /// signal handler for SIGHUP on the console (executing the two rm commands) /// </summary> /// <param name="debuggeeDir">Path to the debuggee directory</param> /// <param name="dbgStdInName">File where the stdin for the debugger process is redirected to</param> /// <param name="dbgStdOutName">File where the stdout for the debugger process is redirected to</param> /// <param name="pidFifo">File where the debugger pid is written to</param> /// <param name="dbgCmdScript">Script file to pass the debugger launch command</param> /// <param name="debuggerCmd">Command to the debugger</param> /// <param name="debuggerArgs">MIDebugger arguments</param> /// <returns></returns> internal static string LaunchLocalDebuggerCommand( string debuggeeDir, string dbgStdInName, string dbgStdOutName, string pidFifo, string dbgCmdScript, string debuggerCmd, string debuggerArgs) { // On OSX, 'wait' will return once there is a status change from the launched process rather than for it to exit, so // we need to use 'fg' there. This works as our bash prompt is launched through apple script rather than 'bash -c'. // On Linux, fg will fail with 'no job control' because our commands are being executed through 'bash -c', and // bash doesn't support fg in this mode, so we need to use 'wait' there. string waitForCompletionCommand = PlatformUtilities.IsOSX() ? "fg > /dev/null; " : "wait $pid; "; // echo the shell pid so that we can monitor it // Change to the current working directory // find the tty // enable monitor on the session // set the trap command to remove the fifos // execute the debugger command in the background // Clear the output of executing a process in the background: [job number] pid // echo and wait the debugger pid to know whether we need to fake an exit by the debugger return FormattableString.Invariant($"echo $$ > {pidFifo} ; cd \"{debuggeeDir}\" ; DbgTerm=`tty` ; set -o monitor ; trap 'rm \"{dbgStdInName}\" \"{dbgStdOutName}\" \"{pidFifo}\" \"{dbgCmdScript}\"' EXIT ; {debuggerCmd} {debuggerArgs} --tty=$DbgTerm < \"{dbgStdInName}\" > \"{dbgStdOutName}\" & clear; pid=$! ; echo $pid > \"{pidFifo}\" ; {waitForCompletionCommand}"); } internal static string GetDebuggerCommand(LocalLaunchOptions localOptions) { string quotedDebuggerPath = String.Format(CultureInfo.InvariantCulture, "\"{0}\"", localOptions.MIDebuggerPath); if (PlatformUtilities.IsLinux()) { string debuggerPathCorrectElevation = quotedDebuggerPath; string prompt = string.Empty; // If running as root, make sure the new console is also root. bool isRoot = UnixNativeMethods.GetEUid() == 0; // If the system doesn't allow a non-root process to attach to another process, try to run GDB as root if (localOptions.ProcessId.HasValue && !isRoot && UnixUtilities.GetRequiresRootAttach(localOptions.DebuggerMIMode)) { prompt = String.Format(CultureInfo.CurrentCulture, "echo -n '{0}'; read yn; if [ \"$yn\" != 'y' ] && [ \"$yn\" != 'Y' ] ; then exit 1; fi; ", MICoreResources.Warn_AttachAsRootProcess); // Prefer pkexec for a nice graphical prompt, but fall back to sudo if it's not available if (File.Exists(UnixUtilities.PKExecPath)) { debuggerPathCorrectElevation = String.Concat(UnixUtilities.PKExecPath, " ", debuggerPathCorrectElevation); } else if (File.Exists(UnixUtilities.SudoPath)) { debuggerPathCorrectElevation = String.Concat(UnixUtilities.SudoPath, " ", debuggerPathCorrectElevation); } else { Debug.Fail("Root required to attach, but no means of elevating available!"); } } return String.Concat(prompt, debuggerPathCorrectElevation); } else { return quotedDebuggerPath; } } internal static string MakeFifo(string identifier = null, Logger logger = null) { string path = Path.Combine(Path.GetTempPath(), Utilities.GetMIEngineTemporaryFilename(identifier)); // Mod is normally in octal, but C# has no octal values. This is 384 (rw owner, no rights anyone else) const int rw_owner = 384; byte[] pathAsBytes = new byte[Encoding.UTF8.GetByteCount(path) + 1]; Encoding.UTF8.GetBytes(path, 0, path.Length, pathAsBytes, 0); int result = UnixNativeMethods.MkFifo(pathAsBytes, rw_owner); if (result != 0) { // Failed to create the fifo. Bail. logger?.WriteLine("Failed to create fifo"); throw new ArgumentException("MakeFifo failed to create fifo at path {0}", path); } return path; } internal static bool GetRequiresRootAttach(MIMode mode) { // If "ptrace_scope" is a value other than 0, only root can attach to arbitrary processes if (GetPtraceScope() != 0) { return true; // Attaching to any non-child process requires root } return false; } private static int GetPtraceScope() { // See: https://www.kernel.org/doc/Documentation/security/Yama.txt if (!File.Exists(UnixUtilities.PtraceScopePath)) { // If the scope file doesn't exist, security is disabled return 0; } try { string scope = File.ReadAllText(UnixUtilities.PtraceScopePath); return Int32.Parse(scope, CultureInfo.CurrentCulture); } catch { // If we were unable to determine the current scope setting, assume we need root return -1; } } internal static bool IsProcessRunning(int processId) { // When getting the process group ID, getpgid will return -1 // if there is no process with the ID specified. return UnixNativeMethods.GetPGid(processId) >= 0; } public static bool IsBinarySigned(string filePath, Logger logger) { if (!PlatformUtilities.IsOSX()) { throw new NotImplementedException(); } Process p = new Process { StartInfo = { CreateNoWindow = true, UseShellExecute = false, FileName = CodeSignPath, Arguments = "--display " + filePath, RedirectStandardOutput = true, RedirectStandardError = true } }; p.OutputDataReceived += (sender, e) => { OutputNonEmptyString(e.Data, "codeSign-stdout: ", logger); }; p.ErrorDataReceived += (sender, e) => { OutputNonEmptyString(e.Data, "codeSign-stderr: ", logger); }; p.Start(); p.BeginOutputReadLine(); p.BeginErrorReadLine(); p.WaitForExit(); return p.ExitCode == 0; } internal static void OutputNonEmptyString(string str, string prefix, Logger logger) { if (!String.IsNullOrWhiteSpace(str) && logger != null) { logger.WriteLine(prefix + str); } } internal static void KillProcessTree(Process p) { bool isLinux = PlatformUtilities.IsLinux(); bool isOSX = PlatformUtilities.IsOSX(); if (isLinux || isOSX) { // On linux run 'ps -x -o "%p %P"' (similarly on Mac), which generates a list of the process ids (%p) and parent process ids (%P). // Using this list, issue a 'kill' command for each child process. Kill the children (recursively) to eliminate // the entire process tree rooted at p. Process ps = new Process(); ps.StartInfo.FileName = "/bin/ps"; ps.StartInfo.Arguments = isLinux ? "-x -o \"%p %P\"" : "-x -o \"pid ppid\""; ps.StartInfo.RedirectStandardOutput = true; ps.StartInfo.UseShellExecute = false; ps.Start(); string line; List<Tuple<int, int>> processAndParent = new List<Tuple<int, int>>(); char[] whitespace = new char[] { ' ', '\t' }; while ((line = ps.StandardOutput.ReadLine()) != null) { line = line.Trim(); int id, pid; if (Int32.TryParse(line.Substring(0, line.IndexOfAny(whitespace)), NumberStyles.Integer, CultureInfo.InvariantCulture, out id) && Int32.TryParse(line.Substring(line.IndexOfAny(whitespace)).Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out pid)) { processAndParent.Add(new Tuple<int, int>(id, pid)); } } KillChildren(processAndParent, p.Id); } } private static void KillChildren(List<Tuple<int, int>> processes, int pid) { processes.ForEach((p) => { if (p.Item2 == pid) { KillChildren(processes, p.Item1); Kill(p.Item1, 9); } }); } internal static void Interrupt(int pid) { Kill(pid, 5); } private static void Kill(int pid, int signal) { var k = Process.Start("/bin/kill", String.Format(CultureInfo.InvariantCulture, "-{0} {1}", signal, pid)); k.WaitForExit(); } } } <|start_filename|>src/SSHDebugPS/Docker/TransportSettings/DockerTransportSettings.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.SSHDebugPS.Utilities; namespace Microsoft.SSHDebugPS.Docker { internal abstract class DockerTransportSettingsBase : IPipeTransportSettings { protected abstract string SubCommand { get; } protected abstract string SubCommandArgs { get; } internal string HostName { get; private set; } internal bool HostIsUnix { get; private set; } public DockerTransportSettingsBase(string hostname, bool hostIsUnix) { HostIsUnix = hostIsUnix; if (!string.IsNullOrWhiteSpace(hostname)) { HostName = hostname; } else { HostName = string.Empty; } } public DockerTransportSettingsBase(DockerTransportSettingsBase settings) : this(settings.HostName, settings.HostIsUnix) { } private static string WindowsExe => "docker.exe"; private static string UnixExe => "docker"; // 0 = docker command parameters // 1 = docker subcommand // 2 = docker subcommand parameters private const string _baseCommandFormat = "{0} {1} {2}"; // 0 = hostname property private const string _hostnameFormat = "--host \"{0}\""; private string GenerateExeCommandArgs() { var hostnameArg = string.Empty; if (!string.IsNullOrWhiteSpace(this.HostName)) hostnameArg = _hostnameFormat.FormatInvariantWithArgs(this.HostName); return _baseCommandFormat.FormatInvariantWithArgs(hostnameArg, SubCommand, SubCommandArgs); } #region IPipeTransportSettings public string CommandArgs => GenerateExeCommandArgs(); public string Command => HostIsUnix ? UnixExe : WindowsExe; #endregion } internal class DockerCommandSettings : DockerTransportSettingsBase { private string _cmd; private string _args; public DockerCommandSettings(string hostname, bool hostIsUnix) : base(hostname, hostIsUnix) { } public void SetCommand(string cmd, string args) { _cmd = cmd; _args = args; } protected override string SubCommand => _cmd; protected override string SubCommandArgs => _args; } } <|start_filename|>test/DebuggerTesting/Attribution/TestSettings.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Text; using DebuggerTesting.Utilities; namespace DebuggerTesting { internal sealed class TestSettings : ITestSettings { #region Constructor internal TestSettings( SupportedArchitecture debuggeeArchitecture, string compilerName, SupportedCompiler compilerType, string compilerPath, IDictionary<string, string> compilerProperties, string debuggerName, SupportedDebugger debuggerType, string debuggerPath, string debuggerAdapterPath, string miMode, IDictionary<string, string> debuggerProperties) { this.CompilerSettings = new CompilerSettings(compilerName, compilerType, compilerPath, debuggeeArchitecture, compilerProperties); this.DebuggerSettings = new DebuggerSettings(debuggerName, debuggerType, debuggerPath, debuggerAdapterPath, miMode, debuggeeArchitecture, debuggerProperties); } private TestSettings(ITestSettings original, string name) { this.Name = name; this.CompilerSettings = original.CompilerSettings; this.DebuggerSettings = original.DebuggerSettings; } #endregion #region Methods public static bool operator ==(TestSettings left, TestSettings right) { if (Object.ReferenceEquals(left, null)) return Object.ReferenceEquals(right, null); return left.Equals(right); } public static bool operator !=(TestSettings left, TestSettings right) { if (Object.ReferenceEquals(left, null)) return !Object.ReferenceEquals(right, null); return !left.Equals(right); } internal static ITestSettings CloneWithName(ITestSettings original, string name) { return new TestSettings(original, name); } public override bool Equals(object obj) { return this.Equals(obj as TestSettings); } public bool Equals(TestSettings obj) { if (Object.ReferenceEquals(obj, null)) return false; if (!String.Equals(this.Name, obj.Name, StringComparison.Ordinal)) return false; if (this.CompilerSettings != obj.CompilerSettings) return false; if (this.DebuggerSettings != obj.DebuggerSettings) return false; return true; } public override int GetHashCode() { return HashUtilities.CombineHashCodes( this.Name?.GetHashCode() ?? 0, this.CompilerSettings?.GetHashCode() ?? 0, this.DebuggerSettings?.GetHashCode() ?? 0); } public override string ToString() { StringBuilder builder = new StringBuilder(); builder.Append(this.CompilerSettings.CompilerName); builder.Append("/"); builder.Append(this.CompilerSettings.DebuggeeArchitecture); builder.Append("/"); builder.Append(this.DebuggerSettings.DebuggerName); return builder.ToString(); } #endregion #region Properties public string Name { get; private set; } public ICompilerSettings CompilerSettings { get; private set; } public IDebuggerSettings DebuggerSettings { get; private set; } #endregion } } <|start_filename|>test/CppTests/Tests/DebuggeeMonikers.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace CppTests.Tests { /// <summary> /// To make it easier to work with debuggees, each test works with a copy of the original debuggee. /// This allows tests to compile with different options, remove symbols or modify source in ways that /// would effect other tests. /// The debuggee will be copied into a folder appended with the moniker. /// </summary> internal static class DebuggeeMonikers { internal static class HelloWorld { public const int Sample = 1; } internal static class KitchenSink { public const int Attach = 1; public const int Threading = 2; public const int Breakpoint = 3; public const int Execution = 4; public const int Expression = 5; public const int Environment = 6; } internal static class SharedLib { public const int Default = 1; public const int MismatchedSource = 2; } internal static class CoreDump { public const int Default = 1; public const int MismatchedSource = 2; public const int Action = 3; } internal static class Exception { public const int Default = 1; } internal static class Optimization { public const int OptimizationWithSymbols = 1; public const int OptimizationWithoutSymbols = 2; } internal static class SourceMapping { public const int Default = 1; } } } <|start_filename|>src/DebugEngineHost/HostConfigurationException.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Globalization; namespace Microsoft.DebugEngineHost { internal sealed class HostConfigurationException : Exception { private const int E_DEBUG_ENGINE_NOT_REGISTERED = unchecked((int)0x80040019); public HostConfigurationException(string missingLocation) : base(string.Format(CultureInfo.InvariantCulture, "Missing configuration section '{0}'", missingLocation)) { this.HResult = E_DEBUG_ENGINE_NOT_REGISTERED; } } } <|start_filename|>test/CppTests/debuggees/optimization/src/mylib.h<|end_filename|> #include <string> #include "mylib_base.h" using namespace std; class myClass:public myBase { public: int DisplayAge(int age); string DisplayName(string firstName, string lastName); }; <|start_filename|>src/MIDebugEngine/Engine.Impl/LaunchErrorException.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; namespace Microsoft.MIDebugEngine { internal class LaunchErrorException : Exception { public LaunchErrorException(string message) : base(message) { } } } <|start_filename|>src/JDbgUnitTests/UtilsTests.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using JDbg; using Xunit; namespace JDbgUnitTests { public class UtilsTests { [Fact] public void UInt32FromBigEndianBytesTest() { uint num = Utils.UInt32FromBigEndianBytes(new byte[4] { 0xAA, 0xBB, 0xCC, 0xDD }); Assert.Equal(0xAABBCCDD, num); } [Fact] public void BigEndianBytesFromUInt32Test() { byte[] bytes = Utils.BigEndianBytesFromUInt32(0xAABBCCDD); Assert.Equal(4, bytes.Length); Assert.Equal(0xAA, bytes[0]); Assert.Equal(0xBB, bytes[1]); Assert.Equal(0xCC, bytes[2]); Assert.Equal(0xDD, bytes[3]); } [Fact] public void BigEndianBytesFromUInt16Test() { UInt16 num = Utils.UInt16FromBigEndianBytes(new byte[2] { 0xAA, 0xBB }); Assert.Equal(0xAABB, num); } [Fact] public void ULongFromBigEndianBytesTest() { ulong num = Utils.ULongFromBigEndiantBytes(new byte[2] { 0xAA, 0xBB }); Assert.Equal(0xAABBul, num); num = Utils.ULongFromBigEndiantBytes(new byte[8] { 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF, 0xAB, 0xCD }); Assert.Equal(0xAABBCCDDEEFFABCD, num); } } } <|start_filename|>test/DebuggerTesting/OpenDebug/Events/BreakpointEvent.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Globalization; using Newtonsoft.Json; namespace DebuggerTesting.OpenDebug.Events { public enum BreakpointReason { Unset = 0, Changed, New, } #region BreakpointEventValue public sealed class BreakpointEventValue : EventValue { public sealed class Body { public sealed class Breakpoint { [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public int? id; [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public bool? verified; [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public string message; [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public int? line; [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public int? column; } [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public string reason; [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public Breakpoint breakpoint; } public Body body = new Body(); } #endregion /// <summary> /// Event that fires when a breakpoint has been modified /// </summary> public class BreakpointEvent : Event<BreakpointEventValue> { private bool verifyLineRange; private int startLine; private int endLine; public BreakpointEvent(BreakpointReason reason, int? line) : base("breakpoint") { this.ExpectedResponse.body.reason = GetReason(reason); if (line != null) { this.ExpectedResponse.body.breakpoint = new BreakpointEventValue.Body.Breakpoint(); this.ExpectedResponse.body.breakpoint.line = line; } } /// <summary> /// Create an expected breakpoint event that works over a range of lines /// </summary> public BreakpointEvent(BreakpointReason reason, int startLine, int endLine) : this(reason, line: null) { Parameter.ThrowIfNegativeOrZero(startLine, nameof(startLine)); Parameter.ThrowIfNegativeOrZero(startLine, nameof(endLine)); this.startLine = startLine; this.endLine = endLine; this.verifyLineRange = true; } private static string GetReason(BreakpointReason reason) { Parameter.ThrowIfIsInvalid(reason, BreakpointReason.Unset, nameof(reason)); return reason.ToString().ToLowerInvariant(); } public override void ProcessActualResponse(IActualResponse response) { base.ProcessActualResponse(response); if (this.verifyLineRange) StoppedEvent.VerifyLineRange(this?.ActualEvent?.body?.breakpoint?.line, this.startLine, this.endLine); } private string GetExpectedLine() { if (this.verifyLineRange) return "{0}-{1}".FormatInvariantWithArgs(this.startLine, this.endLine); return (this.ExpectedResponse.body.breakpoint?.line ?? 0).ToString(CultureInfo.InvariantCulture); } public override string ToString() { return "{0} ({1}, line {2})".FormatInvariantWithArgs(base.ToString(), this.ExpectedResponse.body.reason, this.GetExpectedLine()); } } } <|start_filename|>src/AndroidDebugLauncher/StringExtensions.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using System.IO; namespace AndroidDebugLauncher { internal static class StringExtensions { public static IEnumerable<string> GetLines(this string content) { using (var reader = new StringReader(content)) { while (true) { var line = reader.ReadLine(); if (line == null) break; yield return line; } } } } } <|start_filename|>test/CppTests/debuggees/MacOSApp/src/Shared/main.hpp<|end_filename|> // // main.hpp // TestApp // // Created by <NAME> on 8/31/21. // #ifndef main_hpp #define main_hpp #include <stdio.h> #endif /* main_hpp */ <|start_filename|>.devcontainer/Dockerfile<|end_filename|> FROM mcr.microsoft.com/vscode/devcontainers/dotnet:0.201.7-5.0 # Install gcc, g++ and make RUN sudo apt update && \ sudo apt install build-essential -y # Built with ❤ by [Pipeline Foundation](https://pipeline.foundation) <|start_filename|>src/SSHDebugPS/WSL/WSLException.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Runtime.Serialization; namespace Microsoft.SSHDebugPS.WSL { [Serializable] internal class WSLException : Exception { public WSLException(string message) : base(message) { } public WSLException(string message, Exception innerException) : base(message, innerException) { } protected WSLException(SerializationInfo info, StreamingContext context) : base(info, context) { } } } <|start_filename|>test/DebuggerTesting/Utilities/EnumerableExtensions.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; namespace DebuggerTesting.Utilities { public static class EnumerableExtensions { public static ISet<TKey> ToKeySet<TKey, TValue>(this IDictionary<TKey, TValue> dictionary) { return new HashSet<TKey>(dictionary.Keys); } } } <|start_filename|>test/Android/Attach/Glass2.TestSetup.cmd<|end_filename|> @echo off setlocal if "%_DeviceId%"=="" echo ERROR: DeviceId not set. This should be set by androidtest.cmd.& exit /b -1 if not exist "%_SdkRoot%\platform-tools\adb.exe" echo ERROR: Cannot find adb.exe.& exit /b -1 set _adb=%_SdkRoot%\platform-tools\adb.exe "%_adb%" -s "%_DeviceId%" shell am start -n com.Attach/android.app.NativeActivity :: there is no way to check if this returns an error code AFAIK. https://code.google.com/p/android/issues/detail?id=3254 :: if the am start fails, the test will fail. exit /b 0 <|start_filename|>test/DebuggerTesting/Attribution/SupportedCompilerAttribute.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; namespace DebuggerTesting { /// <summary> /// Attribute used by xUnit theory test for specifying which compilers and debuggee architectures /// are required by the test. /// </summary> [AttributeUsage(AttributeTargets.Method, AllowMultiple = true, Inherited = false)] public class SupportedCompilerAttribute : Attribute { #region Constructor public SupportedCompilerAttribute(SupportedCompiler compiler, SupportedArchitecture debuggeeArchitecture) { this.Compiler = compiler; this.Architecture = debuggeeArchitecture; } #endregion #region Properties public SupportedCompiler Compiler { get; private set; } public SupportedArchitecture Architecture { get; private set; } #endregion } } <|start_filename|>test/CppTests/debuggees/kitchensink/src/arguments.h<|end_filename|> #pragma once #include "global.h" #include <iostream> #include <vector> #include <string> #include <stdarg.h> #include "feature.h" using namespace std; class Arguments : public Feature { public: Arguments(); virtual void CoreRun(); int argc = 0; char ** argv = NULL; bool runNonTerminating = false; bool runCalling = false; bool runThreading = false; bool runExpression = false; bool runEnvironment = false; }; <|start_filename|>test/DebuggerTesting/Ordering/DependencyTestOrderer.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Linq; using Xunit.Abstractions; using Xunit.Sdk; namespace DebuggerTesting.Ordering { public class DependencyTestOrderer : DependencyOrderer<ITestCase, string>, ITestCaseOrderer { // These are used in attributes, so they must be constant. public const string TypeName = nameof(DebuggerTesting) + "." + nameof(Ordering) + "." + nameof(DependencyTestOrderer); public const string AssemblyName = nameof(DebuggerTesting); public IEnumerable<TTestCase> OrderTestCases<TTestCase>(IEnumerable<TTestCase> testCases) where TTestCase : ITestCase { return OrderBasedOnDependencies(testCases.Cast<ITestCase>()).Cast<TTestCase>(); } #region Dependency Helpers protected override int GetIndexOfDependency(IList<ITestCase> tests, string testName) { for (int i = tests.Count - 1; i >= 0; i--) { string currentTestName = tests[i].TestMethod.Method.Name; if (string.Equals(currentTestName, testName, StringComparison.Ordinal)) return i; } return -1; } protected override IEnumerable<string> GetDependencies(ITestCase testCase) { IMethodInfo testMethodInfo = testCase.TestMethod.Method; if (testMethodInfo == null) return null; IEnumerable<IAttributeInfo> attributes = testMethodInfo.GetCustomAttributes(typeof(DependsOnTestAttribute)); return attributes.Select(x => x.GetConstructorArguments().OfType<string>().First()); } #endregion protected override string GetItemName(ITestCase item) { return item.DisplayName; } } } <|start_filename|>test/DebuggerTesting/OpenDebug/Commands/Responses/ReadMemoryResponseValue.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Newtonsoft.Json; namespace DebuggerTesting.OpenDebug.Commands.Responses { public sealed class ReadMemoryResponseValue : CommandResponseValue { public sealed class Body { public string address; [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public int unreadableBytes; [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public string data; } public Body body = new Body(); } } <|start_filename|>test/DebuggerTesting/OpenDebug/IDebuggerRunner.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using DebuggerTesting.OpenDebug.Commands; using DarRunner = DebugAdapterRunner.DebugAdapterRunner; namespace DebuggerTesting.OpenDebug { /// <summary> /// A wrapper around the DAR debugger adapter runner. /// The abstracts parameters that need to be passed to the DAR runner. /// It also has logic to check for leaked processes and files. /// </summary> public interface IDebuggerRunner : ILoggingComponent, IDisposable { /// <summary> /// The debug adapter runner this wraps. /// </summary> DarRunner DarRunner { get; } /// <summary> /// If an error is encountered running a previous command, this gets set to true /// and subsequent commands are not issued. /// </summary> bool ErrorEncountered { get; set; } /// <summary> /// When a break event occurs this reports the thread id of the current thread. /// </summary> int StoppedThreadId { get; } /// <summary> /// Runs a debug adapter command. /// </summary> /// <param name="command">The command to run</param> /// <param name="expectedEvents">[OPTIONAL] If the command expects to raise events, provide the list of events to look for.</param> void RunCommand(ICommand command, params IEvent[] expectedEvents); R RunCommand<R>(ICommandWithResponse<R> command, params IEvent[] expectedEvents); /// <summary> /// Provides a builder for describing expected events and command. /// First provides events in the order they are expected, then finish /// with the command to be run. /// </summary> IRunBuilder Expects { get; } /// <summary> /// Performs a disconnct command and verifies that child processes are closed. /// If they are not, this fails the test. /// If you just call Dispose, the processes are closed, but the test does not fail. /// </summary> void DisconnectAndVerify(); InitializeResponseValue InitializeResponse { get; } /// <summary> /// Gets the settings for the debugger /// </summary> IDebuggerSettings DebuggerSettings { get; } } } <|start_filename|>test/Android/CallStack/CallStack/CallStack.NativeActivity/Source1.cpp<|end_filename|> #include "Header1.h" #include "Header2.h" bool func3(int *x, int *y) { ++x; ++y; return x == y; } int func2(int x, int y) { ++x; --y; func3(&x, &y); return x + y; } void func1() { int x = 10, y = 20; func2(x, y); func6(func7, func8); return; } <|start_filename|>src/MIDebugPackage/Properties/AssemblyInfo.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Microsoft.MIDebugPackage")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: CLSCompliant(false)] [assembly: NeutralResourcesLanguage("en-US")] <|start_filename|>test/DebuggerTesting/OpenDebug/Commands/AttachCommand.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace DebuggerTesting.OpenDebug.Commands { public abstract class AttachCommand<T> : Command<T> where T : LaunchCommandArgs, new() { public AttachCommand() : base("attach") { } } } <|start_filename|>test/Android/Stepping/Stepping/Stepping.NativeActivity/Header1.h<|end_filename|> #pragma once void func1(); void func2(); <|start_filename|>test/DebuggerTesting/Utilities/HashUtilities.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace DebuggerTesting.Utilities { internal static class HashUtilities { #region Methods public static int CombineHashCodes(int h1, int h2) { return (h1 << 5) + h1 ^ h2; } internal static int CombineHashCodes(int h1, int h2, int h3) { return HashUtilities.CombineHashCodes(HashUtilities.CombineHashCodes(h1, h2), h3); } internal static int CombineHashCodes(int h1, int h2, int h3, int h4) { return HashUtilities.CombineHashCodes(HashUtilities.CombineHashCodes(h1, h2), HashUtilities.CombineHashCodes(h3, h4)); } internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5) { return HashUtilities.CombineHashCodes(HashUtilities.CombineHashCodes(h1, h2, h3, h4), h5); } #endregion } } <|start_filename|>test/CppTests/Tests/SharedLibTests.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Globalization; using System.IO; using DebuggerTesting; using DebuggerTesting.Compilation; using DebuggerTesting.OpenDebug; using DebuggerTesting.OpenDebug.Commands; using DebuggerTesting.OpenDebug.CrossPlatCpp; using DebuggerTesting.OpenDebug.Extensions; using DebuggerTesting.Ordering; using Xunit; using Xunit.Abstractions; namespace CppTests.Tests { [TestCaseOrderer(DependencyTestOrderer.TypeName, DependencyTestOrderer.AssemblyName)] public class SharedLibTests : TestBase { #region Constructor public SharedLibTests(ITestOutputHelper outputHelper) : base(outputHelper) { } #endregion #region Fields private const string srcLibName = "mylib.cpp"; private const string srcAppName = "myapp.cpp"; private const string outAppName = "myapp"; private const string outLibName = "mylib"; private const string debuggeeName = "sharedlib"; #endregion #region Methods [Theory] [RequiresTestSettings] public void CompileSharedLibDebuggee(ITestSettings settings) { this.TestPurpose("Create and compile the 'sharedlib' debuggee"); this.WriteSettings(settings); //Compile the shared library CompileSharedLib(settings, DebuggeeMonikers.SharedLib.Default); //Compile the application CompileApp(settings, DebuggeeMonikers.SharedLib.Default); } [Theory] [DependsOnTest(nameof(CompileSharedLibDebuggee))] // TODO: https://github.com/microsoft/MIEngine/issues/1170 // - lldb [UnsupportedDebugger(SupportedDebugger.VsDbg | SupportedDebugger.Lldb, SupportedArchitecture.x86 | SupportedArchitecture.x64)] [RequiresTestSettings] public void SharedLibBasic(ITestSettings settings) { this.TestPurpose("This test checks to see if basic debugging scenarios work for application invoked shared library."); this.WriteSettings(settings); this.Comment("Start running targeted scenarios"); RunTargetedScenarios(settings, outAppName, DebuggeeMonikers.SharedLib.Default); } [Theory] // TODO: https://github.com/microsoft/MIEngine/issues/1170 // - lldb [UnsupportedDebugger(SupportedDebugger.VsDbg | SupportedDebugger.Lldb, SupportedArchitecture.x86 | SupportedArchitecture.x64)] [RequiresTestSettings] public void SharedLibMismatchSourceAndSymbols(ITestSettings settings) { this.TestPurpose("This test checks to see if it crashs when debugging the mismatch source and symbols of shared library."); this.WriteSettings(settings); //Compile the shared library CompileSharedLib(settings, DebuggeeMonikers.SharedLib.MismatchedSource); //Compile the application CompileApp(settings, DebuggeeMonikers.SharedLib.MismatchedSource); this.Comment("Apply changes in the source of shared library after build"); ApplyChangesInSharedLib(settings, DebuggeeMonikers.SharedLib.MismatchedSource); this.Comment("Start running targeted scenarios"); RunTargetedScenarios(settings, outAppName, DebuggeeMonikers.SharedLib.MismatchedSource); } #endregion #region Function Helper /// <summary> /// Compile the shared library /// </summary> private void CompileSharedLib(ITestSettings settings, int debuggeeMoniker) { IDebuggee debuggee = Debuggee.Create(this, settings.CompilerSettings, debuggeeName, debuggeeMoniker, outLibName, CompilerOutputType.SharedLibrary); debuggee.AddSourceFiles(srcLibName); debuggee.Compile(); } /// <summary> /// Compile the application /// </summary> private void CompileApp(ITestSettings settings, int debuggeeMoniker) { IDebuggee debuggee = Debuggee.Open(this, settings.CompilerSettings, debuggeeName, debuggeeMoniker, outAppName); switch (settings.DebuggerSettings.DebuggerType) { case SupportedDebugger.Gdb_Cygwin: case SupportedDebugger.Gdb_Gnu: case SupportedDebugger.Lldb: debuggee.AddLibraries("dl"); break; case SupportedDebugger.Gdb_MinGW: // The sharedlib debuggee contains both POSIX and Windows support on loading dynamic library, we use "_MinGW" to identify the relevant testing code debuggee.AddDefineConstant("_MINGW"); break; } debuggee.AddSourceFiles(srcAppName); debuggee.Compile(); } /// <summary> /// Apply changes in shared library so that the source and symbols is not matached anymore /// </summary> private void ApplyChangesInSharedLib(ITestSettings settings, int debuggeeMoniker) { IDebuggee debuggee = Debuggee.Open(this, settings.CompilerSettings, debuggeeName, debuggeeMoniker, outLibName); string libPath = string.Format(CultureInfo.InvariantCulture, Path.Combine(debuggee.SourceRoot, srcLibName)); Assert.True(File.Exists(libPath), string.Format(CultureInfo.InvariantCulture, "ERROR: Didn't find the source file:{0} under {1}", libPath, debuggee.SourceRoot)); try { using (StreamWriter writer = File.AppendText(libPath)) { //TODO: I just simply added a new line to make the symbols mismatch after compile the library, we can add some real code changes here if need it. writer.WriteLine(System.Environment.NewLine); } } catch { this.Comment("ERROR: Didn't apply the changes in shared library successfully."); throw; } } /// <summary> /// Testing the common targeted scenarios /// </summary> private void RunTargetedScenarios(ITestSettings settings, string outputName, int debuggeeMoniker) { this.Comment("Set initial debuggee"); IDebuggee debuggee = Debuggee.Open(this, settings.CompilerSettings, debuggeeName, debuggeeMoniker, outAppName); using (IDebuggerRunner runner = CreateDebugAdapterRunner(settings)) { this.Comment("Configure launch"); runner.Launch(settings.DebuggerSettings, debuggee); this.Comment("Set initial function breakpoints"); FunctionBreakpoints functionBreakpoints = new FunctionBreakpoints("main", "myClass::DisplayName", "myClass::DisplayAge"); runner.SetFunctionBreakpoints(functionBreakpoints); this.Comment("Set line breakpoints to the lines with entry of shared library"); SourceBreakpoints bps = debuggee.Breakpoints(srcAppName, 71, 77); runner.SetBreakpoints(bps); this.Comment("Launch and run until first breakpoint in the entry of main"); runner.ExpectBreakpointAndStepToTarget(srcAppName, startLine: 62, targetLine: 63) .AfterConfigurationDone(); this.Comment("Continue to go to the line which is the first entry of shared library"); runner.Expects.HitBreakpointEvent(srcAppName, 71) .AfterContinue(); this.Comment("Step into the function in shared library"); runner.Expects.HitStepEvent(srcLibName, 23) .AfterStepIn(); this.Comment("Step out to go back to the entry in main function"); runner.Expects.HitStepEvent(srcAppName, 71) .AfterStepOut(); this.Comment("Step over to go to the line which is the second entry of shared library"); runner.Expects.HitStepEvent(srcAppName, 73).AfterStepOver(); this.Comment("Step over a function which have a breakpoint set in shared library"); runner.ExpectBreakpointAndStepToTarget(srcLibName, startLine: 8, targetLine: 9).AfterStepOver(); this.Comment("Step over a line in function which is inside shared library"); runner.Expects.HitStepEvent(srcLibName, 10).AfterStepOver(); this.Comment("Step out to go back to the entry in main function"); runner.ExpectStepAndStepToTarget(srcAppName, startLine: 73, targetLine: 75).AfterStepOut(); this.Comment("Continue to hit breakpoint in function which is inside shared library"); runner.ExpectBreakpointAndStepToTarget(srcLibName, startLine: 15, targetLine: 16) .AfterContinue(); this.Comment("Continue to hit breakpoint which set in the last entry of shared library"); runner.Expects.HitBreakpointEvent(srcAppName, 77).AfterContinue(); this.Comment("Step over a function which don't have breakpoint set in shared library"); runner.Expects.HitStepEvent(srcAppName, 79) .AfterStepOver(); this.Comment("Continue to run till at the end of the application"); runner.Expects.TerminatedEvent().AfterContinue(); runner.DisconnectAndVerify(); } } #endregion } } <|start_filename|>test/DebuggerTesting/Compilation/CompilerOption.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; namespace DebuggerTesting.Compilation { [Flags] public enum CompilerOption { None = 0x0, GenerateSymbols = 0x1, SupportThreading = 0x2, OptimizeLevel1 = 0x4, OptimizeLevel2 = 0x8, OptimizeLevel3 = 0x10 } } <|start_filename|>src/DebugEngineHost/HostWaitLoop.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Microsoft.DebugEngineHost { public sealed class HostWaitLoop { private readonly object _progressLock = new object(); private VSImpl.VsWaitLoop _vsWaitLoop; public HostWaitLoop(string message) { try { _vsWaitLoop = VSImpl.VsWaitLoop.TryCreate(message); } catch (FileNotFoundException) { // Visual Studio is not installed on this box } } /// <summary> /// Sets the text of the dialog without changing the progress. /// </summary> /// <param name="text">Text to set.</param> public void SetText(string text) { _vsWaitLoop.SetText(text); } /// <summary> /// Waits on the specified handle. This method should be called only once. /// </summary> /// <param name="launchCompleteHandle">[Required] handle to wait on</param> /// <param name="cancellationSource">[Required] Object to signal cancellation if cancellation is requested</param> /// <returns>true if we were able to successfully wait, false if we failed to wait and should fall back to the CLR provided wait function</returns> /// <exception cref="FileNotFoundException">Thrown by the JIT if Visual Studio is not installed</exception> public void Wait(WaitHandle launchCompleteHandle, CancellationTokenSource cancellationSource) { if (_vsWaitLoop != null) { _vsWaitLoop.Wait(launchCompleteHandle, cancellationSource); lock (_progressLock) { _vsWaitLoop = null; } } else { launchCompleteHandle.WaitOne(); // For glass, fall back to waiting using the .NET Framework APIs } } public void SetProgress(int totalSteps, int currentStep, string progressText) { lock (_progressLock) { if (_vsWaitLoop != null) { _vsWaitLoop.SetProgress(totalSteps, currentStep, progressText); } } } } } <|start_filename|>test/Android/EvalPrimitiveTypes/EvalPrimitiveTypes/EvalPrimitiveTypes.NativeActivity/Header1.h<|end_filename|> #pragma once void Func(); <|start_filename|>src/OpenDebugAD7/TextPositionTuple.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.IO; using Microsoft.VisualStudio.Debugger.Interop; using Microsoft.VisualStudio.Shared.VSCodeDebugProtocol.Messages; namespace OpenDebugAD7 { internal class TextPositionTuple { public readonly Source Source; public readonly int Line; public readonly int Column; public static readonly TextPositionTuple Nil = new TextPositionTuple(null, 0, 0); private TextPositionTuple(Source source, int line, int column) { this.Source = source; this.Line = line; this.Column = column; } public static TextPositionTuple GetTextPositionOfFrame(PathConverter converter, IDebugStackFrame2 frame) { IDebugDocumentContext2 documentContext; if (frame.GetDocumentContext(out documentContext) == 0 && documentContext != null) { TEXT_POSITION[] beginPosition = new TEXT_POSITION[1]; TEXT_POSITION[] endPosition = new TEXT_POSITION[1]; documentContext.GetStatementRange(beginPosition, endPosition); string filePath; documentContext.GetName(enum_GETNAME_TYPE.GN_FILENAME, out filePath); string convertedFilePath = converter.ConvertDebuggerPathToClient(filePath); Source source = new Source() { Path = convertedFilePath, Name = Path.GetFileName(convertedFilePath) }; int line = converter.ConvertDebuggerLineToClient((int)beginPosition[0].dwLine); int column = unchecked((int)(beginPosition[0].dwColumn + 1)); return new TextPositionTuple(source, line, column); } return null; } } } <|start_filename|>src/MIDebugEngine/AD7.Impl/HashAlgorithmId.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Linq; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; using MICore; namespace Microsoft.MIDebugEngine { public class HashAlgorithmId { // The AD7 Guid representing this hash algorithm public readonly Guid AD7GuidHashAlgorithm = Guid.Empty; // Size in bytes of a hash returned by this hash algorithm public readonly uint HashSize = 0; public readonly MIHashAlgorithmName MIHashAlgorithmName; private HashAlgorithmId(Guid guidHashAlgorithm, uint size, MIHashAlgorithmName hashAlgorithmName) { AD7GuidHashAlgorithm = guidHashAlgorithm; HashSize = size; MIHashAlgorithmName = hashAlgorithmName; } public static readonly HashAlgorithmId MD5 = new HashAlgorithmId(AD7Guids.guidSourceHashMD5, 16, MIHashAlgorithmName.MD5); public static readonly HashAlgorithmId SHA1 = new HashAlgorithmId(AD7Guids.guidSourceHashSHA1, 20, MIHashAlgorithmName.SHA1); public static readonly HashAlgorithmId SHA1Normalized = new HashAlgorithmId(AD7Guids.guidSourceHashSHA1Normalized, 20, MIHashAlgorithmName.SHA1); public static readonly HashAlgorithmId SHA256 = new HashAlgorithmId(AD7Guids.guidSourceHashSHA256, 32, MIHashAlgorithmName.SHA256); public static readonly HashAlgorithmId SHA256Normalized = new HashAlgorithmId(AD7Guids.guidSourceHashSHA256Normalized, 32, MIHashAlgorithmName.SHA256); } } <|start_filename|>test/DebuggerTesting/Ordering/DependsOnTestAttribute.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; namespace DebuggerTesting.Ordering { [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)] public class DependsOnTestAttribute : Attribute { public DependsOnTestAttribute(string testName) { Parameter.ThrowIfNull(testName, nameof(testName)); this.TestName = testName; } public string TestName { get; set; } } } <|start_filename|>test/CppTests/debuggees/sourcemap/src/writer/writer.h<|end_filename|> #pragma once #include <stdio.h> #include <string> class Writer { public: Writer(); void Write(const std::string msg); void Write(const int number); void WriteLine(const std::string msg); void WriteLine(const int number); }; <|start_filename|>src/AndroidDebugLauncher/TextColumn.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AndroidDebugLauncher { /// <summary> /// Code for parsing output from programs that write tables with fixed-width colmuns. Used for parsing /// the output from the 'ps' command. /// </summary> [DebuggerDisplay("Name={Name}")] internal class TextColumn { /// <summary> /// [Required] Name of the column /// </summary> readonly public string Name; /// <summary> /// [Required] Character index where the column starts /// </summary> readonly public int StartIndex; /// <summary> /// [Optional] Length of the colmun. This will be -1 for the last column. /// </summary> readonly public int Length; private TextColumn(string name, int startIndex, int length) { this.Name = name; this.StartIndex = startIndex; this.Length = length; } /// <summary> /// Parsers the header line from a table, returning an array of columns /// </summary> /// <param name="headerLine">The line of text with the header</param> /// <returns>[Optional] Array of columns</returns> public static TextColumn[] TryParseHeader(string headerLine) { List<TextColumn> columns = new List<TextColumn>(); int startIndex = 0; int position = 0; // Move past any initial whitespace if (!SkipWhitespace(ref position, headerLine)) { return null; // line is nothing but whitespace } int nameStartIndex = position; while (true) { // Skip until the start of the next column int nextWhitespace = headerLine.IndexOfAny(s_spaceChars, position); position = nextWhitespace; if (position >= 0 && SkipWhitespace(ref position, headerLine)) { // Position is currently at the start of the next column. Create an object for the column we just went past TextColumn newColumn = new TextColumn(headerLine.Substring(nameStartIndex, nextWhitespace - nameStartIndex), startIndex, position - startIndex); columns.Add(newColumn); nameStartIndex = startIndex = position; } else { // Create the last column if (nextWhitespace < 0) nextWhitespace = headerLine.Length; TextColumn newColumn = new TextColumn(headerLine.Substring(nameStartIndex, nextWhitespace - nameStartIndex), startIndex, -1); columns.Add(newColumn); return columns.ToArray(); } } } public string ExtractCell(string row) { if (row.Length < this.StartIndex) return string.Empty; int length = this.Length; if (length < 0) length = row.Length - this.StartIndex; // The header and the data rows don't exsactly match up where they start - // sometimes the data rows are a column sooner (ex: 'NAME', 'PC') and sometimes the // data rows are a colmn after (ex: 'PID', 'PPID'). // // USER PID PPID VSIZE RSS WCHAN PC NAME // root 1 0 640 496 c00bd520 00019fb8 S /init // root 2 0 0 0 c00335a0 00000000 S kthreadd // root 3 2 0 0 c001e39c 00000000 S ksoftirqd/0 int startIndex = this.StartIndex; int? delta = FindColumnBreak(row, this.StartIndex); if (!delta.HasValue) return string.Empty; startIndex += delta.Value; length -= delta.Value; if (this.Length > 0) { delta = FindColumnBreak(row, startIndex + length); if (delta.HasValue) { length += delta.Value; } } while (length > 0 && IsSpace(row, startIndex + length - 1)) { length--; } return row.Substring(startIndex, length); } /// <summary> /// Hunt arround to try and find a column break near the specified index /// </summary> /// <param name="row">line of text to test</param> /// <param name="index">Expected spot for the column break</param> /// <returns>null if no column break could be found, otherwise the delta between the expected index and where it was really found</returns> private int? FindColumnBreak(string row, int index) { int[] candidateDeltas = { 0, -1, 1, -2, 2, -3, 3 }; foreach (int delta in candidateDeltas) { if (IsColmnBreakIndex(row, index + delta)) { return delta; } } return null; } /// <summary> /// Check if the specified position is a column break /// </summary> /// <param name="row">Line of text to check</param> /// <param name="index">Index to check</param> /// <returns>Returns true if the position before index is a space, and index is NOT a space</returns> private static bool IsColmnBreakIndex(string row, int index) { return IsSpace(row, index - 1) && !IsSpace(row, index); } private static bool SkipWhitespace(ref int position, string headerLine) { while (true) { if (position == headerLine.Length) { position = -1; return false; } if (!IsSpace(headerLine[position])) return true; position++; } } static private readonly char[] s_spaceChars = { ' ', '\t' }; private static bool IsSpace(char ch) { return (ch == ' ' || ch == '\t'); } private static bool IsSpace(string str, int index) { if (index < 0 || index >= str.Length) return true; // index outside of the range of a string. It is considered whitespace return IsSpace(str[index]); } } } <|start_filename|>src/MICore/JsonLaunchOptions.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace MICore.Json.LaunchOptions { public abstract partial class BaseOptions { /// <summary> /// Semicolon separated list of directories to use to search for .so files. Example: "c:\dir1;c:\dir2". /// </summary> [JsonProperty("additionalSOLibSearchPath", DefaultValueHandling = DefaultValueHandling.Ignore)] public string AdditionalSOLibSearchPath { get; set; } /// <summary> /// Full path to program executable. /// </summary> [JsonProperty("program")] public string Program { get; set; } /// <summary> /// The type of the engine. Must be "cppdbg". /// </summary> [JsonProperty("type", DefaultValueHandling = DefaultValueHandling.Ignore)] public string Type { get; set; } /// <summary> /// The architecture of the debuggee. This will automatically be detected unless this parameter is set. Allowed values are x86, arm, arm64, mips, x64, amd64, x86_64. /// </summary> [JsonProperty("targetArchitecture", DefaultValueHandling = DefaultValueHandling.Ignore)] public string TargetArchitecture { get; set; } /// <summary> /// .natvis file to be used when debugging this process. This option is not compatible with GDB pretty printing. Please also see "showDisplayString" if using this setting. /// </summary> [JsonProperty("visualizerFile", DefaultValueHandling = DefaultValueHandling.Ignore)] public string VisualizerFile { get; set; } /// <summary> /// When a visualizerFile is specified, showDisplayString will enable the display string. Turning this option on can cause slower performance during debugging. /// </summary> [JsonProperty("showDisplayString", DefaultValueHandling = DefaultValueHandling.Ignore)] public bool? ShowDisplayString { get; set; } /// <summary> /// Indicates the console debugger that the MIDebugEngine will connect to. Allowed values are "gdb" "lldb". /// </summary> [JsonProperty("MIMode", DefaultValueHandling = DefaultValueHandling.Ignore)] public string MIMode { get; set; } /// <summary> /// The path to the mi debugger (such as gdb). When unspecified, it will search path first for the debugger. /// </summary> [JsonProperty("miDebuggerPath", DefaultValueHandling = DefaultValueHandling.Ignore)] public string MiDebuggerPath { get; set; } /// <summary> /// Arguments for the mi debugger. /// </summary> [JsonProperty("miDebuggerArgs", DefaultValueHandling = DefaultValueHandling.Ignore)] public string MiDebuggerArgs { get; set; } /// <summary> /// Network address of the MI Debugger Server to connect to (example: localhost:1234). /// </summary> [JsonProperty("miDebuggerServerAddress", DefaultValueHandling = DefaultValueHandling.Ignore)] public string MiDebuggerServerAddress { get; set; } /// <summary> /// Optional source file mappings passed to the debug engine. Example: '{ "/original/source/path":"/current/source/path" }' /// </summary> [JsonProperty("sourceFileMap", DefaultValueHandling = DefaultValueHandling.Ignore)] public Dictionary<string, object> SourceFileMap { get; protected set; } /// <summary> /// When present, this tells the debugger to connect to a remote computer using another executable as a pipe that will relay standard input/output between VS Code and the MI-enabled debugger backend executable (such as gdb). /// </summary> [JsonProperty("pipeTransport", DefaultValueHandling = DefaultValueHandling.Ignore)] public PipeTransport PipeTransport { get; set; } /// <summary> /// Supports explcit control of symbol loading. The processing of Exceptions lists and symserver entries. /// </summary> [JsonProperty("symbolLoadInfo", DefaultValueHandling = DefaultValueHandling.Ignore)] public SymbolLoadInfo SymbolLoadInfo { get; set; } /// <summary> /// One or more GDB/LLDB commands to execute in order to setup the underlying debugger. Example: "setupCommands": [ { "text": "-enable-pretty-printing", "description": "Enable GDB pretty printing", "ignoreFailures": true }]. /// </summary> [JsonProperty("setupCommands", DefaultValueHandling = DefaultValueHandling.Ignore)] public List<SetupCommand> SetupCommands { get; protected set; } /// <summary> /// One or more commands to execute in order to setup underlying debugger after debugger has been attached. i.e. flashing and resetting the board /// </summary> [JsonProperty("postRemoteConnectCommands", DefaultValueHandling = DefaultValueHandling.Ignore)] public List<SetupCommand> PostRemoteConnectCommands { get; protected set; } /// <summary> /// Explicitly control whether hardware breakpoints are used. If an optional limit is provided, additionally restrict the number of hardware breakpoints for remote targets. Example: "hardwareBreakpoints": { "require": true, "limit": 5 }. /// </summary> [JsonProperty("hardwareBreakpoints", DefaultValueHandling = DefaultValueHandling.Ignore)] public HardwareBreakpointInfo HardwareBreakpointInfo { get; set; } } public partial class AttachOptions : BaseOptions { #region Public Properties for Serialization [JsonProperty("processId")] public int ProcessId { get; private set; } #endregion #region Constructors public AttachOptions() { this.SourceFileMap = new Dictionary<string, object>(); } public AttachOptions( string program, int processId, string type = null, string targetArchitecture = null, string visualizerFile = null, bool? showDisplayString = null, string additionalSOLibSearchPath = null, string MIMode = null, string miDebuggerPath = null, string miDebuggerArgs = null, string miDebuggerServerAddress = null, HardwareBreakpointInfo hardwareBreakpointInfo = null, Dictionary<string, object> sourceFileMap = null, PipeTransport pipeTransport = null, SymbolLoadInfo symbolLoadInfo = null) { this.Program = program; this.Type = type; this.TargetArchitecture = targetArchitecture; this.VisualizerFile = visualizerFile; this.ShowDisplayString = showDisplayString; this.AdditionalSOLibSearchPath = additionalSOLibSearchPath; this.MIMode = MIMode; this.MiDebuggerPath = miDebuggerPath; this.MiDebuggerArgs = miDebuggerArgs; this.MiDebuggerServerAddress = miDebuggerServerAddress; this.ProcessId = processId; this.HardwareBreakpointInfo = hardwareBreakpointInfo; this.SourceFileMap = sourceFileMap; this.PipeTransport = pipeTransport; this.SymbolLoadInfo = symbolLoadInfo; } #endregion } public partial class Environment { #region Public Properties for Serialization [JsonProperty("name", DefaultValueHandling = DefaultValueHandling.Ignore)] public string Name { get; set; } [JsonProperty("value", DefaultValueHandling = DefaultValueHandling.Ignore)] public string Value { get; set; } #endregion #region Constructors public Environment() { } public Environment(string name = null, string value = null) { this.Name = name; this.Value = value; } #endregion } public partial class SymbolLoadInfo { #region Public Properties for Serialization /// <summary> /// If true, symbols for all libs will be loaded, otherwise no solib symbols will be loaded. Modified by ExceptionList. Default value is true. /// </summary> [JsonProperty("loadAll", DefaultValueHandling = DefaultValueHandling.Ignore)] public bool? LoadAll { get; set; } /// <summary> /// List of filenames (wildcards allowed). Modifies behavior of LoadAll. /// If LoadAll is true then don't load symbols for libs that match any name in the list. /// Otherwise only load symbols for libs that match. /// </summary> [JsonProperty("exceptionList", DefaultValueHandling = DefaultValueHandling.Ignore)] public string ExceptionList { get; set; } #endregion #region Constructors public SymbolLoadInfo() { } public SymbolLoadInfo(bool? loadAll = null, string exceptionList = null) { this.LoadAll = loadAll; this.ExceptionList = exceptionList; } #endregion } public partial class HardwareBreakpointInfo { #region Public Properties for Serialization /// <summary> /// If true, always use hardware breakpoints. Default value is false. /// </summary> [JsonProperty("require")] public bool Require { get; set; } /// <summary> /// When <see cref="Require"/> is true, restrict the number of available hardware breakpoints. Default is 0, in which case there is no limit. This setting is only enforced with remote GDB targets. /// </summary> [JsonProperty("limit", DefaultValueHandling = DefaultValueHandling.Ignore)] public int? Limit { get; set; } #endregion #region Constructors public HardwareBreakpointInfo() { } public HardwareBreakpointInfo(bool require = false, int? limit = null) { this.Require = require; this.Limit = limit; } #endregion } public partial class LaunchOptions : BaseOptions { #region Public Properties for Serialization /// <summary> /// Command line arguments passed to the program. /// </summary> [JsonProperty("args", DefaultValueHandling = DefaultValueHandling.Ignore)] public List<string> Args { get; private set; } /// <summary> /// The working directory of the target /// </summary> [JsonProperty("cwd", DefaultValueHandling = DefaultValueHandling.Ignore)] public string Cwd { get; set; } /// <summary> /// If provided, this replaces the default commands used to launch a target with some other commands. For example, this can be "-target-attach" in order to attach to a target process. An empty command list replaces the launch commands with nothing, which can be useful if the debugger is being provided launch options as command line options. Example: "customLaunchSetupCommands": [ { "text": "target-run", "description": "run target", "ignoreFailures": false }]. /// </summary> [JsonProperty("customLaunchSetupCommands", DefaultValueHandling = DefaultValueHandling.Ignore)] public List<SetupCommand> CustomLaunchSetupCommands { get; private set; } /// <summary> /// The command to execute after the debugger is fully setup in order to cause the target process to run. Allowed values are "exec-run", "exec-continue", "None". The default value is "exec-run". /// </summary> [JsonProperty("launchCompleteCommand", DefaultValueHandling = DefaultValueHandling.Ignore), JsonConverter(typeof(LaunchCompleteCommandConverter))] public LaunchCompleteCommand? LaunchCompleteCommand { get; set; } /// <summary> /// Environment variables to add to the environment for the program. Example: [ { "name": "squid", "value": "clam" } ]. /// </summary> [JsonProperty("environment", DefaultValueHandling = DefaultValueHandling.Ignore)] public List<Environment> Environment { get; private set; } /// <summary> /// Optional parameter. If true, the debugger should stop at the entrypoint of the target. If processId is passed, has no effect. /// </summary> [JsonProperty("stopAtEntry", DefaultValueHandling = DefaultValueHandling.Ignore)] public bool? StopAtEntry { get; set; } /// <summary> /// Optional full path to debug server to launch. Defaults to null. /// </summary> [JsonProperty("debugServerPath", DefaultValueHandling = DefaultValueHandling.Ignore)] public string DebugServerPath { get; set; } /// <summary> /// Optional debug server args. Defaults to null. /// </summary> [JsonProperty("debugServerArgs", DefaultValueHandling = DefaultValueHandling.Ignore)] public string DebugServerArgs { get; set; } /// <summary> /// Optional server-started pattern to look for in the debug server output. Defaults to null. /// </summary> [JsonProperty("serverStarted", DefaultValueHandling = DefaultValueHandling.Ignore)] public string ServerStarted { get; set; } /// <summary> /// Optional time, in milliseconds, for the debugger to wait for the debugServer to start up. Default is 10000. /// </summary> [JsonProperty("serverLaunchTimeout", DefaultValueHandling = DefaultValueHandling.Ignore)] public int? ServerLaunchTimeout { get; set; } /// <summary> /// Search stdout stream for server-started pattern and log stdout to debug output. Defaults to true. /// </summary> [JsonProperty("filterStdout", DefaultValueHandling = DefaultValueHandling.Ignore)] public bool? FilterStdout { get; set; } /// <summary> /// Search stderr stream for server-started pattern and log stderr to debug output. Defaults to false. /// </summary> [JsonProperty("filterStderr", DefaultValueHandling = DefaultValueHandling.Ignore)] public bool? FilterStderr { get; set; } /// <summary> /// Optional full path to a core dump file for the specified program. Defaults to null. /// </summary> [JsonProperty("coreDumpPath", DefaultValueHandling = DefaultValueHandling.Ignore)] public string CoreDumpPath { get; set; } /// <summary> /// If true, a console is launched for the debuggee. If false, no console is launched. Note this option is ignored in some cases for technical reasons. /// </summary> [JsonProperty("externalConsole", DefaultValueHandling = DefaultValueHandling.Ignore)] public bool? ExternalConsole { get; set; } /// <summary> /// If true, disables debuggee console redirection that is required for Integrated Terminal support. /// </summary> [JsonProperty("avoidWindowsConsoleRedirection", DefaultValueHandling = DefaultValueHandling.Ignore)] public bool? AvoidWindowsConsoleRedirection { get; set; } /// <summary> /// Optional parameter. If true, the debugger should stop after connecting to the target. /// </summary> [JsonProperty("stopAtConnect", DefaultValueHandling = DefaultValueHandling.Ignore)] public bool? StopAtConnect { get; set; } #endregion #region Constructors public LaunchOptions() { this.Args = new List<string>(); this.SetupCommands = new List<SetupCommand>(); this.PostRemoteConnectCommands = new List<SetupCommand>(); this.CustomLaunchSetupCommands = new List<SetupCommand>(); this.Environment = new List<Environment>(); this.SourceFileMap = new Dictionary<string, object>(); } public LaunchOptions( string program, List<string> args = null, string type = null, string targetArchitecture = null, string cwd = null, List<SetupCommand> setupCommands = null, List<SetupCommand> postRemoteConnectCommands = null, List<SetupCommand> customLaunchSetupCommands = null, LaunchCompleteCommand? launchCompleteCommand = null, string visualizerFile = null, bool? showDisplayString = null, List<Environment> environment = null, string additionalSOLibSearchPath = null, string MIMode = null, string miDebuggerPath = null, string miDebuggerArgs = null, string miDebuggerServerAddress = null, bool? stopAtEntry = null, string debugServerPath = null, string debugServerArgs = null, string serverStarted = null, bool? filterStdout = null, bool? filterStderr = null, int? serverLaunchTimeout = null, string coreDumpPath = null, bool? externalConsole = null, HardwareBreakpointInfo hardwareBreakpointInfo = null, Dictionary<string, object> sourceFileMap = null, PipeTransport pipeTransport = null, bool? stopAtConnect = null) { this.Program = program; this.Args = args; this.Type = type; this.TargetArchitecture = targetArchitecture; this.Cwd = cwd; this.SetupCommands = setupCommands; this.PostRemoteConnectCommands = postRemoteConnectCommands; this.CustomLaunchSetupCommands = customLaunchSetupCommands; this.LaunchCompleteCommand = launchCompleteCommand; this.VisualizerFile = visualizerFile; this.ShowDisplayString = showDisplayString; this.Environment = environment; this.AdditionalSOLibSearchPath = additionalSOLibSearchPath; this.MIMode = MIMode; this.MiDebuggerPath = miDebuggerPath; this.MiDebuggerArgs = miDebuggerArgs; this.MiDebuggerServerAddress = miDebuggerServerAddress; this.StopAtEntry = stopAtEntry; this.DebugServerPath = debugServerPath; this.DebugServerArgs = debugServerArgs; this.ServerStarted = serverStarted; this.FilterStdout = filterStdout; this.FilterStderr = filterStderr; this.ServerLaunchTimeout = serverLaunchTimeout; this.CoreDumpPath = coreDumpPath; this.ExternalConsole = externalConsole; this.HardwareBreakpointInfo = hardwareBreakpointInfo; this.SourceFileMap = sourceFileMap; this.PipeTransport = pipeTransport; this.StopAtConnect = stopAtConnect; } #endregion #region Private class /// <summary> /// Custom converter to avoid dependency on System.Runtime.Serialization.Primitives.dll /// </summary> private class LaunchCompleteCommandConverter : JsonConverter { public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if (objectType == typeof(LaunchCompleteCommand?) && reader.TokenType == JsonToken.String) { String value = reader.Value.ToString(); if (value.Equals("exec-continue", StringComparison.Ordinal)) { return MICore.LaunchCompleteCommand.ExecContinue; } if (value.Equals("exec-run", StringComparison.Ordinal)) { return MICore.LaunchCompleteCommand.ExecRun; } if (value.Equals("None", StringComparison.Ordinal)) { return MICore.LaunchCompleteCommand.None; } throw new InvalidLaunchOptionsException(String.Format(CultureInfo.CurrentCulture, MICoreResources.Error_InvalidLaunchCompleteCommandValue, reader.Value)); } Debug.Fail(String.Format(CultureInfo.CurrentCulture, "Unexpected objectType '{0}' passed for launchCompleteCommand serialization.", objectType.ToString())); return null; } public override bool CanConvert(Type objectType) { return objectType == typeof(LaunchCompleteCommand?); } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { throw new NotImplementedException(); } } #endregion } public partial class PipeTransport : PipeTransportOptions { #region Public Properties for Serialization /// <summary> /// When present, this tells the debugger override the PipeTransport's fields if the client's current platform is Windows and the field is defined in this configuration. /// </summary> [JsonProperty("windows", DefaultValueHandling = DefaultValueHandling.Ignore)] public PipeTransportOptions Windows { get; private set; } /// <summary> /// When present, this tells the debugger override the PipeTransport's fields if the client's current platform is OSX and the field is defined in this configuration. /// </summary> [JsonProperty("osx", DefaultValueHandling = DefaultValueHandling.Ignore)] public PipeTransportOptions OSX { get; private set; } /// <summary> /// When present, this tells the debugger override the PipeTransport's fields if the client's current platform is Linux and the field is defined in this configuration. /// </summary> [JsonProperty("linux", DefaultValueHandling = DefaultValueHandling.Ignore)] public PipeTransportOptions Linux { get; private set; } #endregion #region Constructors public PipeTransport() { } public PipeTransport(PipeTransportOptions windows = null, PipeTransportOptions osx = null, PipeTransportOptions linux = null) { this.Windows = windows; this.OSX = osx; this.Linux = linux; } #endregion } public partial class PipeTransportOptions { #region Public Properties for Serialization /// <summary> /// The fully qualified path to the working directory for the pipe program. /// </summary> [JsonProperty("pipeCwd", DefaultValueHandling = DefaultValueHandling.Ignore)] public string PipeCwd { get; set; } /// <summary> /// The fully qualified pipe command to execute. /// </summary> [JsonProperty("pipeProgram", DefaultValueHandling = DefaultValueHandling.Ignore)] public string PipeProgram { get; set; } /// <summary> /// Command line arguments passed to the pipe program to configure the connection. /// </summary> [JsonProperty("pipeArgs", DefaultValueHandling = DefaultValueHandling.Ignore)] public List<string> PipeArgs { get; private set; } /// <summary> /// Command line arguments passed to the pipe program to execute a remote command. /// </summary> [JsonProperty("pipeCmd", DefaultValueHandling = DefaultValueHandling.Ignore)] public List<string> PipeCmd { get; private set; } /// <summary> /// The full path to the debugger on the target machine, for example /usr/bin/gdb. /// </summary> [JsonProperty("debuggerPath", DefaultValueHandling = DefaultValueHandling.Ignore)] public string DebuggerPath { get; set; } /// <summary> /// Environment variables passed to the pipe program. /// </summary> [JsonProperty("pipeEnv", DefaultValueHandling = DefaultValueHandling.Ignore)] public Dictionary<string, string> PipeEnv { get; private set; } /// <summary> /// Should arguments that contain characters that need to be quoted (example: spaces) be quoted? Defaults to 'true'. If set to false, the debugger command will no longer be automatically quoted. /// </summary> [JsonProperty("quoteArgs", DefaultValueHandling = DefaultValueHandling.Ignore)] public bool? QuoteArgs { get; private set; } #endregion #region Constructors public PipeTransportOptions() { this.PipeArgs = new List<string>(); this.PipeEnv = new Dictionary<string, string>(); } public PipeTransportOptions(string pipeCwd = null, string pipeProgram = null, List<string> pipeArgs = null, string debuggerPath = null, Dictionary<string, string> pipeEnv = null, bool? quoteArgs = null) { this.PipeCwd = pipeCwd; this.PipeProgram = pipeProgram; this.PipeArgs = pipeArgs; this.DebuggerPath = debuggerPath; this.PipeEnv = pipeEnv; this.QuoteArgs = quoteArgs; } #endregion } public partial class SetupCommand { #region Public Properties for Serialization /// <summary> /// The debugger command to execute. /// </summary> [JsonProperty("text", DefaultValueHandling = DefaultValueHandling.Ignore)] public string Text { get; set; } /// <summary> /// Optional description for the command. /// </summary> [JsonProperty("description", DefaultValueHandling = DefaultValueHandling.Ignore)] public string Description { get; set; } /// <summary> /// If true, failures from the command should be ignored. Default value is false. /// </summary> [JsonProperty("ignoreFailures", DefaultValueHandling = DefaultValueHandling.Ignore)] public bool? IgnoreFailures { get; set; } #endregion #region Constructors public SetupCommand() { } public SetupCommand(string text = null, string description = null, bool? ignoreFailures = null) { this.Text = text; this.Description = description; this.IgnoreFailures = ignoreFailures; } #endregion } public partial class SourceFileMapOptions { #region Public Properties for Serialization /// <summary> /// The editor's path. /// </summary> [JsonProperty("editorPath", DefaultValueHandling = DefaultValueHandling.Ignore)] public string EditorPath { get; set; } /// <summary> /// Use this source mapping for breakpoint binding? Default is true. /// </summary> [JsonProperty("useForBreakpoints", DefaultValueHandling = DefaultValueHandling.Ignore)] public bool? UseForBreakpoints { get; set; } #endregion #region Constructors public SourceFileMapOptions() { } public SourceFileMapOptions(string editorPath = null, bool? useForBreakpoints = null) { this.EditorPath = editorPath; this.UseForBreakpoints = useForBreakpoints; } #endregion } public static class LaunchOptionHelpers { public static BaseOptions GetLaunchOrAttachOptions(JObject parsedJObject) { BaseOptions baseOptions = null; string requestType = parsedJObject["request"]?.Value<string>(); if (String.IsNullOrWhiteSpace(requestType)) { // If request isn't specified, see if we can determine what it is if (!String.IsNullOrWhiteSpace(parsedJObject["processId"]?.Value<string>())) { requestType = "attach"; } else if (!String.IsNullOrWhiteSpace(parsedJObject["program"]?.Value<string>())) { requestType = "launch"; } else { throw new InvalidLaunchOptionsException(String.Format(CultureInfo.CurrentCulture, MICoreResources.Error_BadRequiredAttribute, "program")); } } switch (requestType) { case "launch": // handle launch case baseOptions = parsedJObject.ToObject<Json.LaunchOptions.LaunchOptions>(); break; case "attach": // handle attach case baseOptions = parsedJObject.ToObject<Json.LaunchOptions.AttachOptions>(); break; default: throw new InvalidLaunchOptionsException(String.Format(CultureInfo.CurrentCulture, MICoreResources.Error_BadRequiredAttribute, "request")); } return baseOptions; } } } <|start_filename|>test/DebuggerTesting/Utilities/PlatformUtilities.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Diagnostics; using System.Reflection; using System.Runtime.InteropServices; namespace DebuggerTesting.Utilities { public static class PlatformUtilities { private enum RuntimePlatform { Unset = 0, Unknown, Windows, MacOSX, Unix, } private static RuntimePlatform _runtimePlatform; private static RuntimePlatform GetRuntimePlatform() { if (_runtimePlatform == RuntimePlatform.Unset) { _runtimePlatform = CalculateRuntimePlatform(); } return _runtimePlatform; } private static RuntimePlatform CalculateRuntimePlatform() { if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { return RuntimePlatform.Windows; } else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { return RuntimePlatform.MacOSX; } else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { return RuntimePlatform.Unix; } return RuntimePlatform.Unknown; } /* * Is this Windows? */ public static bool IsWindows { get { return GetRuntimePlatform() == RuntimePlatform.Windows; } } /* * Is this OS X? */ public static bool IsOSX { get { return GetRuntimePlatform() == RuntimePlatform.MacOSX; } } /* * Is this Linux? */ public static bool IsLinux { get { return GetRuntimePlatform() == RuntimePlatform.Unix; } } public static bool Is64Bit { get { return true; } } // Abstract API call to add an environment variable to a new process public static void SetEnvironmentVariable(this ProcessStartInfo processStartInfo, string key, string value) { processStartInfo.Environment[key] = value; } // Abstract API call to add an environment variable to a new process public static string GetEnvironmentVariable(this ProcessStartInfo processStartInfo, string key) { if (processStartInfo.Environment.ContainsKey(key)) return processStartInfo.Environment[key]; return null; } // Abstract API call to Marshal.SizeOf public static int MarshalSizeOf<T>() { return Marshal.SizeOf<T>(); } } } <|start_filename|>test/Android/BreakPointEnableAndDisable/BreakPointEnableAndDisable/BreakPointEnableAndDisable.NativeActivity/Source1.cpp<|end_filename|> #include "Header1.h" void func1() { int i = 0; int sum = 0; while (i < 5) { sum = sum + i; i++; } return; } void func2() { MyClass myClass; myClass.Func(); return; } void MyClass::Func() { int i = 0; int sum = 0; while (i < 5) { sum = sum + i; i++; } return; } void func() { func1(); func2(); return; } <|start_filename|>src/SSHDebugPS/Utilities/StringExtensionMethods.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Globalization; namespace Microsoft.SSHDebugPS.Utilities { internal static class StringExtensionMethods { public static string FormatInvariantWithArgs(this string format, params object[] args) { return string.Format(CultureInfo.InvariantCulture, format, args); } public static string FormatCurrentCultureWithArgs(this string format, params object[] args) { return string.Format(CultureInfo.CurrentCulture, format, args); } public static string ToInvariant(this FormattableString value) { return FormattableString.Invariant(value); } } } <|start_filename|>test/DebuggerTesting/Settings/PathSettings.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.IO; using System.Reflection; using System.Text; using DebuggerTesting.Utilities; namespace DebuggerTesting.Settings { public static class PathSettings { private static string tempPath; public static string TempPath { get { if (PathSettings.tempPath == null) { PathSettings.tempPath = Path.GetTempPath(); } return PathSettings.tempPath; } } private static string rootPath; private static string RootPath { get { if (PathSettings.rootPath == null) { // Allow root path to be overridden for dev environments PathSettings.rootPath = Environment.GetEnvironmentVariable("TEST_ROOT"); #if !CORECLR if (String.IsNullOrEmpty(PathSettings.rootPath)) { // If not overridden, the root path is one level up from the path containing the test binaries string thisAssemblyFolder = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetPath()); PathSettings.rootPath = Path.GetDirectoryName(thisAssemblyFolder); } #endif } return PathSettings.rootPath; } } private static string testsPath; public static string TestsPath { get { if (PathSettings.testsPath == null) { PathSettings.testsPath = Path.Combine(PathSettings.RootPath, "tests"); #if !CORECLR // If the normal debuggees path doesn't exist, try an alternative one. // This may occur if running the test from VS. if (!Directory.Exists(PathSettings.testsPath)) { string thisAssemblyFolder = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetPath()); if (Directory.Exists(thisAssemblyFolder)) { PathSettings.testsPath = thisAssemblyFolder; } } #endif } return PathSettings.testsPath; } } private static string debuggeesPath; public static string DebuggeesPath { get { if (PathSettings.debuggeesPath == null) { PathSettings.debuggeesPath = Path.Combine(PathSettings.TestsPath, "debuggees"); } return PathSettings.debuggeesPath; } } private static string debugAdaptersPath; public static string DebugAdaptersPath { get { if (PathSettings.debugAdaptersPath == null) { PathSettings.debugAdaptersPath = Path.Combine(PathSettings.RootPath, "extension", "debugAdapters"); } return PathSettings.debugAdaptersPath; } } private static string testConfigurationFilePath; public static string TestConfigurationFilePath { get { if (PathSettings.testConfigurationFilePath == null) { PathSettings.testConfigurationFilePath = Path.Combine(PathSettings.TestsPath, "config.xml"); // If the normal config file path doesn't exist, try an alternative one. // This may occur if running the test from VS. if (!File.Exists(PathSettings.testConfigurationFilePath)) { string alternatePath = Path.Combine(PathSettings.RootPath, "config.xml"); if (File.Exists(alternatePath)) { PathSettings.testConfigurationFilePath = alternatePath; } } } return PathSettings.testConfigurationFilePath; } } public static string GetDebugPathString() { StringBuilder sb = new StringBuilder(); sb.Append("Temp ="); sb.AppendLine(PathSettings.TempPath); sb.Append("Adapters ="); sb.AppendLine(PathSettings.DebugAdaptersPath); sb.Append("Tests ="); sb.AppendLine(PathSettings.TestsPath); sb.Append("Debuggees ="); sb.AppendLine(PathSettings.DebuggeesPath); sb.Append("Config ="); sb.AppendLine(PathSettings.TestConfigurationFilePath); return sb.ToString(); } } } <|start_filename|>test/CppTests/debuggees/kitchensink/src/environment.cpp<|end_filename|> #include "environment.h" #include <cstdlib> Environment::Environment() : Feature("Environment") { } void Environment::CoreRun() { const char* varName1 = "VAR_NAME_1"; this->Log("Getting environment variable: ", varName1); const char* varValue1 = std::getenv(varName1); this->Log("Obtained variable"); } <|start_filename|>src/MIDebugEngine/Engine.Impl/CygwinFileMapper.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Runtime.InteropServices; using Microsoft.Win32.SafeHandles; using MICore; namespace Microsoft.MIDebugEngine { internal class CygwinFilePathMapper { private DebuggedProcess _debuggedProcess; private Dictionary<string, string> _cygwinToWindows; public CygwinFilePathMapper(DebuggedProcess debuggedProcess) { _debuggedProcess = debuggedProcess; _cygwinToWindows = new Dictionary<string, string>(); } /// <summary> /// Maps cygwin paths (/usr/bin) to Windows Paths (C:\User\bin) /// /// We cache these paths because most of the time it comes from callstacks that we need to provide /// source file maps. /// </summary> /// <param name="origCygwinPath">A string representing the cygwin path.</param> /// <returns>A string as a full Windows path</returns> public string MapCygwinToWindows(string origCygwinPath) { if (!(_debuggedProcess.LaunchOptions is LocalLaunchOptions)) { return origCygwinPath; } LocalLaunchOptions localLaunchOptions = (LocalLaunchOptions)_debuggedProcess.LaunchOptions; string cygwinPath = PlatformUtilities.WindowsPathToUnixPath(origCygwinPath); string windowsPath = cygwinPath; lock (_cygwinToWindows) { if (!_cygwinToWindows.TryGetValue(cygwinPath, out windowsPath)) { if (!LaunchCygPathAndReadResult(cygwinPath, localLaunchOptions.MIDebuggerPath, convertToWindowsPath: true, out windowsPath)) { return origCygwinPath; } _cygwinToWindows.Add(cygwinPath, windowsPath); } } return windowsPath; } /// <summary> /// Maps Windows paths (C:\User\bin) to Cygwin Paths (/usr/bin) /// /// Not cached since we only do this for setting the program, symbol, and working dir. /// </summary> /// <param name="origWindowsPath">A string representing the Windows path.</param> /// <returns>A string as a full unix path</returns> public string MapWindowsToCygwin(string origWindowsPath) { if (!(_debuggedProcess.LaunchOptions is LocalLaunchOptions)) { return origWindowsPath; } LocalLaunchOptions localLaunchOptions = (LocalLaunchOptions)_debuggedProcess.LaunchOptions; string windowsPath = PlatformUtilities.UnixPathToWindowsPath(origWindowsPath); if (!LaunchCygPathAndReadResult(windowsPath, localLaunchOptions.MIDebuggerPath, convertToWindowsPath: false, out string cygwinPath)) { return origWindowsPath; } return cygwinPath; } // There is an issue launching Cygwin apps that if a process is launched using a bitness mismatched console, // process launch will fail. To avoid that, launch cygpath with its own console. This requires calling CreateProcess // directly because the creation flags are not exposed in System.Diagnostics.Process. // // Return true if successful. False otherwise. private bool LaunchCygPathAndReadResult(string inputPath, string miDebuggerPath, bool convertToWindowsPath, out string outputPath) { outputPath = ""; if (String.IsNullOrEmpty(miDebuggerPath)) { return false; } string cygpathPath = Path.Combine(Path.GetDirectoryName(miDebuggerPath), "cygpath.exe"); if (!File.Exists(cygpathPath)) { return false; } List<IDisposable> disposableHandles = new List<IDisposable>(); try { // Create the anonymous pipe that will act as stdout for the cygpath process SECURITY_ATTRIBUTES pPipeSec = new SECURITY_ATTRIBUTES(); pPipeSec.bInheritHandle = 1; SafeFileHandle stdoutRead; SafeFileHandle stdoutWrite; if (!CreatePipe(out stdoutRead, out stdoutWrite, ref pPipeSec, 4096)) { Debug.Fail("Unexpected failure CreatePipe in LaunchCygPathAndReadResult"); return false; } SetHandleInformation(stdoutRead, HANDLE_FLAGS.INHERIT, 0); disposableHandles.Add(stdoutRead); disposableHandles.Add(stdoutWrite); const int STARTF_USESTDHANDLES = 0x00000100; const int STARTF_USESHOWWINDOW = 0x00000001; const int SW_HIDE = 0; STARTUPINFO startupInfo = new STARTUPINFO(); startupInfo.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW; startupInfo.hStdOutput = stdoutWrite; startupInfo.wShowWindow = SW_HIDE; startupInfo.cb = Marshal.SizeOf(startupInfo); PROCESS_INFORMATION processInfo = new PROCESS_INFORMATION(); SECURITY_ATTRIBUTES processSecurityAttributes = new SECURITY_ATTRIBUTES(); SECURITY_ATTRIBUTES threadSecurityAttributes = new SECURITY_ATTRIBUTES(); processSecurityAttributes.nLength = Marshal.SizeOf(processSecurityAttributes); threadSecurityAttributes.nLength = Marshal.SizeOf(threadSecurityAttributes); const uint DETACHED_PROCESS = 0x00000008; uint flags = DETACHED_PROCESS; string command = string.Empty; if (convertToWindowsPath) { // -w, --windows print Windows form of NAMEs (C:\WINNT) // ex: "C:\\cygwin64\\bin\\cygpath.exe -w " + inputPath, command = String.Concat(cygpathPath, " -w ", inputPath); } else { // -u, --unix (default) print Unix form of NAMEs (/cygdrive/c/winnt) // ex: "C:\\cygwin64\\bin\\cygpath.exe -u " + inputPath, command = String.Concat(cygpathPath, " -u ", inputPath); } if (!CreateProcess( null, command, ref processSecurityAttributes, ref threadSecurityAttributes, true, flags, IntPtr.Zero, null, ref startupInfo, out processInfo )) { Debug.Fail("Launching cygpath for source mapping failed"); return false; } SafeFileHandle processSH = new SafeFileHandle(processInfo.hProcess, true); SafeFileHandle threadSH = new SafeFileHandle(processInfo.hThread, true); disposableHandles.Add(processSH); disposableHandles.Add(threadSH); const int timeout = 5000; if (WaitForSingleObject(processInfo.hProcess, timeout) != 0) { Debug.Fail("cygpath failed to map source file."); return false; } uint exitCode = 0; if (!GetExitCodeProcess(processInfo.hProcess, out exitCode)) { Debug.Fail("cygpath failed to get exit code from cygpath."); return false; } if (exitCode != 0) { Debug.Fail("cygpath returned error exit code."); return false; } FileStream fs = new FileStream(stdoutRead, FileAccess.Read); StreamReader sr = new StreamReader(fs); outputPath = sr.ReadLine(); } finally { foreach (IDisposable h in disposableHandles) { h.Dispose(); } } return true; } #region pinvoke definitions [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] private struct STARTUPINFO { public Int32 cb; public string lpReserved; public string lpDesktop; public string lpTitle; public Int32 dwX; public Int32 dwY; public Int32 dwXSize; public Int32 dwYSize; public Int32 dwXCountChars; public Int32 dwYCountChars; public Int32 dwFillAttribute; public Int32 dwFlags; public Int16 wShowWindow; public Int16 cbReserved2; public IntPtr lpReserved2; public IntPtr hStdInput; public SafeFileHandle hStdOutput; public IntPtr hStdError; } [StructLayout(LayoutKind.Sequential)] private struct PROCESS_INFORMATION { public IntPtr hProcess; public IntPtr hThread; public int dwProcessId; public int dwThreadId; } [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)] private static extern bool CreateProcess( string lpApplicationName, string lpCommandLine, ref SECURITY_ATTRIBUTES lpProcessAttributes, ref SECURITY_ATTRIBUTES lpThreadAttributes, bool bInheritHandles, uint dwCreationFlags, IntPtr lpEnvironment, string lpCurrentDirectory, [In] ref STARTUPINFO lpStartupInfo, out PROCESS_INFORMATION lpProcessInformation ); [StructLayout(LayoutKind.Sequential)] private struct SECURITY_ATTRIBUTES { public int nLength; private IntPtr _lpSecurityDescriptor; public int bInheritHandle; } [DllImport("kernel32.dll", SetLastError = true, PreserveSig = true)] private static extern UInt32 WaitForSingleObject(IntPtr hHandle, UInt32 dwMilliseconds); [DllImport("kernel32.dll", SetLastError = true, PreserveSig = true)] private static extern bool CreatePipe(out SafeFileHandle hReadPipe, out SafeFileHandle hWritePipe, ref SECURITY_ATTRIBUTES lpPipeAttributes, uint nSize); [DllImport("kernel32.dll", SetLastError = true, PreserveSig = true)] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool GetExitCodeProcess(IntPtr hProcess, out uint lpExitCode); [DllImport("kernel32.dll", SetLastError = true, PreserveSig = true)] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool DuplicateHandle(SafeFileHandle hSourceProcessHandle, SafeFileHandle hSourceHandle, SafeFileHandle hTargetProcessHandle, out SafeFileHandle lpTargetHandle, uint dwDesiredAccess, [MarshalAs(UnmanagedType.Bool)] bool bInheritHandle, uint dwOptions); [Flags] private enum HANDLE_FLAGS : uint { None = 0, INHERIT = 1, PROTECT_FROM_CLOSE = 2 } [DllImport("kernel32.dll", SetLastError = true)] private static extern bool SetHandleInformation(SafeFileHandle hObject, HANDLE_FLAGS dwMask, uint flags); #endregion } } <|start_filename|>src/MIDebugEngine/Engine.Impl/DebuggedModule.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Text; using MICore; namespace Microsoft.MIDebugEngine { public class DebuggedModule { private uint _loadOrder; private const ulong INVALID_ADDRESS = 0xffffffffffffffff; public DebuggedModule(string id, string name, ulong baseAddr, ulong size, bool symbolsLoaded, string symPath, uint loadOrder) { Id = id; Name = name; Sections = new List<Section>(); Sections.Add(new Section(String.Empty, baseAddr, size)); // TODO real module info SymbolsLoaded = symbolsLoaded; SymbolPath = symPath; // symbols in module _loadOrder = loadOrder; } public DebuggedModule(string id, string name, ValueListValue sections, bool symbolsLoaded, uint loadOrder) { Id = id; Name = name; Sections = new List<Section>(); LoadSections(sections); SymbolsLoaded = symbolsLoaded; SymbolPath = name; // symbols in module _loadOrder = loadOrder; } private void LoadSections(ValueListValue sectionList) { if (sectionList == null) { return; } List<Section> sections = new List<Section>(); foreach (var s in sectionList.Content) { string name = s.FindString("name"); ulong addr = s.FindAddr("addr"); uint size = 0; try { size = s.FindUint("size"); } catch (OverflowException) { //TODO: sometimes for iOS, size is being reported as a number larger than uint //TODO: currnetly, this is only superficial information displayed in the UI. //TODO: so just swallow the exception and show zero. //TODO: this may be a bug in the lldb side } if (addr != INVALID_ADDRESS) { sections.Add(new Section(name, addr, size)); } } if (sections.Count > 0) { Sections = sections; } } private class Section { public readonly string Name; public ulong BaseAddress; public ulong Size; public Section(string name, ulong baseAddr, ulong size) { Name = name; BaseAddress = baseAddr; Size = size; } } public bool AddressInModule(ulong address) { return Sections.Find((s) => s.BaseAddress <= address && address < s.BaseAddress + s.Size) != null; } private Section TextSection { get { if (Sections.Count > 1) { Section t = Sections.Find((s) => s.Name == "__TEXT"); if (t != null) { return t; } } return Sections[0]; } } private List<Section> Sections { get; set; } public string Id { get; private set; } public string Name { get; private set; } public ulong BaseAddress { get { return TextSection.BaseAddress; } } public ulong Size { get { return TextSection.Size; } } public bool SymbolsLoaded { get; set; } public string SymbolPath { get; private set; } public uint GetLoadOrder() { return _loadOrder; } public Object Client { get; internal set; } // really AD7Module public bool IgnoreSource { get; internal set; } // filter out source references from this module } } <|start_filename|>src/IOSDebugLauncher/VcRemoteClient.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.DebugEngineHost; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Security; using System.Runtime.ExceptionServices; using System.Text; using System.Threading; using System.Threading.Tasks; namespace IOSDebugLauncher { internal class VcRemoteClient : HttpClient { private IOSLaunchOptions _launchOptions; private VcRemoteClient() : base() { } private VcRemoteClient(HttpMessageHandler handler) : base(handler, true) { } public static VcRemoteClient GetInstance(IOSLaunchOptions options) { VcRemoteClient client = null; string baseAddressFormat = string.Empty; if (options.Secure) { var handler = new RequestAuthHandler(); client = new VcRemoteClient(handler); client.ServerCertificateValidationCallback = handler.ServerCertificateValidationCallback; baseAddressFormat = @"https://{0}:{1}/"; } else { client = new VcRemoteClient(); baseAddressFormat = @"http://{0}:{1}/"; } client.BaseAddress = new Uri(string.Format(CultureInfo.InvariantCulture, baseAddressFormat, options.RemoteMachineName, options.VcRemotePort)); client.Timeout = new TimeSpan(0, 0, 10); //10 second timeout client.Secure = options.Secure; client._launchOptions = options; return client; } public Launcher.RemotePorts StartDebugListener() { string remotePortsJsonString; CallVcRemote(new Uri("debug/setupForDebugging?target=" + _launchOptions.IOSDebugTarget.ToString() + "&deviceUdid=" + _launchOptions.DeviceUdid, UriKind.Relative), LauncherResources.Info_StartingDebugListener, out remotePortsJsonString); try { return JsonConvert.DeserializeObject<Launcher.RemotePorts>(remotePortsJsonString); } catch (JsonException) { Telemetry.SendLaunchError(Telemetry.LaunchFailureCode.BadJson.ToString(), _launchOptions.IOSDebugTarget); throw new LauncherException(LauncherResources.Error_BadJSon); } } public string GetRemoteAppPath() { string appPath = string.Empty; var response = CallVcRemote(new Uri("debug/appRemotePath?package=" + _launchOptions.PackageId + "&deviceUdid=" + _launchOptions.DeviceUdid, UriKind.Relative), LauncherResources.Info_GettingInfo, out appPath); if (string.IsNullOrWhiteSpace(appPath)) { Telemetry.SendLaunchError(Telemetry.LaunchFailureCode.BadPackageId.ToString(), _launchOptions.IOSDebugTarget); Debug.Fail("Invalid return from vcremote for packageId"); throw new InvalidOperationException(); } return appPath; } private HttpResponseMessage CallVcRemote(Uri endpoint, string waitLoopMessage, out string responseBody) { ManualResetEvent doneEvent = new ManualResetEvent(false); CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); var waitLoop = new HostWaitLoop(waitLoopMessage); ExceptionDispatchInfo exceptionDispatchInfo = null; HttpResponseMessage response = null; string content = null; ThreadPool.QueueUserWorkItem(async (object o) => { string failureCode = Telemetry.VcRemoteFailureCode.VcRemoteSucces.ToString(); try { response = await this.GetAsync(endpoint, cancellationTokenSource.Token); response.EnsureSuccessStatusCode(); content = await response.Content.ReadAsStringAsync(); } catch (HttpRequestException) { if (response != null) { if (response.StatusCode == HttpStatusCode.Unauthorized) { exceptionDispatchInfo = ExceptionDispatchInfo.Capture(new LauncherException(LauncherResources.Error_Unauthorized)); failureCode = Telemetry.VcRemoteFailureCode.VcRemoteUnauthorized.ToString(); } else { exceptionDispatchInfo = ExceptionDispatchInfo.Capture(new LauncherException(string.Format(CultureInfo.CurrentCulture, LauncherResources.Error_VcRemoteUnknown, response.StatusCode.ToString()))); failureCode = Telemetry.VcRemoteFailureCode.VcRemoteUnkown.ToString(); } } else { exceptionDispatchInfo = ExceptionDispatchInfo.Capture(new LauncherException(LauncherResources.Error_UnableToReachServer)); failureCode = Telemetry.VcRemoteFailureCode.VcRemoteNoConnection.ToString(); } } catch (TaskCanceledException) { //timeout exceptionDispatchInfo = ExceptionDispatchInfo.Capture(new LauncherException(LauncherResources.Error_UnableToReachServer)); failureCode = Telemetry.VcRemoteFailureCode.VcRemoteNoConnection.ToString(); } catch (Exception e) { exceptionDispatchInfo = ExceptionDispatchInfo.Capture(e); failureCode = e.GetType().FullName; } doneEvent.Set(); Telemetry.SendLaunchError(failureCode, _launchOptions.IOSDebugTarget); }); waitLoop.Wait(doneEvent, cancellationTokenSource); if (exceptionDispatchInfo != null) { exceptionDispatchInfo.Throw(); } if (response == null) { Debug.Fail("Null resposne? Should be impossible."); throw new InvalidOperationException(); } responseBody = content; return response; } public RemoteCertificateValidationCallback ServerCertificateValidationCallback { get; private set; } public bool Secure { get; private set; } } } <|start_filename|>src/SSHDebugPS/WSL/WSLCommandLine.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.SSHDebugPS.Utilities; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using ThreadHelper = Microsoft.VisualStudio.Shell.ThreadHelper; using static Microsoft.VisualStudio.Shell.VsTaskLibraryHelper; using System.Linq; namespace Microsoft.SSHDebugPS.WSL { internal static class WSLCommandLine { static string s_exePath; public static string ExePath { get { if (s_exePath == null) throw new InvalidOperationException(); return s_exePath; } } public static void EnsureInitialized() { if (s_exePath == null) { string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), Environment.Is64BitProcess ? "System32" : "sysnative", "wsl.exe"); if (!File.Exists(path)) { throw new WSLException(StringResources.Error_WSLNotInstalled); } s_exePath = path; } } public static ProcessStartInfo GetExecStartInfo(string distroName, string commandText) { return GetWSLStartInfo(GetExecCommandLineArgs(distroName, commandText), Encoding.UTF8); } public static string GetExecCommandLineArgs(string distroName, string commandText) { return FormattableString.Invariant($"-d {distroName} -- {commandText}"); } public static IEnumerable<string> GetInstalledDistros() { HashSet<string> distributions = new HashSet<string>(StringComparer.OrdinalIgnoreCase); ThreadHelper.JoinableTaskFactory.Run(StringResources.WaitingOp_EnumeratingWSLDistros, async (progress, cancellationToken) => { ProcessStartInfo startInfo = GetWSLStartInfo("-l -v", Encoding.Unicode); ProcessResult processResult = await LocalProcessAsyncRunner.ExecuteProcessAsync(startInfo, cancellationToken); if (processResult.ExitCode != 0) { const int NoDistrosExitCode = -1; if (processResult.ExitCode == NoDistrosExitCode) { // Older versions of wsl don't like the '-v' and will also fail with -1 for that reason. Check if this is why we are seeing the failure ProcessResult retryResult = await LocalProcessAsyncRunner.ExecuteProcessAsync(GetWSLStartInfo("-l", Encoding.Unicode), cancellationToken); // If the exit code is still NoDistros then they really don't have any distros if (retryResult.ExitCode == NoDistrosExitCode) { throw new WSLException(StringResources.Error_WSLNoDistros); } // For any other code, they don't have WSL 2 installed. else { throw new WSLException(StringResources.WSL_V2Required); } } else { if (processResult.StdErr.Count > 0) { VsOutputWindowWrapper.WriteLine(StringResources.Error_WSLExecErrorOut_Args2.FormatCurrentCultureWithArgs(startInfo.FileName, startInfo.Arguments)); foreach (string line in processResult.StdErr) { VsOutputWindowWrapper.WriteLine("\t" + line); } } throw new WSLException(StringResources.Error_WSLEnumDistrosFailed_Args1.FormatCurrentCultureWithArgs(processResult.ExitCode)); } } // Parse the installed distributions /* Ouput looks like: NAME STATE VERSION * Ubuntu Stopped 2 docker-desktop-data Running 2 docker-desktop Running 2 */ Regex distributionRegex = new Regex(@"^\*?\s+(?<name>\S+)\s"); foreach (string line in processResult.StdOut.Skip(1)) { Match match = distributionRegex.Match(line); if (match.Success) { string distroName = match.Groups["name"].Value; if (distroName.StartsWith("docker-desktop", StringComparison.OrdinalIgnoreCase)) { continue; } distributions.Add(distroName); } } }); if (distributions.Count == 0) { throw new WSLException(StringResources.Error_WSLNoDistros); } return distributions; } private static ProcessStartInfo GetWSLStartInfo(string args, Encoding encoding) { return new ProcessStartInfo(s_exePath, args) { UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true, CreateNoWindow = true, StandardOutputEncoding = encoding, StandardErrorEncoding = encoding }; } } } <|start_filename|>test/Android/Stepping/Stepping/Stepping.NativeActivity/Source2.cpp<|end_filename|> #include "Header2.h" void func3() { func4(); return; } void func4() { int x = 10; int y = 11; return; } <|start_filename|>test/DebuggerTesting/OpenDebug/Commands/ThreadsCommand.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using DebuggerTesting.OpenDebug.Commands.Responses; namespace DebuggerTesting.OpenDebug.Commands { public class ThreadsCommand : CommandWithResponse<object, ThreadsResponseValue> { public ThreadsCommand() : base("threads") { } } } <|start_filename|>src/JDbg/Jdwp.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Net.Sockets; using System.Text; using System.Threading.Tasks; using System.Globalization; namespace JDbg { /// <summary> /// Implemtation of a JDWP infrastructure. Facilitates the sending and receiving of jdwp packets on an underling tranposrt. /// /// NOTE: Current transport is hardcoded to TCP. This could be interface'd in the future to support other transports. /// </summary> internal class Jdwp { private TcpTransport _transport; private JdwpCommand.IDSizes _IDSizes; private Jdwp(string hostname, int port) { _transport = new TcpTransport(hostname, port, OnPacketReceived, OnDisconnect); } /// <summary> /// Attach to hostname:port for jdwp communication. /// </summary> /// <param name="hostname"></param> /// <param name="port"></param> /// <returns></returns> public static Jdwp Attach(string hostname, int port) { Jdwp jdbg = new Jdwp(hostname, port); return jdbg; } private void OnPacketReceived(byte[] packet) { Debug.Assert(packet.Length >= JdwpCommand.HEADER_SIZE); if (packet.Length < JdwpCommand.HEADER_SIZE) { throw new ArgumentException("buffer too small to be a full packet", nameof(packet)); } //byte 8 of the packet header tells us whether this is a reply or not if ((packet[8] & 0x80) > 0) { OnReplyPacketReceived(packet); } else { OnCommandPacketReceived(packet); } } private void OnDisconnect(/*OPTIONAL*/ SocketException socketException) { // This handles disconnects if, for example, the app exits // If we have any waiting operations, we want to abort them List<WaitingOperationDescriptor> operationsToAbort = null; lock (_waitingOperations) { operationsToAbort = new List<WaitingOperationDescriptor>(_waitingOperations.Values); _waitingOperations.Clear(); } foreach (var operation in operationsToAbort) { if (socketException == null) { operation.Abort(); } else { operation.OnSocketError(socketException); } } // Otherwise just drop the connection } private void OnReplyPacketReceived(byte[] packetBytes) { ReplyPacketParser packet = new ReplyPacketParser(packetBytes, _IDSizes); uint id = packet.Id; WaitingOperationDescriptor waitingOperation = null; lock (_waitingOperations) { if (_waitingOperations.TryGetValue(id, out waitingOperation)) { _waitingOperations.Remove(id); } } if (waitingOperation != null) { try { waitingOperation.OnComplete(packet); } catch (JdwpException e) { waitingOperation.OnJdwpException(e); } } else { Debug.Fail("How did we get a reply packet that we don't have a waiting operation for?"); } } private void OnCommandPacketReceived(byte[] packet) { //TODO This is where we would handle commands sent from the VM to the debugger. //The most common case of the VM sending command packets to the debugger is for Events. } /// <summary> /// Send a command packet to the VM /// </summary> /// <param name="command"></param> /// <returns></returns> public Task SendCommandAsync(JdwpCommand command) { var waitingOperation = new WaitingOperationDescriptor(command); lock (_waitingOperations) { _waitingOperations.Add(command.PacketId, waitingOperation); } SendToTransport(command); return waitingOperation.Task; } private class WaitingOperationDescriptor { private readonly JdwpCommand _command; private readonly TaskCompletionSource<object> _completionSource = new TaskCompletionSource<object>(); public WaitingOperationDescriptor(JdwpCommand command) { _command = command; } internal void OnComplete(ReplyPacketParser replyPacket) { if (replyPacket.Succeeded) { _command.DecodeSuccessReply(replyPacket); _completionSource.SetResult(null); } else { _command.DecodeFailureReply(replyPacket); _completionSource.SetException(new JdwpException(ErrorCode.CommandFailure, string.Format(CultureInfo.CurrentCulture, "JDWP Error. Id: {0} Error Code: {1}", replyPacket.Id, replyPacket.ErrorCode))); } } public Task<object> Task { get { return _completionSource.Task; } } internal void Abort() { _completionSource.TrySetException(new OperationCanceledException()); } internal void OnSocketError(SocketException socketException) { _completionSource.TrySetException(new JdwpException(ErrorCode.SocketError, "Socket error reading the result", socketException)); } internal void OnJdwpException(JdwpException jdwpException) { _completionSource.SetException(jdwpException); } } private readonly Dictionary<uint, WaitingOperationDescriptor> _waitingOperations = new Dictionary<uint, WaitingOperationDescriptor>(); private void SendToTransport(JdwpCommand command) { _transport.Send(command.GetPacketBytes()); } public void Close() { if (_transport != null) { _transport.Close(); } //Abort remaining WaitingOperations List<WaitingOperationDescriptor> operationsToAbort = null; lock (_waitingOperations) { operationsToAbort = new List<WaitingOperationDescriptor>(_waitingOperations.Values); _waitingOperations.Clear(); } foreach (var operation in operationsToAbort) { operation.Abort(); } } public void SetIDSizes(JdwpCommand.IDSizes idSizes) { _IDSizes = idSizes; } } } <|start_filename|>src/MIDebugEngine/Natvis.Impl/NatvisXsdTypes.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Xml.Serialization; // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.0 // // 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.0.30319.33440. // namespace Microsoft.MIDebugEngine.Natvis { /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.33440")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://schemas.microsoft.com/vstudio/debugger/natvis/2010")] [System.Xml.Serialization.XmlRootAttribute(Namespace = "http://schemas.microsoft.com/vstudio/debugger/natvis/2010", IsNullable = false)] public partial class AutoVisualizer { private VersionType _versionField; private LocalizedStringType[] _localizedStringsField; private UIVisualizerType[] _uIVisualizerField; private object[] _itemsField; /// <remarks/> public VersionType Version { get { return _versionField; } set { _versionField = value; } } /// <remarks/> [System.Xml.Serialization.XmlArrayItemAttribute("LocalizedString", IsNullable = false)] public LocalizedStringType[] LocalizedStrings { get { return _localizedStringsField; } set { _localizedStringsField = value; } } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute("UIVisualizer")] public UIVisualizerType[] UIVisualizer { get { return _uIVisualizerField; } set { _uIVisualizerField = value; } } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute("HResult", typeof(HResultType))] [System.Xml.Serialization.XmlElementAttribute("Type", typeof(VisualizerType))] [System.Xml.Serialization.XmlElementAttribute("Alias", typeof(AliasType))] public object[] Items { get { return _itemsField; } set { _itemsField = value; } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.33440")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/vstudio/debugger/natvis/2010")] public partial class VersionType { private string _nameField; private string _minField; private string _maxField; /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute()] public string Name { get { return _nameField; } set { _nameField = value; } } /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute()] public string Min { get { return _minField; } set { _minField = value; } } /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute()] public string Max { get { return _maxField; } set { _maxField = value; } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.33440")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/vstudio/debugger/natvis/2010")] public partial class AlternativeHResultType { private string _nameField; /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute()] public string Name { get { return _nameField; } set { _nameField = value; } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.33440")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/vstudio/debugger/natvis/2010")] public partial class HResultType { private AlternativeHResultType[] _alternativeHResultField; private string _hRValueField; private string _hRDescriptionField; private string _nameField; /// <remarks/> [System.Xml.Serialization.XmlElementAttribute("AlternativeHResult")] public AlternativeHResultType[] AlternativeHResult { get { return _alternativeHResultField; } set { _alternativeHResultField = value; } } /// <remarks/> public string HRValue { get { return _hRValueField; } set { _hRValueField = value; } } /// <remarks/> public string HRDescription { get { return _hRDescriptionField; } set { _hRDescriptionField = value; } } /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute()] public string Name { get { return _nameField; } set { _nameField = value; } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.33440")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/vstudio/debugger/natvis/2010")] public partial class UIVisualizerItemType { private string _serviceIdField; private int _idField; private string _valueField; /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute()] public string ServiceId { get { return _serviceIdField; } set { _serviceIdField = value; } } /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute()] public int Id { get { return _idField; } set { _idField = value; } } /// <remarks/> [System.Xml.Serialization.XmlTextAttribute()] public string Value { get { return _valueField; } set { _valueField = value; } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.33440")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.Xml.Serialization.XmlTypeAttribute(TypeName = "ExpandType", Namespace = "http://schemas.microsoft.com/vstudio/debugger/natvis/2010")] public partial class ExpandType1 { private object[] _itemsField; /// <remarks/> [System.Xml.Serialization.XmlElementAttribute("ArrayItems", typeof(ArrayItemsType))] [System.Xml.Serialization.XmlElementAttribute("CustomListItems", typeof(CustomListItemsType))] [System.Xml.Serialization.XmlElementAttribute("ExpandedItem", typeof(ExpandedItemType))] [System.Xml.Serialization.XmlElementAttribute("IndexListItems", typeof(IndexListItemsType))] [System.Xml.Serialization.XmlElementAttribute("Item", typeof(ItemType))] [System.Xml.Serialization.XmlElementAttribute("LinkedListItems", typeof(LinkedListItemsType))] [System.Xml.Serialization.XmlElementAttribute("Synthetic", typeof(SyntheticItemType))] [System.Xml.Serialization.XmlElementAttribute("TreeItems", typeof(TreeItemsType))] public object[] Items { get { return _itemsField; } set { _itemsField = value; } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.33440")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/vstudio/debugger/natvis/2010")] public partial class ArrayItemsType { private ArrayDirectionType _directionField; private bool _directionFieldSpecified; private string _rankField; private string _sizeField; private string _lowerBoundField; private ValuePointerType[] _valuePointerField; private bool _optionalField; private bool _optionalFieldSpecified; private string _conditionField; /// <remarks/> public ArrayDirectionType Direction { get { return _directionField; } set { _directionField = value; } } /// <remarks/> [System.Xml.Serialization.XmlIgnoreAttribute()] public bool DirectionSpecified { get { return _directionFieldSpecified; } set { _directionFieldSpecified = value; } } /// <remarks/> public string Rank { get { return _rankField; } set { _rankField = value; } } /// <remarks/> public string Size { get { return _sizeField; } set { _sizeField = value; } } /// <remarks/> public string LowerBound { get { return _lowerBoundField; } set { _lowerBoundField = value; } } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute("ValuePointer")] public ValuePointerType[] ValuePointer { get { return _valuePointerField; } set { _valuePointerField = value; } } /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute()] public bool Optional { get { return _optionalField; } set { _optionalField = value; } } /// <remarks/> [System.Xml.Serialization.XmlIgnoreAttribute()] public bool OptionalSpecified { get { return _optionalFieldSpecified; } set { _optionalFieldSpecified = value; } } /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute()] public string Condition { get { return _conditionField; } set { _conditionField = value; } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.33440")] [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/vstudio/debugger/natvis/2010")] public enum ArrayDirectionType { /// <remarks/> Forward, /// <remarks/> Backward, } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.33440")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/vstudio/debugger/natvis/2010")] public partial class ValuePointerType { private string _conditionField; private string _valueField; /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute()] public string Condition { get { return _conditionField; } set { _conditionField = value; } } /// <remarks/> [System.Xml.Serialization.XmlTextAttribute()] public string Value { get { return _valueField; } set { _valueField = value; } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.33440")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/vstudio/debugger/natvis/2010")] public partial class CustomListItemsType { private VariableType[] _itemsField; private CustomListSizeType[] _items1Field; private SkipType _itemField; private bool _optionalField; private bool _optionalFieldSpecified; private string _conditionField; private uint _maxItemsPerViewField; private bool _maxItemsPerViewFieldSpecified; /// <remarks/> [System.Xml.Serialization.XmlElementAttribute("Variable")] public VariableType[] Items { get { return _itemsField; } set { _itemsField = value; } } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute("Size")] public CustomListSizeType[] Items1 { get { return _items1Field; } set { _items1Field = value; } } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute("Skip")] public SkipType Item { get { return _itemField; } set { _itemField = value; } } /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute()] public bool Optional { get { return _optionalField; } set { _optionalField = value; } } /// <remarks/> [System.Xml.Serialization.XmlIgnoreAttribute()] public bool OptionalSpecified { get { return _optionalFieldSpecified; } set { _optionalFieldSpecified = value; } } /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute()] public string Condition { get { return _conditionField; } set { _conditionField = value; } } /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute()] public uint MaxItemsPerView { get { return _maxItemsPerViewField; } set { _maxItemsPerViewField = value; } } /// <remarks/> [System.Xml.Serialization.XmlIgnoreAttribute()] public bool MaxItemsPerViewSpecified { get { return _maxItemsPerViewFieldSpecified; } set { _maxItemsPerViewFieldSpecified = value; } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.33440")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/vstudio/debugger/natvis/2010")] public partial class VariableType { private string _nameField; private string _initialValueField; /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute()] public string Name { get { return _nameField; } set { _nameField = value; } } /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute()] public string InitialValue { get { return _initialValueField; } set { _initialValueField = value; } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.33440")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/vstudio/debugger/natvis/2010")] public partial class CustomListSizeType { private string _conditionField; private string _valueField; /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute()] public string Condition { get { return _conditionField; } set { _conditionField = value; } } /// <remarks/> [System.Xml.Serialization.XmlTextAttribute()] public string Value { get { return _valueField; } set { _valueField = value; } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.33440")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/vstudio/debugger/natvis/2010")] public partial class SkipType { private string _valueField; /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute()] public string Value { get { return _valueField; } set { _valueField = value; } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.33440")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/vstudio/debugger/natvis/2010")] public partial class ExpandedItemType { private bool _optionalField; private bool _optionalFieldSpecified; private string _conditionField; private string _valueField; /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute()] public bool Optional { get { return _optionalField; } set { _optionalField = value; } } /// <remarks/> [System.Xml.Serialization.XmlIgnoreAttribute()] public bool OptionalSpecified { get { return _optionalFieldSpecified; } set { _optionalFieldSpecified = value; } } /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute()] public string Condition { get { return _conditionField; } set { _conditionField = value; } } /// <remarks/> [System.Xml.Serialization.XmlTextAttribute()] public string Value { get { return _valueField; } set { _valueField = value; } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.33440")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/vstudio/debugger/natvis/2010")] public partial class IndexListItemsType { private IndexNodeType[] _sizeField; private IndexNodeType[] _valueNodeField; private bool _optionalField; private bool _optionalFieldSpecified; private string _conditionField; /// <remarks/> [System.Xml.Serialization.XmlElementAttribute("Size")] public IndexNodeType[] Size { get { return _sizeField; } set { _sizeField = value; } } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute("ValueNode")] public IndexNodeType[] ValueNode { get { return _valueNodeField; } set { _valueNodeField = value; } } /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute()] public bool Optional { get { return _optionalField; } set { _optionalField = value; } } /// <remarks/> [System.Xml.Serialization.XmlIgnoreAttribute()] public bool OptionalSpecified { get { return _optionalFieldSpecified; } set { _optionalFieldSpecified = value; } } /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute()] public string Condition { get { return _conditionField; } set { _conditionField = value; } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.33440")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/vstudio/debugger/natvis/2010")] public partial class IndexNodeType { private string _conditionField; private string _valueField; /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute()] public string Condition { get { return _conditionField; } set { _conditionField = value; } } /// <remarks/> [System.Xml.Serialization.XmlTextAttribute()] public string Value { get { return _valueField; } set { _valueField = value; } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.33440")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/vstudio/debugger/natvis/2010")] public partial class ItemType { private string _nameField; private bool _optionalField; private bool _optionalFieldSpecified; private string _conditionField; private string _valueField; /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute()] public string Name { get { return _nameField; } set { _nameField = value; } } /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute()] public bool Optional { get { return _optionalField; } set { _optionalField = value; } } /// <remarks/> [System.Xml.Serialization.XmlIgnoreAttribute()] public bool OptionalSpecified { get { return _optionalFieldSpecified; } set { _optionalFieldSpecified = value; } } /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute()] public string Condition { get { return _conditionField; } set { _conditionField = value; } } /// <remarks/> [System.Xml.Serialization.XmlTextAttribute()] public string Value { get { return _valueField; } set { _valueField = value; } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.33440")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/vstudio/debugger/natvis/2010")] public partial class LinkedListItemsType { private string _sizeField; private string _headPointerField; private string _nextPointerField; private string _valueNodeField; private bool _optionalField; private bool _optionalFieldSpecified; private string _conditionField; private bool _noValueHeadPointer; /// <remarks/> public string Size { get { return _sizeField; } set { _sizeField = value; } } /// <remarks/> public string HeadPointer { get { return _headPointerField; } set { _headPointerField = value; } } /// <remarks/> public string NextPointer { get { return _nextPointerField; } set { _nextPointerField = value; } } /// <remarks/> public string ValueNode { get { return _valueNodeField; } set { _valueNodeField = value; } } public bool NoValueHeadPointer { get { return _noValueHeadPointer; } set { _noValueHeadPointer = value; } } /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute()] public bool Optional { get { return _optionalField; } set { _optionalField = value; } } /// <remarks/> [System.Xml.Serialization.XmlIgnoreAttribute()] public bool OptionalSpecified { get { return _optionalFieldSpecified; } set { _optionalFieldSpecified = value; } } /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute()] public string Condition { get { return _conditionField; } set { _conditionField = value; } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.33440")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/vstudio/debugger/natvis/2010")] public partial class SyntheticItemType { private CustomVisualizerType[] _customVisualizerField; private DisplayStringType[] _displayStringField; private StringViewType[] _stringViewField; private object[] _expandField; private string _nameField; private string _expressionField; private bool _optionalField; private bool _optionalFieldSpecified; private string _conditionField; /// <remarks/> [System.Xml.Serialization.XmlElementAttribute("CustomVisualizer")] public CustomVisualizerType[] CustomVisualizer { get { return _customVisualizerField; } set { _customVisualizerField = value; } } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute("DisplayString")] public DisplayStringType[] DisplayString { get { return _displayStringField; } set { _displayStringField = value; } } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute("StringView")] public StringViewType[] StringView { get { return _stringViewField; } set { _stringViewField = value; } } /// <remarks/> [System.Xml.Serialization.XmlArrayItemAttribute("ArrayItems", typeof(ArrayItemsType), IsNullable = false)] [System.Xml.Serialization.XmlArrayItemAttribute("CustomListItems", typeof(CustomListItemsType), IsNullable = false)] [System.Xml.Serialization.XmlArrayItemAttribute("ExpandedItem", typeof(ExpandedItemType), IsNullable = false)] [System.Xml.Serialization.XmlArrayItemAttribute("IndexListItems", typeof(IndexListItemsType), IsNullable = false)] [System.Xml.Serialization.XmlArrayItemAttribute("Item", typeof(ItemType), IsNullable = false)] [System.Xml.Serialization.XmlArrayItemAttribute("LinkedListItems", typeof(LinkedListItemsType), IsNullable = false)] [System.Xml.Serialization.XmlArrayItemAttribute("Synthetic", typeof(SyntheticItemType), IsNullable = false)] [System.Xml.Serialization.XmlArrayItemAttribute("TreeItems", typeof(TreeItemsType), IsNullable = false)] public object[] Expand { get { return _expandField; } set { _expandField = value; } } /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute()] public string Name { get { return _nameField; } set { _nameField = value; } } /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute()] public string Expression { get { return _expressionField; } set { _expressionField = value; } } /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute()] public bool Optional { get { return _optionalField; } set { _optionalField = value; } } /// <remarks/> [System.Xml.Serialization.XmlIgnoreAttribute()] public bool OptionalSpecified { get { return _optionalFieldSpecified; } set { _optionalFieldSpecified = value; } } /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute()] public string Condition { get { return _conditionField; } set { _conditionField = value; } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.33440")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/vstudio/debugger/natvis/2010")] public partial class CustomVisualizerType { private string _visualizerIdField; private bool _optionalField; private bool _optionalFieldSpecified; private string _conditionField; /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute()] public string VisualizerId { get { return _visualizerIdField; } set { _visualizerIdField = value; } } /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute()] public bool Optional { get { return _optionalField; } set { _optionalField = value; } } /// <remarks/> [System.Xml.Serialization.XmlIgnoreAttribute()] public bool OptionalSpecified { get { return _optionalFieldSpecified; } set { _optionalFieldSpecified = value; } } /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute()] public string Condition { get { return _conditionField; } set { _conditionField = value; } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.33440")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/vstudio/debugger/natvis/2010")] public partial class DisplayStringType { private bool _optionalField; private bool _optionalFieldSpecified; private string _conditionField; private string _legacyAddinField; private string _exportField; private string _valueField; /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute()] public bool Optional { get { return _optionalField; } set { _optionalField = value; } } /// <remarks/> [System.Xml.Serialization.XmlIgnoreAttribute()] public bool OptionalSpecified { get { return _optionalFieldSpecified; } set { _optionalFieldSpecified = value; } } /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute()] public string Condition { get { return _conditionField; } set { _conditionField = value; } } /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute()] public string LegacyAddin { get { return _legacyAddinField; } set { _legacyAddinField = value; } } /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute()] public string Export { get { return _exportField; } set { _exportField = value; } } /// <remarks/> [System.Xml.Serialization.XmlTextAttribute()] public string Value { get { return _valueField; } set { _valueField = value; } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.33440")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/vstudio/debugger/natvis/2010")] public partial class StringViewType { private bool _optionalField; private bool _optionalFieldSpecified; private string _conditionField; private string _valueField; /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute()] public bool Optional { get { return _optionalField; } set { _optionalField = value; } } /// <remarks/> [System.Xml.Serialization.XmlIgnoreAttribute()] public bool OptionalSpecified { get { return _optionalFieldSpecified; } set { _optionalFieldSpecified = value; } } /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute()] public string Condition { get { return _conditionField; } set { _conditionField = value; } } /// <remarks/> [System.Xml.Serialization.XmlTextAttribute()] public string Value { get { return _valueField; } set { _valueField = value; } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.33440")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/vstudio/debugger/natvis/2010")] public partial class TreeItemsType { private string _sizeField; private string _headPointerField; private string _leftPointerField; private string _rightPointerField; private IndexNodeType _valueNodeField; private bool _optionalField; private bool _optionalFieldSpecified; private string _conditionField; /// <remarks/> public string Size { get { return _sizeField; } set { _sizeField = value; } } /// <remarks/> public string HeadPointer { get { return _headPointerField; } set { _headPointerField = value; } } /// <remarks/> public string LeftPointer { get { return _leftPointerField; } set { _leftPointerField = value; } } /// <remarks/> public string RightPointer { get { return _rightPointerField; } set { _rightPointerField = value; } } /// <remarks/> public IndexNodeType ValueNode { get { return _valueNodeField; } set { _valueNodeField = value; } } /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute()] public bool Optional { get { return _optionalField; } set { _optionalField = value; } } /// <remarks/> [System.Xml.Serialization.XmlIgnoreAttribute()] public bool OptionalSpecified { get { return _optionalFieldSpecified; } set { _optionalFieldSpecified = value; } } /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute()] public string Condition { get { return _conditionField; } set { _conditionField = value; } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.33440")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/vstudio/debugger/natvis/2010")] public partial class AlternativeTypeType { private string _nameField; private int _priorityField; private bool _priorityFieldSpecified; private bool _inheritableField; private bool _inheritableFieldSpecified; /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute()] public string Name { get { return _nameField; } set { _nameField = value; } } /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute()] public int Priority { get { return _priorityField; } set { _priorityField = value; } } /// <remarks/> [System.Xml.Serialization.XmlIgnoreAttribute()] public bool PrioritySpecified { get { return _priorityFieldSpecified; } set { _priorityFieldSpecified = value; } } /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute()] public bool Inheritable { get { return _inheritableField; } set { _inheritableField = value; } } /// <remarks/> [System.Xml.Serialization.XmlIgnoreAttribute()] public bool InheritableSpecified { get { return _inheritableFieldSpecified; } set { _inheritableFieldSpecified = value; } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.33440")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/vstudio/debugger/natvis/2010")] public partial class VisualizerType { private AlternativeTypeType[] _alternativeTypeField; private VersionType _versionField; private CustomVisualizerType[] _customVisualizerField; private object[] _itemsField; private string _nameField; private string _includeViewField; private string _excludeViewField; private int _priorityField; private bool _priorityFieldSpecified; private bool _inheritableField; private bool _inheritableFieldSpecified; /// <remarks/> [System.Xml.Serialization.XmlElementAttribute("AlternativeType")] public AlternativeTypeType[] AlternativeType { get { return _alternativeTypeField; } set { _alternativeTypeField = value; } } /// <remarks/> public VersionType Version { get { return _versionField; } set { _versionField = value; } } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute("CustomVisualizer")] public CustomVisualizerType[] CustomVisualizer { get { return _customVisualizerField; } set { _customVisualizerField = value; } } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute("DisplayString", typeof(DisplayStringType))] [System.Xml.Serialization.XmlElementAttribute("Expand", typeof(ExpandType1))] [System.Xml.Serialization.XmlElementAttribute("StringView", typeof(StringViewType))] [System.Xml.Serialization.XmlElementAttribute("UIVisualizer", typeof(UIVisualizerItemType))] public object[] Items { get { return _itemsField; } set { _itemsField = value; } } /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute()] public string Name { get { return _nameField; } set { _nameField = value; } } /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute()] public string IncludeView { get { return _includeViewField; } set { _includeViewField = value; } } /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute()] public string ExcludeView { get { return _excludeViewField; } set { _excludeViewField = value; } } /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute()] public int Priority { get { return _priorityField; } set { _priorityField = value; } } /// <remarks/> [System.Xml.Serialization.XmlIgnoreAttribute()] public bool PrioritySpecified { get { return _priorityFieldSpecified; } set { _priorityFieldSpecified = value; } } /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute()] public bool Inheritable { get { return _inheritableField; } set { _inheritableField = value; } } /// <remarks/> [System.Xml.Serialization.XmlIgnoreAttribute()] public bool InheritableSpecified { get { return _inheritableFieldSpecified; } set { _inheritableFieldSpecified = value; } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.33440")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/vstudio/debugger/natvis/2010")] public partial class UIVisualizerType { private string _serviceIdField; private int _idField; private string _menuNameField; private string _descriptionField; private string _valueField; /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute()] public string ServiceId { get { return _serviceIdField; } set { _serviceIdField = value; } } /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute()] public int Id { get { return _idField; } set { _idField = value; } } /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute()] public string MenuName { get { return _menuNameField; } set { _menuNameField = value; } } /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute()] public string Description { get { return _descriptionField; } set { _descriptionField = value; } } /// <remarks/> [System.Xml.Serialization.XmlTextAttribute()] public string Value { get { return _valueField; } set { _valueField = value; } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.33440")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/vstudio/debugger/natvis/2010")] public partial class LocalizedStringType { private uint _idField; private string _valueField; /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute()] public uint Id { get { return _idField; } set { _idField = value; } } /// <remarks/> [System.Xml.Serialization.XmlTextAttribute()] public string Value { get { return _valueField; } set { _valueField = value; } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.33440")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/vstudio/debugger/natvis/2010")] public partial class AliasType { private string _valueField; private string _nameField; /// <remarks/> public string Value { get { return _valueField; } set { _valueField = value; } } /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute()] public string Name { get { return _nameField; } set { _nameField = value; } } } } <|start_filename|>test/Android/FunctionBreakPoints/FunctionBreakPoints/FunctionBreakPoints.NativeActivity/Source1.cpp<|end_filename|> #include "Header1.h" int MyClass :: Func() { int i = 1; int sum = 0; for (; i < 10; i++) { sum = sum + i; } return sum; } int Func1() { int i = 1; int sum = 0; for (; i < 10; i++) { sum = sum + i; } return sum; } void Func2() { int x = 0; return; } void Func() { Func1(); MyClass myClass; myClass.Func(); Func2(); return; } <|start_filename|>test/CppTests/Tests/SourceMappingTests.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Globalization; using System.IO; using DebuggerTesting; using DebuggerTesting.Compilation; using DebuggerTesting.OpenDebug; using DebuggerTesting.OpenDebug.Commands; using DebuggerTesting.OpenDebug.CrossPlatCpp; using DebuggerTesting.OpenDebug.Events; using DebuggerTesting.OpenDebug.Extensions; using DebuggerTesting.Ordering; using DebuggerTesting.Utilities; using Xunit; using Xunit.Abstractions; namespace CppTests.Tests { [TestCaseOrderer(DependencyTestOrderer.TypeName, DependencyTestOrderer.AssemblyName)] public class SourceMappingTests : TestBase { #region Constructor public SourceMappingTests(ITestOutputHelper outputHelper) : base(outputHelper) { } #endregion #region SourceMappingHelper private static class SourceMappingHelper { public const string Main = "main.cpp"; public const string Writer = "writer.cpp"; public const string WriterFolder = "writer"; public const string Manager = "manager.cpp"; public const string ManagerFolder = "manager"; private const string Name = "sourcemap"; private const string OutputName = "mapping"; public static IDebuggee OpenAndCompile(ILoggingComponent logger, ICompilerSettings settings, int moniker) { return DebuggeeHelper.OpenAndCompile(logger, settings, moniker, SourceMappingHelper.Name, SourceMappingHelper.OutputName, SourceMappingHelper.AddSourceFiles); } public static IDebuggee Open(ILoggingComponent logger, ICompilerSettings settings, int moniker) { return DebuggeeHelper.Open(logger, settings, moniker, SourceMappingHelper.Name, SourceMappingHelper.OutputName); } private static void AddSourceFiles(IDebuggee debuggee) { debuggee.AddSourceFiles( SourceMappingHelper.Main, Path.Combine(SourceMappingHelper.WriterFolder, SourceMappingHelper.Writer), Path.Combine(SourceMappingHelper.ManagerFolder, SourceMappingHelper.Manager)); } } #endregion private static void ValidateMappingToFrame(string expectedFileName, string expectedFilePath, IFrameInspector frame, StringComparison comparison) { Assert.True(frame.SourceName.Equals(expectedFileName, comparison), string.Format(CultureInfo.InvariantCulture, "Frame File name. Expected: {0} Actual: {1}", expectedFileName, frame.SourceName)); Assert.True(frame.SourcePath.Equals(expectedFilePath, comparison), string.Format(CultureInfo.InvariantCulture, "Frame full path. Expected: {0} Actual: {1}", expectedFilePath, frame.SourcePath)); } private string EnsureDriveLetterLowercase(string path) { if (path.Length > 2 && path[1] == ':') { path = String.Format(CultureInfo.CurrentUICulture, "{0}{1}", Char.ToLowerInvariant(path[0]), path.Substring(1)); } return path; } [Theory] [RequiresTestSettings] public void CompileSourceMapForSourceMapping(ITestSettings settings) { this.TestPurpose("Compiles source map debuggee for source mapping."); this.WriteSettings(settings); IDebuggee debuggee = SourceMappingHelper.OpenAndCompile(this, settings.CompilerSettings, DebuggeeMonikers.SourceMapping.Default); } [Theory] [DependsOnTest(nameof(CompileSourceMapForSourceMapping))] [RequiresTestSettings] public void MapSpecificFile(ITestSettings settings) { this.TestPurpose("Validate Specific File Mapping."); this.WriteSettings(settings); IDebuggee debuggee = SourceMappingHelper.Open(this, settings.CompilerSettings, DebuggeeMonikers.SourceMapping.Default); // VsDbg is case insensitive on Windows so sometimes stackframe file names might all be lowercase StringComparison comparison = settings.DebuggerSettings.DebuggerType == SupportedDebugger.VsDbg ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; using (IDebuggerRunner runner = CreateDebugAdapterRunner(settings)) { this.Comment("Configure"); LaunchCommand launch = new LaunchCommand(settings.DebuggerSettings, debuggee.OutputPath, false); launch.Args.externalConsole = false; this.Comment("Setting up Source File Mappings"); Dictionary<string, string> sourceMappings = new Dictionary<string, string>(); string pathRoot = Path.GetPathRoot(debuggee.SourceRoot); string sourceFileMapping = Path.Combine(pathRoot, Path.GetRandomFileName(), SourceMappingHelper.Writer); string compileFileMapping = Path.Combine(debuggee.SourceRoot, SourceMappingHelper.WriterFolder, SourceMappingHelper.Writer); if (PlatformUtilities.IsWindows) { // Move file to the location Directory.CreateDirectory(Path.GetDirectoryName(sourceFileMapping)); File.Copy(compileFileMapping, sourceFileMapping, true); } // Drive letter should be lowercase sourceMappings.Add(compileFileMapping, sourceFileMapping); launch.Args.sourceFileMap = sourceMappings; try { runner.RunCommand(launch); this.Comment("Set Breakpoint"); SourceBreakpoints writerBreakpoints = debuggee.Breakpoints(SourceMappingHelper.Writer, 9); runner.SetBreakpoints(writerBreakpoints); runner.Expects.StoppedEvent(StoppedReason.Breakpoint).AfterConfigurationDone(); using (IThreadInspector threadInspector = runner.GetThreadInspector()) { IEnumerator<IFrameInspector> frameEnumerator = threadInspector.Stack.GetEnumerator(); // Move to first stack item Assert.True(frameEnumerator.MoveNext()); this.Comment("Verify path is changed for writer.cpp frame"); ValidateMappingToFrame(SourceMappingHelper.Writer, EnsureDriveLetterLowercase(sourceFileMapping), frameEnumerator.Current, comparison); // Move to second stack item Assert.True(frameEnumerator.MoveNext()); this.Comment("Verify path is not changed for main.cpp frame."); ValidateMappingToFrame(SourceMappingHelper.Main, EnsureDriveLetterLowercase(Path.Combine(debuggee.SourceRoot, SourceMappingHelper.Main)), frameEnumerator.Current, comparison); writerBreakpoints.Remove(9); runner.SetBreakpoints(writerBreakpoints); this.Comment("Continue to end"); runner.Expects.TerminatedEvent().AfterContinue(); runner.DisconnectAndVerify(); } } finally { if (PlatformUtilities.IsWindows) { // Cleanup the directory if (Directory.Exists(Path.GetDirectoryName(sourceFileMapping))) { Directory.Delete(Path.GetDirectoryName(sourceFileMapping), true); } } } } } [Theory] [DependsOnTest(nameof(CompileSourceMapForSourceMapping))] [RequiresTestSettings] public void MapDirectory(ITestSettings settings) { this.TestPurpose("Validate Source Mapping."); this.WriteSettings(settings); IDebuggee debuggee = SourceMappingHelper.Open(this, settings.CompilerSettings, DebuggeeMonikers.SourceMapping.Default); // VsDbg is case insensitive on Windows so sometimes stackframe file names might all be lowercase StringComparison comparison = settings.DebuggerSettings.DebuggerType == SupportedDebugger.VsDbg ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; using (IDebuggerRunner runner = CreateDebugAdapterRunner(settings)) { this.Comment("Configure"); LaunchCommand launch = new LaunchCommand(settings.DebuggerSettings, debuggee.OutputPath, false, "-fCalling"); launch.Args.externalConsole = false; this.Comment("Setting up Source File Mappings"); Dictionary<string, string> sourceMappings = new Dictionary<string, string>(); string pathRoot = Path.GetPathRoot(debuggee.SourceRoot); string mgrDirectoryMapping = Path.Combine(debuggee.SourceRoot, SourceMappingHelper.Manager, Path.GetRandomFileName()); string writerDirectoryMapping = Path.Combine(pathRoot, Path.GetRandomFileName(), Path.GetRandomFileName()); string rootDirectoryMapping = Path.Combine(pathRoot, Path.GetRandomFileName()); sourceMappings.Add(Path.Combine(debuggee.SourceRoot, SourceMappingHelper.WriterFolder), writerDirectoryMapping); sourceMappings.Add(Path.Combine(debuggee.SourceRoot, SourceMappingHelper.ManagerFolder), mgrDirectoryMapping); sourceMappings.Add(debuggee.SourceRoot, rootDirectoryMapping); launch.Args.sourceFileMap = sourceMappings; try { if (PlatformUtilities.IsWindows) { // Create all the directories but only some of the files will exist on disk. foreach (var dir in sourceMappings.Values) { Directory.CreateDirectory(dir); } File.Copy(Path.Combine(debuggee.SourceRoot, SourceMappingHelper.WriterFolder, SourceMappingHelper.Writer), Path.Combine(writerDirectoryMapping, SourceMappingHelper.Writer), true); File.Copy(Path.Combine(debuggee.SourceRoot, SourceMappingHelper.Main), Path.Combine(rootDirectoryMapping, SourceMappingHelper.Main), true); } runner.RunCommand(launch); this.Comment("Set Breakpoint"); SourceBreakpoints writerBreakpoints = debuggee.Breakpoints(SourceMappingHelper.Writer, 9); SourceBreakpoints managerBreakpoints = debuggee.Breakpoints(SourceMappingHelper.Manager, 8); runner.SetBreakpoints(writerBreakpoints); runner.SetBreakpoints(managerBreakpoints); runner.Expects.StoppedEvent(StoppedReason.Breakpoint).AfterConfigurationDone(); using (IThreadInspector threadInspector = runner.GetThreadInspector()) { IEnumerator<IFrameInspector> frameEnumerator = threadInspector.Stack.GetEnumerator(); // Move to first stack item Assert.True(frameEnumerator.MoveNext()); this.Comment(string.Format(CultureInfo.InvariantCulture, "Verify source path for {0}.", SourceMappingHelper.Writer)); // Since file is there, lowercase the drive letter ValidateMappingToFrame(SourceMappingHelper.Writer, EnsureDriveLetterLowercase(Path.Combine(writerDirectoryMapping, SourceMappingHelper.Writer)), frameEnumerator.Current, comparison); // Move to second stack item Assert.True(frameEnumerator.MoveNext()); this.Comment(string.Format(CultureInfo.InvariantCulture, "Verify source path for {0}.", SourceMappingHelper.Main)); // Since file is there, lowercase the drive letter ValidateMappingToFrame(SourceMappingHelper.Main, EnsureDriveLetterLowercase(Path.Combine(rootDirectoryMapping, SourceMappingHelper.Main)), frameEnumerator.Current, comparison); } runner.Expects.StoppedEvent(StoppedReason.Breakpoint).AfterContinue(); using (IThreadInspector threadInspector = runner.GetThreadInspector()) { IEnumerator<IFrameInspector> frameEnumerator = threadInspector.Stack.GetEnumerator(); // Move to first stack item Assert.True(frameEnumerator.MoveNext()); this.Comment(string.Format(CultureInfo.InvariantCulture, "Verify source path for {0}.", SourceMappingHelper.Manager)); // Since file is not there, keep what was passed in ValidateMappingToFrame(SourceMappingHelper.Manager, EnsureDriveLetterLowercase(Path.Combine(mgrDirectoryMapping, SourceMappingHelper.Manager)), frameEnumerator.Current, comparison); // Move to second stack item Assert.True(frameEnumerator.MoveNext()); this.Comment(string.Format(CultureInfo.InvariantCulture, "Verify source path for {0}.", SourceMappingHelper.Main)); // Since file is there, lowercase the drive letter ValidateMappingToFrame(SourceMappingHelper.Main, EnsureDriveLetterLowercase(Path.Combine(rootDirectoryMapping, SourceMappingHelper.Main)), frameEnumerator.Current, comparison); } writerBreakpoints.Remove(9); managerBreakpoints.Remove(8); runner.SetBreakpoints(writerBreakpoints); runner.SetBreakpoints(managerBreakpoints); this.Comment("Continue to end"); runner.Expects.TerminatedEvent().AfterContinue(); runner.DisconnectAndVerify(); } finally { if (PlatformUtilities.IsWindows) { foreach (var dir in sourceMappings.Values) { if (Directory.Exists(dir)) { Directory.Delete(dir, recursive: true); } } } } } } } } <|start_filename|>src/MICore/Utilities.cs<|end_filename|> using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MICore { internal static class Utilities { private const string TempNamePrefix = "Microsoft-MIEngine-"; private const string Separator = "-"; internal static string GetMIEngineTemporaryFilename(string identifier = null) { // add the identifier + separator if the identifier exists string optionalIdentifier = string.IsNullOrEmpty(identifier) ? string.Empty : identifier + Separator; string filename = String.Concat(TempNamePrefix, optionalIdentifier, Path.GetRandomFileName()); return filename; } } } <|start_filename|>test/CppTests/debuggees/exception/src/main.cpp<|end_filename|> #include "exception.h" #include <iostream> #include <string> using namespace std; int main(int argc, char* argv[]) { cout << "Start testing" << endl; bool isUnhandledException = false; bool isHandledException = false; bool isReThrowException = false; if (argc > 1) { for (int i = 1; i < argc; i++) { string input = argv[i]; if (input.compare("-CallRaisedUnhandledException") == 0) { isUnhandledException = true; } else if (input.compare("-CallRaisedHandledException") == 0) { isHandledException = true; } else if (input.compare("-CallRaisedReThrowException") == 0) { isReThrowException = true; } } } int myVar1 = 100; int myVar2 = 200; int mySum = myVar1 + myVar2; myException *pInstance = new myException(); int result = pInstance->RecursiveFunc(mySum); if (isHandledException) { pInstance->RaisedHandledException(myVar1); } if (isUnhandledException) { pInstance->RaisedUnhandledException(myVar2); } pInstance->EvalFunc(myVar1, myVar2); if (isReThrowException) { pInstance->RaisedReThrowException(); } if (pInstance != NULL) { delete pInstance; } cout << "Finish testing" << endl; return 0; } <|start_filename|>src/OpenDebugAD7/AD7Utils.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.VisualStudio.Debugger.Interop; namespace OpenDebugAD7 { internal class AD7Utils { public static bool IsAnnotatedFrame(ref FRAMEINFO frameInfo) { enum_FRAMEINFO_FLAGS_VALUES flags = unchecked((enum_FRAMEINFO_FLAGS_VALUES)frameInfo.m_dwFlags); return flags.HasFlag(enum_FRAMEINFO_FLAGS_VALUES.FIFV_ANNOTATEDFRAME); } public static string GetMemoryReferenceFromIDebugProperty(IDebugProperty2 property) { if (property != null && property.GetMemoryContext(out IDebugMemoryContext2 memoryContext) == HRConstants.S_OK) { CONTEXT_INFO[] contextInfo = new CONTEXT_INFO[1]; if (memoryContext.GetInfo(enum_CONTEXT_INFO_FIELDS.CIF_ADDRESS, contextInfo) == HRConstants.S_OK) { if (contextInfo[0].dwFields.HasFlag(enum_CONTEXT_INFO_FIELDS.CIF_ADDRESS)) { return contextInfo[0].bstrAddress; } } } return null; } } } <|start_filename|>test/DebugAdapterRunner/OpenDebug/Messages.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Newtonsoft.Json; namespace OpenDebug { public class DispatcherMessage { public int seq; public string type; public DispatcherMessage(string typ) { type = typ; } } public class DispatcherRequest : DispatcherMessage { public string command; public dynamic arguments; public DispatcherRequest() : base("request") { } public DispatcherRequest(int id, string cmd, dynamic arg) : base("request") { seq = id; command = cmd; arguments = arg; } } public class DispatcherResponse : DispatcherMessage { public bool success; public string message; public int request_seq; public string command; public dynamic body; public bool running; public dynamic refs; public DispatcherResponse() : base("response") { } public DispatcherResponse(string msg) : base("response") { success = false; message = msg; } public DispatcherResponse(bool succ, string msg) : base("response") { success = succ; message = msg; } public DispatcherResponse(dynamic m) : base("response") { seq = m.seq; success = m.success; message = m.message; request_seq = m.request_seq; command = m.command; body = m.body; running = m.running; refs = m.refs; } public DispatcherResponse(int rseq, string cmd) : base("response") { request_seq = rseq; command = cmd; } } public class DispatcherEvent : DispatcherMessage { [JsonProperty(PropertyName = "event")] public string eventType; public dynamic body; public DispatcherEvent() : base("event") { } public DispatcherEvent(dynamic m) : base("event") { seq = m.seq; eventType = m["event"]; body = m.body; } public DispatcherEvent(string type, dynamic bdy = null) : base("event") { eventType = type; body = bdy; } } } <|start_filename|>src/MICore/Transports/MockTransport.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Text; using System.Threading; using System.Diagnostics; using System.IO; using Microsoft.DebugEngineHost; namespace MICore { // // MockTransport // Reads a text file and makes it look like a transport // For lines that start with "-" then it waits until someone Sends a command, which should match // (gdb) lines are ignored // For all other lines they are sent to the callback public class MockTransport : ITransport { private ITransportCallback _callback; private Thread _thread; private string _nextCommand; private bool _bQuit; private TextReader _reader; private AutoResetEvent _commandEvent; private string _filename; private int _lineNumber; public MockTransport(string logfilename) { _filename = logfilename; } public void Init(ITransportCallback transportCallback, LaunchOptions options, Logger logger, HostWaitLoop waitLoop = null) { _bQuit = false; _callback = transportCallback; _commandEvent = new AutoResetEvent(false); _reader = new StreamReader(File.OpenRead(_filename)); _thread = new Thread(TransportLoop); _nextCommand = null; _thread.Start(); } public void Send(string cmd) { Debug.Assert(_nextCommand == null); _nextCommand = cmd; _commandEvent.Set(); } public void Close() { _bQuit = true; if (_thread != Thread.CurrentThread) { _thread.Join(); } } public bool IsClosed { get { return _bQuit; } } public int DebuggerPid { get { throw new NotImplementedException(); } } private void TransportLoop() { _lineNumber = 0; // discard first line _reader.ReadLine(); _lineNumber = 1; while (!_bQuit) { string line = _reader.ReadLine(); if (line == null) { break; } line = line.TrimEnd(); _lineNumber++; Debug.WriteLine("#{0}:{1}", _lineNumber, line); if (line[0] == '-') { _commandEvent.WaitOne(); // wait for a command if (line != _nextCommand) { Debug.Assert(false, "Unexpected command sent " + line + " expecting " + _nextCommand); break; } _nextCommand = null; } else if (!line.StartsWith("-", StringComparison.Ordinal)) { _callback.OnStdOutLine(line); } } } public int ExecuteSyncCommand(string commandDescription, string commandText, int timeout, out string output, out string error) { throw new NotImplementedException(); } public bool CanExecuteCommand() { return false; } } } <|start_filename|>test/CppTests/debuggees/optimization/src/mylib.cpp<|end_filename|> #include "mylib.h" #include <iostream> #include <string> using namespace std; int myClass::DisplayAge(int age) { age++; cout << "my age: " << age << endl; return age; } string myClass::DisplayName(string firstName, string lastName) { string name = firstName + lastName; cout << "my name: " << name << endl; return name; } extern "C" myClass* Create() { return new myClass; } extern "C" void Destroy(myClass *myclass) { delete myclass; } <|start_filename|>test/DebuggerTesting/Tests/AttributionTests.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using System.Linq; using System.Reflection; using Xunit; using Xunit.Abstractions; namespace DebuggerTesting.Tests { public sealed class AttributionTests : ILoggingComponent { #region Constructor public AttributionTests(ITestOutputHelper outputHelper) { this.OutputHelper = outputHelper; } #endregion #region ILoggingComponent Members public ITestOutputHelper OutputHelper { get; private set; } #endregion #region Methods #region Test Methods [Fact] public void TestPlatformWithoutAttribute() { this.TestPurpose("Check that tests without SupportedPlatformAttribute will run with all test settings."); IEnumerable<ITestSettings> actual = AttributionTests.FilterSettings( nameof(AttributionTests.MockTest_PlatformNeutral), SupportedPlatform.Windows, SupportedArchitecture.x64); IEnumerable<ITestSettings> expected = AttributionTests.ChangeName( AttributionTests.AllSettings, nameof(AttributionTests.MockTest_PlatformNeutral)); Assert.Equal(expected, actual); actual = AttributionTests.FilterSettings( nameof(AttributionTests.MockTest_PlatformNeutral), SupportedPlatform.Windows, SupportedArchitecture.x86); Assert.Equal(expected, actual); actual = AttributionTests.FilterSettings( nameof(AttributionTests.MockTest_PlatformNeutral), SupportedPlatform.Linux, SupportedArchitecture.x64); Assert.Equal(expected, actual); actual = AttributionTests.FilterSettings( nameof(AttributionTests.MockTest_PlatformNeutral), SupportedPlatform.Linux, SupportedArchitecture.x86); Assert.Equal(expected, actual); actual = AttributionTests.FilterSettings( nameof(AttributionTests.MockTest_PlatformNeutral), SupportedPlatform.MacOS, SupportedArchitecture.x64); Assert.Equal(expected, actual); actual = AttributionTests.FilterSettings( nameof(AttributionTests.MockTest_PlatformNeutral), SupportedPlatform.MacOS, SupportedArchitecture.x86); Assert.Equal(expected, actual); } [Fact] public void TestPlatformIsSame() { this.TestPurpose("Check that tests with SupportedPlatformAttribute will run on the specified platform."); IEnumerable<ITestSettings> actual = AttributionTests.FilterSettings( nameof(AttributionTests.MockTest_PlatformWindows), SupportedPlatform.Windows, SupportedArchitecture.x64); IEnumerable<ITestSettings> expected = AttributionTests.ChangeName( AttributionTests.AllSettings, nameof(AttributionTests.MockTest_PlatformWindows)); Assert.Equal(expected, actual); } [Fact] public void TestPlatformIsSameArchitectureIsSame() { this.TestPurpose("Check that tests with SupportedPlatformAttribute will run on the specified platform and architecture."); IEnumerable<ITestSettings> actual = AttributionTests.FilterSettings( nameof(AttributionTests.MockTest_PlatformMac64), SupportedPlatform.MacOS, SupportedArchitecture.x64); IEnumerable<ITestSettings> expected = AttributionTests.ChangeName( AttributionTests.AllSettings, nameof(AttributionTests.MockTest_PlatformMac64)); Assert.Equal(expected, actual); } [Fact] public void TestPlatformIsSameArchitectureIsDifferent() { this.TestPurpose("Check that tests with SupportedPlatformAttribute will not run on the specified platform and different architecture."); IEnumerable<ITestSettings> actual = AttributionTests.FilterSettings( nameof(AttributionTests.MockTest_PlatformLinux86), SupportedPlatform.Linux, SupportedArchitecture.x64); IEnumerable<ITestSettings> expected = Enumerable.Empty<ITestSettings>(); Assert.Equal(expected, actual); } [Fact] public void TestPlatformIsDifferent() { this.TestPurpose("Check that tests with SupportedPlatformAttribute will not run on a different platform."); IEnumerable<ITestSettings> actual = AttributionTests.FilterSettings( nameof(AttributionTests.MockTest_PlatformWindows), SupportedPlatform.Linux, SupportedArchitecture.x86); IEnumerable<ITestSettings> expected = Enumerable.Empty<ITestSettings>(); Assert.Equal(expected, actual); actual = AttributionTests.FilterSettings( nameof(AttributionTests.MockTest_PlatformWindows), SupportedPlatform.MacOS, SupportedArchitecture.x86); Assert.Equal(expected, actual); } [Fact] public void TestDebuggerSupported() { this.TestPurpose("Check that tests with a single SupportedDebuggerAttribute will only run with the specified debugger."); IEnumerable<ITestSettings> actual = AttributionTests.FilterSettings( nameof(AttributionTests.MockTest_DebuggerGdbSupported), SupportedPlatform.Windows, SupportedArchitecture.x64); IEnumerable<ITestSettings> expected = AttributionTests.ChangeName( new ITestSettings[] { AttributionTests.Settings_GppGdbX64, AttributionTests.Settings_GppGdbX86 }, nameof(AttributionTests.MockTest_DebuggerGdbSupported)); Assert.Equal(expected, actual); } [Fact] public void TestDebuggerMultipleSupported() { this.TestPurpose("Check that tests with several SupportedDebuggerAttribute will only run with the specified debuggers."); IEnumerable<ITestSettings> actual = AttributionTests.FilterSettings( nameof(AttributionTests.MockTest_DebuggerGdbLldbSupported), SupportedPlatform.Windows, SupportedArchitecture.x64); IEnumerable<ITestSettings> expected = AttributionTests.ChangeName( new ITestSettings[] { AttributionTests.Settings_GppGdbX64, AttributionTests.Settings_GppGdbX86, AttributionTests.Settings_ClangLldbX64 }, nameof(AttributionTests.MockTest_DebuggerGdbLldbSupported)); Assert.Equal(expected, actual); } [Fact] public void TestDebuggerUnmatched() { this.TestPurpose("Check that tests that do not match the settings will not run."); IEnumerable<ITestSettings> settings = new ITestSettings[] { AttributionTests.Settings_ClangLldbX64, AttributionTests.Settings_ClangLldbX86 }; IEnumerable<ITestSettings> actual = settings.FilterSettings( AttributionTests.GetTestMethodInfo(nameof(AttributionTests.MockTest_DebuggerGdbSupported)), SupportedPlatform.Windows, SupportedArchitecture.x64); IEnumerable<ITestSettings> expected = Enumerable.Empty<ITestSettings>(); Assert.Equal(expected, actual); } [Fact] public void TestDebuggerUnsupported() { this.TestPurpose("Check that tests with a single UnsupportedDebuggerAttribute will not run for the specified debugger."); IEnumerable<ITestSettings> actual = AttributionTests.FilterSettings( nameof(AttributionTests.MockTest_DebuggerLldbUnsupported), SupportedPlatform.Windows, SupportedArchitecture.x64); IEnumerable<ITestSettings> expected = AttributionTests.ChangeName( new ITestSettings[] { AttributionTests.Settings_GppGdbX64, AttributionTests.Settings_GppGdbX86, AttributionTests.Settings_CygwinGppGdbX64, AttributionTests.Settings_CygwinGppGdbX86, AttributionTests.Settings_MingwGppGdbX64, AttributionTests.Settings_MingwGppGdbX86 }, nameof(AttributionTests.MockTest_DebuggerLldbUnsupported)); Assert.Equal(expected, actual); } [Fact] public void TestDebuggerMultipleUnsupported() { this.TestPurpose("Check that tests with multiple UnsupportedDebuggerAttribute will not run for the specified debuggers."); IEnumerable<ITestSettings> actual = AttributionTests.FilterSettings( nameof(AttributionTests.MockTest_DebuggerGdbLldbUnsupported), SupportedPlatform.Windows, SupportedArchitecture.x64); IEnumerable<ITestSettings> expected = AttributionTests.ChangeName( new ITestSettings[] { AttributionTests.Settings_GppGdbX64, AttributionTests.Settings_CygwinGppGdbX64, AttributionTests.Settings_CygwinGppGdbX86, AttributionTests.Settings_MingwGppGdbX86, }, nameof(AttributionTests.MockTest_DebuggerGdbLldbUnsupported)); Assert.Equal(expected, actual); } [Fact] public void TestDebuggerSupportedUnsupportedIsSame() { this.TestPurpose("Check that tests that specify the same debugger as supported and unsupported will not run with that debugger."); IEnumerable<ITestSettings> actual = AttributionTests.FilterSettings( nameof(AttributionTests.MockTest_DebuggerGdbSupportedUnsupported), SupportedPlatform.Windows, SupportedArchitecture.x64); IEnumerable<ITestSettings> expected = Enumerable.Empty<ITestSettings>(); Assert.Equal(expected, actual); } [Fact] public void TestCompilerSupported() { this.TestPurpose("Check that tests with a single SupportedCompilerAttribute will only run with the specified compiler."); IEnumerable<ITestSettings> actual = AttributionTests.FilterSettings( nameof(AttributionTests.MockTest_CompilerGPlusPlus86Supported), SupportedPlatform.Windows, SupportedArchitecture.x64); IEnumerable<ITestSettings> expected = AttributionTests.ChangeName( new ITestSettings[] { AttributionTests.Settings_GppGdbX86, AttributionTests.Settings_CygwinGppGdbX86, AttributionTests.Settings_MingwGppGdbX86 }, nameof(AttributionTests.MockTest_CompilerGPlusPlus86Supported)); Assert.Equal(expected, actual); } [Fact] public void TestCompilerMultipleSupported() { this.TestPurpose("Check that tests with several SupportedCompilerAttribute will only run with the specified compilers."); IEnumerable<ITestSettings> actual = AttributionTests.FilterSettings( nameof(AttributionTests.MockTest_CompilerGPlusPlus86ClangPlusPlus64Supported), SupportedPlatform.Windows, SupportedArchitecture.x64); IEnumerable<ITestSettings> expected = AttributionTests.ChangeName( new ITestSettings[] { AttributionTests.Settings_GppGdbX64, AttributionTests.Settings_CygwinGppGdbX64, AttributionTests.Settings_MingwGppGdbX64, AttributionTests.Settings_ClangLldbX86 }, nameof(AttributionTests.MockTest_CompilerGPlusPlus86ClangPlusPlus64Supported)); Assert.Equal(expected, actual); } #endregion #region Mock Tests #pragma warning disable xUnit1013 public void MockTest_PlatformNeutral(ITestSettings settings) { } [SupportedPlatform(SupportedPlatform.Windows, SupportedArchitecture.x64 | SupportedArchitecture.x86)] public void MockTest_PlatformWindows(ITestSettings settings) { } [SupportedPlatform(SupportedPlatform.MacOS, SupportedArchitecture.x64)] public void MockTest_PlatformMac64(ITestSettings settings) { } [SupportedPlatform(SupportedPlatform.Linux, SupportedArchitecture.x86)] public void MockTest_PlatformLinux86(ITestSettings settings) { } [SupportedDebugger(SupportedDebugger.Gdb_Gnu, SupportedArchitecture.x64 | SupportedArchitecture.x86)] public void MockTest_DebuggerGdbSupported(ITestSettings settings) { } [SupportedDebugger(SupportedDebugger.Gdb_Gnu, SupportedArchitecture.x64 | SupportedArchitecture.x86)] [SupportedDebugger(SupportedDebugger.Lldb, SupportedArchitecture.x64)] public void MockTest_DebuggerGdbLldbSupported(ITestSettings settings) { } [UnsupportedDebugger(SupportedDebugger.Lldb, SupportedArchitecture.x64 | SupportedArchitecture.x86)] public void MockTest_DebuggerLldbUnsupported(ITestSettings settings) { } [UnsupportedDebugger(SupportedDebugger.Gdb_Gnu, SupportedArchitecture.x86)] [UnsupportedDebugger(SupportedDebugger.Lldb, SupportedArchitecture.x64 | SupportedArchitecture.x86)] [UnsupportedDebugger(SupportedDebugger.Gdb_MinGW, SupportedArchitecture.x64)] public void MockTest_DebuggerGdbLldbUnsupported(ITestSettings settings) { } [SupportedDebugger(SupportedDebugger.Gdb_Gnu, SupportedArchitecture.x64 | SupportedArchitecture.x86)] [UnsupportedDebugger(SupportedDebugger.Gdb_Gnu, SupportedArchitecture.x64 | SupportedArchitecture.x86)] public void MockTest_DebuggerGdbSupportedUnsupported(ITestSettings settings) { } [SupportedCompiler(SupportedCompiler.GPlusPlus, SupportedArchitecture.x86)] public void MockTest_CompilerGPlusPlus86Supported(ITestSettings settings) { } [SupportedCompiler(SupportedCompiler.GPlusPlus, SupportedArchitecture.x64)] [SupportedCompiler(SupportedCompiler.ClangPlusPlus, SupportedArchitecture.x86)] public void MockTest_CompilerGPlusPlus86ClangPlusPlus64Supported(ITestSettings settings) { } #pragma warning restore xUnit1013 #endregion #region Helpers private static IEnumerable<ITestSettings> ChangeName(IEnumerable<ITestSettings> settings, string name) { return settings.Select(s => TestSettings.CloneWithName(s, name)).ToArray(); } private static TestSettings CreateClangLldbSettings(SupportedArchitecture debuggeeArchitecture, string compilerName, string debuggerName) { return new TestSettings(debuggeeArchitecture, compilerName, SupportedCompiler.ClangPlusPlus, "clang++", null, debuggerName, SupportedDebugger.Lldb, "lldb-mi", null, "lldb", null); } private static TestSettings CreateGppGdbSettings(SupportedArchitecture debuggeeArchitecture, string compilerName, string debuggerName, SupportedDebugger debuggerType) { return new TestSettings(debuggeeArchitecture, compilerName, SupportedCompiler.GPlusPlus, "g++", null, debuggerName, debuggerType, "gdb", null, null, null); } private static IEnumerable<ITestSettings> FilterSettings(string methodName, SupportedPlatform platform, SupportedArchitecture platformArchitecture) { MethodInfo methodInfo = AttributionTests.GetTestMethodInfo(methodName); return AttributionTests.AllSettings.FilterSettings(methodInfo, platform, platformArchitecture); } private static MethodInfo GetTestMethodInfo(string methodName) { MethodInfo testMethod = typeof(AttributionTests).GetTypeInfo().GetDeclaredMethod(methodName); Assert.NotNull(testMethod); return testMethod; } #endregion #endregion #region Properties private static IEnumerable<ITestSettings> AllSettings { get { if (null == AttributionTests.s_settings) { lock (AttributionTests.s_syncObject) { if (null == AttributionTests.s_settings) { IList<ITestSettings> settings = new List<ITestSettings>(); settings.Add(AttributionTests.Settings_GppGdbX64); settings.Add(AttributionTests.Settings_GppGdbX86); settings.Add(AttributionTests.Settings_CygwinGppGdbX64); settings.Add(AttributionTests.Settings_CygwinGppGdbX86); settings.Add(AttributionTests.Settings_MingwGppGdbX64); settings.Add(AttributionTests.Settings_MingwGppGdbX86); settings.Add(AttributionTests.Settings_ClangLldbX64); settings.Add(AttributionTests.Settings_ClangLldbX86); AttributionTests.s_settings = settings; } } } return AttributionTests.s_settings; } } #endregion #region Fields private static IEnumerable<ITestSettings> s_settings; private static object s_syncObject = new object(); private static readonly ITestSettings Settings_GppGdbX64 = AttributionTests.CreateGppGdbSettings(SupportedArchitecture.x64, "Gpp", "Gdb", SupportedDebugger.Gdb_Gnu); private static readonly ITestSettings Settings_GppGdbX86 = AttributionTests.CreateGppGdbSettings(SupportedArchitecture.x86, "Gpp", "Gdb", SupportedDebugger.Gdb_Gnu); private static readonly ITestSettings Settings_CygwinGppGdbX64 = AttributionTests.CreateGppGdbSettings(SupportedArchitecture.x64, "GppCygwin64", "GdbCygwin64", SupportedDebugger.Gdb_Cygwin); private static readonly ITestSettings Settings_CygwinGppGdbX86 = AttributionTests.CreateGppGdbSettings(SupportedArchitecture.x86, "GppCygwin86", "GdbCygwin86", SupportedDebugger.Gdb_Cygwin); private static readonly ITestSettings Settings_MingwGppGdbX64 = AttributionTests.CreateGppGdbSettings(SupportedArchitecture.x64, "GppMingw64", "GdbMingw64", SupportedDebugger.Gdb_MinGW); private static readonly ITestSettings Settings_MingwGppGdbX86 = AttributionTests.CreateGppGdbSettings(SupportedArchitecture.x86, "GppMingw86", "GdbMingw86", SupportedDebugger.Gdb_MinGW); private static readonly ITestSettings Settings_ClangLldbX64 = AttributionTests.CreateClangLldbSettings(SupportedArchitecture.x64, "Clang", "Lldb"); private static readonly ITestSettings Settings_ClangLldbX86 = AttributionTests.CreateClangLldbSettings(SupportedArchitecture.x86, "Clang", "Lldb"); #endregion } } <|start_filename|>src/MICore/RunInTerminalLauncher.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Linq; using Microsoft.DebugEngineHost; namespace MICore { internal class RunInTerminalLauncher { private string _title; private Dictionary<string, string> _environment; /// <summary> /// /// </summary> /// <param name="title"></param> /// <param name="envEntries">Environment Entries for launching the command in the RunInTerminal Protocol call.</param> public RunInTerminalLauncher(string title, ReadOnlyCollection<EnvironmentEntry> envEntries) { _title = title; _environment = new Dictionary<string, string>(); if (envEntries != null && envEntries.Any()) { foreach (var envEntry in envEntries) { Debug.Assert(!_environment.ContainsKey(envEntry.Name), FormattableString.Invariant($"Duplicate key ${envEntry.Name} detected!")); _environment[envEntry.Name] = envEntry.Value; } } } public void Launch(List<string> cmdArgs, bool useExternalConsole, Action<int?> launchCompleteAction, Action<string> launchFailureAction, Logger logger) { if (HostRunInTerminal.IsRunInTerminalAvailable()) { HostRunInTerminal.RunInTerminal(_title, string.Empty, useExternalConsole, cmdArgs, new ReadOnlyDictionary<string, string>(_environment), launchCompleteAction, launchFailureAction); } } } } <|start_filename|>test/Android/EvalPrimitiveTypes/EvalPrimitiveTypes/EvalPrimitiveTypes.NativeActivity/Source1.cpp<|end_filename|> #include "Header1.h" void Func() { bool _bool = true; char _char = 'a'; unsigned char _unsignedchar = 'b'; signed char _signedchar = 'c'; short int _shortint = 0x0001; unsigned short _unsignedshort = 0x0010; wchar_t _wchar_t = 'd'; float _float = 1.01f; int _int = 0x00000020; unsigned int _unsignedint = 0x00000040; long _long = 0x00000050; unsigned long _unsignedlong = 0x00000050; double _double = 0x0000000000000011; long double _longdouble = 0x0000000000000012; long long _longlong = 0x0000000000000013; return; //bp } <|start_filename|>src/MIDebugEngine/Engine.Impl/EngineCallback.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Text; using Microsoft.VisualStudio.Debugger.Interop; using System.Diagnostics; using System.Collections.ObjectModel; using System.Threading; using MICore; using Microsoft.DebugEngineHost; namespace Microsoft.MIDebugEngine { internal class EngineCallback : ISampleEngineCallback, MICore.IDeviceAppLauncherEventCallback { private readonly IDebugEventCallback2 _eventCallback; private readonly AD7Engine _engine; private int _sentProgramDestroy; public EngineCallback(AD7Engine engine, IDebugEventCallback2 ad7Callback) { _engine = engine; _eventCallback = HostMarshal.GetThreadSafeEventCallback(ad7Callback); } public void Send(IDebugEvent2 eventObject, string iidEvent, IDebugProgram2 program, IDebugThread2 thread) { uint attributes; Guid riidEvent = new Guid(iidEvent); if (!(eventObject is AD7OutputDebugStringEvent)) { _engine.Logger.WriteLine("Send Event {0}", eventObject.GetType().Name); } EngineUtils.RequireOk(eventObject.GetAttributes(out attributes)); EngineUtils.RequireOk(_eventCallback.Event(_engine, null, program, thread, eventObject, ref riidEvent, attributes)); } public void Send(IDebugEvent2 eventObject, string iidEvent, IDebugThread2 thread) { IDebugProgram2 program = _engine; if (!_engine.ProgramCreateEventSent) { // Any events before programe create shouldn't include the program program = null; } Send(eventObject, iidEvent, program, thread); } public void OnError(string message) { SendMessage(message, OutputMessage.Severity.Error, isAsync: true); } /// <summary> /// Sends an error to the user, blocking until the user dismisses the error /// </summary> /// <param name="message">string to display to the user</param> public void OnErrorImmediate(string message) { SendMessage(message, OutputMessage.Severity.Error, isAsync: false); } public void OnWarning(string message) { SendMessage(message, OutputMessage.Severity.Warning, isAsync: true); } public void OnModuleLoad(DebuggedModule debuggedModule) { // This will get called when the entrypoint breakpoint is fired because the engine sends a mod-load event // for the exe. if (_engine.DebuggedProcess != null) { Debug.Assert(_engine.DebuggedProcess.WorkerThread.IsPollThread()); } AD7Module ad7Module = new AD7Module(debuggedModule, _engine.DebuggedProcess); AD7ModuleLoadEvent eventObject = new AD7ModuleLoadEvent(ad7Module, true /* this is a module load */); debuggedModule.Client = ad7Module; // The sample engine does not support binding breakpoints as modules load since the primary exe is the only module // symbols are loaded for. A production debugger will need to bind breakpoints when a new module is loaded. Send(eventObject, AD7ModuleLoadEvent.IID, null); } public void OnSymbolsLoaded(DebuggedModule module) { var eventObject = new AD7SymbolLoadEvent(module.Client as AD7Module); Send(eventObject, AD7SymbolLoadEvent.IID, null); } public void OnModuleUnload(DebuggedModule debuggedModule) { Debug.Assert(_engine.DebuggedProcess.WorkerThread.IsPollThread()); AD7Module ad7Module = (AD7Module)debuggedModule.Client; Debug.Assert(ad7Module != null); AD7ModuleLoadEvent eventObject = new AD7ModuleLoadEvent(ad7Module, false /* this is a module unload */); Send(eventObject, AD7ModuleLoadEvent.IID, null); } public void OnOutputString(string outputString) { AD7OutputDebugStringEvent eventObject = new AD7OutputDebugStringEvent(outputString); Send(eventObject, AD7OutputDebugStringEvent.IID, null); } public void OnOutputMessage(OutputMessage outputMessage) { try { if (outputMessage.ErrorCode == 0) { var eventObject = new AD7MessageEvent(outputMessage, isAsync: true); Send(eventObject, AD7MessageEvent.IID, null); } else { var eventObject = new AD7ErrorEvent(outputMessage, isAsync: true); Send(eventObject, AD7ErrorEvent.IID, null); } } catch { // Since we are often trying to report an exception, if something goes wrong we don't want to take down the process, // so ignore the failure. } } public void OnProcessExit(uint exitCode) { if (Interlocked.Exchange(ref _sentProgramDestroy, 1) == 0) { AD7ProgramDestroyEvent eventObject = new AD7ProgramDestroyEvent(exitCode); try { Send(eventObject, AD7ProgramDestroyEvent.IID, null); } catch (InvalidOperationException) { // If debugging has already stopped, this can throw } } } public void OnEntryPoint(DebuggedThread thread) { AD7EntryPointEvent eventObject = new AD7EntryPointEvent(); Send(eventObject, AD7EntryPointEvent.IID, (AD7Thread)thread.Client); } public void OnThreadExit(DebuggedThread debuggedThread, uint exitCode) { Debug.Assert(_engine.DebuggedProcess.WorkerThread.IsPollThread()); AD7Thread ad7Thread = (AD7Thread)debuggedThread.Client; Debug.Assert(ad7Thread != null); AD7ThreadDestroyEvent eventObject = new AD7ThreadDestroyEvent(exitCode); Send(eventObject, AD7ThreadDestroyEvent.IID, ad7Thread); } public void OnThreadStart(DebuggedThread debuggedThread) { // This will get called when the entrypoint breakpoint is fired because the engine sends a thread start event // for the main thread of the application. if (_engine.DebuggedProcess != null) { Debug.Assert(_engine.DebuggedProcess.WorkerThread.IsPollThread()); } AD7ThreadCreateEvent eventObject = new AD7ThreadCreateEvent(); Send(eventObject, AD7ThreadCreateEvent.IID, (IDebugThread2)debuggedThread.Client); } public void OnBreakpoint(DebuggedThread thread, ReadOnlyCollection<object> clients) { IDebugBoundBreakpoint2[] boundBreakpoints = new IDebugBoundBreakpoint2[clients.Count]; int i = 0; foreach (object objCurrentBreakpoint in clients) { boundBreakpoints[i] = (IDebugBoundBreakpoint2)objCurrentBreakpoint; i++; } // An engine that supports more advanced breakpoint features such as hit counts, conditions and filters // should notify each bound breakpoint that it has been hit and evaluate conditions here. // The sample engine does not support these features. AD7BreakpointEvent eventObject = new AD7BreakpointEvent(boundBreakpoints); AD7Thread ad7Thread = (AD7Thread)thread.Client; Send(eventObject, AD7BreakpointEvent.IID, ad7Thread); } // Exception events are sent when an exception occurs in the debuggee that the debugger was not expecting. public void OnException(DebuggedThread thread, string name, string description, uint code, Guid? exceptionCategory = null, ExceptionBreakpointStates state = ExceptionBreakpointStates.None) { AD7ExceptionEvent eventObject = new AD7ExceptionEvent(name, description, code, exceptionCategory, state); AD7Thread ad7Thread = (AD7Thread)thread.Client; Send(eventObject, AD7ExceptionEvent.IID, ad7Thread); } public void OnExpressionEvaluationComplete(IVariableInformation var, IDebugProperty2 prop = null) { AD7ExpressionCompleteEvent eventObject = new AD7ExpressionCompleteEvent(_engine, var, prop); Send(eventObject, AD7ExpressionCompleteEvent.IID, var.Client); } public void OnStepComplete(DebuggedThread thread) { // Step complete is sent when a step has finished AD7StepCompleteEvent eventObject = new AD7StepCompleteEvent(); AD7Thread ad7Thread = (AD7Thread)thread.Client; Send(eventObject, AD7StepCompleteEvent.IID, ad7Thread); } public void OnAsyncBreakComplete(DebuggedThread thread) { // This will get called when the engine receives the breakpoint event that is created when the user // hits the pause button in vs. Debug.Assert(_engine.DebuggedProcess.WorkerThread.IsPollThread()); AD7Thread ad7Thread = (AD7Thread)thread.Client; AD7AsyncBreakCompleteEvent eventObject = new AD7AsyncBreakCompleteEvent(); Send(eventObject, AD7AsyncBreakCompleteEvent.IID, ad7Thread); } public void OnLoadComplete() { AD7LoadCompleteEvent eventObject = new AD7LoadCompleteEvent(); Send(eventObject, AD7LoadCompleteEvent.IID, null); } public void OnProgramDestroy(uint exitCode) { AD7ProgramDestroyEvent eventObject = new AD7ProgramDestroyEvent(exitCode); Send(eventObject, AD7ProgramDestroyEvent.IID, null); } // Engines notify the debugger that a breakpoint has bound through the breakpoint bound event. public void OnBreakpointBound(object objBoundBreakpoint) { AD7BoundBreakpoint boundBreakpoint = (AD7BoundBreakpoint)objBoundBreakpoint; IDebugPendingBreakpoint2 pendingBreakpoint; ((IDebugBoundBreakpoint2)boundBreakpoint).GetPendingBreakpoint(out pendingBreakpoint); AD7BreakpointBoundEvent eventObject = new AD7BreakpointBoundEvent((AD7PendingBreakpoint)pendingBreakpoint, boundBreakpoint); Send(eventObject, AD7BreakpointBoundEvent.IID, null); } // Engines notify the SDM that a pending breakpoint failed to bind through the breakpoint error event public void OnBreakpointError(AD7ErrorBreakpoint bperr) { AD7BreakpointErrorEvent eventObject = new AD7BreakpointErrorEvent(bperr); Send(eventObject, AD7BreakpointErrorEvent.IID, null); } // Engines notify the SDM that a bound breakpoint change resulted in an error public void OnBreakpointUnbound(AD7BoundBreakpoint bp, enum_BP_UNBOUND_REASON reason) { AD7BreakpointUnboundEvent eventObject = new AD7BreakpointUnboundEvent(bp, reason); Send(eventObject, AD7BreakpointUnboundEvent.IID, null); } public void OnCustomDebugEvent(Guid guidVSService, Guid sourceId, int messageCode, object parameter1, object parameter2) { var eventObject = new AD7CustomDebugEvent(guidVSService, sourceId, messageCode, parameter1, parameter2); Send(eventObject, AD7CustomDebugEvent.IID, null); } public void OnStopComplete(DebuggedThread thread) { var eventObject = new AD7StopCompleteEvent(); Send(eventObject, AD7StopCompleteEvent.IID, (AD7Thread)thread.Client); } private void SendMessage(string message, OutputMessage.Severity severity, bool isAsync) { try { // IDebugErrorEvent2 is used to report error messages to the user when something goes wrong in the debug engine. // The sample engine doesn't take advantage of this. AD7MessageEvent eventObject = new AD7MessageEvent(new OutputMessage(message, enum_MESSAGETYPE.MT_MESSAGEBOX, severity), isAsync); Send(eventObject, AD7MessageEvent.IID, null); } catch { // Since we are often trying to report an exception, if something goes wrong we don't want to take down the process, // so ignore the failure. } } } } <|start_filename|>test/DebuggerTesting/Utilities/SupportedArchitectureExtensions.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; namespace DebuggerTesting.Utilities { public static class SupportedArchitectureExtensions { #region Methods public static string ToArchitectureString(this SupportedArchitecture architecture) { switch (architecture) { case SupportedArchitecture.x86: return "x86"; case SupportedArchitecture.x64: return "x64"; case SupportedArchitecture.arm: return "arm"; default: throw new ArgumentOutOfRangeException(nameof(architecture)); } } #endregion } } <|start_filename|>test/Android/EvalCompoundDataTypes/EvalCompoundDataTypes/EvalCompoundDataTypes.NativeActivity/Header1.h<|end_filename|> #pragma once #include <string> using namespace std; class Cat { public: int age; double weight; string name; }; struct Book { int ID; double price; string title; }; void Func(); <|start_filename|>test/DebuggerTesting/OpenDebug/IEvent.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace DebuggerTesting.OpenDebug { public interface IEvent : IResponse { string Name { get; } /// <summary> /// Called after an event is hit if the event response matches. /// This method is called with the actual match. /// This can be used to read data from the event. /// </summary> void ProcessActualResponse(IActualResponse response); } } <|start_filename|>src/DebugEngineHost.VSCode/HostRunInTerminal.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; namespace Microsoft.DebugEngineHost { public static class HostRunInTerminal { private static Action<string, string, bool, List<string>, Dictionary<string, object>, Action<int?>, Action<string>> s_runInTerminalCallback; /// <summary> /// Checks to see if RunInTerminal is available /// </summary> /// <returns></returns> public static bool IsRunInTerminalAvailable() { return s_runInTerminalCallback != null; } /// <summary> /// Passes the call to the UI to attempt to RunInTerminal if possible. /// </summary> public static void RunInTerminal(string title, string cwd, bool useExternalConsole, IReadOnlyList<string> commandArgs, IReadOnlyDictionary<string, string> environmentVars, Action<int?> success, Action<string> failure) { if (s_runInTerminalCallback != null) { Dictionary<string, object> env = new Dictionary<string, object>(); foreach (var item in environmentVars) { env.Add(item.Key, item.Value); } s_runInTerminalCallback(title, cwd, useExternalConsole, commandArgs.ToList<string>(), env, success, failure); } } /// <summary> /// Registers callback to call when RunInTerminal is called /// </summary> /// <param name="runInTerminalCallback">Callback for RunInTerminal</param> public static void RegisterRunInTerminalCallback(Action<string, string, bool, List<string>, Dictionary<string, object>, Action<int?>, Action<string>> runInTerminalCallback) { Debug.Assert(runInTerminalCallback != null, "Callback should not be null."); s_runInTerminalCallback = runInTerminalCallback; } } } <|start_filename|>src/DebugEngineHost.VSCode/HostOutputWindow.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Diagnostics; namespace Microsoft.DebugEngineHost { public static class HostOutputWindow { private static Action<string> s_launchErrorCallback; public static void InitializeLaunchErrorCallback(Action<string> launchErrorCallback) { Debug.Assert(launchErrorCallback != null, "Bogus arguments to InitializeLaunchErrorCallback"); s_launchErrorCallback = launchErrorCallback; } public static void WriteLaunchError(string outputMessage) { if (s_launchErrorCallback != null) { s_launchErrorCallback(outputMessage); } } } } <|start_filename|>test/DebuggerTesting/OpenDebug/Commands/Responses/CompletionsResponseValue.cs<|end_filename|> // // Copyright (c) Microsoft. All rights reserved. // // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Newtonsoft.Json; namespace DebuggerTesting.OpenDebug.Commands.Responses { public sealed class CompletionItem { public string label; [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public string text; [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public string sortText; [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public string type; [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public int? start; [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public int? length; [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public int? selectionStart; [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public int? selectionLength; } public sealed class CompletionsResponseValue : CommandResponseValue { public sealed class Body { public CompletionItem[] targets; } public Body body = new Body(); } } <|start_filename|>test/CppTests/debuggees/kitchensink/src/expression.h<|end_filename|> #include <string> #include "feature.h" using namespace std; extern "C" void func(); int accumulate(int x); extern void (*callback)(); class Expression: public Feature { public: Expression(); virtual void CoreRun(); private: void checkCallStack(void(*callback)()); void checkPrettyPrinting(); void checkPrimitiveTypes(); void checkArrayAndPointers(); void checkClassOnStackAndHeap(); void checkSpecialValues(); void checkTreeOfValue(); }; namespace Test { class Student { public: string name; int age; Student(){} }; int max(int x, int y); double max(double, double y); } <|start_filename|>src/OpenDebugAD7/AD7Impl/AD7Guids.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace OpenDebugAD7.AD7Impl { internal static class AD7Guids { public static readonly Guid guidSourceHashMD5 = new Guid("406ea660-64cf-4c82-b6f0-42d48172a799"); public static readonly Guid guidSourceHashSHA1 = new Guid("ff1816ec-aa5e-4d10-87f7-6f4963833460"); public static readonly Guid guidSourceHashSHA256 = new Guid("8829d00f-11b8-4213-878b-770e8597ac16"); public static readonly Guid guidSourceHashSHA1Normalized = new Guid("1E090697-3EB3-4A01-B2F2-1336408F43C2"); public static readonly Guid guidSourceHashSHA256Normalized = new Guid("AE85F156-6530-4A56-BC1F-051B5D2816EA"); } } <|start_filename|>src/SSHDebugPS/PipeConnection.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Text; using System.Threading; using Microsoft.SSHDebugPS.Utilities; namespace Microsoft.SSHDebugPS { /// <summary> /// Abstract base class for connections based on a pipe connection to a command line tool (docker.exe, wsl.exe, etc) /// </summary> internal abstract class PipeConnection : Connection { private readonly object _lock = new object(); private Connection _outerConnection; private bool _isClosed; private readonly string _name; public override string Name => _name; protected Connection OuterConnection => _outerConnection; protected bool IsClosed => _isClosed; /// <summary> /// Create a new pipe connection object /// </summary> /// <param name="outerConnection">[Optional] the SSH connection (or maybe something else in future) used to connect to the target.</param> /// <param name="name">The full name of this connection</param> public PipeConnection(Connection outerConnection, string name) { Debug.Assert(!string.IsNullOrWhiteSpace(name)); _name = name; _outerConnection = outerConnection; } public override void Close() { _isClosed = true; if (_outerConnection != null) { _outerConnection.Close(); _outerConnection = null; } } public override string MakeDirectory(string path) { Debug.Assert(!string.IsNullOrWhiteSpace(path), nameof(path)); if (string.IsNullOrWhiteSpace(path)) { return string.Empty; } string command = "mkdir -p '{0}'".FormatInvariantWithArgs(path); // -p ignores if the directory is already there ExecuteCommand(command, Timeout.Infinite); return GetFullPath(path); } private string GetFullPath(string path) { string pwd = ExecuteCommand("pwd", Timeout.Infinite); string fullpath = ExecuteCommand($"cd '{path}'; pwd", Timeout.Infinite); ExecuteCommand($"cd '{pwd}'", Timeout.Infinite); return fullpath; } public override string GetUserHomeDirectory() { string commandOutput = ExecuteCommand("echo $HOME", Timeout.Infinite); return commandOutput.TrimEnd('\n', '\r'); } public override bool IsOSX() { return false; } public override bool IsLinux() { if (!ExecuteCommand("uname", Timeout.Infinite, commandOutput: out string commandOutput, errorMessage: out string errorMessage, out _)) { return false; } return commandOutput.StartsWith("Linux", StringComparison.OrdinalIgnoreCase); } /// <summary> /// Retrieves system information such as username and architecture /// </summary> /// <returns>SystemInformation containing username and architecture. If it was unable to obtain any of these, the value will be set to string.Empty.</returns> public SystemInformation GetSystemInformation() { string commandOutput; string errorMessage; int exitCode; string username = string.Empty; if (ExecuteCommand("id -u -n", Timeout.Infinite, commandOutput: out commandOutput, errorMessage: out errorMessage, exitCode: out exitCode)) { username = commandOutput; } string architecture = string.Empty; if (ExecuteCommand("uname -m", Timeout.Infinite, commandOutput: out commandOutput, errorMessage: out errorMessage, exitCode: out exitCode)) { architecture = commandOutput; } return new SystemInformation(username, architecture); } public override List<Process> ListProcesses() { SystemInformation systemInformation = GetSystemInformation(); List<Process> processes; string psErrorMessage; // Try using 'ps' first if (!PSListProcess(systemInformation, out psErrorMessage, out processes)) { string procErrorMessage; // try using the /proc file system if (!ProcFSListProcess(systemInformation, out procErrorMessage, out processes)) { StringBuilder sb = new StringBuilder(); sb.Append(psErrorMessage); sb.AppendLine(string.Empty); sb.AppendLine(procErrorMessage); VSMessageBoxHelper.PostErrorMessage(StringResources.Error_ProcessListFailedTitle, sb.ToString()); return new List<Process>(0); } } return processes; } /// <summary> /// Query 'ps' command for a list of processes /// </summary> private bool PSListProcess(SystemInformation systemInformation, out string errorMessage, out List<Process> processes) { errorMessage = string.Empty; string commandOutput; int exitCode; if (!ExecuteCommand(PSOutputParser.PSCommandLine, Timeout.Infinite, out commandOutput, out errorMessage, out exitCode)) { // Clear output and errorMessage commandOutput = string.Empty; errorMessage = string.Empty; if (!ExecuteCommand(PSOutputParser.AltPSCommandLine, Timeout.Infinite, out commandOutput, out errorMessage, out exitCode)) { if (exitCode == 127) { //command doesn't Exist errorMessage = StringResources.Error_PSMissing; } else { errorMessage = StringResources.Error_PSErrorFormat.FormatCurrentCultureWithArgs(exitCode, errorMessage); } processes = null; return false; } } processes = PSOutputParser.Parse(commandOutput, systemInformation); return true; } protected virtual string ProcFSErrorMessage => StringResources.Error_ProcFSError; /// <summary> /// Query /proc for a list of processes /// </summary> private bool ProcFSListProcess(SystemInformation systemInformation, out string errorMessage, out List<Process> processes) { errorMessage = string.Empty; processes = null; int exitCode; string commandOutput; if (!ExecuteCommand(ProcFSOutputParser.CommandText, Timeout.Infinite, out commandOutput, out errorMessage, out exitCode)) { errorMessage = ProcFSErrorMessage.FormatCurrentCultureWithArgs(errorMessage); return false; } processes = ProcFSOutputParser.Parse(commandOutput, systemInformation); return true; } } } <|start_filename|>test/DebuggerTesting/OpenDebug/Commands/Responses/ScopesResponseValue.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Newtonsoft.Json; namespace DebuggerTesting.OpenDebug.Commands.Responses { #region ScopesResponseValue public sealed class ScopesResponseValue : CommandResponseValue { public sealed class Body { public sealed class Scope { public Scope(string name, bool expensive) { this.name = name; this.expensive = expensive; } public bool expensive; public string name; [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public int? variablesReference; } public Scope[] scopes; } public Body body = new Body(); } #endregion internal class ScopesResponse : CommandResponse<ScopesResponseValue> { public ScopesResponse(string commandName) : base(commandName) { this.ExpectedResponse.body.scopes = new ScopesResponseValue.Body.Scope[] { new ScopesResponseValue.Body.Scope("Locals", false) }; } } } <|start_filename|>test/DebuggerTesting/Compilation/ClangCompiler.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using DebuggerTesting.Utilities; namespace DebuggerTesting.Compilation { internal sealed class ClangCompiler : GppStyleCompiler { public ClangCompiler(ILoggingComponent logger, ICompilerSettings settings) : base(logger, settings) { } protected override void SetAdditionalArguments(ArgumentBuilder builder) { base.SetAdditionalArguments(builder); DefineConstant(builder, "DEBUGGEE_COMPILER", "Clang"); } } } <|start_filename|>test/DebuggerTesting/Utilities/FileUtilities.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.IO; namespace DebuggerTesting.Utilities { internal class FileUtilities { public static void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs) { // Get the subdirectories for the specified directory. DirectoryInfo sourceDir = new DirectoryInfo(sourceDirName); if (!sourceDir.Exists) { throw new DirectoryNotFoundException( "Source directory does not exist or could not be found: " + sourceDirName); } // If the destination directory doesn't exist, create it. if (!Directory.Exists(destDirName)) { Directory.CreateDirectory(destDirName); } // Get the files in the directory and copy them to the new location. foreach (FileInfo file in sourceDir.GetFiles()) { file.CopyTo(Path.Combine(destDirName, file.Name), overwrite: true); } // If copying subdirectories, copy them and their contents to new location. if (copySubDirs) { foreach (DirectoryInfo subdir in sourceDir.GetDirectories()) { DirectoryCopy(subdir.FullName, Path.Combine(destDirName, subdir.Name), copySubDirs); } } } } } <|start_filename|>test/DebuggerTesting/Attribution/SupportedPlatformAttribute.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; namespace DebuggerTesting { /// <summary> /// Attribute used by xUnit theory test for specifying which platforms and platform architectures /// are required by the test. /// </summary> [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] public class SupportedPlatformAttribute : Attribute { #region Constructor public SupportedPlatformAttribute(SupportedPlatform platform, SupportedArchitecture architecture) { this.Architecture = architecture; this.Platform = platform; } #endregion #region Properties public SupportedArchitecture Architecture { get; private set; } public SupportedPlatform Platform { get; private set; } #endregion } } <|start_filename|>src/MIDebugEngine/AD7.Impl/AD7Expression.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Text; using Microsoft.VisualStudio.Debugger.Interop; using System.Threading.Tasks; using Microsoft.VisualStudio.Debugger.Interop.DAP; namespace Microsoft.MIDebugEngine { // This class represents a succesfully parsed expression to the debugger. // It is returned as a result of a successful call to IDebugExpressionContext2.ParseText // It allows the debugger to obtain the values of an expression in the debuggee. // For the purposes of this sample, this means obtaining the values of locals and parameters from a stack frame. public class AD7Expression : IDebugExpression2, IDebugExpressionDAP { private AD7Engine _engine; private IVariableInformation _var; internal AD7Expression(AD7Engine engine, IVariableInformation var) { _engine = engine; _var = var; } #region IDebugExpression2 Members // This method cancels asynchronous expression evaluation as started by a call to the IDebugExpression2::EvaluateAsync method. int IDebugExpression2.Abort() { throw new NotImplementedException(); } // This method evaluates the expression asynchronously. // This method should return immediately after it has started the expression evaluation. // When the expression is successfully evaluated, an IDebugExpressionEvaluationCompleteEvent2 // must be sent to the IDebugEventCallback2 event callback // // This is primarily used for the immediate window int IDebugExpression2.EvaluateAsync(enum_EVALFLAGS dwFlags, IDebugEventCallback2 pExprCallback) { if (((dwFlags & enum_EVALFLAGS.EVAL_NOSIDEEFFECTS) != 0 && (dwFlags & enum_EVALFLAGS.EVAL_ALLOWBPS) == 0) && _var.IsVisualized) { IVariableInformation variable = _engine.DebuggedProcess.Natvis.Cache.Lookup(_var); if (variable == null) { _var.AsyncError(pExprCallback, new AD7ErrorProperty(_var.Name, ResourceStrings.NoSideEffectsVisualizerMessage)); } else { _var = variable; // use the old value Task.Run(() => { new EngineCallback(_engine, pExprCallback).OnExpressionEvaluationComplete(variable); }); } } else { _var.AsyncEval(pExprCallback); } return Constants.S_OK; } // This method evaluates the expression synchronously. int IDebugExpression2.EvaluateSync(enum_EVALFLAGS dwFlags, uint dwTimeout, IDebugEventCallback2 pExprCallback, out IDebugProperty2 ppResult) { return EvaluateSyncInternal(dwFlags, DAPEvalFlags.NONE, dwTimeout, pExprCallback, out ppResult); } #endregion #region IDebugExpressionDAP int IDebugExpressionDAP.EvaluateSync(enum_EVALFLAGS dwFlags, DAPEvalFlags dapFlags, uint dwTimeout, IDebugEventCallback2 pExprCallback, out IDebugProperty2 ppResult) { return EvaluateSyncInternal(dwFlags, dapFlags, dwTimeout, pExprCallback, out ppResult); } #endregion private int EvaluateSyncInternal(enum_EVALFLAGS dwFlags, DAPEvalFlags dapFlags, uint dwTimeout, IDebugEventCallback2 pExprCallback, out IDebugProperty2 ppResult) { ppResult = null; if ((dwFlags & enum_EVALFLAGS.EVAL_NOSIDEEFFECTS) != 0 && _var.IsVisualized) { IVariableInformation variable = _engine.DebuggedProcess.Natvis.Cache.Lookup(_var); if (variable == null) { ppResult = new AD7ErrorProperty(_var.Name, ResourceStrings.NoSideEffectsVisualizerMessage); } else { _var = variable; ppResult = new AD7Property(_engine, _var); } return Constants.S_OK; } _var.SyncEval(dwFlags, dapFlags); ppResult = new AD7Property(_engine, _var); return Constants.S_OK; } } } <|start_filename|>test/DebuggerTesting/SupportedArchitecture.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; namespace DebuggerTesting { [Flags] public enum SupportedArchitecture { x86 = 0x1, x64 = 0x2, arm = 0x4 } } <|start_filename|>src/IOSDebugLauncher/RequestAuthHandler.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Security; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Threading.Tasks; namespace IOSDebugLauncher { internal class RequestAuthHandler : WebRequestHandler { /// <summary> /// Creates a new instance of the RequestAuthHandler class. /// </summary> public RequestAuthHandler() { this.ClientCertificateOptions = ClientCertificateOption.Automatic; this.UseDefaultCredentials = false; this.UseProxy = false; this.ServerCertificateValidationCallback = delegate (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { if (sslPolicyErrors == SslPolicyErrors.None) return true; if ((sslPolicyErrors & System.Net.Security.SslPolicyErrors.RemoteCertificateNameMismatch) != 0) { if (sender is HttpWebRequest) { var request2 = sender as HttpWebRequest; var requestUri = request2.RequestUri; if (requestUri.HostNameType == UriHostNameType.IPv4 || requestUri.HostNameType == UriHostNameType.IPv6 || requestUri.HostNameType == UriHostNameType.Dns) { X509Extension ext2 = (certificate as X509Certificate2).Extensions["Subject Alternative Name"]; if (ext2 != null) { string subjAltName = ext2.Format(false); if (subjAltName.IndexOf(requestUri.Host, StringComparison.OrdinalIgnoreCase) == -1) return false; } else return false; } else return false; } else if (sender is SslStream) { //nothing to do, fall through } else return false; } if ((sslPolicyErrors & System.Net.Security.SslPolicyErrors.RemoteCertificateChainErrors) != 0) { if (chain != null && chain.ChainStatus != null) { foreach (System.Security.Cryptography.X509Certificates.X509ChainStatus status in chain.ChainStatus) { if (status.Status == System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.UntrustedRoot) { // Self-signed certificates with an untrusted root are valid. continue; } else { if (status.Status != System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.NoError) { // If there are any other errors in the certificate chain, the certificate is invalid, // so the method returns false. return false; } } } return true; } } return false; }; } } } <|start_filename|>src/MIDebugPackage/Install.cmd<|end_filename|> @echo off setlocal if "%~1"=="-?" goto help if "%~1"=="/?" goto help if "%~1"=="" goto help if /i "%PROCESSOR_ARCHITECTURE%"=="amd64" call %SystemRoot%\SysWow64\cmd.exe /C %~dpf0 %* & goto eof if /i NOT "%PROCESSOR_ARCHITECTURE%"=="x86" echo ERROR: Unsupported processor - script should only be run on an x86 or x64 OS & exit /b -1 set ScriptDir=%~dp0 set InstallAction=Install set DestDir= :ArgLoopStart if "%~1"=="" goto ArgLoopDone if "%~1"=="/restore" set InstallAction=RestoreBackup& goto ArgOk set DestDir=%~1 if "%DestDir:~0,1%"=="/" echo ERROR: Unknown switch '%DestDir%'& exit /b -1 if "%DestDir:~0,1%"=="-" echo ERROR: Unknown switch '%DestDir%'& exit /b -1 goto ArgOk :ArgOk shift goto :ArgLoopStart :ArgLoopDone if "%DestDir%"=="" echo ERROR: Destination directory must be provided.& exit /b -1 if NOT exist "%DestDir%\Common7\IDE\devenv.exe" echo ERROR: Destination directory '%DestDir%' is incorrect. Specify the root to a VS install.& exit /b -1 REM make sure we are elevated net session >nul 2>&1 if NOT "%ERRORLEVEL%"=="0" echo ERROR: Must be called from an elevated command prompt.& exit /b -1 set BackupDir=%DestDir%\.MDDDebuggerBackup\ set MDDDebuggerDir=%DestDir%\Common7\IDE\CommonExtensions\Microsoft\MDD\Debugger\ set FilesToInstall=Microsoft.MICore.dll Microsoft.MIDebugEngine.dll Microsoft.MIDebugEngine.pkgdef Microsoft.MIDebugPackage.dll Microsoft.MIDebugPackage.pkgdef Microsoft.AndroidDebugLauncher.dll Microsoft.AndroidDebugLauncher.pkgdef Microsoft.IOSDebugLauncher.dll Microsoft.IOSDebugLauncher.pkgdef Microsoft.JDbg.dll Microsoft.DebugEngineHost.dll Microsoft.MICore.XmlSerializers.dll Microsoft.SSHDebugPS.dll Microsoft.SSHDebugPS.pkgdef OpenFolderSchema.json REM Add in the Facade assemblies we need to run on the desktop CLR if we are running in VS 2015. In VS 2017, Roslyn adds these, so don't add our own copy. if not exist "%DestDir%\Common7\IDE\PrivateAssemblies\System.Diagnostics.Process.dll" set FilesToInstall=%FilesToInstall% System.Diagnostics.Process.dll System.IO.FileSystem.dll System.IO.FileSystem.Primitives.dll System.Net.Security.dll System.Net.Sockets.dll System.Reflection.TypeExtensions.dll System.Runtime.InteropServices.RuntimeInformation.dll System.Security.Cryptography.X509Certificates.dll System.Threading.Thread.dll goto %InstallAction% :Install if exist "%BackupDir%" goto InstallFiles if not exist "%MDDDebuggerDir%" goto InstallFiles echo INFO: Backing up MDD Debugger to '%BackupDir%'. mkdir "%BackupDir%" set CopyError= for /f %%f in ('dir /b "%MDDDebuggerDir%"') do call :CopyFile "%MDDDebuggerDir%\%%f" "%BackupDir%" if NOT "%CopyError%"=="" echo ERROR: Failed to backup one or more files& echo.& exit /b -1 rem clean all files after backup call :CleanDebuggerDir goto InstallFiles :RestoreBackup if not exist "%BackupDir%" echo ERROR: No backup exists.& exit /b -1 if not exist "%MDDDebuggerDir%" mkdir "%MDDDebuggerDir%" echo Restoring from backup call :CleanDebuggerDir set CopyError= for /f %%f in ('dir /b "%BackupDir%"') do call :CopyFile "%BackupDir%\%%f" "%MDDDebuggerDir%" if NOT "%CopyError%"=="" echo ERROR: Failed to restore one or more files& echo.& exit /b -1 call :UpdateConfiguration echo MDD Debugger succesfully restored from backup goto eof :InstallFiles if not exist "%MDDDebuggerDir%" mkdir "%MDDDebuggerDir%" echo Installing Files set CopyError= for %%f in (%FilesToInstall%) do call :CopyFile "%ScriptDir%%%f" "%MDDDebuggerDir%" if NOT "%CopyError%"=="" echo ERROR: Failed to install one or more files& echo.& exit /b -1 call :UpdateConfiguration echo MDD Debugger succesfully installed goto eof rem %1 is file %2 is dest dir rem both must be quoted prior to calling copy file :CopyFile echo copy %1 %2 copy /y %1 %2 if NOT "%ERRORLEVEL%"=="0" set CopyError=1 goto eof :UpdateConfiguration call "%DestDir%\Common7\IDE\devenv.com" /updateconfiguration goto eof :CleanDebuggerDir pushd %MDDDebuggerDir% for %%f in (*) do del %%f popd goto eof :help set X86ProgFiles=%ProgramFiles(x86)% if "%X86ProgFiles%"=="" set X86ProgFiles=%ProgramFiles% echo Install.cmd [^/restore] ^<dest-dir^> echo. echo This script should be run on the test machine and it updates the MDD debugger echo bits to bits from the directory where the script is. echo. echo Example of installing to VS 2015: echo %0 "%X86ProgFiles%\Microsoft Visual Studio 14.0" echo. echo Example of installing to VS 2017: echo %0 "%X86ProgFiles%\Microsoft Visual Studio\2017\Enterprise" echo. echo Example of restoring VS 2017: echo %0 /restore "%X86ProgFiles%\Microsoft Visual Studio\2017\Enterprise" echo. :eof <|start_filename|>src/SSHDebugPS/LineBuffer.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Microsoft.SSHDebugPS { internal class LineBuffer { private readonly StringBuilder _textBuffer = new StringBuilder(); public LineBuffer() { } public void ProcessText(string unbufferedText, out IEnumerable<string> newLines) { List<string> newLineList = null; int startLength = _textBuffer.Length; _textBuffer.Append(unbufferedText); int newStartIndex = 0; for (int c = startLength; c < _textBuffer.Length; c++) { if (_textBuffer[c] == '\n') { int lineLength = c - newStartIndex; if (lineLength > 0 && _textBuffer[c - 1] == '\r') { lineLength--; } if (newLineList == null) { newLineList = new List<string>(); } string lineToAdd = _textBuffer.ToString(newStartIndex, lineLength); newLineList.Add(lineToAdd); newStartIndex = c + 1; } } if (newStartIndex > 0) { _textBuffer.Remove(0, newStartIndex); } newLines = newLineList ?? Enumerable.Empty<string>(); } } } <|start_filename|>src/OpenDebugAD7/AD7Impl/AD7Process.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.VisualStudio.Debugger.Interop; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace OpenDebugAD7.AD7Impl { internal sealed class AD7Process : IDebugProcess2 { public readonly AD_PROCESS_ID PhysicalProcessId; private readonly IDebugPort2 _port; private readonly Lazy<Guid> _processId = new Lazy<Guid>(() => Guid.NewGuid(), LazyThreadSafetyMode.PublicationOnly); internal AD7Process(IDebugPort2 port, AD_PROCESS_ID processId) { _port = port; this.PhysicalProcessId = processId; } public int Attach(IDebugEventCallback2 pCallback, Guid[] rgguidSpecificEngines, uint celtSpecificEngines, int[] rghrEngineAttach) { throw new NotImplementedException(); } public int CanDetach() { throw new NotImplementedException(); } public int CauseBreak() { throw new NotImplementedException(); } public int Detach() { throw new NotImplementedException(); } public int EnumPrograms(out IEnumDebugPrograms2 ppEnum) { throw new NotImplementedException(); } public int EnumThreads(out IEnumDebugThreads2 ppEnum) { throw new NotImplementedException(); } public int GetAttachedSessionName(out string pbstrSessionName) { throw new NotImplementedException(); } public int GetInfo(enum_PROCESS_INFO_FIELDS Fields, PROCESS_INFO[] pProcessInfo) { throw new NotImplementedException(); } public int GetName(enum_GETNAME_TYPE gnType, out string pbstrName) { throw new NotImplementedException(); } public int GetPhysicalProcessId(AD_PROCESS_ID[] pProcessId) { pProcessId[0] = this.PhysicalProcessId; return HRConstants.S_OK; } public int GetPort(out IDebugPort2 ppPort) { ppPort = _port; return HRConstants.S_OK; } public int GetProcessId(out Guid pguidProcessId) { pguidProcessId = _processId.Value; return HRConstants.S_OK; } public int GetServer(out IDebugCoreServer2 ppServer) { throw new NotImplementedException(); } public int Terminate() { throw new NotImplementedException(); } } } <|start_filename|>test/DebuggerTesting/OpenDebug/Commands/VariablesCommand.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using DebuggerTesting.OpenDebug.Commands.Responses; namespace DebuggerTesting.OpenDebug.Commands { public sealed class VariablesCommandArgs : JsonValue { public int variablesReference; } public class VariablesCommand : CommandWithResponse<VariablesCommandArgs, VariablesResponseValue> { public VariablesCommand(int variablesRefernce) : base("variables") { this.Args.variablesReference = variablesRefernce; } } } <|start_filename|>src/IOSDebugLauncher/Telemetry.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.DebugEngineHost; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace IOSDebugLauncher { /// <summary> /// Class for sending telemetry /// </summary> internal static class Telemetry { private const string Event_LaunchError = @"VS/Diagnostics/Debugger/iOS/LaunchFailure"; private const string Property_LaunchErrorResult = @"VS.Diagnostics.Debugger.iOS.FailureResult"; private const string Property_LaunchErrorTarget = @"VS.Diagnostics.Debugger.iOS.Target"; private const string Event_VcRemoteClientError = @"VS/Diagnostics/Debugger/iOS/VcRemoteClientFailure"; private const string Property_VcRemoteClientErrorResult = @"VS.Diagnostics.Debugger.iOS.VcRemoteClientFailureResult"; #region LaunchFailure support public enum LaunchFailureCode { /// <summary> /// Indicates that the error shouldn't be sent to telemetry /// </summary> NoReport, /// <summary> /// No error, launch is success /// </summary> LaunchSuccess, /// <summary> /// Launch failed for unkown reason /// </summary> LaunchFailure, /// <summary> /// vcremote is returning json that cannot be parsed correctly /// </summary> BadJson, /// <summary> /// vcremote was unable to return a remote path for the given packageID /// </summary> BadPackageId, }; public enum VcRemoteFailureCode { /// <summary> /// Indicates no error occured when calling vcremote /// </summary> VcRemoteSucces, /// <summary> /// Unable to access vcremote due to bad authorization (certificate issue) /// </summary> VcRemoteUnauthorized, /// <summary> /// Unable to reach vcremote for some reason /// </summary> VcRemoteNoConnection, /// <summary> /// Unknown Error from vcremote /// </summary> VcRemoteUnkown, } public static void SendLaunchError(string failureCode, IOSDebugTarget target) { HostTelemetry.SendEvent(Event_LaunchError, new KeyValuePair<string, object>(Property_LaunchErrorResult, failureCode), new KeyValuePair<string, object>(Property_LaunchErrorTarget, target.ToString()) ); } public static void SendVcRemoteClientError(string failureCode) { HostTelemetry.SendEvent(Event_VcRemoteClientError, new KeyValuePair<string, object>(Property_VcRemoteClientErrorResult, failureCode)); } #endregion } } <|start_filename|>src/AndroidDebugLauncher/PwdOutputParser.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AndroidDebugLauncher { internal static class PwdOutputParser { public static string ExtractWorkingDirectory(string commandOutput, string packageName) { IEnumerable<string> allLines = commandOutput.GetLines(); // Linux will allow just about anything in a directory name as long as it is excaped. Android is much // more picky about package names. Let's reject characters which are invalid in a package name, highly // unlikely that any Android distribution would decide to use in the base directory, and likely to show // up in any debug spew we should ignore. char[] invalidPackageNameChars = { ' ', '\t', '*', '[', ']', '(', ')', '{', '}', ':' }; // run-as is giving debug spew on a Galaxy S6, so we need to look at all the lines, and find the one that could be the working directory IEnumerable<string> workingDirectoryLines = allLines.Where( line => line.Length > 0 && line[0] == '/' && line.IndexOfAny(invalidPackageNameChars) < 0 ); if (workingDirectoryLines.Count() == 1) { return workingDirectoryLines.Single(); } RunAsOutputParser.ThrowIfRunAsErrors(commandOutput, packageName); throw new LauncherException(Telemetry.LaunchFailureCode.BadPwdOutput, string.Format(CultureInfo.CurrentCulture, LauncherResources.Error_ShellCommandBadResults, "pwd")); } } } <|start_filename|>src/SSHDebugPS/IPipeTransportSettings.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.SSHDebugPS { /// <summary> /// This interface returns the tranport's executalbe command and the base set of arguments to use. /// </summary> public interface IPipeTransportSettings { string CommandArgs { get; } string Command { get; } } } <|start_filename|>src/OpenDebugAD7/LanguageUtilities.cs<|end_filename|> // // Copyright (c) Microsoft. All rights reserved. // // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Linq; namespace OpenDebugAD7 { internal static class LanguageUtilities { /// <summary> /// This method does a simple validation on the input 'identifier'. /// </summary> /// <param name="identifier">the identifier to validate</param> /// <returns>'true' if this is a valid identifier name. 'false' if otherwise.</returns> public static bool IsValidIdentifier(string identifier) { // Check to see if identifier is null or blank. if (string.IsNullOrWhiteSpace(identifier)) { return false; } /* * Most languages require the first character in the indentifier not be a number. * * Languages: * - C * - C++ * - Rust * - Python */ string digits = "0123456789"; if (digits.Contains(identifier[0], StringComparison.Ordinal)) { return false; } /* * Check to see if we got an '=' if the user is trying to do a * comparison on a non-existant psuedo variable like 'name'. */ if (identifier.Where(c => c == '=').Any()) { return false; } return true; } } } <|start_filename|>test/DebuggerTesting/IDebuggerSettings.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; namespace DebuggerTesting { /// <summary> /// Interface describing the settings used to debug a debuggee. /// </summary> public interface IDebuggerSettings { #region Properties SupportedArchitecture DebuggeeArchitecture { get; } string DebuggerName { get; } SupportedDebugger DebuggerType { get; } string DebuggerPath { get; } string DebuggerAdapterPath { get; } string MIMode { get; } IDictionary<string, string> Properties { get; } #endregion } } <|start_filename|>test/DebugAdapterRunner/OpenDebug/DAPConstants.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace OpenDebug { internal static class DAPConstants { public const string TwoCrLf = "\r\n\r\n"; public const string ContentLength = "Content-Length: "; } } <|start_filename|>test/CppTests/debuggees/exception/src/exception.h<|end_filename|> class myException { public: int RaisedUnhandledException(int a); int RaisedHandledException(int b); int EvalFunc(int a, int b); int RecursiveFunc(int a); void RaisedThrowNewException(); void RaisedReThrowException(); }; class newException { public: int code; newException(int c); ~newException(); }; <|start_filename|>src/OpenDebugAD7/ErrorBuilder.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Globalization; using Microsoft.VisualStudio.Debugger.Interop; using OpenDebug; namespace OpenDebugAD7 { internal class ErrorBuilder { public readonly Func<string> ScenarioStringFactory; public ErrorBuilder(Func<string> scenarioStringFactory) { ScenarioStringFactory = scenarioStringFactory; } public void CheckHR(int hr) { if (hr < 0) { ThrowHR(hr); } } public void CheckOutput<T>(T value) where T : class { if (value == null) { ThrowMissingOutParam(); } } public void ThrowHR(int hr) { throw new AD7Exception(ScenarioStringFactory(), GetErrorDescription(hr)); } public static string GetErrorDescription(int hr) { // The error messages here are based on the codes that the MIEngine can return plus a few others that seem likely // that some other engine would want to return. switch (hr) { case HRConstants.E_NOTIMPL: return new NotImplementedException().Message; case HRConstants.COMQC_E_BAD_MESSAGE: return AD7Resources.Msg_COMQC_E_BAD_MESSAGE; case HRConstants.RPC_E_SERVERFAULT: return AD7Resources.Msg_RPC_E_SERVERFAULT; case HRConstants.RPC_E_DISCONNECTED: return AD7Resources.Msg_RPC_E_DISCONNECTED; case HRConstants.E_ACCESSDENIED: return AD7Resources.Msg_E_ACCESSDENIED; // The description for these messages are useless, so do what vsdebug does and return nothing for these case HRConstants.E_FAIL: case HRConstants.E_INVALIDARG: return string.Empty; case HRConstants.E_CRASHDUMP_UNSUPPORTED: return AD7Resources.Msg_E_CRASHDUMP_UNSUPPORTED; default: return string.Format(CultureInfo.CurrentCulture, AD7Resources.Msg_UnknownError, hr); } } private void ThrowMissingOutParam() { throw new AD7Exception(ScenarioStringFactory(), AD7Resources.Error_MissingOutParam); } internal string GetMessageForException(Exception e) { if (e is AD7Exception) { return e.Message; } else { return string.Format(CultureInfo.CurrentCulture, ScenarioStringFactory(), Utilities.GetExceptionDescription(e)); } } } } <|start_filename|>test/DebuggerTesting/OpenDebug/Commands/ScopesCommand.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using DebuggerTesting.OpenDebug.Commands.Responses; namespace DebuggerTesting.OpenDebug.Commands { public sealed class ScopesArgs : JsonValue { public int frameId; } public class ScopesCommand : CommandWithResponse<ScopesArgs, ScopesResponseValue> { public ScopesCommand(int frameId) : base("scopes") { this.Args.frameId = frameId; this.ExpectedResponse = new ScopesResponse(this.Name); } public int VariablesReference { get; private set; } public override void ProcessActualResponse(IActualResponse response) { base.ProcessActualResponse(response); this.VariablesReference = this.ActualResponse?.body?.scopes?[0]?.variablesReference ?? -1; } } } <|start_filename|>src/MICoreUnitTests/BasicLaunchOptionsTests.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using MICore; using Xunit; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Collections.ObjectModel; using System.Xml.Serialization; namespace MICoreUnitTests { public class BasicLaunchOptionsTests { [Fact] public void TestLaunchOptions_Local1() { string fakeFilePath = typeof(BasicLaunchOptionsTests).Assembly.Location; string content = string.Concat("<LocalLaunchOptions xmlns=\"http://schemas.microsoft.com/vstudio/MDDDebuggerOptions/2014\"\n", "MIDebuggerPath=\"", fakeFilePath, "\"\n", "MIDebuggerServerAddress=\"myserverbox:345\"\n", "ExePath=\"", fakeFilePath, "\"\n", "TargetArchitecture=\"arm\"\n", "/>"); var baseOptions = GetLaunchOptions(content); Assert.IsAssignableFrom<LocalLaunchOptions>(baseOptions); var options = (LocalLaunchOptions)baseOptions; Assert.Equal(options.MIDebuggerPath, fakeFilePath); Assert.Equal("myserverbox:345", options.MIDebuggerServerAddress); Assert.Equal(options.ExePath, fakeFilePath); Assert.Equal(TargetArchitecture.ARM, options.TargetArchitecture); Assert.True(string.IsNullOrEmpty(options.AdditionalSOLibSearchPath)); Assert.True(string.IsNullOrEmpty(options.AbsolutePrefixSOLibSearchPath)); Assert.Equal(MIMode.Gdb, options.DebuggerMIMode); Assert.Equal(LaunchCompleteCommand.ExecRun, options.LaunchCompleteCommand); Assert.Null(options.CustomLaunchSetupCommands); Assert.True(options.SetupCommands != null && options.SetupCommands.Count == 0); Assert.True(String.IsNullOrEmpty(options.CoreDumpPath)); Assert.False(options.UseExternalConsole); Assert.False(options.IsCoreDump); } [Fact] public void TestLaunchOptions_Pipe1() { string fakeFilePath = typeof(BasicLaunchOptionsTests).Assembly.Location; string content = string.Concat("<PipeLaunchOptions xmlns=\"http://schemas.microsoft.com/vstudio/MDDDebuggerOptions/2014\"\n", "PipePath=\"", fakeFilePath, "\"\n", "ExePath=\"/home/user/myname/foo\" ExeArguments=\"arg1 arg2\"\n", "TargetArchitecture=\"AMD64\"\n", "WorkingDirectory=\"/home/user/myname\"\n", ">\n", " <SetupCommands>\n", " <Command>-gdb-set my-example-setting on</Command>\n", " </SetupCommands>\n", "</PipeLaunchOptions>"); var baseOptions = GetLaunchOptions(content); Assert.IsAssignableFrom<PipeLaunchOptions>(baseOptions); var options = (PipeLaunchOptions)baseOptions; Assert.Equal(options.PipePath, fakeFilePath); Assert.Null(options.PipeCwd); Assert.Equal("/home/user/myname/foo", options.ExePath); Assert.Equal("arg1 arg2", options.ExeArguments); Assert.Equal(TargetArchitecture.X64, options.TargetArchitecture); Assert.True(string.IsNullOrEmpty(options.AdditionalSOLibSearchPath)); Assert.True(string.IsNullOrEmpty(options.AbsolutePrefixSOLibSearchPath)); Assert.Equal(MIMode.Gdb, options.DebuggerMIMode); Assert.Equal(LaunchCompleteCommand.ExecRun, options.LaunchCompleteCommand); Assert.True(options.CustomLaunchSetupCommands == null); Assert.True(options.SetupCommands != null && options.SetupCommands.Count == 1); Assert.True(options.SetupCommands[0].IsMICommand); Assert.Equal("-gdb-set my-example-setting on", options.SetupCommands[0].CommandText); Assert.Contains("gdb-set", options.SetupCommands[0].Description, StringComparison.Ordinal); Assert.False(options.SetupCommands[0].IgnoreFailures); Assert.True(options.PipeEnvironment.Count == 0); } [Fact] public void TestLaunchOptions_Pipe2() { // Test for: // MIMode=lldb // Having commands in CustomLaunchSetupCommands // Specifying the LaunchCompleteCommand string fakeFilePath = typeof(BasicLaunchOptionsTests).Assembly.Location; string content = string.Concat("<PipeLaunchOptions xmlns=\"http://schemas.microsoft.com/vstudio/MDDDebuggerOptions/2014\"\n", "PipePath=\"", fakeFilePath, "\"\n", "PipeCwd=\"/home/user/my program/src\"\n", "ExePath=\"/home/user/myname/foo\"\n", "TargetArchitecture=\"x86_64\"\n", "AbsolutePrefixSOLibSearchPath='/system/bin'\n", "AdditionalSOLibSearchPath='/a/b/c;/a/b/c'\n", "MIMode='lldb'\n", ">\n", " <CustomLaunchSetupCommands>\n", " <Command Description='Example description'>Example command</Command>\n", " </CustomLaunchSetupCommands>\n", " <LaunchCompleteCommand>None</LaunchCompleteCommand>\n", " <PipeEnvironment>\n", " <EnvironmentEntry Name='PipeVar1' Value='PipeValue1' />\n", " </PipeEnvironment>\n", "</PipeLaunchOptions>"); var baseOptions = GetLaunchOptions(content); Assert.IsAssignableFrom<PipeLaunchOptions>(baseOptions); var options = (PipeLaunchOptions)baseOptions; Assert.Equal(options.PipePath, fakeFilePath); Assert.Equal("/home/user/my program/src", options.PipeCwd); Assert.Equal("/home/user/myname/foo", options.ExePath); Assert.Equal(TargetArchitecture.X64, options.TargetArchitecture); Assert.Equal("/system/bin", options.AbsolutePrefixSOLibSearchPath); string[] searchPaths = options.GetSOLibSearchPath().ToArray(); Assert.Equal(2, searchPaths.Length); Assert.Equal("/home/user/myname", searchPaths[0]); Assert.Equal("/a/b/c", searchPaths[1]); Assert.Equal(MIMode.Lldb, options.DebuggerMIMode); Assert.True(options.SetupCommands != null && options.SetupCommands.Count == 0); Assert.True(options.CustomLaunchSetupCommands != null && options.CustomLaunchSetupCommands.Count == 1); var command = options.CustomLaunchSetupCommands[0]; Assert.False(command.IsMICommand); Assert.Equal("Example command", command.CommandText); Assert.Equal("Example description", command.Description); Assert.Equal(LaunchCompleteCommand.None, options.LaunchCompleteCommand); Assert.Equal("PipeVar1", options.PipeEnvironment.First().Name); Assert.Equal("PipeValue1", options.PipeEnvironment.First().Value); } // TODO this test is broken by a bug: the assembly binder only searches the unit test // project's output directory for dependencies and thus won't find assemblies in the // package cache. This can be worked around by moving the missing assembly // (System.Net.Security) to that directory. [Fact] public void TestLaunchOptions_Tcp1() { // Tests for: // TcpLaunchOptions // Using CustomLaunchSetupCommands without specifying a namespace // Using CustomLaunchSetupCommands/LaunchCompleteCommand like an attach string content = @"<TcpLaunchOptions Hostname=""destinationComputer"" Port=""1234"" ExePath=""/a/b/c"" TargetArchitecture=""ARM""> <CustomLaunchSetupCommands> <Command IgnoreFailures=""false"" Description=""Attaching to the 'foo' process"">-target-attach 1234</Command> </CustomLaunchSetupCommands> <LaunchCompleteCommand>exec-continue</LaunchCompleteCommand> </TcpLaunchOptions>"; var baseOptions = GetLaunchOptions(content); Assert.IsAssignableFrom<TcpLaunchOptions>(baseOptions); var options = (TcpLaunchOptions)baseOptions; Assert.Equal("/a/b/c", options.ExePath); Assert.Equal(TargetArchitecture.ARM, options.TargetArchitecture); Assert.Equal(MIMode.Gdb, options.DebuggerMIMode); Assert.True(options.SetupCommands != null && options.SetupCommands.Count == 0); Assert.True(options.CustomLaunchSetupCommands != null && options.CustomLaunchSetupCommands.Count == 1); var command = options.CustomLaunchSetupCommands[0]; Assert.True(command.IsMICommand); Assert.Equal("-target-attach 1234", command.CommandText); Assert.Equal("Attaching to the 'foo' process", command.Description); Assert.Equal(LaunchCompleteCommand.ExecContinue, options.LaunchCompleteCommand); } [Fact] public void TestLaunchOptions_Tcp2() { // Test for missing port attribute string content = @"<TcpLaunchOptions Hostname=""destinationComputer"" ExePath=""/a/b/c"" TargetArchitecture=""ARM""/>"; try { GetLaunchOptions(content); Assert.True(false, "Should be unreachable"); } catch (InvalidLaunchOptionsException e) { Assert.Contains("Port", e.Message, StringComparison.Ordinal); } } [Fact] public void TestLaunchOptions_BadXml1() { // Test bad XML (extra close element) string content = @"<TcpLaunchOptions/></TcpLaunchOptions>"; try { GetLaunchOptions(content); Assert.True(false, "Should be unreachable"); } catch (InvalidLaunchOptionsException e) { Assert.StartsWith("Launch options", e.Message, StringComparison.Ordinal); } } [Fact] public void TestLaunchOptions_BadXml2() { // Test for missing port attribute string content = @"<ThisIsNotAKnownType/>"; try { GetLaunchOptions(content); Assert.True(false, "Should be unreachable"); } catch (InvalidLaunchOptionsException e) { Assert.StartsWith("Launch options", e.Message, StringComparison.Ordinal); } } [Fact] public void TestLaunchOptions_BadXml3() { // Tests for: // TcpLaunchOptions // Using CustomLaunchSetupCommands without specifying a namespace // Using CustomLaunchSetupCommands/LaunchCompleteCommand like an attach string content = @"<TcpLaunchOptions xmlns=""http://schemas.microsoft.com/ThisIsABogusNamespace"" Hostname =""destinationComputer"" Port=""1234"" ExePath=""/a/b/c"" TargetArchitecture=""ARM""/>"; try { GetLaunchOptions(content); Assert.True(false, "Should be unreachable"); } catch (InvalidLaunchOptionsException e) { Assert.StartsWith("Launch options", e.Message, StringComparison.Ordinal); } } /// <summary> /// Compilation test, do not execute. /// Verify that types relied upon by launcher extensions are exported by MIEngine in current build. /// Don't change this test without checking with C++ team. /// </summary> internal void VerifyCoreApisPresent() { LaunchOptions launchOptions = new LocalLaunchOptions("/usr/bin/gdb", "10.10.10.10:2345"); launchOptions.ExePath = @"c:\users\me\myapp.out"; launchOptions.AdditionalSOLibSearchPath = @"c:\temp;e:\foo\bar"; launchOptions.TargetArchitecture = TargetArchitecture.ARM; launchOptions.WorkingDirectory = "/home/user"; launchOptions.DebuggerMIMode = MIMode.Gdb; launchOptions.WaitDynamicLibLoad = false; launchOptions.VisualizerFile = @"c:\myproject\file.natvis"; launchOptions.SourceMap = new ReadOnlyCollection<SourceMapEntry>(new List<SourceMapEntry>()); launchOptions.Environment = new ReadOnlyCollection<EnvironmentEntry>(new List<EnvironmentEntry>()); Microsoft.DebugEngineHost.HostConfigurationStore configStore = null; IDeviceAppLauncherEventCallback eventCallback = null; IPlatformAppLauncher iLauncher = null; IPlatformAppLauncherSerializer iSerializer = null; iLauncher.Initialize(configStore, eventCallback); iLauncher.OnResume(); iLauncher.SetLaunchOptions(string.Empty, string.Empty, string.Empty, (object)null, TargetEngine.Native); iLauncher.SetupForDebugging(out launchOptions); iLauncher.Dispose(); XmlSerializer serializer = iSerializer.GetXmlSerializer("foobar"); } private LaunchOptions GetLaunchOptions(string content) { return LaunchOptions.GetInstance(null, "bogus-exe-path", null, null, content, false, null, TargetEngine.Native, null); } } } <|start_filename|>test/CppTests/debuggees/kitchensink/src/global.h<|end_filename|> #pragma once #define STRINGIFY2( x) #x #define STRINGIFY(x) STRINGIFY2(x) #if DEBUGGEE_ARCH==32 #define ARCH "x86" #elif DEBUGGEE_ARCH==64 #define ARCH "x64" #elif DEBUGGEE_ARCH==arm #define ARCH "arm" #else #define ARCH "Unknown" #endif <|start_filename|>test/DebuggerTesting/Utilities/ArgumentBuilder.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Text; namespace DebuggerTesting.Utilities { /// <summary> /// A class that builds an arguments string /// </summary> public class ArgumentBuilder { #region Constructor /// <summary> /// Constructs a new argument builder /// </summary> /// <param name="prefix">String to use in front of the name portion of an argument.</param> /// <param name="suffix">String to use in between the name and value portions of an argument.</param> public ArgumentBuilder(string prefix, string suffix) { this.builder = new StringBuilder(); this.prefix = prefix; this.suffix = suffix; } #endregion #region Methods /// <summary> /// Appends an argument value to the builder /// </summary> public void AppendArgument(string value) { if (!String.IsNullOrWhiteSpace(value)) { this.builder.Append(" "); this.builder.Append(value); } } /// <summary> /// Appends an argument value with surrounding quotes to the builder /// </summary> public void AppendArgumentQuoted(string value) { if (!String.IsNullOrWhiteSpace(value)) this.AppendArgument("\"" + value + "\""); } /// <summary> /// Appends an argument name to the builder /// </summary> private void AppendName(string name) { Parameter.ThrowIfNullOrWhiteSpace(name, nameof(name)); builder.Append(" "); if (!String.IsNullOrEmpty(this.prefix)) { builder.Append(this.prefix); } builder.Append(name); } /// <summary> /// Appends an argument name and value to the builder /// </summary> public void AppendNamedArgument(string name, string value, string overrideSuffix = null) { Parameter.ThrowIfNullOrWhiteSpace(name, nameof(name)); this.AppendName(name); if (!String.IsNullOrWhiteSpace(value)) { string suffix = overrideSuffix ?? this.suffix; if (!String.IsNullOrEmpty(suffix)) { builder.Append(suffix); } this.builder.Append(value); } } /// <summary> /// Appends an argument name and value with surrounding quotes to the builder /// </summary> public void AppendNamedArgumentQuoted(string name, string value, string overrideSuffix = null) { Parameter.ThrowIfNullOrWhiteSpace(name, nameof(name)); if (!String.IsNullOrWhiteSpace(value)) this.AppendNamedArgument(name, ArgumentBuilder.MakeQuoted(value), overrideSuffix); } public static string MakeQuotedIfRequired(string value) { if (value.Contains("\"") || value.Contains("'") || value.Contains(" ")) return MakeQuoted(value); return value; } public static string MakeQuoted(string value) { if (null == value) return null; return "\"" + value.Replace("\"", "\\\"") + "\""; } /// <summary> /// Renders the argument string from the builder /// </summary> public override string ToString() { return this.builder?.ToString().Trim(); } #endregion #region Fields private StringBuilder builder = null; private string prefix = null; private string suffix = null; #endregion } } <|start_filename|>src/DebugEngineHost.VSCode/Logger.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using System.Threading.Tasks; namespace Microsoft.DebugEngineHost { /// <summary> /// VS Code only class to write to the log. This is enabled through the '--engineLogging[=file]' command line argument. /// </summary> public static class Logger { public static void WriteFrame([CallerMemberName]string caller = null) { CoreWrite(caller); } public static void WriteLine(string s) { CoreWrite(s); } private static void CoreWrite(string line) { HostLogger.Instance?.WriteLine(line); } } } <|start_filename|>test/DebuggerTesting/OpenDebug/Events/OutputEvent.cs<|end_filename|> // // Copyright (c) Microsoft. All rights reserved. // // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; namespace DebuggerTesting.OpenDebug.Events { public enum CategoryValue { Console = 0, Stdout = 1, Stderr = 2, Telemetry = 3, Unknown = Int32.MaxValue } public sealed class OutputEventValue : EventValue { public sealed class Body { public string output; public string category; } public Body body = new Body(); } public sealed class OutputEvent : Event<OutputEventValue> { public OutputEvent(string text, CategoryValue category, bool ignoreResponseOrder) : base("output") { this.IgnoreResponseOrder = ignoreResponseOrder; this.ExpectedResponse.body.category = GetCategory(category); this.ExpectedResponse.body.output = text; } private static string GetCategory(CategoryValue category) { Parameter.ThrowIfIsInvalid(category, CategoryValue.Unknown, nameof(category)); return category.ToString().ToLowerInvariant(); } } } <|start_filename|>test/Android/BreakPointWhenTrueCondition/BreakPointWhenTrueCondition/BreakPointWhenTrueCondition.NativeActivity/Source1.cpp<|end_filename|> #include "Header1.h" int Func1() { int i = 1; int sum = 0; MyClass myClass; myClass.isTrue = true; for (; i < 10; i++) { sum = sum + i; } return sum; } void Func() { Func1(); return; } <|start_filename|>src/SSHDebugPS/CommandRunner.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Diagnostics; using System.IO; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.VisualStudio.Debugger.Interop.UnixPortSupplier; namespace Microsoft.SSHDebugPS { internal class ErrorOccuredEventArgs : EventArgs { private string _errorMessage = null; public ErrorOccuredEventArgs(Exception e) { Exception = e; } public ErrorOccuredEventArgs(string message) { _errorMessage = message; } public string ErrorMessage { get => !string.IsNullOrWhiteSpace(_errorMessage) ? _errorMessage : Exception.Message; } public Exception Exception { get; } } internal interface ICommandRunner : IDisposable { event EventHandler<string> OutputReceived; event EventHandler<int> Closed; event EventHandler<ErrorOccuredEventArgs> ErrorOccured; void Start(); void Write(string text); void WriteLine(string text); } /// <summary> /// Run a single command on Windows. This reads output as ReadLine. Run needs to be called to run the command. /// </summary> internal class LocalCommandRunner : ICommandRunner { protected const int BUFMAX = 4096; protected ProcessStartInfo ProcessStartInfo { get; } private System.Diagnostics.Process _process; private byte _readerCompleteCount = 0; private bool _processExited = false; private StreamWriter _stdInWriter; private StreamReader _stdOutReader; private StreamReader _stdErrReader; private readonly object _lock = new object(); public event EventHandler<string> OutputReceived; public event EventHandler<int> Closed; public event EventHandler<ErrorOccuredEventArgs> ErrorOccured; protected bool IsDisposeStarted => _process == null; public LocalCommandRunner(IPipeTransportSettings settings) : this(settings.Command, settings.CommandArgs) { } public LocalCommandRunner(string command, string commandArgs) { ProcessStartInfo = new ProcessStartInfo(command, commandArgs); ProcessStartInfo.RedirectStandardError = true; ProcessStartInfo.RedirectStandardInput = true; ProcessStartInfo.RedirectStandardOutput = true; ProcessStartInfo.UseShellExecute = false; ProcessStartInfo.CreateNoWindow = true; } public static LocalCommandRunner CreateInstance(bool handleRawOutput, IPipeTransportSettings settings) { return CreateInstance(handleRawOutput, settings.Command, settings.CommandArgs); } public static LocalCommandRunner CreateInstance(bool handleRawOutput, string command, string args) { if (handleRawOutput) { return new RawLocalCommandRunner(command, args); } else { return new LocalCommandRunner(command, args); } } public void Start() { ThrowIfDisposed(); lock (_lock) { _process = new System.Diagnostics.Process(); _process.StartInfo = this.ProcessStartInfo; _process.Exited += OnProcessExited; _process.EnableRaisingEvents = true; _process.Start(); _stdInWriter = new StreamWriter(_process.StandardInput.BaseStream, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false), BUFMAX); _stdOutReader = new StreamReader(_process.StandardOutput.BaseStream, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false), false, BUFMAX); _stdErrReader = new StreamReader(_process.StandardError.BaseStream, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false), false, BUFMAX); _ = ReadStdOutAsync(_stdOutReader); _ = ReadLoopAsync(_stdErrReader, OnErrorReceived); } } public void Write(string text) { ThrowIfDisposed(); lock (_lock) { EnsureRunning(); _stdInWriter.Write(text); _stdInWriter.Flush(); } } public void WriteLine(string text) { ThrowIfDisposed(); lock (_lock) { EnsureRunning(); _stdInWriter.WriteLine(text); _stdInWriter.Flush(); } } protected void ReportException(Exception ex) { ErrorOccured?.Invoke(this, new ErrorOccuredEventArgs(ex)); } private void OnProcessExited(object sender, EventArgs args) { bool shouldClose = false; lock (_lock) { Debug.Assert(_processExited == false, "ProcessExit shouldn't be set more than once"); _processExited = true; shouldClose = _readerCompleteCount == 2; } if (shouldClose) { Closed?.Invoke(this, _process.ExitCode); } } protected virtual void OnErrorReceived(string error) { ErrorOccured?.Invoke(this, new ErrorOccuredEventArgs(error)); } protected virtual Task ReadStdOutAsync(StreamReader stdOutReader) { return ReadLoopAsync(stdOutReader, OnOutputReceived); } protected void OnOutputReceived(string line) { OutputReceived?.Invoke(this, line); } private async Task ReadLoopAsync(StreamReader reader, Action<string> action) { try { while (!this.IsDisposeStarted) { string line = await reader.ReadLineAsync().ConfigureAwait(false); if (this.IsDisposeStarted) { // Dispose was called return; } if (line == null) { OnReaderComplete(); return; // end of stream } action(line); } } catch (Exception e) { if (!this.IsDisposeStarted) // ignore exceptions if we are disposing { ReportException(e); Dispose(); } } } protected void OnReaderComplete() { bool shouldClose = false; lock (_lock) { Debug.Assert(_readerCompleteCount < 2, "OnReaderComplete should not be called more than twice"); _readerCompleteCount++; shouldClose = _readerCompleteCount == 2 && _processExited; } if (shouldClose) { Closed?.Invoke(this, _process.ExitCode); } } private void EnsureRunning() { if (_process == null || _process.HasExited) { throw new InvalidOperationException(StringResources.Error_ShellNotRunning); } } private void CleanUpProcess() { if (_process != null) { lock (_lock) { System.Diagnostics.Process process = _process; if (process != null) { _process = null; if (!process.HasExited) { try { process.Kill(); } catch (Exception) { // Process may already be dead } } // clean up event handlers. process.Exited -= OnProcessExited; _stdInWriter.Close(); _stdInWriter = null; _stdOutReader.Close(); _stdOutReader = null; _stdErrReader.Close(); _stdErrReader = null; process.Close(); } } } } #region IDisposable Support private bool _disposedValue = false; // To detect redundant calls protected virtual void Dispose(bool disposing) { if (!_disposedValue) { if (disposing) { CleanUpProcess(); } _disposedValue = true; } } public void Dispose() { // Do not change this code. Put cleanup code in Dispose(bool disposing) above. Dispose(true); } protected void ThrowIfDisposed() { if (_disposedValue) { throw new ObjectDisposedException("LocalCommandRunner"); } } #endregion } /// <summary> /// Launches a local command where the OutputReceived event is fired with the raw line ending characters /// </summary> internal class RawLocalCommandRunner : LocalCommandRunner { public RawLocalCommandRunner(string command, string args) : base(command, args) { } protected override Task ReadStdOutAsync(StreamReader stdOutReader) { // Async reads against the stream aren't completing even though data is available, possibly because PineZorro // is using `.Result` on an I/O object. So use a dedicated thread instead. TaskCompletionSource<object> tcs = new TaskCompletionSource<object>(); // We shouldn't need a full stack for this thread, so reduce the stack size to 256KB const int stackSize = 256 * 1024; var thread = new Thread(() => { SyncReadStdOut(stdOutReader); tcs.SetResult(null); }, stackSize); thread.Name = string.Concat("SSHDebugPS: ", Path.GetFileNameWithoutExtension(this.ProcessStartInfo.FileName), " stdout reader"); thread.Start(); return tcs.Task; } private void SyncReadStdOut(StreamReader stdOutReader) { try { char[] buffer = new char[BUFMAX]; while (!this.IsDisposeStarted) { int bytesRead = stdOutReader.Read(buffer, 0, buffer.Length); if (bytesRead > 0) { string result = new string(buffer, 0, bytesRead); OnOutputReceived(result); } else { OnReaderComplete(); return; } } } catch (Exception ex) { if (!this.IsDisposeStarted) { ReportException(ex); Dispose(); } } } protected override void OnErrorReceived(string error) { // stderr doesn't need to be read using raw I/O, but the call back does expect new line characters, so add them base.OnErrorReceived(error + Environment.NewLine); } } /// <summary> /// Shell that uses a remote Connection to send commands and receive input/output /// </summary> internal class RemoteCommandRunner : ICommandRunner, IDebugUnixShellCommandCallback { private readonly string _commandText; private readonly Connection _remoteConnection; private IDebugUnixShellAsyncCommand _asyncCommand; private bool _isRunning; private readonly bool _handleRawOutput; public RemoteCommandRunner(IPipeTransportSettings settings, Connection remoteConnection, bool handleRawOutput) : this(settings.Command, settings.CommandArgs, remoteConnection, handleRawOutput) { } public RemoteCommandRunner(string command, string arguments, Connection remoteConnection, bool handleRawOutput) { _remoteConnection = remoteConnection; _commandText = string.Concat(command, " ", arguments); _handleRawOutput = handleRawOutput; } public void Start() { _remoteConnection.BeginExecuteAsyncCommand(_commandText, runInShell: _handleRawOutput == false, callback: this, asyncCommand: out _asyncCommand); _isRunning = true; } public event EventHandler<string> OutputReceived; public event EventHandler<int> Closed; public event EventHandler<ErrorOccuredEventArgs> ErrorOccured; public void Dispose() { if (_isRunning) { _asyncCommand.Abort(); _isRunning = false; } } public void Write(string text) { EnsureRunning(); _asyncCommand.Write(text); } public void WriteLine(string text) { EnsureRunning(); _asyncCommand.WriteLine(text); } void IDebugUnixShellCommandCallback.OnOutputLine(string line) { OutputReceived?.Invoke(this, line); } void IDebugUnixShellCommandCallback.OnExit(string exitCode) { _isRunning = false; int code; if (!Int32.TryParse(exitCode, out code)) { ErrorOccured?.Invoke(this, new ErrorOccuredEventArgs(StringResources.Error_ExitCodeNotParseable)); code = -1; } Closed?.Invoke(this, code); } private void EnsureRunning() { if (!_isRunning) throw new InvalidOperationException(StringResources.Error_ShellNotRunning); } } } <|start_filename|>test/DebuggerTesting/OpenDebug/Commands/StepCommands.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; namespace DebuggerTesting.OpenDebug.Commands { public class ThreadCommandArgs : JsonValue { public int threadId; } public class ContinueCommand : Command<ThreadCommandArgs> { public ContinueCommand(int threadId) : base("continue") { this.Args.threadId = threadId; this.Timeout = TimeSpan.FromSeconds(10); } } public class StepInCommand : Command<ThreadCommandArgs> { public StepInCommand(int threadId) : base("stepIn") { this.Args.threadId = threadId; this.Timeout = TimeSpan.FromSeconds(10); } } public class StepOutCommand : Command<ThreadCommandArgs> { public StepOutCommand(int threadId) : base("stepOut") { this.Args.threadId = threadId; this.Timeout = TimeSpan.FromSeconds(10); } } public class StepOverCommand : Command<ThreadCommandArgs> { public StepOverCommand(int threadId) : base("next") { this.Args.threadId = threadId; this.Timeout = TimeSpan.FromSeconds(10); } } } <|start_filename|>src/OpenDebugAD7/DebugEventLogger.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Diagnostics; using Microsoft.VisualStudio.Shared.VSCodeDebugProtocol; using Microsoft.VisualStudio.Shared.VSCodeDebugProtocol.Messages; namespace OpenDebugAD7 { /// <summary>The various categories of debugger event logging.</summary> internal enum LoggingCategory { /// <summary>Standard out stream from the debuggee.</summary> StdOut, /// <summary>Standard error stream from the debuggee.</summary> StdErr, /// <summary>Status messages from the debugger.</summary> DebuggerStatus, /// <summary>Error messages from the debugger.</summary> DebuggerError, /// <summary>Diagnostic engine logs.</summary> EngineLogging, /// <summary>Event tracing between the debug adapter and VS Code.</summary> AdapterTrace, /// <summary>Response tracing between the debug adapter and VS Code.</summary> AdapterResponse, /// <summary>Telemetry messages.</summary> Telemetry, /// <summary>Exception messages.</summary> Exception, /// <summary>Module load/unload events.</summary> Module, /// <summary>Process exit message.</summary> ProcessExit, } /// <summary>Logging class to handle when and how various classes of output should be logged.</summary> internal class DebugEventLogger { private readonly Dictionary<LoggingCategory, bool> _isLoggingEnabled; private Action<DebugEvent> _sendToOutput; private Action<OutputEvent> _traceCallback; /// <summary> /// Create a new <see cref="DebugEventLogger"/> to log events to the given logging callback. /// </summary> /// <param name="outputCallback">Callback to manage the logging output.</param> public DebugEventLogger(Action<DebugEvent> outputCallback, List<LoggingCategory> loggingCategories) { Debug.Assert(outputCallback != null, "Trying to create a logger with no callback!"); _sendToOutput = outputCallback; _isLoggingEnabled = new Dictionary<LoggingCategory, bool>() { // Default on categories { LoggingCategory.StdOut, true }, { LoggingCategory.StdErr, true }, { LoggingCategory.DebuggerStatus, true }, { LoggingCategory.DebuggerError, true }, { LoggingCategory.Telemetry, true }, { LoggingCategory.Exception, true }, { LoggingCategory.Module, true }, { LoggingCategory.ProcessExit, true }, // Default off categories { LoggingCategory.EngineLogging, false }, { LoggingCategory.AdapterTrace, false }, { LoggingCategory.AdapterResponse, false }, }; foreach (var category in loggingCategories) { _isLoggingEnabled[category] = true; } // If AdapterTrace or AdapterResponse is set at commandline, write trace logging to Console.Error if (_isLoggingEnabled[LoggingCategory.AdapterTrace] || _isLoggingEnabled[LoggingCategory.AdapterResponse]) { _traceCallback = (s => Console.Error.WriteLine(s.Output)); } else { _traceCallback = _sendToOutput; } } /// <summary> /// Set the logging configuration for a specific category of event. /// </summary> /// <param name="category">The category of event to modify.</param> /// <param name="isEnabled">True if the category should log events, otherwise false to ignore them.</param> public void SetLoggingConfiguration(LoggingCategory category, bool isEnabled) { _isLoggingEnabled[category] = isEnabled; } /// <summary> /// Sends the message line to the logging output callback if the given category has logging enabled. /// </summary> /// <param name="category">The category of debug event logging.</param> /// <param name="message">The message to log.</param> /// <param name="data">Logging data to send alongside the message, if any.</param> public void WriteLine(LoggingCategory category, string message, Dictionary<string, object> data = null) { Write(category, message + Environment.NewLine, data); } /// <summary> /// Sends the message to the logging output callback if the given category has logging enabled. /// </summary> /// <param name="category">The category of debug event logging.</param> /// <param name="message">The message to log.</param> /// <param name="data">Logging data to send alongside the message, if any.</param> public void Write(LoggingCategory category, string message, Dictionary<string, object> data = null) { // Default to logging the message if we haven't set a status for this category. if (_isLoggingEnabled.ContainsKey(category) && !_isLoggingEnabled[category]) { return; } _sendToOutput.Invoke(CreateOutputEvent(category, message, data)); } public void TraceLogger_EventHandler(object sender, LogEventArgs args) { string message = args.Message + Environment.NewLine; LoggingCategory category = LoggingCategory.DebuggerError; if (args.Message.StartsWith("<-- ", StringComparison.Ordinal)) { category = LoggingCategory.AdapterTrace; } else if (args.Message.StartsWith("--> ", StringComparison.Ordinal)) { category = LoggingCategory.AdapterResponse; } WriteTrace(category, message); } private void WriteTrace(LoggingCategory category, string message) { // Default to logging the message if we haven't set a status for this category. if (_isLoggingEnabled.ContainsKey(category) && !_isLoggingEnabled[category]) { return; } _traceCallback.Invoke(CreateOutputEvent(category, message)); } private OutputEvent CreateOutputEvent(LoggingCategory category, string message, Dictionary<string, object> data = null) { // By default send debugger messages to the standard console. OutputEvent.CategoryValue outputCategory = OutputEvent.CategoryValue.Console; switch (category) { case LoggingCategory.StdOut: outputCategory = OutputEvent.CategoryValue.Stdout; break; case LoggingCategory.StdErr: outputCategory = OutputEvent.CategoryValue.Stderr; break; case LoggingCategory.DebuggerError: outputCategory = OutputEvent.CategoryValue.Stderr; break; case LoggingCategory.Telemetry: outputCategory = OutputEvent.CategoryValue.Telemetry; break; default: break; } return new OutputEvent { Category = outputCategory, Output = message, Data = data }; } } } <|start_filename|>test/DebuggerTesting/Attribution/RequiresTestSettingsAttribute.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using DebuggerTesting.Settings; using DebuggerTesting.Utilities; using Xunit.Sdk; namespace DebuggerTesting { /// <summary> /// Attribute used for providing an xUnit theory test with test setting data. /// </summary> [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] [DataDiscoverer("DebuggerTesting.TestFramework.TestSettingsDataDiscoverer", "DebuggerTesting")] public class RequiresTestSettingsAttribute : DataAttribute { #region Constructor static RequiresTestSettingsAttribute() { if (PlatformUtilities.IsLinux) s_platform = SupportedPlatform.Linux; else if (PlatformUtilities.IsOSX) s_platform = SupportedPlatform.MacOS; else if (PlatformUtilities.IsWindows) s_platform = SupportedPlatform.Windows; else throw new PlatformNotSupportedException(); s_platformArchitecture = PlatformUtilities.Is64Bit ? SupportedArchitecture.x64 : SupportedArchitecture.x86; } #endregion #region Methods /// <summary> /// Retrieves the parameters that will be passed into the test method. /// </summary> /// <param name="testMethod">The method information of the test method.</param> public override IEnumerable<object[]> GetData(MethodInfo testMethod) { return TestSettingsHelper.GetSettings(testMethod, s_platform, s_platformArchitecture) .Select(settings => new object[] { settings }); } #endregion #region Fields private static SupportedPlatform s_platform; private static SupportedArchitecture s_platformArchitecture; #endregion } } <|start_filename|>src/SSHDebugPS/NativeMethods.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; namespace Microsoft.SSHDebugPS { internal static class NativeMethods { [StructLayout(LayoutKind.Sequential)] public struct MSG { public IntPtr handle; public uint msg; public IntPtr wParam; public IntPtr lParam; public uint time; public System.Drawing.Point p; } [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] static internal extern bool PeekMessage(out MSG lpMsg, IntPtr hWnd, uint wMsgFilterMin, uint wMsgFilterMax, uint wRemoveMsg); internal const uint WM_KEYFIRST = 0x0100; internal const uint WM_CHAR = 0x0102; // internal const uint WM_KEYLAST = 0x0108; } } <|start_filename|>test/DebuggerTesting/OpenDebug/ICommand.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; namespace DebuggerTesting.OpenDebug { /// <summary> /// Represents a Debug Adapter command. /// </summary> public interface ICommand { string Name { get; } /// <summary> /// The object that gets converted to JSON to represent the commands args. /// </summary> object DynamicArgs { get; } /// <summary> /// Represents the expected response from the command. /// If the actual response does not match this value, the command will throw. /// </summary> IResponse ExpectedResponse { get; } /// <summary> /// Sets the expectation of the commands success value /// </summary> bool ExpectsSuccess { get; set; } /// <summary> /// After the command is run if the command response matches ExpectedResponse, /// this method is called with the actual match. /// This can be used to read data from the response. /// </summary> void ProcessActualResponse(IActualResponse response); /// <summary> /// Set this to override the default timeout for the duration of this command. /// </summary> TimeSpan Timeout { get; set; } void Run(IDebuggerRunner runner, params IEvent[] expectedEvents); } /// <summary> /// Applies to a Debug Adapter command that can return results. /// </summary> public interface ICommandWithResponse<T> : ICommand { T ActualResponse { get; } new T Run(IDebuggerRunner runner, params IEvent[] expectedEvents); } /// <summary> /// Provides a way to get the command to interperet the actual result /// that comes back from the Debug Adapter. /// </summary> public interface IActualResponse { R Convert<R>(); } } <|start_filename|>test/CppTests/debuggees/kitchensink/src/environment.h<|end_filename|> #pragma once #include "global.h" #include <iostream> #include <vector> #include <string> #include <stdarg.h> #include "feature.h" using namespace std; class Environment : public Feature { public: Environment(); virtual void CoreRun(); }; <|start_filename|>test/Android/SwitchFramesInCallStack/SwitchFramesInCallStack/SwitchFramesInCallStack.NativeActivity/Header2.h<|end_filename|> #pragma once typedef void (*func4)(); typedef int (*func5)(int, int); int* func6(func4 f4, func5 f5); void func7(); int func8(int x, int y); <|start_filename|>src/OpenDebugAD7/OpenDebug/CustomProtocolObjects.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Globalization; using Microsoft.VisualStudio.Shared.VSCodeDebugProtocol.Messages; using Newtonsoft.Json; namespace OpenDebug.CustomProtocolObjects { public class OpenDebugStoppedEvent : DebugEvent { // Summary: // Protocol type for this event. public const string EventType = "stopped"; // Summary: // Creates a new instance of the Microsoft.VisualStudio.Shared.VSCodeDebugProtocol.Messages.StoppedEvent // class. public OpenDebugStoppedEvent() : base(EventType) { // All threads are always stopped. this.AllThreadsStopped = true; } // Summary: // The reason for the event. For backward compatibility this string is shown in // the UI if the 'description' attribute is missing (but it must not be translated). [JsonProperty("reason")] public StoppedEvent.ReasonValue Reason { get; set; } // Summary: // The full reason for the event, e.g. 'Paused on exception'. This string is shown // in the UI as is. [JsonProperty("description", DefaultValueHandling = DefaultValueHandling.Ignore)] public string Description { get; set; } // Summary: // The thread which was stopped. [JsonProperty("threadId", DefaultValueHandling = DefaultValueHandling.Ignore)] public int? ThreadId { get; set; } // Summary: // A value of true hints to the frontend that this event should not change the focus. [JsonProperty("preserveFocusHint", DefaultValueHandling = DefaultValueHandling.Ignore)] public bool? PreserveFocusHint { get; set; } // Summary: // Additional information. E.g. if reason is 'exception', text contains the exception // name. This string is shown in the UI. [JsonProperty("text", DefaultValueHandling = DefaultValueHandling.Ignore)] public string Text { get; set; } // Summary: // If allThreadsStopped is true, a debug adapter can announce that all threads have // stopped. * The client should use this information to enable that all threads // can be expanded to access their stacktraces. * If the attribute is missing or // false, only the thread with the given threadId can be expanded. [JsonProperty("allThreadsStopped", DefaultValueHandling = DefaultValueHandling.Ignore)] public bool? AllThreadsStopped { get; set; } // Custom fields for Testing [JsonProperty("source", DefaultValueHandling = DefaultValueHandling.Ignore)] public Source Source { get; set; } [JsonProperty("line", DefaultValueHandling = DefaultValueHandling.Ignore)] public int Line { get; set; } [JsonProperty("column", DefaultValueHandling = DefaultValueHandling.Ignore)] public int Column { get; set; } } public class OpenDebugThread : Thread { public OpenDebugThread(int id, string name) : base() { base.Id = id; if(string.IsNullOrEmpty(name)) { base.Name = string.Format(CultureInfo.CurrentCulture, "Thread #{0}", id); } else { base.Name = name; } } } } <|start_filename|>test/CppTests/debuggees/hello/src/hello.cpp<|end_filename|> #include <iostream> using namespace std; int main(int argc, char *argv[]) { int x,y; cout << "Hello, World!" << endl; x = 6; y = 7; return argc - 1; } <|start_filename|>src/JDbg/JdwpException.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace JDbg { public enum ErrorCode { VMUnavailable, InvalidResponse, SocketError, ConnectFailure, SendFailure, CommandFailure, FailedToInitialize } public class JdwpException : Exception { public readonly ErrorCode ErrorCode; internal JdwpException(ErrorCode errorCode, string message) : base(message) { this.ErrorCode = errorCode; } internal JdwpException(ErrorCode errorCode, string message, Exception innerException) : base(message, innerException) { this.ErrorCode = errorCode; } } } <|start_filename|>test/DebuggerTesting/OpenDebug/Events/StoppedEvent.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Globalization; using DebuggerTesting.OpenDebug.Commands.Responses; using Newtonsoft.Json; using Xunit; namespace DebuggerTesting.OpenDebug.Events { public enum StoppedReason { Unknown = 0, Step, Breakpoint, Pause, Exception, Entry, InstructionBreakpoint } #region StoppedEventValue public sealed class StoppedEventValue : EventValue { public sealed class Body { [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public string reason; [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public Source source; [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public int? line; [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public string text; [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public int? threadId; } public Body body = new Body(); } #endregion public interface IStoppedInfo { StoppedReason Reason { get; } string Filename { get; } int? Line { get; } string Text { get; } int? ThreadId { get; } } /// <summary> /// Event that fires when entering break mode /// </summary> public class StoppedEvent : Event<StoppedEventValue> { private bool verifyLineRange; private int startLine; private int endLine; private ulong address; public StoppedEvent(ulong address) : base("stopped") { this.address = address; this.ExpectedResponse.body.reason = FromReason(StoppedReason.InstructionBreakpoint); this.verifyLineRange = false; } public StoppedEvent(StoppedReason? reason = null, string fileName = null, int? lineNumber = null, string text = null) : base("stopped") { this.ExpectedResponse.body.reason = FromReason(reason); if (fileName != null) { this.ExpectedResponse.body.source = new Source(); this.ExpectedResponse.body.source.name = fileName; } this.ExpectedResponse.body.line = lineNumber; this.ExpectedResponse.body.text = text; this.verifyLineRange = false; } /// <summary> /// Create an expected stopped event that works over a range of lines /// </summary> public StoppedEvent(StoppedReason? reason, string fileName, int startLine, int endLine) : base("stopped") { Parameter.ThrowIfNegativeOrZero(startLine, nameof(startLine)); Parameter.ThrowIfNegativeOrZero(startLine, nameof(endLine)); this.ExpectedResponse.body.reason = FromReason(reason); if (fileName != null) { this.ExpectedResponse.body.source = new Source(); this.ExpectedResponse.body.source.name = fileName; } this.startLine = startLine; this.endLine = endLine; this.verifyLineRange = true; } private static string FromReason(StoppedReason? reason) { if (reason == null) return null; Parameter.ThrowIfIsInvalid(reason.Value, StoppedReason.Unknown, nameof(reason)); if (reason == StoppedReason.InstructionBreakpoint) { return "instruction breakpoint"; } return Enum.GetName(typeof(StoppedReason), reason.Value).ToLowerInvariant(); } private static StoppedReason? ToReason(string value) { StoppedReason reason; if (Enum.TryParse(value, true, out reason)) return reason; return null; } /// <summary> /// The actual information from the event /// </summary> public IStoppedInfo ActualEventInfo { get; private set; } public int ThreadId { get { return this.ActualEventInfo.ThreadId ?? -1; } } public override void ProcessActualResponse(IActualResponse response) { base.ProcessActualResponse(response); this.ActualEventInfo = new StoppedInfo(this.ActualEvent); if (this.verifyLineRange) VerifyLineRange(this.ActualEventInfo.Line, this.startLine, this.endLine); } /// <summary> /// Validates that the line number was withing an expected range. /// This may occur on debuggers that change behavior between different versions or on different platforms. /// </summary> /// <param name="actualLine">The line number that was encountered.</param> /// <param name="expectedStartLine">The first valid line number that could be encountered.</param> /// <param name="expectedLineRange">The range of valid line numbers.</param> internal static void VerifyLineRange(int? actualLine, int expectedStartLine, int expectedEndLine) { // If verifying over line range check result and error now if (actualLine == null || actualLine < expectedStartLine || actualLine > expectedEndLine) { string message = "Expected a line within {0}-{1} but actual line was {2}.".FormatInvariantWithArgs(expectedStartLine, expectedEndLine, actualLine); Assert.True(false, message); } } private string GetExpectedLine() { if (this.verifyLineRange) return "{0}-{1}".FormatInvariantWithArgs(this.startLine, this.endLine); return (this.ExpectedResponse.body.line ?? 0).ToString(CultureInfo.InvariantCulture); } public override string ToString() { string source = null; if (this.ExpectedResponse.body.source != null) { source = " ({0}:{1})".FormatInvariantWithArgs(this.ExpectedResponse.body.source.name, this.GetExpectedLine()); } return "{0} ({1}){2}".FormatInvariantWithArgs(base.ToString(), this.ExpectedResponse.body.reason, source); } #region StoppedInfo private class StoppedInfo : IStoppedInfo { public StoppedInfo(StoppedEventValue value) { this.Reason = ToReason(value?.body?.reason) ?? StoppedReason.Unknown; this.Filename = value?.body?.source?.name; this.Line = value?.body?.line; this.Text = value?.body?.text; this.ThreadId = value?.body?.threadId; } public string Filename { get; private set; } public int? Line { get; private set; } public StoppedReason Reason { get; private set; } public string Text { get; private set; } public int? ThreadId { get; private set; } } #endregion } } <|start_filename|>test/DebuggerTesting/OpenDebug/Commands/CompletionsCommand.cs<|end_filename|> // // Copyright (c) Microsoft. All rights reserved. // // Licensed under the MIT license. See LICENSE file in the project root for full license information. using DebuggerTesting.OpenDebug.Commands.Responses; namespace DebuggerTesting.OpenDebug.Commands { public sealed class CompletionsArgs : JsonValue { public int? frameId; public string text; public int column; public int? line; } public class CompletionsCommand : CommandWithResponse<CompletionsArgs, CompletionsResponseValue> { public CompletionsCommand(int? frameId, string text, int column, int? line) : base("completions") { this.Args.frameId = frameId; this.Args.text = text; this.Args.column = column; this.Args.line = line; } } } <|start_filename|>test/DebuggerTesting/Utilities/ProcessHelper.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using DebuggerTesting.Utilities.Windows; using System.IO; using System.ComponentModel; namespace DebuggerTesting.Utilities { public static class ProcessHelper { #region Methods public static void AddToPath(this Process process, string value) { string existingPath = PlatformUtilities.GetEnvironmentVariable(process.StartInfo, "Path"); string newPath = string.IsNullOrWhiteSpace(existingPath) ? value : existingPath + ";" + value; PlatformUtilities.SetEnvironmentVariable(process.StartInfo, "Path", newPath); } /// <summary> /// Creates a ProcessStartInfo object from a file name and arguments /// </summary> public static ProcessStartInfo CreateProcessStartInfo(string fileName, string arguments) { Parameter.ThrowIfNull(fileName, nameof(fileName)); ProcessStartInfo startInfo = new ProcessStartInfo(); #if !CORECLR startInfo.WindowStyle = ProcessWindowStyle.Hidden; #endif startInfo.FileName = fileName; startInfo.Arguments = arguments; startInfo.UseShellExecute = false; startInfo.RedirectStandardOutput = true; startInfo.RedirectStandardError = true; startInfo.CreateNoWindow = true; startInfo.WorkingDirectory = Path.GetDirectoryName(fileName); return startInfo; } /// <summary> /// Creates a Process object initialized with a ProcessStartInfo object /// </summary> public static Process CreateProcess(ProcessStartInfo startInfo) { Parameter.ThrowIfNull(startInfo, nameof(startInfo)); Process process = new Process(); process.StartInfo = startInfo; return process; } /// <summary> /// Creates a Process object from a file name and arguments /// </summary> public static Process CreateProcess(string fileName, string arguments) { return ProcessHelper.CreateProcess(ProcessHelper.CreateProcessStartInfo(fileName, arguments)); } /// <summary> /// Provides a way to assure a process will is closed or killed when dispose is called /// </summary> public static IDisposable ProcessCleanup(ILoggingComponent logger, Process p) { return new ProcessCleanupHelper(logger, p); } #region ProcessCleanupHelper Class private sealed class ProcessCleanupHelper : DisposableObject { ILoggingComponent logger; Process process; public ProcessCleanupHelper(ILoggingComponent logger, Process process) { this.logger = logger; this.process = process; } protected override void Dispose(bool isDisposing) { if (isDisposing) { if (this.process != null) { int killCount = ProcessHelper.KillProcess(process, recurse: true); if (killCount > 0) { this.logger.WriteLine("Killed {0} debuggee process(es).", killCount); } this.process.Dispose(); this.process = null; } } base.Dispose(isDisposing); } } #endregion /// <summary> /// Kills a process and child processes if requested /// </summary> /// <param name="process">The process to kill</param> /// <param name="recurse">True to kill child processes</param> /// <returns>The count of processes killed</returns> public static int KillProcess(Process process, bool recurse = false) { return KillProcess(process.Id, recurse); } /// <summary> /// Kills a process and child processes if requested /// </summary> /// <param name="processId">The process to kill</param> /// <param name="recurse">True to kill child processes</param> /// <returns>The count of processes killed</returns> public static int KillProcess(int processId, bool recurse = false) { if (recurse) { int killCount = 0; int[] childProcessIds = ProcessHelper.FindChildProcesses(processId); killCount += ProcessHelper.KillProcess(processId, recurse: false); foreach (int childProcessId in childProcessIds) { killCount += ProcessHelper.KillProcess(childProcessId, recurse: true); } return killCount; } else { if (!IsProcessRunning(processId)) { return 0; } // This can fail, but don't want to raise an exception in the dispose that hides the root error. try { Kill(processId); return 1; } catch (Exception) { return 0; } } } public static bool IsProcessRunning(int processId) { if (PlatformUtilities.IsLinux || PlatformUtilities.IsOSX) { return UnixNativeMethods.GetPGid(processId) >= 0; } else if (PlatformUtilities.IsWindows) { try { return !TryGetProcessById(processId)?.HasExited ?? false; } catch (Exception) { return false; } } else { throw new NotSupportedException(); } } private static void Kill(int processId) { if (PlatformUtilities.IsLinux || PlatformUtilities.IsOSX) { const int sigkill = 9; UnixNativeMethods.Kill(processId, sigkill); } else if (PlatformUtilities.IsWindows) { try { TryGetProcessById(processId)?.Kill(); } catch (Exception) { } } else { throw new NotSupportedException(); } } /// <summary> /// Trys to get a Process from a process id. Returns null if the process doesn't exist. /// </summary> private static Process TryGetProcessById(int processId) { try { return Process.GetProcessById(processId); } catch (ArgumentException) { return null; } } /// <summary> /// Try to get child processes by using 'pgrep -P ##' /// NOTE: This command is not on OSX 10.7 and earlier /// </summary> private static int[] FindChildProcesses(int parentProcessId) { try { return ProcessHelper.FindChildProcessIds(parentProcessId) .Select((id) => id) .ToArray(); } catch (Exception) { return new int[] { }; } } private static IEnumerable<int> FindChildProcessIds(int id) { if (PlatformUtilities.IsLinux || PlatformUtilities.IsOSX) { List<int> childProcessIds = new List<int>(1); string pgrepArgs = "-P {0}".FormatInvariantWithArgs(id); using (Process pgrepProcess = ProcessHelper.CreateProcess("pgrep", pgrepArgs)) { pgrepProcess.Start(); pgrepProcess.WaitForExit(); string childLine; while ((childLine = pgrepProcess.StandardOutput.ReadLine()) != null) { int childProcessId = childLine.ToInt() ?? -1; if (childProcessId > 0) { childProcessIds.Add(childProcessId); } } return childProcessIds; } } else if (PlatformUtilities.IsWindows) { // Find all processes that are parented by the specified id return from p in Process.GetProcesses() where WindowsProcessNativeMethods.GetParentProcessId(p.Id) == id select p.Id; } throw new NotSupportedException(); } public static void InvokeIfAlive(this Process process, Action action) { if (!process.HasExited) { lock (process) { if (!process.HasExited) { action(); } } } } #endregion } } <|start_filename|>test/Android/Locals/Locals/Locals.NativeActivity/main.cpp<|end_filename|> /* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #define LOGI(...) ((void)__android_log_print(ANDROID_LOG_INFO, "AndroidProject1.NativeActivity", __VA_ARGS__)) #define LOGW(...) ((void)__android_log_print(ANDROID_LOG_WARN, "AndroidProject1.NativeActivity", __VA_ARGS__)) class SimpleClass { private: int _a; int _b; public: SimpleClass(int a, int b) : _a(a), _b(b) { } void TestMe() { _a += 0; // bp here } }; class BaseClass { protected: int _a; public: BaseClass(int a) : _a(a) { } void TestMe() { _a += 0; // bp here; } }; class DerivedClass : public BaseClass { protected: int _b; public: DerivedClass(int a, int b) : BaseClass(a), _b(b) { } void TestMe() { _b += 0; // bp here } }; void x_2() { int x = 0xBEEF; x += 0; // bp here } void x_1() { int x = 0xDEAD; x += 0; // bp here x_2(); x += 0; // bp here } /** * This is the main entry point of a native application that is using * android_native_app_glue. It runs in its own thread, with its own * event loop for receiving input events and doing other things. */ void android_main(struct android_app* state) { int i = 0; int j = 1; int k = 0xDEADBEEF; int* p = &k; float f = 0.2; char* name = "TEST NAME"; const char* const_name = "TEST NAME"; char name_array[10] = "TEST NAME"; int numbers[4] = { 10, 20, 30, 40 }; int* numbers_points[4] = { &i, &j, &k, p }; SimpleClass simpleClass(0xDEAD, 0xBEEF); SimpleClass* pSimpleClass = new SimpleClass(0xDEAD, 0xBEEF); DerivedClass derivedClass(0xDEAD, 0xBEEF); DerivedClass* pDerivedClass = new DerivedClass(0xDEAD, 0xBEEF); char* escaped = "Hello\n\tWorld!\n"; const char* const_escaped = "Hello\n\tWorld!\n"; i += 0; // breakpoint here simpleClass.TestMe(); pSimpleClass->TestMe(); derivedClass.TestMe(); pDerivedClass->TestMe(); delete pSimpleClass; delete pDerivedClass; x_1(); } <|start_filename|>src/SSHDebugPS/ProcFSOutputParser.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Text.RegularExpressions; using Microsoft.SqlServer.Server; namespace Microsoft.SSHDebugPS { public class ProcFSOutputParser { // for process user, can also use 'stat -c %U /proc/<pid>/exe' public static string CommandText => @"echo shell-process:$$; for filename in /proc/[0-9]*; do echo $filename,cmdline:$(tr '\0' ' ' < $filename/cmdline 2>/dev/null),ls:$(ls -lh $filename/exe 2>/dev/null); done"; private const string ShellProcessPrefix = "shell-process:"; private readonly Regex _linePattern = new Regex(@"^/proc/([0-9]+),cmdline:(.*),ls:(.*)$", RegexOptions.None); private List<Process> _processList = new List<Process>(); private uint _shellProcess = uint.MaxValue; internal static List<Process> Parse(string output, SystemInformation systemInformation) { return new ProcFSOutputParser().ParseInternal(output, systemInformation); } private ProcFSOutputParser() { } private List<Process> ParseInternal(string output, SystemInformation systemInformation) { using (var reader = new StringReader(output)) { while (true) { var line = reader.ReadLine(); if (line == null) break; ProcessLine(line.Trim(), systemInformation); } if (_processList.Count == 0) { throw new CommandFailedException(StringResources.Error_PSFailed); } _processList.Sort( (x, y) => x.Id < y.Id ? -1 : x.Id == y.Id ? 0 : 1); } return _processList; } private void ProcessLine(string line, SystemInformation systemInformation) { if (string.IsNullOrWhiteSpace(line)) return; if (line.StartsWith(ShellProcessPrefix, StringComparison.Ordinal)) { if (line.Length > ShellProcessPrefix.Length) { uint.TryParse(line.Substring(ShellProcessPrefix.Length).Trim(), NumberStyles.None, CultureInfo.InvariantCulture, out _shellProcess); } return; } Match match = _linePattern.Match(line); if (match == null || !match.Success) { Debug.Fail("Unexpected output text from ps script"); return; } string processIdAsString = match.Groups[1].Value; string commandLine = match.Groups[2].Value; string[] lsColumns = match.Groups[3].Value.Split(' ', '\t'); if (!uint.TryParse(processIdAsString, NumberStyles.None, CultureInfo.InvariantCulture, out uint processId)) { Debug.Fail("Unexpected process ID larger than 2^32"); return; } if (processId == _shellProcess) return; // ignore the shell process // Example ls output: lrwxrwxrwx 1 root root 0 Apr 27 17:51 /proc/7/exe string procUsername = lsColumns.Length >= 5 ? lsColumns[2] : string.Empty; if (commandLine.Length == 0) { // If we didn't have access to /proc/<PID>/cmdline, use placeholder text commandLine = StringResources.ProcessName_Unknown; } // If the passed in username is empty, then treat all processes as the same user bool isSameUser = string.IsNullOrWhiteSpace(systemInformation.UserName) ? true : systemInformation.UserName.Equals(procUsername, StringComparison.Ordinal); // Note: // For Flags, will need to parse /proc/[pid]/stat flags. Process process = new Process(processId, systemInformation.Architecture, /* Flags */ 0, procUsername, commandLine, isSameUser); _processList.Add(process); } } } <|start_filename|>test/DebuggerTesting/Compilation/IDebuggee.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Diagnostics; namespace DebuggerTesting.Compilation { public interface IDebuggee { #region Methods void AddDefineConstant(string name, string value = null); void AddLibraries(params string[] libraries); void AddSourceFiles(params string[] fileNames); IDebuggee Clone(); void Compile(); Process Launch(params string[] arguments); #endregion #region Properties CompilerOption CompilerOptions { get; set; } string OutputPath { get; } CompilerOutputType OutputType { get; } string SourceRoot { get; } #endregion } } <|start_filename|>test/DebuggerTesting/SupportedPlatform.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; namespace DebuggerTesting { [Flags] public enum SupportedPlatform { Linux = 0x1, MacOS = 0x2, Windows = 0x4 } } <|start_filename|>tools/iOS/CertTool/CertTool.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Net.Security; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication12 { internal class CertTool { private const int RemotePort = 3030; private const string MachineName = "Chucks-mac-mini"; public static bool ValidateServerCertificate( object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyError ) { return true; } private static void Main(string[] args) { Task.Run(async () => { Console.WriteLine("Enter PIN: "); string pin = Console.ReadLine(); WebRequestHandler handler = new WebRequestHandler(); handler.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(ValidateServerCertificate); using (HttpClient client = new HttpClient(handler, true)) { client.BaseAddress = new Uri(string.Format(@"https://{0}:{1}", MachineName, RemotePort)); X509Store store = null; try { var response = await client.GetAsync("certs/" + pin); response.EnsureSuccessStatusCode(); byte[] rawCert = await response.Content.ReadAsByteArrayAsync(); X509Certificate2Collection certs = new X509Certificate2Collection(); certs.Import(rawCert, "", X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.UserKeySet); store = new X509Store(StoreName.My, StoreLocation.CurrentUser); store.Open(OpenFlags.ReadWrite); X509Certificate2Collection oldCerts = new X509Certificate2Collection(); foreach (var cert in certs) { oldCerts.AddRange(store.Certificates.Find(X509FindType.FindBySubjectDistinguishedName, cert.Subject, false)); } store.RemoveRange(certs); store.AddRange(certs); store.Close(); Console.WriteLine("Success"); } catch (HttpRequestException e) { Console.WriteLine("Error communicating with vcremote. Make sure that vcremote is running in secure mode and that a new client cert has been generated."); } finally { if (store != null) { store.Close(); } } } }).Wait(); } } } <|start_filename|>test/DebuggerTesting/Settings/DiagnosticsSettings.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; namespace DebuggerTesting.Settings { public static class DiagnosticsSettings { private static bool? logMIEngine; /// <summary> /// Set to true to log mi engine output /// </summary> public static bool LogMIEngine { get { // Allow setting to be overridden for dev environments if (DiagnosticsSettings.logMIEngine == null) DiagnosticsSettings.logMIEngine = Environment.GetEnvironmentVariable("TEST_LOGMIENGINE").ToBool(); if (DiagnosticsSettings.logMIEngine == null) DiagnosticsSettings.logMIEngine = true; return logMIEngine.Value; } } private static bool? logDebugAdapter; /// <summary> /// Set to true to log debug adapter output /// </summary> public static bool LogDebugAdapter { get { // Allow setting to be overridden for dev environments if (DiagnosticsSettings.logDebugAdapter == null) DiagnosticsSettings.logDebugAdapter = Environment.GetEnvironmentVariable("TEST_LOGDEBUGADAPTER").ToBool(); if (DiagnosticsSettings.logDebugAdapter == null) DiagnosticsSettings.logDebugAdapter = true; return DiagnosticsSettings.logDebugAdapter.Value; } } } } <|start_filename|>test/CppTests/debuggees/kitchensink/src/feature.cpp<|end_filename|> #include "feature.h" Feature::Feature(string name) { this->_name = name; } string Feature::GetName() { return this->_name; } void Feature::Log() { cout << endl; } void Feature::Run() { this->Log(); this->Log("##### Feature '", this->GetName(), "' #####"); this->CoreRun(); this->Log("----- Feature '", this->GetName(), "' -----"); } <|start_filename|>test/Android/BreakPointWhenTrueCondition/BreakPointWhenTrueCondition/BreakPointWhenTrueCondition.NativeActivity/Header1.h<|end_filename|> #pragma once void Func(); int Func1(); class MyClass { public: bool isTrue; int Func(); }; <|start_filename|>src/MIDebugEngine/AD7.Definitions/AD7Hresult.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.MIDebugEngine { // These are managed definitions of the well-known AD7 HRESULTS. Defined in msdbg.idl. static public class AD7_HRESULT { public const int S_ATTACH_DEFERRED = unchecked((int)0x40004); public const int S_ATTACH_IGNORED = unchecked((int)0x40005); public const int S_JIT_USERCANCELLED = unchecked((int)0x400B0); public const int S_JIT_NOT_REG_FOR_ENGINE = unchecked((int)0x400B5); public const int S_TERMINATE_PROCESSES_STILL_DETACHING = unchecked((int)0x400C0); public const int S_TERMINATE_PROCESSES_STILL_TERMINATING = unchecked((int)0x400C1); public const int S_ENC_SETIP_REQUIRES_CONTINUE = unchecked((int)0x40106); public const int S_WEBDBG_UNABLE_TO_DIAGNOSE = unchecked((int)0x40120); public const int S_WEBDBG_DEBUG_VERB_BLOCKED = unchecked((int)0x40121); public const int S_ASP_USER_ACCESS_DENIED = unchecked((int)0x40125); public const int S_JMC_LIMITED_SUPPORT = unchecked((int)0x40146); public const int S_CANNOT_REMAP_IN_EXCEPTION = unchecked((int)0x40150); public const int S_CANNOT_REMAP_NOT_AT_SEQUENCE_POINT = unchecked((int)0x40151); public const int S_GETPARENT_NO_PARENT = unchecked((int)0x40531); public const int S_GETDERIVEDMOST_NO_DERIVED_MOST = unchecked((int)0x40541); public const int S_GETMEMORYBYTES_NO_MEMORY_BYTES = unchecked((int)0x40551); public const int S_GETMEMORYCONTEXT_NO_MEMORY_CONTEXT = unchecked((int)0x40561); public const int S_GETSIZE_NO_SIZE = unchecked((int)0x40571); public const int S_GETEXTENDEDINFO_NO_EXTENDEDINFO = unchecked((int)0x40591); public const int S_ASYNC_STOP = unchecked((int)0x40B02); public const int E_ATTACH_DEBUGGER_ALREADY_ATTACHED = unchecked((int)0x80040001); public const int E_ATTACH_DEBUGGEE_PROCESS_SECURITY_VIOLATION = unchecked((int)0x80040002); public const int E_ATTACH_CANNOT_ATTACH_TO_DESKTOP = unchecked((int)0x80040003); public const int E_LAUNCH_NO_INTEROP = unchecked((int)0x80040005); public const int E_LAUNCH_DEBUGGING_NOT_POSSIBLE = unchecked((int)0x80040006); public const int E_LAUNCH_KERNEL_DEBUGGER_ENABLED = unchecked((int)0x80040007); public const int E_LAUNCH_KERNEL_DEBUGGER_PRESENT = unchecked((int)0x80040008); public const int E_INTEROP_NOT_SUPPORTED = unchecked((int)0x80040009); public const int E_TOO_MANY_PROCESSES = unchecked((int)0x8004000A); public const int E_MSHTML_SCRIPT_DEBUGGING_DISABLED = unchecked((int)0x8004000B); public const int E_SCRIPT_PDM_NOT_REGISTERED = unchecked((int)0x8004000C); public const int E_DE_CLR_DBG_SERVICES_NOT_INSTALLED = unchecked((int)0x8004000D); public const int E_ATTACH_NO_CLR_PROGRAMS = unchecked((int)0x8004000E); public const int E_REMOTE_SERVER_CLOSED = unchecked((int)0x80040010); public const int E_CLR_NOT_SUPPORTED = unchecked((int)0x80040016); public const int E_64BIT_CLR_NOT_SUPPORTED = unchecked((int)0x80040017); public const int E_CANNOT_MIX_MINDUMP_DEBUGGING = unchecked((int)0x80040018); public const int E_DEBUG_ENGINE_NOT_REGISTERED = unchecked((int)0x80040019); public const int E_LAUNCH_SXS_ERROR = unchecked((int)0x8004001A); public const int E_REMOTE_SERVER_DOES_NOT_EXIST = unchecked((int)0x80040020); public const int E_REMOTE_SERVER_ACCESS_DENIED = unchecked((int)0x80040021); public const int E_REMOTE_SERVER_MACHINE_DOES_NOT_EXIST = unchecked((int)0x80040022); public const int E_DEBUGGER_NOT_REGISTERED_PROPERLY = unchecked((int)0x80040023); public const int E_FORCE_GUEST_MODE_ENABLED = unchecked((int)0x80040024); public const int E_GET_IWAM_USER_FAILURE = unchecked((int)0x80040025); public const int E_REMOTE_SERVER_INVALID_NAME = unchecked((int)0x80040026); public const int E_REMOTE_SERVER_MACHINE_NO_DEFAULT = unchecked((int)0x80040027); public const int E_AUTO_LAUNCH_EXEC_FAILURE = unchecked((int)0x80040028); public const int E_SERVICE_ACCESS_DENIED = unchecked((int)0x80040029); public const int E_SERVICE_ACCESS_DENIED_ON_CALLBACK = unchecked((int)0x8004002A); public const int E_REMOTE_COMPONENTS_NOT_REGISTERED = unchecked((int)0x8004002B); public const int E_DCOM_ACCESS_DENIED = unchecked((int)0x8004002C); public const int E_SHARE_LEVEL_ACCESS_CONTROL_ENABLED = unchecked((int)0x8004002D); public const int E_WORKGROUP_REMOTE_LOGON_FAILURE = unchecked((int)0x8004002E); public const int E_WINAUTH_CONNECT_NOT_SUPPORTED = unchecked((int)0x8004002F); public const int E_EVALUATE_BUSY_WITH_EVALUATION = unchecked((int)0x80040030); public const int E_EVALUATE_TIMEOUT = unchecked((int)0x80040031); public const int E_INTEROP_NOT_SUPPORTED_FOR_THIS_CLR = unchecked((int)0x80040032); public const int E_CLR_INCOMPATIBLE_PROTOCOL = unchecked((int)0x80040033); public const int E_CLR_CANNOT_DEBUG_FIBER_PROCESS = unchecked((int)0x80040034); public const int E_PROCESS_OBJECT_ACCESS_DENIED = unchecked((int)0x80040035); public const int E_PROCESS_TOKEN_ACCESS_DENIED = unchecked((int)0x80040036); public const int E_PROCESS_TOKEN_ACCESS_DENIED_NO_TS = unchecked((int)0x80040037); public const int E_OPERATION_REQUIRES_ELEVATION = unchecked((int)0x80040038); public const int E_ATTACH_REQUIRES_ELEVATION = unchecked((int)0x80040039); public const int E_MEMORY_NOTSUPPORTED = unchecked((int)0x80040040); public const int E_DISASM_NOTSUPPORTED = unchecked((int)0x80040041); public const int E_DISASM_BADADDRESS = unchecked((int)0x80040042); public const int E_DISASM_NOTAVAILABLE = unchecked((int)0x80040043); public const int E_BP_DELETED = unchecked((int)0x80040060); public const int E_PROCESS_DESTROYED = unchecked((int)0x80040070); public const int E_PROCESS_DEBUGGER_IS_DEBUGGEE = unchecked((int)0x80040071); public const int E_TERMINATE_FORBIDDEN = unchecked((int)0x80040072); public const int E_THREAD_DESTROYED = unchecked((int)0x80040075); public const int E_PORTSUPPLIER_NO_PORT = unchecked((int)0x80040080); public const int E_PORT_NO_REQUEST = unchecked((int)0x80040090); public const int E_COMPARE_CANNOT_COMPARE = unchecked((int)0x800400A0); public const int E_JIT_INVALID_PID = unchecked((int)0x800400B1); public const int E_JIT_VSJITDEBUGGER_NOT_REGISTERED = unchecked((int)0x800400B3); public const int E_JIT_APPID_NOT_REGISTERED = unchecked((int)0x800400B4); public const int E_SESSION_TERMINATE_DETACH_FAILED = unchecked((int)0x800400C2); public const int E_SESSION_TERMINATE_FAILED = unchecked((int)0x800400C3); public const int E_DETACH_NO_PROXY = unchecked((int)0x800400D0); public const int E_DETACH_TS_UNSUPPORTED = unchecked((int)0x800400E0); public const int E_DETACH_IMPERSONATE_FAILURE = unchecked((int)0x800400F0); public const int E_CANNOT_SET_NEXT_STATEMENT_ON_NONLEAF_FRAME = unchecked((int)0x80040100); public const int E_TARGET_FILE_MISMATCH = unchecked((int)0x80040101); public const int E_IMAGE_NOT_LOADED = unchecked((int)0x80040102); public const int E_FIBER_NOT_SUPPORTED = unchecked((int)0x80040103); public const int E_CANNOT_SETIP_TO_DIFFERENT_FUNCTION = unchecked((int)0x80040104); public const int E_CANNOT_SET_NEXT_STATEMENT_ON_EXCEPTION = unchecked((int)0x80040105); public const int E_ENC_SETIP_REQUIRES_CONTINUE = unchecked((int)0x80040107); public const int E_CANNOT_SET_NEXT_STATEMENT_INTO_FINALLY = unchecked((int)0x80040108); public const int E_CANNOT_SET_NEXT_STATEMENT_OUT_OF_FINALLY = unchecked((int)0x80040109); public const int E_CANNOT_SET_NEXT_STATEMENT_INTO_CATCH = unchecked((int)0x8004010A); public const int E_CANNOT_SET_NEXT_STATEMENT_GENERAL = unchecked((int)0x8004010B); public const int E_CANNOT_SET_NEXT_STATEMENT_INTO_OR_OUT_OF_FILTER = unchecked((int)0x8004010C); public const int E_ASYNCBREAK_NO_PROGRAMS = unchecked((int)0x80040110); public const int E_ASYNCBREAK_DEBUGGEE_NOT_INITIALIZED = unchecked((int)0x80040111); public const int E_WEBDBG_DEBUG_VERB_BLOCKED = unchecked((int)0x80040121); public const int E_ASP_USER_ACCESS_DENIED = unchecked((int)0x80040125); public const int E_AUTO_ATTACH_NOT_REGISTERED = unchecked((int)0x80040126); public const int E_AUTO_ATTACH_DCOM_ERROR = unchecked((int)0x80040127); public const int E_AUTO_ATTACH_NOT_SUPPORTED = unchecked((int)0x80040128); public const int E_AUTO_ATTACH_CLASSNOTREG = unchecked((int)0x80040129); public const int E_CANNOT_CONTINUE_DURING_PENDING_EXPR_EVAL = unchecked((int)0x80040130); public const int E_REMOTE_REDIRECTION_UNSUPPORTED = unchecked((int)0x80040135); public const int E_INVALID_WORKING_DIRECTORY = unchecked((int)0x80040136); public const int E_LAUNCH_FAILED_WITH_ELEVATION = unchecked((int)0x80040137); public const int E_LAUNCH_ELEVATION_REQUIRED = unchecked((int)0x80040138); public const int E_CANNOT_FIND_INTERNET_EXPLORER = unchecked((int)0x80040139); public const int E_EXCEPTION_CANNOT_BE_INTERCEPTED = unchecked((int)0x80040140); public const int E_EXCEPTION_CANNOT_UNWIND_ABOVE_CALLBACK = unchecked((int)0x80040141); public const int E_INTERCEPT_CURRENT_EXCEPTION_NOT_SUPPORTED = unchecked((int)0x80040142); public const int E_INTERCEPT_CANNOT_UNWIND_LASTCHANCE_INTEROP = unchecked((int)0x80040143); public const int E_JMC_CANNOT_SET_STATUS = unchecked((int)0x80040145); public const int E_DESTROYED = unchecked((int)0x80040201); public const int E_REMOTE_NOMSVCMON = unchecked((int)0x80040202); public const int E_REMOTE_BADIPADDRESS = unchecked((int)0x80040203); public const int E_REMOTE_MACHINEDOWN = unchecked((int)0x80040204); public const int E_REMOTE_MACHINEUNSPECIFIED = unchecked((int)0x80040205); public const int E_CRASHDUMP_ACTIVE = unchecked((int)0x80040206); public const int E_ALL_THREADS_SUSPENDED = unchecked((int)0x80040207); public const int E_LOAD_DLL_TL = unchecked((int)0x80040208); public const int E_LOAD_DLL_SH = unchecked((int)0x80040209); public const int E_LOAD_DLL_EM = unchecked((int)0x8004020A); public const int E_LOAD_DLL_EE = unchecked((int)0x8004020B); public const int E_LOAD_DLL_DM = unchecked((int)0x8004020C); public const int E_LOAD_DLL_MD = unchecked((int)0x8004020D); public const int E_IOREDIR_BADFILE = unchecked((int)0x8004020E); public const int E_IOREDIR_BADSYNTAX = unchecked((int)0x8004020F); public const int E_REMOTE_BADVERSION = unchecked((int)0x80040210); public const int E_CRASHDUMP_UNSUPPORTED = unchecked((int)0x80040211); public const int E_REMOTE_BAD_CLR_VERSION = unchecked((int)0x80040212); public const int E_UNSUPPORTED_BINARY = unchecked((int)0x80040215); public const int E_DEBUGGEE_BLOCKED = unchecked((int)0x80040216); public const int E_REMOTE_NOUSERMSVCMON = unchecked((int)0x80040217); public const int E_STEP_WIN9xSYSCODE = unchecked((int)0x80040218); public const int E_INTEROP_ORPC_INIT = unchecked((int)0x80040219); public const int E_CANNOT_DEBUG_WIN32 = unchecked((int)0x8004021B); public const int E_CANNOT_DEBUG_WIN64 = unchecked((int)0x8004021C); public const int E_MINIDUMP_READ_WIN9X = unchecked((int)0x8004021D); public const int E_CROSS_TSSESSION_ATTACH = unchecked((int)0x8004021E); public const int E_STEP_BP_SET_FAILED = unchecked((int)0x8004021F); public const int E_LOAD_DLL_TL_INCORRECT_VERSION = unchecked((int)0x80040220); public const int E_LOAD_DLL_DM_INCORRECT_VERSION = unchecked((int)0x80040221); public const int E_REMOTE_NOMSVCMON_PIPE = unchecked((int)0x80040222); public const int E_LOAD_DLL_DIA = unchecked((int)0x80040223); public const int E_DUMP_CORRUPTED = unchecked((int)0x80040224); public const int E_INTEROP_WIN64 = unchecked((int)0x80040225); public const int E_CRASHDUMP_DEPRECATED = unchecked((int)0x80040227); public const int E_DEVICEBITS_NOT_SIGNED = unchecked((int)0x80040401); public const int E_ATTACH_NOT_ENABLED = unchecked((int)0x80040402); public const int E_REMOTE_DISCONNECT = unchecked((int)0x80040403); public const int E_BREAK_ALL_FAILED = unchecked((int)0x80040404); public const int E_DEVICE_ACCESS_DENIED_SELECT_YES = unchecked((int)0x80040405); public const int E_DEVICE_ACCESS_DENIED = unchecked((int)0x80040406); public const int E_DEVICE_CONNRESET = unchecked((int)0x80040407); public const int E_BAD_NETCF_VERSION = unchecked((int)0x80040408); public const int E_REFERENCE_NOT_VALID = unchecked((int)0x80040501); public const int E_PROPERTY_NOT_VALID = unchecked((int)0x80040511); public const int E_SETVALUE_VALUE_CANNOT_BE_SET = unchecked((int)0x80040521); public const int E_SETVALUE_VALUE_IS_READONLY = unchecked((int)0x80040522); public const int E_SETVALUEASREFERENCE_NOTSUPPORTED = unchecked((int)0x80040523); public const int E_CANNOT_GET_UNMANAGED_MEMORY_CONTEXT = unchecked((int)0x80040561); public const int E_GETREFERENCE_NO_REFERENCE = unchecked((int)0x80040581); public const int E_CODE_CONTEXT_OUT_OF_SCOPE = unchecked((int)0x800405A1); public const int E_INVALID_SESSIONID = unchecked((int)0x800405A2); public const int E_SERVER_UNAVAILABLE_ON_CALLBACK = unchecked((int)0x800405A3); public const int E_ACCESS_DENIED_ON_CALLBACK = unchecked((int)0x800405A4); public const int E_UNKNOWN_AUTHN_SERVICE_ON_CALLBACK = unchecked((int)0x800405A5); public const int E_NO_SESSION_AVAILABLE = unchecked((int)0x800405A6); public const int E_CLIENT_NOT_LOGGED_ON = unchecked((int)0x800405A7); public const int E_OTHER_USERS_SESSION = unchecked((int)0x800405A8); public const int E_USER_LEVEL_ACCESS_CONTROL_REQUIRED = unchecked((int)0x800405A9); public const int E_SCRIPT_CLR_EE_DISABLED = unchecked((int)0x800405B0); public const int E_HTTP_SERVERERROR = unchecked((int)0x80040700); public const int E_HTTP_UNAUTHORIZED = unchecked((int)0x80040701); public const int E_HTTP_SENDREQUEST_FAILED = unchecked((int)0x80040702); public const int E_HTTP_FORBIDDEN = unchecked((int)0x80040703); public const int E_HTTP_NOT_SUPPORTED = unchecked((int)0x80040704); public const int E_HTTP_NO_CONTENT = unchecked((int)0x80040705); public const int E_HTTP_NOT_FOUND = unchecked((int)0x80040706); public const int E_HTTP_BAD_REQUEST = unchecked((int)0x80040707); public const int E_HTTP_ACCESS_DENIED = unchecked((int)0x80040708); public const int E_HTTP_CONNECT_FAILED = unchecked((int)0x80040709); public const int E_HTTP_EXCEPTION = unchecked((int)0x8004070A); public const int E_HTTP_TIMEOUT = unchecked((int)0x8004070B); public const int E_64BIT_COMPONENTS_NOT_INSTALLED = unchecked((int)0x80040750); public const int E_UNMARSHAL_SERVER_FAILED = unchecked((int)0x80040751); public const int E_UNMARSHAL_CALLBACK_FAILED = unchecked((int)0x80040752); public const int E_RPC_REQUIRES_AUTHENTICATION = unchecked((int)0x80040755); public const int E_LOGON_FAILURE_ON_CALLBACK = unchecked((int)0x80040756); public const int E_REMOTE_SERVER_UNAVAILABLE = unchecked((int)0x80040757); public const int E_FIREWALL_USER_CANCELED = unchecked((int)0x80040758); public const int E_REMOTE_CREDENTIALS_PROHIBITED = unchecked((int)0x80040759); public const int E_FIREWALL_NO_EXCEPTIONS = unchecked((int)0x8004075A); public const int E_FIREWALL_CANNOT_OPEN_APPLICATION = unchecked((int)0x8004075B); public const int E_FIREWALL_CANNOT_OPEN_PORT = unchecked((int)0x8004075C); public const int E_FIREWALL_CANNOT_OPEN_FILE_SHARING = unchecked((int)0x8004075D); public const int E_REMOTE_DEBUGGING_UNSUPPORTED = unchecked((int)0x8004075E); public const int E_REMOTE_BAD_MSDBG2 = unchecked((int)0x8004075F); public const int E_ATTACH_USER_CANCELED = unchecked((int)0x80040760); public const int E_FUNCTION_NOT_JITTED = unchecked((int)0x80040800); public const int E_NO_CODE_CONTEXT = unchecked((int)0x80040801); public const int E_BAD_CLR_DIASYMREADER = unchecked((int)0x80040802); public const int E_CLR_SHIM_ERROR = unchecked((int)0x80040803); public const int E_AUTOATTACH_ACCESS_DENIED = unchecked((int)0x80040900); public const int E_AUTOATTACH_WEBSERVER_NOT_FOUND = unchecked((int)0x80040901); public const int E_DBGEXTENSION_NOT_FOUND = unchecked((int)0x80040910); public const int E_DBGEXTENSION_FUNCTION_NOT_FOUND = unchecked((int)0x80040911); public const int E_DBGEXTENSION_FAULTED = unchecked((int)0x80040912); public const int E_DBGEXTENSION_RESULT_INVALID = unchecked((int)0x80040913); public const int E_PROGRAM_IN_RUNMODE = unchecked((int)0x80040914); public const int E_CAUSALITY_NO_SERVER_RESPONSE = unchecked((int)0x80040920); public const int E_CAUSALITY_REMOTE_NOT_REGISTERED = unchecked((int)0x80040921); public const int E_CAUSALITY_BREAKPOINT_NOT_HIT = unchecked((int)0x80040922); public const int E_CAUSALITY_BREAKPOINT_BIND_ERROR = unchecked((int)0x80040923); public const int E_CAUSALITY_PROJECT_DISABLED = unchecked((int)0x80040924); public const int E_NO_ATTACH_WHILE_DDD = unchecked((int)0x80040A00); public const int E_SQLLE_ACCESSDENIED = unchecked((int)0x80040A01); public const int E_SQL_SP_ENABLE_PERMISSION_DENIED = unchecked((int)0x80040A02); public const int E_SQL_DEBUGGING_NOT_ENABLED_ON_SERVER = unchecked((int)0x80040A03); public const int E_SQL_CANT_FIND_SSDEBUGPS_ON_CLIENT = unchecked((int)0x80040A04); public const int E_SQL_EXECUTED_BUT_NOT_DEBUGGED = unchecked((int)0x80040A05); public const int E_SQL_VDT_INIT_RETURNED_SQL_ERROR = unchecked((int)0x80040A06); public const int E_ATTACH_FAILED_ABORT_SILENTLY = unchecked((int)0x80040A07); public const int E_SQL_REGISTER_FAILED = unchecked((int)0x80040A08); public const int E_DE_NOT_SUPPORTED_PRE_8_0 = unchecked((int)0x80040B00); public const int E_PROGRAM_DESTROY_PENDING = unchecked((int)0x80040B01); public const int E_MANAGED_FEATURE_NOTSUPPORTED = unchecked((int)0x80040BAD); } } <|start_filename|>test/CppTests/Tests/AttachTests.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Diagnostics; using System.Linq; using DebuggerTesting; using DebuggerTesting.Compilation; using DebuggerTesting.OpenDebug; using DebuggerTesting.OpenDebug.CrossPlatCpp; using DebuggerTesting.OpenDebug.Events; using DebuggerTesting.OpenDebug.Extensions; using DebuggerTesting.Ordering; using DebuggerTesting.Utilities; using Xunit; using Xunit.Abstractions; namespace CppTests.Tests { [TestCaseOrderer(DependencyTestOrderer.TypeName, DependencyTestOrderer.AssemblyName)] public class AttachTests : TestBase { #region Constructor public AttachTests(ITestOutputHelper outputHelper) : base(outputHelper) { } #endregion [Theory] [RequiresTestSettings] public void CompileKitchenSinkForAttach(ITestSettings settings) { this.TestPurpose("Compiles the kitchen sink debuggee for attach."); this.WriteSettings(settings); IDebuggee debuggee = SinkHelper.OpenAndCompile(this, settings.CompilerSettings, DebuggeeMonikers.KitchenSink.Attach); } [Theory] [DependsOnTest(nameof(CompileKitchenSinkForAttach))] [RequiresTestSettings] // TODO: Re-enable for vsdbg [UnsupportedDebugger(SupportedDebugger.Gdb_Cygwin | SupportedDebugger.Gdb_MinGW | SupportedDebugger.Lldb | SupportedDebugger.VsDbg, SupportedArchitecture.x64 | SupportedArchitecture.x86)] public void AttachAsyncBreak(ITestSettings settings) { this.TestPurpose("Verifies attach and that breakpoints can be set from break mode."); this.WriteSettings(settings); IDebuggee debuggee = SinkHelper.Open(this, settings.CompilerSettings, DebuggeeMonikers.KitchenSink.Attach); Process debuggeeProcess = debuggee.Launch("-fNonTerminating", "-fCalling"); using (ProcessHelper.ProcessCleanup(this, debuggeeProcess)) using (IDebuggerRunner runner = CreateDebugAdapterRunner(settings)) { this.Comment("Attach to debuggee"); runner.Attach(settings.DebuggerSettings, debuggeeProcess); runner.ConfigurationDone(); this.Comment("Attempt to break all"); StoppedEvent breakAllEvent = new StoppedEvent(StoppedReason.Pause); runner.Expects.Event(breakAllEvent) .AfterAsyncBreak(); this.WriteLine("Break all stopped on:"); this.WriteLine(breakAllEvent.ActualEvent.ToString()); this.Comment("Set breakpoint while breaking code."); runner.SetBreakpoints(debuggee.Breakpoints(SinkHelper.NonTerminating, 28)); this.Comment("Start running after the async break (since we have no idea where we are) and then hit the breakpoint"); runner.Expects.HitBreakpointEvent(SinkHelper.NonTerminating, 28) .AfterContinue(); this.Comment("Evaluate the shouldExit member to true to stop the infinite loop."); using (IThreadInspector threadInspector = runner.GetThreadInspector()) { IFrameInspector firstFrame = threadInspector.Stack.First(); this.WriteLine(firstFrame.ToString()); firstFrame.GetVariable("shouldExitLocal").Value = "true"; } this.Comment("Continue until debuggee exists"); runner.Expects.ExitedEvent(exitCode: 0).TerminatedEvent().AfterContinue(); this.Comment("Verify debugger and debuggee closed"); runner.DisconnectAndVerify(); Assert.True(debuggeeProcess.HasExited, "Debuggee still running."); } } [Theory] [DependsOnTest(nameof(CompileKitchenSinkForAttach))] [RequiresTestSettings] // TODO: Re-enable for vsdbg [UnsupportedDebugger(SupportedDebugger.Gdb_Cygwin | SupportedDebugger.Gdb_MinGW | SupportedDebugger.Lldb | SupportedDebugger.VsDbg, SupportedArchitecture.x64 | SupportedArchitecture.x86)] public void Detach(ITestSettings settings) { this.TestPurpose("Verify debugger can detach and reattach to a debuggee."); this.WriteSettings(settings); this.Comment("Starting debuggee"); IDebuggee debuggee = SinkHelper.Open(this, settings.CompilerSettings, DebuggeeMonikers.KitchenSink.Attach); Process debuggeeProcess = debuggee.Launch("-fNonTerminating", "-fCalling"); using (ProcessHelper.ProcessCleanup(this, debuggeeProcess)) { using (IDebuggerRunner runner = CreateDebugAdapterRunner(settings)) { this.Comment("Attaching first time"); runner.Attach(settings.DebuggerSettings, debuggeeProcess); runner.ConfigurationDone(); this.Comment("Attempt to break all"); StoppedEvent breakAllEvent = new StoppedEvent(StoppedReason.Pause); runner.Expects.Event(breakAllEvent) .AfterAsyncBreak(); this.WriteLine("Break all stopped on:"); this.WriteLine(breakAllEvent.ActualEvent.ToString()); this.Comment("Detach then verify debugger closed"); runner.DisconnectAndVerify(); } Assert.False(debuggeeProcess.HasExited, "Debuggee should still be running."); using (IDebuggerRunner runner = CreateDebugAdapterRunner(settings)) { this.Comment("Attaching second time"); runner.Attach(settings.DebuggerSettings, debuggeeProcess); runner.ConfigurationDone(); this.Comment("Detach then verify debugger closed"); runner.DisconnectAndVerify(); } } } } } <|start_filename|>test/DebuggerTesting/Ordering/DependencyOrderer.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Linq; namespace DebuggerTesting.Ordering { /// <summary> /// Base class that provides generic way to order items that declare their /// dependency. This removes items that can't fullfil their dependencies as /// well as items with circular dependencies. /// </summary> public abstract class DependencyOrderer<T, TKey> { protected IEnumerable<T> OrderBasedOnDependencies(IEnumerable<T> itemsEnumerable) { List<T> items = new List<T>(itemsEnumerable); // Keep track of times we are stuck in a loop int stallCount = 0; int i = 0; while (i < items.Count) { T currentItem = items[i]; IEnumerable<int> dependencyIndexes = GetDependencyIndexes(items, currentItem); if (dependencyIndexes == null) continue; if (dependencyIndexes.Any(x => x < 0)) { // Remove item if dependency cannot be resolved in this set of items Debug.WriteLine("ERROR: Cannot find dependency for '{0}'.".FormatWithArgs(GetItemName(currentItem))); // Remove the item and start over items.RemoveAt(i); stallCount = 0; i = 0; continue; } // Move the current test after any required dependencies. // Verify we aren't stuck in an infinite loop int lastDependencyIndex = dependencyIndexes.Any() ? dependencyIndexes.Max() : -1; if (lastDependencyIndex > i) { MoveAfter(items, i, lastDependencyIndex); stallCount++; if (stallCount > (items.Count - i)) { Debug.WriteLine("ERROR: Circular test dependency found."); // Based on the stall count, the items at the end of the list // have a circular reference. Remove them all. items.RemoveRange(i, items.Count - i); break; } } else { stallCount = 0; i++; } } return items; } private static void MoveAfter(IList list, int itemIndex, int afterIndex) { while (itemIndex < afterIndex) { SwapItems(list, itemIndex, itemIndex + 1); itemIndex += 1; } } private static void SwapItems(IList list, int indexA, int indexB) { object item = list[indexA]; list[indexA] = list[indexB]; list[indexB] = item; } #region Dependency Helpers private IEnumerable<int> GetDependencyIndexes(IList<T> items, T currentItem) { IEnumerable<TKey> dependencies = GetDependencies(currentItem); return dependencies?.Select(x => GetIndexOfDependency(items, x)); } protected abstract IEnumerable<TKey> GetDependencies(T currentItem); protected abstract int GetIndexOfDependency(IList<T> items, TKey dependency); protected virtual string GetItemName(T item) { return item.ToString(); } #endregion } } <|start_filename|>src/SSHDebugPS/Docker/DockerPortPicker.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Runtime.InteropServices; using System.Windows; using System.Windows.Interop; using Microsoft.SSHDebugPS.UI; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Debugger.Interop; using Microsoft.VisualStudio.OLE.Interop; using Microsoft.VisualStudio.Shell; namespace Microsoft.SSHDebugPS.Docker { [ComVisible(true)] //{91BDF293-E6A0-49C4-B033-6F36CFC4FF98} [Guid("91BDF293-E6A0-49C4-B033-6F36CFC4FF98")] public class DockerLinuxPortPicker : DockerPortPickerBase { internal override bool SupportSSHConnections => true; } [ComVisible(true)] //{AE75778B-70E8-4F53-B3FE-59E048D3D01B} [Guid("AE75778B-70E8-4F53-B3FE-59E048D3D01B")] public class DockerWindowsPortPicker : DockerPortPickerBase { internal override bool SupportSSHConnections => false; } [ComVisible(true)] public abstract class DockerPortPickerBase : IDebugPortPicker { internal abstract bool SupportSSHConnections { get; } int IDebugPortPicker.DisplayPortPicker(IntPtr hwndParentDialog, out string pbstrPortId) { ThreadHelper.ThrowIfNotOnUIThread(); // If this is null, then the PortPicker handler shows an error. Set to empty by default return ConnectionManager.ShowContainerPickerWindow(hwndParentDialog, SupportSSHConnections, out pbstrPortId) ? VSConstants.S_OK : VSConstants.S_FALSE; } private VisualStudio.OLE.Interop.IServiceProvider _serviceProvider = null; int IDebugPortPicker.SetSite(VisualStudio.OLE.Interop.IServiceProvider pSP) { _serviceProvider = pSP; return VSConstants.S_OK; } } } <|start_filename|>test/CppTests/debuggees/kitchensink/src/threading.h<|end_filename|> #pragma once #include <atomic> #include "global.h" #include <string> #include <thread> #include <condition_variable> #include <chrono> #include "feature.h" using namespace std; class Threading : public Feature { public: Threading(); virtual void CoreRun(); condition_variable mainClosing; std::atomic_int runningWorkingThreadCount; std::mutex mainClosingMutex; }; <|start_filename|>test/DebuggerTesting/OpenDebug/Extensions/ThreadInspector.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using DebuggerTesting.OpenDebug.Commands; using DebuggerTesting.OpenDebug.Commands.Responses; using DebuggerTesting.Utilities; namespace DebuggerTesting.OpenDebug.Extensions { internal class ThreadInspector : DisposableObject, IThreadInspector { private int threadId; private IList<FrameInspector> frameInspectors = new List<FrameInspector>(20); #region Constructor/Dispose public ThreadInspector(IDebuggerRunner runner, int? threadId = null) { Parameter.ThrowIfNull(runner, nameof(runner)); this.DebuggerRunner = runner; this.threadId = threadId ?? runner.StoppedThreadId; } protected override void Dispose(bool isDisposing) { if (isDisposing) { this.Refresh(); this.DebuggerRunner = null; } base.Dispose(isDisposing); } #endregion public IDebuggerRunner DebuggerRunner { get; private set; } public int ThreadId { get { return this.threadId; } } public IEnumerable<IFrameInspector> Stack { get { this.VerifyNotDisposed(); int startFrame = 0; while (true) { StackTraceCommand stackTraceCommand = new StackTraceCommand(this.threadId, startFrame); StackTraceResponseValue response = this.DebuggerRunner.RunCommand(stackTraceCommand); if (response?.body?.stackFrames == null || response.body.stackFrames.Length <= 0) yield break; startFrame += response.body.stackFrames.Length; foreach (var stackFrame in response.body.stackFrames) { string name = stackFrame.name; int id = stackFrame.id ?? -1; string sourceName = stackFrame.source?.name; string sourcePath = stackFrame.source?.path; int? sourceReference = stackFrame.source?.sourceReference; int? line = stackFrame.line; int? column = stackFrame.column; string instructionPointerReference = stackFrame.instructionPointerReference; FrameInspector frame = new FrameInspector(this.DebuggerRunner, name, id, sourceName, sourcePath, sourceReference, line, column, instructionPointerReference); this.frameInspectors.Add(frame); yield return frame; } } } } public void Refresh() { this.frameInspectors.SafeDisposeAll(); this.frameInspectors.Clear(); } } } <|start_filename|>src/OpenDebugAD7/AD7ExtensionMethods.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.VisualStudio.Debugger.Interop; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace OpenDebugAD7 { internal static class AD7ExtensionMethods { public static int Id(this IDebugThread2 thread) { uint unsignedId; thread.GetThreadId(out unsignedId); return (unchecked((int)unsignedId)); } } } <|start_filename|>src/SSHDebugPS/IConnection.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using System.Threading; using Microsoft.DebugEngineHost; using Microsoft.SSHDebugPS.Utilities; using Microsoft.VisualStudio.Debugger.Interop.UnixPortSupplier; namespace Microsoft.SSHDebugPS { // Needs to be public to support the ContainerPicker UI public interface IConnection { string Name { get; } void Close(); int ExecuteCommand(string commandText, int timeout, out string commandOutput, out string errorMessage); List<Process> ListProcesses(); } internal abstract class Connection : IConnection { #region Methods for implementing IDebugUnixShellPort /// <inheritdoc cref="IDebugUnixShellPort.BeginExecuteAsyncCommand(string, bool, IDebugUnixShellCommandCallback, out IDebugUnixShellAsyncCommand)"/> public abstract void BeginExecuteAsyncCommand(string commandText, bool runInShell, IDebugUnixShellCommandCallback callback, out IDebugUnixShellAsyncCommand asyncCommand); /// <inheritdoc cref="IDebugUnixShellPort.CopyFile(string, string)"/> public abstract void CopyFile(string sourcePath, string destinationPath); /// <inheritdoc cref="IDebugUnixShellPort.MakeDirectory(string)"/> public abstract string MakeDirectory(string path); /// <inheritdoc cref="IDebugUnixShellPort.GetUserHomeDirectory"/> public abstract string GetUserHomeDirectory(); /// <inheritdoc cref="IDebugUnixShellPort.IsOSX"/> public abstract bool IsOSX(); /// <inheritdoc cref="IDebugUnixShellPort.IsLinux"/> public abstract bool IsLinux(); #endregion #region IConnection public abstract string Name { get; } public abstract List<Process> ListProcesses(); public abstract void Close(); // TODO: This is wrong. It doesn't show UI but allows an infinite timeout /// <summary> /// Exceutes the specified command on the remote system /// </summary> /// <param name="commandText">The shell command text to execute</param> /// <param name="timeout">Timeout to wait for the command to complete before aborting</param> /// <param name="commandOutput">The stdout produced by the command</param> /// <param name="errorMessage">The stderr produced by the command</param> /// <returns>The exit code of the command</returns> public abstract int ExecuteCommand(string commandText, int timeout, out string commandOutput, out string errorMessage); #endregion /// <summary> /// Executes the specified command, throwing a CommandFailedException if it failed /// </summary> /// <param name="commandText">Text of the command to execute</param> /// <param name="timeout">timeout in milliseconds</param> /// <returns>The stdout text the command produced</returns> public string ExecuteCommand(string commandText, int timeout) { int exitCode = ExecuteCommand(commandText, timeout, out string commandOutput, out string errorMessage); if (exitCode != 0) { string error = StringResources.CommandFailedMessageFormat.FormatCurrentCultureWithArgs(commandText, exitCode, errorMessage); throw new CommandFailedException(error); } return commandOutput; } /// <summary> /// Executes the specified command, return false if the exit code is non-zero /// </summary> /// <param name="commandText">The shell command text to execute</param> /// <param name="timeout">Timeout to wait for the command to complete before aborting</param> /// <param name="commandOutput">The stdout produced by the command</param> /// <param name="errorMessage">The stderr produced by the command</param> /// <param name="exitCode">The exit code of the command</param> /// <returns>true if command succeeded.</returns> public bool ExecuteCommand(string commandText, int timeout, out string commandOutput, out string errorMessage, out int exitCode) { exitCode = ExecuteCommand(commandText, timeout, out commandOutput, out errorMessage); return exitCode == 0; } } public class Process { public uint Id { get; private set; } /// <summary> /// Only used by the PSOutputParser /// </summary> public uint Flags { get; private set; } public string SystemArch { get; private set; } public string CommandLine { get; private set; } public string UserName { get; private set; } public bool IsSameUser { get; private set; } public Process(uint id, string arch, uint flags, string userName, string commandLine, bool isSameUser) { this.Id = id; this.Flags = flags; this.UserName = userName; this.CommandLine = commandLine; this.IsSameUser = isSameUser; this.SystemArch = arch; } } internal class SystemInformation { public string UserName { get; private set; } public string Architecture { get; private set; } public SystemInformation(string username, string architecture) { this.UserName = username; this.Architecture = architecture; } } } <|start_filename|>test/DebuggerTesting/OpenDebug/Commands/SetVariableCommand.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using DebuggerTesting.OpenDebug.Commands.Responses; namespace DebuggerTesting.OpenDebug.Commands { public sealed class SetVariableCommandArgs { public string name; public string value; public int variablesReference; } public class SetVariableCommand : CommandWithResponse<SetVariableCommandArgs, SetVariableResponseValue> { public SetVariableCommand(int variablesReference, string name, string value) : base("setVariable") { Parameter.ThrowIfNullOrWhiteSpace(name, nameof(name)); Parameter.ThrowIfNullOrWhiteSpace(value, nameof(value)); this.Args.variablesReference = variablesReference; this.Args.name = name; this.Args.value = value; } public override string ToString() { return "{0} ({1}={2})".FormatInvariantWithArgs(base.ToString(), this.Args.name, this.Args.value); } } } <|start_filename|>test/DebuggerTesting/OpenDebug/Extensions/VariableInspector.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using System.Linq; using DebuggerTesting.OpenDebug.Commands; using DebuggerTesting.OpenDebug.Commands.Responses; using DebuggerTesting.Utilities; namespace DebuggerTesting.OpenDebug.Extensions { /// <summary> /// Returns info on a variable, and allows expanded evaluation of variable info. /// </summary> internal class VariableInspector : DisposableObject, IVariableInspector { private Dictionary<string, IVariableInspector> variables; private string name; private string value; private int parentVariablesReference; private int? variablesReference; #region Constructor/Create/Dispose public VariableInspector(IDebuggerRunner runner, int parentVariablesReference, string name, string value, int? variablesReference) { Parameter.ThrowIfNull(runner, nameof(runner)); this.DebuggerRunner = runner; this.parentVariablesReference = parentVariablesReference; this.name = name; this.value = value; this.variablesReference = variablesReference; } protected override void Dispose(bool isDisposing) { if (isDisposing) { DisposableHelper.SafeDisposeAll(this.variables?.Values); this.variables = null; this.DebuggerRunner = null; } base.Dispose(isDisposing); } #endregion public IDebuggerRunner DebuggerRunner { get; private set; } #region Variable Info public string Name { get { this.VerifyNotDisposed(); return this.name; } } public string Value { get { this.VerifyNotDisposed(); return this.value; } set { this.VerifyNotDisposed(); this.DebuggerRunner.RunCommand(this.GetSetVariableCommand(value)); } } public int? VariablesReference { get { this.VerifyNotDisposed(); return this.variablesReference; } } #endregion public void SetVariableValueExpectFailure(string expression) { this.DebuggerRunner.RunCommandExpectFailure(this.GetSetVariableCommand(expression)); } public IDictionary<string, IVariableInspector> Variables { get { this.VerifyNotDisposed(); if (this.VariablesReference == null || this.VariablesReference == 0) return null; if (this.variables == null) { this.variables = GetChildVariables(this.DebuggerRunner, this.VariablesReference.Value); } return this.variables; } } internal static Dictionary<string, IVariableInspector> GetChildVariables(IDebuggerRunner runner, int variablesReference) { VariablesResponseValue variablesResponse = runner.RunCommand(new VariablesCommand(variablesReference)); return variablesResponse.body.variables.ToDictionary<VariablesResponseValue.Body.Variable, string, IVariableInspector>(v => v.name, v => new VariableInspector(runner, variablesReference, v.name, v.value, v.variablesReference)); } private ICommandWithResponse<SetVariableResponseValue> GetSetVariableCommand(string expression) { return new SetVariableCommand(this.parentVariablesReference, this.name, expression); } public override string ToString() { return "{0}={1}".FormatInvariantWithArgs(this.Name, this.Value); } } } <|start_filename|>test/DebuggerTesting/Compilation/ICompiler.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; namespace DebuggerTesting.Compilation { internal interface ICompiler { #region Methods void Compile( CompilerOutputType outputType, IEnumerable<string> libraries, IEnumerable<string> sourceFilePaths, string targetFilePath, CompilerOption options, IDictionary<string, string> defineConstants); #endregion } } <|start_filename|>test/DebuggerTesting/OpenDebug/Events/TerminatedEvent.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace DebuggerTesting.OpenDebug.Events { public sealed class TerminatedEventValue : EventValue { } public class TerminatedEvent : Event<TerminatedEventValue> { public TerminatedEvent() : base("terminated") { } } } <|start_filename|>test/CppTests/OpenDebug/CrossPlatCpp/AttachCommand.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using DebuggerTesting.OpenDebug.Commands; using DebuggerTesting.Utilities; using Newtonsoft.Json; namespace DebuggerTesting.OpenDebug.CrossPlatCpp { public class AttachCommand : AttachCommand<CppLaunchCommandArgs> { public AttachCommand(IDebuggerSettings settings, Process process) { this.Timeout = TimeSpan.FromSeconds(15); this.Args.processId = process.Id; this.Args.name = CreateName(settings); this.Args.program = process.StartInfo.FileName; this.Args.args = new string[] { }; this.Args.request = "attach"; this.Args.environment = new EnvironmentEntry[] { }; this.Args.launchOptionType = "Local"; this.Args.sourceFileMap = new Dictionary<string, string>(); if (settings.DebuggerType == SupportedDebugger.VsDbg) { this.Args.type = "cppvsdbg"; } else { this.Args.stopAtEntry = false; this.Args.cwd = Path.GetDirectoryName(process.StartInfo.FileName); this.Args.type = "cppdbg"; this.Args.miDebuggerPath = settings.DebuggerPath; this.Args.targetArchitecture = settings.DebuggeeArchitecture.ToArchitectureString(); this.Args.noDebug = false; this.Args.coreDumpPath = null; this.Args.MIMode = settings.MIMode; } } private string CreateName(IDebuggerSettings settings) { string debuggerName = Enum.GetName(typeof(SupportedDebugger), settings.DebuggerType); return "C++ ({0})".FormatInvariantWithArgs(debuggerName); } public override string ToString() { return "{0} ({1})".FormatInvariantWithArgs(base.ToString(), this.Args.program); } } } <|start_filename|>test/Android/EvalCompoundDataTypes/EvalCompoundDataTypes/EvalCompoundDataTypes.NativeActivity/Source1.cpp<|end_filename|> #include "Header1.h" void Func() { Cat cat; cat.age = 1; cat.weight = 2.50; Book book; book.ID = 100001; book.price = 10.50; book.title = "Android C++"; int x = 0; return; } <|start_filename|>src/MICore/InvalidCoreDumpOperationException.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; namespace MICore { public sealed class InvalidCoreDumpOperationException : InvalidOperationException { } } <|start_filename|>src/DebugEngineHost.VSCode/HostWaitLoop.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Threading; namespace Microsoft.DebugEngineHost { /// <summary> /// Nop implementation of the HostWaitLoop for VSCode /// </summary> public sealed class HostWaitLoop { public HostWaitLoop(string message) { } public void Wait(WaitHandle launchCompleteHandle, CancellationTokenSource cancellationSource) { // Note: at least for now we don't have at sort of UI to allow cancellation, so // ignore the cancelation source. launchCompleteHandle.WaitOne(); } public void SetProgress(int totalSteps, int currentStep, string progressText) { } public void SetText(string text) { } } } <|start_filename|>src/SSHDebugPS/UI/Controls/Automation/ContainerListBoxAutomationPeer.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Windows.Automation.Peers; namespace Microsoft.SSHDebugPS.UI { public class ContainerListBoxAutomationPeer : ListBoxAutomationPeer { public ContainerListBoxAutomationPeer(ContainerListBox owner) : base(owner) { } protected override ItemAutomationPeer CreateItemAutomationPeer(object item) { return new ContainerListBoxItemAutomationPeer<DockerContainerViewModel>(item, this); } } } <|start_filename|>test/DebuggerTesting/OpenDebug/Commands/SetInstructionBreakpointCommand.cs<|end_filename|> // // Copyright (c) Microsoft. All rights reserved. // // Licensed under the MIT license. See LICENSE file in the project root for full license information. using DebuggerTesting.OpenDebug.Commands.Responses; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DebuggerTesting.OpenDebug.Commands { #region SetInstructionBreakpointCommandArgs public sealed class SetInstructionBreakpointCommandArgs : JsonValue { public sealed class InstructionBreakpoint { public InstructionBreakpoint(string instructionReference, string condition = null) { this.instructionReference = instructionReference; this.condition = condition; } public string instructionReference; [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public int? offset; [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public string condition; } public InstructionBreakpoint[] breakpoints; } #endregion #region InstructionBreakpoints public sealed class InstructionBreakpoints { private List<SetInstructionBreakpointCommandArgs.InstructionBreakpoint> breakpoints; public InstructionBreakpoints() { this.breakpoints = new List<SetInstructionBreakpointCommandArgs.InstructionBreakpoint>(); } public InstructionBreakpoints(params string[] addresses) : this() { foreach (string address in addresses) { this.Add(address); } } public InstructionBreakpoints Add(string address, string condition = null) { this.breakpoints.Add(new SetInstructionBreakpointCommandArgs.InstructionBreakpoint(address, condition)); return this; } public InstructionBreakpoints Remove(string address) { this.breakpoints.RemoveAll(bp => String.Equals(bp.instructionReference, address, StringComparison.Ordinal)); return this; } internal IList<SetInstructionBreakpointCommandArgs.InstructionBreakpoint> Breakpoints { get { return this.breakpoints; } } } #endregion public class SetInstructionBreakpointsCommand : CommandWithResponse<SetInstructionBreakpointCommandArgs, SetBreakpointsResponseValue> { public SetInstructionBreakpointsCommand() : base("setInstructionBreakpoints") { } public SetInstructionBreakpointsCommand(InstructionBreakpoints breakpoints) : this() { this.Args.breakpoints = breakpoints.Breakpoints.ToArray(); } public override string ToString() { return "{0} ({1})".FormatInvariantWithArgs(base.ToString(), String.Join(", ", this.Args.breakpoints.Select(bp => bp.instructionReference))); } } } <|start_filename|>test/DebuggerTesting/Utilities/StringExtensions.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; namespace DebuggerTesting { public static class StringExtensions { /// <summary> /// Formats the format string with the given arguments using the current culture. /// </summary> public static string FormatWithArgs(this string format, params object[] args) { return format.FormatWithArgs(CultureInfo.CurrentCulture, args); } /// <summary> /// Formats the format string with the given arguments using the invariant culture. /// </summary> public static string FormatInvariantWithArgs(this string format, params object[] args) { return format.FormatWithArgs(CultureInfo.InvariantCulture, args); } /// <summary> /// Formats the format string with the given arguments using the given culture. /// </summary> private static string FormatWithArgs(this string format, IFormatProvider provider, params object[] args) { return String.Format(provider, format, args); } /// <summary> /// Determines if string has ASCII characters only. /// </summary> public static bool HasAsciiOnly(this string value) { if (String.IsNullOrEmpty(value)) return true; return value.All(c => c <= 0x7F); } /// <summary> /// Converts a string to its base64 representation using the given encoding. /// </summary> public static string ToBase64String(this string value, Encoding encoding) { Parameter.ThrowIfNull(encoding, nameof(encoding)); if (String.IsNullOrEmpty(value)) return value; return Convert.ToBase64String(encoding.GetBytes(value)); } /// <summary> /// Creates a string representation of the contents of the dictionary. /// Returns a line for each entry in the format "key=value" /// </summary> public static string ToReadableString<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, string prefix = null) { if (dictionary == null || dictionary.Count == 0) return string.Empty; // Creates an aggregate that accumulates in a string builder return dictionary.Aggregate( new StringBuilder(), (sb, x) => sb.AppendFormat(CultureInfo.InvariantCulture, "{0}{1}={2}", prefix, x.Key, x.Value).AppendLine(), sb => sb.ToString()); } /// <summary> /// Parses a string to int. If the string is not a valid int, this converts to null /// </summary> public static int? ToInt(this string value) { int x; if (int.TryParse(value, out x)) return x; else return null; } /// <summary> /// Parses a string to bool. If the string is not a valid bool, this converts to null /// </summary> public static bool? ToBool(this string value) { bool x; if (bool.TryParse(value, out x)) return x; else return null; } } } <|start_filename|>test/CppTests/Tests/EnvironmentTests.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Linq; using DebuggerTesting; using DebuggerTesting.Compilation; using DebuggerTesting.OpenDebug; using DebuggerTesting.OpenDebug.Commands; using DebuggerTesting.OpenDebug.CrossPlatCpp; using DebuggerTesting.OpenDebug.Events; using DebuggerTesting.OpenDebug.Extensions; using DebuggerTesting.Ordering; using Xunit; using Xunit.Abstractions; namespace CppTests.Tests { [TestCaseOrderer(DependencyTestOrderer.TypeName, DependencyTestOrderer.AssemblyName)] public class EnvironmentTests : TestBase { #region Constructor public EnvironmentTests(ITestOutputHelper outputHelper) : base(outputHelper) { } #endregion #region Methods [Theory] [RequiresTestSettings] public void CompileKitchenSinkForEnvironmentTests(ITestSettings settings) { this.TestPurpose("Compiles the kitchen sink debuggee."); this.WriteSettings(settings); IDebuggee debuggee = SinkHelper.OpenAndCompile(this, settings.CompilerSettings, DebuggeeMonikers.KitchenSink.Environment); } [Theory] [DependsOnTest(nameof(CompileKitchenSinkForEnvironmentTests))] [RequiresTestSettings] public void EnvironmentVariablesBasic(ITestSettings settings) { this.TestPurpose("Tests basic operation of environment variables"); TestEnvironmentVariable(settings, "VAR_NAME_1", "simpleTest", false); } [Theory] [DependsOnTest(nameof(CompileKitchenSinkForEnvironmentTests))] [RequiresTestSettings] // Need to support 'runInTerminal' request. // Re-enable lldb for test machines [UnsupportedDebugger(SupportedDebugger.VsDbg | SupportedDebugger.Lldb, SupportedArchitecture.x86 | SupportedArchitecture.x64)] public void EnvironmentVariablesBasicNewTerminal(ITestSettings settings) { this.TestPurpose("Tests basic operation of environment variables using a new terminal window"); TestEnvironmentVariable(settings, "VAR_NAME_1", "simpleTest", true); } [Theory] [DependsOnTest(nameof(CompileKitchenSinkForEnvironmentTests))] [RequiresTestSettings] public void EnvironmentVariablesUndefined(ITestSettings settings) { this.TestPurpose("Tests environment variables that are undefined"); TestEnvironmentVariable(settings, "VAR_NAME_1", null, false); } [Theory] [DependsOnTest(nameof(CompileKitchenSinkForEnvironmentTests))] [RequiresTestSettings] // Need to support 'runInTerminal' request. // Re-enable lldb for test machines [UnsupportedDebugger(SupportedDebugger.VsDbg | SupportedDebugger.Lldb, SupportedArchitecture.x86 | SupportedArchitecture.x64)] public void EnvironmentVariablesUndefinedNewTerminal(ITestSettings settings) { this.TestPurpose("Tests environment variables that are undefined using a new terminal window"); TestEnvironmentVariable(settings, "VAR_NAME_1", null, true); } [Theory] [DependsOnTest(nameof(CompileKitchenSinkForEnvironmentTests))] [RequiresTestSettings] public void EnvironmentVariablesSingleQuote(ITestSettings settings) { this.TestPurpose("Tests environment variables that include a single quote"); TestEnvironmentVariable(settings, "VAR_NAME_1", "quot'edstring", false); } [Theory] [DependsOnTest(nameof(CompileKitchenSinkForEnvironmentTests))] [RequiresTestSettings] // TODO There is a bug in LLDB: when executing the new terminal through the AppleScript, // it doesn't escape quotes and fails // TODO VsDbg: // Need to support 'runInTerminal' request. [UnsupportedDebugger(SupportedDebugger.Lldb | SupportedDebugger.VsDbg, SupportedArchitecture.x86 | SupportedArchitecture.x64)] public void EnvironmentVariablesSingleQuoteNewTerminal(ITestSettings settings) { this.TestPurpose("Tests environment variables that include a single quote in a new terminal window"); TestEnvironmentVariable(settings, "VAR_NAME_1", "quot'edstring", true); } [Theory] [DependsOnTest(nameof(CompileKitchenSinkForEnvironmentTests))] [RequiresTestSettings] public void EnvironmentVariablesDoubleQuote(ITestSettings settings) { this.TestPurpose("Tests environment variables that include a double quote"); TestEnvironmentVariable(settings, "VAR_NAME_1", "quot\"edstring", false); } [Theory] [DependsOnTest(nameof(CompileKitchenSinkForEnvironmentTests))] [RequiresTestSettings] // TODO There is a bug in LLDB: when executing the new terminal through the AppleScript, // it doesn't escape quotes and fails // TODO VsDbg: // Need to support 'runInTerminal' request. [UnsupportedDebugger(SupportedDebugger.Lldb | SupportedDebugger.VsDbg, SupportedArchitecture.x86 | SupportedArchitecture.x64)] public void EnvironmentVariablesDoubleQuoteNewTerminal(ITestSettings settings) { this.TestPurpose("Tests environment variables that include a double quote in a new terminal window"); TestEnvironmentVariable(settings, "VAR_NAME_1", "quot\"edstring", true); } [Theory] [DependsOnTest(nameof(CompileKitchenSinkForEnvironmentTests))] [RequiresTestSettings] public void EnvironmentVariablesSpaces(ITestSettings settings) { this.TestPurpose("Tests environment variables that include a space"); TestEnvironmentVariable(settings, "VAR_NAME_1", "string with spaces", false); } [Theory] [DependsOnTest(nameof(CompileKitchenSinkForEnvironmentTests))] [RequiresTestSettings] // Need to support 'runInTerminal' request. // darwin-debug does not support spaces in environment variables [UnsupportedDebugger(SupportedDebugger.VsDbg | SupportedDebugger.Lldb, SupportedArchitecture.x86 | SupportedArchitecture.x64)] public void EnvironmentVariablesSpacesNewTerminal(ITestSettings settings) { this.TestPurpose("Tests environment variables that include a space in a new terminal window"); TestEnvironmentVariable(settings, "VAR_NAME_1", "string with spaces", true); } [Theory(Skip = "Need to modify the debuggee so that the name of the environment variable is not hardcoded.")] [DependsOnTest(nameof(CompileKitchenSinkForEnvironmentTests))] [RequiresTestSettings] [SupportedDebugger(SupportedDebugger.VsDbg, SupportedArchitecture.x86 | SupportedArchitecture.x64)] public void EnvironmentVariablesSpecialCharactersName(ITestSettings settings) { this.TestPurpose("Tests environment variables that include a space in a new terminal window"); TestEnvironmentVariable(settings, "_(){}[]$*+-\\/\"#',;.@!?", "simpleValue", true); } private void TestEnvironmentVariable(ITestSettings settings, string variableName, string variableValue, bool newTerminal) { this.WriteSettings(settings); IDebuggee debuggee = SinkHelper.Open(this, settings.CompilerSettings, DebuggeeMonikers.KitchenSink.Environment); using (IDebuggerRunner runner = CreateDebugAdapterRunner(settings)) { this.Comment("Configure launch"); LaunchCommand launch = new LaunchCommand(settings.DebuggerSettings, debuggee.OutputPath, false, "-fEnvironment") { StopAtEntry = false }; if (variableValue != null) { launch.Args.environment = new EnvironmentEntry[] { new EnvironmentEntry { Name = variableName, Value = variableValue } }; } launch.Args.externalConsole = newTerminal; runner.RunCommand(launch); this.Comment("Set breakpoint"); runner.SetBreakpoints(debuggee.Breakpoints(SinkHelper.Environment, 14)); runner.Expects.StoppedEvent(StoppedReason.Breakpoint).AfterConfigurationDone(); using (IThreadInspector threadInspector = runner.GetThreadInspector()) { IFrameInspector currentFrame = threadInspector.Stack.First(); this.Comment("Verify locals variables on current frame."); currentFrame.AssertEvaluateAsString("varValue1", EvaluateContext.Watch, variableValue); } this.Comment("Continue until end"); runner.Expects.ExitedEvent() .TerminatedEvent() .AfterContinue(); runner.DisconnectAndVerify(); } } #endregion } } <|start_filename|>src/AndroidDebugLauncher/NdkToolVersion.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AndroidDebugLauncher { internal struct NdkToolVersion : IComparable<NdkToolVersion> { /// <summary> /// [Optional] array of version parts (ex: { major, minor, etc }). This will be null if the default constructor is called. /// </summary> private readonly uint[] _versionParts; /// <summary> /// Creates a new NdkVersion structure /// </summary> /// <param name="versionParts">[Required] array of units for each part (ex: { major, minor, etc })</param> public NdkToolVersion(uint[] versionParts) { if (versionParts == null) { throw new ArgumentNullException(nameof(versionParts)); } _versionParts = versionParts; } /// <summary> /// Compare this version to another /// </summary> /// <param name="other">value to compare against</param> /// <returns> /// Less than zero: This object is less than the other parameter. /// Zero: This object is equal to other. /// Greater than zero: This object is greater than other. /// </returns> public int CompareTo(NdkToolVersion other) { for (int index = 0; true; index++) { if (index >= this.Length) { if (index != other.Length) { return -1; // 'other' is larger } else { return 0; // equal } } else if (index >= other.Length) { return 1; // 'this' is larger } uint thisPart = _versionParts[index]; uint otherPart = other._versionParts[index]; if (thisPart != otherPart) { if (thisPart > otherPart) return 1; else return -1; } } } public static bool TryParse(string versionString, out NdkToolVersion version) { string[] versionPartStrings = versionString.Split('.'); if (versionPartStrings.Length < 2) { version = new NdkToolVersion(); return false; } uint[] versionParts = new uint[versionPartStrings.Length]; for (int c = 0; c < versionParts.Length; c++) { if (!uint.TryParse(versionPartStrings[c], NumberStyles.None, CultureInfo.InvariantCulture, out versionParts[c])) { version = new NdkToolVersion(); return false; } } version = new NdkToolVersion(versionParts); return true; } public override string ToString() { if (_versionParts == null) { throw new InvalidOperationException(); } IEnumerable<string> parts = _versionParts.Select((x) => x.ToString(CultureInfo.InvariantCulture)); return string.Join(".", parts); } private int Length { get { return _versionParts != null ? _versionParts.Length : 0; } } } } <|start_filename|>src/MIDebugEngine/AD7.Impl/AD7Events.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Text; using Microsoft.VisualStudio.Debugger.Interop; using MICore; using System.Diagnostics; using System.Globalization; // This file contains the various event objects that are sent to the debugger from the sample engine via IDebugEventCallback2::Event. // These are used in EngineCallback.cs. // The events are how the engine tells the debugger about what is happening in the debuggee process. // There are three base classe the other events derive from: AD7AsynchronousEvent, AD7StoppingEvent, and AD7SynchronousEvent. These // each implement the IDebugEvent2.GetAttributes method for the type of event they represent. // Most events sent the debugger are asynchronous events. namespace Microsoft.MIDebugEngine { #region Event base classes internal class AD7AsynchronousEvent : IDebugEvent2 { public const uint Attributes = (uint)enum_EVENTATTRIBUTES.EVENT_ASYNCHRONOUS; int IDebugEvent2.GetAttributes(out uint eventAttributes) { eventAttributes = Attributes; return Constants.S_OK; } } internal class AD7StoppingEvent : IDebugEvent2 { public const uint Attributes = (uint)enum_EVENTATTRIBUTES.EVENT_ASYNC_STOP; int IDebugEvent2.GetAttributes(out uint eventAttributes) { eventAttributes = Attributes; return Constants.S_OK; } } internal class AD7SynchronousEvent : IDebugEvent2 { public const uint Attributes = (uint)enum_EVENTATTRIBUTES.EVENT_SYNCHRONOUS; int IDebugEvent2.GetAttributes(out uint eventAttributes) { eventAttributes = Attributes; return Constants.S_OK; } } internal class AD7SynchronousStoppingEvent : IDebugEvent2 { public const uint Attributes = (uint)enum_EVENTATTRIBUTES.EVENT_STOPPING | (uint)enum_EVENTATTRIBUTES.EVENT_SYNCHRONOUS; int IDebugEvent2.GetAttributes(out uint eventAttributes) { eventAttributes = Attributes; return Constants.S_OK; } } #endregion // The debug engine (DE) sends this interface to the session debug manager (SDM) when an instance of the DE is created. internal sealed class AD7EngineCreateEvent : AD7AsynchronousEvent, IDebugEngineCreateEvent2 { public const string IID = "FE5B734C-759D-4E59-AB04-F103343BDD06"; private IDebugEngine2 _engine; private AD7EngineCreateEvent(AD7Engine engine) { _engine = engine; } public static void Send(AD7Engine engine) { AD7EngineCreateEvent eventObject = new AD7EngineCreateEvent(engine); engine.Callback.Send(eventObject, IID, null, null); } int IDebugEngineCreateEvent2.GetEngine(out IDebugEngine2 engine) { engine = _engine; return Constants.S_OK; } } // This interface is sent by the debug engine (DE) to the session debug manager (SDM) when a program is attached to. internal sealed class AD7ProgramCreateEvent : AD7SynchronousEvent, IDebugProgramCreateEvent2 { public const string IID = "96CD11EE-ECD4-4E89-957E-B5D496FC4139"; internal static void Send(AD7Engine engine) { AD7ProgramCreateEvent eventObject = new AD7ProgramCreateEvent(); engine.Callback.Send(eventObject, IID, engine, null); } } // This interface is sent by the debug engine (DE) to the session debug manager (SDM) when a module is loaded or unloaded. internal sealed class AD7ModuleLoadEvent : AD7AsynchronousEvent, IDebugModuleLoadEvent2 { public const string IID = "989DB083-0D7C-40D1-A9D9-921BF611A4B2"; private readonly AD7Module _module; private readonly bool _fLoad; public AD7ModuleLoadEvent(AD7Module module, bool fLoad) { _module = module; _fLoad = fLoad; } int IDebugModuleLoadEvent2.GetModule(out IDebugModule2 module, ref string debugMessage, ref int fIsLoad) { module = _module; if (_fLoad) { string symbolLoadStatus = _module.DebuggedModule.SymbolsLoaded ? ResourceStrings.ModuleLoadedWithSymbols : ResourceStrings.ModuleLoadedWithoutSymbols; debugMessage = string.Format(CultureInfo.CurrentCulture, ResourceStrings.ModuleLoadMessage, _module.DebuggedModule.Name, symbolLoadStatus); fIsLoad = 1; } else { debugMessage = string.Format(CultureInfo.CurrentCulture, ResourceStrings.ModuleUnloadMessage, _module.DebuggedModule.Name); fIsLoad = 0; } return Constants.S_OK; } } // This interface is sent by the debug engine (DE) to the session debug manager (SDM) when a modules symbols are loaded. internal sealed class AD7SymbolLoadEvent : AD7AsynchronousEvent, IDebugSymbolSearchEvent2 { public const string IID = "EA5B9681-2CE5-4F7A-B842-5183911CE5C6"; private readonly AD7Module _module; public AD7SymbolLoadEvent(AD7Module module) { _module = module; } int IDebugSymbolSearchEvent2.GetSymbolSearchInfo(out IDebugModule3 pModule, ref string pbstrDebugMessage, enum_MODULE_INFO_FLAGS[] pdwModuleInfoFlags) { pModule = _module; pdwModuleInfoFlags[0] = enum_MODULE_INFO_FLAGS.MIF_SYMBOLS_LOADED; return Constants.S_OK; } } // This interface is sent by the debug engine (DE) to the session debug manager (SDM) when a program has run to completion // or is otherwise destroyed. internal sealed class AD7ProgramDestroyEvent : AD7SynchronousEvent, IDebugProgramDestroyEvent2 { public const string IID = "E147E9E3-6440-4073-A7B7-A65592C714B5"; private readonly uint _exitCode; public AD7ProgramDestroyEvent(uint exitCode) { _exitCode = exitCode; } #region IDebugProgramDestroyEvent2 Members int IDebugProgramDestroyEvent2.GetExitCode(out uint exitCode) { exitCode = _exitCode; return Constants.S_OK; } #endregion } internal sealed class AD7MessageEvent : IDebugEvent2, IDebugMessageEvent2 { public const string IID = "3BDB28CF-DBD2-4D24-AF03-01072B67EB9E"; private readonly OutputMessage _outputMessage; private readonly bool _isAsync; public AD7MessageEvent(OutputMessage outputMessage, bool isAsync) { _outputMessage = outputMessage; _isAsync = isAsync; } int IDebugEvent2.GetAttributes(out uint eventAttributes) { if (_isAsync) eventAttributes = (uint)enum_EVENTATTRIBUTES.EVENT_ASYNCHRONOUS; else eventAttributes = (uint)enum_EVENTATTRIBUTES.EVENT_IMMEDIATE; return Constants.S_OK; } int IDebugMessageEvent2.GetMessage(enum_MESSAGETYPE[] pMessageType, out string pbstrMessage, out uint pdwType, out string pbstrHelpFileName, out uint pdwHelpId) { return ConvertMessageToAD7(_outputMessage, pMessageType, out pbstrMessage, out pdwType, out pbstrHelpFileName, out pdwHelpId); } internal static int ConvertMessageToAD7(OutputMessage outputMessage, enum_MESSAGETYPE[] pMessageType, out string pbstrMessage, out uint pdwType, out string pbstrHelpFileName, out uint pdwHelpId) { const uint MB_ICONERROR = 0x00000010; const uint MB_ICONWARNING = 0x00000030; pMessageType[0] = outputMessage.MessageType; pbstrMessage = outputMessage.Message; pdwType = 0; if ((outputMessage.MessageType & enum_MESSAGETYPE.MT_TYPE_MASK) == enum_MESSAGETYPE.MT_MESSAGEBOX) { switch (outputMessage.SeverityValue) { case OutputMessage.Severity.Error: pdwType |= MB_ICONERROR; break; case OutputMessage.Severity.Warning: pdwType |= MB_ICONWARNING; break; } } pbstrHelpFileName = null; pdwHelpId = 0; return Constants.S_OK; } int IDebugMessageEvent2.SetResponse(uint dwResponse) { return Constants.S_OK; } } internal sealed class AD7ErrorEvent : IDebugEvent2, IDebugErrorEvent2 { public const string IID = "FDB7A36C-8C53-41DA-A337-8BD86B14D5CB"; private readonly OutputMessage _outputMessage; private readonly bool _isAsync; public AD7ErrorEvent(OutputMessage outputMessage, bool isAsync) { _outputMessage = outputMessage; _isAsync = isAsync; } int IDebugEvent2.GetAttributes(out uint eventAttributes) { if (_isAsync) eventAttributes = (uint)enum_EVENTATTRIBUTES.EVENT_ASYNCHRONOUS; else eventAttributes = (uint)enum_EVENTATTRIBUTES.EVENT_IMMEDIATE; return Constants.S_OK; } int IDebugErrorEvent2.GetErrorMessage(enum_MESSAGETYPE[] pMessageType, out string errorFormat, out int hrErrorReason, out uint pdwType, out string helpFilename, out uint pdwHelpId) { hrErrorReason = unchecked((int)_outputMessage.ErrorCode); return AD7MessageEvent.ConvertMessageToAD7(_outputMessage, pMessageType, out errorFormat, out pdwType, out helpFilename, out pdwHelpId); } } internal sealed class AD7BreakpointErrorEvent : AD7AsynchronousEvent, IDebugBreakpointErrorEvent2 { public const string IID = "ABB0CA42-F82B-4622-84E4-6903AE90F210"; private AD7ErrorBreakpoint _error; public AD7BreakpointErrorEvent(AD7ErrorBreakpoint error) { _error = error; } public int GetErrorBreakpoint(out IDebugErrorBreakpoint2 ppErrorBP) { ppErrorBP = _error; return Constants.S_OK; } } internal sealed class AD7BreakpointUnboundEvent : AD7AsynchronousEvent, IDebugBreakpointUnboundEvent2 { public const string IID = "78d1db4f-c557-4dc5-a2dd-5369d21b1c8c"; private readonly enum_BP_UNBOUND_REASON _reason; private AD7BoundBreakpoint _bp; public AD7BreakpointUnboundEvent(AD7BoundBreakpoint bp, enum_BP_UNBOUND_REASON reason) { _reason = reason; _bp = bp; } public int GetBreakpoint(out IDebugBoundBreakpoint2 ppBP) { ppBP = _bp; return Constants.S_OK; } public int GetReason(enum_BP_UNBOUND_REASON[] pdwUnboundReason) { pdwUnboundReason[0] = _reason; return Constants.S_OK; } } // This interface is sent by the debug engine (DE) to the session debug manager (SDM) when a thread is created in a program being debugged. internal sealed class AD7ThreadCreateEvent : AD7AsynchronousEvent, IDebugThreadCreateEvent2 { public const string IID = "2090CCFC-70C5-491D-A5E8-BAD2DD9EE3EA"; } // This interface is sent by the debug engine (DE) to the session debug manager (SDM) when a thread has exited. internal sealed class AD7ThreadDestroyEvent : AD7AsynchronousEvent, IDebugThreadDestroyEvent2 { public const string IID = "2C3B7532-A36F-4A6E-9072-49BE649B8541"; private readonly uint _exitCode; public AD7ThreadDestroyEvent(uint exitCode) { _exitCode = exitCode; } #region IDebugThreadDestroyEvent2 Members int IDebugThreadDestroyEvent2.GetExitCode(out uint exitCode) { exitCode = _exitCode; return Constants.S_OK; } #endregion } // This interface is sent by the debug engine (DE) to the session debug manager (SDM) when a program is loaded, but before any code is executed. internal sealed class AD7LoadCompleteEvent : AD7AsynchronousEvent, IDebugLoadCompleteEvent2 { public const string IID = "B1844850-1349-45D4-9F12-495212F5EB0B"; public AD7LoadCompleteEvent() { } } internal sealed class AD7EntryPointEvent : AD7StoppingEvent, IDebugEntryPointEvent2 { public const string IID = "E8414A3E-1642-48EC-829E-5F4040E16DA9"; public AD7EntryPointEvent() { } } internal sealed class AD7ExpressionCompleteEvent : AD7AsynchronousEvent, IDebugExpressionEvaluationCompleteEvent2 { private AD7Engine _engine; public const string IID = "C0E13A85-238A-4800-8315-D947C960A843"; public AD7ExpressionCompleteEvent(AD7Engine engine, IVariableInformation var, IDebugProperty2 prop = null) { _engine = engine; _var = var; _prop = prop; } public int GetExpression(out IDebugExpression2 expr) { expr = new AD7Expression(_engine, _var); return Constants.S_OK; } public int GetResult(out IDebugProperty2 prop) { prop = _prop != null ? _prop : new AD7Property(_engine, _var); return Constants.S_OK; } private IVariableInformation _var; private IDebugProperty2 _prop; } // This interface tells the session debug manager (SDM) that an exception has occurred in the debuggee. internal sealed class AD7ExceptionEvent : AD7StoppingEvent, IDebugExceptionEvent2 { public const string IID = "51A94113-8788-4A54-AE15-08B74FF922D0"; public AD7ExceptionEvent(string name, string description, uint code, Guid? exceptionCategory, ExceptionBreakpointStates state) { _name = name; _code = code; _description = string.IsNullOrEmpty(description) ? name : description; _category = exceptionCategory ?? EngineConstants.EngineId; switch (state) { case ExceptionBreakpointStates.None: _state = enum_EXCEPTION_STATE.EXCEPTION_STOP_SECOND_CHANCE; break; case ExceptionBreakpointStates.BreakThrown: _state = enum_EXCEPTION_STATE.EXCEPTION_STOP_FIRST_CHANCE | enum_EXCEPTION_STATE.EXCEPTION_STOP_USER_FIRST_CHANCE; break; case ExceptionBreakpointStates.BreakUserHandled: _state = enum_EXCEPTION_STATE.EXCEPTION_STOP_USER_UNCAUGHT; break; default: Debug.Fail("Unexpected state value"); _state = enum_EXCEPTION_STATE.EXCEPTION_STOP_SECOND_CHANCE; break; } } #region IDebugExceptionEvent2 Members public int CanPassToDebuggee() { // Cannot pass it on return Constants.S_FALSE; } public int GetException(EXCEPTION_INFO[] pExceptionInfo) { EXCEPTION_INFO ex = new EXCEPTION_INFO(); ex.bstrExceptionName = _name; ex.dwCode = _code; ex.dwState = _state; ex.guidType = _category; pExceptionInfo[0] = ex; return Constants.S_OK; } public int GetExceptionDescription(out string pbstrDescription) { pbstrDescription = _description; return Constants.S_OK; } public int PassToDebuggee(int fPass) { return Constants.S_OK; } private string _name; private uint _code; private string _description; private Guid _category; private enum_EXCEPTION_STATE _state; #endregion } // This interface tells the session debug manager (SDM) that a step has completed internal sealed class AD7StepCompleteEvent : AD7StoppingEvent, IDebugStepCompleteEvent2 { public const string IID = "0f7f24c1-74d9-4ea6-a3ea-7edb2d81441d"; } // This interface tells the session debug manager (SDM) that an asynchronous break has been successfully completed. internal sealed class AD7AsyncBreakCompleteEvent : AD7StoppingEvent, IDebugBreakEvent2 { public const string IID = "c7405d1d-e24b-44e0-b707-d8a5a4e1641b"; } // This interface is sent by the debug engine (DE) to the session debug manager (SDM) to output a string for debug tracing. internal sealed class AD7OutputDebugStringEvent : AD7AsynchronousEvent, IDebugOutputStringEvent2 { public const string IID = "569c4bb1-7b82-46fc-ae28-4536ddad753e"; private string _str; public AD7OutputDebugStringEvent(string str) { _str = str; } #region IDebugOutputStringEvent2 Members int IDebugOutputStringEvent2.GetString(out string pbstrString) { pbstrString = _str; return Constants.S_OK; } #endregion } // This interface is sent when a pending breakpoint has been bound in the debuggee. internal sealed class AD7BreakpointBoundEvent : AD7AsynchronousEvent, IDebugBreakpointBoundEvent2 { public const string IID = "1dddb704-cf99-4b8a-b746-dabb01dd13a0"; private AD7PendingBreakpoint _pendingBreakpoint; private AD7BoundBreakpoint _boundBreakpoint; public AD7BreakpointBoundEvent(AD7PendingBreakpoint pendingBreakpoint, AD7BoundBreakpoint boundBreakpoint) { _pendingBreakpoint = pendingBreakpoint; _boundBreakpoint = boundBreakpoint; } #region IDebugBreakpointBoundEvent2 Members int IDebugBreakpointBoundEvent2.EnumBoundBreakpoints(out IEnumDebugBoundBreakpoints2 ppEnum) { IDebugBoundBreakpoint2[] boundBreakpoints = new IDebugBoundBreakpoint2[1]; boundBreakpoints[0] = _boundBreakpoint; ppEnum = new AD7BoundBreakpointsEnum(boundBreakpoints); return Constants.S_OK; } int IDebugBreakpointBoundEvent2.GetPendingBreakpoint(out IDebugPendingBreakpoint2 ppPendingBP) { ppPendingBP = _pendingBreakpoint; return Constants.S_OK; } #endregion } // This Event is sent when a breakpoint is hit in the debuggee internal sealed class AD7BreakpointEvent : AD7StoppingEvent, IDebugBreakpointEvent2 { public const string IID = "501C1E21-C557-48B8-BA30-A1EAB0BC4A74"; IDebugBoundBreakpoint2[] _boundBreakpoints; public AD7BreakpointEvent(IDebugBoundBreakpoint2[] boundBreakpoints) { _boundBreakpoints = boundBreakpoints; } #region IDebugBreakpointEvent2 Members int IDebugBreakpointEvent2.EnumBreakpoints(out IEnumDebugBoundBreakpoints2 ppEnum) { ppEnum = new AD7BoundBreakpointsEnum(_boundBreakpoints); return Constants.S_OK; } #endregion } internal sealed class AD7StopCompleteEvent : AD7StoppingEvent, IDebugStopCompleteEvent2 { public const string IID = "3DCA9DCD-FB09-4AF1-A926-45F293D48B2D"; } internal sealed class AD7ProcessInfoUpdatedEvent : AD7AsynchronousEvent, IDebugProcessInfoUpdatedEvent158 { public const string IID = "96C242FC-F584-4C3E-8FED-384D3D13EF36"; private readonly string _name; private readonly uint _pid; public AD7ProcessInfoUpdatedEvent(string name, uint pid) { _name = name; _pid = pid; } public int GetUpdatedProcessInfo(out string pbstrName, out uint pdwSystemProcessId) { pbstrName = _name; pdwSystemProcessId = _pid; return Constants.S_OK; } internal static void Send(AD7Engine engine, string name, uint pid) { AD7ProcessInfoUpdatedEvent eventObject = new AD7ProcessInfoUpdatedEvent(name, pid); engine.Callback.Send(eventObject, IID, engine, null); } } internal sealed class AD7CustomDebugEvent : AD7AsynchronousEvent, IDebugCustomEvent110 { public const string IID = "2615D9BC-1948-4D21-81EE-7A963F20CF59"; private readonly Guid _guidVSService; private readonly Guid _sourceId; private readonly int _messageCode; private readonly object _parameter1; private readonly object _parameter2; public AD7CustomDebugEvent(Guid guidVSService, Guid sourceId, int messageCode, object parameter1, object parameter2) { _guidVSService = guidVSService; _sourceId = sourceId; _messageCode = messageCode; _parameter1 = parameter1; _parameter2 = parameter2; } int IDebugCustomEvent110.GetCustomEventInfo(out Guid guidVSService, VsComponentMessage[] message) { guidVSService = _guidVSService; message[0].SourceId = _sourceId; message[0].MessageCode = (uint)_messageCode; message[0].Parameter1 = _parameter1; message[0].Parameter2 = _parameter2; return Constants.S_OK; } } } <|start_filename|>test/DebuggerTesting/Compilation/VisualCPlusPlusCompiler.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.IO; using System.Linq; using DebuggerTesting.Utilities; namespace DebuggerTesting.Compilation { internal class VisualCPlusPlusCompiler : CompilerBase { public VisualCPlusPlusCompiler(ILoggingComponent logger, ICompilerSettings settings) : base(logger, settings, addDebuggerDirToPath: false) { } protected override bool CompileCore( CompilerOutputType outputType, SupportedArchitecture architecture, IEnumerable<string> libraries, IEnumerable<string> sourceFilePaths, string targetFilePath, CompilerOption options, IDictionary<string, string> defineConstants) { ArgumentBuilder clBuilder = new ArgumentBuilder("/", ":"); ArgumentBuilder linkBuilder = new ArgumentBuilder("/", ":"); foreach (var defineConstant in defineConstants) { DefineConstant(clBuilder, defineConstant.Key, defineConstant.Value); } DefineConstant(clBuilder, "_WIN32"); // Suppresses error C4996 for 'getenv' (in debuggees/kitchensink/src/environment.cpp) DefineConstant(clBuilder, "_CRT_SECURE_NO_WARNINGS"); if (options.HasFlag(CompilerOption.GenerateSymbols)) { clBuilder.AppendNamedArgument("ZI", null); clBuilder.AppendNamedArgument("Debug", null); } if (!options.HasFlag(CompilerOption.OptimizeLevel1) && !options.HasFlag(CompilerOption.OptimizeLevel2) && !options.HasFlag(CompilerOption.OptimizeLevel3)) { // Disable optimization clBuilder.AppendNamedArgument("Od", null); } // Add options that are set by default in VS AddDefaultOptions(clBuilder); if (this.Settings.Properties != null) { // Get the include folders from the compiler properties string rawIncludes; if(!this.Settings.Properties.TryGetValue("Include", out rawIncludes)) { rawIncludes = String.Empty; } IEnumerable<string> includes = rawIncludes.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries).Select(x => x.Trim()); foreach (string include in includes) { clBuilder.AppendNamedArgumentQuoted("I", include, string.Empty); } // Get the lib folders from the compiler properties string rawLibs; if (!this.Settings.Properties.TryGetValue("Lib", out rawLibs)) { rawLibs = String.Empty; } IEnumerable<string> libs = rawLibs.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries).Select(x => x.Trim()); foreach (string lib in libs) { linkBuilder.AppendNamedArgumentQuoted("LIBPATH", lib); } } switch (outputType) { case CompilerOutputType.SharedLibrary: // Create.DLL clBuilder.AppendNamedArgument("LD", null); clBuilder.AppendNamedArgument("Fo", Path.GetDirectoryName(targetFilePath) + Path.DirectorySeparatorChar); clBuilder.AppendNamedArgument("Fe", targetFilePath); break; case CompilerOutputType.ObjectFile: // Name obj clBuilder.AppendNamedArgument("Fo", targetFilePath); break; case CompilerOutputType.Unspecified: // Treat Unspecified as Executable, since executable is the default case CompilerOutputType.Executable: // Compiling an executable does not have a command line option, it's the default // Name exe clBuilder.AppendNamedArgument("Fo", Path.GetDirectoryName(targetFilePath) + Path.DirectorySeparatorChar); clBuilder.AppendNamedArgument("Fe", targetFilePath); break; default: throw new ArgumentOutOfRangeException(nameof(outputType), "Unhandled output type: " + outputType); } // Specify the PDB name clBuilder.AppendNamedArgument("Fd", Path.ChangeExtension(targetFilePath, "pdb")); // Define a constant for the platform name. DefineConstant(clBuilder, "DEBUGGEE_PLATFORM", GetPlatformName()); DefineConstant(clBuilder, "DEBUGGEE_COMPILER", "Visual C++"); foreach (string sourceFilePath in sourceFilePaths) { clBuilder.AppendArgument(sourceFilePath); } foreach (string library in libraries) { clBuilder.AppendArgument(library); } switch (architecture) { case SupportedArchitecture.x64: DefineConstant(clBuilder, "DEBUGGEE_ARCH", "64"); linkBuilder.AppendNamedArgument("MACHINE", "X64"); break; case SupportedArchitecture.x86: DefineConstant(clBuilder, "DEBUGGEE_ARCH", "32"); linkBuilder.AppendNamedArgument("MACHINE", "X86"); break; default: throw new ArgumentOutOfRangeException(nameof(architecture), "Unhandled target architecture: " + architecture); } // Pass the linker arguments (Note, the link parameter doesn't use the ":" suffix) clBuilder.AppendNamedArgument("link", linkBuilder.ToString(), overrideSuffix: " "); return 0 == this.RunCompiler(clBuilder.ToString(), targetFilePath); } protected static void DefineConstant(ArgumentBuilder clBuilder, string name, string value = null) { string constant = name; if (value != null) constant += "=" + ArgumentBuilder.MakeQuotedIfRequired(value); clBuilder.AppendNamedArgument("D", constant, overrideSuffix: string.Empty); } private static void AddDefaultOptions(ArgumentBuilder clBuilder) { // Make wchar_t a native type clBuilder.AppendNamedArgument("Zc", "wchar_t"); // Remove unreferenced function or data clBuilder.AppendNamedArgument("Zc", "inline"); // Use standard C++ scope rules clBuilder.AppendNamedArgument("Zc", "forScope"); // Minimal rebuild clBuilder.AppendNamedArgument("Gm", null); // Enable C++ exceptions clBuilder.AppendNamedArgument("EHsc", null); // Multi-threaded debug dll clBuilder.AppendNamedArgument("MDd", null); // Floating point mode clBuilder.AppendNamedArgument("fp", "precise"); // Turn on warnings and treat as errors clBuilder.AppendNamedArgument("W3", null); clBuilder.AppendNamedArgument("WX", null); // Turn on sdl warnings clBuilder.AppendNamedArgument("sdl", null); // __cdecl calling convention clBuilder.AppendNamedArgument("Gd", null); } } } <|start_filename|>test/CppTests/debuggees/kitchensink/src/nonterminating.h<|end_filename|> #pragma once #include "global.h" #include <iostream> #include <vector> #include <string> #include <thread> #include <stdarg.h> #include <condition_variable> #include <chrono> #include "feature.h" using namespace std; class NonTerminating : public Feature { public: NonTerminating(); virtual void CoreRun(); bool shouldExit = false; private: void DoSleep(); }; <|start_filename|>test/CppTests/OpenDebug/CrossPlatCpp/DebuggerRunner.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Text.RegularExpressions; using System.Threading; using DebugAdapterRunner; using DebuggerTesting.OpenDebug.Commands; using DebuggerTesting.Settings; using DebuggerTesting.Utilities; using Xunit; using Xunit.Abstractions; using DarRunner = DebugAdapterRunner.DebugAdapterRunner; namespace DebuggerTesting.OpenDebug.CrossPlatCpp { /// <summary> /// Provides a wrapper to initialize and close a debug adapter. /// The constructur will initiate the connection to the debug adapter. /// Disposing this wrapper will close the connection. /// </summary> public class DebuggerRunner : DisposableObject, IDebuggerRunner { #if DEBUG private IDebugFailUI savedDebugFailUI; #endif private string engineLogPath; private static Regex _engineLogRegEx; #region Constructor/Create/Dispose private DebuggerRunner(ILoggingComponent logger, ITestSettings testSettings, IEnumerable<Tuple<string, CallbackRequestHandler>> callbackHandlers) { Parameter.ThrowIfNull(testSettings, nameof(testSettings)); this.OutputHelper = logger.OutputHelper; this.DebuggerSettings = testSettings.DebuggerSettings; #if DEBUG this.savedDebugFailUI = UDebug.DebugFailUI; UDebug.DebugFailUI = new XUnitDefaultDebugFailUI(this.OutputHelper); #endif this.WriteLine("Creating Debug Adapter Runner."); string adapterId = (this.DebuggerSettings.DebuggerType == SupportedDebugger.VsDbg) ? "cppvsdbg" : "cppdbg"; string debugAdapterRelativePath = this.DebuggerSettings.DebuggerAdapterPath ?? "OpenDebugAD7"; string debugAdapterFullPath = Path.Combine(PathSettings.DebugAdaptersPath, debugAdapterRelativePath); Assert.True(Directory.Exists(Path.GetDirectoryName(debugAdapterFullPath)), "Debug Adapter Path {0} does not exist.".FormatInvariantWithArgs(debugAdapterFullPath)); // Output engine log to temp folder if requested. this.engineLogPath = Path.Combine(PathSettings.TempPath, "EngineLog-{0}-{1}-{2}.log".FormatInvariantWithArgs(testSettings.Name, testSettings.DebuggerSettings.DebuggeeArchitecture.ToString(), testSettings.DebuggerSettings.DebuggerType.ToString())); this.WriteLine("Logging engine to: {0}", this.engineLogPath); this.DarRunner = new DarRunner( adapterPath: debugAdapterFullPath, traceDebugAdapterOutput: DiagnosticsSettings.LogDebugAdapter ? DebugAdapterRunner.TraceDebugAdapterMode.Memory : DebugAdapterRunner.TraceDebugAdapterMode.None, engineLogPath: this.engineLogPath, pauseForDebugger: false, isVsDbg: this.DebuggerSettings.DebuggerType == SupportedDebugger.VsDbg, isNative: true, responseTimeout: 5000); if (callbackHandlers != null) { foreach (Tuple<string, CallbackRequestHandler> handlerPair in callbackHandlers) { this.DarRunner.AddCallbackRequestHandler(handlerPair.Item1, handlerPair.Item2); } } this.WriteLine("Initializing debugger."); this.initializeResponse = this.RunCommand(new InitializeCommand(adapterId)); } public static IDebuggerRunner Create(ILoggingComponent logger, ITestSettings testSettings, IEnumerable<Tuple<string, CallbackRequestHandler>> callbackHandlers) { return new DebuggerRunner(logger, testSettings, callbackHandlers); } protected override void Dispose(bool isDisposing) { // If we disposed is called and the adapter is still running, send // a disconnect command. if (isDisposing) { #if DEBUG UDebug.DebugFailUI = this.savedDebugFailUI; #endif this.DisconnectDebugAdapter(throwOnFailure: false); } else { try { // If in the finalizer, just try to kill the process if (this.DarRunner?.DebugAdapter?.HasExited == false) { ProcessHelper.KillProcess(this.DarRunner.DebugAdapter, recurse: true); } } catch (InvalidOperationException e) { // If the process has exited but is already cleaned up, it will throw an InvalidOperationException with the message "Process has not been started" this.WriteLine("InvalidOperationException: {0}. /n StackTrace: {1}", e.Message, e.StackTrace); } } base.Dispose(isDisposing); } /// <summary> /// Call this to close the debug adapter. If child processes still exist /// this will throw. /// </summary> public void DisconnectAndVerify() { this.DisconnectDebugAdapter(throwOnFailure: true); } private void DisconnectDebugAdapter(bool throwOnFailure) { if (this.DarRunner?.DebugAdapter?.HasExited == false) { this.Comment("Disconnecting Debug Adapter Runner."); this.RunCommand(new DisconnectCommand()); // Wait 60 seconds for the adapter to close int attempts = 0; int maxAttempts = 10 * 60; // 60 seconds while (this.DarRunner.DebugAdapter.HasExited == false && attempts < maxAttempts) { Thread.Sleep(100); attempts++; } } // If the adapter is still running, forcibly stop it if (this.DarRunner?.DebugAdapter?.HasExited == false) { this.Comment("Killing Debug Adapter Runner."); int killCount = ProcessHelper.KillProcess(this.DarRunner.DebugAdapter, recurse: true); this.WriteLine("Killed {0} process(es).", killCount); // At this point the test is likely throwing a failure exception. // Failing the test due to failed cleanup will probably mask the error. // Just log the output to the test log. this.WriteLine("ERROR: Debug adapter was still running. Found and killed extra processes."); Assert.False(throwOnFailure, "ERROR: Debug adapter still running. Processes not cleaned up properly."); } if (!throwOnFailure && DiagnosticsSettings.LogDebugAdapter) { this.Comment("Debug Adapter Log"); this.WriteLine(this.DarRunner.DebugAdapterOutput); } // Check for any abandoned debugger files or processes this.CheckDebuggerArtifacts(throwOnFailure); } private static Regex EngineLogRegEx { get { const string engineLogArtifacts = @".*TempFile=(?<tempFile>.+)|" + @".*ShellPid=(?<shellPid>\d+)|" + @".*DebuggerPid=(?<debuggerPid>\d+)"; if (_engineLogRegEx == null) _engineLogRegEx = new Regex(engineLogArtifacts, RegexOptions.Compiled | RegexOptions.Multiline); return _engineLogRegEx; } } /// <summary> /// Check for abandoned files or processes /// </summary> /// <param name="throwOnFailure">Fail the test if abandoned artifacts found</param> private void CheckDebuggerArtifacts(bool throwOnFailure) { try { if (string.IsNullOrEmpty(this.engineLogPath) || !File.Exists(this.engineLogPath)) return; string engineLogContent = File.ReadAllText(this.engineLogPath); // Add the MIEngine log to the test log (if it is enabled) if (!throwOnFailure && DiagnosticsSettings.LogMIEngine) { this.Comment("Engine Log"); this.WriteLine(engineLogContent); } // Parse the mi engine's log to find associated temp files and debugger pids // This only checks for any process ids or files logged by the mi engine // and may not be a complete list. List<string> tempFiles = new List<string>(3); List<int> associatedPids = new List<int>(2); foreach (Match match in EngineLogRegEx.Matches(engineLogContent)) { string tempFile = match.Groups?["tempFile"]?.Value; string shellPid = match.Groups?["shellPid"]?.Value; string debuggerPid = match.Groups?["debuggerPid"]?.Value; if (!string.IsNullOrEmpty(tempFile)) tempFiles.Add(tempFile); else if (!string.IsNullOrEmpty(shellPid)) associatedPids.Add(int.Parse(shellPid, CultureInfo.InvariantCulture)); else if (!string.IsNullOrEmpty(debuggerPid)) associatedPids.Add(int.Parse(debuggerPid, CultureInfo.InvariantCulture)); } // Check for abandoned temp files foreach (string tempFile in tempFiles) { if (File.Exists(tempFile)) { this.WriteLine("ERROR: Debug Adapter abandoned temp file: " + tempFile); TryDeleteFile(tempFile); Assert.False(throwOnFailure, "ERROR: Debug Adapter abandoned temp file: " + tempFile); } } // Check for abandoned processes foreach (int associatedPid in associatedPids) { if (ProcessHelper.IsProcessRunning(associatedPid)) { this.WriteLine("ERROR: Debug Adapter abandoned process: " + associatedPid.ToString(CultureInfo.InvariantCulture)); ProcessHelper.KillProcess(associatedPid, recurse: true); Assert.False(throwOnFailure, "ERROR: Debug Adapter abandoned process: " + associatedPid.ToString(CultureInfo.InvariantCulture)); } } } catch (Exception ex) { this.WriteLine("Error checking engine log. {0}", UDebug.ExceptionToString(ex)); } } private static void TryDeleteFile(string tempFile) { // This is already in cleanup code, ignore exceptions try { File.Delete(tempFile); } catch (IOException) { } } #endregion #region ILoggingComponent Members public ITestOutputHelper OutputHelper { get; private set; } #endregion #region IDebuggerRunner Members public IDebuggerSettings DebuggerSettings { get; private set; } private InitializeResponseValue initializeResponse { get; set; } InitializeResponseValue IDebuggerRunner.InitializeResponse { get { return this.initializeResponse; } } public bool ErrorEncountered { get; set; } public DarRunner DarRunner { get; private set; } public R RunCommand<R>(ICommandWithResponse<R> command, params IEvent[] expectedEvents) { return command.Run(this, expectedEvents); } public void RunCommand(ICommand command, params IEvent[] expectedEvents) { command.Run(this, expectedEvents); } /// <summary> /// This gets populated when a stopped event occurs. It has the thread /// id of the stopped thread. /// </summary> public int StoppedThreadId { get { return this.DarRunner.CurrentThreadId; } } public IRunBuilder Expects { get { return new RunBuilder(this); } } #endregion #region XUnitDefaultDebugFailUI #if DEBUG /// <summary> /// Implements the Debug Fail UI for the UDebug class /// </summary> internal class XUnitDefaultDebugFailUI : IDebugFailUI { private ITestOutputHelper outputHelper; public XUnitDefaultDebugFailUI(ITestOutputHelper outputHelper) { this.outputHelper = outputHelper; } DebugUIResult IDebugFailUI.ShowFailure(string message, string callLocation, string exception, string callStack) { string header = exception + ": " + message; this.outputHelper.WriteLine(header + Environment.NewLine + callStack); Debug.Fail(header, callStack); return DebugUIResult.Ignore; } } #endif //DEBUG #endregion } } <|start_filename|>src/SSHDebugPS/UI/ViewModels/ConnectionViewModel.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using liblinux; using Microsoft.SSHDebugPS.SSH; using Microsoft.VisualStudio.Shell; namespace Microsoft.SSHDebugPS.UI { public interface IConnectionViewModel { string DisplayName { get; } IConnection Connection { get; } } internal class LocalConnectionViewModel : IConnectionViewModel { public LocalConnectionViewModel() { } #region IConnectionViewModel public string DisplayName => UIResources.LocalMachine; public IConnection Connection { get => null; } #endregion } internal class SSHConnectionViewModel : IConnectionViewModel { private ConnectionInfo connectionInfo { get; } internal SSHConnectionViewModel(SSHConnection connection) { this.sshConnection = connection; } internal SSHConnectionViewModel(ConnectionInfo connectionInfo) { this.connectionInfo = connectionInfo; } private SSHConnection sshConnection; protected IConnection GetConnection() { ThreadHelper.ThrowIfNotOnUIThread(); if (this.sshConnection == null) { if (this.connectionInfo != null) { this.sshConnection = SSHHelper.CreateSSHConnectionFromConnectionInfo(connectionInfo); } } return this.sshConnection; } #region IConnectionViewModel public string DisplayName { get { return sshConnection?.Name ?? SSHPortSupplier.GetFormattedSSHConnectionName(connectionInfo); } } public IConnection Connection { get { ThreadHelper.ThrowIfNotOnUIThread(); return GetConnection(); } } #endregion } } <|start_filename|>test/CppTests/Tests/ExpressionTests.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Linq; using DebuggerTesting; using DebuggerTesting.Compilation; using DebuggerTesting.OpenDebug; using DebuggerTesting.OpenDebug.Commands; using DebuggerTesting.OpenDebug.CrossPlatCpp; using DebuggerTesting.OpenDebug.Events; using DebuggerTesting.OpenDebug.Extensions; using DebuggerTesting.Ordering; using DebuggerTesting.Utilities; using Xunit; using Xunit.Abstractions; namespace CppTests.Tests { [TestCaseOrderer(DependencyTestOrderer.TypeName, DependencyTestOrderer.AssemblyName)] public class ExpressionTests : TestBase { #region Constructor public ExpressionTests(ITestOutputHelper outputHelper) : base(outputHelper) { } #endregion #region Methods [Theory] [RequiresTestSettings] public void CompileKitchenSinkForExpressionTests(ITestSettings settings) { this.TestPurpose("Compile kitchen sink debuggee for expression tests."); this.WriteSettings(settings); IDebuggee debuggee = SinkHelper.OpenAndCompile(this, settings.CompilerSettings, DebuggeeMonikers.KitchenSink.Expression); } [Theory] [DependsOnTest(nameof(CompileKitchenSinkForExpressionTests))] [RequiresTestSettings] public void LocalsBasic(ITestSettings settings) { this.TestPurpose("Check primitives displying in locals."); this.WriteSettings(settings); IDebuggee debuggee = SinkHelper.Open(this, settings.CompilerSettings, DebuggeeMonikers.KitchenSink.Expression); using (IDebuggerRunner runner = CreateDebugAdapterRunner(settings)) { this.Comment("Configure launch."); runner.Launch(settings.DebuggerSettings, debuggee, "-fExpression"); this.Comment("Set a line breakpoints so that we can stop."); runner.SetBreakpoints(debuggee.Breakpoints(SinkHelper.Expression, 31)); this.Comment("To start debugging and break"); runner.Expects.StoppedEvent(StoppedReason.Breakpoint).AfterConfigurationDone(); using (IThreadInspector threadInspector = runner.GetThreadInspector()) { IFrameInspector currentFrame = threadInspector.Stack.First(); this.Comment("To verify locals variables on current frame."); Assert.Subset(new HashSet<string>() { "mybool", "mychar", "myint", "mywchar", "myfloat", "mydouble", "this" }, currentFrame.Variables.ToKeySet()); currentFrame.AssertVariables( "mybool", "true", "myint", "100"); currentFrame.GetVariable("mychar").AssertValueAsChar('A'); currentFrame.GetVariable("mywchar").AssertValueAsWChar('z'); currentFrame.GetVariable("myfloat").AssertValueAsFloat(299); currentFrame.GetVariable("mydouble").AssertValueAsDouble(321); } this.Comment("Run to completion"); runner.Expects.TerminatedEvent().AfterContinue(); runner.DisconnectAndVerify(); } } [Theory] [DependsOnTest(nameof(CompileKitchenSinkForExpressionTests))] [RequiresTestSettings] public void WatchBasic(ITestSettings settings) { this.TestPurpose("Evaluate some expressions in watch."); this.WriteSettings(settings); IDebuggee debuggee = SinkHelper.Open(this, settings.CompilerSettings, DebuggeeMonikers.KitchenSink.Expression); using (IDebuggerRunner runner = CreateDebugAdapterRunner(settings)) { this.Comment("Configure launch"); runner.Launch(settings.DebuggerSettings, debuggee, "-fExpression"); this.Comment("Set a line breakpoints so that we can stop."); runner.SetBreakpoints(debuggee.Breakpoints(SinkHelper.Expression, 31)); this.Comment("To start debugging and break"); runner.Expects.StoppedEvent(StoppedReason.Breakpoint).AfterConfigurationDone(); using (IThreadInspector threadInspector = runner.GetThreadInspector()) { IFrameInspector currentFrame = threadInspector.Stack.First(); this.Comment("To evaluate variables and functions in watch."); string evalMyInt = currentFrame.Evaluate("myint-=100", EvaluateContext.Watch); currentFrame.AssertEvaluateAsChar("mychar", EvaluateContext.Watch, 'A'); string evalMyBool = currentFrame.Evaluate("mybool", EvaluateContext.Watch); currentFrame.AssertEvaluateAsWChar("mywchar", EvaluateContext.Watch, 'z'); currentFrame.AssertEvaluateAsDouble("mydouble", EvaluateContext.Watch, 321); currentFrame.AssertEvaluateAsFloat("myfloat", EvaluateContext.Watch, 299); string evalFuncMaxInt = currentFrame.Evaluate("Test::max(myint,1)", EvaluateContext.Watch); currentFrame.AssertEvaluateAsDouble("Test::max(mydouble,0.0)-321.0", EvaluateContext.Watch, 0); Assert.Equal("0", evalMyInt); Assert.Equal("true", evalMyBool); Assert.Equal("1", evalFuncMaxInt); } this.Comment("Run to completion"); runner.Expects.TerminatedEvent().AfterContinue(); runner.DisconnectAndVerify(); } } [Theory] [DependsOnTest(nameof(CompileKitchenSinkForExpressionTests))] [RequiresTestSettings] public void DataTipBasic(ITestSettings settings) { this.TestPurpose("To test evaluation in datatip."); this.WriteSettings(settings); IDebuggee debuggee = SinkHelper.Open(this, settings.CompilerSettings, DebuggeeMonikers.KitchenSink.Expression); using (IDebuggerRunner runner = CreateDebugAdapterRunner(settings)) { this.Comment("Configure launch."); runner.Launch(settings.DebuggerSettings, debuggee, "-fExpression"); this.Comment("To set a breakpoint so that we can stop at somewhere for evaluation."); runner.SetBreakpoints(debuggee.Breakpoints(SinkHelper.Expression, 19)); this.Comment("To start debugging and break"); runner.Expects.StoppedEvent(StoppedReason.Breakpoint).AfterConfigurationDone(); using (IThreadInspector threadInspector = runner.GetThreadInspector()) { IFrameInspector currentFrame; this.Comment("To evaluate in datatip on the first frame."); currentFrame = threadInspector.Stack.First(); Assert.Equal("true", currentFrame.Evaluate("isCalled", EvaluateContext.DataTip)); currentFrame.AssertEvaluateAsDouble("d", EvaluateContext.DataTip, 10.1); // We only verify the major contents in datatip Assert.Contains(@"accumulate(int)", currentFrame.Evaluate("accumulate", EvaluateContext.DataTip), StringComparison.Ordinal); this.Comment("To evaluate in datatip on the fourth frame."); currentFrame = threadInspector.Stack.ElementAt(3); currentFrame.AssertEvaluateAsDouble("mydouble", EvaluateContext.DataTip, double.PositiveInfinity); currentFrame.AssertEvaluateAsChar("mynull", EvaluateContext.DataTip, '\0'); this.Comment("To evaluate in datatip on the fifth frame."); currentFrame = threadInspector.Stack.ElementAt(4); currentFrame.AssertEvaluateAsObject("student", EvaluateContext.DataTip, "name", @"""John""", "age", "10"); Assert.Matches(@"0x[0-9A-Fa-f]+", currentFrame.Evaluate("pStu", EvaluateContext.DataTip)); this.Comment("To evaluate in datatip on the sixth frame."); currentFrame = threadInspector.Stack.ElementAt(5); currentFrame.AssertEvaluateAsIntArray("arr", EvaluateContext.DataTip, 0, 1, 2, 3, 4); Assert.Matches(@"0x[0-9A-Fa-f]+", currentFrame.Evaluate("pArr", EvaluateContext.DataTip)); this.Comment("To evaluate in datatip on the seventh frame."); currentFrame = threadInspector.Stack.ElementAt(6); Assert.Equal("true", currentFrame.Evaluate("mybool", EvaluateContext.DataTip)); Assert.Equal("100", currentFrame.Evaluate("myint", EvaluateContext.DataTip)); currentFrame.AssertEvaluateAsFloat("myfloat", EvaluateContext.DataTip, 299); currentFrame.AssertEvaluateAsDouble("mydouble", EvaluateContext.DataTip, 321); currentFrame.AssertEvaluateAsChar("mychar", EvaluateContext.DataTip, 'A'); currentFrame.AssertEvaluateAsWChar("mywchar", EvaluateContext.DataTip, 'z'); } this.Comment("Continue to run to exist."); runner.Expects.TerminatedEvent().AfterContinue(); runner.DisconnectAndVerify(); } } [Theory] [DependsOnTest(nameof(CompileKitchenSinkForExpressionTests))] // TODO: https://github.com/microsoft/MIEngine/issues/1170 // - lldb [UnsupportedDebugger(SupportedDebugger.Lldb, SupportedArchitecture.x64 | SupportedArchitecture.x86)] [RequiresTestSettings] public void CallStackBasic(ITestSettings settings) { this.TestPurpose("To check all frames of callstack on a thead and evaluation on each frame."); this.WriteSettings(settings); IDebuggee debuggee = SinkHelper.Open(this, settings.CompilerSettings, DebuggeeMonikers.KitchenSink.Expression); this.Comment("Here are stack frames in a list we expect the actual to match with this."); StackFrame[] expectedstackFrames = ExpressionTests.GenerateFramesList(settings.DebuggerSettings); using (IDebuggerRunner runner = CreateDebugAdapterRunner(settings)) { this.Comment("Configure launch."); runner.Launch(settings.DebuggerSettings, debuggee, "-fExpression"); this.Comment("Set a breakpoint so that we can stop after starting debugging."); runner.SetBreakpoints(debuggee.Breakpoints(SinkHelper.Expression, 19)); this.Comment("To start debugging and break"); runner.Expects.StoppedEvent(StoppedReason.Breakpoint, SinkHelper.Expression, 19).AfterConfigurationDone(); this.Comment("To step in several times into the innermost layer of a recursive call."); runner.ExpectStepAndStepToTarget(SinkHelper.Expression, 9, 10).AfterStepIn(); runner.Expects.HitStepEvent(SinkHelper.Expression, 12).AfterStepIn(); runner.ExpectStepAndStepToTarget(SinkHelper.Expression, 9, 10).AfterStepIn(); runner.Expects.HitStepEvent(SinkHelper.Expression, 12).AfterStepIn(); runner.ExpectStepAndStepToTarget(SinkHelper.Expression, 9, 10).AfterStepIn(); using (IThreadInspector threadInspector = runner.GetThreadInspector()) { IEnumerable<IFrameInspector> stackOfCurrentThread = threadInspector.Stack; this.Comment("To verify the count of stack frames count."); Assert.True(stackOfCurrentThread.Count() >= 13, "Expected the stack frame count to be at least 13 deep"); this.Comment("To verify each frame, include frame name, line number and source name."); int index = 0; foreach (IFrameInspector frame in stackOfCurrentThread) { if (index >= 13) break; StackFrame expectedstackFrame = expectedstackFrames[index]; this.Comment("Comparing Names. Expecected: {0}, Actual: {1}", expectedstackFrame.Name, frame.Name); Assert.Contains(expectedstackFrame.Name, frame.Name, StringComparison.Ordinal); this.Comment("Comparing line number. Expecected: {0}, Actual: {1}", expectedstackFrame.Line, frame.Line); Assert.Equal(expectedstackFrame.Line, frame.Line); this.Comment("Comparing Source Name. Expecected: {0}, Actual: {1}", expectedstackFrame.SourceName, frame.SourceName); Assert.Equal(expectedstackFrame.SourceName, frame.SourceName); index++; } } this.Comment("Continue to run to exist."); runner.Expects.TerminatedEvent().AfterContinue(); runner.DisconnectAndVerify(); } } [Theory] [DependsOnTest(nameof(CompileKitchenSinkForExpressionTests))] [RequiresTestSettings] public void EvaluateOnFrames(ITestSettings settings) { this.TestPurpose("To check evalution on different frame with different variable types."); this.WriteSettings(settings); this.Comment("Open the debugge with a initialization."); IDebuggee debuggee = SinkHelper.Open(this, settings.CompilerSettings, DebuggeeMonikers.KitchenSink.Expression); using (IDebuggerRunner runner = CreateDebugAdapterRunner(settings)) { this.Comment("Configure launch."); runner.Launch(settings.DebuggerSettings, debuggee, "-fExpression"); this.Comment("Set a breakpoint so that we can stop at a line."); runner.SetBreakpoints(debuggee.Breakpoints(SinkHelper.Expression, 19)); this.Comment("To start debugging and break"); runner.Expects.StoppedEvent(StoppedReason.Breakpoint).AfterConfigurationDone(); using (IThreadInspector threadInspector = runner.GetThreadInspector()) { IFrameInspector currentFrame; this.Comment("To evaluate on the first frame."); currentFrame = threadInspector.Stack.First(); currentFrame.AssertVariables("isCalled", "true"); Assert.Equal("true", currentFrame.Evaluate("isCalled||false", EvaluateContext.Watch)); currentFrame.AssertEvaluateAsDouble("d", EvaluateContext.Watch, 10.1); this.Comment("Switch to next frame then evaluate on that frame."); currentFrame = threadInspector.Stack.ElementAt(1); currentFrame.GetVariable("_f").AssertValueAsFloat(1); currentFrame.AssertEvaluateAsFloat("_f", EvaluateContext.Watch, 1); this.Comment("To evaluate string and vector type on it, the try to enable pretty printing to evaluate again."); currentFrame = threadInspector.Stack.ElementAt(2); currentFrame.GetVariable("vec").AssertValueAsVector(5); currentFrame.AssertEvaluateAsVector("vec", EvaluateContext.Watch, 5); this.Comment("To evaluate some special values on the fourth frame."); currentFrame = threadInspector.Stack.ElementAt(3); currentFrame.AssertEvaluateAsDouble("mydouble=1.0", EvaluateContext.Watch, 1); currentFrame.GetVariable("mynull").AssertValueAsChar('\0'); this.Comment("To evaluate class on stack on the fifth frame."); currentFrame = threadInspector.Stack.ElementAt(4); IVariableInspector varInspector; varInspector = currentFrame.GetVariable("student"); Assert.Equal("10", varInspector.GetVariable("age").Value); Assert.Equal("19", currentFrame.Evaluate("student.age=19", EvaluateContext.Watch)); this.Comment("To evaluate array on the sixth frame."); currentFrame = threadInspector.Stack.ElementAt(5); Assert.Equal("10", currentFrame.Evaluate("*(pArr+1)=10", EvaluateContext.Watch)); Assert.Equal("100", currentFrame.Evaluate("arr[0]=100", EvaluateContext.Watch)); } this.Comment("Continue to run to exist."); runner.Expects.TerminatedEvent().AfterContinue(); runner.DisconnectAndVerify(); } } [Theory] [DependsOnTest(nameof(CompileKitchenSinkForExpressionTests))] // TODO: https://github.com/microsoft/MIEngine/issues/1170 // - lldb [UnsupportedDebugger(SupportedDebugger.Lldb, SupportedArchitecture.x64 | SupportedArchitecture.x86)] [RequiresTestSettings] public void EvaluateInvalidExpression(ITestSettings settings) { this.TestPurpose("To test invalid expression evaluation return apropriate errors."); this.WriteSettings(settings); IDebuggee debuggee = SinkHelper.Open(this, settings.CompilerSettings, DebuggeeMonikers.KitchenSink.Expression); using (IDebuggerRunner runner = CreateDebugAdapterRunner(settings)) { this.Comment("Configure launch."); runner.Launch(settings.DebuggerSettings, debuggee, "-fExpression"); this.Comment("Set a breakpoint so that we can stop at a line."); runner.SetBreakpoints(debuggee.Breakpoints(SinkHelper.Expression, 31)); this.Comment("To start debugging and hit breakpoint."); runner.Expects.HitBreakpointEvent().AfterConfigurationDone(); using (IThreadInspector threadInspector = runner.GetThreadInspector()) { IFrameInspector currentFrame = threadInspector.Stack.First(); this.Comment("To evaluate some invalid expression on curren stack frame."); currentFrame.AssertEvaluateAsError("notExistVar", EvaluateContext.Watch); } this.Comment("Continue to run to exist."); runner.Expects.TerminatedEvent().AfterContinue(); runner.DisconnectAndVerify(); } } #region Assign expression [Theory] [DependsOnTest(nameof(CompileKitchenSinkForExpressionTests))] [RequiresTestSettings] public void AssignIntExpressionToVariable(ITestSettings settings) { this.TestPurpose("Assign an expression to a variable."); this.WriteSettings(settings); IDebuggee debuggee = SinkHelper.Open(this, settings.CompilerSettings, DebuggeeMonikers.KitchenSink.Expression); using (IDebuggerRunner runner = CreateDebugAdapterRunner(settings)) { this.Comment("Configure launch."); runner.Launch(settings.DebuggerSettings, debuggee, "-fExpression"); this.Comment("Set a breakpoint so that we can stop at a line."); runner.SetBreakpoints(debuggee.Breakpoints(SinkHelper.Expression, 31)); this.Comment("Start debugging and hit breakpoint."); runner.Expects.HitBreakpointEvent().AfterConfigurationDone(); using (IThreadInspector threadInspector = runner.GetThreadInspector()) { IFrameInspector currentFrame = threadInspector.Stack.First(); this.Comment("Assign an expression to a variable."); currentFrame.GetVariable("myint").Value = "39+3"; } // Start another inspector to refresh values using (IThreadInspector threadInspector = runner.GetThreadInspector()) { IFrameInspector currentFrame = threadInspector.Stack.First(); this.Comment("Check the value of the variable has been updated."); Assert.Equal("42", currentFrame.GetVariable("myint").Value); } this.Comment("Continue to run to exist."); runner.Expects.TerminatedEvent().AfterContinue(); runner.DisconnectAndVerify(); } } [Theory] [DependsOnTest(nameof(CompileKitchenSinkForExpressionTests))] [RequiresTestSettings] public void AssignInvalidExpressionToVariable(ITestSettings settings) { this.TestPurpose("Assign an invalid expression to a variable."); this.WriteSettings(settings); IDebuggee debuggee = SinkHelper.Open(this, settings.CompilerSettings, DebuggeeMonikers.KitchenSink.Expression); using (IDebuggerRunner runner = CreateDebugAdapterRunner(settings)) { this.Comment("Configure launch."); runner.Launch(settings.DebuggerSettings, debuggee, "-fExpression"); this.Comment("Set a breakpoint so that we can stop at a line."); runner.SetBreakpoints(debuggee.Breakpoints(SinkHelper.Expression, 31)); this.Comment("Start debugging and hit breakpoint."); runner.Expects.StoppedEvent(StoppedReason.Breakpoint).AfterConfigurationDone(); using (IThreadInspector threadInspector = runner.GetThreadInspector()) { IFrameInspector currentFrame = threadInspector.Stack.First(); this.Comment("Assign an invalid expression to a variable."); currentFrame.GetVariable("myint").SetVariableValueExpectFailure("39+nonexistingint"); } // Start another inspector to refresh values using (IThreadInspector threadInspector = runner.GetThreadInspector()) { IFrameInspector currentFrame = threadInspector.Stack.First(); this.Comment("Check the value of the variable hasn't been updated."); Assert.Equal("100", currentFrame.GetVariable("myint").Value); } this.Comment("Continue to run to exist."); runner.Expects.TerminatedEvent().AfterContinue(); runner.DisconnectAndVerify(); } } #endregion #endregion #region Private methods private static StackFrame[] GenerateFramesList(IDebuggerSettings debugger) { // VsDbg moves the stack pointer to the return address which is not necessarily the calling address if (debugger.DebuggerType == SupportedDebugger.VsDbg) { // Visual C++ compiler for x64 and x86 generate symbols differently which means that the line numbers will be different. if (debugger.DebuggeeArchitecture == SupportedArchitecture.x64) { return new[] { new StackFrame(10, "accumulate(", "expression.cpp", null), new StackFrame(12, "accumulate(", "expression.cpp", null), new StackFrame(12, "accumulate(", "expression.cpp", null), new StackFrame(20, "func(", "expression.cpp", null), new StackFrame(81, "Expression::checkCallStack(", "expression.cpp", null), new StackFrame(74, "Expression::checkPrettyPrinting(", "expression.cpp", null), new StackFrame(63, "Expression::checkSpecialValues(", "expression.cpp", null), new StackFrame(53, "Expression::checkClassOnStackAndHeap(", "expression.cpp", null), new StackFrame(40, "Expression::checkArrayAndPointers(", "expression.cpp", null), new StackFrame(32, "Expression::checkPrimitiveTypes(", "expression.cpp", null), new StackFrame(86, "Expression::CoreRun(", "expression.cpp", null), new StackFrame(23, "Feature::Run(", "feature.cpp", null), new StackFrame(45, "main", "main.cpp", null) }; } else { return new[] { new StackFrame(10, "accumulate(", "expression.cpp", null), new StackFrame(12, "accumulate(", "expression.cpp", null), new StackFrame(12, "accumulate(", "expression.cpp", null), new StackFrame(19, "func(", "expression.cpp", null), new StackFrame(81, "Expression::checkCallStack(", "expression.cpp", null), new StackFrame(75, "Expression::checkPrettyPrinting(", "expression.cpp", null), new StackFrame(63, "Expression::checkSpecialValues(", "expression.cpp", null), new StackFrame(54, "Expression::checkClassOnStackAndHeap(", "expression.cpp", null), new StackFrame(40, "Expression::checkArrayAndPointers(", "expression.cpp", null), new StackFrame(32, "Expression::checkPrimitiveTypes(", "expression.cpp", null), new StackFrame(86, "Expression::CoreRun(", "expression.cpp", null), new StackFrame(23, "Feature::Run(", "feature.cpp", null), new StackFrame(46, "main", "main.cpp", null) }; } } else { return new[] { new StackFrame(10, "accumulate(", "expression.cpp", null), new StackFrame(12, "accumulate(", "expression.cpp", null), new StackFrame(12, "accumulate(", "expression.cpp", null), new StackFrame(19, "func(", "expression.cpp", null), new StackFrame(80, "Expression::checkCallStack(", "expression.cpp", null), new StackFrame(74, "Expression::checkPrettyPrinting(", "expression.cpp", null), new StackFrame(62, "Expression::checkSpecialValues(", "expression.cpp", null), new StackFrame(53, "Expression::checkClassOnStackAndHeap(", "expression.cpp", null), new StackFrame(39, "Expression::checkArrayAndPointers(", "expression.cpp", null), new StackFrame(31, "Expression::checkPrimitiveTypes(", "expression.cpp", null), new StackFrame(85, "Expression::CoreRun(", "expression.cpp", null), new StackFrame(22, "Feature::Run(", "feature.cpp", null), new StackFrame(45, "main", "main.cpp", null) }; } } #endregion } #region Class of Stack Frame /// <summary> /// Represent a stack frame /// </summary> internal class StackFrame { public int Line { get; private set; } public string Name { get; private set; } public string SourceName { get; private set; } public string SourcePath { get; private set; } public StackFrame(int line, string name, string sourceName, string sourcePath) { this.Line = line; this.Name = name; this.SourceName = sourceName; this.SourcePath = sourcePath; } } #endregion } <|start_filename|>test/DebuggerTesting/OpenDebug/Commands/Responses/CommandResponse.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Newtonsoft.Json; namespace DebuggerTesting.OpenDebug.Commands.Responses { public class CommandResponseValue : JsonValue { public bool success; public string command; [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public string message; [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public int? request_seq; [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public int? seq; } public abstract class CommandResponse<T> : Response<T> where T : CommandResponseValue, new() { public CommandResponse(string commandName, bool success = true) { this.ExpectedResponse.command = commandName; this.ExpectedResponse.success = success; this.ExpectedResponse.message = null; } public CommandResponse(string commandName, string message) { this.ExpectedResponse.command = commandName; this.ExpectedResponse.success = false; this.ExpectedResponse.message = message; } public override string ToString() { if (this.ExpectedResponse.message != null) return "{0} (Fail '{1}')".FormatInvariantWithArgs(base.ToString(), this.ExpectedResponse.message); else return "{0} ({1})".FormatInvariantWithArgs(base.ToString(), this.ExpectedResponse.success ? "Success" : "Fail"); } } /// <summary> /// The most common command response, returns the command name and a bool with success result. /// </summary> public sealed class CommandResponse : CommandResponse<CommandResponseValue> { public CommandResponse(string commandName, bool success) : base(commandName, success) { } } } <|start_filename|>src/DebugEngineHost/HostWaitDialog.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Microsoft.DebugEngineHost { /// <summary> /// Provides an optional wait dialog to allow long running operations to be canceled. Some hosts /// may not implement the dialog, in which case these methods will be a nop. /// </summary> public sealed class HostWaitDialog : IDisposable { private VSImpl.VSWaitDialog _theDialog; public HostWaitDialog(string format, string caption) { try { _theDialog = new VSImpl.VSWaitDialog(format, caption); } catch (FileNotFoundException) { _theDialog = null; } } public void ShowWaitDialog(string item) { if (_theDialog != null) { _theDialog.ShowWaitDialog(item); } } public void EndWaitDialog() { if (_theDialog != null) { _theDialog.EndWaitDialog(); } } public void Dispose() { EndWaitDialog(); } } } <|start_filename|>src/DebugEngineHost/VSImpl/VSEventCallbackWrapper.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.VisualStudio.Debugger.Interop; using Microsoft.VisualStudio.OLE.Interop; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Microsoft.DebugEngineHost.VSImpl { /// <summary> /// This class is VS only (_NOT_ VS Code) /// </summary> internal class VSEventCallbackWrapper : IDebugEventCallback2 { // If we store the event callback in a normal IDebugEventCallback2 member, COM interop will attempt to call back to the main UI // thread the first time that we invoke the call back. To work around this, we will instead store the event call back in the // global interface table like we would if we implemented this code in native. private readonly uint _cookie; // NOTE: The GIT doesn't aggregate the free threaded marshaler, so we can't store it in an RCW // or the CLR will just call right back to the main thread to try and marshal it. private readonly IntPtr _pGIT; private Guid _IID_IDebugEventCallback2 = typeof(IDebugEventCallback2).GUID; private readonly object _cacheLock = new object(); private int _cachedEventCallbackThread; private IDebugEventCallback2 _cacheEventCallback; internal VSEventCallbackWrapper(IDebugEventCallback2 ad7Callback) { // Obtain the GIT from COM, and store the event callback in it Guid CLSID_StdGlobalInterfaceTable = new Guid("00000323-0000-0000-C000-000000000046"); Guid IID_IGlobalInterfaceTable = typeof(IGlobalInterfaceTable).GUID; const int CLSCTX_INPROC_SERVER = 0x1; _pGIT = NativeMethods.CoCreateInstance(ref CLSID_StdGlobalInterfaceTable, IntPtr.Zero, CLSCTX_INPROC_SERVER, ref IID_IGlobalInterfaceTable); var git = GetGlobalInterfaceTable(); git.RegisterInterfaceInGlobal(ad7Callback, ref _IID_IDebugEventCallback2, out _cookie); Marshal.ReleaseComObject(git); } ~VSEventCallbackWrapper() { // NOTE: This object does NOT implement the dispose pattern. The reasons are -- // 1. The underlying thing we are disposing is the SDM's IDebugEventCallback2. We are not going to get // deterministic release of this without both implementing the dispose pattern on this object but also // switching to use Marshal.ReleaseComObject everywhere. Marshal.ReleaseComObject is difficult to get // right and there isn't a large need to deterministically release the SDM's event callback. // 2. There is some risk of deadlock if we tried to implement the dispose pattern because of the trickiness // of releasing cross-thread COM interfaces. We could avoid this by doing an async dispose, but then // we losing the primary benefit of dispose which is the deterministic release. if (_cookie != 0) { var git = GetGlobalInterfaceTable(); git.RevokeInterfaceFromGlobal(_cookie); Marshal.ReleaseComObject(git); } if (_pGIT != IntPtr.Zero) { Marshal.Release(_pGIT); } } int IDebugEventCallback2.Event(IDebugEngine2 engine, IDebugProcess2 process, IDebugProgram2 program, IDebugThread2 thread, IDebugEvent2 @event, ref Guid riidEvent, uint attribs) { IDebugEventCallback2 ad7EventCallback = GetAD7EventCallback(); return ad7EventCallback.Event(engine, process, program, thread, @event, ref riidEvent, attribs); } private IGlobalInterfaceTable GetGlobalInterfaceTable() { Debug.Assert(_pGIT != IntPtr.Zero, "GetGlobalInterfaceTable called before the m_pGIT is initialized"); // NOTE: We want to use GetUniqueObjectForIUnknown since the GIT will exist in both the STA and the MTA, and we don't want // them to be the same rcw return (IGlobalInterfaceTable)Marshal.GetUniqueObjectForIUnknown(_pGIT); } private IDebugEventCallback2 GetAD7EventCallback() { Debug.Assert(_cookie != 0, "GetEventCallback called before m_cookie is initialized"); // We send esentially all events from the same thread, so lets optimize the common case int currentThreadId = Thread.CurrentThread.ManagedThreadId; if (_cacheEventCallback != null && _cachedEventCallbackThread == currentThreadId) { lock (_cacheLock) { if (_cacheEventCallback != null && _cachedEventCallbackThread == currentThreadId) { return _cacheEventCallback; } } } var git = GetGlobalInterfaceTable(); IntPtr pCallback; git.GetInterfaceFromGlobal(_cookie, ref _IID_IDebugEventCallback2, out pCallback); Marshal.ReleaseComObject(git); var eventCallback = (IDebugEventCallback2)Marshal.GetObjectForIUnknown(pCallback); Marshal.Release(pCallback); lock (_cacheLock) { _cachedEventCallbackThread = currentThreadId; _cacheEventCallback = eventCallback; } return eventCallback; } private static class NativeMethods { [DllImport("ole32.dll", ExactSpelling = true, PreserveSig = false)] public static extern IntPtr CoCreateInstance( [In] ref Guid clsid, IntPtr punkOuter, int context, [In] ref Guid iid); } } } <|start_filename|>src/OpenDebugAD7/AD7Exception.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Globalization; using System.Runtime.Serialization; namespace OpenDebugAD7 { internal class AD7Exception : Exception { public AD7Exception(string message) : base(message) { } public AD7Exception(string scenario, string reason) : base(string.Format(CultureInfo.CurrentCulture, scenario, reason)) { } } } <|start_filename|>src/OpenDebugAD7/OpenDebug/Program.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Net; using System.Net.Sockets; using System.Reflection; using System.Runtime.InteropServices; using System.Text; using System.Threading; using Microsoft.DebugEngineHost; using Microsoft.DebugEngineHost.VSCode; using OpenDebugAD7; namespace OpenDebug { internal class Program { private const int DEFAULT_PORT = 4711; private static int Main(string[] argv) { int port = -1; List<LoggingCategory> loggingCategories = new List<LoggingCategory>(); // parse command line arguments foreach (var a in argv) { if ((a == null) || (a == "undefined")) { continue; } switch (a) { case "-h": case "-?": case "/?": case "--help": Console.WriteLine("OpenDebugAD7: Visual Studio Code debug adapter bridge for using Visual Studio"); Console.WriteLine("debug engines in VS Code"); Console.WriteLine(); Console.WriteLine("Available command line arguments:"); Console.WriteLine("--trace: print the requests coming from VS Code to the console."); Console.WriteLine("--trace=response: print requests and response from VS Code to the console."); Console.WriteLine("--engineLogging[=filePath]: Enable logging from the debug engine. If not"); Console.WriteLine(" specified, the log will go to the console."); Console.WriteLine("--server[=port_num] : Start the debug adapter listening for requests on the"); Console.WriteLine(" specified TCP/IP port instead of stdin/out. If port is not specified"); Console.WriteLine(" TCP {0} will be used.", DEFAULT_PORT); Console.WriteLine("--pauseForDebugger: Pause the OpenDebugAD7.exe process at startup until a"); Console.WriteLine(" debugger attaches."); return 1; case "--trace": loggingCategories.Add(LoggingCategory.AdapterTrace); break; case "--trace=response": loggingCategories.Add(LoggingCategory.AdapterTrace); loggingCategories.Add(LoggingCategory.AdapterResponse); break; case "--engineLogging": loggingCategories.Add(LoggingCategory.EngineLogging); HostLogger.EnableHostLogging(); break; case "--server": port = DEFAULT_PORT; break; case "--pauseForDebugger": Console.WriteLine("OpenDebugAD7.exe is waiting for a managed debugger to attach to it."); while (!Debugger.IsAttached) { System.Threading.Thread.Sleep(100); } break; default: if (a.StartsWith("--server=", StringComparison.Ordinal)) { string portString = a.Substring("--server=".Length); if (!int.TryParse(portString, out port)) { Console.Error.WriteLine("OpenDebugAD7: ERROR: Unable to parse port string '{0}'.", portString); return -1; } } else if (a.StartsWith("--engineLogging=", StringComparison.Ordinal)) { HostLogger.EnableHostLogging(); try { HostLogger.Instance.LogFilePath = a.Substring("--engineLogging=".Length); } catch (Exception e) { Console.Error.WriteLine("OpenDebugAD7: ERROR: Unable to open log file. " + e.Message); return -1; } } else if (a.StartsWith("--adapterDirectory=", StringComparison.Ordinal)) { string adapterDirectory = a.Substring("--adapterDirectory=".Length); if (!Directory.Exists(adapterDirectory)) { Console.Error.WriteLine("OpenDebugAD7: ERROR: adapter directory '{0}' does not exist.", adapterDirectory); return -1; } EngineConfiguration.SetAdapterDirectory(adapterDirectory); } else { Console.Error.WriteLine("OpenDebugAD7: ERROR: Unknown command line argument '{0}'.", a); return -1; } break; } } if (port > 0) { // TCP/IP server RunServer(port, loggingCategories); } try { // stdin/stdout Console.Error.WriteLine("waiting for v8 protocol on stdin/stdout"); if (Utilities.IsWindows()) { // Avoid sending the BOM on Windows if the Beta Unicode feature is enabled in Windows 10 Console.OutputEncoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false); Console.InputEncoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false); } Dispatch(Console.OpenStandardInput(), Console.OpenStandardOutput(), loggingCategories); } catch (Exception e) { Utilities.ReportException(e); } return 0; } private static async void RunServer(int port, List<LoggingCategory> loggingCategories) { TcpListener serverSocket = new TcpListener(IPAddress.Parse("127.0.0.1"), port); DisableInheritance(serverSocket.Server); serverSocket.Start(); Console.Error.WriteLine("waiting for v8 protocol on port " + port); while (true) { var clientSocket = await serverSocket.AcceptSocketAsync(); DisableInheritance(clientSocket); if (clientSocket != null) { Console.Error.WriteLine(">> accepted connection from client"); new System.Threading.Thread(() => { using (var networkStream = new NetworkStream(clientSocket)) { try { Dispatch(networkStream, networkStream, loggingCategories); } catch (Exception e) { Console.Error.WriteLine("Exception: " + e); } } clientSocket.Dispose(); Console.Error.WriteLine(">> client connection closed"); }).Start(); } } } private static void Dispatch(Stream inputStream, Stream outputStream, List<LoggingCategory> loggingCategories) { AD7DebugSession debugSession = new AD7DebugSession(inputStream, outputStream, loggingCategories); debugSession.Protocol.Run(); debugSession.Protocol.WaitForReader(); } public static void DisableInheritance(Socket s) { if (Utilities.IsWindows()) { Win32.DisableInheritance(s); } } private static class Win32 { public static void DisableInheritance(Socket s) { Type t = s.GetType(); PropertyInfo handle = t.GetTypeInfo().GetDeclaredProperty("Handle"); if (handle != null) { SetHandleInformation((IntPtr)handle.GetValue(s), HANDLE_FLAG_INHERIT, 0); } } private const int HANDLE_FLAG_INHERIT = 1; [DllImport("kernel32.dll", SetLastError = true)] public static extern int SetHandleInformation(IntPtr hObject, int dwMask, int dwFlags); } } } <|start_filename|>src/DebugEngineHost/HostLoader.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.Win32; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace Microsoft.DebugEngineHost { /// <summary> /// Provides support for loading dependant assemblies using information from the configuration store. /// </summary> public static class HostLoader { /// <summary> /// Looks up the specified CLSID in the VS registry and loads it /// </summary> /// <param name="configStore">Registry root to lookup the type</param> /// <param name="clsid">CLSID to CoCreate</param> /// <returns>[Optional] loaded object. Null if the type is not registered, or points to a type that doesn't exist</returns> public static object VsCoCreateManagedObject(HostConfigurationStore configStore, Guid clsid) { string assemblyNameString, className, codeBase; if (!GetManagedTypeInfoForCLSID(configStore, clsid, out assemblyNameString, out className, out codeBase)) { return null; } if (codeBase != null && !File.Exists(codeBase)) { return null; } AssemblyName assemblyName = new AssemblyName(assemblyNameString); if (codeBase != null) { assemblyName.CodeBase = "file:///" + codeBase; } Assembly assemblyObject = Assembly.Load(assemblyName); return assemblyObject.CreateInstance(className); } private static bool GetManagedTypeInfoForCLSID(HostConfigurationStore configStore, Guid clsid, out string assembly, out string className, out string codeBase) { assembly = null; className = null; codeBase = null; string keyPath = configStore.RegistryRoot + @"\CLSID\" + clsid.ToString("B"); using (RegistryKey key = Registry.LocalMachine.OpenSubKey(keyPath)) { if (key == null) return false; object oAssembly = key.GetValue("Assembly"); object oClassName = key.GetValue("Class"); object oCodeBase = key.GetValue("CodeBase"); if (oAssembly == null || !(oAssembly is string)) return false; if (oClassName == null || !(oClassName is string)) return false; // CodeBase is not required, but it is an error if it isn't a string if (oCodeBase != null && !(oCodeBase is string)) return false; assembly = (string)oAssembly; className = (string)oClassName; codeBase = (string)oCodeBase; return true; } } } } <|start_filename|>test/CppTests/debuggees/kitchensink/src/threading.cpp<|end_filename|> #include "threading.h" Threading::Threading() : Feature("Threading"), runningWorkingThreadCount(0) { } // Body of "worker" threads. Loop for loopCount seconds void WorkerThreadLoop(Threading* t, int loopCount, string threadName) { t->Log("Starting thread ", threadName, ". LoopCount: ", loopCount); t->runningWorkingThreadCount++; // Wait until main is ready before closing thread unique_lock<mutex> lk(t->mainClosingMutex); t->mainClosing.wait(lk); t->Log("Ending thread ", threadName, ". LoopCount: ", loopCount); t->runningWorkingThreadCount--; } void Threading::CoreRun() { this->Log("Creating a few threads."); thread A(WorkerThreadLoop, this, 3, "A-Blue"); thread B(WorkerThreadLoop, this, 2, "B-Green"); thread C(WorkerThreadLoop, this, 0, "C-Orange"); thread D(WorkerThreadLoop, this, 1, "D-Red"); this->Log("Wait for threads to start..."); while (this->runningWorkingThreadCount < 4) { this_thread::sleep_for(chrono::milliseconds(100)); } this->Log("All threads running!"); this->Log("Notify threads to close..."); while (this->runningWorkingThreadCount > 0) { this->mainClosing.notify_all(); this_thread::sleep_for(chrono::milliseconds(100)); } A.join(); B.join(); C.join(); D.join(); } <|start_filename|>src/DebugEngineHost/HostLogger.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Microsoft.DebugEngineHost { public sealed class HostLogger { /// <summary> /// Callback for programmatic display of log messages /// </summary> /// <param name="outputString"></param> public delegate void OutputCallback(string outputString); private StreamWriter _streamWriter; private OutputCallback _callback; private readonly object _locker = new object(); internal HostLogger(StreamWriter streamWriter = null, OutputCallback callback = null) { _streamWriter = streamWriter; _callback = callback; } public void WriteLine(string line) { lock (_locker) { if (_streamWriter != null) _streamWriter.WriteLine(line); _callback?.Invoke(line); } } public void Flush() { lock (_locker) { if (_streamWriter != null) _streamWriter.Flush(); } } public void Close() { lock (_locker) { if (_streamWriter != null) _streamWriter.Close(); _streamWriter = null; } } internal static StreamWriter GetStreamForName(string logFileName, bool throwInUseError) { if (string.IsNullOrEmpty(logFileName)) { return null; } string tempDirectory = Path.GetTempPath(); StreamWriter writer = null; if (Path.IsPathRooted(logFileName) || (!string.IsNullOrEmpty(tempDirectory) && Directory.Exists(tempDirectory))) { string filePath = Path.Combine(tempDirectory, logFileName); try { FileStream stream = File.Open(filePath, FileMode.Create, FileAccess.Write, FileShare.Read); writer = new StreamWriter(stream); } catch (IOException) { if (throwInUseError) throw; // ignore failures from the log being in use by another process } } else { throw new ArgumentOutOfRangeException(nameof(logFileName)); } return writer; } /// <summary> /// Get a logger after the user has explicitly configured a log file/callback /// </summary> /// <param name="logFileName"></param> /// <param name="callback"></param> /// <returns>The host logger object</returns> public static HostLogger GetLoggerFromCmd(string logFileName, HostLogger.OutputCallback callback) { StreamWriter writer = HostLogger.GetStreamForName(logFileName, throwInUseError: true); return new HostLogger(writer, callback); } } } <|start_filename|>test/CppTests/debuggees/sourcemap/src/manager/manager.cpp<|end_filename|> #include "manager.h" Manager::Manager() { } void Manager::AddInt(int number) { this->items.push_back(number); } int Manager::RemoveInt() { int val = this->items.back(); this->items.pop_back(); return val; } int Manager::Size() { return (int)this->items.size(); } int Manager::Sum() { int sum = 0; for (auto & it : items) { sum += it; } return sum; } <|start_filename|>test/DebuggerTesting/OpenDebug/Commands/DisconnectCommand.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace DebuggerTesting.OpenDebug.Commands { #region DisconnectCommandArgs public sealed class DisconnectCommandArgs : JsonValue { public sealed class ExtensionHostData { public bool restart; } public ExtensionHostData extensionHostData = new ExtensionHostData(); } #endregion /// <summary> /// Disconnects the debugger. /// </summary> public class DisconnectCommand : Command<DisconnectCommandArgs> { public DisconnectCommand() : base("disconnect") { this.Args.extensionHostData.restart = false; } } } <|start_filename|>test/Android/EvalComplexExpression/EvalComplexExpression/EvalComplexExpression.NativeActivity/Header1.h<|end_filename|> #pragma once void Func(int x); int Func(int x, double y); void Func(); <|start_filename|>src/DebugEngineHost/HostOutputWindow.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; namespace Microsoft.DebugEngineHost { /// <summary> /// Provides direct access to the underlying output window without going through debug events /// </summary> public static class HostOutputWindow { // Use an extra class so that we have a seperate class which depends on VS interfaces private static class VsImpl { internal static void SetText(string outputMessage) { int hr; var outputWindow = (IVsOutputWindow)Package.GetGlobalService(typeof(SVsOutputWindow)); if (outputWindow == null) return; IVsOutputWindowPane pane; Guid guidDebugOutputPane = VSConstants.GUID_OutWindowDebugPane; hr = outputWindow.GetPane(ref guidDebugOutputPane, out pane); if (hr < 0) return; pane.Clear(); pane.Activate(); hr = pane.OutputString(outputMessage); if (hr < 0) return; var shell = (IVsUIShell)Package.GetGlobalService(typeof(SVsUIShell)); if (shell == null) return; Guid commandSet = VSConstants.GUID_VSStandardCommandSet97; object inputVariant = null; shell.PostExecCommand(commandSet, (uint)VSConstants.VSStd97CmdID.OutputWindow, 0, ref inputVariant); } } /// <summary> /// Write text to the Debug VS Output window pane directly. This is used to write information before the session create event. /// </summary> /// <param name="outputMessage"></param> public static void WriteLaunchError(string outputMessage) { try { VsImpl.SetText(outputMessage); } catch (Exception) { } } } } <|start_filename|>test/DebuggerTesting/OpenDebug/Commands/SourceCommand.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using DebuggerTesting.OpenDebug.Commands.Responses; namespace DebuggerTesting.OpenDebug.Commands { public sealed class SourceCommandArgs : JsonValue { public int sourceReference; } public class SourceCommand : CommandWithResponse<SourceCommandArgs, SourceResponseValue> { public SourceCommand(int sourceReference) : base("source") { this.Args.sourceReference = sourceReference; } } } <|start_filename|>src/MICore/Debugger.cs<|end_filename|>  // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Threading; using System.Text; using System.Diagnostics; using System.Threading.Tasks; using System.Globalization; using System.Linq; using Microsoft.Win32.SafeHandles; using Microsoft.DebugEngineHost; using System.Runtime.InteropServices; using System.Text.RegularExpressions; namespace MICore { public enum ProcessState { NotConnected, Running, Stopped, Exited }; public class Debugger : ITransportCallback { private const string Event_UnsupportedWindowsGdb = "VS/Diagnostics/Debugger/MIEngine/UnsupportedWindowsGdb"; private const string Property_GdbVersion = "VS.Diagnostics.Debugger.MIEngine.GdbVersion"; public event EventHandler BreakModeEvent; public event EventHandler RunModeEvent; public event EventHandler ProcessExitEvent; public event EventHandler DebuggerExitEvent; public event EventHandler<DebuggerAbortedEventArgs> DebuggerAbortedEvent; public event EventHandler<string> OutputStringEvent; public event EventHandler EvaluationEvent; public event EventHandler ErrorEvent; public event EventHandler ModuleLoadEvent; // occurs when stopped after a libraryLoadEvent public event EventHandler LibraryLoadEvent; // a shared library was loaded public event EventHandler BreakChangeEvent; // a breakpoint was changed public event EventHandler BreakCreatedEvent; // a breakpoint was created public event EventHandler ThreadCreatedEvent; public event EventHandler ThreadExitedEvent; public event EventHandler ThreadGroupExitedEvent; public event EventHandler<ResultEventArgs> TelemetryEvent; private int _exiting; public ProcessState ProcessState { get; private set; } private MIResults _miResults; public bool EntrypointHit { get; protected set; } public bool IsCygwin { get; protected set; } public bool IsMinGW { get; protected set; } public bool SendNewLineAfterCmd { get; protected set; } public virtual void FlushBreakStateData() { } public bool IsClosed { get { return _closeMessage != null; } } public uint MaxInstructionSize { get; private set; } public bool Is64BitArch { get; private set; } public CommandLock CommandLock { get { return _commandLock; } } public MICommandFactory MICommandFactory { get; protected set; } public Logger Logger { private set; get; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] protected readonly LaunchOptions _launchOptions; public LaunchOptions LaunchOptions { get { return this._launchOptions; } } private Queue<Func<Task>> _internalBreakActions = new Queue<Func<Task>>(); private TaskCompletionSource<object> _internalBreakActionCompletionSource; private TaskCompletionSource<object> _consoleDebuggerInitializeCompletionSource = new TaskCompletionSource<object>(); private LinkedList<string> _initializationLog = new LinkedList<string>(); private LinkedList<string> _initialErrors = new LinkedList<string>(); private int _localDebuggerPid = -1; protected bool _connected; private bool _terminating; private bool _detaching; public bool IsStopDebuggingInProgress { get { return _terminating || _detaching || this.ProcessState == MICore.ProcessState.Exited; } } public class ResultEventArgs : EventArgs { public ResultEventArgs(Results results, uint id) { Results = results; Id = id; } public ResultEventArgs(Results results) { Results = results; } public Results Results { get; private set; } public ResultClass ResultClass { get { return Results.ResultClass; } } public uint Id { get; private set; } }; public class StoppingEventArgs : ResultEventArgs { public readonly BreakRequest AsyncRequest; public StoppingEventArgs(Results results, uint id, BreakRequest asyncRequest = BreakRequest.None) : base(results, id) { AsyncRequest = asyncRequest; } public StoppingEventArgs(Results results, BreakRequest asyncRequest = BreakRequest.None) : this(results, 0, asyncRequest) { } } private ITransport _transport; private CommandLock _commandLock = new CommandLock(); /// <summary> /// The last command we sent over the transport. This includes both the command name and arguments. /// </summary> private string _lastCommandText; private uint _lastCommandId; /// <summary> /// Message used in any DebuggerDisposedExceptions once the debugger is closed. Setting /// this to non-null indicates that the debugger is now closed. It is only set once. /// </summary> private string _closeMessage; /// <summary> /// [Optional] If a console command is being executed, list where we append the output /// </summary> private StringBuilder _consoleCommandOutput; private bool _pendingInternalBreak; internal bool IsRequestingInternalAsyncBreak { get { return _pendingInternalBreak; } } private bool _waitingToStop; private Timer _breakTimer = null; private int _retryCount; private const int BREAK_DELTA = 3000; // millisec before trying to break again private const int BREAK_RETRY_MAX = 3; // maximum times to retry // The key is the thread group, the value is the pid private Dictionary<string, int> _debuggeePids; public Debugger(LaunchOptions launchOptions, Logger logger) { _launchOptions = launchOptions; _debuggeePids = new Dictionary<string, int>(); Logger = logger; _miResults = new MIResults(logger); } protected void SetDebuggerPid(int debuggerPid) { // Used for testing Logger.WriteLine(string.Concat("DebuggerPid=", debuggerPid)); _localDebuggerPid = debuggerPid; } /// <summary> /// Check if the local debugger process is running. /// For Windows, it returns False always to avoid shortcuts taken when it returns True. /// </summary> /// <returns>True if the local debugger process is running and the platform is Linux or OS X. /// False otherwise.</returns> private bool IsUnixDebuggerRunning() { if (_localDebuggerPid > 0) { if (PlatformUtilities.IsLinux() || PlatformUtilities.IsOSX()) { return UnixUtilities.IsProcessRunning(_localDebuggerPid); } } return false; } private void RetryBreak(object o) { lock (_internalBreakActions) { if (_waitingToStop && _retryCount < BREAK_RETRY_MAX) { Logger.WriteLine("Debugger failed to break. Trying again."); CmdBreak(BreakRequest.Internal); _retryCount++; } else { if (_breakTimer != null) { _breakTimer.Dispose(); _breakTimer = null; } } } } public Task AddInternalBreakAction(Func<Task> func) { if (this.ProcessState == ProcessState.Stopped || !_connected || this.MICommandFactory.AllowCommandsWhileRunning()) { return func(); } else { lock (_internalBreakActions) { if (_internalBreakActionCompletionSource == null) { _internalBreakActionCompletionSource = new TaskCompletionSource<object>(); } _internalBreakActions.Enqueue(func); if (!_pendingInternalBreak) { _pendingInternalBreak = true; CmdBreak(BreakRequest.Internal); _retryCount = 0; _waitingToStop = true; // When using signals to stop the process, do not kick off another break attempt. The debug break injection and // signal based models are reliable so no retries are needed. Cygwin can't currently async-break reliably, so // use retries there. if (!IsLocalGdbTarget() && !this.IsCygwin) { _breakTimer = new Timer(RetryBreak, null, BREAK_DELTA, BREAK_DELTA); } } return _internalBreakActionCompletionSource.Task; } } } private async void OnStopped(Results results) { string reason = results.TryFindString("reason"); if (reason.StartsWith("exited", StringComparison.Ordinal) || reason.StartsWith("disconnected", StringComparison.Ordinal)) { if (this.ProcessState != ProcessState.Exited) { this.ProcessState = ProcessState.Exited; if (ProcessExitEvent != null) { ProcessExitEvent(this, new ResultEventArgs(results)); } } return; } //if this is an exception reported from LLDB, it will not currently contain a frame object in the MI //if we don't have a frame, check if this is an exception and retrieve the frame if (!results.Contains("frame") && !_terminating && (string.Compare(reason, "exception-received", StringComparison.OrdinalIgnoreCase) == 0 || string.Compare(reason, "signal-received", StringComparison.OrdinalIgnoreCase) == 0) ) { //get the info for the current frame Results frameResult = await MICommandFactory.StackInfoFrame(); //add the frame to the stopping results results = results.Add("frame", frameResult.Find("frame")); } bool fIsAsyncBreak = MICommandFactory.IsAsyncBreakSignal(results); if (await DoInternalBreakActions(fIsAsyncBreak)) { return; } this.ProcessState = ProcessState.Stopped; FlushBreakStateData(); if (!_terminating) { if (!results.Contains("frame")) { if (ModuleLoadEvent != null) { ModuleLoadEvent(this, new ResultEventArgs(results)); } } else if (BreakModeEvent != null) { BreakRequest request = _requestingRealAsyncBreak; _requestingRealAsyncBreak = BreakRequest.None; BreakModeEvent(this, new StoppingEventArgs(results, request)); } } } protected virtual void OnStateChanged(string mode, string strresult) { this.OnStateChanged(mode, _miResults.ParseResultList(strresult)); } protected void OnStateChanged(string mode, Results results) { if (mode == "stopped") { OnStopped(results); } else if (mode == "running") { this.ProcessState = ProcessState.Running; if (RunModeEvent != null) { RunModeEvent(this, new ResultEventArgs(results)); } } else if (mode == "exit") { OnDebuggerProcessExit(null); } else if (mode.StartsWith("done,bkpt=", StringComparison.Ordinal)) { // TODO handle breakpoint binding } else if (mode == "done") { } else if (mode == "connected") { if (this.ProcessState == ProcessState.NotConnected) this.ProcessState = ProcessState.Running; if (RunModeEvent != null) { RunModeEvent(this, new ResultEventArgs(results)); } } else { Debug.Fail("Unknown mode: " + mode); } return; } /// <summary> /// Handles executing internal break actions /// </summary> /// <param name="fIsAsyncBreak">Is the stopping action coming from an async break</param> /// <returns>Returns true if the process is continued and we should not enter break state, returns false if the process is stopped and we should enter break state.</returns> private async Task<bool> DoInternalBreakActions(bool fIsAsyncBreak) { TaskCompletionSource<object> source = null; Func<Task> item = null; Exception firstException = null; while (true) { lock (_internalBreakActions) { _waitingToStop = false; if (_internalBreakActions.Count == 0) { _pendingInternalBreak = false; _internalBreakActionCompletionSource = null; break; } source = _internalBreakActionCompletionSource; item = _internalBreakActions.Dequeue(); } try { await item(); } catch (Exception e) when (ExceptionHelper.BeforeCatch(e, Logger, reportOnlyCorrupting: true)) { if (firstException != null) { firstException = e; } } } bool processContinued = false; if (source != null) { if (this.IsClosed) { source.TrySetException(new DebuggerDisposedException(_closeMessage)); } else { if (_requestingRealAsyncBreak == BreakRequest.Internal && fIsAsyncBreak && (!_terminating && !_detaching)) { CmdContinueAsync(); processContinued = true; } if (firstException != null) { source.TrySetException(firstException); } else { source.TrySetResult(null); } } } return processContinued; } public void Init(ITransport transport, LaunchOptions options, HostWaitLoop waitLoop = null) { _lastCommandId = 1000; _transport = transport; FlushBreakStateData(); this.SendNewLineAfterCmd = (options is LocalLaunchOptions && PlatformUtilities.IsWindows() && this.MICommandFactory.Mode == MIMode.Gdb); _transport.Init(this, options, Logger, waitLoop); } public void SetTargetArch(TargetArchitecture arch) { switch (arch) { case TargetArchitecture.ARM: MaxInstructionSize = 4; Is64BitArch = false; break; case TargetArchitecture.ARM64: MaxInstructionSize = 8; Is64BitArch = true; break; case TargetArchitecture.X86: MaxInstructionSize = 20; Is64BitArch = false; break; case TargetArchitecture.X64: MaxInstructionSize = 26; Is64BitArch = true; break; case TargetArchitecture.Mips: MaxInstructionSize = 4; Is64BitArch = false; break; default: throw new ArgumentOutOfRangeException(nameof(arch)); } } public async Task WaitForConsoleDebuggerInitialize(CancellationToken token) { if (_consoleDebuggerInitializeCompletionSource == null) { Debug.Fail("Why is WaitForConsoleDebuggerInitialize called more than once? Not allowed."); throw new InvalidOperationException(); } using (token.Register(() => { _consoleDebuggerInitializeCompletionSource.TrySetException(new OperationCanceledException()); })) { await _consoleDebuggerInitializeCompletionSource.Task; } lock (_waitingOperations) { _consoleDebuggerInitializeCompletionSource = null; // We no longer care about keeping these, so empty them out _initializationLog = null; _initialErrors = null; } } protected void CloseQuietly() { if (Interlocked.CompareExchange(ref _exiting, 1, 0) == 0) { string closeMessage; if (this.ProcessState == ProcessState.Exited && !_terminating && !_detaching) { closeMessage = MICoreResources.Error_TargetProcessExited; } else { closeMessage = MICoreResources.Error_DebuggerClosed; } Close(closeMessage); } } private void Close(string closeMessage) { Debug.Assert(closeMessage != null, "Invalid close message. Very bad."); Debug.Assert(_closeMessage == null, "Why was Close called more than once? Should be impossible."); _closeMessage = closeMessage; _transport.Close(); lock (_waitingOperations) { foreach (var value in _waitingOperations.Values) { value.Abort(_closeMessage); } _waitingOperations.Clear(); } lock (_internalBreakActions) { if (_internalBreakActionCompletionSource != null) { _internalBreakActionCompletionSource.SetException(new DebuggerDisposedException(_closeMessage)); } _internalBreakActions.Clear(); } } public Task CmdStopAtMain() { this.VerifyNotDebuggingCoreDump(); return CmdAsync("-break-insert main", ResultClass.done); } public Task CmdStart() { this.VerifyNotDebuggingCoreDump(); return CmdAsync("-exec-run", ResultClass.running); } internal bool IsRequestingRealAsyncBreak { get { return _requestingRealAsyncBreak != BreakRequest.None; } } public enum BreakRequest // order is important so a stop request doesn't get overridden by an internal request { None, Internal, Async, Stop } protected BreakRequest _requestingRealAsyncBreak = BreakRequest.None; public Task CmdBreak(BreakRequest request) { if (request > _requestingRealAsyncBreak) { _requestingRealAsyncBreak = request; } return CmdBreakInternal(); } protected bool IsLocalLaunchUsingServer() { return (_launchOptions is LocalLaunchOptions localLaunchOptions && (!String.IsNullOrWhiteSpace(localLaunchOptions.MIDebuggerServerAddress) || !String.IsNullOrWhiteSpace(localLaunchOptions.DebugServer))); } internal bool IsLocalGdbTarget() { return (MICommandFactory.Mode == MIMode.Gdb && _launchOptions is LocalLaunchOptions && !IsLocalLaunchUsingServer()); } private bool IsRemoteGdbTarget() { return MICommandFactory.Mode == MIMode.Gdb && (_launchOptions is PipeLaunchOptions || _launchOptions is UnixShellPortLaunchOptions || IsLocalLaunchUsingServer()); } protected bool IsCoreDump { get { return this._launchOptions.IsCoreDump; } } public async Task<Results> CmdTerminate() { if (!_terminating) { _terminating = true; if (ProcessState == ProcessState.Running) { // MinGW and Cygwin on Windows don't support async break. Because of this, // the normal path of sending an internal async break so we can exit doesn't work. // Therefore, we will call TerminateProcess on the debuggee with the exit code of 0 // to terminate debugging. if (this.IsLocalGdbTarget() && (this.IsCygwin || this.IsMinGW) && _debuggeePids.Count > 0) { if (TerminateAllPids()) { // OperationThread's _runningOpCompleteEvent is doing WaitOne(). Calling MICommandFactory.Terminate() will Set() it, unblocking the UI. await MICommandFactory.Terminate(); return new Results(ResultClass.done); } } else { await AddInternalBreakAction(() => MICommandFactory.Terminate()); } } else { await MICommandFactory.Terminate(); } } return new Results(ResultClass.done); } [DllImport("kernel32.dll", SetLastError = true)] private static extern IntPtr OpenProcess(int dwDesiredAccess, [MarshalAs(UnmanagedType.Bool)] bool bInheritHandle, int dwProcessId); [DllImport("kernel32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool TerminateProcess(IntPtr hProcess, uint uExitCode); [DllImport("kernel32.dll", SetLastError = true)] private static extern bool CloseHandle(IntPtr hHandle); /// <summary> /// Call PInvoke to terminate all debuggee PIDs. This is to solve MinGW/Cygwin issues in Windows and SHOULD NOT be used in other cases. /// </summary> /// <returns>True if any pids were terminated successfully</returns> private bool TerminateAllPids() { var terminated = false; foreach (var pid in _debuggeePids) { int debuggeePid = pid.Value; IntPtr handle = IntPtr.Zero; try { // 0x1 = Terminate handle = OpenProcess(0x1, false, debuggeePid); if (handle != IntPtr.Zero && TerminateProcess(handle, 0)) { terminated = true; } } finally { if (handle != IntPtr.Zero) { bool close = CloseHandle(handle); Debug.Assert(close, "Why did CloseHandle fail?"); } } } return terminated; } public async Task<Results> CmdDetach() { _detaching = true; if (ProcessState == ProcessState.Running) { await AddInternalBreakAction(() => CmdAsync("-target-detach", ResultClass.done)); } else { await CmdAsync("-target-detach", ResultClass.done); } return new Results(ResultClass.done); } public Task CmdBreakInternal() { this.VerifyNotDebuggingCoreDump(); Debug.Assert(_requestingRealAsyncBreak != BreakRequest.None); // Note that interrupt doesn't work on OS X with gdb: // https://sourceware.org/bugzilla/show_bug.cgi?id=20035 if (IsLocalGdbTarget()) { bool useSignal = false; int debuggeePid = 0; lock (_debuggeePids) { if (_debuggeePids.Count > 0) { debuggeePid = _debuggeePids.First().Value; useSignal = true; } } if (PlatformUtilities.IsLinux() || PlatformUtilities.IsOSX()) { // for local linux debugging, send a signal to one of the debuggee processes rather than // using -exec-interrupt. -exec-interrupt does not work with attach and, in some instances, launch. // End result is either deadlocks or missed bps (since binding in runtime requires break state). // NOTE: this is not required for remote. Remote will not be using LocalLinuxTransport if (useSignal) { return CmdBreakUnix(debuggeePid, ResultClass.done); } } } else if (IsRemoteGdbTarget() && _transport is PipeTransport) { int pid = PidByInferior("i1"); if (pid != 0 && ((PipeTransport)_transport).Interrupt(pid)) { return Task.FromResult<Results>(new Results(ResultClass.done)); } } else if (IsRemoteGdbTarget() && _transport is UnixShellPortTransport) { int pid = PidByInferior("i1"); if (pid != 0 && ((UnixShellPortTransport)_transport).Interrupt(pid)) { return Task.FromResult<Results>(new Results(ResultClass.done)); } } var res = CmdAsync("-exec-interrupt", ResultClass.done); return res.ContinueWith((t) => { if (t.Result.Contains("reason")) // interrupt finished synchronously { ScheduleResultProcessing(() => OnStopped(t.Result)); } }); } public void CmdContinueAsync() { this.VerifyNotDebuggingCoreDump(); PostCommand("-exec-continue"); } public void CmdExitAsync() { // 'gdb' required for legacy PostCommand("-gdb-exit"); } private string Escape(string str) { StringBuilder outStr = new StringBuilder(); for (int i = 0; i < str.Length; ++i) { switch (str[i]) { case '\"': outStr.Append("\\\""); break; case '\\': outStr.Append("\\\\"); break; default: outStr.Append(str[i]); break; } } return outStr.ToString(); } /// <summary> /// Sends 'cmd' to the debuggee as a console command. /// </summary> /// <param name="cmd">The command to send.</param> /// <param name="allowWhileRunning">Set to 'true' if the process can be running while the command is executed.</param> /// <param name="ignoreFailures">Ignore any failure that occur when executing the command.</param> /// <returns></returns> public async Task<string> ConsoleCmdAsync(string cmd, bool allowWhileRunning, bool ignoreFailures = false) { if (!(this.ProcessState == ProcessState.Running && allowWhileRunning) && this.ProcessState != ProcessState.Stopped && this.ProcessState != ProcessState.NotConnected) { if (this.ProcessState == ProcessState.Exited) { throw new DebuggerDisposedException(GetTargetProcessExitedReason()); } else { throw new InvalidOperationException(MICoreResources.Error_ProcessMustBeStopped); } } using (ExclusiveLockToken lockToken = await _commandLock.AquireExclusive()) { // check again now that we have the lock if (!(this.ProcessState == ProcessState.Running && allowWhileRunning) && this.ProcessState != ProcessState.Stopped && this.ProcessState != ProcessState.NotConnected) { if (this.ProcessState == ProcessState.Exited) { throw new DebuggerDisposedException(GetTargetProcessExitedReason()); } else { throw new InvalidOperationException(MICoreResources.Error_ProcessMustBeStopped); } } Debug.Assert(_consoleCommandOutput == null, "How is m_consoleCommandOutput already set? Should be impossible."); _consoleCommandOutput = new StringBuilder(); try { await ExclusiveCmdAsync("-interpreter-exec console \"" + Escape(cmd) + "\"", ignoreFailures ? ResultClass.None : ResultClass.done, lockToken); return _consoleCommandOutput.ToString(); } finally { _consoleCommandOutput = null; } } } private string GetTargetProcessExitedReason() { if (_closeMessage != null) { return _closeMessage; } return MICoreResources.Error_TargetProcessExited; } public async Task<Results> CmdAsync(string command, ResultClass expectedResultClass) { await _commandLock.AquireShared(); try { return await CmdAsyncInternal(command, expectedResultClass); } finally { _commandLock.ReleaseShared(); } } public Task<Results> ExclusiveCmdAsync(string command, ResultClass expectedResultClass, ExclusiveLockToken exclusiveLockToken) { if (ExclusiveLockToken.IsNullOrClosed(exclusiveLockToken)) { throw new ArgumentNullException(nameof(exclusiveLockToken)); } return CmdAsyncInternal(command, expectedResultClass); } private Task<Results> CmdAsyncInternal(string command, ResultClass expectedResultClass) { var waitingOperation = new WaitingOperationDescriptor(command, expectedResultClass); uint id; lock (_waitingOperations) { if (this.IsClosed) { throw new DebuggerDisposedException(_closeMessage); } id = ++_lastCommandId; _waitingOperations.Add(id, waitingOperation); _lastCommandText = command; } SendToTransport(id.ToString(CultureInfo.InvariantCulture) + command); return waitingOperation.Task; } private Task<Results> CmdBreakUnix(int debugeePid, ResultClass expectedResultClass) { // Send sigtrap to the debuggee process. This is the equivalent of hitting ctrl-c on the console. // This will cause gdb to async-break. This is necessary because gdb does not support async break // when attached. UnixUtilities.Interrupt(debugeePid); return Task.FromResult<Results>(new Results(ResultClass.done)); } #region ITransportCallback implementation // Note: this can be called from any thread void ITransportCallback.OnStdOutLine(string line) { if (_initializationLog != null) { lock (_waitingOperations) { // check again now that the lock is aquired if (_initializationLog != null) { _initializationLog.AddLast(line); } } } ScheduleStdOutProcessing(line); } void ITransportCallback.OnStdErrorLine(string line) { Logger.WriteLine("STDERR: " + line); if (_initialErrors != null) { lock (_waitingOperations) { if (_initialErrors != null) { _initialErrors.AddLast(line); } if (_initializationLog != null) { _initializationLog.AddLast(line); } } } } public void OnDebuggerProcessExit(/*OPTIONAL*/ string exitCode) { // GDB has exited. Cleanup. Only let one thread perform the cleanup if (Interlocked.CompareExchange(ref _exiting, 1, 0) == 0) { if (_consoleDebuggerInitializeCompletionSource != null) { lock (_waitingOperations) { if (_consoleDebuggerInitializeCompletionSource != null) { MIDebuggerInitializeFailedException exception; string version = GdbVersionFromLog(); // We can't use IsMinGW or IsCygwin because we never connected to the debugger bool isMinGWOrCygwin = _launchOptions is LocalLaunchOptions && PlatformUtilities.IsWindows() && this.MICommandFactory.Mode == MIMode.Gdb; if (isMinGWOrCygwin && version != null && IsUnsupportedWindowsGdbVersion(version)) { exception = new MIDebuggerInitializeFailedUnsupportedGdbException( this.MICommandFactory.Name, _initialErrors.ToList().AsReadOnly(), _initializationLog.ToList().AsReadOnly(), version); SendUnsupportedWindowsGdbEvent(version); } else { exception = new MIDebuggerInitializeFailedException( this.MICommandFactory.Name, _initialErrors.ToList().AsReadOnly(), _initializationLog.ToList().AsReadOnly()); } _initialErrors = null; _initializationLog = null; _consoleDebuggerInitializeCompletionSource.TrySetException(exception); } } } string message; if (string.IsNullOrEmpty(exitCode)) message = string.Format(CultureInfo.CurrentCulture, MICoreResources.Error_MIDebuggerExited_UnknownCode, this.MICommandFactory.Name); else message = string.Format(CultureInfo.CurrentCulture, MICoreResources.Error_MIDebuggerExited_WithCode, this.MICommandFactory.Name, exitCode); Close(message); if (this.ProcessState != ProcessState.Exited && !_terminating && !_detaching) { if (DebuggerAbortedEvent != null) { DebuggerAbortedEvent(this, new DebuggerAbortedEventArgs(message, exitCode)); } } else { if (DebuggerExitEvent != null) { DebuggerExitEvent(this, null); } } } } string GdbVersionFromLog() { foreach (string line in _initializationLog) { // Second set of parenthesis looks for a Cygwin-specific version number // Cygwin example: GNU gdb (GDB) (Cygwin 7.11.1-2) 7.11.1 // MinGW example: GNU gdb (GDB) 8.0.1 Match match = Regex.Match(line, "GNU gdb \\(GDB\\) (?:\\(Cygwin (\\d+[\\d\\.-]*)\\) )?(\\d+[\\d\\.-]*)"); if (match.Success) { return match.Groups[1].Success ? match.Groups[1].Value : match.Groups[2].Value; } } return null; } bool IsUnsupportedWindowsGdbVersion(string version) { return new string[] { "7.12", "7.12-1", "7.12-2", "7.12-3", "7.12.1", "7.12.1-1" }.Contains(version); } void SendUnsupportedWindowsGdbEvent(string version) { HostTelemetry.SendEvent(Event_UnsupportedWindowsGdb, new KeyValuePair<string, object>(Property_GdbVersion, version)); } void ITransportCallback.AppendToInitializationLog(string line) { Logger.WriteLine(line); if (_initializationLog != null) { lock (_waitingOperations) { // check again now that the lock is aquired if (_initializationLog != null) { _initializationLog.AddLast(line); } } } } void ITransportCallback.LogText(string line) { if (!line.EndsWith("\n", StringComparison.Ordinal)) { line += "\n"; } if (OutputStringEvent != null) { OutputStringEvent(this, line); } } #endregion // inherited classes can override this for thread marshalling etc protected virtual void ScheduleStdOutProcessing(string line) { ProcessStdOutLine(line); } protected virtual void ScheduleResultProcessing(Action func) { func(); } // a Token is a sequence of decimal digits followed by something else // returns null if not a token, or not followed by something else private string ParseToken(ref string cmd) { if (char.IsDigit(cmd, 0)) { int i; for (i = 1; i < cmd.Length; i++) { if (!char.IsDigit(cmd, i)) break; } if (i < cmd.Length) { string token = cmd.Substring(0, i); cmd = cmd.Substring(i); return token; } } return null; } private class WaitingOperationDescriptor { /// <summary> /// Text of the command that we sent to the debugger (ex: '-target-attach 72') /// </summary> public readonly string Command; private readonly ResultClass _expectedResultClass; private readonly TaskCompletionSource<Results> _completionSource = new TaskCompletionSource<Results>(); public DateTime StartTime { get; private set; } /// <summary> /// True if the transport has echoed back text which is the same as this command /// </summary> public bool EchoReceived { get; set; } public WaitingOperationDescriptor(string command, ResultClass expectedResultClass) { this.Command = command; _expectedResultClass = expectedResultClass; StartTime = DateTime.Now; } internal void OnComplete(Results results, MICommandFactory commandFactory) { if (_expectedResultClass != ResultClass.None && _expectedResultClass != results.ResultClass) { string miError = null; if (results.ResultClass == ResultClass.error) { // Fixes: https://github.com/microsoft/vscode-cpptools/issues/2492 try { miError = results.FindString("msg"); } catch (MIResultFormatException) { try { // TODO: Remove after update to mainline lldb-mi // lldb-mi has certain instances (such as the -exec-* commands) that calls the message // "message" instead of "msg" miError = results.FindString("message"); } catch (MIResultFormatException) { // make the error a generic '<Unknown Error>' message miError = MICoreResources.Error_UnknownError; } } } else { miError = String.Format(CultureInfo.CurrentCulture, MICoreResources.Error_UnexpectedResultClass, Enum.GetName(typeof(ResultClass), _expectedResultClass), Enum.GetName(typeof(ResultClass), results.ResultClass)); } _completionSource.SetException(new UnexpectedMIResultException(commandFactory.Name, this.Command, miError)); } else { _completionSource.SetResult(results); } } public Task<Results> Task { get { return _completionSource.Task; } } internal void Abort(string abortMessage) { _completionSource.SetException(new DebuggerDisposedException(abortMessage, Command)); } } private readonly Dictionary<uint, WaitingOperationDescriptor> _waitingOperations = new Dictionary<uint, WaitingOperationDescriptor>(); /// <summary> /// Returns true it is a (gdb) prompt. /// </summary> /// <param name="prompt">The prompt from the debugger</param> /// <returns>True if (gdb) prompt, false otherwise</returns> /// <remarks>For SSH transport connecting to gdb, it has a trailing space following the prompt like "(gdb) ".</remarks> private static bool IsGdbPrompt(string prompt) { const string gdbPrompt = "(gdb)"; return prompt.StartsWith(gdbPrompt, StringComparison.Ordinal) && prompt.Trim().Length == gdbPrompt.Length; } public void ProcessStdOutLine(string line) { string originalLine = line; if (line.Length == 0) { return; } else if (IsGdbPrompt(line)) { if (_consoleDebuggerInitializeCompletionSource != null) { lock (_waitingOperations) { if (_consoleDebuggerInitializeCompletionSource != null) { _consoleDebuggerInitializeCompletionSource.TrySetResult(null); } } } } else { string token = ParseToken(ref line); char c = line[0]; string noprefix = line.Substring(1).Trim(); if (token != null) { // Look for event handlers registered on a specific Result id if (c == '^') { uint id = uint.Parse(token, CultureInfo.InvariantCulture); WaitingOperationDescriptor waitingOperation = null; lock (_waitingOperations) { if (_waitingOperations.TryGetValue(id, out waitingOperation)) { _waitingOperations.Remove(id); } } if (waitingOperation != null) { Results results = _miResults.ParseCommandOutput(noprefix); Logger.WriteLine(id.ToString(CultureInfo.InvariantCulture) + ": elapsed time " + ((int)(DateTime.Now - waitingOperation.StartTime).TotalMilliseconds).ToString(CultureInfo.InvariantCulture)); waitingOperation.OnComplete(results, this.MICommandFactory); return; } } // Check to see if we are just getting the echo of the command we sent else if (c == '-') { uint id = uint.Parse(token, CultureInfo.InvariantCulture); lock (_waitingOperations) { WaitingOperationDescriptor waitingOperation; if (_waitingOperations.TryGetValue(id, out waitingOperation) && !waitingOperation.EchoReceived && line == waitingOperation.Command) { // This is just the echo. Ignore. waitingOperation.EchoReceived = true; return; } } } } switch (c) { case '~': OnDebuggeeOutput(noprefix); // Console stream break; case '^': OnResult(noprefix, token); break; case '*': OnOutOfBand(noprefix); break; case '&': OnLogStreamOutput(noprefix); break; case '=': OnNotificationOutput(noprefix); break; default: // Token is not prepended, use original line. OnDebuggeeOutput(originalLine + '\n'); break; } } } private void OnUnknown(string cmd) { Debug.WriteLine("DBG:Unknown command: {0}", cmd); } private void OnResult(string cmd, string token) { uint id = token != null ? uint.Parse(token, CultureInfo.InvariantCulture) : 0; Results results = _miResults.ParseCommandOutput(cmd); if (results.ResultClass == ResultClass.done) { if (EvaluationEvent != null) { EvaluationEvent(this, new ResultEventArgs(results, id)); } } else if (results.ResultClass == ResultClass.error) { if (ErrorEvent != null) { ErrorEvent(this, new ResultEventArgs(results, id)); } } else { OnStateChanged(cmd, ""); } } private void OnDebuggeeOutput(string cmd) { string decodedOutput = _miResults.ParseCString(cmd); if (_consoleCommandOutput == null) { if (OutputStringEvent != null) { OutputStringEvent(this, decodedOutput); } } else { _consoleCommandOutput.Append(decodedOutput); } } public void WriteOutput(string message) { if (OutputStringEvent != null) { OutputStringEvent(this, message + '\n'); } } private void OnLogStreamOutput(string cmd) { if (_consoleCommandOutput == null) { // We see this in the transport diagnostics, we don't need to see it anywhere else } else { string decodedOutput = _miResults.ParseCString(cmd); _consoleCommandOutput.Append(decodedOutput); } } private void OnOutOfBand(string cmd) { if (cmd.StartsWith("stopped,", StringComparison.Ordinal)) { string status = _miResults.ParseCString(cmd.Substring(8)); OnStateChanged("stopped", status); } else if (cmd.StartsWith("stopped", StringComparison.Ordinal)) { if (PlatformUtilities.IsWindows() && this.LaunchOptions is LocalLaunchOptions && ((LocalLaunchOptions)this.LaunchOptions).ProcessId.HasValue && this.MICommandFactory.Mode == MIMode.Gdb && !this.IsCygwin ) { // mingw enters break mode with no status flags on the mi response during attach. // In order to keey the entrypoint state correct, set it to true and continue // the break. this.EntrypointHit = true; CmdContinueAsync(); } else { Debug.Fail("Unknown out-of-band msg: " + cmd); } } else if (cmd.StartsWith("running,", StringComparison.Ordinal)) { string status = _miResults.ParseCString(cmd.Substring(8)); OnStateChanged("running", status); } else { Debug.Fail("Unknown out-of-band msg: " + cmd); } } private void OnNotificationOutput(string cmd) { Results results = null; if ((results = MICommandFactory.IsModuleLoad(cmd)) != null) { if (LibraryLoadEvent != null) { LibraryLoadEvent(this, new ResultEventArgs(results)); } } else if (cmd.StartsWith("breakpoint-modified,", StringComparison.Ordinal)) { results = _miResults.ParseResultList(cmd.Substring(20)); if (BreakChangeEvent != null) { BreakChangeEvent(this, new ResultEventArgs(results)); } } else if (cmd.StartsWith("breakpoint-created,", StringComparison.Ordinal)) { results = _miResults.ParseResultList(cmd.Substring("breakpoint-created,".Length)); if (BreakCreatedEvent != null) { BreakCreatedEvent(this, new ResultEventArgs(results)); } } else if (cmd.StartsWith("thread-group-started,", StringComparison.Ordinal)) { results = _miResults.ParseResultList(cmd.Substring("thread-group-started,".Length)); HandleThreadGroupStarted(results); } else if (cmd.StartsWith("thread-group-exited,", StringComparison.Ordinal)) { results = _miResults.ParseResultList(cmd.Substring("thread-group-exited,".Length)); HandleThreadGroupExited(results); if (ThreadGroupExitedEvent != null) { ThreadGroupExitedEvent(this, new ResultEventArgs(results, 0)); } } else if (cmd.StartsWith("thread-created,", StringComparison.Ordinal)) { results = _miResults.ParseResultList(cmd.Substring("thread-created,".Length)); ThreadCreatedEvent(this, new ResultEventArgs(results, 0)); } else if (cmd.StartsWith("thread-exited,", StringComparison.Ordinal)) { results = _miResults.ParseResultList(cmd.Substring("thread-exited,".Length)); ThreadExitedEvent(this, new ResultEventArgs(results, 0)); } else if (cmd.StartsWith("telemetry,", StringComparison.Ordinal)) { results = _miResults.ParseResultList(cmd.Substring("telemetry,".Length)); if (this.TelemetryEvent != null) { this.TelemetryEvent(this, new ResultEventArgs(results)); } } else { // append a newline if the message didn't come with one if (!cmd.EndsWith("\n", StringComparison.Ordinal)) { cmd += "\n"; } OnDebuggeeOutput("=" + cmd); } } /// <summary> /// Obtains the last command (ex: '-exec-break') that we sent to the debugger. This is used in telemetry, and probably shouldn't /// be used for any other reason. /// </summary> /// <returns>The empty string if we haven't sent any commands yet. Otherwise the text of the command</returns> public string GetLastSentCommandName() { string lastCommandText = _lastCommandText; if (string.IsNullOrEmpty(lastCommandText)) { // We haven't sent any commands yet return string.Empty; } int spaceIndex = lastCommandText.IndexOf(' '); if (spaceIndex >= 0) { // The last command had arguments. Remove them. return lastCommandText.Substring(0, spaceIndex); } else { // The last command took no arguments. return lastCommandText; } } private void HandleThreadGroupStarted(Results results) { string threadGroupId = results.FindString("id"); string pidString = results.FindString("pid"); int pid = Int32.Parse(pidString, CultureInfo.InvariantCulture); // Ignore pid 0 due to spurious thread group created event on iOS (lldb). // On android the scheduler runs as pid 0, but that process cannot currently be debugged anyway. if (pid != 0) { lock (_debuggeePids) { _debuggeePids.Add(threadGroupId, pid); } } } public uint InferiorByPid(int pid) { foreach (var grp in _debuggeePids) { if (grp.Value == pid) { return InferiorNumber(grp.Key); } } return 0; } public int PidByInferior(string inf) { if (_debuggeePids.ContainsKey(inf)) { return _debuggeePids[inf]; } return 0; } public uint InferiorNumber(string groupId) { // Inferior names are of the form "iX" where X in the inferior number if (groupId.Length >= 2 && groupId[0] == 'i') { uint id; if (UInt32.TryParse(groupId.Substring(1), out id)) { return id; } } return 1; // default to the first inferior if group-id not understood } private void HandleThreadGroupExited(Results results) { string threadGroupId = results.TryFindString("id"); bool isThreadGroupEmpty = false; if (!String.IsNullOrEmpty(threadGroupId)) { lock (_debuggeePids) { if (_debuggeePids.Remove(threadGroupId)) { isThreadGroupEmpty = _debuggeePids.Count == 0; } } } if (isThreadGroupEmpty) { ScheduleStdOutProcessing(@"*stopped,reason=""exited"""); if (!IsUnixDebuggerRunning()) { // Processing the fake "stopped" event sent above will normally cause the debugger to close, but if // the debugger process is already gone (e.g. because the terminal window was closed), we won't get // a response, so queue a fake "exit" event for processing as well. ScheduleStdOutProcessing("^exit"); } } } private async void PostCommand(string cmd) { try { await _commandLock.AquireShared(); try { _lastCommandText = cmd; SendToTransport(cmd); } finally { _commandLock.ReleaseShared(); } } catch (ObjectDisposedException) { // This method has 'post' semantics, so if debugging is already stopped, we don't want to throw } } private void SendToTransport(string cmd) { _transport.Send(cmd); // https://github.com/Microsoft/MIEngine/issues/616 : // If it is local gdb (MinGW/Cygwin) on Windows, we need to send an extra line after commands // so that if it errors, the error will come through. if (this.SendNewLineAfterCmd) { _transport.Send(String.Empty); } } public static ulong ParseAddr(string addr, bool throwOnError = false) { ulong res = 0; if (string.IsNullOrEmpty(addr)) { if (throwOnError) { throw new ArgumentNullException(nameof(addr)); } return 0; } else if (addr.StartsWith("0x", StringComparison.OrdinalIgnoreCase)) { if (throwOnError) { res = ulong.Parse(addr.Substring(2), System.Globalization.NumberStyles.HexNumber, CultureInfo.InvariantCulture); } else { ulong.TryParse(addr.Substring(2), System.Globalization.NumberStyles.HexNumber, CultureInfo.InvariantCulture, out res); } } else { if (throwOnError) { res = ulong.Parse(addr, System.Globalization.NumberStyles.Integer, CultureInfo.InvariantCulture); } else { ulong.TryParse(addr, System.Globalization.NumberStyles.Integer, CultureInfo.InvariantCulture, out res); } } return res; } public static uint ParseUint(string str, bool throwOnError = false) { uint value = 0; if (string.IsNullOrEmpty(str)) { if (throwOnError) { throw new ArgumentException(null, nameof(str)); } return value; } else if (str.StartsWith("0x", StringComparison.OrdinalIgnoreCase)) { if (throwOnError) { value = uint.Parse(str.Substring(2), System.Globalization.NumberStyles.HexNumber, CultureInfo.InvariantCulture); } else { uint.TryParse(str.Substring(2), System.Globalization.NumberStyles.HexNumber, CultureInfo.InvariantCulture, out value); } } else { if (throwOnError) { value = uint.Parse(str, System.Globalization.NumberStyles.Integer, CultureInfo.InvariantCulture); } else { uint.TryParse(str, System.Globalization.NumberStyles.Integer, CultureInfo.InvariantCulture, out value); } } return value; } public void VerifyNotDebuggingCoreDump() { if (this.IsCoreDump) throw new InvalidCoreDumpOperationException(); } } public class DebuggerAbortedEventArgs { public readonly string Message; public readonly string /*OPTIONAL*/ ExitCode; public DebuggerAbortedEventArgs(string message, string exitCode) { Debug.Assert(message != null, "Invalid argument"); this.Message = message; this.ExitCode = exitCode; } }; } <|start_filename|>test/DebuggerTesting/OpenDebug/Commands/StackTraceCommand.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using DebuggerTesting.OpenDebug.Commands.Responses; using Newtonsoft.Json; namespace DebuggerTesting.OpenDebug.Commands { public sealed class StackTraceArgs : ThreadCommandArgs { public int levels; [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public int? startFrame; } public class StackTraceCommand : CommandWithResponse<StackTraceArgs, StackTraceResponseValue> { public StackTraceCommand(int threadId, int? startFrame = null) : base("stackTrace") { this.Args.threadId = threadId; this.Args.levels = 20; this.Args.startFrame = startFrame; } } } <|start_filename|>test/DebuggerTesting/Utilities/DisposableObject.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; namespace DebuggerTesting { /// <summary> /// Base class for disposable objects. /// </summary> public abstract class DisposableObject : IDisposable { #region Constructor protected DisposableObject() { } #endregion #region Destructor ~DisposableObject() { if (!this.IsDisposed) { this.Dispose(isDisposing: false); } } #endregion #region IDisposable Members public void Dispose() { UDebug.Assert(!this.IsDisposed, "This was already disposed"); if (!this.IsDisposed) { this.Dispose(isDisposing: true); GC.SuppressFinalize(this); } } #endregion #region Methods protected virtual void Dispose(bool isDisposing) { this.IsDisposed = true; } /// <summary> /// Throws an exception if the object is disposed. /// </summary> protected void VerifyNotDisposed() { if (this.IsDisposed) throw new ObjectDisposedException(this.GetType().FullName); } #endregion #region Properties /// <summary> /// Gets a value indicating whether the object is disposed. /// </summary> public bool IsDisposed { get; private set; } #endregion } } <|start_filename|>test/CppTests/OpenDebug/CrossPlatCpp/DebuggerRunnerExtensions.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Diagnostics; using DebuggerTesting.Compilation; namespace DebuggerTesting.OpenDebug.CrossPlatCpp { public static class DebuggerRunnerExtensions { public static void Launch(this IDebuggerRunner runner, IDebuggerSettings settings, bool stopAtEntry, string program, params string[] args) { runner.RunCommand(new LaunchCommand(settings, program, false, args) { StopAtEntry = stopAtEntry }); } public static void Launch(this IDebuggerRunner runner, IDebuggerSettings settings, bool stopAtEntry, IDebuggee debuggee, params string[] args) { runner.Launch(settings, stopAtEntry, debuggee.OutputPath, args); } public static void Launch(this IDebuggerRunner runner, IDebuggerSettings settings, IDebuggee debuggee, params string[] args) { runner.Launch(settings, false, debuggee.OutputPath, args); } public static void Attach(this IDebuggerRunner runner, IDebuggerSettings settings, Process process) { runner.RunCommand(new AttachCommand(settings, process)); } public static void LaunchCoreDump(this IDebuggerRunner runner, IDebuggerSettings settings, IDebuggee debuggee, string coreDumpPath) { runner.RunCommand(new LaunchCommand(settings, debuggee.OutputPath, coreDumpPath)); } } } <|start_filename|>src/SSHDebugPS/SSH/SSHRemoteShell.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using liblinux; using liblinux.Shell; namespace Microsoft.SSHDebugPS.SSH { /// <summary> /// Wrapper for liblinux's StreamingShell /// </summary> internal class SSHRemoteShell : ICommandRunner { private StreamingShell _shell; public SSHRemoteShell(UnixSystem remoteSystem) { _shell = new StreamingShell(remoteSystem); _shell.OutputReceived += OnOutputReceived; _shell.Closed += OnClosedOrDisconnected; _shell.Disconnected += OnClosedOrDisconnected; _shell.ErrorOccured += OnError; } public void Start() { _shell.BeginOutputRead(); } public event EventHandler<string> OutputReceived; public event EventHandler<int> Closed; public event EventHandler<ErrorOccuredEventArgs> ErrorOccured; private void OnOutputReceived(object sender, OutputReceivedEventArgs e) { OutputReceived?.Invoke(sender, e?.Output); } private void OnClosedOrDisconnected(object sender, EventArgs e) { // No exit code here, so assume success? Closed?.Invoke(sender, 0); } private void OnError(object sender, liblinux.ErrorOccuredEventArgs e) { ErrorOccured?.Invoke(sender, new ErrorOccuredEventArgs(e.Exception)); } public void Dispose() { if (_shell != null) { _shell.OutputReceived -= OnOutputReceived; _shell.Closed -= OnClosedOrDisconnected; _shell.Disconnected -= OnClosedOrDisconnected; _shell.ErrorOccured -= OnError; _shell.Dispose(); _shell = null; } } public void Write(string text) { _shell.Write(text); _shell.Flush(); } public void WriteCommandStart(string startCommand) { _shell.WriteLine(startCommand); } public void WriteLine(string text) { _shell.WriteLine(text); _shell.Flush(); } } } <|start_filename|>src/SSHDebugPS/UI/Controls/Automation/ContainerListBoxItemAutomationPeer.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Windows.Automation; using System.Windows.Automation.Peers; using System.Windows.Automation.Provider; namespace Microsoft.SSHDebugPS.UI { /// <summary> /// This automationpeer class is here to support the custom expand/collapse action on the listbox item /// </summary> /// <typeparam name="T">Must be IContainerViewModel</typeparam> public class ContainerListBoxItemAutomationPeer<T> : ListBoxItemAutomationPeer, IExpandCollapseProvider where T : IContainerViewModel { public ContainerListBoxItemAutomationPeer(object item, ContainerListBoxAutomationPeer ownerAutomationPeer) : base(item, ownerAutomationPeer) { } /// <summary> /// Item is from the constructor and is the IContainerViewModel, not the listboxitem /// </summary> protected T ViewModel { get { return (T)Item; } } #region IExpandCollapseProvider public ExpandCollapseState ExpandCollapseState { get { return ViewModel.IsExpanded ? ExpandCollapseState.Expanded : ExpandCollapseState.Collapsed; } } public void Expand() { ViewModel.IsExpanded = true; } public void Collapse() { ViewModel.IsExpanded = false; } #endregion public override object GetPattern(PatternInterface patternInterface) { if (patternInterface == PatternInterface.ExpandCollapse) { return this; } return base.GetPattern(patternInterface); } #region Core overrides protected override AutomationControlType GetAutomationControlTypeCore() { return AutomationControlType.ListItem; } protected override string GetLocalizedControlTypeCore() { return ControlType.Button.LocalizedControlType; } protected override string GetNameCore() { return ViewModel.ContainerAutomationName; } protected override bool IsKeyboardFocusableCore() { return true; } #endregion } } <|start_filename|>src/OpenDebugAD7/ThreadFrameEnumInfo.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.VisualStudio.Debugger.Interop; namespace OpenDebugAD7 { public class ThreadFrameEnumInfo { internal IEnumDebugFrameInfo2 FrameEnum { get; private set; } internal uint TotalFrames { get; private set; } internal uint CurrentPosition { get; set; } internal ThreadFrameEnumInfo(IEnumDebugFrameInfo2 frameEnum, uint totalFrames) { FrameEnum = frameEnum; TotalFrames = totalFrames; CurrentPosition = 0; } } } <|start_filename|>src/SSHDebugPS/Utilities/ExitCodes.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.SSHDebugPS.Utilities { internal class ExitCodes { // Official codes public static int SUCCESS = 0; public static int LINUX_COMMANDCANNOTEXECUTE = 126; public static int LINUX_COMMANDNOTFOUND = 127; public static int OPERATION_TIMEDOUT = 1490; // Custom codes internal static int OBJECTDISPOSED = 1999; } } <|start_filename|>test/DebuggerTesting/OpenDebug/Commands/DisassembleCommand.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using DebuggerTesting.OpenDebug.Commands.Responses; using Newtonsoft.Json; using System; namespace DebuggerTesting.OpenDebug.Commands { public sealed class DisassembleArgs : JsonValue { public string memoryReference; public int? offset; public int? instructionOffset; public int instructionCount; public bool? resolveSymbols; } public class DisassembleCommand : CommandWithResponse<DisassembleArgs, DisassembleResponseValue> { public DisassembleCommand(string memoryReference, int? offset, int? instructionOffset, int instructionCount, bool? resolveSymbols) : base("disassemble") { this.Args.memoryReference = memoryReference; this.Args.offset = offset; this.Args.instructionOffset = instructionOffset; this.Args.instructionCount = instructionCount; this.Args.resolveSymbols = resolveSymbols; } } } <|start_filename|>src/MIDebugEngine/Natvis.Impl/NatvisNames.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Text.RegularExpressions; using MICore; using System.Globalization; namespace Microsoft.MIDebugEngine.Natvis { internal class TypeName { public string FullyQualifiedName { get; private set; } public List<TypeName> Qualifiers { get; private set; } public string BaseName { get; set; } public List<TypeName> Args { get; private set; } // template arguements public List<TypeName> Parameters { get; private set; } // parameter types public bool IsWildcard { get; private set; } public bool IsArray { get; private set; } public bool IsFunction { get; private set; } public int[] Dimensions { get; private set; } public bool IsConst { get; private set; } private void SetArraySize(int[] Dims) { IsArray = true; Dimensions = Dims; } private static Regex s_identifier = new Regex("^[a-zA-Z$_][a-zA-Z$_0-9]*"); private static Regex s_numeric = new Regex("^[0-9]+(u|l|ul)*"); // only decimal constants private static Regex s_simpleType = new Regex( @"^(signed\s+char|unsigned\s+char|char16_t|char32_t|wchar_t|char|" + @"signed\s+short\s+int|signed\s+short|unsigned\s+short\s+int|unsigned\s+short|short\s+int|short|" + @"signed\s+int|unsigned\s+int|int|" + @"signed\s+long\s+int|unsigned\s+long\s+int|long\s+int|long|" + @"signed\s+long\s+long\s+int|long\s+long\s+int|unsigned\s+long\s+long\s+int|long\s+long" + @"float|double|" + @"long\s+double|bool|void)\b" // matches prefixes ending in '$' (e.g. void$Foo), these are checked for below ); private static readonly TypeName s_any = new TypeName() { IsWildcard = true }; private TypeName() { Args = new List<TypeName>(); Qualifiers = new List<TypeName>(); Parameters = null; IsWildcard = false; IsArray = false; } private TypeName(string name) : this() { BaseName = name; } /// <summary> /// Match this typeName to a candidate typeName. This type support wildcard matching against the candidate /// </summary> /// <param name="t"></param> /// <returns></returns> public bool Match(TypeName t) { if (IsWildcard) { return true; } if (Qualifiers.Count != t.Qualifiers.Count) { return false; } if (BaseName != t.BaseName) { return false; } for (int i = 0; i < Qualifiers.Count; ++i) { if (!Qualifiers[i].Match(t.Qualifiers[i])) { return false; } } // args must match one-for one, // or if last arg is a wildcard it will match any number of additional args if (Args.Count > t.Args.Count || (Args.Count == 0 && t.Args.Count > 0) || (Args.Count < t.Args.Count && !Args[Args.Count - 1].IsWildcard)) { return false; } for (int arg = 0; arg < Args.Count; ++arg) { if (!Args[arg].Match(t.Args[arg])) { return false; } } if (IsArray != t.IsArray) { return false; } if (IsArray) { if (Dimensions.Length != t.Dimensions.Length) { return false; } for (int i = 0; i < Dimensions.Length; i++) { if (Dimensions[i] != t.Dimensions[i]) { if (Dimensions[i] != -1) { return false; } } } } return true; } /// <summary> /// Return a parsed type name /// Acceptable name format: /// typeName = ["const "] ([unqualifiedName "::"]* unqualifiedName | simpleTypeName) ['*'] [Array] | funtionDef /// unqualifiedName = identifier | identifier '<' templateList '>' /// templatelist = listElem | listElem ',' templateList /// listElem = typeName | numericConstant | '*' /// Array = '[]' | '[' [numericConstant ',']* numericConstant ']' /// functionDef = typeName (parameterList) /// /// </summary> /// <param name="fullyQualifiedName"></param> /// <returns></returns> public static TypeName Parse(string fullyQualifiedName, Logger logger) { if (String.IsNullOrEmpty(fullyQualifiedName)) return null; string rest = null; TypeName t = MatchTypeName(fullyQualifiedName.Trim(), out rest); if (!String.IsNullOrWhiteSpace(rest)) { logger.WriteLine("Natvis failed to parse typename: " + fullyQualifiedName); return null; } return t; } /// <summary> /// /// </summary> /// <param name="name">Trimmed string containing a type name</param> /// <param name="rest">Trimmed remainder of string after name match</param> /// <returns></returns> private static TypeName MatchTypeName(string name, out string rest) { string original = name; if (name.StartsWith("const ", StringComparison.Ordinal)) { name = name.Substring(6).Trim(); // TODO: we just ignore const } TypeName t = MatchSimpleTypeName(name, out rest); if (t == null) { List<TypeName> qualifiers = new List<TypeName>(); t = MatchUnqualifiedName(name, out rest); while (t != null && rest.Length > 2 && rest.StartsWith("::", StringComparison.Ordinal)) { // process qualifiers qualifiers.Add(t); t = MatchUnqualifiedName(rest.Substring(2).Trim(), out rest); } if (t == null) { return null; } t.Qualifiers = qualifiers; // add qualifiers to the type } if (rest.StartsWith("const", StringComparison.Ordinal)) { rest = rest.Substring(5).Trim(); } while (rest.StartsWith("*", StringComparison.Ordinal) || rest.StartsWith("&", StringComparison.Ordinal)) { t.BaseName += rest[0]; rest = rest.Substring(1).Trim(); if (rest.StartsWith("const", StringComparison.Ordinal)) { rest = rest.Substring(5).Trim(); } } MatchArray(t, rest, out rest); // add array or pointer if (rest.StartsWith("(", StringComparison.Ordinal)) { t.IsFunction = true; t.Parameters = new List<TypeName>(); if (!MatchParameterList(rest.Substring(1).Trim(), out rest, t.Parameters)) { return null; } if (rest.Length > 0 && rest[0] == ')') { rest = rest.Substring(1).Trim(); } else { return null; } } // complete the full name of the type t.FullyQualifiedName = original.Substring(0, original.Length - rest.Length); return t; } private static TypeName MatchSimpleTypeName(string name, out string rest) { rest = String.Empty; var m = s_simpleType.Match(name); if (m.Success) { // The simpleType regular expression will succeed for strings that look like // simple types, but are terminated by '$'. // Since the $ is a valid C++ identifier character we check it here to make // sure we haven't accidentally matched a prefix, e.g. int$Foo string r = name.Substring(m.Length); if (r.Length > 0 && r[0] == '$') { return null; } rest = r.Trim(); return new TypeName(m.Value); } return null; } private static TypeName MatchUnqualifiedName(string name, out string rest) { string basename = MatchIdentifier(name, out rest); if (String.IsNullOrEmpty(basename)) { return null; } TypeName t = new TypeName(basename); if (rest.Length > 0 && rest[0] == '<') { if (!MatchTemplateList(rest.Substring(1).Trim(), out rest, t.Args) || rest.Length < 1 || rest[0] != '>') { return null; } rest = rest.Substring(1).Trim(); } return t; } private static void MatchArray(TypeName t, string name, out string rest) { if (name.StartsWith("[]", StringComparison.Ordinal)) { t.SetArraySize(new int[] { -1 }); rest = name.Substring(2).Trim(); } else if (name.StartsWith("[", StringComparison.Ordinal)) // TODO: handle multiple dimensions { string num = MatchConstant(name.Substring(1).Trim(), out rest); if (rest.StartsWith("]", StringComparison.Ordinal)) { t.SetArraySize(new int[] { Int32.Parse(num, CultureInfo.InvariantCulture) }); } rest = rest.Substring(1).Trim(); } else { rest = name; } } private static string MatchIdentifier(string name, out string rest) { rest = String.Empty; var m = s_identifier.Match(name); if (m.Success) { rest = name.Substring(m.Length).Trim(); } return m.Value; } private static string MatchConstant(string name, out string rest) { rest = String.Empty; var m = s_numeric.Match(name); if (m.Success) { rest = name.Substring(m.Length).Trim(); } return m.Value; } private static bool MatchTemplateList(string templist, out string rest, List<TypeName> args) { TypeName t; string arg = MatchConstant(templist, out rest); // no constants allowed in parameter lists if (!String.IsNullOrEmpty(arg)) { var constantArg = new TypeName(arg); constantArg.FullyQualifiedName = arg; args.Add(constantArg); } else if (templist.StartsWith("*", StringComparison.Ordinal)) { rest = templist.Substring(1).Trim(); args.Add(TypeName.s_any); } else if ((t = MatchTypeName(templist, out rest)) != null) { args.Add(t); } else { return false; } if (rest.Length > 1 && rest[0] == ',') { return MatchTemplateList(rest.Substring(1).Trim(), out rest, args); } return true; } private static bool MatchParameterList(string plist, out string rest, List<TypeName> args) { rest = plist; while (rest.Length > 0 && rest[0] != ')') { TypeName t; if ((t = MatchTypeName(rest, out rest)) == null) { return false; } args.Add(t); if (t != null && rest.Length > 1 && rest[0] == ',') { rest = rest.Substring(1).Trim(); } } return true; } } } <|start_filename|>src/OpenDebugAD7/OpenDebug/PathUtilities.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.IO; // This code is based on https://github.com/Microsoft/vscode-mono-debug/blob/master/src/common/PathUtilities.cs namespace OpenDebug { public class PathUtilities { public static string NormalizePath(string path) { return new Uri(path).LocalPath; //return Path.GetFullPath(new Uri(path).LocalPath).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar); } public static string CombineAndNormalize(string path1, string path2) { var p = Path.Combine(path1, path2); return PathUtilities.NormalizePath(p); } /** * Make path relative to target. * Finds common prefix of both paths and then converts path into a path that is relative to the prefix. * If there is no common prefix, null is returned. */ public static string MakeRelative(string target, string path) { var t = target.Split(Path.DirectorySeparatorChar); var p = path.Split(Path.DirectorySeparatorChar); var i = 0; for (; i < Math.Min(t.Length, p.Length) && t[i] == p[i]; i++) { } var result = ""; for (; i < p.Length; i++) { result = Path.Combine(result, p[i]); } return result; } public static string RemoveFirstSegment(string path) { if (path[0] == Path.DirectorySeparatorChar) { path = path.Substring(1); } int pos = path.IndexOf(Path.DirectorySeparatorChar, StringComparison.Ordinal); if (pos >= 0) { path = path.Substring(pos + 1); } else { return null; } if (path.Length > 0) { return path; } return null; } public static string MakePathAbsolute(string path, string path2) { if (path != null && !Path.IsPathRooted(path)) { var dir = Path.GetDirectoryName(path2); path = Path.Combine(dir, path); path = new Uri(path).LocalPath; // normalize } return path; } public static string MakeRelativePath(string dir_path, string path) { /* if (!dir_path.EndsWith(""+Path.DirectorySeparatorChar)) { dir_path += Path.DirectorySeparatorChar; } */ Uri uri1 = new Uri(path); Uri uri2 = new Uri(dir_path); return uri2.MakeRelativeUri(uri1).ToString(); } } } <|start_filename|>src/DebugEngineHost/VSImpl/VsWaitLoop.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Shell; using System.Threading; using Microsoft.Win32.SafeHandles; using Microsoft.VisualStudio; using System.Diagnostics; using System.Runtime.InteropServices; namespace Microsoft.DebugEngineHost.VSImpl { // Seperate class for waiting using VS interfaces // ************************************************************ // * IMPORTANT: This needs to be a seperate class as when the JIT'er tries to JIT anything in this // * class it may through a FileNotFound exception for the VS assemblies. Do _NOT_ reference the // * VS assemblies from another class. // ************************************************************ internal class VsWaitLoop { private readonly IVsCommonMessagePump _messagePump; private VsWaitLoop(string text) { int hr; var messagePumpFactory = (IVsCommonMessagePumpFactory)Package.GetGlobalService(typeof(SVsCommonMessagePumpFactory)); if (messagePumpFactory == null) { return; // normal case in glass } IVsCommonMessagePump messagePump; hr = messagePumpFactory.CreateInstance(out messagePump); if (hr != 0) return; hr = messagePump.SetAllowCancel(true); if (hr != 0) return; hr = messagePump.SetWaitText(text); if (hr != 0) return; hr = messagePump.SetStatusBarText(string.Empty); if (hr != 0) return; _messagePump = messagePump; } static public VsWaitLoop TryCreate(string text) { VsWaitLoop waitLoop = new VsWaitLoop(text); if (waitLoop._messagePump == null) return null; return waitLoop; } /// <summary> /// Waits on the specified handle using the VS wait UI. /// </summary> /// <param name="launchCompleteHandle">[Required] handle to wait on</param> /// <param name="cancellationSource">[Required] Object to signal cancellation if cancellation is requested</param> /// <returns>true if we were able to successfully wait, false if we failed to wait and should fall back to the CLR provided wait function</returns> /// <exception cref="FileNotFoundException">Thrown by the JIT if Visual Studio is not installed</exception> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods", MessageId = "System.Runtime.InteropServices.SafeHandle.DangerousGetHandle")] public void Wait(WaitHandle launchCompleteHandle, CancellationTokenSource cancellationSource) { int hr; SafeWaitHandle safeWaitHandle = launchCompleteHandle.SafeWaitHandle; bool addRefSucceeded = false; try { safeWaitHandle.DangerousAddRef(ref addRefSucceeded); if (!addRefSucceeded) { throw new ObjectDisposedException("launchCompleteHandle"); } IntPtr nativeHandle = safeWaitHandle.DangerousGetHandle(); IntPtr[] handles = { nativeHandle }; uint waitResult; hr = _messagePump.ModalWaitForObjects(handles, (uint)handles.Length, out waitResult); if (hr == 0) { return; } else if (hr == VSConstants.E_PENDING || hr == VSConstants.E_ABORT) { // E_PENDING: user canceled // E_ABORT: application exit cancellationSource.Cancel(); throw new OperationCanceledException(); } else { Debug.Fail("Unexpected result from ModalWaitForObjects"); Marshal.ThrowExceptionForHR(hr); } } finally { if (addRefSucceeded) { safeWaitHandle.DangerousRelease(); } } } public void SetProgress(int totalSteps, int currentStep, string progressText) { _messagePump.SetProgressInfo(totalSteps, currentStep, progressText); } public void SetText(string text) { _messagePump.SetWaitText(text); } } } <|start_filename|>test/LaunchOptionsGen/LaunchOptionsGen.cs<|end_filename|> using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace LaunchOptionsGen { class LaunchOptionsGen { static int Main(string[] args) { string templatePath; Dictionary<string, string> properties; if (!ValidateCommandLine(args, out templatePath, out properties)) { Console.WriteLine("Syntax error: arguments to LaunchOptionsGen.exe are incorrect."); return -1; } if (!File.Exists(templatePath)) { Console.WriteLine("Error: File {0} does not exist."); return -1; } string outputFile = Path.Combine(Path.GetDirectoryName(Path.GetFullPath(templatePath)), "LaunchOptions.xml"); string[] lines = File.ReadAllLines(templatePath); string pattern = @"\$([a-zA-Z0-9]+)\$"; Regex regex = new Regex(pattern); for (int i = 0; i < lines.Length; i++) { string line = lines[i]; Match m = regex.Match(line); while (m.Success) { string key = m.Groups[1].Captures[0].Value; string value; if (properties.TryGetValue(key, out value)) { line = line.Replace(m.Value, value); } else { Console.WriteLine("Error: LaunchOptions template file contains properties that were not specified on the command line to LaunchOptionsGen.exe"); return -1; } m = m.NextMatch(); } lines[i] = line; } File.WriteAllLines(outputFile, lines); return 0; } private static bool ValidateCommandLine(string[] args, out string templatePath, out Dictionary<string, string> properties) { templatePath = null; properties = new Dictionary<string, string>(); if (args.Length < 1) { return false; } templatePath = args[0]; if (templatePath.IndexOfAny(Path.GetInvalidPathChars()) != -1) { return false; } if (args.Length > 1) { for (int i = 1; i < args.Length; i++) { string arg = args[i]; string[] pair = arg.Split('='); if (pair.Length != 2) { return false; } string key = pair[0]; string value = pair[1]; value.Replace("\"", ""); //strip single quotes in the case of paths properties.Add(pair[0].Trim(), pair[1].Trim()); } } return true; } } } <|start_filename|>test/DebuggerTesting/Compilation/GppCompiler.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using DebuggerTesting.Utilities; namespace DebuggerTesting.Compilation { internal sealed class GppCompiler : GppStyleCompiler { public GppCompiler(ILoggingComponent logger, ICompilerSettings settings) : base(logger, settings) { } protected override void SetAdditionalArguments(ArgumentBuilder builder) { base.SetAdditionalArguments(builder); DefineConstant(builder, "DEBUGGEE_COMPILER", "G++"); } } } <|start_filename|>test/DebuggerTesting/OpenDebug/Events/Event.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace DebuggerTesting.OpenDebug.Events { public abstract class EventValue : JsonValue { public string @event; } public abstract class Event<T> : Response<T>, IEvent where T : EventValue, new() { public Event(string eventName) { Parameter.ThrowIfNull(eventName, nameof(eventName)); this.ExpectedResponse.@event = eventName; } public string Name { get { return this.ExpectedResponse.@event; } } public virtual void ProcessActualResponse(IActualResponse response) { this.ActualEvent = response.Convert<T>(); } public T ActualEvent { get; protected set; } public override string ToString() { return this.Name; } } } <|start_filename|>test/DebuggerTesting/OpenDebug/Commands/Responses/SourceResponseValue.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Newtonsoft.Json; namespace DebuggerTesting.OpenDebug.Commands.Responses { public sealed class SourceResponseValue : CommandResponseValue { public sealed class Body { [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public string content; } public Body body = new Body(); } } <|start_filename|>src/JDbgUnitTests/JdwpTests.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using JDbg; using Xunit; namespace JDbgUnitTests { public class JdwpTests { [Fact] public void VersionPacketTest() { var versionCommand = new VersionCommand(); byte[] packetBytes = versionCommand.GetPacketBytes(); Assert.Equal(0x00, packetBytes[0]); Assert.Equal(0x00, packetBytes[1]); Assert.Equal(0x00, packetBytes[2]); Assert.Equal(0x0b, packetBytes[3]); Assert.Equal(0x00, packetBytes[4]); Assert.Equal(0x00, packetBytes[5]); Assert.Equal(0x00, packetBytes[6]); Assert.Equal(0x01, packetBytes[7]); Assert.Equal(0x00, packetBytes[8]); Assert.Equal(0x01, packetBytes[9]); Assert.Equal(0x01, packetBytes[10]); } } } <|start_filename|>test/Android/Exceptions/Exceptions/Exceptions.NativeActivity/main.cpp<|end_filename|> /* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #define LOGI(...) ((void)__android_log_print(ANDROID_LOG_INFO, "AndroidProject1.NativeActivity", __VA_ARGS__)) #define LOGW(...) ((void)__android_log_print(ANDROID_LOG_WARN, "AndroidProject1.NativeActivity", __VA_ARGS__)) void divide_by_zero() { for (int i = -1; i < 2; i++) { int j = 5 / i; } } void segmentation_fault() { int* i = 0; int j = *i; } /** * This is the main entry point of a native application that is using * android_native_app_glue. It runs in its own thread, with its own * event loop for receiving input events and doing other things. */ void android_main(struct android_app* state) { int i = 0; int j = 0; //bp here switch (i) { case 1: divide_by_zero(); break; case 2: segmentation_fault(); break; } } <|start_filename|>test/DebugAdapterRunner/Command.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; namespace DebugAdapterRunner { /// <summary>Base test script command</summary> /// <remarks>Commands that are sent to the debug adapters can use DebugAdapterCommand. /// Custom commands can be derived from this base class</remarks> public class Command { public string Name; public List<DebugAdapterResponse> ExpectedResponses = new List<DebugAdapterResponse>(); public virtual void Run(DebugAdapterRunner runner) { } } } <|start_filename|>src/JDbg/TcpTransport.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Net.Sockets; using System.Text; using System.Threading; using System.Threading.Tasks; namespace JDbg { /// <summary> /// Delegate to call when a packet arrives /// </summary> /// <param name="packet">[Required] bytes of the packet</param> internal delegate void OnPacket(byte[] packet); /// <summary> /// Delegate to call when the target disconnects on a Socket error occurres /// </summary> /// <param name="exception">[Optional] socket exception that caused the disconnect</param> internal delegate void OnDisconnect(SocketException exception); /// <summary> /// Transport built on TCP to be used by Jdwp /// </summary> internal class TcpTransport { private OnPacket _onPacket; private OnDisconnect _onDisconnect; private TcpClient _client; //NetworkStream m_stream; private Thread _thread; private bool _bQuit; public TcpTransport(string hostname, int port, OnPacket onPacket, OnDisconnect onDisconnect) { _bQuit = false; _client = new TcpClient(); _client.NoDelay = true; _client.ReceiveBufferSize = 2048; _client.SendBufferSize = 2048; _client.ReceiveTimeout = 0; _client.SendTimeout = 30000; _client.LingerState = new LingerOption(true, 30); _client.Connect(hostname, port); //m_stream = m_client.GetStream(); _onPacket = onPacket; _onDisconnect = onDisconnect; DoHandShake(); StartThread("JDbg.TcpTransport"); } private void StartThread(string name) { _thread = new Thread(TransportLoop); _thread.Name = name; _thread.Start(); } private void DoHandShake() { string handShakeString = "JDWP-Handshake"; byte[] handShakeStringBytes = Encoding.UTF8.GetBytes(handShakeString); Send(handShakeStringBytes); try { byte[] handShakeReply = new byte[handShakeStringBytes.Length]; int bytesReceived = _client.Client.Receive(handShakeReply); string reply = Encoding.UTF8.GetString(handShakeReply); if (bytesReceived < handShakeStringBytes.Length || string.Compare(reply, handShakeString, StringComparison.Ordinal) != 0) { if (bytesReceived == 0) { throw new JdwpException(ErrorCode.VMUnavailable, "VM is not accepting connections from the debugger"); } throw new JdwpException(ErrorCode.InvalidResponse, "Invalid response to connect message"); } } catch (SocketException e) { throw new JdwpException(ErrorCode.SocketError, "Handshake failed due to SocketException", e); } } //public void Send(byte[] packet) //{ // m_client.Client.Send(packet); //} private void TransportLoop() { SocketException disconnectException = null; try { while (!_bQuit) { //the first four bytes will be the size of the whole packet byte[] packetSizeBytes = new byte[4]; if (!TryReceive(packetSizeBytes) || _bQuit) { break; } uint packetSize = Utils.UInt32FromBigEndianBytes(packetSizeBytes); if (packetSize < JdwpCommand.HEADER_SIZE) { Debug.Fail("How did we read 4 bytes that don't give us a size larger than the packet header?"); continue; } //the remainder of the packet is the size minus 4 (since we already read the size) byte[] packetBytes = new byte[packetSize]; Array.Copy(packetSizeBytes, 0, packetBytes, 0, 4); int remainingPacketByteCount = (int)packetSize - 4; if (!TryReceive(packetBytes, 4, remainingPacketByteCount) || _bQuit) { break; } _onPacket(packetBytes); } } catch (SocketException e) { disconnectException = e; } if (!_bQuit) { _onDisconnect(disconnectException); } } public void Send(byte[] buffer) { try { int bytesSent = _client.Client.Send(buffer); if (bytesSent != buffer.Length) { throw new JdwpException(ErrorCode.SendFailure, "Failed to send bytes."); } } catch (SocketException e) { throw new JdwpException(ErrorCode.SendFailure, "Failed to send bytes.", e); } } private bool TryReceive(byte[] buffer) { return TryReceive(buffer, 0, buffer.Length); } private bool TryReceive(byte[] buffer, int offset, int size) { int bytesReceived = 0; int sizeRemaining = size; while (bytesReceived < size) { int newBytes = _client.Client.Receive(buffer, offset, sizeRemaining, SocketFlags.None); if (newBytes == 0) { return false; } bytesReceived += newBytes; offset += newBytes; sizeRemaining -= newBytes; } return true; } public void Close() { _bQuit = true; if (_client != null) { _client.Close(); } } } } <|start_filename|>src/AndroidDebugLauncher/NDKPrebuiltFilePath.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.IO; namespace AndroidDebugLauncher { public class NDKPrebuiltFilePath : INDKFilePath { public string PartialFilePath { get; } private NDKPrebuiltFilePath(string partialFilePath) { this.PartialFilePath = partialFilePath; } public static NDKPrebuiltFilePath[] GDBPaths() { return new NDKPrebuiltFilePath[] { new NDKPrebuiltFilePath(@"windows\bin\gdb.exe"), // windows-x86 NDK path new NDKPrebuiltFilePath(@"windows-x86_64\bin\gdb.exe"), // windows-x86 NDK path }; } public string TryResolve(string ndkRoot) { string prebuiltDirectory = GetPrebuiltDirectory(ndkRoot); string path = Path.Combine(prebuiltDirectory, PartialFilePath); if (File.Exists(path)) { return path; } return null; } public string GetSearchPathDescription(string ndkRoot) { return GetPrebuiltDirectory(ndkRoot); } private static string GetPrebuiltDirectory(string ndkRoot) { return Path.Combine(ndkRoot, "prebuilt"); } public static NDKPrebuiltFilePath[] GDBServerPaths(string targetArchitecture) { string gdbServerPartialPath = Path.Combine( String.Concat("android-", targetArchitecture), "gdbserver", "gdbserver"); return new NDKPrebuiltFilePath[] { new NDKPrebuiltFilePath(gdbServerPartialPath) }; } } } <|start_filename|>test/DebuggerTesting/ILoggingComponent.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.IO; using Xunit.Abstractions; namespace DebuggerTesting { /// <summary> /// A component that can log to the test output. /// </summary> public interface ILoggingComponent { ITestOutputHelper OutputHelper { get; } } /// <summary> /// Provide some extensions to a test logging component. /// </summary> public static class LoggingTestExtensions { public static void WriteLine(this ILoggingComponent component, string message = "", params object[] args) { // Invalid XML characters cause xUnit not to write the whole results file // For now we only handle null characters since that's what's causing issues and // this is just a temporary workaround. // See https://github.com/xunit/xunit/issues/876#issuecomment-253337669 if (!string.IsNullOrEmpty(message)) { message = message.Replace("\0", "<null>"); } if (args.Length > 0) component?.OutputHelper?.WriteLine(message, args); else component?.OutputHelper?.WriteLine(message); } public static void WriteLines(this ILoggingComponent component, StreamReader reader) { Parameter.ThrowIfNull(reader, nameof(reader)); string line = null; while (null != (line = reader.ReadLine())) { component.WriteLine(line); } } /// <summary> /// Log a message with details on the tests current settings /// </summary> public static void WriteSettings(this ILoggingComponent component, ITestSettings testSettings) { component.WriteLine("Test: {0}", testSettings.Name); component.WriteLine(testSettings.CompilerSettings.ToString()); component.WriteLine(testSettings.DebuggerSettings.ToString()); } /// <summary> /// Log a message commenting on what the test is currently trying to accomplish. /// </summary> public static void Comment(this ILoggingComponent component, string message, params object[] args) { component.WriteLine(); component.WriteLine("# " + message + GetTimestamp(), args); } /// <summary> /// Log a message commenting on what the overall purpose of the test /// </summary> public static void TestPurpose(this ILoggingComponent component, string message) { string timestamp = GetTimestamp(); string commentLine = new string('#', message.Length + timestamp.Length + 4); component.WriteLine(commentLine); component.WriteLine("# {0}{1} #", message , timestamp); component.WriteLine(commentLine); } private static string GetTimestamp() { return " ({0:HH:mm:ss.fff})".FormatInvariantWithArgs(DateTime.Now); } } } <|start_filename|>test/DebuggerTesting/Compilation/XCodeRunCompiler.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.IO; using System.Collections.Generic; using DebuggerTesting.Utilities; namespace DebuggerTesting.Compilation { internal sealed class XCodeCompiler : CompilerBase { #region Constructor public XCodeCompiler(ILoggingComponent logger, ICompilerSettings settings) : base(logger, settings, false) { } #endregion #region Methods protected override bool CompileCore( CompilerOutputType outputType, SupportedArchitecture architecture, IEnumerable<string> libraries, IEnumerable<string> sourceFilePaths, string targetFilePath, CompilerOption options, IDictionary<string, string> defineConstants) { if (outputType != CompilerOutputType.MacOSApp) { throw new InvalidOperationException("Output type is: " + outputType); } //xcodebuild -project TestApp.xcodeproj -configuration Debug -scheme "TestApp (macOS)" CONFIGURATION_BUILD_DIR="./out/xcoderun/x64/" string project = string.Empty; foreach (string sourceFile in sourceFilePaths) { if (sourceFile.EndsWith(".xcodeproj")) { project = sourceFile; } } if (string.IsNullOrWhiteSpace(project)) { throw new InvalidOperationException(".xcodeproj is missing"); } ArgumentBuilder builder = new ArgumentBuilder("-", " "); builder.AppendNamedArgument("project", project); builder.AppendNamedArgument("configuration", "Debug"); builder.AppendNamedArgumentQuoted("scheme", "TestApp (macOS)"); return 0 == this.RunCompiler(builder.ToString() + " CONFIGURATION_BUILD_DIR=\"" + Path.GetDirectoryName(targetFilePath) + "\"", targetFilePath); } #endregion } } <|start_filename|>test/CppTests/Tests/OptimizationTest.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Linq; using DebuggerTesting; using DebuggerTesting.Compilation; using DebuggerTesting.OpenDebug; using DebuggerTesting.OpenDebug.Commands; using DebuggerTesting.OpenDebug.CrossPlatCpp; using DebuggerTesting.OpenDebug.Extensions; using DebuggerTesting.Ordering; using Xunit; using Xunit.Abstractions; namespace CppTests.Tests { [TestCaseOrderer(DependencyTestOrderer.TypeName, DependencyTestOrderer.AssemblyName)] public class OptimizationTests : TestBase { #region Constructor public OptimizationTests(ITestOutputHelper outputHelper) : base(outputHelper) { } #endregion #region Member Variables private const string Name = "optimization"; private const string SourceName = "source.cpp"; private const string UserDefinedClassName = "foo.cpp"; private const string SrcLibName = "mylib.cpp"; private const string OutLibName = "mylib"; #endregion #region Methods [Theory] [RequiresTestSettings] public void CompileSharedLibDebuggeeWithoutSymbol(ITestSettings settings) { this.TestPurpose("Create and compile the 'sharedlib' debuggee"); this.WriteSettings(settings); //Compile the shared library CompileSharedLib(settings, DebuggeeMonikers.Optimization.OptimizationWithoutSymbols, false); //Compile the application CompileApp(settings, DebuggeeMonikers.Optimization.OptimizationWithoutSymbols); } [Theory] [DependsOnTest(nameof(CompileSharedLibDebuggeeWithoutSymbol))] [UnsupportedDebugger(SupportedDebugger.VsDbg, SupportedArchitecture.x86 | SupportedArchitecture.x64)] [RequiresTestSettings] public void TestSharedLibWithoutSymbol(ITestSettings settings) { this.TestPurpose("Tests basic bps and source information for shared library without symbols"); this.WriteSettings(settings); IDebuggee debuggee = Debuggee.Open(this, settings.CompilerSettings, Name, DebuggeeMonikers.Optimization.OptimizationWithoutSymbols); using (IDebuggerRunner runner = CreateDebugAdapterRunner(settings)) { this.Comment("Configure launch"); runner.Launch(settings.DebuggerSettings, debuggee); SourceBreakpoints mainBreakpoints = debuggee.Breakpoints(SourceName, 87, 91); this.Comment("Set initial breakpoints"); runner.SetBreakpoints(mainBreakpoints); this.Comment("Launch and run until 1st bp"); runner.Expects.HitBreakpointEvent(SourceName, 87) .AfterConfigurationDone(); this.Comment("Step into the library source"); runner.Expects.HitStepEvent(SourceName, 89) .AfterStepIn(); this.Comment("Check the stack for debugging shared library without symbols"); using (IThreadInspector inspector = runner.GetThreadInspector()) { IFrameInspector currentFrame = inspector.Stack.First(); inspector.AssertStackFrameNames(true, "main"); this.Comment("run to continue to 2nd bp"); runner.Expects.HitBreakpointEvent(SourceName, 91) .AfterContinue(); this.Comment("Check the stack for debugging shared library without symbols"); currentFrame = inspector.Stack.First(); inspector.AssertStackFrameNames(true, "main"); this.Comment("Check the local variables in main function"); IVariableInspector age = currentFrame.Variables["age"]; Assert.Matches("31", age.Value); } runner.DisconnectAndVerify(); } } [Theory] [RequiresTestSettings] public void CompileSharedLibDebuggeeWithSymbol(ITestSettings settings) { this.TestPurpose("Create and compile the 'sharedlib' debuggee"); this.WriteSettings(settings); //Compile the shared library CompileSharedLib(settings, DebuggeeMonikers.Optimization.OptimizationWithSymbols,true); //Compile the application CompileApp(settings, DebuggeeMonikers.Optimization.OptimizationWithSymbols); } [Theory] [DependsOnTest(nameof(CompileSharedLibDebuggeeWithSymbol))] [UnsupportedDebugger(SupportedDebugger.VsDbg, SupportedArchitecture.x86 | SupportedArchitecture.x64)] [RequiresTestSettings] public void TestOptimizedBpsAndSource(ITestSettings settings) { this.TestPurpose("Tests basic operation of bps and source information for optimized app"); this.WriteSettings(settings); IDebuggee debuggee = Debuggee.Open(this, settings.CompilerSettings, Name, DebuggeeMonikers.Optimization.OptimizationWithSymbols); using (IDebuggerRunner runner = CreateDebugAdapterRunner(settings)) { this.Comment("Configure launch"); runner.Launch(settings.DebuggerSettings, debuggee); SourceBreakpoints mainBreakpoints = debuggee.Breakpoints(SourceName, 68); SourceBreakpoints userDefinedClassBreakpoints = debuggee.Breakpoints(UserDefinedClassName, 8,15,54); this.Comment("Set initial breakpoints"); runner.SetBreakpoints(mainBreakpoints); runner.SetBreakpoints(userDefinedClassBreakpoints); this.Comment("Launch and run until 1st bp"); runner.Expects.HitBreakpointEvent(UserDefinedClassName, 8) .AfterConfigurationDone(); this.Comment("run until 2nd bp"); runner.Expects.HitBreakpointEvent(UserDefinedClassName, 54) .AfterContinue(); this.Comment("run until 3rd bp"); runner.Expects.HitBreakpointEvent(SourceName, 68) .AfterContinue(); //Todo: this has different behavior on Mac(:16), Other Platforms(15) I have logged bug#247891 to track this.Comment("run until 4th bp"); runner.ExpectBreakpointAndStepToTarget(UserDefinedClassName, 15, 16).AfterContinue(); this.Comment("continue to next bp"); runner.Expects.HitBreakpointEvent(UserDefinedClassName, 54) .AfterContinue(); this.Comment("Check the current callstack frame"); using (IThreadInspector threadInspector = runner.GetThreadInspector()) { this.Comment("Get current frame object"); IFrameInspector currentFrame = threadInspector.Stack.First(); this.Comment("Verify current frame"); threadInspector.AssertStackFrameNames(true, "Foo::Sum"); } this.Comment("step out to main entry"); runner.Expects.HitStepEvent(SourceName, 69) .AfterStepOut(); runner.Expects.ExitedEvent(0).TerminatedEvent().AfterContinue(); runner.DisconnectAndVerify(); } } [Theory] [DependsOnTest(nameof(CompileSharedLibDebuggeeWithSymbol))] [RequiresTestSettings] public void TestOptimizedLocals(ITestSettings settings) { this.TestPurpose("Tests basic local expression which is not been optimized"); this.WriteSettings(settings); IDebuggee debuggee = Debuggee.Open(this, settings.CompilerSettings, Name, DebuggeeMonikers.Optimization.OptimizationWithSymbols); using (IDebuggerRunner runner = CreateDebugAdapterRunner(settings)) { this.Comment("Configure launch"); runner.Launch(settings.DebuggerSettings, debuggee); SourceBreakpoints userDefinedClassBreakpoints = debuggee.Breakpoints(UserDefinedClassName, 54); this.Comment("Set initial breakpoints"); runner.SetBreakpoints(userDefinedClassBreakpoints); this.Comment("Launch and run until 1st bp"); runner.Expects.HitBreakpointEvent(UserDefinedClassName, 54) .AfterConfigurationDone(); this.Comment("Check the un-optimized values"); using (IThreadInspector inspector = runner.GetThreadInspector()) { IFrameInspector currentFrame = inspector.Stack.First(); IVariableInspector sum = currentFrame.Variables["sum"]; IVariableInspector first = currentFrame.Variables["first"]; this.Comment("Check the local variables in sub function"); Assert.Matches("^0",sum.Value); Assert.Matches("^1",first.Value); this.Comment("Step out"); runner.Expects.HitStepEvent(SourceName, 66) .AfterStepOut(); this.Comment("Evaluate the expression:"); currentFrame = inspector.Stack.First(); inspector.AssertStackFrameNames(true, "main"); } runner.DisconnectAndVerify(); } } [Theory] [DependsOnTest(nameof(CompileSharedLibDebuggeeWithSymbol))] // TODO: Re-enable for Gdb_Gnu and Gdb_MinGW [UnsupportedDebugger(SupportedDebugger.Gdb_MinGW | SupportedDebugger.Gdb_Gnu | SupportedDebugger.VsDbg, SupportedArchitecture.x86 | SupportedArchitecture.x64)] [RequiresTestSettings] public void TestOptimizedSharedLib(ITestSettings settings) { this.TestPurpose("Tests basic bps and source information for shared library"); this.WriteSettings(settings); IDebuggee debuggee = Debuggee.Open(this, settings.CompilerSettings, Name, DebuggeeMonikers.Optimization.OptimizationWithSymbols); using (IDebuggerRunner runner = CreateDebugAdapterRunner(settings)) { this.Comment("Configure launch"); runner.Launch(settings.DebuggerSettings, debuggee); SourceBreakpoints mainBreakpoints = debuggee.Breakpoints(SourceName, 87, 89); SourceBreakpoints libBreakpoints = debuggee.Breakpoints(SrcLibName, 9, 12); this.Comment("Set initial breakpoints"); runner.SetBreakpoints(mainBreakpoints); runner.SetBreakpoints(libBreakpoints); this.Comment("Launch and run until 1st bp"); runner.Expects.HitBreakpointEvent(SourceName, 87) .AfterConfigurationDone(); //Todo: this has different behavior on Mac, I have logged bug#247895 to track //Del said that Different compilers generate symbols differently. //Our tests have to be resilient to this fact. The location of the step is reasonable, //so this is by design. this.Comment("enter into the library source"); runner.ExpectBreakpointAndStepToTarget(SrcLibName, 8, 9).AfterContinue(); this.Comment("Step over"); runner.Expects.HitStepEvent(SrcLibName, 10).AfterStepOver(); this.Comment("Check the un-optimized values in shared library"); using (IThreadInspector inspector = runner.GetThreadInspector()) { IFrameInspector currentFrame = inspector.Stack.First(); IVariableInspector age = currentFrame.Variables["age"]; this.Comment("Check the local variable in sub function"); Assert.Matches("31", age.Value); this.Comment("run to continue"); if(settings.DebuggerSettings.DebuggerType == SupportedDebugger.Lldb) { runner.Expects.HitBreakpointEvent(SourceName, 89) .AfterContinue(); this.Comment("Verify current frame for main func"); inspector.AssertStackFrameNames(true, "main"); } else { runner.Expects.HitBreakpointEvent(SrcLibName, 12) .AfterContinue(); this.Comment("Verify current frame for library func"); inspector.AssertStackFrameNames(true, "myClass::DisplayAge"); this.Comment("Step out to main entry"); runner.Expects.HitBreakpointEvent(SourceName, 89).AfterContinue(); this.Comment("Verify current frame for main entry"); inspector.AssertStackFrameNames(true, "main"); } this.Comment("Evaluate the expression:"); //skip the Mac's verification as bug#247893 currentFrame = inspector.Stack.First(); string strAge = currentFrame.Evaluate("myclass->DisplayAge(30)"); if (settings.DebuggerSettings.DebuggerType == SupportedDebugger.Gdb_MinGW || settings.DebuggerSettings.DebuggerType == SupportedDebugger.Gdb_Cygwin) { Assert.Equal("Cannot evaluate function -- may be inlined", strAge); } } runner.DisconnectAndVerify(); } } #endregion #region Function Helper private void CompileSharedLib(ITestSettings settings, int debuggeeMoniker, bool symbol) { IDebuggee debuggee = Debuggee.Create(this, settings.CompilerSettings, Name, debuggeeMoniker, OutLibName, CompilerOutputType.SharedLibrary); debuggee.AddSourceFiles(SrcLibName); debuggee.CompilerOptions = CompilerOption.OptimizeLevel2; if (symbol) { debuggee.CompilerOptions = CompilerOption.GenerateSymbols; } debuggee.Compile(); } private void CompileApp(ITestSettings settings, int debuggeeMoniker) { IDebuggee debuggee = Debuggee.Open(this, settings.CompilerSettings, Name, debuggeeMoniker, null, CompilerOutputType.Executable); switch (settings.DebuggerSettings.DebuggerType) { case SupportedDebugger.Gdb_Cygwin: case SupportedDebugger.Gdb_Gnu: case SupportedDebugger.Lldb: debuggee.AddLibraries("dl"); break; } debuggee.AddSourceFiles(SourceName,UserDefinedClassName); debuggee.CompilerOptions = CompilerOption.OptimizeLevel2; debuggee.CompilerOptions = CompilerOption.GenerateSymbols; debuggee.Compile(); } #endregion } } <|start_filename|>test/Android/Breakpoint/Breakpoint/Breakpoint.NativeActivity/main.cpp<|end_filename|> /* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #define LOGI(...) ((void)__android_log_print(ANDROID_LOG_INFO, "AndroidProject1.NativeActivity", __VA_ARGS__)) #define LOGW(...) ((void)__android_log_print(ANDROID_LOG_WARN, "AndroidProject1.NativeActivity", __VA_ARGS__)) void break_test_1() { for (int i = 0; i < 2; i++) { int j = 0; // set bp here, line 25 j++; } int i = 0; i++; //set bp here, line 29 } void loop_while_true() { bool flag = true; while (flag) { int i = 0; // set bp here, line 38 } } void break_test_2() { loop_while_true(); int i = 0; // set bp here, line 45 loop_while_true(); int j = 0; // set bp here, line 48 } /** * This is the main entry point of a native application that is using * android_native_app_glue. It runs in its own thread, with its own * event loop for receiving input events and doing other things. */ void android_main(struct android_app* state) { break_test_1(); break_test_2(); } <|start_filename|>src/MIDebugEngine/Engine.Impl/Disassembly.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Diagnostics; using MICore; using System.Globalization; namespace Microsoft.MIDebugEngine { internal class DisasmInstruction { public ulong Addr; public string AddressString; public string Symbol; public uint Offset; public string Opcode; public string CodeBytes; public string File; public uint Line; public uint OffsetInLine; }; internal class DisassemblyBlock { static private long s_touchCount = 0; internal long Touch; private readonly DisasmInstruction[] _instructions; private int FindIndex(ulong addr) { // allow addresses within an instruction to match the instruction for (int i = 0; i < _instructions.Length - 1; ++i) { if (_instructions[i].Addr <= addr && _instructions[i + 1].Addr > addr) { return i; } } if (_instructions[_instructions.Length - 1].Addr == addr) { return _instructions.Length - 1; } return -1; } internal ulong Address { get { return _instructions[0].Addr; } } internal int Count { get { return _instructions.Length; } } public bool Contains(ulong addr, int cnt) { if (_instructions.Length == 0) return false; if (_instructions[0].Addr > addr || addr > _instructions[_instructions.Length - 1].Addr) return false; int i = FindIndex(addr); if (i < 0) { return false; } i += cnt; Touch = Interlocked.Increment(ref s_touchCount); return 0 <= i && i <= _instructions.Length; } public bool TryFetch(ulong addr, int cnt, out ICollection<DisasmInstruction> instructions) { instructions = null; if (!Contains(addr, cnt)) return false; int i = FindIndex(addr); if (cnt < 0) { i = i + cnt; cnt = -cnt; } instructions = new ArraySegment<DisasmInstruction>(_instructions, i, cnt); return true; } public bool TryFetch(ulong startAddr, ulong endAddr, out ICollection<DisasmInstruction> instructions) { instructions = null; if (!Contains(startAddr, 1)) return false; if (!Contains(endAddr, 1)) return false; int i = FindIndex(startAddr); int j = FindIndex(endAddr); instructions = new ArraySegment<DisasmInstruction>(_instructions, i, j-i); return true; } public DisasmInstruction At(ulong addr) { Debug.Assert(Contains(addr, 1), "Address not in block"); Touch = ++s_touchCount; for (int i = 0; i < _instructions.Length; ++i) { if (_instructions[i].Addr == addr) { return _instructions[i]; } } return null; } public DisassemblyBlock(DisasmInstruction[] ins) { Touch = ++s_touchCount; _instructions = ins; } } internal class Disassembly { private const int cacheSize = 10; // number of cached blocks to keep private SortedList<ulong, DisassemblyBlock> _disassemlyCache; private DebuggedProcess _process; public Disassembly(DebuggedProcess process) { _process = process; _disassemlyCache = new SortedList<ulong, DisassemblyBlock>(); } private ICollection<DisasmInstruction> UpdateCache(ulong address, int nInstructions, DisasmInstruction[] instructions) { ICollection<DisasmInstruction> ret = null; if (instructions != null && instructions.Length > 0) { DisassemblyBlock block = new DisassemblyBlock(instructions); lock (_disassemlyCache) { // push to the cache DeleteRangeFromCache(block); // removes any entry with the same key if (_disassemlyCache.Count >= cacheSize) { long max = 0; int toDelete = -1; for (int i = 0; i < _disassemlyCache.Count; ++i) { var e = _disassemlyCache.ElementAt(i); if (e.Value.Touch > max) { max = e.Value.Touch; toDelete = i; } } Debug.Assert(toDelete >= 0, "Failed to flush from the cache"); _disassemlyCache.RemoveAt(toDelete); } _disassemlyCache.Add(block.Address, block); } var kv = block.TryFetch(address, nInstructions, out ret); } return ret; } /// <summary> /// Seek backward n instructions from a target address /// </summary> /// <param name="address">target address</param> /// <param name="nInstructions">number of instructions</param> /// <returns> address - n on failure, else the address of an instruction n back from the target address</returns> public async Task<ulong> SeekBack(ulong address, int nInstructions) { ICollection<DisasmInstruction> ret = null; ulong defaultAddr = address >= (ulong)nInstructions ? address - (ulong)nInstructions : 0; lock (_disassemlyCache) { // check the cache, look for it to contain nInstructions back from the address var kv = _disassemlyCache.FirstOrDefault((p) => p.Value.TryFetch(address, -nInstructions, out ret)); if (kv.Value != null) return ret.First().Addr; } ulong endAddress; ulong startAddress; var range = await _process.FindValidMemoryRange(address, (uint)(_process.MaxInstructionSize * (nInstructions+1)), (int)(_process.MaxInstructionSize * -nInstructions)); startAddress = range.Item1; endAddress = range.Item2; if (endAddress - startAddress == 0 || address < startAddress) // bad address range, no instructions { return defaultAddr; } lock (_disassemlyCache) { // check the cache with the adjusted range var kv = _disassemlyCache.FirstOrDefault((p) => p.Value.TryFetch(startAddress, address < endAddress ? address : endAddress, out ret)); } if (ret == null) { DisasmInstruction[] instructions = await Disassemble(_process, startAddress, endAddress); if (instructions == null) { return defaultAddr; // unknown error condition } // when seeking back require that the disassembly contain an instruction at the target address (x86 has varying length instructions) instructions = await VerifyDisassembly(instructions, startAddress, endAddress, address); ret = UpdateCache(address, -nInstructions, instructions); if (ret == null) { return defaultAddr; } } int nLess = ret.Count((i) => i.Addr < address); if (nLess < nInstructions) { // not enough instructions were fetched; back up one byte for each missing instruction return ret.First().Addr < (ulong)(nInstructions - nLess) ? 0 : (ulong)((long)ret.First().Addr - (nInstructions - nLess)); } else { return ret.First().Addr; } } // /// <summary> /// Fetch disassembly for a range of instructions. /// </summary> /// <param name="address">Beginning address of an instruction to use as a starting point for disassembly.</param> /// <param name="nInstructions">Number of instructions to disassemble.</param> /// <returns></returns> public async Task<ICollection<DisasmInstruction>> FetchInstructions(ulong address, int nInstructions) { ICollection<DisasmInstruction> ret = null; lock (_disassemlyCache) { // check the cache var kv = _disassemlyCache.FirstOrDefault((p) => p.Value.TryFetch(address, nInstructions, out ret)); if (kv.Value != null) return ret; } ulong endAddress; ulong startAddress; var range = await _process.FindValidMemoryRange(address, (uint)(_process.MaxInstructionSize * nInstructions), 0); startAddress = range.Item1; endAddress = range.Item2; int gap = (int)(startAddress - address); // num of bytes before instructions begin if (endAddress > startAddress && nInstructions > gap) { nInstructions -= gap; } else { nInstructions = 0; } if (endAddress - startAddress == 0 || nInstructions == 0) { return null; } lock (_disassemlyCache) { // re-check the cache with the verified memory range var kv = _disassemlyCache.FirstOrDefault((p) => p.Value.TryFetch(startAddress, nInstructions, out ret)); if (kv.Value != null) return ret; } DisasmInstruction[] instructions = await Disassemble(_process, startAddress, endAddress); instructions = await VerifyDisassembly(instructions, startAddress, endAddress, address); return UpdateCache(address, nInstructions, instructions); } private async Task<DisasmInstruction[]> VerifyDisassembly(DisasmInstruction[] instructions, ulong startAddress, ulong endAddress, ulong targetAddress) { if (startAddress > targetAddress || targetAddress > endAddress) { return instructions; } var originalInstructions = instructions; int count = 0; while (instructions != null && (instructions.Length == 0 || Array.Find(instructions, (i)=>i.Addr == targetAddress) == null) && count < _process.MaxInstructionSize) { count++; startAddress--; // back up one byte instructions = await Disassemble(_process, startAddress, endAddress); // try again } return instructions == null ? originalInstructions : instructions; } private void DeleteRangeFromCache(DisassemblyBlock block) { for (int i = 0; i < _disassemlyCache.Count; ++i) { DisassemblyBlock elem = _disassemlyCache.ElementAt(i).Value; if (block.Contains(elem.Address, elem.Count)) { _disassemlyCache.RemoveAt(i); break; } } } // this is inefficient so we try and grab everything in one gulp internal static async Task<DisasmInstruction[]> Disassemble(DebuggedProcess process, ulong startAddr, ulong endAddr) { string cmd = "-data-disassemble -s " + EngineUtils.AsAddr(startAddr, process.Is64BitArch) + " -e " + EngineUtils.AsAddr(endAddr, process.Is64BitArch) + " -- 2"; Results results = await process.CmdAsync(cmd, ResultClass.None); if (results.ResultClass != ResultClass.done) { return null; } return DecodeDisassemblyInstructions(results.Find<ValueListValue>("asm_insns").AsArray<TupleValue>()); } // this is inefficient so we try and grab everything in one gulp internal async Task<IEnumerable<DisasmInstruction>> Disassemble(DebuggedProcess process, string file, uint line, uint dwInstructions) { if (file.IndexOf(' ') >= 0) // only needs escaping if filename contains a space { file = process.EnsureProperPathSeparators(file); } string cmd = "-data-disassemble -f " + file + " -l " + line.ToString(CultureInfo.InvariantCulture) + " -n " + dwInstructions.ToString(CultureInfo.InvariantCulture) + " -- 1"; Results results = await process.CmdAsync(cmd, ResultClass.None); if (results.ResultClass != ResultClass.done) { return null; } return DecodeSourceAnnotatedDisassemblyInstructions(process, results.Find<ResultListValue>("asm_insns").FindAll<TupleValue>("src_and_asm_line")); } private static DisasmInstruction[] DecodeDisassemblyInstructions(TupleValue[] items) { DisasmInstruction[] instructions = new DisasmInstruction[items.Length]; for (int i = 0; i < items.Length; i++) { DisasmInstruction inst = new DisasmInstruction(); inst.Addr = items[i].FindAddr("address"); inst.AddressString = items[i].FindString("address"); inst.Symbol = items[i].TryFindString("func-name"); inst.Offset = items[i].Contains("offset") ? items[i].FindUint("offset") : 0; inst.Opcode = items[i].FindString("inst"); inst.CodeBytes = items[i].TryFindString("opcodes"); inst.Line = 0; inst.File = null; instructions[i] = inst; } return instructions; } private static IEnumerable<DisasmInstruction> DecodeSourceAnnotatedDisassemblyInstructions(DebuggedProcess process, TupleValue[] items) { foreach (var item in items) { uint line = item.FindUint("line"); string file = process.GetMappedFileFromTuple(item); ValueListValue asm_items = item.Find<ValueListValue>("line_asm_insn"); uint lineOffset = 0; foreach (var asm_item in asm_items.Content) { DisasmInstruction disassemblyData = new DisasmInstruction(); disassemblyData.Addr = asm_item.FindAddr("address"); disassemblyData.AddressString = asm_item.FindString("address"); disassemblyData.Symbol = asm_item.TryFindString("func-name"); disassemblyData.Offset = asm_item.Contains("offset") ? asm_item.FindUint("offset") : 0; disassemblyData.Opcode = asm_item.FindString("inst"); disassemblyData.CodeBytes = asm_item.TryFindString("opcodes"); disassemblyData.Line = line; disassemblyData.File = file; if (lineOffset == 0) { lineOffset = disassemblyData.Offset; // offset to start of current line } disassemblyData.OffsetInLine = disassemblyData.Offset - lineOffset; yield return disassemblyData; } } } } } <|start_filename|>src/DebugEngineHost.VSCode/Host.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; namespace Microsoft.DebugEngineHost { /// <summary> /// Enumeration of Host User Interfaces that an engine can be run from. /// This must be kept in sync with all DebugEngineHost implementations (see _Readme.txt) /// </summary> public enum HostUIIdentifier { /// <summary> /// Visual Studio IDE /// </summary> VSIDE = 0, /// <summary> /// Visual Studio Code /// </summary> VSCode = 1, /// <summary> /// XamarinStudio /// </summary> XamarinStudio = 2 } public static class Host { public static void EnsureMainThreadInitialized() { // no initialization is required } /// <summary> /// Called by a debug engine to determine which UI is using it. /// </summary> /// <returns></returns> public static HostUIIdentifier GetHostUIIdentifier() { return HostUIIdentifier.VSCode; } } } <|start_filename|>src/Microsoft.VisualStudio.Debugger.Interop.UnixPortSupplier/Microsoft.VisualStudio.Debugger.Interop.UnixPortSupplier.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Runtime.InteropServices; using Microsoft.VisualStudio.Debugger.Interop; namespace Microsoft.VisualStudio.Debugger.Interop.UnixPortSupplier { /// <summary> /// Interface implemented by the IDebugPort2 object from the SSH port supplier or /// any other port supplier that wants to support debugging via remote command /// execution and standard I/O redirection. /// </summary> [ComImport()] [ComVisible(true)] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [Guid("5FE438B2-46BA-4637-88B3-E7B908D17331")] public interface IDebugUnixShellPort { /// <summary> /// Synchronously executes the specified shell command and returns the output and exit code /// of the command. /// </summary> /// <param name="commandDescription">Description of the command to use in a wait /// dialog if command takes a long time to execute</param> /// <param name="commandText">Command line to execute on the remote system</param> /// <param name="commandOutput">Stdout/err which the command writes</param> /// <param name="timeout">timeout before the command should be aborted</param> /// <param name="exitCode">exit code of the command</param> void ExecuteSyncCommand(string commandDescription, string commandText, out string commandOutput, int timeout, out int exitCode); /// <summary> /// Starts the execution of the specified command, using call back interfaces to /// receive its output, and using a command interface to send it input or abort /// it. /// </summary> /// <param name="commandText">Text of the command to execut</param> /// <param name="runInShell">True if the command should be executed in a shell and PTY. It is important to note that callers should pass /// True unless their callback implementation is capable of handling raw output text, as <see cref="IDebugUnixShellCommandCallback.OnOutputLine(string)"/> /// will be sent unbuffered output when this is false, so the implementation must be able to handle partial lines or multiple lines in /// one call to OnOutputLine.</param> /// <param name="callback">Callback which will receive the output and events /// from the command</param> /// <param name="asyncCommand">Returned command object</param> void BeginExecuteAsyncCommand(string commandText, bool runInShell, IDebugUnixShellCommandCallback callback, out IDebugUnixShellAsyncCommand asyncCommand); /// <summary> /// Copy a single file from the local machine to the remote machine. /// </summary> /// <param name="sourcePath">File on the local machine.</param> /// <param name="destinationPath">Destination path on the remote machine.</param> void CopyFile(string sourcePath, string destinationPath); /// <summary> /// Creates directory provided the path. Does not fail if the directory already exists. /// </summary> /// <param name="path">Path on the remote machine.</param> /// <returns>Full path of the created directory.</returns> string MakeDirectory(string path); /// <summary> /// Gets the home directory of the user. /// </summary> /// <returns>Home directory of the user.</returns> string GetUserHomeDirectory(); /// <returns>True if the remote machine is OSX.</returns> bool IsOSX(); /// <returns>True if the remote machine is Linux.</returns> bool IsLinux(); } /// <summary> /// Interface implemented by a port that supports explicit cleanup /// </summary> [ComImport()] [ComVisible(true)] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [Guid("1ECAAA80-36DB-4DA8-88B3-B298B0221BF6")] public interface IDebugPortCleanup { /// <summary> /// Clean up debugging resources /// </summary> void Clean(); } /// <summary> /// Interface implemented by an IDebugPort2 that supports using gdbserver to attach to a remote process /// </summary> [ComImport()] [ComVisible(true)] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [Guid("C517EE50-4852-4D95-916E-1A1C89710466")] public interface IDebugGdbServerAttach { /// <summary> /// Attaches gdbserver to a process. /// </summary> /// <param name="processId">Id of the process.</param> /// <param name="preAttachCommand">Command to run before starting gdbserver.</param> /// <returns>Communications addr:port</returns> string GdbServerAttachProcess(int processId, string preAttachCommand); } /// <summary> /// Interface representing an executing asynchronous command. This is returned from /// <see cref="IDebugUnixShellPort.BeginExecuteAsyncCommand(string, bool, IDebugUnixShellCommandCallback, out IDebugUnixShellAsyncCommand)"/>. /// </summary> [ComImport()] [ComVisible(true)] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [Guid("0BB77830-931D-4B54-822E-7BB56FA10049")] public interface IDebugUnixShellAsyncCommand { /// <summary> /// Writes to the standard input stream of the executing command /// </summary> /// <param name="text">Text to send to the command</param> void Write(string text); /// <summary> /// Writes to the standard input steam of the executing command, appending a newline /// </summary> /// <param name="text">Text to send to the command</param> void WriteLine(string text); /// <summary> /// Aborts the executing command /// </summary> void Abort(); } /// <summary> /// Interface to receive events from an executing async command. This is passed to /// <see cref="IDebugUnixShellPort.BeginExecuteAsyncCommand(string, bool, IDebugUnixShellCommandCallback, out IDebugUnixShellAsyncCommand)"/>. /// </summary> [ComImport()] [ComVisible(true)] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [Guid("0CE7C176-1AF3-4DBD-BA4E-1BBDB242B190")] public interface IDebugUnixShellCommandCallback { /// <summary> /// Notification fired when the command has output available /// </summary> /// <param name="line">Text that the executing command wrote to standard out or error. /// <para>If `false` is passed for `runInShell` when <see cref="IDebugUnixShellPort.BeginExecuteAsyncCommand(string, bool, IDebugUnixShellCommandCallback, out IDebugUnixShellAsyncCommand)"/> /// was called then this text will NOT be buffered, so either partial lines or multiple lines are possible, and this text will include new line /// characters. /// </para> /// <para> /// If `true` is passed for `runInShell` then this will be a single line of output with new line characters removed. /// </para> /// </param> void OnOutputLine(string line); /// <summary> /// Fired when the command finishes /// </summary> /// <param name="exitCode">The exit code of the command, assuming one was printed.</param> void OnExit(string exitCode); }; /// <summary> /// Interface to query unix process architecture information. /// </summary> [ComImport()] [ComVisible(true)] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [Guid("61D4C2C4-7CA8-4472-8446-7B1DF5C9D16D")] public interface IDebugUnixProcess { /// <summary> /// Gets the architecture unix process. /// </summary> /// <returns>The string representation of the process's architecture. The format of this is architecture-specific and will match that returned by uname -m. Example: 'x86_64'</returns> string GetProcessArchitecture(); }; } <|start_filename|>tools/iOS/DebugListenerTool/DebugListenerTool.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Sockets; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Threading; using System.Threading.Tasks; namespace ConsoleApplication9 { internal class DebugListenerTool { private const int RemotePort = 3030; private const int LldbProxyPort = 3002; private const string MachineName = "Chucks-mac-mini"; private static void Main(string[] args) { Task.Run(() => { var handler = new WebRequestHandler(); handler.ServerCertificateValidationCallback = (a, b, c, d) => { return true; }; using (var client = new TcpClient()) { client.Connect(MachineName, LldbProxyPort); Console.WriteLine("Connection made to debug proxy server."); bool bRunning = true; ManualResetEvent e = new ManualResetEvent(false); ThreadPool.QueueUserWorkItem((o) => { using (var reader = new StreamReader(client.GetStream())) { while (bRunning) { try { string line = reader.ReadLine(); if (line != null) { Console.WriteLine(line); } } catch (IOException) { } } } e.Set(); }); using (var writer = new StreamWriter(client.GetStream())) { while (bRunning) { string line = Console.ReadLine(); writer.WriteLine(line); writer.Flush(); if (string.Compare(line, "quit", StringComparison.OrdinalIgnoreCase) == 0) { bRunning = false; } } } e.WaitOne(); } }).Wait(); } } } <|start_filename|>test/CppTests/debuggees/optimization/src/foo.cpp<|end_filename|> #include "foo.h" #include <iostream> #include <string> using namespace std; Foo::Foo() { cout << "default constructor called" << endl; this->number = 10; FillContainer(); } Foo::Foo(int number) { cout << "one-argument constructor called" << endl; if (Validate(number)) { this->number = number; FillContainer(); } else { this->number = 10; FillContainer(); } } bool Foo::Validate(int number) { if (number <= 0 || number>100) { return false; } else { return true; } } void Foo::FillContainer() { for (int i = 1; i <= this->number; ++i) { m_collection.push_back(i); } } int Foo::Sum() { vector<int>::const_iterator iterBegin = m_collection.begin(); vector<int>::const_iterator iterEnd = m_collection.end(); int sum = 0; int first = m_collection[0]; cout << first << endl; while (iterBegin != iterEnd) { sum += *iterBegin; ++iterBegin; } return sum; } <|start_filename|>src/WindowsDebugLauncher/Program.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.IO.Pipes; using System.Linq; using System.Text; using System.Threading; namespace WindowsDebugLauncher { internal class Program { private static int Main(string[] argv) { DebugLauncher.LaunchParameters parameters = new DebugLauncher.LaunchParameters(); parameters.PipeServer = "."; // Currently only supporting local pipe connections // Avoid sending the BOM on Windows if the Beta Unicode feature is enabled in Windows 10 Console.OutputEncoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false); Console.InputEncoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false); foreach (var a in argv) { if (String.IsNullOrEmpty(a)) { continue; } switch (a) { case "-h": case "-?": case "/?": case "--help": HelpMessage(); return 1; case "--pauseForDebugger": { while (!Debugger.IsAttached) { Thread.Sleep(500); } } break; default: if (a.StartsWith("--stdin=", StringComparison.OrdinalIgnoreCase)) { string stdin = a.Substring("--stdin=".Length); if (string.IsNullOrWhiteSpace(stdin)) { GenerateError("--stdin"); return -1; } parameters.StdInPipeName = stdin; } else if (a.StartsWith("--stdout=", StringComparison.OrdinalIgnoreCase)) { string stdout = a.Substring("--stdout=".Length); if (string.IsNullOrWhiteSpace(stdout)) { GenerateError("--stdout"); return -1; } parameters.StdOutPipeName = stdout; } else if (a.StartsWith("--stderr=", StringComparison.OrdinalIgnoreCase)) { string stderr = a.Substring("--stderr=".Length); if (string.IsNullOrWhiteSpace(stderr)) { GenerateError("--stderr"); return -1; } parameters.StdErrPipeName = stderr; } else if (a.StartsWith("--pid=", StringComparison.OrdinalIgnoreCase)) { string pid = a.Substring("--pid=".Length); if (string.IsNullOrWhiteSpace(pid)) { GenerateError("--pid"); return -1; } parameters.PidPipeName = pid; } else if (a.StartsWith("--dbgExe=", StringComparison.OrdinalIgnoreCase)) { string dbgExe = a.Substring("--dbgExe=".Length); if (String.IsNullOrEmpty(dbgExe) || !File.Exists(dbgExe)) { GenerateError("--dbgExe"); return -1; } parameters.DbgExe = dbgExe; } else { parameters.DbgExeArgs.AddRange(ParseDebugExeArgs(a)); } break; } } if (!parameters.ValidateParameters()) { Console.Error.WriteLine("One or more required values are missing."); HelpMessage(); return -1; } DebugLauncher launcher = new DebugLauncher(parameters); launcher.StartPipeConnection(); return 0; } private static void GenerateError(string flag) { Console.Error.WriteLine(FormattableString.Invariant($"Value for flag:'{flag}' is missing or incorrect.")); HelpMessage(); } /// <summary> /// Parse dbgargs for spaces and quoted strings /// </summary> private static List<string> ParseDebugExeArgs(string line) { List<string> args = new List<string>(); bool inQuotedString = false; bool isEscape = false; StringBuilder builder = new StringBuilder(); foreach (char c in line) { if (isEscape) { switch (c) { case 'n': builder.Append('\n'); break; case 'r': builder.Append('\r'); break; case '\\': builder.Append('\\'); break; case '"': builder.Append('\"'); break; case ' ': builder.Append(' '); break; default: throw new ArgumentException(FormattableString.Invariant($"Invalid escape sequence: \\{c}")); } isEscape = false; continue; } if (c == '\\') { isEscape = true; continue; } if (!inQuotedString && c == '"') { inQuotedString = true; continue; } if (inQuotedString && c == '"') { inQuotedString = false; continue; } if (!inQuotedString && c == ' ') { if (builder.Length > 0) { args.Add(builder.ToString()); builder.Clear(); } continue; } builder.Append(c); } if (builder.Length > 0) { args.Add(builder.ToString()); } return args; } private static void HelpMessage() { Console.WriteLine("WindowsDebugLauncher: Launching debuggers for use with MIEngine in a separate process."); Console.WriteLine("--stdin=<value> '<value>' is NamedPipeName for debugger stdin"); Console.WriteLine("--stdout=<value> '<value>' is NamedPipeName for debugger stdout"); Console.WriteLine("--stderr=<value> '<value>' is NamedPipeName for debugger stderr"); Console.WriteLine("--pid=<value> '<value>' is NamedPipeName for debugger pid"); Console.WriteLine("--dbgExe=<value> '<value>' is the path to the debugger"); } } } <|start_filename|>src/MIDebugEngine/AD7.Impl/AD7MemoryAddress.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using Microsoft.VisualStudio.Debugger.Interop; using MICore; namespace Microsoft.MIDebugEngine { // And implementation of IDebugCodeContext2 and IDebugMemoryContext2. // IDebugMemoryContext2 represents a position in the address space of the machine running the program being debugged. // IDebugCodeContext2 represents the starting position of a code instruction. // For most run-time architectures today, a code context can be thought of as an address in a program's execution stream. internal sealed class AD7MemoryAddress : IDebugCodeContext2 { private readonly AD7Engine _engine; private readonly ulong _address; /*OPTIONAL*/ private string _functionName; private IDebugDocumentContext2 _documentContext; public AD7MemoryAddress(AD7Engine engine, ulong address, /*OPTIONAL*/ string functionName) { _engine = engine; _address = address; _functionName = functionName; } internal ulong Address { get { return _address; } } internal AD7Engine Engine { get { return _engine; } } public void SetDocumentContext(IDebugDocumentContext2 docContext) { _documentContext = docContext; } #region IDebugMemoryContext2 Members // Adds a specified value to the current context's address to create a new context. public int Add(ulong dwCount, out IDebugMemoryContext2 newAddress) { // NB: this is not correct for IDebugCodeContext2 according to the docs // https://docs.microsoft.com/en-us/visualstudio/extensibility/debugger/reference/idebugcodecontext2#remarks // But it's not used in practice (instead: IDebugDisassemblyStream2.Seek) newAddress = new AD7MemoryAddress(_engine, (uint)dwCount + _address, null); return Constants.S_OK; } // Compares the memory context to each context in the given array in the manner indicated by compare flags, // returning an index of the first context that matches. public int Compare(enum_CONTEXT_COMPARE contextCompare, IDebugMemoryContext2[] compareToItems, uint compareToLength, out uint foundIndex) { foundIndex = uint.MaxValue; try { for (uint c = 0; c < compareToLength; c++) { AD7MemoryAddress compareTo = compareToItems[c] as AD7MemoryAddress; if (compareTo == null) { continue; } if (!AD7Engine.ReferenceEquals(_engine, compareTo._engine)) { continue; } bool result; switch (contextCompare) { case enum_CONTEXT_COMPARE.CONTEXT_EQUAL: result = (_address == compareTo._address); break; case enum_CONTEXT_COMPARE.CONTEXT_LESS_THAN: result = (_address < compareTo._address); break; case enum_CONTEXT_COMPARE.CONTEXT_GREATER_THAN: result = (_address > compareTo._address); break; case enum_CONTEXT_COMPARE.CONTEXT_LESS_THAN_OR_EQUAL: result = (_address <= compareTo._address); break; case enum_CONTEXT_COMPARE.CONTEXT_GREATER_THAN_OR_EQUAL: result = (_address >= compareTo._address); break; // The debug engine doesn't understand scopes case enum_CONTEXT_COMPARE.CONTEXT_SAME_SCOPE: result = (_address == compareTo._address); break; case enum_CONTEXT_COMPARE.CONTEXT_SAME_FUNCTION: if (_address == compareTo._address) { result = true; break; } string funcThis = Engine.GetAddressDescription(_address); if (string.IsNullOrEmpty(funcThis)) { result = false; break; } string funcCompareTo = Engine.GetAddressDescription(compareTo._address); result = (funcThis == funcCompareTo); break; case enum_CONTEXT_COMPARE.CONTEXT_SAME_MODULE: result = (_address == compareTo._address); if (result == false) { DebuggedModule module = _engine.DebuggedProcess.ResolveAddress(_address); if (module != null) { result = module.AddressInModule(compareTo._address); } } break; case enum_CONTEXT_COMPARE.CONTEXT_SAME_PROCESS: result = true; break; default: // A new comparison was invented that we don't support return Constants.E_NOTIMPL; } if (result) { foundIndex = c; return Constants.S_OK; } } return Constants.S_FALSE; } catch (MIException e) { return e.HResult; } catch (Exception e) { return EngineUtils.UnexpectedException(e); } } // Gets information that describes this context. public int GetInfo(enum_CONTEXT_INFO_FIELDS dwFields, CONTEXT_INFO[] pinfo) { try { pinfo[0].dwFields = 0; if ((dwFields & (enum_CONTEXT_INFO_FIELDS.CIF_ADDRESS | enum_CONTEXT_INFO_FIELDS.CIF_ADDRESSABSOLUTE)) != 0) { string addr = EngineUtils.AsAddr(_address, _engine.DebuggedProcess.Is64BitArch); if ((dwFields & enum_CONTEXT_INFO_FIELDS.CIF_ADDRESS) != 0) { pinfo[0].bstrAddress = addr; pinfo[0].dwFields |= enum_CONTEXT_INFO_FIELDS.CIF_ADDRESS; } if ((dwFields & enum_CONTEXT_INFO_FIELDS.CIF_ADDRESSABSOLUTE) != 0) { pinfo[0].bstrAddressAbsolute = addr; pinfo[0].dwFields |= enum_CONTEXT_INFO_FIELDS.CIF_ADDRESSABSOLUTE; } } // Fields not supported by the sample if ((dwFields & enum_CONTEXT_INFO_FIELDS.CIF_ADDRESSOFFSET) != 0) { } if ((dwFields & enum_CONTEXT_INFO_FIELDS.CIF_MODULEURL) != 0) { DebuggedModule module = _engine.DebuggedProcess.ResolveAddress(_address); if (module != null) { pinfo[0].bstrModuleUrl = module.Name; pinfo[0].dwFields |= enum_CONTEXT_INFO_FIELDS.CIF_MODULEURL; } } if ((dwFields & enum_CONTEXT_INFO_FIELDS.CIF_FUNCTION) != 0) { if (string.IsNullOrEmpty(_functionName)) { _functionName = Engine.GetAddressDescription(_address); } if (!(string.IsNullOrEmpty(_functionName))) { pinfo[0].bstrFunction = _functionName; pinfo[0].dwFields |= enum_CONTEXT_INFO_FIELDS.CIF_FUNCTION; } } return Constants.S_OK; } catch (MIException e) { return e.HResult; } catch (Exception e) { return EngineUtils.UnexpectedException(e); } } // Gets the user-displayable name for this context public int GetName(out string pbstrName) { pbstrName = _functionName ?? Engine.GetAddressDescription(_address); return Constants.S_OK; } // Subtracts a specified value from the current context's address to create a new context. public int Subtract(ulong dwCount, out IDebugMemoryContext2 ppMemCxt) { ppMemCxt = new AD7MemoryAddress(_engine, _address - (uint)dwCount, null); return Constants.S_OK; } #endregion #region IDebugCodeContext2 Members // Gets the document context for this code-context. If no document context is available, return S_FALSE. public int GetDocumentContext(out IDebugDocumentContext2 ppSrcCxt) { int hr = Constants.S_OK; if (_documentContext == null) hr = Constants.S_FALSE; ppSrcCxt = _documentContext; return hr; } // Gets the language information for this code context. public int GetLanguageInfo(ref string pbstrLanguage, ref Guid pguidLanguage) { if (_documentContext != null) { return _documentContext.GetLanguageInfo(ref pbstrLanguage, ref pguidLanguage); } else { return Constants.S_FALSE; } } #endregion } } <|start_filename|>src/OpenDebugAD7/Constants.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace OpenDebugAD7 { internal static class HRConstants { public const int S_OK = 0; public const int S_FALSE = 1; public const int E_FAIL = unchecked((int)0x80004005); public const int E_INVALIDARG = unchecked((int)0x80070057); public const int E_NOTIMPL = unchecked((int)0x80004001); public const int E_ABORT = unchecked((int)(0x80004004)); public const int COMQC_E_BAD_MESSAGE = unchecked((int)0x80110604); public const int RPC_E_SERVERFAULT = unchecked((int)0x80010105); public const int RPC_E_DISCONNECTED = unchecked((int)0x80010108); public const int E_ACCESSDENIED = unchecked((int)0x80070005); public const int E_CRASHDUMP_UNSUPPORTED = unchecked((int)0x80040211); } internal static class Constants { // POST_PREVIEW_TODO: no-func-eval support, radix, timeout public const uint EvaluationRadix = 10; public const uint ParseRadix = 10; public const uint EvaluationTimeout = 5000; public const int DisconnectTimeout = 2000; public const int DefaultTracepointCallstackDepth = 10; public const int InvalidProcessId = -1; } } <|start_filename|>src/JDbg/JdwpCommand.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace JDbg { /// <summary> /// This is the base clas for all Jdwp Commands. Commands that have payloads should override /// GetPayloadBytes. Commands that expect payloads in succesful replies should override DecodeSuccessReply. /// Commands that expect payloads in error replies should override DecodeErrorReply. /// </summary> public class JdwpCommand { //This class represents a two byte tuple made up of the Command Set ID and the Command ID protected class CommandId : Tuple<byte, byte> { public byte CommandSet { get { return this.Item1; } } public byte Command { get { return this.Item2; } } public CommandId(byte commandSet, byte command) : base(commandSet, command) { } } public struct IDSizes { public IDSizes(int fieldIDSize, int methodIDSize, int objectIDSize, int referenceTypeIDSize, int frameIDSize) { _fieldIDSize = fieldIDSize; _methodIDSize = methodIDSize; _objectIDSize = objectIDSize; _referenceTypeIDSize = referenceTypeIDSize; _frameIDSize = frameIDSize; } private int _fieldIDSize; public int FieldIDSize { get { if (_fieldIDSize == 0) { throw new JdwpException(ErrorCode.FailedToInitialize, "IDSizes was not intialized!"); } return _fieldIDSize; } } private int _methodIDSize; public int MethodIDSize { get { if (_methodIDSize == 0) { throw new JdwpException(ErrorCode.FailedToInitialize, "IDSizes was not intialized!"); } return _methodIDSize; } } private int _objectIDSize; public int ObjectIDSize { get { if (_objectIDSize == 0) { throw new JdwpException(ErrorCode.FailedToInitialize, "IDSizes was not intialized!"); } return _objectIDSize; } } private int _referenceTypeIDSize; public int ReferenceTypeIDSize { get { if (_referenceTypeIDSize == 0) { throw new JdwpException(ErrorCode.FailedToInitialize, "IDSizes was not intialized!"); } return _referenceTypeIDSize; } } private int _frameIDSize; public int FrameIDSize { get { if (_frameIDSize == 0) { throw new JdwpException(ErrorCode.FailedToInitialize, "IDSizes was not intialized!"); } return _frameIDSize; } } } /// <summary> /// Class to hold command id tuples for the VirtualMachine command set (1). /// See http://docs.oracle.com/javase/7/docs/technotes/guides/jpda/jdwp-spec.html for more info. /// </summary> protected class VirtualMachineCommandSet : CommandId { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] public static readonly VirtualMachineCommandSet Version = new VirtualMachineCommandSet(1); [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] public static readonly VirtualMachineCommandSet ClassesBySignature = new VirtualMachineCommandSet(2); [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] public static readonly VirtualMachineCommandSet AllClasses = new VirtualMachineCommandSet(3); [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] public static readonly VirtualMachineCommandSet AllThreads = new VirtualMachineCommandSet(4); [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] public static readonly VirtualMachineCommandSet TopLevelThreadGroups = new VirtualMachineCommandSet(5); [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] public static readonly VirtualMachineCommandSet Dispose = new VirtualMachineCommandSet(6); [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] public static readonly VirtualMachineCommandSet IDSizes = new VirtualMachineCommandSet(7); [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] public static readonly VirtualMachineCommandSet Suspend = new VirtualMachineCommandSet(8); [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] public static readonly VirtualMachineCommandSet Resume = new VirtualMachineCommandSet(9); [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] public static readonly VirtualMachineCommandSet Exit = new VirtualMachineCommandSet(10); [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] public static readonly VirtualMachineCommandSet CreateString = new VirtualMachineCommandSet(11); [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] public static readonly VirtualMachineCommandSet Capabilities = new VirtualMachineCommandSet(12); [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] public static readonly VirtualMachineCommandSet ClassPaths = new VirtualMachineCommandSet(13); [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] public static readonly VirtualMachineCommandSet DisposeObjects = new VirtualMachineCommandSet(14); [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] public static readonly VirtualMachineCommandSet HoldEvents = new VirtualMachineCommandSet(15); [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] public static readonly VirtualMachineCommandSet ReleaseEvents = new VirtualMachineCommandSet(16); [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] public static readonly VirtualMachineCommandSet CapabilitiesNew = new VirtualMachineCommandSet(17); [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] public static readonly VirtualMachineCommandSet RedefineClasses = new VirtualMachineCommandSet(18); [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] public static readonly VirtualMachineCommandSet SetDefaultStratum = new VirtualMachineCommandSet(19); [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] public static readonly VirtualMachineCommandSet AllClassesWithGeneric = new VirtualMachineCommandSet(20); [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] public static readonly VirtualMachineCommandSet InstanceCounts = new VirtualMachineCommandSet(21); public VirtualMachineCommandSet(byte command) : base(1, command) { } } protected class EventRequestCommandSet : CommandId { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] public static readonly EventRequestCommandSet Set = new EventRequestCommandSet(1); [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] public static readonly EventRequestCommandSet Clear = new EventRequestCommandSet(2); [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] public static readonly EventRequestCommandSet ClearAllBreakpoints = new EventRequestCommandSet(3); public EventRequestCommandSet(byte command) : base(15, command) { } } public const uint HEADER_SIZE = 11; private static uint s_nextPacketId = 0; private CommandId _commandId; public uint PacketId { get; private set; } protected JdwpCommand(CommandId commandId) { _commandId = commandId; this.PacketId = ++s_nextPacketId; } //overridden by commands that have paylaods protected virtual byte[] GetPayloadBytes() { return new byte[0]; } //overriden by commands that need to decode reply payloads internal virtual void DecodeSuccessReply(ReplyPacketParser bytes) { } internal virtual void DecodeFailureReply(ReplyPacketParser bytes) { } public byte[] GetPacketBytes() { byte[] payloadBytes = GetPayloadBytes(); if (payloadBytes == null) { payloadBytes = new byte[0]; } uint packetSize = HEADER_SIZE + (uint)payloadBytes.Length; byte[] packetBytes = new byte[packetSize]; //bytes 0-3 are the length, big-endian byte[] lenghtBytes = Utils.BigEndianBytesFromUInt32(packetSize); Array.Copy(lenghtBytes, 0, packetBytes, 0, 4); //bytes 4-7 are the command ID, big-endian byte[] idBytes = Utils.BigEndianBytesFromUInt32(PacketId); Array.Copy(idBytes, 0, packetBytes, 4, 4); //byte 8 is flags, always zero for command packets packetBytes[8] = 0; //byte 9 is the command set packetBytes[9] = _commandId.CommandSet; //byte 10 is the command packetBytes[10] = _commandId.Command; //remainder of packet is the payload bytes Array.Copy(payloadBytes, 0, packetBytes, HEADER_SIZE, payloadBytes.Length); return packetBytes; } } /// <summary> /// Version Command. Retreives the version of the JVM. No command payload. Reply payload is described by VersionCommand.Reply. /// </summary> public class VersionCommand : JdwpCommand { public struct Reply { public string description; public int jdwpMajor; public int jdwpMinor; public string vmVersion; public string vmName; } private Reply _reply; public VersionCommand() : base(VirtualMachineCommandSet.Version) { } internal override void DecodeSuccessReply(ReplyPacketParser reply) { _reply = new Reply(); _reply.description = reply.ReadString(); _reply.jdwpMajor = (int)reply.ReadUInt32(); _reply.jdwpMinor = (int)reply.ReadUInt32(); _reply.vmVersion = reply.ReadString(); _reply.vmName = reply.ReadString(); } public Reply GetReply() { return _reply; } } /// <summary> /// Retrieves the sizes of ID's from the JVM /// </summary> public class IDSizesCommand : JdwpCommand { private IDSizes _reply; public IDSizesCommand() : base(VirtualMachineCommandSet.IDSizes) { } internal override void DecodeSuccessReply(ReplyPacketParser bytes) { int fieldIDSize = (int)bytes.ReadUInt32(); int methodIDSize = (int)bytes.ReadUInt32(); int objectIDsize = (int)bytes.ReadUInt32(); int referenceTypeIDSize = (int)bytes.ReadUInt32(); int frameIDSize = (int)bytes.ReadUInt32(); _reply = new IDSizes(fieldIDSize, methodIDSize, objectIDsize, referenceTypeIDSize, frameIDSize); } public IDSizes GetReply() { return _reply; } } /// <summary> /// Retrieves all class names (with generics) from the JVM /// </summary> public class AllClassesWithGenericCommand : JdwpCommand { public struct ClassData { public byte refTypeFlag; public ulong typeID; public string signature; public string genericSignature; public int status; } public AllClassesWithGenericCommand() : base(VirtualMachineCommandSet.AllClassesWithGeneric) { } private List<ClassData> _classData; public List<ClassData> GetClassData() { return _classData; } internal override void DecodeSuccessReply(ReplyPacketParser bytes) { int countClasses = (int)bytes.ReadUInt32(); _classData = new List<ClassData>(); for (int i = 0; i < countClasses; i++) { ClassData classData = new ClassData(); classData.refTypeFlag = bytes.ReadByte(); classData.typeID = bytes.ReadReferenceTypeID(); classData.signature = bytes.ReadString(); classData.genericSignature = bytes.ReadString(); classData.status = (int)bytes.ReadUInt32(); _classData.Add(classData); } } } /// <summary> /// Dispose Command. Closes the communication with the current JVM, equivalent of detach. No command payload or reply payload. /// </summary> public class DisposeCommand : JdwpCommand { public DisposeCommand() : base(VirtualMachineCommandSet.Dispose) { } } /// <summary> /// Resume Command. Resumes the JVM after it has been suspended or stopped due to an event. No command payload and no reply payload. /// </summary> public class ResumeCommand : JdwpCommand { public ResumeCommand() : base(VirtualMachineCommandSet.Resume) { } } } <|start_filename|>test/DebuggerTesting/Attribution/DebuggerAttribute.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; namespace DebuggerTesting { public abstract class DebuggerAttribute : Attribute { #region Constructor public DebuggerAttribute(SupportedDebugger debugger, SupportedArchitecture architecture) { this.Debugger = debugger; this.Architecture = architecture; } #endregion #region Properties public SupportedDebugger Debugger { get; private set; } public SupportedArchitecture Architecture { get; private set; } #endregion } } <|start_filename|>test/CppTests/debuggees/kitchensink/src/main.h<|end_filename|> #pragma once #include "global.h" #include <iostream> #include <vector> <|start_filename|>test/CppTests/debuggees/sharedlib/src/mylib.h<|end_filename|> #pragma once #include <string> #include "mylib_base.h" using namespace std; class myClass :public myBase { public: int DisplayAge(int age); string DisplayName(string firstName, string lastName); }; <|start_filename|>test/DebuggerTesting/OpenDebug/Extensions/DebuggeeExtensions.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using DebuggerTesting.Compilation; using DebuggerTesting.OpenDebug.Commands; namespace DebuggerTesting.OpenDebug.Extensions { public static class DebuggeeExtensions { /// <summary> /// Creates a SourceBreakpoints object that can be used to keep /// track of all the breakpoints in a file. /// </summary> public static SourceBreakpoints Breakpoints(this IDebuggee debuggee, string sourceRelativePath, params int[] lineNumbers) { SourceBreakpoints breakpoints = new SourceBreakpoints(debuggee, sourceRelativePath); foreach (int lineNumber in lineNumbers) breakpoints.Add(lineNumber); return breakpoints; } } } <|start_filename|>src/SSHDebugPS/WSL/WSLPort.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.SSHDebugPS.WSL { internal class WSLPort : AD7Port { public WSLPort(AD7PortSupplier portSupplier, string name, bool isInAddPort) : base(portSupplier, name, isInAddPort) { } protected override Connection GetConnectionInternal() { return new WSLConnection(Name); } } } <|start_filename|>test/Android/Stepping/Stepping/Stepping.NativeActivity/Header2.h<|end_filename|> #pragma once void func3(); void func4(); <|start_filename|>test/CppTests/Tests/SampleTests.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.IO; using System.Linq; using DebuggerTesting; using DebuggerTesting.Compilation; using DebuggerTesting.OpenDebug; using DebuggerTesting.OpenDebug.CrossPlatCpp; using DebuggerTesting.OpenDebug.Events; using DebuggerTesting.OpenDebug.Extensions; using DebuggerTesting.Ordering; using DebuggerTesting.Settings; using DebuggerTesting.Utilities; using Xunit; using Xunit.Abstractions; namespace CppTests.Tests { [TestCaseOrderer(DependencyTestOrderer.TypeName, DependencyTestOrderer.AssemblyName)] public class SampleTests : TestBase { #region Constructor public SampleTests(ITestOutputHelper outputHelper) : base(outputHelper) { } #endregion #region Methods [Fact] public void ValidateSettings() { this.WriteLine(PathSettings.GetDebugPathString()); AssertDirectoryExists(PathSettings.TempPath); AssertDirectoryExists(PathSettings.DebugAdaptersPath); AssertDirectoryExists(PathSettings.TestsPath); AssertDirectoryExists(PathSettings.DebuggeesPath); AssertFileExists(PathSettings.TestConfigurationFilePath); } private static void AssertDirectoryExists(string path) { Assert.True(Directory.Exists(path), "Directory '{0}' does not exist.".FormatInvariantWithArgs(path)); } private static void AssertFileExists(string path) { Assert.True(File.Exists(path), "File '{0}' does not exist.".FormatInvariantWithArgs(path)); } [Theory] [RequiresTestSettings] public void LaunchNonExistentDebuggee(ITestSettings settings) { this.TestPurpose("This test checks to see the debugger handles trying to start when there is no debuggee."); this.WriteSettings(settings); using (IDebuggerRunner runner = CreateDebugAdapterRunner(settings)) { LaunchCommand launch = new LaunchCommand(settings.DebuggerSettings, "foofoo"); launch.ExpectsSuccess = false; runner.RunCommand(launch); Assert.Matches(".*does not exist.*", launch.Message); runner.DisconnectAndVerify(); } } private const string HelloName = "hello"; private const string HelloSourceName = "hello.cpp"; private const string HexNumberPattern = @"0x[0-9A-Fa-f]+"; [Theory] [RequiresTestSettings] public void CompileHelloDebuggee(ITestSettings settings) { this.TestPurpose("Create and compile the 'hello' debuggee"); this.WriteSettings(settings); IDebuggee debuggee = Debuggee.Create(this, settings.CompilerSettings, HelloName, DebuggeeMonikers.HelloWorld.Sample); debuggee.AddSourceFiles(HelloSourceName); debuggee.Compile(); } [Theory] [DependsOnTest(nameof(CompileHelloDebuggee))] [RequiresTestSettings] [UnsupportedDebugger(SupportedDebugger.Lldb, SupportedArchitecture.x64 | SupportedArchitecture.x86)] public void TestArguments(ITestSettings settings) { this.TestPurpose("This test checks to see if arguments are passed to the debugee."); this.WriteSettings(settings); IDebuggee debuggee = Debuggee.Open(this, settings.CompilerSettings, HelloName, DebuggeeMonikers.HelloWorld.Sample); this.Comment("Run the debuggee, check argument count"); using (IDebuggerRunner runner = CreateDebugAdapterRunner(settings)) { runner.Launch(settings.DebuggerSettings, debuggee, "Param 1", "Param 2"); int args = 2; runner.Expects.ExitedEvent(exitCode: args).TerminatedEvent().AfterConfigurationDone(); runner.DisconnectAndVerify(); } } [Theory] [DependsOnTest(nameof(CompileHelloDebuggee))] [RequiresTestSettings] public void TestFolderol(ITestSettings settings) { this.TestPurpose("This test checks a bunch of commands and events."); this.WriteSettings(settings); IDebuggee debuggee = Debuggee.Open(this, settings.CompilerSettings, HelloName, DebuggeeMonikers.HelloWorld.Sample); using (IDebuggerRunner runner = CreateDebugAdapterRunner(settings)) { this.Comment("Launch the debuggee"); runner.Launch(settings.DebuggerSettings, debuggee); StoppedEvent stopAtBreak = new StoppedEvent(StoppedReason.Breakpoint); // VsDbg does not fire Breakpoint Change events when breakpoints are set. // Instead it sends a new breakpoint event when it is bound (after configuration done). bool bindsLate = (settings.DebuggerSettings.DebuggerType == SupportedDebugger.VsDbg); this.Comment("Set a breakpoint on line 8, but expect it to resolve to line 9."); runner.Expects.ConditionalEvent(!bindsLate, x => x.BreakpointChangedEvent(BreakpointReason.Changed, 9)) .AfterSetBreakpoints(debuggee.Breakpoints(HelloSourceName, 8)); this.Comment("Start debuggging until breakpoint is hit."); runner.Expects.ConditionalEvent(bindsLate, x => x.BreakpointChangedEvent(BreakpointReason.Changed, 9)) .Event(stopAtBreak) .AfterConfigurationDone(); Assert.Equal(HelloSourceName, stopAtBreak.ActualEventInfo.Filename); Assert.Equal(9, stopAtBreak.ActualEventInfo.Line); Assert.Equal(StoppedReason.Breakpoint, stopAtBreak.ActualEventInfo.Reason); this.Comment("Step forward twice until we have initialized variables"); runner.Expects.StoppedEvent(StoppedReason.Step, HelloSourceName, 10) .AfterStepOver(); runner.Expects.StoppedEvent(StoppedReason.Step, HelloSourceName, 11) .AfterStepIn(); this.Comment("Inspect the stack and try evaluation."); using (IThreadInspector inspector = runner.GetThreadInspector()) { this.Comment("Get the stack trace"); IFrameInspector mainFrame = inspector.Stack.First(); inspector.AssertStackFrameNames(true, "main.*"); this.WriteLine("Main frame: {0}", mainFrame); this.Comment("Get variables"); Assert.Subset(new HashSet<string>() { "x", "y", "argc", "argv" }, mainFrame.Variables.ToKeySet()); mainFrame.AssertVariables( "x", "6", "argc", "1"); IVariableInspector argv = mainFrame.Variables["argv"]; Assert.Matches(HexNumberPattern, argv.Value); this.Comment("Expand a variable (argv has *argv under it)"); string variableName = "*argv"; if (settings.DebuggerSettings.DebuggerType == SupportedDebugger.VsDbg) { variableName = String.Empty; } Assert.Contains(variableName, argv.Variables.Keys); Assert.Matches(HexNumberPattern, argv.Variables[variableName].Value); this.Comment("Evaluate with side effect"); string result = mainFrame.Evaluate("x = x + 1"); Assert.Equal("7", result); } this.Comment("Step to force stack info to refresh"); runner.Expects.StoppedEvent(StoppedReason.Step).AfterStepOver(); using (IThreadInspector inspector = runner.GetThreadInspector()) { this.Comment("Evaluation has side effect, make sure it propagates"); Assert.Equal("7", inspector.Stack.First().Variables["x"].Value); } runner.Expects.ExitedEvent(0).TerminatedEvent().AfterContinue(); runner.DisconnectAndVerify(); } } #endregion } } <|start_filename|>src/MIDebugPackage/PkgCmdID.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // MUST match PkgCmdID.h using System; namespace Microsoft.MIDebugPackage { internal static class PkgCmdIDList { public const uint cmdidLaunchMIDebug = 0x100; public const uint cmdidMIDebugExec = 0x101; public const uint cmdidMIDebugLog = 0x102; }; } <|start_filename|>src/AndroidDebugLauncher/AndroidLaunchOptions.cs<|end_filename|> // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using MICore; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml; using System.Globalization; namespace AndroidDebugLauncher { internal class AndroidLaunchOptions { public AndroidLaunchOptions(MICore.Xml.LaunchOptions.AndroidLaunchOptions xmlOptions, TargetEngine targetEngine) { if (xmlOptions == null) { throw new ArgumentNullException(nameof(xmlOptions)); } this.Package = LaunchOptions.RequireAttribute(xmlOptions.Package, "Package"); this.IsAttach = xmlOptions.Attach; if (!IsAttach) { // LaunchActivity is only required when we're launching this.LaunchActivity = LaunchOptions.RequireAttribute(xmlOptions.LaunchActivity, "LaunchActivity"); } this.SDKRoot = GetOptionalDirectoryAttribute(xmlOptions.SDKRoot, "SDKRoot"); this.NDKRoot = GetOptionalDirectoryAttribute(xmlOptions.NDKRoot, "NDKRoot"); this.TargetArchitecture = LaunchOptions.ConvertTargetArchitectureAttribute(xmlOptions.TargetArchitecture); if (targetEngine == TargetEngine.Native) this.IntermediateDirectory = RequireValidDirectoryAttribute(xmlOptions.IntermediateDirectory, "IntermediateDirectory"); else this.IntermediateDirectory = GetOptionalDirectoryAttribute(xmlOptions.IntermediateDirectory, "IntermediateDirectory"); if (targetEngine == TargetEngine.Java) { this.JVMHost = LaunchOptions.RequireAttribute(xmlOptions.JVMHost, "JVMHost"); this.JVMPort = xmlOptions.JVMPort; this.SourceRoots = GetSourceRoots(xmlOptions.SourceRoots); foreach (SourceRoot root in this.SourceRoots) { EnsureValidDirectory(root.Path, "SourceRoots"); } } this.AdditionalSOLibSearchPath = xmlOptions.AdditionalSOLibSearchPath; this.AbsolutePrefixSOLibSearchPath = xmlOptions.AbsolutePrefixSOLibSearchPath ?? "\"\""; this.DeviceId = LaunchOptions.RequireAttribute(xmlOptions.DeviceId, "DeviceId"); this.LogcatServiceId = GetLogcatServiceIdAttribute(xmlOptions.LogcatServiceId); this.WaitDynamicLibLoad = xmlOptions.WaitDynamicLibLoad; CheckTargetArchitectureSupported(); } public static SourceRoot[] GetSourceRoots(string pathList) { List<SourceRoot> sourceRoots = new List<MICore.SourceRoot>(); if (!string.IsNullOrWhiteSpace(pathList)) { string format = "{0}**"; string wildcardEnding = string.Format(CultureInfo.InvariantCulture, format, Path.DirectorySeparatorChar); string altWildcardEnding = string.Format(CultureInfo.InvariantCulture, format, Path.AltDirectorySeparatorChar); foreach (string path in pathList.Split(new char[] { ';' })) { string trimmedPath = path.Trim(); if (trimmedPath.EndsWith(wildcardEnding, StringComparison.OrdinalIgnoreCase) || trimmedPath.EndsWith(altWildcardEnding, StringComparison.OrdinalIgnoreCase)) { string rootedPath = trimmedPath.Substring(0, trimmedPath.Length - 2); sourceRoots.Add(new MICore.SourceRoot(rootedPath, true)); } else { sourceRoots.Add(new MICore.SourceRoot(trimmedPath, false)); } } } return sourceRoots.ToArray(); } private string GetOptionalDirectoryAttribute(string value, string attributeName) { if (value == null) return null; EnsureValidDirectory(value, attributeName); return value; } private string RequireValidDirectoryAttribute(string value, string attributeName) { LaunchOptions.RequireAttribute(value, attributeName); EnsureValidDirectory(value, attributeName); return value; } private void EnsureValidDirectory(string value, string attributeName) { if (value.IndexOfAny(Path.GetInvalidPathChars()) >= 0 || !Path.IsPathRooted(value) || !Directory.Exists(value)) { throw new LauncherException(Telemetry.LaunchFailureCode.NoReport, string.Format(CultureInfo.CurrentCulture, LauncherResources.Error_InvalidDirectoryAttribute, attributeName, value)); } } private Guid GetLogcatServiceIdAttribute(string attributeValue) { const string attributeName = "LogcatServiceId"; if (!string.IsNullOrEmpty(attributeValue)) { Guid value; if (!Guid.TryParse(attributeValue, out value)) { throw new LauncherException(Telemetry.LaunchFailureCode.NoReport, string.Format(CultureInfo.CurrentCulture, LauncherResources.Error_InvalidAttribute, attributeName)); } return value; } else { return Guid.Empty; } } /// <summary> /// [Required] Package name to spawn /// </summary> public string Package { get; private set; } /// <summary> /// [Otprional] Activity name to spawn /// /// This is required for a launch /// This is not required for an attach /// </summary> public string LaunchActivity { get; private set; } /// <summary> /// [Optional] Root of the Android SDK /// </summary> public string SDKRoot { get; private set; } /// <summary> /// [Optional] Root of the Android NDK /// </summary> public string NDKRoot { get; private set; } /// <summary> /// [Required] Target architecture of the application /// </summary> public TargetArchitecture TargetArchitecture { get; private set; } private void CheckTargetArchitectureSupported() { switch (this.TargetArchitecture) { case MICore.TargetArchitecture.X86: case MICore.TargetArchitecture.X64: case MICore.TargetArchitecture.ARM: case MICore.TargetArchitecture.ARM64: return; default: throw new LauncherException(Telemetry.LaunchFailureCode.NoReport, string.Format(CultureInfo.CurrentCulture, LauncherResources.UnsupportedTargetArchitecture, this.TargetArchitecture)); } } /// <summary> /// [Required] Directory where files from the device/emulator will be downloaded to. /// </summary> public string IntermediateDirectory { get; private set; } /// <summary> /// [Optional] Absolute prefix for directories to search for shared library symbols /// </summary> public string AbsolutePrefixSOLibSearchPath { get; private set; } /// <summary> /// [Optional] Additional directories to add to the search path /// </summary> public string AdditionalSOLibSearchPath { get; private set; } /// <summary> /// [Required] ADB device ID of the device/emulator to target /// </summary> public string DeviceId { get; private set; } /// <summary> /// [Optional] The VS Service id of the logcat service used by the launching project system /// </summary> public Guid LogcatServiceId { get; private set; } /// <summary> /// [Optional] Set to true if we are performing an attach instead of a launch. Default is false. /// </summary> public bool IsAttach { get; private set; } /// <summary> /// [Optional] If true, wait for dynamic library load to finish. /// </summary> public bool WaitDynamicLibLoad { get; private set; } public string JVMHost { get; private set; } public int JVMPort { get; private set; } public SourceRoot[] SourceRoots { get; private set; } } }
lygstate/MIEngine
<|start_filename|>common/src/main/java/org/rembx/jeeshop/mail/Mailer.java<|end_filename|> package org.rembx.jeeshop.mail; import org.apache.commons.lang.StringUtils; import org.rembx.jeeshop.configuration.NamedConfiguration; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; import javax.mail.*; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; import java.util.Date; import java.util.Properties; /** */ @ApplicationScoped public class Mailer { @Inject @NamedConfiguration("mail.smtp.host") private String host; @Inject @NamedConfiguration("mail.smtp.port") private String port; @Inject @NamedConfiguration("mail.auth.user") private String user; @Inject @NamedConfiguration("mail.auth.password") private String password; @Inject @NamedConfiguration("mail.from") private String sender; @Inject @NamedConfiguration("mail.smtp.timeout") private String readTimeout; @Inject @NamedConfiguration("mail.smtp.connectiontimeout") private String connectTimeout; @Inject @NamedConfiguration("debug") private String debug; public void sendMail(String subject, String to, String content) throws MessagingException { Properties props = new Properties(); props.put("mail.smtp.host", host); props.put("mail.smtp.port", port); props.put("mail.smtp.socketFactory.port", port); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.put("mail.smtp.connectiontimeout",connectTimeout); props.put("mail.smtp.timeout",readTimeout); Authenticator authenticator = null; if (StringUtils.isNotEmpty(user)) { props.put("mail.smtp.auth", "true"); authenticator = new Authenticator() { private PasswordAuthentication pa = new PasswordAuthentication(user, password); @Override public PasswordAuthentication getPasswordAuthentication() { return pa; } }; } Session session = Session.getInstance(props, authenticator); session.setDebug(Boolean.parseBoolean(debug)); MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(sender)); InternetAddress[] address = {new InternetAddress(to)}; message.setRecipients(Message.RecipientType.TO, address); message.setSubject(subject,"UTF-8"); message.setSentDate(new Date()); Multipart multipart = new MimeMultipart("alternative"); MimeBodyPart htmlPart = new MimeBodyPart(); htmlPart.setContent(content, "text/html; charset=utf-8"); multipart.addBodyPart(htmlPart); message.setContent(multipart); Transport.send(message); } } <|start_filename|>admin/src/main/webapp/app/user/js/login.js<|end_filename|> (function (){ var app = angular.module('admin-login',[]); app.config(['$httpProvider', function($httpProvider){ $httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest'; }]); app.controller('LoginController', ['AuthService','$scope', function(AuthService,$scope){ var login = this; login.credentials = {}; login.authenticationFailed = false; this.login = function (){ AuthService.login(login.credentials); }; this.logout = function (){ AuthService.logout(login.credentials); login.credentials={}; }; this.isAuthenticated = function(){ return AuthService.isAuthenticated(); }; this.hasAuthenticationFailed = function(){ return AuthService.hasAuthenticationFailed(); }; }]); app.factory('AuthService', ['$http', function ($http) { var auth = this; auth.wrapper = { logged:false, login:null, hasAuthenticationFailed:false }; return { login: function (credentials) { var stringView= new StringView(credentials.login + ':' + credentials.password); var encoded = stringView.toBase64(); $http.defaults.headers.common.Authorization = 'Basic ' + encoded; var success = false; $http.head('rs/users/administrators'). success(function(data){ auth.wrapper.logged = true; auth.wrapper.login = credentials.login; auth.wrapper.hasAuthenticationFailed = false; }). error(function(data){ auth.wrapper.hasAuthenticationFailed = true; }); }, isAuthenticated: function () { return auth.wrapper.logged === true; }, isNotAuthenticated: function () { return auth.wrapper.logged === false; }, hasAuthenticationFailed: function () { return auth.wrapper.hasAuthenticationFailed; }, logout: function () { auth.wrapper.logged = false; auth.wrapper.login = null; $http.defaults.headers.common.Authorization=null; } }; }]); })(); <|start_filename|>user/src/main/java/org/rembx/jeeshop/user/model/User.java<|end_filename|> package org.rembx.jeeshop.user.model; import javax.json.bind.annotation.JsonbTransient; import javax.persistence.*; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; import java.util.Date; import java.util.Set; import java.util.UUID; /** * Created by remi on 21/05/14. */ @Entity @XmlType @XmlAccessorType(XmlAccessType.FIELD) @Table(name = "`user`") public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(unique = true, nullable = false, length = 100) @NotNull @Email private String login; @Column(nullable = false, length = 100) @NotNull private String password; @Column(nullable = false, length = 50) @NotNull @Size(max = 50) private String firstname; @Column(nullable = false, length = 50) @NotNull @Size(max = 50) private String lastname; @Size(max = 30) @Column(nullable = false) private String gender; // TODO replace with enum @Phone private String phoneNumber; @OneToOne(cascade = {CascadeType.ALL}) private Address address; @OneToOne private Address deliveryAddress; @Temporal(TemporalType.TIMESTAMP) private Date birthDate; @Transient private Integer age; @Temporal(TemporalType.TIMESTAMP) private Date creationDate; @Temporal(TemporalType.TIMESTAMP) private Date updateDate; private Boolean disabled; private Boolean activated; @Column(columnDefinition = "BINARY(16)") @JsonbTransient private UUID actionToken; private String preferredLocale; private Boolean newslettersSubscribed; @ManyToMany @JoinTable(name = "User_Role", joinColumns = @JoinColumn(name = "userId"), inverseJoinColumns = @JoinColumn(name = "roleId")) @JsonbTransient private Set<Role> roles; public User() { } public User(String login, String password, String firstname, String lastname, String phoneNumber, Address address, Date birthDate, String preferredLocale, Address deliveryAddress) { this.login = login; this.password = password; this.firstname = firstname; this.lastname = lastname; this.phoneNumber = phoneNumber; this.address = address; this.birthDate = birthDate; this.preferredLocale = preferredLocale; this.deliveryAddress = deliveryAddress; } public User(String login, String password, String gender, String firstname, String lastname, String phoneNumber, Address address, Date birthDate, String preferredLocale, Address deliveryAddress) { this.login = login; this.password = password; this.gender = gender; this.firstname = firstname; this.lastname = lastname; this.phoneNumber = phoneNumber; this.address = address; this.birthDate = birthDate; this.preferredLocale = preferredLocale; this.deliveryAddress = deliveryAddress; } @PrePersist public void prePersist() { this.creationDate = new Date(); this.activated = false; } @PreUpdate public void preUpdate(){ this.updateDate = new Date(); } public void setId(Long id) { this.id = id; } public Long getId() { return id; } public String getLogin() { return login; } public void setLogin(String login) { this.login = login; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getFirstname() { return firstname; } public void setFirstname(String firstname) { this.firstname = firstname; } public String getLastname() { return lastname; } public void setLastname(String lastname) { this.lastname = lastname; } public String getPhoneNumber() { return phoneNumber; } public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } public Address getAddress() { return address; } public void setAddress(Address address) { this.address = address; } public Address getDeliveryAddress() { return deliveryAddress; } public void setDeliveryAddress(Address deliveryAddress) { this.deliveryAddress = deliveryAddress; } public Date getBirthDate() { return birthDate; } public void setBirthDate(Date birthDate) { this.birthDate = birthDate; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public Set<Role> getRoles() { return roles; } public void setRoles(Set<Role> roles) { this.roles = roles; } public Date getCreationDate() { return creationDate; } public void setCreationDate(Date creationDate) { this.creationDate = creationDate; } public Boolean getDisabled() { return disabled; } public void setDisabled(Boolean disabled) { this.disabled = disabled; } public Boolean getActivated() { return activated; } public void setActivated(Boolean activated) { this.activated = activated; } public UUID getActionToken() { return actionToken; } public void setActionToken(UUID actionToken) { this.actionToken = actionToken; } public String getPreferredLocale() { return preferredLocale; } public void setPreferredLocale(String preferredLocale) { this.preferredLocale = preferredLocale; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public Date getUpdateDate() { return updateDate; } public void setUpdateDate(Date updateDate) { this.updateDate = updateDate; } public Boolean getNewslettersSubscribed() { return newslettersSubscribed; } public void setNewslettersSubscribed(Boolean newslettersSubscribed) { this.newslettersSubscribed = newslettersSubscribed; } @Override public String toString() { return "User{" + "actionToken=" + actionToken + ", id=" + id + ", login='" + login + '\'' + ", password='" + password + '\'' + ", firstname='" + firstname + '\'' + ", lastname='" + lastname + '\'' + ", phoneNumber='" + phoneNumber + '\'' + ", birthDate=" + birthDate + ", age=" + age + ", disabled=" + disabled + ", activated=" + activated + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; User user = (User) o; if (actionToken != null ? !actionToken.equals(user.actionToken) : user.actionToken != null) return false; if (activated != null ? !activated.equals(user.activated) : user.activated != null) return false; if (age != null ? !age.equals(user.age) : user.age != null) return false; if (birthDate != null ? !birthDate.equals(user.birthDate) : user.birthDate != null) return false; if (disabled != null ? !disabled.equals(user.disabled) : user.disabled != null) return false; if (firstname != null ? !firstname.equals(user.firstname) : user.firstname != null) return false; if (gender != null ? !gender.equals(user.gender) : user.gender != null) return false; if (id != null ? !id.equals(user.id) : user.id != null) return false; if (lastname != null ? !lastname.equals(user.lastname) : user.lastname != null) return false; if (login != null ? !login.equals(user.login) : user.login != null) return false; if (password != null ? !password.equals(user.password) : user.password != null) return false; if (phoneNumber != null ? !phoneNumber.equals(user.phoneNumber) : user.phoneNumber != null) return false; if (preferredLocale != null ? !preferredLocale.equals(user.preferredLocale) : user.preferredLocale != null) return false; return true; } @Override public int hashCode() { int result = id != null ? id.hashCode() : 0; result = 31 * result + (login != null ? login.hashCode() : 0); result = 31 * result + (password != null ? password.hashCode() : 0); result = 31 * result + (firstname != null ? firstname.hashCode() : 0); result = 31 * result + (lastname != null ? lastname.hashCode() : 0); result = 31 * result + (gender != null ? gender.hashCode() : 0); result = 31 * result + (phoneNumber != null ? phoneNumber.hashCode() : 0); result = 31 * result + (birthDate != null ? birthDate.hashCode() : 0); result = 31 * result + (age != null ? age.hashCode() : 0); result = 31 * result + (disabled != null ? disabled.hashCode() : 0); result = 31 * result + (activated != null ? activated.hashCode() : 0); result = 31 * result + (actionToken != null ? actionToken.hashCode() : 0); result = 31 * result + (preferredLocale != null ? preferredLocale.hashCode() : 0); return result; } } <|start_filename|>catalog/src/main/java/org/rembx/jeeshop/catalog/CatalogItemService.java<|end_filename|> package org.rembx.jeeshop.catalog; import org.rembx.jeeshop.catalog.model.CatalogItem; import org.rembx.jeeshop.rest.WebApplicationException; import javax.validation.constraints.NotNull; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import java.util.List; import java.util.Set; import static org.rembx.jeeshop.role.JeeshopRoles.ADMIN; import static org.rembx.jeeshop.role.JeeshopRoles.STORE_ADMIN; public interface CatalogItemService<T extends CatalogItem> { List<T> findAll(String search, Integer start, Integer size, String orderBy, Boolean isDesc, String locale); T find(SecurityContext securityContext, @NotNull Long productId, String locale); T create(SecurityContext securityContext, T item); T modify(SecurityContext securityContext, T item); void delete(SecurityContext securityContext, Long itemId); Set<String> findPresentationsLocales(SecurityContext securityContext, @NotNull Long catalogId); PresentationResource findPresentationByLocale(@NotNull Long productId, @NotNull String locale); default void attachOwner(SecurityContext securityContext, CatalogItem catalogItem) { if (securityContext.isUserInRole(ADMIN) && catalogItem.getOwner() == null) { throw new WebApplicationException(Response.Status.BAD_REQUEST); } else if (securityContext.isUserInRole(STORE_ADMIN) && catalogItem.getOwner() == null) { catalogItem.setOwner(securityContext.getUserPrincipal().getName()); } } } <|start_filename|>catalog/src/main/java/org/rembx/jeeshop/catalog/Discounts.java<|end_filename|> package org.rembx.jeeshop.catalog; import io.quarkus.hibernate.orm.PersistenceUnit; import org.rembx.jeeshop.catalog.model.*; import org.rembx.jeeshop.catalog.model.Discount.ApplicableTo; import org.rembx.jeeshop.rest.WebApplicationException; import javax.annotation.security.PermitAll; import javax.annotation.security.RolesAllowed; import javax.enterprise.context.ApplicationScoped; import javax.persistence.EntityManager; import javax.transaction.Transactional; import javax.validation.constraints.NotNull; import javax.ws.rs.*; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import java.util.List; import java.util.Set; import static org.rembx.jeeshop.catalog.model.QDiscount.discount; import static org.rembx.jeeshop.role.AuthorizationUtils.isAdminUser; import static org.rembx.jeeshop.role.AuthorizationUtils.isOwner; import static org.rembx.jeeshop.role.JeeshopRoles.*; /** * @author remi */ @Path("/rs/discounts") @ApplicationScoped public class Discounts implements CatalogItemService<Discount> { private final EntityManager entityManager; private final CatalogItemFinder catalogItemFinder; private final PresentationResource presentationResource; private DiscountFinder discountFinder; Discounts(@PersistenceUnit(CatalogPersistenceUnit.NAME) EntityManager entityManager, CatalogItemFinder catalogItemFinder, PresentationResource presentationResource, DiscountFinder discountFinder) { this.entityManager = entityManager; this.catalogItemFinder = catalogItemFinder; this.presentationResource = presentationResource; this.discountFinder = discountFinder; } @POST @Transactional @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @RolesAllowed({ADMIN, STORE_ADMIN}) public Discount create(@Context SecurityContext securityContext, Discount discount) { attachOwner(securityContext, discount); entityManager.persist(discount); return discount; } @DELETE @Transactional @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @RolesAllowed({ADMIN, STORE_ADMIN}) @Path("/{discountId}") public void delete(@Context SecurityContext securityContext, @PathParam("discountId") Long discountId) { Discount discount = entityManager.find(Discount.class, discountId); checkNotNull(discount); if (isAdminUser(securityContext) || isOwner(securityContext, discount.getOwner())) { List<Product> productHolders = catalogItemFinder.findForeignHolder(QProduct.product, QProduct.product.discounts, discount); for (Product product : productHolders) { product.getDiscounts().remove(discount); } List<SKU> skuHolders = catalogItemFinder.findForeignHolder(QSKU.sKU, QSKU.sKU.discounts, discount); for (SKU sku : skuHolders) { sku.getDiscounts().remove(discount); } entityManager.remove(discount); } else throw new WebApplicationException(Response.Status.FORBIDDEN); } @PUT @Transactional @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @RolesAllowed({ADMIN, STORE_ADMIN}) public Discount modify(@Context SecurityContext securityContext, Discount discount) { Discount originalDiscount = entityManager.find(Discount.class, discount.getId()); checkNotNull(originalDiscount); if (isAdminUser(securityContext) || isOwner(securityContext, discount.getOwner())) { discount.setPresentationByLocale(originalDiscount.getPresentationByLocale()); return entityManager.merge(discount); } else throw new WebApplicationException(Response.Status.FORBIDDEN); } @GET @Path("/") @Produces(MediaType.APPLICATION_JSON) @RolesAllowed({ADMIN, ADMIN_READONLY}) public List<Discount> findAll(@QueryParam("search") String search, @QueryParam("start") Integer start, @QueryParam("size") Integer size , @QueryParam("orderBy") String orderBy, @QueryParam("isDesc") Boolean isDesc, @QueryParam("locale") String locale) { if (search != null) return catalogItemFinder.findBySearchCriteria(discount, search, start, size, orderBy, isDesc, locale); else return catalogItemFinder.findAll(discount, start, size, orderBy, isDesc, locale); } @GET @Path("/visible") @Produces(MediaType.APPLICATION_JSON) @PermitAll public List<Discount> findVisible(@NotNull @QueryParam("applicableTo") ApplicableTo applicableTo, @QueryParam("locale") String locale) { return discountFinder.findVisibleDiscounts(applicableTo, locale); } @GET @Path("/count") @Produces(MediaType.APPLICATION_JSON) @RolesAllowed({ADMIN, ADMIN_READONLY}) public Long count(@QueryParam("search") String search) { if (search != null) return catalogItemFinder.countBySearchCriteria(discount, search); else return catalogItemFinder.countAll(discount); } @GET @Path("/{discountId}") @Produces(MediaType.APPLICATION_JSON) @RolesAllowed({ADMIN, STORE_ADMIN, ADMIN_READONLY}) public Discount find(@Context SecurityContext securityContext, @PathParam("discountId") @NotNull Long discountId, @QueryParam("locale") String locale) { Discount discount = entityManager.find(Discount.class, discountId); checkNotNull(discount); if (isAdminUser(securityContext) || isOwner(securityContext, discount.getOwner())) return discount; else return catalogItemFinder.filterVisible(discount, locale); } @GET @Path("/{discountId}/presentationslocales") @Produces(MediaType.APPLICATION_JSON) @RolesAllowed({ADMIN, STORE_ADMIN, ADMIN_READONLY}) public Set<String> findPresentationsLocales(@Context SecurityContext securityContext, @PathParam("discountId") @NotNull Long discountId) { Discount discount = entityManager.find(Discount.class, discountId); checkNotNull(discount); if (!isAdminUser(securityContext) && !isOwner(securityContext, discount.getOwner())) throw new WebApplicationException(Response.Status.FORBIDDEN); return discount.getPresentationByLocale().keySet(); } @Path("/{discountId}/presentations/{locale}") @PermitAll public PresentationResource findPresentationByLocale(@PathParam("discountId") @NotNull Long discountId, @NotNull @PathParam("locale") String locale) { Discount discount = entityManager.find(Discount.class, discountId); checkNotNull(discount); Presentation presentation = discount.getPresentationByLocale().get(locale); return presentationResource.init(discount, locale, presentation); } private void checkNotNull(Discount discount) { if (discount == null) { throw new WebApplicationException(Response.Status.NOT_FOUND); } } } <|start_filename|>user/src/main/java/org/rembx/jeeshop/user/model/Address.java<|end_filename|> package org.rembx.jeeshop.user.model; import javax.persistence.*; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; @Entity @XmlType @XmlAccessorType(XmlAccessType.FIELD) public class Address { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Size(max = 255) @NotNull @Column(nullable = false, length = 255) private String street; @Column(nullable = false, length = 255) @Size( max = 255) @NotNull private String city; @Column(nullable = false, length = 10) @Size(min = 1, max = 10) @NotNull private String zipCode; @Column(length = 50, nullable = false) @Size(max = 50) @NotNull private String firstname; @Column(length = 50, nullable = false) @Size(max = 50) @NotNull private String lastname; @Size(max = 30) @Column(length = 30, nullable = false) @NotNull private String gender; @Size(max=100) @Column(length = 100) private String company; @NotNull @Size(min = 3, max = 3) @Column(nullable = false, length = 3) private String countryIso3Code; public Address() { } public Address(String street, String city, String zipCode, String firstname, String lastname, String gender, String company, String countryIso3Code) { this.street = street; this.city = city; this.zipCode = zipCode; this.firstname = firstname; this.lastname = lastname; this.gender = gender; this.company = company; this.countryIso3Code = countryIso3Code; } public Long getId() { return id; } public String getStreet() { return street; } public void setStreet(String street) { this.street = street; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getZipCode() { return zipCode; } public void setZipCode(String zipCode) { this.zipCode = zipCode; } public String getCountryIso3Code() { return countryIso3Code; } public void setCountryIso3Code(String countryIso3Code) { this.countryIso3Code = countryIso3Code; } public void setId(Long id) { this.id = id; } public String getFirstname() { return firstname; } public void setFirstname(String firstname) { this.firstname = firstname; } public String getLastname() { return lastname; } public void setLastname(String lastname) { this.lastname = lastname; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public String getCompany() { return company; } public void setCompany(String company) { this.company = company; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Address address = (Address) o; if (city != null ? !city.equals(address.city) : address.city != null) return false; if (company != null ? !company.equals(address.company) : address.company != null) return false; if (countryIso3Code != null ? !countryIso3Code.equals(address.countryIso3Code) : address.countryIso3Code != null) return false; if (firstname != null ? !firstname.equals(address.firstname) : address.firstname != null) return false; if (gender != null ? !gender.equals(address.gender) : address.gender != null) return false; if (id != null ? !id.equals(address.id) : address.id != null) return false; if (lastname != null ? !lastname.equals(address.lastname) : address.lastname != null) return false; if (street != null ? !street.equals(address.street) : address.street != null) return false; if (zipCode != null ? !zipCode.equals(address.zipCode) : address.zipCode != null) return false; return true; } @Override public int hashCode() { int result = id != null ? id.hashCode() : 0; result = 31 * result + (street != null ? street.hashCode() : 0); result = 31 * result + (city != null ? city.hashCode() : 0); result = 31 * result + (zipCode != null ? zipCode.hashCode() : 0); result = 31 * result + (firstname != null ? firstname.hashCode() : 0); result = 31 * result + (lastname != null ? lastname.hashCode() : 0); result = 31 * result + (gender != null ? gender.hashCode() : 0); result = 31 * result + (company != null ? company.hashCode() : 0); result = 31 * result + (countryIso3Code != null ? countryIso3Code.hashCode() : 0); return result; } @Override public String toString() { return "Address{" + "id=" + id + ", street='" + street + '\'' + ", city='" + city + '\'' + ", zipCode='" + zipCode + '\'' + ", firstname='" + firstname + '\'' + ", lastname='" + lastname + '\'' + ", gender='" + gender + '\'' + ", company='" + company + '\'' + ", countryIso3Code='" + countryIso3Code + '\'' + '}'; } } <|start_filename|>catalog/src/main/java/org/rembx/jeeshop/catalog/model/Catalog.java<|end_filename|> package org.rembx.jeeshop.catalog.model; import javax.persistence.*; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import java.util.List; /** * Created by remi on 20/05/14. */ @Entity @XmlRootElement @XmlAccessorType(XmlAccessType.FIELD) @Cacheable public class Catalog extends CatalogItem { @ManyToMany(cascade = {CascadeType.PERSIST}) @JoinTable(joinColumns = @JoinColumn(name = "catalogId"), inverseJoinColumns = @JoinColumn(name = "categoryId")) @OrderColumn(name="orderIdx") private List<Category> rootCategories; @Transient private List<Long> rootCategoriesIds; public Catalog() { } public Catalog(String name) { this.name = name; } public Catalog(Long id, String name) { this.id = id; this.name = name; } public List<Category> getRootCategories() { return rootCategories; } public void setRootCategories(List<Category> rootCategories) { this.rootCategories = rootCategories; } public List<Long> getRootCategoriesIds() { return rootCategoriesIds; } public void setRootCategoriesIds(List<Long> rootCategoriesIds) { this.rootCategoriesIds = rootCategoriesIds; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (!super.equals(o)) return false; Catalog catalog = (Catalog) o; if (rootCategories != null ? !rootCategories.equals(catalog.rootCategories) : catalog.rootCategories != null) return false; return true; } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + (rootCategories != null ? rootCategories.hashCode() : 0); return result; } } <|start_filename|>catalog/src/main/java/org/rembx/jeeshop/catalog/model/Store.java<|end_filename|> package org.rembx.jeeshop.catalog.model; import javax.persistence.*; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import java.util.List; import java.util.Objects; @Entity @XmlRootElement @XmlAccessorType(XmlAccessType.FIELD) @Cacheable public class Store extends CatalogItem { @ManyToMany(cascade = {CascadeType.PERSIST}) @JoinTable(joinColumns = @JoinColumn(name = "storeId"), inverseJoinColumns = @JoinColumn(name = "catalogId")) @OrderColumn(name="orderIdx") List<Catalog> catalogs; @Transient List<Long> catalogsIds; @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER) List<Premises> premisses; public Store() { } public Store(String name) { this.name = name; } public Store(Long id, String name) { this.id = id; this.name = name; } public List<Catalog> getCatalogs() { return catalogs; } public void setCatalogs(List<Catalog> catalogs) { this.catalogs = catalogs; } public List<Premises> getPremisses() { return premisses; } public void setPremisses(List<Premises> premisses) { this.premisses = premisses; } public List<Long> getCatalogsIds() { return catalogsIds; } public void setCatalogsIds(List<Long> catalogsIds) { this.catalogsIds = catalogsIds; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (!super.equals(o)) return false; Store store = (Store) o; return Objects.equals(premisses, store.premisses); } @Override public int hashCode() { return Objects.hash(super.hashCode(), premisses); } } <|start_filename|>order/src/main/java/org/rembx/jeeshop/order/mail/Mails.java<|end_filename|> package org.rembx.jeeshop.order.mail; /** * Created by remi on 14/12/14. */ public enum Mails { orderAccepted, orderValidated, orderShipped } <|start_filename|>catalog/src/test/java/org/rembx/jeeshop/catalog/model/DiscountTest.java<|end_filename|> package org.rembx.jeeshop.catalog.model; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.rembx.jeeshop.catalog.model.Discount.ApplicableTo.ORDER; import static org.rembx.jeeshop.catalog.model.Discount.Trigger.AMOUNT; import static org.rembx.jeeshop.catalog.model.Discount.Type.DISCOUNT_RATE; import static org.rembx.jeeshop.catalog.model.Discount.Type.ORDER_DISCOUNT_AMOUNT; import static org.rembx.jeeshop.catalog.model.Discount.Type.SHIPPING_FEE_DISCOUNT_AMOUNT; public class DiscountTest { @Test public void processAmountDiscountWithRate() throws Exception { Discount discount = new Discount("discount1", "a discount", ORDER, DISCOUNT_RATE, AMOUNT, null,10.0, 2.0, 1, true,null,null, false, "<EMAIL>"); assertThat(discount.processDiscount(10.0,10.0)).isEqualTo(9); } @Test public void processAmountDiscountWithRate_andCurrentPriceDifferentFromOriginalPrice() throws Exception { Discount discount = new Discount("discount1", "a discount", ORDER, DISCOUNT_RATE, AMOUNT, null,10.0, 2.0, 1, true,null,null, false, "<EMAIL>"); assertThat(discount.processDiscount(10.0,20.0)).isEqualTo(8); } @Test public void processAmountDiscountWithDiscountValue() throws Exception { Discount discount = new Discount("discount1", "a discount", ORDER, ORDER_DISCOUNT_AMOUNT, AMOUNT, null,5.0, 2.0, 1, true,null,null, false, "<EMAIL>"); assertThat(discount.processDiscount(10.0,10.0)).isEqualTo(5); } @Test public void processShippingDiscount() throws Exception { Discount discount = new Discount("discount1", "a discount", ORDER, SHIPPING_FEE_DISCOUNT_AMOUNT, AMOUNT, null,5.0, 2.0, 1, true,null,null, false, "<EMAIL>"); assertThat(discount.processDiscount(10.0,10.0)).isEqualTo(5); } @Test public void isEligible_givenItemsPriceLowerThanTriggerValueAndAmountTrigger_shouldReturnFalse_() throws Exception{ Discount discount = new Discount("discount1", "a discount", ORDER, DISCOUNT_RATE, AMOUNT, null, 0.1, 2.0, 1, true,null,null, false, "<EMAIL>"); assertThat(discount.isEligible(1.9)).isFalse(); } @Test public void isEligible_givenItemsPriceGreaterOrEqualThanTriggerValueAndAmountTrigger_shouldReturnTrue_() throws Exception{ Discount discount = new Discount("discount1", "a discount", ORDER, DISCOUNT_RATE, AMOUNT, null, 0.1, 2.0, 1, true,null,null, false, "<EMAIL>"); assertThat(discount.isEligible(2.0)).isTrue(); } @Test public void isEligible_WhenDiscountHasNullTriggerValue_shouldReturnTrue_() throws Exception{ Discount discount = new Discount("discount1", "a discount", ORDER, DISCOUNT_RATE, AMOUNT, null, 0.1, null, 1, true,null,null, false, "<EMAIL>"); assertThat(discount.isEligible(2.0)).isTrue(); } } <|start_filename|>order/src/main/java/org/rembx/jeeshop/order/PaymentTransactionEngine.java<|end_filename|> package org.rembx.jeeshop.order; import org.rembx.jeeshop.order.model.Order; import org.rembx.jeeshop.order.model.PaymentInfo; /** * Created by remi on 07/12/14. */ public interface PaymentTransactionEngine { public void processPayment(Order order); } <|start_filename|>user/src/main/java/org/rembx/jeeshop/user/model/Role.java<|end_filename|> package org.rembx.jeeshop.user.model; import javax.persistence.*; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; /** * Created by remi on 03/06/14. */ @Entity @Table(name = "`role`") public class Role { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @NotNull @Column(unique = true, nullable = false) @Enumerated(EnumType.STRING) private RoleName name; public Role() { } public Role(RoleName name) { this.name = name; } public Long getId() { return id; } public RoleName getName() { return name; } public void setName(RoleName role) { this.name = role; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Role role1 = (Role) o; if (id != null ? !id.equals(role1.id) : role1.id != null) return false; if (name != null ? !name.equals(role1.name) : role1.name != null) return false; return true; } @Override public int hashCode() { int result = id != null ? id.hashCode() : 0; result = 31 * result + (name != null ? name.hashCode() : 0); return result; } } <|start_filename|>order/src/test/java/org/rembx/jeeshop/order/FeesTest.java<|end_filename|> package org.rembx.jeeshop.order; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; public class FeesTest { @Test public void getShippingFeesShouldReturnConfiguredShippingFeeAsDouble() throws Exception { OrderConfiguration orderConfiguration = orderConfiguration(); Fees fees = new Fees(orderConfiguration); assertThat(fees.getShippingFee()).isEqualTo(11.0); } @Test public void getVATShouldReturnConfiguredVATAsDouble() throws Exception { OrderConfiguration orderConfiguration = orderConfiguration(); Fees fees = new Fees(orderConfiguration); assertThat(fees.getShippingFee()).isEqualTo(11); } @Test public void getVATOrShippingFeeShouldReturnNullWhenNoMatchingOrderConfiguration() throws Exception { Fees fees = new Fees(null); assertThat(fees.getShippingFee()).isEqualTo(null); assertThat(fees.getVAT()).isEqualTo(null); } private OrderConfiguration orderConfiguration() { return new OrderConfiguration("11.0", "19.6"); } } <|start_filename|>order/src/test/java/org/rembx/jeeshop/order/OrdersCT.java<|end_filename|> package org.rembx.jeeshop.order; import org.apache.http.auth.BasicUserPrincipal; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.rembx.jeeshop.catalog.model.CatalogPersistenceUnit; import org.rembx.jeeshop.catalog.test.TestCatalog; import org.rembx.jeeshop.mail.Mailer; import org.rembx.jeeshop.order.model.Order; import org.rembx.jeeshop.order.model.OrderItem; import org.rembx.jeeshop.order.model.OrderStatus; import org.rembx.jeeshop.order.test.TestOrder; import org.rembx.jeeshop.rest.WebApplicationException; import org.rembx.jeeshop.role.JeeshopRoles; import org.rembx.jeeshop.user.MailTemplateFinder; import org.rembx.jeeshop.user.UserFinder; import org.rembx.jeeshop.user.model.Address; import org.rembx.jeeshop.user.model.User; import org.rembx.jeeshop.user.model.UserPersistenceUnit; import org.rembx.jeeshop.user.test.TestUser; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; import static org.mockito.Mockito.*; import static org.rembx.jeeshop.order.model.OrderStatus.PAYMENT_VALIDATED; public class OrdersCT { private static EntityManagerFactory emf; private static EntityManagerFactory catalogEmf; EntityManager entityManager; private EntityManager catalogEntityManager; private TestOrder testOrder; private TestCatalog testCatalog; private TestUser testUser; private SecurityContext sessionContextMock; private PriceEngine priceEngineMock; private PaymentTransactionEngine paymentTransactionEngine; private Orders service; @BeforeAll public static void beforeClass() { emf = Persistence.createEntityManagerFactory(UserPersistenceUnit.NAME); catalogEmf = Persistence.createEntityManagerFactory(CatalogPersistenceUnit.NAME); } @BeforeEach public void setup() { testOrder = TestOrder.getInstance(); testCatalog = TestCatalog.getInstance(); testUser = TestUser.getInstance(); entityManager = emf.createEntityManager(); catalogEntityManager = catalogEmf.createEntityManager(); sessionContextMock = mock(SecurityContext.class); priceEngineMock = mock(PriceEngine.class); final MailTemplateFinder mailTemplateFinder = MailTemplateFinder.getInstance(entityManager); paymentTransactionEngine = new DefaultPaymentTransactionEngine( new OrderFinder(entityManager, catalogEntityManager, new OrderConfiguration("20", "3")), mailTemplateFinder, new Mailer(), catalogEntityManager); service = new Orders(entityManager, new OrderFinder(entityManager, catalogEntityManager, new OrderConfiguration("11.0", "20.0")), new UserFinder(entityManager), mailTemplateFinder, null, priceEngineMock, paymentTransactionEngine); } @Test public void find() throws Exception { assertThat(service.find(sessionContextMock,1L, null)).isEqualTo(testOrder.firstOrder()); } @Test public void find_withEnhanceResult_shouldReturnEnhancedOrder() throws Exception { Order enhancedOrder = service.find(sessionContextMock,1L, true); assertThat(enhancedOrder).isEqualTo(testOrder.firstOrder()); assertThatOrderIsEnhanced(enhancedOrder); } @Test public void find_withUnknownId_ShouldThrowException() throws Exception { try { service.find(sessionContextMock, 999L, null); fail("should have thrown ex"); } catch (WebApplicationException e) { assertThat(e.getResponse().getStatusInfo()).isEqualTo(Response.Status.NOT_FOUND); } } @Test public void find_whenClientHasUserRoleAndOrderBelongsToAnotherUser_ShouldThrowException() throws Exception { entityManager.getTransaction().begin(); User user = new User("<EMAIL>", "test", "M.", "John", "Doe", "+33616161616", null, null, "fr_FR", null); entityManager.persist(user); entityManager.getTransaction().commit(); when(sessionContextMock.isUserInRole(JeeshopRoles.USER)).thenReturn(true); when(sessionContextMock.isUserInRole(JeeshopRoles.ADMIN)).thenReturn(false); when(sessionContextMock.getUserPrincipal()).thenReturn(new BasicUserPrincipal("<EMAIL>")); try { service.find(sessionContextMock, 1L, null); fail("should have thrown ex"); } catch (WebApplicationException e) { assertThat(e.getResponse().getStatusInfo()).isEqualTo(Response.Status.UNAUTHORIZED); } finally { entityManager.getTransaction().begin(); entityManager.remove(user); entityManager.persist(user); } } @Test public void findAll_shouldReturnNoneEmptyList() { assertThat(service.findAll(sessionContextMock, null, null, null, null, null, null, null, null)).containsExactly(testOrder.firstOrder(), testOrder.secondOrder()); } @Test public void findAll_withPagination_shouldReturnNoneEmptyListPaginated() { List<Order> orders = service.findAll(sessionContextMock, null, 0, 1, null, null, null, null, null); assertThat(orders).isNotEmpty(); assertThat(orders).containsExactly(testOrder.firstOrder()); } @Test public void findAll_ByLogin_shouldReturnSearchedOrder() { List<Order> orders = service.findAll(sessionContextMock, testOrder.firstOrder().getUser().getLogin(), 0, 1, null, null, null, null, null); assertThat(orders).isNotEmpty(); assertThat(orders).containsExactly(testOrder.firstOrder()); } @Test public void findAll_ByStatus_shouldReturnOrdersWithMatchingStatus() { List<Order> orders = service.findAll(sessionContextMock, null, 0, 1, null, null, OrderStatus.PAYMENT_VALIDATED, null, null); assertThat(orders).isNotEmpty(); assertThat(orders).containsExactly(testOrder.firstOrder()); } @Test public void findAll_ByStatus_shouldReturnEmptyListWhenThereAreNoOrdersInGivenStatus() { List<Order> orders = service.findAll(sessionContextMock, null, 0, 1, null, null, OrderStatus.DELIVERED, null, null); assertThat(orders).isEmpty(); } @Test public void findAll_ByStatus_shouldReturnEmptyListWhenThereAreNoOrdersWithItemsMatchingGivenSKUId() { List<Order> orders = service.findAll(sessionContextMock,null, 0, 1, null, null, null, 2L, null); assertThat(orders).isEmpty(); } @Test public void findAll_withEnhancedResults_shouldReturnEnhancedOrders() { List<Order> orders = service.findAll(sessionContextMock, null, 0, 1, null, null, null, null, true); assertThat(orders).isNotEmpty(); assertThat(orders).containsExactly(testOrder.firstOrder()); assertThat(orders.get(0).getDeliveryFee()).isNotNull(); assertThatOrderIsEnhanced(orders.get(0)); } @Test public void findAll_BySkuId_shouldReturnOrdersWithItemsHavingGivenSkuIdAndStatus() { List<Order> orders = service.findAll(sessionContextMock,null, 0, 1, null, null, OrderStatus.PAYMENT_VALIDATED, 1L, null); assertThat(orders).isNotEmpty(); assertThat(orders).containsExactly(testOrder.firstOrder()); } @Test public void findAll_BySkuId_shouldReturnOrdersWithItemsHavingGivenSkuId() { List<Order> orders = service.findAll(sessionContextMock,null, 0, 1, null, null, null, 1L, null); assertThat(orders).isNotEmpty(); assertThat(orders).containsExactly(testOrder.firstOrder()); } @Test public void findAll_whenClientHasUserRoleOnly_shouldReturnNoneEmptyList_WithoutOrdersWithStatusCREATED() { when(sessionContextMock.isUserInRole(JeeshopRoles.USER)).thenReturn(true); when(sessionContextMock.isUserInRole(JeeshopRoles.ADMIN)).thenReturn(false); when(sessionContextMock.getUserPrincipal()).thenReturn(new BasicUserPrincipal(testOrder.firstOrdersUser().getLogin())); assertThat(service.findAll(sessionContextMock,null, null, null, null, null, null, null, null)).containsExactly(testOrder.firstOrder()); } @Test public void findAll_whenClientHasUserRoleOnlyAndwithPagination_shouldReturnNoneEmptyListPaginated() { when(sessionContextMock.isUserInRole(JeeshopRoles.USER)).thenReturn(true); when(sessionContextMock.isUserInRole(JeeshopRoles.ADMIN)).thenReturn(false); when(sessionContextMock.getUserPrincipal()).thenReturn(new BasicUserPrincipal(testOrder.firstOrdersUser().getLogin())); List<Order> orders = service.findAll(sessionContextMock, null, 0, 1, null, null, null, null, null); assertThat(orders).isNotEmpty(); assertThat(orders).containsExactly(testOrder.firstOrder()); } @Test public void findAll_whenClientHasUserRoleOnlyAndByLogin_shouldReturnSearchedOrder() { when(sessionContextMock.isUserInRole(JeeshopRoles.USER)).thenReturn(true); when(sessionContextMock.isUserInRole(JeeshopRoles.ADMIN)).thenReturn(false); when(sessionContextMock.getUserPrincipal()).thenReturn(new BasicUserPrincipal(testOrder.firstOrdersUser().getLogin())); List<Order> orders = service.findAll(sessionContextMock, testOrder.firstOrder().getUser().getLogin(), 0, 1, null, null, null, null, null); assertThat(orders).isNotEmpty(); assertThat(orders).containsExactly(testOrder.firstOrder()); } @Test public void findAll_whenClientHasUserRoleOnlyAndByStatus_shouldReturnOrdersWithMatchingStatus() { when(sessionContextMock.isUserInRole(JeeshopRoles.USER)).thenReturn(true); when(sessionContextMock.isUserInRole(JeeshopRoles.ADMIN)).thenReturn(false); when(sessionContextMock.getUserPrincipal()).thenReturn(new BasicUserPrincipal(testOrder.firstOrdersUser().getLogin())); List<Order> orders = service.findAll(sessionContextMock, null, 0, 1, null, null, OrderStatus.PAYMENT_VALIDATED, null, null); assertThat(orders).isNotEmpty(); assertThat(orders).containsExactly(testOrder.firstOrder()); } @Test public void findAll_whenClientHasUserRoleAndByStatusCREATED_shouldReturnOrdersWithThisStatus() { when(sessionContextMock.isUserInRole(JeeshopRoles.USER)).thenReturn(true); when(sessionContextMock.isUserInRole(JeeshopRoles.ADMIN)).thenReturn(false); when(sessionContextMock.getUserPrincipal()).thenReturn(new BasicUserPrincipal(testOrder.firstOrdersUser().getLogin())); List<Order> orders = service.findAll(sessionContextMock, null, 0, 1, null, null, OrderStatus.CREATED, null, null); assertThat(orders).isNotEmpty(); assertThat(orders).containsExactly(testOrder.secondOrder()); } @Test public void count() { assertThat(service.count(null, null, null)).isGreaterThan(0); } @Test public void count_withUnknownSearchCriteria() { assertThat(service.count("unknown", null, null)).isEqualTo(0); } @Test public void create_shouldThrowBadRequestWhenParametersHaveId() throws Exception { Address address = new Address("7 Rue des arbres", "Paris", "92800", "John", "Doe", "M.", null, "USA"); address.setId(777L); OrderItem orderItemWithId = new OrderItem(); orderItemWithId.setId(777L); Set<OrderItem> orderItems = Collections.singleton(orderItemWithId); try { Order order = new Order(null, address, new Address("7 Rue des arbres", "Paris", "92800", "John", "Doe", "M.", null, "USA")); service.create(sessionContextMock, order, null); fail("should have thrown ex"); } catch (WebApplicationException e) { assertThat(e.getResponse().getStatusInfo()).isEqualTo(Response.Status.BAD_REQUEST); } try { Order order = new Order(null, new Address("7 Rue des arbres", "Paris", "92800", "John", "Doe", "M.", null, "USA"), address); service.create(sessionContextMock, order, null); fail("should have thrown ex"); } catch (WebApplicationException e) { assertThat(e.getResponse().getStatusInfo()).isEqualTo(Response.Status.BAD_REQUEST); } try { Order order = new Order(orderItems, new Address("7 Rue des arbres", "Paris", "92800", "John", "Doe", "M.", null, "USA"), address); service.create(sessionContextMock, order, null); fail("should have thrown ex"); } catch (WebApplicationException e) { assertThat(e.getResponse().getStatusInfo()).isEqualTo(Response.Status.BAD_REQUEST); } } @Test public void create_shouldPersistOrderAndItsAddressesInCascade_SetCurrentUserToOrderForUserRole_AndProcessPayment() throws Exception { Address deliveryAddress = new Address("7 Rue des arbres", "Paris", "92800", "John", "Doe", "M.", null, "USA"); Address billingAddress = new Address("8 Rue Toto", "Paris", "75001", "John", "Doe", "M.", null, "FRA"); when(sessionContextMock.isUserInRole(JeeshopRoles.USER)).thenReturn(true); when(sessionContextMock.getUserPrincipal()).thenReturn(new BasicUserPrincipal(testOrder.firstOrdersUser().getLogin())); entityManager.getTransaction().begin(); Order order = new Order(new HashSet<>(), new Address("7 Rue des arbres", "Paris", "92800", "John", "Doe", "M.", null, "USA"), new Address("8 Rue Toto", "Paris", "75001", "John", "Doe", "M.", null, "FRA")); order.setOrderDiscounts(new HashSet<>()); service.create(sessionContextMock, order, null); entityManager.getTransaction().commit(); verify(sessionContextMock).isUserInRole(JeeshopRoles.USER); //verify(mailerMock).sendMail(testMailTemplate.orderConfirmationMailTemplate().getSubject(), testOrder.firstOrdersUser().getLogin(), "<html><body>Hello M. <NAME>. Your order has been registered...</body></html>"); final Order persistedOrder = entityManager.find(Order.class, order.getId()); assertThat(persistedOrder).isNotNull(); assertThat(persistedOrder.getStatus()).isEqualTo(PAYMENT_VALIDATED); assertThat(persistedOrder.getUser()).isEqualTo(testOrder.firstOrdersUser()); deliveryAddress.setId(persistedOrder.getDeliveryAddress().getId()); billingAddress.setId(persistedOrder.getBillingAddress().getId()); assertThat(persistedOrder.getBillingAddress()).isEqualTo(billingAddress); assertThat(persistedOrder.getDeliveryAddress()).isEqualTo(deliveryAddress); entityManager.getTransaction().begin(); entityManager.remove(order); entityManager.getTransaction().commit(); } @Test public void create_shouldPersistOrderWithOrderItems_computePrice_andProcessPayment() throws Exception { Set<OrderItem> orderItems = new HashSet<>(); orderItems.add(new OrderItem(1L, 1L, 2)); orderItems.add(new OrderItem(2L, 2L, 3)); when(sessionContextMock.isUserInRole(JeeshopRoles.USER)).thenReturn(true); when(sessionContextMock.getUserPrincipal()).thenReturn(new BasicUserPrincipal(testOrder.firstOrdersUser().getLogin())); entityManager.getTransaction().begin(); Order order = new Order(orderItems, new Address("7 Rue des arbres", "Paris", "92800", "John", "Doe", "M.", null, "USA"), new Address("7 Rue des arbres", "Paris", "92800", "John", "Doe", "M.", null, "USA")); order.setOrderDiscounts(new HashSet<>()); service.create(sessionContextMock, order, null); entityManager.getTransaction().commit(); verify(sessionContextMock).isUserInRole(JeeshopRoles.USER); verify(priceEngineMock).computePrice(order); final Order persistedOrder = entityManager.find(Order.class, order.getId()); assertThat(persistedOrder).isNotNull(); assertThat(persistedOrder.getStatus()).isEqualTo(PAYMENT_VALIDATED); assertThat(persistedOrder.getUser()).isEqualTo(testOrder.firstOrdersUser()); assertThat(persistedOrder.getItems()).hasSize(2); entityManager.getTransaction().begin(); entityManager.remove(order); entityManager.getTransaction().commit(); } @Test public void create_shouldSetGivenUserByLoginInOrder_ForADMINRole() throws Exception { when(sessionContextMock.isUserInRole(JeeshopRoles.USER)).thenReturn(false); when(sessionContextMock.isUserInRole(JeeshopRoles.ADMIN)).thenReturn(true); entityManager.getTransaction().begin(); Order order = new Order(new HashSet<>(), new Address("7 Rue des arbres", "Paris", "92800", "John", "Doe", "M.", null, "USA"), new Address("7 Rue des arbres", "Paris", "92800", "John", "Doe", "M.", null, "USA")); order.setOrderDiscounts(new HashSet<>()); service.create(sessionContextMock, order, "<EMAIL>"); entityManager.getTransaction().commit(); verify(sessionContextMock).isUserInRole(JeeshopRoles.USER); verify(sessionContextMock).isUserInRole(JeeshopRoles.ADMIN); final Order persistedOrder = entityManager.find(Order.class, order.getId()); assertThat(persistedOrder).isNotNull(); assertThat(persistedOrder.getStatus()).isEqualTo(PAYMENT_VALIDATED); assertThat(persistedOrder.getUser()).isEqualTo(testOrder.firstOrdersUser()); entityManager.getTransaction().begin(); entityManager.remove(order); entityManager.getTransaction().commit(); } @Test public void delete_shouldRemove() { entityManager.getTransaction().begin(); Order order = new Order(); order.setUser(testUser.firstUser()); order.setStatus(OrderStatus.VALIDATED); entityManager.persist(order); entityManager.getTransaction().commit(); entityManager.getTransaction().begin(); service.delete(order.getId()); entityManager.getTransaction().commit(); assertThat(entityManager.find(Order.class, order.getId())).isNull(); } @Test public void delete_NotExistingEntry_shouldThrowNotFoundEx() { try { entityManager.getTransaction().begin(); service.delete(666L); entityManager.getTransaction().commit(); fail("should have thrown ex"); } catch (WebApplicationException e) { assertThat(e.getResponse().getStatusInfo()).isEqualTo(Response.Status.NOT_FOUND); } } @Test public void modifyUnknownCatalog_ShouldThrowNotFoundException() { Order detachedOrder = new Order(); detachedOrder.setId(9999L); try { service.modify(detachedOrder); fail("should have thrown ex"); } catch (WebApplicationException e) { assertThat(e.getResponse().getStatusInfo()).isEqualTo(Response.Status.NOT_FOUND); } } private void assertThatOrderIsEnhanced(Order order) { assertThat(order.getDeliveryFee()).isEqualTo(11.0); assertThat(order.getVat()).isEqualTo(20.0); order.getItems().forEach(orderItem -> { assertThat(orderItem.getDisplayName()).isNotNull(); assertThat(orderItem.getSkuReference()).isNotNull(); } ); order.getOrderDiscounts().forEach(orderDiscount -> { assertThat(orderDiscount.getDisplayName()).isNotNull(); assertThat(orderDiscount.getRateType()).isNotNull(); } ); } } <|start_filename|>common/src/test/java/org/rembx/jeeshop/mail/MailerIT.java<|end_filename|> package org.rembx.jeeshop.mail; import com.icegreen.greenmail.util.GreenMail; import com.icegreen.greenmail.util.ServerSetupTest; import org.jboss.weld.environment.se.Weld; import org.jboss.weld.environment.se.WeldContainer; import org.junit.*; import javax.mail.MessagingException; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail; public class MailerIT { protected static Weld weld; protected static WeldContainer container; private GreenMail server; @BeforeClass public static void init() { weld = new Weld(); container = weld.initialize(); } @AfterClass public static void close() { weld.shutdown(); } @Before public void setUp() { server = new GreenMail(ServerSetupTest.SMTP); server.start(); } @After public void tearDown() { server.stop(); } @Test public void sendMail() throws Exception{ Mailer mailer = container.instance().select(Mailer.class).get(); try { mailer.sendMail("Test Subject", "<EMAIL>", "<h1>Hello</h1>"); } catch (MessagingException e) { e.printStackTrace(); fail(); } assertThat(server.getReceivedMessages().length).isEqualTo(1); assertThat(server.getReceivedMessages()[0].getSubject()).isEqualTo("Test Subject"); } @Test public void sendMail_shouldThrowConnectTimeoutEx_WhenNoSmtpServerAvailable(){ server.stop(); Mailer mailer = container.instance().select(Mailer.class).get(); try { mailer.sendMail("Test Subject", "<EMAIL>", "<h1>Hello</h1>"); fail("should have thrown ex"); }catch (MessagingException e){ assertThat(e.getMessage()).startsWith("Couldn't connect to host"); } } } <|start_filename|>admin/src/main/webapp/app/order/js/order.js<|end_filename|> (function () { var app = angular.module('admin-order', []); app.controller('OrderOperationController', ['$http', function ($http) { var ctrl = this; ctrl.alerts = []; ctrl.isProcessing = false; ctrl.skuId = null; ctrl.closeAlert = function (index) { ctrl.alerts.splice(index, 1); }; var escapeCSVField = function (field) { if (field == null) { return ""; } var escaped = field.replace(/"/g, ''); escaped = escaped.replace(/<br\/*>|<p>/g, ' '); escaped = escaped.replace(/<.*>/g, ''); // remove html tags return escaped; }; ctrl.payedOrdersAsCSV = function () { ctrl.isProcessing = true; ctrl.alerts = []; var paymentValidatedStatus = "PAYMENT_VALIDATED"; var uri = 'rs/orders?status=' + paymentValidatedStatus + '&orderBy=id&isDesc=false&enhanced=true'; if (ctrl.skuId != null) { uri += '&skuId=' + ctrl.skuId; } $http.get(uri).success(function (orders) { ctrl.isProcessing = false; if (orders.length == 0) { ctrl.alerts.push({ type: 'warning', msg: 'No orders found matching criteria with status ' + paymentValidatedStatus }); return; } var csvContent = "Order ID;Order Reference;Company;Gender;First name;Last name;Address;Zip Code;City;Country code (ISO 3166);Phone;E-mail;Product name;Product reference;Quantity\n"; for (i in orders) { var order = orders[i]; for (j in order.items) { var orderItem = order.items[j]; csvContent += order.id + ";" + order.reference + ";" + escapeCSVField(order.deliveryAddress.company) + ";" + escapeCSVField(order.deliveryAddress.gender) + ";" + escapeCSVField(order.deliveryAddress.firstname) + ";" + escapeCSVField(order.deliveryAddress.lastname) + ';' + escapeCSVField(order.deliveryAddress.street) + ';' + escapeCSVField(order.deliveryAddress.zipCode) + ';' + escapeCSVField(order.deliveryAddress.city) + ';' + escapeCSVField(order.deliveryAddress.countryIso3Code) + ';' + escapeCSVField(order.user.phoneNumber) + ';' + escapeCSVField(order.user.login) + ';' + escapeCSVField(orderItem.displayName) + ';' + escapeCSVField(orderItem.skuReference) + ';' + orderItem.quantity + '\n'; } } var encodedUri = encodeURI('data:text/csv;charset=utf-8,' + csvContent); window.open(encodedUri); }).error(function () { if (orders.length == 0) { ctrl.alerts.push({type: 'danger', msg: 'Technical error'}); } }); }; }]); app.controller('OrdersController', ['$http', '$uibModal', function ($http, $uibModal) { var ctrl = this; ctrl.alerts = []; ctrl.entries = []; ctrl.currentPage = 1; ctrl.totalCount = null; ctrl.pageSize = 10; ctrl.searchValue = null; ctrl.isProcessing = false; ctrl.searchOnlyPaymentValidated = false; ctrl.orderBy = null; ctrl.orderDesc = false; ctrl.findEntries = function (orderBy, orderDesc) { ctrl.isProcessing = true; ctrl.alerts = []; var offset = ctrl.pageSize * (ctrl.currentPage - 1); var uri = 'rs/orders?start=' + offset + '&size=' + ctrl.pageSize; if (orderBy != null) { ctrl.orderBy = orderBy; ctrl.orderDesc = !ctrl.orderDesc; if (orderDesc != null) { ctrl.orderDesc = orderDesc; } uri += '&orderBy=' + orderBy + '&isDesc=' + ctrl.orderDesc; } var countURI = 'rs/orders/count'; if (ctrl.searchValue != null && !(ctrl.searchValue === "")) { var searchArg = '&search=' + ctrl.searchValue; uri = uri + searchArg; countURI = countURI + '?' + searchArg; } if (ctrl.searchOnlyPaymentValidated) { var searchArg = '&status=PAYMENT_VALIDATED'; uri = uri + searchArg; countURI = countURI + '?' + searchArg; } $http.get(uri).success(function (data) { ctrl.entries = data; ctrl.isProcessing = false; }); $http.get(countURI).success(function (data) { ctrl.totalCount = data; ctrl.isProcessing = false; }); }; ctrl.findEntries(); ctrl.pageChanged = function () { ctrl.findEntries(); }; ctrl.delete = function (index, message) { var modalInstance = $uibModal.open({ templateUrl: 'app/util/confirm-delete-danger.html', controller: ['$uibModalInstance','$scope', function ($uibModalInstance, $scope) { $scope.modalInstance = $uibModalInstance; $scope.confirmMessage = message; }], size: 'sm' }); modalInstance.result.then(function () { ctrl.alerts = []; $http.delete('rs/orders/' + ctrl.entries[index].id) .success(function (data) { ctrl.entries.splice(index, 1); ctrl.findEntries(); }) .error(function (data) { ctrl.alerts.push({type: 'danger', msg: 'Technical error'}); }); }, function () { }); }; ctrl.closeAlert = function (index) { ctrl.alerts.splice(index, 1); }; }]); app.controller('OrderController', ['$http', '$stateParams', '$state', function ($http, $stateParams, $state) { var ctrl = this; ctrl.entry = {}; ctrl.alerts = []; ctrl.skuPerId = []; ctrl.discountPerId = []; ctrl.findOrder = function () { if ($stateParams.orderId == "") return; $http.get('rs/orders/' + $stateParams.orderId) .success(function (data) { ctrl.entry = data; ctrl.convertEntryDates(); }); }; ctrl.getOrderItemsSKUs = function () { if (ctrl.entry.items == null) { return; } for (i in ctrl.entry.items) { $http.get('rs/skus/' + ctrl.entry.items[i].skuId) .success(function (data) { ctrl.skuPerId[data.id] = data; }); } }; ctrl.getOrderDiscounts = function () { if (ctrl.entry.orderDiscounts == null) { return; } for (i in ctrl.entry.orderDiscounts) { $http.get('rs/discounts/' + ctrl.entry.orderDiscounts[i].discountId) .success(function (data) { ctrl.discountPerId[data.id] = data; }); } }; ctrl.edit = function () { $http.put('rs/orders', ctrl.entry) .success(function (data) { ctrl.entry = data; ctrl.convertEntryDates(); ctrl.alerts.push({type: 'success', msg: 'Update complete'}) }) .error(function (data, status) { if (status == 403) ctrl.alerts.push({type: 'warning', msg: 'Operation not allowed'}); else ctrl.alerts.push({type: 'danger', msg: 'Technical error'}); }); }; ctrl.closeAlert = function (index) { ctrl.alerts.splice(index, 1); }; ctrl.exitDetailView = function () { $state.go('^', {}, {reload: true}); }; ctrl.convertEntryDates = function () { // hack for dates returned as timestamp by service ctrl.entry.creationDate = ctrl.entry.creationDate != null ? new Date(ctrl.entry.creationDate) : null; ctrl.entry.updateDate = ctrl.entry.creationDate != null ? new Date(ctrl.entry.creationDate) : null; ctrl.entry.paymentDate = ctrl.entry.paymentDate != null ? new Date(ctrl.entry.paymentDate) : null; ctrl.entry.deliveryDate = ctrl.entry.deliveryDate != null ? new Date(ctrl.entry.deliveryDate) : null; }; ctrl.findOrder(); }]); })(); <|start_filename|>catalog/src/test/java/org/rembx/jeeshop/catalog/StoresCT.java<|end_filename|> package org.rembx.jeeshop.catalog; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.rembx.jeeshop.catalog.model.Catalog; import org.rembx.jeeshop.catalog.model.Store; import org.rembx.jeeshop.catalog.test.CatalogItemCRUDTester; import org.rembx.jeeshop.catalog.test.TestCatalog; import org.rembx.jeeshop.rest.WebApplicationException; import javax.ws.rs.core.Response; import java.time.DayOfWeek; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; public class StoresCT { private Stores localService; private CatalogItemCRUDTester<Store> tester; @BeforeEach public void setupClass() { tester = new CatalogItemCRUDTester<>(Store.class); this.localService = new Stores(tester.getEntityManager(), new CatalogItemFinder(tester.getEntityManager()), null); tester.setService(this.localService); } @Test public void findAll_shouldReturnNoneEmptyList() { assertThat(localService.findAll(null, null, null, null, null, null)).isNotEmpty(); } @Test public void find_shouldLoadSchedules() { tester.setAdminUser(); Store store = localService.find(tester.getSecurityContext(), 2L, null); assertThat(store).isNotNull(); assertThat(store.getPremisses()).isNotEmpty(); assertThat(store.getPremisses().get(0).getSchedules()).isNotEmpty(); assertThat(store.getPremisses().get(0).getSchedules().get(0).getDayOfWeek()).isEqualTo(DayOfWeek.MONDAY); } @Test public void find_shouldLoadNonVisibleItem_for_admin() { tester.setAdminUser(); Store store = localService.find(tester.getSecurityContext(), 1L, null); assertThat(store).isNotNull(); } @Test public void find_shouldLoadNonVisibleItem_for_store_admin() { tester.setStoreAdminUser(); Store store = localService.find(tester.getSecurityContext(), 1L, null); assertThat(store).isNotNull(); } @Test public void create_shouldSetupOwner_for_admin() { tester.setAdminUser(); Store store = new Store("Superstore"); store.setOwner(TestCatalog.OWNER); Store actualStore = tester.test_create(store); assertThat(actualStore).isNotNull(); assertThat(actualStore.getOwner()).isEqualTo(TestCatalog.OWNER); } @Test public void create_shouldThrowBadRequest_whenOwnerIsNull_for_admin() { tester.setAdminUser(); Store store = new Store("Superstore"); try { tester.test_create(store); fail("should have thrown an exception"); } catch (WebApplicationException e) { assertThat(e.getResponse().getStatusInfo()).isEqualTo(Response.Status.BAD_REQUEST); } } @Test public void create_shouldSetupOwner_for_store_admin() { tester.setStoreAdminUser(); Store store = new Store("Superstore"); Store actualStore = tester.test_create(store); assertThat(actualStore).isNotNull(); assertThat(actualStore.getOwner()).isEqualTo(TestCatalog.OWNER); } @Test public void delete_shouldRemove_for_admin() { tester.setAdminUser(); Store store = new Store("Superstore"); store.setOwner(TestCatalog.OWNER); tester.test_delete(store); assertThat(tester.getEntityManager().find(Store.class, store.getId())).isNull(); } @Test public void delete_shouldRemove_for_store_admin() { tester.setStoreAdminUser(); Store store = new Store("Superstore"); store.setOwner(TestCatalog.OWNER); tester.test_delete(store); assertThat(tester.getEntityManager().find(Store.class, store.getId())).isNull(); } @Test public void delete_shouldThrowForbidden_for_store_admin() { try { tester.setStoreAdminUser(); Store store = new Store("Superstore"); store.setOwner("<EMAIL>"); tester.test_delete(store); fail("Should have throw an exception"); } catch (WebApplicationException e) { assertThat(e.getResponse().getStatusInfo()).isEqualTo(Response.Status.FORBIDDEN); } } @Test public void modify_shouldThrowForbidden_for_store_admin() { try { tester.setSAnotherStoreAdminUser(); Store store = new Store(1L, "Superstore"); tester.test_modify(store); fail("Should have throw an exception"); } catch (WebApplicationException e) { assertThat(e.getResponse().getStatusInfo()).isEqualTo(Response.Status.FORBIDDEN); } } @Test public void modify_shouldThrowNotFound_for_store_admin() { try { tester.setStoreAdminUser(); Store store = new Store(666L, "Superstore"); tester.test_modify(store); fail("Should have throw an exception"); } catch (WebApplicationException e) { assertThat(e.getResponse().getStatusInfo()).isEqualTo(Response.Status.NOT_FOUND); } } @Test public void modify_shouldModify_for_store_admin() { tester.setStoreAdminUser(); Store store = new Store(1L, "Superstore 2"); store.setOwner(TestCatalog.OWNER); tester.test_modify(store); Store actual = tester.getEntityManager().find(Store.class, store.getId()); assertThat(actual).isNotNull(); assertThat(actual.getName()).isEqualTo("Superstore 2"); } @Test public void modify_shouldModify_for_admin() { tester.setAdminUser(); Store store = new Store(1L, "Superstore 2"); store.setOwner(TestCatalog.OWNER); tester.test_modify(store); Store actual = tester.getEntityManager().find(Store.class, store.getId()); assertThat(actual).isNotNull(); assertThat(actual.getName()).isEqualTo("Superstore 2"); } @Test public void findCatalog_should_retrieve_catalogs() { List<Catalog> catalogs = localService.findCatalogs(tester.getSecurityContext(), 2L, null); assertThat(catalogs).isNotEmpty(); } } <|start_filename|>admin/src/main/webapp/app/util/js/util.js<|end_filename|> (function (){ var app = angular.module('admin-util',[]); app.factory('LocalesService', function () { return { allLocales: function () { return [ {displayName: "Albanian (Albania)", name: "sq_AL"}, {displayName: "Albanian", name: "sq"}, {displayName: "Arabic (Algeria)", name: "ar_DZ"}, {displayName: "Arabic (Bahrain)", name: "ar_BH"}, {displayName: "Arabic (Egypt)", name: "ar_EG"}, {displayName: "Arabic (Iraq)", name: "ar_IQ"}, {displayName: "Arabic (Jordan)", name: "ar_JO"}, {displayName: "Arabic (Kuwait)", name: "ar_KW"}, {displayName: "Arabic (Lebanon)", name: "ar_LB"}, {displayName: "Arabic (Libya)", name: "ar_LY"}, {displayName: "Arabic (Morocco)", name: "ar_MA"}, {displayName: "Arabic (Oman)", name: "ar_OM"}, {displayName: "Arabic (Qatar)", name: "ar_QA"}, {displayName: "Arabic (Saudi Arabia)", name: "ar_SA"}, {displayName: "Arabic (Sudan)", name: "ar_SD"}, {displayName: "Arabic (Syria)", name: "ar_SY"}, {displayName: "Arabic (Tunisia)", name: "ar_TN"}, {displayName: "Arabic (United Arab Emirates)", name: "ar_AE"}, {displayName: "Arabic (Yemen)", name: "ar_YE"}, {displayName: "Arabic", name: "ar"}, {displayName: "Belarusian (Belarus)", name: "be_BY"}, {displayName: "Belarusian", name: "be"}, {displayName: "Bulgarian (Bulgaria)", name: "bg_BG"}, {displayName: "Bulgarian", name: "bg"}, {displayName: "Catalan (Spain)", name: "ca_ES"}, {displayName: "Catalan", name: "ca"}, {displayName: "Chinese (China)", name: "zh_CN"}, {displayName: "Chinese (Hong Kong)", name: "zh_HK"}, {displayName: "Chinese (Singapore)", name: "zh_SG"}, {displayName: "Chinese (Taiwan)", name: "zh_TW"}, {displayName: "Chinese", name: "zh"}, {displayName: "Croatian (Croatia)", name: "hr_HR"}, {displayName: "Croatian", name: "hr"}, {displayName: "Czech (Czech Republic)", name: "cs_CZ"}, {displayName: "Czech", name: "cs"}, {displayName: "Danish (Denmark)", name: "da_DK"}, {displayName: "Danish", name: "da"}, {displayName: "Dutch (Belgium)", name: "nl_BE"}, {displayName: "Dutch (Netherlands)", name: "nl_NL"}, {displayName: "Dutch", name: "nl"}, {displayName: "English (Australia)", name: "en_AU"}, {displayName: "English (Canada)", name: "en_CA"}, {displayName: "English (India)", name: "en_IN"}, {displayName: "English (Ireland)", name: "en_IE"}, {displayName: "English (Malta)", name: "en_MT"}, {displayName: "English (New Zealand)", name: "en_NZ"}, {displayName: "English (Philippines)", name: "en_PH"}, {displayName: "English (Singapore)", name: "en_SG"}, {displayName: "English (South Africa)", name: "en_ZA"}, {displayName: "English (United Kingdom)", name: "en_GB"}, {displayName: "English (United States)", name: "en_US"}, {displayName: "English", name: "en"}, {displayName: "Estonian (Estonia)", name: "et_EE"}, {displayName: "Estonian", name: "et"}, {displayName: "Finnish (Finland)", name: "fi_FI"}, {displayName: "Finnish", name: "fi"}, {displayName: "French (Belgium)", name: "fr_BE"}, {displayName: "French (Canada)", name: "fr_CA"}, {displayName: "French (France)", name: "fr_FR"}, {displayName: "French (Luxembourg)", name: "fr_LU"}, {displayName: "French (Switzerland)", name: "fr_CH"}, {displayName: "French", name: "fr"}, {displayName: "German (Austria)", name: "de_AT"}, {displayName: "German (Germany)", name: "de_DE"}, {displayName: "German (Greece)", name: "de_GR"}, {displayName: "German (Luxembourg)", name: "de_LU"}, {displayName: "German (Switzerland)", name: "de_CH"}, {displayName: "German", name: "de"}, {displayName: "Greek (Cyprus)", name: "el_CY"}, {displayName: "Greek (Greece)", name: "el_GR"}, {displayName: "Greek", name: "el"}, {displayName: "Hebrew (Israel)", name: "iw_IL"}, {displayName: "Hebrew", name: "iw"}, {displayName: "Hindi (India)", name: "hi_IN"}, {displayName: "Hindi", name: "hi"}, {displayName: "Hungarian (Hungary)", name: "hu_HU"}, {displayName: "Hungarian", name: "hu"}, {displayName: "Icelandic (Iceland)", name: "is_IS"}, {displayName: "Icelandic", name: "is"}, {displayName: "Indonesian (Indonesia)", name: "in_ID"}, {displayName: "Indonesian", name: "in"}, {displayName: "Irish (Ireland)", name: "ga_IE"}, {displayName: "Irish", name: "ga"}, {displayName: "Italian (Italy)", name: "it_IT"}, {displayName: "Italian (Switzerland)", name: "it_CH"}, {displayName: "Italian", name: "it"}, {displayName: "Japanese (Japan)", name: "ja_JP"}, {displayName: "Japanese (Japan,JP)", name: "ja_JP_JP_#u-ca-japanese"}, {displayName: "Japanese", name: "ja"}, {displayName: "Korean (South Korea)", name: "ko_KR"}, {displayName: "Korean", name: "ko"}, {displayName: "Latvian (Latvia)", name: "lv_LV"}, {displayName: "Latvian", name: "lv"}, {displayName: "Lithuanian (Lithuania)", name: "lt_LT"}, {displayName: "Lithuanian", name: "lt"}, {displayName: "Macedonian (Macedonia)", name: "mk_MK"}, {displayName: "Macedonian", name: "mk"}, {displayName: "Malay (Malaysia)", name: "ms_MY"}, {displayName: "Malay", name: "ms"}, {displayName: "Maltese (Malta)", name: "mt_MT"}, {displayName: "Maltese", name: "mt"}, {displayName: "Norwegian (Norway)", name: "no_NO"}, {displayName: "Norwegian (Norway,Nynorsk)", name: "no_NO_NY"}, {displayName: "Norwegian", name: "no"}, {displayName: "Polish (Poland)", name: "pl_PL"}, {displayName: "Polish", name: "pl"}, {displayName: "Portuguese (Brazil)", name: "pt_BR"}, {displayName: "Portuguese (Portugal)", name: "pt_PT"}, {displayName: "Portuguese", name: "pt"}, {displayName: "Romanian (Romania)", name: "ro_RO"}, {displayName: "Romanian", name: "ro"}, {displayName: "Russian (Russia)", name: "ru_RU"}, {displayName: "Russian", name: "ru"}, {displayName: "Serbian (Bosnia and Herzegovina)", name: "sr_BA"}, {displayName: "Serbian (Latin)", name: "sr__#Latn"}, {displayName: "Serbian (Latin,Bosnia and Herzegovina)", name: "sr_BA_#Latn"}, {displayName: "Serbian (Latin,Montenegro)", name: "sr_ME_#Latn"}, {displayName: "Serbian (Latin,Serbia)", name: "sr_RS_#Latn"}, {displayName: "Serbian (Montenegro)", name: "sr_ME"}, {displayName: "Serbian (Serbia and Montenegro)", name: "sr_CS"}, {displayName: "Serbian (Serbia)", name: "sr_RS"}, {displayName: "Serbian", name: "sr"}, {displayName: "Slovak (Slovakia)", name: "sk_SK"}, {displayName: "Slovak", name: "sk"}, {displayName: "Slovenian (Slovenia)", name: "sl_SI"}, {displayName: "Slovenian", name: "sl"}, {displayName: "Spanish (Argentina)", name: "es_AR"}, {displayName: "Spanish (Bolivia)", name: "es_BO"}, {displayName: "Spanish (Chile)", name: "es_CL"}, {displayName: "Spanish (Colombia)", name: "es_CO"}, {displayName: "Spanish (Costa Rica)", name: "es_CR"}, {displayName: "Spanish (Cuba)", name: "es_CU"}, {displayName: "Spanish (Dominican Republic)", name: "es_DO"}, {displayName: "Spanish (Ecuador)", name: "es_EC"}, {displayName: "Spanish (El Salvador)", name: "es_SV"}, {displayName: "Spanish (Guatemala)", name: "es_GT"}, {displayName: "Spanish (Honduras)", name: "es_HN"}, {displayName: "Spanish (Mexico)", name: "es_MX"}, {displayName: "Spanish (Nicaragua)", name: "es_NI"}, {displayName: "Spanish (Panama)", name: "es_PA"}, {displayName: "Spanish (Paraguay)", name: "es_PY"}, {displayName: "Spanish (Peru)", name: "es_PE"}, {displayName: "Spanish (Puerto Rico)", name: "es_PR"}, {displayName: "Spanish (Spain)", name: "es_ES"}, {displayName: "Spanish (United States)", name: "es_US"}, {displayName: "Spanish (Uruguay)", name: "es_UY"}, {displayName: "Spanish (Venezuela)", name: "es_VE"}, {displayName: "Spanish", name: "es"}, {displayName: "Swedish (Sweden)", name: "sv_SE"}, {displayName: "Swedish", name: "sv"}, {displayName: "Thai (Thailand)", name: "th_TH"}, {displayName: "Thai (Thailand,TH)", name: "th_TH_TH_#u-nu-thai"}, {displayName: "Thai", name: "th"}, {displayName: "Turkish (Turkey)", name: "tr_TR"}, {displayName: "Turkish", name: "tr"}, {displayName: "Ukrainian (Ukraine)", name: "uk_UA"}, {displayName: "Ukrainian", name: "uk"}, {displayName: "Vietnamese (Vietnam)", name: "vi_VN"} ]; } }; }); })(); <|start_filename|>user/src/test/java/org/rembx/jeeshop/user/test/TestMailTemplate.java<|end_filename|> package org.rembx.jeeshop.user.test; import org.rembx.jeeshop.user.mail.Mails; import org.rembx.jeeshop.user.model.MailTemplate; import org.rembx.jeeshop.user.model.UserPersistenceUnit; import javax.persistence.EntityManager; import javax.persistence.Persistence; /** * MailTemplate test utility */ public class TestMailTemplate { private static TestMailTemplate instance; private static MailTemplate mailTemplate1; private static MailTemplate userRegistrationMailTpl; private static MailTemplate ressetPasswordMailTpl; private static MailTemplate changePasswordMailTpl; public static TestMailTemplate getInstance() { if (instance != null) return instance; EntityManager entityManager = Persistence.createEntityManagerFactory(UserPersistenceUnit.NAME).createEntityManager(); entityManager.getTransaction().begin(); mailTemplate1 = new MailTemplate("Newsletter1", "fr_FR", "<html><body>bla bla...</body></html>", "Hello Subject"); userRegistrationMailTpl = new MailTemplate(Mails.userRegistration.name(), "fr_FR", "<html><body>Welcome ${gender} ${firstname} ${lastname}</body></html>", "New Registration Subject"); ressetPasswordMailTpl = new MailTemplate(Mails.userResetPassword.name(), "fr_FR", "<html><body>Here is the link to reset your password</body></html>", "Reset Password Subject"); changePasswordMailTpl = new MailTemplate(Mails.userChangePassword.name(), "fr_FR", "<html><body>Hello there, your password has changed!</body></html>", "Change Password Subject"); entityManager.persist(mailTemplate1); entityManager.persist(userRegistrationMailTpl); entityManager.persist(ressetPasswordMailTpl); entityManager.persist(changePasswordMailTpl); entityManager.getTransaction().commit(); instance = new TestMailTemplate(); entityManager.close(); return instance; } public MailTemplate firstMailTemplate() { return mailTemplate1; } public MailTemplate userRegistrationMailTemplate(){ return userRegistrationMailTpl; } public MailTemplate resetPasswordMailTemplate(){ return ressetPasswordMailTpl; } public MailTemplate changePasswordMailTpl(){ return changePasswordMailTpl; } } <|start_filename|>catalog/src/test/java/org/rembx/jeeshop/catalog/SKUsCT.java<|end_filename|> package org.rembx.jeeshop.catalog; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.rembx.jeeshop.catalog.model.Discount; import org.rembx.jeeshop.catalog.model.SKU; import org.rembx.jeeshop.catalog.test.CatalogItemCRUDTester; import org.rembx.jeeshop.catalog.test.TestCatalog; import org.rembx.jeeshop.rest.WebApplicationException; import javax.ws.rs.core.Response; import java.util.Date; import java.util.List; import static org.assertj.core.api.Assertions.fail; import static org.rembx.jeeshop.catalog.test.Assertions.assertThat; import static org.rembx.jeeshop.catalog.test.Assertions.assertThatDiscountsOf; public class SKUsCT { private SKUs localService; private CatalogItemCRUDTester<SKU> tester; @BeforeEach public void setup() { tester = new CatalogItemCRUDTester<>(SKU.class); localService = new SKUs(tester.getEntityManager(), new CatalogItemFinder(tester.getEntityManager()), null); tester.setService(this.localService); } @Test public void find_withIdOfVisibleSKU_ShouldReturnExpectedSKU() { SKU catalogItem = localService.find(tester.getSecurityContext(), tester.getFixtures().aVisibleSKU().getId(), null); assertThat(catalogItem).isEqualTo(tester.getFixtures().aVisibleSKU()); assertThat(catalogItem.isVisible()).isTrue(); } @Test public void find_withIdOfDisableSKU_ShouldThrowForbiddenException() { try { localService.find(tester.getSecurityContext(), tester.getFixtures().aDisabledSKU().getId(), null); fail("should have thrown ex"); } catch (WebApplicationException e) { assertThat(e.getResponse().getStatusInfo()).isEqualTo(Response.Status.FORBIDDEN); } } @Test public void find_withIdOfUnAvailableSKU_ShouldReturnUnAvailableSKU() { assertThat(localService.find(tester.getSecurityContext(), tester.getFixtures().aSKUNotAvailable().getId(), null)).isEqualTo(tester.getFixtures().aSKUNotAvailable()); assertThat(localService.find(tester.getSecurityContext(), tester.getFixtures().aSKUNotAvailable().getId(), null).isAvailable()).isFalse(); } @Test public void find_withIdOfExpiredSKU_ShouldThrowForbiddenException() { try { localService.find(tester.getSecurityContext(), tester.getFixtures().anExpiredSKU().getId(), null); fail("should have thrown ex"); } catch (WebApplicationException e) { assertThat(e.getResponse().getStatusInfo()).isEqualTo(Response.Status.FORBIDDEN); } } @Test public void find_withUnknownSKUId_ShouldThrowNotFoundException() { try { localService.find(tester.getSecurityContext(), 9999L, null); fail("should have thrown ex"); } catch (WebApplicationException e) { assertThat(e.getResponse().getStatusInfo()).isEqualTo(Response.Status.NOT_FOUND); } } @Test public void findDiscounts_shouldReturn404ExWhenSKUNotFound() { try { localService.findDiscounts(tester.getSecurityContext(), 9999L); fail("should have thrown ex"); } catch (WebApplicationException e) { assertThat(e.getResponse().getStatusInfo()).isEqualTo(Response.Status.NOT_FOUND); } } @Test public void findDiscounts_shouldNotReturnExpiredNorDisabledDiscounts() { List<Discount> discounts = localService.findDiscounts(tester.getSecurityContext(), tester.getFixtures().aSKUWithDiscounts().getId()); assertThat(discounts).isNotEmpty(); assertThatDiscountsOf(discounts).areVisibleDiscountsOfASKUWithDiscounts(); } @Test public void findAll_shouldReturnNoneEmptyList() { assertThat(localService.findAll(null, null, null, null, null, null)).isNotEmpty(); } @Test public void findAll_withPagination_shouldReturnNoneEmptyListPaginated() { List<SKU> categories = localService.findAll(null, 0, 1, null, null, null); assertThat(categories).isNotEmpty(); assertThat(categories).hasSize(1); } @Test public void findAll_withIdSearchParam_shouldReturnResultsWithMatchingId() { assertThat(localService.findAll(tester.getFixtures().aSKUNotAvailable().getId().toString(), null, null, null, null, null)).containsExactly(tester.getFixtures().aSKUNotAvailable()); } @Test public void findAll_withNameSearchParam_shouldReturnResultsWithMatchingName() { assertThat(localService.findAll(tester.getFixtures().aSKUNotAvailable().getName(), null, null, null, null, null)).containsExactly(tester.getFixtures().aSKUNotAvailable()); } @Test public void modifyUnknownSKU_ShouldThrowNotFoundException() { SKU detachedProductToModify = new SKU(9999L, null, null, null, null, null, null, null, null, null); try { localService.modify(tester.getSecurityContext(), detachedProductToModify); fail("should have thrown ex"); } catch (WebApplicationException e) { assertThat(e.getResponse().getStatusInfo()).isEqualTo(Response.Status.NOT_FOUND); } } @Test public void modify_ShouldThrowForbiddenException_for_store_admin() { tester.setSAnotherStoreAdminUser(); SKU sku = new SKU(tester.getFixtures().aVisibleSKU().getId(), "New name"); try { tester.test_modify(sku); ; fail("should have thrown ex"); } catch (WebApplicationException e) { assertThat(e.getResponse().getStatusInfo()).isEqualTo(Response.Status.FORBIDDEN); } } @Test public void modify_ShouldModify_for_store_admin() { tester.setStoreAdminUser(); SKU sku = new SKU(tester.getFixtures().aVisibleSKU().getId(), "New name"); tester.test_modify(sku); Assertions.assertThat(sku.getName()).isEqualTo("New name"); } @Test public void countAll() { assertThat(localService.count(null)).isGreaterThan(0); } @Test public void countAll_withUnknownSearchCriteria() { assertThat(localService.count("666")).isEqualTo(0); } @Test public void create_shouldPersistAndAttachOwner_for_admin() { tester.setAdminUser(); SKU sku = new SKU("name", "description", 1.0, 2, "reference", new Date(), new Date(), false, 1, "<EMAIL>"); SKU createdSKU = tester.test_create(sku); assertThat(createdSKU).isNotNull(); assertThat(createdSKU.getOwner()).isEqualTo("<EMAIL>"); } @Test public void create_shouldPersistAndAttachOwner_for_store_admin() { tester.setStoreAdminUser(); SKU sku = new SKU("name", "description", 1.0, 2, "reference", new Date(), new Date(), false, 1, null); SKU createdSKU = tester.test_create(sku); assertThat(createdSKU).isNotNull(); assertThat(createdSKU.getOwner()).isEqualTo(TestCatalog.OWNER); } @Test public void create_shouldThrow_BadRequest_for_Admin() { try { tester.setAdminUser(); SKU sku = new SKU("Test", ""); tester.test_create(sku); fail("should have throw an exception"); } catch (WebApplicationException e) { assertThat(e.getResponse().getStatusInfo()).isEqualTo(Response.Status.BAD_REQUEST); } } @Test public void delete_shouldRemove_for_admin() { tester.setAdminUser(); SKU sku = new SKU("Test", ""); sku.setOwner("<EMAIL>"); tester.test_delete(sku); assertThat(tester.getEntityManager().find(SKU.class, sku.getId())).isNull(); } @Test public void delete_shouldRemove_for_store_Admin() { tester.setStoreAdminUser(); SKU sku = new SKU("Test", ""); sku.setOwner(TestCatalog.OWNER); tester.test_delete(sku); assertThat(tester.getEntityManager().find(SKU.class, sku.getId())).isNull(); } @Test public void delete_shouldThrow_Forbidden_for_store_Admin() { try { tester.setStoreAdminUser(); SKU sku = new SKU("Test", ""); sku.setOwner("<EMAIL>"); tester.test_delete(sku); fail("should have throw an exception"); } catch (WebApplicationException e) { assertThat(e.getResponse().getStatusInfo()).isEqualTo(Response.Status.FORBIDDEN); } } @Test public void delete_NotExistingEntry_shouldThrowNotFoundEx() { try { tester.getEntityManager().getTransaction().begin(); localService.delete(tester.getSecurityContext(), 666L); tester.getEntityManager().getTransaction().commit(); fail("should have thrown ex"); } catch (WebApplicationException e) { assertThat(e.getResponse().getStatusInfo()).isEqualTo(Response.Status.NOT_FOUND); } } } <|start_filename|>common/src/main/java/org/rembx/jeeshop/configuration/NamedConfiguration.java<|end_filename|> package org.rembx.jeeshop.configuration; import javax.enterprise.util.Nonbinding; import javax.inject.Qualifier; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @Qualifier @Retention(RetentionPolicy.RUNTIME) public @interface NamedConfiguration { @Nonbinding String value() default ""; @Nonbinding String configurationFile() default ""; } <|start_filename|>catalog/src/main/java/org/rembx/jeeshop/catalog/Catalogs.java<|end_filename|> package org.rembx.jeeshop.catalog; import io.quarkus.hibernate.orm.PersistenceUnit; import org.rembx.jeeshop.catalog.model.Catalog; import org.rembx.jeeshop.catalog.model.CatalogPersistenceUnit; import org.rembx.jeeshop.catalog.model.Category; import org.rembx.jeeshop.catalog.model.Presentation; import org.rembx.jeeshop.rest.WebApplicationException; import javax.annotation.security.PermitAll; import javax.annotation.security.RolesAllowed; import javax.enterprise.context.ApplicationScoped; import javax.persistence.EntityManager; import javax.transaction.Transactional; import javax.validation.constraints.NotNull; import javax.ws.rs.*; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import java.util.ArrayList; import java.util.List; import java.util.Set; import static org.rembx.jeeshop.catalog.model.QCatalog.catalog; import static org.rembx.jeeshop.catalog.model.QCategory.category; import static org.rembx.jeeshop.role.AuthorizationUtils.isAdminUser; import static org.rembx.jeeshop.role.AuthorizationUtils.isOwner; import static org.rembx.jeeshop.role.JeeshopRoles.*; @Path("/rs/catalogs") @ApplicationScoped public class Catalogs implements CatalogItemService<Catalog> { private final EntityManager entityManager; private final CatalogItemFinder catalogItemFinder; private final PresentationResource presentationResource; Catalogs(@PersistenceUnit(CatalogPersistenceUnit.NAME) EntityManager entityManager, CatalogItemFinder catalogItemFinder, PresentationResource presentationResource) { this.entityManager = entityManager; this.catalogItemFinder = catalogItemFinder; this.presentationResource = presentationResource; } @GET @Path("/") @Produces(MediaType.APPLICATION_JSON) @RolesAllowed({ADMIN, ADMIN_READONLY}) public List<Catalog> findAll(@QueryParam("search") String search, @QueryParam("start") Integer start, @QueryParam("size") Integer size, @QueryParam("orderBy") String orderBy, @QueryParam("isDesc") Boolean isDesc, @QueryParam("locale") String locale) { return search != null ? catalogItemFinder.findBySearchCriteria(catalog, search, start, size, orderBy, isDesc, locale) : catalogItemFinder.findAll(catalog, start, size, orderBy, isDesc, locale); } @GET @Path("/count") @Produces(MediaType.APPLICATION_JSON) @RolesAllowed({ADMIN, ADMIN_READONLY}) public Long count(@QueryParam("search") String search) { return search != null ? catalogItemFinder.countBySearchCriteria(catalog, search) : catalogItemFinder.countAll(catalog); } @GET @Path("/{catalogId}") @Produces(MediaType.APPLICATION_JSON) @PermitAll public Catalog find(@Context SecurityContext securityContext, @PathParam("catalogId") @NotNull Long catalogId, @QueryParam("locale") String locale) { Catalog catalog = entityManager.find(Catalog.class, catalogId); if (isAdminUser(securityContext) || isOwner(securityContext, catalog.getOwner())) return catalog; else return catalogItemFinder.filterVisible(catalog, locale); } @POST @Transactional @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @RolesAllowed({ADMIN, STORE_ADMIN}) public Catalog create(@Context SecurityContext securityContext, Catalog catalog) { attachOwner(securityContext, catalog); if (catalog.getRootCategoriesIds() != null) { List<Category> newCategories = new ArrayList<>(); catalog.getRootCategoriesIds().forEach(categoryId -> newCategories.add(entityManager.find(Category.class, categoryId))); catalog.setRootCategories(newCategories); } entityManager.persist(catalog); return catalog; } @DELETE @Transactional @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @RolesAllowed({ADMIN, STORE_ADMIN}) @Path("/{catalogId}") public void delete(@Context SecurityContext securityContext, @PathParam("catalogId") Long catalogId) { Catalog loadedCatalog = entityManager.find(Catalog.class, catalogId); checkNotNull(loadedCatalog); if (isAdminUser(securityContext) || isOwner(securityContext, loadedCatalog.getOwner())) entityManager.remove(loadedCatalog); else throw new WebApplicationException(Response.Status.FORBIDDEN); } @PUT @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Transactional @RolesAllowed({ADMIN, STORE_ADMIN}) public Catalog modify(@Context SecurityContext securityContext, Catalog catalogToModify) { Catalog originalCatalog = entityManager.find(Catalog.class, catalogToModify.getId()); checkNotNull(originalCatalog); if (!isAdminUser(securityContext) && !isOwner(securityContext, originalCatalog.getOwner())) throw new WebApplicationException(Response.Status.FORBIDDEN); if (catalogToModify.getRootCategoriesIds() != null) { List<Category> newCategories = new ArrayList<>(); catalogToModify.getRootCategoriesIds().forEach(categoryId -> newCategories.add(entityManager.find(Category.class, categoryId))); catalogToModify.setRootCategories(newCategories); } else { catalogToModify.setRootCategories(originalCatalog.getRootCategories()); } catalogToModify.setPresentationByLocale(originalCatalog.getPresentationByLocale()); return entityManager.merge(catalogToModify); } @GET @Path("/{catalogId}/presentationslocales") @Produces(MediaType.APPLICATION_JSON) @RolesAllowed({ADMIN, STORE_ADMIN, ADMIN_READONLY}) public Set<String> findPresentationsLocales(@Context SecurityContext securityContext, @PathParam("catalogId") @NotNull Long catalogId) { Catalog catalog = entityManager.find(Catalog.class, catalogId); checkNotNull(catalog); if (!isAdminUser(securityContext) && !isOwner(securityContext, catalog.getOwner())) throw new WebApplicationException(Response.Status.FORBIDDEN); return catalog.getPresentationByLocale().keySet(); } @Path("/{catalogId}/presentations/{locale}") @PermitAll public PresentationResource findPresentationByLocale(@PathParam("catalogId") @NotNull Long catalogId, @NotNull @PathParam("locale") String locale) { Catalog catalog = entityManager.find(Catalog.class, catalogId); checkNotNull(catalog); Presentation presentation = catalog.getPresentationByLocale().get(locale); return presentationResource.init(catalog, locale, presentation); } @GET @Path("/{catalogId}/categories") @Produces(MediaType.APPLICATION_JSON) @PermitAll public List<Category> findCategories(@Context SecurityContext securityContext, @PathParam("catalogId") @NotNull Long catalogId, @QueryParam("locale") String locale) { Catalog catalog = entityManager.find(Catalog.class, catalogId); checkNotNull(catalog); List<Category> rootCategories = catalog.getRootCategories(); if (rootCategories.isEmpty()) { return new ArrayList<>(); } if (isAdminUser(securityContext) || isOwner(securityContext, catalog.getOwner())) { return rootCategories; } else { return catalogItemFinder.findVisibleCatalogItems(category, rootCategories, locale); } } private void checkNotNull(Catalog originalCatalog) { if (originalCatalog == null) { throw new WebApplicationException(Response.Status.NOT_FOUND); } } } <|start_filename|>catalog/src/main/java/org/rembx/jeeshop/catalog/model/Product.java<|end_filename|> package org.rembx.jeeshop.catalog.model; import javax.persistence.*; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; import java.util.Date; import java.util.List; /** * Created by remi on 20/05/14. */ @Entity @XmlType @XmlAccessorType(XmlAccessType.FIELD) @Cacheable public class Product extends CatalogItem { @ManyToMany(cascade = {CascadeType.PERSIST}) @JoinTable(joinColumns = @JoinColumn(name = "productId"), inverseJoinColumns = @JoinColumn(name = "skuId")) @OrderColumn(name = "orderIdx") private List<SKU> childSKUs; @Transient private List<Long> childSKUsIds; @ManyToMany(cascade = {CascadeType.PERSIST}) @JoinTable(joinColumns = @JoinColumn(name = "productId"), inverseJoinColumns = @JoinColumn(name = "discountId")) @OrderColumn(name = "orderIdx") private List<Discount> discounts; @Transient private List<Long> discountsIds; public Product() { } public Product(Long id, String name) { this.id = id; this.name = name; } public Product(String name) { this.name = name; } public Product(String name, String description, Date startDate, Date endDate, Boolean disabled, String owner) { this.name = name; this.description = description; this.startDate = startDate; this.endDate = endDate; this.disabled = disabled; this.owner = owner; } public Product(Long id, String name, String description, Date startDate, Date endDate, Boolean disabled) { this.id = id; this.name = name; this.description = description; this.startDate = startDate; this.endDate = endDate; this.disabled = disabled; } public List<SKU> getChildSKUs() { return childSKUs; } public void setChildSKUs(List<SKU> childSKUs) { this.childSKUs = childSKUs; } public List<Discount> getDiscounts() { return discounts; } public void setDiscounts(List<Discount> discounts) { this.discounts = discounts; } public List<Long> getChildSKUsIds() { return childSKUsIds; } public void setChildSKUsIds(List<Long> childSKUsIds) { this.childSKUsIds = childSKUsIds; } public List<Long> getDiscountsIds() { return discountsIds; } public void setDiscountsIds(List<Long> discountsIds) { this.discountsIds = discountsIds; } } <|start_filename|>catalog/src/main/java/org/rembx/jeeshop/catalog/Categories.java<|end_filename|> package org.rembx.jeeshop.catalog; import io.quarkus.hibernate.orm.PersistenceUnit; import org.rembx.jeeshop.catalog.model.*; import org.rembx.jeeshop.rest.WebApplicationException; import javax.annotation.security.PermitAll; import javax.annotation.security.RolesAllowed; import javax.enterprise.context.ApplicationScoped; import javax.persistence.EntityManager; import javax.transaction.Transactional; import javax.validation.constraints.NotNull; import javax.ws.rs.*; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import java.util.ArrayList; import java.util.List; import java.util.Set; import static org.rembx.jeeshop.catalog.model.QCategory.category; import static org.rembx.jeeshop.catalog.model.QProduct.product; import static org.rembx.jeeshop.role.AuthorizationUtils.isAdminUser; import static org.rembx.jeeshop.role.AuthorizationUtils.isOwner; import static org.rembx.jeeshop.role.JeeshopRoles.*; /** * @author remi */ @Path("/rs/categories") @ApplicationScoped public class Categories implements CatalogItemService<Category> { private final EntityManager entityManager; private final CatalogItemFinder catalogItemFinder; private final PresentationResource presentationResource; Categories(@PersistenceUnit(CatalogPersistenceUnit.NAME) EntityManager entityManager, CatalogItemFinder catalogItemFinder, PresentationResource presentationResource) { this.entityManager = entityManager; this.catalogItemFinder = catalogItemFinder; this.presentationResource = presentationResource; } @POST @Transactional @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @RolesAllowed({ADMIN, STORE_ADMIN}) public Category create(@Context SecurityContext securityContext, Category category) { attachOwner(securityContext, category); if (category.getChildCategories() != null) { List<Category> newCategories = new ArrayList<>(); category.getChildCategoriesIds().forEach(categoryId -> newCategories.add(entityManager.find(Category.class, categoryId))); category.setChildCategories(newCategories); } if (category.getChildProductsIds() != null) { List<Product> newProducts = new ArrayList<>(); category.getChildProductsIds().forEach(productId -> newProducts.add(entityManager.find(Product.class, productId))); category.setChildProducts(newProducts); } entityManager.persist(category); return category; } @DELETE @Transactional @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @RolesAllowed({ADMIN, STORE_ADMIN}) @Path("/{categoryId}") public void delete(@Context SecurityContext securityContext, @PathParam("categoryId") Long categoryId) { Category category = entityManager.find(Category.class, categoryId); checkNotNull(category); if (!isOwner(securityContext, category.getOwner()) && !isAdminUser(securityContext)) throw new WebApplicationException(Response.Status.FORBIDDEN); else { List<Category> categoryHolders = catalogItemFinder.findForeignHolder(QCategory.category, QCategory.category.childCategories, category); for (Category categoryHolder : categoryHolders) { categoryHolder.getChildCategories().remove(category); } List<Catalog> catalogHolders = catalogItemFinder.findForeignHolder(QCatalog.catalog, QCatalog.catalog.rootCategories, category); for (Catalog catalogHolder : catalogHolders) { catalogHolder.getRootCategories().remove(category); } entityManager.remove(category); } } @PUT @Transactional @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @RolesAllowed({ADMIN, STORE_ADMIN}) public Category modify(@Context SecurityContext securityContext, Category category) { Category originalCategory = entityManager.find(Category.class, category.getId()); checkNotNull(originalCategory); if (isOwner(securityContext, originalCategory.getOwner()) || isAdminUser(securityContext)) { if (category.getChildCategoriesIds() != null) { List<Category> newCategories = new ArrayList<>(); category.getChildCategoriesIds().forEach(categoryId -> newCategories.add(entityManager.find(Category.class, categoryId))); category.setChildCategories(newCategories); } else { category.setChildCategories(originalCategory.getChildCategories()); } if (category.getChildProductsIds() != null) { List<Product> newProducts = new ArrayList<>(); category.getChildProductsIds().forEach(productId -> newProducts.add(entityManager.find(Product.class, productId))); category.setChildProducts(newProducts); } else { category.setChildProducts(originalCategory.getChildProducts()); } category.setPresentationByLocale(originalCategory.getPresentationByLocale()); return entityManager.merge(category); } else { throw new WebApplicationException(Response.Status.FORBIDDEN); } } @GET @Path("/") @Produces(MediaType.APPLICATION_JSON) @RolesAllowed({ADMIN, ADMIN_READONLY}) public List<Category> findAll(@QueryParam("search") String search, @QueryParam("start") Integer start, @QueryParam("size") Integer size , @QueryParam("orderBy") String orderBy, @QueryParam("isDesc") Boolean isDesc, @QueryParam("locale") String locale) { if (search != null) return catalogItemFinder.findBySearchCriteria(category, search, start, size, orderBy, isDesc, locale); else return catalogItemFinder.findAll(category, start, size, orderBy, isDesc, locale); } @GET @Path("/count") @Produces(MediaType.APPLICATION_JSON) @RolesAllowed({ADMIN, ADMIN_READONLY}) public Long count(@QueryParam("search") String search) { if (search != null) return catalogItemFinder.countBySearchCriteria(category, search); else return catalogItemFinder.countAll(category); } @GET @Path("/{categoryId}") @Produces(MediaType.APPLICATION_JSON) @PermitAll public Category find(@Context SecurityContext securityContext, @PathParam("categoryId") @NotNull Long categoryId, @QueryParam("locale") String locale) { Category category = entityManager.find(Category.class, categoryId); checkNotNull(category); return !isAdminUser(securityContext) && !isOwner(securityContext, category.getOwner()) ? catalogItemFinder.filterVisible(category, locale) : category; } @GET @Path("/{categoryId}/presentationslocales") @Produces(MediaType.APPLICATION_JSON) @RolesAllowed({ADMIN, STORE_ADMIN, ADMIN_READONLY}) public Set<String> findPresentationsLocales(@Context SecurityContext securityContext, @PathParam("categoryId") @NotNull Long categoryId) { Category category = entityManager.find(Category.class, categoryId); checkNotNull(category); if (!isAdminUser(securityContext) && !isOwner(securityContext, category.getOwner())) throw new WebApplicationException(Response.Status.FORBIDDEN); return category.getPresentationByLocale().keySet(); } @Path("/{categoryId}/presentations/{locale}") @PermitAll public PresentationResource findPresentationByLocale(@PathParam("categoryId") @NotNull Long categoryId, @NotNull @PathParam("locale") String locale) { Category category = entityManager.find(Category.class, categoryId); checkNotNull(category); Presentation presentation = category.getPresentationByLocale().get(locale); return presentationResource.init(category, locale, presentation); } @GET @Path("/{categoryId}/categories") @Produces(MediaType.APPLICATION_JSON) @PermitAll public List<Category> findChildCategories(@Context SecurityContext securityContext, @PathParam("categoryId") @NotNull Long categoryId, @QueryParam("locale") String locale) { Category cat = entityManager.find(Category.class, categoryId); checkNotNull(cat); List<Category> childCategories = cat.getChildCategories(); if (childCategories.isEmpty()) { return new ArrayList<>(); } return !isAdminUser(securityContext) && !isOwner(securityContext, cat.getOwner()) ? catalogItemFinder.findVisibleCatalogItems(category, childCategories, locale) : childCategories; } @GET @Path("/{categoryId}/products") @Produces(MediaType.APPLICATION_JSON) @PermitAll public List<Product> findChildProducts(@Context SecurityContext securityContext, @PathParam("categoryId") @NotNull Long categoryId, @QueryParam("locale") String locale) { Category cat = entityManager.find(Category.class, categoryId); checkNotNull(cat); List<Product> childProducts = cat.getChildProducts(); if (childProducts.isEmpty()) { return new ArrayList<>(); } return !isOwner(securityContext, cat.getOwner()) && isAdminUser(securityContext) ? catalogItemFinder.findVisibleCatalogItems(product, childProducts, locale) : childProducts; } private void checkNotNull(Category cat) { if (cat == null) { throw new WebApplicationException(Response.Status.NOT_FOUND); } } } <|start_filename|>order/src/main/java/org/rembx/jeeshop/order/PriceEngine.java<|end_filename|> package org.rembx.jeeshop.order; import org.rembx.jeeshop.order.model.Order; import org.rembx.jeeshop.order.model.PaymentInfo; import javax.enterprise.context.ApplicationScoped; import javax.enterprise.context.RequestScoped; /** * Created by remi on 07/12/14. */ @ApplicationScoped public interface PriceEngine { public void computePrice(Order order); } <|start_filename|>catalog/src/test/java/org/rembx/jeeshop/catalog/test/TestCatalog.java<|end_filename|> package org.rembx.jeeshop.catalog.test; import com.google.common.collect.Lists; import org.assertj.core.api.AbstractAssert; import org.rembx.jeeshop.catalog.model.*; import javax.persistence.EntityManager; import javax.persistence.Persistence; import java.sql.Timestamp; import java.time.DayOfWeek; import java.time.LocalTime; import java.time.ZonedDateTime; import java.util.*; import static org.assertj.core.api.Assertions.assertThat; import static org.rembx.jeeshop.catalog.model.Discount.ApplicableTo.ORDER; import static org.rembx.jeeshop.catalog.model.Discount.Trigger.AMOUNT; import static org.rembx.jeeshop.catalog.model.Discount.Type.DISCOUNT_RATE; /** * Catalog test utility */ public class TestCatalog { private static TestCatalog instance; // Date are initialized with java.sql.Timestamp as JPA get a Timestamp instance private final static Date now = Timestamp.from(ZonedDateTime.now().toInstant()); private final static Date tomorrow = Timestamp.from(ZonedDateTime.now().plusDays(1).toInstant()); private final static Date yesterday = Timestamp.from(ZonedDateTime.now().minusDays(1).toInstant()); public final static String OWNER = "<EMAIL>"; private static Store store; private static Store hiddenStore; private static Catalog catalog; private static Catalog emptyCatalog; private static Category rootCat1Empty; private static Category rootCat2; private static Category rootCat3Expired; private static Category childCat1Empty; private static Category childCat2; private static Category childCat3Expired; private static Category childCat4Disabled; private static Category childCat5WithPresentation; private static Category childCat6WithoutPresentation; private static Product product1; private static Product product2Expired; private static Product product3Disabled; private static Product product4; private static SKU sku1; private static SKU sku2; private static SKU sku3; private static SKU sku4; private static SKU sku5; private static Discount discount1; public static TestCatalog getInstance() { if (instance != null) return instance; EntityManager entityManager = Persistence.createEntityManagerFactory(CatalogPersistenceUnit.NAME).createEntityManager(); entityManager.getTransaction().begin(); emptyCatalog = new Catalog("empty"); emptyCatalog.setOwner(OWNER); entityManager.persist(emptyCatalog); catalog = new Catalog("test"); catalog.setOwner(OWNER); rootCat1Empty = new Category("rootCat1", "Root category 1 empty", now, tomorrow, false, OWNER); rootCat2 = new Category("rootCat2", "Root category 2 with child categories", now, tomorrow, false, OWNER); rootCat3Expired = new Category("rootCat3", "Root category 3 expired", now, yesterday, false, OWNER); childCat1Empty = new Category("childCat1", "Child category 1", now, tomorrow, false, OWNER); childCat2 = new Category("childCat2", "Child category 2 with products", now, tomorrow, false, OWNER); childCat3Expired = new Category("childCat3", "Child category 3 expired", now, yesterday, false, OWNER); childCat4Disabled = new Category("childCat4", "Child category 4 disabled", now, tomorrow, true, OWNER); childCat5WithPresentation = new Category("childCat5", "Child category 5 with presentation", now, tomorrow, false, OWNER); childCat6WithoutPresentation = new Category("childCat6", "Child category 6 without presentation", now, tomorrow, true, OWNER); childCat6WithoutPresentation.setPresentationByLocale(new HashMap<>()); Presentation presentationUKChildCat5 = new Presentation("en", "Chocolat cakes", PresentationTexts.TEXT_1000, PresentationTexts.TEXT_2000); Presentation presentationUSChildCat5 = new Presentation("en_US", "Chocolat cakes", PresentationTexts.TEXT_1000, PresentationTexts.TEXT_2000); childCat5WithPresentation.setPresentationByLocale(new HashMap<String, Presentation>() {{ put(Locale.ENGLISH.toString(), presentationUKChildCat5); put(Locale.US.toString(), presentationUSChildCat5); }}); product1 = new Product("product1", "description", now, tomorrow, false, OWNER); product2Expired = new Product("product2", "description", now, yesterday, false, OWNER); product3Disabled = new Product("product3", "description", now, yesterday, true, OWNER); product4 = new Product("product4", "description", now, yesterday, false, OWNER); sku1 = new SKU("sku1", "Sku1 enabled", 10d, 100, "X1213JJLB-1", now, tomorrow, false, 3, OWNER); sku2 = new SKU("sku2", "Sku2 disabled", 10d, 100, "X1213JJLB-2", now, tomorrow, true, 3, OWNER); sku3 = new SKU("sku3", "Sku3 expired", 10d, 100, "X1213JJLB-3", now, yesterday, false, 3, OWNER); sku4 = new SKU("sku4", "Sku4 not available", 10d, 2, "X1213JJLB-4", now, tomorrow, false, 3, OWNER); sku5 = new SKU("sku5", "Sku5 with discounts", 10d, 100, "X1213JJLB-5", now, tomorrow, false, 3, OWNER); discount1 = new Discount("discount1", "a discount", ORDER, DISCOUNT_RATE, AMOUNT, null, 0.1, 2.0, 1, true, now, tomorrow, false, OWNER); sku5.setDiscounts(Arrays.asList(discount1)); catalog.setRootCategories(Arrays.asList(rootCat1Empty, rootCat2, rootCat3Expired)); rootCat2.setChildCategories(Arrays.asList(childCat1Empty, childCat2, childCat3Expired, childCat4Disabled, childCat5WithPresentation, childCat6WithoutPresentation)); childCat2.setChildProducts(Arrays.asList(product1, product2Expired, product3Disabled, product4)); product1.setChildSKUs(Arrays.asList(sku1, sku2, sku3, sku4, sku5)); hiddenStore = new Store("Hidden Shop"); hiddenStore.setOwner(OWNER); hiddenStore.setDisabled(true); entityManager.persist(hiddenStore); store = new Store("Shop"); store.setOwner(OWNER); PremisesOpeningSchedules schedules = new PremisesOpeningSchedules(store, DayOfWeek.MONDAY, LocalTime.MIN, LocalTime.MAX); PremisesAddress address = new PremisesAddress("10, rue des lilas", "Paris", "75001", "FRA"); Premises premises = new Premises(); premises.setAddress(address); premises.setSchedules(Lists.newArrayList(schedules)); store.setPremisses(Lists.newArrayList(premises)); store.setCatalogs(Lists.newArrayList(catalog)); entityManager.persist(store); entityManager.getTransaction().commit(); instance = new TestCatalog(); entityManager.close(); return instance; } public Long getCatalogId() { return catalog.getId(); } public static Catalog getCatalog() { return catalog; } public Long getEmptyCatalogId() { return emptyCatalog.getId(); } public Category aRootCategoryWithChildCategories() { return rootCat2; } public Category aCategoryWithProducts() { return childCat2; } public Category aCategoryWithoutProducts() { return childCat1Empty; } public Category aCategoryWithPresentation() { return childCat5WithPresentation; } public Category aCategoryWithoutPresentation() { return childCat6WithoutPresentation; } public Category anExpiredCategory() { return childCat3Expired; } public Category aDisabledCategory() { return childCat4Disabled; } public Product anExpiredProduct() { return product2Expired; } public Product aDisabledProduct() { return product3Disabled; } public Product aProductWithSKUs() { return product1; } public Product aProductWithoutSKUs() { return product4; } public SKU aVisibleSKU() { return sku1; } public SKU aDisabledSKU() { return sku2; } public SKU anExpiredSKU() { return sku3; } public SKU aSKUNotAvailable() { return sku4; } public SKU aSKUWithDiscounts() { return sku5; } public Discount aVisibleDisount() { return discount1; } public static class CatalogItemAssert extends AbstractAssert<CatalogItemAssert, CatalogItem> { CatalogItemAssert(CatalogItem actual) { super(actual, CatalogItemAssert.class); } public CatalogItemAssert hasLocalizedPresentationShortDescription(String locale, String text) { assertThat(actual.getPresentationByLocale().get(locale).getShortDescription()).isEqualTo(text); assertThat(actual.getLocalizedPresentation().getShortDescription()).isEqualTo(text); return this; } } public static class CategoriesAssert extends AbstractAssert<CategoriesAssert, List<Category>> { CategoriesAssert(List<Category> actual) { super(actual, CategoriesAssert.class); } /** * Visible categories are not disabled and have an endDate after current date */ public CategoriesAssert areVisibleRootCategories() { assertThat(actual).containsExactly(catalog.getRootCategories().get(0), catalog.getRootCategories().get(1)); return this; } /** * Visible categories are not disabled and have an endDate after current date */ public CategoriesAssert areVisibleChildCategoriesOfARootCategoryWithChildCategories() { assertThat(actual).containsExactly(catalog.getRootCategories().get(1).getChildCategories().get(0), catalog.getRootCategories().get(1).getChildCategories().get(1), catalog.getRootCategories().get(1).getChildCategories().get(4)); return this; } } public static class ProductsAssert extends AbstractAssert<ProductsAssert, List<Product>> { ProductsAssert(List<Product> actual) { super(actual, ProductsAssert.class); } /** * Visible products are not disabled and have an endDate after current date */ public ProductsAssert areVisibleProductsOfAChildCategoryWithProducts() { assertThat(actual).containsExactly(catalog.getRootCategories().get(1).getChildCategories().get(1).getChildProducts().get(0)); return this; } } public static class SKUsAssert extends AbstractAssert<SKUsAssert, List<SKU>> { SKUsAssert(List<SKU> actual) { super(actual, SKUsAssert.class); } /** * Visible skus are not disabled and have an endDate after current date */ public SKUsAssert areVisibleSKUsOfAProductWithSKUs() { assertThat(actual).containsExactly( catalog.getRootCategories().get(1).getChildCategories().get(1).getChildProducts().get(0).getChildSKUs().get(0), catalog.getRootCategories().get(1).getChildCategories().get(1).getChildProducts().get(0).getChildSKUs().get(3), catalog.getRootCategories().get(1).getChildCategories().get(1).getChildProducts().get(0).getChildSKUs().get(4)); return this; } } public static class SKUDiscountsAssert extends AbstractAssert<SKUDiscountsAssert, List<Discount>> { SKUDiscountsAssert(List<Discount> actual) { super(actual, SKUDiscountsAssert.class); } /** * Visible discounts are not disabled and have an endDate after current date */ public SKUDiscountsAssert areVisibleDiscountsOfASKUWithDiscounts() { assertThat(actual).containsExactly(catalog.getRootCategories().get(1).getChildCategories().get(1) .getChildProducts().get(0).getChildSKUs().get(4).getDiscounts().get(0)); return this; } } } <|start_filename|>common/src/main/java/org/rembx/jeeshop/rest/WebApplicationException.java<|end_filename|> package org.rembx.jeeshop.rest; import javax.ws.rs.core.Response; // FIXME ? @ApplicationException public class WebApplicationException extends javax.ws.rs.WebApplicationException{ public WebApplicationException(Response.Status status) { super(status); } } <|start_filename|>user/src/main/java/org/rembx/jeeshop/user/Users.java<|end_filename|> package org.rembx.jeeshop.user; import com.google.common.collect.Sets; import freemarker.template.Configuration; import freemarker.template.Template; import io.quarkus.hibernate.orm.PersistenceUnit; import org.rembx.jeeshop.mail.Mailer; import org.rembx.jeeshop.rest.WebApplicationException; import org.rembx.jeeshop.user.mail.Mails; import org.rembx.jeeshop.user.model.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.security.PermitAll; import javax.annotation.security.RolesAllowed; import javax.enterprise.context.ApplicationScoped; import javax.persistence.EntityManager; import javax.transaction.Transactional; import javax.validation.constraints.NotNull; import javax.ws.rs.*; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import java.io.StringWriter; import java.util.List; import java.util.UUID; import static org.rembx.jeeshop.role.JeeshopRoles.*; import static org.rembx.jeeshop.user.tools.CryptTools.hashSha256Base64; /** * Customer resource */ @Path("/rs/users") @ApplicationScoped public class Users { private final static Logger LOG = LoggerFactory.getLogger(Users.class); private EntityManager entityManager; private UserFinder userFinder; private RoleFinder roleFinder; private CountryChecker countryChecker; private Mailer mailer; private MailTemplateFinder mailTemplateFinder; Users(@PersistenceUnit(UserPersistenceUnit.NAME) EntityManager entityManager, UserFinder userFinder, RoleFinder roleFinder, CountryChecker countryChecker, MailTemplateFinder mailTemplateFinder, Mailer mailer) { this.entityManager = entityManager; this.userFinder = userFinder; this.roleFinder = roleFinder; this.countryChecker = countryChecker; this.mailTemplateFinder = mailTemplateFinder; this.mailer = mailer; } @POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @PermitAll public User create(@Context SecurityContext securityContext, @NotNull User user) { if (user.getId() != null) { throw new WebApplicationException(Response.Status.BAD_REQUEST); } User userByLogin = userFinder.findByLogin(user.getLogin()); if (userByLogin != null) { throw new WebApplicationException(Response.Status.CONFLICT); } final Address userAddress = user.getAddress(); if (userAddress != null) { if (userAddress.getId() != null) { throw new WebApplicationException(Response.Status.BAD_REQUEST); } if (!countryChecker.isAvailable(userAddress.getCountryIso3Code())) { LOG.error("Country {} is not available", userAddress.getCountryIso3Code()); throw new WebApplicationException(Response.Status.BAD_REQUEST); } } entityManager.persist(user); Role userRole = roleFinder.findByName(RoleName.user); user.setRoles(Sets.newHashSet(userRole)); user.setPassword(<PASSWORD>(<PASSWORD>())); if (!securityContext.isUserInRole(ADMIN)) { user.setActivated(false); generateActionTokenAndSendMail(user, Mails.userRegistration); } return user; } @PUT @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Path("/{userLogin}") @PermitAll public void activate(@NotNull @PathParam("userLogin") String userLogin, @NotNull String token) { User user = userFinder.findByLogin(userLogin); if (user != null && user.getActionToken() != null && user.getActionToken().equals(UUID.fromString(token))) { user.setActivated(true); user.setActionToken(null); } else { throw new WebApplicationException(Response.Status.NOT_FOUND); } } @POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Path("/{userLogin}/password") @PermitAll public void sendResetPasswordMail(@NotNull @PathParam("userLogin") String userLogin) { User user = userFinder.findByLogin(userLogin); if (user != null) { generateActionTokenAndSendMail(user, Mails.userResetPassword); } else { throw new WebApplicationException(Response.Status.NOT_FOUND); } } @PUT @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Path("/{userLogin}/password") @PermitAll public void resetPassword(@Context SecurityContext securityContext, @NotNull @PathParam("userLogin") String userLogin, @QueryParam("token") String token, @NotNull String newPassword) { User user; if (securityContext.isUserInRole(ADMIN)) { user = userFinder.findByLogin(userLogin); } else if (securityContext.isUserInRole(USER)) { user = userFinder.findByLogin(securityContext.getUserPrincipal().getName()); if (!userLogin.equals(user.getLogin())) { throw new WebApplicationException(Response.Status.UNAUTHORIZED); } } else { user = userFinder.findByLogin(userLogin); if (user == null || !user.getActionToken().equals(UUID.fromString(token))) { throw new WebApplicationException(Response.Status.NOT_FOUND); } user.setActionToken(null); } user.setPassword(<PASSWORD>(<PASSWORD>)); user.setActivated(true); sendMail(user, Mails.userChangePassword); } @DELETE @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @RolesAllowed(ADMIN) @Path("/{userId}") public void delete(@NotNull @PathParam("userId") Long userId) { User catalog = entityManager.find(User.class, userId); checkNotNull(catalog); entityManager.remove(catalog); } @PUT @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Transactional @RolesAllowed({ADMIN, USER}) public User modify(@Context SecurityContext securityContext, @NotNull User user) { User existingUser = null; if (securityContext.isUserInRole(USER) && !securityContext.isUserInRole(ADMIN)) { existingUser = userFinder.findByLogin(securityContext.getUserPrincipal().getName()); if (!existingUser.getId().equals(user.getId()) || !existingUser.getLogin().equals(user.getLogin())) { throw new WebApplicationException(Response.Status.UNAUTHORIZED); } user.setActivated(existingUser.getActivated()); user.setDisabled(existingUser.getDisabled()); user.setActionToken(existingUser.getActionToken()); } if (existingUser == null) { existingUser = entityManager.find(User.class, user.getId()); } checkNotNull(existingUser); user.setPassword(existingUser.<PASSWORD>()); user.setCreationDate(existingUser.getCreationDate()); user.setRoles(existingUser.getRoles()); return entityManager.merge(user); } @HEAD @Path("/") @Produces(MediaType.APPLICATION_JSON) @PermitAll public Boolean authenticate() { return true; } @HEAD @Path("/administrators") @Produces(MediaType.APPLICATION_JSON) @RolesAllowed({ADMIN, ADMIN_READONLY}) public Boolean authenticateAdminUser() { return true; } @GET @Path("/") @Produces(MediaType.APPLICATION_JSON) @RolesAllowed({ADMIN, ADMIN_READONLY}) public List<User> findAll(@QueryParam("search") String search, @QueryParam("start") Integer start, @QueryParam("size") Integer size , @QueryParam("orderBy") String orderBy, @QueryParam("isDesc") Boolean isDesc) { if (search != null) return userFinder.findBySearchCriteria(search, start, size, orderBy, isDesc); else return userFinder.findAll(start, size, orderBy, isDesc); } @GET @Path("/{customerId}") @Produces(MediaType.APPLICATION_JSON) @RolesAllowed({ADMIN, ADMIN_READONLY}) public User find(@PathParam("customerId") @NotNull Long customerId) { User user = entityManager.find(User.class, customerId); if (user == null) { throw new WebApplicationException(Response.Status.NOT_FOUND); } return user; } @GET @Path("/count") @Produces(MediaType.APPLICATION_JSON) @RolesAllowed({ADMIN, ADMIN_READONLY}) public Long count(@QueryParam("search") String search) { if (search != null) return userFinder.countBySearchCriteria(search); else return userFinder.countAll(); } @GET @Path("/current") @Produces(MediaType.APPLICATION_JSON) @RolesAllowed({ADMIN, ADMIN_READONLY, USER}) public User findCurrentUser(@Context SecurityContext securityContext) { User user = userFinder.findByLogin(securityContext.getUserPrincipal().getName()); if (user == null) { throw new WebApplicationException(Response.Status.NOT_FOUND); } return user; } private void checkNotNull(User originalUser) { if (originalUser == null) { throw new WebApplicationException(Response.Status.NOT_FOUND); } } private User generateActionTokenAndSendMail(User user, Mails mailType) { user.setActionToken(UUID.randomUUID()); sendMail(user, mailType); return user; } private void sendMail(User user, Mails mailType) { MailTemplate mailTemplate = mailTemplateFinder.findByNameAndLocale(mailType.name(), user.getPreferredLocale()); if (mailTemplate == null) { LOG.debug("Mail template " + mailType + " is not configured."); return; } try { Template mailContentTpl = new Template(mailType.name(), mailTemplate.getContent(), new Configuration(Configuration.VERSION_2_3_21)); final StringWriter mailBody = new StringWriter(); mailContentTpl.process(user, mailBody); mailer.sendMail(mailTemplate.getSubject(), user.getLogin(), mailBody.toString()); } catch (Exception e) { LOG.error("Unable to send mail " + mailType + " to user " + user.getLogin(), e); } return; } } <|start_filename|>admin/src/main/webapp/app/mail/js/mail.js<|end_filename|> (function () { var app = angular.module('admin-mail', []); app.controller('MailTemplatesController', ['$http', '$uibModal', function ($http, $uibModal) { var ctrl = this; ctrl.entries = []; ctrl.alerts = []; ctrl.currentPage = 1; ctrl.totalCount = null; ctrl.pageSize = 10; ctrl.searchValue = null; ctrl.isProcessing = false; ctrl.orderBy = null; ctrl.orderDesc = false; ctrl.findEntries = function (orderBy) { ctrl.isProcessing = true; ctrl.alerts = []; var offset = ctrl.pageSize * (ctrl.currentPage - 1); var uri = 'rs/mailtemplates'; var countURI = 'rs/mailtemplates/count'; if (ctrl.searchValue != null && !(ctrl.searchValue === "")) { uri = uri + '?name=' + ctrl.searchValue; $http.get(countURI).success(function (data) { ctrl.totalCount = data; ctrl.isProcessing = false; }); } else { uri = uri + '?start=' + offset + '&size=' + ctrl.pageSize; } if (orderBy != null) { ctrl.orderBy = orderBy; ctrl.orderDesc = !ctrl.orderDesc; uri += '&orderBy=' + orderBy + '&isDesc=' + ctrl.orderDesc; } $http.get(uri).success(function (data) { ctrl.entries = data; ctrl.isProcessing = false; }); }; ctrl.findEntries(); ctrl.pageChanged = function () { ctrl.findEntries(); }; ctrl.delete = function (index, message) { var modalInstance = $uibModal.open({ templateUrl: 'app/util/confirm-dialog.html', controller: ['$uibModalInstance','$scope', function ($uibModalInstance, $scope) { $scope.modalInstance = $uibModalInstance; $scope.confirmMessage = message; }], size: 'sm' }); modalInstance.result.then(function () { ctrl.alerts = []; $http.delete('rs/mailtemplates/' + ctrl.entries[index].id) .success(function (data) { ctrl.entries.splice(index, 1); ctrl.findEntries(); }) .error(function (data) { ctrl.alerts.push({type: 'danger', msg: 'Technical error'}); }); }, function () { }); }; ctrl.closeAlert = function (index) { ctrl.alerts.splice(index, 1); }; }]); app.controller('MailTemplateController', ['$http', '$stateParams', '$state', 'LocalesService', function ($http, $stateParams, $state, LocalesService) { var ctrl = this; ctrl.availableLocales = LocalesService.allLocales(); ctrl.entry = {}; ctrl.entryChilds = {}; ctrl.isEditionMode = ($stateParams.mailId != ""); ctrl.alerts = []; ctrl.findMailTemplate = function () { if (!ctrl.isEditionMode) return; $http.get('rs/mailtemplates/' + $stateParams.mailId) .success(function (data) { ctrl.entry = data; ctrl.convertEntryDates(); }); }; ctrl.createOrEdit = function () { ctrl.alerts = []; if (ctrl.isEditionMode) { ctrl.edit(); } else { ctrl.create(); } }; ctrl.create = function () { $http.post('rs/mailtemplates', ctrl.entry) .success(function (data) { ctrl.entry = data; ctrl.alerts.push({type: 'success', msg: 'Creation complete'}); ctrl.convertEntryDates(); }) .error(function (data, status) { if (status == 409) { ctrl.alerts.push({ type: 'danger', msg: 'An e-mail template with same locale and name already exists' }) } else if (status == 403) { ctrl.alerts.push({type: 'warning', msg: 'Operation not allowed'}) } else { ctrl.alerts.push({type: 'danger', msg: 'Technical error'}) } }); }; ctrl.edit = function () { $http.put('rs/mailtemplates', ctrl.entry) .success(function (data) { ctrl.entry = data; ctrl.alerts.push({type: 'success', msg: 'Update complete'}); ctrl.convertEntryDates(); }) .error(function (data, status) { if (status == 409) { ctrl.alerts.push({ type: 'danger', msg: 'An e-mail template with same locale and name already exists' }); } else if (status == 403) { ctrl.alerts.push({type: 'warning', msg: 'Operation not allowed'}); } else { ctrl.alerts.push({type: 'danger', msg: 'Technical error'}) } }); }; ctrl.convertEntryDates = function () { // hack for dates returned as timestamp by service ctrl.entry.creationDate = ctrl.entry.creationDate != null ? new Date(ctrl.entry.creationDate) : null; ctrl.entry.updateDate = ctrl.entry.creationDate != null ? new Date(ctrl.entry.creationDate) : null; }; ctrl.exitDetailView = function () { $state.go('^', {}, {reload: true}); }; ctrl.closeAlert = function (index) { ctrl.alerts.splice(index, 1); }; ctrl.findMailTemplate(); }]); app.controller('MailOperationController', ['$http', 'LocalesService', function ($http, LocalesService) { var ctrl = this; ctrl.alerts = []; ctrl.isProcessing = false; ctrl.recipient = null; ctrl.mailTemplateName = null; ctrl.locale = null; ctrl.mailTemplateProperties = {}; ctrl.availableLocales = LocalesService.allLocales(); var testUser = { "id": 5, "login": "<EMAIL>", "password": "<PASSWORD>", "firstname": "John", "lastname": "Doe", "gender": "M.", "phoneNumber": "0101010101", "birthDate": "1982-10-15T23:00:00.000Z", "age": 33, "creationDate": "2015-03-09T21:06:02.000Z", "updateDate": "2015-03-09T21:06:02.000Z", "disabled": false, "activated": true, "preferredLocale": "fr", "newslettersSubscribed": true, "actionToken": "<PASSWORD>" }; var testAdress = { "id": 14, "street": "125 rue de la paix", "city": "Paris", "zipCode": "75001", "firstname": "John", "lastname": "Doe", "gender": "M.", "company": "Fake company", "countryIso3Code": "FRA" }; var testOrder = { "id": 7, "items": [{ "id": 1, "productId": 1, "skuId": 1, "quantity": 1, "price": 10, "displayName": "Fake product", "skuReference": "1234", "presentationImageURI": "http://localhost/fakeimage.jpg" }], "orderDiscounts": [], "status": "PAYMENT_VALIDATED", "creationDate": "2015-02-23T01:54:10.000Z", "updateDate": "2015-02-23T01:54:10.000Z", "price": 22, "transactionId": "450344", "parcelTrackingKey": "Fake parcel tracking ID", "deliveryDate": null, "paymentDate": "2015-02-22T23:00:00.000Z", "deliveryFee": 12.0, "vat": 20.0, "reference": "02232015-7-450344" }; testOrder["billingAddress"] = testAdress; testOrder["deliveryAddress"] = testAdress; testOrder["user"] = testUser; ctrl.closeAlert = function (index) { ctrl.alerts.splice(index, 1); }; ctrl.sendMail = function () { ctrl.isProcessing = true; ctrl.alerts = []; if (ctrl.mailTemplateName == "userRegistration" || ctrl.mailTemplateName == 'userActivation' || ctrl.mailTemplateName == 'userResetPassword') { ctrl.mailTemplateProperties = testUser; } else if (ctrl.mailTemplateName == "orderAccepted" || ctrl.mailTemplateName == 'orderValidated' || ctrl.mailTemplateName == 'orderShipped') { ctrl.mailTemplateProperties = testOrder; } var uri = 'rs/mailtemplates/test/' + ctrl.recipient + '?templateName=' + ctrl.mailTemplateName + '&locale=' + ctrl.locale; $http.post(uri, ctrl.mailTemplateProperties).success(function (orders) { ctrl.isProcessing = false; ctrl.alerts.push({type: 'success', msg: 'Mail has been sent successfully'}); }).error(function (data, status) { ctrl.isProcessing = false; if (status == 404) { ctrl.alerts.push({ type: 'warning', msg: 'No mail template found matching mail template and locale' }); } if (status == 403) { ctrl.alerts.push({type: 'warning', msg: 'Operation not allowed'}); } else { ctrl.alerts.push({type: 'danger', msg: 'Technical error'}); } }); }; }]); })(); <|start_filename|>catalog/src/main/java/org/rembx/jeeshop/catalog/model/CatalogPersistenceUnit.java<|end_filename|> package org.rembx.jeeshop.catalog.model; /** * Created by remi on 25/05/14. */ public interface CatalogPersistenceUnit { public final static String NAME = "Catalog"; } <|start_filename|>catalog/src/main/java/org/rembx/jeeshop/catalog/model/PremisesAddress.java<|end_filename|> package org.rembx.jeeshop.catalog.model; import javax.persistence.*; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; import java.util.Objects; @Entity @XmlType @Table(name = "premises_address") @XmlAccessorType(XmlAccessType.FIELD) public class PremisesAddress { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Size(max = 255) @NotNull @Column(nullable = false, length = 255) private String street; @Column(nullable = false, length = 255) @Size(max = 255) @NotNull private String city; @Column(nullable = false, length = 10) @Size(min = 1, max = 10) @NotNull private String zipCode; @NotNull @Size(min = 3, max = 3) @Column(nullable = false, length = 3) private String countryIso3Code; public PremisesAddress() { } public PremisesAddress(String street, String city, String zipCode, String countryIso3Code) { this.street = street; this.city = city; this.zipCode = zipCode; this.countryIso3Code = countryIso3Code; } public Long getId() { return id; } public String getStreet() { return street; } public void setStreet(String street) { this.street = street; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getZipCode() { return zipCode; } public void setZipCode(String zipCode) { this.zipCode = zipCode; } public String getCountryIso3Code() { return countryIso3Code; } public void setCountryIso3Code(String countryIso3Code) { this.countryIso3Code = countryIso3Code; } public void setId(Long id) { this.id = id; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; PremisesAddress that = (PremisesAddress) o; return Objects.equals(id, that.id) && Objects.equals(street, that.street) && Objects.equals(city, that.city) && Objects.equals(zipCode, that.zipCode) && Objects.equals(countryIso3Code, that.countryIso3Code); } @Override public int hashCode() { return Objects.hash(id, street, city, zipCode, countryIso3Code); } @Override public String toString() { return "PremisesAddress{" + "id=" + id + ", street='" + street + '\'' + ", city='" + city + '\'' + ", zipCode='" + zipCode + '\'' + ", countryIso3Code='" + countryIso3Code + '\'' + '}'; } } <|start_filename|>order/src/test/java/org/rembx/jeeshop/order/test/TestMailTemplate.java<|end_filename|> package org.rembx.jeeshop.order.test; import org.rembx.jeeshop.order.mail.Mails; import org.rembx.jeeshop.user.model.MailTemplate; import org.rembx.jeeshop.user.model.UserPersistenceUnit; import javax.persistence.EntityManager; import javax.persistence.Persistence; /** * MailTemplate test utility */ public class TestMailTemplate { private static TestMailTemplate instance; private static MailTemplate orderConfirmationTpl; public static TestMailTemplate getInstance() { if (instance != null) return instance; EntityManager entityManager = Persistence.createEntityManagerFactory(UserPersistenceUnit.NAME).createEntityManager(); entityManager.getTransaction().begin(); orderConfirmationTpl = new MailTemplate(Mails.orderValidated.name(), "fr_FR", "<html><body>Hello ${gender} ${firstname} ${lastname}. Your order has been registered...</body></html>", "Order Confirmation"); entityManager.persist(orderConfirmationTpl); entityManager.getTransaction().commit(); instance = new TestMailTemplate(); entityManager.close(); return instance; } public MailTemplate orderConfirmationMailTemplate(){ return orderConfirmationTpl; } } <|start_filename|>common/src/main/java/org/rembx/jeeshop/configuration/ConfigurationProducer.java<|end_filename|> package org.rembx.jeeshop.configuration; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.enterprise.inject.Produces; import javax.enterprise.inject.spi.InjectionPoint; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Map; import java.util.Properties; /** * Configuration Producer * <p/> * Produces a value for a given @NamedConfiguration annotated property. * This value is retrieved from a property file named with the lower case class name where this property is declared * <p/> * User: remi */ public class ConfigurationProducer { private final static Logger logger = LoggerFactory.getLogger(ConfigurationProducer.class); private final static String CONFIGURATION_FILE_SUFFIX = ".properties"; /** * Stores every property files associated to classes using NamedConfiguration annotation */ private static final Map<String, Properties> configurations = new HashMap<>(); @Produces @NamedConfiguration String retrieveNamedConfiguration(InjectionPoint injectionPoint) { String configurationFilePath; NamedConfiguration namedConfiguration = injectionPoint.getAnnotated().getAnnotation(NamedConfiguration.class); if (namedConfiguration.value() == null || StringUtils.isEmpty(namedConfiguration.value())) { return null; } if (namedConfiguration.configurationFile() == null || StringUtils.isEmpty(namedConfiguration.configurationFile())) { configurationFilePath = "/" + injectionPoint.getMember().getDeclaringClass().getSimpleName().toLowerCase() + CONFIGURATION_FILE_SUFFIX; } else { configurationFilePath = namedConfiguration.configurationFile(); } Properties properties = loadConfigurationFile(configurationFilePath); return properties.getProperty(namedConfiguration.value()); } private Properties loadConfigurationFile(String configurationFilePath) { if (configurations.get(configurationFilePath) != null) { return configurations.get(configurationFilePath); } logger.debug("Loading property file : {}", configurationFilePath); Properties properties = new Properties(); try (InputStream configurationFile = getClass().getResourceAsStream(configurationFilePath)) { if (configurationFile == null) throw new IllegalStateException("File :" + configurationFilePath + " not found"); properties.load(configurationFile); configurations.put(configurationFilePath,properties); } catch (IOException e) { throw new RuntimeException("Failed to load configuration file: " + configurationFilePath, e); } logger.debug("Property file load successful"); return properties; } } <|start_filename|>user/src/main/java/org/rembx/jeeshop/user/CountryChecker.java<|end_filename|> package org.rembx.jeeshop.user; import org.rembx.jeeshop.configuration.NamedConfiguration; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; import java.util.Arrays; /** * User finder utility */ @ApplicationScoped public class CountryChecker { @Inject @NamedConfiguration(value = "countries.available",configurationFile = "/global.properties") private String availableCountriesStr; private String[] availableCountries; public CountryChecker() { } public CountryChecker(String availableCountries) { this.availableCountriesStr = availableCountries; } public boolean isAvailable(String country){ if (availableCountries == null){ availableCountries = availableCountriesStr.split(","); } return Arrays.asList(availableCountries).contains(country); } } <|start_filename|>media/src/main/java/org/rembx/jeeshop/media/model/Media.java<|end_filename|> package org.rembx.jeeshop.media.model; import javax.persistence.*; import javax.validation.constraints.Size; /** * Created by remi on 20/05/14. */ @Entity public class Media { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Size(max = 255) @Column(nullable = false, length = 255) private String uri; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getUri() { return uri; } public void setUri(String uri) { this.uri = uri; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Media media = (Media) o; if (id != null ? !id.equals(media.id) : media.id != null) return false; if (uri != null ? !uri.equals(media.uri) : media.uri != null) return false; return true; } @Override public int hashCode() { int result = id != null ? id.hashCode() : 0; result = 31 * result + (uri != null ? uri.hashCode() : 0); return result; } } <|start_filename|>user/src/main/java/org/rembx/jeeshop/user/model/MailTemplate.java<|end_filename|> package org.rembx.jeeshop.user.model; import org.rembx.jeeshop.media.model.Media; import javax.json.bind.annotation.JsonbTransient; import javax.persistence.*; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlTransient; import javax.xml.bind.annotation.XmlType; import java.util.Date; import java.util.Set; /** * Newsletter entity */ @Entity @XmlType @XmlAccessorType(XmlAccessType.FIELD) public class MailTemplate { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(nullable = false, length = 100) @NotNull private String name; @Size(max = 25) @Column(length = 25, nullable=true) private String locale; @NotNull @Column(nullable = false) String content; @NotNull @Column(nullable = false) String subject; @ManyToMany @JoinTable(name = "MailTemplate_Media", joinColumns = @JoinColumn(name = "mailTemplateId"), inverseJoinColumns = @JoinColumn(name = "mediaId")) @JsonbTransient Set<Media> medias; @Temporal(TemporalType.TIMESTAMP) private Date creationDate; @Temporal(TemporalType.TIMESTAMP) private Date updateDate; public MailTemplate() { } public MailTemplate(String name, String locale, String content, String subject) { this.name = name; this.locale = locale; this.content = content; this.subject = subject; } @PrePersist public void prePersist() { this.creationDate = new Date(); } @PreUpdate public void preUpdate(){ this.updateDate = new Date(); } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public Set<Media> getMedias() { return medias; } public void setMedias(Set<Media> medias) { this.medias = medias; } public String getLocale() { return locale; } public void setLocale(String locale) { this.locale = locale; } public String getSubject() { return subject; } public void setSubject(String subject) { this.subject = subject; } public Date getCreationDate() { return creationDate; } public void setCreationDate(Date creationDate) { this.creationDate = creationDate; } public Date getUpdateDate() { return updateDate; } public void setUpdateDate(Date updateDate) { this.updateDate = updateDate; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; MailTemplate that = (MailTemplate) o; if (content != null ? !content.equals(that.content) : that.content != null) return false; if (id != null ? !id.equals(that.id) : that.id != null) return false; if (locale != null ? !locale.equals(that.locale) : that.locale != null) return false; if (name != null ? !name.equals(that.name) : that.name != null) return false; if (subject != null ? !subject.equals(that.subject) : that.subject != null) return false; return true; } @Override public int hashCode() { int result = id != null ? id.hashCode() : 0; result = 31 * result + (name != null ? name.hashCode() : 0); result = 31 * result + (locale != null ? locale.hashCode() : 0); result = 31 * result + (content != null ? content.hashCode() : 0); result = 31 * result + (subject != null ? subject.hashCode() : 0); return result; } } <|start_filename|>admin/src/main/webapp/app/css/app.css<|end_filename|> #loaderDiv { position:fixed; top:0; left:0; width:100%; height:100%; z-index:1100; } .ajax-loader { position: absolute; left: 50%; top: 50%; margin-left: -32px; /* -1 * image width / 2 */ margin-top: -32px; /* -1 * image height / 2 */ display: block; } .side_menu_item_title { margin-left:1.5em; } th a{ color: #333; } <|start_filename|>user/src/test/java/org/rembx/jeeshop/user/MailTemplatesCT.java<|end_filename|> package org.rembx.jeeshop.user; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.rembx.jeeshop.mail.Mailer; import org.rembx.jeeshop.rest.WebApplicationException; import org.rembx.jeeshop.user.mail.Mails; import org.rembx.jeeshop.user.model.MailTemplate; import org.rembx.jeeshop.user.model.User; import org.rembx.jeeshop.user.model.UserPersistenceUnit; import org.rembx.jeeshop.user.test.TestMailTemplate; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import javax.ws.rs.core.Response; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; public class MailTemplatesCT { private MailTemplates service; private TestMailTemplate testMailTemplate; private static EntityManagerFactory entityManagerFactory; EntityManager entityManager; private Mailer mailerMock; @BeforeAll public static void beforeClass() { entityManagerFactory = Persistence.createEntityManagerFactory(UserPersistenceUnit.NAME); } @BeforeEach public void setup() { testMailTemplate = TestMailTemplate.getInstance(); entityManager = entityManagerFactory.createEntityManager(); mailerMock = mock(Mailer.class); service = new MailTemplates(entityManager, new MailTemplateFinder(entityManager), mailerMock); } @Test public void findAll_shouldReturnNoneEmptyList() { assertThat(service.findAll(null, null, null, null, null)).isNotEmpty(); } @Test public void findAll_withPagination_shouldReturnNoneEmptyListPaginated() { List<MailTemplate> mailTemplates = service.findAll(null, 0, 1, null, null); assertThat(mailTemplates).isNotEmpty(); assertThat(mailTemplates).containsExactly(testMailTemplate.firstMailTemplate()); } @Test public void findByName_shouldReturnMatchingMailTemplate() { List<MailTemplate> newsletters = service.findAll(testMailTemplate.firstMailTemplate().getName(), null, null, null, null); assertThat(newsletters).containsExactly(testMailTemplate.firstMailTemplate()); } @Test public void find_unknownId_shouldThrowException() throws Exception { try { service.find(999L); fail("should have thrown ex"); } catch (WebApplicationException e) { assertThat(e.getResponse().getStatusInfo()).isEqualTo(Response.Status.NOT_FOUND); } } @Test public void count() { assertThat(service.count()).isGreaterThan(0); } @Test public void find() throws Exception { assertThat(service.find(1L)).isNotNull(); } @Test public void create_shouldPersist() { MailTemplate mailTemplate = new MailTemplate("TestNewsletter", "en_GB", "test content", "Test Subject"); entityManager.getTransaction().begin(); service.create(mailTemplate); entityManager.getTransaction().commit(); assertThat(entityManager.find(MailTemplate.class, mailTemplate.getId())).isNotNull(); entityManager.remove(mailTemplate); } @Test public void create_shouldThrowConflictException_WhenThereIsAlreadyAMailTemplateWithSameLocaleAndName() { MailTemplate mailTemplate = new MailTemplate("Newsletter1", "fr_FR", "test content", "Test Subject"); try { service.create(mailTemplate); fail("Should have thrown exception"); } catch (WebApplicationException e) { assertThat(e.getResponse().getStatusInfo()).isEqualTo(Response.Status.CONFLICT); } } @Test public void modify_ShouldModify() { MailTemplate detachedMailTemplateToModify = new MailTemplate("TestNewsletter2", "fr_FR", "test2 content", "Test2 Subject"); detachedMailTemplateToModify.setId(testMailTemplate.firstMailTemplate().getId()); service.modify(detachedMailTemplateToModify); } @Test public void create_shouldThrowConflictException_WhenThereIsAlreadyAMailTemplateWithSameLocaleAndNameAndDifferentID() { MailTemplate mailTemplate = new MailTemplate(Mails.userRegistration.name(), "fr_FR", "test content", "Test Subject"); mailTemplate.setId(testMailTemplate.firstMailTemplate().getId()); try { service.modify(mailTemplate); fail("Should have thrown exception"); } catch (WebApplicationException e) { assertThat(e.getResponse().getStatusInfo()).isEqualTo(Response.Status.CONFLICT); } } @Test public void modifyUnknown_ShouldThrowNotFoundException() { MailTemplate detachedMailTemplate = new MailTemplate(); detachedMailTemplate.setId(9999L); try { service.modify(detachedMailTemplate); fail("should have thrown ex"); } catch (WebApplicationException e) { assertThat(e.getResponse().getStatusInfo()).isEqualTo(Response.Status.NOT_FOUND); } } @Test public void delete_shouldRemove() { entityManager.getTransaction().begin(); MailTemplate mailTemplate = new MailTemplate("TestNewsletter3", "fr_FR", "test content 3", "Test Subject3"); entityManager.persist(mailTemplate); entityManager.getTransaction().commit(); entityManager.getTransaction().begin(); service.delete(mailTemplate.getId()); entityManager.getTransaction().commit(); assertThat(entityManager.find(MailTemplate.class, mailTemplate.getId())).isNull(); } @Test public void delete_NotExistingEntry_shouldThrowNotFoundEx() { try { entityManager.getTransaction().begin(); service.delete(666L); entityManager.getTransaction().commit(); fail("should have thrown ex"); } catch (WebApplicationException e) { assertThat(e.getResponse().getStatusInfo()).isEqualTo(Response.Status.NOT_FOUND); } } @Test public void sendTestEmail_shouldSendMailFromFTLAndPropertiesToRecipient() throws Exception { String recipient = "<EMAIL>"; User user = new User(); user.setGender("Miss"); user.setFirstname("Jane"); user.setLastname("Doe"); service.sendTestEmail(user, Mails.userRegistration.name(), "fr_FR", recipient); verify(mailerMock).sendMail(testMailTemplate.userRegistrationMailTemplate().getSubject(), recipient, "<html><body>Welcome <NAME></body></html>"); } @Test public void sendTestEmail_shouldThrowNotFoundExWhenNoMailTemplateFoundForGivenParams() throws Exception { try { service.sendTestEmail(null, "unknown", "fr_FR", "<EMAIL>"); } catch (WebApplicationException e) { assertThat(e.getResponse().getStatusInfo()).isEqualTo(Response.Status.NOT_FOUND); return; } fail("Should have thrown NOT_FOUND WebApplicationException"); } } <|start_filename|>order/src/main/java/org/rembx/jeeshop/order/Orders.java<|end_filename|> package org.rembx.jeeshop.order; import io.quarkus.hibernate.orm.PersistenceUnit; import io.quarkus.undertow.runtime.HttpSessionContext; import org.apache.commons.collections.CollectionUtils; import org.rembx.jeeshop.mail.Mailer; import org.rembx.jeeshop.order.model.Order; import org.rembx.jeeshop.order.model.OrderStatus; import org.rembx.jeeshop.rest.WebApplicationException; import org.rembx.jeeshop.user.MailTemplateFinder; import org.rembx.jeeshop.user.UserFinder; import org.rembx.jeeshop.user.model.User; import org.rembx.jeeshop.user.model.UserPersistenceUnit; import javax.annotation.Resource; import javax.annotation.security.RolesAllowed; import javax.enterprise.context.ApplicationScoped; import javax.enterprise.context.RequestScoped; import javax.inject.Inject; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.transaction.Transactional; import javax.validation.constraints.NotNull; import javax.ws.rs.*; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import java.util.List; import static org.rembx.jeeshop.role.JeeshopRoles.*; /** * Orders resource. */ @Path("/rs/orders") @ApplicationScoped public class Orders { private OrderConfiguration orderConfiguration; private EntityManager entityManager; private OrderFinder orderFinder; private UserFinder userFinder; private Mailer mailer; private MailTemplateFinder mailTemplateFinder; private PaymentTransactionEngine paymentTransactionEngine; private PriceEngine priceEngine; Orders(@PersistenceUnit(UserPersistenceUnit.NAME) EntityManager entityManager, OrderFinder orderFinder, UserFinder userFinder, MailTemplateFinder mailTemplateFinder, Mailer mailer, PriceEngine priceEngine, PaymentTransactionEngine paymentTransactionEngine) { this.entityManager = entityManager; this.orderFinder = orderFinder; this.userFinder = userFinder; this.mailTemplateFinder = mailTemplateFinder; this.mailer = mailer; this.priceEngine = priceEngine; this.paymentTransactionEngine = paymentTransactionEngine; } @GET @Path("/{orderId}") @Produces(MediaType.APPLICATION_JSON) @RolesAllowed({ADMIN, ADMIN_READONLY, USER}) public Order find(@Context SecurityContext securityContext, @PathParam("orderId") @NotNull Long orderId, @QueryParam("enhanced") Boolean enhanced) { Order order = entityManager.find(Order.class, orderId); if (securityContext.isUserInRole(USER) && !securityContext.isUserInRole(ADMIN)) { User authenticatedUser = userFinder.findByLogin(securityContext.getUserPrincipal().getName()); if (!order.getUser().equals(authenticatedUser)) { throw new WebApplicationException(Response.Status.UNAUTHORIZED); } } if (enhanced != null && enhanced) { orderFinder.enhanceOrder(order); } checkNotNull(order); return order; } @GET @Path("/") @Produces(MediaType.APPLICATION_JSON) @RolesAllowed({ADMIN, ADMIN_READONLY, USER}) public List<Order> findAll(@Context SecurityContext securityContext, @QueryParam("search") String search, @QueryParam("start") Integer start, @QueryParam("size") Integer size, @QueryParam("orderBy") String orderBy, @QueryParam("isDesc") Boolean isDesc, @QueryParam("status") OrderStatus status, @QueryParam("skuId") Long skuId, @QueryParam("enhanced") Boolean enhanced) { if (securityContext.isUserInRole(USER) && !securityContext.isUserInRole(ADMIN)) { User authenticatedUser = userFinder.findByLogin(securityContext.getUserPrincipal().getName()); return orderFinder.findByUser(authenticatedUser, start, size, orderBy, isDesc, status); } else { return orderFinder.findAll(start, size, orderBy, isDesc, search, status, skuId, enhanced != null ? enhanced : false); } } @POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @RolesAllowed({USER, ADMIN}) public Order create(@Context SecurityContext securityContext, Order order, @QueryParam("userLogin") String userLogin) { checkOrder(order); assignOrderToUser(securityContext, order, userLogin); order.setStatus(OrderStatus.CREATED); priceEngine.computePrice(order); assignOrderToOrderItems(order); entityManager.persist(order); paymentTransactionEngine.processPayment(order); return order; } @PUT @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @RolesAllowed(ADMIN) public Order modify(@NotNull Order order) { Order existingOrder = entityManager.find(Order.class, order.getId()); checkNotNull(existingOrder); order.setUser(existingOrder.getUser()); order.getItems().forEach(orderItem -> orderItem.setOrder(order)); return entityManager.merge(order); } @DELETE @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @RolesAllowed(ADMIN) @Path("/{orderId}") public void delete(@PathParam("orderId") Long orderId) { Order order = entityManager.find(Order.class, orderId); checkNotNull(order); entityManager.remove(order); } @GET @Path("/count") @Produces(MediaType.APPLICATION_JSON) @RolesAllowed({ADMIN, ADMIN_READONLY}) public Long count(@QueryParam("search") String search, @QueryParam("status") OrderStatus status, @QueryParam("skuId") Long skuId) { return orderFinder.countAll(search, status, skuId); } @GET @Path("/fixeddeliveryfee") @Produces(MediaType.APPLICATION_JSON) @RolesAllowed({ADMIN, ADMIN_READONLY}) public Double getFixedDeliveryFee() { if (orderConfiguration != null) { return orderConfiguration.getFixedDeliveryFee(); } return null; } private void assignOrderToUser(SecurityContext securityContext, Order order, String userLogin) { User user; if (securityContext.isUserInRole(USER)) { user = userFinder.findByLogin(securityContext.getUserPrincipal().getName()); order.setUser(user); } if (securityContext.isUserInRole(ADMIN)) { user = userFinder.findByLogin(userLogin); order.setUser(user); } } private void checkNotNull(Order order) { if (order == null) { throw new WebApplicationException(Response.Status.NOT_FOUND); } } private void assignOrderToOrderItems(Order order) { if (CollectionUtils.isEmpty(order.getItems())) return; order.getItems().forEach(orderItem -> { if (orderItem.getId() != null) throw new WebApplicationException(Response.Status.BAD_REQUEST); orderItem.setOrder(order); }); } private void checkOrder(Order order) { // TODO Complete checks on OrderItems, checks skuId and discountId visibility. Check that user does not add too much discount. if (order.getId() != null || (order.getDeliveryAddress() != null && order.getDeliveryAddress().getId() != null) || (order.getBillingAddress() != null && order.getBillingAddress().getId() != null)) { throw new WebApplicationException(Response.Status.BAD_REQUEST); } } } <|start_filename|>catalog/src/main/java/org/rembx/jeeshop/catalog/model/PremisesOpeningSchedules.java<|end_filename|> package org.rembx.jeeshop.catalog.model; import javax.persistence.*; import javax.validation.constraints.NotNull; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; import java.time.DayOfWeek; import java.time.LocalTime; @Entity @XmlType @XmlAccessorType(XmlAccessType.FIELD) @Cacheable public class PremisesOpeningSchedules { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) protected Long id; @ManyToOne(cascade = CascadeType.DETACH, fetch = FetchType.LAZY) private Store store; @Enumerated(EnumType.ORDINAL) @NotNull @Column(nullable = false) DayOfWeek dayOfWeek; @Column LocalTime timeOpen; @Column LocalTime timeClose; public PremisesOpeningSchedules() { } public PremisesOpeningSchedules(Long id) { this.id = id; } public PremisesOpeningSchedules(Store store, DayOfWeek dayOfWeek, LocalTime timeOpen, LocalTime timeClose) { this.store = store; this.dayOfWeek = dayOfWeek; this.timeOpen = timeOpen; this.timeClose = timeClose; } public Store getStore() { return store; } public void setStore(Store store) { this.store = store; } public DayOfWeek getDayOfWeek() { return dayOfWeek; } public void setDayOfWeek(DayOfWeek dayOfWeek) { this.dayOfWeek = dayOfWeek; } public LocalTime getTimeOpen() { return timeOpen; } public void setTimeOpen(LocalTime timeOpen) { this.timeOpen = timeOpen; } public LocalTime getTimeClose() { return timeClose; } public void setTimeClose(LocalTime timeClose) { this.timeClose = timeClose; } } <|start_filename|>common/src/test/java/org/rembx/jeeshop/configuration/ConfigurationProducerCT.java<|end_filename|> package org.rembx.jeeshop.configuration; import org.jboss.weld.environment.se.Weld; import org.jboss.weld.environment.se.WeldContainer; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import javax.inject.Inject; import static org.junit.Assert.*; /** * Injection test using weld container */ public class ConfigurationProducerCT { protected static Weld weld; protected static WeldContainer container; @BeforeClass public static void init() { weld = new Weld(); container = weld.initialize(); } @AfterClass public static void close() { weld.shutdown(); } @Test public void withConfiguredFileProperty_shouldBeInjectedAsConfiguredValue() throws Exception { NamedConfigurationUse injected = container.instance().select(NamedConfigurationUse.class).get(); assertNotNull(injected); assertEquals("dummyHost", injected.getHostName()); assertEquals("dummyTimeout", injected.getTimeout()); } @Test public void withNotConfiguredFileProperty_shouldBeInjectedAsNull() throws Exception { NamedConfigurationUse injected = container.instance().select(NamedConfigurationUse.class).get(); assertNotNull(injected); assertNull(injected.getPort()); } @Test public void withUnknownFile_shouldThrowException() throws Exception { try{ NamedConfigurationWithoutConfigurationFile injected = container.instance().select(NamedConfigurationWithoutConfigurationFile.class).get(); fail(); }catch (IllegalStateException e){ } } } class NamedConfigurationUse { @Inject @NamedConfiguration("host.name") private String hostName; @Inject @NamedConfiguration("toto.toto") private String port; @Inject @NamedConfiguration(value = "timeout", configurationFile = "/namedconfigurationcustom.properties") private String timeout; String getTimeout() { return timeout; } String getPort() { return port; } public String getHostName() { return hostName; } } class NamedConfigurationWithoutConfigurationFile { @Inject @NamedConfiguration("toto.unknown") private String hostName; public String getHostName() { return hostName; } } <|start_filename|>common/src/test/java/org/rembx/jeeshop/util/DateUtilTest.java<|end_filename|> package org.rembx.jeeshop.util; import org.junit.Before; import org.junit.Test; import java.text.SimpleDateFormat; import java.time.LocalDateTime; import java.time.Month; import java.time.ZoneId; import java.time.ZonedDateTime; import java.util.Date; import static org.assertj.core.api.Assertions.assertThat; public class DateUtilTest { @Test public void testDateToLocalDateTime() throws Exception { SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss z"); Date date = sdf.parse("2001.07.04 12:08:56 UTC"); ZonedDateTime localDateTime = DateUtil.dateToLocalDateTime(date); assertThat(ZonedDateTime.of(LocalDateTime.of(2001, Month.JULY, 4, 12, 8, 56), ZoneId.of("Z"))).isEqualTo(localDateTime); } } <|start_filename|>catalog/src/test/java/org/rembx/jeeshop/catalog/CategoriesCT.java<|end_filename|> package org.rembx.jeeshop.catalog; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.rembx.jeeshop.catalog.model.Category; import org.rembx.jeeshop.catalog.model.Product; import org.rembx.jeeshop.catalog.test.CatalogItemCRUDTester; import org.rembx.jeeshop.catalog.test.PresentationTexts; import org.rembx.jeeshop.catalog.test.TestCatalog; import org.rembx.jeeshop.rest.WebApplicationException; import javax.ws.rs.core.Response; import java.util.Date; import java.util.List; import java.util.Locale; import java.util.Set; import static org.rembx.jeeshop.catalog.test.Assertions.*; public class CategoriesCT { private Categories localService; private CatalogItemCRUDTester<Category> tester; @BeforeEach public void setup() { tester = new CatalogItemCRUDTester<>(Category.class); localService = new Categories(tester.getEntityManager(), new CatalogItemFinder(tester.getEntityManager()), null); tester.setService(this.localService); } @Test public void find_withIdOfVisibleCategory_ShouldReturnExpectedCategory() { tester.setAdminUser(); Category category = localService.find(tester.getSecurityContext(), tester.getFixtures().aCategoryWithProducts().getId(), null); assertThat(category).isEqualTo(tester.getFixtures().aCategoryWithProducts()); assertThat(category.isVisible()).isTrue(); } @Test public void find_withIdOfDisableCategory_ShouldThrowForbiddenException() { try { tester.setPublicUser(); localService.find(tester.getSecurityContext(), tester.getFixtures().aDisabledCategory().getId(), null); fail("should have thrown ex"); } catch (WebApplicationException e) { assertThat(e.getResponse().getStatusInfo()).isEqualTo(Response.Status.FORBIDDEN); } } @Test public void find_withIdOfExpiredCategory_ShouldThrowForbiddenException() { try { tester.setPublicUser(); localService.find(tester.getSecurityContext(), tester.getFixtures().anExpiredCategory().getId(), null); fail("should have thrown ex"); } catch (WebApplicationException e) { assertThat(e.getResponse().getStatusInfo()).isEqualTo(Response.Status.FORBIDDEN); } } @Test public void find_idOfCategoryWithPresentation_ShouldReturnExpectedPresentation() { tester.setPublicUser(); Category actual = localService.find(tester.getSecurityContext(), tester.getFixtures().aCategoryWithPresentation().getId(), Locale.ENGLISH.toString()); assertThat(actual).hasLocalizedPresentationShortDescription(Locale.ENGLISH.toString(), PresentationTexts.TEXT_1000); } @Test public void find_idOfCategoryWithPresentation_WithNoLocaleSpecifiedShouldReturnFallbackLocalePresentation() { tester.setPublicUser(); Category category = localService.find(tester.getSecurityContext(), tester.getFixtures().aCategoryWithPresentation().getId(), null); assertThat(category).hasLocalizedPresentationShortDescription(Locale.ENGLISH.toString(), PresentationTexts.TEXT_1000); } @Test public void find_idOfCategoryWithPresentation_WithNotSupportedLocaleSpecifiedShouldReturnFallbackLocalePresentation() { tester.setPublicUser(); Category category = localService.find(tester.getSecurityContext(), tester.getFixtures().aCategoryWithPresentation().getId(), "it_IT"); assertThat(category).hasLocalizedPresentationShortDescription(Locale.ENGLISH.toString(), PresentationTexts.TEXT_1000); } @Test public void findLocales_OfACategoryWithPresentations_shouldReturnExpectedPresentations() { tester.setAdminUser(); Set<String> locales = localService.findPresentationsLocales(tester.getSecurityContext(), tester.getFixtures().aCategoryWithPresentation().getId()); assertThat(locales).containsOnly(Locale.US.toString(), Locale.ENGLISH.toString()); } @Test public void find_withUnknownCategoryId_ShouldThrowNotFoundException() { try { tester.setAdminUser(); localService.find(tester.getSecurityContext(), 9999L, null); fail("should have thrown ex"); } catch (WebApplicationException e) { assertThat(e.getResponse().getStatusInfo()).isEqualTo(Response.Status.NOT_FOUND); } } @Test public void findCategories_shouldReturn404ExWhenCategoryNotFound() { try { tester.setAdminUser(); localService.findChildCategories(tester.getSecurityContext(), 9999L, null); fail("should have thrown ex"); } catch (WebApplicationException e) { assertThat(e.getResponse().getStatusInfo()).isEqualTo(Response.Status.NOT_FOUND); } } @Test public void findCategories_shouldNotReturnExpiredNorDisabledCategories() { tester.setPublicUser(); List<Category> categories = localService.findChildCategories(tester.getSecurityContext(), tester.getFixtures().aRootCategoryWithChildCategories().getId(), null); assertThat(categories).isNotEmpty(); assertThatCategoriesOf(categories).areVisibleChildCategoriesOfARootCategoryWithChildCategories(); } @Test public void findCategories_shouldReturnEmptyListWhenNoChildCategories() { tester.setAdminUser(); List<Category> categories = localService.findChildCategories(tester.getSecurityContext(), tester.getFixtures().aCategoryWithProducts().getId(), null); assertThat(categories).isEmpty(); } @Test public void findProducts_shouldReturn404ExWhenCategoryNotFound() { try { tester.setAdminUser(); localService.findChildProducts(tester.getSecurityContext(), 9999L, null); fail("should have thrown ex"); } catch (WebApplicationException e) { assertThat(e.getResponse().getStatusInfo()).isEqualTo(Response.Status.NOT_FOUND); } } @Test public void findProducts_shouldNotReturnExpiredNorDisabledProducts() { tester.setAdminUser(); List<Product> products = localService.findChildProducts(tester.getSecurityContext(), tester.getFixtures().aCategoryWithProducts().getId(), null); assertThat(products).isNotEmpty(); assertThatProductsOf(products).areVisibleProductsOfAChildCategoryWithProducts(); } @Test public void findProducts_shouldReturnEmptyListWhenNoChildProducts() { tester.setAdminUser(); List<Product> products = localService.findChildProducts(tester.getSecurityContext(), tester.getFixtures().aCategoryWithoutProducts().getId(), null); assertThat(products).isEmpty(); } @Test public void findAll_shouldReturnNoneEmptyList() { assertThat(localService.findAll(null, null, null, null, null, null)).isNotEmpty(); } @Test public void findAll_withPagination_shouldReturnNoneEmptyListPaginated() { List<Category> categories = localService.findAll(null, 0, 1, null, null, null); assertThat(categories).isNotEmpty(); assertThat(categories).hasSize(1); } @Test public void findAll_withIdSearchParam_shouldReturnResultsWithMatchingId() { assertThat(localService.findAll(tester.getFixtures().aCategoryWithoutProducts().getId().toString(), null, null, null, null, null)).containsExactly(tester.getFixtures().aCategoryWithoutProducts()); } @Test public void findAll_withNameSearchParam_shouldReturnResultsWithMatchingName() { assertThat(localService.findAll(tester.getFixtures().aCategoryWithoutProducts().getName(), null, null, null, null, null)).containsExactly(tester.getFixtures().aCategoryWithoutProducts()); } @Test public void modifyCategory_ShouldModifyCategoryAttributesAndPreserveCategoriesWhenNotProvided() { tester.setAdminUser(); Category category = new Category(tester.getFixtures().aRootCategoryWithChildCategories().getId(), "New name"); tester.test_modify(category); assertThat(category.getName()).isEqualTo("New name"); assertThat(category.getChildCategories()).isNotEmpty(); } @Test public void modifyCategory_ShouldModifyCategoryAttributesAndPreserveChildProductsWhenNotProvided() { tester.setAdminUser(); Category category = new Category(tester.getFixtures().aCategoryWithProducts().getId(), "New name"); ; tester.test_modify(category); assertThat(category.getName()).isEqualTo("New name"); assertThat(category.getChildProducts()).isNotEmpty(); } @Test public void modifyUnknownCategory_ShouldThrowNotFoundException() { try { Category category = new Category(9999L, null); localService.modify(tester.getSecurityContext(), category); fail("should have thrown ex"); } catch (WebApplicationException e) { assertThat(e.getResponse().getStatusInfo()).isEqualTo(Response.Status.NOT_FOUND); } } @Test public void countAll() { assertThat(localService.count(null)).isGreaterThan(0); } @Test public void countAll_withUnknownSearchCriteria() { assertThat(localService.count("666")).isEqualTo(0); } @Test public void create_shouldSetupOwner_for_admin() { tester.setAdminUser(); Category category = new Category("name", "description", new Date(), new Date(), false, "<EMAIL>"); category.setOwner(TestCatalog.OWNER); Category actualCategory = tester.test_create(category); assertThat(actualCategory).isNotNull(); assertThat(actualCategory.getOwner()).isEqualTo(TestCatalog.OWNER); } @Test public void create_shouldSetupOwner_for_store_admin() { tester.setStoreAdminUser(); Category category = new Category("name", ""); Category actualCategory = tester.test_create(category); assertThat(actualCategory).isNotNull(); assertThat(actualCategory.getOwner()).isEqualTo(TestCatalog.OWNER); } @Test public void create_withoutOwner_shouldThrow_BadRequestEx_for_admin() { try { tester.setAdminUser(); Category category = new Category("name", "description"); tester.test_create(category); fail("should have thrown ex"); } catch (WebApplicationException e) { assertThat(e.getResponse().getStatusInfo()).isEqualTo(Response.Status.BAD_REQUEST); } } @Test public void delete_shouldRemove() { tester.setStoreAdminUser(); Category category = new Category("Test category", ""); category.setOwner(TestCatalog.OWNER); tester.test_delete(category); assertThat(tester.getEntityManager().find(Category.class, category.getId())).isNull(); } @Test public void delete_NotExistingEntry_shouldThrowNotFoundEx() { try { tester.setStoreAdminUser(); localService.delete(tester.getSecurityContext(), 666L); fail("should have thrown ex"); } catch (WebApplicationException e) { assertThat(e.getResponse().getStatusInfo()).isEqualTo(Response.Status.NOT_FOUND); } } @Test public void delete_NonManagedEntry_shouldThrowForbiddenEx() { try { tester.setStoreAdminUser(); Category category = new Category("Test category", ""); category.setOwner("<EMAIL>"); tester.test_delete(category); fail("should have thrown ex"); } catch (WebApplicationException e) { assertThat(e.getResponse().getStatusInfo()).isEqualTo(Response.Status.FORBIDDEN); } } } <|start_filename|>order/src/test/java/org/rembx/jeeshop/order/test/TestOrder.java<|end_filename|> package org.rembx.jeeshop.order.test; import com.google.common.collect.Sets; import org.rembx.jeeshop.order.model.Order; import org.rembx.jeeshop.order.model.OrderItem; import org.rembx.jeeshop.order.model.OrderStatus; import org.rembx.jeeshop.user.model.Address; import org.rembx.jeeshop.user.model.User; import org.rembx.jeeshop.user.model.UserPersistenceUnit; import org.rembx.jeeshop.user.test.TestUser; import javax.persistence.EntityManager; import javax.persistence.Persistence; /** * Created by remi on 30/11/14. */ public class TestOrder { private static TestOrder instance; private static Order order1; private static Order order2; private static OrderItem orderItem1; private static TestUser testUser; public static TestOrder getInstance() { if (instance != null) return instance; testUser = TestUser.getInstance(); EntityManager entityManager = Persistence.createEntityManagerFactory(UserPersistenceUnit.NAME).createEntityManager(); entityManager.getTransaction().begin(); Address deliveryAddress = new Address("21 Blue street", "Chicago", "78801", "John", "Doe", "M.", null, "FRA"); Address billingAddress = new Address("53 Green street", "Chicago", "78801", "John", "Doe", "M.", null, "FRA"); entityManager.persist(deliveryAddress); entityManager.persist(billingAddress); order1 = new Order(testUser.firstUser(), null, deliveryAddress, billingAddress, OrderStatus.PAYMENT_VALIDATED); orderItem1 = new OrderItem(1L, 1L, 2); orderItem1.setOrder(order1); order1.setItems(Sets.newHashSet(orderItem1)); entityManager.persist(order1); order2 = new Order(testUser.firstUser(), null, null, null, OrderStatus.CREATED); entityManager.persist(order2); entityManager.getTransaction().commit(); instance = new TestOrder(); entityManager.close(); return instance; } public Order firstOrder() { return order1; } public Order secondOrder() { return order2; } public User firstOrdersUser() { return order1.getUser(); } } <|start_filename|>catalog/src/main/java/org/rembx/jeeshop/catalog/DiscountFinder.java<|end_filename|> package org.rembx.jeeshop.catalog; import com.querydsl.jpa.impl.JPAQueryFactory; import io.quarkus.hibernate.orm.PersistenceUnit; import org.rembx.jeeshop.catalog.model.CatalogPersistenceUnit; import org.rembx.jeeshop.catalog.model.Discount; import org.rembx.jeeshop.catalog.model.Discount.ApplicableTo; import javax.enterprise.context.ApplicationScoped; import javax.persistence.EntityManager; import java.util.Date; import java.util.List; import static org.rembx.jeeshop.catalog.model.QDiscount.discount; @ApplicationScoped public class DiscountFinder { private final EntityManager entityManager; DiscountFinder(@PersistenceUnit(CatalogPersistenceUnit.NAME) EntityManager entityManager) { this.entityManager = entityManager; } /* * Returns all discounts visible to end user * @param applicableTo the applicable type of discount * @param locale the locale for results localization * @return the visible discounts: not disabled, with startDate and endDate respectively before and after now and without * voucher code */ public List<Discount> findVisibleDiscounts(ApplicableTo applicableTo, String locale) { Date now = new Date(); List<Discount> results = new JPAQueryFactory(entityManager) .selectFrom(discount).where( discount.disabled.isFalse(), discount.endDate.after(now).or(discount.endDate.isNull()), discount.startDate.before(now).or(discount.startDate.isNull()), discount.applicableTo.eq(applicableTo), discount.voucherCode.isNull() ).fetch(); results.forEach((discount) -> discount.setLocalizedPresentation(locale)); return results; } /* * Returns all discounts eligible for end-user * @param applicableTo the applicable type of discount * @param locale the locale for results localization * @return the visible discounts: not disabled, with startDate and endDate respectively before and after now and without * voucher code, applicable to given number of orders */ public List<Discount> findEligibleOrderDiscounts(String locale, Long completedOrderNumbers) { Date now = new Date(); List<Discount> results = new JPAQueryFactory(entityManager) .selectFrom(discount).where( discount.disabled.isFalse(), discount.endDate.after(now).or(discount.endDate.isNull()), discount.startDate.before(now).or(discount.startDate.isNull()), discount.applicableTo.eq(ApplicableTo.ORDER), discount.triggerRule.ne(Discount.Trigger.ORDER_NUMBER).or( discount.triggerValue.eq(completedOrderNumbers.doubleValue() + 1) ), discount.voucherCode.isNull() ) .fetch(); results.forEach((discount) -> discount.setLocalizedPresentation(locale)); return results; } } <|start_filename|>user/src/main/java/org/rembx/jeeshop/order/model/Order.java<|end_filename|> package org.rembx.jeeshop.order.model; import org.rembx.jeeshop.user.model.Address; import org.rembx.jeeshop.user.model.User; import javax.persistence.*; import javax.validation.constraints.NotNull; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Set; /** * Order entity */ @Entity @Table(name = "Orders") @XmlRootElement @XmlAccessorType(XmlAccessType.FIELD) public class Order { public static final String ORDER_REF_SEPARATOR = "-"; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @ManyToOne @NotNull User user; @OneToMany(cascade = CascadeType.ALL, mappedBy = "order", fetch = FetchType.EAGER) Set<OrderItem> items; @ElementCollection (fetch = FetchType.EAGER) @CollectionTable(name = "OrderDiscount", joinColumns = @JoinColumn(name = "order_id")) Set<OrderDiscount> orderDiscounts; @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER) Address deliveryAddress; @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER) Address billingAddress; @Enumerated(EnumType.STRING) @Column(nullable = false,length = 30) private OrderStatus status; @Temporal(TemporalType.TIMESTAMP) @Column(nullable = false) private Date creationDate; @Temporal(TemporalType.TIMESTAMP) private Date updateDate; Double price; @Column(length = 50) private String transactionId; @Column(length = 50) private String parcelTrackingKey; @Temporal(TemporalType.TIMESTAMP) private Date deliveryDate; @Temporal(TemporalType.TIMESTAMP) private Date paymentDate; // Transient properties @Transient PaymentInfo paymentInfo; // Used for payment systems such as SIPS @Transient private Double deliveryFee; @Transient private Double vat; @Transient private String reference; public Order() { } public Order( Set<OrderItem> items, Address deliveryAddress, Address billingAddress) { this.items = items; this.deliveryAddress = deliveryAddress; this.billingAddress = billingAddress; } public Order(User user, Set<OrderItem> items, Address deliveryAddress, Address billingAddress, OrderStatus status) { this.user = user; this.items = items; this.deliveryAddress = deliveryAddress; this.billingAddress = billingAddress; this.status = status; } @PrePersist public void prePersist() { final Date date = new Date(); this.creationDate = date; this.updateDate = date; } @PreUpdate public void preUpdate(){ this.updateDate = new Date(); } @PostLoad @PostPersist @PostUpdate public void computeOrderReference(){ SimpleDateFormat sdf = new SimpleDateFormat("MMddyyyy"); reference = sdf.format(creationDate)+ORDER_REF_SEPARATOR+id; if (transactionId != null){ reference += ORDER_REF_SEPARATOR +transactionId; } } public PaymentInfo getPaymentInfo() { return paymentInfo; } public void setPaymentInfo(PaymentInfo paymentInfo) { this.paymentInfo = paymentInfo; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } public Address getDeliveryAddress() { return deliveryAddress; } public void setDeliveryAddress(Address deliveryAddress) { this.deliveryAddress = deliveryAddress; } public Address getBillingAddress() { return billingAddress; } public void setBillingAddress(Address billingAddress) { this.billingAddress = billingAddress; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public OrderStatus getStatus() { return status; } public void setStatus(OrderStatus status) { this.status = status; } public Date getCreationDate() { return creationDate; } public void setCreationDate(Date creationDate) { this.creationDate = creationDate; } public Date getUpdateDate() { return updateDate; } public Double getPrice() { return price; } public void setPrice(Double price) { this.price = price; } public void setUpdateDate(Date updateDate) { this.updateDate = updateDate; } public String getTransactionId() { return transactionId; } public void setTransactionId(String transactionId) { this.transactionId = transactionId; } public String getParcelTrackingKey() { return parcelTrackingKey; } public void setParcelTrackingKey(String parcelTrackingKey) { this.parcelTrackingKey = parcelTrackingKey; } public Date getDeliveryDate() { return deliveryDate; } public void setDeliveryDate(Date deliveryDate) { this.deliveryDate = deliveryDate; } public Date getPaymentDate() { return paymentDate; } public void setPaymentDate(Date paymentDate) { this.paymentDate = paymentDate; } public Set<OrderItem> getItems() { return items; } public void setItems(Set<OrderItem> items) { this.items = items; } public Set<OrderDiscount> getOrderDiscounts() { return orderDiscounts; } public void setOrderDiscounts(Set<OrderDiscount> orderDiscounts) { this.orderDiscounts = orderDiscounts; } public Double getDeliveryFee() { return deliveryFee; } public void setDeliveryFee(Double deliveryFee) { this.deliveryFee = deliveryFee; } public String getReference() { return reference; } public void setReference(String reference) { this.reference = reference; } public Double getVat() { return vat; } public void setVat(Double vat) { this.vat = vat; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Order order = (Order) o; if (id != null ? !id.equals(order.id) : order.id != null) return false; if (parcelTrackingKey != null ? !parcelTrackingKey.equals(order.parcelTrackingKey) : order.parcelTrackingKey != null) return false; if (price != null ? !price.equals(order.price) : order.price != null) return false; if (reference != null ? !reference.equals(order.reference) : order.reference != null) return false; if (status != order.status) return false; if (transactionId != null ? !transactionId.equals(order.transactionId) : order.transactionId != null) return false; return true; } @Override public int hashCode() { int result = id != null ? id.hashCode() : 0; result = 31 * result + (status != null ? status.hashCode() : 0); result = 31 * result + (price != null ? price.hashCode() : 0); result = 31 * result + (transactionId != null ? transactionId.hashCode() : 0); result = 31 * result + (parcelTrackingKey != null ? parcelTrackingKey.hashCode() : 0); result = 31 * result + (reference != null ? reference.hashCode() : 0); return result; } @Override public String toString() { return "Order{" + "id=" + id + ", status=" + status + ", price=" + price + ", transactionId='" + transactionId + '\'' + ", parcelTrackingKey='" + parcelTrackingKey + '\'' + ", deliveryFee=" + deliveryFee + ", reference='" + reference + '\'' + '}'; } } <|start_filename|>user/src/main/java/org/rembx/jeeshop/user/model/Phone.java<|end_filename|> package org.rembx.jeeshop.user.model; import javax.validation.Constraint; import javax.validation.Payload; import javax.validation.ReportAsSingleViolation; import javax.validation.constraints.NotNull; import javax.validation.constraints.Pattern; import javax.validation.constraints.Size; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.RetentionPolicy.RUNTIME; @Size(max = 15) @Pattern(regexp = "\\+?[0-9\\s]+") @ReportAsSingleViolation @Target({METHOD, FIELD}) @Retention(RUNTIME) @Documented public @interface Phone { // ====================================== // = Attributes = // ====================================== String message() default "phone"; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; } <|start_filename|>user/src/main/java/org/rembx/jeeshop/order/model/OrderItem.java<|end_filename|> package org.rembx.jeeshop.order.model; import javax.json.bind.annotation.JsonbTransient; import javax.persistence.*; import javax.validation.constraints.NotNull; import javax.xml.bind.annotation.*; import java.net.URI; /** * Order item. * Represents a stock unit price and its ordered quantity */ @Entity @XmlAccessorType(XmlAccessType.FIELD) public class OrderItem { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @ManyToOne @JsonbTransient private Order order; @NotNull @Column(name = "product_id") private Long productId; @NotNull @Column(name = "sku_id") private Long skuId; @NotNull @Column(nullable = false) private Integer quantity; private Double price; // Transient computed properties @Transient private String displayName; @Transient private String skuReference; @Transient private String presentationImageURI; public OrderItem() { } public OrderItem(Long skuId, Long productId, Integer quantity) { this.skuId = skuId; this.productId = productId; this.quantity = quantity; } public Integer getQuantity() { return quantity; } public void setQuantity(Integer quantity) { this.quantity = quantity; } public Long getSkuId() { return skuId; } public void setSkuId(Long skuId) { this.skuId = skuId; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Order getOrder() { return order; } public void setOrder(Order order) { this.order = order; } public Long getProductId() { return productId; } public void setProductId(Long productId) { this.productId = productId; } public String getDisplayName() { return displayName; } public void setDisplayName(String displayName) { this.displayName = displayName; } public Double getPrice() { return price; } public void setPrice(Double price) { this.price = price; } public String getPresentationImageURI() { return presentationImageURI; } public void setPresentationImageURI(String presentationImageURI) { this.presentationImageURI = presentationImageURI; } public String getSkuReference() { return skuReference; } public void setSkuReference(String skuReference) { this.skuReference = skuReference; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; OrderItem orderItem = (OrderItem) o; if (displayName != null ? !displayName.equals(orderItem.displayName) : orderItem.displayName != null) return false; if (id != null ? !id.equals(orderItem.id) : orderItem.id != null) return false; if (presentationImageURI != null ? !presentationImageURI.equals(orderItem.presentationImageURI) : orderItem.presentationImageURI != null) return false; if (price != null ? !price.equals(orderItem.price) : orderItem.price != null) return false; if (productId != null ? !productId.equals(orderItem.productId) : orderItem.productId != null) return false; if (quantity != null ? !quantity.equals(orderItem.quantity) : orderItem.quantity != null) return false; if (skuId != null ? !skuId.equals(orderItem.skuId) : orderItem.skuId != null) return false; return true; } @Override public int hashCode() { int result = id != null ? id.hashCode() : 0; result = 31 * result + (productId != null ? productId.hashCode() : 0); result = 31 * result + (skuId != null ? skuId.hashCode() : 0); result = 31 * result + (quantity != null ? quantity.hashCode() : 0); result = 31 * result + (displayName != null ? displayName.hashCode() : 0); result = 31 * result + (presentationImageURI != null ? presentationImageURI.hashCode() : 0); result = 31 * result + (price != null ? price.hashCode() : 0); return result; } @Override public String toString() { return "OrderItem{" + "id=" + id + ", productId=" + productId + ", skuId=" + skuId + ", quantity=" + quantity + ", price=" + price + ", displayName='" + displayName + '\'' + ", skuReference='" + skuReference + '\'' + ", presentationImageURI='" + presentationImageURI + '\'' + '}'; } } <|start_filename|>catalog/src/test/java/org/rembx/jeeshop/catalog/CatalogsCT.java<|end_filename|> package org.rembx.jeeshop.catalog; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.rembx.jeeshop.catalog.model.Catalog; import org.rembx.jeeshop.catalog.model.Category; import org.rembx.jeeshop.catalog.test.CatalogItemCRUDTester; import org.rembx.jeeshop.catalog.test.TestCatalog; import org.rembx.jeeshop.rest.WebApplicationException; import org.rembx.jeeshop.role.JeeshopRoles; import javax.ws.rs.core.Response; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; import static org.mockito.Mockito.when; import static org.rembx.jeeshop.catalog.test.Assertions.assertThatCategoriesOf; public class CatalogsCT { private Catalogs localService; private CatalogItemCRUDTester<Catalog> tester; @BeforeEach public void setupClass() { tester = new CatalogItemCRUDTester<>(Catalog.class); this.localService = new Catalogs(tester.getEntityManager(), new CatalogItemFinder(tester.getEntityManager()), null); tester.setService(this.localService); } @Test public void findCategories_shouldReturn404ExWhenCatalogNotFound() { try { localService.findCategories(null, 9999L, null); fail("should have thrown ex"); } catch (WebApplicationException e) { assertThat(e.getResponse().getStatusInfo()).isEqualTo(Response.Status.NOT_FOUND); } } @Test public void findCategories_shouldReturnEmptyListWhenCatalogIsEmpty() { List<Category> categories = localService.findCategories(null, tester.getFixtures().getEmptyCatalogId(), null); assertThat(categories).isEmpty(); } @Test public void findCategories_shouldNotReturnExpiredNorDisabledRootCategories() { when(tester.getSecurityContext().isUserInRole(JeeshopRoles.ADMIN)).thenReturn(false); when(tester.getSecurityContext().isUserInRole(JeeshopRoles.STORE_ADMIN)).thenReturn(false); List<Category> categories = localService.findCategories(tester.getSecurityContext(), tester.getFixtures().getCatalogId(), null); assertThatCategoriesOf(categories).areVisibleRootCategories(); } @Test public void findAll_shouldReturnNoneEmptyList() { assertThat(localService.findAll(null, null, null, null, null, null)).isNotEmpty(); } @Test public void findAll_withPagination_shouldReturnNoneEmptyListPaginated() { List<Catalog> catalogs = localService.findAll(null, 0, 1, null, null, null); assertThat(catalogs).isNotEmpty(); assertThat(catalogs).hasSize(1); } @Test public void findAll_withIdSearchParam_shouldReturnResultsWithMatchingId() { assertThat(localService.findAll(tester.getFixtures().getCatalogId().toString(), null, null, null, null, null)).containsExactly(TestCatalog.getCatalog()); } @Test public void findAll_withNameSearchParam_shouldReturnResultsWithMatchingName() { assertThat(localService.findAll(TestCatalog.getCatalog().getName(), null, null, null, null, null)).containsExactly(TestCatalog.getCatalog()); } @Test public void find_withIdOfVisibleCatalog_ShouldReturnExpectedCatalog() { tester.setStoreAdminUser(); Catalog catalog = localService.find(tester.getSecurityContext(), tester.getFixtures().getCatalogId(), null); assertThat(catalog).isNotNull(); assertThat(catalog.isVisible()).isTrue(); } @Test public void modifyCatalog_ShouldModifyCatalogAttributesAndPreserveRootCategoriesWhenNotProvided() { tester.setStoreAdminUser(); Catalog detachedCatalogToModify = new Catalog(2L, "New name"); tester.test_modify(detachedCatalogToModify); assertThat(detachedCatalogToModify.getName()).isEqualTo("New name"); assertThat(detachedCatalogToModify.getRootCategories()).isNotEmpty(); } @Test public void modifyUnknownCatalog_ShouldThrowNotFoundException() { tester.setStoreAdminUser(); Catalog detachedCatalogToModify = new Catalog(9999L, null); try { tester.test_modify(detachedCatalogToModify); fail("should have thrown ex"); } catch (WebApplicationException e) { assertThat(e.getResponse().getStatusInfo()).isEqualTo(Response.Status.NOT_FOUND); } } @Test public void modifyNonManagedCatalog_ShouldThrowForbiddenException() { tester.setSAnotherStoreAdminUser(); Catalog detachedCatalogToModify = new Catalog(1L, "name"); try { tester.test_modify(detachedCatalogToModify); fail("should have thrown ex"); } catch (WebApplicationException e) { assertThat(e.getResponse().getStatusInfo()).isEqualTo(Response.Status.FORBIDDEN); } } @Test public void countAll() { assertThat(localService.count(null)).isGreaterThan(0); } @Test public void countAll_withUnknownSearchCriteria() { assertThat(localService.count("666")).isEqualTo(0); } @Test public void create_shouldSetupOwner_for_admin() { tester.setAdminUser(); Catalog catalog = new Catalog("Catalog"); catalog.setOwner(TestCatalog.OWNER); Catalog actualCatalog = tester.test_create(catalog); assertThat(actualCatalog).isNotNull(); assertThat(actualCatalog.getOwner()).isEqualTo(TestCatalog.OWNER); } @Test public void create_shouldThrowBadRequest_whenOwnerIsNull_for_admin() { tester.setAdminUser(); Catalog catalog = new Catalog("Catalog"); try { tester.test_create(catalog); fail("should have thrown an exception"); } catch (WebApplicationException e) { assertThat(e.getResponse().getStatusInfo()).isEqualTo(Response.Status.BAD_REQUEST); } } @Test public void create_shouldSetupOwner_for_store_admin() { tester.setStoreAdminUser(); Catalog catalog = new Catalog("Catalog"); Catalog actualCatalog = tester.test_create(catalog); assertThat(actualCatalog).isNotNull(); assertThat(actualCatalog.getOwner()).isEqualTo(TestCatalog.OWNER); } @Test public void delete_shouldRemove() { tester.setStoreAdminUser(); Catalog catalog = new Catalog("Test Catalog"); catalog.setOwner(TestCatalog.OWNER); tester.test_delete(catalog); assertThat(tester.getEntityManager().find(Catalog.class, catalog.getId())).isNull(); } @Test public void delete_shouldThrowForbidden_for_store_admin() { try { tester.setStoreAdminUser(); Catalog catalog = new Catalog("catalog"); catalog.setOwner("<EMAIL>"); tester.test_delete(catalog); fail("Should have throw an exception"); } catch (WebApplicationException e) { assertThat(e.getResponse().getStatusInfo()).isEqualTo(Response.Status.FORBIDDEN); } } @Test public void delete_NotExistingEntry_shouldThrowNotFoundEx() { try { tester.setStoreAdminUser(); localService.delete(tester.getSecurityContext(), 666L); fail("should have thrown ex"); } catch (WebApplicationException e) { assertThat(e.getResponse().getStatusInfo()).isEqualTo(Response.Status.NOT_FOUND); } } } <|start_filename|>user/src/main/java/org/rembx/jeeshop/user/RoleFinder.java<|end_filename|> package org.rembx.jeeshop.user; import com.querydsl.jpa.impl.JPAQueryFactory; import io.quarkus.hibernate.orm.PersistenceUnit; import org.rembx.jeeshop.user.model.Role; import org.rembx.jeeshop.user.model.RoleName; import org.rembx.jeeshop.user.model.UserPersistenceUnit; import javax.enterprise.context.ApplicationScoped; import javax.enterprise.context.RequestScoped; import javax.persistence.EntityManager; import static org.rembx.jeeshop.user.model.QRole.role; /** * User finder utility */ @ApplicationScoped public class RoleFinder { private EntityManager entityManager; RoleFinder(@PersistenceUnit(UserPersistenceUnit.NAME) EntityManager entityManager) { this.entityManager = entityManager; } public Role findByName(RoleName name) { return new JPAQueryFactory(entityManager) .selectFrom(role).where( role.name.eq(name)) .fetchOne(); } } <|start_filename|>order/src/main/java/org/rembx/jeeshop/order/PriceEngineImpl.java<|end_filename|> package org.rembx.jeeshop.order; import io.quarkus.arc.DefaultBean; import io.quarkus.hibernate.orm.PersistenceUnit; import org.apache.commons.collections.CollectionUtils; import org.rembx.jeeshop.catalog.DiscountFinder; import org.rembx.jeeshop.catalog.model.CatalogPersistenceUnit; import org.rembx.jeeshop.catalog.model.Discount; import org.rembx.jeeshop.catalog.model.SKU; import org.rembx.jeeshop.order.model.Order; import org.rembx.jeeshop.order.model.OrderDiscount; import org.rembx.jeeshop.order.model.OrderItem; import javax.enterprise.context.ApplicationScoped; import javax.enterprise.context.RequestScoped; import javax.enterprise.inject.Default; import javax.inject.Inject; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import java.util.HashSet; import java.util.List; /** * Order price engine * Computes order's price and updates Order's properties */ @ApplicationScoped @Default public class PriceEngineImpl implements PriceEngine { private EntityManager entityManager; private OrderConfiguration orderConfiguration; private DiscountFinder discountFinder; private OrderFinder orderFinder; PriceEngineImpl(@PersistenceUnit(CatalogPersistenceUnit.NAME) EntityManager entityManager, OrderConfiguration orderConfiguration, OrderFinder orderFinder, DiscountFinder discountFinder) { this.entityManager = entityManager; this.orderConfiguration = orderConfiguration; this.orderFinder = orderFinder; this.discountFinder = discountFinder; } @Override public void computePrice(Order order) { if (CollectionUtils.isEmpty(order.getItems())){ throw new IllegalStateException("Order items list is empty "+order); } Double price = 0.0; for (OrderItem orderItem : order.getItems()){ SKU sku = entityManager.find(SKU.class,(orderItem).getSkuId()); price += (sku.getPrice()*(orderItem).getQuantity()); orderItem.setPrice(sku.getPrice()); } final Double fixedDeliveryFee = orderConfiguration.getFixedDeliveryFee(); price = applyEligibleDiscounts(order, price); if (fixedDeliveryFee != null){ price += fixedDeliveryFee; order.setDeliveryFee(fixedDeliveryFee); } order.setPrice(price); } private Double applyEligibleDiscounts(Order order, Double price) { double originalPrice = price; Long userCompletedOrders = orderFinder.countUserCompletedOrders(order.getUser()); List<Discount> userEligibleOrderDiscounts = discountFinder.findEligibleOrderDiscounts(null,userCompletedOrders); if (userEligibleOrderDiscounts == null) { return price; } if (order.getOrderDiscounts() == null){ order.setOrderDiscounts(new HashSet<>()); } for (Discount discount : userEligibleOrderDiscounts){ if (discount.isEligible(originalPrice)){ price = discount.processDiscount(price, originalPrice); order.getOrderDiscounts().add(new OrderDiscount(discount.getId(),discount.getDiscountValue())); } } return price; } } <|start_filename|>catalog/src/main/java/org/rembx/jeeshop/catalog/model/CatalogItem.java<|end_filename|> package org.rembx.jeeshop.catalog.model; import javax.json.bind.annotation.JsonbTransient; import javax.persistence.*; import javax.validation.constraints.Email; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import javax.xml.bind.annotation.XmlTransient; import java.text.SimpleDateFormat; import java.time.ZonedDateTime; import java.util.*; import static org.rembx.jeeshop.util.DateUtil.dateToLocalDateTime; import static org.rembx.jeeshop.util.LocaleUtil.FALLBACK; import static org.rembx.jeeshop.util.LocaleUtil.getLocaleCode; /** * Parent class of all catalog node types * Group common properties used by catalog node elements */ @MappedSuperclass @Inheritance(strategy = InheritanceType.JOINED) public abstract class CatalogItem { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) protected Long id; /** * Technical name */ @Column(nullable = false, length = 50) @NotNull @Size(max = 50) protected String name; /** * Technical description */ @Size(max = 255) @Column(length = 255) protected String description; /** * When true, entity is disabled, and not visible by end customer */ protected Boolean disabled; /** * When defined, entity is not visible when current date is lower than it */ @Temporal(TemporalType.TIMESTAMP) protected Date startDate; /** * When defined, entity is not visible when current date is greater than it */ @Temporal(TemporalType.TIMESTAMP) protected Date endDate; /** * True when entity is visible */ @Transient protected boolean visible; @ManyToMany(cascade = {CascadeType.PERSIST,CascadeType.REMOVE, CascadeType.MERGE}) @JoinTable(joinColumns = @JoinColumn(name = "catalogItemId", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "presentationId")) @MapKey(name = "locale") @JsonbTransient private Map<String, Presentation> presentationByLocale; @Transient private Presentation localizedPresentation; @Email @NotNull @Column(nullable = false, length = 100) String owner; public CatalogItem() { } @PrePersist @PreUpdate protected void computeDisabled() { if (disabled == null) { disabled = false; } } @PostLoad @PostPersist @PostUpdate protected void computeIsVisible() { ZonedDateTime now = ZonedDateTime.now(); if (this.isDisabled() || (endDate != null && dateToLocalDateTime(endDate).isBefore(now)) || (startDate != null && dateToLocalDateTime(startDate).isAfter(now))) { visible = false; } else { visible = true; } } public void setLocalizedPresentation(String locale) { // TODO missing test!! and Fallback Presentation localizedPresentation; if (presentationByLocale == null || presentationByLocale.size()==0){ return; } localizedPresentation = presentationByLocale.get(getLocaleCode(locale)); if (localizedPresentation == null && locale != null){ String [] splitted = locale.split("_"); if (splitted.length > 1){ localizedPresentation = presentationByLocale.get(getLocaleCode(splitted[0])); } } if (localizedPresentation == null && presentationByLocale.get(FALLBACK.toString()) != null) { localizedPresentation = presentationByLocale.get(FALLBACK.toString()); } setLocalizedPresentation(localizedPresentation); } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Boolean isDisabled() { return disabled; } public void setDisabled(Boolean disabled) { this.disabled = disabled; } public Date getStartDate() { return startDate; } public void setStartDate(Date startDate) { this.startDate = startDate; } public Date getEndDate() { return endDate; } public void setEndDate(Date endDate) { this.endDate = endDate; } public boolean isVisible() { return visible; } public Presentation getLocalizedPresentation() { return localizedPresentation; } public void setLocalizedPresentation(Presentation localizedPresentation) { this.localizedPresentation = localizedPresentation; } public Map<String, Presentation> getPresentationByLocale() { return presentationByLocale; } public void setPresentationByLocale(Map<String, Presentation> presentationByLocale) { this.presentationByLocale = presentationByLocale; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; CatalogItem that = (CatalogItem) o; if (description != null ? !description.equals(that.description) : that.description != null) return false; if (disabled != null ? !disabled.equals(that.disabled) : that.disabled != null) return false; if (endDate != null ? !endDate.equals(that.endDate) : that.endDate != null) return false; if (id != null ? !id.equals(that.id) : that.id != null) return false; if (name != null ? !name.equals(that.name) : that.name != null) return false; if (startDate != null ? !startDate.equals(that.startDate) : that.startDate != null) return false; return true; } @Override public int hashCode() { int result = id != null ? id.hashCode() : 0; result = 31 * result + (name != null ? name.hashCode() : 0); result = 31 * result + (description != null ? description.hashCode() : 0); result = 31 * result + (disabled != null ? disabled.hashCode() : 0); result = 31 * result + (startDate != null ? startDate.hashCode() : 0); result = 31 * result + (endDate != null ? endDate.hashCode() : 0); return result; } @Override public String toString() { return "CatalogItem{" + "id=" + id + ", name='" + name + '\'' + ", description='" + description + '\'' + ", disabled=" + disabled + ", startDate=" + startDate + ", endDate=" + endDate + '}'; } static public void main(String[] args) { Locale[] availableLocales = SimpleDateFormat.getAvailableLocales(); List<Locale> list = new ArrayList<Locale>(Arrays.asList(availableLocales)); list.remove(0); TreeSet<String> set = new TreeSet<>(); int localeLength = 0; for (Locale a : list) { if (a.toString().length()>localeLength) localeLength = a.toString().length(); set.add("{displayName:\"" + a.getDisplayName(Locale.ENGLISH) + "\"," + "name:\"" + a.toString() + "\"},"); } System.out.println(localeLength); String buff = ""; for (String i : set){ ; buff += i; if (buff.length()>160){ System.out.println(buff); buff =""; } } } public String getOwner() { return owner; } public void setOwner(String owner) { this.owner = owner; } } <|start_filename|>catalog/src/test/java/org/rembx/jeeshop/catalog/DiscountsCT.java<|end_filename|> package org.rembx.jeeshop.catalog; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.rembx.jeeshop.catalog.model.Discount; import org.rembx.jeeshop.catalog.test.CatalogItemCRUDTester; import org.rembx.jeeshop.catalog.test.TestCatalog; import org.rembx.jeeshop.rest.WebApplicationException; import javax.ws.rs.core.Response; import java.util.List; import static org.assertj.core.api.Assertions.fail; import static org.rembx.jeeshop.catalog.model.Discount.ApplicableTo.ORDER; import static org.rembx.jeeshop.catalog.model.Discount.Trigger.AMOUNT; import static org.rembx.jeeshop.catalog.model.Discount.Trigger.QUANTITY; import static org.rembx.jeeshop.catalog.model.Discount.Type.DISCOUNT_RATE; import static org.rembx.jeeshop.catalog.test.Assertions.assertThat; public class DiscountsCT { private Discounts localService; private CatalogItemCRUDTester<Discount> tester; @BeforeEach public void setup() { this.tester = new CatalogItemCRUDTester<>(Discount.class); localService = new Discounts(tester.getEntityManager(), new CatalogItemFinder(tester.getEntityManager()), null, new DiscountFinder(tester.getEntityManager())); this.tester.setService(this.localService); } @Test public void find_withIdOfVisibleDiscount_ShouldReturnExpectedDiscount() { Discount catalogItem = localService.find(tester.getSecurityContext(), tester.getFixtures().aVisibleDisount().getId(), null); assertThat(catalogItem).isEqualTo(tester.getFixtures().aVisibleDisount()); assertThat(catalogItem.isVisible()).isTrue(); } @Test public void findAll_shouldReturnNoneEmptyList() { assertThat(localService.findAll(null, null, null, null, null, null)).isNotEmpty(); } @Test public void findAll_withPagination_shouldReturnNoneEmptyListPaginated() { List<Discount> discounts = localService.findAll(null, 0, 1, null, null, null); assertThat(discounts).isNotEmpty(); assertThat(discounts).hasSize(1); } @Test public void findAll_withIdSearchParam_shouldReturnResultsWithMatchingId() { assertThat(localService.findAll(tester.getFixtures().aVisibleDisount().getId().toString(), null, null, null, null, null)).containsExactly(tester.getFixtures().aVisibleDisount()); } @Test public void findAll_withNameSearchParam_shouldReturnResultsWithMatchingName() { assertThat(localService.findAll(tester.getFixtures().aVisibleDisount().getName(), null, null, null, null, null)).containsExactly(tester.getFixtures().aVisibleDisount()); } @Test public void modifyUnknownDiscount_ShouldThrowNotFoundException() { Discount detachedDiscountToModify = new Discount(9999L); try { localService.modify(tester.getSecurityContext(), detachedDiscountToModify); fail("should have thrown ex"); } catch (WebApplicationException e) { assertThat(e.getResponse().getStatusInfo()).isEqualTo(Response.Status.NOT_FOUND); } } @Test public void countAll() { assertThat(localService.count(null)).isGreaterThan(0); } @Test public void countAll_withUnknownSearchCriteria() { assertThat(localService.count("666")).isEqualTo(0); } @Test public void create_shouldPersist_for_admin_user() { tester.setAdminUser(); Discount discount = new Discount("discount777", "a discount", ORDER, DISCOUNT_RATE, AMOUNT, null, 0.1, 2.0, 1, true, null, null, false, "<EMAIL>"); Discount createdDiscount = tester.test_create(discount); assertThat(createdDiscount).isNotNull(); assertThat(createdDiscount.getOwner()).isEqualTo("<EMAIL>"); } @Test public void delete_shouldRemove_for_admin() { tester.setAdminUser(); Discount discount = new Discount("discount888", "a discount", ORDER, DISCOUNT_RATE, QUANTITY, null, 0.1, 2.0, 1, true, null, null, false, "<EMAIL>"); tester.test_delete(discount); assertThat(tester.getEntityManager().find(Discount.class, discount.getId())).isNull(); } @Test public void delete_shouldRemove_for_store_admin() { tester.setStoreAdminUser(); Discount discount = new Discount("discount888", "a discount", ORDER, DISCOUNT_RATE, QUANTITY, null, 0.1, 2.0, 1, true, null, null, false, TestCatalog.OWNER); tester.test_delete(discount); assertThat(tester.getEntityManager().find(Discount.class, discount.getId())).isNull(); } @Test public void delete_shouldThrowForbiddenException_for_store_admin() { try { tester.setStoreAdminUser(); Discount discount = new Discount("discount888", "a discount", ORDER, DISCOUNT_RATE, QUANTITY, null, 0.1, 2.0, 1, true, null, null, false, "<EMAIL>"); tester.test_delete(discount); fail("Should have throw an exception"); } catch (WebApplicationException e) { assertThat(e.getResponse().getStatusInfo()).isEqualTo(Response.Status.FORBIDDEN); } } @Test public void delete_NotExistingEntry_shouldThrowNotFoundEx() { try { tester.setAdminUser(); localService.delete(tester.getSecurityContext(), 666L); fail("should have thrown ex"); } catch (WebApplicationException e) { assertThat(e.getResponse().getStatusInfo()).isEqualTo(Response.Status.NOT_FOUND); } } @Test //TODO public void findVisible() { } } <|start_filename|>catalog/src/main/java/org/rembx/jeeshop/catalog/model/Discount.java<|end_filename|> package org.rembx.jeeshop.catalog.model; import javax.json.bind.annotation.JsonbTransient; import javax.persistence.*; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; import java.util.Date; import java.util.List; /** * Discount entity */ @Entity @XmlType @XmlAccessorType(XmlAccessType.FIELD) @Cacheable public class Discount extends CatalogItem { public static enum Type { DISCOUNT_RATE, ORDER_DISCOUNT_AMOUNT, SHIPPING_FEE_DISCOUNT_AMOUNT } public static enum Trigger { QUANTITY, AMOUNT, ORDER_NUMBER } public static enum ApplicableTo { ORDER, ITEM } @Size(max = 100) @Column(length = 100) private String voucherCode; private Integer usesPerCustomer; @Enumerated(EnumType.STRING) @Column(length = 50) private Type type; @Enumerated(EnumType.STRING) @Column(length = 50) private Trigger triggerRule; @Enumerated(EnumType.STRING) @NotNull @Column(length = 10, nullable = false) private ApplicableTo applicableTo; private Double triggerValue; private Double discountValue; @ManyToMany(mappedBy = "discounts") @JsonbTransient private List<SKU> skus; @ManyToMany(mappedBy = "discounts") @JsonbTransient private List<Product> products; @Transient private Boolean rateType; @PostLoad @PostPersist @PostUpdate protected void comptuteRateType() { rateType = (type != null && type.equals(Type.DISCOUNT_RATE)); } /** * Cannot be used with other discounts when true */ private Boolean uniqueUse; public Discount() { } public Discount(Long id) { this.id = id; } public Discount(String name, String description, ApplicableTo applicableTo, Type type, Trigger triggerRule, String voucherCode, Double discountValue, Double triggerValue, Integer usesPerCustomer, Boolean uniqueUse, Date startDate, Date endDate, Boolean disabled, String owner) { this.name = name; this.description = description; this.applicableTo = applicableTo; this.type = type; this.triggerRule = triggerRule; this.voucherCode = voucherCode; this.discountValue = discountValue; this.triggerValue = triggerValue; this.usesPerCustomer = usesPerCustomer; this.uniqueUse = uniqueUse; this.startDate = startDate; this.endDate = endDate; this.disabled = disabled; this.owner = owner; } public boolean isEligible(Double itemsPrice){ // TODO continue implem of triggerRule if (triggerRule != null) { switch (triggerRule) { case AMOUNT: if (triggerValue != null && itemsPrice < triggerValue) { return false; } break; } } return true; } public Double processDiscount(Double currentPrice, Double originItemsPrice) { // TODO continue implem of triggerRule if (!isEligible(originItemsPrice)){ return currentPrice; } switch (type) { case DISCOUNT_RATE: currentPrice = currentPrice - originItemsPrice * discountValue / 100; break; case ORDER_DISCOUNT_AMOUNT: currentPrice -= discountValue; break; case SHIPPING_FEE_DISCOUNT_AMOUNT: currentPrice -= discountValue; } return currentPrice; } public Type getType() { return type; } public void setType(Type type) { this.type = type; } public Trigger getTrigger() { return triggerRule; } public void setTrigger(Trigger triggerRule) { this.triggerRule = triggerRule; } public String getVoucherCode() { return voucherCode; } public void setVoucherCode(String voucherCode) { this.voucherCode = voucherCode; } public List<SKU> getSkus() { return skus; } public void setSkus(List<SKU> skus) { this.skus = skus; } public List<Product> getProducts() { return products; } public void setProducts(List<Product> products) { this.products = products; } public Integer getUsesPerCustomer() { return usesPerCustomer; } public void setUsesPerCustomer(Integer usesPerCustomer) { this.usesPerCustomer = usesPerCustomer; } public Boolean getUniqueUse() { return uniqueUse; } public void setUniqueUse(Boolean uniqueUse) { this.uniqueUse = uniqueUse; } public Trigger getTriggerRule() { return triggerRule; } public void setTriggerRule(Trigger triggerRule) { this.triggerRule = triggerRule; } public ApplicableTo getApplicableTo() { return applicableTo; } public void setApplicableTo(ApplicableTo applicableTo) { this.applicableTo = applicableTo; } public Double getDiscountValue() { return discountValue; } public void setDiscountValue(Double discountValue) { this.discountValue = discountValue; } public Boolean getRateType() { return rateType; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (!super.equals(o)) return false; Discount discount1 = (Discount) o; if (applicableTo != discount1.applicableTo) return false; if (discountValue != null ? !discountValue.equals(discount1.discountValue) : discount1.discountValue != null) return false; if (triggerRule != discount1.triggerRule) return false; if (triggerValue != null ? !triggerValue.equals(discount1.triggerValue) : discount1.triggerValue != null) return false; if (type != discount1.type) return false; if (uniqueUse != null ? !uniqueUse.equals(discount1.uniqueUse) : discount1.uniqueUse != null) return false; if (usesPerCustomer != null ? !usesPerCustomer.equals(discount1.usesPerCustomer) : discount1.usesPerCustomer != null) return false; if (voucherCode != null ? !voucherCode.equals(discount1.voucherCode) : discount1.voucherCode != null) return false; return true; } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + (voucherCode != null ? voucherCode.hashCode() : 0); result = 31 * result + (usesPerCustomer != null ? usesPerCustomer.hashCode() : 0); result = 31 * result + (type != null ? type.hashCode() : 0); result = 31 * result + (triggerRule != null ? triggerRule.hashCode() : 0); result = 31 * result + (applicableTo != null ? applicableTo.hashCode() : 0); result = 31 * result + (triggerValue != null ? triggerValue.hashCode() : 0); result = 31 * result + (discountValue != null ? discountValue.hashCode() : 0); result = 31 * result + (uniqueUse != null ? uniqueUse.hashCode() : 0); return result; } } <|start_filename|>user/src/test/java/org/rembx/jeeshop/user/test/TestUser.java<|end_filename|> package org.rembx.jeeshop.user.test; import org.rembx.jeeshop.user.model.*; import javax.persistence.EntityManager; import javax.persistence.Persistence; import java.sql.Timestamp; import java.time.ZonedDateTime; import java.util.Date; /** * User test utility */ public class TestUser { private static TestUser instance; private static User user1; // Date are initialized with java.sql.Timestamp as JPA get a Timestamp instance private final static Date now = Timestamp.from(ZonedDateTime.now().toInstant()); private final static Date yesterday = Timestamp.from(ZonedDateTime.now().minusDays(1).toInstant()); public static TestUser getInstance() { if (instance != null) return instance; EntityManager entityManager = Persistence.createEntityManagerFactory(UserPersistenceUnit.NAME).createEntityManager(); entityManager.getTransaction().begin(); Address address = new Address("21 Blue street", "Chicago", "78801", "John", "Doe","M.",null, "FRA"); user1 = new User("<EMAIL>", "test", "John", "Doe", "+33616161616",null,yesterday,"fr_FR",null); user1.setGender("M."); entityManager.persist(address); entityManager.persist(user1); Role adminRole = new Role(RoleName.admin); Role userRole = new Role(RoleName.user); entityManager.persist(adminRole); entityManager.persist(userRole); entityManager.getTransaction().commit(); instance = new TestUser(); entityManager.close(); return instance; } public User firstUser() { return user1; } } <|start_filename|>user/src/main/java/org/rembx/jeeshop/user/model/Newsletter.java<|end_filename|> package org.rembx.jeeshop.user.model; import javax.persistence.*; import javax.validation.constraints.NotNull; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; import java.util.Date; /** * Newsletter entity */ @Entity @XmlType @XmlAccessorType(XmlAccessType.FIELD) public class Newsletter { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(nullable = false, length = 100) @NotNull private String name; @Column(nullable = false, length = 100) @NotNull String mailTemplateName; @Temporal(TemporalType.TIMESTAMP) private Date creationDate; @Temporal(TemporalType.TIMESTAMP) private Date updateDate; @Temporal(TemporalType.TIMESTAMP) private Date dueDate; public Newsletter() { } public Newsletter(String name, Date dueDate) { this.name = name; this.dueDate = dueDate; } @PrePersist public void prePersist() { this.creationDate = new Date(); } @PreUpdate public void preUpdate(){ this.updateDate = new Date(); } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Date getCreationDate() { return creationDate; } public void setCreationDate(Date creationDate) { this.creationDate = creationDate; } public Date getUpdateDate() { return updateDate; } public void setUpdateDate(Date updateDate) { this.updateDate = updateDate; } public String getMailTemplateName() { return mailTemplateName; } public void setMailTemplateName(String mailTemplateName) { this.mailTemplateName = mailTemplateName; } public Date getDueDate() { return dueDate; } public void setDueDate(Date dueDate) { this.dueDate = dueDate; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Newsletter that = (Newsletter) o; if (id != null ? !id.equals(that.id) : that.id != null) return false; if (name != null ? !name.equals(that.name) : that.name != null) return false; if (mailTemplateName != null ? !mailTemplateName.equals(that.mailTemplateName) : that.mailTemplateName != null) return false; if (creationDate != null ? !creationDate.equals(that.creationDate) : that.creationDate != null) return false; if (updateDate != null ? !updateDate.equals(that.updateDate) : that.updateDate != null) return false; return !(dueDate != null ? !dueDate.equals(that.dueDate) : that.dueDate != null); } @Override public int hashCode() { int result = id != null ? id.hashCode() : 0; result = 31 * result + (name != null ? name.hashCode() : 0); result = 31 * result + (mailTemplateName != null ? mailTemplateName.hashCode() : 0); result = 31 * result + (creationDate != null ? creationDate.hashCode() : 0); result = 31 * result + (updateDate != null ? updateDate.hashCode() : 0); result = 31 * result + (dueDate != null ? dueDate.hashCode() : 0); return result; } } <|start_filename|>common/src/test/java/org/rembx/jeeshop/configuration/TestProducer.java<|end_filename|> package org.rembx.jeeshop.configuration; import javax.enterprise.inject.Produces; import java.util.Calendar; import java.util.GregorianCalendar; /** * Created with IntelliJ IDEA. * User: bantos * Date: 29/11/13 * Time: 21:04 */ public class TestProducer { public final static Calendar calendar = new GregorianCalendar(2013, 0, 9, 18, 1, 0); @Produces private Calendar calendar(){ return calendar; } } <|start_filename|>admin/src/main/webapp/app/catalog/js/catalog.js<|end_filename|> (function () { var app = angular.module('admin-catalog', []); app.directive("commonCatalogFormFields", function () { return { restrict: "A", templateUrl: "app/catalog/common-catalog-form-fields.html" }; }); app.directive("presentationsAccordion", function () { return { restrict: "E", templateUrl: "app/catalog/presentations-accordion.html" }; }); app.directive("featuresAccordion", function () { return { restrict: "E", templateUrl: "app/catalog/pres-features-accordion.html" }; }); app.directive("catalogRelationshipsForm", function () { function link(scope, element, attrs) { attrs.$observe('relationshipsTitle', function (value) { scope.relationshipsTitle = value; }); attrs.$observe('resource', function (value) { scope.relationshipsResource = value; }); attrs.$observe('relationshipsProperty', function (value) { scope.relationshipsProperty = value; }); } return { restrict: "A", scope: true, templateUrl: "app/catalog/relationships-accordion.html", link: link }; }); app.controller("CatalogEntriesController", ['$http', '$uibModal', '$scope', '$state', '$stateParams', function ($http, $uibModal, $scope, $state, $stateParams) { var ctrl = this; ctrl.alerts = []; ctrl.entries = []; ctrl.currentPage = 1; ctrl.totalCount = null; ctrl.pageSize = 10; ctrl.searchValue = null; ctrl.isProcessing = false; ctrl.orderBy = null; ctrl.orderDesc = false; ctrl.isDetailState = function () { return $state.includes('detail'); }; ctrl.findEntries = function (orderBy) { ctrl.isProcessing = true; ctrl.alerts = []; var offset = ctrl.pageSize * (ctrl.currentPage - 1); var uri = 'rs/' + $stateParams.resource + "?start=" + offset + "&size=" + ctrl.pageSize; if (orderBy != null) { ctrl.orderBy = orderBy; ctrl.orderDesc = !ctrl.orderDesc; uri += '&orderBy=' + orderBy + '&isDesc=' + ctrl.orderDesc; } var countURI = 'rs/' + $stateParams.resource + '/count'; if (ctrl.searchValue != null && !(ctrl.searchValue === "")) { var searchArg = 'search=' + ctrl.searchValue; uri = uri + '&' + searchArg; countURI = countURI + '?' + searchArg; } $http.get(uri).success(function (data) { ctrl.entries = data; ctrl.isProcessing = false; }); $http.get(countURI).success(function (data) { ctrl.totalCount = data; ctrl.isProcessing = false; }); }; ctrl.findEntries(); ctrl.pageChanged = function () { ctrl.findEntries(); }; ctrl.delete = function (index, message) { var modalInstance = $uibModal.open({ templateUrl: 'app/util/confirm-dialog.html', controller: ['$uibModalInstance', '$scope', function ($uibModalInstance, $scope) { $scope.modalInstance = $uibModalInstance; $scope.confirmMessage = message; }], size: 'sm' }); modalInstance.result.then(function () { ctrl.alerts = []; $http.delete('rs/' + $stateParams.resource + "/" + ctrl.entries[index].id) .success(function (data) { ctrl.entries.splice(index, 1); ctrl.findEntries(); }) .error(function (data) { ctrl.alerts.push({type: 'danger', msg: 'Technical error'}); }); }, function () { }); }; }]); app.controller('CatalogEntryController', ['$http', '$scope', '$stateParams', '$state', function ($http, $scope, $stateParams, $state) { var ctrl = this; ctrl.alerts = []; ctrl.entry = {}; ctrl.entryChilds = {}; $scope.isEditionMode = ($stateParams.itemId != ""); ctrl.closeAlert = function (index) { ctrl.alerts.splice(index, 1); }; ctrl.createOrEdit = function () { if ($scope.isEditionMode) { ctrl.edit(); } else { ctrl.create(); } }; ctrl.create = function () { $http.post('rs/' + $stateParams.resource, ctrl.entry) .success(function (data) { ctrl.entry = data; ctrl.convertEntryDates(); ctrl.alerts.push({type: 'success', msg: 'Creation complete'}) }) .error(function (data, status) { if (status == 403) ctrl.alerts.push({type: 'warning', msg: 'Operation not allowed'}); else ctrl.alerts.push({type: 'danger', msg: 'Technical error'}); }); }; ctrl.edit = function () { var updatedResource = ctrl.entry delete updatedResource.rootCategories delete updatedResource.presentationByLocale $http.put('rs/' + $stateParams.resource, ctrl.entry) .success(function (data) { ctrl.entry = data; ctrl.convertEntryDates(); ctrl.alerts.push({type: 'success', msg: 'Update complete'}) }) .error(function (data, status) { if (status == 403) ctrl.alerts.push({type: 'warning', msg: 'Operation not allowed'}); else ctrl.alerts.push({type: 'danger', msg: 'Technical error'}); }); }; ctrl.convertEntryDates = function () { // hack for dates returned as timestamp by service ctrl.entry.startDate = ctrl.entry.startDate != null ? new Date(ctrl.entry.startDate) : null; ctrl.entry.endDate = ctrl.entry.endDate != null ? new Date(ctrl.entry.endDate) : null; }; ctrl.exitDetailView = function () { $state.go('^', {}, {reload: true}); }; if ($scope.isEditionMode) { $http.get('rs/' + $stateParams.resource + '/' + $stateParams.itemId) .success(function (data) { ctrl.entry = data; ctrl.convertEntryDates(); }); } else { ctrl.alerts.push({ type: 'info', msg: 'Save this item to access localized content (texts, images, ...) configuration' }); } }]); app.controller('CatalogRelationshipsController', ['$http', '$scope', '$uibModal', '$log', '$stateParams', function ($http, $scope, $uibModal, $log, $stateParams) { var ctrl = this; $scope.itemsIds = []; $scope.items = []; $scope.accordion = { open: false }; $scope.initRelationshipsIdsProperty = function () { $scope.itemsIds = []; for (i in $scope.items) { $scope.itemsIds[i] = $scope.items[i].id; } $scope.catalogEntryCtrl.entry[$scope.relationshipsProperty] = $scope.itemsIds; }; $scope.removeItem = function (index) { $scope.items.splice(index, 1); $scope.initRelationshipsIdsProperty(); }; $scope.$watch('catalogEntryCtrl.entry', function () { $scope.accordion.open = false; }); $scope.$watch('accordion.open', function (isOpen) { if (isOpen) { if ($scope.catalogEntryCtrl.entry.id == null) { return; } $http.get('rs/' + $stateParams.resource + '/' + $stateParams.itemId + '/' + $scope.relationshipsResource) .success(function (data) { $scope.items = data; $scope.initRelationshipsIdsProperty(); }); } }); $scope.open = function (size) { var modalInstance = $uibModal.open({ templateUrl: 'relationshipsSelector.html', controller: 'CatalogRelationshipsModalController', size: size, resolve: { items: function () { return $scope.items; }, itemsIds: function () { return $scope.itemsIds; }, relationshipsResource: function () { return $scope.relationshipsResource; } } }); modalInstance.result.then(function (selectedItems) { for (i in selectedItems) { $scope.items.push(selectedItems[i]); } $scope.initRelationshipsIdsProperty(); }, function () { $log.info('Modal dismissed at: ' + new Date()); }); }; }]); app.controller('CatalogRelationshipsModalController', ['$http', '$scope', '$uibModalInstance', '$stateParams', 'items', 'relationshipsResource', function ($http, $scope, $uibModalInstance, $stateParams, items, relationshipsResource) { ctrl = this; $scope.items = items; $scope.relationshipsResource = relationshipsResource; $scope.results = []; $scope.selected = []; $scope.currentPage = 1; $scope.totalCount = 0; $scope.pageSize = 10; $scope.search = function () { // TODO merge with catalogEntriesCtrl listing and add search to it var offset = $scope.pageSize * ($scope.currentPage - 1); var uri = 'rs/' + $scope.relationshipsResource + "?start=" + offset + "&size=" + $scope.pageSize; var countURI = 'rs/' + $scope.relationshipsResource + '/count'; if ($scope.searchValue != null && !($scope.searchValue === "")) { var searchArg = 'search=' + $scope.searchValue; uri = uri + '&' + searchArg; countURI = countURI + '?' + searchArg; } $http.get(uri).success(function (data) { $scope.results = data; }); $http.get(countURI).success(function (data) { $scope.totalCount = data; }); }; $scope.pageChanged = function () { $scope.search(); }; $scope.isAlreadyLinked = function (itemId) { var isLinked = false; for (i in $scope.items) { if ($scope.items[i].id === itemId) { isLinked = true; break; } } return isLinked; }; $scope.ok = function () { var selectedItems = []; for (i in $scope.results) { if ($scope.selected[$scope.results[i].id] != null && $scope.selected[$scope.results[i].id] === true) { selectedItems.push($scope.results[i]); } } $uibModalInstance.close(selectedItems); }; $scope.cancel = function () { $uibModalInstance.dismiss('cancel'); }; }]); app.controller('PresentationsController', ['$http', '$scope', '$uibModal', '$log', '$stateParams', 'LocalesService', function ($http, $scope, $uibModal, $log, $stateParams, LocalesService) { var ctrl = this; var getAvailableLocales = function () { $http.get('rs/' + $stateParams.resource + '/' + $stateParams.itemId + '/presentationslocales') .success(function (data) { $scope.locales = data; }); }; $scope.isEditionMode = ($stateParams.itemId != ""); $scope.itemId = $stateParams.itemId; $scope.resource = $stateParams.resource; $scope.locales = []; $scope.locale = null; // edition mode $scope.accordion = { open: false }; $scope.removeItem = function (index, message) { var modalInstance = $uibModal.open({ templateUrl: 'app/util/confirm-dialog.html', controller: ['$uibModalInstance', '$scope', function ($uibModalInstance, $scope) { $scope.modalInstance = $uibModalInstance; $scope.confirmMessage = message; }], size: 'sm' }); modalInstance.result.then(function () { $scope.catalogEntryCtrl.alerts = []; $http.delete('rs/' + $scope.resource + '/' + $scope.itemId + '/presentations/' + $scope.locales[index]) .success(function (data) { $scope.locales.splice(index, 1); $scope.catalogEntryCtrl.alerts.push({type: 'success', msg: 'Presentations update complete'}); }) .error(function (data) { $scope.catalogEntryCtrl.alerts.push({type: 'danger', msg: 'Technical error'}); }); }, function () { }); }; $scope.$watch('catalogEntryCtrl.entry', function () { $scope.accordion.open = false; }); $scope.$watch('accordion.open', function (isOpen) { if (isOpen) { if ($scope.catalogEntryCtrl.entry.id == null) { $scope.locales = []; } getAvailableLocales(); } }); $scope.addOrEditPresentation = function (size, locale) { $scope.locale = locale; var modalInstance = $uibModal.open({ templateUrl: 'addOrEditPresentation.html', controller: 'PresentationsModalController', size: size, resolve: { locales: function () { return $scope.locales; }, locale: function () { return $scope.locale; }, presentationsResourceURI: function () { return 'rs/' + $stateParams.resource + '/' + $scope.catalogEntryCtrl.entry.id + '/presentations'; }, entryId: function () { return $scope.catalogEntryCtrl.entry.id; } } }); modalInstance.result.then(function (errors) { $scope.catalogEntryCtrl.alerts = []; if (errors != null && errors.length > 0) { $scope.catalogEntryCtrl.alerts.push(errors[0]); getAvailableLocales(); } }, function () { }); }; }]); app.controller('PresentationsModalController', ['$http', '$scope', '$uibModalInstance', '$stateParams', '$upload', 'LocalesService', 'locales', 'locale', 'presentationsResourceURI', 'entryId', function ($http, $scope, $uibModalInstance, $stateParams, $upload, LocalesService, locales, locale, presentationsResourceURI, entryId) { ctrl = this; $scope.locales = locales; $scope.locale = locale; // set when edition mode $scope.isEditionMode = ($scope.locale != null); $scope.selectedLocale = null; $scope.presentation = {}; $scope.entryId = entryId; $scope.isProcessing = { thumbnail: false, largeImage: false, smallImage: false }; $scope.feature = {}; $scope.isNewLocaleSelected = function () { return $scope.presentation.id == null }; $scope.addFeature = function (feature) { $scope.presentation.features[feature.name] = feature.value; $scope.feature = {}; }; $scope.removeFeature = function (name) { delete $scope.presentation.features[name]; }; var getPresentationByLocale = function (locale) { $scope.selectedLocale = locale; $http.get(presentationsResourceURI + "/" + locale) .success(function (data) { $scope.presentation = data; $scope.locale = locale; }) .error(function (data) { $scope.presentation = {}; $scope.locale = null; }); }; if (locale != null) { getPresentationByLocale(locale); } $scope.isLocaleSelected = function () { return $scope.selectedLocale != null; }; $scope.selectLocale = function () { getPresentationByLocale($scope.selectedLocale); }; $scope.removePresentationMedia = function (presentationPropertyName) { $scope.presentation[presentationPropertyName] = null; }; $scope.getPresentationMediaURI = function (presentationPropertyName) { if ($scope.presentation[presentationPropertyName] != null) { return 'rs/medias/' + $stateParams.resource + '/' + $scope.entryId + '/' + $scope.selectedLocale + '/' + $scope.presentation[presentationPropertyName].uri + '?refresh=' + $scope.isProcessing[presentationPropertyName]; } }; $scope.onFileSelect = function ($files, presentationPropertyName) { $scope.isProcessing[presentationPropertyName] = true; var file = $files[0]; var presentationMedia = { uri: file.name }; $scope.presentation[presentationPropertyName] = presentationMedia; $scope.upload = $upload.upload({ url: 'rs/medias/' + $stateParams.resource + '/' + $scope.entryId + '/' + $scope.selectedLocale + '/upload', method: 'POST', //headers: {'header-key': 'header-value'}, withCredentials: true, file: file }).progress(function (evt) { }).success(function (data, status, headers, config) { $scope.isProcessing[presentationPropertyName] = false; }) .error(function (data, status, headers, config) { $scope.isProcessing[presentationPropertyName] = false; }); }; $scope.save = function () { var messages = []; $http.put(presentationsResourceURI + "/" + locale, $scope.presentation) .success(function (data) { $scope.presentation = data; messages.push({type: 'success', msg: 'Presentations update complete'}); $uibModalInstance.close(messages); }) .error(function (data, status) { if (status == 403) messages.push({type: 'warning', msg: 'Operation not allowed'}); else messages.push({type: 'danger', msg: 'Technical error'}); $uibModalInstance.close(messages); }); }; $scope.add = function () { var messages = []; $scope.presentation.locale = $scope.selectedLocale; $http.post(presentationsResourceURI + "/" + $scope.selectedLocale, $scope.presentation) .success(function (data) { $scope.presentation = data; messages.push({type: 'success', msg: 'Presentation creation complete'}); $uibModalInstance.close(messages); }) .error(function (data, status) { if (status == 403) messages.push({type: 'warning', msg: 'Operation now allowed'}); else messages.push({type: 'danger', msg: 'Technical error'}); $uibModalInstance.close(messages); }); }; $scope.cancel = function () { $uibModalInstance.dismiss('cancel'); }; $scope.availableLocales = LocalesService.allLocales(); }]); })(); <|start_filename|>order/src/main/java/org/rembx/jeeshop/order/OrderFinder.java<|end_filename|> package org.rembx.jeeshop.order; import com.querydsl.core.types.dsl.BooleanExpression; import com.querydsl.core.types.dsl.ComparableExpressionBase; import com.querydsl.jpa.impl.JPAQuery; import com.querydsl.jpa.impl.JPAQueryFactory; import io.quarkus.hibernate.orm.PersistenceUnit; import org.apache.commons.lang.math.NumberUtils; import org.rembx.jeeshop.catalog.model.CatalogPersistenceUnit; import org.rembx.jeeshop.catalog.model.Discount; import org.rembx.jeeshop.catalog.model.Product; import org.rembx.jeeshop.catalog.model.SKU; import org.rembx.jeeshop.order.model.Order; import org.rembx.jeeshop.order.model.OrderStatus; import org.rembx.jeeshop.user.model.User; import org.rembx.jeeshop.user.model.UserPersistenceUnit; import javax.enterprise.context.ApplicationScoped; import javax.enterprise.context.RequestScoped; import javax.inject.Inject; import javax.persistence.EntityManager; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.rembx.jeeshop.order.model.QOrder.order; @ApplicationScoped public class OrderFinder { private EntityManager entityManager; private EntityManager catalogEntityManager; private OrderConfiguration orderConfiguration; OrderFinder(@PersistenceUnit(UserPersistenceUnit.NAME) EntityManager entityManager, @PersistenceUnit(CatalogPersistenceUnit.NAME) EntityManager catalogEntityManager, OrderConfiguration orderConfiguration) { this.entityManager = entityManager; this.catalogEntityManager = catalogEntityManager; this.orderConfiguration = orderConfiguration; } private static final Map<String, ComparableExpressionBase<?>> sortProperties = new HashMap<>() {{ put("id", order.id); put("owner", order.user.lastname); put("login", order.user.login); put("status", order.status); put("creationDate", order.creationDate); put("updateDate", order.updateDate); }}; public Long countUserCompletedOrders(User user) { return new JPAQueryFactory(entityManager) .selectFrom(order) .where( order.user.eq(user), order.status.notIn(OrderStatus.CREATED, OrderStatus.CANCELLED, OrderStatus.RETURNED)) .fetchCount(); } public Long countAll(String searchCriteria, OrderStatus status, Long skuId) { JPAQuery<Order> query = new JPAQueryFactory(entityManager).selectFrom(order) .where(matchesSearchAndStatusAndItemsSkuId(searchCriteria, status, skuId)); return query.fetchCount(); } public List<Order> findAll(Integer offset, Integer limit, String orderby, Boolean isDesc, String searchCriteria, OrderStatus status, Long skuId, boolean enhanceResult) { JPAQuery<Order> query = new JPAQueryFactory(entityManager).selectFrom(order) .where(matchesSearchAndStatusAndItemsSkuId(searchCriteria, status, skuId)); if (offset != null) query.offset(offset); if (limit != null) query.limit(limit); sortBy(orderby, isDesc, query); List<Order> orders = query.fetch(); if (enhanceResult) orders.forEach(this::enhanceOrder); return orders; } public List<Order> findByUser(User user, Integer offset, Integer limit, String orderby, Boolean isDesc, OrderStatus status) { JPAQuery<Order> query = new JPAQueryFactory(entityManager).selectFrom(order) .where( order.user.eq(user), status != null && status.equals(OrderStatus.CREATED) ? null : order.status.ne(OrderStatus.CREATED), status != null ? order.status.eq(status) : null); if (offset != null) query.offset(offset); if (limit != null) query.limit(limit); sortBy(orderby, isDesc, query); return query.fetch(); } private BooleanExpression matchesSearchAndStatusAndItemsSkuId(String searchCriteria, OrderStatus status, Long skuId) { BooleanExpression expression = null; if (searchCriteria != null) expression = matchesSearchCriteria(searchCriteria); if (status != null) { expression = expression != null ? expression.and(order.status.eq(status)) : order.status.eq(status); } if (skuId != null) { expression = expression != null ? expression.and(order.items.any().skuId.eq(skuId)) : order.items.any().skuId.eq(skuId); } return expression; } private void sortBy(String orderby, Boolean isDesc, JPAQuery<Order> query) { if (orderby != null && sortProperties.containsKey(orderby)) { if (isDesc) { query.orderBy(sortProperties.get(orderby).desc()); } else { query.orderBy(sortProperties.get(orderby).asc()); } } } private BooleanExpression matchesSearchCriteria(String search) { BooleanExpression searchExpression = order.user.login.containsIgnoreCase(search) .or(order.user.firstname.containsIgnoreCase(search)) .or(order.user.lastname.containsIgnoreCase(search)) .or(order.transactionId.containsIgnoreCase(search)); if (NumberUtils.isNumber(search)) { Long searchId = Long.parseLong(search); searchExpression = order.id.eq(searchId).or(order.transactionId.eq(search)); } return searchExpression; } /** * Enhance given order with Catalog items data and order static configuration. * * @param order the order to enhance */ public void enhanceOrder(Order order) { User user = order.getUser(); order.getItems().forEach(orderItem -> { Product product = catalogEntityManager.find(Product.class, orderItem.getProductId()); SKU sku = catalogEntityManager.find(SKU.class, orderItem.getSkuId()); product.setLocalizedPresentation(user.getPreferredLocale()); orderItem.setDisplayName(product.getLocalizedPresentation() != null ? product.getLocalizedPresentation().getDisplayName() : product.getName()); orderItem.setSkuReference(sku.getReference()); if (product.getLocalizedPresentation() != null && product.getLocalizedPresentation().getSmallImage() != null) orderItem.setPresentationImageURI("products/" + orderItem.getProductId() + "/" + product.getLocalizedPresentation().getLocale() + "/" + product.getLocalizedPresentation().getSmallImage().getUri()); }); order.getOrderDiscounts().forEach(orderDiscount -> { Discount discount = catalogEntityManager.find(Discount.class, orderDiscount.getDiscountId()); discount.setLocalizedPresentation(user.getPreferredLocale()); orderDiscount.setDisplayName(discount.getLocalizedPresentation().getDisplayName() != null ? discount.getLocalizedPresentation().getDisplayName() : discount.getName()); orderDiscount.setRateType(discount.getRateType()); if (discount.getLocalizedPresentation() != null && discount.getLocalizedPresentation().getSmallImage() != null) orderDiscount.setPresentationImageURI("discounts/" + orderDiscount.getDiscountId() + "/" + discount.getLocalizedPresentation().getLocale() + "/" + discount.getLocalizedPresentation().getSmallImage().getUri()); }); order.setDeliveryFee(orderConfiguration.getFixedDeliveryFee()); order.setVat(orderConfiguration.getVAT()); } } <|start_filename|>common/src/main/java/org/rembx/jeeshop/rest/WebApplicationExceptionMapper.java<|end_filename|> package org.rembx.jeeshop.rest; import javax.ws.rs.core.Response; /** * Avoid logging of stack trace for WebApplicationException instances thrown by application */ public class WebApplicationExceptionMapper implements javax.ws.rs.ext.ExceptionMapper<WebApplicationException> { @Override public Response toResponse(WebApplicationException e) { return e.getResponse(); } } <|start_filename|>catalog/src/main/java/org/rembx/jeeshop/catalog/Stores.java<|end_filename|> package org.rembx.jeeshop.catalog; import io.quarkus.hibernate.orm.PersistenceUnit; import org.rembx.jeeshop.catalog.model.Catalog; import org.rembx.jeeshop.catalog.model.CatalogPersistenceUnit; import org.rembx.jeeshop.catalog.model.Presentation; import org.rembx.jeeshop.catalog.model.Store; import org.rembx.jeeshop.rest.WebApplicationException; import javax.annotation.security.PermitAll; import javax.annotation.security.RolesAllowed; import javax.enterprise.context.ApplicationScoped; import javax.persistence.EntityManager; import javax.transaction.Transactional; import javax.validation.constraints.NotNull; import javax.ws.rs.*; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import java.util.ArrayList; import java.util.List; import java.util.Set; import static org.rembx.jeeshop.catalog.model.QCatalog.catalog; import static org.rembx.jeeshop.catalog.model.QStore.store; import static org.rembx.jeeshop.role.AuthorizationUtils.isAdminUser; import static org.rembx.jeeshop.role.AuthorizationUtils.isOwner; import static org.rembx.jeeshop.role.JeeshopRoles.*; @Path("/rs/stores") @ApplicationScoped public class Stores implements CatalogItemService<Store> { private final EntityManager entityManager; private final CatalogItemFinder catalogItemFinder; private final PresentationResource presentationResource; Stores(@PersistenceUnit(CatalogPersistenceUnit.NAME) EntityManager entityManager, CatalogItemFinder catalogItemFinder, PresentationResource presentationResource) { this.entityManager = entityManager; this.catalogItemFinder = catalogItemFinder; this.presentationResource = presentationResource; } @GET @Path("/") @Produces(MediaType.APPLICATION_JSON) @RolesAllowed({ADMIN, ADMIN_READONLY}) public List<Store> findAll(@QueryParam("search") String search, @QueryParam("start") Integer start, @QueryParam("size") Integer size, @QueryParam("orderBy") String orderBy, @QueryParam("isDesc") Boolean isDesc, @QueryParam("locale") String locale) { if (search != null) return catalogItemFinder.findBySearchCriteria(store, search, start, size, orderBy, isDesc, locale); else { return catalogItemFinder.findAll(store, start, size, orderBy, isDesc, locale); } } @GET @Path("/count") @Produces(MediaType.APPLICATION_JSON) @RolesAllowed({ADMIN, ADMIN_READONLY}) public Long count(@QueryParam("search") String search) { if (search != null) return catalogItemFinder.countBySearchCriteria(store, search); else return catalogItemFinder.countAll(store); } @GET @Path("/{storeId}") @Produces(MediaType.APPLICATION_JSON) @PermitAll public Store find(@Context SecurityContext securityContext, @PathParam("storeId") @NotNull Long itemId, @QueryParam("locale") String locale) { Store store = entityManager.find(Store.class, itemId); if (isAdminUser(securityContext) || isOwner(securityContext, store.getOwner())) return store; else return catalogItemFinder.filterVisible(store, locale); } @POST @Transactional @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @RolesAllowed({ADMIN, STORE_ADMIN}) public Store create(@Context SecurityContext securityContext, Store store) { attachOwner(securityContext, store); entityManager.persist(store); return store; } @DELETE @Transactional @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @RolesAllowed({ADMIN, STORE_ADMIN}) @Path("/{storeId}") public void delete(@Context SecurityContext securityContext, @PathParam("storeId") Long storeId) { Store store = entityManager.find(Store.class, storeId); checkNotNull(store); if (isOwner(securityContext, store.getOwner()) || isAdminUser(securityContext)) { entityManager.remove(store); } else { throw new WebApplicationException(Response.Status.FORBIDDEN); } } @PUT @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Transactional @RolesAllowed({ADMIN, STORE_ADMIN}) public Store modify(@Context SecurityContext securityContext, Store store) { Store originalCatalog = entityManager.find(Store.class, store.getId()); checkNotNull(originalCatalog); if (!isOwner(securityContext, originalCatalog.getOwner()) && !isAdminUser(securityContext)) throw new WebApplicationException(Response.Status.FORBIDDEN); if (store.getCatalogsIds() != null) { List<Catalog> catalogs = new ArrayList<>(); store.getCatalogsIds().forEach(categoryId -> catalogs.add(entityManager.find(Catalog.class, categoryId))); store.setCatalogs(catalogs); } else { store.setCatalogs(originalCatalog.getCatalogs()); } store.setPresentationByLocale(originalCatalog.getPresentationByLocale()); return entityManager.merge(store); } @GET @Path("/{storeId}/presentationslocales") @Produces(MediaType.APPLICATION_JSON) @RolesAllowed({ADMIN, STORE_ADMIN, ADMIN_READONLY}) public Set<String> findPresentationsLocales(@Context SecurityContext securityContext, @PathParam("storeId") @NotNull Long storeId) { Store loadedStore = entityManager.find(Store.class, storeId); checkNotNull(loadedStore); if (!isAdminUser(securityContext) && !isOwner(securityContext, loadedStore.getOwner())) throw new WebApplicationException(Response.Status.FORBIDDEN); return loadedStore.getPresentationByLocale().keySet(); } @Path("/{storeId}/presentations/{locale}") @PermitAll public PresentationResource findPresentationByLocale(@PathParam("storedId") @NotNull Long storeId, @NotNull @PathParam("locale") String locale) { Store store = entityManager.find(Store.class, storeId); checkNotNull(store); Presentation presentation = store.getPresentationByLocale().get(locale); return presentationResource.init(store, locale, presentation); } @GET @Path("/{storeId}/catalogs") @Produces(MediaType.APPLICATION_JSON) @PermitAll public List<Catalog> findCatalogs(@Context SecurityContext securityContext, @PathParam("storeId") @NotNull Long storeId, @QueryParam("locale") String locale) { Store loadedStore = entityManager.find(Store.class, storeId); checkNotNull(loadedStore); List<Catalog> catalogs = loadedStore.getCatalogs(); if (catalogs.isEmpty()) { return new ArrayList<>(); } if (isAdminUser(securityContext) || isOwner(securityContext, loadedStore.getOwner())) { return catalogs; } else { return catalogItemFinder.findVisibleCatalogItems(catalog, catalogs, locale); } } private void checkNotNull(Store originalCatalog) { if (originalCatalog == null) { throw new WebApplicationException(Response.Status.NOT_FOUND); } } } <|start_filename|>order/src/main/java/org/rembx/jeeshop/order/DefaultPaymentTransactionEngine.java<|end_filename|> package org.rembx.jeeshop.order; import freemarker.template.Configuration; import freemarker.template.Template; import io.quarkus.hibernate.orm.PersistenceUnit; import org.rembx.jeeshop.catalog.model.CatalogPersistenceUnit; import org.rembx.jeeshop.catalog.model.SKU; import org.rembx.jeeshop.mail.Mailer; import org.rembx.jeeshop.order.model.Order; import org.rembx.jeeshop.order.model.OrderStatus; import org.rembx.jeeshop.user.MailTemplateFinder; import org.rembx.jeeshop.user.model.MailTemplate; import org.rembx.jeeshop.user.model.User; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.enterprise.context.ApplicationScoped; import javax.enterprise.context.RequestScoped; import javax.inject.Inject; import javax.persistence.EntityManager; import java.io.StringWriter; import java.util.Date; import java.util.UUID; import static org.rembx.jeeshop.order.mail.Mails.orderValidated; /** * Default implementation of PaymentTransactionEngine */ @ApplicationScoped public class DefaultPaymentTransactionEngine implements PaymentTransactionEngine { private final static Logger LOG = LoggerFactory.getLogger(DefaultPaymentTransactionEngine.class); private OrderFinder orderFinder; private MailTemplateFinder mailTemplateFinder; private Mailer mailer; private EntityManager catalogEntityManager; DefaultPaymentTransactionEngine( OrderFinder orderFinder, MailTemplateFinder mailTemplateFinder, Mailer mailer, @PersistenceUnit(CatalogPersistenceUnit.NAME) EntityManager catalogEntityManager) { this.orderFinder = orderFinder; this.mailTemplateFinder = mailTemplateFinder; this.mailer = mailer; this.catalogEntityManager = catalogEntityManager; } @Override public void processPayment(Order order) { LOG.warn("Default implementation of PaymentTransactionEngine. Please provide a final PayamentTransactionEngine implementation"); updateOrderWithPaymentInfo(order); updateSkusQuantities(order); order.computeOrderReference(); orderFinder.enhanceOrder(order); sendOrderConfirmationMail(order); } private void updateOrderWithPaymentInfo(Order order) { order.setStatus(OrderStatus.PAYMENT_VALIDATED); order.setPaymentDate(new Date()); order.setTransactionId(UUID.randomUUID().toString()); } protected void updateSkusQuantities(Order order) { order.getItems().forEach(orderItem -> { SKU sku = catalogEntityManager.find(SKU.class, (orderItem).getSkuId()); sku.setQuantity(sku.getQuantity() - (orderItem).getQuantity()); }); } protected void sendOrderConfirmationMail(Order order) { User user = order.getUser(); MailTemplate mailTemplate = mailTemplateFinder.findByNameAndLocale(orderValidated.name(), user.getPreferredLocale()); if (mailTemplate == null){ LOG.warn("orderValidated e-mail template does not exist. Configure this missing template to allow user e-mail notification"); return; } try { Template mailContentTpl = new Template(orderValidated.name(), mailTemplate.getContent(), new Configuration(Configuration.VERSION_2_3_21)); final StringWriter mailBody = new StringWriter(); mailContentTpl.process(order, mailBody); mailer.sendMail(mailTemplate.getSubject(), user.getLogin(), mailBody.toString()); } catch (Exception e) { LOG.error("Unable to send mail " + orderValidated + " to user " + user.getLogin(), e); } } } <|start_filename|>user/src/main/java/org/rembx/jeeshop/order/model/OrderStatus.java<|end_filename|> package org.rembx.jeeshop.order.model; /** * Statuses for Order lifecycle */ public enum OrderStatus { CREATED, VALIDATED, PAYMENT_VALIDATED, CANCELLED,READY_FOR_SHIPMENT, SHIPPED, DELIVERED, RETURNED } <|start_filename|>order/src/test/java/org/rembx/jeeshop/order/EligibleDiscountsCT.java<|end_filename|> package org.rembx.jeeshop.order; import org.junit.jupiter.api.Test; // TODO! public class EligibleDiscountsCT { @Test public void testFindEligible() throws Exception { } } <|start_filename|>user/src/main/java/org/rembx/jeeshop/user/model/UserPersistenceUnit.java<|end_filename|> package org.rembx.jeeshop.user.model; /** * Created by remi on 25/05/14. */ public interface UserPersistenceUnit { public final static String NAME = "User"; } <|start_filename|>admin/src/main/webapp/errors/error-401.jsp<|end_filename|> <%@ page contentType="text/plain"%> <% response.sendError(response.SC_FORBIDDEN, "forbidden"); %> <|start_filename|>catalog/src/main/java/org/rembx/jeeshop/catalog/PresentationResource.java<|end_filename|> package org.rembx.jeeshop.catalog; import io.quarkus.hibernate.orm.PersistenceUnit; import org.rembx.jeeshop.catalog.model.CatalogItem; import org.rembx.jeeshop.catalog.model.CatalogPersistenceUnit; import org.rembx.jeeshop.catalog.model.Presentation; import org.rembx.jeeshop.rest.WebApplicationException; import javax.annotation.security.RolesAllowed; import javax.enterprise.context.ApplicationScoped; import javax.enterprise.context.RequestScoped; import javax.inject.Inject; import javax.persistence.EntityManager; import javax.transaction.*; import javax.transaction.NotSupportedException; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import static javax.transaction.Transactional.TxType.REQUIRED; import static javax.transaction.Transactional.TxType.REQUIRES_NEW; import static org.rembx.jeeshop.role.JeeshopRoles.ADMIN; /** * Sub-resource of CatalogItem resources (Catalogs, Categories,...) dedicated to a Presentation instance. * * @author remi */ @ApplicationScoped public class PresentationResource { private Presentation presentation; private CatalogItem parentCatalogItem; private String locale; private EntityManager entityManager; private UserTransaction transaction; PresentationResource(@PersistenceUnit(CatalogPersistenceUnit.NAME) EntityManager entityManager, UserTransaction userTransaction) { this.entityManager = entityManager; this.transaction = userTransaction; } @GET @Produces(MediaType.APPLICATION_JSON) public Presentation find() { checkEntityNotNull(); return presentation; } @DELETE @Produces(MediaType.APPLICATION_JSON) @Transactional(value = REQUIRES_NEW) @RolesAllowed(ADMIN) public void delete() { checkEntityNotNull(); parentCatalogItem.getPresentationByLocale().remove(presentation.getLocale()); entityManager.merge(parentCatalogItem); entityManager.remove(entityManager.merge(presentation)); } @POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Transactional(value = REQUIRES_NEW) @RolesAllowed(ADMIN) public Presentation createLocalizedPresentation(Presentation presentation) { if (this.presentation != null) { // Item already exist throw new WebApplicationException(Response.Status.BAD_REQUEST); } presentation.setLocale(locale); entityManager.persist(presentation); parentCatalogItem.getPresentationByLocale().put(locale, presentation); entityManager.merge(parentCatalogItem); return presentation; } @PUT @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Transactional(REQUIRES_NEW) @RolesAllowed(ADMIN) public Presentation modifyLocalizedPresentation(Presentation presentation) { checkEntityNotNull(); if (this.presentation == null) { throw new WebApplicationException(Response.Status.BAD_REQUEST); } entityManager.merge(presentation); return presentation; } private void checkEntityNotNull() { if (presentation == null) { throw new WebApplicationException(Response.Status.NOT_FOUND); } } public PresentationResource init(CatalogItem parentCatalogItem, String locale, Presentation presentation) { this.presentation = presentation; this.locale = locale; this.parentCatalogItem = parentCatalogItem; return this; } } <|start_filename|>user/src/main/java/org/rembx/jeeshop/user/tools/CryptTools.java<|end_filename|> package org.rembx.jeeshop.user.tools; import com.google.common.hash.Hashing; import org.apache.commons.codec.binary.Base64; public class CryptTools { public static String hashSha256Base64(String strToHash) { byte[] digest = Hashing.sha256().hashBytes(strToHash.getBytes()).asBytes(); return Base64.encodeBase64String(digest); } } <|start_filename|>order/src/main/java/org/rembx/jeeshop/order/EligibleDiscounts.java<|end_filename|> package org.rembx.jeeshop.order; import io.quarkus.undertow.runtime.HttpSessionContext; import org.rembx.jeeshop.catalog.DiscountFinder; import org.rembx.jeeshop.catalog.model.Discount; import org.rembx.jeeshop.role.JeeshopRoles; import org.rembx.jeeshop.user.UserFinder; import org.rembx.jeeshop.user.model.User; import javax.annotation.Resource; import javax.annotation.security.RolesAllowed; import javax.enterprise.context.ApplicationScoped; import javax.enterprise.context.RequestScoped; import javax.inject.Inject; import javax.transaction.Transactional; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.SecurityContext; import java.util.List; /** * Orders resource. */ @Path("discounts/eligible") @ApplicationScoped public class EligibleDiscounts { private DiscountFinder discountFinder; private UserFinder userFinder; private OrderFinder orderFinder; private OrderConfiguration orderConfiguration; EligibleDiscounts(UserFinder userFinder, DiscountFinder discountFinder, OrderFinder orderFinder) { this.userFinder = userFinder; this.discountFinder = discountFinder; this.orderFinder = orderFinder; } @GET @Produces(MediaType.APPLICATION_JSON) @RolesAllowed(JeeshopRoles.USER) public List<Discount> findEligible(@Context SecurityContext securityContext, @QueryParam("locale") String locale) { User currentUser = userFinder.findByLogin(securityContext.getUserPrincipal().getName()); Long completedOrders = orderFinder.countUserCompletedOrders(currentUser); return discountFinder.findEligibleOrderDiscounts(locale, completedOrders ); } } <|start_filename|>admin/src/main/webapp/app/order/order-operations.html<|end_filename|> <div class="text-center" ng-controller="OrderOperationController as operationsController"> <div class="row"> <div class="col-md-12 text-center"> <span> <uib-alert ng-repeat="alert in operationsController.alerts" type="{{alert.type}}" close="operationsController.closeAlert($index)">{{alert.msg}} </uib-alert> </span> </div> </div> <div id="loaderDiv" ng-show="operationsController.isProcessing"> <img src="app/images/loading.gif" class="ajax-loader"/> </div> <div class="row" style="margin-top:1em"> <div class="col-md-6 text-left form-group"> <h4>Process Payed orders</h4> <label for="skuId"> SKU Id </label> <input type="number" class="form-control" id="skuId" ng-model="operationsController.skuId" placeholder="Filter by SKU id..." maxlength="20"/> <p class="help-block">Filter orders with items matching given SKU identifier</p> <br/> <button type="button" class="btn btn-primary" ng-click="operationsController.payedOrdersAsCSV()">Export CSV </button> <p class="help-block">Export orders items for orders with payment validated to a CSV file with items delivery information</p> </div> </div> </div> <|start_filename|>admin/src/main/java/org/rembx/jeeshop/admin/ApplicationConfig.java<|end_filename|> package org.rembx.jeeshop.admin; import org.rembx.jeeshop.catalog.*; import org.rembx.jeeshop.media.Medias; import org.rembx.jeeshop.order.Orders; import org.rembx.jeeshop.rest.WebApplicationExceptionMapper; import org.rembx.jeeshop.user.MailTemplates; import org.rembx.jeeshop.user.Users; import javax.ws.rs.ApplicationPath; import javax.ws.rs.core.Application; import java.util.HashSet; import java.util.Set; @ApplicationPath("/") public class ApplicationConfig extends Application { @Override public Set<Class<?>> getClasses() { Set<Class<?>> classes = new HashSet<>(); classes.add(Stores.class); classes.add(Catalogs.class); classes.add(Categories.class); classes.add(Products.class); classes.add(SKUs.class); classes.add(Discounts.class); classes.add(Users.class); classes.add(Medias.class); classes.add(MailTemplates.class); classes.add(Orders.class); classes.add(WebApplicationExceptionMapper.class); return classes; } } <|start_filename|>catalog/src/main/java/org/rembx/jeeshop/catalog/SKUs.java<|end_filename|> package org.rembx.jeeshop.catalog; import io.quarkus.hibernate.orm.PersistenceUnit; import org.rembx.jeeshop.catalog.model.*; import org.rembx.jeeshop.rest.WebApplicationException; import javax.annotation.security.PermitAll; import javax.annotation.security.RolesAllowed; import javax.enterprise.context.ApplicationScoped; import javax.persistence.EntityManager; import javax.transaction.Transactional; import javax.validation.constraints.NotNull; import javax.ws.rs.*; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import java.util.ArrayList; import java.util.List; import java.util.Set; import static org.rembx.jeeshop.catalog.model.QDiscount.discount; import static org.rembx.jeeshop.catalog.model.QSKU.sKU; import static org.rembx.jeeshop.role.AuthorizationUtils.isAdminUser; import static org.rembx.jeeshop.role.AuthorizationUtils.isOwner; import static org.rembx.jeeshop.role.JeeshopRoles.*; /** * @author remi */ @Path("/rs/skus") @ApplicationScoped public class SKUs implements CatalogItemService<SKU> { private final EntityManager entityManager; private final CatalogItemFinder catalogItemFinder; private final PresentationResource presentationResource; SKUs(@PersistenceUnit(CatalogPersistenceUnit.NAME) EntityManager entityManager, CatalogItemFinder catalogItemFinder, PresentationResource presentationResource) { this.entityManager = entityManager; this.catalogItemFinder = catalogItemFinder; this.presentationResource = presentationResource; } @POST @Transactional @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @RolesAllowed({ADMIN, STORE_ADMIN}) public SKU create(@Context SecurityContext securityContext, SKU sku) { attachOwner(securityContext, sku); if (sku.getDiscountsIds() != null) { List<Discount> newDiscounts = new ArrayList<>(); sku.getDiscountsIds().forEach(discountId -> newDiscounts.add(entityManager.find(Discount.class, discountId))); sku.setDiscounts(newDiscounts); } entityManager.persist(sku); return sku; } @DELETE @Transactional @Path("/{skuId}") @RolesAllowed({ADMIN, STORE_ADMIN}) @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public void delete(@Context SecurityContext securityContext, @PathParam("skuId") Long skuId) { SKU sku = entityManager.find(SKU.class, skuId); checkNotNull(sku); if (isAdminUser(securityContext) || isOwner(securityContext, sku.getOwner())) { List<Product> productHolders = catalogItemFinder.findForeignHolder(QProduct.product, QProduct.product.childSKUs, sku); for (Product product : productHolders) { product.getChildSKUs().remove(sku); } List<Discount> discountHolders = catalogItemFinder.findForeignHolder(QDiscount.discount, QDiscount.discount.skus, sku); for (Discount discount : discountHolders) { sku.getDiscounts().remove(discount); discount.getSkus().remove(sku); } entityManager.remove(sku); } else throw new WebApplicationException(Response.Status.FORBIDDEN); } @PUT @Transactional @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @RolesAllowed({ADMIN, STORE_ADMIN}) public SKU modify(@Context SecurityContext securityContext, SKU sku) { SKU originalSKU = entityManager.find(SKU.class, sku.getId()); checkNotNull(originalSKU); if (isAdminUser(securityContext) || isOwner(securityContext, originalSKU.getOwner())) { if (sku.getDiscountsIds() != null) { List<Discount> newDiscounts = new ArrayList<>(); sku.getDiscountsIds().forEach(discountId -> newDiscounts.add(entityManager.find(Discount.class, discountId))); sku.setDiscounts(newDiscounts); } else { sku.setDiscounts(originalSKU.getDiscounts()); } sku.setPresentationByLocale(originalSKU.getPresentationByLocale()); return entityManager.merge(sku); } else { throw new WebApplicationException(Response.Status.FORBIDDEN); } } @GET @Path("/") @Produces(MediaType.APPLICATION_JSON) @RolesAllowed({ADMIN, ADMIN_READONLY}) public List<SKU> findAll(@QueryParam("search") String search, @QueryParam("start") Integer start, @QueryParam("size") Integer size , @QueryParam("orderBy") String orderBy, @QueryParam("isDesc") Boolean isDesc, @QueryParam("locale") String locale) { if (search != null) return catalogItemFinder.findBySearchCriteria(sKU, search, start, size, orderBy, isDesc, locale); else return catalogItemFinder.findAll(sKU, start, size, orderBy, isDesc, locale); } @GET @Path("/count") @Produces(MediaType.APPLICATION_JSON) @RolesAllowed({ADMIN, ADMIN_READONLY}) public Long count(@QueryParam("search") String search) { if (search != null) return catalogItemFinder.countBySearchCriteria(sKU, search); else return catalogItemFinder.countAll(sKU); } @GET @Path("/{skuId}") @Produces(MediaType.APPLICATION_JSON) @PermitAll public SKU find(@Context SecurityContext securityContext, @PathParam("skuId") @NotNull Long skuId, @QueryParam("locale") String locale) { SKU sku = entityManager.find(SKU.class, skuId); checkNotNull(sku); if (isAdminUser(securityContext) || isOwner(securityContext, sku.getOwner())) return sku; else return catalogItemFinder.filterVisible(sku, locale); } @GET @Path("/{skuId}/presentationslocales") @Produces(MediaType.APPLICATION_JSON) @RolesAllowed({ADMIN, STORE_ADMIN, ADMIN_READONLY}) public Set<String> findPresentationsLocales(@Context SecurityContext securityContext, @PathParam("skuId") @NotNull Long skuId) { SKU sku = entityManager.find(SKU.class, skuId); checkNotNull(sku); if (!isAdminUser(securityContext) && !isOwner(securityContext, sku.getOwner())) throw new WebApplicationException(Response.Status.FORBIDDEN); return sku.getPresentationByLocale().keySet(); } @Path("/{skuId}/presentations/{locale}") @PermitAll public PresentationResource findPresentationByLocale(@PathParam("skuId") @NotNull Long skuId, @NotNull @PathParam("locale") String locale) { SKU sku = entityManager.find(SKU.class, skuId); checkNotNull(sku); Presentation presentation = sku.getPresentationByLocale().get(locale); return presentationResource.init(sku, locale, presentation); } @GET @Path("/{skuId}/discounts") @Produces(MediaType.APPLICATION_JSON) @RolesAllowed({ADMIN, STORE_ADMIN, ADMIN_READONLY}) public List<Discount> findDiscounts(@Context SecurityContext securityContext, @PathParam("skuId") @NotNull Long skuId) { SKU sku = entityManager.find(SKU.class, skuId); checkNotNull(sku); List<Discount> discounts = sku.getDiscounts(); if (discounts.isEmpty()) { return new ArrayList<>(); } if (isAdminUser(securityContext) || isOwner(securityContext, sku.getOwner())) return discounts; else return catalogItemFinder.findVisibleCatalogItems(discount, discounts, null); } private void checkNotNull(SKU sku) { if (sku == null) { throw new WebApplicationException(Response.Status.NOT_FOUND); } } } <|start_filename|>catalog/src/main/java/org/rembx/jeeshop/catalog/model/Presentation.java<|end_filename|> package org.rembx.jeeshop.catalog.model; import org.rembx.jeeshop.media.model.Media; import javax.json.bind.annotation.JsonbTransient; import javax.persistence.*; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlTransient; import javax.xml.bind.annotation.XmlType; import java.util.List; import java.util.Map; /** * Hold presentation data associated to catalog items such as descriptions, * media... * */ @Entity @XmlType @XmlAccessorType(XmlAccessType.FIELD) @Cacheable public class Presentation { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @NotNull @Size(min = 1, max = 25) @Column(length = 25, nullable=false) private String locale; @Size(max = 255) @Column(length = 255) private String displayName; @Size(max = 255) @Column(length = 255) private String promotion; @Size(max = 1000) @Column(length =1000) private String shortDescription; @Size(max = 2000) @Column(length =2000) private String mediumDescription; @Size(max = 5000 ) @Column(length = 5000) private String longDescription; @ManyToOne(cascade = {CascadeType.PERSIST,CascadeType.MERGE, CascadeType.REMOVE}) @JoinColumn(referencedColumnName = "id") private Media thumbnail; @ManyToOne(cascade = {CascadeType.PERSIST,CascadeType.MERGE, CascadeType.REMOVE}) @JoinColumn(referencedColumnName = "id") private Media smallImage; @ManyToOne(cascade = {CascadeType.PERSIST,CascadeType.MERGE, CascadeType.REMOVE}) @JoinColumn(referencedColumnName = "id") private Media largeImage; @ManyToOne(cascade = {CascadeType.PERSIST,CascadeType.MERGE, CascadeType.REMOVE}) @JoinColumn(referencedColumnName = "id") private Media video; @ManyToMany(cascade = {CascadeType.PERSIST,CascadeType.MERGE, CascadeType.REMOVE}) @JoinTable(joinColumns = @JoinColumn(name = "presentationId"), inverseJoinColumns = @JoinColumn(name = "mediaId")) @OrderColumn(name = "orderIdx") @JsonbTransient private List<Media> otherMedia; @ElementCollection(fetch = FetchType.EAGER) @MapKeyColumn(name="name") @Column(name="value") @CollectionTable(name="Presentation_Feature", joinColumns=@JoinColumn(name="presentationId")) private Map<String,String> features; public Presentation() { } public Presentation(String locale, String displayName, String shortDescription, String description) { this.locale = locale; this.displayName = displayName; this.shortDescription = shortDescription; this.longDescription = description; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getLocale() { return locale; } public void setLocale(String locale) { this.locale = locale; } public String getDisplayName() { return displayName; } public void setDisplayName(String displayName) { this.displayName = displayName; } public String getShortDescription() { return shortDescription; } public void setShortDescription(String shortDescription) { this.shortDescription = shortDescription; } public String getLongDescription() { return longDescription; } public void setLongDescription(String description) { this.longDescription = description; } public Media getThumbnail() { return thumbnail; } public void setThumbnail(Media thumbnail) { this.thumbnail = thumbnail; } public Media getSmallImage() { return smallImage; } public void setSmallImage(Media smallImage) { this.smallImage = smallImage; } public Media getLargeImage() { return largeImage; } public void setLargeImage(Media largeImage) { this.largeImage = largeImage; } public Media getVideo() { return video; } public void setVideo(Media video) { this.video = video; } public List<Media> getOtherMedia() { return otherMedia; } public void setOtherMedia(List<Media> otherMedia) { this.otherMedia = otherMedia; } public Map<String, String> getFeatures() { return features; } public void setFeatures(Map<String, String> features) { this.features = features; } public String getPromotion() { return promotion; } public void setPromotion(String promotion) { this.promotion = promotion; } public String getMediumDescription() { return mediumDescription; } public void setMediumDescription(String mediumDescription) { this.mediumDescription = mediumDescription; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Presentation that = (Presentation) o; if (displayName != null ? !displayName.equals(that.displayName) : that.displayName != null) return false; if (id != null ? !id.equals(that.id) : that.id != null) return false; if (locale != null ? !locale.equals(that.locale) : that.locale != null) return false; if (shortDescription != null ? !shortDescription.equals(that.shortDescription) : that.shortDescription != null) return false; return true; } @Override public int hashCode() { int result = id != null ? id.hashCode() : 0; result = 31 * result + (locale != null ? locale.hashCode() : 0); result = 31 * result + (displayName != null ? displayName.hashCode() : 0); result = 31 * result + (shortDescription != null ? shortDescription.hashCode() : 0); return result; } } <|start_filename|>admin/src/main/webapp/app/app.js<|end_filename|> require('../node_modules/jquery/dist/jquery.min.js'); require('../node_modules/angular-file-upload-shim/dist/angular-file-upload-html5-shim.js'); require('../node_modules/angular/angular.js'); require('../node_modules/angular-sanitize/angular-sanitize.js'); require('../node_modules/angular-ui-router/release/angular-ui-router.js'); require('../node_modules/angular-file-upload-shim/dist/angular-file-upload.js'); require('../node_modules/angular-ui-bootstrap/dist/ui-bootstrap-tpls.js'); require ('./util/js/util.js'); require ('./user/js/login.js'); require ('./user/js/user.js'); require ('./order/js/order.js'); require ('./mail/js/mail.js'); require ('./catalog/js/catalog.js'); (function () { var app = angular.module('admin', ['ui.bootstrap', 'ui.router', 'angularFileUpload', 'admin-util', 'admin-catalog', 'admin-login', 'admin-user', 'admin-mail', 'admin-order']); app.controller('RestrictedAccessController', ['$state', 'AuthService', function ($state, AuthService) { var ctrl = this; ctrl.hasAccess = function () { if (!AuthService.isAuthenticated()) { $state.go('home'); return false; } return true; }; }]); app.controller('DatepickerDemoCtrl', ['$scope', function ($scope) { $scope.today = function () { $scope.dt = new Date(); }; $scope.today(); $scope.open = function ($event) { $event.preventDefault(); $event.stopPropagation(); $scope.opened = true; }; $scope.dateOptions = { startingDay: 1 }; }]); app.config(['$stateProvider', '$urlRouterProvider', '$locationProvider', function ($stateProvider, $urlRouterProvider, $locationProvider) { // For any unmatched url, redirect to /home $urlRouterProvider.otherwise("home"); $locationProvider.hashPrefix("!"); $stateProvider .state('home', { url: "/home", templateUrl: "app/home/index.html" }) .state('index', { url: "", templateUrl: "app/home/index.html" }) .state('catalog', { url: "/catalog", templateUrl: 'app/catalog/index.html' }) .state('catalog.items', { url: "/:resource", templateUrl: 'app/catalog/catalog-entries.html' }) .state('catalog.items.detail', { url: "/:itemId", templateUrl: function ($stateParams) { return 'app/catalog/' + $stateParams.resource + '-form.html'; } }) .state('user', { url: "/user", templateUrl: 'app/user/index.html' }) .state('user.users', { url: "/users", templateUrl: 'app/user/user-entries.html' }) .state('user.users.detail', { url: "/:userId", templateUrl: 'app/user/user-form.html' }) .state('order', { url: "/order", templateUrl: 'app/order/index.html' }) .state('order.orders', { url: "/orders", templateUrl: 'app/order/order-entries.html' }) .state('order.operations', { url: "/operations", templateUrl: 'app/order/order-operations.html' }) .state('order.orders.detail', { url: "/:orderId", templateUrl: 'app/order/order-form.html' }) .state('mail', { url: "/mail", templateUrl: "app/mail/index.html" }) .state('mail.templates', { url: "/mail", templateUrl: "app/mail/mailtemplate-entries.html" }) .state('mail.operations', { url: "/mail", templateUrl: "app/mail/mail-operations.html" }) .state('mail.templates.detail', { url: "/:mailId", templateUrl: "app/mail/mailtemplate-form.html" }) .state('statistic', { url: "/statistic", templateUrl: 'app/statistic/index.html' }); }]); })(); <|start_filename|>catalog/src/test/java/org/rembx/jeeshop/catalog/ProductsCT.java<|end_filename|> package org.rembx.jeeshop.catalog; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.rembx.jeeshop.catalog.model.Product; import org.rembx.jeeshop.catalog.model.SKU; import org.rembx.jeeshop.catalog.test.CatalogItemCRUDTester; import org.rembx.jeeshop.catalog.test.TestCatalog; import org.rembx.jeeshop.rest.WebApplicationException; import javax.ws.rs.core.Response; import java.util.Date; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; import static org.rembx.jeeshop.catalog.test.Assertions.assertThatSKUsOf; public class ProductsCT { private Products localService; private CatalogItemCRUDTester<Product> tester; @BeforeEach public void setup() { tester = new CatalogItemCRUDTester<>(Product.class); localService = new Products(tester.getEntityManager(), new CatalogItemFinder(tester.getEntityManager()), null); tester.setService(this.localService); } @Test public void find_withIdOfVisibleProduct_ShouldReturnExpectedProduct() { assertThat(localService.find(null, tester.getFixtures().aProductWithSKUs().getId(), null)).isEqualTo(tester.getFixtures().aProductWithSKUs()); assertThat(localService.find(null, tester.getFixtures().aProductWithSKUs().getId(), null).isVisible()).isTrue(); } @Test public void find_withIdOfDisableProduct_ShouldThrowForbiddenException() { try { localService.find(null, tester.getFixtures().aDisabledProduct().getId(), null); fail("should have thrown ex"); } catch (WebApplicationException e) { assertThat(e.getResponse().getStatusInfo()).isEqualTo(Response.Status.FORBIDDEN); } } @Test public void find_withIdOfExpiredProduct_ShouldThrowForbiddenException() { try { localService.find(null, tester.getFixtures().anExpiredProduct().getId(), null); fail("should have thrown ex"); } catch (WebApplicationException e) { assertThat(e.getResponse().getStatusInfo()).isEqualTo(Response.Status.FORBIDDEN); } } @Test public void find_withUnknownProductId_ShouldThrowNotFoundException() { try { localService.find(null, 9999L, null); fail("should have thrown ex"); } catch (WebApplicationException e) { assertThat(e.getResponse().getStatusInfo()).isEqualTo(Response.Status.NOT_FOUND); } } @Test public void findSKUs_shouldReturn404ExWhenProductNotFound() { try { localService.findChildSKUs(null, 9999L, null); fail("should have thrown ex"); } catch (WebApplicationException e) { assertThat(e.getResponse().getStatusInfo()).isEqualTo(Response.Status.NOT_FOUND); } } @Test public void findSKUs_shouldNotReturnExpiredNorDisabledSKUs() { List<SKU> skus = localService.findChildSKUs(null, tester.getFixtures().aProductWithSKUs().getId(), null); assertThat(skus).isNotEmpty(); assertThatSKUsOf(skus).areVisibleSKUsOfAProductWithSKUs(); } @Test public void findSKUs_shouldReturnEmptyListWhenNoChildProducts() { List<SKU> skus = localService.findChildSKUs(null, tester.getFixtures().aProductWithoutSKUs().getId(), null); assertThat(skus).isEmpty(); } @Test public void findAll_shouldReturnNoneEmptyList() { assertThat(localService.findAll(null, null, null, null, null, null)).isNotEmpty(); } @Test public void findAll_withPagination_shouldReturnNoneEmptyListPaginated() { List<Product> categories = localService.findAll(null, 0, 1, null, null, null); assertThat(categories).isNotEmpty(); assertThat(categories).hasSize(1); } @Test public void findAll_withIdSearchParam_shouldReturnResultsWithMatchingId() { assertThat(localService.findAll(tester.getFixtures().aProductWithoutSKUs().getId().toString(), null, null, null, null, null)).containsExactly(tester.getFixtures().aProductWithoutSKUs()); } @Test public void findAll_withNameSearchParam_shouldReturnResultsWithMatchingName() { assertThat(localService.findAll(tester.getFixtures().aProductWithoutSKUs().getName(), null, null, null, null, null)).containsExactly(tester.getFixtures().aProductWithoutSKUs()); } @Test public void modifyProduct_ShouldModifyProductAttributesAndPreserveSKUsWhenNotProvided() { tester.setAdminUser(); Product product = new Product(tester.getFixtures().aProductWithSKUs().getId(), "New name"); tester.test_modify(product); assertThat(product.getName()).isEqualTo("New name"); assertThat(product.getChildSKUs()).containsOnlyElementsOf(product.getChildSKUs()); } @Test public void modifyUnknownProduct_ShouldThrowNotFoundException() { Product detachedProductToModify = new Product(9999L, null); try { tester.setAdminUser(); localService.modify(tester.getSecurityContext(), detachedProductToModify); fail("should have thrown ex"); } catch (WebApplicationException e) { assertThat(e.getResponse().getStatusInfo()).isEqualTo(Response.Status.NOT_FOUND); } } @Test public void countAll() { assertThat(localService.count(null)).isGreaterThan(0); } @Test public void countAll_withUnknownSearchCriteria() { assertThat(localService.count("666")).isEqualTo(0); } @Test public void create_shouldPersist_for_admin() { tester.setAdminUser(); Product product = new Product("name", "description", new Date(), new Date(), false, TestCatalog.OWNER); Product actualProduct = tester.test_create(product); assertThat(actualProduct).isNotNull(); assertThat(actualProduct.getOwner()).isEqualTo(TestCatalog.OWNER); } @Test public void create_withoutOwner_shouldThrow_BadRequest_for_admin() { try { tester.setAdminUser(); Product product = new Product("name"); tester.test_create(product); fail("Should have thrown an exception"); } catch (WebApplicationException e) { assertThat(e.getResponse().getStatusInfo()).isEqualTo(Response.Status.BAD_REQUEST); } } @Test public void create_shouldPersist_for_store_admin() { tester.setAdminUser(); Product product = new Product("name", "description", new Date(), new Date(), false, TestCatalog.OWNER); Product actualProduct = tester.test_create(product); assertThat(actualProduct).isNotNull(); assertThat(actualProduct.getOwner()).isEqualTo(TestCatalog.OWNER); } @Test public void delete_shouldRemove() { tester.setStoreAdminUser(); Product product = new Product("Test", "", null, null, null, "<EMAIL>"); product.setOwner(TestCatalog.OWNER); tester.test_delete(product); assertThat(tester.getEntityManager().find(Product.class, product.getId())).isNull(); } @Test public void delete_NonManagedEntity_shouldThrow_Forbidden() { try { tester.setStoreAdminUser(); Product product = new Product("Test", "", null, null, null, "<EMAIL>"); tester.test_delete(product); } catch (WebApplicationException e) { assertThat(e.getResponse().getStatusInfo()).isEqualTo(Response.Status.FORBIDDEN); } } @Test public void delete_NotExistingEntry_shouldThrowNotFoundEx() { try { tester.setAdminUser(); localService.delete(tester.getSecurityContext(), 666L); fail("should have thrown ex"); } catch (WebApplicationException e) { assertThat(e.getResponse().getStatusInfo()).isEqualTo(Response.Status.NOT_FOUND); } } } <|start_filename|>common/src/main/java/org/rembx/jeeshop/util/LocaleUtil.java<|end_filename|> package org.rembx.jeeshop.util; import org.apache.commons.lang.LocaleUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Locale; public class LocaleUtil { private static Logger logger = LoggerFactory.getLogger(LocaleUtil.class); public static final Locale FALLBACK = Locale.ENGLISH; public static String getLocaleCode(String localeStr) { Locale locale = FALLBACK; try { locale = (localeStr != null)? LocaleUtils.toLocale(localeStr):FALLBACK; } catch (IllegalArgumentException e) { logger.warn("cannot get locale from {}. Returning fallback locale: "+FALLBACK,localeStr); } return locale.toString(); } } <|start_filename|>media/src/test/java/org/rembx/jeeshop/media/MediasTest.java<|end_filename|> package org.rembx.jeeshop.media; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.rembx.jeeshop.rest.WebApplicationException; import javax.ws.rs.core.Response; import java.io.File; import java.nio.file.Files; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; public class MediasTest { Medias medias; @BeforeEach public void setup() { medias = new Medias(); } @Test public void get_shouldReturnFile_whenThereIsAFileWithPathMatchingGivenParams() throws Exception { java.nio.file.Path basePath = medias.getBasePath(); java.nio.file.Path testFilePath = basePath.resolve("categories").resolve("999").resolve("en_GB"); if (!Files.exists(testFilePath)) { Files.createDirectories(testFilePath); } File testFile = new File(testFilePath.toFile(), "testMedias.test"); testFile.createNewFile(); assertThat(medias.get("categories", 999L, "en_GB", "testMedias.test")).isNotNull(); } @Test public void get_shouldThrowNotFound_whenThereAreNoFileMatchingGivenParams() throws Exception { try { medias.get("categories", 999L, "en_GB", "unknown.test"); fail("Should have thrown ex"); } catch (WebApplicationException e) { assertThat(e.getResponse().getStatus()).isEqualTo(Response.Status.NOT_FOUND.getStatusCode()); } } } <|start_filename|>common/src/test/java/org/rembx/jeeshop/util/LocaleUtilTest.java<|end_filename|> package org.rembx.jeeshop.util; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class LocaleUtilTest { @Test public void getLocaleCode_shouldReturnLocaleCode() throws Exception { assertThat(LocaleUtil.getLocaleCode("en_GB")).isEqualTo("en_GB"); } @Test public void getLocaleCode_shouldFallbackForInvalidLocale() throws Exception { assertThat(LocaleUtil.getLocaleCode("qsdpjsd")).isEqualTo(LocaleUtil.FALLBACK.toString()); } @Test public void getLocaleCode_shouldFallbackWhenNullLocaleProvided() throws Exception { assertThat(LocaleUtil.getLocaleCode(null)).isEqualTo(LocaleUtil.FALLBACK.toString()); } } <|start_filename|>common/src/main/java/org/rembx/jeeshop/role/JeeshopRoles.java<|end_filename|> package org.rembx.jeeshop.role; /** * Jeeshop roles */ public interface JeeshopRoles { String USER = "user"; String ADMIN = "admin"; String ADMIN_READONLY = "adminRO"; String STORE_ADMIN = "store_admin"; } <|start_filename|>catalog/src/main/java/org/rembx/jeeshop/catalog/OwnerUtils.java<|end_filename|> package org.rembx.jeeshop.catalog; <|start_filename|>catalog/src/main/java/org/rembx/jeeshop/catalog/CatalogItemFinder.java<|end_filename|> package org.rembx.jeeshop.catalog; import com.querydsl.core.types.EntityPath; import com.querydsl.core.types.dsl.BooleanExpression; import com.querydsl.core.types.dsl.ComparableExpressionBase; import com.querydsl.core.types.dsl.ListPath; import com.querydsl.core.types.dsl.SimpleExpression; import com.querydsl.jpa.impl.JPAQuery; import com.querydsl.jpa.impl.JPAQueryFactory; import io.quarkus.hibernate.orm.PersistenceUnit; import io.quarkus.security.identity.SecurityIdentity; import org.apache.commons.lang.math.NumberUtils; import org.rembx.jeeshop.catalog.model.*; import org.rembx.jeeshop.rest.WebApplicationException; import org.rembx.jeeshop.role.JeeshopRoles; import javax.enterprise.context.ApplicationScoped; import javax.persistence.EntityManager; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import static org.rembx.jeeshop.catalog.model.QStore.store; /** * Utility class for common finders on CatalogItem entities */ @ApplicationScoped public class CatalogItemFinder { private EntityManager entityManager; CatalogItemFinder(@PersistenceUnit(value = CatalogPersistenceUnit.NAME) EntityManager entityManager) { this.entityManager = entityManager; } public <T extends CatalogItem> List<T> findVisibleCatalogItems(EntityPath<T> entityPath, List<T> items, String locale) { QCatalogItem qCatalogItem = new QCatalogItem(entityPath); Date now = new Date(); List<T> results = new JPAQueryFactory(entityManager) .selectFrom(entityPath).where( qCatalogItem.disabled.isFalse(), qCatalogItem.endDate.after(now).or(qCatalogItem.endDate.isNull()), qCatalogItem.startDate.before(now).or(qCatalogItem.startDate.isNull()), qCatalogItem.in(items) ) .fetch(); results.forEach((catalogItem) -> { catalogItem.setLocalizedPresentation(locale); mapCatalogItemChildrenPresentation(catalogItem, locale); }); return results; } public <T extends CatalogItem> List<T> findAll(EntityPath<T> entityPath, Integer offset, Integer limit, String orderBy, Boolean isDesc, String locale) { QCatalogItem qCatalogItem = new QCatalogItem(entityPath); JPAQuery<T> query = new JPAQueryFactory(entityManager).selectFrom(entityPath); addOffsetAndLimitToQuery(offset, limit, query, orderBy, isDesc, qCatalogItem); List<T> catalogItems = query.fetch(); return locale != null ? catalogItems.stream().peek(c -> { c.setLocalizedPresentation(locale); mapCatalogItemChildrenPresentation(c, locale); }).collect(Collectors.toList()) : catalogItems; } public <T extends CatalogItem, P extends CatalogItem> List<P> findForeignHolder(EntityPath<P> hp, ListPath<T, ? extends SimpleExpression<T>> h, T c) { return new JPAQueryFactory(entityManager) .selectFrom(hp) .where(h.contains(c)) .fetch(); } public <T extends CatalogItem> List<T> findBySearchCriteria(EntityPath<T> entityPath, String searchCriteria, Integer offset, Integer limit, String orderBy, Boolean isDesc, String locale) { QCatalogItem qCatalogItem = new QCatalogItem(entityPath); JPAQuery<T> query = new JPAQueryFactory(entityManager).selectFrom(entityPath) .where(buildSearchPredicate(searchCriteria, qCatalogItem)); addOffsetAndLimitToQuery(offset, limit, query, orderBy, isDesc, qCatalogItem); List<T> fetch = query.fetch(); return locale != null ? fetch.stream().peek(c -> { c.setLocalizedPresentation(locale); mapCatalogItemChildrenPresentation(c, locale); }).collect(Collectors.toList()) : fetch; } public Long countAll(EntityPath<? extends CatalogItem> entityPath) { QCatalogItem qCatalogItem = new QCatalogItem(entityPath); JPAQuery query = new JPAQueryFactory(entityManager).selectFrom(qCatalogItem); return query.fetchCount(); } public Long countBySearchCriteria(EntityPath<? extends CatalogItem> entityPath, String searchCriteria) { QCatalogItem qCatalogItem = new QCatalogItem(entityPath); JPAQuery query = new JPAQueryFactory(entityManager) .selectFrom(qCatalogItem) .where(buildSearchPredicate(searchCriteria, qCatalogItem)); return query.fetchCount(); } public <T extends CatalogItem> T filterVisible(T catalogItem, String locale) { if (catalogItem == null) { throw new WebApplicationException(Response.Status.NOT_FOUND); } if (!catalogItem.isVisible()) { throw new WebApplicationException((Response.Status.FORBIDDEN)); } catalogItem.setLocalizedPresentation(locale); mapCatalogItemChildrenPresentation(catalogItem, locale); return catalogItem; } private <T extends CatalogItem> void mapCatalogItemChildrenPresentation(T catalogItem, String locale) { if (locale == null) return; if (catalogItem instanceof Catalog) { ((Catalog) catalogItem).setRootCategories(((Catalog) catalogItem).getRootCategories().stream() .peek(c -> c.setLocalizedPresentation(locale)) .collect(Collectors.toList())); } else if (catalogItem instanceof Category) { ((Category) catalogItem).setChildCategories(((Category) catalogItem).getChildCategories().stream() .peek(c -> c.setLocalizedPresentation(locale)) .collect(Collectors.toList())); } else if (catalogItem instanceof Product) { ((Product) catalogItem).setChildSKUs(((Product) catalogItem).getChildSKUs().stream() .peek(c -> c.setLocalizedPresentation(locale)) .collect(Collectors.toList())); ((Product) catalogItem).setDiscounts(((Product) catalogItem).getDiscounts().stream() .peek(c -> c.setLocalizedPresentation(locale)) .collect(Collectors.toList())); } } private void addOffsetAndLimitToQuery(Integer offset, Integer limit, JPAQuery query, String orderBy, Boolean isDesc, QCatalogItem qCatalogItem) { if (offset != null) query.offset(offset); if (limit != null) query.limit(limit); sortBy(orderBy, isDesc, query, qCatalogItem); } private BooleanExpression buildSearchPredicate(String search, QCatalogItem qCatalogItem) { BooleanExpression searchPredicate = qCatalogItem.name.containsIgnoreCase(search) .or(qCatalogItem.description.containsIgnoreCase(search)); if (NumberUtils.isNumber(search)) { Long searchId = Long.parseLong(search); searchPredicate = qCatalogItem.id.eq(searchId); } return searchPredicate; } private <T extends CatalogItem> void sortBy(String orderby, Boolean isDesc, JPAQuery<T> query, QCatalogItem qCatalogItem) { Map<String, ComparableExpressionBase<?>> sortProperties = new HashMap<String, ComparableExpressionBase<?>>() {{ put("id", qCatalogItem.id); put("name", qCatalogItem.name); put("description", qCatalogItem.description); put("startDate", qCatalogItem.startDate); put("endDate", qCatalogItem.endDate); put("disabled", qCatalogItem.disabled); }}; if (orderby != null && sortProperties.containsKey(orderby)) { if (isDesc) { query.orderBy(sortProperties.get(orderby).desc()); } else { query.orderBy(sortProperties.get(orderby).asc()); } } } public <T extends CatalogItem> T findOne(EntityPath<T> entityPath, Long itemId, SecurityContext securityIdentity) { QCatalogItem qCatalogItem = new QCatalogItem(entityPath); JPAQuery<T> query = new JPAQueryFactory(entityManager) .selectFrom(entityPath) .where(qCatalogItem.id.eq(itemId)); if (securityIdentity.isUserInRole(JeeshopRoles.ADMIN)) { return query.fetchOne(); } else if (securityIdentity.isUserInRole(JeeshopRoles.STORE_ADMIN)) { return query.where(qCatalogItem.owner.eq(securityIdentity.getUserPrincipal().getName())) .fetchOne(); } throw new WebApplicationException(Response.Status.FORBIDDEN); } } <|start_filename|>media/src/main/java/org/rembx/jeeshop/media/Medias.java<|end_filename|> package org.rembx.jeeshop.media; import org.apache.commons.fileupload.FileItemIterator; import org.apache.commons.fileupload.FileItemStream; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.apache.commons.lang.StringUtils; import org.rembx.jeeshop.rest.WebApplicationException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.security.RolesAllowed; import javax.servlet.http.HttpServletRequest; import javax.validation.constraints.NotNull; import javax.ws.rs.*; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import static org.rembx.jeeshop.role.JeeshopRoles.ADMIN; import static org.rembx.jeeshop.role.JeeshopRoles.ADMIN_READONLY; /** * TODO file location base folder to be accessible by web server */ @Path("/rs/medias") public class Medias { static final String JEESHOP_MEDIA_DIR = "jeeshop-media"; static final String JEESHOP_DATA_DIR = "JEESHOP_DATA_DIR"; static final String OPENSHIFT_DATA_DIR = "OPENSHIFT_DATA_DIR"; private static Logger LOG = LoggerFactory.getLogger(Medias.class); @POST @Consumes("multipart/form-data") @Produces(MediaType.APPLICATION_JSON) @RolesAllowed(ADMIN) @Path("/{type}/{id}/{locale}/upload") public void upload(@Context HttpServletRequest request, @NotNull @PathParam("type") String itemType, @NotNull @PathParam("id") Long itemId, @NotNull @PathParam("locale") String locale) { try { ServletFileUpload upload = new ServletFileUpload(); FileItemIterator iterator = upload.getItemIterator(request); while (iterator.hasNext()) { FileItemStream item = iterator.next(); java.nio.file.Path itemBasePath = getBasePath().resolve(itemType).resolve(itemId.toString()).resolve(locale); if (!Files.exists(itemBasePath)) Files.createDirectories(itemBasePath); java.nio.file.Path filePath = itemBasePath.resolve(item.getName()); Files.copy(item.openStream(), filePath, StandardCopyOption.REPLACE_EXISTING); LOG.info("File written to " + filePath); } } catch (IOException | FileUploadException e) { LOG.error("Could not handle upload of file with type: " + itemType + " and id: " + itemId, e); throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR); } } @GET @Produces(MediaType.APPLICATION_OCTET_STREAM) @RolesAllowed({ADMIN, ADMIN_READONLY}) @Path("/{type}/{id}/{locale}/{filename}") public File get(@NotNull @PathParam("type") String itemType, @NotNull @PathParam("id") Long itemId, @NotNull @PathParam("locale") String locale, @NotNull @PathParam("filename") String fileName) { java.nio.file.Path filePath = getBasePath().resolve(itemType).resolve(itemId.toString()).resolve(locale).resolve(fileName); if (!Files.exists(filePath)) throw new WebApplicationException(Response.Status.NOT_FOUND); return filePath.toFile(); } java.nio.file.Path getBasePath() { java.nio.file.Path path; if (StringUtils.isNotEmpty(System.getenv(OPENSHIFT_DATA_DIR))) { path = Paths.get(System.getenv(OPENSHIFT_DATA_DIR)).resolve(JEESHOP_MEDIA_DIR); } else if (StringUtils.isNotEmpty(System.getenv(JEESHOP_DATA_DIR))) { path = Paths.get(System.getenv(JEESHOP_DATA_DIR)).resolve(JEESHOP_MEDIA_DIR); } else { path = Paths.get(Medias.JEESHOP_MEDIA_DIR); } return path; } } <|start_filename|>admin/src/main/webapp/app/util/confirm-delete-danger.html<|end_filename|> <div class="modal-header"> <div class="alert alert-danger text-center" role="alert"> <span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span> <span class="sr-only">Error:</span> ITEM REMOVAL<br/><b>No way back !</b> </div> </div> <div class="modal-body"> <p>{{confirmMessage}}</p> <p><b>Are you sure?</b> (We strongly recommend you to archive this item instead)</p> </div> <div class="modal-footer"> <button class="btn btn-primary" ng-click="modalInstance.dismiss()">Cancel</button> <button class="btn btn-danger" ng-click="modalInstance.close()" style="margin-left:1em">Delete</button> </div> <|start_filename|>user/src/test/java/org/rembx/jeeshop/order/model/OrderTest.java<|end_filename|> package org.rembx.jeeshop.order.model; import org.junit.jupiter.api.Test; import java.text.SimpleDateFormat; import static org.assertj.core.api.Assertions.assertThat; public class OrderTest { Order order; @Test public void testPrePersist() throws Exception { Order order = new Order(); assertThat(order.getUpdateDate()).isNull(); order.prePersist(); assertThat(order.getUpdateDate()).isNotNull(); } @Test public void testPreUpdate() throws Exception { Order order = new Order(); assertThat(order.getCreationDate()).isNull(); assertThat(order.getUpdateDate()).isNull(); order.prePersist(); assertThat(order.getCreationDate()).isNotNull(); assertThat(order.getUpdateDate()).isNotNull(); } @Test public void computeOrderReference_orderWithoutTransactionId() throws Exception { order = new Order(); order.setId(1L); order.setCreationDate(new SimpleDateFormat("MMddyyyy").parse("11222222")); assertThat(order.getReference()).isNull(); order.computeOrderReference(); assertThat(order.getReference()).isEqualTo("11222222-1"); } @Test public void computeOrderReference_orderWithTransactionId() throws Exception { order = new Order(); order.setId(1L); order.setCreationDate(new SimpleDateFormat("MMddyyyy").parse("11222222")); order.setTransactionId("1234"); order.computeOrderReference(); assertThat(order.getReference()).isEqualTo("11222222-1-1234"); } } <|start_filename|>user/src/main/java/org/rembx/jeeshop/user/MailTemplates.java<|end_filename|> package org.rembx.jeeshop.user; import freemarker.template.Configuration; import freemarker.template.Template; import io.quarkus.hibernate.orm.PersistenceUnit; import org.rembx.jeeshop.mail.Mailer; import org.rembx.jeeshop.rest.WebApplicationException; import org.rembx.jeeshop.user.model.MailTemplate; import org.rembx.jeeshop.user.model.UserPersistenceUnit; import javax.annotation.security.RolesAllowed; import javax.enterprise.context.ApplicationScoped; import javax.enterprise.context.RequestScoped; import javax.inject.Inject; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.transaction.Transactional; import javax.validation.constraints.NotNull; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.io.StringWriter; import java.util.List; import static org.rembx.jeeshop.role.JeeshopRoles.ADMIN; import static org.rembx.jeeshop.role.JeeshopRoles.ADMIN_READONLY; /** * Mail template resource */ @Path("/rs/mailtemplates") @ApplicationScoped public class MailTemplates { private Mailer mailer; private EntityManager entityManager; private MailTemplateFinder mailTemplateFinder; MailTemplates(@PersistenceUnit(UserPersistenceUnit.NAME) EntityManager entityManager, MailTemplateFinder mailTemplateFinder, Mailer mailer) { this.entityManager = entityManager; this.mailTemplateFinder = mailTemplateFinder; this.mailer = mailer; } @POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @RolesAllowed(ADMIN) public MailTemplate create(MailTemplate mailTemplate) { MailTemplate existingTpl = mailTemplateFinder.findByNameAndLocale(mailTemplate.getName(), mailTemplate.getLocale()); if (existingTpl != null) { throw new WebApplicationException(Response.Status.CONFLICT); } entityManager.persist(mailTemplate); return mailTemplate; } @POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @RolesAllowed(ADMIN) @Path("/test/{recipient}") public void sendTestEmail(Object properties, @NotNull @QueryParam("templateName") String templateName, @NotNull @QueryParam("locale") String locale, @NotNull @PathParam("recipient") String recipient) { MailTemplate existingTpl = mailTemplateFinder.findByNameAndLocale(templateName, locale); if (existingTpl == null) { throw new WebApplicationException(Response.Status.NOT_FOUND); } try { sendMail(existingTpl, recipient, properties); } catch (Exception e) { throw new IllegalStateException(e); } } @DELETE @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @RolesAllowed(ADMIN) @Transactional @Path("/{id}") public void delete(@PathParam("id") Long id) { MailTemplate mailTemplate = entityManager.find(MailTemplate.class, id); checkNotNull(mailTemplate); entityManager.remove(mailTemplate); } @PUT @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Transactional @RolesAllowed(ADMIN) public MailTemplate modify(MailTemplate mailTemplate) { MailTemplate existingMailTemplate = entityManager.find(MailTemplate.class, mailTemplate.getId()); checkNotNull(existingMailTemplate); MailTemplate existingTplWithSameLocaleAndName = mailTemplateFinder.findByNameAndLocale(mailTemplate.getName(), mailTemplate.getLocale()); if (existingTplWithSameLocaleAndName != null && !existingTplWithSameLocaleAndName.getId().equals(mailTemplate.getId())) { throw new WebApplicationException(Response.Status.CONFLICT); } mailTemplate.setCreationDate(existingMailTemplate.getCreationDate()); return entityManager.merge(mailTemplate); } @GET @Path("/") @Produces(MediaType.APPLICATION_JSON) @RolesAllowed({ADMIN, ADMIN_READONLY}) public List<MailTemplate> findAll(@QueryParam("name") String name, @QueryParam("start") Integer start, @QueryParam("size") Integer size , @QueryParam("orderBy") String orderBy, @QueryParam("isDesc") Boolean isDesc) { if (name != null) { return mailTemplateFinder.findByName(name); } return mailTemplateFinder.findAll(start, size, orderBy, isDesc); } @GET @Path("/{id}") @Produces(MediaType.APPLICATION_JSON) @RolesAllowed({ADMIN, ADMIN_READONLY}) public MailTemplate find(@PathParam("id") @NotNull Long id) { MailTemplate mailTemplate = entityManager.find(MailTemplate.class, id); if (mailTemplate == null) { throw new WebApplicationException(Response.Status.NOT_FOUND); } return mailTemplate; } @GET @Path("/count") @Produces(MediaType.APPLICATION_JSON) @RolesAllowed({ADMIN, ADMIN_READONLY}) public Long count() { return mailTemplateFinder.countAll(); } private void checkNotNull(MailTemplate mailTemplate) { if (mailTemplate == null) { throw new WebApplicationException(Response.Status.NOT_FOUND); } } private void sendMail(MailTemplate mailTemplate, String recipient, Object properties) throws Exception { Template mailContentTpl = new Template(mailTemplate.getName(), mailTemplate.getContent(), new Configuration(Configuration.VERSION_2_3_21)); final StringWriter mailBody = new StringWriter(); mailContentTpl.process(properties, mailBody); mailer.sendMail(mailTemplate.getSubject(), recipient, mailBody.toString()); } } <|start_filename|>order/src/main/java/org/rembx/jeeshop/order/OrderConfiguration.java<|end_filename|> package org.rembx.jeeshop.order; import org.rembx.jeeshop.configuration.NamedConfiguration; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; @ApplicationScoped public class OrderConfiguration { @Inject @NamedConfiguration("fixed.delivery.fee") private String fixedDeliveryFee; @Inject @NamedConfiguration("vat") private String vat; public OrderConfiguration() { } public OrderConfiguration(String fixedDeliveryFee, String vat) { this.fixedDeliveryFee = fixedDeliveryFee; this.vat = vat; } public Double getFixedDeliveryFee() { return Double.parseDouble(fixedDeliveryFee); } public Double getVAT() { return Double.parseDouble(vat); } } <|start_filename|>common/src/main/java/org/rembx/jeeshop/role/AuthorizationUtils.java<|end_filename|> package org.rembx.jeeshop.role; import javax.ws.rs.core.SecurityContext; /** * Created by remi on 24/06/14. */ public class AuthorizationUtils { public static boolean isAdminUser(SecurityContext sessionContext) { return sessionContext != null && sessionContext.getUserPrincipal() != null && sessionContext.isUserInRole(JeeshopRoles.ADMIN); } public static boolean isOwner(SecurityContext securityContext, String owner) { return securityContext != null && securityContext.getUserPrincipal() != null && owner != null && securityContext.isUserInRole(JeeshopRoles.STORE_ADMIN) && owner.equals(securityContext.getUserPrincipal().getName()); } } <|start_filename|>catalog/src/test/java/org/rembx/jeeshop/catalog/PresentationResourceCT.java<|end_filename|> package org.rembx.jeeshop.catalog; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.rembx.jeeshop.catalog.model.CatalogItem; import org.rembx.jeeshop.catalog.model.CatalogPersistenceUnit; import org.rembx.jeeshop.catalog.model.Presentation; import org.rembx.jeeshop.catalog.test.TestCatalog; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import java.util.HashMap; import java.util.UUID; import static org.assertj.core.api.Assertions.assertThat; public class PresentationResourceCT { private PresentationResource service; private TestCatalog testCatalog; private static EntityManagerFactory entityManagerFactory; EntityManager entityManager; @BeforeAll public static void beforeClass() { entityManagerFactory = Persistence.createEntityManagerFactory(CatalogPersistenceUnit.NAME); } @BeforeEach public void setup() { testCatalog = TestCatalog.getInstance(); entityManager = entityManagerFactory.createEntityManager(); } @Test public void find_shouldReturnPresentation() { Presentation presentation = new Presentation("en_GB", "presentation1", "short description", "long description"); service = new PresentationResource(entityManager, null).init(null, null, presentation); assertThat(service.find()).isEqualTo(presentation); } @Test public void createLocalizedPresentation_shouldPersistGivenPresentationAndLinkItToParentCatalogItem() { CatalogItem parentCatalogItem = testCatalog.aCategoryWithoutPresentation(); Presentation presentation = new Presentation(null, "presentation test", "testShortDesc", "testLongDesc"); service = new PresentationResource(entityManager, null).init(parentCatalogItem, "fr_FR", null); entityManager.getTransaction().begin(); // wrap call in transaction as method is transactional service.createLocalizedPresentation(presentation); entityManager.getTransaction().commit(); assertThat(presentation.getId()).isNotNull(); assertThat(entityManager.find(Presentation.class, presentation.getId())).isNotNull(); assertThat(parentCatalogItem.getPresentationByLocale().get("fr_FR")).isNotNull(); assertThat(parentCatalogItem.getPresentationByLocale().get("fr_FR").getLocale()).isEqualTo("fr_FR"); // cleanup removePersistedTestData(parentCatalogItem, presentation); } @Test public void modifyLocalizedPresentation_shouldUpdateGivenPresentation() { Presentation presentation = createTestPresentation(); service = new PresentationResource(entityManager, null).init(null, "fr_FR", presentation); UUID uuid = UUID.randomUUID(); presentation.setShortDescription(uuid.toString()); entityManager.getTransaction().begin(); // wrap call in transaction as method is transactional service.modifyLocalizedPresentation(presentation); entityManager.getTransaction().commit(); assertThat(entityManager.find(Presentation.class, presentation.getId()).getShortDescription()).isEqualTo(uuid.toString()); // cleanup removePersistedTestData(null, presentation); } @Test public void deleteGivenPresentation_shouldRemoveIt() { CatalogItem parentCatalogItem = testCatalog.aCategoryWithoutPresentation(); Presentation presentation = createTestPresentation(); parentCatalogItem.getPresentationByLocale().put("fr_FR",presentation); service = new PresentationResource(entityManager, null).init(parentCatalogItem, "fr_FR", presentation); entityManager.getTransaction().begin(); // wrap call in transaction as method is transactional service.delete(); entityManager.getTransaction().commit(); assertThat(entityManager.find(Presentation.class, presentation.getId())).isNull(); assertThat(parentCatalogItem.getPresentationByLocale().get("fr_FR")).isNull(); } private Presentation createTestPresentation() { entityManager.getTransaction().begin(); Presentation presentation = new Presentation("fr_FR", "presentation test", "testShortDesc", "testLongDesc"); entityManager.persist(presentation); entityManager.getTransaction().commit(); return presentation; } private void removePersistedTestData(CatalogItem parentCatalogItem, Presentation presentation) { entityManager.getTransaction().begin(); entityManager.remove(presentation); if (parentCatalogItem != null) parentCatalogItem.setPresentationByLocale(new HashMap<>()); entityManager.getTransaction().commit(); } } <|start_filename|>admin/src/main/webapp/app/user/js/user.js<|end_filename|> (function () { var app = angular.module('admin-user', []); app.controller('UsersController', ['$http', '$uibModal', function ($http, $uibModal) { var ctrl = this; ctrl.alerts = []; ctrl.entries = []; ctrl.currentPage = 1; ctrl.totalCount = null; ctrl.pageSize = 10; ctrl.searchValue = null; ctrl.isProcessing = false; ctrl.orderBy = null; ctrl.orderDesc = false; ctrl.findEntries = function (orderBy) { ctrl.isProcessing = true; ctrl.alerts = []; var offset = ctrl.pageSize * (ctrl.currentPage - 1); var uri = 'rs/users?start=' + offset + '&size=' + ctrl.pageSize; if (orderBy != null) { ctrl.orderBy = orderBy; ctrl.orderDesc = !ctrl.orderDesc; uri += '&orderBy=' + orderBy + '&isDesc=' + ctrl.orderDesc; } var countURI = 'rs/users/count'; if (ctrl.searchValue != null && !(ctrl.searchValue === "")) { var searchArg = 'search=' + ctrl.searchValue; uri = uri + '&' + searchArg; countURI = countURI + '?' + searchArg; } $http.get(uri).success(function (data) { ctrl.entries = data; ctrl.isProcessing = false; }); $http.get(countURI).success(function (data) { ctrl.totalCount = data; ctrl.isProcessing = false; }); }; ctrl.findEntries(); ctrl.pageChanged = function () { ctrl.findEntries(); }; ctrl.delete = function (index, message) { var modalInstance = $uibModal.open({ templateUrl: 'app/util/confirm-delete-danger.html', controller: ['$uibModalInstance', '$scope', function ($uibModalInstance, $scope) { $scope.modalInstance = $uibModalInstance; $scope.confirmMessage = message; }], size: 'sm' }); modalInstance.result.then(function () { ctrl.alerts = []; $http.delete('rs/users/' + ctrl.entries[index].id) .success(function (data) { ctrl.entries.splice(index, 1); ctrl.findEntries(); }) .error(function (data) { ctrl.alerts.push({type: 'danger', msg: 'Technical error'}); }); }, function () { }); }; ctrl.closeAlert = function (index) { ctrl.alerts.splice(index, 1); }; }]); app.controller('UserController', ['$http', '$stateParams', '$state', '$uibModal', function ($http, $stateParams, $state, $uibModal) { var ctrl = this; ctrl.alerts = []; ctrl.entry = {}; ctrl.isEditionMode = ($stateParams.userId != ""); ctrl.findUser = function () { if (!ctrl.isEditionMode) return; $http.get('rs/users/' + $stateParams.userId) .success(function (data) { ctrl.entry = data; ctrl.convertEntryDates(); }); }; ctrl.createOrEdit = function () { ctrl.alerts = []; if (ctrl.isEditionMode) { ctrl.edit(); } else { ctrl.create(); } }; ctrl.create = function () { $http.post('rs/users', ctrl.entry) .success(function (data) { ctrl.entry = data; ctrl.convertEntryDates(); ctrl.alerts.push({type: 'success', msg: 'Creation complete'}); }) .error(function (data, status) { if (status == 403) ctrl.alerts.push({type: 'warning', msg: 'Operation not allowed'}); else ctrl.alerts.push({type: 'danger', msg: 'Technical error'}); }); }; ctrl.edit = function () { $http.put('rs/users', ctrl.entry) .success(function (data) { ctrl.entry = data; ctrl.convertEntryDates(); ctrl.alerts.push({type: 'success', msg: 'Update complete'}) }) .error(function (data, status) { if (status == 403) ctrl.alerts.push({type: 'warning', msg: 'Operation not allowed'}); else ctrl.alerts.push({type: 'danger', msg: 'Technical error'}) }); }; ctrl.resetPassword = function (login) { var resetPasswordDialog = $uibModal.open({ templateUrl: 'app/user/reset-password-dialog.html', size: 'lg', controller: 'ResetPasswordModalController', resolve: { login: function () { return login; } } }); resetPasswordDialog.result.then(function success() { }, function error() { }); }; ctrl.exitDetailView = function () { $state.go('^', {}, {reload: true}); }; ctrl.convertEntryDates = function () { // hack for dates returned as timestamp by service ctrl.entry.birthDate = ctrl.entry.birthDate != null ? new Date(ctrl.entry.birthDate) : null; ctrl.entry.creationDate = ctrl.entry.creationDate != null ? new Date(ctrl.entry.creationDate) : null; ctrl.entry.updateDate = ctrl.entry.creationDate != null ? new Date(ctrl.entry.creationDate) : null; }; ctrl.closeAlert = function (index) { ctrl.alerts.splice(index, 1); }; ctrl.findUser(); }]); app.controller('ResetPasswordModalController', ['$uibModalInstance', '$scope', 'login', function ($uibModalInstance, $scope, login) { $scope.modalInstance = $uibModalInstance; $scope.submitForm = function () { var newPassword = $scope.newPassword; var confirmNewPassword = $scope.confirmNewPassword; if (newPassword === confirmNewPassword) { var uri = 'rs/users/' + login + '/password'; $http.put(uri, newPassword) .success(function () { ctrl.isProcessing = false; ctrl.alerts.push({type: 'success', msg: 'Password successfully updated'}); }) .error(function (data, status) { if (status == 403) ctrl.alerts.push({type: 'warning', msg: 'Operation not allowed'}); else ctrl.alerts.push({type: 'danger', msg: 'Technical error'}); }); $scope.modalInstance.dismiss('close'); } else { $scope.nomatch = true; } }; $scope.cancelForm = function () { $scope.modalInstance.dismiss('close'); }; }]); })(); <|start_filename|>catalog/src/test/java/org/rembx/jeeshop/catalog/test/Assertions.java<|end_filename|> package org.rembx.jeeshop.catalog.test; import org.rembx.jeeshop.catalog.model.*; import java.util.List; /** * Created by remi on 25/05/14. */ public class Assertions extends org.assertj.core.api.Assertions{ public static TestCatalog.CatalogItemAssert assertThat(CatalogItem catalogItem) { return new TestCatalog.CatalogItemAssert(catalogItem); } public static TestCatalog.CategoriesAssert assertThatCategoriesOf(List<Category> categories) { return new TestCatalog.CategoriesAssert(categories); } public static TestCatalog.ProductsAssert assertThatProductsOf(List<Product> products) { return new TestCatalog.ProductsAssert(products); } public static TestCatalog.SKUsAssert assertThatSKUsOf(List<SKU> skus) { return new TestCatalog.SKUsAssert(skus); } public static TestCatalog.SKUDiscountsAssert assertThatDiscountsOf(List<Discount> discounts) { return new TestCatalog.SKUDiscountsAssert(discounts); } } <|start_filename|>catalog/src/main/java/org/rembx/jeeshop/catalog/model/SKU.java<|end_filename|> package org.rembx.jeeshop.catalog.model; import javax.persistence.*; import javax.validation.constraints.Size; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; import java.util.Date; import java.util.List; /** * Stock keeping unit */ @Entity @XmlType @XmlAccessorType(XmlAccessType.FIELD) @Cacheable public class SKU extends CatalogItem{ private Double price; @Size(min=3, max = 3) @Column(length = 3) private String currency; @Size(max = 50) @Column(length = 50) private String reference; private Integer threshold; private Integer quantity; @ManyToMany(cascade = {CascadeType.PERSIST}) @JoinTable(joinColumns = @JoinColumn(name = "skuId"), inverseJoinColumns = @JoinColumn(name = "discountId")) @OrderColumn(name = "orderIdx") private List<Discount> discounts; @Transient private List<Long> discountsIds; /** * Calculated field true if quantity > threshold */ @Transient private boolean available; public SKU() { } public SKU(Long id, String name) { this.id = id; this.name = name; } public SKU(String name, String description) { this.name = name; this.description = description; } public SKU(String name, String description, Double price, Integer quantity, String reference, Date startDate, Date endDate, Boolean disabled, Integer threshold, String owner) { this.name = name; this.description = description; this.price = price; this.quantity = quantity; this.reference = reference; this.disabled = disabled; this.startDate = startDate; this.endDate = endDate; this.threshold = threshold; this.owner = owner; } public SKU(Long id, String name, String description, Double price, Integer quantity, String reference, Date startDate, Date endDate, Boolean disabled, Integer threshold) { this.id = id; this.name = name; this.description = description; this.price = price; this.quantity = quantity; this.reference = reference; this.disabled = disabled; this.startDate = startDate; this.endDate = endDate; this.threshold = threshold; } @PostLoad @PostPersist @PostUpdate private void fillTransient() { if (quantity==null) { available = false; return; } if (threshold == null) threshold = 0; available = quantity >threshold; } public Double getPrice() { return price; } public void setPrice(Double price) { this.price = price; } public String getCurrency() { return currency; } public void setCurrency(String currency) { this.currency = currency; } public String getReference() { return reference; } public void setReference(String reference) { this.reference = reference; } public Integer getThreshold() { return threshold; } public void setThreshold(Integer threshold) { this.threshold = threshold; } public Integer getQuantity() { return quantity; } public void setQuantity(Integer quantity) { this.quantity = quantity; } public List<Discount> getDiscounts() { return discounts; } public void setDiscounts(List<Discount> discounts) { this.discounts = discounts; } public Boolean isAvailable() { return available; } public void setAvailable(Boolean available) { this.available = available; } public List<Long> getDiscountsIds() { return discountsIds; } public void setDiscountsIds(List<Long> discountsIds) { this.discountsIds = discountsIds; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (!super.equals(o)) return false; SKU sku = (SKU) o; if (available != sku.available) return false; if (currency != null ? !currency.equals(sku.currency) : sku.currency != null) return false; if (price != null ? !price.equals(sku.price) : sku.price != null) return false; if (quantity != null ? !quantity.equals(sku.quantity) : sku.quantity != null) return false; if (reference != null ? !reference.equals(sku.reference) : sku.reference != null) return false; if (threshold != null ? !threshold.equals(sku.threshold) : sku.threshold != null) return false; return true; } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + (price != null ? price.hashCode() : 0); result = 31 * result + (currency != null ? currency.hashCode() : 0); result = 31 * result + (reference != null ? reference.hashCode() : 0); result = 31 * result + (threshold != null ? threshold.hashCode() : 0); result = 31 * result + (quantity != null ? quantity.hashCode() : 0); result = 31 * result + (available ? 1 : 0); return result; } } <|start_filename|>user/src/main/java/org/rembx/jeeshop/order/model/PaymentInfo.java<|end_filename|> package org.rembx.jeeshop.order.model; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; @XmlType @XmlAccessorType(XmlAccessType.FIELD) public class PaymentInfo { /** * Used to store payment form response for Payment solutions such as SIPS. */ private String paymentFormResponse; public PaymentInfo() { } public PaymentInfo(String paymentFormResponse) { this.paymentFormResponse = paymentFormResponse; } public String getPaymentFormResponse() { return paymentFormResponse; } public void setPaymentFormResponse(String paymentFormResponse) { this.paymentFormResponse = paymentFormResponse; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; PaymentInfo that = (PaymentInfo) o; if (paymentFormResponse != null ? !paymentFormResponse.equals(that.paymentFormResponse) : that.paymentFormResponse != null) return false; return true; } @Override public int hashCode() { return paymentFormResponse != null ? paymentFormResponse.hashCode() : 0; } } <|start_filename|>catalog/src/main/java/org/rembx/jeeshop/catalog/model/Category.java<|end_filename|> package org.rembx.jeeshop.catalog.model; import javax.json.bind.annotation.JsonbTransient; import javax.persistence.*; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; import java.util.Date; import java.util.List; /** * Created by remi on 20/05/14. */ @Entity @XmlType @XmlAccessorType(XmlAccessType.FIELD) @Cacheable public class Category extends CatalogItem { @ManyToMany(cascade = {CascadeType.PERSIST}) @JoinTable(joinColumns = @JoinColumn(name = "parentCategoryId"), inverseJoinColumns = @JoinColumn(name = "childCategoryId")) @OrderColumn(name = "orderIdx") private List<Category> childCategories; @Transient private List<Long> childCategoriesIds; @ManyToMany(cascade = {CascadeType.PERSIST}) @JoinTable(joinColumns = @JoinColumn(name = "categoryId"), inverseJoinColumns = @JoinColumn(name = "productId")) @OrderColumn(name = "orderIdx") @JsonbTransient private List<Product> childProducts; @Transient private List<Long> childProductsIds; public Category() { } public Category(Long id, String name) { this.id = id; this.name = name; } public Category(String name, String description) { this.name = name; this.description = description; } public Category(Long id, String name, String description, Date startDate, Date endDate, Boolean disabled) { this.id = id; this.name = name; this.description = description; this.startDate = startDate; this.endDate = endDate; this.disabled = disabled; } public Category(String name, String description, Date startDate, Date endDate, Boolean disabled, String owner) { this.name = name; this.description = description; this.startDate = startDate; this.endDate = endDate; this.disabled = disabled; this.owner = owner; } public List<Category> getChildCategories() { return childCategories; } public void setChildCategories(List<Category> childCategories) { this.childCategories = childCategories; } public List<Product> getChildProducts() { return childProducts; } public void setChildProducts(List<Product> childProducts) { this.childProducts = childProducts; } public List<Long> getChildCategoriesIds() { return childCategoriesIds; } public void setChildCategoriesIds(List<Long> childCategoriesIds) { this.childCategoriesIds = childCategoriesIds; } public List<Long> getChildProductsIds() { return childProductsIds; } public void setChildProductsIds(List<Long> childProductsIds) { this.childProductsIds = childProductsIds; } } <|start_filename|>user/src/main/java/org/rembx/jeeshop/order/model/OrderDiscount.java<|end_filename|> package org.rembx.jeeshop.order.model; import javax.persistence.*; import javax.validation.constraints.NotNull; /** * OrderDiscount entity */ @Embeddable public class OrderDiscount { public OrderDiscount() { } public OrderDiscount(Long discountId, Double discountValue) { this.discountId = discountId; this.discountValue = discountValue; } @NotNull @Column(name = "discount_id") private Long discountId; private Double discountValue; @Transient private String displayName; @Transient private String presentationImageURI; @Transient private Boolean rateType; public Long getDiscountId() { return discountId; } public void setDiscountId(Long discountId) { this.discountId = discountId; } public String getDisplayName() { return displayName; } public void setDisplayName(String displayName) { this.displayName = displayName; } public String getPresentationImageURI() { return presentationImageURI; } public void setPresentationImageURI(String presentationImageURI) { this.presentationImageURI = presentationImageURI; } public Double getDiscountValue() { return discountValue; } public void setDiscountValue(Double discountValue) { this.discountValue = discountValue; } public Boolean getRateType() { return rateType; } public void setRateType(Boolean rateType) { this.rateType = rateType; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; OrderDiscount that = (OrderDiscount) o; if (discountId != null ? !discountId.equals(that.discountId) : that.discountId != null) return false; if (discountValue != null ? !discountValue.equals(that.discountValue) : that.discountValue != null) return false; if (displayName != null ? !displayName.equals(that.displayName) : that.displayName != null) return false; if (presentationImageURI != null ? !presentationImageURI.equals(that.presentationImageURI) : that.presentationImageURI != null) return false; return true; } @Override public int hashCode() { int result = discountId != null ? discountId.hashCode() : 0; result = 31 * result + (discountValue != null ? discountValue.hashCode() : 0); result = 31 * result + (displayName != null ? displayName.hashCode() : 0); result = 31 * result + (presentationImageURI != null ? presentationImageURI.hashCode() : 0); return result; } } <|start_filename|>user/src/main/java/org/rembx/jeeshop/user/UserFinder.java<|end_filename|> package org.rembx.jeeshop.user; import com.querydsl.core.types.dsl.BooleanExpression; import com.querydsl.core.types.dsl.ComparableExpressionBase; import com.querydsl.jpa.impl.JPAQuery; import com.querydsl.jpa.impl.JPAQueryFactory; import io.quarkus.hibernate.orm.PersistenceUnit; import org.rembx.jeeshop.user.model.User; import org.rembx.jeeshop.user.model.UserPersistenceUnit; import javax.enterprise.context.ApplicationScoped; import javax.enterprise.context.RequestScoped; import javax.persistence.EntityManager; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.rembx.jeeshop.user.model.QUser.user; /** * User finder utility */ @ApplicationScoped public class UserFinder { private EntityManager entityManager; private static final Map<String, ComparableExpressionBase<?>> sortProperties = new HashMap<String, ComparableExpressionBase<?>>() {{ put("id", user.id); put("login", user.login); put("gender", user.gender); put("firstname", user.firstname); put("lastname", user.lastname); put("disabled", user.disabled); put("activated", user.activated); put("newslettersSubscribed", user.newslettersSubscribed); put("birthDate", user.birthDate); put("phoneNumber", user.phoneNumber); put("preferredLocale", user.preferredLocale); put("creationDate", user.creationDate.stringValue()); put("updateDate", user.updateDate); }}; public UserFinder(@PersistenceUnit(UserPersistenceUnit.NAME) EntityManager entityManager) { this.entityManager = entityManager; } public User findByLogin(String login) { return new JPAQueryFactory(entityManager) .selectFrom(user).where( user.login.eq(login)) .fetchOne(); } public List<User> findAll(Integer offset, Integer limit, String orderBy, Boolean isDesc) { JPAQuery<User> query = new JPAQueryFactory(entityManager).selectFrom(user); if (offset != null) query.offset(offset); if (limit != null) query.limit(limit); sortBy(orderBy, isDesc, query); return query.fetch(); } public Long countAll() { return new JPAQueryFactory(entityManager) .selectFrom(user) .fetchCount(); } public Long countBySearchCriteria(String searchCriteria) { JPAQuery<User> query = new JPAQueryFactory(entityManager).selectFrom(user) .where(buildSearchPredicate(searchCriteria)); return query.fetchCount(); } public List<User> findBySearchCriteria(String searchCriteria, Integer offset, Integer limit, String orderBy, Boolean isDesc) { JPAQuery<User> query = new JPAQueryFactory(entityManager).selectFrom(user) .where(buildSearchPredicate(searchCriteria)); if (offset != null) query.offset(offset); if (limit != null) query.limit(limit); sortBy(orderBy, isDesc, query); return query.fetch(); } private BooleanExpression buildSearchPredicate(String search) { return user.login.containsIgnoreCase(search) .or(user.firstname.containsIgnoreCase(search)) .or(user.lastname.containsIgnoreCase(search)); } private void sortBy(String orderby, Boolean isDesc, JPAQuery<User> query) { if (orderby != null && sortProperties.containsKey(orderby)) { if (isDesc) { query.orderBy(sortProperties.get(orderby).desc()); } else { query.orderBy(sortProperties.get(orderby).asc()); } } } } <|start_filename|>common/src/main/java/org/rembx/jeeshop/util/DateUtil.java<|end_filename|> package org.rembx.jeeshop.util; import java.time.Instant; import java.time.LocalDateTime; import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.util.Date; /** * Created by remi on 25/05/14. */ public class DateUtil { public static ZonedDateTime dateToLocalDateTime(Date date){ Instant endDateInstant = Instant.ofEpochMilli(date.getTime()); return ZonedDateTime.ofInstant(endDateInstant, ZoneOffset.UTC); } } <|start_filename|>admin/src/main/webapp/webpack.config.js<|end_filename|> module.exports = { entry: { app : './app/app.js' }, output: { filename: '[name]_bundle.js', path: './dist' } }; <|start_filename|>catalog/src/test/java/org/rembx/jeeshop/catalog/CatalogItemFinderTest.java<|end_filename|> package org.rembx.jeeshop.catalog; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.rembx.jeeshop.catalog.model.Catalog; import org.rembx.jeeshop.catalog.model.CatalogItem; import org.rembx.jeeshop.rest.WebApplicationException; import javax.ws.rs.core.Response; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; import static org.junit.jupiter.api.Assertions.assertEquals; public class CatalogItemFinderTest { private CatalogItemFinder instance; CatalogItem visibleCatalogItem = new CatalogItem() { @Override public boolean isVisible() { return true; } }; @BeforeEach public void setup() { instance = new CatalogItemFinder(null); } @Test public void find_VisibleCatalogItem_ShouldReturnExpectedProduct() { assertThat(instance.filterVisible(visibleCatalogItem, null)).isEqualTo(visibleCatalogItem); } @Test public void find_NotVisibleCatalogItem_ShouldThrowForbiddenException() { try { instance.filterVisible(new Catalog(), null); fail("should have thrown ex"); } catch (WebApplicationException e) { assertEquals(Response.Status.FORBIDDEN, e.getResponse().getStatusInfo()); } } @Test public void find_NullCatalogItem_ShouldThrowNotFoundException() { try { instance.filterVisible(null, null); fail("should have thrown ex"); } catch (WebApplicationException e) { assertEquals(Response.Status.NOT_FOUND, e.getResponse().getStatusInfo()); } } } <|start_filename|>catalog/src/test/java/org/rembx/jeeshop/catalog/test/CatalogItemCRUDTester.java<|end_filename|> package org.rembx.jeeshop.catalog.test; import org.apache.http.auth.BasicUserPrincipal; import org.rembx.jeeshop.catalog.CatalogItemService; import org.rembx.jeeshop.catalog.model.CatalogItem; import org.rembx.jeeshop.catalog.model.CatalogPersistenceUnit; import org.rembx.jeeshop.role.JeeshopRoles; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import javax.ws.rs.core.SecurityContext; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class CatalogItemCRUDTester<T extends CatalogItem> { private static EntityManagerFactory entityManagerFactory; protected EntityManager entityManager; protected SecurityContext securityContext; protected TestCatalog testCatalog; private Class<T> itemClass; protected CatalogItemService<T> service; public CatalogItemService<T> getService() { return service; } public void setService(CatalogItemService<T> service) { this.service = service; } public CatalogItemCRUDTester(Class<T> itemClass) { this.itemClass = itemClass; entityManagerFactory = Persistence.createEntityManagerFactory(CatalogPersistenceUnit.NAME); testCatalog = TestCatalog.getInstance(); entityManager = entityManagerFactory.createEntityManager(); securityContext = mock(SecurityContext.class); } public T test_create(T catalogItem) { entityManager.getTransaction().begin(); service.create(securityContext, catalogItem); entityManager.getTransaction().commit(); return refreshCatalogItem(catalogItem); } public void test_delete(T catalogItem) { entityManager.getTransaction().begin(); entityManager.persist(catalogItem); entityManager.getTransaction().commit(); entityManager.getTransaction().begin(); service.delete(securityContext, catalogItem.getId()); entityManager.getTransaction().commit(); } public void test_modify(T catalogItem) { service.modify(securityContext, catalogItem); } private T refreshCatalogItem(T store) { T actualStore = entityManager.find(itemClass, store.getId()); entityManager.remove(store); return actualStore; } public void setAdminUser() { when(securityContext.getUserPrincipal()).thenReturn(new BasicUserPrincipal("<EMAIL>")); when(securityContext.isUserInRole(JeeshopRoles.ADMIN)).thenReturn(true); } public void setStoreAdminUser() { when(securityContext.isUserInRole(JeeshopRoles.ADMIN)).thenReturn(false); when(securityContext.isUserInRole(JeeshopRoles.STORE_ADMIN)).thenReturn(true); when(securityContext.getUserPrincipal()).thenReturn(new BasicUserPrincipal(TestCatalog.OWNER)); } public void setSAnotherStoreAdminUser() { when(securityContext.isUserInRole(JeeshopRoles.ADMIN)).thenReturn(false); when(securityContext.isUserInRole(JeeshopRoles.STORE_ADMIN)).thenReturn(true); when(securityContext.getUserPrincipal()).thenReturn(new BasicUserPrincipal("<EMAIL>")); } public void setPublicUser() { when(securityContext.isUserInRole(JeeshopRoles.ADMIN)).thenReturn(false); when(securityContext.isUserInRole(JeeshopRoles.STORE_ADMIN)).thenReturn(false); } public EntityManager getEntityManager() { return entityManager; } public SecurityContext getSecurityContext() { return securityContext; } public TestCatalog getFixtures() { return testCatalog; } } <|start_filename|>catalog/src/main/java/org/rembx/jeeshop/catalog/Products.java<|end_filename|> package org.rembx.jeeshop.catalog; import io.quarkus.hibernate.orm.PersistenceUnit; import org.rembx.jeeshop.catalog.model.*; import org.rembx.jeeshop.rest.WebApplicationException; import javax.annotation.security.PermitAll; import javax.annotation.security.RolesAllowed; import javax.enterprise.context.ApplicationScoped; import javax.persistence.EntityManager; import javax.transaction.Transactional; import javax.validation.constraints.NotNull; import javax.ws.rs.*; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import java.util.ArrayList; import java.util.List; import java.util.Set; import static org.rembx.jeeshop.catalog.model.QDiscount.discount; import static org.rembx.jeeshop.catalog.model.QProduct.product; import static org.rembx.jeeshop.catalog.model.QSKU.sKU; import static org.rembx.jeeshop.role.AuthorizationUtils.isAdminUser; import static org.rembx.jeeshop.role.AuthorizationUtils.isOwner; import static org.rembx.jeeshop.role.JeeshopRoles.*; @Path("/rs/products") @ApplicationScoped public class Products implements CatalogItemService<Product> { private EntityManager entityManager; private CatalogItemFinder catalogItemFinder; private PresentationResource presentationResource; Products(@PersistenceUnit(CatalogPersistenceUnit.NAME) EntityManager entityManager, CatalogItemFinder catalogItemFinder, PresentationResource presentationResource) { this.entityManager = entityManager; this.catalogItemFinder = catalogItemFinder; this.presentationResource = presentationResource; } @POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Transactional @RolesAllowed({ADMIN, STORE_ADMIN}) public Product create(@Context SecurityContext securityContext, Product product) { attachOwner(securityContext, product); if (product.getChildSKUsIds() != null) { List<SKU> newSkus = new ArrayList<>(); product.getChildSKUsIds().forEach(skuId -> newSkus.add(entityManager.find(SKU.class, skuId))); product.setChildSKUs(newSkus); } if (product.getDiscountsIds() != null) { List<Discount> newDiscounts = new ArrayList<>(); product.getDiscountsIds().forEach(discountId -> newDiscounts.add(entityManager.find(Discount.class, discountId))); product.setDiscounts(newDiscounts); } entityManager.persist(product); return product; } @DELETE @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Transactional @RolesAllowed({ADMIN, STORE_ADMIN}) @Path("/{productId}") public void delete(@Context SecurityContext securityContext, @PathParam("productId") Long productId) { Product product = entityManager.find(Product.class, productId); checkNotNull(product); if (isAdminUser(securityContext) || isOwner(securityContext, product.getOwner())) { List<Category> categoryHolders = catalogItemFinder.findForeignHolder(QCategory.category, QCategory.category.childProducts, product); for (Category category : categoryHolders) { category.getChildProducts().remove(product); } List<Discount> discountHolders = catalogItemFinder.findForeignHolder(QDiscount.discount, QDiscount.discount.products, product); for (Discount discount : discountHolders) { product.getDiscounts().remove(discount); discount.getProducts().remove(product); } entityManager.remove(product); } else { throw new WebApplicationException(Response.Status.FORBIDDEN); } } @PUT @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Transactional @RolesAllowed({ADMIN, STORE_ADMIN}) public Product modify(@Context SecurityContext securityContext, Product product) { Product originalProduct = entityManager.find(Product.class, product.getId()); checkNotNull(originalProduct); if (isAdminUser(securityContext) || isOwner(securityContext, originalProduct.getOwner())) { if (product.getChildSKUsIds() != null) { List<SKU> newSkus = new ArrayList<>(); product.getChildSKUsIds().forEach(skuId -> newSkus.add(entityManager.find(SKU.class, skuId))); product.setChildSKUs(newSkus); } else { product.setChildSKUs(originalProduct.getChildSKUs()); } if (product.getDiscountsIds() != null) { List<Discount> newDiscounts = new ArrayList<>(); product.getDiscountsIds().forEach(discountId -> newDiscounts.add(entityManager.find(Discount.class, discountId))); product.setDiscounts(newDiscounts); } else { product.setDiscounts(originalProduct.getDiscounts()); } product.setPresentationByLocale(originalProduct.getPresentationByLocale()); return entityManager.merge(product); } else { throw new WebApplicationException(Response.Status.FORBIDDEN); } } @GET @Path("/") @Produces(MediaType.APPLICATION_JSON) @RolesAllowed({ADMIN, ADMIN_READONLY}) public List<Product> findAll(@QueryParam("search") String search, @QueryParam("start") Integer start, @QueryParam("size") Integer size , @QueryParam("orderBy") String orderBy, @QueryParam("isDesc") Boolean isDesc, @QueryParam("locale") String locale) { if (search != null) return catalogItemFinder.findBySearchCriteria(product, search, start, size, orderBy, isDesc, locale); else return catalogItemFinder.findAll(product, start, size, orderBy, isDesc, locale); } @GET @Path("/count") @Produces(MediaType.APPLICATION_JSON) @RolesAllowed({ADMIN, ADMIN_READONLY}) public Long count(@QueryParam("search") String search) { if (search != null) return catalogItemFinder.countBySearchCriteria(product, search); else return catalogItemFinder.countAll(product); } @GET @Path("/{productId}") @Produces(MediaType.APPLICATION_JSON) @PermitAll public Product find(@Context SecurityContext sessionContext, @PathParam("productId") @NotNull Long productId, @QueryParam("locale") String locale) { Product product = entityManager.find(Product.class, productId); checkNotNull(product); if (isAdminUser(sessionContext) || isOwner(sessionContext, product.getOwner())) return product; else return catalogItemFinder.filterVisible(product, locale); } @GET @Path("/{productId}/presentationslocales") @Produces(MediaType.APPLICATION_JSON) @RolesAllowed({ADMIN, STORE_ADMIN, ADMIN_READONLY}) public Set<String> findPresentationsLocales(@Context SecurityContext securityContext, @PathParam("productId") @NotNull Long productId) { Product product = entityManager.find(Product.class, productId); checkNotNull(product); if (!isAdminUser(securityContext) && !isOwner(securityContext, product.getOwner())) throw new WebApplicationException(Response.Status.FORBIDDEN); return product.getPresentationByLocale().keySet(); } @Path("/{productId}/presentations/{locale}") @PermitAll public PresentationResource findPresentationByLocale(@PathParam("productId") @NotNull Long productId, @NotNull @PathParam("locale") String locale) { Product product = entityManager.find(Product.class, productId); checkNotNull(product); Presentation presentation = product.getPresentationByLocale().get(locale); return presentationResource.init(product, locale, presentation); } @GET @Path("/{productId}/skus") @Produces(MediaType.APPLICATION_JSON) @PermitAll public List<SKU> findChildSKUs(@Context SecurityContext sessionContext, @PathParam("productId") @NotNull Long productId, @QueryParam("locale") String locale) { Product product = entityManager.find(Product.class, productId); checkNotNull(product); List<SKU> childSKUs = product.getChildSKUs(); if (childSKUs.isEmpty()) { return new ArrayList<>(); } if (isAdminUser(sessionContext) || isOwner(sessionContext, product.getOwner())) return childSKUs; else return catalogItemFinder.findVisibleCatalogItems(sKU, childSKUs, locale); } @GET @Path("/{productId}/discounts") @Produces(MediaType.APPLICATION_JSON) @RolesAllowed({ADMIN, STORE_ADMIN, ADMIN_READONLY}) public List<Discount> findDiscounts(@Context SecurityContext sessionContext, @PathParam("productId") @NotNull Long productId) { Product product = entityManager.find(Product.class, productId); checkNotNull(product); List<Discount> discounts = product.getDiscounts(); if (discounts.isEmpty()) { return new ArrayList<>(); } if (isAdminUser(sessionContext) || isOwner(sessionContext, product.getOwner())) return discounts; else return catalogItemFinder.findVisibleCatalogItems(discount, discounts, null); } private void checkNotNull(Product product) { if (product == null) { throw new WebApplicationException(Response.Status.NOT_FOUND); } } } <|start_filename|>order/src/test/java/org/rembx/jeeshop/order/PriceEngineImplTest.java<|end_filename|> package org.rembx.jeeshop.order; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.rembx.jeeshop.catalog.DiscountFinder; import org.rembx.jeeshop.catalog.model.SKU; import org.rembx.jeeshop.order.model.Order; import org.rembx.jeeshop.order.model.OrderItem; import javax.persistence.EntityManager; import java.util.HashSet; import java.util.Set; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; import static org.mockito.Mockito.*; public class PriceEngineImplTest { // TODO complete discounts application test EntityManager entityManager; private OrderConfiguration orderConfiguration; private OrderFinder orderFinder; private DiscountFinder discountFinder; private PriceEngineImpl orderPriceEngine; @BeforeEach public void setup() { entityManager = mock(EntityManager.class); orderConfiguration = mock(OrderConfiguration.class); orderFinder = mock(OrderFinder.class); discountFinder = mock(DiscountFinder.class); orderPriceEngine = new PriceEngineImpl(entityManager, orderConfiguration, orderFinder, discountFinder); } @Test public void computePrice_ShouldAddPriceOfEachOrderItemsMultipliedByQuantityWithFixedDeliveryFee() { SKU sku = new SKU(); sku.setPrice(10.0); SKU sku2 = new SKU(); sku2.setPrice(20.0); when(entityManager.find(SKU.class, 1L)).thenReturn(sku); when(entityManager.find(SKU.class, 2L)).thenReturn(sku2); when(orderConfiguration.getFixedDeliveryFee()).thenReturn(11.0); Order order = new Order(); Set<OrderItem> items = new HashSet<>(); items.add(new OrderItem(1L, 1L, 1)); items.add(new OrderItem(2L, 2L, 2)); order.setItems(items); orderPriceEngine.computePrice(order); verify(entityManager).find(SKU.class, 1L); verify(entityManager).find(SKU.class, 2L); verify(orderConfiguration).getFixedDeliveryFee(); assertThat(order.getPrice()).isEqualTo(61.0); } @Test public void computePrice_ShouldAddPriceOfEachOrderItemsMultipliedByQuantity() { SKU sku = new SKU(); sku.setPrice(10.0); SKU sku2 = new SKU(); sku2.setPrice(20.0); when(entityManager.find(SKU.class, 1L)).thenReturn(sku); when(entityManager.find(SKU.class, 2L)).thenReturn(sku2); when(orderConfiguration.getFixedDeliveryFee()).thenReturn(null); Order order = new Order(); Set<OrderItem> items = new HashSet<>(); items.add(new OrderItem(1L, 1L, 1)); items.add(new OrderItem(2L, 2L, 2)); order.setItems(items); orderPriceEngine.computePrice(order); verify(entityManager).find(SKU.class, 1L); verify(entityManager).find(SKU.class, 2L); verify(orderConfiguration).getFixedDeliveryFee(); assertThat(order.getPrice()).isEqualTo(50.0); for (OrderItem item : order.getItems()) { if (item.getSkuId().equals(1L)) assertThat(item.getPrice()).isEqualTo(10.0); else assertThat(item.getPrice()).isEqualTo(20.0); } } @Test public void computePrice_ShouldThrowEx_whenOrderHasNoItems() { Order order = new Order(); try { orderPriceEngine.computePrice(order); fail("Should have thrown ex"); } catch (IllegalStateException e) { } } } <|start_filename|>catalog/src/main/java/org/rembx/jeeshop/catalog/model/Premises.java<|end_filename|> package org.rembx.jeeshop.catalog.model; import javax.persistence.*; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import java.util.List; @Entity @XmlRootElement @XmlAccessorType(XmlAccessType.FIELD) @Cacheable public class Premises { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) Long id; @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER) PremisesAddress address; @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER) List<PremisesOpeningSchedules> schedules; public Premises() { } public Premises(Long id) { this.id = id; } public Premises(Long id, PremisesAddress address, List<PremisesOpeningSchedules> schedules) { this.id = id; this.address = address; this.schedules = schedules; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public PremisesAddress getAddress() { return address; } public void setAddress(PremisesAddress address) { this.address = address; } public List<PremisesOpeningSchedules> getSchedules() { return schedules; } public void setSchedules(List<PremisesOpeningSchedules> schedules) { this.schedules = schedules; } } <|start_filename|>user/src/main/java/org/rembx/jeeshop/user/MailTemplateFinder.java<|end_filename|> package org.rembx.jeeshop.user; import com.querydsl.core.types.dsl.ComparableExpressionBase; import com.querydsl.jpa.impl.JPAQuery; import com.querydsl.jpa.impl.JPAQueryFactory; import io.quarkus.hibernate.orm.PersistenceUnit; import org.rembx.jeeshop.user.model.MailTemplate; import org.rembx.jeeshop.user.model.UserPersistenceUnit; import javax.annotation.Resource; import javax.enterprise.context.ApplicationScoped; import javax.enterprise.context.RequestScoped; import javax.inject.Inject; import javax.persistence.EntityManager; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.rembx.jeeshop.user.model.QMailTemplate.mailTemplate; /** * Newsletter finder utility */ @ApplicationScoped public class MailTemplateFinder { public final static String DEFAULT_LOCALE = "en_GB"; private EntityManager entityManager; private static final Map<String, ComparableExpressionBase<?>> sortProperties = new HashMap<String, ComparableExpressionBase<?>>() {{ put("id", mailTemplate.id); put("name", mailTemplate.name); put("locale", mailTemplate.locale); put("creationDate", mailTemplate.creationDate); put("updateDate", mailTemplate.updateDate); }}; public static MailTemplateFinder getInstance(EntityManager entityManager) { return new MailTemplateFinder(entityManager); } MailTemplateFinder( @PersistenceUnit(UserPersistenceUnit.NAME) EntityManager entityManager) { this.entityManager = entityManager; } public MailTemplate findByNameAndLocale(String name, String locale) { if (locale == null) { locale = DEFAULT_LOCALE; } return new JPAQueryFactory(entityManager) .selectFrom(mailTemplate).where( mailTemplate.name.eq(name) .and(mailTemplate.locale.eq(locale).or(mailTemplate.locale.startsWith(locale)))) .fetchOne(); } public List<MailTemplate> findByName(String name) { return new JPAQueryFactory(entityManager) .selectFrom(mailTemplate).where( mailTemplate.name.startsWith(name)) .fetch(); } public List<MailTemplate> findAll(Integer offset, Integer limit, String orderBy, Boolean isDesc) { JPAQuery<MailTemplate> query = new JPAQueryFactory(entityManager).selectFrom(mailTemplate); if (offset != null) query.offset(offset); if (limit != null) query.limit(limit); sortBy(orderBy, isDesc, query); return query.fetch(); } public Long countAll() { JPAQuery query = new JPAQueryFactory(entityManager).selectFrom(mailTemplate); return query.fetchCount(); } private void sortBy(String orderby, Boolean isDesc, JPAQuery<MailTemplate> query) { if (orderby != null && sortProperties.containsKey(orderby)) { if (isDesc) { query.orderBy(sortProperties.get(orderby).desc()); } else { query.orderBy(sortProperties.get(orderby).asc()); } } } } <|start_filename|>order/src/main/java/org/rembx/jeeshop/order/Fees.java<|end_filename|> package org.rembx.jeeshop.order; import javax.annotation.security.PermitAll; import javax.enterprise.context.ApplicationScoped; import javax.enterprise.context.RequestScoped; import javax.inject.Inject; import javax.transaction.Transactional; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; @Path("/rs/fees") @ApplicationScoped public class Fees { private OrderConfiguration orderConfiguration; Fees(OrderConfiguration orderConfiguration) { this.orderConfiguration = orderConfiguration; } @GET @Produces(MediaType.APPLICATION_JSON) @Path("/shipping") @PermitAll public Double getShippingFee() { if (orderConfiguration!=null){ return orderConfiguration.getFixedDeliveryFee(); } return null; } @GET @Path("/vat") @Produces(MediaType.APPLICATION_JSON) @PermitAll public Double getVAT() { if (orderConfiguration!=null){ return orderConfiguration.getVAT(); } return null; } } <|start_filename|>user/src/main/java/org/rembx/jeeshop/user/mail/Mails.java<|end_filename|> package org.rembx.jeeshop.user.mail; public enum Mails { userRegistration, userActivation, userResetPassword, userChangePassword } <|start_filename|>user/src/test/java/org/rembx/jeeshop/user/tools/CryptToolsTest.java<|end_filename|> package org.rembx.jeeshop.user.tools; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; public class CryptToolsTest { @Test public void testHashSha256Base64() throws Exception { assertThat(CryptTools.hashSha256Base64("jeeshop")).isEqualTo("DjYu7nlNFk6BdxO+LwxZJ3mBAfxgwytTS2cVRbmnIO8="); } } <|start_filename|>user/src/main/java/org/rembx/jeeshop/user/model/RoleName.java<|end_filename|> package org.rembx.jeeshop.user.model; public enum RoleName { user, admin, store_admin } <|start_filename|>user/src/test/java/org/rembx/jeeshop/user/UsersCT.java<|end_filename|> package org.rembx.jeeshop.user; import org.apache.http.auth.BasicUserPrincipal; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.rembx.jeeshop.mail.Mailer; import org.rembx.jeeshop.rest.WebApplicationException; import org.rembx.jeeshop.role.JeeshopRoles; import org.rembx.jeeshop.user.model.Address; import org.rembx.jeeshop.user.model.User; import org.rembx.jeeshop.user.model.UserPersistenceUnit; import org.rembx.jeeshop.user.test.TestMailTemplate; import org.rembx.jeeshop.user.test.TestUser; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import java.util.Date; import java.util.List; import java.util.UUID; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; import static org.mockito.Mockito.*; import static org.rembx.jeeshop.user.tools.CryptTools.hashSha256Base64; public class UsersCT { private Users service; private TestUser testUser; private TestMailTemplate testMailTemplate; private static EntityManagerFactory entityManagerFactory; EntityManager entityManager; private Mailer mailerMock; private SecurityContext sessionContextMock; @BeforeAll public static void beforeClass() { entityManagerFactory = Persistence.createEntityManagerFactory(UserPersistenceUnit.NAME); } @BeforeEach public void setup() { testUser = TestUser.getInstance(); testMailTemplate = TestMailTemplate.getInstance(); entityManager = entityManagerFactory.createEntityManager(); mailerMock = mock(Mailer.class); sessionContextMock = mock(SecurityContext.class); service = new Users(entityManager, new UserFinder(entityManager), new RoleFinder(entityManager), new CountryChecker("FRA,GBR"), new MailTemplateFinder(entityManager), mailerMock); } @Test public void findAll_shouldReturnNoneEmptyList() { assertThat(service.findAll(null, null, null, null, null)).isNotEmpty(); } @Test public void findAll_withPagination_shouldReturnNoneEmptyListPaginated() { List<User> users = service.findAll(null, 0, 1, null, null); assertThat(users).isNotEmpty(); assertThat(users).containsExactly(testUser.firstUser()); } @Test public void findAll_ByLogin_shouldReturnSearchedUser() { List<User> users = service.findAll(testUser.firstUser().getLogin(), 0, 1, null, null); assertThat(users).isNotEmpty(); assertThat(users).containsExactly(testUser.firstUser()); } @Test public void findAll_ByFirstName_shouldReturnSearchedUser() { List<User> users = service.findAll(testUser.firstUser().getFirstname(), 0, 1, null, null); assertThat(users).isNotEmpty(); assertThat(users).containsExactly(testUser.firstUser()); } @Test public void findAll_ByLastName_shouldReturnSearchedUser() { List<User> users = service.findAll(testUser.firstUser().getLastname(), 0, 1, null, null); assertThat(users).isNotEmpty(); assertThat(users).containsExactly(testUser.firstUser()); } @Test public void find() throws Exception { assertThat(service.find(1L)).isNotNull(); } @Test public void find_withUnknownId_ShouldThrowException() throws Exception { try { service.find(999L); fail("should have thrown ex"); } catch (WebApplicationException e) { assertThat(e.getResponse().getStatusInfo()).isEqualTo(Response.Status.NOT_FOUND); } } @Test public void count() { assertThat(service.count(null)).isGreaterThan(0); } @Test public void count_withUnknownSearchCriteria() { assertThat(service.count("unknown")).isEqualTo(0); } @Test public void create_shouldThrowBadRequestExWhenUserHasAnId() throws Exception { User user = new User(); user.setId(777L); try { service.create(sessionContextMock, user); fail("should have thrown ex"); } catch (WebApplicationException e) { assertThat(e.getResponse().getStatusInfo()).isEqualTo(Response.Status.BAD_REQUEST); } } @Test public void create_shouldThrowConflictExWhenUserWithGivenLoginAlreadyExists() throws Exception { User user = new User(); user.setLogin("<EMAIL>"); try { service.create(sessionContextMock, user); fail("should have thrown ex"); } catch (WebApplicationException e) { assertThat(e.getResponse().getStatusInfo()).isEqualTo(Response.Status.CONFLICT); } } @Test public void create_shouldThrowBadRequestExceptionExWhenUsersCountryIsNotAvailable() throws Exception { User user = new User(); user.setLogin("<EMAIL>"); Address address = new Address(); address.setCountryIso3Code("ZZZ"); user.setAddress(address); try { service.create(sessionContextMock, user); fail("should have thrown ex"); } catch (WebApplicationException e) { assertThat(e.getResponse().getStatusInfo()).isEqualTo(Response.Status.BAD_REQUEST); } } @Test public void create_shouldThrowBadRequestExceptionExWhenUserAddressHasAnId() throws Exception { User user = new User(); user.setLogin("<EMAIL>"); Address address = new Address(); address.setId(1L); user.setAddress(address); try { service.create(sessionContextMock, user); fail("should have thrown ex"); } catch (WebApplicationException e) { assertThat(e.getResponse().getStatusInfo()).isEqualTo(Response.Status.BAD_REQUEST); } } @Test public void create_shouldOnlyPersistUserWhenOperationIsTriggeredByAdminUser() throws Exception { User user = new User("<EMAIL>", "test", "John", "Doe", "+33616161616", null, new Date(), "fr_FR", null); user.setGender("M."); when(sessionContextMock.isUserInRole(JeeshopRoles.ADMIN)).thenReturn(true); entityManager.getTransaction().begin(); service.create(sessionContextMock, user); entityManager.getTransaction().commit(); verify(sessionContextMock).isUserInRole(JeeshopRoles.ADMIN); assertThat(entityManager.find(User.class, user.getId())).isNotNull(); removeTestUser(user); } @Test public void create_shouldPersistEndUserAndRetrieveUserRegistrationMailTemplateAndSendMail() throws Exception { User user = new User("<EMAIL>", "test", "John", "Doe", "+33616161616", null, new Date(), "fr_FR", null); user.setGender("M."); when(sessionContextMock.isUserInRole(JeeshopRoles.ADMIN)).thenReturn(false); entityManager.getTransaction().begin(); service.create(sessionContextMock, user); entityManager.getTransaction().commit(); verify(sessionContextMock).isUserInRole(JeeshopRoles.ADMIN); verify(mailerMock).sendMail(testMailTemplate.userRegistrationMailTemplate().getSubject(), user.getLogin(), "<html><body>Welcome M. <NAME></body></html>"); assertThat(entityManager.find(User.class, user.getId())).isNotNull(); assertThat(user.getActivated()).isFalse(); assertThat(user.getActionToken()).isNotNull(); entityManager.remove(user); } @Test public void create_shouldJustPersistEndUserEvenWhenExceptionDuringMailSending() throws Exception { User user = new User("<EMAIL>", "test", "John", "Doe", "+33616161616", null, new Date(), "fr_FR", null); user.setGender("M."); Address address = new Address("7 blue street", "Nowhere", "00001", "John", "Doe", "M.", null, "FRA"); user.setAddress(address); when(sessionContextMock.isUserInRole(JeeshopRoles.ADMIN)).thenReturn(false); entityManager.getTransaction().begin(); service.create(sessionContextMock, user); entityManager.getTransaction().commit(); doThrow(new IllegalStateException("Test Exception")).when(mailerMock).sendMail(testMailTemplate.userRegistrationMailTemplate().getSubject(), user.getLogin(), testMailTemplate.userRegistrationMailTemplate().getContent()); verify(sessionContextMock).isUserInRole(JeeshopRoles.ADMIN); verify(mailerMock).sendMail(testMailTemplate.userRegistrationMailTemplate().getSubject(), user.getLogin(), "<html><body>Welcome M. <NAME></body></html>"); final User persistedUser = entityManager.find(User.class, user.getId()); assertThat(persistedUser).isNotNull(); assertThat(persistedUser.getAddress()).isEqualTo(address); entityManager.remove(user); } @Test public void activate_shouldActivateUserAndClearActionToken() throws Exception { User user = new User("<EMAIL>", "test", "John", "Doe", "+33616161616", null, new Date(), "fr_FR", null); user.setGender("M."); final UUID actionToken = UUID.randomUUID(); user.setActionToken(actionToken); user.setActivated(false); entityManager.getTransaction().begin(); entityManager.persist(user); entityManager.getTransaction().commit(); service.activate(user.getLogin(), actionToken.toString()); final User modifiedUser = entityManager.find(User.class, user.getId()); assertThat(modifiedUser).isNotNull(); assertThat(modifiedUser.getActivated()).isTrue(); assertThat(modifiedUser.getActionToken()).isNull(); } @Test public void activate_shouldThrowNotFoundExWhenUserIsNotFound() throws Exception { try { service.activate("unknown_login", UUID.randomUUID().toString()); fail("should have thrown ex"); } catch (WebApplicationException e) { assertThat(e.getResponse().getStatusInfo()).isEqualTo(Response.Status.NOT_FOUND); } } @Test public void sendResetPasswordMail_shouldGenerateActionTokenAndSendResetPasswordMail() throws Exception { entityManager.getTransaction().begin(); service.sendResetPasswordMail(testUser.firstUser().getLogin()); entityManager.getTransaction().commit(); verify(mailerMock).sendMail(testMailTemplate.resetPasswordMailTemplate().getSubject(), testUser.firstUser().getLogin(), "<html><body>Here is the link to reset your password</body></html>"); User persistedUser = entityManager.find(User.class, testUser.firstUser().getId()); assertThat(persistedUser).isNotNull(); entityManager.getTransaction().begin(); persistedUser.setActionToken(null); entityManager.getTransaction().commit(); } @Test public void sendResetPasswordMail_shouldThrowNotFoundEX_WhenUserIsNotFound() throws Exception { try { service.sendResetPasswordMail("unknown_login"); fail("should have thrown ex"); } catch (WebApplicationException e) { assertThat(e.getResponse().getStatusInfo()).isEqualTo(Response.Status.NOT_FOUND); } } @Test public void resetPassword_shouldUpdateUserPasswordWhenActionTokenMatchesUserActionToken() throws Exception { User user = notActivatedTestUser(); service.resetPassword(sessionContextMock, user.getLogin(), user.getActionToken().toString(), "<PASSWORD>"); final User updatedUser = entityManager.find(User.class, user.getId()); assertThat(updatedUser).isNotNull(); assertThat(updatedUser.getPassword()).isEqualTo(hashSha256Base64("<PASSWORD>")); assertThat(updatedUser.getActionToken()).isNull(); verify(mailerMock).sendMail(testMailTemplate.changePasswordMailTpl().getSubject(), user.getLogin(), testMailTemplate.changePasswordMailTpl().getContent()); removeTestUser(user); } @Test public void resetPassword_shouldUpdateUserPasswordForAuthenticatedUser() throws Exception { User user = notActivatedTestUser(); when(sessionContextMock.isUserInRole(JeeshopRoles.USER)).thenReturn(true); when(sessionContextMock.getUserPrincipal()).thenReturn(new BasicUserPrincipal(user.getLogin())); service.resetPassword(sessionContextMock, user.getLogin(), null, "<PASSWORD>"); final User updatedUser = entityManager.find(User.class, user.getId()); assertThat(updatedUser).isNotNull(); assertThat(updatedUser.getPassword()).isEqualTo(hashSha256Base64("<PASSWORD>")); verify(mailerMock).sendMail(testMailTemplate.changePasswordMailTpl().getSubject(), user.getLogin(), testMailTemplate.changePasswordMailTpl().getContent()); removeTestUser(user); } @Test public void resetPassword_shouldUpdateUserPasswordForAuthenticatedADMINUser() throws Exception { User user = notActivatedTestUser(); when(sessionContextMock.isUserInRole(JeeshopRoles.ADMIN)).thenReturn(true); service.resetPassword(sessionContextMock, user.getLogin(), null, "newPassword"); final User updatedUser = entityManager.find(User.class, user.getId()); assertThat(updatedUser).isNotNull(); assertThat(updatedUser.getPassword()).isEqualTo(hashSha256Base64("newPassword")); verify(mailerMock).sendMail(testMailTemplate.changePasswordMailTpl().getSubject(), user.getLogin(), testMailTemplate.changePasswordMailTpl().getContent()); removeTestUser(user); } @Test public void resetPassword_shouldReturnNotFoundResponse_whenUserIsNotFound() throws Exception { try { service.resetPassword(sessionContextMock, "unknown_login", null, null); fail("should have thrown ex"); } catch (WebApplicationException e) { assertThat(e.getResponse().getStatusInfo()).isEqualTo(Response.Status.NOT_FOUND); } } @Test public void resetPassword_shouldReturnUnauthorizedResponse_whenAuthenticatedUserDoesNotMatchLogin() throws Exception { try { when(sessionContextMock.isUserInRole(JeeshopRoles.USER)).thenReturn(true); when(sessionContextMock.getUserPrincipal()).thenReturn(new BasicUserPrincipal(testUser.firstUser().getLogin())); service.resetPassword(sessionContextMock, "not_matching_login", null, null); fail("should have thrown ex"); } catch (WebApplicationException e) { assertThat(e.getResponse().getStatusInfo()).isEqualTo(Response.Status.UNAUTHORIZED); } } @Test public void modifyUser_ShouldModifyUser() { User detachedUserToModify = new User("<EMAIL>", "test", "John", "Doe", "+33616161616", null, new Date(), "fr_FR", null); detachedUserToModify.setId(testUser.firstUser().getId()); service.modify(sessionContextMock, detachedUserToModify); } @Test public void modifyUnknownUser_ShouldThrowNotFoundException() { User detachedUser = new User("<EMAIL>", "test", "John", "Doe", "+33616161616", null, new Date(), "fr_FR", null); detachedUser.setId(9999L); try { service.modify(sessionContextMock, detachedUser); fail("should have thrown ex"); } catch (WebApplicationException e) { assertThat(e.getResponse().getStatusInfo()).isEqualTo(Response.Status.NOT_FOUND); } } @Test public void modify_ShouldThrowUnauthorizedError_WhenAuthenticatedUserDoesNotMatchLogin() throws Exception { User detachedUserToModify = new User("<EMAIL>", "test", "John", "Doe", "+33616161616", null, new Date(), "fr_FR", null); try { when(sessionContextMock.isUserInRole(JeeshopRoles.USER)).thenReturn(true); when(sessionContextMock.getUserPrincipal()).thenReturn(new BasicUserPrincipal(testUser.firstUser().getLogin())); service.modify(sessionContextMock, detachedUserToModify); fail("should have thrown ex"); } catch (WebApplicationException e) { assertThat(e.getResponse().getStatusInfo()).isEqualTo(Response.Status.UNAUTHORIZED); } } @Test public void delete_shouldRemove() { entityManager.getTransaction().begin(); User user = new User("<EMAIL>", "test", "John", "Doe", "+33616161616", null, new Date(), "fr_FR", null); user.setGender("M."); entityManager.persist(user); entityManager.getTransaction().commit(); entityManager.getTransaction().begin(); service.delete(user.getId()); entityManager.getTransaction().commit(); assertThat(entityManager.find(User.class, user.getId())).isNull(); } @Test public void delete_NotExistingEntry_shouldThrowNotFoundEx() { try { entityManager.getTransaction().begin(); service.delete(666L); entityManager.getTransaction().commit(); fail("should have thrown ex"); } catch (WebApplicationException e) { assertThat(e.getResponse().getStatusInfo()).isEqualTo(Response.Status.NOT_FOUND); } } @Test public void findCurrentUser_shouldReturnCurrentAuthenticatedUser() throws Exception { when(sessionContextMock.getUserPrincipal()).thenReturn(new BasicUserPrincipal(testUser.firstUser().getLogin())); assertThat(service.findCurrentUser(sessionContextMock)).isEqualTo(testUser.firstUser()); } private User notActivatedTestUser() { User user = new User("<EMAIL>", "password", "<PASSWORD>", "Doe", "+33616161616", null, new Date(), "fr_FR", null); user.setGender("M."); final UUID actionToken = UUID.randomUUID(); user.setActionToken(actionToken); user.setActivated(false); entityManager.getTransaction().begin(); entityManager.persist(user); entityManager.getTransaction().commit(); return user; } private void removeTestUser(User user) { entityManager.getTransaction().begin(); entityManager.remove(user); entityManager.getTransaction().commit(); } }
remibantos/jeeshop
<|start_filename|>Makefile<|end_filename|> ## https://www.thapaliya.com/en/writings/well-documented-makefiles/ .DEFAULT_GOAL:=help SHELL:=/bin/bash BUILD_VERSION ?= dev DOCKER_REGISTRY ?= registry.hub.docker.com DOCKER_REPOSITORY := $(DOCKER_REGISTRY)/line/abc-user-feedback ##@ Helpers .PHONY: help help: ## Display this help @awk 'BEGIN {FS = ":.*##"; printf "\nUsage:\n make \033[36m\033[0m\n\nTargets:\n"} /^[a-zA-Z_-]+:.*?##/ { printf " \033[36m%-10s\033[0m %s\n", $$1, $$2 }' $(MAKEFILE_LIST) ##@ Building .PHONY: build-docker build-docker: ## Build the project $(info Building project) docker build \ --build-arg BUILD_VERSION=$(BUILD_VERSION) \ -t $(DOCKER_REPOSITORY):$(BUILD_VERSION) \ -t $(DOCKER_REPOSITORY):latest \ . ##@ Publish .PHONY: publish-docker publish-docker: ## Push docker image $(info Push docker image) docker push $(DOCKER_REPOSITORY):$(BUILD_VERSION) docker push $(DOCKER_REPOSITORY):latest ##@ Running .PHONY: migrate migrate: ## Run all database migrations $(info Run migration) ##@ Miscellaneous .PHONY: clean clean: ## Cleanup the project folders $(info Cleanup dist, build) rm -rf ./dist rm -rf ./.next <|start_filename|>public/locales/ja/common.json<|end_filename|> { "menu.administration": "アドミン", "menu.account": "アカウント設定", "menu.password.change": "パスワード設定", "menu.logout": "ログアウト", "menu.member": "ユーザー管理", "placeholder.email": "メールアドレス", "placeholder.password": "<PASSWORD>", "placeholder.password.rule": "半角英数字特殊文字混在で8文字以上", "placeholder.password.confirm": "パスワードを再度入力", "placeholder.password.current": "現在のパスワードを入力", "placeholder.select.role": "権限を選択", "placeholder.invitation.mail": "メールアドレスを入力", "validation.email": "入力されたメールアドレスは登録されていません。\nメールアドレスを確認してください。", "validation.email.domain": "メールアドレスが間違っています。正しく入力されているかご確認ください。", "validation.email_password": "ログインできませんでした。メールアドレス・パスワードが間違っていないかご確認ください。", "validation.password": "パスワードは、半角英数字・記号を含む8~20文字で入力してください。", "validation.password.confirm": "パスワードが一致しません。", "validation.password.nickname": "ニックネームを確認してください。", "validation.select.role": "権限を選択してください。", "action.delete": "削除", "action.cancel": "キャンセル", "action.save": "保存する", "action.search": "検索", "action.clear": "条件を削除", "action.confirm": "確認", "action.password.set": "パスワードを設定", "action.login": "ログイン", "action.remember_email": "メールアドレスを保存する", "action.password.forgot": "パスワードを忘れた方はこちら", "action.send.mail.password.reset": "パスワード再設定メールを送付", "action.submit.password.reset": "再設定", "action.download.excel": "Excelにダウンロード", "action.download.csv": "CSVにダウンロード", "action.member.invite": "ユーザーを追加する", "action.user.role.binding": "{{role}}変更", "action.member.to.owner": "Owner変更", "action.member.to.manager": "Manager変更", "action.member.to.guest": "Guest変更", "action.member.to.admin": "Admin変更", "action.member.delete": "ユーザーを削除する", "action.send.mail.invitation": "ユーザー追加メールを送付する", "action.account.delete": "アカウント削除", "label.email": "メールアドレス", "label.password_current": "<PASSWORD>", "label.password_new": "<PASSWORD>", "label.password_confirm": "<PASSWORD>(確認)", "label.setting.user": "ユーザーセッティング", "snackbar.success.send.mail.invitation": "メールを送付しました。", "snackbar.success.send.mail.reset.password": "メールを送付しました。", "snackbar.success.settings.profile": "アカウント情報の変更を保存しました。", "snackbar.success.change.password": "アカウント情報の変更を保存しました。", "snackbar.success.role.binding": "変更が完了しました。", "snackbar.success.user.delete": "アカウントが削除されました。", "description.password.reset": "管理画面へのログインに使用しているメールアドレスを入力してください。入力されたメールアドレス宛に、パスワード再設定メールを送付します。\n*パスワード再設定リンクの有効期限は24時間です。", "title.password.reset": "パスワードの再設定", "title.feedback.list": "フィードバック管理", "title.feedback.detail": "フィードバック詳細", "title.member": "ユーザー管理", "title.settings.profile": "アカウント設定", "title.account.delete": "アカウント削除", "confirm.delete.member": "ユーザーを削除しますか?", "confirm.account.delete": "アカウントを削除します。よろしいですか?", "error.password.not_correct": "現在のパスワードを再度確認してください。", "error.user.already_registerd": "メールアドレスが間違っています。正しく入力されているかご確認ください。", "error.user.not_registerd": "登録されていないユーザーです。", "error.user.not_verified": "まだ認証されていないユーザーです。" } <|start_filename|>Dockerfile<|end_filename|> # Build stage FROM node:16-alpine AS builder WORKDIR /pre ENV NODE_OPTIONS="–max_old_space_size=4096" ENV NEXT_TELEMETRY_DISABLED 1 RUN apk --no-cache add --virtual builds-deps build-base python3 COPY . . RUN yarn --frozen-lockfile RUN yarn build:server RUN yarn build:client RUN yarn install --production --ignore-scripts --prefer-offline # Runtime stage FROM node:16-alpine WORKDIR /usr/app ENV NODE_ENV production COPY --from=builder /pre/public ./public COPY --from=builder /pre/next-i18next.config.js ./next-i18next.config.js COPY --from=builder /pre/dist ./dist COPY --from=builder /pre/template ./template COPY --from=builder /pre/.next ./.next COPY --from=builder /pre/node_modules ./node_modules COPY --from=builder /pre/package.json ./package.json EXPOSE 3000 CMD yarn start <|start_filename|>next-i18next.config.js<|end_filename|> module.exports = { i18n: { defaultNS: 'common', defaultLocale: 'en', locales: ['en', 'ja'], localeExtension: 'json', } } <|start_filename|>public/locales/en/common.json<|end_filename|> { "menu.administration": "Administration", "menu.account": "Account", "menu.password.change": "Change password", "menu.logout": "Logout", "menu.member": "Members", "placeholder.email": "Email", "placeholder.password": "Password", "placeholder.password.rule": "Including 8 or more letters, numbers, and special characters", "placeholder.password.confirm": "<PASSWORD>", "placeholder.password.current": "Current password", "placeholder.select.role": "Select role", "placeholder.invitation.mail": "Send emails to user per line", "validation.email": "Check your email", "validation.email.domain": "Check your email", "validation.email_password": "<PASSWORD> your email/password", "validation.password": "The password must contain at least 8 letters of English, numbers, and special characters", "validation.password.confirm": "<PASSWORD>", "validation.password.nickname": "Check your nickname", "validation.select.role": "Select role", "action.delete": "Delete", "action.cancel": "Cancel", "action.save": "Save", "action.search": "Search", "action.clear": "Clear", "action.confirm": "Confirm", "action.password.set": "Set", "action.login": "Login", "action.remember_email": "Remember email", "action.password.forgot": "Forget password", "action.send.mail.password.reset": "Send email", "action.submit.password.reset": "Submit", "action.download.excel": "Excel download", "action.download.csv": "CSV download", "action.member.invite": "Invite member", "action.user.role.binding": "To {{role}}", "action.member.to.owner": "To owner", "action.member.to.manager": "To manager", "action.member.to.guest": "To guest", "action.member.to.admin": "To admin", "action.member.delete": "Delete member", "action.send.mail.invitation": "Send invitation", "action.account.delete": "Delete account", "label.email": "Email", "label.password_current": "<PASSWORD>", "label.password_new": "<PASSWORD>", "label.password_confirm": "<PASSWORD>", "label.setting.user": "User setting", "snackbar.success.send.mail.invitation": "Success send invitation mail", "snackbar.success.send.mail.reset.password": "Success send email", "snackbar.success.settings.profile": "Success save profile", "snackbar.success.change.password": "Success save password", "snackbar.success.role.binding": "Success role change", "snackbar.success.user.delete": "Success delete user", "description.password.reset": "Send reset password email.\n(it expired after 24 hours)", "title.password.reset": "Reset password", "title.feedback.list": "Feedback list", "title.feedback.detail": "Feedback detail", "title.member": "Member", "title.settings.profile": "Profile", "title.account.delete": "Delete account", "confirm.delete.member": "Delete this member?", "confirm.account.delete": "Delete this account?", "error.password.not_correct": "Check your password", "error.user.already_registerd": "User already registerd", "error.user.not_registerd": "User not registered", "error.user.not_verified": "User not verified" } <|start_filename|>src/client/next.config.js<|end_filename|> /* */ const path = require('path') const { i18n } = require('../../next-i18next.config') const nextConfig = { i18n, distDir: '../../.next', api: { externalResolver: true }, experimental: { externalDir: true }, serverRuntimeConfig: {}, publicRuntimeConfig: { BUILD_VERSION: process.env.BUILD_VERSION || 'dev', SMTP_HOST: process.env.SMTP_HOST }, webpack: (config, { buildId, dev, isServer, defaultLoaders, webpack }) => { /** * Plugins */ /** * next.js doesn't know alias, so extends webpack config * {@link https://webpack.js.org/configuration/resolve} */ config.resolve.alias['~'] = path.join(__dirname) config.resolve.alias['@'] = path.join(__dirname, '../') config.externals = config.externals || {} config.externals['styletron-server'] = 'styletron-server' /** * Modules */ config.module.rules.push( /** * for import graphql files * {@link https://github.com/apollographql/graphql-tag} */ { test: /\.svg$/, use: ['@svgr/webpack'] } ) config.plugins.push( new webpack.DefinePlugin({ 'process.env.IS_SERVER': isServer }) ) config.resolve.fallback = { fs: false, os: false, http: false, https: false, net: false, tls: false, zlib: false } return config }, webpackDevMiddleware: (config) => { return config } } module.exports = nextConfig
line/abc-user-feedback
<|start_filename|>main.go<|end_filename|> package main import ( "flag" "net/http" "github.com/howeyc/fsnotify" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promhttp" "github.com/prometheus/common/log" ) var ( address = flag.String("beanstalkd.address", "localhost:11300", "Beanstalkd server address") connectionTimeout = flag.Duration("beanstalkd.connection-timeout", 0, "Timeout value for tcp connection to Beanstalkd") logLevel = flag.String("log.level", "warning", "The log level.") mappingConfig = flag.String("mapping-config", "", "A file that describes a mapping of tube names.") sleepBetweenStats = flag.Int("sleep-between-tube-stats", 5000, "The number of milliseconds to sleep between tube stats.") numTubeStatWorkers = flag.Int("num-tube-stat-workers", 1, "The number of concurrent workers to use to fetch tube stats.") listenAddress = flag.String("web.listen-address", ":8080", "Address to listen on for web interface and telemetry.") metricsPath = flag.String("web.telemetry-path", "/metrics", "Path under which to expose metrics.") ) var ( mapper *tubeMapper registry *prometheus.Registry ) func watchConfig(fileName string, mapper *tubeMapper) { watcher, err := fsnotify.NewWatcher() if err != nil { log.Fatal(err) } err = watcher.WatchFlags(fileName, fsnotify.FSN_MODIFY) if err != nil { log.Fatal(err) } for { select { case ev := <-watcher.Event: log.Warnf("Config file changed (%s), attempting reload", ev) err = mapper.initFromFile(fileName) if err != nil { log.Errorf("Error reloading config: %v", err) mapper.configLoadsMetric.WithLabelValues("failure").Inc() } else { log.Warn("Config reloaded successfully") mapper.configLoadsMetric.WithLabelValues("success").Inc() } // Re-add the file watcher since it can get lost on some changes. E.g. // saving a file with vim results in a RENAME-MODIFY-DELETE event // sequence, after which the newly written file is no longer watched. err = watcher.WatchFlags(fileName, fsnotify.FSN_MODIFY) case err := <-watcher.Error: log.Errorf("Error watching config: %v", err) } } } func main() { flag.Parse() if *logLevel == "debug" { log.Base().SetLevel("debug") } mapper = newTubeMapper() if *mappingConfig != "" { err := mapper.initFromFile(*mappingConfig) if err != nil { log.Fatal("Error loading mapping config:", err) } go watchConfig(*mappingConfig, mapper) } exporter := NewExporter(*address) exporter.SetConnectionTimeout(*connectionTimeout) registry = prometheus.NewRegistry() registry.MustRegister(exporter) http.Handle(*metricsPath, promhttp.HandlerFor( registry, promhttp.HandlerOpts{ErrorHandling: promhttp.ContinueOnError}, )) http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { w.Write([]byte(` <html> <head><title>Beanstalkd Exporter</title></head> <body> <h1>Beanstalkd Exporter</h1> <p><a href='` + *metricsPath + `'>Metrics</a></p> </body> </html> `), ) }) log.Warnf("Listening on port %s .", *listenAddress) log.Fatal(http.ListenAndServe(*listenAddress, nil)) } <|start_filename|>lazy_conn.go<|end_filename|> package main import ( "io" "net" "sync" "time" "github.com/prometheus/common/log" ) type lazyConn struct { m sync.Mutex conn net.Conn addr string dialTimeout time.Duration readTimeout time.Duration } func newLazyConn(addr string, dialTimeout time.Duration, readTimeout time.Duration) (io.ReadWriteCloser, error) { l := &lazyConn{ dialTimeout: dialTimeout, readTimeout: readTimeout, addr: addr, } if err := l.connect(); err != nil { return nil, err } return l, nil } func (l *lazyConn) connect() error { conn, err := net.DialTimeout("tcp", l.addr, l.dialTimeout) if err != nil { l.conn = nil return err } l.conn = conn return nil } func (l *lazyConn) withTimeout() net.Conn { if l.readTimeout > 0 { err := l.conn.SetReadDeadline(time.Now().Add(l.readTimeout)) if err != nil { log.Warnf("unable to set timeout: %s", err) } } return l.conn } // Read implements the io.Reader interface and attempt // to reconnect to beanstalk in case of io.EOF. func (l *lazyConn) Read(p []byte) (n int, err error) { l.m.Lock() defer l.m.Unlock() if l.conn == nil { if err := l.connect(); err != nil { return 0, io.ErrUnexpectedEOF } } n, err = l.withTimeout().Read(p) switch { case err == io.EOF: fallthrough case err == io.ErrUnexpectedEOF: l.conn = nil } return n, err } // Write implements the io.Writer interface and attempt // to reconnect to beanstalk in case of io.EOF. func (l *lazyConn) Write(p []byte) (n int, err error) { l.m.Lock() defer l.m.Unlock() if l.conn == nil { if err := l.connect(); err != nil { return 0, io.ErrClosedPipe } } n, err = l.withTimeout().Write(p) if n == 0 && err != io.ErrClosedPipe { l.conn = nil } return n, err } // Close the TCP connection. func (l *lazyConn) Close() error { return l.conn.Close() } <|start_filename|>Dockerfile<|end_filename|> FROM golang:alpine as build-env RUN apk add git # Copy source + vendor COPY . /go/src/github.com/messagebird/beanstalkd_exporter WORKDIR /go/src/github.com/messagebird/beanstalkd_exporter # Build ENV GOPATH=/go RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 GO111MODULE=off go build -v -a -ldflags "-s -w" -o /go/bin/beanstalkd_exporter . # Build mininal image with compiled app FROM scratch COPY examples/ /etc/beanstalkd_exporter/ COPY --from=build-env /go/bin/beanstalkd_exporter /usr/bin/beanstalkd_exporter ENTRYPOINT ["beanstalkd_exporter"] CMD ["-beanstalkd.address", "beanstalkd:11300"]
practo/beanstalkd_exporter
<|start_filename|>torisetsu_test.go<|end_filename|> package main import ( "reflect" "strings" "testing" ) const ( default_license = "mit" default_author = "" default_comparison_license = "[MIT](http://opensource.org/licenses/mit-license.php)" default_comparison_author = "[](https://github.com/)" ) func createCoparisonTemplate(comparison_license, comparison_author string) []byte { body := []string{ "Overview", "## Description", "## Demo", "## VS.", "## Requirement", "## Usage", "## Install", "## Contribution", "## License", comparison_license, "## Author", comparison_author, } return []byte("\n" + strings.Join(body, "\n\n")) } func compareTestData(license, author, comparison_license, comparison_author string) bool { readme_template := createReadTemplate(license, author) comparison_template := createCoparisonTemplate(comparison_license, comparison_author) return reflect.DeepEqual(readme_template, comparison_template) } func TestRun_noFlag(t *testing.T) { license, _ := flagLicense(default_license) author := flagAuthor(default_author) comparison_license := default_comparison_license comparison_author := default_comparison_author result := compareTestData(license, author, comparison_license, comparison_author) if !result { t.Fatalf("Test Failed") } } func TestRun_licenseFlag(t *testing.T) { license, _ := flagLicense("unlicense") author := flagAuthor(default_author) comparison_license := "[The Unlicense](http://unlicense.org/)" comparison_author := default_comparison_author result := compareTestData(license, author, comparison_license, comparison_author) if !result { t.Fatalf("Test Failed") } } func TestRun_authorFlag(t *testing.T) { license, _ := flagLicense(default_license) author := flagAuthor("syossan27") comparison_license := default_comparison_license comparison_author := "[syossan27](https://github.com/syossan27)" result := compareTestData(license, author, comparison_license, comparison_author) if !result { t.Fatalf("Test Failed") } } <|start_filename|>torisetsu.go<|end_filename|> package main import ( "bufio" "errors" "fmt" "github.com/urfave/cli" "github.com/mitchellh/go-homedir" "os" "strings" "torisetsu/foundation" ) const ( ExitCodeOK = iota ExitCodeError defaultLicense = "mit" ) var ( homeDir string configDir string flags = []cli.Flag{ cli.StringFlag{ Name: "license, l", Value: defaultLicense, Usage: "This flag specifies the choose license to print.\n\t" + strings.Join(chooseLicenceStrings, "\n\t"), }, cli.StringFlag{ Name: "author, a", Value: "", Usage: "This flag specifies the author name to print.", }, cli.StringFlag{ Name: "template, t", Value: "", Usage: "Input the name of the file except for the extension.", }, } chooseLicenceStrings = []string{ "Choose License:", " none\t: None", " apache\t: Apache License 2.0", " mit\t: MIT License", " al\t: Artistic License 2.0", " bsd2\t: BSD 2-clause 'Simplified' License", " bsd3\t: BSD 3-clause 'New' or 'Revised' License", " cc0\t: Creative Commons Zero v1.0 Universal", " epl\t: Eclipse Public License 1.0", " agpl\t: GNU Affero General Public License v3.0", " gpl2\t: GNU General Public License v2.0", " gpl3\t: GNU General Public License v3.0", " lgpl2\t: GNU Lesser General Public License v2.1", " lgpl3\t: GNU Lesser General Public License v3.0", " iscl\t: ISC License", " mpl\t: Mozilla Public License 2.0", " unlicense\t: The Unlicense", } licenseList = map[string]string{ "none": "None", "apache": "[Apache License 2.0](http://www.apache.org/licenses/LICENSE-2.0)", "mit": "[MIT](http://opensource.org/licenses/mit-license.php)", "al": "[Artistic License 2.0](http://www.perlfoundation.org/artistic_license_2_0)", "bsd2": "[BSD 2-clause 'Simplified' License](https://opensource.org/licenses/BSD-2-Clause)", "bsd3": "[BSD 3-clause 'New' or 'Revised' License](https://opensource.org/licenses/BSD-3-Clause)", "cc0": "[Creative Commons Zero v1.0 Universal](http://creativecommons.org/publicdomain/zero/1.0/legalcode)", "epl": "[Eclipse Public License 1.0](http://www.eclipse.org/legal/epl-v10.html)", "agpl": "[GNU Affero General Public License v3.0](http://www.gnu.org/licenses/agpl-3.0.html)", "gpl2": "[GNU General Public License v2.0](http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt)", "gpl3": "[GNU General Public License v3.0](http://www.gnu.org/licenses/gpl-3.0.txt)", "lgpl2": "[GNU Lesser General Public License v2.1](http://www.gnu.org/licenses/lgpl-2.1.html)", "lgpl3": "[GNU Lesser General Public License v3.0](http://www.gnu.org/licenses/lgpl-3.0.html)", "iscl": "[ISC License](http://opensource.org/licenses/isc-license.txt)", "mpl": "[Mozilla Public License 2.0](https://www.mozilla.org/en-US/MPL/2.0/)", "unlicense": "[The Unlicense](http://unlicense.org/)", } ) func makeApp() *cli.App { app := cli.NewApp() app.Name = "torisetsu" app.Usage = "Write README.md Template" app.Version = "1.1" app.Flags = flags app.Action = action return app } func action(c *cli.Context) { file, err := os.OpenFile("README.md", os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0600) if err != nil { foundation.PrintError("README.md is not exist") os.Exit(ExitCodeError) } defer file.Close() homeDir, err = homedir.Dir() if err != nil { foundation.PrintError("Failed fetch homeDir: " + err.Error()) os.Exit(ExitCodeError) } configDir = homeDir + "/.torisetsu" // Flag license license, err := flagLicense(c.String("license")) if err != nil { foundation.PrintError("Failed fetch license: " + err.Error()) os.Exit(ExitCodeError) } // Flag author author := flagAuthor(c.String("author")) // Flag template template, err := flagTemplate(c.String("template"), license, author) if err != nil { foundation.PrintError("Failed fetch template: " + err.Error()) os.Exit(ExitCodeError) } writer := bufio.NewWriter(file) writer.Write(template) writer.Flush() foundation.PrintSuccess("Complete add README.md!") os.Exit(ExitCodeOK) } func flagLicense(licenseName string) (string, error) { if license, ok := licenseList[licenseName]; ok { return license, nil } else { return "", errors.New("selected license can not be used") } } func flagAuthor(author string) string { return fmt.Sprintf("[%s](https://github.com/%s)", author, author) } // it's so foolish code. // Need Refactoring. func flagTemplate(template, license, author string) ([]byte, error) { if template == "" { if FileExists(configDir + "/default.md") { templateCotent, err := readTemplate("default", license, author) if err != nil { return nil, err } return templateCotent, nil } else { templateContent := createReadTemplate(license, author) return templateContent, nil } } else { templateContent, err := readTemplate(template, license, author) if err != nil { return nil, err } return templateContent, nil } } func readTemplate(templateName, license, author string) ([]byte, error) { f, err := os.Open(configDir + "/" + templateName + ".md") if err != nil { return []byte(""), err } templateContent := make([]string, 0) s := bufio.NewScanner(f) for s.Scan() { insertText := s.Text() if insertText == "torisetsu.license" { insertText = license } else if insertText == "torisetsu.author" { insertText = author } templateContent = append(templateContent, insertText) } if s.Err() != nil { return []byte(""), err } return []byte(strings.Join(templateContent, "\n")), nil } func createReadTemplate(license, author string) []byte { body := []string{ "Overview", "## Description", "## Demo", "## VS.", "## Requirement", "## Usage", "## Install", "## Contribution", "## License", fmt.Sprintf(license), "## Author", fmt.Sprintf(author), } return []byte("\n" + strings.Join(body, "\n\n")) } func FileExists(filename string) bool { _, err := os.Stat(filename) return err == nil } func main() { app := makeApp() app.Run(os.Args) } <|start_filename|>foundation/printer.go<|end_filename|> package foundation import ( "github.com/fatih/color" ) func PrintError(msg string) { color.Red("Error: " + msg) } func PrintSuccess(msg string) { color.Green(msg) }
syossan27/torisetsu
<|start_filename|>lang/pt.js<|end_filename|> rg2.setDictionary({ code: 'pt', language: 'Português - Brasil', translation: '<NAME> + <NAME>', 'Events' : 'Eventos', 'Course' : 'Percurso', 'Courses': 'Percursos', 'Controls': 'Controles', 'Results': 'Resultados', 'Draw': 'Desenho', 'Show': 'Exibir', 'Runners': 'Corredores', 'Routes': 'Rotas', 'Route': 'Rota', 'Name': 'Nome', 'Time': 'Tempo', 'Replay': 'Repetir', 'All': 'Tudo', 'Help': 'Ajuda', 'Options': 'Opções', 'Reset': 'Reiniciar', 'Zoom out': 'Menos zoom', 'Zoom in': 'Mais zoom', 'Rotate right': 'Girar a direita', 'Rotate left': 'Girar a esquerda', 'Splits': 'Parciais', 'Splits table': 'Tabela de parciais', 'Select runners on Results tab': 'Selecione corredores na Guia de resultados', 'Log in': 'Login', 'User name': 'Nome de usuário', 'Password': '<PASSWORD>', 'Show controls': 'Exibir controles', 'Hide controls': 'Esconder controles', 'Show initials': 'Exibir iniciais', 'Show names': 'Exibir nomes', 'Hide names': 'Esconder nomes', 'Show info panel': 'Exibir painel de informações', 'Hide info panel': 'Esconder painel de informações', 'Select an event': 'Selecione um evento', 'Slower': 'Mais lento', 'Run': 'Executa', 'Pause': 'Pausa', 'Faster': 'Mais rápido', 'Real time': 'Tempo real', 'Mass start': 'Largada em massa', 'Start at': 'Inicia em', 'Length': 'Distância', 'Full tails': 'Detalhes completos', 'No results available': 'Sem resultados disponíveis', 'Configuration options': 'Opções de configuração', 'Language': 'Idioma', 'Map intensity %': 'Intensidade do mapa %', 'Route intensity %': 'Intensidade da rota %', 'Route width': 'Largura da rota', 'Replay label font size': 'Tamanho da fonte da legenda de repetição', 'Course overprint width': 'Largura da sobreposição de percurso', 'Control circle size': 'Tamanho do circulo do controle', 'Snap to control when drawing': 'Snap para controle quando desenhando', 'Show +3 time loss for GPS routes': 'Exibir +3 tempos perdidos por rotas do GPS', 'Show GPS speed colours': 'Exibir cores de velocidade do GPS', 'Event statistics': 'Estatísticas do evento', 'Drawn routes': 'Desenhar rotas', 'GPS routes': 'Rotas do GPS', 'Comments': 'Comentários', 'Draw route': 'Desenhar rota', 'Select course': 'Selecione percurso', 'Select name': 'Selecione nome', 'Type your comment': 'Escreva seu comentário', 'Load GPS file (GPX or TCX)': 'Carregue arquivo do GPS (GPX ou TCX)', 'Save': 'Salvar', '+3 sec': '+3 seg', 'Undo': 'Desfazer', 'Save GPS route': 'Salvar rota do GPS', 'Align map to next control': 'Alinhar mapa ao próximo controle', 'Move track and map together (or right click-drag)': 'Mover trilha e mapa juntos (ou clique botão direito do mouse e arraste)', 'Map is georeferenced': 'Mapa está georreferenciado', 'International event': 'Evento internacional', 'National event': 'Evento nacional', 'Regional event': 'Evento regional', 'Local event': 'Evento local', 'Training event': 'Evento treino', 'Unknown': 'Desconhecido', 'Warning': 'Alerta', 'Your route has been saved': 'Sua rota foi salva', 'Your route was not saved. Please try again': 'Sua rota não foi salva. Por favor tente novamente', 'Loading courses': 'Carregando percursos', 'Loading results': 'Carregando resultados', 'Loading map': 'Carregando mapa', 'Loading routes': 'Carregando rotas', 'Saving courses': 'Salvando percursos', 'Saving results': 'Salvando resultados', 'Saving routes': 'Salvando rotas', 'Map loaded': 'Map carregado', 'Total time': 'Tempo total', 'Left click to add/lock/unlock a handle': 'Clique botão esquerdo do mouse para adicionar / bloquear / desbloquear uma alça', 'Green - draggable': 'Verde - arrastável', 'Red - locked': 'Vermelho - bloqueado', 'Right click to delete a handle': 'Clique botão direito do mouse para excluir uma alça', 'Drag a handle to adjust track around locked point(s)': 'Arraste uma alça para ajustar faixa em torno do(s) ponto(s) bloqueado(s)', 'Autofit': 'Autopreenchimento', 'Route already drawn': 'Rota já desenhada', 'If you draw a new route it will overwrite the old route for this runner.': 'Se você desenhar uma nova rota isto irá substituir a rota anterior para este corredor.', 'GPS routes are saved separately and will not be overwritten.': 'Rotas do GPS são salvas separadamente e não serão substituídas.', 'Search': 'Buscar' }); <|start_filename|>lang/fr.js<|end_filename|> rg2.setDictionary({ code: 'fr', language: 'Français', translation: '<EMAIL>', 'Events' : 'Compétition', 'Course' : 'Parcours', 'Courses': 'Parcours', 'Controls': 'Contrôles', 'Results': 'Résultats', 'Draw': 'Dessiner', 'Show': 'Afficher', 'Runners': 'Coureurs', 'Routes': 'Tracés', 'Route': 'Trace', 'Name': 'Nom', 'Time': 'Chrono', 'Replay': 'Rejouer', 'All': 'Tous', 'Help': 'Aide', 'Options': 'Options', 'Reset': 'RAZ', 'Zoom out': 'Zoom -', 'Zoom in': 'Zoom +', 'Splits': 'Splits', 'Splits table': 'Table des Temps intermédiaires', 'Select runners on Results tab': "Sélectionner les coureurs dans l'onglet Résultats", 'Log in': 'Login', 'User name': 'Utilisateur', 'Password': '<PASSWORD>', 'Show controls': 'Afficher les contrôles', 'Hide controls': 'Cacher les contrôles', 'Show initials': 'Afficher les initiales', 'Show names': 'Afficher les noms', 'Hide names': 'Cacher les noms', 'Show info panel': "Afficher le panneau d'information", 'Hide info panel': "Cacher le panneau d'information", 'Select an event': 'Choisir une compétition', 'Slower': 'Plus lentement', 'Run': 'Démarrer', 'Pause': 'Pause', 'Faster': 'Plus vite', 'Real time': 'Heures réelles', 'Mass start': 'Départ de masse', 'Start at': 'Début à', 'Length': 'Long.', 'Full tails': 'Trainée', 'No results available': 'Aucun résultat disponible', 'Configuration options': 'Options de configuration', 'Language': 'Langue', 'Map intensity %': 'Intensité de la carte %', 'Route intensity %': 'Intensité de la trace %', 'Route width': 'Epaisseur de la trace', 'Replay label font size': 'Taille de police', 'Course overprint width': 'Ep. du trait interpostes', 'Control circle size': 'Dim. du poste de contrôle', 'Snap to control when drawing': 'Magnétisme vers le poste lors du dessin', 'Show +3 time loss for GPS routes': 'Afficher +3 fois la perte de temps pour les tracés GPS', 'Show GPS speed colours': 'Afficher les couleurs de vitesse GPS', 'Event statistics': 'Statistiques', 'Drawn routes': 'Routes dessinées', 'GPS routes': 'Routes GPS', 'Comments': 'Commentaires', 'Draw route': 'Dessiner un tracé', 'Select course': 'Sélectionner le parcours', 'Select name': 'Sélectionner le nom', 'Type your comment': 'Votre commentaire', 'Load GPS file (GPX or TCX)': 'Charger un fichier GPS (GPX or TCX)', 'Save': 'Enregistrer', '+3 sec': '+3 sec', 'Undo': 'Annuler', 'Save GPS route': 'Enregistrer un tracé GPS', 'Move track and map together (or right click-drag)': 'Déplacer simultanément le tracé et la carte (ou clic-droit et glisser)', 'Map is georeferenced': 'Carte géo-référencée', 'International event': 'Compétition internationale', 'National event': 'Compétition nationale', 'Regional event': 'Compétition régionale', 'Local event': 'Compétition locale', 'Training event': 'Entraînement', 'Unknown': 'Inconnu', 'Warning': 'Avertissement', 'Your route has been saved': 'Votre tracé a été enregistré', 'Your route was not saved. Please try again': "Votre tracé n'a pas été enregistré - Essayez à nouveau", 'Loading courses': 'Chargement des parcours', 'Loading results': 'Chargement des résultats', 'Loading map': 'Chargement de la carte', 'Loading routes': 'Chargement des tracés', 'Saving courses': 'Enregistrement des parcours', 'Saving results': 'Enregistrement des résultats', 'Saving routes': 'Enregistrement des tracés', 'Map loaded': 'Carte chargée', 'Total time': 'Temps total', 'Left click to add/lock/unlock a handle': "Clic gauche pour ajouter/bloquer/débloquer un point d'ancrage", 'Green - draggable': 'Vert - déplaçable', 'Red - locked': 'Rouge - bloqué', 'Right click to delete a handle': "Clic droit pour enlever un point d'ancrage", 'Drag a handle to adjust track around locked point(s)': 'Faire glisser un poignée pour ajuster la trace autour du(des) point(s) bloqué(s)', 'Autofit': 'Autofit', 'Route already drawn': 'Tracé déjà dessiné', 'If you draw a new route it will overwrite the old route for this runner.': "Si vous dessinez un nouveau tracé pour ce coureur, il remplacera l'original.", 'GPS routes are saved separately and will not be overwritten.': 'Les traces GPS sont enregistrées séparément et ne sont pas remplacées.', 'Search': 'Rechercher' }); <|start_filename|>js/events.js<|end_filename|> (function () { function Events() { this.events = []; this.activeEventID = null; } Events.prototype = { Constructor : Events, deleteAllEvents : function () { this.events.length = 0; this.activeEventID = null; }, addEvent : function (eventObject) { this.events.push(eventObject); }, getEventInfo : function (kartatid) { var realid, info; kartatid = kartatid || this.getKartatEventID(); realid = this.getEventIDForKartatID(kartatid); info = this.events[realid]; info.id = realid; info.controls = rg2.controls.getControlCount(); return info; }, getKartatEventID : function () { return this.events[this.activeEventID].kartatid; }, getActiveMapID : function () { return this.events[this.activeEventID].mapid; }, getMapFileName : function () { return this.events[this.activeEventID].mapfilename; }, setActiveEventID : function (eventid) { if (eventid === null) { this.activeEventID = null; } else { this.activeEventID = parseInt(eventid, 10); } }, getActiveEventID : function () { return this.activeEventID; }, getEventIDForKartatID : function (kartatID) { var i; for (i = 0; i < this.events.length; i += 1) { if (this.events[i].kartatid === kartatID) { return i; } } return undefined; }, getActiveEventDate : function () { if (this.activeEventID !== null) { return this.events[this.activeEventID].date; } return ""; }, getActiveEventName : function () { if (this.activeEventID !== null) { return this.events[this.activeEventID].name; } return "Routegadget 2"; }, getEventEditDropdown : function (dropdown) { var i; dropdown.options.add(rg2.utils.generateOption(null, 'No event selected')); for (i = (this.events.length - 1); i > -1; i -= 1) { dropdown.options.add(rg2.utils.generateOption(this.events[i].kartatid, this.events[i].kartatid + ": " + this.events[i].date + ": " + rg2.he.decode(this.events[i].name))); } return dropdown; }, isScoreEvent : function () { if (this.activeEventID !== null) { return ((this.events[this.activeEventID].format === rg2.config.FORMAT_SCORE_EVENT) || (this.events[this.activeEventID].format === rg2.config.FORMAT_SCORE_EVENT_NO_RESULTS)); } return false; }, hasResults : function () { if (this.activeEventID !== null) { return ((this.events[this.activeEventID].format === rg2.config.FORMAT_NORMAL) || (this.events[this.activeEventID].format === rg2.config.FORMAT_SCORE_EVENT)); } return true; }, mapIsGeoreferenced : function () { if (this.activeEventID === null) { return false; } return this.events[this.activeEventID].worldfile.valid; }, eventIsLocked : function () { if (this.activeEventID === null) { return false; } return this.events[this.activeEventID].locked; }, getLengthUnits : function () { if ((this.activeEventID === null) || (!this.mapIsGeoreferenced())) { return "px"; } return "m"; }, getMetresPerPixel : function () { var lat1, lat2, lon1, lon2, size, pixels, w; if ((this.activeEventID === null) || (!this.mapIsGeoreferenced())) { return undefined; } size = rg2.getMapSize(); pixels = rg2.utils.getDistanceBetweenPoints(0, 0, size.width, size.height); w = this.events[this.activeEventID].worldfile; lon1 = w.C; lat1 = w.F; lon2 = (w.A * size.width) + (w.B * size.height) + w.C; lat2 = (w.D * size.width) + (w.E * size.height) + w.F; return rg2.utils.getLatLonDistance(lat1, lon1, lat2, lon2) / pixels; }, getWorldFile : function () { return this.events[this.activeEventID].worldfile; }, formatEventsAsMenu : function () { var title, html, i; html = ''; for (i = this.events.length - 1; i >= 0; i -= 1) { title = rg2.t(this.events[i].type) + ": " + this.events[i].date; if (this.events[i].worldfile.valid) { title += ": " + rg2.t("Map is georeferenced"); } if (this.events[i].comment !== "") { title += ": " + this.events[i].comment; } html += '<li title="' + title + '" id=event-' + i + "><a href='#" + this.events[i].kartatid + "'>"; if (this.events[i].comment !== "") { html += "<i class='fa fa-info-circle event-info-icon' id='info-" + i + "'></i>"; } if (this.events[i].worldfile.valid) { html += "<i class='fa fa-globe-americas event-info-icon' id='info-" + i + "'>&nbsp</i>"; } if (this.events[i].locked) { html += "<i class='fa fa-lock event-info-icon' id='info-" + i + "'>&nbsp</i>"; } html += this.events[i].date + ": " + this.events[i].name + "</a></li>"; } return html; } }; rg2.Events = Events; }()); <|start_filename|>Gruntfile.js<|end_filename|> /* eslint-env node */ module.exports = function (grunt) { // Project configuration. grunt.initConfig({ pkg: grunt.file.readJSON("package.json"), uglify: { options: { banner: '// Version <%= pkg.version %> <%= grunt.template.today("isoDateTime") %>;\n', sourceMap: true, }, build: { src: jsFileList, dest: jsMinFile, }, manager: { src: jsManagerSrc, dest: jsManagerMinFile, }, }, postcss: { options: { failOnError: true, map: false, processors: [ require('autoprefixer'), require('cssnano')({preset: "default"}) ] }, dist: { src: "css/rg2.css", dest: "css/rg2-<%= pkg.version %>.min.css" } }, sync: { rel: { files: [ { src: ["rg2api.php", "index.php", "app/**", "html/**", "img/favicon.ico", "img/manifest.json"], dest: "rel/", }, ], verbose: true, pretend: false, // Don't do any disk operations - just write log. Default: false failOnError: true, // Fail the task when copying is not possible. Default: false updateAndDelete: true, }, }, bumpup: "package.json", replace: { jsversion: { src: "js/config.js", overwrite: true, replacements: [ { from: /RG2VERSION.*'/, to: "RG2VERSION: '<%= pkg.version %>'", }, ], }, phpversion: { src: ["rg2api.php", "index.php"], overwrite: true, replacements: [ { from: /\('RG2VERSION'.*\)/, to: "('RG2VERSION', '<%= pkg.version %>')", }, ], }, }, clean: { minified: ["js/*.min.js", "js/*.js.map", "css/*.min.css"], }, }); // Load all the grunt tasks require("load-grunt-tasks")(grunt); for (var i = 0; i < clubs.length; i++) { var club = clubs[i]; grunt.config(["sync", club], { files: [ { cwd: "rel/", expand: true, src: "**", dest: "website/" + club + ".routegadget.co.uk/public_html/rg2/", }, ], verbose: true, // Default: false pretend: false, // Don't do any disk operations - just write log. Default: false failOnError: true, // Fail the task when copying is not possible. Default: false ignoreInDest: "rg2-config.php", updateAndDelete: true, }); } // clok has a different directory set-up grunt.config(["sync", "clok"], { files: [ { cwd: "rel/", expand: true, src: "**", dest: "website/clok.routegadget.co.uk/public_html/gadget/rg2/", }, ], verbose: true, // Default: false pretend: false, // Don't do any disk operations - just write log. Default: false failOnError: true, // Fail the task when copying is not possible. Default: false ignoreInDest: "rg2-config.php", updateAndDelete: true, }); grunt.registerTask("default", ["build"]); // increment minor version number: do anything else by editting package.json by hand grunt.registerTask("bump", ["bumpup"]); grunt.registerTask("build", ["clean:minified", "postcss", "uglify", "build-manager"]); grunt.registerTask("build-manager", ["uglify:manager"]); grunt.registerTask("deploy", ["replace:jsversion", "replace:phpversion", "build", "sync:rel"]); }; var jsFileList = [ "js/rg2.js", "js/animation.js", "js/canvas.js", "js/config.js", "js/control.js", "js/controls.js", "js/course.js", "js/courses.js", "js/draw.js", "js/event.js", "js/events.js", "js/gpstrack.js", "js/handles.js", "js/map.js", "js/plugins.js", "js/result.js", "js/results.js", "js/rg2getjson.js", "js/rg2input.js", "js/rg2ui.js", "js/runner.js", "js/stats.js", "js/utils.js", "js/lib/he.js", ]; var jsManagerSrc = [ "js/manager.js", "js/courseparser.js", "js/resultparseriofv2.js", "js/resultparseriofv3.js", "js/resultparsercsv.js", "js/resultparser.js", "js/managerui.js", ]; var jsMinFile = "js/rg2-<%= pkg.version %>.min.js"; var jsManagerMinFile = "js/rg2manager-<%= pkg.version %>.min.js"; // installed routegadget.co.uk clubs that need to be updated for a new release // careful: clok has a different config so is set up separately var clubs = [ "aire", "albania", "ayroc", "bado", "baoc", "basoc", "bko", "boc", "bok", "bl", "chig", "claro", "clyde", "coboc", "cuoc", "cvfr", "darkandwhite", "dee", "devonoc", "ebor", "ecko", "elo", "epoc", "eryri", "esoc", "euoc", "gmoa", "gramp", "go", "halo", "happyherts", "havoc", "hoc", "interlopers", "invoc", "jk", "kerno", "kfo", "kongmmm", "lamm", "leioc", "loc", "log", "lok", "lvo", "maroc", "masterplanadventure", "mdoc", "mid-wales", "moravian", "mvoc", "nato", "ngoc", "noroc", "nwo", "od", "omm", "orox", "ouoc", "oureaevents", "pfo", "potoc", "quantock", "rafo", "roxburghreivers", "run-herts", "sa", "sarum", "saxons", "sboc", "scottish6days", "seloc", "sl_2020", "slow", "slmm", "smbo", "smoc", "sn", "so", "soa", "soc", "solway", "sos", "sportident", "sroc", "stag", "start", "suffoc", "swoc", "syo", "tay", "test", "purple-thistle", "tinto", "tvoc", "walton", "waoc", "wcoc", "wim", "wmoc", "wrekin", "wsco2008", "wsx", ]; <|start_filename|>js/animation.js<|end_filename|> (function () { function Animation() { 'use strict'; this.runners = []; // possible time increment values in milliseconds when timer expires this.deltas = [100, 200, 500, 1000, 2000, 3000, 5000, 7500, 10000, 15000, 20000, 50000, 100000]; // value in milliseconds this.timerInterval = 100; this.resetAnimation(); } Animation.prototype = { Constructor : Animation, resetAnimation : function () { this.units = rg2.events.getLengthUnits(); this.runners.length = 0; clearInterval(this.timer); this.timer = null; // current time of animation this.animationSecs = 0; // animation time in millisecs to avoid rounding problems at very slow speed // animationSecs is always int(milliSecs/1000) this.milliSecs = 0; this.deltaIndex = 3; $("#rg2-animation-speed").empty().text("x " + (this.deltas[this.deltaIndex] / 100)); // if not real time then mass start this.realTime = false; this.earliestStartSecs = 0; this.latestFinishSecs = 0; this.tailLength = 0; this.tailStartTimeSecs = 0; this.useFullTails = false; // control to start from if this option selected this.massStartControl = 0; // run each leg as a mass start if true this.massStartByControl = false; this.displayNames = true; this.displayInitials = false; this.updateAnimationDetails(); $("#btn-start-stop").removeClass('fa-pause').addClass('fa-play').prop('title', rg2.t('Run')); $("#btn-real-time").removeClass().addClass('fa fa-users').prop('title', rg2.t('Real time') + ' > ' + rg2.t('Mass start')); $("#btn-toggle-names").prop('title', rg2.t('Show initials')); }, // @@param courseresults: array of results to be removed // @@param doAnimate: true if add to replay, false if remove from replay animateRunners : function (courseresults, doAnimate) { var i; for (i = 0; i < courseresults.length; i += 1) { if (doAnimate) { this.addRunner(new rg2.Runner(courseresults[i]), false); } else { this.removeRunner(courseresults[i], false); } } this.updateAnimationDetails(); }, addRunner : function (runner, updateDetails) { var i; for (i = 0; i < this.runners.length; i += 1) { if (this.runners[i].runnerid === runner.runnerid) { // runner already exists so ignore return; } } this.runners.push(runner); if (updateDetails) { this.updateAnimationDetails(); } }, updateAnimationDetails : function () { var html; if (this.runners.length > 0) { html = this.getAnimationNames(this.animationSecs); $("#rg2-track-names").empty().append(html).show(); $("#rg2-animation-controls").show(); } else { $("#rg2-track-names").hide(); $("#rg2-animation-controls").hide(); } this.calculateAnimationRange(); $("#rg2-clock").text(rg2.utils.formatSecsAsHHMMSS(this.animationSecs)); }, updateNameDetails : function (time) { var html = this.getAnimationNames(time); if (html !== "") { $("#rg2-track-names").empty().append(html).show(); } else { $("#rg2-track-names").hide(); } }, // slider callback clockSliderMoved : function (time) { this.resetAnimationTime(time); rg2.redraw(false); }, getAnimationNames : function (time) { var i, html, tracks, info, oldCourse; // major refactoring for #400 // get all tracks displayed so we can add them if they are not animated as well tracks = rg2.results.getDisplayedTrackDetails(); for (i = 0; i < this.runners.length; i += 1) { // people can be in both lists: just accept it info = {}; info.colour = this.runners[i].colour; info.course = this.runners[i].coursename; info.name = this.runners[i].name.trim(); if (this.realTime) { info.distance = this.getDistanceAtTime(i, this.animationSecs - this.runners[i].starttime); } else { info.distance = this.getDistanceAtTime(i, time); } tracks.push(info); } if (tracks.length === 0) { return ""; } // need to do this to allow a stable (deterministic) sort // otherwise people with same colour can end up next to each other in name list // still not perfect but better than it was for (i = 0; i < tracks.length; i += 1) { tracks[i].index = i; } tracks.sort(function (a, b) { if (a.course !== b.course) { if (a.course > b.course) { return 1; } return -1; } if (a.index > b.index) { return 1; } if (a.index < b.index) { return -1; } return 0; }); html = "<table>"; oldCourse = ""; for (i = 0; i < tracks.length; i += 1) { if (oldCourse !== tracks[i].course) { html += "<tr><th colspan='3'>" + tracks[i].course + "</th></tr>"; oldCourse = tracks[i].course; } html += "<tr><td style='color:" + tracks[i].colour + ";'><i class='fa fa-circle'></i></td><td class='align-left'>" + tracks[i].name + "</td>"; // eslint-disable-next-line no-prototype-builtins if (tracks[i].hasOwnProperty('distance')) { html += "<td class='align-right'>" + tracks[i].distance + this.units; } else { html += "<td>"; } html += "</td></tr>"; } html += "</table>"; return html; }, getDistanceAtTime : function (idx, time) { var dist, cumDist; cumDist = this.runners[idx].cumulativeDistance; dist = (time > (cumDist.length - 1)) ? cumDist[cumDist.length - 1] : cumDist[time]; if (dist === undefined) { dist = 0; } return dist; }, getMaxControls : function () { var maxControls, i; maxControls = 0; // find maximum number of controls to set size of table for (i = 0; i < this.runners.length; i += 1) { maxControls = Math.max(maxControls, this.runners[i].splits.length); } // allow for start and finish return (maxControls - 2); }, getSplitsTableHeader: function (controls) { var html, i; html = "<table class='splitstable'><tr><th>" + rg2.t("Course") + "</th><th>" + rg2.t("Name") + "</th>"; for (i = 1; i <= controls; i += 1) { html += "<th>" + i + "</th>"; } return (html + "<th>F</th></tr>"); }, getSplitsTable : function () { var html, i, j, run, maxControls, legSplit, prevControlSecs; if (this.runners.length < 1) { return "<p>" + rg2.t("Select runners on Results tab") + ".</p>"; } legSplit = []; prevControlSecs = 0; maxControls = this.getMaxControls(); html = this.getSplitsTableHeader(maxControls); for (i = 0; i < this.runners.length; i += 1) { run = this.runners[i]; prevControlSecs = 0; html += "<tr class='splitsname-row'><td>" + run.coursename + "</td><td>" + run.name + "</td>"; for (j = 1; j < run.splits.length; j += 1) { html += "<td>" + rg2.utils.formatSecsAsMMSS(run.splits[j]) + "</td>"; legSplit[j] = run.splits[j] - prevControlSecs; prevControlSecs = run.splits[j]; } html += "</tr><tr class='splitstime-row'><td></td><td></td>"; for (j = 1; j < run.splits.length; j += 1) { html += "<td>" + rg2.utils.formatSecsAsMMSS(legSplit[j]) + "</td>"; } if (isNaN(run.cumulativeTrackDistance[run.cumulativeTrackDistance.length - 1])) { html += "</tr><tr class='splitsdistance-row'><td></td><td>--</td>"; } else { html += "</tr><tr class='splitsdistance-row'><td></td><td>" + run.cumulativeTrackDistance[run.cumulativeTrackDistance.length - 1] + " " + this.units + "</td>"; } for (j = 1; j < run.splits.length; j += 1) { if (isNaN(run.legTrackDistance[j])) { // handle various problems with missing splits html += "<td>--</td>"; } else { html += "<td>" + run.legTrackDistance[j] + "</td>"; } } } html += "</tr></table>"; return html; }, removeRunner : function (runnerid, updateDetails) { var i; for (i = 0; i < this.runners.length; i += 1) { if (this.runners[i].runnerid === runnerid) { // delete 1 runner at position i this.runners.splice(i, 1); } } if (updateDetails) { this.updateAnimationDetails(); } }, toggleAnimation : function () { if (this.timer === null) { this.startAnimation(); $("#btn-start-stop").removeClass("fa-play").addClass("fa-pause").prop("title", rg2.t("Pause")); } else { this.stopAnimation(); $("#btn-start-stop").removeClass("fa-pause").addClass("fa-play").prop("title", rg2.t("Run")); } }, startAnimation : function () { if (this.timer === null) { this.timer = setInterval(this.timerExpired.bind(this), this.timerInterval); } }, calculateAnimationRange : function () { // in theory start time will be less than 24:00 // TODO: races over midnight: a few other things to sort out before we get to that var i; this.earliestStartSecs = 86400; this.latestFinishSecs = 0; this.slowestTimeSecs = 0; for (i = 0; i < this.runners.length; i += 1) { if (this.runners[i].starttime < this.earliestStartSecs) { this.earliestStartSecs = this.runners[i].starttime; } if ((this.runners[i].starttime + this.runners[i].x.length) > this.latestFinishSecs) { this.latestFinishSecs = this.runners[i].starttime + this.runners[i].x.length; } if ((this.runners[i].x.length) > this.slowestTimeSecs) { this.slowestTimeSecs = this.runners[i].x.length; } } this.resetAnimationTime(0); }, stopAnimation : function () { clearInterval(this.timer); this.timer = null; }, // extra function level in for test purposes timerExpired : function () { // a bit convoluted, but time expiry calls redraw, and redraw then calls runAnimation rg2.redraw(true); }, setFullTails : function (fullTails) { if (fullTails) { this.useFullTails = true; } else { this.useFullTails = false; } rg2.redraw(false); }, setTailLength : function (minutes) { this.tailLength = 60 * minutes; rg2.redraw(false); }, setStartControl : function (control) { var i; this.massStartControl = parseInt(control, 10); if (this.massStartControl === rg2.config.MASS_START_BY_CONTROL) { this.massStartControl = 0; this.massStartByControl = true; // get split time at control 1 for (i = 0; i < this.runners.length; i += 1) { this.runners[i].nextStopTime = this.runners[i].splits[1]; } } else { this.massStartByControl = false; for (i = 0; i < this.runners.length; i += 1) { this.runners[i].nextStopTime = rg2.config.VERY_HIGH_TIME_IN_SECS; } } this.resetAnimationTime(0); }, setReplayType : function () { // toggles between mass start and real time if (this.realTime) { this.realTime = false; $("#btn-real-time").removeClass().addClass('fa fa-users').prop('title', rg2.t('Mass start') + ' > ' + rg2.t('Real time')); if (rg2.courses.getHighestControlNumber() > 0) { $("#rg2-control-select").prop('disabled', false); } } else { this.realTime = true; $("#btn-real-time").removeClass().addClass('fa fa-clock').prop('title', rg2.t('Real time') + ' > ' + rg2.t('Mass start')); $("#rg2-control-select").prop('disabled', true); } // go back to start this.resetAnimationTime(0); }, resetAnimationTime : function (time) { // sets animation time if (this.realTime) { // if we got a time it was from the slider so use it // otherwise reset to base time if (time > 0) { this.animationSecs = time; } else { this.animationSecs = this.earliestStartSecs; } this.startSecs = this.earliestStartSecs; $("#rg2-clock-slider").slider("option", "max", this.latestFinishSecs); $("#rg2-clock-slider").slider("option", "min", this.earliestStartSecs); } else { if (time > 0) { this.animationSecs = time; } else { this.animationSecs = 0; } this.startSecs = 0; $("#rg2-clock-slider").slider("option", "max", this.slowestTimeSecs); $("#rg2-clock-slider").slider("option", "min", 0); } this.milliSecs = this.animationSecs * 1000; $("#rg2-clock-slider").slider("value", this.animationSecs); $("#rg2-clock").text(rg2.utils.formatSecsAsHHMMSS(this.animationSecs)); }, toggleNameDisplay : function () { var title = ""; if (this.displayNames) { if (this.displayInitials) { this.displayNames = false; this.displayInitials = false; title = "Show names"; } else { this.displayInitials = true; title = "Hide names"; } } else { this.displayNames = true; title = "Show initials"; } $("#btn-toggle-names").prop("title", rg2.t(title)); }, displayName : function (runner, time) { var text; if (this.displayNames) { // make sure we have a valid position to display if ((time < runner.x.length) && (time >= 0)) { rg2.ctx.fillStyle = "black"; rg2.ctx.font = rg2.options.replayFontSize + 'pt Arial'; rg2.ctx.globalAlpha = rg2.config.FULL_INTENSITY; rg2.ctx.textAlign = "left"; if (this.displayInitials) { text = runner.initials; } else { text = runner.name; } rg2.ctx.save(); // centre map on runner location rg2.ctx.translate(runner.x[time], runner.y[time]); // rotate map so that text stays horizontal rg2.ctx.rotate(rg2.ctx.displayAngle); // no real science: offsets just look OK rg2.ctx.fillText(text, 12, 6); rg2.ctx.restore(); } } }, incrementAnimationTime : function () { // only increment time if we haven't got to the end already if (this.realTime) { if (this.animationSecs < this.latestFinishSecs) { this.milliSecs += this.deltas[this.deltaIndex]; } } else { if (this.animationSecs < this.slowestTimeSecs) { this.milliSecs += this.deltas[this.deltaIndex]; } } this.animationSecs = parseInt((this.milliSecs / 1000), 10); // find earliest time we need to worry about when drawing screen if (this.useFullTails) { this.tailStartTimeSecs = this.startSecs + 1; } else { this.tailStartTimeSecs = Math.max(this.animationSecs - this.tailLength, this.startSecs + 1); } }, drawAnimation : function () { // This function draws the current state of the animation. var runner, timeOffset, i, t; $("#rg2-clock-slider").slider("value", this.animationSecs); $("#rg2-clock").text(rg2.utils.formatSecsAsHHMMSS(this.animationSecs)); rg2.ctx.lineWidth = rg2.options.routeWidth; rg2.ctx.globalAlpha = rg2.config.FULL_INTENSITY; for (i = 0; i < this.runners.length; i += 1) { runner = this.runners[i]; if (this.realTime) { timeOffset = runner.starttime; } else { if ((this.massStartControl === 0) || (runner.splits.length < this.massStartControl)) { // no offset since we are starting from the start timeOffset = 0; } else { // offset needs to move forward (hence negative) to time at control timeOffset = -1 * runner.splits[this.massStartControl]; } } rg2.ctx.strokeStyle = runner.colour; rg2.ctx.globalAlpha = rg2.options.routeIntensity; rg2.ctx.beginPath(); rg2.ctx.moveTo(runner.x[this.tailStartTimeSecs - timeOffset], runner.y[this.tailStartTimeSecs - timeOffset]); // t runs as real time seconds or 0-based seconds depending on this.realTime //runner.x[] is always indexed in 0-based time so needs to be adjusted for starttime offset for (t = this.tailStartTimeSecs; t < this.animationSecs; t += 1) { if ((t > timeOffset) && ((t - timeOffset) < runner.nextStopTime)) { rg2.ctx.lineTo(runner.x[t - timeOffset], runner.y[t - timeOffset]); } } rg2.ctx.stroke(); rg2.ctx.beginPath(); if ((t - timeOffset) < runner.nextStopTime) { t = t - timeOffset; } else { t = runner.nextStopTime; } rg2.ctx.arc(runner.x[t], runner.y[t], rg2.config.RUNNER_DOT_RADIUS, 0, 2 * Math.PI, false); rg2.ctx.globalAlpha = rg2.config.FULL_INTENSITY; rg2.ctx.strokeStyle = rg2.config.BLACK; rg2.ctx.stroke(); rg2.ctx.fillStyle = runner.colour; rg2.ctx.fill(); this.displayName(runner, t); } this.updateNameDetails(t); if (this.massStartByControl) { this.checkForStopControl(this.animationSecs); } }, // see if all runners have reached stop control and reset if they have checkForStopControl : function (currentTime) { var i, legTime, allAtControl; allAtControl = true; // work out if everybody has got to the next control for (i = 0; i < this.runners.length; i += 1) { legTime = this.runners[i].splits[this.massStartControl + 1] - this.runners[i].splits[this.massStartControl]; if (legTime > currentTime) { allAtControl = false; break; } } if (allAtControl) { //move on to next control this.massStartControl += 1; // find time at next control for (i = 0; i < this.runners.length; i += 1) { if (this.massStartControl < (this.runners[i].splits.length)) { // splits includes a start time so index to control is + 1 this.runners[i].nextStopTime = this.runners[i].splits[this.massStartControl + 1]; } else { this.runners[i].nextStopTime = rg2.config.VERY_HIGH_TIME_IN_SECS; } } this.resetAnimationTime(0); } }, goSlower : function () { if (this.deltaIndex > 0) { this.deltaIndex -= 1; } $("#rg2-animation-speed").empty().text("x " + (this.deltas[this.deltaIndex] / 100)); }, goFaster : function () { if (this.deltaIndex < (this.deltas.length - 1)) { this.deltaIndex += 1; } $("#rg2-animation-speed").empty().text("x " + (this.deltas[this.deltaIndex] / 100)); } }; rg2.Animation = Animation; }()); <|start_filename|>css/rg2.css<|end_filename|> /* Routegadget RG2 Custom CSS */ html, body { width: 100%; height: 100%; margin: 0; border: 0; display: block; font: 16px/26px -apple-system,Roboto,"Segoe UI","Helvetica Neue",Arial,sans-serif; } .ui-widget { font: 16px/26px -apple-system,Roboto,"Segoe UI","Helvetica Neue",Arial,sans-serif; } #rg2-header-container { background: #002bd9; color: white; position: relative; height: 30px; border-bottom: 4px solid black; font-size: 20px; line-height: 30px; } .rg2-result-search { width: 97%; margin: 3px; } .rg2-event-search { width: 97%; margin: 3px; font-size: 1em; } .input-group { margin-top: 5px; } .form-control { width: 90%; } #rg2-course-select, #rg2-name-select { min-width: 200px; max-width: 200px; } #rg2-manager-event-select { width: 100%; } #rg2-new-comments { margin-top:10px; margin-bottom: 10px; width: 100%; height: 50px; } #rg2-animation-controls { display: flex; flex-flow: column wrap; width: 350px; position: absolute; right: 0; bottom: 0; } .rg2-ani-row { background: silver; color: white; vertical-align: middle; height: 36px; z-index: 100; line-height: 36px; } .row-1 { border: 4px solid darkgray; font-size: 20px; } .row-2 { border-left: 4px solid darkgray; border-right: 4px solid darkgray; } .row-3 { border: 4px solid darkgray; color: black; } #rg2-resize-info { position: absolute; vertical-align: middle; padding-right: 10px; } #rg2-header { position: absolute; vertical-align: middle; left: 35px; } .rg2-button { background: silver; color: white; float: right; width: 30px; text-align: center; border-right: 4px solid darkgray; } .rg2-button-left { background: silver; color: white; float: left; width: 30px; text-align: center; border-right: 4px solid darkgray; } .rg2-button-right { background: silver; color: white; float: right; width: 30px; text-align: center; border-left: 4px solid darkgray; } .rg2-wide-button { background: silver; color: white; float: left; width: 55px; text-align: center; border-right: 4px solid darkgray; } .rg2-button:hover { color: darkgray; } .rg2-button-left:hover{ color: darkgray; } #btn-edit-delete-event, #btn-add-event { margin:0 auto; display:block; } #rg2-about { position: absolute; right: 0; padding-right: 20px; } #rg2-about-dialog { font-size: 0.75em; display: none; } #rg2-about-dialog hr { height: 10px; border: 0; box-shadow: 0 10px 10px -10px #8c8b8b inset; } #rg2-about-dialog table { width: 100%; } #rg2-about-dialog thead tr { background: #002bd9; color: #fff } #rg2-about-dialog thead th { text-align: left; } #rg2-about-dialog tbody td:nth-child(odd) { background: #ddd; } #rg2-about-dialog tbody td:nth-child(even) { background: #eee; } #rg2-about-dialog tbody td:first-child { width: 15%; } #rg2-about-dialog tbody td { text-align: left; } .splitstable { font-size: 0.75em; } .splitstable th { font-weight: bold; background-color: white; } .splitsname-row { background-color: #C0C0C0; } .splitstime-row { background-color: #E0E0E0; } .splitsdistance-row { background-color: white; } .showcourse { float: right; } .allitemsrow { font-weight: bold; } .rg2-hr { margin-top: 10px; margin-bottom: 10px; } #rg2-clock { font-weight: bold; font-size: 26px; color: black; text-align: center; float:left; margin-left: 20px; } #rg2-tails-type { padding: 0 5px; border-right: 4px solid darkgray; float:left; } #spn-tail-length { width: 30px; } #rg2-tails-spinner { float: left; padding: 0 5px; border-right: 4px solid darkgray; } .rg2-spinner { width: 40px; } .rg2-run-green { color: green; } .rg2-run-red { color: red; } .options { float: right; padding-right: 5px; margin-top: 5px; clear:both; } #rg2-container { height: 100%; width: 100%; position: relative; background: white; overflow: hidden; display: none; } #rg2-info-panel { font-size: 0.75em; width: 360px; position: absolute; z-index: 100; height: 99%; } #rg2-info-panel-tab-headers { overflow: hidden; position: relative; } #rg2-info-panel-tab-headers .ui-tabs-nav a { padding: .5em; } #rg2-info-panel-tab-body { overflow: auto; /* add scroll bars if needed */ height: 95.5% } #rg2-event-list .ui-menu-item { list-style-image: none; } #rg2-event-list .ui-menu-item a { text-decoration: none; } #rg2-event-list li:nth-child(odd) { background: #eee; } .rg2-active-event { border: 2px solid black; } #rg2-hide-info-panel-control { position:absolute; left: 366px; top: 4px; z-index: 100; color: black; width: 20px; text-align: center; border: 1px solid #AAA; background: #E0E0E0; } #rg2-map-canvas { position: absolute; z-index: 50; } .rg2-progress-display { border: 1px solid darkgray; background: rgb(204 204 204); background: rgb(204 204 204 / 100%); padding : 2px; font:1.0em/1.0em Arial, sans-serif; text-align:center; height: auto; width: 200px; z-index: 90; position: absolute; } #rg2-map-load-progress { top: 100px; left: 400px; } #rg2-load-progress { top: 200px; left: 400px; } .rg2-gps-text { line-height: 1.75em; } .rg2-gps-text ul { list-style-position: inside; margin: 0 0 0 15px; padding: 0; } .track-names { border: 1px solid darkgray; background: rgb(204 204 204); background: rgb(204 204 204 / 75%); padding : 2px; position: absolute; font:0.75em Arial, sans-serif; top: 0; right: 0; height: auto; width: auto; z-index: 90; max-height: 500px; overflow: auto; margin-top:5px; margin-right: 5px; } .align-right { text-align: right; } .align-left { text-align: left; } .align-center { text-align: center; } .track-names th { background: rgb(150 150 150); background: rgb(150 150 150 / 75%); text-align: left; } #rg2-replay-start-control { float: right; margin-right:5px } #rg2-control-select { width: 80px; } .pushright { float: right; } .singlerow { display: table; margin: auto; width: 99%; padding: 0.5em; text-align: center; } .singlerowitem { display: table-cell; } #rg2-manage-edit .ui-button { margin-top: 10px; margin-bottom: 10px; } /* mass start/real time icon colour */ .active { color: green; } /* light green background */ .valid { background-color: #9fc; border-radius: 3px; } .coursemenutable tbody tr:nth-child(odd) { background-color: #eee; } .coursemenutable tr, .coursemenutable td, .coursemenutable th { padding-left: 5px; padding-right: 5px; text-align: center; } p.showcourse { padding-left: 5px; } /* apply style to first td or th element in table / which is Name in this case */ table.resulttable td, table.resulttable th { padding-left: 5px; padding-right: 5px; text-align: center; } table.resulttable td + td, table.resulttable th + th { width: 80%; text-align: left; } table.resulttable td + td + td, table.resulttable th + th + th { text-align: center; } table.resulttable tbody tr:nth-child(odd) { background: #eee; } #rg2-result-list .ui-accordion, #rg2-result-list .ui-accordion-content { padding: 0; } #rg2-select-gps-file .ui-button { width: 300px; margin-bottom: 10px; } #rg2-button-bar .ui-button-text-icon-primary, #rg2-button-bar .ui-button-text-icons, #rg2-button-bar .ui-button-text { font-size: 0.75em; padding: .2em .2em .2em 1em; } #rg2-clock-slider { margin: 10px 15px; width: 175px; float:right; } #rg2-clock-slider .ui-state-default { background: silver; border: 4px solid darkgray; } #rg2-clock-slider .ui-state-focus { outline: none; } #rg2-clock-slider .ui-state-hover { background: darkgray; } #rg2-clock-slider .ui-slider-handle { width: 15px; height: 20px; } #rg2-tails-spinner .ui-widget-content { border: 2px solid darkgray; } #rg2-tails-spinner .ui-spinner { display: inline; } #rg2-tails-spinner .ui-state-default { background: silver; color: darkgray; } #rg2-tails-spinner .ui-state-active { color: silver; } #rg2-tails-spinner .ui-spinner input { font: 16px Helvetica, "Helvetica Neue", Arial, sans-serif; margin-bottom: 9px } #rg2-event-comments { margin-top: 10px; margin-bottom: 10px; width: 95%; height: 50px; } #rg2-add-new-event .ui-button { margin-top: 10px; margin-bottom: 10px; } #rg2-new-event-details input { margin-top: 5px; margin-bottom: 5px; } /* spinner icons */ #rg2-tails-spinner .ui-icon, #rg2-tails-spinner .ui-widget-content .ui-icon { background-image: url("../img/ui-icons_222222_256x240.png"); } #rg2-tails-spinner .ui-widget-header .ui-icon { background-image: url("../img/ui-icons_222222_256x240.png"); } #rg2-tails-spinner .ui-state-default .ui-icon { background-image: url("../img/ui-icons_888888_256x240.png"); } #rg2-tails-spinner .ui-state-hover .ui-icon, #rg2-tails-spinner .ui-state-focus .ui-icon { background-image: url("../img/ui-icons_454545_256x240.png"); } #rg2-tails-spinner .ui-state-active .ui-icon { background-image: url("../img/ui-icons_454545_256x240.png"); } #rg2-tails-spinner .ui-state-highlight .ui-icon { background-image: url("../img/ui-icons_2e83ff_256x240.png"); } #rg2-tails-spinner .ui-state-error .ui-icon, .ui-state-error-text .ui-icon { background-image: url("../img/ui-icons_cd0a0a_256x240.png"); } /* allow close button on dialog to be hidden * see http://api.jqueryui.com/dialog */ .no-close .ui-dialog-titlebar-close { display: none; } /* * prevent selection of objects everywhere */ body { -ms-user-select: none; -webkit-user-select: none; -khtml-user-select: none; -moz-user-select: none; -webkit-touch-callout: none; -webkit-user-drag: none; user-select: none; } .selectable { -ms-user-select: all; -webkit-user-select: all; -khtml-user-select: all; -moz-user-select: all; -webkit-touch-callout: all; -webkit-user-drag: all; user-select: all; } .manage-input { margin-top: 3px; margin-right: 3px; width: 200px; } .manage-label { margin-left: 3px; } #rg2-draw label { margin-left: 3px; } .no-top-margin { margin-top: 0; margin-bottom: 2px; } #rg2-manage-create { padding-right: 5px; } #rg2-manage-create > div::after { display: block; content: ""; clear: both; } #rg2-manage-create div, #rg2-manage-map div, #rg2-manage-edit div { margin-top: 5px; } .manage-file-input { margin-top: 4px; margin-bottom: 4px; width: 200px; } .manage-file-input-div { height: 41px; } .manage-file-label { margin-top: 9px; margin-bottom: 9px; } .manage-event-edit-div { height: 30px; } .manage-event-edit-div label, .manage-event-edit-div input { display: inline-block; } .manage-event-edit-div label { width: 80px; } #manage-edit-options input { width: 220px; } #manage-edit-options .ui-accordion-content { padding: 1em 0.5em; } #rg2-option-controls input[type="checkbox"] { margin-left: 10px; margin-top: 10px; } #rg2-draw .ui-button { margin-left: 5px; margin-top: 5px; } #rg2-edit-event-comments { width: 95%; height: 50px; } #rg2-event-selected { width: 95%; } #rg2-world-file-map { height: 180px; } .rg2-first { color: darkblue; font-weight: bold; } .rg2-second { color: red; font-weight: bold; } .rg2-third { color: green; font-weight: bold; } .rg2-results-table-container { height: 100%; } #rg2-results-grid-wrapper { height: 200px; } <|start_filename|>lang/fi.js<|end_filename|> rg2.setDictionary({ // Suomeksi code: 'fi', language: 'Suomi', translation: '<EMAIL>', 'Events': 'Tapahtumat', 'Course': 'Rata', 'Courses': 'Radat', 'Controls': 'Rastit', 'Results': 'Tulokset', 'Draw': 'Piirrä', 'Show': 'Näytä', 'Runners': 'Osallistujat', 'Routes': 'Reitit', 'Route': 'Reitti', 'Name': 'Nimi', 'Time': 'Aika', 'Replay': 'Toista', 'All': 'Kaikki', 'Help': 'Ohje', 'Options': 'Asetukset', 'Reset': 'Tyhjennä', 'Zoom out': 'Loitonna', 'Zoom in': 'Lähennä', 'Rotate right': 'Käännä oikealle', 'Rotate left': 'Käännä vasemmalle', 'Splits': 'Väliajat', 'Splits table': 'Väliaikataulukko', 'Select runners on Results tab': 'Valitse osallistuja tuloslistalta', 'Log in': 'Kirjaudu', 'User name': 'Käyttäjätunnus', 'Password': '<PASSWORD>', 'Show controls': 'Näytä rastit', 'Hide controls': 'Piilota rastit', 'Show initials': 'Näytä nimikirjaimet', 'Show names': 'Näytä nimet', 'Hide names': 'Piilota nimet', 'Show info panel': 'Näytä tiedot', 'Hide info panel': 'Piilota tiedot', 'Select an event': 'Valitse tapahtuma', 'Slower': 'Hitaammin', 'Run': 'Toista', 'Pause': 'Pysäytä', 'Faster': 'Nopeammin', 'Real time': 'Reaaliaika', 'Mass start': 'Yhteislähtö', 'Start at': 'Aloita kohdasta', 'Length': 'Pituus', 'Full tails': 'Koko reitti', 'No results available': 'Tuloksia ei ole saatavilla', 'Configuration options': 'Asetukset', 'Language': 'Kieli', 'Map intensity %': 'Kartan näkyvyys %', 'Route intensity %': 'Reitin näkyvyys %', 'Route width': 'Reitin leveys', 'Replay label font size': 'Nimien fonttikoko', 'Course overprint width': 'Reittipiirroksen leveys', 'Control circle size': 'Rastiympyrän koko', 'Snap to control when drawing': 'Valitse rastipiste automaattisesti', 'Show +3 time loss for GPS routes': 'Näytä +3 aikamerkinnät GPS reiteillä', 'Show GPS speed colours': 'Näytä GPS nopeus väreinä', 'Event statistics': 'Tapahtuman tilastot', 'Drawn routes': 'Piiretyt reitit', 'GPS routes': 'GPS reitit', 'Comments': 'Kommentit', 'Draw route': 'Piirrä reitti', 'Select course': 'Valitse rata', 'Select name': 'Valitse nimi', 'Type your comment': 'Kirjoita kommentti', 'Load GPS file (GPX or TCX)': 'Lataa GPS-tiedosto (GPX tai TCX)', 'Save': 'Tallenna', '+3 sec': '+3 s', 'Undo': 'Kumoa', 'Save GPS route': 'Tallenna GPS reitti', 'Align map to next control': 'Kohdista kartta seuraavaan rastipisteeseen', 'Move track and map together (or right click-drag)': 'Siirrä reittiä ja rataa yhdessä (tai raahaa oikealla napilla)', 'Map is georeferenced': 'Kartta on paikkatarkka', 'International event': 'Kansainvälinen kilpailu', 'National event': 'Kansallinen kilpailu', 'Regional event': 'Alueellinen kilpailu', 'Local event': 'Paikallinen tapahtuma', 'Training event': 'Harjoitus', 'Unknown': 'Tuntematon', 'Warning': 'Varoitus', 'Your route has been saved': 'Reittisi on tallennettu', 'Your route was not saved. Please try again': 'Reittiä ei tallennettu. Yritä uudelleen.', 'Loading courses': 'Ladataan ratoja', 'Loading results': 'Ladataan tuloksia', 'Loading map': 'Ladataan karttoja', 'Loading routes': 'Ladataan reittejä', 'Saving courses': 'Tallennetaan ratoja', 'Saving results': 'Tallennetaan tuloksia', 'Saving routes': 'Tallennetaan reittejä', 'Map loaded': 'Kartat on ladattu', 'Total time': 'Kokonaisaika', 'Left click to add/lock/unlock a handle': 'Vasen painike lisää/lukitse/avaa piste', 'Green - draggable': 'Vihreä - siirrettävä', 'Red - locked': 'Punainen - lukittu', 'Right click to delete a handle': 'Poista piste hiiren oikealla', 'Drag a handle to adjust track around locked point(s)': 'Kohdista reitti siirtämällä lukitsemattomia pisteitä', 'Autofit': 'Sovita automaattisesti', 'Route already drawn': 'Reitti on jo piirretty', 'If you draw a new route it will overwrite the old route for this runner.': 'Jos piirrät uuden reitin poistetaan kilpailijan vanha reitti.', 'GPS routes are saved separately and will not be overwritten.': 'GPS reitit tallennetaan erikseen eikä niitä ylikirjoiteta.', 'Route deleted': 'Reitti poistettu', 'Route has been deleted': 'Reitti on poistettu', 'Delete failed': 'Poisto epäonnistui', 'Search': 'Hae', 'Share route': 'Jaa reitti', 'Copy and paste this link to share your route': 'Kopio tämä linkki jakaaksesi reittisi' }); <|start_filename|>js/map.js<|end_filename|> (function () { function Georef(description, name, params) { this.description = description; this.name = name; this.params = params; } function Georefs() { var i, codes, params; this.georefsystems = []; this.georefsystems.push(new Georef("Not georeferenced", "none", "")); this.georefsystems.push(new Georef("GB National Grid", "EPSG:27700", "+proj=tmerc +lat_0=49 +lon_0=-2 +k=0.9996012717 +x_0=400000 +y_0=-100000 +ellps=airy +datum=OSGB36 +units=m +no_defs")); this.georefsystems.push(new Georef("Google EPSG:900913", "EPSG:900913", "+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +no_defs")); if (rg2Config.epsg_code !== undefined) { // if more than one user-defined then they come in as |-separated strings codes = rg2Config.epsg_code.split("|"); params = rg2Config.epsg_params.split("|"); for (i = 0; i <codes.length; i = i + 1) { this.georefsystems.push(new Georef(codes[i].replace(" ", ""), codes[i].replace(" ", ""), params[i])); } this.defaultGeorefVal = codes[0].replace(" ", ""); } else { // default to GB National Grid this.defaultGeorefVal = "EPSG:27700"; } } Georefs.prototype = { Constructor : Georefs, getDefault : function () { return this.defaultGeorefVal; }, getDropdown : function (dropdown) { var i; for (i = 0; i < this.georefsystems.length; i += 1) { dropdown.options.add(rg2.utils.generateOption(this.georefsystems[i].name, this.georefsystems[i].description)); } return dropdown; }, getParams : function (name) { var i, params; params = ""; for (i = 0; i < this.georefsystems.length; i += 1) { if (this.georefsystems[i].name === name) { return this.georefsystems[i].params; } } return params; } }; function Worldfile(wf) { // see http://en.wikipedia.org/wiki/World_file if (wf.A === undefined) { this.valid = false; this.A = 0; this.B = 0; this.C = 0; this.D = 0; this.E = 0; this.F = 0; } else { this.A = parseFloat(wf.A); this.B = parseFloat(wf.B); this.C = parseFloat(wf.C); this.D = parseFloat(wf.D); this.E = parseFloat(wf.E); this.F = parseFloat(wf.F); this.valid = true; // helps make later calculations easier this.AEDB = (wf.A * wf.E) - (wf.D * wf.B); this.xCorrection = (wf.B * wf.F) - (wf.E * wf.C); this.yCorrection = (wf.D * wf.C) - (wf.A * wf.F); } } Worldfile.prototype = { Constructor : Worldfile, // use worldfile to generate X value getX : function (lng, lat) { return Math.round(((this.E * lng) - (this.B * lat) + this.xCorrection) / this.AEDB); }, // use worldfile to generate y value getY : function (lng, lat) { return Math.round(((-1 * this.D * lng) + (this.A * lat) + this.yCorrection) / this.AEDB); }, // use worldfile to generate longitude getLon : function (x, y) { return (this.A * x) + (this.B * y) + this.C; }, // use worldfile to generate latitude getLat : function (x, y) { return (this.D * x) + (this.E * y) + this.F; } }; function Map(data) { if (data !== undefined) { // existing map from database this.mapid = data.mapid; this.name = data.name; // worldfile for GPS to map image conversion (for GPS files) this.worldfile = new Worldfile(data); // worldfile for local co-ords to map image conversion (for georeferenced courses) this.localworldfile = new Worldfile({A: data.localA, B: data.localB, C: data.localC, D: data.localD, E: data.localE, F: data.localF}); if (data.mapfilename === undefined) { this.mapfilename = this.mapid + '.' + 'jpg'; } else { this.mapfilename = data.mapfilename; } } else { // new map to be added this.mapid = 0; this.name = ""; this.worldfile = new Worldfile(0); this.localworldfile = new Worldfile(0); } this.xpx = []; this.ypx = []; this.lat = []; this.lon = []; } rg2.Georefs = Georefs; rg2.Worldfile = Worldfile; rg2.Map = Map; }()); <|start_filename|>.stylelintrc.js<|end_filename|> /** @type {import('stylelint').Config} */ module.exports = { extends: ["stylelint-config-standard", "stylelint-config-prettier"], ignoreFiles: ["**/*.min.css"], rules: { "property-no-vendor-prefix": null, "no-descending-specificity": null, } }; <|start_filename|>js/canvas.js<|end_filename|> (function () { var canvas, ctx, map; canvas = $("#rg2-map-canvas")[0]; ctx = canvas.getContext('2d'); map = new Image(); ctx.displayAngle = 0; function loadNewMap(mapFile) { $("#rg2-map-load-progress-label").text(rg2.t("Loading map")); $("#rg2-map-load-progress").show(); map.src = mapFile; } function drawSelectEventText() { if (!rg2.config.managing) { ctx.font = '30pt Arial'; ctx.textAlign = 'center'; ctx.fillStyle = rg2.config.BLACK; ctx.fillText(rg2.t("Select an event"), rg2.canvas.width / 2, rg2.canvas.height / 2); } } /* called whenever anything changes enough to need screen redraw * @param fromTimer {Boolean} true if called from timer: used to determine if animation time should be incremented */ function redraw(fromTimer) { // Clear the entire canvas // first save current transformed state ctx.save(); // reset everything back to initial size/state/orientation ctx.setTransform(1, 0, 0, 1, 0, 0); // fill canvas to erase things: clearRect doesn't work on Android (?) and leaves the old map as background when changing ctx.globalAlpha = rg2.config.FULL_INTENSITY; ctx.fillStyle = rg2.config.GREY; ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height); // go back to where we started ctx.restore(); if (map.height > 0) { // set map background white so that dimmed maps do not have grey showing through ctx.fillStyle = rg2.config.WHITE; // this might have been reset by the ctx.restore() ctx.globalAlpha = rg2.config.FULL_INTENSITY; ctx.fillRect(0, 0, map.width, map.height); // set transparency of map ctx.globalAlpha = rg2.options.mapIntensity; // using non-zero map height to show we have a map loaded ctx.drawImage(map, 0, 0); var active = $("#rg2-info-panel").tabs("option", "active"); if (active === rg2.config.TAB_DRAW) { rg2.courses.drawCourses(rg2.config.DIM); rg2.controls.drawControls(false); rg2.results.drawTracks(); rg2.drawing.drawNewTrack(); } else { if (active === rg2.config.TAB_CREATE) { rg2.manager.drawControls(); } else { rg2.courses.drawCourses(rg2.config.DIM); rg2.results.drawTracks(); rg2.controls.drawControls(false); if (fromTimer) { rg2.animation.incrementAnimationTime(); } rg2.animation.drawAnimation(); } } } else { drawSelectEventText(); } } function applyMapRotation(angle, x, y, moveMap) { var pt; // save new absolute angle ctx.displayAngle = (ctx.displayAngle - angle) % (Math.PI * 2); // rotate around given co-ordinates ctx.translate(x, y); ctx.rotate(angle); if (moveMap) { // move map so that given point is centre-bottom of screen pt = ctx.transformedPoint((canvas.width / 2), (canvas.height * 0.9)); ctx.translate(pt.x - x, pt.y - y); } else { // put map back where it started ctx.translate(-1 * x, -1 * y); } ctx.save(); redraw(false); } function rotateMap(direction) { // rotate a little bit from UI control input // direction is -1 for left and 1 for right var angle; angle = direction * (Math.PI / 36); // rotate around centre of map applyMapRotation(angle, (map.width / 2), (map.height / 2), false); } function alignMap(angle, x, y) { // align to an absolute angle: 0 is up/north // rotate around defined x, y applyMapRotation((ctx.displayAngle - angle) % (Math.PI * 2), x, y, true); } function resetMapState() { // place map in centre of canvas and scale it down to fit var mapscale, heightscale; heightscale = canvas.height / map.height; rg2.input.lastX = canvas.width / 2; rg2.input.lastY = canvas.height / 2; rg2.input.zoomSize = 1; rg2.input.dragStart = null; // looks odd but this works for initialisation rg2.input.dragged = true; // don't stretch map: just shrink to fit if (heightscale < 1) { mapscale = heightscale; } else { mapscale = 1; } // move map into view on small screens // avoid annoying jumps on larger screens if (rg2.input.infoPanelMaximised || window.innerWidth >= rg2.config.BIG_SCREEN_BREAK_POINT) { ctx.setTransform(mapscale, 0, 0, mapscale, $("#rg2-info-panel").outerWidth(), 0); } else { ctx.setTransform(mapscale, 0, 0, mapscale, 0, 0); } // don't need to rotate here since the call to setTransform above does that for us ctx.displayAngle = 0; ctx.save(); redraw(false); } function showInfoDisplay(show, title, position) { var chevronRemove, chevronAdd; rg2.input.infoPanelMaximised = show; $("#rg2-resize-info").prop("title", rg2.t(title)); $("#rg2-hide-info-panel-control").css("left", position); if (show) { $("#rg2-info-panel").show(); chevronRemove = "fa-chevron-right"; chevronAdd = "fa-chevron-left"; } else { $("#rg2-info-panel").hide(); chevronRemove = "fa-chevron-left"; chevronAdd = "fa-chevron-right"; } $("#rg2-hide-info-panel-icon").removeClass(chevronRemove).addClass(chevronAdd).prop("title", rg2.t(title)); } function resizeInfoDisplay() { if (rg2.input.infoPanelMaximised) { showInfoDisplay(false, "Show info panel", "0px"); } else { showInfoDisplay(true, "Hide info panel", "366px"); } // move map around if necesssary resetMapState(); } function zoom(zoomDirection) { var pt, factor, tempZoom; factor = Math.pow(rg2.input.scaleFactor, zoomDirection); tempZoom = rg2.input.zoomSize * factor; // limit zoom to avoid things disappearing // chosen values seem reasonable after some quick tests if ((tempZoom < 50) && (tempZoom > 0.05)) { rg2.input.zoomSize = tempZoom; pt = ctx.transformedPoint(rg2.input.lastX, rg2.input.lastY); ctx.translate(pt.x, pt.y); ctx.scale(factor, factor); ctx.translate(-pt.x, -pt.y); ctx.save(); redraw(false); } } function trackTransforms(ctx) { var xform, svg, savedTransforms, save, restore, scale, translate, setTransform, pt, rotate; svg = document.createElementNS("http://www.w3.org/2000/svg", 'svg'); xform = svg.createSVGMatrix(); savedTransforms = []; save = ctx.save; ctx.save = function () { savedTransforms.push(xform.translate(0, 0)); return save.call(ctx); }; restore = ctx.restore; ctx.restore = function () { xform = savedTransforms.pop(); return restore.call(ctx); }; scale = ctx.scale; ctx.scale = function (sx, sy) { xform = xform.scaleNonUniform(sx, sy); return scale.call(ctx, sx, sy); }; translate = ctx.translate; ctx.translate = function (dx, dy) { xform = xform.translate(dx, dy); return translate.call(ctx, dx, dy); }; setTransform = ctx.setTransform; ctx.setTransform = function (a, b, c, d, e, f) { xform.a = a; xform.b = b; xform.c = c; xform.d = d; xform.e = e; xform.f = f; return setTransform.call(ctx, a, b, c, d, e, f); }; pt = svg.createSVGPoint(); ctx.transformedPoint = function (x, y) { // converts x, y screen co-ords to x, y in map image pt.x = x; pt.y = y; return pt.matrixTransform(xform.inverse()); }; //ctx.getTransform = function () { // return xform; //}; //transform = ctx.transform; //ctx.transform = function (a, b, c, d, e, f) { // m2 = svg.createSVGMatrix(); // m2.a = a; // m2.b = b; // m2.c = c; // m2.d = d; // m2.e = e; // m2.f = f; // xform = xform.multiply(m2); // return transform.call(ctx, a, b, c, d, e, f); //}; rotate = ctx.rotate; ctx.rotate = function (radians) { xform = xform.rotate(radians * 180 / Math.PI); return rotate.call(ctx, radians); }; } function getMapSize() { return { height: map.height, width: map.width }; } function resizeCanvas() { rg2.input.scaleFactor = rg2.config.DEFAULT_SCALE_FACTOR; // allow for header $("#rg2-container").css("height", window.innerHeight - 36); canvas.width = window.innerWidth; // allow for header canvas.height = window.innerHeight - 36; rg2.ui.setTitleBar(); resetMapState(); } function mapLoadedCallback() { $("#rg2-map-load-progress").hide(); resetMapState(); if (rg2.config.managing) { rg2.manager.mapLoadCallback(); } } function addListeners() { canvas.addEventListener('touchstart', rg2.handleTouchStart, false); canvas.addEventListener('touchmove', rg2.handleTouchMove, false); canvas.addEventListener('touchend', rg2.handleTouchEnd, false); canvas.addEventListener('DOMMouseScroll', rg2.handleScroll, false); canvas.addEventListener('mousewheel', rg2.handleScroll, false); canvas.addEventListener('mousedown', rg2.handleMouseDown, false); canvas.addEventListener('mousemove', rg2.handleMouseMove, false); canvas.addEventListener('mouseup', rg2.handleMouseUp, false); window.addEventListener('resize', resizeCanvas, false); // force redraw once map has loaded map.addEventListener("load", function () { mapLoadedCallback(); }, false); } function setUpCanvas() { addListeners(); trackTransforms(ctx); resizeCanvas(); } rg2.zoom = zoom; rg2.rotateMap = rotateMap; rg2.alignMap = alignMap; rg2.redraw = redraw; rg2.canvas = canvas; rg2.setUpCanvas = setUpCanvas; rg2.ctx = ctx; rg2.addListeners = addListeners; rg2.resetMapState = resetMapState; rg2.getMapSize = getMapSize; rg2.loadNewMap = loadNewMap; rg2.resizeInfoDisplay = resizeInfoDisplay; }()); <|start_filename|>js/rg2input.js<|end_filename|> (function () { var input = { dragStart: null, // looks odd but this works for initialisation dragged: true, infoPanelMaximised: true, scaleFactor: 1.1 }; function handleInputDown(evt) { input.dragStart = rg2.ctx.transformedPoint(input.lastX, input.lastY); input.dragged = false; // need to cache this here since IE and FF don't set it for mousemove events input.whichButton = evt.which; //console.log ("InputDown " + input.lastX + " " + input.lastY + " " + input.dragStart.x + " " + input.dragStart.y); } function handleInputMove() { var pt; if (input.dragStart) { pt = rg2.ctx.transformedPoint(input.lastX, input.lastY); Math.round(pt.x); Math.round(pt.y); // console.log ("Mousemove after " + pt.x + ": " + pt.y); // simple debounce so that very small drags are treated as clicks instead if ((Math.abs(pt.x - input.dragStart.x) + Math.abs(pt.y - input.dragStart.y)) > 5) { if (rg2.drawing.gpsFileLoaded()) { rg2.drawing.adjustTrack({x: Math.round(input.dragStart.x), y: Math.round(input.dragStart.y)}, pt, input.whichButton); } else { if ($("#rg2-info-panel").tabs("option", "active") === rg2.config.TAB_CREATE) { rg2.manager.adjustControls({x: Math.round(input.dragStart.x), y: Math.round(input.dragStart.y)}, pt, input.whichButton); } else { rg2.ctx.translate(pt.x - input.dragStart.x, pt.y - input.dragStart.y); } } input.dragged = true; rg2.redraw(false); } } } function handleInputUp(evt) { // console.log("Input up " + input.dragged); var active = $("#rg2-info-panel").tabs("option", "active"); if (!input.dragged) { if (active === rg2.config.TAB_CREATE) { rg2.manager.mouseUp(Math.round(input.dragStart.x), Math.round(input.dragStart.y)); } else { // pass button that was clicked rg2.drawing.mouseUp(Math.round(input.dragStart.x), Math.round(input.dragStart.y), evt.which); } } else { if (active === rg2.config.TAB_CREATE) { rg2.manager.dragEnded(); } else { rg2.drawing.dragEnded(); } } input.dragStart = null; rg2.redraw(false); } function savePinchInfo(evt) { input.pinchStart0 = rg2.ctx.transformedPoint(evt.touches[0].pageX, evt.touches[0].pageY); input.pinchStart1 = rg2.ctx.transformedPoint(evt.touches[1].pageX, evt.touches[1].pageY); input.pinched = true; } // homegrown touch handling: seems no worse than adding some other library in // pinch zoom is primitive but works function handleTouchStart(evt) { evt.preventDefault(); if (evt.touches.length > 1) { savePinchInfo(evt); } input.lastX = evt.touches[0].pageX; input.lastY = evt.touches[0].pageY; handleInputDown(evt); } function handleTouchMove(evt) { var oldDistance, newDistance; if (evt.touches.length > 1) { if (!input.pinched) { savePinchInfo(evt); } } else { input.pinched = false; } if (input.pinched && (evt.touches.length > 1)) { input.pinchEnd0 = rg2.ctx.transformedPoint(evt.touches[0].pageX, evt.touches[0].pageY); input.pinchEnd1 = rg2.ctx.transformedPoint(evt.touches[1].pageX, evt.touches[1].pageY); oldDistance = rg2.utils.getDistanceBetweenPoints(input.pinchStart0.x, input.pinchStart0.y, input.pinchStart1.x, input.pinchStart1.y); newDistance = rg2.utils.getDistanceBetweenPoints(input.pinchEnd0.x, input.pinchEnd0.y, input.pinchEnd1.x, input.pinchEnd1.y); if ((oldDistance / newDistance) > 1.1) { rg2.zoom(-1); input.pinchStart0 = input.pinchEnd0; input.pinchStart1 = input.pinchEnd1; } else if ((oldDistance / newDistance) < 0.9) { rg2.zoom(1); input.pinchStart0 = input.pinchEnd0; input.pinchStart1 = input.pinchEnd1; } } else { input.lastX = evt.touches[0].pageX; input.lastY = evt.touches[0].pageY; handleInputMove(evt); } } function handleTouchEnd(evt) { handleInputUp(evt); input.pinched = false; } function handleScroll(evt) { var delta = evt.wheelDelta ? evt.wheelDelta / 40 : evt.detail ? -evt.detail : 0; if (delta) { rg2.zoom(delta); } evt.stopPropagation(); return evt.preventDefault() && false; } function saveMouseEvent(evt) { input.lastX = evt.offsetX || (evt.layerX - rg2.canvas.offsetLeft); input.lastY = evt.offsetY || (evt.layerY - rg2.canvas.offsetTop); } function handleMouseDown(evt) { saveMouseEvent(evt); handleInputDown(evt); evt.stopPropagation(); return evt.preventDefault() && false; } function handleMouseMove(evt) { saveMouseEvent(evt); handleInputMove(evt); evt.stopPropagation(); return evt.preventDefault() && false; } function handleMouseUp(evt) { handleInputUp(evt); evt.stopPropagation(); return evt.preventDefault() && false; } rg2.input = input; rg2.handleMouseDown = handleMouseDown; rg2.handleMouseUp = handleMouseUp; rg2.handleMouseMove = handleMouseMove; rg2.handleTouchEnd = handleTouchEnd; rg2.handleTouchStart = handleTouchStart; rg2.handleTouchMove = handleTouchMove; rg2.handleScroll = handleScroll; }()); <|start_filename|>js/controls.js<|end_filename|> (function () { function Controls() { this.controls = []; this.displayControls = false; } Controls.prototype = { Constructor : Controls, addControl : function (code, x, y) { var i, newCode; newCode = true; for (i = 0; i < this.controls.length; i += 1) { if (this.controls[i].code === code) { newCode = false; break; } } if (newCode) { this.controls.push(new rg2.Control(code, x, y)); } }, deleteAllControls : function () { this.controls.length = 0; }, drawControls : function (drawDot) { var i, l, opt; if (this.displayControls) { opt = rg2.getOverprintDetails(); //rg2.ctx.globalAlpha = 1.0; l = this.controls.length; for (i = 0; i < l; i += 1) { // Assume things starting with 'F' or 'M' are Finish or Mal if ((this.controls[i].code.indexOf('F') === 0) || (this.controls[i].code.indexOf('M') === 0)) { this.drawFinish(this.controls[i].x, this.controls[i].y, this.controls[i].code, opt); } else { // Assume things starting with 'S' are a Start if (this.controls[i].code.indexOf('S') === 0) { this.drawStart(this.controls[i].x, this.controls[i].y, this.controls[i].code, (1.5 * Math.PI), opt); } else { // Else it's a normal control this.drawSingleControl(this.controls[i].x, this.controls[i].y, this.controls[i].code, Math.PI * 0.25, opt); if (drawDot) { rg2.ctx.fillRect(this.controls[i].x - 1, this.controls[i].y - 1, 3, 3); } } } } } }, drawSingleControl : function (x, y, code, angle, opt) { var scale, metrics, xoffset, yoffset; //Draw the white halo around the controls rg2.ctx.beginPath(); rg2.ctx.strokeStyle = "white"; rg2.ctx.lineWidth = opt.overprintWidth + 2; rg2.ctx.arc(x, y, opt.controlRadius, 0, 2 * Math.PI, false); rg2.ctx.stroke(); //Draw the white halo around the control code rg2.ctx.beginPath(); rg2.ctx.textAlign = "center"; rg2.ctx.font = opt.font; rg2.ctx.strokeStyle = "white"; rg2.ctx.miterLimit = 2; rg2.ctx.lineJoin = "circle"; rg2.ctx.lineWidth = 1.5; rg2.ctx.textBaseline = "middle"; metrics = rg2.ctx.measureText(code); // offset to left if left of centre, to right if right of centre if (angle < Math.PI) { xoffset = metrics.width / 2; } else { xoffset = -1 * metrics.width / 2; } // control radius is also the control code text height // offset up if above half way, down if below half way if ((angle >= (Math.PI / 2)) && (angle <= (Math.PI * 1.5))) { yoffset = -1 * opt.controlRadius / 2; } else { yoffset = opt.controlRadius / 2; } // empirically looks OK with this scale scale = 1.3; rg2.ctx.strokeText(code, x + (opt.controlRadius * scale * Math.sin(angle)) + xoffset, y + (opt.controlRadius * scale * Math.cos(angle)) + yoffset); //Draw the purple control rg2.ctx.beginPath(); rg2.ctx.font = opt.font; rg2.ctx.fillStyle = rg2.config.PURPLE; rg2.ctx.strokeStyle = rg2.config.PURPLE; rg2.ctx.lineWidth = opt.overprintWidth; rg2.ctx.arc(x, y, opt.controlRadius, 0, 2 * Math.PI, false); rg2.ctx.fillText(code, x + (opt.controlRadius * scale * Math.sin(angle)) + xoffset, y + (opt.controlRadius * scale * Math.cos(angle)) + yoffset); rg2.ctx.stroke(); }, drawFinish : function (x, y, code, opt) { //Draw the white halo around the finish control rg2.ctx.strokeStyle = "white"; rg2.ctx.lineWidth = opt.overprintWidth + 2; rg2.ctx.beginPath(); rg2.ctx.arc(x, y, opt.finishInnerRadius, 0, 2 * Math.PI, false); rg2.ctx.stroke(); rg2.ctx.beginPath(); rg2.ctx.arc(x, y, opt.finishOuterRadius, 0, 2 * Math.PI, false); rg2.ctx.stroke(); //Draw the white halo around the finish code rg2.ctx.beginPath(); rg2.ctx.font = opt.font; rg2.ctx.textAlign = "left"; rg2.ctx.strokeStyle = "white"; rg2.ctx.miterLimit = 2; rg2.ctx.lineJoin = "circle"; rg2.ctx.lineWidth = 1.5; rg2.ctx.strokeText(code, x + (opt.controlRadius * 1.5), y + opt.controlRadius); rg2.ctx.stroke(); //Draw the purple finish control rg2.ctx.beginPath(); rg2.ctx.fillStyle = rg2.config.PURPLE; rg2.ctx.strokeStyle = rg2.config.PURPLE; rg2.ctx.lineWidth = opt.overprintWidth; rg2.ctx.arc(x, y, opt.finishInnerRadius, 0, 2 * Math.PI, false); rg2.ctx.stroke(); rg2.ctx.beginPath(); rg2.ctx.arc(x, y, opt.finishOuterRadius, 0, 2 * Math.PI, false); rg2.ctx.fillText(code, x + (opt.controlRadius * 1.5), y + opt.controlRadius); rg2.ctx.stroke(); }, drawStart : function (startx, starty, code, angle, opt) { //Draw the white halo around the start triangle var x, y, DEGREES_120; x = []; y = []; DEGREES_120 = (2 * Math.PI / 3); angle = angle + (Math.PI / 2); rg2.ctx.lineCap = 'round'; rg2.ctx.strokeStyle = "white"; rg2.ctx.lineWidth = opt.overprintWidth + 2; rg2.ctx.beginPath(); x[0] = startx + (opt.startTriangleLength * Math.sin(angle)); y[0] = starty - (opt.startTriangleLength * Math.cos(angle)); rg2.ctx.moveTo(x[0], y[0]); x[1] = startx + (opt.startTriangleLength * Math.sin(angle + DEGREES_120)); y[1] = starty - (opt.startTriangleLength * Math.cos(angle + DEGREES_120)); rg2.ctx.lineTo(x[1], y[1]); rg2.ctx.stroke(); rg2.ctx.beginPath(); rg2.ctx.moveTo(x[1], y[1]); x[2] = startx + (opt.startTriangleLength * Math.sin(angle - DEGREES_120)); y[2] = starty - (opt.startTriangleLength * Math.cos(angle - DEGREES_120)); rg2.ctx.lineTo(x[2], y[2]); rg2.ctx.stroke(); rg2.ctx.beginPath(); rg2.ctx.moveTo(x[2], y[2]); rg2.ctx.lineTo(x[0], y[0]); rg2.ctx.stroke(); //Draw the white halo around the start code rg2.ctx.beginPath(); rg2.ctx.font = opt.font; rg2.ctx.textAlign = "left"; rg2.ctx.strokeStyle = "white"; rg2.ctx.miterLimit = 2; rg2.ctx.lineJoin = "circle"; rg2.ctx.lineWidth = 1.5; rg2.ctx.strokeText(code, x[0] + (opt.controlRadius * 1.25), y[0] + (opt.controlRadius * 1.25)); rg2.ctx.stroke(); //Draw the purple start control rg2.ctx.strokeStyle = rg2.config.PURPLE; rg2.ctx.lineWidth = opt.overprintWidth; rg2.ctx.font = opt.font; rg2.ctx.fillStyle = rg2.config.PURPLE; rg2.ctx.beginPath(); rg2.ctx.moveTo(x[0], y[0]); rg2.ctx.lineTo(x[1], y[1]); rg2.ctx.stroke(); rg2.ctx.beginPath(); rg2.ctx.moveTo(x[1], y[1]); rg2.ctx.lineTo(x[2], y[2]); rg2.ctx.stroke(); rg2.ctx.beginPath(); rg2.ctx.moveTo(x[2], y[2]); rg2.ctx.lineTo(x[0], y[0]); rg2.ctx.fillText(code, x[0] + (opt.controlRadius * 1.25), y[0] + (opt.controlRadius * 1.25)); rg2.ctx.stroke(); }, toggleControlDisplay : function () { if (this.displayControls) { $("#btn-toggle-controls").removeClass("fa-ban").addClass("fa-circle-o"); $("#btn-toggle-controls").prop("title", rg2.t("Show controls")); } else { $("#btn-toggle-controls").removeClass("fa-circle-o").addClass("fa-ban"); $("#btn-toggle-controls").prop("title", rg2.t("Hide controls")); } this.displayControls = !this.displayControls; }, displayAllControls : function () { this.displayControls = true; }, getControlCount : function () { return this.controls.length; } }; rg2.Controls = Controls; }()); <|start_filename|>js/resultparseriofv2.js<|end_filename|> (function () { function ResultParserIOFV2(xml) { this.results = []; this.valid = true; this.processIOFV2Results(xml); return {results: this.results, valid: this.valid}; } ResultParserIOFV2.prototype = { Constructor : ResultParserIOFV2, getDBID : function (element, index) { if (element.length === 0) { return index; } // remove new lines from empty <PersonId> tags element = element[0].textContent.replace(/[\n\r]/g, '').trim(); if (element) { return element; } return index; }, getName : function (personlist) { var temp; temp = personlist.getElementsByTagName('Given')[0].textContent + " " + personlist.getElementsByTagName('Family')[0].textContent; // remove new lines from empty <Given> and <Family> tags return (temp.replace(/[\n\r]/g, '').trim()); }, processIOFV2Results : function (xml) { var classlist, personlist, resultlist, i, j, result, course; try { classlist = xml.getElementsByTagName('ClassResult'); for (i = 0; i < classlist.length; i += 1) { course = classlist[i].getElementsByTagName('ClassShortName')[0].textContent; personlist = classlist[i].getElementsByTagName('PersonResult'); for (j = 0; j < personlist.length; j += 1) { result = {}; result.course = course; result.name = this.getName(personlist[j]); result.dbid = this.getDBID(personlist[j].getElementsByTagName('PersonId'), j); result.club = rg2.utils.extractTextContentZero(personlist[j].getElementsByTagName('ShortName'), ''); resultlist = personlist[j].getElementsByTagName('Result'); this.extractIOFV2Results(resultlist, result); if (result.status !== 'DidNotStart') { this.results.push(result); } } } } catch (err) { this.valid = false; rg2.utils.showWarningDialog("XML parse error", "Error processing XML file. Error is : " + err.message); return; } }, getStartFinishTimeAsSecs : function (element) { var time; if (element.length > 0) { time = element[0].getElementsByTagName('Clock')[0].textContent; return rg2.utils.getSecsFromHHMMSS(time); } return 0; }, getPosition : function (element) { if (element.length > 0) { return parseInt(element[0].textContent, 10); } return ''; }, getTime : function (element) { if (element.length > 0) { return element[0].textContent.replace(/[\n\r]/g, ''); } return ''; }, extractIOFV2Results : function (resultlist, result) { var i, finishtime, splitlist; for (i = 0; i < resultlist.length; i += 1) { result.status = rg2.utils.extractAttributeZero(resultlist[i].getElementsByTagName('CompetitorStatus'), "value", ""); result.position = this.getPosition(resultlist[i].getElementsByTagName('ResultPosition')); result.chipid = rg2.utils.extractTextContentZero(resultlist[i].getElementsByTagName('CCardId'), 0); // assuming first <Time> is the total time... result.time = this.getTime(resultlist[i].getElementsByTagName('Time')); result.starttime = this.getStartFinishTimeAsSecs(resultlist[i].getElementsByTagName('StartTime')); result.splits = ""; result.codes = []; splitlist = resultlist[i].getElementsByTagName('SplitTime'); result.controls = splitlist.length; this.extractIOFV2Splits(splitlist, result); finishtime = this.getStartFinishTimeAsSecs(resultlist[i].getElementsByTagName('FinishTime')); result.splits += Math.max(finishtime - result.starttime, 0); } }, extractIOFV2Splits : function (splitlist, result) { var l, temp; for (l = 0; l < splitlist.length; l += 1) { if (l > 0) { result.splits += ";"; } temp = splitlist[l].getElementsByTagName('Time'); if (temp.length > 0) { // previously read timeFormat but some files lied! // allow for XML files that don't tell you what is going on // getSecsFromHHMMSS copes with MM:SS as well result.splits += rg2.utils.getSecsFromHHMMSS(temp[0].textContent); result.codes[l] = rg2.utils.extractTextContentZero(splitlist[l].getElementsByTagName('ControlCode'), ""); } else { result.splits += 0; result.codes[l] = ""; } } // add finish split result.splits += ";"; } }; rg2.ResultParserIOFV2 = ResultParserIOFV2; }()); <|start_filename|>lang/de.js<|end_filename|> rg2.setDictionary({ language: 'Deutsch', code: 'de', translation: '<EMAIL>', 'Events' : 'Wettkämpfe', 'Course' : 'Strecke', 'Courses': 'Strecken', 'Results': 'Ergebnisse', 'Draw': 'Zeichnen', 'Show': 'Anzeigen', 'Runners': 'Läufer', 'Routes': 'Routen', 'Route': 'Route', 'Name': 'Name', 'Time': 'Zeit', 'Replay': 'Animation', 'All': 'Alle', 'Help': 'Hilfe', 'Options': 'Optionen', 'Reset': 'Zurücksetzen', 'Zoom out': 'Verkleinern', 'Zoom in': 'Vergrößern', 'Splits': 'Zwischenzeiten', 'Splits table': 'Zwischenzeiten-Tabelle', 'Select runners on Results tab': 'Läufer auf dem Ergebnis-Reiter auswählen', 'Log in': 'Anmelden', 'User name': 'Benutzername', 'Password': '<PASSWORD>', 'Show controls': 'Zeige Posten', 'Hide controls': 'Verberge Posten', 'Show initials': 'Zeige Initialien', 'Show names': 'Zeige Namen', 'Hide names': 'Verberge Namen', 'Show info panel': 'Zeige Auswahl-Panel', 'Hide info panel': 'Verberge Auswahl-Panel', 'Select an event': 'Wähle einen Wettkampf aus', 'Slower': 'Langsamer', 'Run': 'Start', 'Pause': 'Pause', 'Faster': 'Schneller', 'Real time': 'Echtzeit', 'Mass start': 'Massenstart', 'Start at': 'Beginne bei', 'Length': 'Länge', 'Full tails': 'Vollständige Spur', // maybe 'Volle Spur' will suffice if this one is too long? 'No results available': 'Keine Ergebnisse verfügbar', 'Configuration options': 'Konfigurations-Optionen', 'Language': 'Sprache', 'Map intensity %': 'Intensität Karte %', 'Route intensity %': 'Intensität Route %', 'Route width': 'Routen-Breite', 'Replay label font size': 'Schriftgröße Animations-Text', 'Course overprint width': 'Stiftbreite Bahn-Signaturen', 'Control circle size': 'Postenkreis-Größe', 'Snap to control when drawing': 'Snap to control when drawing', 'Show +3 time loss for GPS routes': 'Zeige +3 Zeitverlust bei GPS-Routen', 'Show GPS speed colours': 'Zeige Farben für Geschwindigkeit bei GPS', 'Event statistics': 'Wettkampf-Statistik', 'Drawn routes': 'Gezeichnete Routen', 'GPS routes': 'GPS-Routen', 'Comments': 'Kommentare', 'Draw route': 'Route zeichnen', 'Select course': 'Wähle Strecke', 'Select name': 'Wähle Name', 'Type your comment': 'Dein Kommentar', 'Load GPS file (GPX or TCX)': 'Lade GPS-Datei (GPX oder TCX)', 'Save': 'Speichern', '+3 sec': '+3 Sek', 'Undo': 'Rückgängig', 'Save GPS route': 'GPS-Route speichern', 'Move track and map together (or right click-drag)': 'Verschiebe Route und Karte zusammen (oder ziehe mit Rechts-Klick)', 'Map is georeferenced': 'Karte ist geo-referenziert', 'International event': 'Internationaler Wettkampf', 'National event': 'Nationaler Wettkampf', 'Regional event': 'Regionaler Wettkampf', 'Local event': 'Kleiner Wettkampf', 'Training event': 'Trainings-Wettkampf', 'Unknown': 'Unbekannt', 'Warning': 'Achtung', 'Your route has been saved': 'Deine Route wurde gespeichert', 'Your route was not saved. Please try again': 'Deine Route wurde nicht gespeichert! Bitte versuche es erneut', 'Total time': 'Gesamtzeit', 'Left click to add/lock/unlock a handle': 'Links-Klick zum Hinzufügen/Sperren/Lösen eines Bearbeitungspunkts', 'Green - draggable': 'Grün - Verschiebbar', 'Red - locked': 'Rot - Gesperrt', 'Right click to delete a handle': 'Rechts-Klick zum Löschen eines Bearbeitungspunkts', 'Drag a handle to adjust track around locked point(s)': 'Ziehe einen Bearbeitungspunkt, um die Route anzupassen', 'Search': 'Suchen' }); <|start_filename|>.prettierrc.js<|end_filename|> /** @type {import('prettier').Options} */ module.exports = { semi: true, trailingComma: "all", bracketSpacing: true, singleQuote: false, arrowParens: "avoid", printWidth: 125, }; <|start_filename|>.eslintrc.js<|end_filename|> /* eslint-env node */ /** @type {import('eslint').Linter.Config} */ module.exports = { env: { browser: true, jquery: true, }, extends: ["eslint:recommended", "prettier"], ignorePatterns: ["js/lib/**/*", "*.min.js"], parserOptions: { ecmaVersion: 6, }, globals: { rg2: "writable", rg2Config: "readonly" }, };
HenryJobst/rg2
<|start_filename|>composer.json<|end_filename|> { "name": "jasonpriem/human-name-parser", "description": "Takes human names of arbitrary complexity and various wacky formats and parses them out.", "autoload": { "classmap": ["Name.php", "Parser.php"] } }
jasonpriem/HumanNameParser.php
<|start_filename|>Assets/acorn/setup assets [not for production use]/scripts/Editor/avatarCreator.cs<|end_filename|> using UnityEditor; using UnityEngine; namespace Acorn.Editor { public class avatarCreator /// <summary> /// Creates Avatar and Avatar Masks of selected objects/rigs. /// </summary> { [MenuItem("Tools/AvatarTools/CreateAvatarMask")] private static void CreateAvatarMask() { GameObject activeGameObject = Selection.activeGameObject; if (activeGameObject != null) { AvatarMask avatarMask = new AvatarMask(); avatarMask.AddTransformPath(activeGameObject.transform); var path = string.Format("Assets/{0}.mask", activeGameObject.name.Replace(':', '_')); AssetDatabase.CreateAsset(avatarMask, path); } } [MenuItem("Tools/AvatarTools/CreateAvatar")] private static void CreateAvatar() { GameObject activeGameObject = Selection.activeGameObject; if (activeGameObject != null) { Avatar avatar = AvatarBuilder.BuildGenericAvatar(activeGameObject, ""); avatar.name = activeGameObject.name; Debug.Log(avatar.isHuman ? "is human" : "is generic"); var path = string.Format("Assets/{0}.ht", avatar.name.Replace(':', '_')); AssetDatabase.CreateAsset(avatar, path); } } } } <|start_filename|>Assets/acorn/setup assets [not for production use]/scripts/Runtime/MirrorPose.cs<|end_filename|> using System.Collections; using System.Collections.Generic; using UnityEngine; using EasyButtons; using System.Linq; #if UNITY_EDITOR using UnityEditor; #endif namespace Acorn { public class MirrorPose : MonoBehaviour { /// <summary> ///Mirror's poses, useful for stuff like walk cycles. /// </summary> [SerializeField] [HideInInspector] Transform[] individualSwaps; [SerializeField] [HideInInspector] IKPair[] swapPairs; Quaternion mirrorRotationNormal = new Quaternion(1, 0, 0, 0); Object[] undoObjects; [Button("Mirror Pose", ButtonSpacing.Before)] void SwapSide() { swapPairs = swapPairs.OrderByDescending(s => GetChildDepth(s.leftIKHandle)).ToArray(); individualSwaps = individualSwaps.OrderByDescending(s => GetChildDepth(s)).ToArray(); undoObjects = swapPairs.SelectMany(pair => new Transform[] { pair.leftIKHandle, pair.rightIKHandle }) .Concat(individualSwaps) .Select(s => s as Object) .ToArray(); Vector3 mirrorNomral = transform.right; //mirrorRotationNormal = new Quaternion(transform.right.x, transform.right.y, transform.right.z, 0); #if UNITY_EDITOR Undo.RecordObjects(undoObjects, "Mirror Pose"); #endif for (int i = 0; i < swapPairs.Length; i++) { Vector3 newRightPosition = MirrorPosition(swapPairs[i].leftIKHandle.localPosition); Quaternion newRightRotation = MirrorQuaternion(swapPairs[i].leftIKHandle.localRotation); Vector3 newLeftPosition = MirrorPosition(swapPairs[i].rightIKHandle.localPosition); Quaternion newLeftRotation = MirrorQuaternion(swapPairs[i].rightIKHandle.localRotation); swapPairs[i].leftIKHandle.localPosition = newLeftPosition; swapPairs[i].leftIKHandle.localRotation = newLeftRotation; swapPairs[i].rightIKHandle.localPosition = newRightPosition; swapPairs[i].rightIKHandle.localRotation = newRightRotation; } for (int i = 0; i < individualSwaps.Length; i++) { Vector3 newIndividualPosition = MirrorPosition(individualSwaps[i].localPosition); Quaternion newIndividualRotation = MirrorQuaternion(individualSwaps[i].localRotation); individualSwaps[i].localPosition = newIndividualPosition; individualSwaps[i].localRotation = newIndividualRotation; } } Vector3 MirrorPosition(Vector3 position) { Vector3 normal = transform.right; return Vector3.Reflect(position, normal); } Quaternion MirrorQuaternion(Quaternion quaternion) { Vector3 normal = transform.right; Quaternion mirrorNormalQuat = new Quaternion(normal.x, normal.y, normal.z, 0).normalized; return mirrorNormalQuat * quaternion * mirrorNormalQuat; } Quaternion GetRelativeRotation(Quaternion parentRotation, Quaternion childRotation) { return Quaternion.Inverse(parentRotation) * childRotation; } static int GetChildDepth(Transform child) { MirrorPose thisScript = child.GetComponentInParent<MirrorPose>(); if (!thisScript) { return -1; } int depthIndex = 0; Transform currentParent = child.parent; while (currentParent.transform != thisScript.transform) { depthIndex++; currentParent = currentParent.parent; } return depthIndex; } [System.Serializable] public class IKPair { public Transform leftIKHandle; public Transform rightIKHandle; } } } <|start_filename|>Assets/acorn/setup assets [not for production use]/scripts/Runtime/FK_IK_switch.cs<|end_filename|> using System.Collections; using System.Collections.Generic; using EasyButtons; using DitzelGames; using UnityEngine; namespace Acorn { public class FK_IK_switch : MonoBehaviour /// <summary> /// Controller for FK IK switches on all Acorn, /// as well as Visibility ON/OFF for Handles, both on Edit and Play mode. /// </summary> { // IK-FK Switch Variables // IK Script Component - FastIKLook [HideInInspector] public DitzelGames.FastIK.FastIKLook head_fastIKLook; // IK Script Component - FastIKFabric [HideInInspector] public DitzelGames.FastIK.FastIKFabric leftHand_fastIKFabric; [HideInInspector] public DitzelGames.FastIK.FastIKFabric rightHand_fastIKFabric; [HideInInspector] public DitzelGames.FastIK.FastIKFabric leftFoot_fastIKFabric; [HideInInspector] public DitzelGames.FastIK.FastIKFabric rightFoot_fastIKFabric; // Handle Renderers [HideInInspector] public MeshRenderer head_handleRenderer; [HideInInspector] public MeshRenderer[] leftHand_handleRenderer; [HideInInspector] public MeshRenderer[] rightHand_handleRenderer; [HideInInspector] public MeshRenderer[] leftFoot_handleRenderer; [HideInInspector] public MeshRenderer[] rightFoot_handleRenderer; [HideInInspector] public MeshRenderer[] root_handleRenderer; // Visibility Variables [Header("Handles Visibility (Play Mode)")] public bool handlesVis = true; private bool head_Vis = true; private bool leftHand_Vis = true; private bool rightHand_Vis = true; private bool leftFoot_Vis = true; private bool rightFoot_Vis =true; private bool root_Vis = true; // Match FK-IK Transform Variables [HideInInspector] public Transform leftHand; [HideInInspector] public Transform leftHand_IKHandle; [HideInInspector] public Transform rightHand; [HideInInspector] public Transform rightHand_IKHandle; [HideInInspector] public Transform leftFoot; [HideInInspector] public Transform leftFoot_IKHandle; [HideInInspector] public Transform rightFoot; [HideInInspector] public Transform rightFoot_IKHandle; // FK-IK Switch // All FK [Button("All FK", ButtonMode.DisabledInPlayMode, ButtonSpacing.Before)] void all_FK(){ head_FK(); leftHand_FK(); rightHand_FK(); leftFoot_FK(); rightFoot_FK(); Debug.Log("Switch All to FK"); } // All IK [Button("All IK", ButtonMode.DisabledInPlayMode, ButtonSpacing.After)] void all_IK(){ head_IK(); leftHand_IK(); rightHand_IK(); leftFoot_IK(); rightFoot_IK(); Debug.Log("Switch All to IK"); } // Head [Button("Head FK", ButtonMode.DisabledInPlayMode, ButtonSpacing.Before)] void head_FK(){ head_fastIKLook.enabled = false; head_handleRenderer.enabled = false; Debug.Log("Switch Head to FK"); } [Button("Head IK", ButtonMode.DisabledInPlayMode, ButtonSpacing.After)] void head_IK(){ head_fastIKLook.enabled = true; head_handleRenderer.enabled = true; Debug.Log("Switch Head to IK"); } // Left Hand [Button("Left Hand FK", ButtonMode.DisabledInPlayMode, ButtonSpacing.Before)] void leftHand_FK(){ leftHand_fastIKFabric.enabled = false; for(int i = 0; i < leftHand_handleRenderer.Length; i++){ leftHand_handleRenderer[i].enabled = false; } Debug.Log("Switch Left Hand to FK"); } [Button("Left Hand IK", ButtonMode.DisabledInPlayMode, ButtonSpacing.After)] void leftHand_IK(){ leftHand_fastIKFabric.enabled = true; for(int i = 0; i < leftHand_handleRenderer.Length; i++){ leftHand_handleRenderer[i].enabled = true; } // Match FK-IK Transforms leftHand_IKHandle.position = leftHand.position; leftHand_IKHandle.rotation = leftHand.rotation; Debug.Log("Switch Left Hand to IK, and Match IK to FK Position + Rotation"); } // Right Hand [Button("Right Hand FK", ButtonMode.DisabledInPlayMode, ButtonSpacing.Before)] void rightHand_FK(){ rightHand_fastIKFabric.enabled = false; for(int i = 0; i < rightHand_handleRenderer.Length; i++){ rightHand_handleRenderer[i].enabled = false; } Debug.Log("Switch Right Hand to FK"); } [Button("Right Hand IK", ButtonMode.DisabledInPlayMode, ButtonSpacing.After)] void rightHand_IK(){ rightHand_fastIKFabric.enabled = true; for(int i = 0; i < rightHand_handleRenderer.Length; i++){ rightHand_handleRenderer[i].enabled = true; } // Match FK-IK Transforms rightHand_IKHandle.position = rightHand.position; rightHand_IKHandle.rotation = rightHand.rotation; Debug.Log("Switch Right Hand to IK, and Match IK to FK Position + Rotation"); } // Left Foot [Button("Left Foot FK", ButtonMode.DisabledInPlayMode, ButtonSpacing.Before)] void leftFoot_FK(){ leftFoot_fastIKFabric.enabled = false; for(int i = 0; i < leftFoot_handleRenderer.Length; i++){ leftFoot_handleRenderer[i].enabled = false; } Debug.Log("Switch Left Foot to FK"); } [Button("Left Foot IK", ButtonMode.DisabledInPlayMode, ButtonSpacing.After)] void leftFoot_IK(){ leftFoot_fastIKFabric.enabled = true; for(int i = 0; i < leftFoot_handleRenderer.Length; i++){ leftFoot_handleRenderer[i].enabled = true; } // Match FK-IK Transforms leftFoot_IKHandle.position = leftFoot.position; leftFoot_IKHandle.rotation = leftFoot.rotation; Debug.Log("Switch Left Foot to IK, and Match IK to FK Position + Rotation"); } // Right Foot [Button("Right Foot FK", ButtonMode.DisabledInPlayMode, ButtonSpacing.Before)] void rightFoot_FK(){ rightFoot_fastIKFabric.enabled = false; for(int i = 0; i < rightFoot_handleRenderer.Length; i++){ rightFoot_handleRenderer[i].enabled = false; } Debug.Log("Switch Right Foot to FK"); } [Button("Right Foot IK", ButtonMode.DisabledInPlayMode, ButtonSpacing.After)] void rightFoot_IK(){ rightFoot_fastIKFabric.enabled = true; for(int i = 0; i < rightFoot_handleRenderer.Length; i++){ rightFoot_handleRenderer[i].enabled = true; } // Match FK-IK Transforms rightFoot_IKHandle.position = rightFoot.position; rightFoot_IKHandle.rotation = rightFoot.rotation; Debug.Log("Switch Right Foot to IK, and Match IK to FK Position + Rotation"); } // Visibility Functions void LateUpdate(){ VisAll(); } void VisAll(){ if(handlesVis == false){ VisOff(); } else{ VisOn(); } } void Vis(){ head_handleRenderer.enabled = head_Vis; for(int i = 0; i < leftHand_handleRenderer.Length; i++){ leftHand_handleRenderer[i].enabled = leftHand_Vis; } for(int i = 0; i < rightHand_handleRenderer.Length; i++){ rightHand_handleRenderer[i].enabled = rightHand_Vis; } for(int i = 0; i < leftFoot_handleRenderer.Length; i++){ leftFoot_handleRenderer[i].enabled = leftFoot_Vis; } for(int i = 0; i < rightFoot_handleRenderer.Length; i++){ rightFoot_handleRenderer[i].enabled = rightFoot_Vis; } for(int i = 0; i < root_handleRenderer.Length; i++){ root_handleRenderer[i].enabled = root_Vis; } } // Visibility OFF Button [Button("Visibility OFF", ButtonMode.DisabledInPlayMode, ButtonSpacing.Before)] void VisOff(){ head_handleRenderer.enabled = false; for(int i = 0; i < leftHand_handleRenderer.Length; i++){ leftHand_handleRenderer[i].enabled = false; } for(int i = 0; i < rightHand_handleRenderer.Length; i++){ rightHand_handleRenderer[i].enabled = false; } for(int i = 0; i < leftFoot_handleRenderer.Length; i++){ leftFoot_handleRenderer[i].enabled = false; } for(int i = 0; i < rightFoot_handleRenderer.Length; i++){ rightFoot_handleRenderer[i].enabled = false; } for(int i = 0; i < root_handleRenderer.Length; i++){ root_handleRenderer[i].enabled = false; } Debug.Log("Set Visibility OFF on all Handles"); } // Visibility ON Button [Button("Visibility ON", ButtonMode.DisabledInPlayMode, ButtonSpacing.After)] void VisOn(){ head_handleRenderer.enabled = true; for(int i = 0; i < leftHand_handleRenderer.Length; i++){ leftHand_handleRenderer[i].enabled = true; } for(int i = 0; i < rightHand_handleRenderer.Length; i++){ rightHand_handleRenderer[i].enabled = true; } for(int i = 0; i < leftFoot_handleRenderer.Length; i++){ leftFoot_handleRenderer[i].enabled = true; } for(int i = 0; i < rightFoot_handleRenderer.Length; i++){ rightFoot_handleRenderer[i].enabled = true; } for(int i = 0; i < root_handleRenderer.Length; i++){ root_handleRenderer[i].enabled = true; } Debug.Log("Set Visibility ON on all Handles"); } } }
diegodelarocha/Acorn
<|start_filename|>protobuf/identity_pb2/identity.pb.go<|end_filename|> // Copyright 2017 Intel Corporation // // 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. // ----------------------------------------------------------------------------- // Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.25.0-devel // protoc v3.14.0 // source: protobuf/identity_pb2/identity.proto package identity import ( protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" sync "sync" ) const ( // Verify that this generated code is sufficiently up-to-date. _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) // Verify that runtime/protoimpl is sufficiently up-to-date. _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) type Policy_EntryType int32 const ( Policy_ENTRY_TYPE_UNSET Policy_EntryType = 0 Policy_PERMIT_KEY Policy_EntryType = 1 Policy_DENY_KEY Policy_EntryType = 2 ) // Enum value maps for Policy_EntryType. var ( Policy_EntryType_name = map[int32]string{ 0: "ENTRY_TYPE_UNSET", 1: "PERMIT_KEY", 2: "DENY_KEY", } Policy_EntryType_value = map[string]int32{ "ENTRY_TYPE_UNSET": 0, "PERMIT_KEY": 1, "DENY_KEY": 2, } ) func (x Policy_EntryType) Enum() *Policy_EntryType { p := new(Policy_EntryType) *p = x return p } func (x Policy_EntryType) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (Policy_EntryType) Descriptor() protoreflect.EnumDescriptor { return file_protobuf_identity_pb2_identity_proto_enumTypes[0].Descriptor() } func (Policy_EntryType) Type() protoreflect.EnumType { return &file_protobuf_identity_pb2_identity_proto_enumTypes[0] } func (x Policy_EntryType) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use Policy_EntryType.Descriptor instead. func (Policy_EntryType) EnumDescriptor() ([]byte, []int) { return file_protobuf_identity_pb2_identity_proto_rawDescGZIP(), []int{0, 0} } type Policy struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // name of the policy, this should be unique. Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` // list of Entries // The entries will be processed in order from first to last. Entries []*Policy_Entry `protobuf:"bytes,2,rep,name=entries,proto3" json:"entries,omitempty"` } func (x *Policy) Reset() { *x = Policy{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_identity_pb2_identity_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *Policy) String() string { return protoimpl.X.MessageStringOf(x) } func (*Policy) ProtoMessage() {} func (x *Policy) ProtoReflect() protoreflect.Message { mi := &file_protobuf_identity_pb2_identity_proto_msgTypes[0] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use Policy.ProtoReflect.Descriptor instead. func (*Policy) Descriptor() ([]byte, []int) { return file_protobuf_identity_pb2_identity_proto_rawDescGZIP(), []int{0} } func (x *Policy) GetName() string { if x != nil { return x.Name } return "" } func (x *Policy) GetEntries() []*Policy_Entry { if x != nil { return x.Entries } return nil } // Policy will be stored in a Policy list to account for state collisions type PolicyList struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Policies []*Policy `protobuf:"bytes,1,rep,name=policies,proto3" json:"policies,omitempty"` } func (x *PolicyList) Reset() { *x = PolicyList{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_identity_pb2_identity_proto_msgTypes[1] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *PolicyList) String() string { return protoimpl.X.MessageStringOf(x) } func (*PolicyList) ProtoMessage() {} func (x *PolicyList) ProtoReflect() protoreflect.Message { mi := &file_protobuf_identity_pb2_identity_proto_msgTypes[1] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use PolicyList.ProtoReflect.Descriptor instead. func (*PolicyList) Descriptor() ([]byte, []int) { return file_protobuf_identity_pb2_identity_proto_rawDescGZIP(), []int{1} } func (x *PolicyList) GetPolicies() []*Policy { if x != nil { return x.Policies } return nil } type Role struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // Role name Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` // Name of corresponding policy PolicyName string `protobuf:"bytes,2,opt,name=policy_name,json=policyName,proto3" json:"policy_name,omitempty"` } func (x *Role) Reset() { *x = Role{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_identity_pb2_identity_proto_msgTypes[2] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *Role) String() string { return protoimpl.X.MessageStringOf(x) } func (*Role) ProtoMessage() {} func (x *Role) ProtoReflect() protoreflect.Message { mi := &file_protobuf_identity_pb2_identity_proto_msgTypes[2] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use Role.ProtoReflect.Descriptor instead. func (*Role) Descriptor() ([]byte, []int) { return file_protobuf_identity_pb2_identity_proto_rawDescGZIP(), []int{2} } func (x *Role) GetName() string { if x != nil { return x.Name } return "" } func (x *Role) GetPolicyName() string { if x != nil { return x.PolicyName } return "" } // Roles will be stored in a RoleList to account for state collisions type RoleList struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Roles []*Role `protobuf:"bytes,1,rep,name=roles,proto3" json:"roles,omitempty"` } func (x *RoleList) Reset() { *x = RoleList{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_identity_pb2_identity_proto_msgTypes[3] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *RoleList) String() string { return protoimpl.X.MessageStringOf(x) } func (*RoleList) ProtoMessage() {} func (x *RoleList) ProtoReflect() protoreflect.Message { mi := &file_protobuf_identity_pb2_identity_proto_msgTypes[3] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use RoleList.ProtoReflect.Descriptor instead. func (*RoleList) Descriptor() ([]byte, []int) { return file_protobuf_identity_pb2_identity_proto_rawDescGZIP(), []int{3} } func (x *RoleList) GetRoles() []*Role { if x != nil { return x.Roles } return nil } type Policy_Entry struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // Whether this is a Permit_KEY or Deny_KEY entry Type Policy_EntryType `protobuf:"varint,1,opt,name=type,proto3,enum=Policy_EntryType" json:"type,omitempty"` // This should be a list of public keys or * to refer to all participants. // If using *, it should be the only key in the list. Key string `protobuf:"bytes,2,opt,name=key,proto3" json:"key,omitempty"` } func (x *Policy_Entry) Reset() { *x = Policy_Entry{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_identity_pb2_identity_proto_msgTypes[4] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *Policy_Entry) String() string { return protoimpl.X.MessageStringOf(x) } func (*Policy_Entry) ProtoMessage() {} func (x *Policy_Entry) ProtoReflect() protoreflect.Message { mi := &file_protobuf_identity_pb2_identity_proto_msgTypes[4] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use Policy_Entry.ProtoReflect.Descriptor instead. func (*Policy_Entry) Descriptor() ([]byte, []int) { return file_protobuf_identity_pb2_identity_proto_rawDescGZIP(), []int{0, 0} } func (x *Policy_Entry) GetType() Policy_EntryType { if x != nil { return x.Type } return Policy_ENTRY_TYPE_UNSET } func (x *Policy_Entry) GetKey() string { if x != nil { return x.Key } return "" } var File_protobuf_identity_pb2_identity_proto protoreflect.FileDescriptor var file_protobuf_identity_pb2_identity_proto_rawDesc = []byte{ 0x0a, 0x24, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x69, 0x64, 0x65, 0x6e, 0x74, 0x69, 0x74, 0x79, 0x5f, 0x70, 0x62, 0x32, 0x2f, 0x69, 0x64, 0x65, 0x6e, 0x74, 0x69, 0x74, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0xc8, 0x01, 0x0a, 0x06, 0x50, 0x6f, 0x6c, 0x69, 0x63, 0x79, 0x12, 0x12, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x27, 0x0a, 0x07, 0x65, 0x6e, 0x74, 0x72, 0x69, 0x65, 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x0d, 0x2e, 0x50, 0x6f, 0x6c, 0x69, 0x63, 0x79, 0x2e, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x52, 0x07, 0x65, 0x6e, 0x74, 0x72, 0x69, 0x65, 0x73, 0x1a, 0x40, 0x0a, 0x05, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x12, 0x25, 0x0a, 0x04, 0x74, 0x79, 0x70, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x11, 0x2e, 0x50, 0x6f, 0x6c, 0x69, 0x63, 0x79, 0x2e, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x54, 0x79, 0x70, 0x65, 0x52, 0x04, 0x74, 0x79, 0x70, 0x65, 0x12, 0x10, 0x0a, 0x03, 0x6b, 0x65, 0x79, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x6b, 0x65, 0x79, 0x22, 0x3f, 0x0a, 0x09, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x54, 0x79, 0x70, 0x65, 0x12, 0x14, 0x0a, 0x10, 0x45, 0x4e, 0x54, 0x52, 0x59, 0x5f, 0x54, 0x59, 0x50, 0x45, 0x5f, 0x55, 0x4e, 0x53, 0x45, 0x54, 0x10, 0x00, 0x12, 0x0e, 0x0a, 0x0a, 0x50, 0x45, 0x52, 0x4d, 0x49, 0x54, 0x5f, 0x4b, 0x45, 0x59, 0x10, 0x01, 0x12, 0x0c, 0x0a, 0x08, 0x44, 0x45, 0x4e, 0x59, 0x5f, 0x4b, 0x45, 0x59, 0x10, 0x02, 0x22, 0x31, 0x0a, 0x0a, 0x50, 0x6f, 0x6c, 0x69, 0x63, 0x79, 0x4c, 0x69, 0x73, 0x74, 0x12, 0x23, 0x0a, 0x08, 0x70, 0x6f, 0x6c, 0x69, 0x63, 0x69, 0x65, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x07, 0x2e, 0x50, 0x6f, 0x6c, 0x69, 0x63, 0x79, 0x52, 0x08, 0x70, 0x6f, 0x6c, 0x69, 0x63, 0x69, 0x65, 0x73, 0x22, 0x3b, 0x0a, 0x04, 0x52, 0x6f, 0x6c, 0x65, 0x12, 0x12, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x1f, 0x0a, 0x0b, 0x70, 0x6f, 0x6c, 0x69, 0x63, 0x79, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0a, 0x70, 0x6f, 0x6c, 0x69, 0x63, 0x79, 0x4e, 0x61, 0x6d, 0x65, 0x22, 0x27, 0x0a, 0x08, 0x52, 0x6f, 0x6c, 0x65, 0x4c, 0x69, 0x73, 0x74, 0x12, 0x1b, 0x0a, 0x05, 0x72, 0x6f, 0x6c, 0x65, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x05, 0x2e, 0x52, 0x6f, 0x6c, 0x65, 0x52, 0x05, 0x72, 0x6f, 0x6c, 0x65, 0x73, 0x42, 0x1e, 0x0a, 0x1a, 0x73, 0x61, 0x77, 0x74, 0x6f, 0x6f, 0x74, 0x68, 0x2e, 0x69, 0x64, 0x65, 0x6e, 0x74, 0x69, 0x74, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x50, 0x01, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( file_protobuf_identity_pb2_identity_proto_rawDescOnce sync.Once file_protobuf_identity_pb2_identity_proto_rawDescData = file_protobuf_identity_pb2_identity_proto_rawDesc ) func file_protobuf_identity_pb2_identity_proto_rawDescGZIP() []byte { file_protobuf_identity_pb2_identity_proto_rawDescOnce.Do(func() { file_protobuf_identity_pb2_identity_proto_rawDescData = protoimpl.X.CompressGZIP(file_protobuf_identity_pb2_identity_proto_rawDescData) }) return file_protobuf_identity_pb2_identity_proto_rawDescData } var file_protobuf_identity_pb2_identity_proto_enumTypes = make([]protoimpl.EnumInfo, 1) var file_protobuf_identity_pb2_identity_proto_msgTypes = make([]protoimpl.MessageInfo, 5) var file_protobuf_identity_pb2_identity_proto_goTypes = []interface{}{ (Policy_EntryType)(0), // 0: Policy.EntryType (*Policy)(nil), // 1: Policy (*PolicyList)(nil), // 2: PolicyList (*Role)(nil), // 3: Role (*RoleList)(nil), // 4: RoleList (*Policy_Entry)(nil), // 5: Policy.Entry } var file_protobuf_identity_pb2_identity_proto_depIdxs = []int32{ 5, // 0: Policy.entries:type_name -> Policy.Entry 1, // 1: PolicyList.policies:type_name -> Policy 3, // 2: RoleList.roles:type_name -> Role 0, // 3: Policy.Entry.type:type_name -> Policy.EntryType 4, // [4:4] is the sub-list for method output_type 4, // [4:4] is the sub-list for method input_type 4, // [4:4] is the sub-list for extension type_name 4, // [4:4] is the sub-list for extension extendee 0, // [0:4] is the sub-list for field type_name } func init() { file_protobuf_identity_pb2_identity_proto_init() } func file_protobuf_identity_pb2_identity_proto_init() { if File_protobuf_identity_pb2_identity_proto != nil { return } if !protoimpl.UnsafeEnabled { file_protobuf_identity_pb2_identity_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*Policy); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_identity_pb2_identity_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*PolicyList); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_identity_pb2_identity_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*Role); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_identity_pb2_identity_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*RoleList); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_identity_pb2_identity_proto_msgTypes[4].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*Policy_Entry); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: file_protobuf_identity_pb2_identity_proto_rawDesc, NumEnums: 1, NumMessages: 5, NumExtensions: 0, NumServices: 0, }, GoTypes: file_protobuf_identity_pb2_identity_proto_goTypes, DependencyIndexes: file_protobuf_identity_pb2_identity_proto_depIdxs, EnumInfos: file_protobuf_identity_pb2_identity_proto_enumTypes, MessageInfos: file_protobuf_identity_pb2_identity_proto_msgTypes, }.Build() File_protobuf_identity_pb2_identity_proto = out.File file_protobuf_identity_pb2_identity_proto_rawDesc = nil file_protobuf_identity_pb2_identity_proto_goTypes = nil file_protobuf_identity_pb2_identity_proto_depIdxs = nil } <|start_filename|>examples/intkey_go/src/sawtooth_intkey_client/show.go<|end_filename|> /** * Copyright 2018 Intel Corporation * * 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 main import ( "fmt" "github.com/jessevdk/go-flags" ) type Show struct { Args struct { Name string `positional-arg-name:"name" required:"true" description:"Name of key to show"` } `positional-args:"true"` Url string `long:"url" description:"Specify URL of REST API"` } func (args *Show) Name() string { return "show" } func (args *Show) KeyfilePassed() string { return "" } func (args *Show) UrlPassed() string { return args.Url } func (args *Show) Register(parent *flags.Command) error { _, err := parent.AddCommand(args.Name(), "Displays the specified intkey value", "Shows the value of the key <name>.", args) if err != nil { return err } return nil } func (args *Show) Run() error { // Construct client name := args.Args.Name intkeyClient, err := GetClient(args, false) if err != nil { return err } value, err := intkeyClient.Show(name) if err != nil { return err } fmt.Println(name, ": ", value) return nil } <|start_filename|>examples/smallbank/smallbank_go/src/protobuf/smallbank_pb2/smallbank.pb.go<|end_filename|> // Copyright 2017 Intel Corporation // // 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. // ----------------------------------------------------------------------------- // Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.25.0-devel // protoc v3.14.0 // source: protobuf/smallbank_pb2/smallbank.proto package smallbank_pb2 import ( protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" sync "sync" ) const ( // Verify that this generated code is sufficiently up-to-date. _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) // Verify that runtime/protoimpl is sufficiently up-to-date. _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) type SmallbankTransactionPayload_PayloadType int32 const ( SmallbankTransactionPayload_PAYLOAD_TYPE_UNSET SmallbankTransactionPayload_PayloadType = 0 SmallbankTransactionPayload_CREATE_ACCOUNT SmallbankTransactionPayload_PayloadType = 1 SmallbankTransactionPayload_DEPOSIT_CHECKING SmallbankTransactionPayload_PayloadType = 2 SmallbankTransactionPayload_WRITE_CHECK SmallbankTransactionPayload_PayloadType = 3 SmallbankTransactionPayload_TRANSACT_SAVINGS SmallbankTransactionPayload_PayloadType = 4 SmallbankTransactionPayload_SEND_PAYMENT SmallbankTransactionPayload_PayloadType = 5 SmallbankTransactionPayload_AMALGAMATE SmallbankTransactionPayload_PayloadType = 6 ) // Enum value maps for SmallbankTransactionPayload_PayloadType. var ( SmallbankTransactionPayload_PayloadType_name = map[int32]string{ 0: "PAYLOAD_TYPE_UNSET", 1: "CREATE_ACCOUNT", 2: "DEPOSIT_CHECKING", 3: "WRITE_CHECK", 4: "TRANSACT_SAVINGS", 5: "SEND_PAYMENT", 6: "AMALGAMATE", } SmallbankTransactionPayload_PayloadType_value = map[string]int32{ "PAYLOAD_TYPE_UNSET": 0, "CREATE_ACCOUNT": 1, "DEPOSIT_CHECKING": 2, "WRITE_CHECK": 3, "TRANSACT_SAVINGS": 4, "SEND_PAYMENT": 5, "AMALGAMATE": 6, } ) func (x SmallbankTransactionPayload_PayloadType) Enum() *SmallbankTransactionPayload_PayloadType { p := new(SmallbankTransactionPayload_PayloadType) *p = x return p } func (x SmallbankTransactionPayload_PayloadType) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (SmallbankTransactionPayload_PayloadType) Descriptor() protoreflect.EnumDescriptor { return file_protobuf_smallbank_pb2_smallbank_proto_enumTypes[0].Descriptor() } func (SmallbankTransactionPayload_PayloadType) Type() protoreflect.EnumType { return &file_protobuf_smallbank_pb2_smallbank_proto_enumTypes[0] } func (x SmallbankTransactionPayload_PayloadType) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use SmallbankTransactionPayload_PayloadType.Descriptor instead. func (SmallbankTransactionPayload_PayloadType) EnumDescriptor() ([]byte, []int) { return file_protobuf_smallbank_pb2_smallbank_proto_rawDescGZIP(), []int{1, 0} } type Account struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // Customer ID CustomerId uint32 `protobuf:"varint,1,opt,name=customer_id,json=customerId,proto3" json:"customer_id,omitempty"` // Customer Name CustomerName string `protobuf:"bytes,2,opt,name=customer_name,json=customerName,proto3" json:"customer_name,omitempty"` // Savings Balance (in cents to avoid float) SavingsBalance uint32 `protobuf:"varint,3,opt,name=savings_balance,json=savingsBalance,proto3" json:"savings_balance,omitempty"` // Checking Balance (in cents to avoid float) CheckingBalance uint32 `protobuf:"varint,4,opt,name=checking_balance,json=checkingBalance,proto3" json:"checking_balance,omitempty"` } func (x *Account) Reset() { *x = Account{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_smallbank_pb2_smallbank_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *Account) String() string { return protoimpl.X.MessageStringOf(x) } func (*Account) ProtoMessage() {} func (x *Account) ProtoReflect() protoreflect.Message { mi := &file_protobuf_smallbank_pb2_smallbank_proto_msgTypes[0] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use Account.ProtoReflect.Descriptor instead. func (*Account) Descriptor() ([]byte, []int) { return file_protobuf_smallbank_pb2_smallbank_proto_rawDescGZIP(), []int{0} } func (x *Account) GetCustomerId() uint32 { if x != nil { return x.CustomerId } return 0 } func (x *Account) GetCustomerName() string { if x != nil { return x.CustomerName } return "" } func (x *Account) GetSavingsBalance() uint32 { if x != nil { return x.SavingsBalance } return 0 } func (x *Account) GetCheckingBalance() uint32 { if x != nil { return x.CheckingBalance } return 0 } type SmallbankTransactionPayload struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields PayloadType SmallbankTransactionPayload_PayloadType `protobuf:"varint,1,opt,name=payload_type,json=payloadType,proto3,enum=SmallbankTransactionPayload_PayloadType" json:"payload_type,omitempty"` CreateAccount *SmallbankTransactionPayload_CreateAccountTransactionData `protobuf:"bytes,2,opt,name=create_account,json=createAccount,proto3" json:"create_account,omitempty"` DepositChecking *SmallbankTransactionPayload_DepositCheckingTransactionData `protobuf:"bytes,3,opt,name=deposit_checking,json=depositChecking,proto3" json:"deposit_checking,omitempty"` WriteCheck *SmallbankTransactionPayload_WriteCheckTransactionData `protobuf:"bytes,4,opt,name=write_check,json=writeCheck,proto3" json:"write_check,omitempty"` TransactSavings *SmallbankTransactionPayload_TransactSavingsTransactionData `protobuf:"bytes,5,opt,name=transact_savings,json=transactSavings,proto3" json:"transact_savings,omitempty"` SendPayment *SmallbankTransactionPayload_SendPaymentTransactionData `protobuf:"bytes,6,opt,name=send_payment,json=sendPayment,proto3" json:"send_payment,omitempty"` Amalgamate *SmallbankTransactionPayload_AmalgamateTransactionData `protobuf:"bytes,7,opt,name=amalgamate,proto3" json:"amalgamate,omitempty"` } func (x *SmallbankTransactionPayload) Reset() { *x = SmallbankTransactionPayload{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_smallbank_pb2_smallbank_proto_msgTypes[1] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *SmallbankTransactionPayload) String() string { return protoimpl.X.MessageStringOf(x) } func (*SmallbankTransactionPayload) ProtoMessage() {} func (x *SmallbankTransactionPayload) ProtoReflect() protoreflect.Message { mi := &file_protobuf_smallbank_pb2_smallbank_proto_msgTypes[1] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use SmallbankTransactionPayload.ProtoReflect.Descriptor instead. func (*SmallbankTransactionPayload) Descriptor() ([]byte, []int) { return file_protobuf_smallbank_pb2_smallbank_proto_rawDescGZIP(), []int{1} } func (x *SmallbankTransactionPayload) GetPayloadType() SmallbankTransactionPayload_PayloadType { if x != nil { return x.PayloadType } return SmallbankTransactionPayload_PAYLOAD_TYPE_UNSET } func (x *SmallbankTransactionPayload) GetCreateAccount() *SmallbankTransactionPayload_CreateAccountTransactionData { if x != nil { return x.CreateAccount } return nil } func (x *SmallbankTransactionPayload) GetDepositChecking() *SmallbankTransactionPayload_DepositCheckingTransactionData { if x != nil { return x.DepositChecking } return nil } func (x *SmallbankTransactionPayload) GetWriteCheck() *SmallbankTransactionPayload_WriteCheckTransactionData { if x != nil { return x.WriteCheck } return nil } func (x *SmallbankTransactionPayload) GetTransactSavings() *SmallbankTransactionPayload_TransactSavingsTransactionData { if x != nil { return x.TransactSavings } return nil } func (x *SmallbankTransactionPayload) GetSendPayment() *SmallbankTransactionPayload_SendPaymentTransactionData { if x != nil { return x.SendPayment } return nil } func (x *SmallbankTransactionPayload) GetAmalgamate() *SmallbankTransactionPayload_AmalgamateTransactionData { if x != nil { return x.Amalgamate } return nil } type SmallbankTransactionPayload_CreateAccountTransactionData struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // Customer ID CustomerId uint32 `protobuf:"varint,1,opt,name=customer_id,json=customerId,proto3" json:"customer_id,omitempty"` // Customer Name CustomerName string `protobuf:"bytes,2,opt,name=customer_name,json=customerName,proto3" json:"customer_name,omitempty"` // Initial Savings Balance (in cents to avoid float) InitialSavingsBalance uint32 `protobuf:"varint,3,opt,name=initial_savings_balance,json=initialSavingsBalance,proto3" json:"initial_savings_balance,omitempty"` // Initial Checking Balance (in cents to avoid float) InitialCheckingBalance uint32 `protobuf:"varint,4,opt,name=initial_checking_balance,json=initialCheckingBalance,proto3" json:"initial_checking_balance,omitempty"` } func (x *SmallbankTransactionPayload_CreateAccountTransactionData) Reset() { *x = SmallbankTransactionPayload_CreateAccountTransactionData{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_smallbank_pb2_smallbank_proto_msgTypes[2] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *SmallbankTransactionPayload_CreateAccountTransactionData) String() string { return protoimpl.X.MessageStringOf(x) } func (*SmallbankTransactionPayload_CreateAccountTransactionData) ProtoMessage() {} func (x *SmallbankTransactionPayload_CreateAccountTransactionData) ProtoReflect() protoreflect.Message { mi := &file_protobuf_smallbank_pb2_smallbank_proto_msgTypes[2] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use SmallbankTransactionPayload_CreateAccountTransactionData.ProtoReflect.Descriptor instead. func (*SmallbankTransactionPayload_CreateAccountTransactionData) Descriptor() ([]byte, []int) { return file_protobuf_smallbank_pb2_smallbank_proto_rawDescGZIP(), []int{1, 0} } func (x *SmallbankTransactionPayload_CreateAccountTransactionData) GetCustomerId() uint32 { if x != nil { return x.CustomerId } return 0 } func (x *SmallbankTransactionPayload_CreateAccountTransactionData) GetCustomerName() string { if x != nil { return x.CustomerName } return "" } func (x *SmallbankTransactionPayload_CreateAccountTransactionData) GetInitialSavingsBalance() uint32 { if x != nil { return x.InitialSavingsBalance } return 0 } func (x *SmallbankTransactionPayload_CreateAccountTransactionData) GetInitialCheckingBalance() uint32 { if x != nil { return x.InitialCheckingBalance } return 0 } type SmallbankTransactionPayload_DepositCheckingTransactionData struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // Customer ID CustomerId uint32 `protobuf:"varint,1,opt,name=customer_id,json=customerId,proto3" json:"customer_id,omitempty"` // Amount Amount uint32 `protobuf:"varint,2,opt,name=amount,proto3" json:"amount,omitempty"` } func (x *SmallbankTransactionPayload_DepositCheckingTransactionData) Reset() { *x = SmallbankTransactionPayload_DepositCheckingTransactionData{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_smallbank_pb2_smallbank_proto_msgTypes[3] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *SmallbankTransactionPayload_DepositCheckingTransactionData) String() string { return protoimpl.X.MessageStringOf(x) } func (*SmallbankTransactionPayload_DepositCheckingTransactionData) ProtoMessage() {} func (x *SmallbankTransactionPayload_DepositCheckingTransactionData) ProtoReflect() protoreflect.Message { mi := &file_protobuf_smallbank_pb2_smallbank_proto_msgTypes[3] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use SmallbankTransactionPayload_DepositCheckingTransactionData.ProtoReflect.Descriptor instead. func (*SmallbankTransactionPayload_DepositCheckingTransactionData) Descriptor() ([]byte, []int) { return file_protobuf_smallbank_pb2_smallbank_proto_rawDescGZIP(), []int{1, 1} } func (x *SmallbankTransactionPayload_DepositCheckingTransactionData) GetCustomerId() uint32 { if x != nil { return x.CustomerId } return 0 } func (x *SmallbankTransactionPayload_DepositCheckingTransactionData) GetAmount() uint32 { if x != nil { return x.Amount } return 0 } type SmallbankTransactionPayload_WriteCheckTransactionData struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // Customer ID CustomerId uint32 `protobuf:"varint,1,opt,name=customer_id,json=customerId,proto3" json:"customer_id,omitempty"` // Amount Amount uint32 `protobuf:"varint,2,opt,name=amount,proto3" json:"amount,omitempty"` } func (x *SmallbankTransactionPayload_WriteCheckTransactionData) Reset() { *x = SmallbankTransactionPayload_WriteCheckTransactionData{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_smallbank_pb2_smallbank_proto_msgTypes[4] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *SmallbankTransactionPayload_WriteCheckTransactionData) String() string { return protoimpl.X.MessageStringOf(x) } func (*SmallbankTransactionPayload_WriteCheckTransactionData) ProtoMessage() {} func (x *SmallbankTransactionPayload_WriteCheckTransactionData) ProtoReflect() protoreflect.Message { mi := &file_protobuf_smallbank_pb2_smallbank_proto_msgTypes[4] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use SmallbankTransactionPayload_WriteCheckTransactionData.ProtoReflect.Descriptor instead. func (*SmallbankTransactionPayload_WriteCheckTransactionData) Descriptor() ([]byte, []int) { return file_protobuf_smallbank_pb2_smallbank_proto_rawDescGZIP(), []int{1, 2} } func (x *SmallbankTransactionPayload_WriteCheckTransactionData) GetCustomerId() uint32 { if x != nil { return x.CustomerId } return 0 } func (x *SmallbankTransactionPayload_WriteCheckTransactionData) GetAmount() uint32 { if x != nil { return x.Amount } return 0 } type SmallbankTransactionPayload_TransactSavingsTransactionData struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // Customer ID CustomerId uint32 `protobuf:"varint,1,opt,name=customer_id,json=customerId,proto3" json:"customer_id,omitempty"` // Amount Amount int32 `protobuf:"varint,2,opt,name=amount,proto3" json:"amount,omitempty"` } func (x *SmallbankTransactionPayload_TransactSavingsTransactionData) Reset() { *x = SmallbankTransactionPayload_TransactSavingsTransactionData{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_smallbank_pb2_smallbank_proto_msgTypes[5] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *SmallbankTransactionPayload_TransactSavingsTransactionData) String() string { return protoimpl.X.MessageStringOf(x) } func (*SmallbankTransactionPayload_TransactSavingsTransactionData) ProtoMessage() {} func (x *SmallbankTransactionPayload_TransactSavingsTransactionData) ProtoReflect() protoreflect.Message { mi := &file_protobuf_smallbank_pb2_smallbank_proto_msgTypes[5] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use SmallbankTransactionPayload_TransactSavingsTransactionData.ProtoReflect.Descriptor instead. func (*SmallbankTransactionPayload_TransactSavingsTransactionData) Descriptor() ([]byte, []int) { return file_protobuf_smallbank_pb2_smallbank_proto_rawDescGZIP(), []int{1, 3} } func (x *SmallbankTransactionPayload_TransactSavingsTransactionData) GetCustomerId() uint32 { if x != nil { return x.CustomerId } return 0 } func (x *SmallbankTransactionPayload_TransactSavingsTransactionData) GetAmount() int32 { if x != nil { return x.Amount } return 0 } type SmallbankTransactionPayload_SendPaymentTransactionData struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // Source Customer ID SourceCustomerId uint32 `protobuf:"varint,1,opt,name=source_customer_id,json=sourceCustomerId,proto3" json:"source_customer_id,omitempty"` // Destination Customer ID DestCustomerId uint32 `protobuf:"varint,2,opt,name=dest_customer_id,json=destCustomerId,proto3" json:"dest_customer_id,omitempty"` // Amount Amount uint32 `protobuf:"varint,3,opt,name=amount,proto3" json:"amount,omitempty"` } func (x *SmallbankTransactionPayload_SendPaymentTransactionData) Reset() { *x = SmallbankTransactionPayload_SendPaymentTransactionData{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_smallbank_pb2_smallbank_proto_msgTypes[6] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *SmallbankTransactionPayload_SendPaymentTransactionData) String() string { return protoimpl.X.MessageStringOf(x) } func (*SmallbankTransactionPayload_SendPaymentTransactionData) ProtoMessage() {} func (x *SmallbankTransactionPayload_SendPaymentTransactionData) ProtoReflect() protoreflect.Message { mi := &file_protobuf_smallbank_pb2_smallbank_proto_msgTypes[6] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use SmallbankTransactionPayload_SendPaymentTransactionData.ProtoReflect.Descriptor instead. func (*SmallbankTransactionPayload_SendPaymentTransactionData) Descriptor() ([]byte, []int) { return file_protobuf_smallbank_pb2_smallbank_proto_rawDescGZIP(), []int{1, 4} } func (x *SmallbankTransactionPayload_SendPaymentTransactionData) GetSourceCustomerId() uint32 { if x != nil { return x.SourceCustomerId } return 0 } func (x *SmallbankTransactionPayload_SendPaymentTransactionData) GetDestCustomerId() uint32 { if x != nil { return x.DestCustomerId } return 0 } func (x *SmallbankTransactionPayload_SendPaymentTransactionData) GetAmount() uint32 { if x != nil { return x.Amount } return 0 } type SmallbankTransactionPayload_AmalgamateTransactionData struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // Source Customer ID SourceCustomerId uint32 `protobuf:"varint,1,opt,name=source_customer_id,json=sourceCustomerId,proto3" json:"source_customer_id,omitempty"` // Destination Customer ID DestCustomerId uint32 `protobuf:"varint,2,opt,name=dest_customer_id,json=destCustomerId,proto3" json:"dest_customer_id,omitempty"` } func (x *SmallbankTransactionPayload_AmalgamateTransactionData) Reset() { *x = SmallbankTransactionPayload_AmalgamateTransactionData{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_smallbank_pb2_smallbank_proto_msgTypes[7] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *SmallbankTransactionPayload_AmalgamateTransactionData) String() string { return protoimpl.X.MessageStringOf(x) } func (*SmallbankTransactionPayload_AmalgamateTransactionData) ProtoMessage() {} func (x *SmallbankTransactionPayload_AmalgamateTransactionData) ProtoReflect() protoreflect.Message { mi := &file_protobuf_smallbank_pb2_smallbank_proto_msgTypes[7] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use SmallbankTransactionPayload_AmalgamateTransactionData.ProtoReflect.Descriptor instead. func (*SmallbankTransactionPayload_AmalgamateTransactionData) Descriptor() ([]byte, []int) { return file_protobuf_smallbank_pb2_smallbank_proto_rawDescGZIP(), []int{1, 5} } func (x *SmallbankTransactionPayload_AmalgamateTransactionData) GetSourceCustomerId() uint32 { if x != nil { return x.SourceCustomerId } return 0 } func (x *SmallbankTransactionPayload_AmalgamateTransactionData) GetDestCustomerId() uint32 { if x != nil { return x.DestCustomerId } return 0 } var File_protobuf_smallbank_pb2_smallbank_proto protoreflect.FileDescriptor var file_protobuf_smallbank_pb2_smallbank_proto_rawDesc = []byte{ 0x0a, 0x26, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x73, 0x6d, 0x61, 0x6c, 0x6c, 0x62, 0x61, 0x6e, 0x6b, 0x5f, 0x70, 0x62, 0x32, 0x2f, 0x73, 0x6d, 0x61, 0x6c, 0x6c, 0x62, 0x61, 0x6e, 0x6b, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0xa3, 0x01, 0x0a, 0x07, 0x41, 0x63, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x12, 0x1f, 0x0a, 0x0b, 0x63, 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x65, 0x72, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x0a, 0x63, 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x65, 0x72, 0x49, 0x64, 0x12, 0x23, 0x0a, 0x0d, 0x63, 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x65, 0x72, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0c, 0x63, 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x65, 0x72, 0x4e, 0x61, 0x6d, 0x65, 0x12, 0x27, 0x0a, 0x0f, 0x73, 0x61, 0x76, 0x69, 0x6e, 0x67, 0x73, 0x5f, 0x62, 0x61, 0x6c, 0x61, 0x6e, 0x63, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x0e, 0x73, 0x61, 0x76, 0x69, 0x6e, 0x67, 0x73, 0x42, 0x61, 0x6c, 0x61, 0x6e, 0x63, 0x65, 0x12, 0x29, 0x0a, 0x10, 0x63, 0x68, 0x65, 0x63, 0x6b, 0x69, 0x6e, 0x67, 0x5f, 0x62, 0x61, 0x6c, 0x61, 0x6e, 0x63, 0x65, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x0f, 0x63, 0x68, 0x65, 0x63, 0x6b, 0x69, 0x6e, 0x67, 0x42, 0x61, 0x6c, 0x61, 0x6e, 0x63, 0x65, 0x22, 0xad, 0x0c, 0x0a, 0x1b, 0x53, 0x6d, 0x61, 0x6c, 0x6c, 0x62, 0x61, 0x6e, 0x6b, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x50, 0x61, 0x79, 0x6c, 0x6f, 0x61, 0x64, 0x12, 0x4b, 0x0a, 0x0c, 0x70, 0x61, 0x79, 0x6c, 0x6f, 0x61, 0x64, 0x5f, 0x74, 0x79, 0x70, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x28, 0x2e, 0x53, 0x6d, 0x61, 0x6c, 0x6c, 0x62, 0x61, 0x6e, 0x6b, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x50, 0x61, 0x79, 0x6c, 0x6f, 0x61, 0x64, 0x2e, 0x50, 0x61, 0x79, 0x6c, 0x6f, 0x61, 0x64, 0x54, 0x79, 0x70, 0x65, 0x52, 0x0b, 0x70, 0x61, 0x79, 0x6c, 0x6f, 0x61, 0x64, 0x54, 0x79, 0x70, 0x65, 0x12, 0x60, 0x0a, 0x0e, 0x63, 0x72, 0x65, 0x61, 0x74, 0x65, 0x5f, 0x61, 0x63, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x39, 0x2e, 0x53, 0x6d, 0x61, 0x6c, 0x6c, 0x62, 0x61, 0x6e, 0x6b, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x50, 0x61, 0x79, 0x6c, 0x6f, 0x61, 0x64, 0x2e, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x41, 0x63, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x44, 0x61, 0x74, 0x61, 0x52, 0x0d, 0x63, 0x72, 0x65, 0x61, 0x74, 0x65, 0x41, 0x63, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x12, 0x66, 0x0a, 0x10, 0x64, 0x65, 0x70, 0x6f, 0x73, 0x69, 0x74, 0x5f, 0x63, 0x68, 0x65, 0x63, 0x6b, 0x69, 0x6e, 0x67, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x3b, 0x2e, 0x53, 0x6d, 0x61, 0x6c, 0x6c, 0x62, 0x61, 0x6e, 0x6b, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x50, 0x61, 0x79, 0x6c, 0x6f, 0x61, 0x64, 0x2e, 0x44, 0x65, 0x70, 0x6f, 0x73, 0x69, 0x74, 0x43, 0x68, 0x65, 0x63, 0x6b, 0x69, 0x6e, 0x67, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x44, 0x61, 0x74, 0x61, 0x52, 0x0f, 0x64, 0x65, 0x70, 0x6f, 0x73, 0x69, 0x74, 0x43, 0x68, 0x65, 0x63, 0x6b, 0x69, 0x6e, 0x67, 0x12, 0x57, 0x0a, 0x0b, 0x77, 0x72, 0x69, 0x74, 0x65, 0x5f, 0x63, 0x68, 0x65, 0x63, 0x6b, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x36, 0x2e, 0x53, 0x6d, 0x61, 0x6c, 0x6c, 0x62, 0x61, 0x6e, 0x6b, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x50, 0x61, 0x79, 0x6c, 0x6f, 0x61, 0x64, 0x2e, 0x57, 0x72, 0x69, 0x74, 0x65, 0x43, 0x68, 0x65, 0x63, 0x6b, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x44, 0x61, 0x74, 0x61, 0x52, 0x0a, 0x77, 0x72, 0x69, 0x74, 0x65, 0x43, 0x68, 0x65, 0x63, 0x6b, 0x12, 0x66, 0x0a, 0x10, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x5f, 0x73, 0x61, 0x76, 0x69, 0x6e, 0x67, 0x73, 0x18, 0x05, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x3b, 0x2e, 0x53, 0x6d, 0x61, 0x6c, 0x6c, 0x62, 0x61, 0x6e, 0x6b, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x50, 0x61, 0x79, 0x6c, 0x6f, 0x61, 0x64, 0x2e, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x53, 0x61, 0x76, 0x69, 0x6e, 0x67, 0x73, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x44, 0x61, 0x74, 0x61, 0x52, 0x0f, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x53, 0x61, 0x76, 0x69, 0x6e, 0x67, 0x73, 0x12, 0x5a, 0x0a, 0x0c, 0x73, 0x65, 0x6e, 0x64, 0x5f, 0x70, 0x61, 0x79, 0x6d, 0x65, 0x6e, 0x74, 0x18, 0x06, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x37, 0x2e, 0x53, 0x6d, 0x61, 0x6c, 0x6c, 0x62, 0x61, 0x6e, 0x6b, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x50, 0x61, 0x79, 0x6c, 0x6f, 0x61, 0x64, 0x2e, 0x53, 0x65, 0x6e, 0x64, 0x50, 0x61, 0x79, 0x6d, 0x65, 0x6e, 0x74, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x44, 0x61, 0x74, 0x61, 0x52, 0x0b, 0x73, 0x65, 0x6e, 0x64, 0x50, 0x61, 0x79, 0x6d, 0x65, 0x6e, 0x74, 0x12, 0x56, 0x0a, 0x0a, 0x61, 0x6d, 0x61, 0x6c, 0x67, 0x61, 0x6d, 0x61, 0x74, 0x65, 0x18, 0x07, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x36, 0x2e, 0x53, 0x6d, 0x61, 0x6c, 0x6c, 0x62, 0x61, 0x6e, 0x6b, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x50, 0x61, 0x79, 0x6c, 0x6f, 0x61, 0x64, 0x2e, 0x41, 0x6d, 0x61, 0x6c, 0x67, 0x61, 0x6d, 0x61, 0x74, 0x65, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x44, 0x61, 0x74, 0x61, 0x52, 0x0a, 0x61, 0x6d, 0x61, 0x6c, 0x67, 0x61, 0x6d, 0x61, 0x74, 0x65, 0x1a, 0xd6, 0x01, 0x0a, 0x1c, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x41, 0x63, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x44, 0x61, 0x74, 0x61, 0x12, 0x1f, 0x0a, 0x0b, 0x63, 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x65, 0x72, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x0a, 0x63, 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x65, 0x72, 0x49, 0x64, 0x12, 0x23, 0x0a, 0x0d, 0x63, 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x65, 0x72, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0c, 0x63, 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x65, 0x72, 0x4e, 0x61, 0x6d, 0x65, 0x12, 0x36, 0x0a, 0x17, 0x69, 0x6e, 0x69, 0x74, 0x69, 0x61, 0x6c, 0x5f, 0x73, 0x61, 0x76, 0x69, 0x6e, 0x67, 0x73, 0x5f, 0x62, 0x61, 0x6c, 0x61, 0x6e, 0x63, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x15, 0x69, 0x6e, 0x69, 0x74, 0x69, 0x61, 0x6c, 0x53, 0x61, 0x76, 0x69, 0x6e, 0x67, 0x73, 0x42, 0x61, 0x6c, 0x61, 0x6e, 0x63, 0x65, 0x12, 0x38, 0x0a, 0x18, 0x69, 0x6e, 0x69, 0x74, 0x69, 0x61, 0x6c, 0x5f, 0x63, 0x68, 0x65, 0x63, 0x6b, 0x69, 0x6e, 0x67, 0x5f, 0x62, 0x61, 0x6c, 0x61, 0x6e, 0x63, 0x65, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x16, 0x69, 0x6e, 0x69, 0x74, 0x69, 0x61, 0x6c, 0x43, 0x68, 0x65, 0x63, 0x6b, 0x69, 0x6e, 0x67, 0x42, 0x61, 0x6c, 0x61, 0x6e, 0x63, 0x65, 0x1a, 0x59, 0x0a, 0x1e, 0x44, 0x65, 0x70, 0x6f, 0x73, 0x69, 0x74, 0x43, 0x68, 0x65, 0x63, 0x6b, 0x69, 0x6e, 0x67, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x44, 0x61, 0x74, 0x61, 0x12, 0x1f, 0x0a, 0x0b, 0x63, 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x65, 0x72, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x0a, 0x63, 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x65, 0x72, 0x49, 0x64, 0x12, 0x16, 0x0a, 0x06, 0x61, 0x6d, 0x6f, 0x75, 0x6e, 0x74, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x06, 0x61, 0x6d, 0x6f, 0x75, 0x6e, 0x74, 0x1a, 0x54, 0x0a, 0x19, 0x57, 0x72, 0x69, 0x74, 0x65, 0x43, 0x68, 0x65, 0x63, 0x6b, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x44, 0x61, 0x74, 0x61, 0x12, 0x1f, 0x0a, 0x0b, 0x63, 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x65, 0x72, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x0a, 0x63, 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x65, 0x72, 0x49, 0x64, 0x12, 0x16, 0x0a, 0x06, 0x61, 0x6d, 0x6f, 0x75, 0x6e, 0x74, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x06, 0x61, 0x6d, 0x6f, 0x75, 0x6e, 0x74, 0x1a, 0x59, 0x0a, 0x1e, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x53, 0x61, 0x76, 0x69, 0x6e, 0x67, 0x73, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x44, 0x61, 0x74, 0x61, 0x12, 0x1f, 0x0a, 0x0b, 0x63, 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x65, 0x72, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x0a, 0x63, 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x65, 0x72, 0x49, 0x64, 0x12, 0x16, 0x0a, 0x06, 0x61, 0x6d, 0x6f, 0x75, 0x6e, 0x74, 0x18, 0x02, 0x20, 0x01, 0x28, 0x05, 0x52, 0x06, 0x61, 0x6d, 0x6f, 0x75, 0x6e, 0x74, 0x1a, 0x8c, 0x01, 0x0a, 0x1a, 0x53, 0x65, 0x6e, 0x64, 0x50, 0x61, 0x79, 0x6d, 0x65, 0x6e, 0x74, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x44, 0x61, 0x74, 0x61, 0x12, 0x2c, 0x0a, 0x12, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x5f, 0x63, 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x65, 0x72, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x10, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x43, 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x65, 0x72, 0x49, 0x64, 0x12, 0x28, 0x0a, 0x10, 0x64, 0x65, 0x73, 0x74, 0x5f, 0x63, 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x65, 0x72, 0x5f, 0x69, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x0e, 0x64, 0x65, 0x73, 0x74, 0x43, 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x65, 0x72, 0x49, 0x64, 0x12, 0x16, 0x0a, 0x06, 0x61, 0x6d, 0x6f, 0x75, 0x6e, 0x74, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x06, 0x61, 0x6d, 0x6f, 0x75, 0x6e, 0x74, 0x1a, 0x73, 0x0a, 0x19, 0x41, 0x6d, 0x61, 0x6c, 0x67, 0x61, 0x6d, 0x61, 0x74, 0x65, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x44, 0x61, 0x74, 0x61, 0x12, 0x2c, 0x0a, 0x12, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x5f, 0x63, 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x65, 0x72, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x10, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x43, 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x65, 0x72, 0x49, 0x64, 0x12, 0x28, 0x0a, 0x10, 0x64, 0x65, 0x73, 0x74, 0x5f, 0x63, 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x65, 0x72, 0x5f, 0x69, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x0e, 0x64, 0x65, 0x73, 0x74, 0x43, 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x65, 0x72, 0x49, 0x64, 0x22, 0x98, 0x01, 0x0a, 0x0b, 0x50, 0x61, 0x79, 0x6c, 0x6f, 0x61, 0x64, 0x54, 0x79, 0x70, 0x65, 0x12, 0x16, 0x0a, 0x12, 0x50, 0x41, 0x59, 0x4c, 0x4f, 0x41, 0x44, 0x5f, 0x54, 0x59, 0x50, 0x45, 0x5f, 0x55, 0x4e, 0x53, 0x45, 0x54, 0x10, 0x00, 0x12, 0x12, 0x0a, 0x0e, 0x43, 0x52, 0x45, 0x41, 0x54, 0x45, 0x5f, 0x41, 0x43, 0x43, 0x4f, 0x55, 0x4e, 0x54, 0x10, 0x01, 0x12, 0x14, 0x0a, 0x10, 0x44, 0x45, 0x50, 0x4f, 0x53, 0x49, 0x54, 0x5f, 0x43, 0x48, 0x45, 0x43, 0x4b, 0x49, 0x4e, 0x47, 0x10, 0x02, 0x12, 0x0f, 0x0a, 0x0b, 0x57, 0x52, 0x49, 0x54, 0x45, 0x5f, 0x43, 0x48, 0x45, 0x43, 0x4b, 0x10, 0x03, 0x12, 0x14, 0x0a, 0x10, 0x54, 0x52, 0x41, 0x4e, 0x53, 0x41, 0x43, 0x54, 0x5f, 0x53, 0x41, 0x56, 0x49, 0x4e, 0x47, 0x53, 0x10, 0x04, 0x12, 0x10, 0x0a, 0x0c, 0x53, 0x45, 0x4e, 0x44, 0x5f, 0x50, 0x41, 0x59, 0x4d, 0x45, 0x4e, 0x54, 0x10, 0x05, 0x12, 0x0e, 0x0a, 0x0a, 0x41, 0x4d, 0x41, 0x4c, 0x47, 0x41, 0x4d, 0x41, 0x54, 0x45, 0x10, 0x06, 0x42, 0x0f, 0x5a, 0x0d, 0x73, 0x6d, 0x61, 0x6c, 0x6c, 0x62, 0x61, 0x6e, 0x6b, 0x5f, 0x70, 0x62, 0x32, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( file_protobuf_smallbank_pb2_smallbank_proto_rawDescOnce sync.Once file_protobuf_smallbank_pb2_smallbank_proto_rawDescData = file_protobuf_smallbank_pb2_smallbank_proto_rawDesc ) func file_protobuf_smallbank_pb2_smallbank_proto_rawDescGZIP() []byte { file_protobuf_smallbank_pb2_smallbank_proto_rawDescOnce.Do(func() { file_protobuf_smallbank_pb2_smallbank_proto_rawDescData = protoimpl.X.CompressGZIP(file_protobuf_smallbank_pb2_smallbank_proto_rawDescData) }) return file_protobuf_smallbank_pb2_smallbank_proto_rawDescData } var file_protobuf_smallbank_pb2_smallbank_proto_enumTypes = make([]protoimpl.EnumInfo, 1) var file_protobuf_smallbank_pb2_smallbank_proto_msgTypes = make([]protoimpl.MessageInfo, 8) var file_protobuf_smallbank_pb2_smallbank_proto_goTypes = []interface{}{ (SmallbankTransactionPayload_PayloadType)(0), // 0: SmallbankTransactionPayload.PayloadType (*Account)(nil), // 1: Account (*SmallbankTransactionPayload)(nil), // 2: SmallbankTransactionPayload (*SmallbankTransactionPayload_CreateAccountTransactionData)(nil), // 3: SmallbankTransactionPayload.CreateAccountTransactionData (*SmallbankTransactionPayload_DepositCheckingTransactionData)(nil), // 4: SmallbankTransactionPayload.DepositCheckingTransactionData (*SmallbankTransactionPayload_WriteCheckTransactionData)(nil), // 5: SmallbankTransactionPayload.WriteCheckTransactionData (*SmallbankTransactionPayload_TransactSavingsTransactionData)(nil), // 6: SmallbankTransactionPayload.TransactSavingsTransactionData (*SmallbankTransactionPayload_SendPaymentTransactionData)(nil), // 7: SmallbankTransactionPayload.SendPaymentTransactionData (*SmallbankTransactionPayload_AmalgamateTransactionData)(nil), // 8: SmallbankTransactionPayload.AmalgamateTransactionData } var file_protobuf_smallbank_pb2_smallbank_proto_depIdxs = []int32{ 0, // 0: SmallbankTransactionPayload.payload_type:type_name -> SmallbankTransactionPayload.PayloadType 3, // 1: SmallbankTransactionPayload.create_account:type_name -> SmallbankTransactionPayload.CreateAccountTransactionData 4, // 2: SmallbankTransactionPayload.deposit_checking:type_name -> SmallbankTransactionPayload.DepositCheckingTransactionData 5, // 3: SmallbankTransactionPayload.write_check:type_name -> SmallbankTransactionPayload.WriteCheckTransactionData 6, // 4: SmallbankTransactionPayload.transact_savings:type_name -> SmallbankTransactionPayload.TransactSavingsTransactionData 7, // 5: SmallbankTransactionPayload.send_payment:type_name -> SmallbankTransactionPayload.SendPaymentTransactionData 8, // 6: SmallbankTransactionPayload.amalgamate:type_name -> SmallbankTransactionPayload.AmalgamateTransactionData 7, // [7:7] is the sub-list for method output_type 7, // [7:7] is the sub-list for method input_type 7, // [7:7] is the sub-list for extension type_name 7, // [7:7] is the sub-list for extension extendee 0, // [0:7] is the sub-list for field type_name } func init() { file_protobuf_smallbank_pb2_smallbank_proto_init() } func file_protobuf_smallbank_pb2_smallbank_proto_init() { if File_protobuf_smallbank_pb2_smallbank_proto != nil { return } if !protoimpl.UnsafeEnabled { file_protobuf_smallbank_pb2_smallbank_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*Account); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_smallbank_pb2_smallbank_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*SmallbankTransactionPayload); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_smallbank_pb2_smallbank_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*SmallbankTransactionPayload_CreateAccountTransactionData); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_smallbank_pb2_smallbank_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*SmallbankTransactionPayload_DepositCheckingTransactionData); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_smallbank_pb2_smallbank_proto_msgTypes[4].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*SmallbankTransactionPayload_WriteCheckTransactionData); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_smallbank_pb2_smallbank_proto_msgTypes[5].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*SmallbankTransactionPayload_TransactSavingsTransactionData); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_smallbank_pb2_smallbank_proto_msgTypes[6].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*SmallbankTransactionPayload_SendPaymentTransactionData); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_smallbank_pb2_smallbank_proto_msgTypes[7].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*SmallbankTransactionPayload_AmalgamateTransactionData); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: file_protobuf_smallbank_pb2_smallbank_proto_rawDesc, NumEnums: 1, NumMessages: 8, NumExtensions: 0, NumServices: 0, }, GoTypes: file_protobuf_smallbank_pb2_smallbank_proto_goTypes, DependencyIndexes: file_protobuf_smallbank_pb2_smallbank_proto_depIdxs, EnumInfos: file_protobuf_smallbank_pb2_smallbank_proto_enumTypes, MessageInfos: file_protobuf_smallbank_pb2_smallbank_proto_msgTypes, }.Build() File_protobuf_smallbank_pb2_smallbank_proto = out.File file_protobuf_smallbank_pb2_smallbank_proto_rawDesc = nil file_protobuf_smallbank_pb2_smallbank_proto_goTypes = nil file_protobuf_smallbank_pb2_smallbank_proto_depIdxs = nil } <|start_filename|>examples/smallbank/smallbank_go/src/sawtooth_smallbank/handler/handler.go<|end_filename|> /** * Copyright 2017 Intel Corporation * * 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 handler import ( "crypto/sha512" "encoding/hex" "fmt" "github.com/golang/protobuf/proto" "github.com/hyperledger/sawtooth-sdk-go/examples/smallbank/smallbank_go/src/protobuf/smallbank_pb2" "github.com/hyperledger/sawtooth-sdk-go/logging" "github.com/hyperledger/sawtooth-sdk-go/processor" "github.com/hyperledger/sawtooth-sdk-go/protobuf/processor_pb2" "strings" ) var logger *logging.Logger = logging.Get() var namespace = hexdigest("smallbank")[:6] type SmallbankHandler struct { } func (self *SmallbankHandler) FamilyName() string { return "smallbank" } func (self *SmallbankHandler) FamilyVersions() []string { return []string{"1.0"} } func (self *SmallbankHandler) Namespaces() []string { return []string{namespace} } func (self *SmallbankHandler) Apply(request *processor_pb2.TpProcessRequest, context *processor.Context) error { payload, err := unpackPayload(request.GetPayload()) if err != nil { return err } logger.Debugf("smallbank txn %v: type %v", request.Signature, payload.PayloadType) switch payload.PayloadType { case smallbank_pb2.SmallbankTransactionPayload_CREATE_ACCOUNT: return applyCreateAccount(payload.CreateAccount, context) case smallbank_pb2.SmallbankTransactionPayload_DEPOSIT_CHECKING: return applyDepositChecking(payload.DepositChecking, context) case smallbank_pb2.SmallbankTransactionPayload_WRITE_CHECK: return applyWriteCheck(payload.WriteCheck, context) case smallbank_pb2.SmallbankTransactionPayload_TRANSACT_SAVINGS: return applyTransactSavings(payload.TransactSavings, context) case smallbank_pb2.SmallbankTransactionPayload_SEND_PAYMENT: return applySendPayment(payload.SendPayment, context) case smallbank_pb2.SmallbankTransactionPayload_AMALGAMATE: return applyAmalgamate(payload.Amalgamate, context) default: return &processor.InvalidTransactionError{ Msg: fmt.Sprintf("Invalid PayloadType: '%v'", payload.PayloadType)} } } func applyCreateAccount(createAccountData *smallbank_pb2.SmallbankTransactionPayload_CreateAccountTransactionData, context *processor.Context) error { account, err := loadAccount(createAccountData.CustomerId, context) if err != nil { return err } if account != nil { return &processor.InvalidTransactionError{Msg: "Account already exists"} } if createAccountData.CustomerName == "" { return &processor.InvalidTransactionError{Msg: "Customer Name must be set"} } new_account := &smallbank_pb2.Account{ CustomerId: createAccountData.CustomerId, CustomerName: createAccountData.CustomerName, SavingsBalance: createAccountData.InitialSavingsBalance, CheckingBalance: createAccountData.InitialCheckingBalance, } saveAccount(new_account, context) return nil } func applyDepositChecking(depositCheckingData *smallbank_pb2.SmallbankTransactionPayload_DepositCheckingTransactionData, context *processor.Context) error { account, err := loadAccount(depositCheckingData.CustomerId, context) if err != nil { return err } if account == nil { return &processor.InvalidTransactionError{Msg: "Account must exist"} } new_account := &smallbank_pb2.Account{ CustomerId: account.CustomerId, CustomerName: account.CustomerName, SavingsBalance: account.SavingsBalance, CheckingBalance: account.CheckingBalance + depositCheckingData.Amount, } saveAccount(new_account, context) return nil } func applyWriteCheck(writeCheckData *smallbank_pb2.SmallbankTransactionPayload_WriteCheckTransactionData, context *processor.Context) error { account, err := loadAccount(writeCheckData.CustomerId, context) if err != nil { return err } if account == nil { return &processor.InvalidTransactionError{Msg: "Account must exist"} } new_account := &smallbank_pb2.Account{ CustomerId: account.CustomerId, CustomerName: account.CustomerName, SavingsBalance: account.SavingsBalance, CheckingBalance: account.CheckingBalance - writeCheckData.Amount, } saveAccount(new_account, context) return nil } func applyTransactSavings(transactSavingsData *smallbank_pb2.SmallbankTransactionPayload_TransactSavingsTransactionData, context *processor.Context) error { account, err := loadAccount(transactSavingsData.CustomerId, context) if err != nil { return err } if account == nil { return &processor.InvalidTransactionError{Msg: "Account must exist"} } var new_balance uint32 if transactSavingsData.Amount < 0 { if uint32(-transactSavingsData.Amount) > account.SavingsBalance { return &processor.InvalidTransactionError{Msg: "Insufficient funds in source savings account"} } new_balance = account.SavingsBalance - uint32(-transactSavingsData.Amount) } else { new_balance = account.SavingsBalance + uint32(transactSavingsData.Amount) } new_account := &smallbank_pb2.Account{ CustomerId: account.CustomerId, CustomerName: account.CustomerName, SavingsBalance: new_balance, CheckingBalance: account.CheckingBalance, } saveAccount(new_account, context) return nil } func applySendPayment(sendPaymentData *smallbank_pb2.SmallbankTransactionPayload_SendPaymentTransactionData, context *processor.Context) error { source_account, err := loadAccount(sendPaymentData.SourceCustomerId, context) if err != nil { return err } dest_account, err := loadAccount(sendPaymentData.DestCustomerId, context) if err != nil { return err } if source_account == nil || dest_account == nil { return &processor.InvalidTransactionError{Msg: "Both source and dest accounts must exist"} } if source_account.CheckingBalance < sendPaymentData.Amount { return &processor.InvalidTransactionError{Msg: "Insufficient funds in source checking account"} } new_source_account := &smallbank_pb2.Account{ CustomerId: source_account.CustomerId, CustomerName: source_account.CustomerName, SavingsBalance: source_account.SavingsBalance, CheckingBalance: source_account.CheckingBalance - sendPaymentData.Amount, } new_dest_account := &smallbank_pb2.Account{ CustomerId: dest_account.CustomerId, CustomerName: dest_account.CustomerName, SavingsBalance: dest_account.SavingsBalance, CheckingBalance: dest_account.CheckingBalance + sendPaymentData.Amount, } saveAccount(new_source_account, context) saveAccount(new_dest_account, context) return nil } func applyAmalgamate(amalgamateData *smallbank_pb2.SmallbankTransactionPayload_AmalgamateTransactionData, context *processor.Context) error { source_account, err := loadAccount(amalgamateData.SourceCustomerId, context) if err != nil { return err } dest_account, err := loadAccount(amalgamateData.DestCustomerId, context) if err != nil { return err } if source_account == nil || dest_account == nil { return &processor.InvalidTransactionError{Msg: "Both source and dest accounts must exist"} } new_source_account := &smallbank_pb2.Account{ CustomerId: source_account.CustomerId, CustomerName: source_account.CustomerName, SavingsBalance: 0, CheckingBalance: source_account.CheckingBalance, } new_dest_account := &smallbank_pb2.Account{ CustomerId: dest_account.CustomerId, CustomerName: dest_account.CustomerName, SavingsBalance: dest_account.SavingsBalance, CheckingBalance: dest_account.CheckingBalance + source_account.SavingsBalance, } saveAccount(new_source_account, context) saveAccount(new_dest_account, context) return nil } func unpackPayload(payloadData []byte) (*smallbank_pb2.SmallbankTransactionPayload, error) { payload := &smallbank_pb2.SmallbankTransactionPayload{} err := proto.Unmarshal(payloadData, payload) if err != nil { return nil, &processor.InternalError{ Msg: fmt.Sprint("Failed to unmarshal SmallbankTransaction: %v", err)} } return payload, nil } func unpackAccount(accountData []byte) (*smallbank_pb2.Account, error) { account := &smallbank_pb2.Account{} err := proto.Unmarshal(accountData, account) if err != nil { return nil, &processor.InternalError{ Msg: fmt.Sprint("Failed to unmarshal Account: %v", err)} } return account, nil } func loadAccount(customer_id uint32, context *processor.Context) (*smallbank_pb2.Account, error) { address := namespace + hexdigest(fmt.Sprint(customer_id))[:64] results, err := context.GetState([]string{address}) if err != nil { return nil, err } if len(string(results[address])) > 0 { account, err := unpackAccount(results[address]) if err != nil { return nil, err } return account, nil } return nil, nil } func saveAccount(account *smallbank_pb2.Account, context *processor.Context) error { address := namespace + hexdigest(fmt.Sprint(account.CustomerId))[:64] data, err := proto.Marshal(account) if err != nil { return &processor.InternalError{Msg: fmt.Sprint("Failed to serialize Account:", err)} } addresses, err := context.SetState(map[string][]byte{ address: data, }) if err != nil { return err } if len(addresses) == 0 { return &processor.InternalError{Msg: "No addresses in set response"} } return nil } func hexdigest(str string) string { hash := sha512.New() hash.Write([]byte(str)) hashBytes := hash.Sum(nil) return strings.ToLower(hex.EncodeToString(hashBytes)) } <|start_filename|>protobuf/transaction_receipt_pb2/transaction_receipt.pb.go<|end_filename|> // Copyright 2017 Intel Corporation // // 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. // ----------------------------------------------------------------------------- // Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.25.0-devel // protoc v3.14.0 // source: protobuf/transaction_receipt_pb2/transaction_receipt.proto package txn_receipt_pb2 import ( protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" events_pb2 "github.com/hyperledger/sawtooth-sdk-go/protobuf/events_pb2" reflect "reflect" sync "sync" ) const ( // Verify that this generated code is sufficiently up-to-date. _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) // Verify that runtime/protoimpl is sufficiently up-to-date. _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) type StateChange_Type int32 const ( StateChange_TYPE_UNSET StateChange_Type = 0 StateChange_SET StateChange_Type = 1 StateChange_DELETE StateChange_Type = 2 ) // Enum value maps for StateChange_Type. var ( StateChange_Type_name = map[int32]string{ 0: "TYPE_UNSET", 1: "SET", 2: "DELETE", } StateChange_Type_value = map[string]int32{ "TYPE_UNSET": 0, "SET": 1, "DELETE": 2, } ) func (x StateChange_Type) Enum() *StateChange_Type { p := new(StateChange_Type) *p = x return p } func (x StateChange_Type) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (StateChange_Type) Descriptor() protoreflect.EnumDescriptor { return file_protobuf_transaction_receipt_pb2_transaction_receipt_proto_enumTypes[0].Descriptor() } func (StateChange_Type) Type() protoreflect.EnumType { return &file_protobuf_transaction_receipt_pb2_transaction_receipt_proto_enumTypes[0] } func (x StateChange_Type) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use StateChange_Type.Descriptor instead. func (StateChange_Type) EnumDescriptor() ([]byte, []int) { return file_protobuf_transaction_receipt_pb2_transaction_receipt_proto_rawDescGZIP(), []int{1, 0} } type TransactionReceipt struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // State changes made by this transaction // StateChange is defined in protos/transaction_receipt.proto StateChanges []*StateChange `protobuf:"bytes,1,rep,name=state_changes,json=stateChanges,proto3" json:"state_changes,omitempty"` // Events fired by this transaction Events []*events_pb2.Event `protobuf:"bytes,2,rep,name=events,proto3" json:"events,omitempty"` // Transaction family defined data Data [][]byte `protobuf:"bytes,3,rep,name=data,proto3" json:"data,omitempty"` TransactionId string `protobuf:"bytes,4,opt,name=transaction_id,json=transactionId,proto3" json:"transaction_id,omitempty"` } func (x *TransactionReceipt) Reset() { *x = TransactionReceipt{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_transaction_receipt_pb2_transaction_receipt_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *TransactionReceipt) String() string { return protoimpl.X.MessageStringOf(x) } func (*TransactionReceipt) ProtoMessage() {} func (x *TransactionReceipt) ProtoReflect() protoreflect.Message { mi := &file_protobuf_transaction_receipt_pb2_transaction_receipt_proto_msgTypes[0] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use TransactionReceipt.ProtoReflect.Descriptor instead. func (*TransactionReceipt) Descriptor() ([]byte, []int) { return file_protobuf_transaction_receipt_pb2_transaction_receipt_proto_rawDescGZIP(), []int{0} } func (x *TransactionReceipt) GetStateChanges() []*StateChange { if x != nil { return x.StateChanges } return nil } func (x *TransactionReceipt) GetEvents() []*events_pb2.Event { if x != nil { return x.Events } return nil } func (x *TransactionReceipt) GetData() [][]byte { if x != nil { return x.Data } return nil } func (x *TransactionReceipt) GetTransactionId() string { if x != nil { return x.TransactionId } return "" } // StateChange objects have the type of SET, which is either an insert or // update, or DELETE. Items marked as a DELETE will have no byte value. type StateChange struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Address string `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty"` Value []byte `protobuf:"bytes,2,opt,name=value,proto3" json:"value,omitempty"` Type StateChange_Type `protobuf:"varint,3,opt,name=type,proto3,enum=StateChange_Type" json:"type,omitempty"` } func (x *StateChange) Reset() { *x = StateChange{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_transaction_receipt_pb2_transaction_receipt_proto_msgTypes[1] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *StateChange) String() string { return protoimpl.X.MessageStringOf(x) } func (*StateChange) ProtoMessage() {} func (x *StateChange) ProtoReflect() protoreflect.Message { mi := &file_protobuf_transaction_receipt_pb2_transaction_receipt_proto_msgTypes[1] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use StateChange.ProtoReflect.Descriptor instead. func (*StateChange) Descriptor() ([]byte, []int) { return file_protobuf_transaction_receipt_pb2_transaction_receipt_proto_rawDescGZIP(), []int{1} } func (x *StateChange) GetAddress() string { if x != nil { return x.Address } return "" } func (x *StateChange) GetValue() []byte { if x != nil { return x.Value } return nil } func (x *StateChange) GetType() StateChange_Type { if x != nil { return x.Type } return StateChange_TYPE_UNSET } // A collection of state changes. type StateChangeList struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields StateChanges []*StateChange `protobuf:"bytes,1,rep,name=state_changes,json=stateChanges,proto3" json:"state_changes,omitempty"` } func (x *StateChangeList) Reset() { *x = StateChangeList{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_transaction_receipt_pb2_transaction_receipt_proto_msgTypes[2] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *StateChangeList) String() string { return protoimpl.X.MessageStringOf(x) } func (*StateChangeList) ProtoMessage() {} func (x *StateChangeList) ProtoReflect() protoreflect.Message { mi := &file_protobuf_transaction_receipt_pb2_transaction_receipt_proto_msgTypes[2] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use StateChangeList.ProtoReflect.Descriptor instead. func (*StateChangeList) Descriptor() ([]byte, []int) { return file_protobuf_transaction_receipt_pb2_transaction_receipt_proto_rawDescGZIP(), []int{2} } func (x *StateChangeList) GetStateChanges() []*StateChange { if x != nil { return x.StateChanges } return nil } var File_protobuf_transaction_receipt_pb2_transaction_receipt_proto protoreflect.FileDescriptor var file_protobuf_transaction_receipt_pb2_transaction_receipt_proto_rawDesc = []byte{ 0x0a, 0x3a, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x72, 0x65, 0x63, 0x65, 0x69, 0x70, 0x74, 0x5f, 0x70, 0x62, 0x32, 0x2f, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x72, 0x65, 0x63, 0x65, 0x69, 0x70, 0x74, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x20, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x65, 0x76, 0x65, 0x6e, 0x74, 0x73, 0x5f, 0x70, 0x62, 0x32, 0x2f, 0x65, 0x76, 0x65, 0x6e, 0x74, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0xa2, 0x01, 0x0a, 0x12, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x63, 0x65, 0x69, 0x70, 0x74, 0x12, 0x31, 0x0a, 0x0d, 0x73, 0x74, 0x61, 0x74, 0x65, 0x5f, 0x63, 0x68, 0x61, 0x6e, 0x67, 0x65, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x0c, 0x2e, 0x53, 0x74, 0x61, 0x74, 0x65, 0x43, 0x68, 0x61, 0x6e, 0x67, 0x65, 0x52, 0x0c, 0x73, 0x74, 0x61, 0x74, 0x65, 0x43, 0x68, 0x61, 0x6e, 0x67, 0x65, 0x73, 0x12, 0x1e, 0x0a, 0x06, 0x65, 0x76, 0x65, 0x6e, 0x74, 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x06, 0x2e, 0x45, 0x76, 0x65, 0x6e, 0x74, 0x52, 0x06, 0x65, 0x76, 0x65, 0x6e, 0x74, 0x73, 0x12, 0x12, 0x0a, 0x04, 0x64, 0x61, 0x74, 0x61, 0x18, 0x03, 0x20, 0x03, 0x28, 0x0c, 0x52, 0x04, 0x64, 0x61, 0x74, 0x61, 0x12, 0x25, 0x0a, 0x0e, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x69, 0x64, 0x18, 0x04, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0d, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x49, 0x64, 0x22, 0x91, 0x01, 0x0a, 0x0b, 0x53, 0x74, 0x61, 0x74, 0x65, 0x43, 0x68, 0x61, 0x6e, 0x67, 0x65, 0x12, 0x18, 0x0a, 0x07, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x12, 0x14, 0x0a, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x12, 0x25, 0x0a, 0x04, 0x74, 0x79, 0x70, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x11, 0x2e, 0x53, 0x74, 0x61, 0x74, 0x65, 0x43, 0x68, 0x61, 0x6e, 0x67, 0x65, 0x2e, 0x54, 0x79, 0x70, 0x65, 0x52, 0x04, 0x74, 0x79, 0x70, 0x65, 0x22, 0x2b, 0x0a, 0x04, 0x54, 0x79, 0x70, 0x65, 0x12, 0x0e, 0x0a, 0x0a, 0x54, 0x59, 0x50, 0x45, 0x5f, 0x55, 0x4e, 0x53, 0x45, 0x54, 0x10, 0x00, 0x12, 0x07, 0x0a, 0x03, 0x53, 0x45, 0x54, 0x10, 0x01, 0x12, 0x0a, 0x0a, 0x06, 0x44, 0x45, 0x4c, 0x45, 0x54, 0x45, 0x10, 0x02, 0x22, 0x44, 0x0a, 0x0f, 0x53, 0x74, 0x61, 0x74, 0x65, 0x43, 0x68, 0x61, 0x6e, 0x67, 0x65, 0x4c, 0x69, 0x73, 0x74, 0x12, 0x31, 0x0a, 0x0d, 0x73, 0x74, 0x61, 0x74, 0x65, 0x5f, 0x63, 0x68, 0x61, 0x6e, 0x67, 0x65, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x0c, 0x2e, 0x53, 0x74, 0x61, 0x74, 0x65, 0x43, 0x68, 0x61, 0x6e, 0x67, 0x65, 0x52, 0x0c, 0x73, 0x74, 0x61, 0x74, 0x65, 0x43, 0x68, 0x61, 0x6e, 0x67, 0x65, 0x73, 0x42, 0x2a, 0x0a, 0x15, 0x73, 0x61, 0x77, 0x74, 0x6f, 0x6f, 0x74, 0x68, 0x2e, 0x73, 0x64, 0x6b, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x50, 0x01, 0x5a, 0x0f, 0x74, 0x78, 0x6e, 0x5f, 0x72, 0x65, 0x63, 0x65, 0x69, 0x70, 0x74, 0x5f, 0x70, 0x62, 0x32, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( file_protobuf_transaction_receipt_pb2_transaction_receipt_proto_rawDescOnce sync.Once file_protobuf_transaction_receipt_pb2_transaction_receipt_proto_rawDescData = file_protobuf_transaction_receipt_pb2_transaction_receipt_proto_rawDesc ) func file_protobuf_transaction_receipt_pb2_transaction_receipt_proto_rawDescGZIP() []byte { file_protobuf_transaction_receipt_pb2_transaction_receipt_proto_rawDescOnce.Do(func() { file_protobuf_transaction_receipt_pb2_transaction_receipt_proto_rawDescData = protoimpl.X.CompressGZIP(file_protobuf_transaction_receipt_pb2_transaction_receipt_proto_rawDescData) }) return file_protobuf_transaction_receipt_pb2_transaction_receipt_proto_rawDescData } var file_protobuf_transaction_receipt_pb2_transaction_receipt_proto_enumTypes = make([]protoimpl.EnumInfo, 1) var file_protobuf_transaction_receipt_pb2_transaction_receipt_proto_msgTypes = make([]protoimpl.MessageInfo, 3) var file_protobuf_transaction_receipt_pb2_transaction_receipt_proto_goTypes = []interface{}{ (StateChange_Type)(0), // 0: StateChange.Type (*TransactionReceipt)(nil), // 1: TransactionReceipt (*StateChange)(nil), // 2: StateChange (*StateChangeList)(nil), // 3: StateChangeList (*events_pb2.Event)(nil), // 4: Event } var file_protobuf_transaction_receipt_pb2_transaction_receipt_proto_depIdxs = []int32{ 2, // 0: TransactionReceipt.state_changes:type_name -> StateChange 4, // 1: TransactionReceipt.events:type_name -> Event 0, // 2: StateChange.type:type_name -> StateChange.Type 2, // 3: StateChangeList.state_changes:type_name -> StateChange 4, // [4:4] is the sub-list for method output_type 4, // [4:4] is the sub-list for method input_type 4, // [4:4] is the sub-list for extension type_name 4, // [4:4] is the sub-list for extension extendee 0, // [0:4] is the sub-list for field type_name } func init() { file_protobuf_transaction_receipt_pb2_transaction_receipt_proto_init() } func file_protobuf_transaction_receipt_pb2_transaction_receipt_proto_init() { if File_protobuf_transaction_receipt_pb2_transaction_receipt_proto != nil { return } if !protoimpl.UnsafeEnabled { file_protobuf_transaction_receipt_pb2_transaction_receipt_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*TransactionReceipt); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_transaction_receipt_pb2_transaction_receipt_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*StateChange); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_transaction_receipt_pb2_transaction_receipt_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*StateChangeList); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: file_protobuf_transaction_receipt_pb2_transaction_receipt_proto_rawDesc, NumEnums: 1, NumMessages: 3, NumExtensions: 0, NumServices: 0, }, GoTypes: file_protobuf_transaction_receipt_pb2_transaction_receipt_proto_goTypes, DependencyIndexes: file_protobuf_transaction_receipt_pb2_transaction_receipt_proto_depIdxs, EnumInfos: file_protobuf_transaction_receipt_pb2_transaction_receipt_proto_enumTypes, MessageInfos: file_protobuf_transaction_receipt_pb2_transaction_receipt_proto_msgTypes, }.Build() File_protobuf_transaction_receipt_pb2_transaction_receipt_proto = out.File file_protobuf_transaction_receipt_pb2_transaction_receipt_proto_rawDesc = nil file_protobuf_transaction_receipt_pb2_transaction_receipt_proto_goTypes = nil file_protobuf_transaction_receipt_pb2_transaction_receipt_proto_depIdxs = nil } <|start_filename|>protobuf/batch_pb2/batch.pb.go<|end_filename|> // Copyright 2016 Intel Corporation // // 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. // ----------------------------------------------------------------------------- // Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.25.0-devel // protoc v3.14.0 // source: protobuf/batch_pb2/batch.proto package batch_pb2 import ( protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" transaction_pb2 "github.com/hyperledger/sawtooth-sdk-go/protobuf/transaction_pb2" reflect "reflect" sync "sync" ) const ( // Verify that this generated code is sufficiently up-to-date. _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) // Verify that runtime/protoimpl is sufficiently up-to-date. _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) type BatchHeader struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // Public key for the client that signed the BatchHeader SignerPublicKey string `protobuf:"bytes,1,opt,name=signer_public_key,json=signerPublicKey,proto3" json:"signer_public_key,omitempty"` // List of transaction.header_signatures that match the order of // transactions required for the batch TransactionIds []string `protobuf:"bytes,2,rep,name=transaction_ids,json=transactionIds,proto3" json:"transaction_ids,omitempty"` } func (x *BatchHeader) Reset() { *x = BatchHeader{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_batch_pb2_batch_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *BatchHeader) String() string { return protoimpl.X.MessageStringOf(x) } func (*BatchHeader) ProtoMessage() {} func (x *BatchHeader) ProtoReflect() protoreflect.Message { mi := &file_protobuf_batch_pb2_batch_proto_msgTypes[0] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use BatchHeader.ProtoReflect.Descriptor instead. func (*BatchHeader) Descriptor() ([]byte, []int) { return file_protobuf_batch_pb2_batch_proto_rawDescGZIP(), []int{0} } func (x *BatchHeader) GetSignerPublicKey() string { if x != nil { return x.SignerPublicKey } return "" } func (x *BatchHeader) GetTransactionIds() []string { if x != nil { return x.TransactionIds } return nil } type Batch struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // The serialized version of the BatchHeader Header []byte `protobuf:"bytes,1,opt,name=header,proto3" json:"header,omitempty"` // The signature derived from signing the header HeaderSignature string `protobuf:"bytes,2,opt,name=header_signature,json=headerSignature,proto3" json:"header_signature,omitempty"` // A list of the transactions that match the list of // transaction_ids listed in the batch header Transactions []*transaction_pb2.Transaction `protobuf:"bytes,3,rep,name=transactions,proto3" json:"transactions,omitempty"` // A debugging flag which indicates this batch should be traced through the // system, resulting in a higher level of debugging output. Trace bool `protobuf:"varint,4,opt,name=trace,proto3" json:"trace,omitempty"` } func (x *Batch) Reset() { *x = Batch{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_batch_pb2_batch_proto_msgTypes[1] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *Batch) String() string { return protoimpl.X.MessageStringOf(x) } func (*Batch) ProtoMessage() {} func (x *Batch) ProtoReflect() protoreflect.Message { mi := &file_protobuf_batch_pb2_batch_proto_msgTypes[1] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use Batch.ProtoReflect.Descriptor instead. func (*Batch) Descriptor() ([]byte, []int) { return file_protobuf_batch_pb2_batch_proto_rawDescGZIP(), []int{1} } func (x *Batch) GetHeader() []byte { if x != nil { return x.Header } return nil } func (x *Batch) GetHeaderSignature() string { if x != nil { return x.HeaderSignature } return "" } func (x *Batch) GetTransactions() []*transaction_pb2.Transaction { if x != nil { return x.Transactions } return nil } func (x *Batch) GetTrace() bool { if x != nil { return x.Trace } return false } type BatchList struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Batches []*Batch `protobuf:"bytes,1,rep,name=batches,proto3" json:"batches,omitempty"` } func (x *BatchList) Reset() { *x = BatchList{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_batch_pb2_batch_proto_msgTypes[2] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *BatchList) String() string { return protoimpl.X.MessageStringOf(x) } func (*BatchList) ProtoMessage() {} func (x *BatchList) ProtoReflect() protoreflect.Message { mi := &file_protobuf_batch_pb2_batch_proto_msgTypes[2] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use BatchList.ProtoReflect.Descriptor instead. func (*BatchList) Descriptor() ([]byte, []int) { return file_protobuf_batch_pb2_batch_proto_rawDescGZIP(), []int{2} } func (x *BatchList) GetBatches() []*Batch { if x != nil { return x.Batches } return nil } var File_protobuf_batch_pb2_batch_proto protoreflect.FileDescriptor var file_protobuf_batch_pb2_batch_proto_rawDesc = []byte{ 0x0a, 0x1e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x62, 0x61, 0x74, 0x63, 0x68, 0x5f, 0x70, 0x62, 0x32, 0x2f, 0x62, 0x61, 0x74, 0x63, 0x68, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x2a, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x70, 0x62, 0x32, 0x2f, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0x62, 0x0a, 0x0b, 0x42, 0x61, 0x74, 0x63, 0x68, 0x48, 0x65, 0x61, 0x64, 0x65, 0x72, 0x12, 0x2a, 0x0a, 0x11, 0x73, 0x69, 0x67, 0x6e, 0x65, 0x72, 0x5f, 0x70, 0x75, 0x62, 0x6c, 0x69, 0x63, 0x5f, 0x6b, 0x65, 0x79, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0f, 0x73, 0x69, 0x67, 0x6e, 0x65, 0x72, 0x50, 0x75, 0x62, 0x6c, 0x69, 0x63, 0x4b, 0x65, 0x79, 0x12, 0x27, 0x0a, 0x0f, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x69, 0x64, 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x09, 0x52, 0x0e, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x49, 0x64, 0x73, 0x22, 0x92, 0x01, 0x0a, 0x05, 0x42, 0x61, 0x74, 0x63, 0x68, 0x12, 0x16, 0x0a, 0x06, 0x68, 0x65, 0x61, 0x64, 0x65, 0x72, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x06, 0x68, 0x65, 0x61, 0x64, 0x65, 0x72, 0x12, 0x29, 0x0a, 0x10, 0x68, 0x65, 0x61, 0x64, 0x65, 0x72, 0x5f, 0x73, 0x69, 0x67, 0x6e, 0x61, 0x74, 0x75, 0x72, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0f, 0x68, 0x65, 0x61, 0x64, 0x65, 0x72, 0x53, 0x69, 0x67, 0x6e, 0x61, 0x74, 0x75, 0x72, 0x65, 0x12, 0x30, 0x0a, 0x0c, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x18, 0x03, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x0c, 0x2e, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x0c, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x12, 0x14, 0x0a, 0x05, 0x74, 0x72, 0x61, 0x63, 0x65, 0x18, 0x04, 0x20, 0x01, 0x28, 0x08, 0x52, 0x05, 0x74, 0x72, 0x61, 0x63, 0x65, 0x22, 0x2d, 0x0a, 0x09, 0x42, 0x61, 0x74, 0x63, 0x68, 0x4c, 0x69, 0x73, 0x74, 0x12, 0x20, 0x0a, 0x07, 0x62, 0x61, 0x74, 0x63, 0x68, 0x65, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x06, 0x2e, 0x42, 0x61, 0x74, 0x63, 0x68, 0x52, 0x07, 0x62, 0x61, 0x74, 0x63, 0x68, 0x65, 0x73, 0x42, 0x24, 0x0a, 0x15, 0x73, 0x61, 0x77, 0x74, 0x6f, 0x6f, 0x74, 0x68, 0x2e, 0x73, 0x64, 0x6b, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x50, 0x01, 0x5a, 0x09, 0x62, 0x61, 0x74, 0x63, 0x68, 0x5f, 0x70, 0x62, 0x32, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( file_protobuf_batch_pb2_batch_proto_rawDescOnce sync.Once file_protobuf_batch_pb2_batch_proto_rawDescData = file_protobuf_batch_pb2_batch_proto_rawDesc ) func file_protobuf_batch_pb2_batch_proto_rawDescGZIP() []byte { file_protobuf_batch_pb2_batch_proto_rawDescOnce.Do(func() { file_protobuf_batch_pb2_batch_proto_rawDescData = protoimpl.X.CompressGZIP(file_protobuf_batch_pb2_batch_proto_rawDescData) }) return file_protobuf_batch_pb2_batch_proto_rawDescData } var file_protobuf_batch_pb2_batch_proto_msgTypes = make([]protoimpl.MessageInfo, 3) var file_protobuf_batch_pb2_batch_proto_goTypes = []interface{}{ (*BatchHeader)(nil), // 0: BatchHeader (*Batch)(nil), // 1: Batch (*BatchList)(nil), // 2: BatchList (*transaction_pb2.Transaction)(nil), // 3: Transaction } var file_protobuf_batch_pb2_batch_proto_depIdxs = []int32{ 3, // 0: Batch.transactions:type_name -> Transaction 1, // 1: BatchList.batches:type_name -> Batch 2, // [2:2] is the sub-list for method output_type 2, // [2:2] is the sub-list for method input_type 2, // [2:2] is the sub-list for extension type_name 2, // [2:2] is the sub-list for extension extendee 0, // [0:2] is the sub-list for field type_name } func init() { file_protobuf_batch_pb2_batch_proto_init() } func file_protobuf_batch_pb2_batch_proto_init() { if File_protobuf_batch_pb2_batch_proto != nil { return } if !protoimpl.UnsafeEnabled { file_protobuf_batch_pb2_batch_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*BatchHeader); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_batch_pb2_batch_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*Batch); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_batch_pb2_batch_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*BatchList); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: file_protobuf_batch_pb2_batch_proto_rawDesc, NumEnums: 0, NumMessages: 3, NumExtensions: 0, NumServices: 0, }, GoTypes: file_protobuf_batch_pb2_batch_proto_goTypes, DependencyIndexes: file_protobuf_batch_pb2_batch_proto_depIdxs, MessageInfos: file_protobuf_batch_pb2_batch_proto_msgTypes, }.Build() File_protobuf_batch_pb2_batch_proto = out.File file_protobuf_batch_pb2_batch_proto_rawDesc = nil file_protobuf_batch_pb2_batch_proto_goTypes = nil file_protobuf_batch_pb2_batch_proto_depIdxs = nil } <|start_filename|>examples/intkey_go/src/sawtooth_intkey_client/main.go<|end_filename|> /** * Copyright 2018 Intel Corporation * * 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 main import ( "crypto/sha512" "encoding/hex" "fmt" "github.com/hyperledger/sawtooth-sdk-go/logging" flags "github.com/jessevdk/go-flags" "os" "os/user" "path" "strings" ) // All subcommands implement this interface type Command interface { Register(*flags.Command) error Name() string KeyfilePassed() string UrlPassed() string Run() error } type Opts struct { Verbose []bool `short:"v" long:"verbose" description:"Enable more verbose output"` Version bool `short:"V" long:"version" description:"Display version information"` } var DISTRIBUTION_VERSION string var logger *logging.Logger = logging.Get() func init() { if len(DISTRIBUTION_VERSION) == 0 { DISTRIBUTION_VERSION = "Unknown" } } func main() { arguments := os.Args[1:] for _, arg := range arguments { if arg == "-V" || arg == "--version" { fmt.Println(DISTRIBUTION_NAME + " (Hyperledger Sawtooth) version " + DISTRIBUTION_VERSION) os.Exit(0) } } var opts Opts parser := flags.NewParser(&opts, flags.Default) parser.Command.Name = "intkey" // Add sub-commands commands := []Command{ &Set{}, &Inc{}, &Dec{}, &Show{}, &List{}, } for _, cmd := range commands { err := cmd.Register(parser.Command) if err != nil { logger.Errorf("Couldn't register command %v: %v", cmd.Name(), err) os.Exit(1) } } remaining, err := parser.Parse() if e, ok := err.(*flags.Error); ok { if e.Type == flags.ErrHelp { return } else { os.Exit(1) } } if len(remaining) > 0 { fmt.Println("Error: Unrecognized arguments passed: ", remaining) os.Exit(2) } switch len(opts.Verbose) { case 2: logger.SetLevel(logging.DEBUG) case 1: logger.SetLevel(logging.INFO) default: logger.SetLevel(logging.WARN) } // If a sub-command was passed, run it if parser.Command.Active == nil { os.Exit(2) } name := parser.Command.Active.Name for _, cmd := range commands { if cmd.Name() == name { err := cmd.Run() if err != nil { fmt.Println("Error: ", err) os.Exit(1) } return } } fmt.Println("Error: Command not found: ", name) } func Sha512HashValue(value string) string { hashHandler := sha512.New() hashHandler.Write([]byte(value)) return strings.ToLower(hex.EncodeToString(hashHandler.Sum(nil))) } func GetClient(args Command, readFile bool) (IntkeyClient, error) { url := args.UrlPassed() if url == "" { url = DEFAULT_URL } keyfile := "" if readFile { var err error keyfile, err = GetKeyfile(args.KeyfilePassed()) if err != nil { return IntkeyClient{}, err } } return NewIntkeyClient(url, keyfile) } func GetKeyfile(keyfile string) (string, error) { if keyfile == "" { username, err := user.Current() if err != nil { return "", err } return path.Join( username.HomeDir, ".sawtooth", "keys", username.Username+".priv"), nil } else { return keyfile, nil } } <|start_filename|>protobuf/state_context_pb2/state_context.pb.go<|end_filename|> // Copyright 2016 Intel Corporation // // 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. // ----------------------------------------------------------------------------- // Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.25.0-devel // protoc v3.14.0 // source: protobuf/state_context_pb2/state_context.proto package state_context_pb2 import ( protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" events_pb2 "github.com/hyperledger/sawtooth-sdk-go/protobuf/events_pb2" reflect "reflect" sync "sync" ) const ( // Verify that this generated code is sufficiently up-to-date. _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) // Verify that runtime/protoimpl is sufficiently up-to-date. _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) type TpStateGetResponse_Status int32 const ( TpStateGetResponse_STATUS_UNSET TpStateGetResponse_Status = 0 TpStateGetResponse_OK TpStateGetResponse_Status = 1 TpStateGetResponse_AUTHORIZATION_ERROR TpStateGetResponse_Status = 2 ) // Enum value maps for TpStateGetResponse_Status. var ( TpStateGetResponse_Status_name = map[int32]string{ 0: "STATUS_UNSET", 1: "OK", 2: "AUTHORIZATION_ERROR", } TpStateGetResponse_Status_value = map[string]int32{ "STATUS_UNSET": 0, "OK": 1, "AUTHORIZATION_ERROR": 2, } ) func (x TpStateGetResponse_Status) Enum() *TpStateGetResponse_Status { p := new(TpStateGetResponse_Status) *p = x return p } func (x TpStateGetResponse_Status) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (TpStateGetResponse_Status) Descriptor() protoreflect.EnumDescriptor { return file_protobuf_state_context_pb2_state_context_proto_enumTypes[0].Descriptor() } func (TpStateGetResponse_Status) Type() protoreflect.EnumType { return &file_protobuf_state_context_pb2_state_context_proto_enumTypes[0] } func (x TpStateGetResponse_Status) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use TpStateGetResponse_Status.Descriptor instead. func (TpStateGetResponse_Status) EnumDescriptor() ([]byte, []int) { return file_protobuf_state_context_pb2_state_context_proto_rawDescGZIP(), []int{2, 0} } type TpStateSetResponse_Status int32 const ( TpStateSetResponse_STATUS_UNSET TpStateSetResponse_Status = 0 TpStateSetResponse_OK TpStateSetResponse_Status = 1 TpStateSetResponse_AUTHORIZATION_ERROR TpStateSetResponse_Status = 2 ) // Enum value maps for TpStateSetResponse_Status. var ( TpStateSetResponse_Status_name = map[int32]string{ 0: "STATUS_UNSET", 1: "OK", 2: "AUTHORIZATION_ERROR", } TpStateSetResponse_Status_value = map[string]int32{ "STATUS_UNSET": 0, "OK": 1, "AUTHORIZATION_ERROR": 2, } ) func (x TpStateSetResponse_Status) Enum() *TpStateSetResponse_Status { p := new(TpStateSetResponse_Status) *p = x return p } func (x TpStateSetResponse_Status) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (TpStateSetResponse_Status) Descriptor() protoreflect.EnumDescriptor { return file_protobuf_state_context_pb2_state_context_proto_enumTypes[1].Descriptor() } func (TpStateSetResponse_Status) Type() protoreflect.EnumType { return &file_protobuf_state_context_pb2_state_context_proto_enumTypes[1] } func (x TpStateSetResponse_Status) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use TpStateSetResponse_Status.Descriptor instead. func (TpStateSetResponse_Status) EnumDescriptor() ([]byte, []int) { return file_protobuf_state_context_pb2_state_context_proto_rawDescGZIP(), []int{4, 0} } type TpStateDeleteResponse_Status int32 const ( TpStateDeleteResponse_STATUS_UNSET TpStateDeleteResponse_Status = 0 TpStateDeleteResponse_OK TpStateDeleteResponse_Status = 1 TpStateDeleteResponse_AUTHORIZATION_ERROR TpStateDeleteResponse_Status = 2 ) // Enum value maps for TpStateDeleteResponse_Status. var ( TpStateDeleteResponse_Status_name = map[int32]string{ 0: "STATUS_UNSET", 1: "OK", 2: "AUTHORIZATION_ERROR", } TpStateDeleteResponse_Status_value = map[string]int32{ "STATUS_UNSET": 0, "OK": 1, "AUTHORIZATION_ERROR": 2, } ) func (x TpStateDeleteResponse_Status) Enum() *TpStateDeleteResponse_Status { p := new(TpStateDeleteResponse_Status) *p = x return p } func (x TpStateDeleteResponse_Status) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (TpStateDeleteResponse_Status) Descriptor() protoreflect.EnumDescriptor { return file_protobuf_state_context_pb2_state_context_proto_enumTypes[2].Descriptor() } func (TpStateDeleteResponse_Status) Type() protoreflect.EnumType { return &file_protobuf_state_context_pb2_state_context_proto_enumTypes[2] } func (x TpStateDeleteResponse_Status) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use TpStateDeleteResponse_Status.Descriptor instead. func (TpStateDeleteResponse_Status) EnumDescriptor() ([]byte, []int) { return file_protobuf_state_context_pb2_state_context_proto_rawDescGZIP(), []int{6, 0} } type TpReceiptAddDataResponse_Status int32 const ( TpReceiptAddDataResponse_STATUS_UNSET TpReceiptAddDataResponse_Status = 0 TpReceiptAddDataResponse_OK TpReceiptAddDataResponse_Status = 1 TpReceiptAddDataResponse_ERROR TpReceiptAddDataResponse_Status = 2 ) // Enum value maps for TpReceiptAddDataResponse_Status. var ( TpReceiptAddDataResponse_Status_name = map[int32]string{ 0: "STATUS_UNSET", 1: "OK", 2: "ERROR", } TpReceiptAddDataResponse_Status_value = map[string]int32{ "STATUS_UNSET": 0, "OK": 1, "ERROR": 2, } ) func (x TpReceiptAddDataResponse_Status) Enum() *TpReceiptAddDataResponse_Status { p := new(TpReceiptAddDataResponse_Status) *p = x return p } func (x TpReceiptAddDataResponse_Status) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (TpReceiptAddDataResponse_Status) Descriptor() protoreflect.EnumDescriptor { return file_protobuf_state_context_pb2_state_context_proto_enumTypes[3].Descriptor() } func (TpReceiptAddDataResponse_Status) Type() protoreflect.EnumType { return &file_protobuf_state_context_pb2_state_context_proto_enumTypes[3] } func (x TpReceiptAddDataResponse_Status) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use TpReceiptAddDataResponse_Status.Descriptor instead. func (TpReceiptAddDataResponse_Status) EnumDescriptor() ([]byte, []int) { return file_protobuf_state_context_pb2_state_context_proto_rawDescGZIP(), []int{8, 0} } type TpEventAddResponse_Status int32 const ( TpEventAddResponse_STATUS_UNSET TpEventAddResponse_Status = 0 TpEventAddResponse_OK TpEventAddResponse_Status = 1 TpEventAddResponse_ERROR TpEventAddResponse_Status = 2 ) // Enum value maps for TpEventAddResponse_Status. var ( TpEventAddResponse_Status_name = map[int32]string{ 0: "STATUS_UNSET", 1: "OK", 2: "ERROR", } TpEventAddResponse_Status_value = map[string]int32{ "STATUS_UNSET": 0, "OK": 1, "ERROR": 2, } ) func (x TpEventAddResponse_Status) Enum() *TpEventAddResponse_Status { p := new(TpEventAddResponse_Status) *p = x return p } func (x TpEventAddResponse_Status) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (TpEventAddResponse_Status) Descriptor() protoreflect.EnumDescriptor { return file_protobuf_state_context_pb2_state_context_proto_enumTypes[4].Descriptor() } func (TpEventAddResponse_Status) Type() protoreflect.EnumType { return &file_protobuf_state_context_pb2_state_context_proto_enumTypes[4] } func (x TpEventAddResponse_Status) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use TpEventAddResponse_Status.Descriptor instead. func (TpEventAddResponse_Status) EnumDescriptor() ([]byte, []int) { return file_protobuf_state_context_pb2_state_context_proto_rawDescGZIP(), []int{10, 0} } // An entry in the State type TpStateEntry struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Address string `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty"` Data []byte `protobuf:"bytes,2,opt,name=data,proto3" json:"data,omitempty"` } func (x *TpStateEntry) Reset() { *x = TpStateEntry{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_state_context_pb2_state_context_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *TpStateEntry) String() string { return protoimpl.X.MessageStringOf(x) } func (*TpStateEntry) ProtoMessage() {} func (x *TpStateEntry) ProtoReflect() protoreflect.Message { mi := &file_protobuf_state_context_pb2_state_context_proto_msgTypes[0] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use TpStateEntry.ProtoReflect.Descriptor instead. func (*TpStateEntry) Descriptor() ([]byte, []int) { return file_protobuf_state_context_pb2_state_context_proto_rawDescGZIP(), []int{0} } func (x *TpStateEntry) GetAddress() string { if x != nil { return x.Address } return "" } func (x *TpStateEntry) GetData() []byte { if x != nil { return x.Data } return nil } // A request from a handler/tp for the values at a series of addresses type TpStateGetRequest struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // The context id that references a context in the contextmanager ContextId string `protobuf:"bytes,1,opt,name=context_id,json=contextId,proto3" json:"context_id,omitempty"` Addresses []string `protobuf:"bytes,2,rep,name=addresses,proto3" json:"addresses,omitempty"` } func (x *TpStateGetRequest) Reset() { *x = TpStateGetRequest{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_state_context_pb2_state_context_proto_msgTypes[1] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *TpStateGetRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*TpStateGetRequest) ProtoMessage() {} func (x *TpStateGetRequest) ProtoReflect() protoreflect.Message { mi := &file_protobuf_state_context_pb2_state_context_proto_msgTypes[1] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use TpStateGetRequest.ProtoReflect.Descriptor instead. func (*TpStateGetRequest) Descriptor() ([]byte, []int) { return file_protobuf_state_context_pb2_state_context_proto_rawDescGZIP(), []int{1} } func (x *TpStateGetRequest) GetContextId() string { if x != nil { return x.ContextId } return "" } func (x *TpStateGetRequest) GetAddresses() []string { if x != nil { return x.Addresses } return nil } // A response from the contextmanager/validator with a series of State entries type TpStateGetResponse struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Entries []*TpStateEntry `protobuf:"bytes,1,rep,name=entries,proto3" json:"entries,omitempty"` Status TpStateGetResponse_Status `protobuf:"varint,2,opt,name=status,proto3,enum=TpStateGetResponse_Status" json:"status,omitempty"` } func (x *TpStateGetResponse) Reset() { *x = TpStateGetResponse{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_state_context_pb2_state_context_proto_msgTypes[2] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *TpStateGetResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*TpStateGetResponse) ProtoMessage() {} func (x *TpStateGetResponse) ProtoReflect() protoreflect.Message { mi := &file_protobuf_state_context_pb2_state_context_proto_msgTypes[2] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use TpStateGetResponse.ProtoReflect.Descriptor instead. func (*TpStateGetResponse) Descriptor() ([]byte, []int) { return file_protobuf_state_context_pb2_state_context_proto_rawDescGZIP(), []int{2} } func (x *TpStateGetResponse) GetEntries() []*TpStateEntry { if x != nil { return x.Entries } return nil } func (x *TpStateGetResponse) GetStatus() TpStateGetResponse_Status { if x != nil { return x.Status } return TpStateGetResponse_STATUS_UNSET } // A request from the handler/tp to put entries in the state of a context type TpStateSetRequest struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields ContextId string `protobuf:"bytes,1,opt,name=context_id,json=contextId,proto3" json:"context_id,omitempty"` Entries []*TpStateEntry `protobuf:"bytes,2,rep,name=entries,proto3" json:"entries,omitempty"` } func (x *TpStateSetRequest) Reset() { *x = TpStateSetRequest{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_state_context_pb2_state_context_proto_msgTypes[3] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *TpStateSetRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*TpStateSetRequest) ProtoMessage() {} func (x *TpStateSetRequest) ProtoReflect() protoreflect.Message { mi := &file_protobuf_state_context_pb2_state_context_proto_msgTypes[3] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use TpStateSetRequest.ProtoReflect.Descriptor instead. func (*TpStateSetRequest) Descriptor() ([]byte, []int) { return file_protobuf_state_context_pb2_state_context_proto_rawDescGZIP(), []int{3} } func (x *TpStateSetRequest) GetContextId() string { if x != nil { return x.ContextId } return "" } func (x *TpStateSetRequest) GetEntries() []*TpStateEntry { if x != nil { return x.Entries } return nil } // A response from the contextmanager/validator with the addresses that were set type TpStateSetResponse struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Addresses []string `protobuf:"bytes,1,rep,name=addresses,proto3" json:"addresses,omitempty"` Status TpStateSetResponse_Status `protobuf:"varint,2,opt,name=status,proto3,enum=TpStateSetResponse_Status" json:"status,omitempty"` } func (x *TpStateSetResponse) Reset() { *x = TpStateSetResponse{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_state_context_pb2_state_context_proto_msgTypes[4] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *TpStateSetResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*TpStateSetResponse) ProtoMessage() {} func (x *TpStateSetResponse) ProtoReflect() protoreflect.Message { mi := &file_protobuf_state_context_pb2_state_context_proto_msgTypes[4] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use TpStateSetResponse.ProtoReflect.Descriptor instead. func (*TpStateSetResponse) Descriptor() ([]byte, []int) { return file_protobuf_state_context_pb2_state_context_proto_rawDescGZIP(), []int{4} } func (x *TpStateSetResponse) GetAddresses() []string { if x != nil { return x.Addresses } return nil } func (x *TpStateSetResponse) GetStatus() TpStateSetResponse_Status { if x != nil { return x.Status } return TpStateSetResponse_STATUS_UNSET } // A request from the handler/tp to delete state entries at an collection of addresses type TpStateDeleteRequest struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields ContextId string `protobuf:"bytes,1,opt,name=context_id,json=contextId,proto3" json:"context_id,omitempty"` Addresses []string `protobuf:"bytes,2,rep,name=addresses,proto3" json:"addresses,omitempty"` } func (x *TpStateDeleteRequest) Reset() { *x = TpStateDeleteRequest{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_state_context_pb2_state_context_proto_msgTypes[5] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *TpStateDeleteRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*TpStateDeleteRequest) ProtoMessage() {} func (x *TpStateDeleteRequest) ProtoReflect() protoreflect.Message { mi := &file_protobuf_state_context_pb2_state_context_proto_msgTypes[5] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use TpStateDeleteRequest.ProtoReflect.Descriptor instead. func (*TpStateDeleteRequest) Descriptor() ([]byte, []int) { return file_protobuf_state_context_pb2_state_context_proto_rawDescGZIP(), []int{5} } func (x *TpStateDeleteRequest) GetContextId() string { if x != nil { return x.ContextId } return "" } func (x *TpStateDeleteRequest) GetAddresses() []string { if x != nil { return x.Addresses } return nil } // A response form the contextmanager/validator with the addresses that were deleted type TpStateDeleteResponse struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Addresses []string `protobuf:"bytes,1,rep,name=addresses,proto3" json:"addresses,omitempty"` Status TpStateDeleteResponse_Status `protobuf:"varint,2,opt,name=status,proto3,enum=TpStateDeleteResponse_Status" json:"status,omitempty"` } func (x *TpStateDeleteResponse) Reset() { *x = TpStateDeleteResponse{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_state_context_pb2_state_context_proto_msgTypes[6] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *TpStateDeleteResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*TpStateDeleteResponse) ProtoMessage() {} func (x *TpStateDeleteResponse) ProtoReflect() protoreflect.Message { mi := &file_protobuf_state_context_pb2_state_context_proto_msgTypes[6] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use TpStateDeleteResponse.ProtoReflect.Descriptor instead. func (*TpStateDeleteResponse) Descriptor() ([]byte, []int) { return file_protobuf_state_context_pb2_state_context_proto_rawDescGZIP(), []int{6} } func (x *TpStateDeleteResponse) GetAddresses() []string { if x != nil { return x.Addresses } return nil } func (x *TpStateDeleteResponse) GetStatus() TpStateDeleteResponse_Status { if x != nil { return x.Status } return TpStateDeleteResponse_STATUS_UNSET } // The request from the transaction processor to the validator append data // to a transaction receipt type TpReceiptAddDataRequest struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // The context id that references a context in the context manager ContextId string `protobuf:"bytes,1,opt,name=context_id,json=contextId,proto3" json:"context_id,omitempty"` Data []byte `protobuf:"bytes,3,opt,name=data,proto3" json:"data,omitempty"` } func (x *TpReceiptAddDataRequest) Reset() { *x = TpReceiptAddDataRequest{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_state_context_pb2_state_context_proto_msgTypes[7] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *TpReceiptAddDataRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*TpReceiptAddDataRequest) ProtoMessage() {} func (x *TpReceiptAddDataRequest) ProtoReflect() protoreflect.Message { mi := &file_protobuf_state_context_pb2_state_context_proto_msgTypes[7] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use TpReceiptAddDataRequest.ProtoReflect.Descriptor instead. func (*TpReceiptAddDataRequest) Descriptor() ([]byte, []int) { return file_protobuf_state_context_pb2_state_context_proto_rawDescGZIP(), []int{7} } func (x *TpReceiptAddDataRequest) GetContextId() string { if x != nil { return x.ContextId } return "" } func (x *TpReceiptAddDataRequest) GetData() []byte { if x != nil { return x.Data } return nil } // The response from the validator to the transaction processor to verify that // data has been appended to a transaction receipt type TpReceiptAddDataResponse struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Status TpReceiptAddDataResponse_Status `protobuf:"varint,2,opt,name=status,proto3,enum=TpReceiptAddDataResponse_Status" json:"status,omitempty"` } func (x *TpReceiptAddDataResponse) Reset() { *x = TpReceiptAddDataResponse{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_state_context_pb2_state_context_proto_msgTypes[8] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *TpReceiptAddDataResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*TpReceiptAddDataResponse) ProtoMessage() {} func (x *TpReceiptAddDataResponse) ProtoReflect() protoreflect.Message { mi := &file_protobuf_state_context_pb2_state_context_proto_msgTypes[8] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use TpReceiptAddDataResponse.ProtoReflect.Descriptor instead. func (*TpReceiptAddDataResponse) Descriptor() ([]byte, []int) { return file_protobuf_state_context_pb2_state_context_proto_rawDescGZIP(), []int{8} } func (x *TpReceiptAddDataResponse) GetStatus() TpReceiptAddDataResponse_Status { if x != nil { return x.Status } return TpReceiptAddDataResponse_STATUS_UNSET } type TpEventAddRequest struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields ContextId string `protobuf:"bytes,1,opt,name=context_id,json=contextId,proto3" json:"context_id,omitempty"` Event *events_pb2.Event `protobuf:"bytes,2,opt,name=event,proto3" json:"event,omitempty"` } func (x *TpEventAddRequest) Reset() { *x = TpEventAddRequest{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_state_context_pb2_state_context_proto_msgTypes[9] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *TpEventAddRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*TpEventAddRequest) ProtoMessage() {} func (x *TpEventAddRequest) ProtoReflect() protoreflect.Message { mi := &file_protobuf_state_context_pb2_state_context_proto_msgTypes[9] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use TpEventAddRequest.ProtoReflect.Descriptor instead. func (*TpEventAddRequest) Descriptor() ([]byte, []int) { return file_protobuf_state_context_pb2_state_context_proto_rawDescGZIP(), []int{9} } func (x *TpEventAddRequest) GetContextId() string { if x != nil { return x.ContextId } return "" } func (x *TpEventAddRequest) GetEvent() *events_pb2.Event { if x != nil { return x.Event } return nil } type TpEventAddResponse struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Status TpEventAddResponse_Status `protobuf:"varint,2,opt,name=status,proto3,enum=TpEventAddResponse_Status" json:"status,omitempty"` } func (x *TpEventAddResponse) Reset() { *x = TpEventAddResponse{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_state_context_pb2_state_context_proto_msgTypes[10] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *TpEventAddResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*TpEventAddResponse) ProtoMessage() {} func (x *TpEventAddResponse) ProtoReflect() protoreflect.Message { mi := &file_protobuf_state_context_pb2_state_context_proto_msgTypes[10] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use TpEventAddResponse.ProtoReflect.Descriptor instead. func (*TpEventAddResponse) Descriptor() ([]byte, []int) { return file_protobuf_state_context_pb2_state_context_proto_rawDescGZIP(), []int{10} } func (x *TpEventAddResponse) GetStatus() TpEventAddResponse_Status { if x != nil { return x.Status } return TpEventAddResponse_STATUS_UNSET } var File_protobuf_state_context_pb2_state_context_proto protoreflect.FileDescriptor var file_protobuf_state_context_pb2_state_context_proto_rawDesc = []byte{ 0x0a, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x73, 0x74, 0x61, 0x74, 0x65, 0x5f, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x78, 0x74, 0x5f, 0x70, 0x62, 0x32, 0x2f, 0x73, 0x74, 0x61, 0x74, 0x65, 0x5f, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x78, 0x74, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x20, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x65, 0x76, 0x65, 0x6e, 0x74, 0x73, 0x5f, 0x70, 0x62, 0x32, 0x2f, 0x65, 0x76, 0x65, 0x6e, 0x74, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0x3c, 0x0a, 0x0c, 0x54, 0x70, 0x53, 0x74, 0x61, 0x74, 0x65, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x12, 0x18, 0x0a, 0x07, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x12, 0x12, 0x0a, 0x04, 0x64, 0x61, 0x74, 0x61, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x04, 0x64, 0x61, 0x74, 0x61, 0x22, 0x50, 0x0a, 0x11, 0x54, 0x70, 0x53, 0x74, 0x61, 0x74, 0x65, 0x47, 0x65, 0x74, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x1d, 0x0a, 0x0a, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x78, 0x74, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x78, 0x74, 0x49, 0x64, 0x12, 0x1c, 0x0a, 0x09, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x65, 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x09, 0x52, 0x09, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x65, 0x73, 0x22, 0xae, 0x01, 0x0a, 0x12, 0x54, 0x70, 0x53, 0x74, 0x61, 0x74, 0x65, 0x47, 0x65, 0x74, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x27, 0x0a, 0x07, 0x65, 0x6e, 0x74, 0x72, 0x69, 0x65, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x0d, 0x2e, 0x54, 0x70, 0x53, 0x74, 0x61, 0x74, 0x65, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x52, 0x07, 0x65, 0x6e, 0x74, 0x72, 0x69, 0x65, 0x73, 0x12, 0x32, 0x0a, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x1a, 0x2e, 0x54, 0x70, 0x53, 0x74, 0x61, 0x74, 0x65, 0x47, 0x65, 0x74, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x2e, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x52, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x22, 0x3b, 0x0a, 0x06, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, 0x10, 0x0a, 0x0c, 0x53, 0x54, 0x41, 0x54, 0x55, 0x53, 0x5f, 0x55, 0x4e, 0x53, 0x45, 0x54, 0x10, 0x00, 0x12, 0x06, 0x0a, 0x02, 0x4f, 0x4b, 0x10, 0x01, 0x12, 0x17, 0x0a, 0x13, 0x41, 0x55, 0x54, 0x48, 0x4f, 0x52, 0x49, 0x5a, 0x41, 0x54, 0x49, 0x4f, 0x4e, 0x5f, 0x45, 0x52, 0x52, 0x4f, 0x52, 0x10, 0x02, 0x22, 0x5b, 0x0a, 0x11, 0x54, 0x70, 0x53, 0x74, 0x61, 0x74, 0x65, 0x53, 0x65, 0x74, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x1d, 0x0a, 0x0a, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x78, 0x74, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x78, 0x74, 0x49, 0x64, 0x12, 0x27, 0x0a, 0x07, 0x65, 0x6e, 0x74, 0x72, 0x69, 0x65, 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x0d, 0x2e, 0x54, 0x70, 0x53, 0x74, 0x61, 0x74, 0x65, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x52, 0x07, 0x65, 0x6e, 0x74, 0x72, 0x69, 0x65, 0x73, 0x22, 0xa3, 0x01, 0x0a, 0x12, 0x54, 0x70, 0x53, 0x74, 0x61, 0x74, 0x65, 0x53, 0x65, 0x74, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x1c, 0x0a, 0x09, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x65, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x09, 0x52, 0x09, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x65, 0x73, 0x12, 0x32, 0x0a, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x1a, 0x2e, 0x54, 0x70, 0x53, 0x74, 0x61, 0x74, 0x65, 0x53, 0x65, 0x74, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x2e, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x52, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x22, 0x3b, 0x0a, 0x06, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, 0x10, 0x0a, 0x0c, 0x53, 0x54, 0x41, 0x54, 0x55, 0x53, 0x5f, 0x55, 0x4e, 0x53, 0x45, 0x54, 0x10, 0x00, 0x12, 0x06, 0x0a, 0x02, 0x4f, 0x4b, 0x10, 0x01, 0x12, 0x17, 0x0a, 0x13, 0x41, 0x55, 0x54, 0x48, 0x4f, 0x52, 0x49, 0x5a, 0x41, 0x54, 0x49, 0x4f, 0x4e, 0x5f, 0x45, 0x52, 0x52, 0x4f, 0x52, 0x10, 0x02, 0x22, 0x53, 0x0a, 0x14, 0x54, 0x70, 0x53, 0x74, 0x61, 0x74, 0x65, 0x44, 0x65, 0x6c, 0x65, 0x74, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x1d, 0x0a, 0x0a, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x78, 0x74, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x78, 0x74, 0x49, 0x64, 0x12, 0x1c, 0x0a, 0x09, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x65, 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x09, 0x52, 0x09, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x65, 0x73, 0x22, 0xa9, 0x01, 0x0a, 0x15, 0x54, 0x70, 0x53, 0x74, 0x61, 0x74, 0x65, 0x44, 0x65, 0x6c, 0x65, 0x74, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x1c, 0x0a, 0x09, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x65, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x09, 0x52, 0x09, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x65, 0x73, 0x12, 0x35, 0x0a, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x1d, 0x2e, 0x54, 0x70, 0x53, 0x74, 0x61, 0x74, 0x65, 0x44, 0x65, 0x6c, 0x65, 0x74, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x2e, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x52, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x22, 0x3b, 0x0a, 0x06, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, 0x10, 0x0a, 0x0c, 0x53, 0x54, 0x41, 0x54, 0x55, 0x53, 0x5f, 0x55, 0x4e, 0x53, 0x45, 0x54, 0x10, 0x00, 0x12, 0x06, 0x0a, 0x02, 0x4f, 0x4b, 0x10, 0x01, 0x12, 0x17, 0x0a, 0x13, 0x41, 0x55, 0x54, 0x48, 0x4f, 0x52, 0x49, 0x5a, 0x41, 0x54, 0x49, 0x4f, 0x4e, 0x5f, 0x45, 0x52, 0x52, 0x4f, 0x52, 0x10, 0x02, 0x22, 0x4c, 0x0a, 0x17, 0x54, 0x70, 0x52, 0x65, 0x63, 0x65, 0x69, 0x70, 0x74, 0x41, 0x64, 0x64, 0x44, 0x61, 0x74, 0x61, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x1d, 0x0a, 0x0a, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x78, 0x74, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x78, 0x74, 0x49, 0x64, 0x12, 0x12, 0x0a, 0x04, 0x64, 0x61, 0x74, 0x61, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x04, 0x64, 0x61, 0x74, 0x61, 0x22, 0x83, 0x01, 0x0a, 0x18, 0x54, 0x70, 0x52, 0x65, 0x63, 0x65, 0x69, 0x70, 0x74, 0x41, 0x64, 0x64, 0x44, 0x61, 0x74, 0x61, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x38, 0x0a, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x20, 0x2e, 0x54, 0x70, 0x52, 0x65, 0x63, 0x65, 0x69, 0x70, 0x74, 0x41, 0x64, 0x64, 0x44, 0x61, 0x74, 0x61, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x2e, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x52, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x22, 0x2d, 0x0a, 0x06, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, 0x10, 0x0a, 0x0c, 0x53, 0x54, 0x41, 0x54, 0x55, 0x53, 0x5f, 0x55, 0x4e, 0x53, 0x45, 0x54, 0x10, 0x00, 0x12, 0x06, 0x0a, 0x02, 0x4f, 0x4b, 0x10, 0x01, 0x12, 0x09, 0x0a, 0x05, 0x45, 0x52, 0x52, 0x4f, 0x52, 0x10, 0x02, 0x22, 0x50, 0x0a, 0x11, 0x54, 0x70, 0x45, 0x76, 0x65, 0x6e, 0x74, 0x41, 0x64, 0x64, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x1d, 0x0a, 0x0a, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x78, 0x74, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x78, 0x74, 0x49, 0x64, 0x12, 0x1c, 0x0a, 0x05, 0x65, 0x76, 0x65, 0x6e, 0x74, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x06, 0x2e, 0x45, 0x76, 0x65, 0x6e, 0x74, 0x52, 0x05, 0x65, 0x76, 0x65, 0x6e, 0x74, 0x22, 0x77, 0x0a, 0x12, 0x54, 0x70, 0x45, 0x76, 0x65, 0x6e, 0x74, 0x41, 0x64, 0x64, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x32, 0x0a, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x1a, 0x2e, 0x54, 0x70, 0x45, 0x76, 0x65, 0x6e, 0x74, 0x41, 0x64, 0x64, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x2e, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x52, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x22, 0x2d, 0x0a, 0x06, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, 0x10, 0x0a, 0x0c, 0x53, 0x54, 0x41, 0x54, 0x55, 0x53, 0x5f, 0x55, 0x4e, 0x53, 0x45, 0x54, 0x10, 0x00, 0x12, 0x06, 0x0a, 0x02, 0x4f, 0x4b, 0x10, 0x01, 0x12, 0x09, 0x0a, 0x05, 0x45, 0x52, 0x52, 0x4f, 0x52, 0x10, 0x02, 0x42, 0x2c, 0x0a, 0x15, 0x73, 0x61, 0x77, 0x74, 0x6f, 0x6f, 0x74, 0x68, 0x2e, 0x73, 0x64, 0x6b, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x50, 0x01, 0x5a, 0x11, 0x73, 0x74, 0x61, 0x74, 0x65, 0x5f, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x78, 0x74, 0x5f, 0x70, 0x62, 0x32, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( file_protobuf_state_context_pb2_state_context_proto_rawDescOnce sync.Once file_protobuf_state_context_pb2_state_context_proto_rawDescData = file_protobuf_state_context_pb2_state_context_proto_rawDesc ) func file_protobuf_state_context_pb2_state_context_proto_rawDescGZIP() []byte { file_protobuf_state_context_pb2_state_context_proto_rawDescOnce.Do(func() { file_protobuf_state_context_pb2_state_context_proto_rawDescData = protoimpl.X.CompressGZIP(file_protobuf_state_context_pb2_state_context_proto_rawDescData) }) return file_protobuf_state_context_pb2_state_context_proto_rawDescData } var file_protobuf_state_context_pb2_state_context_proto_enumTypes = make([]protoimpl.EnumInfo, 5) var file_protobuf_state_context_pb2_state_context_proto_msgTypes = make([]protoimpl.MessageInfo, 11) var file_protobuf_state_context_pb2_state_context_proto_goTypes = []interface{}{ (TpStateGetResponse_Status)(0), // 0: TpStateGetResponse.Status (TpStateSetResponse_Status)(0), // 1: TpStateSetResponse.Status (TpStateDeleteResponse_Status)(0), // 2: TpStateDeleteResponse.Status (TpReceiptAddDataResponse_Status)(0), // 3: TpReceiptAddDataResponse.Status (TpEventAddResponse_Status)(0), // 4: TpEventAddResponse.Status (*TpStateEntry)(nil), // 5: TpStateEntry (*TpStateGetRequest)(nil), // 6: TpStateGetRequest (*TpStateGetResponse)(nil), // 7: TpStateGetResponse (*TpStateSetRequest)(nil), // 8: TpStateSetRequest (*TpStateSetResponse)(nil), // 9: TpStateSetResponse (*TpStateDeleteRequest)(nil), // 10: TpStateDeleteRequest (*TpStateDeleteResponse)(nil), // 11: TpStateDeleteResponse (*TpReceiptAddDataRequest)(nil), // 12: TpReceiptAddDataRequest (*TpReceiptAddDataResponse)(nil), // 13: TpReceiptAddDataResponse (*TpEventAddRequest)(nil), // 14: TpEventAddRequest (*TpEventAddResponse)(nil), // 15: TpEventAddResponse (*events_pb2.Event)(nil), // 16: Event } var file_protobuf_state_context_pb2_state_context_proto_depIdxs = []int32{ 5, // 0: TpStateGetResponse.entries:type_name -> TpStateEntry 0, // 1: TpStateGetResponse.status:type_name -> TpStateGetResponse.Status 5, // 2: TpStateSetRequest.entries:type_name -> TpStateEntry 1, // 3: TpStateSetResponse.status:type_name -> TpStateSetResponse.Status 2, // 4: TpStateDeleteResponse.status:type_name -> TpStateDeleteResponse.Status 3, // 5: TpReceiptAddDataResponse.status:type_name -> TpReceiptAddDataResponse.Status 16, // 6: TpEventAddRequest.event:type_name -> Event 4, // 7: TpEventAddResponse.status:type_name -> TpEventAddResponse.Status 8, // [8:8] is the sub-list for method output_type 8, // [8:8] is the sub-list for method input_type 8, // [8:8] is the sub-list for extension type_name 8, // [8:8] is the sub-list for extension extendee 0, // [0:8] is the sub-list for field type_name } func init() { file_protobuf_state_context_pb2_state_context_proto_init() } func file_protobuf_state_context_pb2_state_context_proto_init() { if File_protobuf_state_context_pb2_state_context_proto != nil { return } if !protoimpl.UnsafeEnabled { file_protobuf_state_context_pb2_state_context_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*TpStateEntry); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_state_context_pb2_state_context_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*TpStateGetRequest); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_state_context_pb2_state_context_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*TpStateGetResponse); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_state_context_pb2_state_context_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*TpStateSetRequest); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_state_context_pb2_state_context_proto_msgTypes[4].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*TpStateSetResponse); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_state_context_pb2_state_context_proto_msgTypes[5].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*TpStateDeleteRequest); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_state_context_pb2_state_context_proto_msgTypes[6].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*TpStateDeleteResponse); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_state_context_pb2_state_context_proto_msgTypes[7].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*TpReceiptAddDataRequest); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_state_context_pb2_state_context_proto_msgTypes[8].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*TpReceiptAddDataResponse); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_state_context_pb2_state_context_proto_msgTypes[9].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*TpEventAddRequest); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_state_context_pb2_state_context_proto_msgTypes[10].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*TpEventAddResponse); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: file_protobuf_state_context_pb2_state_context_proto_rawDesc, NumEnums: 5, NumMessages: 11, NumExtensions: 0, NumServices: 0, }, GoTypes: file_protobuf_state_context_pb2_state_context_proto_goTypes, DependencyIndexes: file_protobuf_state_context_pb2_state_context_proto_depIdxs, EnumInfos: file_protobuf_state_context_pb2_state_context_proto_enumTypes, MessageInfos: file_protobuf_state_context_pb2_state_context_proto_msgTypes, }.Build() File_protobuf_state_context_pb2_state_context_proto = out.File file_protobuf_state_context_pb2_state_context_proto_rawDesc = nil file_protobuf_state_context_pb2_state_context_proto_goTypes = nil file_protobuf_state_context_pb2_state_context_proto_depIdxs = nil } <|start_filename|>mocks/mock_messaging/connection.go<|end_filename|> // Code generated by MockGen. DO NOT EDIT. // Source: connection.go // Package mock_messaging is a generated GoMock package. package mock_messaging import ( reflect "reflect" gomock "github.com/golang/mock/gomock" validator_pb2 "github.com/hyperledger/sawtooth-sdk-go/protobuf/validator_pb2" zmq4 "github.com/pebbe/zmq4" ) // MockConnection is a mock of Connection interface. type MockConnection struct { ctrl *gomock.Controller recorder *MockConnectionMockRecorder } // MockConnectionMockRecorder is the mock recorder for MockConnection. type MockConnectionMockRecorder struct { mock *MockConnection } // NewMockConnection creates a new mock instance. func NewMockConnection(ctrl *gomock.Controller) *MockConnection { mock := &MockConnection{ctrl: ctrl} mock.recorder = &MockConnectionMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockConnection) EXPECT() *MockConnectionMockRecorder { return m.recorder } // Close mocks base method. func (m *MockConnection) Close() { m.ctrl.T.Helper() m.ctrl.Call(m, "Close") } // Close indicates an expected call of Close. func (mr *MockConnectionMockRecorder) Close() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Close", reflect.TypeOf((*MockConnection)(nil).Close)) } // Identity mocks base method. func (m *MockConnection) Identity() string { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Identity") ret0, _ := ret[0].(string) return ret0 } // Identity indicates an expected call of Identity. func (mr *MockConnectionMockRecorder) Identity() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Identity", reflect.TypeOf((*MockConnection)(nil).Identity)) } // Monitor mocks base method. func (m *MockConnection) Monitor(arg0 zmq4.Event) (*zmq4.Socket, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Monitor", arg0) ret0, _ := ret[0].(*zmq4.Socket) ret1, _ := ret[1].(error) return ret0, ret1 } // Monitor indicates an expected call of Monitor. func (mr *MockConnectionMockRecorder) Monitor(arg0 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Monitor", reflect.TypeOf((*MockConnection)(nil).Monitor), arg0) } // RecvData mocks base method. func (m *MockConnection) RecvData() (string, []byte, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "RecvData") ret0, _ := ret[0].(string) ret1, _ := ret[1].([]byte) ret2, _ := ret[2].(error) return ret0, ret1, ret2 } // RecvData indicates an expected call of RecvData. func (mr *MockConnectionMockRecorder) RecvData() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RecvData", reflect.TypeOf((*MockConnection)(nil).RecvData)) } // RecvMsg mocks base method. func (m *MockConnection) RecvMsg() (string, *validator_pb2.Message, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "RecvMsg") ret0, _ := ret[0].(string) ret1, _ := ret[1].(*validator_pb2.Message) ret2, _ := ret[2].(error) return ret0, ret1, ret2 } // RecvMsg indicates an expected call of RecvMsg. func (mr *MockConnectionMockRecorder) RecvMsg() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RecvMsg", reflect.TypeOf((*MockConnection)(nil).RecvMsg)) } // RecvMsgWithId mocks base method. func (m *MockConnection) RecvMsgWithId(corrId string) (string, *validator_pb2.Message, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "RecvMsgWithId", corrId) ret0, _ := ret[0].(string) ret1, _ := ret[1].(*validator_pb2.Message) ret2, _ := ret[2].(error) return ret0, ret1, ret2 } // RecvMsgWithId indicates an expected call of RecvMsgWithId. func (mr *MockConnectionMockRecorder) RecvMsgWithId(corrId interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RecvMsgWithId", reflect.TypeOf((*MockConnection)(nil).RecvMsgWithId), corrId) } // SendData mocks base method. func (m *MockConnection) SendData(id string, data []byte) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "SendData", id, data) ret0, _ := ret[0].(error) return ret0 } // SendData indicates an expected call of SendData. func (mr *MockConnectionMockRecorder) SendData(id, data interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SendData", reflect.TypeOf((*MockConnection)(nil).SendData), id, data) } // SendMsg mocks base method. func (m *MockConnection) SendMsg(t validator_pb2.Message_MessageType, c []byte, corrId string) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "SendMsg", t, c, corrId) ret0, _ := ret[0].(error) return ret0 } // SendMsg indicates an expected call of SendMsg. func (mr *MockConnectionMockRecorder) SendMsg(t, c, corrId interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SendMsg", reflect.TypeOf((*MockConnection)(nil).SendMsg), t, c, corrId) } // SendMsgTo mocks base method. func (m *MockConnection) SendMsgTo(id string, t validator_pb2.Message_MessageType, c []byte, corrId string) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "SendMsgTo", id, t, c, corrId) ret0, _ := ret[0].(error) return ret0 } // SendMsgTo indicates an expected call of SendMsgTo. func (mr *MockConnectionMockRecorder) SendMsgTo(id, t, c, corrId interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SendMsgTo", reflect.TypeOf((*MockConnection)(nil).SendMsgTo), id, t, c, corrId) } // SendNewMsg mocks base method. func (m *MockConnection) SendNewMsg(t validator_pb2.Message_MessageType, c []byte) (string, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "SendNewMsg", t, c) ret0, _ := ret[0].(string) ret1, _ := ret[1].(error) return ret0, ret1 } // SendNewMsg indicates an expected call of SendNewMsg. func (mr *MockConnectionMockRecorder) SendNewMsg(t, c interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SendNewMsg", reflect.TypeOf((*MockConnection)(nil).SendNewMsg), t, c) } // SendNewMsgTo mocks base method. func (m *MockConnection) SendNewMsgTo(id string, t validator_pb2.Message_MessageType, c []byte) (string, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "SendNewMsgTo", id, t, c) ret0, _ := ret[0].(string) ret1, _ := ret[1].(error) return ret0, ret1 } // SendNewMsgTo indicates an expected call of SendNewMsgTo. func (mr *MockConnectionMockRecorder) SendNewMsgTo(id, t, c interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SendNewMsgTo", reflect.TypeOf((*MockConnection)(nil).SendNewMsgTo), id, t, c) } // Socket mocks base method. func (m *MockConnection) Socket() *zmq4.Socket { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Socket") ret0, _ := ret[0].(*zmq4.Socket) return ret0 } // Socket indicates an expected call of Socket. func (mr *MockConnectionMockRecorder) Socket() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Socket", reflect.TypeOf((*MockConnection)(nil).Socket)) } <|start_filename|>protobuf/events_pb2/events.pb.go<|end_filename|> // Copyright 2017 Intel Corporation // // 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. // ----------------------------------------------------------------------------- // Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.25.0-devel // protoc v3.14.0 // source: protobuf/events_pb2/events.proto package events_pb2 import ( protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" sync "sync" ) const ( // Verify that this generated code is sufficiently up-to-date. _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) // Verify that runtime/protoimpl is sufficiently up-to-date. _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) type EventFilter_FilterType int32 const ( EventFilter_FILTER_TYPE_UNSET EventFilter_FilterType = 0 EventFilter_SIMPLE_ANY EventFilter_FilterType = 1 EventFilter_SIMPLE_ALL EventFilter_FilterType = 2 EventFilter_REGEX_ANY EventFilter_FilterType = 3 EventFilter_REGEX_ALL EventFilter_FilterType = 4 ) // Enum value maps for EventFilter_FilterType. var ( EventFilter_FilterType_name = map[int32]string{ 0: "FILTER_TYPE_UNSET", 1: "SIMPLE_ANY", 2: "SIMPLE_ALL", 3: "REGEX_ANY", 4: "REGEX_ALL", } EventFilter_FilterType_value = map[string]int32{ "FILTER_TYPE_UNSET": 0, "SIMPLE_ANY": 1, "SIMPLE_ALL": 2, "REGEX_ANY": 3, "REGEX_ALL": 4, } ) func (x EventFilter_FilterType) Enum() *EventFilter_FilterType { p := new(EventFilter_FilterType) *p = x return p } func (x EventFilter_FilterType) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (EventFilter_FilterType) Descriptor() protoreflect.EnumDescriptor { return file_protobuf_events_pb2_events_proto_enumTypes[0].Descriptor() } func (EventFilter_FilterType) Type() protoreflect.EnumType { return &file_protobuf_events_pb2_events_proto_enumTypes[0] } func (x EventFilter_FilterType) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use EventFilter_FilterType.Descriptor instead. func (EventFilter_FilterType) EnumDescriptor() ([]byte, []int) { return file_protobuf_events_pb2_events_proto_rawDescGZIP(), []int{2, 0} } type Event struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // Used to subscribe to events and servers as a hint for how to deserialize // event_data and what pairs to expect in attributes. EventType string `protobuf:"bytes,1,opt,name=event_type,json=eventType,proto3" json:"event_type,omitempty"` Attributes []*Event_Attribute `protobuf:"bytes,2,rep,name=attributes,proto3" json:"attributes,omitempty"` // Opaque data defined by the event_type. Data []byte `protobuf:"bytes,3,opt,name=data,proto3" json:"data,omitempty"` } func (x *Event) Reset() { *x = Event{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_events_pb2_events_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *Event) String() string { return protoimpl.X.MessageStringOf(x) } func (*Event) ProtoMessage() {} func (x *Event) ProtoReflect() protoreflect.Message { mi := &file_protobuf_events_pb2_events_proto_msgTypes[0] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use Event.ProtoReflect.Descriptor instead. func (*Event) Descriptor() ([]byte, []int) { return file_protobuf_events_pb2_events_proto_rawDescGZIP(), []int{0} } func (x *Event) GetEventType() string { if x != nil { return x.EventType } return "" } func (x *Event) GetAttributes() []*Event_Attribute { if x != nil { return x.Attributes } return nil } func (x *Event) GetData() []byte { if x != nil { return x.Data } return nil } type EventList struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Events []*Event `protobuf:"bytes,1,rep,name=events,proto3" json:"events,omitempty"` } func (x *EventList) Reset() { *x = EventList{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_events_pb2_events_proto_msgTypes[1] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *EventList) String() string { return protoimpl.X.MessageStringOf(x) } func (*EventList) ProtoMessage() {} func (x *EventList) ProtoReflect() protoreflect.Message { mi := &file_protobuf_events_pb2_events_proto_msgTypes[1] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use EventList.ProtoReflect.Descriptor instead. func (*EventList) Descriptor() ([]byte, []int) { return file_protobuf_events_pb2_events_proto_rawDescGZIP(), []int{1} } func (x *EventList) GetEvents() []*Event { if x != nil { return x.Events } return nil } type EventFilter struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // EventFilter is used when subscribing to events to limit the events // received within a given event type. See // validator/server/events/subscription.py for further explanation. Key string `protobuf:"bytes,1,opt,name=key,proto3" json:"key,omitempty"` MatchString string `protobuf:"bytes,2,opt,name=match_string,json=matchString,proto3" json:"match_string,omitempty"` FilterType EventFilter_FilterType `protobuf:"varint,3,opt,name=filter_type,json=filterType,proto3,enum=EventFilter_FilterType" json:"filter_type,omitempty"` } func (x *EventFilter) Reset() { *x = EventFilter{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_events_pb2_events_proto_msgTypes[2] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *EventFilter) String() string { return protoimpl.X.MessageStringOf(x) } func (*EventFilter) ProtoMessage() {} func (x *EventFilter) ProtoReflect() protoreflect.Message { mi := &file_protobuf_events_pb2_events_proto_msgTypes[2] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use EventFilter.ProtoReflect.Descriptor instead. func (*EventFilter) Descriptor() ([]byte, []int) { return file_protobuf_events_pb2_events_proto_rawDescGZIP(), []int{2} } func (x *EventFilter) GetKey() string { if x != nil { return x.Key } return "" } func (x *EventFilter) GetMatchString() string { if x != nil { return x.MatchString } return "" } func (x *EventFilter) GetFilterType() EventFilter_FilterType { if x != nil { return x.FilterType } return EventFilter_FILTER_TYPE_UNSET } type EventSubscription struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // EventSubscription is used when subscribing to events to specify the type // of events being subscribed to, along with any additional filters. See // validator/server/events/subscription.py for further explanation. EventType string `protobuf:"bytes,1,opt,name=event_type,json=eventType,proto3" json:"event_type,omitempty"` Filters []*EventFilter `protobuf:"bytes,2,rep,name=filters,proto3" json:"filters,omitempty"` } func (x *EventSubscription) Reset() { *x = EventSubscription{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_events_pb2_events_proto_msgTypes[3] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *EventSubscription) String() string { return protoimpl.X.MessageStringOf(x) } func (*EventSubscription) ProtoMessage() {} func (x *EventSubscription) ProtoReflect() protoreflect.Message { mi := &file_protobuf_events_pb2_events_proto_msgTypes[3] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use EventSubscription.ProtoReflect.Descriptor instead. func (*EventSubscription) Descriptor() ([]byte, []int) { return file_protobuf_events_pb2_events_proto_rawDescGZIP(), []int{3} } func (x *EventSubscription) GetEventType() string { if x != nil { return x.EventType } return "" } func (x *EventSubscription) GetFilters() []*EventFilter { if x != nil { return x.Filters } return nil } // Transparent data defined by the event_type. type Event_Attribute struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Key string `protobuf:"bytes,1,opt,name=key,proto3" json:"key,omitempty"` Value string `protobuf:"bytes,2,opt,name=value,proto3" json:"value,omitempty"` } func (x *Event_Attribute) Reset() { *x = Event_Attribute{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_events_pb2_events_proto_msgTypes[4] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *Event_Attribute) String() string { return protoimpl.X.MessageStringOf(x) } func (*Event_Attribute) ProtoMessage() {} func (x *Event_Attribute) ProtoReflect() protoreflect.Message { mi := &file_protobuf_events_pb2_events_proto_msgTypes[4] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use Event_Attribute.ProtoReflect.Descriptor instead. func (*Event_Attribute) Descriptor() ([]byte, []int) { return file_protobuf_events_pb2_events_proto_rawDescGZIP(), []int{0, 0} } func (x *Event_Attribute) GetKey() string { if x != nil { return x.Key } return "" } func (x *Event_Attribute) GetValue() string { if x != nil { return x.Value } return "" } var File_protobuf_events_pb2_events_proto protoreflect.FileDescriptor var file_protobuf_events_pb2_events_proto_rawDesc = []byte{ 0x0a, 0x20, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x65, 0x76, 0x65, 0x6e, 0x74, 0x73, 0x5f, 0x70, 0x62, 0x32, 0x2f, 0x65, 0x76, 0x65, 0x6e, 0x74, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0xa1, 0x01, 0x0a, 0x05, 0x45, 0x76, 0x65, 0x6e, 0x74, 0x12, 0x1d, 0x0a, 0x0a, 0x65, 0x76, 0x65, 0x6e, 0x74, 0x5f, 0x74, 0x79, 0x70, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, 0x65, 0x76, 0x65, 0x6e, 0x74, 0x54, 0x79, 0x70, 0x65, 0x12, 0x30, 0x0a, 0x0a, 0x61, 0x74, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x65, 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x10, 0x2e, 0x45, 0x76, 0x65, 0x6e, 0x74, 0x2e, 0x41, 0x74, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x65, 0x52, 0x0a, 0x61, 0x74, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x65, 0x73, 0x12, 0x12, 0x0a, 0x04, 0x64, 0x61, 0x74, 0x61, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x04, 0x64, 0x61, 0x74, 0x61, 0x1a, 0x33, 0x0a, 0x09, 0x41, 0x74, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x65, 0x12, 0x10, 0x0a, 0x03, 0x6b, 0x65, 0x79, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x6b, 0x65, 0x79, 0x12, 0x14, 0x0a, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x22, 0x2b, 0x0a, 0x09, 0x45, 0x76, 0x65, 0x6e, 0x74, 0x4c, 0x69, 0x73, 0x74, 0x12, 0x1e, 0x0a, 0x06, 0x65, 0x76, 0x65, 0x6e, 0x74, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x06, 0x2e, 0x45, 0x76, 0x65, 0x6e, 0x74, 0x52, 0x06, 0x65, 0x76, 0x65, 0x6e, 0x74, 0x73, 0x22, 0xdf, 0x01, 0x0a, 0x0b, 0x45, 0x76, 0x65, 0x6e, 0x74, 0x46, 0x69, 0x6c, 0x74, 0x65, 0x72, 0x12, 0x10, 0x0a, 0x03, 0x6b, 0x65, 0x79, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x6b, 0x65, 0x79, 0x12, 0x21, 0x0a, 0x0c, 0x6d, 0x61, 0x74, 0x63, 0x68, 0x5f, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0b, 0x6d, 0x61, 0x74, 0x63, 0x68, 0x53, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x12, 0x38, 0x0a, 0x0b, 0x66, 0x69, 0x6c, 0x74, 0x65, 0x72, 0x5f, 0x74, 0x79, 0x70, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x17, 0x2e, 0x45, 0x76, 0x65, 0x6e, 0x74, 0x46, 0x69, 0x6c, 0x74, 0x65, 0x72, 0x2e, 0x46, 0x69, 0x6c, 0x74, 0x65, 0x72, 0x54, 0x79, 0x70, 0x65, 0x52, 0x0a, 0x66, 0x69, 0x6c, 0x74, 0x65, 0x72, 0x54, 0x79, 0x70, 0x65, 0x22, 0x61, 0x0a, 0x0a, 0x46, 0x69, 0x6c, 0x74, 0x65, 0x72, 0x54, 0x79, 0x70, 0x65, 0x12, 0x15, 0x0a, 0x11, 0x46, 0x49, 0x4c, 0x54, 0x45, 0x52, 0x5f, 0x54, 0x59, 0x50, 0x45, 0x5f, 0x55, 0x4e, 0x53, 0x45, 0x54, 0x10, 0x00, 0x12, 0x0e, 0x0a, 0x0a, 0x53, 0x49, 0x4d, 0x50, 0x4c, 0x45, 0x5f, 0x41, 0x4e, 0x59, 0x10, 0x01, 0x12, 0x0e, 0x0a, 0x0a, 0x53, 0x49, 0x4d, 0x50, 0x4c, 0x45, 0x5f, 0x41, 0x4c, 0x4c, 0x10, 0x02, 0x12, 0x0d, 0x0a, 0x09, 0x52, 0x45, 0x47, 0x45, 0x58, 0x5f, 0x41, 0x4e, 0x59, 0x10, 0x03, 0x12, 0x0d, 0x0a, 0x09, 0x52, 0x45, 0x47, 0x45, 0x58, 0x5f, 0x41, 0x4c, 0x4c, 0x10, 0x04, 0x22, 0x5a, 0x0a, 0x11, 0x45, 0x76, 0x65, 0x6e, 0x74, 0x53, 0x75, 0x62, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x1d, 0x0a, 0x0a, 0x65, 0x76, 0x65, 0x6e, 0x74, 0x5f, 0x74, 0x79, 0x70, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, 0x65, 0x76, 0x65, 0x6e, 0x74, 0x54, 0x79, 0x70, 0x65, 0x12, 0x26, 0x0a, 0x07, 0x66, 0x69, 0x6c, 0x74, 0x65, 0x72, 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x0c, 0x2e, 0x45, 0x76, 0x65, 0x6e, 0x74, 0x46, 0x69, 0x6c, 0x74, 0x65, 0x72, 0x52, 0x07, 0x66, 0x69, 0x6c, 0x74, 0x65, 0x72, 0x73, 0x42, 0x25, 0x0a, 0x15, 0x73, 0x61, 0x77, 0x74, 0x6f, 0x6f, 0x74, 0x68, 0x2e, 0x73, 0x64, 0x6b, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x50, 0x01, 0x5a, 0x0a, 0x65, 0x76, 0x65, 0x6e, 0x74, 0x73, 0x5f, 0x70, 0x62, 0x32, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( file_protobuf_events_pb2_events_proto_rawDescOnce sync.Once file_protobuf_events_pb2_events_proto_rawDescData = file_protobuf_events_pb2_events_proto_rawDesc ) func file_protobuf_events_pb2_events_proto_rawDescGZIP() []byte { file_protobuf_events_pb2_events_proto_rawDescOnce.Do(func() { file_protobuf_events_pb2_events_proto_rawDescData = protoimpl.X.CompressGZIP(file_protobuf_events_pb2_events_proto_rawDescData) }) return file_protobuf_events_pb2_events_proto_rawDescData } var file_protobuf_events_pb2_events_proto_enumTypes = make([]protoimpl.EnumInfo, 1) var file_protobuf_events_pb2_events_proto_msgTypes = make([]protoimpl.MessageInfo, 5) var file_protobuf_events_pb2_events_proto_goTypes = []interface{}{ (EventFilter_FilterType)(0), // 0: EventFilter.FilterType (*Event)(nil), // 1: Event (*EventList)(nil), // 2: EventList (*EventFilter)(nil), // 3: EventFilter (*EventSubscription)(nil), // 4: EventSubscription (*Event_Attribute)(nil), // 5: Event.Attribute } var file_protobuf_events_pb2_events_proto_depIdxs = []int32{ 5, // 0: Event.attributes:type_name -> Event.Attribute 1, // 1: EventList.events:type_name -> Event 0, // 2: EventFilter.filter_type:type_name -> EventFilter.FilterType 3, // 3: EventSubscription.filters:type_name -> EventFilter 4, // [4:4] is the sub-list for method output_type 4, // [4:4] is the sub-list for method input_type 4, // [4:4] is the sub-list for extension type_name 4, // [4:4] is the sub-list for extension extendee 0, // [0:4] is the sub-list for field type_name } func init() { file_protobuf_events_pb2_events_proto_init() } func file_protobuf_events_pb2_events_proto_init() { if File_protobuf_events_pb2_events_proto != nil { return } if !protoimpl.UnsafeEnabled { file_protobuf_events_pb2_events_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*Event); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_events_pb2_events_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*EventList); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_events_pb2_events_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*EventFilter); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_events_pb2_events_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*EventSubscription); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_events_pb2_events_proto_msgTypes[4].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*Event_Attribute); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: file_protobuf_events_pb2_events_proto_rawDesc, NumEnums: 1, NumMessages: 5, NumExtensions: 0, NumServices: 0, }, GoTypes: file_protobuf_events_pb2_events_proto_goTypes, DependencyIndexes: file_protobuf_events_pb2_events_proto_depIdxs, EnumInfos: file_protobuf_events_pb2_events_proto_enumTypes, MessageInfos: file_protobuf_events_pb2_events_proto_msgTypes, }.Build() File_protobuf_events_pb2_events_proto = out.File file_protobuf_events_pb2_events_proto_rawDesc = nil file_protobuf_events_pb2_events_proto_goTypes = nil file_protobuf_events_pb2_events_proto_depIdxs = nil } <|start_filename|>protobuf/block_pb2/block.pb.go<|end_filename|> // Copyright 2016 Intel Corporation // // 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. // ----------------------------------------------------------------------------- // Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.25.0-devel // protoc v3.14.0 // source: protobuf/block_pb2/block.proto package block_pb2 import ( protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" batch_pb2 "github.com/hyperledger/sawtooth-sdk-go/protobuf/batch_pb2" reflect "reflect" sync "sync" ) const ( // Verify that this generated code is sufficiently up-to-date. _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) // Verify that runtime/protoimpl is sufficiently up-to-date. _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) type BlockHeader struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // Block number in the chain BlockNum uint64 `protobuf:"varint,1,opt,name=block_num,json=blockNum,proto3" json:"block_num,omitempty"` // The header_signature of the previous block that was added to the chain. PreviousBlockId string `protobuf:"bytes,2,opt,name=previous_block_id,json=previousBlockId,proto3" json:"previous_block_id,omitempty"` // Public key for the component internal to the validator that // signed the BlockHeader SignerPublicKey string `protobuf:"bytes,3,opt,name=signer_public_key,json=signerPublicKey,proto3" json:"signer_public_key,omitempty"` // List of batch.header_signatures that match the order of batches // required for the block BatchIds []string `protobuf:"bytes,4,rep,name=batch_ids,json=batchIds,proto3" json:"batch_ids,omitempty"` // Bytes that are set and verified by the consensus algorithm used to // create and validate the block Consensus []byte `protobuf:"bytes,5,opt,name=consensus,proto3" json:"consensus,omitempty"` // The state_root_hash should match the final state_root after all // transactions in the batches have been applied, otherwise the block // is not valid StateRootHash string `protobuf:"bytes,6,opt,name=state_root_hash,json=stateRootHash,proto3" json:"state_root_hash,omitempty"` } func (x *BlockHeader) Reset() { *x = BlockHeader{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_block_pb2_block_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *BlockHeader) String() string { return protoimpl.X.MessageStringOf(x) } func (*BlockHeader) ProtoMessage() {} func (x *BlockHeader) ProtoReflect() protoreflect.Message { mi := &file_protobuf_block_pb2_block_proto_msgTypes[0] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use BlockHeader.ProtoReflect.Descriptor instead. func (*BlockHeader) Descriptor() ([]byte, []int) { return file_protobuf_block_pb2_block_proto_rawDescGZIP(), []int{0} } func (x *BlockHeader) GetBlockNum() uint64 { if x != nil { return x.BlockNum } return 0 } func (x *BlockHeader) GetPreviousBlockId() string { if x != nil { return x.PreviousBlockId } return "" } func (x *BlockHeader) GetSignerPublicKey() string { if x != nil { return x.SignerPublicKey } return "" } func (x *BlockHeader) GetBatchIds() []string { if x != nil { return x.BatchIds } return nil } func (x *BlockHeader) GetConsensus() []byte { if x != nil { return x.Consensus } return nil } func (x *BlockHeader) GetStateRootHash() string { if x != nil { return x.StateRootHash } return "" } type Block struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // The serialized version of the BlockHeader Header []byte `protobuf:"bytes,1,opt,name=header,proto3" json:"header,omitempty"` // The signature derived from signing the header HeaderSignature string `protobuf:"bytes,2,opt,name=header_signature,json=headerSignature,proto3" json:"header_signature,omitempty"` // A list of batches. The batches may contain new batches that other // validators may not have received yet, or they will be all batches needed // for block validation when passed to the journal Batches []*batch_pb2.Batch `protobuf:"bytes,3,rep,name=batches,proto3" json:"batches,omitempty"` } func (x *Block) Reset() { *x = Block{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_block_pb2_block_proto_msgTypes[1] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *Block) String() string { return protoimpl.X.MessageStringOf(x) } func (*Block) ProtoMessage() {} func (x *Block) ProtoReflect() protoreflect.Message { mi := &file_protobuf_block_pb2_block_proto_msgTypes[1] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use Block.ProtoReflect.Descriptor instead. func (*Block) Descriptor() ([]byte, []int) { return file_protobuf_block_pb2_block_proto_rawDescGZIP(), []int{1} } func (x *Block) GetHeader() []byte { if x != nil { return x.Header } return nil } func (x *Block) GetHeaderSignature() string { if x != nil { return x.HeaderSignature } return "" } func (x *Block) GetBatches() []*batch_pb2.Batch { if x != nil { return x.Batches } return nil } var File_protobuf_block_pb2_block_proto protoreflect.FileDescriptor var file_protobuf_block_pb2_block_proto_rawDesc = []byte{ 0x0a, 0x1e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x5f, 0x70, 0x62, 0x32, 0x2f, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x1e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x62, 0x61, 0x74, 0x63, 0x68, 0x5f, 0x70, 0x62, 0x32, 0x2f, 0x62, 0x61, 0x74, 0x63, 0x68, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0xe5, 0x01, 0x0a, 0x0b, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x48, 0x65, 0x61, 0x64, 0x65, 0x72, 0x12, 0x1b, 0x0a, 0x09, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x5f, 0x6e, 0x75, 0x6d, 0x18, 0x01, 0x20, 0x01, 0x28, 0x04, 0x52, 0x08, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x4e, 0x75, 0x6d, 0x12, 0x2a, 0x0a, 0x11, 0x70, 0x72, 0x65, 0x76, 0x69, 0x6f, 0x75, 0x73, 0x5f, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x5f, 0x69, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0f, 0x70, 0x72, 0x65, 0x76, 0x69, 0x6f, 0x75, 0x73, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x49, 0x64, 0x12, 0x2a, 0x0a, 0x11, 0x73, 0x69, 0x67, 0x6e, 0x65, 0x72, 0x5f, 0x70, 0x75, 0x62, 0x6c, 0x69, 0x63, 0x5f, 0x6b, 0x65, 0x79, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0f, 0x73, 0x69, 0x67, 0x6e, 0x65, 0x72, 0x50, 0x75, 0x62, 0x6c, 0x69, 0x63, 0x4b, 0x65, 0x79, 0x12, 0x1b, 0x0a, 0x09, 0x62, 0x61, 0x74, 0x63, 0x68, 0x5f, 0x69, 0x64, 0x73, 0x18, 0x04, 0x20, 0x03, 0x28, 0x09, 0x52, 0x08, 0x62, 0x61, 0x74, 0x63, 0x68, 0x49, 0x64, 0x73, 0x12, 0x1c, 0x0a, 0x09, 0x63, 0x6f, 0x6e, 0x73, 0x65, 0x6e, 0x73, 0x75, 0x73, 0x18, 0x05, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x09, 0x63, 0x6f, 0x6e, 0x73, 0x65, 0x6e, 0x73, 0x75, 0x73, 0x12, 0x26, 0x0a, 0x0f, 0x73, 0x74, 0x61, 0x74, 0x65, 0x5f, 0x72, 0x6f, 0x6f, 0x74, 0x5f, 0x68, 0x61, 0x73, 0x68, 0x18, 0x06, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0d, 0x73, 0x74, 0x61, 0x74, 0x65, 0x52, 0x6f, 0x6f, 0x74, 0x48, 0x61, 0x73, 0x68, 0x22, 0x6c, 0x0a, 0x05, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x12, 0x16, 0x0a, 0x06, 0x68, 0x65, 0x61, 0x64, 0x65, 0x72, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x06, 0x68, 0x65, 0x61, 0x64, 0x65, 0x72, 0x12, 0x29, 0x0a, 0x10, 0x68, 0x65, 0x61, 0x64, 0x65, 0x72, 0x5f, 0x73, 0x69, 0x67, 0x6e, 0x61, 0x74, 0x75, 0x72, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0f, 0x68, 0x65, 0x61, 0x64, 0x65, 0x72, 0x53, 0x69, 0x67, 0x6e, 0x61, 0x74, 0x75, 0x72, 0x65, 0x12, 0x20, 0x0a, 0x07, 0x62, 0x61, 0x74, 0x63, 0x68, 0x65, 0x73, 0x18, 0x03, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x06, 0x2e, 0x42, 0x61, 0x74, 0x63, 0x68, 0x52, 0x07, 0x62, 0x61, 0x74, 0x63, 0x68, 0x65, 0x73, 0x42, 0x24, 0x0a, 0x15, 0x73, 0x61, 0x77, 0x74, 0x6f, 0x6f, 0x74, 0x68, 0x2e, 0x73, 0x64, 0x6b, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x50, 0x01, 0x5a, 0x09, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x5f, 0x70, 0x62, 0x32, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( file_protobuf_block_pb2_block_proto_rawDescOnce sync.Once file_protobuf_block_pb2_block_proto_rawDescData = file_protobuf_block_pb2_block_proto_rawDesc ) func file_protobuf_block_pb2_block_proto_rawDescGZIP() []byte { file_protobuf_block_pb2_block_proto_rawDescOnce.Do(func() { file_protobuf_block_pb2_block_proto_rawDescData = protoimpl.X.CompressGZIP(file_protobuf_block_pb2_block_proto_rawDescData) }) return file_protobuf_block_pb2_block_proto_rawDescData } var file_protobuf_block_pb2_block_proto_msgTypes = make([]protoimpl.MessageInfo, 2) var file_protobuf_block_pb2_block_proto_goTypes = []interface{}{ (*BlockHeader)(nil), // 0: BlockHeader (*Block)(nil), // 1: Block (*batch_pb2.Batch)(nil), // 2: Batch } var file_protobuf_block_pb2_block_proto_depIdxs = []int32{ 2, // 0: Block.batches:type_name -> Batch 1, // [1:1] is the sub-list for method output_type 1, // [1:1] is the sub-list for method input_type 1, // [1:1] is the sub-list for extension type_name 1, // [1:1] is the sub-list for extension extendee 0, // [0:1] is the sub-list for field type_name } func init() { file_protobuf_block_pb2_block_proto_init() } func file_protobuf_block_pb2_block_proto_init() { if File_protobuf_block_pb2_block_proto != nil { return } if !protoimpl.UnsafeEnabled { file_protobuf_block_pb2_block_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*BlockHeader); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_block_pb2_block_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*Block); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: file_protobuf_block_pb2_block_proto_rawDesc, NumEnums: 0, NumMessages: 2, NumExtensions: 0, NumServices: 0, }, GoTypes: file_protobuf_block_pb2_block_proto_goTypes, DependencyIndexes: file_protobuf_block_pb2_block_proto_depIdxs, MessageInfos: file_protobuf_block_pb2_block_proto_msgTypes, }.Build() File_protobuf_block_pb2_block_proto = out.File file_protobuf_block_pb2_block_proto_rawDesc = nil file_protobuf_block_pb2_block_proto_goTypes = nil file_protobuf_block_pb2_block_proto_depIdxs = nil } <|start_filename|>examples/intkey_go/src/sawtooth_intkey_client/intkey_client.go<|end_filename|> /** * Copyright 2018 Intel Corporation * * 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 main import ( bytes2 "bytes" "encoding/base64" "encoding/hex" "errors" "fmt" cbor "github.com/brianolson/cbor_go" "github.com/golang/protobuf/proto" "github.com/hyperledger/sawtooth-sdk-go/protobuf/batch_pb2" "github.com/hyperledger/sawtooth-sdk-go/protobuf/transaction_pb2" "github.com/hyperledger/sawtooth-sdk-go/signing" "gopkg.in/yaml.v2" "io/ioutil" "math/rand" "net/http" "strconv" "strings" "time" ) type IntkeyClient struct { url string signer *signing.Signer } func NewIntkeyClient(url string, keyfile string) (IntkeyClient, error) { var privateKey signing.PrivateKey if keyfile != "" { // Read private key file privateKeyStr, err := ioutil.ReadFile(keyfile) if err != nil { return IntkeyClient{}, errors.New(fmt.Sprintf("Failed to read private key: %v", err)) } // Get private key object privateKey = signing.NewSecp256k1PrivateKey(privateKeyStr) } else { privateKey = signing.NewSecp256k1Context().NewRandomPrivateKey() } cryptoFactory := signing.NewCryptoFactory(signing.NewSecp256k1Context()) signer := cryptoFactory.NewSigner(privateKey) return IntkeyClient{url, signer}, nil } func (intkeyClient IntkeyClient) Set( name string, value uint, wait uint) (string, error) { return intkeyClient.sendTransaction(VERB_SET, name, value, wait) } func (intkeyClient IntkeyClient) Inc( name string, value uint, wait uint) (string, error) { return intkeyClient.sendTransaction(VERB_INC, name, value, wait) } func (intkeyClient IntkeyClient) Dec( name string, value uint, wait uint) (string, error) { return intkeyClient.sendTransaction(VERB_DEC, name, value, wait) } func (intkeyClient IntkeyClient) List() ([]map[interface{}]interface{}, error) { // API to call apiSuffix := fmt.Sprintf("%s?address=%s", STATE_API, intkeyClient.getPrefix()) response, err := intkeyClient.sendRequest(apiSuffix, []byte{}, "", "") if err != nil { return []map[interface{}]interface{}{}, err } var toReturn []map[interface{}]interface{} responseMap := make(map[interface{}]interface{}) err = yaml.Unmarshal([]byte(response), &responseMap) if err != nil { return []map[interface{}]interface{}{}, errors.New(fmt.Sprintf("Error reading response: %v", err)) } encodedEntries := responseMap["data"].([]interface{}) for _, entry := range encodedEntries { entryData, ok := entry.(map[interface{}]interface{}) if !ok { return []map[interface{}]interface{}{}, errors.New("Error reading entry data") } stringData, ok := entryData["data"].(string) if !ok { return []map[interface{}]interface{}{}, errors.New("Error reading string data") } decodedBytes, err := base64.StdEncoding.DecodeString(stringData) if err != nil { return []map[interface{}]interface{}{}, errors.New(fmt.Sprint("Error decoding: %v", err)) } foundMap := make(map[interface{}]interface{}) err = cbor.Loads(decodedBytes, &foundMap) if err != nil { return []map[interface{}]interface{}{}, errors.New(fmt.Sprint("Error binary decoding: %v", err)) } toReturn = append(toReturn, foundMap) } return toReturn, nil } func (intkeyClient IntkeyClient) Show(name string) (string, error) { apiSuffix := fmt.Sprintf("%s/%s", STATE_API, intkeyClient.getAddress(name)) response, err := intkeyClient.sendRequest(apiSuffix, []byte{}, "", name) if err != nil { return "", err } responseMap := make(map[interface{}]interface{}) err = yaml.Unmarshal([]byte(response), &responseMap) if err != nil { return "", errors.New(fmt.Sprint("Error reading response: %v", err)) } data, ok := responseMap["data"].(string) if !ok { return "", errors.New("Error reading as string") } responseData, err := base64.StdEncoding.DecodeString(data) if err != nil { return "", errors.New(fmt.Sprint("Error decoding response: %v", err)) } responseFinal := make(map[interface{}]interface{}) err = cbor.Loads(responseData, &responseFinal) if err != nil { return "", errors.New(fmt.Sprint("Error binary decoding: %v", err)) } return fmt.Sprintf("%v", responseFinal[name]), nil } func (intkeyClient IntkeyClient) getStatus( batchId string, wait uint) (string, error) { // API to call apiSuffix := fmt.Sprintf("%s?id=%s&wait=%d", BATCH_STATUS_API, batchId, wait) response, err := intkeyClient.sendRequest(apiSuffix, []byte{}, "", "") if err != nil { return "", err } responseMap := make(map[interface{}]interface{}) err = yaml.Unmarshal([]byte(response), &responseMap) if err != nil { return "", errors.New(fmt.Sprintf("Error reading response: %v", err)) } entry := responseMap["data"].([]interface{})[0].(map[interface{}]interface{}) return fmt.Sprint(entry["status"]), nil } func (intkeyClient IntkeyClient) sendRequest( apiSuffix string, data []byte, contentType string, name string) (string, error) { // Construct URL var url string if strings.HasPrefix(intkeyClient.url, "http://") { url = fmt.Sprintf("%s/%s", intkeyClient.url, apiSuffix) } else { url = fmt.Sprintf("http://%s/%s", intkeyClient.url, apiSuffix) } // Send request to validator URL var response *http.Response var err error if len(data) > 0 { response, err = http.Post(url, contentType, bytes2.NewBuffer(data)) } else { response, err = http.Get(url) } if err != nil { return "", errors.New( fmt.Sprintf("Failed to connect to REST API: %v", err)) } if response.StatusCode == 404 { logger.Debug(fmt.Sprintf("%v", response)) return "", errors.New(fmt.Sprintf("No such key: %s", name)) } else if response.StatusCode >= 400 { return "", errors.New( fmt.Sprintf("Error %d: %s", response.StatusCode, response.Status)) } defer response.Body.Close() reponseBody, err := ioutil.ReadAll(response.Body) if err != nil { return "", errors.New(fmt.Sprintf("Error reading response: %v", err)) } return string(reponseBody), nil } func (intkeyClient IntkeyClient) sendTransaction( verb string, name string, value uint, wait uint) (string, error) { // construct the payload information in CBOR format payloadData := make(map[string]interface{}) payloadData["Verb"] = verb payloadData["Name"] = name payloadData["Value"] = value payload, err := cbor.Dumps(payloadData) if err != nil { return "", errors.New(fmt.Sprintf("Failed to construct CBOR: %v", err)) } // construct the address address := intkeyClient.getAddress(name) // Construct TransactionHeader rawTransactionHeader := transaction_pb2.TransactionHeader{ SignerPublicKey: intkeyClient.signer.GetPublicKey().AsHex(), FamilyName: FAMILY_NAME, FamilyVersion: FAMILY_VERSION, Dependencies: []string{}, // empty dependency list Nonce: strconv.Itoa(rand.Int()), BatcherPublicKey: intkeyClient.signer.GetPublicKey().AsHex(), Inputs: []string{address}, Outputs: []string{address}, PayloadSha512: Sha512HashValue(string(payload)), } transactionHeader, err := proto.Marshal(&rawTransactionHeader) if err != nil { return "", errors.New( fmt.Sprintf("Unable to serialize transaction header: %v", err)) } // Signature of TransactionHeader transactionHeaderSignature := hex.EncodeToString( intkeyClient.signer.Sign(transactionHeader)) // Construct Transaction transaction := transaction_pb2.Transaction{ Header: transactionHeader, HeaderSignature: transactionHeaderSignature, Payload: []byte(payload), } // Get BatchList rawBatchList, err := intkeyClient.createBatchList( []*transaction_pb2.Transaction{&transaction}) if err != nil { return "", errors.New( fmt.Sprintf("Unable to construct batch list: %v", err)) } batchId := rawBatchList.Batches[0].HeaderSignature batchList, err := proto.Marshal(&rawBatchList) if err != nil { return "", errors.New( fmt.Sprintf("Unable to serialize batch list: %v", err)) } if wait > 0 { waitTime := uint(0) startTime := time.Now() response, err := intkeyClient.sendRequest( BATCH_SUBMIT_API, batchList, CONTENT_TYPE_OCTET_STREAM, name) if err != nil { return "", err } for waitTime < wait { status, err := intkeyClient.getStatus(batchId, wait-waitTime) if err != nil { return "", err } waitTime = uint(time.Now().Sub(startTime)) if status != "PENDING" { return response, nil } } return response, nil } return intkeyClient.sendRequest( BATCH_SUBMIT_API, batchList, CONTENT_TYPE_OCTET_STREAM, name) } func (intkeyClient IntkeyClient) getPrefix() string { return Sha512HashValue(FAMILY_NAME)[:FAMILY_NAMESPACE_ADDRESS_LENGTH] } func (intkeyClient IntkeyClient) getAddress(name string) string { prefix := intkeyClient.getPrefix() nameAddress := Sha512HashValue(name)[FAMILY_VERB_ADDRESS_LENGTH:] return prefix + nameAddress } func (intkeyClient IntkeyClient) createBatchList( transactions []*transaction_pb2.Transaction) (batch_pb2.BatchList, error) { // Get list of TransactionHeader signatures transactionSignatures := []string{} for _, transaction := range transactions { transactionSignatures = append(transactionSignatures, transaction.HeaderSignature) } // Construct BatchHeader rawBatchHeader := batch_pb2.BatchHeader{ SignerPublicKey: intkeyClient.signer.GetPublicKey().AsHex(), TransactionIds: transactionSignatures, } batchHeader, err := proto.Marshal(&rawBatchHeader) if err != nil { return batch_pb2.BatchList{}, errors.New( fmt.Sprintf("Unable to serialize batch header: %v", err)) } // Signature of BatchHeader batchHeaderSignature := hex.EncodeToString( intkeyClient.signer.Sign(batchHeader)) // Construct Batch batch := batch_pb2.Batch{ Header: batchHeader, Transactions: transactions, HeaderSignature: batchHeaderSignature, } // Construct BatchList return batch_pb2.BatchList{ Batches: []*batch_pb2.Batch{&batch}, }, nil } <|start_filename|>protobuf/network_pb2/network.pb.go<|end_filename|> // Copyright 2016, 2017 Intel Corporation // // 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. // ----------------------------------------------------------------------------- // Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.25.0-devel // protoc v3.14.0 // source: protobuf/network_pb2/network.proto package network_pb2 import ( protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" sync "sync" ) const ( // Verify that this generated code is sufficiently up-to-date. _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) // Verify that runtime/protoimpl is sufficiently up-to-date. _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) type GossipMessage_ContentType int32 const ( GossipMessage_CONTENT_TYPE_UNSET GossipMessage_ContentType = 0 GossipMessage_BLOCK GossipMessage_ContentType = 1 GossipMessage_BATCH GossipMessage_ContentType = 2 ) // Enum value maps for GossipMessage_ContentType. var ( GossipMessage_ContentType_name = map[int32]string{ 0: "CONTENT_TYPE_UNSET", 1: "BLOCK", 2: "BATCH", } GossipMessage_ContentType_value = map[string]int32{ "CONTENT_TYPE_UNSET": 0, "BLOCK": 1, "BATCH": 2, } ) func (x GossipMessage_ContentType) Enum() *GossipMessage_ContentType { p := new(GossipMessage_ContentType) *p = x return p } func (x GossipMessage_ContentType) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (GossipMessage_ContentType) Descriptor() protoreflect.EnumDescriptor { return file_protobuf_network_pb2_network_proto_enumTypes[0].Descriptor() } func (GossipMessage_ContentType) Type() protoreflect.EnumType { return &file_protobuf_network_pb2_network_proto_enumTypes[0] } func (x GossipMessage_ContentType) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use GossipMessage_ContentType.Descriptor instead. func (GossipMessage_ContentType) EnumDescriptor() ([]byte, []int) { return file_protobuf_network_pb2_network_proto_rawDescGZIP(), []int{7, 0} } type NetworkAcknowledgement_Status int32 const ( NetworkAcknowledgement_STATUS_UNSET NetworkAcknowledgement_Status = 0 NetworkAcknowledgement_OK NetworkAcknowledgement_Status = 1 NetworkAcknowledgement_ERROR NetworkAcknowledgement_Status = 2 ) // Enum value maps for NetworkAcknowledgement_Status. var ( NetworkAcknowledgement_Status_name = map[int32]string{ 0: "STATUS_UNSET", 1: "OK", 2: "ERROR", } NetworkAcknowledgement_Status_value = map[string]int32{ "STATUS_UNSET": 0, "OK": 1, "ERROR": 2, } ) func (x NetworkAcknowledgement_Status) Enum() *NetworkAcknowledgement_Status { p := new(NetworkAcknowledgement_Status) *p = x return p } func (x NetworkAcknowledgement_Status) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (NetworkAcknowledgement_Status) Descriptor() protoreflect.EnumDescriptor { return file_protobuf_network_pb2_network_proto_enumTypes[1].Descriptor() } func (NetworkAcknowledgement_Status) Type() protoreflect.EnumType { return &file_protobuf_network_pb2_network_proto_enumTypes[1] } func (x NetworkAcknowledgement_Status) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use NetworkAcknowledgement_Status.Descriptor instead. func (NetworkAcknowledgement_Status) EnumDescriptor() ([]byte, []int) { return file_protobuf_network_pb2_network_proto_rawDescGZIP(), []int{8, 0} } // The disconnect message from a client to the server type DisconnectMessage struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields } func (x *DisconnectMessage) Reset() { *x = DisconnectMessage{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_network_pb2_network_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *DisconnectMessage) String() string { return protoimpl.X.MessageStringOf(x) } func (*DisconnectMessage) ProtoMessage() {} func (x *DisconnectMessage) ProtoReflect() protoreflect.Message { mi := &file_protobuf_network_pb2_network_proto_msgTypes[0] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use DisconnectMessage.ProtoReflect.Descriptor instead. func (*DisconnectMessage) Descriptor() ([]byte, []int) { return file_protobuf_network_pb2_network_proto_rawDescGZIP(), []int{0} } // The registration request from a peer to the validator type PeerRegisterRequest struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Endpoint string `protobuf:"bytes,1,opt,name=endpoint,proto3" json:"endpoint,omitempty"` // The current version of the network protocol that is being used by the // sender. This version is an increasing value. ProtocolVersion uint32 `protobuf:"varint,2,opt,name=protocol_version,json=protocolVersion,proto3" json:"protocol_version,omitempty"` } func (x *PeerRegisterRequest) Reset() { *x = PeerRegisterRequest{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_network_pb2_network_proto_msgTypes[1] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *PeerRegisterRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*PeerRegisterRequest) ProtoMessage() {} func (x *PeerRegisterRequest) ProtoReflect() protoreflect.Message { mi := &file_protobuf_network_pb2_network_proto_msgTypes[1] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use PeerRegisterRequest.ProtoReflect.Descriptor instead. func (*PeerRegisterRequest) Descriptor() ([]byte, []int) { return file_protobuf_network_pb2_network_proto_rawDescGZIP(), []int{1} } func (x *PeerRegisterRequest) GetEndpoint() string { if x != nil { return x.Endpoint } return "" } func (x *PeerRegisterRequest) GetProtocolVersion() uint32 { if x != nil { return x.ProtocolVersion } return 0 } // The unregistration request from a peer to the validator type PeerUnregisterRequest struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields } func (x *PeerUnregisterRequest) Reset() { *x = PeerUnregisterRequest{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_network_pb2_network_proto_msgTypes[2] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *PeerUnregisterRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*PeerUnregisterRequest) ProtoMessage() {} func (x *PeerUnregisterRequest) ProtoReflect() protoreflect.Message { mi := &file_protobuf_network_pb2_network_proto_msgTypes[2] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use PeerUnregisterRequest.ProtoReflect.Descriptor instead. func (*PeerUnregisterRequest) Descriptor() ([]byte, []int) { return file_protobuf_network_pb2_network_proto_rawDescGZIP(), []int{2} } type GetPeersRequest struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields } func (x *GetPeersRequest) Reset() { *x = GetPeersRequest{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_network_pb2_network_proto_msgTypes[3] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *GetPeersRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*GetPeersRequest) ProtoMessage() {} func (x *GetPeersRequest) ProtoReflect() protoreflect.Message { mi := &file_protobuf_network_pb2_network_proto_msgTypes[3] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use GetPeersRequest.ProtoReflect.Descriptor instead. func (*GetPeersRequest) Descriptor() ([]byte, []int) { return file_protobuf_network_pb2_network_proto_rawDescGZIP(), []int{3} } type GetPeersResponse struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields PeerEndpoints []string `protobuf:"bytes,1,rep,name=peer_endpoints,json=peerEndpoints,proto3" json:"peer_endpoints,omitempty"` } func (x *GetPeersResponse) Reset() { *x = GetPeersResponse{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_network_pb2_network_proto_msgTypes[4] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *GetPeersResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*GetPeersResponse) ProtoMessage() {} func (x *GetPeersResponse) ProtoReflect() protoreflect.Message { mi := &file_protobuf_network_pb2_network_proto_msgTypes[4] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use GetPeersResponse.ProtoReflect.Descriptor instead. func (*GetPeersResponse) Descriptor() ([]byte, []int) { return file_protobuf_network_pb2_network_proto_rawDescGZIP(), []int{4} } func (x *GetPeersResponse) GetPeerEndpoints() []string { if x != nil { return x.PeerEndpoints } return nil } type PingRequest struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields } func (x *PingRequest) Reset() { *x = PingRequest{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_network_pb2_network_proto_msgTypes[5] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *PingRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*PingRequest) ProtoMessage() {} func (x *PingRequest) ProtoReflect() protoreflect.Message { mi := &file_protobuf_network_pb2_network_proto_msgTypes[5] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use PingRequest.ProtoReflect.Descriptor instead. func (*PingRequest) Descriptor() ([]byte, []int) { return file_protobuf_network_pb2_network_proto_rawDescGZIP(), []int{5} } type PingResponse struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields } func (x *PingResponse) Reset() { *x = PingResponse{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_network_pb2_network_proto_msgTypes[6] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *PingResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*PingResponse) ProtoMessage() {} func (x *PingResponse) ProtoReflect() protoreflect.Message { mi := &file_protobuf_network_pb2_network_proto_msgTypes[6] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use PingResponse.ProtoReflect.Descriptor instead. func (*PingResponse) Descriptor() ([]byte, []int) { return file_protobuf_network_pb2_network_proto_rawDescGZIP(), []int{6} } type GossipMessage struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Content []byte `protobuf:"bytes,1,opt,name=content,proto3" json:"content,omitempty"` ContentType GossipMessage_ContentType `protobuf:"varint,2,opt,name=content_type,json=contentType,proto3,enum=GossipMessage_ContentType" json:"content_type,omitempty"` TimeToLive uint32 `protobuf:"varint,3,opt,name=time_to_live,json=timeToLive,proto3" json:"time_to_live,omitempty"` } func (x *GossipMessage) Reset() { *x = GossipMessage{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_network_pb2_network_proto_msgTypes[7] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *GossipMessage) String() string { return protoimpl.X.MessageStringOf(x) } func (*GossipMessage) ProtoMessage() {} func (x *GossipMessage) ProtoReflect() protoreflect.Message { mi := &file_protobuf_network_pb2_network_proto_msgTypes[7] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use GossipMessage.ProtoReflect.Descriptor instead. func (*GossipMessage) Descriptor() ([]byte, []int) { return file_protobuf_network_pb2_network_proto_rawDescGZIP(), []int{7} } func (x *GossipMessage) GetContent() []byte { if x != nil { return x.Content } return nil } func (x *GossipMessage) GetContentType() GossipMessage_ContentType { if x != nil { return x.ContentType } return GossipMessage_CONTENT_TYPE_UNSET } func (x *GossipMessage) GetTimeToLive() uint32 { if x != nil { return x.TimeToLive } return 0 } // A response sent from the validator to the peer acknowledging message // receipt type NetworkAcknowledgement struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Status NetworkAcknowledgement_Status `protobuf:"varint,1,opt,name=status,proto3,enum=NetworkAcknowledgement_Status" json:"status,omitempty"` } func (x *NetworkAcknowledgement) Reset() { *x = NetworkAcknowledgement{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_network_pb2_network_proto_msgTypes[8] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *NetworkAcknowledgement) String() string { return protoimpl.X.MessageStringOf(x) } func (*NetworkAcknowledgement) ProtoMessage() {} func (x *NetworkAcknowledgement) ProtoReflect() protoreflect.Message { mi := &file_protobuf_network_pb2_network_proto_msgTypes[8] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use NetworkAcknowledgement.ProtoReflect.Descriptor instead. func (*NetworkAcknowledgement) Descriptor() ([]byte, []int) { return file_protobuf_network_pb2_network_proto_rawDescGZIP(), []int{8} } func (x *NetworkAcknowledgement) GetStatus() NetworkAcknowledgement_Status { if x != nil { return x.Status } return NetworkAcknowledgement_STATUS_UNSET } type GossipBlockRequest struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // The id of the block that is being requested BlockId string `protobuf:"bytes,1,opt,name=block_id,json=blockId,proto3" json:"block_id,omitempty"` // A random string that provides uniqueness for requests with // otherwise identical fields. Nonce string `protobuf:"bytes,2,opt,name=nonce,proto3" json:"nonce,omitempty"` TimeToLive uint32 `protobuf:"varint,3,opt,name=time_to_live,json=timeToLive,proto3" json:"time_to_live,omitempty"` } func (x *GossipBlockRequest) Reset() { *x = GossipBlockRequest{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_network_pb2_network_proto_msgTypes[9] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *GossipBlockRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*GossipBlockRequest) ProtoMessage() {} func (x *GossipBlockRequest) ProtoReflect() protoreflect.Message { mi := &file_protobuf_network_pb2_network_proto_msgTypes[9] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use GossipBlockRequest.ProtoReflect.Descriptor instead. func (*GossipBlockRequest) Descriptor() ([]byte, []int) { return file_protobuf_network_pb2_network_proto_rawDescGZIP(), []int{9} } func (x *GossipBlockRequest) GetBlockId() string { if x != nil { return x.BlockId } return "" } func (x *GossipBlockRequest) GetNonce() string { if x != nil { return x.Nonce } return "" } func (x *GossipBlockRequest) GetTimeToLive() uint32 { if x != nil { return x.TimeToLive } return 0 } type GossipBlockResponse struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // The block Content []byte `protobuf:"bytes,1,opt,name=content,proto3" json:"content,omitempty"` } func (x *GossipBlockResponse) Reset() { *x = GossipBlockResponse{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_network_pb2_network_proto_msgTypes[10] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *GossipBlockResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*GossipBlockResponse) ProtoMessage() {} func (x *GossipBlockResponse) ProtoReflect() protoreflect.Message { mi := &file_protobuf_network_pb2_network_proto_msgTypes[10] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use GossipBlockResponse.ProtoReflect.Descriptor instead. func (*GossipBlockResponse) Descriptor() ([]byte, []int) { return file_protobuf_network_pb2_network_proto_rawDescGZIP(), []int{10} } func (x *GossipBlockResponse) GetContent() []byte { if x != nil { return x.Content } return nil } type GossipBatchResponse struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields //The batch Content []byte `protobuf:"bytes,1,opt,name=content,proto3" json:"content,omitempty"` } func (x *GossipBatchResponse) Reset() { *x = GossipBatchResponse{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_network_pb2_network_proto_msgTypes[11] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *GossipBatchResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*GossipBatchResponse) ProtoMessage() {} func (x *GossipBatchResponse) ProtoReflect() protoreflect.Message { mi := &file_protobuf_network_pb2_network_proto_msgTypes[11] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use GossipBatchResponse.ProtoReflect.Descriptor instead. func (*GossipBatchResponse) Descriptor() ([]byte, []int) { return file_protobuf_network_pb2_network_proto_rawDescGZIP(), []int{11} } func (x *GossipBatchResponse) GetContent() []byte { if x != nil { return x.Content } return nil } type GossipBatchByBatchIdRequest struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // The id of the batch that is being requested Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` // A random string that provides uniqueness for requests with // otherwise identical fields. Nonce string `protobuf:"bytes,2,opt,name=nonce,proto3" json:"nonce,omitempty"` TimeToLive uint32 `protobuf:"varint,3,opt,name=time_to_live,json=timeToLive,proto3" json:"time_to_live,omitempty"` } func (x *GossipBatchByBatchIdRequest) Reset() { *x = GossipBatchByBatchIdRequest{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_network_pb2_network_proto_msgTypes[12] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *GossipBatchByBatchIdRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*GossipBatchByBatchIdRequest) ProtoMessage() {} func (x *GossipBatchByBatchIdRequest) ProtoReflect() protoreflect.Message { mi := &file_protobuf_network_pb2_network_proto_msgTypes[12] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use GossipBatchByBatchIdRequest.ProtoReflect.Descriptor instead. func (*GossipBatchByBatchIdRequest) Descriptor() ([]byte, []int) { return file_protobuf_network_pb2_network_proto_rawDescGZIP(), []int{12} } func (x *GossipBatchByBatchIdRequest) GetId() string { if x != nil { return x.Id } return "" } func (x *GossipBatchByBatchIdRequest) GetNonce() string { if x != nil { return x.Nonce } return "" } func (x *GossipBatchByBatchIdRequest) GetTimeToLive() uint32 { if x != nil { return x.TimeToLive } return 0 } type GossipBatchByTransactionIdRequest struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // The id's of the transaction that are in the batches requested Ids []string `protobuf:"bytes,1,rep,name=ids,proto3" json:"ids,omitempty"` // A random string that provides uniqueness for requests with // otherwise identical fields. Nonce string `protobuf:"bytes,2,opt,name=nonce,proto3" json:"nonce,omitempty"` TimeToLive uint32 `protobuf:"varint,3,opt,name=time_to_live,json=timeToLive,proto3" json:"time_to_live,omitempty"` } func (x *GossipBatchByTransactionIdRequest) Reset() { *x = GossipBatchByTransactionIdRequest{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_network_pb2_network_proto_msgTypes[13] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *GossipBatchByTransactionIdRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*GossipBatchByTransactionIdRequest) ProtoMessage() {} func (x *GossipBatchByTransactionIdRequest) ProtoReflect() protoreflect.Message { mi := &file_protobuf_network_pb2_network_proto_msgTypes[13] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use GossipBatchByTransactionIdRequest.ProtoReflect.Descriptor instead. func (*GossipBatchByTransactionIdRequest) Descriptor() ([]byte, []int) { return file_protobuf_network_pb2_network_proto_rawDescGZIP(), []int{13} } func (x *GossipBatchByTransactionIdRequest) GetIds() []string { if x != nil { return x.Ids } return nil } func (x *GossipBatchByTransactionIdRequest) GetNonce() string { if x != nil { return x.Nonce } return "" } func (x *GossipBatchByTransactionIdRequest) GetTimeToLive() uint32 { if x != nil { return x.TimeToLive } return 0 } type GossipConsensusMessage struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Message []byte `protobuf:"bytes,1,opt,name=message,proto3" json:"message,omitempty"` SenderId []byte `protobuf:"bytes,2,opt,name=sender_id,json=senderId,proto3" json:"sender_id,omitempty"` TimeToLive uint32 `protobuf:"varint,3,opt,name=time_to_live,json=timeToLive,proto3" json:"time_to_live,omitempty"` } func (x *GossipConsensusMessage) Reset() { *x = GossipConsensusMessage{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_network_pb2_network_proto_msgTypes[14] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *GossipConsensusMessage) String() string { return protoimpl.X.MessageStringOf(x) } func (*GossipConsensusMessage) ProtoMessage() {} func (x *GossipConsensusMessage) ProtoReflect() protoreflect.Message { mi := &file_protobuf_network_pb2_network_proto_msgTypes[14] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use GossipConsensusMessage.ProtoReflect.Descriptor instead. func (*GossipConsensusMessage) Descriptor() ([]byte, []int) { return file_protobuf_network_pb2_network_proto_rawDescGZIP(), []int{14} } func (x *GossipConsensusMessage) GetMessage() []byte { if x != nil { return x.Message } return nil } func (x *GossipConsensusMessage) GetSenderId() []byte { if x != nil { return x.SenderId } return nil } func (x *GossipConsensusMessage) GetTimeToLive() uint32 { if x != nil { return x.TimeToLive } return 0 } var File_protobuf_network_pb2_network_proto protoreflect.FileDescriptor var file_protobuf_network_pb2_network_proto_rawDesc = []byte{ 0x0a, 0x22, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x6e, 0x65, 0x74, 0x77, 0x6f, 0x72, 0x6b, 0x5f, 0x70, 0x62, 0x32, 0x2f, 0x6e, 0x65, 0x74, 0x77, 0x6f, 0x72, 0x6b, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0x13, 0x0a, 0x11, 0x44, 0x69, 0x73, 0x63, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x22, 0x5c, 0x0a, 0x13, 0x50, 0x65, 0x65, 0x72, 0x52, 0x65, 0x67, 0x69, 0x73, 0x74, 0x65, 0x72, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x1a, 0x0a, 0x08, 0x65, 0x6e, 0x64, 0x70, 0x6f, 0x69, 0x6e, 0x74, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x65, 0x6e, 0x64, 0x70, 0x6f, 0x69, 0x6e, 0x74, 0x12, 0x29, 0x0a, 0x10, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x5f, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x0f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x22, 0x17, 0x0a, 0x15, 0x50, 0x65, 0x65, 0x72, 0x55, 0x6e, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x65, 0x72, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x22, 0x11, 0x0a, 0x0f, 0x47, 0x65, 0x74, 0x50, 0x65, 0x65, 0x72, 0x73, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x22, 0x39, 0x0a, 0x10, 0x47, 0x65, 0x74, 0x50, 0x65, 0x65, 0x72, 0x73, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x25, 0x0a, 0x0e, 0x70, 0x65, 0x65, 0x72, 0x5f, 0x65, 0x6e, 0x64, 0x70, 0x6f, 0x69, 0x6e, 0x74, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x09, 0x52, 0x0d, 0x70, 0x65, 0x65, 0x72, 0x45, 0x6e, 0x64, 0x70, 0x6f, 0x69, 0x6e, 0x74, 0x73, 0x22, 0x0d, 0x0a, 0x0b, 0x50, 0x69, 0x6e, 0x67, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x22, 0x0e, 0x0a, 0x0c, 0x50, 0x69, 0x6e, 0x67, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0xc7, 0x01, 0x0a, 0x0d, 0x47, 0x6f, 0x73, 0x73, 0x69, 0x70, 0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x12, 0x18, 0x0a, 0x07, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x07, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x12, 0x3d, 0x0a, 0x0c, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x5f, 0x74, 0x79, 0x70, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x1a, 0x2e, 0x47, 0x6f, 0x73, 0x73, 0x69, 0x70, 0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x2e, 0x43, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x54, 0x79, 0x70, 0x65, 0x52, 0x0b, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x54, 0x79, 0x70, 0x65, 0x12, 0x20, 0x0a, 0x0c, 0x74, 0x69, 0x6d, 0x65, 0x5f, 0x74, 0x6f, 0x5f, 0x6c, 0x69, 0x76, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x0a, 0x74, 0x69, 0x6d, 0x65, 0x54, 0x6f, 0x4c, 0x69, 0x76, 0x65, 0x22, 0x3b, 0x0a, 0x0b, 0x43, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x54, 0x79, 0x70, 0x65, 0x12, 0x16, 0x0a, 0x12, 0x43, 0x4f, 0x4e, 0x54, 0x45, 0x4e, 0x54, 0x5f, 0x54, 0x59, 0x50, 0x45, 0x5f, 0x55, 0x4e, 0x53, 0x45, 0x54, 0x10, 0x00, 0x12, 0x09, 0x0a, 0x05, 0x42, 0x4c, 0x4f, 0x43, 0x4b, 0x10, 0x01, 0x12, 0x09, 0x0a, 0x05, 0x42, 0x41, 0x54, 0x43, 0x48, 0x10, 0x02, 0x22, 0x7f, 0x0a, 0x16, 0x4e, 0x65, 0x74, 0x77, 0x6f, 0x72, 0x6b, 0x41, 0x63, 0x6b, 0x6e, 0x6f, 0x77, 0x6c, 0x65, 0x64, 0x67, 0x65, 0x6d, 0x65, 0x6e, 0x74, 0x12, 0x36, 0x0a, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x1e, 0x2e, 0x4e, 0x65, 0x74, 0x77, 0x6f, 0x72, 0x6b, 0x41, 0x63, 0x6b, 0x6e, 0x6f, 0x77, 0x6c, 0x65, 0x64, 0x67, 0x65, 0x6d, 0x65, 0x6e, 0x74, 0x2e, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x52, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x22, 0x2d, 0x0a, 0x06, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, 0x10, 0x0a, 0x0c, 0x53, 0x54, 0x41, 0x54, 0x55, 0x53, 0x5f, 0x55, 0x4e, 0x53, 0x45, 0x54, 0x10, 0x00, 0x12, 0x06, 0x0a, 0x02, 0x4f, 0x4b, 0x10, 0x01, 0x12, 0x09, 0x0a, 0x05, 0x45, 0x52, 0x52, 0x4f, 0x52, 0x10, 0x02, 0x22, 0x67, 0x0a, 0x12, 0x47, 0x6f, 0x73, 0x73, 0x69, 0x70, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x19, 0x0a, 0x08, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x49, 0x64, 0x12, 0x14, 0x0a, 0x05, 0x6e, 0x6f, 0x6e, 0x63, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x6e, 0x6f, 0x6e, 0x63, 0x65, 0x12, 0x20, 0x0a, 0x0c, 0x74, 0x69, 0x6d, 0x65, 0x5f, 0x74, 0x6f, 0x5f, 0x6c, 0x69, 0x76, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x0a, 0x74, 0x69, 0x6d, 0x65, 0x54, 0x6f, 0x4c, 0x69, 0x76, 0x65, 0x22, 0x2f, 0x0a, 0x13, 0x47, 0x6f, 0x73, 0x73, 0x69, 0x70, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x18, 0x0a, 0x07, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x07, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x22, 0x2f, 0x0a, 0x13, 0x47, 0x6f, 0x73, 0x73, 0x69, 0x70, 0x42, 0x61, 0x74, 0x63, 0x68, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x18, 0x0a, 0x07, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x07, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x22, 0x65, 0x0a, 0x1b, 0x47, 0x6f, 0x73, 0x73, 0x69, 0x70, 0x42, 0x61, 0x74, 0x63, 0x68, 0x42, 0x79, 0x42, 0x61, 0x74, 0x63, 0x68, 0x49, 0x64, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x0e, 0x0a, 0x02, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x02, 0x69, 0x64, 0x12, 0x14, 0x0a, 0x05, 0x6e, 0x6f, 0x6e, 0x63, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x6e, 0x6f, 0x6e, 0x63, 0x65, 0x12, 0x20, 0x0a, 0x0c, 0x74, 0x69, 0x6d, 0x65, 0x5f, 0x74, 0x6f, 0x5f, 0x6c, 0x69, 0x76, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x0a, 0x74, 0x69, 0x6d, 0x65, 0x54, 0x6f, 0x4c, 0x69, 0x76, 0x65, 0x22, 0x6d, 0x0a, 0x21, 0x47, 0x6f, 0x73, 0x73, 0x69, 0x70, 0x42, 0x61, 0x74, 0x63, 0x68, 0x42, 0x79, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x49, 0x64, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x10, 0x0a, 0x03, 0x69, 0x64, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x09, 0x52, 0x03, 0x69, 0x64, 0x73, 0x12, 0x14, 0x0a, 0x05, 0x6e, 0x6f, 0x6e, 0x63, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x6e, 0x6f, 0x6e, 0x63, 0x65, 0x12, 0x20, 0x0a, 0x0c, 0x74, 0x69, 0x6d, 0x65, 0x5f, 0x74, 0x6f, 0x5f, 0x6c, 0x69, 0x76, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x0a, 0x74, 0x69, 0x6d, 0x65, 0x54, 0x6f, 0x4c, 0x69, 0x76, 0x65, 0x22, 0x71, 0x0a, 0x16, 0x47, 0x6f, 0x73, 0x73, 0x69, 0x70, 0x43, 0x6f, 0x6e, 0x73, 0x65, 0x6e, 0x73, 0x75, 0x73, 0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x12, 0x18, 0x0a, 0x07, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x07, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x12, 0x1b, 0x0a, 0x09, 0x73, 0x65, 0x6e, 0x64, 0x65, 0x72, 0x5f, 0x69, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x08, 0x73, 0x65, 0x6e, 0x64, 0x65, 0x72, 0x49, 0x64, 0x12, 0x20, 0x0a, 0x0c, 0x74, 0x69, 0x6d, 0x65, 0x5f, 0x74, 0x6f, 0x5f, 0x6c, 0x69, 0x76, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x0a, 0x74, 0x69, 0x6d, 0x65, 0x54, 0x6f, 0x4c, 0x69, 0x76, 0x65, 0x42, 0x26, 0x0a, 0x15, 0x73, 0x61, 0x77, 0x74, 0x6f, 0x6f, 0x74, 0x68, 0x2e, 0x73, 0x64, 0x6b, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x50, 0x01, 0x5a, 0x0b, 0x6e, 0x65, 0x74, 0x77, 0x6f, 0x72, 0x6b, 0x5f, 0x70, 0x62, 0x32, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( file_protobuf_network_pb2_network_proto_rawDescOnce sync.Once file_protobuf_network_pb2_network_proto_rawDescData = file_protobuf_network_pb2_network_proto_rawDesc ) func file_protobuf_network_pb2_network_proto_rawDescGZIP() []byte { file_protobuf_network_pb2_network_proto_rawDescOnce.Do(func() { file_protobuf_network_pb2_network_proto_rawDescData = protoimpl.X.CompressGZIP(file_protobuf_network_pb2_network_proto_rawDescData) }) return file_protobuf_network_pb2_network_proto_rawDescData } var file_protobuf_network_pb2_network_proto_enumTypes = make([]protoimpl.EnumInfo, 2) var file_protobuf_network_pb2_network_proto_msgTypes = make([]protoimpl.MessageInfo, 15) var file_protobuf_network_pb2_network_proto_goTypes = []interface{}{ (GossipMessage_ContentType)(0), // 0: GossipMessage.ContentType (NetworkAcknowledgement_Status)(0), // 1: NetworkAcknowledgement.Status (*DisconnectMessage)(nil), // 2: DisconnectMessage (*PeerRegisterRequest)(nil), // 3: PeerRegisterRequest (*PeerUnregisterRequest)(nil), // 4: PeerUnregisterRequest (*GetPeersRequest)(nil), // 5: GetPeersRequest (*GetPeersResponse)(nil), // 6: GetPeersResponse (*PingRequest)(nil), // 7: PingRequest (*PingResponse)(nil), // 8: PingResponse (*GossipMessage)(nil), // 9: GossipMessage (*NetworkAcknowledgement)(nil), // 10: NetworkAcknowledgement (*GossipBlockRequest)(nil), // 11: GossipBlockRequest (*GossipBlockResponse)(nil), // 12: GossipBlockResponse (*GossipBatchResponse)(nil), // 13: GossipBatchResponse (*GossipBatchByBatchIdRequest)(nil), // 14: GossipBatchByBatchIdRequest (*GossipBatchByTransactionIdRequest)(nil), // 15: GossipBatchByTransactionIdRequest (*GossipConsensusMessage)(nil), // 16: GossipConsensusMessage } var file_protobuf_network_pb2_network_proto_depIdxs = []int32{ 0, // 0: GossipMessage.content_type:type_name -> GossipMessage.ContentType 1, // 1: NetworkAcknowledgement.status:type_name -> NetworkAcknowledgement.Status 2, // [2:2] is the sub-list for method output_type 2, // [2:2] is the sub-list for method input_type 2, // [2:2] is the sub-list for extension type_name 2, // [2:2] is the sub-list for extension extendee 0, // [0:2] is the sub-list for field type_name } func init() { file_protobuf_network_pb2_network_proto_init() } func file_protobuf_network_pb2_network_proto_init() { if File_protobuf_network_pb2_network_proto != nil { return } if !protoimpl.UnsafeEnabled { file_protobuf_network_pb2_network_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*DisconnectMessage); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_network_pb2_network_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*PeerRegisterRequest); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_network_pb2_network_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*PeerUnregisterRequest); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_network_pb2_network_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*GetPeersRequest); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_network_pb2_network_proto_msgTypes[4].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*GetPeersResponse); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_network_pb2_network_proto_msgTypes[5].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*PingRequest); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_network_pb2_network_proto_msgTypes[6].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*PingResponse); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_network_pb2_network_proto_msgTypes[7].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*GossipMessage); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_network_pb2_network_proto_msgTypes[8].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*NetworkAcknowledgement); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_network_pb2_network_proto_msgTypes[9].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*GossipBlockRequest); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_network_pb2_network_proto_msgTypes[10].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*GossipBlockResponse); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_network_pb2_network_proto_msgTypes[11].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*GossipBatchResponse); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_network_pb2_network_proto_msgTypes[12].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*GossipBatchByBatchIdRequest); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_network_pb2_network_proto_msgTypes[13].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*GossipBatchByTransactionIdRequest); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_network_pb2_network_proto_msgTypes[14].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*GossipConsensusMessage); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: file_protobuf_network_pb2_network_proto_rawDesc, NumEnums: 2, NumMessages: 15, NumExtensions: 0, NumServices: 0, }, GoTypes: file_protobuf_network_pb2_network_proto_goTypes, DependencyIndexes: file_protobuf_network_pb2_network_proto_depIdxs, EnumInfos: file_protobuf_network_pb2_network_proto_enumTypes, MessageInfos: file_protobuf_network_pb2_network_proto_msgTypes, }.Build() File_protobuf_network_pb2_network_proto = out.File file_protobuf_network_pb2_network_proto_rawDesc = nil file_protobuf_network_pb2_network_proto_goTypes = nil file_protobuf_network_pb2_network_proto_depIdxs = nil } <|start_filename|>protobuf/consensus_pb2/consensus.pb.go<|end_filename|> // Copyright 2018 Intel Corporation // // 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. // ----------------------------------------------------------------------------- // Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.25.0-devel // protoc v3.14.0 // source: protobuf/consensus_pb2/consensus.proto package consensus import ( protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" sync "sync" ) const ( // Verify that this generated code is sufficiently up-to-date. _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) // Verify that runtime/protoimpl is sufficiently up-to-date. _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) type ConsensusRegisterResponse_Status int32 const ( ConsensusRegisterResponse_STATUS_UNSET ConsensusRegisterResponse_Status = 0 ConsensusRegisterResponse_OK ConsensusRegisterResponse_Status = 1 ConsensusRegisterResponse_BAD_REQUEST ConsensusRegisterResponse_Status = 2 ConsensusRegisterResponse_SERVICE_ERROR ConsensusRegisterResponse_Status = 3 ConsensusRegisterResponse_NOT_READY ConsensusRegisterResponse_Status = 4 ) // Enum value maps for ConsensusRegisterResponse_Status. var ( ConsensusRegisterResponse_Status_name = map[int32]string{ 0: "STATUS_UNSET", 1: "OK", 2: "BAD_REQUEST", 3: "SERVICE_ERROR", 4: "NOT_READY", } ConsensusRegisterResponse_Status_value = map[string]int32{ "STATUS_UNSET": 0, "OK": 1, "BAD_REQUEST": 2, "SERVICE_ERROR": 3, "NOT_READY": 4, } ) func (x ConsensusRegisterResponse_Status) Enum() *ConsensusRegisterResponse_Status { p := new(ConsensusRegisterResponse_Status) *p = x return p } func (x ConsensusRegisterResponse_Status) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (ConsensusRegisterResponse_Status) Descriptor() protoreflect.EnumDescriptor { return file_protobuf_consensus_pb2_consensus_proto_enumTypes[0].Descriptor() } func (ConsensusRegisterResponse_Status) Type() protoreflect.EnumType { return &file_protobuf_consensus_pb2_consensus_proto_enumTypes[0] } func (x ConsensusRegisterResponse_Status) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use ConsensusRegisterResponse_Status.Descriptor instead. func (ConsensusRegisterResponse_Status) EnumDescriptor() ([]byte, []int) { return file_protobuf_consensus_pb2_consensus_proto_rawDescGZIP(), []int{6, 0} } type ConsensusSendToResponse_Status int32 const ( ConsensusSendToResponse_STATUS_UNSET ConsensusSendToResponse_Status = 0 ConsensusSendToResponse_OK ConsensusSendToResponse_Status = 1 ConsensusSendToResponse_BAD_REQUEST ConsensusSendToResponse_Status = 2 ConsensusSendToResponse_SERVICE_ERROR ConsensusSendToResponse_Status = 3 ConsensusSendToResponse_NOT_READY ConsensusSendToResponse_Status = 4 ConsensusSendToResponse_UNKNOWN_PEER ConsensusSendToResponse_Status = 5 ) // Enum value maps for ConsensusSendToResponse_Status. var ( ConsensusSendToResponse_Status_name = map[int32]string{ 0: "STATUS_UNSET", 1: "OK", 2: "BAD_REQUEST", 3: "SERVICE_ERROR", 4: "NOT_READY", 5: "UNKNOWN_PEER", } ConsensusSendToResponse_Status_value = map[string]int32{ "STATUS_UNSET": 0, "OK": 1, "BAD_REQUEST": 2, "SERVICE_ERROR": 3, "NOT_READY": 4, "UNKNOWN_PEER": 5, } ) func (x ConsensusSendToResponse_Status) Enum() *ConsensusSendToResponse_Status { p := new(ConsensusSendToResponse_Status) *p = x return p } func (x ConsensusSendToResponse_Status) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (ConsensusSendToResponse_Status) Descriptor() protoreflect.EnumDescriptor { return file_protobuf_consensus_pb2_consensus_proto_enumTypes[1].Descriptor() } func (ConsensusSendToResponse_Status) Type() protoreflect.EnumType { return &file_protobuf_consensus_pb2_consensus_proto_enumTypes[1] } func (x ConsensusSendToResponse_Status) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use ConsensusSendToResponse_Status.Descriptor instead. func (ConsensusSendToResponse_Status) EnumDescriptor() ([]byte, []int) { return file_protobuf_consensus_pb2_consensus_proto_rawDescGZIP(), []int{16, 0} } type ConsensusBroadcastResponse_Status int32 const ( ConsensusBroadcastResponse_STATUS_UNSET ConsensusBroadcastResponse_Status = 0 ConsensusBroadcastResponse_OK ConsensusBroadcastResponse_Status = 1 ConsensusBroadcastResponse_BAD_REQUEST ConsensusBroadcastResponse_Status = 2 ConsensusBroadcastResponse_SERVICE_ERROR ConsensusBroadcastResponse_Status = 3 ConsensusBroadcastResponse_NOT_READY ConsensusBroadcastResponse_Status = 4 ) // Enum value maps for ConsensusBroadcastResponse_Status. var ( ConsensusBroadcastResponse_Status_name = map[int32]string{ 0: "STATUS_UNSET", 1: "OK", 2: "BAD_REQUEST", 3: "SERVICE_ERROR", 4: "NOT_READY", } ConsensusBroadcastResponse_Status_value = map[string]int32{ "STATUS_UNSET": 0, "OK": 1, "BAD_REQUEST": 2, "SERVICE_ERROR": 3, "NOT_READY": 4, } ) func (x ConsensusBroadcastResponse_Status) Enum() *ConsensusBroadcastResponse_Status { p := new(ConsensusBroadcastResponse_Status) *p = x return p } func (x ConsensusBroadcastResponse_Status) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (ConsensusBroadcastResponse_Status) Descriptor() protoreflect.EnumDescriptor { return file_protobuf_consensus_pb2_consensus_proto_enumTypes[2].Descriptor() } func (ConsensusBroadcastResponse_Status) Type() protoreflect.EnumType { return &file_protobuf_consensus_pb2_consensus_proto_enumTypes[2] } func (x ConsensusBroadcastResponse_Status) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use ConsensusBroadcastResponse_Status.Descriptor instead. func (ConsensusBroadcastResponse_Status) EnumDescriptor() ([]byte, []int) { return file_protobuf_consensus_pb2_consensus_proto_rawDescGZIP(), []int{18, 0} } type ConsensusInitializeBlockResponse_Status int32 const ( ConsensusInitializeBlockResponse_STATUS_UNSET ConsensusInitializeBlockResponse_Status = 0 ConsensusInitializeBlockResponse_OK ConsensusInitializeBlockResponse_Status = 1 ConsensusInitializeBlockResponse_BAD_REQUEST ConsensusInitializeBlockResponse_Status = 2 ConsensusInitializeBlockResponse_SERVICE_ERROR ConsensusInitializeBlockResponse_Status = 3 ConsensusInitializeBlockResponse_NOT_READY ConsensusInitializeBlockResponse_Status = 4 ConsensusInitializeBlockResponse_INVALID_STATE ConsensusInitializeBlockResponse_Status = 5 ConsensusInitializeBlockResponse_UNKNOWN_BLOCK ConsensusInitializeBlockResponse_Status = 6 ) // Enum value maps for ConsensusInitializeBlockResponse_Status. var ( ConsensusInitializeBlockResponse_Status_name = map[int32]string{ 0: "STATUS_UNSET", 1: "OK", 2: "BAD_REQUEST", 3: "SERVICE_ERROR", 4: "NOT_READY", 5: "INVALID_STATE", 6: "UNKNOWN_BLOCK", } ConsensusInitializeBlockResponse_Status_value = map[string]int32{ "STATUS_UNSET": 0, "OK": 1, "BAD_REQUEST": 2, "SERVICE_ERROR": 3, "NOT_READY": 4, "INVALID_STATE": 5, "UNKNOWN_BLOCK": 6, } ) func (x ConsensusInitializeBlockResponse_Status) Enum() *ConsensusInitializeBlockResponse_Status { p := new(ConsensusInitializeBlockResponse_Status) *p = x return p } func (x ConsensusInitializeBlockResponse_Status) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (ConsensusInitializeBlockResponse_Status) Descriptor() protoreflect.EnumDescriptor { return file_protobuf_consensus_pb2_consensus_proto_enumTypes[3].Descriptor() } func (ConsensusInitializeBlockResponse_Status) Type() protoreflect.EnumType { return &file_protobuf_consensus_pb2_consensus_proto_enumTypes[3] } func (x ConsensusInitializeBlockResponse_Status) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use ConsensusInitializeBlockResponse_Status.Descriptor instead. func (ConsensusInitializeBlockResponse_Status) EnumDescriptor() ([]byte, []int) { return file_protobuf_consensus_pb2_consensus_proto_rawDescGZIP(), []int{20, 0} } type ConsensusSummarizeBlockResponse_Status int32 const ( ConsensusSummarizeBlockResponse_STATUS_UNSET ConsensusSummarizeBlockResponse_Status = 0 ConsensusSummarizeBlockResponse_OK ConsensusSummarizeBlockResponse_Status = 1 ConsensusSummarizeBlockResponse_BAD_REQUEST ConsensusSummarizeBlockResponse_Status = 2 ConsensusSummarizeBlockResponse_SERVICE_ERROR ConsensusSummarizeBlockResponse_Status = 3 ConsensusSummarizeBlockResponse_NOT_READY ConsensusSummarizeBlockResponse_Status = 4 ConsensusSummarizeBlockResponse_INVALID_STATE ConsensusSummarizeBlockResponse_Status = 5 ConsensusSummarizeBlockResponse_BLOCK_NOT_READY ConsensusSummarizeBlockResponse_Status = 6 ) // Enum value maps for ConsensusSummarizeBlockResponse_Status. var ( ConsensusSummarizeBlockResponse_Status_name = map[int32]string{ 0: "STATUS_UNSET", 1: "OK", 2: "BAD_REQUEST", 3: "SERVICE_ERROR", 4: "NOT_READY", 5: "INVALID_STATE", 6: "BLOCK_NOT_READY", } ConsensusSummarizeBlockResponse_Status_value = map[string]int32{ "STATUS_UNSET": 0, "OK": 1, "BAD_REQUEST": 2, "SERVICE_ERROR": 3, "NOT_READY": 4, "INVALID_STATE": 5, "BLOCK_NOT_READY": 6, } ) func (x ConsensusSummarizeBlockResponse_Status) Enum() *ConsensusSummarizeBlockResponse_Status { p := new(ConsensusSummarizeBlockResponse_Status) *p = x return p } func (x ConsensusSummarizeBlockResponse_Status) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (ConsensusSummarizeBlockResponse_Status) Descriptor() protoreflect.EnumDescriptor { return file_protobuf_consensus_pb2_consensus_proto_enumTypes[4].Descriptor() } func (ConsensusSummarizeBlockResponse_Status) Type() protoreflect.EnumType { return &file_protobuf_consensus_pb2_consensus_proto_enumTypes[4] } func (x ConsensusSummarizeBlockResponse_Status) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use ConsensusSummarizeBlockResponse_Status.Descriptor instead. func (ConsensusSummarizeBlockResponse_Status) EnumDescriptor() ([]byte, []int) { return file_protobuf_consensus_pb2_consensus_proto_rawDescGZIP(), []int{22, 0} } type ConsensusFinalizeBlockResponse_Status int32 const ( ConsensusFinalizeBlockResponse_STATUS_UNSET ConsensusFinalizeBlockResponse_Status = 0 ConsensusFinalizeBlockResponse_OK ConsensusFinalizeBlockResponse_Status = 1 ConsensusFinalizeBlockResponse_BAD_REQUEST ConsensusFinalizeBlockResponse_Status = 2 ConsensusFinalizeBlockResponse_SERVICE_ERROR ConsensusFinalizeBlockResponse_Status = 3 ConsensusFinalizeBlockResponse_NOT_READY ConsensusFinalizeBlockResponse_Status = 4 ConsensusFinalizeBlockResponse_INVALID_STATE ConsensusFinalizeBlockResponse_Status = 5 ConsensusFinalizeBlockResponse_BLOCK_NOT_READY ConsensusFinalizeBlockResponse_Status = 6 ) // Enum value maps for ConsensusFinalizeBlockResponse_Status. var ( ConsensusFinalizeBlockResponse_Status_name = map[int32]string{ 0: "STATUS_UNSET", 1: "OK", 2: "BAD_REQUEST", 3: "SERVICE_ERROR", 4: "NOT_READY", 5: "INVALID_STATE", 6: "BLOCK_NOT_READY", } ConsensusFinalizeBlockResponse_Status_value = map[string]int32{ "STATUS_UNSET": 0, "OK": 1, "BAD_REQUEST": 2, "SERVICE_ERROR": 3, "NOT_READY": 4, "INVALID_STATE": 5, "BLOCK_NOT_READY": 6, } ) func (x ConsensusFinalizeBlockResponse_Status) Enum() *ConsensusFinalizeBlockResponse_Status { p := new(ConsensusFinalizeBlockResponse_Status) *p = x return p } func (x ConsensusFinalizeBlockResponse_Status) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (ConsensusFinalizeBlockResponse_Status) Descriptor() protoreflect.EnumDescriptor { return file_protobuf_consensus_pb2_consensus_proto_enumTypes[5].Descriptor() } func (ConsensusFinalizeBlockResponse_Status) Type() protoreflect.EnumType { return &file_protobuf_consensus_pb2_consensus_proto_enumTypes[5] } func (x ConsensusFinalizeBlockResponse_Status) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use ConsensusFinalizeBlockResponse_Status.Descriptor instead. func (ConsensusFinalizeBlockResponse_Status) EnumDescriptor() ([]byte, []int) { return file_protobuf_consensus_pb2_consensus_proto_rawDescGZIP(), []int{24, 0} } type ConsensusCancelBlockResponse_Status int32 const ( ConsensusCancelBlockResponse_STATUS_UNSET ConsensusCancelBlockResponse_Status = 0 ConsensusCancelBlockResponse_OK ConsensusCancelBlockResponse_Status = 1 ConsensusCancelBlockResponse_BAD_REQUEST ConsensusCancelBlockResponse_Status = 2 ConsensusCancelBlockResponse_SERVICE_ERROR ConsensusCancelBlockResponse_Status = 3 ConsensusCancelBlockResponse_NOT_READY ConsensusCancelBlockResponse_Status = 4 ConsensusCancelBlockResponse_INVALID_STATE ConsensusCancelBlockResponse_Status = 5 ) // Enum value maps for ConsensusCancelBlockResponse_Status. var ( ConsensusCancelBlockResponse_Status_name = map[int32]string{ 0: "STATUS_UNSET", 1: "OK", 2: "BAD_REQUEST", 3: "SERVICE_ERROR", 4: "NOT_READY", 5: "INVALID_STATE", } ConsensusCancelBlockResponse_Status_value = map[string]int32{ "STATUS_UNSET": 0, "OK": 1, "BAD_REQUEST": 2, "SERVICE_ERROR": 3, "NOT_READY": 4, "INVALID_STATE": 5, } ) func (x ConsensusCancelBlockResponse_Status) Enum() *ConsensusCancelBlockResponse_Status { p := new(ConsensusCancelBlockResponse_Status) *p = x return p } func (x ConsensusCancelBlockResponse_Status) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (ConsensusCancelBlockResponse_Status) Descriptor() protoreflect.EnumDescriptor { return file_protobuf_consensus_pb2_consensus_proto_enumTypes[6].Descriptor() } func (ConsensusCancelBlockResponse_Status) Type() protoreflect.EnumType { return &file_protobuf_consensus_pb2_consensus_proto_enumTypes[6] } func (x ConsensusCancelBlockResponse_Status) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use ConsensusCancelBlockResponse_Status.Descriptor instead. func (ConsensusCancelBlockResponse_Status) EnumDescriptor() ([]byte, []int) { return file_protobuf_consensus_pb2_consensus_proto_rawDescGZIP(), []int{26, 0} } type ConsensusCheckBlocksResponse_Status int32 const ( ConsensusCheckBlocksResponse_STATUS_UNSET ConsensusCheckBlocksResponse_Status = 0 ConsensusCheckBlocksResponse_OK ConsensusCheckBlocksResponse_Status = 1 ConsensusCheckBlocksResponse_BAD_REQUEST ConsensusCheckBlocksResponse_Status = 2 ConsensusCheckBlocksResponse_SERVICE_ERROR ConsensusCheckBlocksResponse_Status = 3 ConsensusCheckBlocksResponse_NOT_READY ConsensusCheckBlocksResponse_Status = 4 ConsensusCheckBlocksResponse_UNKNOWN_BLOCK ConsensusCheckBlocksResponse_Status = 5 ) // Enum value maps for ConsensusCheckBlocksResponse_Status. var ( ConsensusCheckBlocksResponse_Status_name = map[int32]string{ 0: "STATUS_UNSET", 1: "OK", 2: "BAD_REQUEST", 3: "SERVICE_ERROR", 4: "NOT_READY", 5: "UNKNOWN_BLOCK", } ConsensusCheckBlocksResponse_Status_value = map[string]int32{ "STATUS_UNSET": 0, "OK": 1, "BAD_REQUEST": 2, "SERVICE_ERROR": 3, "NOT_READY": 4, "UNKNOWN_BLOCK": 5, } ) func (x ConsensusCheckBlocksResponse_Status) Enum() *ConsensusCheckBlocksResponse_Status { p := new(ConsensusCheckBlocksResponse_Status) *p = x return p } func (x ConsensusCheckBlocksResponse_Status) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (ConsensusCheckBlocksResponse_Status) Descriptor() protoreflect.EnumDescriptor { return file_protobuf_consensus_pb2_consensus_proto_enumTypes[7].Descriptor() } func (ConsensusCheckBlocksResponse_Status) Type() protoreflect.EnumType { return &file_protobuf_consensus_pb2_consensus_proto_enumTypes[7] } func (x ConsensusCheckBlocksResponse_Status) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use ConsensusCheckBlocksResponse_Status.Descriptor instead. func (ConsensusCheckBlocksResponse_Status) EnumDescriptor() ([]byte, []int) { return file_protobuf_consensus_pb2_consensus_proto_rawDescGZIP(), []int{28, 0} } type ConsensusCommitBlockResponse_Status int32 const ( ConsensusCommitBlockResponse_STATUS_UNSET ConsensusCommitBlockResponse_Status = 0 ConsensusCommitBlockResponse_OK ConsensusCommitBlockResponse_Status = 1 ConsensusCommitBlockResponse_BAD_REQUEST ConsensusCommitBlockResponse_Status = 2 ConsensusCommitBlockResponse_SERVICE_ERROR ConsensusCommitBlockResponse_Status = 3 ConsensusCommitBlockResponse_NOT_READY ConsensusCommitBlockResponse_Status = 4 ConsensusCommitBlockResponse_UNKNOWN_BLOCK ConsensusCommitBlockResponse_Status = 5 ) // Enum value maps for ConsensusCommitBlockResponse_Status. var ( ConsensusCommitBlockResponse_Status_name = map[int32]string{ 0: "STATUS_UNSET", 1: "OK", 2: "BAD_REQUEST", 3: "SERVICE_ERROR", 4: "NOT_READY", 5: "UNKNOWN_BLOCK", } ConsensusCommitBlockResponse_Status_value = map[string]int32{ "STATUS_UNSET": 0, "OK": 1, "BAD_REQUEST": 2, "SERVICE_ERROR": 3, "NOT_READY": 4, "UNKNOWN_BLOCK": 5, } ) func (x ConsensusCommitBlockResponse_Status) Enum() *ConsensusCommitBlockResponse_Status { p := new(ConsensusCommitBlockResponse_Status) *p = x return p } func (x ConsensusCommitBlockResponse_Status) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (ConsensusCommitBlockResponse_Status) Descriptor() protoreflect.EnumDescriptor { return file_protobuf_consensus_pb2_consensus_proto_enumTypes[8].Descriptor() } func (ConsensusCommitBlockResponse_Status) Type() protoreflect.EnumType { return &file_protobuf_consensus_pb2_consensus_proto_enumTypes[8] } func (x ConsensusCommitBlockResponse_Status) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use ConsensusCommitBlockResponse_Status.Descriptor instead. func (ConsensusCommitBlockResponse_Status) EnumDescriptor() ([]byte, []int) { return file_protobuf_consensus_pb2_consensus_proto_rawDescGZIP(), []int{30, 0} } type ConsensusIgnoreBlockResponse_Status int32 const ( ConsensusIgnoreBlockResponse_STATUS_UNSET ConsensusIgnoreBlockResponse_Status = 0 ConsensusIgnoreBlockResponse_OK ConsensusIgnoreBlockResponse_Status = 1 ConsensusIgnoreBlockResponse_BAD_REQUEST ConsensusIgnoreBlockResponse_Status = 2 ConsensusIgnoreBlockResponse_SERVICE_ERROR ConsensusIgnoreBlockResponse_Status = 3 ConsensusIgnoreBlockResponse_NOT_READY ConsensusIgnoreBlockResponse_Status = 4 ConsensusIgnoreBlockResponse_UNKNOWN_BLOCK ConsensusIgnoreBlockResponse_Status = 5 ) // Enum value maps for ConsensusIgnoreBlockResponse_Status. var ( ConsensusIgnoreBlockResponse_Status_name = map[int32]string{ 0: "STATUS_UNSET", 1: "OK", 2: "BAD_REQUEST", 3: "SERVICE_ERROR", 4: "NOT_READY", 5: "UNKNOWN_BLOCK", } ConsensusIgnoreBlockResponse_Status_value = map[string]int32{ "STATUS_UNSET": 0, "OK": 1, "BAD_REQUEST": 2, "SERVICE_ERROR": 3, "NOT_READY": 4, "UNKNOWN_BLOCK": 5, } ) func (x ConsensusIgnoreBlockResponse_Status) Enum() *ConsensusIgnoreBlockResponse_Status { p := new(ConsensusIgnoreBlockResponse_Status) *p = x return p } func (x ConsensusIgnoreBlockResponse_Status) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (ConsensusIgnoreBlockResponse_Status) Descriptor() protoreflect.EnumDescriptor { return file_protobuf_consensus_pb2_consensus_proto_enumTypes[9].Descriptor() } func (ConsensusIgnoreBlockResponse_Status) Type() protoreflect.EnumType { return &file_protobuf_consensus_pb2_consensus_proto_enumTypes[9] } func (x ConsensusIgnoreBlockResponse_Status) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use ConsensusIgnoreBlockResponse_Status.Descriptor instead. func (ConsensusIgnoreBlockResponse_Status) EnumDescriptor() ([]byte, []int) { return file_protobuf_consensus_pb2_consensus_proto_rawDescGZIP(), []int{32, 0} } type ConsensusFailBlockResponse_Status int32 const ( ConsensusFailBlockResponse_STATUS_UNSET ConsensusFailBlockResponse_Status = 0 ConsensusFailBlockResponse_OK ConsensusFailBlockResponse_Status = 1 ConsensusFailBlockResponse_BAD_REQUEST ConsensusFailBlockResponse_Status = 2 ConsensusFailBlockResponse_SERVICE_ERROR ConsensusFailBlockResponse_Status = 3 ConsensusFailBlockResponse_NOT_READY ConsensusFailBlockResponse_Status = 4 ConsensusFailBlockResponse_UNKNOWN_BLOCK ConsensusFailBlockResponse_Status = 5 ) // Enum value maps for ConsensusFailBlockResponse_Status. var ( ConsensusFailBlockResponse_Status_name = map[int32]string{ 0: "STATUS_UNSET", 1: "OK", 2: "BAD_REQUEST", 3: "SERVICE_ERROR", 4: "NOT_READY", 5: "UNKNOWN_BLOCK", } ConsensusFailBlockResponse_Status_value = map[string]int32{ "STATUS_UNSET": 0, "OK": 1, "BAD_REQUEST": 2, "SERVICE_ERROR": 3, "NOT_READY": 4, "UNKNOWN_BLOCK": 5, } ) func (x ConsensusFailBlockResponse_Status) Enum() *ConsensusFailBlockResponse_Status { p := new(ConsensusFailBlockResponse_Status) *p = x return p } func (x ConsensusFailBlockResponse_Status) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (ConsensusFailBlockResponse_Status) Descriptor() protoreflect.EnumDescriptor { return file_protobuf_consensus_pb2_consensus_proto_enumTypes[10].Descriptor() } func (ConsensusFailBlockResponse_Status) Type() protoreflect.EnumType { return &file_protobuf_consensus_pb2_consensus_proto_enumTypes[10] } func (x ConsensusFailBlockResponse_Status) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use ConsensusFailBlockResponse_Status.Descriptor instead. func (ConsensusFailBlockResponse_Status) EnumDescriptor() ([]byte, []int) { return file_protobuf_consensus_pb2_consensus_proto_rawDescGZIP(), []int{34, 0} } type ConsensusBlocksGetResponse_Status int32 const ( ConsensusBlocksGetResponse_STATUS_UNSET ConsensusBlocksGetResponse_Status = 0 ConsensusBlocksGetResponse_OK ConsensusBlocksGetResponse_Status = 1 ConsensusBlocksGetResponse_BAD_REQUEST ConsensusBlocksGetResponse_Status = 2 ConsensusBlocksGetResponse_SERVICE_ERROR ConsensusBlocksGetResponse_Status = 3 ConsensusBlocksGetResponse_NOT_READY ConsensusBlocksGetResponse_Status = 4 ConsensusBlocksGetResponse_UNKNOWN_BLOCK ConsensusBlocksGetResponse_Status = 5 ) // Enum value maps for ConsensusBlocksGetResponse_Status. var ( ConsensusBlocksGetResponse_Status_name = map[int32]string{ 0: "STATUS_UNSET", 1: "OK", 2: "BAD_REQUEST", 3: "SERVICE_ERROR", 4: "NOT_READY", 5: "UNKNOWN_BLOCK", } ConsensusBlocksGetResponse_Status_value = map[string]int32{ "STATUS_UNSET": 0, "OK": 1, "BAD_REQUEST": 2, "SERVICE_ERROR": 3, "NOT_READY": 4, "UNKNOWN_BLOCK": 5, } ) func (x ConsensusBlocksGetResponse_Status) Enum() *ConsensusBlocksGetResponse_Status { p := new(ConsensusBlocksGetResponse_Status) *p = x return p } func (x ConsensusBlocksGetResponse_Status) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (ConsensusBlocksGetResponse_Status) Descriptor() protoreflect.EnumDescriptor { return file_protobuf_consensus_pb2_consensus_proto_enumTypes[11].Descriptor() } func (ConsensusBlocksGetResponse_Status) Type() protoreflect.EnumType { return &file_protobuf_consensus_pb2_consensus_proto_enumTypes[11] } func (x ConsensusBlocksGetResponse_Status) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use ConsensusBlocksGetResponse_Status.Descriptor instead. func (ConsensusBlocksGetResponse_Status) EnumDescriptor() ([]byte, []int) { return file_protobuf_consensus_pb2_consensus_proto_rawDescGZIP(), []int{36, 0} } type ConsensusChainHeadGetResponse_Status int32 const ( ConsensusChainHeadGetResponse_STATUS_UNSET ConsensusChainHeadGetResponse_Status = 0 ConsensusChainHeadGetResponse_OK ConsensusChainHeadGetResponse_Status = 1 ConsensusChainHeadGetResponse_BAD_REQUEST ConsensusChainHeadGetResponse_Status = 2 ConsensusChainHeadGetResponse_SERVICE_ERROR ConsensusChainHeadGetResponse_Status = 3 ConsensusChainHeadGetResponse_NOT_READY ConsensusChainHeadGetResponse_Status = 4 ConsensusChainHeadGetResponse_NO_CHAIN_HEAD ConsensusChainHeadGetResponse_Status = 5 ) // Enum value maps for ConsensusChainHeadGetResponse_Status. var ( ConsensusChainHeadGetResponse_Status_name = map[int32]string{ 0: "STATUS_UNSET", 1: "OK", 2: "BAD_REQUEST", 3: "SERVICE_ERROR", 4: "NOT_READY", 5: "NO_CHAIN_HEAD", } ConsensusChainHeadGetResponse_Status_value = map[string]int32{ "STATUS_UNSET": 0, "OK": 1, "BAD_REQUEST": 2, "SERVICE_ERROR": 3, "NOT_READY": 4, "NO_CHAIN_HEAD": 5, } ) func (x ConsensusChainHeadGetResponse_Status) Enum() *ConsensusChainHeadGetResponse_Status { p := new(ConsensusChainHeadGetResponse_Status) *p = x return p } func (x ConsensusChainHeadGetResponse_Status) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (ConsensusChainHeadGetResponse_Status) Descriptor() protoreflect.EnumDescriptor { return file_protobuf_consensus_pb2_consensus_proto_enumTypes[12].Descriptor() } func (ConsensusChainHeadGetResponse_Status) Type() protoreflect.EnumType { return &file_protobuf_consensus_pb2_consensus_proto_enumTypes[12] } func (x ConsensusChainHeadGetResponse_Status) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use ConsensusChainHeadGetResponse_Status.Descriptor instead. func (ConsensusChainHeadGetResponse_Status) EnumDescriptor() ([]byte, []int) { return file_protobuf_consensus_pb2_consensus_proto_rawDescGZIP(), []int{38, 0} } type ConsensusSettingsGetResponse_Status int32 const ( ConsensusSettingsGetResponse_STATUS_UNSET ConsensusSettingsGetResponse_Status = 0 ConsensusSettingsGetResponse_OK ConsensusSettingsGetResponse_Status = 1 ConsensusSettingsGetResponse_BAD_REQUEST ConsensusSettingsGetResponse_Status = 2 ConsensusSettingsGetResponse_SERVICE_ERROR ConsensusSettingsGetResponse_Status = 3 ConsensusSettingsGetResponse_NOT_READY ConsensusSettingsGetResponse_Status = 4 ConsensusSettingsGetResponse_UNKNOWN_BLOCK ConsensusSettingsGetResponse_Status = 5 ) // Enum value maps for ConsensusSettingsGetResponse_Status. var ( ConsensusSettingsGetResponse_Status_name = map[int32]string{ 0: "STATUS_UNSET", 1: "OK", 2: "BAD_REQUEST", 3: "SERVICE_ERROR", 4: "NOT_READY", 5: "UNKNOWN_BLOCK", } ConsensusSettingsGetResponse_Status_value = map[string]int32{ "STATUS_UNSET": 0, "OK": 1, "BAD_REQUEST": 2, "SERVICE_ERROR": 3, "NOT_READY": 4, "UNKNOWN_BLOCK": 5, } ) func (x ConsensusSettingsGetResponse_Status) Enum() *ConsensusSettingsGetResponse_Status { p := new(ConsensusSettingsGetResponse_Status) *p = x return p } func (x ConsensusSettingsGetResponse_Status) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (ConsensusSettingsGetResponse_Status) Descriptor() protoreflect.EnumDescriptor { return file_protobuf_consensus_pb2_consensus_proto_enumTypes[13].Descriptor() } func (ConsensusSettingsGetResponse_Status) Type() protoreflect.EnumType { return &file_protobuf_consensus_pb2_consensus_proto_enumTypes[13] } func (x ConsensusSettingsGetResponse_Status) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use ConsensusSettingsGetResponse_Status.Descriptor instead. func (ConsensusSettingsGetResponse_Status) EnumDescriptor() ([]byte, []int) { return file_protobuf_consensus_pb2_consensus_proto_rawDescGZIP(), []int{40, 0} } type ConsensusStateGetResponse_Status int32 const ( ConsensusStateGetResponse_STATUS_UNSET ConsensusStateGetResponse_Status = 0 ConsensusStateGetResponse_OK ConsensusStateGetResponse_Status = 1 ConsensusStateGetResponse_BAD_REQUEST ConsensusStateGetResponse_Status = 2 ConsensusStateGetResponse_SERVICE_ERROR ConsensusStateGetResponse_Status = 3 ConsensusStateGetResponse_NOT_READY ConsensusStateGetResponse_Status = 4 ConsensusStateGetResponse_UNKNOWN_BLOCK ConsensusStateGetResponse_Status = 5 ) // Enum value maps for ConsensusStateGetResponse_Status. var ( ConsensusStateGetResponse_Status_name = map[int32]string{ 0: "STATUS_UNSET", 1: "OK", 2: "BAD_REQUEST", 3: "SERVICE_ERROR", 4: "NOT_READY", 5: "UNKNOWN_BLOCK", } ConsensusStateGetResponse_Status_value = map[string]int32{ "STATUS_UNSET": 0, "OK": 1, "BAD_REQUEST": 2, "SERVICE_ERROR": 3, "NOT_READY": 4, "UNKNOWN_BLOCK": 5, } ) func (x ConsensusStateGetResponse_Status) Enum() *ConsensusStateGetResponse_Status { p := new(ConsensusStateGetResponse_Status) *p = x return p } func (x ConsensusStateGetResponse_Status) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (ConsensusStateGetResponse_Status) Descriptor() protoreflect.EnumDescriptor { return file_protobuf_consensus_pb2_consensus_proto_enumTypes[14].Descriptor() } func (ConsensusStateGetResponse_Status) Type() protoreflect.EnumType { return &file_protobuf_consensus_pb2_consensus_proto_enumTypes[14] } func (x ConsensusStateGetResponse_Status) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use ConsensusStateGetResponse_Status.Descriptor instead. func (ConsensusStateGetResponse_Status) EnumDescriptor() ([]byte, []int) { return file_protobuf_consensus_pb2_consensus_proto_rawDescGZIP(), []int{42, 0} } // A consensus-related message sent between peers type ConsensusPeerMessage struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // Interpretation is left to the consensus engine implementation MessageType string `protobuf:"bytes,1,opt,name=message_type,json=messageType,proto3" json:"message_type,omitempty"` // The opaque payload to send to other nodes Content []byte `protobuf:"bytes,2,opt,name=content,proto3" json:"content,omitempty"` // Used to identify the consensus engine that produced this message Name string `protobuf:"bytes,3,opt,name=name,proto3" json:"name,omitempty"` Version string `protobuf:"bytes,4,opt,name=version,proto3" json:"version,omitempty"` } func (x *ConsensusPeerMessage) Reset() { *x = ConsensusPeerMessage{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_consensus_pb2_consensus_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ConsensusPeerMessage) String() string { return protoimpl.X.MessageStringOf(x) } func (*ConsensusPeerMessage) ProtoMessage() {} func (x *ConsensusPeerMessage) ProtoReflect() protoreflect.Message { mi := &file_protobuf_consensus_pb2_consensus_proto_msgTypes[0] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ConsensusPeerMessage.ProtoReflect.Descriptor instead. func (*ConsensusPeerMessage) Descriptor() ([]byte, []int) { return file_protobuf_consensus_pb2_consensus_proto_rawDescGZIP(), []int{0} } func (x *ConsensusPeerMessage) GetMessageType() string { if x != nil { return x.MessageType } return "" } func (x *ConsensusPeerMessage) GetContent() []byte { if x != nil { return x.Content } return nil } func (x *ConsensusPeerMessage) GetName() string { if x != nil { return x.Name } return "" } func (x *ConsensusPeerMessage) GetVersion() string { if x != nil { return x.Version } return "" } // All information about a block that is relevant to consensus type ConsensusBlock struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields BlockId []byte `protobuf:"bytes,1,opt,name=block_id,json=blockId,proto3" json:"block_id,omitempty"` PreviousId []byte `protobuf:"bytes,2,opt,name=previous_id,json=previousId,proto3" json:"previous_id,omitempty"` // The id of peer that signed this block SignerId []byte `protobuf:"bytes,3,opt,name=signer_id,json=signerId,proto3" json:"signer_id,omitempty"` BlockNum uint64 `protobuf:"varint,4,opt,name=block_num,json=blockNum,proto3" json:"block_num,omitempty"` Payload []byte `protobuf:"bytes,5,opt,name=payload,proto3" json:"payload,omitempty"` // A summary of the contents of the block Summary []byte `protobuf:"bytes,6,opt,name=summary,proto3" json:"summary,omitempty"` } func (x *ConsensusBlock) Reset() { *x = ConsensusBlock{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_consensus_pb2_consensus_proto_msgTypes[1] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ConsensusBlock) String() string { return protoimpl.X.MessageStringOf(x) } func (*ConsensusBlock) ProtoMessage() {} func (x *ConsensusBlock) ProtoReflect() protoreflect.Message { mi := &file_protobuf_consensus_pb2_consensus_proto_msgTypes[1] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ConsensusBlock.ProtoReflect.Descriptor instead. func (*ConsensusBlock) Descriptor() ([]byte, []int) { return file_protobuf_consensus_pb2_consensus_proto_rawDescGZIP(), []int{1} } func (x *ConsensusBlock) GetBlockId() []byte { if x != nil { return x.BlockId } return nil } func (x *ConsensusBlock) GetPreviousId() []byte { if x != nil { return x.PreviousId } return nil } func (x *ConsensusBlock) GetSignerId() []byte { if x != nil { return x.SignerId } return nil } func (x *ConsensusBlock) GetBlockNum() uint64 { if x != nil { return x.BlockNum } return 0 } func (x *ConsensusBlock) GetPayload() []byte { if x != nil { return x.Payload } return nil } func (x *ConsensusBlock) GetSummary() []byte { if x != nil { return x.Summary } return nil } // Information about a peer that is relevant to consensus type ConsensusPeerInfo struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // The unique id for this peer. This can be correlated with the signer id // on consensus blocks. PeerId []byte `protobuf:"bytes,1,opt,name=peer_id,json=peerId,proto3" json:"peer_id,omitempty"` } func (x *ConsensusPeerInfo) Reset() { *x = ConsensusPeerInfo{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_consensus_pb2_consensus_proto_msgTypes[2] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ConsensusPeerInfo) String() string { return protoimpl.X.MessageStringOf(x) } func (*ConsensusPeerInfo) ProtoMessage() {} func (x *ConsensusPeerInfo) ProtoReflect() protoreflect.Message { mi := &file_protobuf_consensus_pb2_consensus_proto_msgTypes[2] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ConsensusPeerInfo.ProtoReflect.Descriptor instead. func (*ConsensusPeerInfo) Descriptor() ([]byte, []int) { return file_protobuf_consensus_pb2_consensus_proto_rawDescGZIP(), []int{2} } func (x *ConsensusPeerInfo) GetPeerId() []byte { if x != nil { return x.PeerId } return nil } // A settings key-value pair type ConsensusSettingsEntry struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Key string `protobuf:"bytes,1,opt,name=key,proto3" json:"key,omitempty"` Value string `protobuf:"bytes,2,opt,name=value,proto3" json:"value,omitempty"` } func (x *ConsensusSettingsEntry) Reset() { *x = ConsensusSettingsEntry{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_consensus_pb2_consensus_proto_msgTypes[3] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ConsensusSettingsEntry) String() string { return protoimpl.X.MessageStringOf(x) } func (*ConsensusSettingsEntry) ProtoMessage() {} func (x *ConsensusSettingsEntry) ProtoReflect() protoreflect.Message { mi := &file_protobuf_consensus_pb2_consensus_proto_msgTypes[3] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ConsensusSettingsEntry.ProtoReflect.Descriptor instead. func (*ConsensusSettingsEntry) Descriptor() ([]byte, []int) { return file_protobuf_consensus_pb2_consensus_proto_rawDescGZIP(), []int{3} } func (x *ConsensusSettingsEntry) GetKey() string { if x != nil { return x.Key } return "" } func (x *ConsensusSettingsEntry) GetValue() string { if x != nil { return x.Value } return "" } // A state key-value pair type ConsensusStateEntry struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Address string `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty"` Data []byte `protobuf:"bytes,2,opt,name=data,proto3" json:"data,omitempty"` } func (x *ConsensusStateEntry) Reset() { *x = ConsensusStateEntry{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_consensus_pb2_consensus_proto_msgTypes[4] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ConsensusStateEntry) String() string { return protoimpl.X.MessageStringOf(x) } func (*ConsensusStateEntry) ProtoMessage() {} func (x *ConsensusStateEntry) ProtoReflect() protoreflect.Message { mi := &file_protobuf_consensus_pb2_consensus_proto_msgTypes[4] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ConsensusStateEntry.ProtoReflect.Descriptor instead. func (*ConsensusStateEntry) Descriptor() ([]byte, []int) { return file_protobuf_consensus_pb2_consensus_proto_rawDescGZIP(), []int{4} } func (x *ConsensusStateEntry) GetAddress() string { if x != nil { return x.Address } return "" } func (x *ConsensusStateEntry) GetData() []byte { if x != nil { return x.Data } return nil } // Sent to connect with the validator type ConsensusRegisterRequest struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // The name of this consensus engine Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` // The version of this consensus engine Version string `protobuf:"bytes,2,opt,name=version,proto3" json:"version,omitempty"` } func (x *ConsensusRegisterRequest) Reset() { *x = ConsensusRegisterRequest{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_consensus_pb2_consensus_proto_msgTypes[5] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ConsensusRegisterRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*ConsensusRegisterRequest) ProtoMessage() {} func (x *ConsensusRegisterRequest) ProtoReflect() protoreflect.Message { mi := &file_protobuf_consensus_pb2_consensus_proto_msgTypes[5] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ConsensusRegisterRequest.ProtoReflect.Descriptor instead. func (*ConsensusRegisterRequest) Descriptor() ([]byte, []int) { return file_protobuf_consensus_pb2_consensus_proto_rawDescGZIP(), []int{5} } func (x *ConsensusRegisterRequest) GetName() string { if x != nil { return x.Name } return "" } func (x *ConsensusRegisterRequest) GetVersion() string { if x != nil { return x.Version } return "" } type ConsensusRegisterResponse struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Status ConsensusRegisterResponse_Status `protobuf:"varint,1,opt,name=status,proto3,enum=ConsensusRegisterResponse_Status" json:"status,omitempty"` // Startup Info ChainHead *ConsensusBlock `protobuf:"bytes,2,opt,name=chain_head,json=chainHead,proto3" json:"chain_head,omitempty"` Peers []*ConsensusPeerInfo `protobuf:"bytes,3,rep,name=peers,proto3" json:"peers,omitempty"` LocalPeerInfo *ConsensusPeerInfo `protobuf:"bytes,4,opt,name=local_peer_info,json=localPeerInfo,proto3" json:"local_peer_info,omitempty"` } func (x *ConsensusRegisterResponse) Reset() { *x = ConsensusRegisterResponse{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_consensus_pb2_consensus_proto_msgTypes[6] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ConsensusRegisterResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*ConsensusRegisterResponse) ProtoMessage() {} func (x *ConsensusRegisterResponse) ProtoReflect() protoreflect.Message { mi := &file_protobuf_consensus_pb2_consensus_proto_msgTypes[6] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ConsensusRegisterResponse.ProtoReflect.Descriptor instead. func (*ConsensusRegisterResponse) Descriptor() ([]byte, []int) { return file_protobuf_consensus_pb2_consensus_proto_rawDescGZIP(), []int{6} } func (x *ConsensusRegisterResponse) GetStatus() ConsensusRegisterResponse_Status { if x != nil { return x.Status } return ConsensusRegisterResponse_STATUS_UNSET } func (x *ConsensusRegisterResponse) GetChainHead() *ConsensusBlock { if x != nil { return x.ChainHead } return nil } func (x *ConsensusRegisterResponse) GetPeers() []*ConsensusPeerInfo { if x != nil { return x.Peers } return nil } func (x *ConsensusRegisterResponse) GetLocalPeerInfo() *ConsensusPeerInfo { if x != nil { return x.LocalPeerInfo } return nil } // A new peer was added type ConsensusNotifyPeerConnected struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields PeerInfo *ConsensusPeerInfo `protobuf:"bytes,1,opt,name=peer_info,json=peerInfo,proto3" json:"peer_info,omitempty"` } func (x *ConsensusNotifyPeerConnected) Reset() { *x = ConsensusNotifyPeerConnected{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_consensus_pb2_consensus_proto_msgTypes[7] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ConsensusNotifyPeerConnected) String() string { return protoimpl.X.MessageStringOf(x) } func (*ConsensusNotifyPeerConnected) ProtoMessage() {} func (x *ConsensusNotifyPeerConnected) ProtoReflect() protoreflect.Message { mi := &file_protobuf_consensus_pb2_consensus_proto_msgTypes[7] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ConsensusNotifyPeerConnected.ProtoReflect.Descriptor instead. func (*ConsensusNotifyPeerConnected) Descriptor() ([]byte, []int) { return file_protobuf_consensus_pb2_consensus_proto_rawDescGZIP(), []int{7} } func (x *ConsensusNotifyPeerConnected) GetPeerInfo() *ConsensusPeerInfo { if x != nil { return x.PeerInfo } return nil } // An existing peer was dropped type ConsensusNotifyPeerDisconnected struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields PeerId []byte `protobuf:"bytes,1,opt,name=peer_id,json=peerId,proto3" json:"peer_id,omitempty"` } func (x *ConsensusNotifyPeerDisconnected) Reset() { *x = ConsensusNotifyPeerDisconnected{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_consensus_pb2_consensus_proto_msgTypes[8] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ConsensusNotifyPeerDisconnected) String() string { return protoimpl.X.MessageStringOf(x) } func (*ConsensusNotifyPeerDisconnected) ProtoMessage() {} func (x *ConsensusNotifyPeerDisconnected) ProtoReflect() protoreflect.Message { mi := &file_protobuf_consensus_pb2_consensus_proto_msgTypes[8] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ConsensusNotifyPeerDisconnected.ProtoReflect.Descriptor instead. func (*ConsensusNotifyPeerDisconnected) Descriptor() ([]byte, []int) { return file_protobuf_consensus_pb2_consensus_proto_rawDescGZIP(), []int{8} } func (x *ConsensusNotifyPeerDisconnected) GetPeerId() []byte { if x != nil { return x.PeerId } return nil } // A new message was received from a peer type ConsensusNotifyPeerMessage struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Message *ConsensusPeerMessage `protobuf:"bytes,1,opt,name=message,proto3" json:"message,omitempty"` SenderId []byte `protobuf:"bytes,2,opt,name=sender_id,json=senderId,proto3" json:"sender_id,omitempty"` } func (x *ConsensusNotifyPeerMessage) Reset() { *x = ConsensusNotifyPeerMessage{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_consensus_pb2_consensus_proto_msgTypes[9] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ConsensusNotifyPeerMessage) String() string { return protoimpl.X.MessageStringOf(x) } func (*ConsensusNotifyPeerMessage) ProtoMessage() {} func (x *ConsensusNotifyPeerMessage) ProtoReflect() protoreflect.Message { mi := &file_protobuf_consensus_pb2_consensus_proto_msgTypes[9] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ConsensusNotifyPeerMessage.ProtoReflect.Descriptor instead. func (*ConsensusNotifyPeerMessage) Descriptor() ([]byte, []int) { return file_protobuf_consensus_pb2_consensus_proto_rawDescGZIP(), []int{9} } func (x *ConsensusNotifyPeerMessage) GetMessage() *ConsensusPeerMessage { if x != nil { return x.Message } return nil } func (x *ConsensusNotifyPeerMessage) GetSenderId() []byte { if x != nil { return x.SenderId } return nil } // A new block was received and passed initial consensus validation type ConsensusNotifyBlockNew struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Block *ConsensusBlock `protobuf:"bytes,1,opt,name=block,proto3" json:"block,omitempty"` } func (x *ConsensusNotifyBlockNew) Reset() { *x = ConsensusNotifyBlockNew{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_consensus_pb2_consensus_proto_msgTypes[10] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ConsensusNotifyBlockNew) String() string { return protoimpl.X.MessageStringOf(x) } func (*ConsensusNotifyBlockNew) ProtoMessage() {} func (x *ConsensusNotifyBlockNew) ProtoReflect() protoreflect.Message { mi := &file_protobuf_consensus_pb2_consensus_proto_msgTypes[10] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ConsensusNotifyBlockNew.ProtoReflect.Descriptor instead. func (*ConsensusNotifyBlockNew) Descriptor() ([]byte, []int) { return file_protobuf_consensus_pb2_consensus_proto_rawDescGZIP(), []int{10} } func (x *ConsensusNotifyBlockNew) GetBlock() *ConsensusBlock { if x != nil { return x.Block } return nil } // This block can be committed successfully type ConsensusNotifyBlockValid struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields BlockId []byte `protobuf:"bytes,1,opt,name=block_id,json=blockId,proto3" json:"block_id,omitempty"` } func (x *ConsensusNotifyBlockValid) Reset() { *x = ConsensusNotifyBlockValid{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_consensus_pb2_consensus_proto_msgTypes[11] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ConsensusNotifyBlockValid) String() string { return protoimpl.X.MessageStringOf(x) } func (*ConsensusNotifyBlockValid) ProtoMessage() {} func (x *ConsensusNotifyBlockValid) ProtoReflect() protoreflect.Message { mi := &file_protobuf_consensus_pb2_consensus_proto_msgTypes[11] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ConsensusNotifyBlockValid.ProtoReflect.Descriptor instead. func (*ConsensusNotifyBlockValid) Descriptor() ([]byte, []int) { return file_protobuf_consensus_pb2_consensus_proto_rawDescGZIP(), []int{11} } func (x *ConsensusNotifyBlockValid) GetBlockId() []byte { if x != nil { return x.BlockId } return nil } // This block cannot be committed successfully type ConsensusNotifyBlockInvalid struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields BlockId []byte `protobuf:"bytes,1,opt,name=block_id,json=blockId,proto3" json:"block_id,omitempty"` } func (x *ConsensusNotifyBlockInvalid) Reset() { *x = ConsensusNotifyBlockInvalid{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_consensus_pb2_consensus_proto_msgTypes[12] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ConsensusNotifyBlockInvalid) String() string { return protoimpl.X.MessageStringOf(x) } func (*ConsensusNotifyBlockInvalid) ProtoMessage() {} func (x *ConsensusNotifyBlockInvalid) ProtoReflect() protoreflect.Message { mi := &file_protobuf_consensus_pb2_consensus_proto_msgTypes[12] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ConsensusNotifyBlockInvalid.ProtoReflect.Descriptor instead. func (*ConsensusNotifyBlockInvalid) Descriptor() ([]byte, []int) { return file_protobuf_consensus_pb2_consensus_proto_rawDescGZIP(), []int{12} } func (x *ConsensusNotifyBlockInvalid) GetBlockId() []byte { if x != nil { return x.BlockId } return nil } // This block has been committed type ConsensusNotifyBlockCommit struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields BlockId []byte `protobuf:"bytes,1,opt,name=block_id,json=blockId,proto3" json:"block_id,omitempty"` } func (x *ConsensusNotifyBlockCommit) Reset() { *x = ConsensusNotifyBlockCommit{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_consensus_pb2_consensus_proto_msgTypes[13] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ConsensusNotifyBlockCommit) String() string { return protoimpl.X.MessageStringOf(x) } func (*ConsensusNotifyBlockCommit) ProtoMessage() {} func (x *ConsensusNotifyBlockCommit) ProtoReflect() protoreflect.Message { mi := &file_protobuf_consensus_pb2_consensus_proto_msgTypes[13] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ConsensusNotifyBlockCommit.ProtoReflect.Descriptor instead. func (*ConsensusNotifyBlockCommit) Descriptor() ([]byte, []int) { return file_protobuf_consensus_pb2_consensus_proto_rawDescGZIP(), []int{13} } func (x *ConsensusNotifyBlockCommit) GetBlockId() []byte { if x != nil { return x.BlockId } return nil } // Confirm that the notification was received. The validator message // correlation id is used to determine which notification this is an ack for. type ConsensusNotifyAck struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields } func (x *ConsensusNotifyAck) Reset() { *x = ConsensusNotifyAck{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_consensus_pb2_consensus_proto_msgTypes[14] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ConsensusNotifyAck) String() string { return protoimpl.X.MessageStringOf(x) } func (*ConsensusNotifyAck) ProtoMessage() {} func (x *ConsensusNotifyAck) ProtoReflect() protoreflect.Message { mi := &file_protobuf_consensus_pb2_consensus_proto_msgTypes[14] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ConsensusNotifyAck.ProtoReflect.Descriptor instead. func (*ConsensusNotifyAck) Descriptor() ([]byte, []int) { return file_protobuf_consensus_pb2_consensus_proto_rawDescGZIP(), []int{14} } // Send a consensus message to a specific, connected peer type ConsensusSendToRequest struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Message *ConsensusPeerMessage `protobuf:"bytes,1,opt,name=message,proto3" json:"message,omitempty"` PeerId []byte `protobuf:"bytes,2,opt,name=peer_id,json=peerId,proto3" json:"peer_id,omitempty"` } func (x *ConsensusSendToRequest) Reset() { *x = ConsensusSendToRequest{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_consensus_pb2_consensus_proto_msgTypes[15] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ConsensusSendToRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*ConsensusSendToRequest) ProtoMessage() {} func (x *ConsensusSendToRequest) ProtoReflect() protoreflect.Message { mi := &file_protobuf_consensus_pb2_consensus_proto_msgTypes[15] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ConsensusSendToRequest.ProtoReflect.Descriptor instead. func (*ConsensusSendToRequest) Descriptor() ([]byte, []int) { return file_protobuf_consensus_pb2_consensus_proto_rawDescGZIP(), []int{15} } func (x *ConsensusSendToRequest) GetMessage() *ConsensusPeerMessage { if x != nil { return x.Message } return nil } func (x *ConsensusSendToRequest) GetPeerId() []byte { if x != nil { return x.PeerId } return nil } type ConsensusSendToResponse struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Status ConsensusSendToResponse_Status `protobuf:"varint,1,opt,name=status,proto3,enum=ConsensusSendToResponse_Status" json:"status,omitempty"` } func (x *ConsensusSendToResponse) Reset() { *x = ConsensusSendToResponse{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_consensus_pb2_consensus_proto_msgTypes[16] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ConsensusSendToResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*ConsensusSendToResponse) ProtoMessage() {} func (x *ConsensusSendToResponse) ProtoReflect() protoreflect.Message { mi := &file_protobuf_consensus_pb2_consensus_proto_msgTypes[16] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ConsensusSendToResponse.ProtoReflect.Descriptor instead. func (*ConsensusSendToResponse) Descriptor() ([]byte, []int) { return file_protobuf_consensus_pb2_consensus_proto_rawDescGZIP(), []int{16} } func (x *ConsensusSendToResponse) GetStatus() ConsensusSendToResponse_Status { if x != nil { return x.Status } return ConsensusSendToResponse_STATUS_UNSET } // Broadcast a consensus message to all peers type ConsensusBroadcastRequest struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Message *ConsensusPeerMessage `protobuf:"bytes,1,opt,name=message,proto3" json:"message,omitempty"` } func (x *ConsensusBroadcastRequest) Reset() { *x = ConsensusBroadcastRequest{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_consensus_pb2_consensus_proto_msgTypes[17] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ConsensusBroadcastRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*ConsensusBroadcastRequest) ProtoMessage() {} func (x *ConsensusBroadcastRequest) ProtoReflect() protoreflect.Message { mi := &file_protobuf_consensus_pb2_consensus_proto_msgTypes[17] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ConsensusBroadcastRequest.ProtoReflect.Descriptor instead. func (*ConsensusBroadcastRequest) Descriptor() ([]byte, []int) { return file_protobuf_consensus_pb2_consensus_proto_rawDescGZIP(), []int{17} } func (x *ConsensusBroadcastRequest) GetMessage() *ConsensusPeerMessage { if x != nil { return x.Message } return nil } type ConsensusBroadcastResponse struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Status ConsensusBroadcastResponse_Status `protobuf:"varint,1,opt,name=status,proto3,enum=ConsensusBroadcastResponse_Status" json:"status,omitempty"` } func (x *ConsensusBroadcastResponse) Reset() { *x = ConsensusBroadcastResponse{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_consensus_pb2_consensus_proto_msgTypes[18] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ConsensusBroadcastResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*ConsensusBroadcastResponse) ProtoMessage() {} func (x *ConsensusBroadcastResponse) ProtoReflect() protoreflect.Message { mi := &file_protobuf_consensus_pb2_consensus_proto_msgTypes[18] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ConsensusBroadcastResponse.ProtoReflect.Descriptor instead. func (*ConsensusBroadcastResponse) Descriptor() ([]byte, []int) { return file_protobuf_consensus_pb2_consensus_proto_rawDescGZIP(), []int{18} } func (x *ConsensusBroadcastResponse) GetStatus() ConsensusBroadcastResponse_Status { if x != nil { return x.Status } return ConsensusBroadcastResponse_STATUS_UNSET } // Initialize a new block built on the block with the given previous id and // begin adding batches to it. If no previous id is specified, the current // head will be used. type ConsensusInitializeBlockRequest struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields PreviousId []byte `protobuf:"bytes,1,opt,name=previous_id,json=previousId,proto3" json:"previous_id,omitempty"` } func (x *ConsensusInitializeBlockRequest) Reset() { *x = ConsensusInitializeBlockRequest{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_consensus_pb2_consensus_proto_msgTypes[19] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ConsensusInitializeBlockRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*ConsensusInitializeBlockRequest) ProtoMessage() {} func (x *ConsensusInitializeBlockRequest) ProtoReflect() protoreflect.Message { mi := &file_protobuf_consensus_pb2_consensus_proto_msgTypes[19] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ConsensusInitializeBlockRequest.ProtoReflect.Descriptor instead. func (*ConsensusInitializeBlockRequest) Descriptor() ([]byte, []int) { return file_protobuf_consensus_pb2_consensus_proto_rawDescGZIP(), []int{19} } func (x *ConsensusInitializeBlockRequest) GetPreviousId() []byte { if x != nil { return x.PreviousId } return nil } type ConsensusInitializeBlockResponse struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Status ConsensusInitializeBlockResponse_Status `protobuf:"varint,1,opt,name=status,proto3,enum=ConsensusInitializeBlockResponse_Status" json:"status,omitempty"` } func (x *ConsensusInitializeBlockResponse) Reset() { *x = ConsensusInitializeBlockResponse{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_consensus_pb2_consensus_proto_msgTypes[20] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ConsensusInitializeBlockResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*ConsensusInitializeBlockResponse) ProtoMessage() {} func (x *ConsensusInitializeBlockResponse) ProtoReflect() protoreflect.Message { mi := &file_protobuf_consensus_pb2_consensus_proto_msgTypes[20] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ConsensusInitializeBlockResponse.ProtoReflect.Descriptor instead. func (*ConsensusInitializeBlockResponse) Descriptor() ([]byte, []int) { return file_protobuf_consensus_pb2_consensus_proto_rawDescGZIP(), []int{20} } func (x *ConsensusInitializeBlockResponse) GetStatus() ConsensusInitializeBlockResponse_Status { if x != nil { return x.Status } return ConsensusInitializeBlockResponse_STATUS_UNSET } // Stop adding batches to the current block and return a summary of its // contents. type ConsensusSummarizeBlockRequest struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields } func (x *ConsensusSummarizeBlockRequest) Reset() { *x = ConsensusSummarizeBlockRequest{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_consensus_pb2_consensus_proto_msgTypes[21] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ConsensusSummarizeBlockRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*ConsensusSummarizeBlockRequest) ProtoMessage() {} func (x *ConsensusSummarizeBlockRequest) ProtoReflect() protoreflect.Message { mi := &file_protobuf_consensus_pb2_consensus_proto_msgTypes[21] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ConsensusSummarizeBlockRequest.ProtoReflect.Descriptor instead. func (*ConsensusSummarizeBlockRequest) Descriptor() ([]byte, []int) { return file_protobuf_consensus_pb2_consensus_proto_rawDescGZIP(), []int{21} } type ConsensusSummarizeBlockResponse struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Status ConsensusSummarizeBlockResponse_Status `protobuf:"varint,1,opt,name=status,proto3,enum=ConsensusSummarizeBlockResponse_Status" json:"status,omitempty"` // A summary of the block contents Summary []byte `protobuf:"bytes,2,opt,name=summary,proto3" json:"summary,omitempty"` } func (x *ConsensusSummarizeBlockResponse) Reset() { *x = ConsensusSummarizeBlockResponse{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_consensus_pb2_consensus_proto_msgTypes[22] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ConsensusSummarizeBlockResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*ConsensusSummarizeBlockResponse) ProtoMessage() {} func (x *ConsensusSummarizeBlockResponse) ProtoReflect() protoreflect.Message { mi := &file_protobuf_consensus_pb2_consensus_proto_msgTypes[22] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ConsensusSummarizeBlockResponse.ProtoReflect.Descriptor instead. func (*ConsensusSummarizeBlockResponse) Descriptor() ([]byte, []int) { return file_protobuf_consensus_pb2_consensus_proto_rawDescGZIP(), []int{22} } func (x *ConsensusSummarizeBlockResponse) GetStatus() ConsensusSummarizeBlockResponse_Status { if x != nil { return x.Status } return ConsensusSummarizeBlockResponse_STATUS_UNSET } func (x *ConsensusSummarizeBlockResponse) GetSummary() []byte { if x != nil { return x.Summary } return nil } // Insert the given consensus data into the block and sign it. If this call is // successful, the consensus engine will receive the block afterwards. type ConsensusFinalizeBlockRequest struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // The consensus data to include in the finalized block Data []byte `protobuf:"bytes,1,opt,name=data,proto3" json:"data,omitempty"` } func (x *ConsensusFinalizeBlockRequest) Reset() { *x = ConsensusFinalizeBlockRequest{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_consensus_pb2_consensus_proto_msgTypes[23] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ConsensusFinalizeBlockRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*ConsensusFinalizeBlockRequest) ProtoMessage() {} func (x *ConsensusFinalizeBlockRequest) ProtoReflect() protoreflect.Message { mi := &file_protobuf_consensus_pb2_consensus_proto_msgTypes[23] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ConsensusFinalizeBlockRequest.ProtoReflect.Descriptor instead. func (*ConsensusFinalizeBlockRequest) Descriptor() ([]byte, []int) { return file_protobuf_consensus_pb2_consensus_proto_rawDescGZIP(), []int{23} } func (x *ConsensusFinalizeBlockRequest) GetData() []byte { if x != nil { return x.Data } return nil } type ConsensusFinalizeBlockResponse struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Status ConsensusFinalizeBlockResponse_Status `protobuf:"varint,1,opt,name=status,proto3,enum=ConsensusFinalizeBlockResponse_Status" json:"status,omitempty"` // The block id of the newly created block BlockId []byte `protobuf:"bytes,2,opt,name=block_id,json=blockId,proto3" json:"block_id,omitempty"` } func (x *ConsensusFinalizeBlockResponse) Reset() { *x = ConsensusFinalizeBlockResponse{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_consensus_pb2_consensus_proto_msgTypes[24] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ConsensusFinalizeBlockResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*ConsensusFinalizeBlockResponse) ProtoMessage() {} func (x *ConsensusFinalizeBlockResponse) ProtoReflect() protoreflect.Message { mi := &file_protobuf_consensus_pb2_consensus_proto_msgTypes[24] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ConsensusFinalizeBlockResponse.ProtoReflect.Descriptor instead. func (*ConsensusFinalizeBlockResponse) Descriptor() ([]byte, []int) { return file_protobuf_consensus_pb2_consensus_proto_rawDescGZIP(), []int{24} } func (x *ConsensusFinalizeBlockResponse) GetStatus() ConsensusFinalizeBlockResponse_Status { if x != nil { return x.Status } return ConsensusFinalizeBlockResponse_STATUS_UNSET } func (x *ConsensusFinalizeBlockResponse) GetBlockId() []byte { if x != nil { return x.BlockId } return nil } // Stop adding batches to the current block and abandon it. type ConsensusCancelBlockRequest struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields } func (x *ConsensusCancelBlockRequest) Reset() { *x = ConsensusCancelBlockRequest{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_consensus_pb2_consensus_proto_msgTypes[25] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ConsensusCancelBlockRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*ConsensusCancelBlockRequest) ProtoMessage() {} func (x *ConsensusCancelBlockRequest) ProtoReflect() protoreflect.Message { mi := &file_protobuf_consensus_pb2_consensus_proto_msgTypes[25] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ConsensusCancelBlockRequest.ProtoReflect.Descriptor instead. func (*ConsensusCancelBlockRequest) Descriptor() ([]byte, []int) { return file_protobuf_consensus_pb2_consensus_proto_rawDescGZIP(), []int{25} } type ConsensusCancelBlockResponse struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Status ConsensusCancelBlockResponse_Status `protobuf:"varint,1,opt,name=status,proto3,enum=ConsensusCancelBlockResponse_Status" json:"status,omitempty"` } func (x *ConsensusCancelBlockResponse) Reset() { *x = ConsensusCancelBlockResponse{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_consensus_pb2_consensus_proto_msgTypes[26] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ConsensusCancelBlockResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*ConsensusCancelBlockResponse) ProtoMessage() {} func (x *ConsensusCancelBlockResponse) ProtoReflect() protoreflect.Message { mi := &file_protobuf_consensus_pb2_consensus_proto_msgTypes[26] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ConsensusCancelBlockResponse.ProtoReflect.Descriptor instead. func (*ConsensusCancelBlockResponse) Descriptor() ([]byte, []int) { return file_protobuf_consensus_pb2_consensus_proto_rawDescGZIP(), []int{26} } func (x *ConsensusCancelBlockResponse) GetStatus() ConsensusCancelBlockResponse_Status { if x != nil { return x.Status } return ConsensusCancelBlockResponse_STATUS_UNSET } // Request that, for each block block in order, the block is checked to // determine whether the block can be committed successfully or not. Blocks // may be checked in parallel. If a new request arrives, it overrides the // previous request allowing the engine to reprioritize the list of blocks to // check. // // NOTE: OK does not mean the blocks will all commit successfully, only that // the directive was received successfully. The engine must listen for // notifications from the consuming component to learn if the blocks would // commit or not. type ConsensusCheckBlocksRequest struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields BlockIds [][]byte `protobuf:"bytes,1,rep,name=block_ids,json=blockIds,proto3" json:"block_ids,omitempty"` } func (x *ConsensusCheckBlocksRequest) Reset() { *x = ConsensusCheckBlocksRequest{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_consensus_pb2_consensus_proto_msgTypes[27] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ConsensusCheckBlocksRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*ConsensusCheckBlocksRequest) ProtoMessage() {} func (x *ConsensusCheckBlocksRequest) ProtoReflect() protoreflect.Message { mi := &file_protobuf_consensus_pb2_consensus_proto_msgTypes[27] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ConsensusCheckBlocksRequest.ProtoReflect.Descriptor instead. func (*ConsensusCheckBlocksRequest) Descriptor() ([]byte, []int) { return file_protobuf_consensus_pb2_consensus_proto_rawDescGZIP(), []int{27} } func (x *ConsensusCheckBlocksRequest) GetBlockIds() [][]byte { if x != nil { return x.BlockIds } return nil } type ConsensusCheckBlocksResponse struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Status ConsensusCheckBlocksResponse_Status `protobuf:"varint,1,opt,name=status,proto3,enum=ConsensusCheckBlocksResponse_Status" json:"status,omitempty"` } func (x *ConsensusCheckBlocksResponse) Reset() { *x = ConsensusCheckBlocksResponse{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_consensus_pb2_consensus_proto_msgTypes[28] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ConsensusCheckBlocksResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*ConsensusCheckBlocksResponse) ProtoMessage() {} func (x *ConsensusCheckBlocksResponse) ProtoReflect() protoreflect.Message { mi := &file_protobuf_consensus_pb2_consensus_proto_msgTypes[28] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ConsensusCheckBlocksResponse.ProtoReflect.Descriptor instead. func (*ConsensusCheckBlocksResponse) Descriptor() ([]byte, []int) { return file_protobuf_consensus_pb2_consensus_proto_rawDescGZIP(), []int{28} } func (x *ConsensusCheckBlocksResponse) GetStatus() ConsensusCheckBlocksResponse_Status { if x != nil { return x.Status } return ConsensusCheckBlocksResponse_STATUS_UNSET } // Request that the block be committed. This request fails if the block has // not already been checked. // // NOTE: OK does not mean the block has been committed, only that the directive // was received successfully. The engine must listen for notifications from the // consuming component to learn when the block commits. type ConsensusCommitBlockRequest struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields BlockId []byte `protobuf:"bytes,1,opt,name=block_id,json=blockId,proto3" json:"block_id,omitempty"` } func (x *ConsensusCommitBlockRequest) Reset() { *x = ConsensusCommitBlockRequest{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_consensus_pb2_consensus_proto_msgTypes[29] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ConsensusCommitBlockRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*ConsensusCommitBlockRequest) ProtoMessage() {} func (x *ConsensusCommitBlockRequest) ProtoReflect() protoreflect.Message { mi := &file_protobuf_consensus_pb2_consensus_proto_msgTypes[29] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ConsensusCommitBlockRequest.ProtoReflect.Descriptor instead. func (*ConsensusCommitBlockRequest) Descriptor() ([]byte, []int) { return file_protobuf_consensus_pb2_consensus_proto_rawDescGZIP(), []int{29} } func (x *ConsensusCommitBlockRequest) GetBlockId() []byte { if x != nil { return x.BlockId } return nil } type ConsensusCommitBlockResponse struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Status ConsensusCommitBlockResponse_Status `protobuf:"varint,1,opt,name=status,proto3,enum=ConsensusCommitBlockResponse_Status" json:"status,omitempty"` } func (x *ConsensusCommitBlockResponse) Reset() { *x = ConsensusCommitBlockResponse{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_consensus_pb2_consensus_proto_msgTypes[30] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ConsensusCommitBlockResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*ConsensusCommitBlockResponse) ProtoMessage() {} func (x *ConsensusCommitBlockResponse) ProtoReflect() protoreflect.Message { mi := &file_protobuf_consensus_pb2_consensus_proto_msgTypes[30] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ConsensusCommitBlockResponse.ProtoReflect.Descriptor instead. func (*ConsensusCommitBlockResponse) Descriptor() ([]byte, []int) { return file_protobuf_consensus_pb2_consensus_proto_rawDescGZIP(), []int{30} } func (x *ConsensusCommitBlockResponse) GetStatus() ConsensusCommitBlockResponse_Status { if x != nil { return x.Status } return ConsensusCommitBlockResponse_STATUS_UNSET } // Inform the consuming component that this block is no longer being considered // and can be held or freed as needed. type ConsensusIgnoreBlockRequest struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields BlockId []byte `protobuf:"bytes,1,opt,name=block_id,json=blockId,proto3" json:"block_id,omitempty"` } func (x *ConsensusIgnoreBlockRequest) Reset() { *x = ConsensusIgnoreBlockRequest{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_consensus_pb2_consensus_proto_msgTypes[31] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ConsensusIgnoreBlockRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*ConsensusIgnoreBlockRequest) ProtoMessage() {} func (x *ConsensusIgnoreBlockRequest) ProtoReflect() protoreflect.Message { mi := &file_protobuf_consensus_pb2_consensus_proto_msgTypes[31] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ConsensusIgnoreBlockRequest.ProtoReflect.Descriptor instead. func (*ConsensusIgnoreBlockRequest) Descriptor() ([]byte, []int) { return file_protobuf_consensus_pb2_consensus_proto_rawDescGZIP(), []int{31} } func (x *ConsensusIgnoreBlockRequest) GetBlockId() []byte { if x != nil { return x.BlockId } return nil } type ConsensusIgnoreBlockResponse struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Status ConsensusIgnoreBlockResponse_Status `protobuf:"varint,1,opt,name=status,proto3,enum=ConsensusIgnoreBlockResponse_Status" json:"status,omitempty"` } func (x *ConsensusIgnoreBlockResponse) Reset() { *x = ConsensusIgnoreBlockResponse{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_consensus_pb2_consensus_proto_msgTypes[32] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ConsensusIgnoreBlockResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*ConsensusIgnoreBlockResponse) ProtoMessage() {} func (x *ConsensusIgnoreBlockResponse) ProtoReflect() protoreflect.Message { mi := &file_protobuf_consensus_pb2_consensus_proto_msgTypes[32] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ConsensusIgnoreBlockResponse.ProtoReflect.Descriptor instead. func (*ConsensusIgnoreBlockResponse) Descriptor() ([]byte, []int) { return file_protobuf_consensus_pb2_consensus_proto_rawDescGZIP(), []int{32} } func (x *ConsensusIgnoreBlockResponse) GetStatus() ConsensusIgnoreBlockResponse_Status { if x != nil { return x.Status } return ConsensusIgnoreBlockResponse_STATUS_UNSET } // Fail this block and any of its descendants and purge them as needed. type ConsensusFailBlockRequest struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields BlockId []byte `protobuf:"bytes,1,opt,name=block_id,json=blockId,proto3" json:"block_id,omitempty"` } func (x *ConsensusFailBlockRequest) Reset() { *x = ConsensusFailBlockRequest{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_consensus_pb2_consensus_proto_msgTypes[33] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ConsensusFailBlockRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*ConsensusFailBlockRequest) ProtoMessage() {} func (x *ConsensusFailBlockRequest) ProtoReflect() protoreflect.Message { mi := &file_protobuf_consensus_pb2_consensus_proto_msgTypes[33] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ConsensusFailBlockRequest.ProtoReflect.Descriptor instead. func (*ConsensusFailBlockRequest) Descriptor() ([]byte, []int) { return file_protobuf_consensus_pb2_consensus_proto_rawDescGZIP(), []int{33} } func (x *ConsensusFailBlockRequest) GetBlockId() []byte { if x != nil { return x.BlockId } return nil } type ConsensusFailBlockResponse struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Status ConsensusFailBlockResponse_Status `protobuf:"varint,1,opt,name=status,proto3,enum=ConsensusFailBlockResponse_Status" json:"status,omitempty"` } func (x *ConsensusFailBlockResponse) Reset() { *x = ConsensusFailBlockResponse{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_consensus_pb2_consensus_proto_msgTypes[34] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ConsensusFailBlockResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*ConsensusFailBlockResponse) ProtoMessage() {} func (x *ConsensusFailBlockResponse) ProtoReflect() protoreflect.Message { mi := &file_protobuf_consensus_pb2_consensus_proto_msgTypes[34] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ConsensusFailBlockResponse.ProtoReflect.Descriptor instead. func (*ConsensusFailBlockResponse) Descriptor() ([]byte, []int) { return file_protobuf_consensus_pb2_consensus_proto_rawDescGZIP(), []int{34} } func (x *ConsensusFailBlockResponse) GetStatus() ConsensusFailBlockResponse_Status { if x != nil { return x.Status } return ConsensusFailBlockResponse_STATUS_UNSET } // Retrieve consensus-related information about blocks. If some blocks could // not be found, only the blocks that could be found will be returned. type ConsensusBlocksGetRequest struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields BlockIds [][]byte `protobuf:"bytes,1,rep,name=block_ids,json=blockIds,proto3" json:"block_ids,omitempty"` } func (x *ConsensusBlocksGetRequest) Reset() { *x = ConsensusBlocksGetRequest{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_consensus_pb2_consensus_proto_msgTypes[35] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ConsensusBlocksGetRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*ConsensusBlocksGetRequest) ProtoMessage() {} func (x *ConsensusBlocksGetRequest) ProtoReflect() protoreflect.Message { mi := &file_protobuf_consensus_pb2_consensus_proto_msgTypes[35] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ConsensusBlocksGetRequest.ProtoReflect.Descriptor instead. func (*ConsensusBlocksGetRequest) Descriptor() ([]byte, []int) { return file_protobuf_consensus_pb2_consensus_proto_rawDescGZIP(), []int{35} } func (x *ConsensusBlocksGetRequest) GetBlockIds() [][]byte { if x != nil { return x.BlockIds } return nil } type ConsensusBlocksGetResponse struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Status ConsensusBlocksGetResponse_Status `protobuf:"varint,1,opt,name=status,proto3,enum=ConsensusBlocksGetResponse_Status" json:"status,omitempty"` Blocks []*ConsensusBlock `protobuf:"bytes,2,rep,name=blocks,proto3" json:"blocks,omitempty"` } func (x *ConsensusBlocksGetResponse) Reset() { *x = ConsensusBlocksGetResponse{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_consensus_pb2_consensus_proto_msgTypes[36] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ConsensusBlocksGetResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*ConsensusBlocksGetResponse) ProtoMessage() {} func (x *ConsensusBlocksGetResponse) ProtoReflect() protoreflect.Message { mi := &file_protobuf_consensus_pb2_consensus_proto_msgTypes[36] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ConsensusBlocksGetResponse.ProtoReflect.Descriptor instead. func (*ConsensusBlocksGetResponse) Descriptor() ([]byte, []int) { return file_protobuf_consensus_pb2_consensus_proto_rawDescGZIP(), []int{36} } func (x *ConsensusBlocksGetResponse) GetStatus() ConsensusBlocksGetResponse_Status { if x != nil { return x.Status } return ConsensusBlocksGetResponse_STATUS_UNSET } func (x *ConsensusBlocksGetResponse) GetBlocks() []*ConsensusBlock { if x != nil { return x.Blocks } return nil } // Retrieve consensus-related information about the chain head. type ConsensusChainHeadGetRequest struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields } func (x *ConsensusChainHeadGetRequest) Reset() { *x = ConsensusChainHeadGetRequest{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_consensus_pb2_consensus_proto_msgTypes[37] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ConsensusChainHeadGetRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*ConsensusChainHeadGetRequest) ProtoMessage() {} func (x *ConsensusChainHeadGetRequest) ProtoReflect() protoreflect.Message { mi := &file_protobuf_consensus_pb2_consensus_proto_msgTypes[37] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ConsensusChainHeadGetRequest.ProtoReflect.Descriptor instead. func (*ConsensusChainHeadGetRequest) Descriptor() ([]byte, []int) { return file_protobuf_consensus_pb2_consensus_proto_rawDescGZIP(), []int{37} } type ConsensusChainHeadGetResponse struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Status ConsensusChainHeadGetResponse_Status `protobuf:"varint,1,opt,name=status,proto3,enum=ConsensusChainHeadGetResponse_Status" json:"status,omitempty"` Block *ConsensusBlock `protobuf:"bytes,2,opt,name=block,proto3" json:"block,omitempty"` } func (x *ConsensusChainHeadGetResponse) Reset() { *x = ConsensusChainHeadGetResponse{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_consensus_pb2_consensus_proto_msgTypes[38] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ConsensusChainHeadGetResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*ConsensusChainHeadGetResponse) ProtoMessage() {} func (x *ConsensusChainHeadGetResponse) ProtoReflect() protoreflect.Message { mi := &file_protobuf_consensus_pb2_consensus_proto_msgTypes[38] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ConsensusChainHeadGetResponse.ProtoReflect.Descriptor instead. func (*ConsensusChainHeadGetResponse) Descriptor() ([]byte, []int) { return file_protobuf_consensus_pb2_consensus_proto_rawDescGZIP(), []int{38} } func (x *ConsensusChainHeadGetResponse) GetStatus() ConsensusChainHeadGetResponse_Status { if x != nil { return x.Status } return ConsensusChainHeadGetResponse_STATUS_UNSET } func (x *ConsensusChainHeadGetResponse) GetBlock() *ConsensusBlock { if x != nil { return x.Block } return nil } // Read the values of these settings from state as of the given block. If some // values settings keys cannot be found, the keys that were found will be // returned. type ConsensusSettingsGetRequest struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields BlockId []byte `protobuf:"bytes,1,opt,name=block_id,json=blockId,proto3" json:"block_id,omitempty"` Keys []string `protobuf:"bytes,2,rep,name=keys,proto3" json:"keys,omitempty"` } func (x *ConsensusSettingsGetRequest) Reset() { *x = ConsensusSettingsGetRequest{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_consensus_pb2_consensus_proto_msgTypes[39] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ConsensusSettingsGetRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*ConsensusSettingsGetRequest) ProtoMessage() {} func (x *ConsensusSettingsGetRequest) ProtoReflect() protoreflect.Message { mi := &file_protobuf_consensus_pb2_consensus_proto_msgTypes[39] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ConsensusSettingsGetRequest.ProtoReflect.Descriptor instead. func (*ConsensusSettingsGetRequest) Descriptor() ([]byte, []int) { return file_protobuf_consensus_pb2_consensus_proto_rawDescGZIP(), []int{39} } func (x *ConsensusSettingsGetRequest) GetBlockId() []byte { if x != nil { return x.BlockId } return nil } func (x *ConsensusSettingsGetRequest) GetKeys() []string { if x != nil { return x.Keys } return nil } type ConsensusSettingsGetResponse struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Status ConsensusSettingsGetResponse_Status `protobuf:"varint,1,opt,name=status,proto3,enum=ConsensusSettingsGetResponse_Status" json:"status,omitempty"` Entries []*ConsensusSettingsEntry `protobuf:"bytes,2,rep,name=entries,proto3" json:"entries,omitempty"` } func (x *ConsensusSettingsGetResponse) Reset() { *x = ConsensusSettingsGetResponse{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_consensus_pb2_consensus_proto_msgTypes[40] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ConsensusSettingsGetResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*ConsensusSettingsGetResponse) ProtoMessage() {} func (x *ConsensusSettingsGetResponse) ProtoReflect() protoreflect.Message { mi := &file_protobuf_consensus_pb2_consensus_proto_msgTypes[40] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ConsensusSettingsGetResponse.ProtoReflect.Descriptor instead. func (*ConsensusSettingsGetResponse) Descriptor() ([]byte, []int) { return file_protobuf_consensus_pb2_consensus_proto_rawDescGZIP(), []int{40} } func (x *ConsensusSettingsGetResponse) GetStatus() ConsensusSettingsGetResponse_Status { if x != nil { return x.Status } return ConsensusSettingsGetResponse_STATUS_UNSET } func (x *ConsensusSettingsGetResponse) GetEntries() []*ConsensusSettingsEntry { if x != nil { return x.Entries } return nil } // Read the data at these addresses from state as of the given block. If some // addresses cannot be found, state at the addresses that were found will be // returned. type ConsensusStateGetRequest struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields BlockId []byte `protobuf:"bytes,1,opt,name=block_id,json=blockId,proto3" json:"block_id,omitempty"` Addresses []string `protobuf:"bytes,2,rep,name=addresses,proto3" json:"addresses,omitempty"` } func (x *ConsensusStateGetRequest) Reset() { *x = ConsensusStateGetRequest{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_consensus_pb2_consensus_proto_msgTypes[41] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ConsensusStateGetRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*ConsensusStateGetRequest) ProtoMessage() {} func (x *ConsensusStateGetRequest) ProtoReflect() protoreflect.Message { mi := &file_protobuf_consensus_pb2_consensus_proto_msgTypes[41] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ConsensusStateGetRequest.ProtoReflect.Descriptor instead. func (*ConsensusStateGetRequest) Descriptor() ([]byte, []int) { return file_protobuf_consensus_pb2_consensus_proto_rawDescGZIP(), []int{41} } func (x *ConsensusStateGetRequest) GetBlockId() []byte { if x != nil { return x.BlockId } return nil } func (x *ConsensusStateGetRequest) GetAddresses() []string { if x != nil { return x.Addresses } return nil } type ConsensusStateGetResponse struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Status ConsensusStateGetResponse_Status `protobuf:"varint,1,opt,name=status,proto3,enum=ConsensusStateGetResponse_Status" json:"status,omitempty"` Entries []*ConsensusStateEntry `protobuf:"bytes,2,rep,name=entries,proto3" json:"entries,omitempty"` } func (x *ConsensusStateGetResponse) Reset() { *x = ConsensusStateGetResponse{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_consensus_pb2_consensus_proto_msgTypes[42] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ConsensusStateGetResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*ConsensusStateGetResponse) ProtoMessage() {} func (x *ConsensusStateGetResponse) ProtoReflect() protoreflect.Message { mi := &file_protobuf_consensus_pb2_consensus_proto_msgTypes[42] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ConsensusStateGetResponse.ProtoReflect.Descriptor instead. func (*ConsensusStateGetResponse) Descriptor() ([]byte, []int) { return file_protobuf_consensus_pb2_consensus_proto_rawDescGZIP(), []int{42} } func (x *ConsensusStateGetResponse) GetStatus() ConsensusStateGetResponse_Status { if x != nil { return x.Status } return ConsensusStateGetResponse_STATUS_UNSET } func (x *ConsensusStateGetResponse) GetEntries() []*ConsensusStateEntry { if x != nil { return x.Entries } return nil } var File_protobuf_consensus_pb2_consensus_proto protoreflect.FileDescriptor var file_protobuf_consensus_pb2_consensus_proto_rawDesc = []byte{ 0x0a, 0x26, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x63, 0x6f, 0x6e, 0x73, 0x65, 0x6e, 0x73, 0x75, 0x73, 0x5f, 0x70, 0x62, 0x32, 0x2f, 0x63, 0x6f, 0x6e, 0x73, 0x65, 0x6e, 0x73, 0x75, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0x81, 0x01, 0x0a, 0x14, 0x43, 0x6f, 0x6e, 0x73, 0x65, 0x6e, 0x73, 0x75, 0x73, 0x50, 0x65, 0x65, 0x72, 0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x12, 0x21, 0x0a, 0x0c, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x5f, 0x74, 0x79, 0x70, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0b, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x54, 0x79, 0x70, 0x65, 0x12, 0x18, 0x0a, 0x07, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x07, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x12, 0x12, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x18, 0x0a, 0x07, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x18, 0x04, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x22, 0xba, 0x01, 0x0a, 0x0e, 0x43, 0x6f, 0x6e, 0x73, 0x65, 0x6e, 0x73, 0x75, 0x73, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x12, 0x19, 0x0a, 0x08, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x07, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x49, 0x64, 0x12, 0x1f, 0x0a, 0x0b, 0x70, 0x72, 0x65, 0x76, 0x69, 0x6f, 0x75, 0x73, 0x5f, 0x69, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0a, 0x70, 0x72, 0x65, 0x76, 0x69, 0x6f, 0x75, 0x73, 0x49, 0x64, 0x12, 0x1b, 0x0a, 0x09, 0x73, 0x69, 0x67, 0x6e, 0x65, 0x72, 0x5f, 0x69, 0x64, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x08, 0x73, 0x69, 0x67, 0x6e, 0x65, 0x72, 0x49, 0x64, 0x12, 0x1b, 0x0a, 0x09, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x5f, 0x6e, 0x75, 0x6d, 0x18, 0x04, 0x20, 0x01, 0x28, 0x04, 0x52, 0x08, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x4e, 0x75, 0x6d, 0x12, 0x18, 0x0a, 0x07, 0x70, 0x61, 0x79, 0x6c, 0x6f, 0x61, 0x64, 0x18, 0x05, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x07, 0x70, 0x61, 0x79, 0x6c, 0x6f, 0x61, 0x64, 0x12, 0x18, 0x0a, 0x07, 0x73, 0x75, 0x6d, 0x6d, 0x61, 0x72, 0x79, 0x18, 0x06, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x07, 0x73, 0x75, 0x6d, 0x6d, 0x61, 0x72, 0x79, 0x22, 0x2c, 0x0a, 0x11, 0x43, 0x6f, 0x6e, 0x73, 0x65, 0x6e, 0x73, 0x75, 0x73, 0x50, 0x65, 0x65, 0x72, 0x49, 0x6e, 0x66, 0x6f, 0x12, 0x17, 0x0a, 0x07, 0x70, 0x65, 0x65, 0x72, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x06, 0x70, 0x65, 0x65, 0x72, 0x49, 0x64, 0x22, 0x40, 0x0a, 0x16, 0x43, 0x6f, 0x6e, 0x73, 0x65, 0x6e, 0x73, 0x75, 0x73, 0x53, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x73, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x12, 0x10, 0x0a, 0x03, 0x6b, 0x65, 0x79, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x6b, 0x65, 0x79, 0x12, 0x14, 0x0a, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x22, 0x43, 0x0a, 0x13, 0x43, 0x6f, 0x6e, 0x73, 0x65, 0x6e, 0x73, 0x75, 0x73, 0x53, 0x74, 0x61, 0x74, 0x65, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x12, 0x18, 0x0a, 0x07, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x12, 0x12, 0x0a, 0x04, 0x64, 0x61, 0x74, 0x61, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x04, 0x64, 0x61, 0x74, 0x61, 0x22, 0x48, 0x0a, 0x18, 0x43, 0x6f, 0x6e, 0x73, 0x65, 0x6e, 0x73, 0x75, 0x73, 0x52, 0x65, 0x67, 0x69, 0x73, 0x74, 0x65, 0x72, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x12, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x18, 0x0a, 0x07, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x22, 0xc3, 0x02, 0x0a, 0x19, 0x43, 0x6f, 0x6e, 0x73, 0x65, 0x6e, 0x73, 0x75, 0x73, 0x52, 0x65, 0x67, 0x69, 0x73, 0x74, 0x65, 0x72, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x39, 0x0a, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x21, 0x2e, 0x43, 0x6f, 0x6e, 0x73, 0x65, 0x6e, 0x73, 0x75, 0x73, 0x52, 0x65, 0x67, 0x69, 0x73, 0x74, 0x65, 0x72, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x2e, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x52, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, 0x2e, 0x0a, 0x0a, 0x63, 0x68, 0x61, 0x69, 0x6e, 0x5f, 0x68, 0x65, 0x61, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x0f, 0x2e, 0x43, 0x6f, 0x6e, 0x73, 0x65, 0x6e, 0x73, 0x75, 0x73, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x52, 0x09, 0x63, 0x68, 0x61, 0x69, 0x6e, 0x48, 0x65, 0x61, 0x64, 0x12, 0x28, 0x0a, 0x05, 0x70, 0x65, 0x65, 0x72, 0x73, 0x18, 0x03, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x12, 0x2e, 0x43, 0x6f, 0x6e, 0x73, 0x65, 0x6e, 0x73, 0x75, 0x73, 0x50, 0x65, 0x65, 0x72, 0x49, 0x6e, 0x66, 0x6f, 0x52, 0x05, 0x70, 0x65, 0x65, 0x72, 0x73, 0x12, 0x3a, 0x0a, 0x0f, 0x6c, 0x6f, 0x63, 0x61, 0x6c, 0x5f, 0x70, 0x65, 0x65, 0x72, 0x5f, 0x69, 0x6e, 0x66, 0x6f, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x12, 0x2e, 0x43, 0x6f, 0x6e, 0x73, 0x65, 0x6e, 0x73, 0x75, 0x73, 0x50, 0x65, 0x65, 0x72, 0x49, 0x6e, 0x66, 0x6f, 0x52, 0x0d, 0x6c, 0x6f, 0x63, 0x61, 0x6c, 0x50, 0x65, 0x65, 0x72, 0x49, 0x6e, 0x66, 0x6f, 0x22, 0x55, 0x0a, 0x06, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, 0x10, 0x0a, 0x0c, 0x53, 0x54, 0x41, 0x54, 0x55, 0x53, 0x5f, 0x55, 0x4e, 0x53, 0x45, 0x54, 0x10, 0x00, 0x12, 0x06, 0x0a, 0x02, 0x4f, 0x4b, 0x10, 0x01, 0x12, 0x0f, 0x0a, 0x0b, 0x42, 0x41, 0x44, 0x5f, 0x52, 0x45, 0x51, 0x55, 0x45, 0x53, 0x54, 0x10, 0x02, 0x12, 0x11, 0x0a, 0x0d, 0x53, 0x45, 0x52, 0x56, 0x49, 0x43, 0x45, 0x5f, 0x45, 0x52, 0x52, 0x4f, 0x52, 0x10, 0x03, 0x12, 0x0d, 0x0a, 0x09, 0x4e, 0x4f, 0x54, 0x5f, 0x52, 0x45, 0x41, 0x44, 0x59, 0x10, 0x04, 0x22, 0x4f, 0x0a, 0x1c, 0x43, 0x6f, 0x6e, 0x73, 0x65, 0x6e, 0x73, 0x75, 0x73, 0x4e, 0x6f, 0x74, 0x69, 0x66, 0x79, 0x50, 0x65, 0x65, 0x72, 0x43, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x65, 0x64, 0x12, 0x2f, 0x0a, 0x09, 0x70, 0x65, 0x65, 0x72, 0x5f, 0x69, 0x6e, 0x66, 0x6f, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x12, 0x2e, 0x43, 0x6f, 0x6e, 0x73, 0x65, 0x6e, 0x73, 0x75, 0x73, 0x50, 0x65, 0x65, 0x72, 0x49, 0x6e, 0x66, 0x6f, 0x52, 0x08, 0x70, 0x65, 0x65, 0x72, 0x49, 0x6e, 0x66, 0x6f, 0x22, 0x3a, 0x0a, 0x1f, 0x43, 0x6f, 0x6e, 0x73, 0x65, 0x6e, 0x73, 0x75, 0x73, 0x4e, 0x6f, 0x74, 0x69, 0x66, 0x79, 0x50, 0x65, 0x65, 0x72, 0x44, 0x69, 0x73, 0x63, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x65, 0x64, 0x12, 0x17, 0x0a, 0x07, 0x70, 0x65, 0x65, 0x72, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x06, 0x70, 0x65, 0x65, 0x72, 0x49, 0x64, 0x22, 0x6a, 0x0a, 0x1a, 0x43, 0x6f, 0x6e, 0x73, 0x65, 0x6e, 0x73, 0x75, 0x73, 0x4e, 0x6f, 0x74, 0x69, 0x66, 0x79, 0x50, 0x65, 0x65, 0x72, 0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x12, 0x2f, 0x0a, 0x07, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x15, 0x2e, 0x43, 0x6f, 0x6e, 0x73, 0x65, 0x6e, 0x73, 0x75, 0x73, 0x50, 0x65, 0x65, 0x72, 0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x52, 0x07, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x12, 0x1b, 0x0a, 0x09, 0x73, 0x65, 0x6e, 0x64, 0x65, 0x72, 0x5f, 0x69, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x08, 0x73, 0x65, 0x6e, 0x64, 0x65, 0x72, 0x49, 0x64, 0x22, 0x40, 0x0a, 0x17, 0x43, 0x6f, 0x6e, 0x73, 0x65, 0x6e, 0x73, 0x75, 0x73, 0x4e, 0x6f, 0x74, 0x69, 0x66, 0x79, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x4e, 0x65, 0x77, 0x12, 0x25, 0x0a, 0x05, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x0f, 0x2e, 0x43, 0x6f, 0x6e, 0x73, 0x65, 0x6e, 0x73, 0x75, 0x73, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x52, 0x05, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x22, 0x36, 0x0a, 0x19, 0x43, 0x6f, 0x6e, 0x73, 0x65, 0x6e, 0x73, 0x75, 0x73, 0x4e, 0x6f, 0x74, 0x69, 0x66, 0x79, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x56, 0x61, 0x6c, 0x69, 0x64, 0x12, 0x19, 0x0a, 0x08, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x07, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x49, 0x64, 0x22, 0x38, 0x0a, 0x1b, 0x43, 0x6f, 0x6e, 0x73, 0x65, 0x6e, 0x73, 0x75, 0x73, 0x4e, 0x6f, 0x74, 0x69, 0x66, 0x79, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x49, 0x6e, 0x76, 0x61, 0x6c, 0x69, 0x64, 0x12, 0x19, 0x0a, 0x08, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x07, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x49, 0x64, 0x22, 0x37, 0x0a, 0x1a, 0x43, 0x6f, 0x6e, 0x73, 0x65, 0x6e, 0x73, 0x75, 0x73, 0x4e, 0x6f, 0x74, 0x69, 0x66, 0x79, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x43, 0x6f, 0x6d, 0x6d, 0x69, 0x74, 0x12, 0x19, 0x0a, 0x08, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x07, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x49, 0x64, 0x22, 0x14, 0x0a, 0x12, 0x43, 0x6f, 0x6e, 0x73, 0x65, 0x6e, 0x73, 0x75, 0x73, 0x4e, 0x6f, 0x74, 0x69, 0x66, 0x79, 0x41, 0x63, 0x6b, 0x22, 0x62, 0x0a, 0x16, 0x43, 0x6f, 0x6e, 0x73, 0x65, 0x6e, 0x73, 0x75, 0x73, 0x53, 0x65, 0x6e, 0x64, 0x54, 0x6f, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x2f, 0x0a, 0x07, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x15, 0x2e, 0x43, 0x6f, 0x6e, 0x73, 0x65, 0x6e, 0x73, 0x75, 0x73, 0x50, 0x65, 0x65, 0x72, 0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x52, 0x07, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x12, 0x17, 0x0a, 0x07, 0x70, 0x65, 0x65, 0x72, 0x5f, 0x69, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x06, 0x70, 0x65, 0x65, 0x72, 0x49, 0x64, 0x22, 0xbb, 0x01, 0x0a, 0x17, 0x43, 0x6f, 0x6e, 0x73, 0x65, 0x6e, 0x73, 0x75, 0x73, 0x53, 0x65, 0x6e, 0x64, 0x54, 0x6f, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x37, 0x0a, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x1f, 0x2e, 0x43, 0x6f, 0x6e, 0x73, 0x65, 0x6e, 0x73, 0x75, 0x73, 0x53, 0x65, 0x6e, 0x64, 0x54, 0x6f, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x2e, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x52, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x22, 0x67, 0x0a, 0x06, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, 0x10, 0x0a, 0x0c, 0x53, 0x54, 0x41, 0x54, 0x55, 0x53, 0x5f, 0x55, 0x4e, 0x53, 0x45, 0x54, 0x10, 0x00, 0x12, 0x06, 0x0a, 0x02, 0x4f, 0x4b, 0x10, 0x01, 0x12, 0x0f, 0x0a, 0x0b, 0x42, 0x41, 0x44, 0x5f, 0x52, 0x45, 0x51, 0x55, 0x45, 0x53, 0x54, 0x10, 0x02, 0x12, 0x11, 0x0a, 0x0d, 0x53, 0x45, 0x52, 0x56, 0x49, 0x43, 0x45, 0x5f, 0x45, 0x52, 0x52, 0x4f, 0x52, 0x10, 0x03, 0x12, 0x0d, 0x0a, 0x09, 0x4e, 0x4f, 0x54, 0x5f, 0x52, 0x45, 0x41, 0x44, 0x59, 0x10, 0x04, 0x12, 0x10, 0x0a, 0x0c, 0x55, 0x4e, 0x4b, 0x4e, 0x4f, 0x57, 0x4e, 0x5f, 0x50, 0x45, 0x45, 0x52, 0x10, 0x05, 0x22, 0x4c, 0x0a, 0x19, 0x43, 0x6f, 0x6e, 0x73, 0x65, 0x6e, 0x73, 0x75, 0x73, 0x42, 0x72, 0x6f, 0x61, 0x64, 0x63, 0x61, 0x73, 0x74, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x2f, 0x0a, 0x07, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x15, 0x2e, 0x43, 0x6f, 0x6e, 0x73, 0x65, 0x6e, 0x73, 0x75, 0x73, 0x50, 0x65, 0x65, 0x72, 0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x52, 0x07, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x22, 0xaf, 0x01, 0x0a, 0x1a, 0x43, 0x6f, 0x6e, 0x73, 0x65, 0x6e, 0x73, 0x75, 0x73, 0x42, 0x72, 0x6f, 0x61, 0x64, 0x63, 0x61, 0x73, 0x74, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x3a, 0x0a, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x22, 0x2e, 0x43, 0x6f, 0x6e, 0x73, 0x65, 0x6e, 0x73, 0x75, 0x73, 0x42, 0x72, 0x6f, 0x61, 0x64, 0x63, 0x61, 0x73, 0x74, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x2e, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x52, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x22, 0x55, 0x0a, 0x06, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, 0x10, 0x0a, 0x0c, 0x53, 0x54, 0x41, 0x54, 0x55, 0x53, 0x5f, 0x55, 0x4e, 0x53, 0x45, 0x54, 0x10, 0x00, 0x12, 0x06, 0x0a, 0x02, 0x4f, 0x4b, 0x10, 0x01, 0x12, 0x0f, 0x0a, 0x0b, 0x42, 0x41, 0x44, 0x5f, 0x52, 0x45, 0x51, 0x55, 0x45, 0x53, 0x54, 0x10, 0x02, 0x12, 0x11, 0x0a, 0x0d, 0x53, 0x45, 0x52, 0x56, 0x49, 0x43, 0x45, 0x5f, 0x45, 0x52, 0x52, 0x4f, 0x52, 0x10, 0x03, 0x12, 0x0d, 0x0a, 0x09, 0x4e, 0x4f, 0x54, 0x5f, 0x52, 0x45, 0x41, 0x44, 0x59, 0x10, 0x04, 0x22, 0x42, 0x0a, 0x1f, 0x43, 0x6f, 0x6e, 0x73, 0x65, 0x6e, 0x73, 0x75, 0x73, 0x49, 0x6e, 0x69, 0x74, 0x69, 0x61, 0x6c, 0x69, 0x7a, 0x65, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x1f, 0x0a, 0x0b, 0x70, 0x72, 0x65, 0x76, 0x69, 0x6f, 0x75, 0x73, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0a, 0x70, 0x72, 0x65, 0x76, 0x69, 0x6f, 0x75, 0x73, 0x49, 0x64, 0x22, 0xe1, 0x01, 0x0a, 0x20, 0x43, 0x6f, 0x6e, 0x73, 0x65, 0x6e, 0x73, 0x75, 0x73, 0x49, 0x6e, 0x69, 0x74, 0x69, 0x61, 0x6c, 0x69, 0x7a, 0x65, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x40, 0x0a, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x28, 0x2e, 0x43, 0x6f, 0x6e, 0x73, 0x65, 0x6e, 0x73, 0x75, 0x73, 0x49, 0x6e, 0x69, 0x74, 0x69, 0x61, 0x6c, 0x69, 0x7a, 0x65, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x2e, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x52, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x22, 0x7b, 0x0a, 0x06, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, 0x10, 0x0a, 0x0c, 0x53, 0x54, 0x41, 0x54, 0x55, 0x53, 0x5f, 0x55, 0x4e, 0x53, 0x45, 0x54, 0x10, 0x00, 0x12, 0x06, 0x0a, 0x02, 0x4f, 0x4b, 0x10, 0x01, 0x12, 0x0f, 0x0a, 0x0b, 0x42, 0x41, 0x44, 0x5f, 0x52, 0x45, 0x51, 0x55, 0x45, 0x53, 0x54, 0x10, 0x02, 0x12, 0x11, 0x0a, 0x0d, 0x53, 0x45, 0x52, 0x56, 0x49, 0x43, 0x45, 0x5f, 0x45, 0x52, 0x52, 0x4f, 0x52, 0x10, 0x03, 0x12, 0x0d, 0x0a, 0x09, 0x4e, 0x4f, 0x54, 0x5f, 0x52, 0x45, 0x41, 0x44, 0x59, 0x10, 0x04, 0x12, 0x11, 0x0a, 0x0d, 0x49, 0x4e, 0x56, 0x41, 0x4c, 0x49, 0x44, 0x5f, 0x53, 0x54, 0x41, 0x54, 0x45, 0x10, 0x05, 0x12, 0x11, 0x0a, 0x0d, 0x55, 0x4e, 0x4b, 0x4e, 0x4f, 0x57, 0x4e, 0x5f, 0x42, 0x4c, 0x4f, 0x43, 0x4b, 0x10, 0x06, 0x22, 0x20, 0x0a, 0x1e, 0x43, 0x6f, 0x6e, 0x73, 0x65, 0x6e, 0x73, 0x75, 0x73, 0x53, 0x75, 0x6d, 0x6d, 0x61, 0x72, 0x69, 0x7a, 0x65, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x22, 0xfb, 0x01, 0x0a, 0x1f, 0x43, 0x6f, 0x6e, 0x73, 0x65, 0x6e, 0x73, 0x75, 0x73, 0x53, 0x75, 0x6d, 0x6d, 0x61, 0x72, 0x69, 0x7a, 0x65, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x3f, 0x0a, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x27, 0x2e, 0x43, 0x6f, 0x6e, 0x73, 0x65, 0x6e, 0x73, 0x75, 0x73, 0x53, 0x75, 0x6d, 0x6d, 0x61, 0x72, 0x69, 0x7a, 0x65, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x2e, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x52, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, 0x18, 0x0a, 0x07, 0x73, 0x75, 0x6d, 0x6d, 0x61, 0x72, 0x79, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x07, 0x73, 0x75, 0x6d, 0x6d, 0x61, 0x72, 0x79, 0x22, 0x7d, 0x0a, 0x06, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, 0x10, 0x0a, 0x0c, 0x53, 0x54, 0x41, 0x54, 0x55, 0x53, 0x5f, 0x55, 0x4e, 0x53, 0x45, 0x54, 0x10, 0x00, 0x12, 0x06, 0x0a, 0x02, 0x4f, 0x4b, 0x10, 0x01, 0x12, 0x0f, 0x0a, 0x0b, 0x42, 0x41, 0x44, 0x5f, 0x52, 0x45, 0x51, 0x55, 0x45, 0x53, 0x54, 0x10, 0x02, 0x12, 0x11, 0x0a, 0x0d, 0x53, 0x45, 0x52, 0x56, 0x49, 0x43, 0x45, 0x5f, 0x45, 0x52, 0x52, 0x4f, 0x52, 0x10, 0x03, 0x12, 0x0d, 0x0a, 0x09, 0x4e, 0x4f, 0x54, 0x5f, 0x52, 0x45, 0x41, 0x44, 0x59, 0x10, 0x04, 0x12, 0x11, 0x0a, 0x0d, 0x49, 0x4e, 0x56, 0x41, 0x4c, 0x49, 0x44, 0x5f, 0x53, 0x54, 0x41, 0x54, 0x45, 0x10, 0x05, 0x12, 0x13, 0x0a, 0x0f, 0x42, 0x4c, 0x4f, 0x43, 0x4b, 0x5f, 0x4e, 0x4f, 0x54, 0x5f, 0x52, 0x45, 0x41, 0x44, 0x59, 0x10, 0x06, 0x22, 0x33, 0x0a, 0x1d, 0x43, 0x6f, 0x6e, 0x73, 0x65, 0x6e, 0x73, 0x75, 0x73, 0x46, 0x69, 0x6e, 0x61, 0x6c, 0x69, 0x7a, 0x65, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x12, 0x0a, 0x04, 0x64, 0x61, 0x74, 0x61, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x04, 0x64, 0x61, 0x74, 0x61, 0x22, 0xfa, 0x01, 0x0a, 0x1e, 0x43, 0x6f, 0x6e, 0x73, 0x65, 0x6e, 0x73, 0x75, 0x73, 0x46, 0x69, 0x6e, 0x61, 0x6c, 0x69, 0x7a, 0x65, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x3e, 0x0a, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x26, 0x2e, 0x43, 0x6f, 0x6e, 0x73, 0x65, 0x6e, 0x73, 0x75, 0x73, 0x46, 0x69, 0x6e, 0x61, 0x6c, 0x69, 0x7a, 0x65, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x2e, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x52, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, 0x19, 0x0a, 0x08, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x5f, 0x69, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x07, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x49, 0x64, 0x22, 0x7d, 0x0a, 0x06, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, 0x10, 0x0a, 0x0c, 0x53, 0x54, 0x41, 0x54, 0x55, 0x53, 0x5f, 0x55, 0x4e, 0x53, 0x45, 0x54, 0x10, 0x00, 0x12, 0x06, 0x0a, 0x02, 0x4f, 0x4b, 0x10, 0x01, 0x12, 0x0f, 0x0a, 0x0b, 0x42, 0x41, 0x44, 0x5f, 0x52, 0x45, 0x51, 0x55, 0x45, 0x53, 0x54, 0x10, 0x02, 0x12, 0x11, 0x0a, 0x0d, 0x53, 0x45, 0x52, 0x56, 0x49, 0x43, 0x45, 0x5f, 0x45, 0x52, 0x52, 0x4f, 0x52, 0x10, 0x03, 0x12, 0x0d, 0x0a, 0x09, 0x4e, 0x4f, 0x54, 0x5f, 0x52, 0x45, 0x41, 0x44, 0x59, 0x10, 0x04, 0x12, 0x11, 0x0a, 0x0d, 0x49, 0x4e, 0x56, 0x41, 0x4c, 0x49, 0x44, 0x5f, 0x53, 0x54, 0x41, 0x54, 0x45, 0x10, 0x05, 0x12, 0x13, 0x0a, 0x0f, 0x42, 0x4c, 0x4f, 0x43, 0x4b, 0x5f, 0x4e, 0x4f, 0x54, 0x5f, 0x52, 0x45, 0x41, 0x44, 0x59, 0x10, 0x06, 0x22, 0x1d, 0x0a, 0x1b, 0x43, 0x6f, 0x6e, 0x73, 0x65, 0x6e, 0x73, 0x75, 0x73, 0x43, 0x61, 0x6e, 0x63, 0x65, 0x6c, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x22, 0xc6, 0x01, 0x0a, 0x1c, 0x43, 0x6f, 0x6e, 0x73, 0x65, 0x6e, 0x73, 0x75, 0x73, 0x43, 0x61, 0x6e, 0x63, 0x65, 0x6c, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x3c, 0x0a, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x24, 0x2e, 0x43, 0x6f, 0x6e, 0x73, 0x65, 0x6e, 0x73, 0x75, 0x73, 0x43, 0x61, 0x6e, 0x63, 0x65, 0x6c, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x2e, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x52, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x22, 0x68, 0x0a, 0x06, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, 0x10, 0x0a, 0x0c, 0x53, 0x54, 0x41, 0x54, 0x55, 0x53, 0x5f, 0x55, 0x4e, 0x53, 0x45, 0x54, 0x10, 0x00, 0x12, 0x06, 0x0a, 0x02, 0x4f, 0x4b, 0x10, 0x01, 0x12, 0x0f, 0x0a, 0x0b, 0x42, 0x41, 0x44, 0x5f, 0x52, 0x45, 0x51, 0x55, 0x45, 0x53, 0x54, 0x10, 0x02, 0x12, 0x11, 0x0a, 0x0d, 0x53, 0x45, 0x52, 0x56, 0x49, 0x43, 0x45, 0x5f, 0x45, 0x52, 0x52, 0x4f, 0x52, 0x10, 0x03, 0x12, 0x0d, 0x0a, 0x09, 0x4e, 0x4f, 0x54, 0x5f, 0x52, 0x45, 0x41, 0x44, 0x59, 0x10, 0x04, 0x12, 0x11, 0x0a, 0x0d, 0x49, 0x4e, 0x56, 0x41, 0x4c, 0x49, 0x44, 0x5f, 0x53, 0x54, 0x41, 0x54, 0x45, 0x10, 0x05, 0x22, 0x3a, 0x0a, 0x1b, 0x43, 0x6f, 0x6e, 0x73, 0x65, 0x6e, 0x73, 0x75, 0x73, 0x43, 0x68, 0x65, 0x63, 0x6b, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x73, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x1b, 0x0a, 0x09, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x5f, 0x69, 0x64, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0c, 0x52, 0x08, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x49, 0x64, 0x73, 0x22, 0xc6, 0x01, 0x0a, 0x1c, 0x43, 0x6f, 0x6e, 0x73, 0x65, 0x6e, 0x73, 0x75, 0x73, 0x43, 0x68, 0x65, 0x63, 0x6b, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x73, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x3c, 0x0a, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x24, 0x2e, 0x43, 0x6f, 0x6e, 0x73, 0x65, 0x6e, 0x73, 0x75, 0x73, 0x43, 0x68, 0x65, 0x63, 0x6b, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x73, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x2e, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x52, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x22, 0x68, 0x0a, 0x06, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, 0x10, 0x0a, 0x0c, 0x53, 0x54, 0x41, 0x54, 0x55, 0x53, 0x5f, 0x55, 0x4e, 0x53, 0x45, 0x54, 0x10, 0x00, 0x12, 0x06, 0x0a, 0x02, 0x4f, 0x4b, 0x10, 0x01, 0x12, 0x0f, 0x0a, 0x0b, 0x42, 0x41, 0x44, 0x5f, 0x52, 0x45, 0x51, 0x55, 0x45, 0x53, 0x54, 0x10, 0x02, 0x12, 0x11, 0x0a, 0x0d, 0x53, 0x45, 0x52, 0x56, 0x49, 0x43, 0x45, 0x5f, 0x45, 0x52, 0x52, 0x4f, 0x52, 0x10, 0x03, 0x12, 0x0d, 0x0a, 0x09, 0x4e, 0x4f, 0x54, 0x5f, 0x52, 0x45, 0x41, 0x44, 0x59, 0x10, 0x04, 0x12, 0x11, 0x0a, 0x0d, 0x55, 0x4e, 0x4b, 0x4e, 0x4f, 0x57, 0x4e, 0x5f, 0x42, 0x4c, 0x4f, 0x43, 0x4b, 0x10, 0x05, 0x22, 0x38, 0x0a, 0x1b, 0x43, 0x6f, 0x6e, 0x73, 0x65, 0x6e, 0x73, 0x75, 0x73, 0x43, 0x6f, 0x6d, 0x6d, 0x69, 0x74, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x19, 0x0a, 0x08, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x07, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x49, 0x64, 0x22, 0xc6, 0x01, 0x0a, 0x1c, 0x43, 0x6f, 0x6e, 0x73, 0x65, 0x6e, 0x73, 0x75, 0x73, 0x43, 0x6f, 0x6d, 0x6d, 0x69, 0x74, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x3c, 0x0a, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x24, 0x2e, 0x43, 0x6f, 0x6e, 0x73, 0x65, 0x6e, 0x73, 0x75, 0x73, 0x43, 0x6f, 0x6d, 0x6d, 0x69, 0x74, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x2e, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x52, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x22, 0x68, 0x0a, 0x06, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, 0x10, 0x0a, 0x0c, 0x53, 0x54, 0x41, 0x54, 0x55, 0x53, 0x5f, 0x55, 0x4e, 0x53, 0x45, 0x54, 0x10, 0x00, 0x12, 0x06, 0x0a, 0x02, 0x4f, 0x4b, 0x10, 0x01, 0x12, 0x0f, 0x0a, 0x0b, 0x42, 0x41, 0x44, 0x5f, 0x52, 0x45, 0x51, 0x55, 0x45, 0x53, 0x54, 0x10, 0x02, 0x12, 0x11, 0x0a, 0x0d, 0x53, 0x45, 0x52, 0x56, 0x49, 0x43, 0x45, 0x5f, 0x45, 0x52, 0x52, 0x4f, 0x52, 0x10, 0x03, 0x12, 0x0d, 0x0a, 0x09, 0x4e, 0x4f, 0x54, 0x5f, 0x52, 0x45, 0x41, 0x44, 0x59, 0x10, 0x04, 0x12, 0x11, 0x0a, 0x0d, 0x55, 0x4e, 0x4b, 0x4e, 0x4f, 0x57, 0x4e, 0x5f, 0x42, 0x4c, 0x4f, 0x43, 0x4b, 0x10, 0x05, 0x22, 0x38, 0x0a, 0x1b, 0x43, 0x6f, 0x6e, 0x73, 0x65, 0x6e, 0x73, 0x75, 0x73, 0x49, 0x67, 0x6e, 0x6f, 0x72, 0x65, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x19, 0x0a, 0x08, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x07, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x49, 0x64, 0x22, 0xc6, 0x01, 0x0a, 0x1c, 0x43, 0x6f, 0x6e, 0x73, 0x65, 0x6e, 0x73, 0x75, 0x73, 0x49, 0x67, 0x6e, 0x6f, 0x72, 0x65, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x3c, 0x0a, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x24, 0x2e, 0x43, 0x6f, 0x6e, 0x73, 0x65, 0x6e, 0x73, 0x75, 0x73, 0x49, 0x67, 0x6e, 0x6f, 0x72, 0x65, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x2e, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x52, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x22, 0x68, 0x0a, 0x06, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, 0x10, 0x0a, 0x0c, 0x53, 0x54, 0x41, 0x54, 0x55, 0x53, 0x5f, 0x55, 0x4e, 0x53, 0x45, 0x54, 0x10, 0x00, 0x12, 0x06, 0x0a, 0x02, 0x4f, 0x4b, 0x10, 0x01, 0x12, 0x0f, 0x0a, 0x0b, 0x42, 0x41, 0x44, 0x5f, 0x52, 0x45, 0x51, 0x55, 0x45, 0x53, 0x54, 0x10, 0x02, 0x12, 0x11, 0x0a, 0x0d, 0x53, 0x45, 0x52, 0x56, 0x49, 0x43, 0x45, 0x5f, 0x45, 0x52, 0x52, 0x4f, 0x52, 0x10, 0x03, 0x12, 0x0d, 0x0a, 0x09, 0x4e, 0x4f, 0x54, 0x5f, 0x52, 0x45, 0x41, 0x44, 0x59, 0x10, 0x04, 0x12, 0x11, 0x0a, 0x0d, 0x55, 0x4e, 0x4b, 0x4e, 0x4f, 0x57, 0x4e, 0x5f, 0x42, 0x4c, 0x4f, 0x43, 0x4b, 0x10, 0x05, 0x22, 0x36, 0x0a, 0x19, 0x43, 0x6f, 0x6e, 0x73, 0x65, 0x6e, 0x73, 0x75, 0x73, 0x46, 0x61, 0x69, 0x6c, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x19, 0x0a, 0x08, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x07, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x49, 0x64, 0x22, 0xc2, 0x01, 0x0a, 0x1a, 0x43, 0x6f, 0x6e, 0x73, 0x65, 0x6e, 0x73, 0x75, 0x73, 0x46, 0x61, 0x69, 0x6c, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x3a, 0x0a, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x22, 0x2e, 0x43, 0x6f, 0x6e, 0x73, 0x65, 0x6e, 0x73, 0x75, 0x73, 0x46, 0x61, 0x69, 0x6c, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x2e, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x52, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x22, 0x68, 0x0a, 0x06, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, 0x10, 0x0a, 0x0c, 0x53, 0x54, 0x41, 0x54, 0x55, 0x53, 0x5f, 0x55, 0x4e, 0x53, 0x45, 0x54, 0x10, 0x00, 0x12, 0x06, 0x0a, 0x02, 0x4f, 0x4b, 0x10, 0x01, 0x12, 0x0f, 0x0a, 0x0b, 0x42, 0x41, 0x44, 0x5f, 0x52, 0x45, 0x51, 0x55, 0x45, 0x53, 0x54, 0x10, 0x02, 0x12, 0x11, 0x0a, 0x0d, 0x53, 0x45, 0x52, 0x56, 0x49, 0x43, 0x45, 0x5f, 0x45, 0x52, 0x52, 0x4f, 0x52, 0x10, 0x03, 0x12, 0x0d, 0x0a, 0x09, 0x4e, 0x4f, 0x54, 0x5f, 0x52, 0x45, 0x41, 0x44, 0x59, 0x10, 0x04, 0x12, 0x11, 0x0a, 0x0d, 0x55, 0x4e, 0x4b, 0x4e, 0x4f, 0x57, 0x4e, 0x5f, 0x42, 0x4c, 0x4f, 0x43, 0x4b, 0x10, 0x05, 0x22, 0x38, 0x0a, 0x19, 0x43, 0x6f, 0x6e, 0x73, 0x65, 0x6e, 0x73, 0x75, 0x73, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x73, 0x47, 0x65, 0x74, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x1b, 0x0a, 0x09, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x5f, 0x69, 0x64, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0c, 0x52, 0x08, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x49, 0x64, 0x73, 0x22, 0xeb, 0x01, 0x0a, 0x1a, 0x43, 0x6f, 0x6e, 0x73, 0x65, 0x6e, 0x73, 0x75, 0x73, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x73, 0x47, 0x65, 0x74, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x3a, 0x0a, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x22, 0x2e, 0x43, 0x6f, 0x6e, 0x73, 0x65, 0x6e, 0x73, 0x75, 0x73, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x73, 0x47, 0x65, 0x74, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x2e, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x52, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, 0x27, 0x0a, 0x06, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x0f, 0x2e, 0x43, 0x6f, 0x6e, 0x73, 0x65, 0x6e, 0x73, 0x75, 0x73, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x52, 0x06, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x73, 0x22, 0x68, 0x0a, 0x06, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, 0x10, 0x0a, 0x0c, 0x53, 0x54, 0x41, 0x54, 0x55, 0x53, 0x5f, 0x55, 0x4e, 0x53, 0x45, 0x54, 0x10, 0x00, 0x12, 0x06, 0x0a, 0x02, 0x4f, 0x4b, 0x10, 0x01, 0x12, 0x0f, 0x0a, 0x0b, 0x42, 0x41, 0x44, 0x5f, 0x52, 0x45, 0x51, 0x55, 0x45, 0x53, 0x54, 0x10, 0x02, 0x12, 0x11, 0x0a, 0x0d, 0x53, 0x45, 0x52, 0x56, 0x49, 0x43, 0x45, 0x5f, 0x45, 0x52, 0x52, 0x4f, 0x52, 0x10, 0x03, 0x12, 0x0d, 0x0a, 0x09, 0x4e, 0x4f, 0x54, 0x5f, 0x52, 0x45, 0x41, 0x44, 0x59, 0x10, 0x04, 0x12, 0x11, 0x0a, 0x0d, 0x55, 0x4e, 0x4b, 0x4e, 0x4f, 0x57, 0x4e, 0x5f, 0x42, 0x4c, 0x4f, 0x43, 0x4b, 0x10, 0x05, 0x22, 0x1e, 0x0a, 0x1c, 0x43, 0x6f, 0x6e, 0x73, 0x65, 0x6e, 0x73, 0x75, 0x73, 0x43, 0x68, 0x61, 0x69, 0x6e, 0x48, 0x65, 0x61, 0x64, 0x47, 0x65, 0x74, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x22, 0xef, 0x01, 0x0a, 0x1d, 0x43, 0x6f, 0x6e, 0x73, 0x65, 0x6e, 0x73, 0x75, 0x73, 0x43, 0x68, 0x61, 0x69, 0x6e, 0x48, 0x65, 0x61, 0x64, 0x47, 0x65, 0x74, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x3d, 0x0a, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x25, 0x2e, 0x43, 0x6f, 0x6e, 0x73, 0x65, 0x6e, 0x73, 0x75, 0x73, 0x43, 0x68, 0x61, 0x69, 0x6e, 0x48, 0x65, 0x61, 0x64, 0x47, 0x65, 0x74, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x2e, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x52, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, 0x25, 0x0a, 0x05, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x0f, 0x2e, 0x43, 0x6f, 0x6e, 0x73, 0x65, 0x6e, 0x73, 0x75, 0x73, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x52, 0x05, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x22, 0x68, 0x0a, 0x06, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, 0x10, 0x0a, 0x0c, 0x53, 0x54, 0x41, 0x54, 0x55, 0x53, 0x5f, 0x55, 0x4e, 0x53, 0x45, 0x54, 0x10, 0x00, 0x12, 0x06, 0x0a, 0x02, 0x4f, 0x4b, 0x10, 0x01, 0x12, 0x0f, 0x0a, 0x0b, 0x42, 0x41, 0x44, 0x5f, 0x52, 0x45, 0x51, 0x55, 0x45, 0x53, 0x54, 0x10, 0x02, 0x12, 0x11, 0x0a, 0x0d, 0x53, 0x45, 0x52, 0x56, 0x49, 0x43, 0x45, 0x5f, 0x45, 0x52, 0x52, 0x4f, 0x52, 0x10, 0x03, 0x12, 0x0d, 0x0a, 0x09, 0x4e, 0x4f, 0x54, 0x5f, 0x52, 0x45, 0x41, 0x44, 0x59, 0x10, 0x04, 0x12, 0x11, 0x0a, 0x0d, 0x4e, 0x4f, 0x5f, 0x43, 0x48, 0x41, 0x49, 0x4e, 0x5f, 0x48, 0x45, 0x41, 0x44, 0x10, 0x05, 0x22, 0x4c, 0x0a, 0x1b, 0x43, 0x6f, 0x6e, 0x73, 0x65, 0x6e, 0x73, 0x75, 0x73, 0x53, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x73, 0x47, 0x65, 0x74, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x19, 0x0a, 0x08, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x07, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x49, 0x64, 0x12, 0x12, 0x0a, 0x04, 0x6b, 0x65, 0x79, 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x09, 0x52, 0x04, 0x6b, 0x65, 0x79, 0x73, 0x22, 0xf9, 0x01, 0x0a, 0x1c, 0x43, 0x6f, 0x6e, 0x73, 0x65, 0x6e, 0x73, 0x75, 0x73, 0x53, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x73, 0x47, 0x65, 0x74, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x3c, 0x0a, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x24, 0x2e, 0x43, 0x6f, 0x6e, 0x73, 0x65, 0x6e, 0x73, 0x75, 0x73, 0x53, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x73, 0x47, 0x65, 0x74, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x2e, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x52, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, 0x31, 0x0a, 0x07, 0x65, 0x6e, 0x74, 0x72, 0x69, 0x65, 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x17, 0x2e, 0x43, 0x6f, 0x6e, 0x73, 0x65, 0x6e, 0x73, 0x75, 0x73, 0x53, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x73, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x52, 0x07, 0x65, 0x6e, 0x74, 0x72, 0x69, 0x65, 0x73, 0x22, 0x68, 0x0a, 0x06, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, 0x10, 0x0a, 0x0c, 0x53, 0x54, 0x41, 0x54, 0x55, 0x53, 0x5f, 0x55, 0x4e, 0x53, 0x45, 0x54, 0x10, 0x00, 0x12, 0x06, 0x0a, 0x02, 0x4f, 0x4b, 0x10, 0x01, 0x12, 0x0f, 0x0a, 0x0b, 0x42, 0x41, 0x44, 0x5f, 0x52, 0x45, 0x51, 0x55, 0x45, 0x53, 0x54, 0x10, 0x02, 0x12, 0x11, 0x0a, 0x0d, 0x53, 0x45, 0x52, 0x56, 0x49, 0x43, 0x45, 0x5f, 0x45, 0x52, 0x52, 0x4f, 0x52, 0x10, 0x03, 0x12, 0x0d, 0x0a, 0x09, 0x4e, 0x4f, 0x54, 0x5f, 0x52, 0x45, 0x41, 0x44, 0x59, 0x10, 0x04, 0x12, 0x11, 0x0a, 0x0d, 0x55, 0x4e, 0x4b, 0x4e, 0x4f, 0x57, 0x4e, 0x5f, 0x42, 0x4c, 0x4f, 0x43, 0x4b, 0x10, 0x05, 0x22, 0x53, 0x0a, 0x18, 0x43, 0x6f, 0x6e, 0x73, 0x65, 0x6e, 0x73, 0x75, 0x73, 0x53, 0x74, 0x61, 0x74, 0x65, 0x47, 0x65, 0x74, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x19, 0x0a, 0x08, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x07, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x49, 0x64, 0x12, 0x1c, 0x0a, 0x09, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x65, 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x09, 0x52, 0x09, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x65, 0x73, 0x22, 0xf0, 0x01, 0x0a, 0x19, 0x43, 0x6f, 0x6e, 0x73, 0x65, 0x6e, 0x73, 0x75, 0x73, 0x53, 0x74, 0x61, 0x74, 0x65, 0x47, 0x65, 0x74, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x39, 0x0a, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x21, 0x2e, 0x43, 0x6f, 0x6e, 0x73, 0x65, 0x6e, 0x73, 0x75, 0x73, 0x53, 0x74, 0x61, 0x74, 0x65, 0x47, 0x65, 0x74, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x2e, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x52, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, 0x2e, 0x0a, 0x07, 0x65, 0x6e, 0x74, 0x72, 0x69, 0x65, 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x14, 0x2e, 0x43, 0x6f, 0x6e, 0x73, 0x65, 0x6e, 0x73, 0x75, 0x73, 0x53, 0x74, 0x61, 0x74, 0x65, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x52, 0x07, 0x65, 0x6e, 0x74, 0x72, 0x69, 0x65, 0x73, 0x22, 0x68, 0x0a, 0x06, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, 0x10, 0x0a, 0x0c, 0x53, 0x54, 0x41, 0x54, 0x55, 0x53, 0x5f, 0x55, 0x4e, 0x53, 0x45, 0x54, 0x10, 0x00, 0x12, 0x06, 0x0a, 0x02, 0x4f, 0x4b, 0x10, 0x01, 0x12, 0x0f, 0x0a, 0x0b, 0x42, 0x41, 0x44, 0x5f, 0x52, 0x45, 0x51, 0x55, 0x45, 0x53, 0x54, 0x10, 0x02, 0x12, 0x11, 0x0a, 0x0d, 0x53, 0x45, 0x52, 0x56, 0x49, 0x43, 0x45, 0x5f, 0x45, 0x52, 0x52, 0x4f, 0x52, 0x10, 0x03, 0x12, 0x0d, 0x0a, 0x09, 0x4e, 0x4f, 0x54, 0x5f, 0x52, 0x45, 0x41, 0x44, 0x59, 0x10, 0x04, 0x12, 0x11, 0x0a, 0x0d, 0x55, 0x4e, 0x4b, 0x4e, 0x4f, 0x57, 0x4e, 0x5f, 0x42, 0x4c, 0x4f, 0x43, 0x4b, 0x10, 0x05, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( file_protobuf_consensus_pb2_consensus_proto_rawDescOnce sync.Once file_protobuf_consensus_pb2_consensus_proto_rawDescData = file_protobuf_consensus_pb2_consensus_proto_rawDesc ) func file_protobuf_consensus_pb2_consensus_proto_rawDescGZIP() []byte { file_protobuf_consensus_pb2_consensus_proto_rawDescOnce.Do(func() { file_protobuf_consensus_pb2_consensus_proto_rawDescData = protoimpl.X.CompressGZIP(file_protobuf_consensus_pb2_consensus_proto_rawDescData) }) return file_protobuf_consensus_pb2_consensus_proto_rawDescData } var file_protobuf_consensus_pb2_consensus_proto_enumTypes = make([]protoimpl.EnumInfo, 15) var file_protobuf_consensus_pb2_consensus_proto_msgTypes = make([]protoimpl.MessageInfo, 43) var file_protobuf_consensus_pb2_consensus_proto_goTypes = []interface{}{ (ConsensusRegisterResponse_Status)(0), // 0: ConsensusRegisterResponse.Status (ConsensusSendToResponse_Status)(0), // 1: ConsensusSendToResponse.Status (ConsensusBroadcastResponse_Status)(0), // 2: ConsensusBroadcastResponse.Status (ConsensusInitializeBlockResponse_Status)(0), // 3: ConsensusInitializeBlockResponse.Status (ConsensusSummarizeBlockResponse_Status)(0), // 4: ConsensusSummarizeBlockResponse.Status (ConsensusFinalizeBlockResponse_Status)(0), // 5: ConsensusFinalizeBlockResponse.Status (ConsensusCancelBlockResponse_Status)(0), // 6: ConsensusCancelBlockResponse.Status (ConsensusCheckBlocksResponse_Status)(0), // 7: ConsensusCheckBlocksResponse.Status (ConsensusCommitBlockResponse_Status)(0), // 8: ConsensusCommitBlockResponse.Status (ConsensusIgnoreBlockResponse_Status)(0), // 9: ConsensusIgnoreBlockResponse.Status (ConsensusFailBlockResponse_Status)(0), // 10: ConsensusFailBlockResponse.Status (ConsensusBlocksGetResponse_Status)(0), // 11: ConsensusBlocksGetResponse.Status (ConsensusChainHeadGetResponse_Status)(0), // 12: ConsensusChainHeadGetResponse.Status (ConsensusSettingsGetResponse_Status)(0), // 13: ConsensusSettingsGetResponse.Status (ConsensusStateGetResponse_Status)(0), // 14: ConsensusStateGetResponse.Status (*ConsensusPeerMessage)(nil), // 15: ConsensusPeerMessage (*ConsensusBlock)(nil), // 16: ConsensusBlock (*ConsensusPeerInfo)(nil), // 17: ConsensusPeerInfo (*ConsensusSettingsEntry)(nil), // 18: ConsensusSettingsEntry (*ConsensusStateEntry)(nil), // 19: ConsensusStateEntry (*ConsensusRegisterRequest)(nil), // 20: ConsensusRegisterRequest (*ConsensusRegisterResponse)(nil), // 21: ConsensusRegisterResponse (*ConsensusNotifyPeerConnected)(nil), // 22: ConsensusNotifyPeerConnected (*ConsensusNotifyPeerDisconnected)(nil), // 23: ConsensusNotifyPeerDisconnected (*ConsensusNotifyPeerMessage)(nil), // 24: ConsensusNotifyPeerMessage (*ConsensusNotifyBlockNew)(nil), // 25: ConsensusNotifyBlockNew (*ConsensusNotifyBlockValid)(nil), // 26: ConsensusNotifyBlockValid (*ConsensusNotifyBlockInvalid)(nil), // 27: ConsensusNotifyBlockInvalid (*ConsensusNotifyBlockCommit)(nil), // 28: ConsensusNotifyBlockCommit (*ConsensusNotifyAck)(nil), // 29: ConsensusNotifyAck (*ConsensusSendToRequest)(nil), // 30: ConsensusSendToRequest (*ConsensusSendToResponse)(nil), // 31: ConsensusSendToResponse (*ConsensusBroadcastRequest)(nil), // 32: ConsensusBroadcastRequest (*ConsensusBroadcastResponse)(nil), // 33: ConsensusBroadcastResponse (*ConsensusInitializeBlockRequest)(nil), // 34: ConsensusInitializeBlockRequest (*ConsensusInitializeBlockResponse)(nil), // 35: ConsensusInitializeBlockResponse (*ConsensusSummarizeBlockRequest)(nil), // 36: ConsensusSummarizeBlockRequest (*ConsensusSummarizeBlockResponse)(nil), // 37: ConsensusSummarizeBlockResponse (*ConsensusFinalizeBlockRequest)(nil), // 38: ConsensusFinalizeBlockRequest (*ConsensusFinalizeBlockResponse)(nil), // 39: ConsensusFinalizeBlockResponse (*ConsensusCancelBlockRequest)(nil), // 40: ConsensusCancelBlockRequest (*ConsensusCancelBlockResponse)(nil), // 41: ConsensusCancelBlockResponse (*ConsensusCheckBlocksRequest)(nil), // 42: ConsensusCheckBlocksRequest (*ConsensusCheckBlocksResponse)(nil), // 43: ConsensusCheckBlocksResponse (*ConsensusCommitBlockRequest)(nil), // 44: ConsensusCommitBlockRequest (*ConsensusCommitBlockResponse)(nil), // 45: ConsensusCommitBlockResponse (*ConsensusIgnoreBlockRequest)(nil), // 46: ConsensusIgnoreBlockRequest (*ConsensusIgnoreBlockResponse)(nil), // 47: ConsensusIgnoreBlockResponse (*ConsensusFailBlockRequest)(nil), // 48: ConsensusFailBlockRequest (*ConsensusFailBlockResponse)(nil), // 49: ConsensusFailBlockResponse (*ConsensusBlocksGetRequest)(nil), // 50: ConsensusBlocksGetRequest (*ConsensusBlocksGetResponse)(nil), // 51: ConsensusBlocksGetResponse (*ConsensusChainHeadGetRequest)(nil), // 52: ConsensusChainHeadGetRequest (*ConsensusChainHeadGetResponse)(nil), // 53: ConsensusChainHeadGetResponse (*ConsensusSettingsGetRequest)(nil), // 54: ConsensusSettingsGetRequest (*ConsensusSettingsGetResponse)(nil), // 55: ConsensusSettingsGetResponse (*ConsensusStateGetRequest)(nil), // 56: ConsensusStateGetRequest (*ConsensusStateGetResponse)(nil), // 57: ConsensusStateGetResponse } var file_protobuf_consensus_pb2_consensus_proto_depIdxs = []int32{ 0, // 0: ConsensusRegisterResponse.status:type_name -> ConsensusRegisterResponse.Status 16, // 1: ConsensusRegisterResponse.chain_head:type_name -> ConsensusBlock 17, // 2: ConsensusRegisterResponse.peers:type_name -> ConsensusPeerInfo 17, // 3: ConsensusRegisterResponse.local_peer_info:type_name -> ConsensusPeerInfo 17, // 4: ConsensusNotifyPeerConnected.peer_info:type_name -> ConsensusPeerInfo 15, // 5: ConsensusNotifyPeerMessage.message:type_name -> ConsensusPeerMessage 16, // 6: ConsensusNotifyBlockNew.block:type_name -> ConsensusBlock 15, // 7: ConsensusSendToRequest.message:type_name -> ConsensusPeerMessage 1, // 8: ConsensusSendToResponse.status:type_name -> ConsensusSendToResponse.Status 15, // 9: ConsensusBroadcastRequest.message:type_name -> ConsensusPeerMessage 2, // 10: ConsensusBroadcastResponse.status:type_name -> ConsensusBroadcastResponse.Status 3, // 11: ConsensusInitializeBlockResponse.status:type_name -> ConsensusInitializeBlockResponse.Status 4, // 12: ConsensusSummarizeBlockResponse.status:type_name -> ConsensusSummarizeBlockResponse.Status 5, // 13: ConsensusFinalizeBlockResponse.status:type_name -> ConsensusFinalizeBlockResponse.Status 6, // 14: ConsensusCancelBlockResponse.status:type_name -> ConsensusCancelBlockResponse.Status 7, // 15: ConsensusCheckBlocksResponse.status:type_name -> ConsensusCheckBlocksResponse.Status 8, // 16: ConsensusCommitBlockResponse.status:type_name -> ConsensusCommitBlockResponse.Status 9, // 17: ConsensusIgnoreBlockResponse.status:type_name -> ConsensusIgnoreBlockResponse.Status 10, // 18: ConsensusFailBlockResponse.status:type_name -> ConsensusFailBlockResponse.Status 11, // 19: ConsensusBlocksGetResponse.status:type_name -> ConsensusBlocksGetResponse.Status 16, // 20: ConsensusBlocksGetResponse.blocks:type_name -> ConsensusBlock 12, // 21: ConsensusChainHeadGetResponse.status:type_name -> ConsensusChainHeadGetResponse.Status 16, // 22: ConsensusChainHeadGetResponse.block:type_name -> ConsensusBlock 13, // 23: ConsensusSettingsGetResponse.status:type_name -> ConsensusSettingsGetResponse.Status 18, // 24: ConsensusSettingsGetResponse.entries:type_name -> ConsensusSettingsEntry 14, // 25: ConsensusStateGetResponse.status:type_name -> ConsensusStateGetResponse.Status 19, // 26: ConsensusStateGetResponse.entries:type_name -> ConsensusStateEntry 27, // [27:27] is the sub-list for method output_type 27, // [27:27] is the sub-list for method input_type 27, // [27:27] is the sub-list for extension type_name 27, // [27:27] is the sub-list for extension extendee 0, // [0:27] is the sub-list for field type_name } func init() { file_protobuf_consensus_pb2_consensus_proto_init() } func file_protobuf_consensus_pb2_consensus_proto_init() { if File_protobuf_consensus_pb2_consensus_proto != nil { return } if !protoimpl.UnsafeEnabled { file_protobuf_consensus_pb2_consensus_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ConsensusPeerMessage); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_consensus_pb2_consensus_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ConsensusBlock); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_consensus_pb2_consensus_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ConsensusPeerInfo); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_consensus_pb2_consensus_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ConsensusSettingsEntry); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_consensus_pb2_consensus_proto_msgTypes[4].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ConsensusStateEntry); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_consensus_pb2_consensus_proto_msgTypes[5].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ConsensusRegisterRequest); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_consensus_pb2_consensus_proto_msgTypes[6].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ConsensusRegisterResponse); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_consensus_pb2_consensus_proto_msgTypes[7].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ConsensusNotifyPeerConnected); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_consensus_pb2_consensus_proto_msgTypes[8].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ConsensusNotifyPeerDisconnected); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_consensus_pb2_consensus_proto_msgTypes[9].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ConsensusNotifyPeerMessage); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_consensus_pb2_consensus_proto_msgTypes[10].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ConsensusNotifyBlockNew); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_consensus_pb2_consensus_proto_msgTypes[11].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ConsensusNotifyBlockValid); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_consensus_pb2_consensus_proto_msgTypes[12].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ConsensusNotifyBlockInvalid); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_consensus_pb2_consensus_proto_msgTypes[13].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ConsensusNotifyBlockCommit); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_consensus_pb2_consensus_proto_msgTypes[14].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ConsensusNotifyAck); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_consensus_pb2_consensus_proto_msgTypes[15].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ConsensusSendToRequest); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_consensus_pb2_consensus_proto_msgTypes[16].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ConsensusSendToResponse); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_consensus_pb2_consensus_proto_msgTypes[17].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ConsensusBroadcastRequest); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_consensus_pb2_consensus_proto_msgTypes[18].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ConsensusBroadcastResponse); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_consensus_pb2_consensus_proto_msgTypes[19].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ConsensusInitializeBlockRequest); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_consensus_pb2_consensus_proto_msgTypes[20].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ConsensusInitializeBlockResponse); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_consensus_pb2_consensus_proto_msgTypes[21].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ConsensusSummarizeBlockRequest); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_consensus_pb2_consensus_proto_msgTypes[22].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ConsensusSummarizeBlockResponse); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_consensus_pb2_consensus_proto_msgTypes[23].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ConsensusFinalizeBlockRequest); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_consensus_pb2_consensus_proto_msgTypes[24].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ConsensusFinalizeBlockResponse); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_consensus_pb2_consensus_proto_msgTypes[25].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ConsensusCancelBlockRequest); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_consensus_pb2_consensus_proto_msgTypes[26].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ConsensusCancelBlockResponse); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_consensus_pb2_consensus_proto_msgTypes[27].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ConsensusCheckBlocksRequest); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_consensus_pb2_consensus_proto_msgTypes[28].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ConsensusCheckBlocksResponse); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_consensus_pb2_consensus_proto_msgTypes[29].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ConsensusCommitBlockRequest); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_consensus_pb2_consensus_proto_msgTypes[30].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ConsensusCommitBlockResponse); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_consensus_pb2_consensus_proto_msgTypes[31].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ConsensusIgnoreBlockRequest); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_consensus_pb2_consensus_proto_msgTypes[32].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ConsensusIgnoreBlockResponse); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_consensus_pb2_consensus_proto_msgTypes[33].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ConsensusFailBlockRequest); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_consensus_pb2_consensus_proto_msgTypes[34].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ConsensusFailBlockResponse); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_consensus_pb2_consensus_proto_msgTypes[35].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ConsensusBlocksGetRequest); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_consensus_pb2_consensus_proto_msgTypes[36].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ConsensusBlocksGetResponse); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_consensus_pb2_consensus_proto_msgTypes[37].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ConsensusChainHeadGetRequest); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_consensus_pb2_consensus_proto_msgTypes[38].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ConsensusChainHeadGetResponse); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_consensus_pb2_consensus_proto_msgTypes[39].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ConsensusSettingsGetRequest); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_consensus_pb2_consensus_proto_msgTypes[40].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ConsensusSettingsGetResponse); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_consensus_pb2_consensus_proto_msgTypes[41].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ConsensusStateGetRequest); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_consensus_pb2_consensus_proto_msgTypes[42].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ConsensusStateGetResponse); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: file_protobuf_consensus_pb2_consensus_proto_rawDesc, NumEnums: 15, NumMessages: 43, NumExtensions: 0, NumServices: 0, }, GoTypes: file_protobuf_consensus_pb2_consensus_proto_goTypes, DependencyIndexes: file_protobuf_consensus_pb2_consensus_proto_depIdxs, EnumInfos: file_protobuf_consensus_pb2_consensus_proto_enumTypes, MessageInfos: file_protobuf_consensus_pb2_consensus_proto_msgTypes, }.Build() File_protobuf_consensus_pb2_consensus_proto = out.File file_protobuf_consensus_pb2_consensus_proto_rawDesc = nil file_protobuf_consensus_pb2_consensus_proto_goTypes = nil file_protobuf_consensus_pb2_consensus_proto_depIdxs = nil } <|start_filename|>protobuf/client_status_pb2/client_status.pb.go<|end_filename|> // Copyright 2017 Intel Corporation // // 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. // ----------------------------------------------------------------------------- // Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.25.0-devel // protoc v3.14.0 // source: protobuf/client_status_pb2/client_status.proto package client_status import ( protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" sync "sync" ) const ( // Verify that this generated code is sufficiently up-to-date. _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) // Verify that runtime/protoimpl is sufficiently up-to-date. _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) // The status of the response message, not the validator's status type ClientStatusGetResponse_Status int32 const ( ClientStatusGetResponse_STATUS_UNSET ClientStatusGetResponse_Status = 0 ClientStatusGetResponse_OK ClientStatusGetResponse_Status = 1 ClientStatusGetResponse_ERROR ClientStatusGetResponse_Status = 2 ) // Enum value maps for ClientStatusGetResponse_Status. var ( ClientStatusGetResponse_Status_name = map[int32]string{ 0: "STATUS_UNSET", 1: "OK", 2: "ERROR", } ClientStatusGetResponse_Status_value = map[string]int32{ "STATUS_UNSET": 0, "OK": 1, "ERROR": 2, } ) func (x ClientStatusGetResponse_Status) Enum() *ClientStatusGetResponse_Status { p := new(ClientStatusGetResponse_Status) *p = x return p } func (x ClientStatusGetResponse_Status) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (ClientStatusGetResponse_Status) Descriptor() protoreflect.EnumDescriptor { return file_protobuf_client_status_pb2_client_status_proto_enumTypes[0].Descriptor() } func (ClientStatusGetResponse_Status) Type() protoreflect.EnumType { return &file_protobuf_client_status_pb2_client_status_proto_enumTypes[0] } func (x ClientStatusGetResponse_Status) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use ClientStatusGetResponse_Status.Descriptor instead. func (ClientStatusGetResponse_Status) EnumDescriptor() ([]byte, []int) { return file_protobuf_client_status_pb2_client_status_proto_rawDescGZIP(), []int{1, 0} } // A request to get miscellaneous information about the validator type ClientStatusGetRequest struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields } func (x *ClientStatusGetRequest) Reset() { *x = ClientStatusGetRequest{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_client_status_pb2_client_status_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ClientStatusGetRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*ClientStatusGetRequest) ProtoMessage() {} func (x *ClientStatusGetRequest) ProtoReflect() protoreflect.Message { mi := &file_protobuf_client_status_pb2_client_status_proto_msgTypes[0] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ClientStatusGetRequest.ProtoReflect.Descriptor instead. func (*ClientStatusGetRequest) Descriptor() ([]byte, []int) { return file_protobuf_client_status_pb2_client_status_proto_rawDescGZIP(), []int{0} } type ClientStatusGetResponse struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Status ClientStatusGetResponse_Status `protobuf:"varint,1,opt,name=status,proto3,enum=ClientStatusGetResponse_Status" json:"status,omitempty"` Peers []*ClientStatusGetResponse_Peer `protobuf:"bytes,2,rep,name=peers,proto3" json:"peers,omitempty"` // The validator's public network endpoint Endpoint string `protobuf:"bytes,3,opt,name=endpoint,proto3" json:"endpoint,omitempty"` } func (x *ClientStatusGetResponse) Reset() { *x = ClientStatusGetResponse{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_client_status_pb2_client_status_proto_msgTypes[1] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ClientStatusGetResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*ClientStatusGetResponse) ProtoMessage() {} func (x *ClientStatusGetResponse) ProtoReflect() protoreflect.Message { mi := &file_protobuf_client_status_pb2_client_status_proto_msgTypes[1] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ClientStatusGetResponse.ProtoReflect.Descriptor instead. func (*ClientStatusGetResponse) Descriptor() ([]byte, []int) { return file_protobuf_client_status_pb2_client_status_proto_rawDescGZIP(), []int{1} } func (x *ClientStatusGetResponse) GetStatus() ClientStatusGetResponse_Status { if x != nil { return x.Status } return ClientStatusGetResponse_STATUS_UNSET } func (x *ClientStatusGetResponse) GetPeers() []*ClientStatusGetResponse_Peer { if x != nil { return x.Peers } return nil } func (x *ClientStatusGetResponse) GetEndpoint() string { if x != nil { return x.Endpoint } return "" } // Information about the validator's peers type ClientStatusGetResponse_Peer struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // The peer's public network endpoint Endpoint string `protobuf:"bytes,1,opt,name=endpoint,proto3" json:"endpoint,omitempty"` } func (x *ClientStatusGetResponse_Peer) Reset() { *x = ClientStatusGetResponse_Peer{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_client_status_pb2_client_status_proto_msgTypes[2] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ClientStatusGetResponse_Peer) String() string { return protoimpl.X.MessageStringOf(x) } func (*ClientStatusGetResponse_Peer) ProtoMessage() {} func (x *ClientStatusGetResponse_Peer) ProtoReflect() protoreflect.Message { mi := &file_protobuf_client_status_pb2_client_status_proto_msgTypes[2] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ClientStatusGetResponse_Peer.ProtoReflect.Descriptor instead. func (*ClientStatusGetResponse_Peer) Descriptor() ([]byte, []int) { return file_protobuf_client_status_pb2_client_status_proto_rawDescGZIP(), []int{1, 0} } func (x *ClientStatusGetResponse_Peer) GetEndpoint() string { if x != nil { return x.Endpoint } return "" } var File_protobuf_client_status_pb2_client_status_proto protoreflect.FileDescriptor var file_protobuf_client_status_pb2_client_status_proto_rawDesc = []byte{ 0x0a, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x5f, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x5f, 0x70, 0x62, 0x32, 0x2f, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x5f, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0x18, 0x0a, 0x16, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x47, 0x65, 0x74, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x22, 0xf6, 0x01, 0x0a, 0x17, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x47, 0x65, 0x74, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x37, 0x0a, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x1f, 0x2e, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x47, 0x65, 0x74, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x2e, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x52, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, 0x33, 0x0a, 0x05, 0x70, 0x65, 0x65, 0x72, 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x1d, 0x2e, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x47, 0x65, 0x74, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x2e, 0x50, 0x65, 0x65, 0x72, 0x52, 0x05, 0x70, 0x65, 0x65, 0x72, 0x73, 0x12, 0x1a, 0x0a, 0x08, 0x65, 0x6e, 0x64, 0x70, 0x6f, 0x69, 0x6e, 0x74, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x65, 0x6e, 0x64, 0x70, 0x6f, 0x69, 0x6e, 0x74, 0x1a, 0x22, 0x0a, 0x04, 0x50, 0x65, 0x65, 0x72, 0x12, 0x1a, 0x0a, 0x08, 0x65, 0x6e, 0x64, 0x70, 0x6f, 0x69, 0x6e, 0x74, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x65, 0x6e, 0x64, 0x70, 0x6f, 0x69, 0x6e, 0x74, 0x22, 0x2d, 0x0a, 0x06, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, 0x10, 0x0a, 0x0c, 0x53, 0x54, 0x41, 0x54, 0x55, 0x53, 0x5f, 0x55, 0x4e, 0x53, 0x45, 0x54, 0x10, 0x00, 0x12, 0x06, 0x0a, 0x02, 0x4f, 0x4b, 0x10, 0x01, 0x12, 0x09, 0x0a, 0x05, 0x45, 0x52, 0x52, 0x4f, 0x52, 0x10, 0x02, 0x42, 0x28, 0x0a, 0x15, 0x73, 0x61, 0x77, 0x74, 0x6f, 0x6f, 0x74, 0x68, 0x2e, 0x73, 0x64, 0x6b, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x50, 0x01, 0x5a, 0x0d, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x5f, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( file_protobuf_client_status_pb2_client_status_proto_rawDescOnce sync.Once file_protobuf_client_status_pb2_client_status_proto_rawDescData = file_protobuf_client_status_pb2_client_status_proto_rawDesc ) func file_protobuf_client_status_pb2_client_status_proto_rawDescGZIP() []byte { file_protobuf_client_status_pb2_client_status_proto_rawDescOnce.Do(func() { file_protobuf_client_status_pb2_client_status_proto_rawDescData = protoimpl.X.CompressGZIP(file_protobuf_client_status_pb2_client_status_proto_rawDescData) }) return file_protobuf_client_status_pb2_client_status_proto_rawDescData } var file_protobuf_client_status_pb2_client_status_proto_enumTypes = make([]protoimpl.EnumInfo, 1) var file_protobuf_client_status_pb2_client_status_proto_msgTypes = make([]protoimpl.MessageInfo, 3) var file_protobuf_client_status_pb2_client_status_proto_goTypes = []interface{}{ (ClientStatusGetResponse_Status)(0), // 0: ClientStatusGetResponse.Status (*ClientStatusGetRequest)(nil), // 1: ClientStatusGetRequest (*ClientStatusGetResponse)(nil), // 2: ClientStatusGetResponse (*ClientStatusGetResponse_Peer)(nil), // 3: ClientStatusGetResponse.Peer } var file_protobuf_client_status_pb2_client_status_proto_depIdxs = []int32{ 0, // 0: ClientStatusGetResponse.status:type_name -> ClientStatusGetResponse.Status 3, // 1: ClientStatusGetResponse.peers:type_name -> ClientStatusGetResponse.Peer 2, // [2:2] is the sub-list for method output_type 2, // [2:2] is the sub-list for method input_type 2, // [2:2] is the sub-list for extension type_name 2, // [2:2] is the sub-list for extension extendee 0, // [0:2] is the sub-list for field type_name } func init() { file_protobuf_client_status_pb2_client_status_proto_init() } func file_protobuf_client_status_pb2_client_status_proto_init() { if File_protobuf_client_status_pb2_client_status_proto != nil { return } if !protoimpl.UnsafeEnabled { file_protobuf_client_status_pb2_client_status_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ClientStatusGetRequest); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_client_status_pb2_client_status_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ClientStatusGetResponse); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_client_status_pb2_client_status_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ClientStatusGetResponse_Peer); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: file_protobuf_client_status_pb2_client_status_proto_rawDesc, NumEnums: 1, NumMessages: 3, NumExtensions: 0, NumServices: 0, }, GoTypes: file_protobuf_client_status_pb2_client_status_proto_goTypes, DependencyIndexes: file_protobuf_client_status_pb2_client_status_proto_depIdxs, EnumInfos: file_protobuf_client_status_pb2_client_status_proto_enumTypes, MessageInfos: file_protobuf_client_status_pb2_client_status_proto_msgTypes, }.Build() File_protobuf_client_status_pb2_client_status_proto = out.File file_protobuf_client_status_pb2_client_status_proto_rawDesc = nil file_protobuf_client_status_pb2_client_status_proto_goTypes = nil file_protobuf_client_status_pb2_client_status_proto_depIdxs = nil } <|start_filename|>protobuf/client_block_pb2/client_block.pb.go<|end_filename|> // Copyright 2017 Intel Corporation // // 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. // ----------------------------------------------------------------------------- // Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.25.0-devel // protoc v3.14.0 // source: protobuf/client_block_pb2/client_block.proto package client_block_pb2 import ( protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" block_pb2 "github.com/hyperledger/sawtooth-sdk-go/protobuf/block_pb2" client_list_control_pb2 "github.com/hyperledger/sawtooth-sdk-go/protobuf/client_list_control_pb2" reflect "reflect" sync "sync" ) const ( // Verify that this generated code is sufficiently up-to-date. _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) // Verify that runtime/protoimpl is sufficiently up-to-date. _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) type ClientBlockListResponse_Status int32 const ( ClientBlockListResponse_STATUS_UNSET ClientBlockListResponse_Status = 0 ClientBlockListResponse_OK ClientBlockListResponse_Status = 1 ClientBlockListResponse_INTERNAL_ERROR ClientBlockListResponse_Status = 2 ClientBlockListResponse_NOT_READY ClientBlockListResponse_Status = 3 ClientBlockListResponse_NO_ROOT ClientBlockListResponse_Status = 4 ClientBlockListResponse_NO_RESOURCE ClientBlockListResponse_Status = 5 ClientBlockListResponse_INVALID_PAGING ClientBlockListResponse_Status = 6 ClientBlockListResponse_INVALID_SORT ClientBlockListResponse_Status = 7 ClientBlockListResponse_INVALID_ID ClientBlockListResponse_Status = 8 ) // Enum value maps for ClientBlockListResponse_Status. var ( ClientBlockListResponse_Status_name = map[int32]string{ 0: "STATUS_UNSET", 1: "OK", 2: "INTERNAL_ERROR", 3: "NOT_READY", 4: "NO_ROOT", 5: "NO_RESOURCE", 6: "INVALID_PAGING", 7: "INVALID_SORT", 8: "INVALID_ID", } ClientBlockListResponse_Status_value = map[string]int32{ "STATUS_UNSET": 0, "OK": 1, "INTERNAL_ERROR": 2, "NOT_READY": 3, "NO_ROOT": 4, "NO_RESOURCE": 5, "INVALID_PAGING": 6, "INVALID_SORT": 7, "INVALID_ID": 8, } ) func (x ClientBlockListResponse_Status) Enum() *ClientBlockListResponse_Status { p := new(ClientBlockListResponse_Status) *p = x return p } func (x ClientBlockListResponse_Status) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (ClientBlockListResponse_Status) Descriptor() protoreflect.EnumDescriptor { return file_protobuf_client_block_pb2_client_block_proto_enumTypes[0].Descriptor() } func (ClientBlockListResponse_Status) Type() protoreflect.EnumType { return &file_protobuf_client_block_pb2_client_block_proto_enumTypes[0] } func (x ClientBlockListResponse_Status) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use ClientBlockListResponse_Status.Descriptor instead. func (ClientBlockListResponse_Status) EnumDescriptor() ([]byte, []int) { return file_protobuf_client_block_pb2_client_block_proto_rawDescGZIP(), []int{1, 0} } type ClientBlockGetResponse_Status int32 const ( ClientBlockGetResponse_STATUS_UNSET ClientBlockGetResponse_Status = 0 ClientBlockGetResponse_OK ClientBlockGetResponse_Status = 1 ClientBlockGetResponse_INTERNAL_ERROR ClientBlockGetResponse_Status = 2 ClientBlockGetResponse_NO_RESOURCE ClientBlockGetResponse_Status = 5 ClientBlockGetResponse_INVALID_ID ClientBlockGetResponse_Status = 8 ) // Enum value maps for ClientBlockGetResponse_Status. var ( ClientBlockGetResponse_Status_name = map[int32]string{ 0: "STATUS_UNSET", 1: "OK", 2: "INTERNAL_ERROR", 5: "NO_RESOURCE", 8: "INVALID_ID", } ClientBlockGetResponse_Status_value = map[string]int32{ "STATUS_UNSET": 0, "OK": 1, "INTERNAL_ERROR": 2, "NO_RESOURCE": 5, "INVALID_ID": 8, } ) func (x ClientBlockGetResponse_Status) Enum() *ClientBlockGetResponse_Status { p := new(ClientBlockGetResponse_Status) *p = x return p } func (x ClientBlockGetResponse_Status) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (ClientBlockGetResponse_Status) Descriptor() protoreflect.EnumDescriptor { return file_protobuf_client_block_pb2_client_block_proto_enumTypes[1].Descriptor() } func (ClientBlockGetResponse_Status) Type() protoreflect.EnumType { return &file_protobuf_client_block_pb2_client_block_proto_enumTypes[1] } func (x ClientBlockGetResponse_Status) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use ClientBlockGetResponse_Status.Descriptor instead. func (ClientBlockGetResponse_Status) EnumDescriptor() ([]byte, []int) { return file_protobuf_client_block_pb2_client_block_proto_rawDescGZIP(), []int{6, 0} } // A request to return a list of blocks from the validator. May include the id // of a particular block to be the `head` of the chain being requested. In that // case the list will include that block (if found), and all blocks previous // to it on the chain. Can be filtered using specific `block_ids`. type ClientBlockListRequest struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields HeadId string `protobuf:"bytes,1,opt,name=head_id,json=headId,proto3" json:"head_id,omitempty"` BlockIds []string `protobuf:"bytes,2,rep,name=block_ids,json=blockIds,proto3" json:"block_ids,omitempty"` Paging *client_list_control_pb2.ClientPagingControls `protobuf:"bytes,3,opt,name=paging,proto3" json:"paging,omitempty"` Sorting []*client_list_control_pb2.ClientSortControls `protobuf:"bytes,4,rep,name=sorting,proto3" json:"sorting,omitempty"` } func (x *ClientBlockListRequest) Reset() { *x = ClientBlockListRequest{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_client_block_pb2_client_block_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ClientBlockListRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*ClientBlockListRequest) ProtoMessage() {} func (x *ClientBlockListRequest) ProtoReflect() protoreflect.Message { mi := &file_protobuf_client_block_pb2_client_block_proto_msgTypes[0] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ClientBlockListRequest.ProtoReflect.Descriptor instead. func (*ClientBlockListRequest) Descriptor() ([]byte, []int) { return file_protobuf_client_block_pb2_client_block_proto_rawDescGZIP(), []int{0} } func (x *ClientBlockListRequest) GetHeadId() string { if x != nil { return x.HeadId } return "" } func (x *ClientBlockListRequest) GetBlockIds() []string { if x != nil { return x.BlockIds } return nil } func (x *ClientBlockListRequest) GetPaging() *client_list_control_pb2.ClientPagingControls { if x != nil { return x.Paging } return nil } func (x *ClientBlockListRequest) GetSorting() []*client_list_control_pb2.ClientSortControls { if x != nil { return x.Sorting } return nil } // A response that lists a chain of blocks with the newest at the beginning, // and the oldest (genesis) block at the end. // // Statuses: // * OK - everything worked as expected // * INTERNAL_ERROR - general error, such as protobuf failing to deserialize // * NOT_READY - the validator does not yet have a genesis block // * NO_ROOT - the head block specified was not found // * NO_RESOURCE - no blocks were found with the parameters specified // * INVALID_PAGING - the paging controls were malformed or out of range // * INVALID_SORT - the sorting controls were malformed or invalid type ClientBlockListResponse struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Status ClientBlockListResponse_Status `protobuf:"varint,1,opt,name=status,proto3,enum=ClientBlockListResponse_Status" json:"status,omitempty"` Blocks []*block_pb2.Block `protobuf:"bytes,2,rep,name=blocks,proto3" json:"blocks,omitempty"` HeadId string `protobuf:"bytes,3,opt,name=head_id,json=headId,proto3" json:"head_id,omitempty"` Paging *client_list_control_pb2.ClientPagingResponse `protobuf:"bytes,4,opt,name=paging,proto3" json:"paging,omitempty"` } func (x *ClientBlockListResponse) Reset() { *x = ClientBlockListResponse{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_client_block_pb2_client_block_proto_msgTypes[1] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ClientBlockListResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*ClientBlockListResponse) ProtoMessage() {} func (x *ClientBlockListResponse) ProtoReflect() protoreflect.Message { mi := &file_protobuf_client_block_pb2_client_block_proto_msgTypes[1] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ClientBlockListResponse.ProtoReflect.Descriptor instead. func (*ClientBlockListResponse) Descriptor() ([]byte, []int) { return file_protobuf_client_block_pb2_client_block_proto_rawDescGZIP(), []int{1} } func (x *ClientBlockListResponse) GetStatus() ClientBlockListResponse_Status { if x != nil { return x.Status } return ClientBlockListResponse_STATUS_UNSET } func (x *ClientBlockListResponse) GetBlocks() []*block_pb2.Block { if x != nil { return x.Blocks } return nil } func (x *ClientBlockListResponse) GetHeadId() string { if x != nil { return x.HeadId } return "" } func (x *ClientBlockListResponse) GetPaging() *client_list_control_pb2.ClientPagingResponse { if x != nil { return x.Paging } return nil } // A request to return a specific block from the validator. The block must be // specified by its unique id, in this case the block's header signature type ClientBlockGetByIdRequest struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields BlockId string `protobuf:"bytes,1,opt,name=block_id,json=blockId,proto3" json:"block_id,omitempty"` } func (x *ClientBlockGetByIdRequest) Reset() { *x = ClientBlockGetByIdRequest{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_client_block_pb2_client_block_proto_msgTypes[2] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ClientBlockGetByIdRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*ClientBlockGetByIdRequest) ProtoMessage() {} func (x *ClientBlockGetByIdRequest) ProtoReflect() protoreflect.Message { mi := &file_protobuf_client_block_pb2_client_block_proto_msgTypes[2] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ClientBlockGetByIdRequest.ProtoReflect.Descriptor instead. func (*ClientBlockGetByIdRequest) Descriptor() ([]byte, []int) { return file_protobuf_client_block_pb2_client_block_proto_rawDescGZIP(), []int{2} } func (x *ClientBlockGetByIdRequest) GetBlockId() string { if x != nil { return x.BlockId } return "" } // A request to return a specific block from the validator. The block must be // specified by its block number type ClientBlockGetByNumRequest struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields BlockNum uint64 `protobuf:"varint,1,opt,name=block_num,json=blockNum,proto3" json:"block_num,omitempty"` } func (x *ClientBlockGetByNumRequest) Reset() { *x = ClientBlockGetByNumRequest{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_client_block_pb2_client_block_proto_msgTypes[3] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ClientBlockGetByNumRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*ClientBlockGetByNumRequest) ProtoMessage() {} func (x *ClientBlockGetByNumRequest) ProtoReflect() protoreflect.Message { mi := &file_protobuf_client_block_pb2_client_block_proto_msgTypes[3] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ClientBlockGetByNumRequest.ProtoReflect.Descriptor instead. func (*ClientBlockGetByNumRequest) Descriptor() ([]byte, []int) { return file_protobuf_client_block_pb2_client_block_proto_rawDescGZIP(), []int{3} } func (x *ClientBlockGetByNumRequest) GetBlockNum() uint64 { if x != nil { return x.BlockNum } return 0 } // A request to return a specific block from the validator. The block // containing the given transaction is returned. If no block on the current // chain contains the transaction, NO_RESOURCE is returned. type ClientBlockGetByTransactionIdRequest struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields TransactionId string `protobuf:"bytes,1,opt,name=transaction_id,json=transactionId,proto3" json:"transaction_id,omitempty"` } func (x *ClientBlockGetByTransactionIdRequest) Reset() { *x = ClientBlockGetByTransactionIdRequest{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_client_block_pb2_client_block_proto_msgTypes[4] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ClientBlockGetByTransactionIdRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*ClientBlockGetByTransactionIdRequest) ProtoMessage() {} func (x *ClientBlockGetByTransactionIdRequest) ProtoReflect() protoreflect.Message { mi := &file_protobuf_client_block_pb2_client_block_proto_msgTypes[4] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ClientBlockGetByTransactionIdRequest.ProtoReflect.Descriptor instead. func (*ClientBlockGetByTransactionIdRequest) Descriptor() ([]byte, []int) { return file_protobuf_client_block_pb2_client_block_proto_rawDescGZIP(), []int{4} } func (x *ClientBlockGetByTransactionIdRequest) GetTransactionId() string { if x != nil { return x.TransactionId } return "" } // A request to return a specific block from the validator. The block // containing the given batch is returned. If no block on the current chain // contains the batch, NO_RESOURCE is returned. type ClientBlockGetByBatchIdRequest struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields BatchId string `protobuf:"bytes,1,opt,name=batch_id,json=batchId,proto3" json:"batch_id,omitempty"` } func (x *ClientBlockGetByBatchIdRequest) Reset() { *x = ClientBlockGetByBatchIdRequest{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_client_block_pb2_client_block_proto_msgTypes[5] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ClientBlockGetByBatchIdRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*ClientBlockGetByBatchIdRequest) ProtoMessage() {} func (x *ClientBlockGetByBatchIdRequest) ProtoReflect() protoreflect.Message { mi := &file_protobuf_client_block_pb2_client_block_proto_msgTypes[5] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ClientBlockGetByBatchIdRequest.ProtoReflect.Descriptor instead. func (*ClientBlockGetByBatchIdRequest) Descriptor() ([]byte, []int) { return file_protobuf_client_block_pb2_client_block_proto_rawDescGZIP(), []int{5} } func (x *ClientBlockGetByBatchIdRequest) GetBatchId() string { if x != nil { return x.BatchId } return "" } // A response that returns the block specified by a ClientBlockGetByIdRequest // or ClientBlockGetByNumRequest. // // Statuses: // * OK - everything worked as expected // * INTERNAL_ERROR - general error, such as protobuf failing to deserialize // * NO_RESOURCE - no block with the specified id exists type ClientBlockGetResponse struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Status ClientBlockGetResponse_Status `protobuf:"varint,1,opt,name=status,proto3,enum=ClientBlockGetResponse_Status" json:"status,omitempty"` Block *block_pb2.Block `protobuf:"bytes,2,opt,name=block,proto3" json:"block,omitempty"` } func (x *ClientBlockGetResponse) Reset() { *x = ClientBlockGetResponse{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_client_block_pb2_client_block_proto_msgTypes[6] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ClientBlockGetResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*ClientBlockGetResponse) ProtoMessage() {} func (x *ClientBlockGetResponse) ProtoReflect() protoreflect.Message { mi := &file_protobuf_client_block_pb2_client_block_proto_msgTypes[6] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ClientBlockGetResponse.ProtoReflect.Descriptor instead. func (*ClientBlockGetResponse) Descriptor() ([]byte, []int) { return file_protobuf_client_block_pb2_client_block_proto_rawDescGZIP(), []int{6} } func (x *ClientBlockGetResponse) GetStatus() ClientBlockGetResponse_Status { if x != nil { return x.Status } return ClientBlockGetResponse_STATUS_UNSET } func (x *ClientBlockGetResponse) GetBlock() *block_pb2.Block { if x != nil { return x.Block } return nil } var File_protobuf_client_block_pb2_client_block_proto protoreflect.FileDescriptor var file_protobuf_client_block_pb2_client_block_proto_rawDesc = []byte{ 0x0a, 0x2c, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x5f, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x5f, 0x70, 0x62, 0x32, 0x2f, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x5f, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x1e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x5f, 0x70, 0x62, 0x32, 0x2f, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x3a, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x5f, 0x6c, 0x69, 0x73, 0x74, 0x5f, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x5f, 0x70, 0x62, 0x32, 0x2f, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x5f, 0x6c, 0x69, 0x73, 0x74, 0x5f, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0xac, 0x01, 0x0a, 0x16, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x4c, 0x69, 0x73, 0x74, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x17, 0x0a, 0x07, 0x68, 0x65, 0x61, 0x64, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, 0x68, 0x65, 0x61, 0x64, 0x49, 0x64, 0x12, 0x1b, 0x0a, 0x09, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x5f, 0x69, 0x64, 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x09, 0x52, 0x08, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x49, 0x64, 0x73, 0x12, 0x2d, 0x0a, 0x06, 0x70, 0x61, 0x67, 0x69, 0x6e, 0x67, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x15, 0x2e, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x50, 0x61, 0x67, 0x69, 0x6e, 0x67, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x73, 0x52, 0x06, 0x70, 0x61, 0x67, 0x69, 0x6e, 0x67, 0x12, 0x2d, 0x0a, 0x07, 0x73, 0x6f, 0x72, 0x74, 0x69, 0x6e, 0x67, 0x18, 0x04, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x13, 0x2e, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x53, 0x6f, 0x72, 0x74, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x73, 0x52, 0x07, 0x73, 0x6f, 0x72, 0x74, 0x69, 0x6e, 0x67, 0x22, 0xd6, 0x02, 0x0a, 0x17, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x4c, 0x69, 0x73, 0x74, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x37, 0x0a, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x1f, 0x2e, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x4c, 0x69, 0x73, 0x74, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x2e, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x52, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, 0x1e, 0x0a, 0x06, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x06, 0x2e, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x52, 0x06, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x73, 0x12, 0x17, 0x0a, 0x07, 0x68, 0x65, 0x61, 0x64, 0x5f, 0x69, 0x64, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, 0x68, 0x65, 0x61, 0x64, 0x49, 0x64, 0x12, 0x2d, 0x0a, 0x06, 0x70, 0x61, 0x67, 0x69, 0x6e, 0x67, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x15, 0x2e, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x50, 0x61, 0x67, 0x69, 0x6e, 0x67, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x52, 0x06, 0x70, 0x61, 0x67, 0x69, 0x6e, 0x67, 0x22, 0x99, 0x01, 0x0a, 0x06, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, 0x10, 0x0a, 0x0c, 0x53, 0x54, 0x41, 0x54, 0x55, 0x53, 0x5f, 0x55, 0x4e, 0x53, 0x45, 0x54, 0x10, 0x00, 0x12, 0x06, 0x0a, 0x02, 0x4f, 0x4b, 0x10, 0x01, 0x12, 0x12, 0x0a, 0x0e, 0x49, 0x4e, 0x54, 0x45, 0x52, 0x4e, 0x41, 0x4c, 0x5f, 0x45, 0x52, 0x52, 0x4f, 0x52, 0x10, 0x02, 0x12, 0x0d, 0x0a, 0x09, 0x4e, 0x4f, 0x54, 0x5f, 0x52, 0x45, 0x41, 0x44, 0x59, 0x10, 0x03, 0x12, 0x0b, 0x0a, 0x07, 0x4e, 0x4f, 0x5f, 0x52, 0x4f, 0x4f, 0x54, 0x10, 0x04, 0x12, 0x0f, 0x0a, 0x0b, 0x4e, 0x4f, 0x5f, 0x52, 0x45, 0x53, 0x4f, 0x55, 0x52, 0x43, 0x45, 0x10, 0x05, 0x12, 0x12, 0x0a, 0x0e, 0x49, 0x4e, 0x56, 0x41, 0x4c, 0x49, 0x44, 0x5f, 0x50, 0x41, 0x47, 0x49, 0x4e, 0x47, 0x10, 0x06, 0x12, 0x10, 0x0a, 0x0c, 0x49, 0x4e, 0x56, 0x41, 0x4c, 0x49, 0x44, 0x5f, 0x53, 0x4f, 0x52, 0x54, 0x10, 0x07, 0x12, 0x0e, 0x0a, 0x0a, 0x49, 0x4e, 0x56, 0x41, 0x4c, 0x49, 0x44, 0x5f, 0x49, 0x44, 0x10, 0x08, 0x22, 0x36, 0x0a, 0x19, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x47, 0x65, 0x74, 0x42, 0x79, 0x49, 0x64, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x19, 0x0a, 0x08, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x49, 0x64, 0x22, 0x39, 0x0a, 0x1a, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x47, 0x65, 0x74, 0x42, 0x79, 0x4e, 0x75, 0x6d, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x1b, 0x0a, 0x09, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x5f, 0x6e, 0x75, 0x6d, 0x18, 0x01, 0x20, 0x01, 0x28, 0x04, 0x52, 0x08, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x4e, 0x75, 0x6d, 0x22, 0x4d, 0x0a, 0x24, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x47, 0x65, 0x74, 0x42, 0x79, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x49, 0x64, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x25, 0x0a, 0x0e, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0d, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x49, 0x64, 0x22, 0x3b, 0x0a, 0x1e, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x47, 0x65, 0x74, 0x42, 0x79, 0x42, 0x61, 0x74, 0x63, 0x68, 0x49, 0x64, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x19, 0x0a, 0x08, 0x62, 0x61, 0x74, 0x63, 0x68, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x62, 0x61, 0x74, 0x63, 0x68, 0x49, 0x64, 0x22, 0xc7, 0x01, 0x0a, 0x16, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x47, 0x65, 0x74, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x36, 0x0a, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x1e, 0x2e, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x47, 0x65, 0x74, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x2e, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x52, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, 0x1c, 0x0a, 0x05, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x06, 0x2e, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x52, 0x05, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x22, 0x57, 0x0a, 0x06, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, 0x10, 0x0a, 0x0c, 0x53, 0x54, 0x41, 0x54, 0x55, 0x53, 0x5f, 0x55, 0x4e, 0x53, 0x45, 0x54, 0x10, 0x00, 0x12, 0x06, 0x0a, 0x02, 0x4f, 0x4b, 0x10, 0x01, 0x12, 0x12, 0x0a, 0x0e, 0x49, 0x4e, 0x54, 0x45, 0x52, 0x4e, 0x41, 0x4c, 0x5f, 0x45, 0x52, 0x52, 0x4f, 0x52, 0x10, 0x02, 0x12, 0x0f, 0x0a, 0x0b, 0x4e, 0x4f, 0x5f, 0x52, 0x45, 0x53, 0x4f, 0x55, 0x52, 0x43, 0x45, 0x10, 0x05, 0x12, 0x0e, 0x0a, 0x0a, 0x49, 0x4e, 0x56, 0x41, 0x4c, 0x49, 0x44, 0x5f, 0x49, 0x44, 0x10, 0x08, 0x42, 0x2b, 0x0a, 0x15, 0x73, 0x61, 0x77, 0x74, 0x6f, 0x6f, 0x74, 0x68, 0x2e, 0x73, 0x64, 0x6b, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x50, 0x01, 0x5a, 0x10, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x5f, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x5f, 0x70, 0x62, 0x32, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( file_protobuf_client_block_pb2_client_block_proto_rawDescOnce sync.Once file_protobuf_client_block_pb2_client_block_proto_rawDescData = file_protobuf_client_block_pb2_client_block_proto_rawDesc ) func file_protobuf_client_block_pb2_client_block_proto_rawDescGZIP() []byte { file_protobuf_client_block_pb2_client_block_proto_rawDescOnce.Do(func() { file_protobuf_client_block_pb2_client_block_proto_rawDescData = protoimpl.X.CompressGZIP(file_protobuf_client_block_pb2_client_block_proto_rawDescData) }) return file_protobuf_client_block_pb2_client_block_proto_rawDescData } var file_protobuf_client_block_pb2_client_block_proto_enumTypes = make([]protoimpl.EnumInfo, 2) var file_protobuf_client_block_pb2_client_block_proto_msgTypes = make([]protoimpl.MessageInfo, 7) var file_protobuf_client_block_pb2_client_block_proto_goTypes = []interface{}{ (ClientBlockListResponse_Status)(0), // 0: ClientBlockListResponse.Status (ClientBlockGetResponse_Status)(0), // 1: ClientBlockGetResponse.Status (*ClientBlockListRequest)(nil), // 2: ClientBlockListRequest (*ClientBlockListResponse)(nil), // 3: ClientBlockListResponse (*ClientBlockGetByIdRequest)(nil), // 4: ClientBlockGetByIdRequest (*ClientBlockGetByNumRequest)(nil), // 5: ClientBlockGetByNumRequest (*ClientBlockGetByTransactionIdRequest)(nil), // 6: ClientBlockGetByTransactionIdRequest (*ClientBlockGetByBatchIdRequest)(nil), // 7: ClientBlockGetByBatchIdRequest (*ClientBlockGetResponse)(nil), // 8: ClientBlockGetResponse (*client_list_control_pb2.ClientPagingControls)(nil), // 9: ClientPagingControls (*client_list_control_pb2.ClientSortControls)(nil), // 10: ClientSortControls (*block_pb2.Block)(nil), // 11: Block (*client_list_control_pb2.ClientPagingResponse)(nil), // 12: ClientPagingResponse } var file_protobuf_client_block_pb2_client_block_proto_depIdxs = []int32{ 9, // 0: ClientBlockListRequest.paging:type_name -> ClientPagingControls 10, // 1: ClientBlockListRequest.sorting:type_name -> ClientSortControls 0, // 2: ClientBlockListResponse.status:type_name -> ClientBlockListResponse.Status 11, // 3: ClientBlockListResponse.blocks:type_name -> Block 12, // 4: ClientBlockListResponse.paging:type_name -> ClientPagingResponse 1, // 5: ClientBlockGetResponse.status:type_name -> ClientBlockGetResponse.Status 11, // 6: ClientBlockGetResponse.block:type_name -> Block 7, // [7:7] is the sub-list for method output_type 7, // [7:7] is the sub-list for method input_type 7, // [7:7] is the sub-list for extension type_name 7, // [7:7] is the sub-list for extension extendee 0, // [0:7] is the sub-list for field type_name } func init() { file_protobuf_client_block_pb2_client_block_proto_init() } func file_protobuf_client_block_pb2_client_block_proto_init() { if File_protobuf_client_block_pb2_client_block_proto != nil { return } if !protoimpl.UnsafeEnabled { file_protobuf_client_block_pb2_client_block_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ClientBlockListRequest); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_client_block_pb2_client_block_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ClientBlockListResponse); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_client_block_pb2_client_block_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ClientBlockGetByIdRequest); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_client_block_pb2_client_block_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ClientBlockGetByNumRequest); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_client_block_pb2_client_block_proto_msgTypes[4].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ClientBlockGetByTransactionIdRequest); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_client_block_pb2_client_block_proto_msgTypes[5].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ClientBlockGetByBatchIdRequest); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_client_block_pb2_client_block_proto_msgTypes[6].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ClientBlockGetResponse); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: file_protobuf_client_block_pb2_client_block_proto_rawDesc, NumEnums: 2, NumMessages: 7, NumExtensions: 0, NumServices: 0, }, GoTypes: file_protobuf_client_block_pb2_client_block_proto_goTypes, DependencyIndexes: file_protobuf_client_block_pb2_client_block_proto_depIdxs, EnumInfos: file_protobuf_client_block_pb2_client_block_proto_enumTypes, MessageInfos: file_protobuf_client_block_pb2_client_block_proto_msgTypes, }.Build() File_protobuf_client_block_pb2_client_block_proto = out.File file_protobuf_client_block_pb2_client_block_proto_rawDesc = nil file_protobuf_client_block_pb2_client_block_proto_goTypes = nil file_protobuf_client_block_pb2_client_block_proto_depIdxs = nil } <|start_filename|>protobuf/client_state_pb2/client_state.pb.go<|end_filename|> // Copyright 2017 Intel Corporation // // 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. // ----------------------------------------------------------------------------- // Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.25.0-devel // protoc v3.14.0 // source: protobuf/client_state_pb2/client_state.proto package client_state_pb2 import ( protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" client_list_control_pb2 "github.com/hyperledger/sawtooth-sdk-go/protobuf/client_list_control_pb2" reflect "reflect" sync "sync" ) const ( // Verify that this generated code is sufficiently up-to-date. _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) // Verify that runtime/protoimpl is sufficiently up-to-date. _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) type ClientStateListResponse_Status int32 const ( ClientStateListResponse_STATUS_UNSET ClientStateListResponse_Status = 0 ClientStateListResponse_OK ClientStateListResponse_Status = 1 ClientStateListResponse_INTERNAL_ERROR ClientStateListResponse_Status = 2 ClientStateListResponse_NOT_READY ClientStateListResponse_Status = 3 ClientStateListResponse_NO_ROOT ClientStateListResponse_Status = 4 ClientStateListResponse_NO_RESOURCE ClientStateListResponse_Status = 5 ClientStateListResponse_INVALID_PAGING ClientStateListResponse_Status = 6 ClientStateListResponse_INVALID_SORT ClientStateListResponse_Status = 7 ClientStateListResponse_INVALID_ADDRESS ClientStateListResponse_Status = 8 ClientStateListResponse_INVALID_ROOT ClientStateListResponse_Status = 9 ) // Enum value maps for ClientStateListResponse_Status. var ( ClientStateListResponse_Status_name = map[int32]string{ 0: "STATUS_UNSET", 1: "OK", 2: "INTERNAL_ERROR", 3: "NOT_READY", 4: "NO_ROOT", 5: "NO_RESOURCE", 6: "INVALID_PAGING", 7: "INVALID_SORT", 8: "INVALID_ADDRESS", 9: "INVALID_ROOT", } ClientStateListResponse_Status_value = map[string]int32{ "STATUS_UNSET": 0, "OK": 1, "INTERNAL_ERROR": 2, "NOT_READY": 3, "NO_ROOT": 4, "NO_RESOURCE": 5, "INVALID_PAGING": 6, "INVALID_SORT": 7, "INVALID_ADDRESS": 8, "INVALID_ROOT": 9, } ) func (x ClientStateListResponse_Status) Enum() *ClientStateListResponse_Status { p := new(ClientStateListResponse_Status) *p = x return p } func (x ClientStateListResponse_Status) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (ClientStateListResponse_Status) Descriptor() protoreflect.EnumDescriptor { return file_protobuf_client_state_pb2_client_state_proto_enumTypes[0].Descriptor() } func (ClientStateListResponse_Status) Type() protoreflect.EnumType { return &file_protobuf_client_state_pb2_client_state_proto_enumTypes[0] } func (x ClientStateListResponse_Status) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use ClientStateListResponse_Status.Descriptor instead. func (ClientStateListResponse_Status) EnumDescriptor() ([]byte, []int) { return file_protobuf_client_state_pb2_client_state_proto_rawDescGZIP(), []int{1, 0} } type ClientStateGetResponse_Status int32 const ( ClientStateGetResponse_STATUS_UNSET ClientStateGetResponse_Status = 0 ClientStateGetResponse_OK ClientStateGetResponse_Status = 1 ClientStateGetResponse_INTERNAL_ERROR ClientStateGetResponse_Status = 2 ClientStateGetResponse_NOT_READY ClientStateGetResponse_Status = 3 ClientStateGetResponse_NO_ROOT ClientStateGetResponse_Status = 4 ClientStateGetResponse_NO_RESOURCE ClientStateGetResponse_Status = 5 ClientStateGetResponse_INVALID_ADDRESS ClientStateGetResponse_Status = 6 ClientStateGetResponse_INVALID_ROOT ClientStateGetResponse_Status = 7 ) // Enum value maps for ClientStateGetResponse_Status. var ( ClientStateGetResponse_Status_name = map[int32]string{ 0: "STATUS_UNSET", 1: "OK", 2: "INTERNAL_ERROR", 3: "NOT_READY", 4: "NO_ROOT", 5: "NO_RESOURCE", 6: "INVALID_ADDRESS", 7: "INVALID_ROOT", } ClientStateGetResponse_Status_value = map[string]int32{ "STATUS_UNSET": 0, "OK": 1, "INTERNAL_ERROR": 2, "NOT_READY": 3, "NO_ROOT": 4, "NO_RESOURCE": 5, "INVALID_ADDRESS": 6, "INVALID_ROOT": 7, } ) func (x ClientStateGetResponse_Status) Enum() *ClientStateGetResponse_Status { p := new(ClientStateGetResponse_Status) *p = x return p } func (x ClientStateGetResponse_Status) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (ClientStateGetResponse_Status) Descriptor() protoreflect.EnumDescriptor { return file_protobuf_client_state_pb2_client_state_proto_enumTypes[1].Descriptor() } func (ClientStateGetResponse_Status) Type() protoreflect.EnumType { return &file_protobuf_client_state_pb2_client_state_proto_enumTypes[1] } func (x ClientStateGetResponse_Status) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use ClientStateGetResponse_Status.Descriptor instead. func (ClientStateGetResponse_Status) EnumDescriptor() ([]byte, []int) { return file_protobuf_client_state_pb2_client_state_proto_rawDescGZIP(), []int{3, 0} } // A request to list every entry in global state. Defaults to the most current // tree, but can fetch older state by specifying a state root. Results can be // further filtered by specifying a subtree with a partial address. type ClientStateListRequest struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields StateRoot string `protobuf:"bytes,1,opt,name=state_root,json=stateRoot,proto3" json:"state_root,omitempty"` Address string `protobuf:"bytes,3,opt,name=address,proto3" json:"address,omitempty"` Paging *client_list_control_pb2.ClientPagingControls `protobuf:"bytes,4,opt,name=paging,proto3" json:"paging,omitempty"` Sorting []*client_list_control_pb2.ClientSortControls `protobuf:"bytes,5,rep,name=sorting,proto3" json:"sorting,omitempty"` } func (x *ClientStateListRequest) Reset() { *x = ClientStateListRequest{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_client_state_pb2_client_state_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ClientStateListRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*ClientStateListRequest) ProtoMessage() {} func (x *ClientStateListRequest) ProtoReflect() protoreflect.Message { mi := &file_protobuf_client_state_pb2_client_state_proto_msgTypes[0] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ClientStateListRequest.ProtoReflect.Descriptor instead. func (*ClientStateListRequest) Descriptor() ([]byte, []int) { return file_protobuf_client_state_pb2_client_state_proto_rawDescGZIP(), []int{0} } func (x *ClientStateListRequest) GetStateRoot() string { if x != nil { return x.StateRoot } return "" } func (x *ClientStateListRequest) GetAddress() string { if x != nil { return x.Address } return "" } func (x *ClientStateListRequest) GetPaging() *client_list_control_pb2.ClientPagingControls { if x != nil { return x.Paging } return nil } func (x *ClientStateListRequest) GetSorting() []*client_list_control_pb2.ClientSortControls { if x != nil { return x.Sorting } return nil } type ClientStateListResponse struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Status ClientStateListResponse_Status `protobuf:"varint,1,opt,name=status,proto3,enum=ClientStateListResponse_Status" json:"status,omitempty"` Entries []*ClientStateListResponse_Entry `protobuf:"bytes,2,rep,name=entries,proto3" json:"entries,omitempty"` StateRoot string `protobuf:"bytes,3,opt,name=state_root,json=stateRoot,proto3" json:"state_root,omitempty"` Paging *client_list_control_pb2.ClientPagingResponse `protobuf:"bytes,4,opt,name=paging,proto3" json:"paging,omitempty"` } func (x *ClientStateListResponse) Reset() { *x = ClientStateListResponse{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_client_state_pb2_client_state_proto_msgTypes[1] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ClientStateListResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*ClientStateListResponse) ProtoMessage() {} func (x *ClientStateListResponse) ProtoReflect() protoreflect.Message { mi := &file_protobuf_client_state_pb2_client_state_proto_msgTypes[1] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ClientStateListResponse.ProtoReflect.Descriptor instead. func (*ClientStateListResponse) Descriptor() ([]byte, []int) { return file_protobuf_client_state_pb2_client_state_proto_rawDescGZIP(), []int{1} } func (x *ClientStateListResponse) GetStatus() ClientStateListResponse_Status { if x != nil { return x.Status } return ClientStateListResponse_STATUS_UNSET } func (x *ClientStateListResponse) GetEntries() []*ClientStateListResponse_Entry { if x != nil { return x.Entries } return nil } func (x *ClientStateListResponse) GetStateRoot() string { if x != nil { return x.StateRoot } return "" } func (x *ClientStateListResponse) GetPaging() *client_list_control_pb2.ClientPagingResponse { if x != nil { return x.Paging } return nil } // A request from a client for a particular entry in global state. // Like State List, it defaults to the newest state, but a state root // can be used to specify older data. Unlike State List the request must be // provided with a full address that corresponds to a single entry. type ClientStateGetRequest struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields StateRoot string `protobuf:"bytes,1,opt,name=state_root,json=stateRoot,proto3" json:"state_root,omitempty"` Address string `protobuf:"bytes,3,opt,name=address,proto3" json:"address,omitempty"` } func (x *ClientStateGetRequest) Reset() { *x = ClientStateGetRequest{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_client_state_pb2_client_state_proto_msgTypes[2] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ClientStateGetRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*ClientStateGetRequest) ProtoMessage() {} func (x *ClientStateGetRequest) ProtoReflect() protoreflect.Message { mi := &file_protobuf_client_state_pb2_client_state_proto_msgTypes[2] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ClientStateGetRequest.ProtoReflect.Descriptor instead. func (*ClientStateGetRequest) Descriptor() ([]byte, []int) { return file_protobuf_client_state_pb2_client_state_proto_rawDescGZIP(), []int{2} } func (x *ClientStateGetRequest) GetStateRoot() string { if x != nil { return x.StateRoot } return "" } func (x *ClientStateGetRequest) GetAddress() string { if x != nil { return x.Address } return "" } // The response to a State Get Request from the client. Sends back just // the data stored at the entry, not the address. Also sends back the // head block id used to facilitate further requests. // // Statuses: // * OK - everything worked as expected // * INTERNAL_ERROR - general error, such as protobuf failing to deserialize // * NOT_READY - the validator does not yet have a genesis block // * NO_ROOT - the state_root specified was not found // * NO_RESOURCE - the address specified doesn't exist // * INVALID_ADDRESS - address isn't a valid, i.e. it's a subtree (truncated) type ClientStateGetResponse struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Status ClientStateGetResponse_Status `protobuf:"varint,1,opt,name=status,proto3,enum=ClientStateGetResponse_Status" json:"status,omitempty"` Value []byte `protobuf:"bytes,2,opt,name=value,proto3" json:"value,omitempty"` StateRoot string `protobuf:"bytes,3,opt,name=state_root,json=stateRoot,proto3" json:"state_root,omitempty"` } func (x *ClientStateGetResponse) Reset() { *x = ClientStateGetResponse{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_client_state_pb2_client_state_proto_msgTypes[3] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ClientStateGetResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*ClientStateGetResponse) ProtoMessage() {} func (x *ClientStateGetResponse) ProtoReflect() protoreflect.Message { mi := &file_protobuf_client_state_pb2_client_state_proto_msgTypes[3] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ClientStateGetResponse.ProtoReflect.Descriptor instead. func (*ClientStateGetResponse) Descriptor() ([]byte, []int) { return file_protobuf_client_state_pb2_client_state_proto_rawDescGZIP(), []int{3} } func (x *ClientStateGetResponse) GetStatus() ClientStateGetResponse_Status { if x != nil { return x.Status } return ClientStateGetResponse_STATUS_UNSET } func (x *ClientStateGetResponse) GetValue() []byte { if x != nil { return x.Value } return nil } func (x *ClientStateGetResponse) GetStateRoot() string { if x != nil { return x.StateRoot } return "" } // An entry in the State type ClientStateListResponse_Entry struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Address string `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty"` Data []byte `protobuf:"bytes,2,opt,name=data,proto3" json:"data,omitempty"` } func (x *ClientStateListResponse_Entry) Reset() { *x = ClientStateListResponse_Entry{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_client_state_pb2_client_state_proto_msgTypes[4] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ClientStateListResponse_Entry) String() string { return protoimpl.X.MessageStringOf(x) } func (*ClientStateListResponse_Entry) ProtoMessage() {} func (x *ClientStateListResponse_Entry) ProtoReflect() protoreflect.Message { mi := &file_protobuf_client_state_pb2_client_state_proto_msgTypes[4] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ClientStateListResponse_Entry.ProtoReflect.Descriptor instead. func (*ClientStateListResponse_Entry) Descriptor() ([]byte, []int) { return file_protobuf_client_state_pb2_client_state_proto_rawDescGZIP(), []int{1, 0} } func (x *ClientStateListResponse_Entry) GetAddress() string { if x != nil { return x.Address } return "" } func (x *ClientStateListResponse_Entry) GetData() []byte { if x != nil { return x.Data } return nil } var File_protobuf_client_state_pb2_client_state_proto protoreflect.FileDescriptor var file_protobuf_client_state_pb2_client_state_proto_rawDesc = []byte{ 0x0a, 0x2c, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x5f, 0x73, 0x74, 0x61, 0x74, 0x65, 0x5f, 0x70, 0x62, 0x32, 0x2f, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x5f, 0x73, 0x74, 0x61, 0x74, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x3a, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x5f, 0x6c, 0x69, 0x73, 0x74, 0x5f, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x5f, 0x70, 0x62, 0x32, 0x2f, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x5f, 0x6c, 0x69, 0x73, 0x74, 0x5f, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0xaf, 0x01, 0x0a, 0x16, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x53, 0x74, 0x61, 0x74, 0x65, 0x4c, 0x69, 0x73, 0x74, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x1d, 0x0a, 0x0a, 0x73, 0x74, 0x61, 0x74, 0x65, 0x5f, 0x72, 0x6f, 0x6f, 0x74, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, 0x73, 0x74, 0x61, 0x74, 0x65, 0x52, 0x6f, 0x6f, 0x74, 0x12, 0x18, 0x0a, 0x07, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x12, 0x2d, 0x0a, 0x06, 0x70, 0x61, 0x67, 0x69, 0x6e, 0x67, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x15, 0x2e, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x50, 0x61, 0x67, 0x69, 0x6e, 0x67, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x73, 0x52, 0x06, 0x70, 0x61, 0x67, 0x69, 0x6e, 0x67, 0x12, 0x2d, 0x0a, 0x07, 0x73, 0x6f, 0x72, 0x74, 0x69, 0x6e, 0x67, 0x18, 0x05, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x13, 0x2e, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x53, 0x6f, 0x72, 0x74, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x73, 0x52, 0x07, 0x73, 0x6f, 0x72, 0x74, 0x69, 0x6e, 0x67, 0x22, 0xc4, 0x03, 0x0a, 0x17, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x53, 0x74, 0x61, 0x74, 0x65, 0x4c, 0x69, 0x73, 0x74, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x37, 0x0a, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x1f, 0x2e, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x53, 0x74, 0x61, 0x74, 0x65, 0x4c, 0x69, 0x73, 0x74, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x2e, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x52, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, 0x38, 0x0a, 0x07, 0x65, 0x6e, 0x74, 0x72, 0x69, 0x65, 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x1e, 0x2e, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x53, 0x74, 0x61, 0x74, 0x65, 0x4c, 0x69, 0x73, 0x74, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x2e, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x52, 0x07, 0x65, 0x6e, 0x74, 0x72, 0x69, 0x65, 0x73, 0x12, 0x1d, 0x0a, 0x0a, 0x73, 0x74, 0x61, 0x74, 0x65, 0x5f, 0x72, 0x6f, 0x6f, 0x74, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, 0x73, 0x74, 0x61, 0x74, 0x65, 0x52, 0x6f, 0x6f, 0x74, 0x12, 0x2d, 0x0a, 0x06, 0x70, 0x61, 0x67, 0x69, 0x6e, 0x67, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x15, 0x2e, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x50, 0x61, 0x67, 0x69, 0x6e, 0x67, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x52, 0x06, 0x70, 0x61, 0x67, 0x69, 0x6e, 0x67, 0x1a, 0x35, 0x0a, 0x05, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x12, 0x18, 0x0a, 0x07, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x12, 0x12, 0x0a, 0x04, 0x64, 0x61, 0x74, 0x61, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x04, 0x64, 0x61, 0x74, 0x61, 0x22, 0xb0, 0x01, 0x0a, 0x06, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, 0x10, 0x0a, 0x0c, 0x53, 0x54, 0x41, 0x54, 0x55, 0x53, 0x5f, 0x55, 0x4e, 0x53, 0x45, 0x54, 0x10, 0x00, 0x12, 0x06, 0x0a, 0x02, 0x4f, 0x4b, 0x10, 0x01, 0x12, 0x12, 0x0a, 0x0e, 0x49, 0x4e, 0x54, 0x45, 0x52, 0x4e, 0x41, 0x4c, 0x5f, 0x45, 0x52, 0x52, 0x4f, 0x52, 0x10, 0x02, 0x12, 0x0d, 0x0a, 0x09, 0x4e, 0x4f, 0x54, 0x5f, 0x52, 0x45, 0x41, 0x44, 0x59, 0x10, 0x03, 0x12, 0x0b, 0x0a, 0x07, 0x4e, 0x4f, 0x5f, 0x52, 0x4f, 0x4f, 0x54, 0x10, 0x04, 0x12, 0x0f, 0x0a, 0x0b, 0x4e, 0x4f, 0x5f, 0x52, 0x45, 0x53, 0x4f, 0x55, 0x52, 0x43, 0x45, 0x10, 0x05, 0x12, 0x12, 0x0a, 0x0e, 0x49, 0x4e, 0x56, 0x41, 0x4c, 0x49, 0x44, 0x5f, 0x50, 0x41, 0x47, 0x49, 0x4e, 0x47, 0x10, 0x06, 0x12, 0x10, 0x0a, 0x0c, 0x49, 0x4e, 0x56, 0x41, 0x4c, 0x49, 0x44, 0x5f, 0x53, 0x4f, 0x52, 0x54, 0x10, 0x07, 0x12, 0x13, 0x0a, 0x0f, 0x49, 0x4e, 0x56, 0x41, 0x4c, 0x49, 0x44, 0x5f, 0x41, 0x44, 0x44, 0x52, 0x45, 0x53, 0x53, 0x10, 0x08, 0x12, 0x10, 0x0a, 0x0c, 0x49, 0x4e, 0x56, 0x41, 0x4c, 0x49, 0x44, 0x5f, 0x52, 0x4f, 0x4f, 0x54, 0x10, 0x09, 0x22, 0x50, 0x0a, 0x15, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x53, 0x74, 0x61, 0x74, 0x65, 0x47, 0x65, 0x74, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x1d, 0x0a, 0x0a, 0x73, 0x74, 0x61, 0x74, 0x65, 0x5f, 0x72, 0x6f, 0x6f, 0x74, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, 0x73, 0x74, 0x61, 0x74, 0x65, 0x52, 0x6f, 0x6f, 0x74, 0x12, 0x18, 0x0a, 0x07, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x22, 0x92, 0x02, 0x0a, 0x16, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x53, 0x74, 0x61, 0x74, 0x65, 0x47, 0x65, 0x74, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x36, 0x0a, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x1e, 0x2e, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x53, 0x74, 0x61, 0x74, 0x65, 0x47, 0x65, 0x74, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x2e, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x52, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, 0x14, 0x0a, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x12, 0x1d, 0x0a, 0x0a, 0x73, 0x74, 0x61, 0x74, 0x65, 0x5f, 0x72, 0x6f, 0x6f, 0x74, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, 0x73, 0x74, 0x61, 0x74, 0x65, 0x52, 0x6f, 0x6f, 0x74, 0x22, 0x8a, 0x01, 0x0a, 0x06, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, 0x10, 0x0a, 0x0c, 0x53, 0x54, 0x41, 0x54, 0x55, 0x53, 0x5f, 0x55, 0x4e, 0x53, 0x45, 0x54, 0x10, 0x00, 0x12, 0x06, 0x0a, 0x02, 0x4f, 0x4b, 0x10, 0x01, 0x12, 0x12, 0x0a, 0x0e, 0x49, 0x4e, 0x54, 0x45, 0x52, 0x4e, 0x41, 0x4c, 0x5f, 0x45, 0x52, 0x52, 0x4f, 0x52, 0x10, 0x02, 0x12, 0x0d, 0x0a, 0x09, 0x4e, 0x4f, 0x54, 0x5f, 0x52, 0x45, 0x41, 0x44, 0x59, 0x10, 0x03, 0x12, 0x0b, 0x0a, 0x07, 0x4e, 0x4f, 0x5f, 0x52, 0x4f, 0x4f, 0x54, 0x10, 0x04, 0x12, 0x0f, 0x0a, 0x0b, 0x4e, 0x4f, 0x5f, 0x52, 0x45, 0x53, 0x4f, 0x55, 0x52, 0x43, 0x45, 0x10, 0x05, 0x12, 0x13, 0x0a, 0x0f, 0x49, 0x4e, 0x56, 0x41, 0x4c, 0x49, 0x44, 0x5f, 0x41, 0x44, 0x44, 0x52, 0x45, 0x53, 0x53, 0x10, 0x06, 0x12, 0x10, 0x0a, 0x0c, 0x49, 0x4e, 0x56, 0x41, 0x4c, 0x49, 0x44, 0x5f, 0x52, 0x4f, 0x4f, 0x54, 0x10, 0x07, 0x42, 0x2b, 0x0a, 0x15, 0x73, 0x61, 0x77, 0x74, 0x6f, 0x6f, 0x74, 0x68, 0x2e, 0x73, 0x64, 0x6b, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x50, 0x01, 0x5a, 0x10, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x5f, 0x73, 0x74, 0x61, 0x74, 0x65, 0x5f, 0x70, 0x62, 0x32, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( file_protobuf_client_state_pb2_client_state_proto_rawDescOnce sync.Once file_protobuf_client_state_pb2_client_state_proto_rawDescData = file_protobuf_client_state_pb2_client_state_proto_rawDesc ) func file_protobuf_client_state_pb2_client_state_proto_rawDescGZIP() []byte { file_protobuf_client_state_pb2_client_state_proto_rawDescOnce.Do(func() { file_protobuf_client_state_pb2_client_state_proto_rawDescData = protoimpl.X.CompressGZIP(file_protobuf_client_state_pb2_client_state_proto_rawDescData) }) return file_protobuf_client_state_pb2_client_state_proto_rawDescData } var file_protobuf_client_state_pb2_client_state_proto_enumTypes = make([]protoimpl.EnumInfo, 2) var file_protobuf_client_state_pb2_client_state_proto_msgTypes = make([]protoimpl.MessageInfo, 5) var file_protobuf_client_state_pb2_client_state_proto_goTypes = []interface{}{ (ClientStateListResponse_Status)(0), // 0: ClientStateListResponse.Status (ClientStateGetResponse_Status)(0), // 1: ClientStateGetResponse.Status (*ClientStateListRequest)(nil), // 2: ClientStateListRequest (*ClientStateListResponse)(nil), // 3: ClientStateListResponse (*ClientStateGetRequest)(nil), // 4: ClientStateGetRequest (*ClientStateGetResponse)(nil), // 5: ClientStateGetResponse (*ClientStateListResponse_Entry)(nil), // 6: ClientStateListResponse.Entry (*client_list_control_pb2.ClientPagingControls)(nil), // 7: ClientPagingControls (*client_list_control_pb2.ClientSortControls)(nil), // 8: ClientSortControls (*client_list_control_pb2.ClientPagingResponse)(nil), // 9: ClientPagingResponse } var file_protobuf_client_state_pb2_client_state_proto_depIdxs = []int32{ 7, // 0: ClientStateListRequest.paging:type_name -> ClientPagingControls 8, // 1: ClientStateListRequest.sorting:type_name -> ClientSortControls 0, // 2: ClientStateListResponse.status:type_name -> ClientStateListResponse.Status 6, // 3: ClientStateListResponse.entries:type_name -> ClientStateListResponse.Entry 9, // 4: ClientStateListResponse.paging:type_name -> ClientPagingResponse 1, // 5: ClientStateGetResponse.status:type_name -> ClientStateGetResponse.Status 6, // [6:6] is the sub-list for method output_type 6, // [6:6] is the sub-list for method input_type 6, // [6:6] is the sub-list for extension type_name 6, // [6:6] is the sub-list for extension extendee 0, // [0:6] is the sub-list for field type_name } func init() { file_protobuf_client_state_pb2_client_state_proto_init() } func file_protobuf_client_state_pb2_client_state_proto_init() { if File_protobuf_client_state_pb2_client_state_proto != nil { return } if !protoimpl.UnsafeEnabled { file_protobuf_client_state_pb2_client_state_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ClientStateListRequest); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_client_state_pb2_client_state_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ClientStateListResponse); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_client_state_pb2_client_state_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ClientStateGetRequest); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_client_state_pb2_client_state_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ClientStateGetResponse); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_client_state_pb2_client_state_proto_msgTypes[4].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ClientStateListResponse_Entry); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: file_protobuf_client_state_pb2_client_state_proto_rawDesc, NumEnums: 2, NumMessages: 5, NumExtensions: 0, NumServices: 0, }, GoTypes: file_protobuf_client_state_pb2_client_state_proto_goTypes, DependencyIndexes: file_protobuf_client_state_pb2_client_state_proto_depIdxs, EnumInfos: file_protobuf_client_state_pb2_client_state_proto_enumTypes, MessageInfos: file_protobuf_client_state_pb2_client_state_proto_msgTypes, }.Build() File_protobuf_client_state_pb2_client_state_proto = out.File file_protobuf_client_state_pb2_client_state_proto_rawDesc = nil file_protobuf_client_state_pb2_client_state_proto_goTypes = nil file_protobuf_client_state_pb2_client_state_proto_depIdxs = nil } <|start_filename|>protobuf/client_event_pb2/client_event.pb.go<|end_filename|> // Copyright 2017 Intel Corporation // // 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. // ----------------------------------------------------------------------------- // Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.25.0-devel // protoc v3.14.0 // source: protobuf/client_event_pb2/client_event.proto package client_event_pb2 import ( protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" events_pb2 "github.com/hyperledger/sawtooth-sdk-go/protobuf/events_pb2" reflect "reflect" sync "sync" ) const ( // Verify that this generated code is sufficiently up-to-date. _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) // Verify that runtime/protoimpl is sufficiently up-to-date. _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) type ClientEventsSubscribeResponse_Status int32 const ( ClientEventsSubscribeResponse_STATUS_UNSET ClientEventsSubscribeResponse_Status = 0 ClientEventsSubscribeResponse_OK ClientEventsSubscribeResponse_Status = 1 ClientEventsSubscribeResponse_INVALID_FILTER ClientEventsSubscribeResponse_Status = 2 ClientEventsSubscribeResponse_UNKNOWN_BLOCK ClientEventsSubscribeResponse_Status = 3 ) // Enum value maps for ClientEventsSubscribeResponse_Status. var ( ClientEventsSubscribeResponse_Status_name = map[int32]string{ 0: "STATUS_UNSET", 1: "OK", 2: "INVALID_FILTER", 3: "UNKNOWN_BLOCK", } ClientEventsSubscribeResponse_Status_value = map[string]int32{ "STATUS_UNSET": 0, "OK": 1, "INVALID_FILTER": 2, "UNKNOWN_BLOCK": 3, } ) func (x ClientEventsSubscribeResponse_Status) Enum() *ClientEventsSubscribeResponse_Status { p := new(ClientEventsSubscribeResponse_Status) *p = x return p } func (x ClientEventsSubscribeResponse_Status) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (ClientEventsSubscribeResponse_Status) Descriptor() protoreflect.EnumDescriptor { return file_protobuf_client_event_pb2_client_event_proto_enumTypes[0].Descriptor() } func (ClientEventsSubscribeResponse_Status) Type() protoreflect.EnumType { return &file_protobuf_client_event_pb2_client_event_proto_enumTypes[0] } func (x ClientEventsSubscribeResponse_Status) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use ClientEventsSubscribeResponse_Status.Descriptor instead. func (ClientEventsSubscribeResponse_Status) EnumDescriptor() ([]byte, []int) { return file_protobuf_client_event_pb2_client_event_proto_rawDescGZIP(), []int{1, 0} } type ClientEventsUnsubscribeResponse_Status int32 const ( ClientEventsUnsubscribeResponse_STATUS_UNSET ClientEventsUnsubscribeResponse_Status = 0 ClientEventsUnsubscribeResponse_OK ClientEventsUnsubscribeResponse_Status = 1 ClientEventsUnsubscribeResponse_INTERNAL_ERROR ClientEventsUnsubscribeResponse_Status = 2 ) // Enum value maps for ClientEventsUnsubscribeResponse_Status. var ( ClientEventsUnsubscribeResponse_Status_name = map[int32]string{ 0: "STATUS_UNSET", 1: "OK", 2: "INTERNAL_ERROR", } ClientEventsUnsubscribeResponse_Status_value = map[string]int32{ "STATUS_UNSET": 0, "OK": 1, "INTERNAL_ERROR": 2, } ) func (x ClientEventsUnsubscribeResponse_Status) Enum() *ClientEventsUnsubscribeResponse_Status { p := new(ClientEventsUnsubscribeResponse_Status) *p = x return p } func (x ClientEventsUnsubscribeResponse_Status) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (ClientEventsUnsubscribeResponse_Status) Descriptor() protoreflect.EnumDescriptor { return file_protobuf_client_event_pb2_client_event_proto_enumTypes[1].Descriptor() } func (ClientEventsUnsubscribeResponse_Status) Type() protoreflect.EnumType { return &file_protobuf_client_event_pb2_client_event_proto_enumTypes[1] } func (x ClientEventsUnsubscribeResponse_Status) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use ClientEventsUnsubscribeResponse_Status.Descriptor instead. func (ClientEventsUnsubscribeResponse_Status) EnumDescriptor() ([]byte, []int) { return file_protobuf_client_event_pb2_client_event_proto_rawDescGZIP(), []int{3, 0} } type ClientEventsGetResponse_Status int32 const ( ClientEventsGetResponse_STATUS_UNSET ClientEventsGetResponse_Status = 0 ClientEventsGetResponse_OK ClientEventsGetResponse_Status = 1 ClientEventsGetResponse_INTERNAL_ERROR ClientEventsGetResponse_Status = 2 ClientEventsGetResponse_INVALID_FILTER ClientEventsGetResponse_Status = 3 ClientEventsGetResponse_UNKNOWN_BLOCK ClientEventsGetResponse_Status = 4 ) // Enum value maps for ClientEventsGetResponse_Status. var ( ClientEventsGetResponse_Status_name = map[int32]string{ 0: "STATUS_UNSET", 1: "OK", 2: "INTERNAL_ERROR", 3: "INVALID_FILTER", 4: "UNKNOWN_BLOCK", } ClientEventsGetResponse_Status_value = map[string]int32{ "STATUS_UNSET": 0, "OK": 1, "INTERNAL_ERROR": 2, "INVALID_FILTER": 3, "UNKNOWN_BLOCK": 4, } ) func (x ClientEventsGetResponse_Status) Enum() *ClientEventsGetResponse_Status { p := new(ClientEventsGetResponse_Status) *p = x return p } func (x ClientEventsGetResponse_Status) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (ClientEventsGetResponse_Status) Descriptor() protoreflect.EnumDescriptor { return file_protobuf_client_event_pb2_client_event_proto_enumTypes[2].Descriptor() } func (ClientEventsGetResponse_Status) Type() protoreflect.EnumType { return &file_protobuf_client_event_pb2_client_event_proto_enumTypes[2] } func (x ClientEventsGetResponse_Status) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use ClientEventsGetResponse_Status.Descriptor instead. func (ClientEventsGetResponse_Status) EnumDescriptor() ([]byte, []int) { return file_protobuf_client_event_pb2_client_event_proto_rawDescGZIP(), []int{5, 0} } type ClientEventsSubscribeRequest struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Subscriptions []*events_pb2.EventSubscription `protobuf:"bytes,1,rep,name=subscriptions,proto3" json:"subscriptions,omitempty"` // The block id (or ids, if trying to walk back a fork) the subscriber last // received events on. It can be set to empty if it has not yet received the // genesis block. LastKnownBlockIds []string `protobuf:"bytes,2,rep,name=last_known_block_ids,json=lastKnownBlockIds,proto3" json:"last_known_block_ids,omitempty"` } func (x *ClientEventsSubscribeRequest) Reset() { *x = ClientEventsSubscribeRequest{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_client_event_pb2_client_event_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ClientEventsSubscribeRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*ClientEventsSubscribeRequest) ProtoMessage() {} func (x *ClientEventsSubscribeRequest) ProtoReflect() protoreflect.Message { mi := &file_protobuf_client_event_pb2_client_event_proto_msgTypes[0] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ClientEventsSubscribeRequest.ProtoReflect.Descriptor instead. func (*ClientEventsSubscribeRequest) Descriptor() ([]byte, []int) { return file_protobuf_client_event_pb2_client_event_proto_rawDescGZIP(), []int{0} } func (x *ClientEventsSubscribeRequest) GetSubscriptions() []*events_pb2.EventSubscription { if x != nil { return x.Subscriptions } return nil } func (x *ClientEventsSubscribeRequest) GetLastKnownBlockIds() []string { if x != nil { return x.LastKnownBlockIds } return nil } type ClientEventsSubscribeResponse struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Status ClientEventsSubscribeResponse_Status `protobuf:"varint,1,opt,name=status,proto3,enum=ClientEventsSubscribeResponse_Status" json:"status,omitempty"` // Additional information about the response status ResponseMessage string `protobuf:"bytes,2,opt,name=response_message,json=responseMessage,proto3" json:"response_message,omitempty"` } func (x *ClientEventsSubscribeResponse) Reset() { *x = ClientEventsSubscribeResponse{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_client_event_pb2_client_event_proto_msgTypes[1] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ClientEventsSubscribeResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*ClientEventsSubscribeResponse) ProtoMessage() {} func (x *ClientEventsSubscribeResponse) ProtoReflect() protoreflect.Message { mi := &file_protobuf_client_event_pb2_client_event_proto_msgTypes[1] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ClientEventsSubscribeResponse.ProtoReflect.Descriptor instead. func (*ClientEventsSubscribeResponse) Descriptor() ([]byte, []int) { return file_protobuf_client_event_pb2_client_event_proto_rawDescGZIP(), []int{1} } func (x *ClientEventsSubscribeResponse) GetStatus() ClientEventsSubscribeResponse_Status { if x != nil { return x.Status } return ClientEventsSubscribeResponse_STATUS_UNSET } func (x *ClientEventsSubscribeResponse) GetResponseMessage() string { if x != nil { return x.ResponseMessage } return "" } type ClientEventsUnsubscribeRequest struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields } func (x *ClientEventsUnsubscribeRequest) Reset() { *x = ClientEventsUnsubscribeRequest{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_client_event_pb2_client_event_proto_msgTypes[2] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ClientEventsUnsubscribeRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*ClientEventsUnsubscribeRequest) ProtoMessage() {} func (x *ClientEventsUnsubscribeRequest) ProtoReflect() protoreflect.Message { mi := &file_protobuf_client_event_pb2_client_event_proto_msgTypes[2] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ClientEventsUnsubscribeRequest.ProtoReflect.Descriptor instead. func (*ClientEventsUnsubscribeRequest) Descriptor() ([]byte, []int) { return file_protobuf_client_event_pb2_client_event_proto_rawDescGZIP(), []int{2} } type ClientEventsUnsubscribeResponse struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Status ClientEventsUnsubscribeResponse_Status `protobuf:"varint,1,opt,name=status,proto3,enum=ClientEventsUnsubscribeResponse_Status" json:"status,omitempty"` } func (x *ClientEventsUnsubscribeResponse) Reset() { *x = ClientEventsUnsubscribeResponse{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_client_event_pb2_client_event_proto_msgTypes[3] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ClientEventsUnsubscribeResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*ClientEventsUnsubscribeResponse) ProtoMessage() {} func (x *ClientEventsUnsubscribeResponse) ProtoReflect() protoreflect.Message { mi := &file_protobuf_client_event_pb2_client_event_proto_msgTypes[3] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ClientEventsUnsubscribeResponse.ProtoReflect.Descriptor instead. func (*ClientEventsUnsubscribeResponse) Descriptor() ([]byte, []int) { return file_protobuf_client_event_pb2_client_event_proto_rawDescGZIP(), []int{3} } func (x *ClientEventsUnsubscribeResponse) GetStatus() ClientEventsUnsubscribeResponse_Status { if x != nil { return x.Status } return ClientEventsUnsubscribeResponse_STATUS_UNSET } type ClientEventsGetRequest struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Subscriptions []*events_pb2.EventSubscription `protobuf:"bytes,1,rep,name=subscriptions,proto3" json:"subscriptions,omitempty"` BlockIds []string `protobuf:"bytes,2,rep,name=block_ids,json=blockIds,proto3" json:"block_ids,omitempty"` } func (x *ClientEventsGetRequest) Reset() { *x = ClientEventsGetRequest{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_client_event_pb2_client_event_proto_msgTypes[4] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ClientEventsGetRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*ClientEventsGetRequest) ProtoMessage() {} func (x *ClientEventsGetRequest) ProtoReflect() protoreflect.Message { mi := &file_protobuf_client_event_pb2_client_event_proto_msgTypes[4] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ClientEventsGetRequest.ProtoReflect.Descriptor instead. func (*ClientEventsGetRequest) Descriptor() ([]byte, []int) { return file_protobuf_client_event_pb2_client_event_proto_rawDescGZIP(), []int{4} } func (x *ClientEventsGetRequest) GetSubscriptions() []*events_pb2.EventSubscription { if x != nil { return x.Subscriptions } return nil } func (x *ClientEventsGetRequest) GetBlockIds() []string { if x != nil { return x.BlockIds } return nil } type ClientEventsGetResponse struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Status ClientEventsGetResponse_Status `protobuf:"varint,1,opt,name=status,proto3,enum=ClientEventsGetResponse_Status" json:"status,omitempty"` Events []*events_pb2.Event `protobuf:"bytes,2,rep,name=events,proto3" json:"events,omitempty"` } func (x *ClientEventsGetResponse) Reset() { *x = ClientEventsGetResponse{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_client_event_pb2_client_event_proto_msgTypes[5] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ClientEventsGetResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*ClientEventsGetResponse) ProtoMessage() {} func (x *ClientEventsGetResponse) ProtoReflect() protoreflect.Message { mi := &file_protobuf_client_event_pb2_client_event_proto_msgTypes[5] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ClientEventsGetResponse.ProtoReflect.Descriptor instead. func (*ClientEventsGetResponse) Descriptor() ([]byte, []int) { return file_protobuf_client_event_pb2_client_event_proto_rawDescGZIP(), []int{5} } func (x *ClientEventsGetResponse) GetStatus() ClientEventsGetResponse_Status { if x != nil { return x.Status } return ClientEventsGetResponse_STATUS_UNSET } func (x *ClientEventsGetResponse) GetEvents() []*events_pb2.Event { if x != nil { return x.Events } return nil } var File_protobuf_client_event_pb2_client_event_proto protoreflect.FileDescriptor var file_protobuf_client_event_pb2_client_event_proto_rawDesc = []byte{ 0x0a, 0x2c, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x5f, 0x65, 0x76, 0x65, 0x6e, 0x74, 0x5f, 0x70, 0x62, 0x32, 0x2f, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x5f, 0x65, 0x76, 0x65, 0x6e, 0x74, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x20, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x65, 0x76, 0x65, 0x6e, 0x74, 0x73, 0x5f, 0x70, 0x62, 0x32, 0x2f, 0x65, 0x76, 0x65, 0x6e, 0x74, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0x89, 0x01, 0x0a, 0x1c, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x45, 0x76, 0x65, 0x6e, 0x74, 0x73, 0x53, 0x75, 0x62, 0x73, 0x63, 0x72, 0x69, 0x62, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x38, 0x0a, 0x0d, 0x73, 0x75, 0x62, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x12, 0x2e, 0x45, 0x76, 0x65, 0x6e, 0x74, 0x53, 0x75, 0x62, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x0d, 0x73, 0x75, 0x62, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x12, 0x2f, 0x0a, 0x14, 0x6c, 0x61, 0x73, 0x74, 0x5f, 0x6b, 0x6e, 0x6f, 0x77, 0x6e, 0x5f, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x5f, 0x69, 0x64, 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x09, 0x52, 0x11, 0x6c, 0x61, 0x73, 0x74, 0x4b, 0x6e, 0x6f, 0x77, 0x6e, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x49, 0x64, 0x73, 0x22, 0xd4, 0x01, 0x0a, 0x1d, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x45, 0x76, 0x65, 0x6e, 0x74, 0x73, 0x53, 0x75, 0x62, 0x73, 0x63, 0x72, 0x69, 0x62, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x3d, 0x0a, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x25, 0x2e, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x45, 0x76, 0x65, 0x6e, 0x74, 0x73, 0x53, 0x75, 0x62, 0x73, 0x63, 0x72, 0x69, 0x62, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x2e, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x52, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, 0x29, 0x0a, 0x10, 0x72, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x5f, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0f, 0x72, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x22, 0x49, 0x0a, 0x06, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, 0x10, 0x0a, 0x0c, 0x53, 0x54, 0x41, 0x54, 0x55, 0x53, 0x5f, 0x55, 0x4e, 0x53, 0x45, 0x54, 0x10, 0x00, 0x12, 0x06, 0x0a, 0x02, 0x4f, 0x4b, 0x10, 0x01, 0x12, 0x12, 0x0a, 0x0e, 0x49, 0x4e, 0x56, 0x41, 0x4c, 0x49, 0x44, 0x5f, 0x46, 0x49, 0x4c, 0x54, 0x45, 0x52, 0x10, 0x02, 0x12, 0x11, 0x0a, 0x0d, 0x55, 0x4e, 0x4b, 0x4e, 0x4f, 0x57, 0x4e, 0x5f, 0x42, 0x4c, 0x4f, 0x43, 0x4b, 0x10, 0x03, 0x22, 0x20, 0x0a, 0x1e, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x45, 0x76, 0x65, 0x6e, 0x74, 0x73, 0x55, 0x6e, 0x73, 0x75, 0x62, 0x73, 0x63, 0x72, 0x69, 0x62, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x22, 0x9a, 0x01, 0x0a, 0x1f, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x45, 0x76, 0x65, 0x6e, 0x74, 0x73, 0x55, 0x6e, 0x73, 0x75, 0x62, 0x73, 0x63, 0x72, 0x69, 0x62, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x3f, 0x0a, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x27, 0x2e, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x45, 0x76, 0x65, 0x6e, 0x74, 0x73, 0x55, 0x6e, 0x73, 0x75, 0x62, 0x73, 0x63, 0x72, 0x69, 0x62, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x2e, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x52, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x22, 0x36, 0x0a, 0x06, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, 0x10, 0x0a, 0x0c, 0x53, 0x54, 0x41, 0x54, 0x55, 0x53, 0x5f, 0x55, 0x4e, 0x53, 0x45, 0x54, 0x10, 0x00, 0x12, 0x06, 0x0a, 0x02, 0x4f, 0x4b, 0x10, 0x01, 0x12, 0x12, 0x0a, 0x0e, 0x49, 0x4e, 0x54, 0x45, 0x52, 0x4e, 0x41, 0x4c, 0x5f, 0x45, 0x52, 0x52, 0x4f, 0x52, 0x10, 0x02, 0x22, 0x6f, 0x0a, 0x16, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x45, 0x76, 0x65, 0x6e, 0x74, 0x73, 0x47, 0x65, 0x74, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x38, 0x0a, 0x0d, 0x73, 0x75, 0x62, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x12, 0x2e, 0x45, 0x76, 0x65, 0x6e, 0x74, 0x53, 0x75, 0x62, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x0d, 0x73, 0x75, 0x62, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x12, 0x1b, 0x0a, 0x09, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x5f, 0x69, 0x64, 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x09, 0x52, 0x08, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x49, 0x64, 0x73, 0x22, 0xd1, 0x01, 0x0a, 0x17, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x45, 0x76, 0x65, 0x6e, 0x74, 0x73, 0x47, 0x65, 0x74, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x37, 0x0a, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x1f, 0x2e, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x45, 0x76, 0x65, 0x6e, 0x74, 0x73, 0x47, 0x65, 0x74, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x2e, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x52, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, 0x1e, 0x0a, 0x06, 0x65, 0x76, 0x65, 0x6e, 0x74, 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x06, 0x2e, 0x45, 0x76, 0x65, 0x6e, 0x74, 0x52, 0x06, 0x65, 0x76, 0x65, 0x6e, 0x74, 0x73, 0x22, 0x5d, 0x0a, 0x06, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, 0x10, 0x0a, 0x0c, 0x53, 0x54, 0x41, 0x54, 0x55, 0x53, 0x5f, 0x55, 0x4e, 0x53, 0x45, 0x54, 0x10, 0x00, 0x12, 0x06, 0x0a, 0x02, 0x4f, 0x4b, 0x10, 0x01, 0x12, 0x12, 0x0a, 0x0e, 0x49, 0x4e, 0x54, 0x45, 0x52, 0x4e, 0x41, 0x4c, 0x5f, 0x45, 0x52, 0x52, 0x4f, 0x52, 0x10, 0x02, 0x12, 0x12, 0x0a, 0x0e, 0x49, 0x4e, 0x56, 0x41, 0x4c, 0x49, 0x44, 0x5f, 0x46, 0x49, 0x4c, 0x54, 0x45, 0x52, 0x10, 0x03, 0x12, 0x11, 0x0a, 0x0d, 0x55, 0x4e, 0x4b, 0x4e, 0x4f, 0x57, 0x4e, 0x5f, 0x42, 0x4c, 0x4f, 0x43, 0x4b, 0x10, 0x04, 0x42, 0x2b, 0x0a, 0x15, 0x73, 0x61, 0x77, 0x74, 0x6f, 0x6f, 0x74, 0x68, 0x2e, 0x73, 0x64, 0x6b, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x50, 0x01, 0x5a, 0x10, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x5f, 0x65, 0x76, 0x65, 0x6e, 0x74, 0x5f, 0x70, 0x62, 0x32, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( file_protobuf_client_event_pb2_client_event_proto_rawDescOnce sync.Once file_protobuf_client_event_pb2_client_event_proto_rawDescData = file_protobuf_client_event_pb2_client_event_proto_rawDesc ) func file_protobuf_client_event_pb2_client_event_proto_rawDescGZIP() []byte { file_protobuf_client_event_pb2_client_event_proto_rawDescOnce.Do(func() { file_protobuf_client_event_pb2_client_event_proto_rawDescData = protoimpl.X.CompressGZIP(file_protobuf_client_event_pb2_client_event_proto_rawDescData) }) return file_protobuf_client_event_pb2_client_event_proto_rawDescData } var file_protobuf_client_event_pb2_client_event_proto_enumTypes = make([]protoimpl.EnumInfo, 3) var file_protobuf_client_event_pb2_client_event_proto_msgTypes = make([]protoimpl.MessageInfo, 6) var file_protobuf_client_event_pb2_client_event_proto_goTypes = []interface{}{ (ClientEventsSubscribeResponse_Status)(0), // 0: ClientEventsSubscribeResponse.Status (ClientEventsUnsubscribeResponse_Status)(0), // 1: ClientEventsUnsubscribeResponse.Status (ClientEventsGetResponse_Status)(0), // 2: ClientEventsGetResponse.Status (*ClientEventsSubscribeRequest)(nil), // 3: ClientEventsSubscribeRequest (*ClientEventsSubscribeResponse)(nil), // 4: ClientEventsSubscribeResponse (*ClientEventsUnsubscribeRequest)(nil), // 5: ClientEventsUnsubscribeRequest (*ClientEventsUnsubscribeResponse)(nil), // 6: ClientEventsUnsubscribeResponse (*ClientEventsGetRequest)(nil), // 7: ClientEventsGetRequest (*ClientEventsGetResponse)(nil), // 8: ClientEventsGetResponse (*events_pb2.EventSubscription)(nil), // 9: EventSubscription (*events_pb2.Event)(nil), // 10: Event } var file_protobuf_client_event_pb2_client_event_proto_depIdxs = []int32{ 9, // 0: ClientEventsSubscribeRequest.subscriptions:type_name -> EventSubscription 0, // 1: ClientEventsSubscribeResponse.status:type_name -> ClientEventsSubscribeResponse.Status 1, // 2: ClientEventsUnsubscribeResponse.status:type_name -> ClientEventsUnsubscribeResponse.Status 9, // 3: ClientEventsGetRequest.subscriptions:type_name -> EventSubscription 2, // 4: ClientEventsGetResponse.status:type_name -> ClientEventsGetResponse.Status 10, // 5: ClientEventsGetResponse.events:type_name -> Event 6, // [6:6] is the sub-list for method output_type 6, // [6:6] is the sub-list for method input_type 6, // [6:6] is the sub-list for extension type_name 6, // [6:6] is the sub-list for extension extendee 0, // [0:6] is the sub-list for field type_name } func init() { file_protobuf_client_event_pb2_client_event_proto_init() } func file_protobuf_client_event_pb2_client_event_proto_init() { if File_protobuf_client_event_pb2_client_event_proto != nil { return } if !protoimpl.UnsafeEnabled { file_protobuf_client_event_pb2_client_event_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ClientEventsSubscribeRequest); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_client_event_pb2_client_event_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ClientEventsSubscribeResponse); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_client_event_pb2_client_event_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ClientEventsUnsubscribeRequest); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_client_event_pb2_client_event_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ClientEventsUnsubscribeResponse); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_client_event_pb2_client_event_proto_msgTypes[4].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ClientEventsGetRequest); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_client_event_pb2_client_event_proto_msgTypes[5].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ClientEventsGetResponse); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: file_protobuf_client_event_pb2_client_event_proto_rawDesc, NumEnums: 3, NumMessages: 6, NumExtensions: 0, NumServices: 0, }, GoTypes: file_protobuf_client_event_pb2_client_event_proto_goTypes, DependencyIndexes: file_protobuf_client_event_pb2_client_event_proto_depIdxs, EnumInfos: file_protobuf_client_event_pb2_client_event_proto_enumTypes, MessageInfos: file_protobuf_client_event_pb2_client_event_proto_msgTypes, }.Build() File_protobuf_client_event_pb2_client_event_proto = out.File file_protobuf_client_event_pb2_client_event_proto_rawDesc = nil file_protobuf_client_event_pb2_client_event_proto_goTypes = nil file_protobuf_client_event_pb2_client_event_proto_depIdxs = nil } <|start_filename|>messaging/connection.go<|end_filename|> /** * Copyright 2017 Intel Corporation * * 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 messaging handles lower-level communication between a transaction // processor and validator. package messaging import ( "fmt" "github.com/golang/protobuf/proto" "github.com/hyperledger/sawtooth-sdk-go/logging" "github.com/hyperledger/sawtooth-sdk-go/protobuf/validator_pb2" zmq "github.com/pebbe/zmq4" uuid "github.com/satori/go.uuid" ) var logger *logging.Logger = logging.Get() // Generate a new UUID func GenerateId() string { return fmt.Sprint(uuid.NewV4()) } // DumpMsg serializes a validator message func DumpMsg(t validator_pb2.Message_MessageType, c []byte, corrId string) ([]byte, error) { msg := &validator_pb2.Message{ MessageType: t, CorrelationId: corrId, Content: c, } return proto.Marshal(msg) } // LoadMsg deserializes a validator message func LoadMsg(data []byte) (msg *validator_pb2.Message, err error) { msg = &validator_pb2.Message{} err = proto.Unmarshal(data, msg) return } type Connection interface { SendData(id string, data []byte) error SendNewMsg(t validator_pb2.Message_MessageType, c []byte) (corrId string, err error) SendNewMsgTo(id string, t validator_pb2.Message_MessageType, c []byte) (corrId string, err error) SendMsg(t validator_pb2.Message_MessageType, c []byte, corrId string) error SendMsgTo(id string, t validator_pb2.Message_MessageType, c []byte, corrId string) error RecvData() (string, []byte, error) RecvMsg() (string, *validator_pb2.Message, error) RecvMsgWithId(corrId string) (string, *validator_pb2.Message, error) Close() Socket() *zmq.Socket Monitor(zmq.Event) (*zmq.Socket, error) Identity() string } // Connection wraps a ZMQ DEALER socket or ROUTER socket and provides some // utility methods for sending and receiving messages. type ZmqConnection struct { identity string uri string socket *zmq.Socket context *zmq.Context incoming map[string]*storedMsg } type storedMsg struct { Id string Msg *validator_pb2.Message } // NewConnection establishes a new connection using the given ZMQ context and // socket type to the given URI. func NewConnection(context *zmq.Context, t zmq.Type, uri string, bind bool) (*ZmqConnection, error) { socket, err := context.NewSocket(t) if err != nil { return nil, fmt.Errorf("Failed to create ZMQ socket: %v", err) } identity := GenerateId() socket.SetIdentity(identity) if bind { logger.Info("Binding to ", uri) err = socket.Bind(uri) } else { logger.Info("Connecting to ", uri) err = socket.Connect(uri) } if err != nil { return nil, fmt.Errorf("Failed to establish connection to %v: %v", uri, err) } return &ZmqConnection{ identity: identity, uri: uri, socket: socket, context: context, incoming: make(map[string]*storedMsg), }, nil } // SendData sends the byte array. // // If id is not "", the id is included as the first part of the message. This // is useful for passing messages to a ROUTER socket so it can route them. func (self *ZmqConnection) SendData(id string, data []byte) error { if id != "" { _, err := self.socket.SendMessage(id, [][]byte{data}) if err != nil { return err } } else { _, err := self.socket.SendMessage([][]byte{data}) if err != nil { return err } } return nil } // SendNewMsg creates a new validator message, assigns a new correlation id, // serializes it, and sends it. It returns the correlation id created. func (self *ZmqConnection) SendNewMsg(t validator_pb2.Message_MessageType, c []byte) (corrId string, err error) { return self.SendNewMsgTo("", t, c) } // SendNewMsgTo sends a new message validator message with the given id sent as // the first part of the message. This is required when sending to a ROUTER // socket, so it knows where to route the message. func (self *ZmqConnection) SendNewMsgTo(id string, t validator_pb2.Message_MessageType, c []byte) (corrId string, err error) { corrId = GenerateId() return corrId, self.SendMsgTo(id, t, c, corrId) } // Send a message with the given correlation id func (self *ZmqConnection) SendMsg(t validator_pb2.Message_MessageType, c []byte, corrId string) error { return self.SendMsgTo("", t, c, corrId) } // Send a message with the given correlation id and the prepends the id like // SendNewMsgTo() func (self *ZmqConnection) SendMsgTo(id string, t validator_pb2.Message_MessageType, c []byte, corrId string) error { data, err := DumpMsg(t, c, corrId) if err != nil { return err } return self.SendData(id, data) } // RecvData receives a ZMQ message from the wrapped socket and returns the // identity of the sender and the data sent. If ZmqConnection does not wrap a // ROUTER socket, the identity returned will be "". func (self *ZmqConnection) RecvData() (string, []byte, error) { msg, err := self.socket.RecvMessage(0) if err != nil { return "", nil, err } switch len(msg) { case 1: data := []byte(msg[0]) return "", data, nil case 2: id := msg[0] data := []byte(msg[1]) return id, data, nil default: return "", nil, fmt.Errorf( "Receive message with unexpected length: %v", len(msg), ) } } // RecvMsg receives a new validator message and returns it deserialized. If // ZmqConnection wraps a ROUTER socket, id will be the identity of the sender. // Otherwise, id will be "". func (self *ZmqConnection) RecvMsg() (string, *validator_pb2.Message, error) { for corrId, stored := range self.incoming { delete(self.incoming, corrId) return stored.Id, stored.Msg, nil } // Receive a message from the socket id, bytes, err := self.RecvData() if err != nil { return "", nil, err } msg, err := LoadMsg(bytes) return id, msg, err } // RecvMsgWithId receives validator messages until a message with the given // correlation id is found and returns this message. Any messages received that // do not match the id are saved for subsequent receives. func (self *ZmqConnection) RecvMsgWithId(corrId string) (string, *validator_pb2.Message, error) { // If the message is already stored, just return it stored, exists := self.incoming[corrId] if exists { return stored.Id, stored.Msg, nil } for { // If the message isn't stored, keep getting messages until it shows up id, bytes, err := self.RecvData() if err != nil { return "", nil, err } msg, err := LoadMsg(bytes) // If the ids match, return it if msg.GetCorrelationId() == corrId { return id, msg, err } // Otherwise, keep the message for later self.incoming[msg.GetCorrelationId()] = &storedMsg{Id: id, Msg: msg} } } // Close closes the wrapped socket. This should be called with defer() after opening the socket. func (self *ZmqConnection) Close() { self.socket.Close() } // Socket returns the wrapped socket. func (self *ZmqConnection) Socket() *zmq.Socket { return self.socket } // Create a new monitor socket pair and return the socket for listening func (self *ZmqConnection) Monitor(events zmq.Event) (*zmq.Socket, error) { endpoint := fmt.Sprintf("inproc://monitor.%v", self.identity) err := self.socket.Monitor(endpoint, events) if err != nil { return nil, err } monitor, err := self.context.NewSocket(zmq.PAIR) err = monitor.Connect(endpoint) if err != nil { return nil, err } return monitor, nil } // Identity returns the identity assigned to the wrapped socket. func (self *ZmqConnection) Identity() string { return self.identity } <|start_filename|>protobuf/client_batch_pb2/client_batch.pb.go<|end_filename|> // Copyright 2017 Intel Corporation // // 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. // ----------------------------------------------------------------------------- // Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.25.0-devel // protoc v3.14.0 // source: protobuf/client_batch_pb2/client_batch.proto package client_batch_pb2 import ( protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" batch_pb2 "github.com/hyperledger/sawtooth-sdk-go/protobuf/batch_pb2" client_list_control_pb2 "github.com/hyperledger/sawtooth-sdk-go/protobuf/client_list_control_pb2" reflect "reflect" sync "sync" ) const ( // Verify that this generated code is sufficiently up-to-date. _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) // Verify that runtime/protoimpl is sufficiently up-to-date. _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) type ClientBatchListResponse_Status int32 const ( ClientBatchListResponse_STATUS_UNSET ClientBatchListResponse_Status = 0 ClientBatchListResponse_OK ClientBatchListResponse_Status = 1 ClientBatchListResponse_INTERNAL_ERROR ClientBatchListResponse_Status = 2 ClientBatchListResponse_NOT_READY ClientBatchListResponse_Status = 3 ClientBatchListResponse_NO_ROOT ClientBatchListResponse_Status = 4 ClientBatchListResponse_NO_RESOURCE ClientBatchListResponse_Status = 5 ClientBatchListResponse_INVALID_PAGING ClientBatchListResponse_Status = 6 ClientBatchListResponse_INVALID_SORT ClientBatchListResponse_Status = 7 ClientBatchListResponse_INVALID_ID ClientBatchListResponse_Status = 8 ) // Enum value maps for ClientBatchListResponse_Status. var ( ClientBatchListResponse_Status_name = map[int32]string{ 0: "STATUS_UNSET", 1: "OK", 2: "INTERNAL_ERROR", 3: "NOT_READY", 4: "NO_ROOT", 5: "NO_RESOURCE", 6: "INVALID_PAGING", 7: "INVALID_SORT", 8: "INVALID_ID", } ClientBatchListResponse_Status_value = map[string]int32{ "STATUS_UNSET": 0, "OK": 1, "INTERNAL_ERROR": 2, "NOT_READY": 3, "NO_ROOT": 4, "NO_RESOURCE": 5, "INVALID_PAGING": 6, "INVALID_SORT": 7, "INVALID_ID": 8, } ) func (x ClientBatchListResponse_Status) Enum() *ClientBatchListResponse_Status { p := new(ClientBatchListResponse_Status) *p = x return p } func (x ClientBatchListResponse_Status) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (ClientBatchListResponse_Status) Descriptor() protoreflect.EnumDescriptor { return file_protobuf_client_batch_pb2_client_batch_proto_enumTypes[0].Descriptor() } func (ClientBatchListResponse_Status) Type() protoreflect.EnumType { return &file_protobuf_client_batch_pb2_client_batch_proto_enumTypes[0] } func (x ClientBatchListResponse_Status) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use ClientBatchListResponse_Status.Descriptor instead. func (ClientBatchListResponse_Status) EnumDescriptor() ([]byte, []int) { return file_protobuf_client_batch_pb2_client_batch_proto_rawDescGZIP(), []int{1, 0} } type ClientBatchGetResponse_Status int32 const ( ClientBatchGetResponse_STATUS_UNSET ClientBatchGetResponse_Status = 0 ClientBatchGetResponse_OK ClientBatchGetResponse_Status = 1 ClientBatchGetResponse_INTERNAL_ERROR ClientBatchGetResponse_Status = 2 ClientBatchGetResponse_NO_RESOURCE ClientBatchGetResponse_Status = 5 ClientBatchGetResponse_INVALID_ID ClientBatchGetResponse_Status = 8 ) // Enum value maps for ClientBatchGetResponse_Status. var ( ClientBatchGetResponse_Status_name = map[int32]string{ 0: "STATUS_UNSET", 1: "OK", 2: "INTERNAL_ERROR", 5: "NO_RESOURCE", 8: "INVALID_ID", } ClientBatchGetResponse_Status_value = map[string]int32{ "STATUS_UNSET": 0, "OK": 1, "INTERNAL_ERROR": 2, "NO_RESOURCE": 5, "INVALID_ID": 8, } ) func (x ClientBatchGetResponse_Status) Enum() *ClientBatchGetResponse_Status { p := new(ClientBatchGetResponse_Status) *p = x return p } func (x ClientBatchGetResponse_Status) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (ClientBatchGetResponse_Status) Descriptor() protoreflect.EnumDescriptor { return file_protobuf_client_batch_pb2_client_batch_proto_enumTypes[1].Descriptor() } func (ClientBatchGetResponse_Status) Type() protoreflect.EnumType { return &file_protobuf_client_batch_pb2_client_batch_proto_enumTypes[1] } func (x ClientBatchGetResponse_Status) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use ClientBatchGetResponse_Status.Descriptor instead. func (ClientBatchGetResponse_Status) EnumDescriptor() ([]byte, []int) { return file_protobuf_client_batch_pb2_client_batch_proto_rawDescGZIP(), []int{3, 0} } // A request to return a list of batches from the validator. May include the id // of a particular block to be the `head` of the chain being requested. In that // case the list will include the batches from that block, and all batches // previous to that block on the chain. Filter with specific `batch_ids`. type ClientBatchListRequest struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields HeadId string `protobuf:"bytes,1,opt,name=head_id,json=headId,proto3" json:"head_id,omitempty"` BatchIds []string `protobuf:"bytes,2,rep,name=batch_ids,json=batchIds,proto3" json:"batch_ids,omitempty"` Paging *client_list_control_pb2.ClientPagingControls `protobuf:"bytes,3,opt,name=paging,proto3" json:"paging,omitempty"` Sorting []*client_list_control_pb2.ClientSortControls `protobuf:"bytes,4,rep,name=sorting,proto3" json:"sorting,omitempty"` } func (x *ClientBatchListRequest) Reset() { *x = ClientBatchListRequest{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_client_batch_pb2_client_batch_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ClientBatchListRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*ClientBatchListRequest) ProtoMessage() {} func (x *ClientBatchListRequest) ProtoReflect() protoreflect.Message { mi := &file_protobuf_client_batch_pb2_client_batch_proto_msgTypes[0] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ClientBatchListRequest.ProtoReflect.Descriptor instead. func (*ClientBatchListRequest) Descriptor() ([]byte, []int) { return file_protobuf_client_batch_pb2_client_batch_proto_rawDescGZIP(), []int{0} } func (x *ClientBatchListRequest) GetHeadId() string { if x != nil { return x.HeadId } return "" } func (x *ClientBatchListRequest) GetBatchIds() []string { if x != nil { return x.BatchIds } return nil } func (x *ClientBatchListRequest) GetPaging() *client_list_control_pb2.ClientPagingControls { if x != nil { return x.Paging } return nil } func (x *ClientBatchListRequest) GetSorting() []*client_list_control_pb2.ClientSortControls { if x != nil { return x.Sorting } return nil } // A response that lists batches from newest to oldest. // // Statuses: // * OK - everything worked as expected // * INTERNAL_ERROR - general error, such as protobuf failing to deserialize // * NOT_READY - the validator does not yet have a genesis block // * NO_ROOT - the head block specified was not found // * NO_RESOURCE - no batches were found with the parameters specified // * INVALID_PAGING - the paging controls were malformed or out of range // * INVALID_SORT - the sorting controls were malformed or invalid type ClientBatchListResponse struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Status ClientBatchListResponse_Status `protobuf:"varint,1,opt,name=status,proto3,enum=ClientBatchListResponse_Status" json:"status,omitempty"` Batches []*batch_pb2.Batch `protobuf:"bytes,2,rep,name=batches,proto3" json:"batches,omitempty"` HeadId string `protobuf:"bytes,3,opt,name=head_id,json=headId,proto3" json:"head_id,omitempty"` Paging *client_list_control_pb2.ClientPagingResponse `protobuf:"bytes,4,opt,name=paging,proto3" json:"paging,omitempty"` } func (x *ClientBatchListResponse) Reset() { *x = ClientBatchListResponse{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_client_batch_pb2_client_batch_proto_msgTypes[1] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ClientBatchListResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*ClientBatchListResponse) ProtoMessage() {} func (x *ClientBatchListResponse) ProtoReflect() protoreflect.Message { mi := &file_protobuf_client_batch_pb2_client_batch_proto_msgTypes[1] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ClientBatchListResponse.ProtoReflect.Descriptor instead. func (*ClientBatchListResponse) Descriptor() ([]byte, []int) { return file_protobuf_client_batch_pb2_client_batch_proto_rawDescGZIP(), []int{1} } func (x *ClientBatchListResponse) GetStatus() ClientBatchListResponse_Status { if x != nil { return x.Status } return ClientBatchListResponse_STATUS_UNSET } func (x *ClientBatchListResponse) GetBatches() []*batch_pb2.Batch { if x != nil { return x.Batches } return nil } func (x *ClientBatchListResponse) GetHeadId() string { if x != nil { return x.HeadId } return "" } func (x *ClientBatchListResponse) GetPaging() *client_list_control_pb2.ClientPagingResponse { if x != nil { return x.Paging } return nil } // Fetches a specific batch by its id (header_signature) from the blockchain. type ClientBatchGetRequest struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields BatchId string `protobuf:"bytes,1,opt,name=batch_id,json=batchId,proto3" json:"batch_id,omitempty"` } func (x *ClientBatchGetRequest) Reset() { *x = ClientBatchGetRequest{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_client_batch_pb2_client_batch_proto_msgTypes[2] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ClientBatchGetRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*ClientBatchGetRequest) ProtoMessage() {} func (x *ClientBatchGetRequest) ProtoReflect() protoreflect.Message { mi := &file_protobuf_client_batch_pb2_client_batch_proto_msgTypes[2] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ClientBatchGetRequest.ProtoReflect.Descriptor instead. func (*ClientBatchGetRequest) Descriptor() ([]byte, []int) { return file_protobuf_client_batch_pb2_client_batch_proto_rawDescGZIP(), []int{2} } func (x *ClientBatchGetRequest) GetBatchId() string { if x != nil { return x.BatchId } return "" } // A response that returns the batch specified by a ClientBatchGetRequest. // // Statuses: // * OK - everything worked as expected, batch has been fetched // * INTERNAL_ERROR - general error, such as protobuf failing to deserialize // * NO_RESOURCE - no batch with the specified id exists type ClientBatchGetResponse struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Status ClientBatchGetResponse_Status `protobuf:"varint,1,opt,name=status,proto3,enum=ClientBatchGetResponse_Status" json:"status,omitempty"` Batch *batch_pb2.Batch `protobuf:"bytes,2,opt,name=batch,proto3" json:"batch,omitempty"` } func (x *ClientBatchGetResponse) Reset() { *x = ClientBatchGetResponse{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_client_batch_pb2_client_batch_proto_msgTypes[3] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ClientBatchGetResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*ClientBatchGetResponse) ProtoMessage() {} func (x *ClientBatchGetResponse) ProtoReflect() protoreflect.Message { mi := &file_protobuf_client_batch_pb2_client_batch_proto_msgTypes[3] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ClientBatchGetResponse.ProtoReflect.Descriptor instead. func (*ClientBatchGetResponse) Descriptor() ([]byte, []int) { return file_protobuf_client_batch_pb2_client_batch_proto_rawDescGZIP(), []int{3} } func (x *ClientBatchGetResponse) GetStatus() ClientBatchGetResponse_Status { if x != nil { return x.Status } return ClientBatchGetResponse_STATUS_UNSET } func (x *ClientBatchGetResponse) GetBatch() *batch_pb2.Batch { if x != nil { return x.Batch } return nil } var File_protobuf_client_batch_pb2_client_batch_proto protoreflect.FileDescriptor var file_protobuf_client_batch_pb2_client_batch_proto_rawDesc = []byte{ 0x0a, 0x2c, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x5f, 0x62, 0x61, 0x74, 0x63, 0x68, 0x5f, 0x70, 0x62, 0x32, 0x2f, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x5f, 0x62, 0x61, 0x74, 0x63, 0x68, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x1e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x62, 0x61, 0x74, 0x63, 0x68, 0x5f, 0x70, 0x62, 0x32, 0x2f, 0x62, 0x61, 0x74, 0x63, 0x68, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x3a, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x5f, 0x6c, 0x69, 0x73, 0x74, 0x5f, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x5f, 0x70, 0x62, 0x32, 0x2f, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x5f, 0x6c, 0x69, 0x73, 0x74, 0x5f, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0xac, 0x01, 0x0a, 0x16, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x42, 0x61, 0x74, 0x63, 0x68, 0x4c, 0x69, 0x73, 0x74, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x17, 0x0a, 0x07, 0x68, 0x65, 0x61, 0x64, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, 0x68, 0x65, 0x61, 0x64, 0x49, 0x64, 0x12, 0x1b, 0x0a, 0x09, 0x62, 0x61, 0x74, 0x63, 0x68, 0x5f, 0x69, 0x64, 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x09, 0x52, 0x08, 0x62, 0x61, 0x74, 0x63, 0x68, 0x49, 0x64, 0x73, 0x12, 0x2d, 0x0a, 0x06, 0x70, 0x61, 0x67, 0x69, 0x6e, 0x67, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x15, 0x2e, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x50, 0x61, 0x67, 0x69, 0x6e, 0x67, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x73, 0x52, 0x06, 0x70, 0x61, 0x67, 0x69, 0x6e, 0x67, 0x12, 0x2d, 0x0a, 0x07, 0x73, 0x6f, 0x72, 0x74, 0x69, 0x6e, 0x67, 0x18, 0x04, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x13, 0x2e, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x53, 0x6f, 0x72, 0x74, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x73, 0x52, 0x07, 0x73, 0x6f, 0x72, 0x74, 0x69, 0x6e, 0x67, 0x22, 0xd8, 0x02, 0x0a, 0x17, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x42, 0x61, 0x74, 0x63, 0x68, 0x4c, 0x69, 0x73, 0x74, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x37, 0x0a, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x1f, 0x2e, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x42, 0x61, 0x74, 0x63, 0x68, 0x4c, 0x69, 0x73, 0x74, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x2e, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x52, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, 0x20, 0x0a, 0x07, 0x62, 0x61, 0x74, 0x63, 0x68, 0x65, 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x06, 0x2e, 0x42, 0x61, 0x74, 0x63, 0x68, 0x52, 0x07, 0x62, 0x61, 0x74, 0x63, 0x68, 0x65, 0x73, 0x12, 0x17, 0x0a, 0x07, 0x68, 0x65, 0x61, 0x64, 0x5f, 0x69, 0x64, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, 0x68, 0x65, 0x61, 0x64, 0x49, 0x64, 0x12, 0x2d, 0x0a, 0x06, 0x70, 0x61, 0x67, 0x69, 0x6e, 0x67, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x15, 0x2e, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x50, 0x61, 0x67, 0x69, 0x6e, 0x67, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x52, 0x06, 0x70, 0x61, 0x67, 0x69, 0x6e, 0x67, 0x22, 0x99, 0x01, 0x0a, 0x06, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, 0x10, 0x0a, 0x0c, 0x53, 0x54, 0x41, 0x54, 0x55, 0x53, 0x5f, 0x55, 0x4e, 0x53, 0x45, 0x54, 0x10, 0x00, 0x12, 0x06, 0x0a, 0x02, 0x4f, 0x4b, 0x10, 0x01, 0x12, 0x12, 0x0a, 0x0e, 0x49, 0x4e, 0x54, 0x45, 0x52, 0x4e, 0x41, 0x4c, 0x5f, 0x45, 0x52, 0x52, 0x4f, 0x52, 0x10, 0x02, 0x12, 0x0d, 0x0a, 0x09, 0x4e, 0x4f, 0x54, 0x5f, 0x52, 0x45, 0x41, 0x44, 0x59, 0x10, 0x03, 0x12, 0x0b, 0x0a, 0x07, 0x4e, 0x4f, 0x5f, 0x52, 0x4f, 0x4f, 0x54, 0x10, 0x04, 0x12, 0x0f, 0x0a, 0x0b, 0x4e, 0x4f, 0x5f, 0x52, 0x45, 0x53, 0x4f, 0x55, 0x52, 0x43, 0x45, 0x10, 0x05, 0x12, 0x12, 0x0a, 0x0e, 0x49, 0x4e, 0x56, 0x41, 0x4c, 0x49, 0x44, 0x5f, 0x50, 0x41, 0x47, 0x49, 0x4e, 0x47, 0x10, 0x06, 0x12, 0x10, 0x0a, 0x0c, 0x49, 0x4e, 0x56, 0x41, 0x4c, 0x49, 0x44, 0x5f, 0x53, 0x4f, 0x52, 0x54, 0x10, 0x07, 0x12, 0x0e, 0x0a, 0x0a, 0x49, 0x4e, 0x56, 0x41, 0x4c, 0x49, 0x44, 0x5f, 0x49, 0x44, 0x10, 0x08, 0x22, 0x32, 0x0a, 0x15, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x42, 0x61, 0x74, 0x63, 0x68, 0x47, 0x65, 0x74, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x19, 0x0a, 0x08, 0x62, 0x61, 0x74, 0x63, 0x68, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x62, 0x61, 0x74, 0x63, 0x68, 0x49, 0x64, 0x22, 0xc7, 0x01, 0x0a, 0x16, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x42, 0x61, 0x74, 0x63, 0x68, 0x47, 0x65, 0x74, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x36, 0x0a, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x1e, 0x2e, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x42, 0x61, 0x74, 0x63, 0x68, 0x47, 0x65, 0x74, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x2e, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x52, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, 0x1c, 0x0a, 0x05, 0x62, 0x61, 0x74, 0x63, 0x68, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x06, 0x2e, 0x42, 0x61, 0x74, 0x63, 0x68, 0x52, 0x05, 0x62, 0x61, 0x74, 0x63, 0x68, 0x22, 0x57, 0x0a, 0x06, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, 0x10, 0x0a, 0x0c, 0x53, 0x54, 0x41, 0x54, 0x55, 0x53, 0x5f, 0x55, 0x4e, 0x53, 0x45, 0x54, 0x10, 0x00, 0x12, 0x06, 0x0a, 0x02, 0x4f, 0x4b, 0x10, 0x01, 0x12, 0x12, 0x0a, 0x0e, 0x49, 0x4e, 0x54, 0x45, 0x52, 0x4e, 0x41, 0x4c, 0x5f, 0x45, 0x52, 0x52, 0x4f, 0x52, 0x10, 0x02, 0x12, 0x0f, 0x0a, 0x0b, 0x4e, 0x4f, 0x5f, 0x52, 0x45, 0x53, 0x4f, 0x55, 0x52, 0x43, 0x45, 0x10, 0x05, 0x12, 0x0e, 0x0a, 0x0a, 0x49, 0x4e, 0x56, 0x41, 0x4c, 0x49, 0x44, 0x5f, 0x49, 0x44, 0x10, 0x08, 0x42, 0x2b, 0x0a, 0x15, 0x73, 0x61, 0x77, 0x74, 0x6f, 0x6f, 0x74, 0x68, 0x2e, 0x73, 0x64, 0x6b, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x50, 0x01, 0x5a, 0x10, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x5f, 0x62, 0x61, 0x74, 0x63, 0x68, 0x5f, 0x70, 0x62, 0x32, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( file_protobuf_client_batch_pb2_client_batch_proto_rawDescOnce sync.Once file_protobuf_client_batch_pb2_client_batch_proto_rawDescData = file_protobuf_client_batch_pb2_client_batch_proto_rawDesc ) func file_protobuf_client_batch_pb2_client_batch_proto_rawDescGZIP() []byte { file_protobuf_client_batch_pb2_client_batch_proto_rawDescOnce.Do(func() { file_protobuf_client_batch_pb2_client_batch_proto_rawDescData = protoimpl.X.CompressGZIP(file_protobuf_client_batch_pb2_client_batch_proto_rawDescData) }) return file_protobuf_client_batch_pb2_client_batch_proto_rawDescData } var file_protobuf_client_batch_pb2_client_batch_proto_enumTypes = make([]protoimpl.EnumInfo, 2) var file_protobuf_client_batch_pb2_client_batch_proto_msgTypes = make([]protoimpl.MessageInfo, 4) var file_protobuf_client_batch_pb2_client_batch_proto_goTypes = []interface{}{ (ClientBatchListResponse_Status)(0), // 0: ClientBatchListResponse.Status (ClientBatchGetResponse_Status)(0), // 1: ClientBatchGetResponse.Status (*ClientBatchListRequest)(nil), // 2: ClientBatchListRequest (*ClientBatchListResponse)(nil), // 3: ClientBatchListResponse (*ClientBatchGetRequest)(nil), // 4: ClientBatchGetRequest (*ClientBatchGetResponse)(nil), // 5: ClientBatchGetResponse (*client_list_control_pb2.ClientPagingControls)(nil), // 6: ClientPagingControls (*client_list_control_pb2.ClientSortControls)(nil), // 7: ClientSortControls (*batch_pb2.Batch)(nil), // 8: Batch (*client_list_control_pb2.ClientPagingResponse)(nil), // 9: ClientPagingResponse } var file_protobuf_client_batch_pb2_client_batch_proto_depIdxs = []int32{ 6, // 0: ClientBatchListRequest.paging:type_name -> ClientPagingControls 7, // 1: ClientBatchListRequest.sorting:type_name -> ClientSortControls 0, // 2: ClientBatchListResponse.status:type_name -> ClientBatchListResponse.Status 8, // 3: ClientBatchListResponse.batches:type_name -> Batch 9, // 4: ClientBatchListResponse.paging:type_name -> ClientPagingResponse 1, // 5: ClientBatchGetResponse.status:type_name -> ClientBatchGetResponse.Status 8, // 6: ClientBatchGetResponse.batch:type_name -> Batch 7, // [7:7] is the sub-list for method output_type 7, // [7:7] is the sub-list for method input_type 7, // [7:7] is the sub-list for extension type_name 7, // [7:7] is the sub-list for extension extendee 0, // [0:7] is the sub-list for field type_name } func init() { file_protobuf_client_batch_pb2_client_batch_proto_init() } func file_protobuf_client_batch_pb2_client_batch_proto_init() { if File_protobuf_client_batch_pb2_client_batch_proto != nil { return } if !protoimpl.UnsafeEnabled { file_protobuf_client_batch_pb2_client_batch_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ClientBatchListRequest); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_client_batch_pb2_client_batch_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ClientBatchListResponse); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_client_batch_pb2_client_batch_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ClientBatchGetRequest); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_client_batch_pb2_client_batch_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ClientBatchGetResponse); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: file_protobuf_client_batch_pb2_client_batch_proto_rawDesc, NumEnums: 2, NumMessages: 4, NumExtensions: 0, NumServices: 0, }, GoTypes: file_protobuf_client_batch_pb2_client_batch_proto_goTypes, DependencyIndexes: file_protobuf_client_batch_pb2_client_batch_proto_depIdxs, EnumInfos: file_protobuf_client_batch_pb2_client_batch_proto_enumTypes, MessageInfos: file_protobuf_client_batch_pb2_client_batch_proto_msgTypes, }.Build() File_protobuf_client_batch_pb2_client_batch_proto = out.File file_protobuf_client_batch_pb2_client_batch_proto_rawDesc = nil file_protobuf_client_batch_pb2_client_batch_proto_goTypes = nil file_protobuf_client_batch_pb2_client_batch_proto_depIdxs = nil } <|start_filename|>protobuf/client_batch_submit_pb2/client_batch_submit.pb.go<|end_filename|> // Copyright 2017 Intel Corporation // // 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. // ----------------------------------------------------------------------------- // Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.25.0-devel // protoc v3.14.0 // source: protobuf/client_batch_submit_pb2/client_batch_submit.proto package client_batch_submit_pb2 import ( protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" batch_pb2 "github.com/hyperledger/sawtooth-sdk-go/protobuf/batch_pb2" reflect "reflect" sync "sync" ) const ( // Verify that this generated code is sufficiently up-to-date. _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) // Verify that runtime/protoimpl is sufficiently up-to-date. _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) type ClientBatchStatus_Status int32 const ( ClientBatchStatus_STATUS_UNSET ClientBatchStatus_Status = 0 ClientBatchStatus_COMMITTED ClientBatchStatus_Status = 1 ClientBatchStatus_INVALID ClientBatchStatus_Status = 2 ClientBatchStatus_PENDING ClientBatchStatus_Status = 3 ClientBatchStatus_UNKNOWN ClientBatchStatus_Status = 4 ) // Enum value maps for ClientBatchStatus_Status. var ( ClientBatchStatus_Status_name = map[int32]string{ 0: "STATUS_UNSET", 1: "COMMITTED", 2: "INVALID", 3: "PENDING", 4: "UNKNOWN", } ClientBatchStatus_Status_value = map[string]int32{ "STATUS_UNSET": 0, "COMMITTED": 1, "INVALID": 2, "PENDING": 3, "UNKNOWN": 4, } ) func (x ClientBatchStatus_Status) Enum() *ClientBatchStatus_Status { p := new(ClientBatchStatus_Status) *p = x return p } func (x ClientBatchStatus_Status) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (ClientBatchStatus_Status) Descriptor() protoreflect.EnumDescriptor { return file_protobuf_client_batch_submit_pb2_client_batch_submit_proto_enumTypes[0].Descriptor() } func (ClientBatchStatus_Status) Type() protoreflect.EnumType { return &file_protobuf_client_batch_submit_pb2_client_batch_submit_proto_enumTypes[0] } func (x ClientBatchStatus_Status) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use ClientBatchStatus_Status.Descriptor instead. func (ClientBatchStatus_Status) EnumDescriptor() ([]byte, []int) { return file_protobuf_client_batch_submit_pb2_client_batch_submit_proto_rawDescGZIP(), []int{0, 0} } type ClientBatchSubmitResponse_Status int32 const ( ClientBatchSubmitResponse_STATUS_UNSET ClientBatchSubmitResponse_Status = 0 ClientBatchSubmitResponse_OK ClientBatchSubmitResponse_Status = 1 ClientBatchSubmitResponse_INTERNAL_ERROR ClientBatchSubmitResponse_Status = 2 ClientBatchSubmitResponse_INVALID_BATCH ClientBatchSubmitResponse_Status = 3 ClientBatchSubmitResponse_QUEUE_FULL ClientBatchSubmitResponse_Status = 4 ) // Enum value maps for ClientBatchSubmitResponse_Status. var ( ClientBatchSubmitResponse_Status_name = map[int32]string{ 0: "STATUS_UNSET", 1: "OK", 2: "INTERNAL_ERROR", 3: "INVALID_BATCH", 4: "QUEUE_FULL", } ClientBatchSubmitResponse_Status_value = map[string]int32{ "STATUS_UNSET": 0, "OK": 1, "INTERNAL_ERROR": 2, "INVALID_BATCH": 3, "QUEUE_FULL": 4, } ) func (x ClientBatchSubmitResponse_Status) Enum() *ClientBatchSubmitResponse_Status { p := new(ClientBatchSubmitResponse_Status) *p = x return p } func (x ClientBatchSubmitResponse_Status) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (ClientBatchSubmitResponse_Status) Descriptor() protoreflect.EnumDescriptor { return file_protobuf_client_batch_submit_pb2_client_batch_submit_proto_enumTypes[1].Descriptor() } func (ClientBatchSubmitResponse_Status) Type() protoreflect.EnumType { return &file_protobuf_client_batch_submit_pb2_client_batch_submit_proto_enumTypes[1] } func (x ClientBatchSubmitResponse_Status) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use ClientBatchSubmitResponse_Status.Descriptor instead. func (ClientBatchSubmitResponse_Status) EnumDescriptor() ([]byte, []int) { return file_protobuf_client_batch_submit_pb2_client_batch_submit_proto_rawDescGZIP(), []int{2, 0} } type ClientBatchStatusResponse_Status int32 const ( ClientBatchStatusResponse_STATUS_UNSET ClientBatchStatusResponse_Status = 0 ClientBatchStatusResponse_OK ClientBatchStatusResponse_Status = 1 ClientBatchStatusResponse_INTERNAL_ERROR ClientBatchStatusResponse_Status = 2 ClientBatchStatusResponse_NO_RESOURCE ClientBatchStatusResponse_Status = 5 ClientBatchStatusResponse_INVALID_ID ClientBatchStatusResponse_Status = 8 ) // Enum value maps for ClientBatchStatusResponse_Status. var ( ClientBatchStatusResponse_Status_name = map[int32]string{ 0: "STATUS_UNSET", 1: "OK", 2: "INTERNAL_ERROR", 5: "NO_RESOURCE", 8: "INVALID_ID", } ClientBatchStatusResponse_Status_value = map[string]int32{ "STATUS_UNSET": 0, "OK": 1, "INTERNAL_ERROR": 2, "NO_RESOURCE": 5, "INVALID_ID": 8, } ) func (x ClientBatchStatusResponse_Status) Enum() *ClientBatchStatusResponse_Status { p := new(ClientBatchStatusResponse_Status) *p = x return p } func (x ClientBatchStatusResponse_Status) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (ClientBatchStatusResponse_Status) Descriptor() protoreflect.EnumDescriptor { return file_protobuf_client_batch_submit_pb2_client_batch_submit_proto_enumTypes[2].Descriptor() } func (ClientBatchStatusResponse_Status) Type() protoreflect.EnumType { return &file_protobuf_client_batch_submit_pb2_client_batch_submit_proto_enumTypes[2] } func (x ClientBatchStatusResponse_Status) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use ClientBatchStatusResponse_Status.Descriptor instead. func (ClientBatchStatusResponse_Status) EnumDescriptor() ([]byte, []int) { return file_protobuf_client_batch_submit_pb2_client_batch_submit_proto_rawDescGZIP(), []int{4, 0} } // Information about the status of a batch submitted to the validator. // // Attributes: // batch_id: The id (header_signature) of the batch // status: The committed status of the batch // invalid_transactions: Info for transactions that failed, if any // // Statuses: // COMMITTED - the batch was accepted and has been committed to the chain // INVALID - the batch failed validation, it should be resubmitted // PENDING - the batch is still being processed // UNKNOWN - no status for the batch could be found (possibly invalid) type ClientBatchStatus struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields BatchId string `protobuf:"bytes,1,opt,name=batch_id,json=batchId,proto3" json:"batch_id,omitempty"` Status ClientBatchStatus_Status `protobuf:"varint,2,opt,name=status,proto3,enum=ClientBatchStatus_Status" json:"status,omitempty"` InvalidTransactions []*ClientBatchStatus_InvalidTransaction `protobuf:"bytes,3,rep,name=invalid_transactions,json=invalidTransactions,proto3" json:"invalid_transactions,omitempty"` } func (x *ClientBatchStatus) Reset() { *x = ClientBatchStatus{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_client_batch_submit_pb2_client_batch_submit_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ClientBatchStatus) String() string { return protoimpl.X.MessageStringOf(x) } func (*ClientBatchStatus) ProtoMessage() {} func (x *ClientBatchStatus) ProtoReflect() protoreflect.Message { mi := &file_protobuf_client_batch_submit_pb2_client_batch_submit_proto_msgTypes[0] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ClientBatchStatus.ProtoReflect.Descriptor instead. func (*ClientBatchStatus) Descriptor() ([]byte, []int) { return file_protobuf_client_batch_submit_pb2_client_batch_submit_proto_rawDescGZIP(), []int{0} } func (x *ClientBatchStatus) GetBatchId() string { if x != nil { return x.BatchId } return "" } func (x *ClientBatchStatus) GetStatus() ClientBatchStatus_Status { if x != nil { return x.Status } return ClientBatchStatus_STATUS_UNSET } func (x *ClientBatchStatus) GetInvalidTransactions() []*ClientBatchStatus_InvalidTransaction { if x != nil { return x.InvalidTransactions } return nil } // Submits a list of Batches to be added to the blockchain. type ClientBatchSubmitRequest struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Batches []*batch_pb2.Batch `protobuf:"bytes,1,rep,name=batches,proto3" json:"batches,omitempty"` } func (x *ClientBatchSubmitRequest) Reset() { *x = ClientBatchSubmitRequest{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_client_batch_submit_pb2_client_batch_submit_proto_msgTypes[1] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ClientBatchSubmitRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*ClientBatchSubmitRequest) ProtoMessage() {} func (x *ClientBatchSubmitRequest) ProtoReflect() protoreflect.Message { mi := &file_protobuf_client_batch_submit_pb2_client_batch_submit_proto_msgTypes[1] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ClientBatchSubmitRequest.ProtoReflect.Descriptor instead. func (*ClientBatchSubmitRequest) Descriptor() ([]byte, []int) { return file_protobuf_client_batch_submit_pb2_client_batch_submit_proto_rawDescGZIP(), []int{1} } func (x *ClientBatchSubmitRequest) GetBatches() []*batch_pb2.Batch { if x != nil { return x.Batches } return nil } // This is a response to a submission of one or more Batches. // Statuses: // * OK - everything with the request worked as expected // * INTERNAL_ERROR - general error, such as protobuf failing to deserialize // * INVALID_BATCH - the batch failed validation, likely due to a bad signature // * QUEUE_FULL - the batch is unable to be queued for processing, due to // a full processing queue. The batch may be submitted again. type ClientBatchSubmitResponse struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Status ClientBatchSubmitResponse_Status `protobuf:"varint,1,opt,name=status,proto3,enum=ClientBatchSubmitResponse_Status" json:"status,omitempty"` } func (x *ClientBatchSubmitResponse) Reset() { *x = ClientBatchSubmitResponse{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_client_batch_submit_pb2_client_batch_submit_proto_msgTypes[2] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ClientBatchSubmitResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*ClientBatchSubmitResponse) ProtoMessage() {} func (x *ClientBatchSubmitResponse) ProtoReflect() protoreflect.Message { mi := &file_protobuf_client_batch_submit_pb2_client_batch_submit_proto_msgTypes[2] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ClientBatchSubmitResponse.ProtoReflect.Descriptor instead. func (*ClientBatchSubmitResponse) Descriptor() ([]byte, []int) { return file_protobuf_client_batch_submit_pb2_client_batch_submit_proto_rawDescGZIP(), []int{2} } func (x *ClientBatchSubmitResponse) GetStatus() ClientBatchSubmitResponse_Status { if x != nil { return x.Status } return ClientBatchSubmitResponse_STATUS_UNSET } // A request for the status of one or more batches, specified by id. // If `wait` is set to true, the validator will wait to respond until all // batches are committed, or until the specified `timeout` in seconds has // elapsed. Defaults to 300. type ClientBatchStatusRequest struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields BatchIds []string `protobuf:"bytes,1,rep,name=batch_ids,json=batchIds,proto3" json:"batch_ids,omitempty"` Wait bool `protobuf:"varint,2,opt,name=wait,proto3" json:"wait,omitempty"` Timeout uint32 `protobuf:"varint,3,opt,name=timeout,proto3" json:"timeout,omitempty"` } func (x *ClientBatchStatusRequest) Reset() { *x = ClientBatchStatusRequest{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_client_batch_submit_pb2_client_batch_submit_proto_msgTypes[3] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ClientBatchStatusRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*ClientBatchStatusRequest) ProtoMessage() {} func (x *ClientBatchStatusRequest) ProtoReflect() protoreflect.Message { mi := &file_protobuf_client_batch_submit_pb2_client_batch_submit_proto_msgTypes[3] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ClientBatchStatusRequest.ProtoReflect.Descriptor instead. func (*ClientBatchStatusRequest) Descriptor() ([]byte, []int) { return file_protobuf_client_batch_submit_pb2_client_batch_submit_proto_rawDescGZIP(), []int{3} } func (x *ClientBatchStatusRequest) GetBatchIds() []string { if x != nil { return x.BatchIds } return nil } func (x *ClientBatchStatusRequest) GetWait() bool { if x != nil { return x.Wait } return false } func (x *ClientBatchStatusRequest) GetTimeout() uint32 { if x != nil { return x.Timeout } return 0 } // This is a response to a request for the status of specific batches. // Statuses: // * OK - everything with the request worked as expected // * INTERNAL_ERROR - general error, such as protobuf failing to deserialize // * NO_RESOURCE - the response contains no data, likely because // no ids were specified in the request type ClientBatchStatusResponse struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Status ClientBatchStatusResponse_Status `protobuf:"varint,1,opt,name=status,proto3,enum=ClientBatchStatusResponse_Status" json:"status,omitempty"` BatchStatuses []*ClientBatchStatus `protobuf:"bytes,2,rep,name=batch_statuses,json=batchStatuses,proto3" json:"batch_statuses,omitempty"` } func (x *ClientBatchStatusResponse) Reset() { *x = ClientBatchStatusResponse{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_client_batch_submit_pb2_client_batch_submit_proto_msgTypes[4] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ClientBatchStatusResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*ClientBatchStatusResponse) ProtoMessage() {} func (x *ClientBatchStatusResponse) ProtoReflect() protoreflect.Message { mi := &file_protobuf_client_batch_submit_pb2_client_batch_submit_proto_msgTypes[4] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ClientBatchStatusResponse.ProtoReflect.Descriptor instead. func (*ClientBatchStatusResponse) Descriptor() ([]byte, []int) { return file_protobuf_client_batch_submit_pb2_client_batch_submit_proto_rawDescGZIP(), []int{4} } func (x *ClientBatchStatusResponse) GetStatus() ClientBatchStatusResponse_Status { if x != nil { return x.Status } return ClientBatchStatusResponse_STATUS_UNSET } func (x *ClientBatchStatusResponse) GetBatchStatuses() []*ClientBatchStatus { if x != nil { return x.BatchStatuses } return nil } type ClientBatchStatus_InvalidTransaction struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields TransactionId string `protobuf:"bytes,1,opt,name=transaction_id,json=transactionId,proto3" json:"transaction_id,omitempty"` Message string `protobuf:"bytes,2,opt,name=message,proto3" json:"message,omitempty"` ExtendedData []byte `protobuf:"bytes,3,opt,name=extended_data,json=extendedData,proto3" json:"extended_data,omitempty"` } func (x *ClientBatchStatus_InvalidTransaction) Reset() { *x = ClientBatchStatus_InvalidTransaction{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_client_batch_submit_pb2_client_batch_submit_proto_msgTypes[5] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ClientBatchStatus_InvalidTransaction) String() string { return protoimpl.X.MessageStringOf(x) } func (*ClientBatchStatus_InvalidTransaction) ProtoMessage() {} func (x *ClientBatchStatus_InvalidTransaction) ProtoReflect() protoreflect.Message { mi := &file_protobuf_client_batch_submit_pb2_client_batch_submit_proto_msgTypes[5] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ClientBatchStatus_InvalidTransaction.ProtoReflect.Descriptor instead. func (*ClientBatchStatus_InvalidTransaction) Descriptor() ([]byte, []int) { return file_protobuf_client_batch_submit_pb2_client_batch_submit_proto_rawDescGZIP(), []int{0, 0} } func (x *ClientBatchStatus_InvalidTransaction) GetTransactionId() string { if x != nil { return x.TransactionId } return "" } func (x *ClientBatchStatus_InvalidTransaction) GetMessage() string { if x != nil { return x.Message } return "" } func (x *ClientBatchStatus_InvalidTransaction) GetExtendedData() []byte { if x != nil { return x.ExtendedData } return nil } var File_protobuf_client_batch_submit_pb2_client_batch_submit_proto protoreflect.FileDescriptor var file_protobuf_client_batch_submit_pb2_client_batch_submit_proto_rawDesc = []byte{ 0x0a, 0x3a, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x5f, 0x62, 0x61, 0x74, 0x63, 0x68, 0x5f, 0x73, 0x75, 0x62, 0x6d, 0x69, 0x74, 0x5f, 0x70, 0x62, 0x32, 0x2f, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x5f, 0x62, 0x61, 0x74, 0x63, 0x68, 0x5f, 0x73, 0x75, 0x62, 0x6d, 0x69, 0x74, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x1e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x62, 0x61, 0x74, 0x63, 0x68, 0x5f, 0x70, 0x62, 0x32, 0x2f, 0x62, 0x61, 0x74, 0x63, 0x68, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0x89, 0x03, 0x0a, 0x11, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x42, 0x61, 0x74, 0x63, 0x68, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, 0x19, 0x0a, 0x08, 0x62, 0x61, 0x74, 0x63, 0x68, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x62, 0x61, 0x74, 0x63, 0x68, 0x49, 0x64, 0x12, 0x31, 0x0a, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x19, 0x2e, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x42, 0x61, 0x74, 0x63, 0x68, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x2e, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x52, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, 0x58, 0x0a, 0x14, 0x69, 0x6e, 0x76, 0x61, 0x6c, 0x69, 0x64, 0x5f, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x18, 0x03, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x25, 0x2e, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x42, 0x61, 0x74, 0x63, 0x68, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x2e, 0x49, 0x6e, 0x76, 0x61, 0x6c, 0x69, 0x64, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x13, 0x69, 0x6e, 0x76, 0x61, 0x6c, 0x69, 0x64, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x1a, 0x7a, 0x0a, 0x12, 0x49, 0x6e, 0x76, 0x61, 0x6c, 0x69, 0x64, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x25, 0x0a, 0x0e, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0d, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x49, 0x64, 0x12, 0x18, 0x0a, 0x07, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x12, 0x23, 0x0a, 0x0d, 0x65, 0x78, 0x74, 0x65, 0x6e, 0x64, 0x65, 0x64, 0x5f, 0x64, 0x61, 0x74, 0x61, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0c, 0x65, 0x78, 0x74, 0x65, 0x6e, 0x64, 0x65, 0x64, 0x44, 0x61, 0x74, 0x61, 0x22, 0x50, 0x0a, 0x06, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, 0x10, 0x0a, 0x0c, 0x53, 0x54, 0x41, 0x54, 0x55, 0x53, 0x5f, 0x55, 0x4e, 0x53, 0x45, 0x54, 0x10, 0x00, 0x12, 0x0d, 0x0a, 0x09, 0x43, 0x4f, 0x4d, 0x4d, 0x49, 0x54, 0x54, 0x45, 0x44, 0x10, 0x01, 0x12, 0x0b, 0x0a, 0x07, 0x49, 0x4e, 0x56, 0x41, 0x4c, 0x49, 0x44, 0x10, 0x02, 0x12, 0x0b, 0x0a, 0x07, 0x50, 0x45, 0x4e, 0x44, 0x49, 0x4e, 0x47, 0x10, 0x03, 0x12, 0x0b, 0x0a, 0x07, 0x55, 0x4e, 0x4b, 0x4e, 0x4f, 0x57, 0x4e, 0x10, 0x04, 0x22, 0x3c, 0x0a, 0x18, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x42, 0x61, 0x74, 0x63, 0x68, 0x53, 0x75, 0x62, 0x6d, 0x69, 0x74, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x20, 0x0a, 0x07, 0x62, 0x61, 0x74, 0x63, 0x68, 0x65, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x06, 0x2e, 0x42, 0x61, 0x74, 0x63, 0x68, 0x52, 0x07, 0x62, 0x61, 0x74, 0x63, 0x68, 0x65, 0x73, 0x22, 0xb1, 0x01, 0x0a, 0x19, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x42, 0x61, 0x74, 0x63, 0x68, 0x53, 0x75, 0x62, 0x6d, 0x69, 0x74, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x39, 0x0a, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x21, 0x2e, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x42, 0x61, 0x74, 0x63, 0x68, 0x53, 0x75, 0x62, 0x6d, 0x69, 0x74, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x2e, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x52, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x22, 0x59, 0x0a, 0x06, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, 0x10, 0x0a, 0x0c, 0x53, 0x54, 0x41, 0x54, 0x55, 0x53, 0x5f, 0x55, 0x4e, 0x53, 0x45, 0x54, 0x10, 0x00, 0x12, 0x06, 0x0a, 0x02, 0x4f, 0x4b, 0x10, 0x01, 0x12, 0x12, 0x0a, 0x0e, 0x49, 0x4e, 0x54, 0x45, 0x52, 0x4e, 0x41, 0x4c, 0x5f, 0x45, 0x52, 0x52, 0x4f, 0x52, 0x10, 0x02, 0x12, 0x11, 0x0a, 0x0d, 0x49, 0x4e, 0x56, 0x41, 0x4c, 0x49, 0x44, 0x5f, 0x42, 0x41, 0x54, 0x43, 0x48, 0x10, 0x03, 0x12, 0x0e, 0x0a, 0x0a, 0x51, 0x55, 0x45, 0x55, 0x45, 0x5f, 0x46, 0x55, 0x4c, 0x4c, 0x10, 0x04, 0x22, 0x65, 0x0a, 0x18, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x42, 0x61, 0x74, 0x63, 0x68, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x1b, 0x0a, 0x09, 0x62, 0x61, 0x74, 0x63, 0x68, 0x5f, 0x69, 0x64, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x09, 0x52, 0x08, 0x62, 0x61, 0x74, 0x63, 0x68, 0x49, 0x64, 0x73, 0x12, 0x12, 0x0a, 0x04, 0x77, 0x61, 0x69, 0x74, 0x18, 0x02, 0x20, 0x01, 0x28, 0x08, 0x52, 0x04, 0x77, 0x61, 0x69, 0x74, 0x12, 0x18, 0x0a, 0x07, 0x74, 0x69, 0x6d, 0x65, 0x6f, 0x75, 0x74, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x07, 0x74, 0x69, 0x6d, 0x65, 0x6f, 0x75, 0x74, 0x22, 0xea, 0x01, 0x0a, 0x19, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x42, 0x61, 0x74, 0x63, 0x68, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x39, 0x0a, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x21, 0x2e, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x42, 0x61, 0x74, 0x63, 0x68, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x2e, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x52, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, 0x39, 0x0a, 0x0e, 0x62, 0x61, 0x74, 0x63, 0x68, 0x5f, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x65, 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x12, 0x2e, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x42, 0x61, 0x74, 0x63, 0x68, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x52, 0x0d, 0x62, 0x61, 0x74, 0x63, 0x68, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x65, 0x73, 0x22, 0x57, 0x0a, 0x06, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, 0x10, 0x0a, 0x0c, 0x53, 0x54, 0x41, 0x54, 0x55, 0x53, 0x5f, 0x55, 0x4e, 0x53, 0x45, 0x54, 0x10, 0x00, 0x12, 0x06, 0x0a, 0x02, 0x4f, 0x4b, 0x10, 0x01, 0x12, 0x12, 0x0a, 0x0e, 0x49, 0x4e, 0x54, 0x45, 0x52, 0x4e, 0x41, 0x4c, 0x5f, 0x45, 0x52, 0x52, 0x4f, 0x52, 0x10, 0x02, 0x12, 0x0f, 0x0a, 0x0b, 0x4e, 0x4f, 0x5f, 0x52, 0x45, 0x53, 0x4f, 0x55, 0x52, 0x43, 0x45, 0x10, 0x05, 0x12, 0x0e, 0x0a, 0x0a, 0x49, 0x4e, 0x56, 0x41, 0x4c, 0x49, 0x44, 0x5f, 0x49, 0x44, 0x10, 0x08, 0x42, 0x32, 0x0a, 0x15, 0x73, 0x61, 0x77, 0x74, 0x6f, 0x6f, 0x74, 0x68, 0x2e, 0x73, 0x64, 0x6b, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x50, 0x01, 0x5a, 0x17, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x5f, 0x62, 0x61, 0x74, 0x63, 0x68, 0x5f, 0x73, 0x75, 0x62, 0x6d, 0x69, 0x74, 0x5f, 0x70, 0x62, 0x32, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( file_protobuf_client_batch_submit_pb2_client_batch_submit_proto_rawDescOnce sync.Once file_protobuf_client_batch_submit_pb2_client_batch_submit_proto_rawDescData = file_protobuf_client_batch_submit_pb2_client_batch_submit_proto_rawDesc ) func file_protobuf_client_batch_submit_pb2_client_batch_submit_proto_rawDescGZIP() []byte { file_protobuf_client_batch_submit_pb2_client_batch_submit_proto_rawDescOnce.Do(func() { file_protobuf_client_batch_submit_pb2_client_batch_submit_proto_rawDescData = protoimpl.X.CompressGZIP(file_protobuf_client_batch_submit_pb2_client_batch_submit_proto_rawDescData) }) return file_protobuf_client_batch_submit_pb2_client_batch_submit_proto_rawDescData } var file_protobuf_client_batch_submit_pb2_client_batch_submit_proto_enumTypes = make([]protoimpl.EnumInfo, 3) var file_protobuf_client_batch_submit_pb2_client_batch_submit_proto_msgTypes = make([]protoimpl.MessageInfo, 6) var file_protobuf_client_batch_submit_pb2_client_batch_submit_proto_goTypes = []interface{}{ (ClientBatchStatus_Status)(0), // 0: ClientBatchStatus.Status (ClientBatchSubmitResponse_Status)(0), // 1: ClientBatchSubmitResponse.Status (ClientBatchStatusResponse_Status)(0), // 2: ClientBatchStatusResponse.Status (*ClientBatchStatus)(nil), // 3: ClientBatchStatus (*ClientBatchSubmitRequest)(nil), // 4: ClientBatchSubmitRequest (*ClientBatchSubmitResponse)(nil), // 5: ClientBatchSubmitResponse (*ClientBatchStatusRequest)(nil), // 6: ClientBatchStatusRequest (*ClientBatchStatusResponse)(nil), // 7: ClientBatchStatusResponse (*ClientBatchStatus_InvalidTransaction)(nil), // 8: ClientBatchStatus.InvalidTransaction (*batch_pb2.Batch)(nil), // 9: Batch } var file_protobuf_client_batch_submit_pb2_client_batch_submit_proto_depIdxs = []int32{ 0, // 0: ClientBatchStatus.status:type_name -> ClientBatchStatus.Status 8, // 1: ClientBatchStatus.invalid_transactions:type_name -> ClientBatchStatus.InvalidTransaction 9, // 2: ClientBatchSubmitRequest.batches:type_name -> Batch 1, // 3: ClientBatchSubmitResponse.status:type_name -> ClientBatchSubmitResponse.Status 2, // 4: ClientBatchStatusResponse.status:type_name -> ClientBatchStatusResponse.Status 3, // 5: ClientBatchStatusResponse.batch_statuses:type_name -> ClientBatchStatus 6, // [6:6] is the sub-list for method output_type 6, // [6:6] is the sub-list for method input_type 6, // [6:6] is the sub-list for extension type_name 6, // [6:6] is the sub-list for extension extendee 0, // [0:6] is the sub-list for field type_name } func init() { file_protobuf_client_batch_submit_pb2_client_batch_submit_proto_init() } func file_protobuf_client_batch_submit_pb2_client_batch_submit_proto_init() { if File_protobuf_client_batch_submit_pb2_client_batch_submit_proto != nil { return } if !protoimpl.UnsafeEnabled { file_protobuf_client_batch_submit_pb2_client_batch_submit_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ClientBatchStatus); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_client_batch_submit_pb2_client_batch_submit_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ClientBatchSubmitRequest); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_client_batch_submit_pb2_client_batch_submit_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ClientBatchSubmitResponse); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_client_batch_submit_pb2_client_batch_submit_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ClientBatchStatusRequest); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_client_batch_submit_pb2_client_batch_submit_proto_msgTypes[4].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ClientBatchStatusResponse); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_client_batch_submit_pb2_client_batch_submit_proto_msgTypes[5].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ClientBatchStatus_InvalidTransaction); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: file_protobuf_client_batch_submit_pb2_client_batch_submit_proto_rawDesc, NumEnums: 3, NumMessages: 6, NumExtensions: 0, NumServices: 0, }, GoTypes: file_protobuf_client_batch_submit_pb2_client_batch_submit_proto_goTypes, DependencyIndexes: file_protobuf_client_batch_submit_pb2_client_batch_submit_proto_depIdxs, EnumInfos: file_protobuf_client_batch_submit_pb2_client_batch_submit_proto_enumTypes, MessageInfos: file_protobuf_client_batch_submit_pb2_client_batch_submit_proto_msgTypes, }.Build() File_protobuf_client_batch_submit_pb2_client_batch_submit_proto = out.File file_protobuf_client_batch_submit_pb2_client_batch_submit_proto_rawDesc = nil file_protobuf_client_batch_submit_pb2_client_batch_submit_proto_goTypes = nil file_protobuf_client_batch_submit_pb2_client_batch_submit_proto_depIdxs = nil } <|start_filename|>protobuf/client_receipt_pb2/client_receipt.pb.go<|end_filename|> // Copyright 2017 Intel Corporation // // 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. // ----------------------------------------------------------------------------- // Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.25.0-devel // protoc v3.14.0 // source: protobuf/client_receipt_pb2/client_receipt.proto package client_receipt_pb2 import ( protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" transaction_receipt_pb2 "github.com/hyperledger/sawtooth-sdk-go/protobuf/transaction_receipt_pb2" reflect "reflect" sync "sync" ) const ( // Verify that this generated code is sufficiently up-to-date. _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) // Verify that runtime/protoimpl is sufficiently up-to-date. _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) type ClientReceiptGetResponse_Status int32 const ( ClientReceiptGetResponse_STATUS_UNSET ClientReceiptGetResponse_Status = 0 ClientReceiptGetResponse_OK ClientReceiptGetResponse_Status = 1 ClientReceiptGetResponse_INTERNAL_ERROR ClientReceiptGetResponse_Status = 2 ClientReceiptGetResponse_NO_RESOURCE ClientReceiptGetResponse_Status = 5 ClientReceiptGetResponse_INVALID_ID ClientReceiptGetResponse_Status = 8 ) // Enum value maps for ClientReceiptGetResponse_Status. var ( ClientReceiptGetResponse_Status_name = map[int32]string{ 0: "STATUS_UNSET", 1: "OK", 2: "INTERNAL_ERROR", 5: "NO_RESOURCE", 8: "INVALID_ID", } ClientReceiptGetResponse_Status_value = map[string]int32{ "STATUS_UNSET": 0, "OK": 1, "INTERNAL_ERROR": 2, "NO_RESOURCE": 5, "INVALID_ID": 8, } ) func (x ClientReceiptGetResponse_Status) Enum() *ClientReceiptGetResponse_Status { p := new(ClientReceiptGetResponse_Status) *p = x return p } func (x ClientReceiptGetResponse_Status) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (ClientReceiptGetResponse_Status) Descriptor() protoreflect.EnumDescriptor { return file_protobuf_client_receipt_pb2_client_receipt_proto_enumTypes[0].Descriptor() } func (ClientReceiptGetResponse_Status) Type() protoreflect.EnumType { return &file_protobuf_client_receipt_pb2_client_receipt_proto_enumTypes[0] } func (x ClientReceiptGetResponse_Status) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use ClientReceiptGetResponse_Status.Descriptor instead. func (ClientReceiptGetResponse_Status) EnumDescriptor() ([]byte, []int) { return file_protobuf_client_receipt_pb2_client_receipt_proto_rawDescGZIP(), []int{1, 0} } // Fetches a specific txn by its id (header_signature) from the blockchain. type ClientReceiptGetRequest struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields TransactionIds []string `protobuf:"bytes,1,rep,name=transaction_ids,json=transactionIds,proto3" json:"transaction_ids,omitempty"` } func (x *ClientReceiptGetRequest) Reset() { *x = ClientReceiptGetRequest{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_client_receipt_pb2_client_receipt_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ClientReceiptGetRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*ClientReceiptGetRequest) ProtoMessage() {} func (x *ClientReceiptGetRequest) ProtoReflect() protoreflect.Message { mi := &file_protobuf_client_receipt_pb2_client_receipt_proto_msgTypes[0] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ClientReceiptGetRequest.ProtoReflect.Descriptor instead. func (*ClientReceiptGetRequest) Descriptor() ([]byte, []int) { return file_protobuf_client_receipt_pb2_client_receipt_proto_rawDescGZIP(), []int{0} } func (x *ClientReceiptGetRequest) GetTransactionIds() []string { if x != nil { return x.TransactionIds } return nil } // A response that returns the txn receipt specified by a // ClientTransactionReceiptGetRequest. // // Statuses: // * OK - everything worked as expected, txn receipt has been fetched // * INTERNAL_ERROR - general error, such as protobuf failing to deserialize // * NO_RESOURCE - no receipt exists for the transaction id specified type ClientReceiptGetResponse struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Status ClientReceiptGetResponse_Status `protobuf:"varint,1,opt,name=status,proto3,enum=ClientReceiptGetResponse_Status" json:"status,omitempty"` Receipts []*transaction_receipt_pb2.TransactionReceipt `protobuf:"bytes,2,rep,name=receipts,proto3" json:"receipts,omitempty"` } func (x *ClientReceiptGetResponse) Reset() { *x = ClientReceiptGetResponse{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_client_receipt_pb2_client_receipt_proto_msgTypes[1] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ClientReceiptGetResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*ClientReceiptGetResponse) ProtoMessage() {} func (x *ClientReceiptGetResponse) ProtoReflect() protoreflect.Message { mi := &file_protobuf_client_receipt_pb2_client_receipt_proto_msgTypes[1] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ClientReceiptGetResponse.ProtoReflect.Descriptor instead. func (*ClientReceiptGetResponse) Descriptor() ([]byte, []int) { return file_protobuf_client_receipt_pb2_client_receipt_proto_rawDescGZIP(), []int{1} } func (x *ClientReceiptGetResponse) GetStatus() ClientReceiptGetResponse_Status { if x != nil { return x.Status } return ClientReceiptGetResponse_STATUS_UNSET } func (x *ClientReceiptGetResponse) GetReceipts() []*transaction_receipt_pb2.TransactionReceipt { if x != nil { return x.Receipts } return nil } var File_protobuf_client_receipt_pb2_client_receipt_proto protoreflect.FileDescriptor var file_protobuf_client_receipt_pb2_client_receipt_proto_rawDesc = []byte{ 0x0a, 0x30, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x5f, 0x72, 0x65, 0x63, 0x65, 0x69, 0x70, 0x74, 0x5f, 0x70, 0x62, 0x32, 0x2f, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x5f, 0x72, 0x65, 0x63, 0x65, 0x69, 0x70, 0x74, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x3a, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x72, 0x65, 0x63, 0x65, 0x69, 0x70, 0x74, 0x5f, 0x70, 0x62, 0x32, 0x2f, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x72, 0x65, 0x63, 0x65, 0x69, 0x70, 0x74, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0x42, 0x0a, 0x17, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x52, 0x65, 0x63, 0x65, 0x69, 0x70, 0x74, 0x47, 0x65, 0x74, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x27, 0x0a, 0x0f, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x69, 0x64, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x09, 0x52, 0x0e, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x49, 0x64, 0x73, 0x22, 0xde, 0x01, 0x0a, 0x18, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x52, 0x65, 0x63, 0x65, 0x69, 0x70, 0x74, 0x47, 0x65, 0x74, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x38, 0x0a, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x20, 0x2e, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x52, 0x65, 0x63, 0x65, 0x69, 0x70, 0x74, 0x47, 0x65, 0x74, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x2e, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x52, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, 0x2f, 0x0a, 0x08, 0x72, 0x65, 0x63, 0x65, 0x69, 0x70, 0x74, 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x13, 0x2e, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x63, 0x65, 0x69, 0x70, 0x74, 0x52, 0x08, 0x72, 0x65, 0x63, 0x65, 0x69, 0x70, 0x74, 0x73, 0x22, 0x57, 0x0a, 0x06, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, 0x10, 0x0a, 0x0c, 0x53, 0x54, 0x41, 0x54, 0x55, 0x53, 0x5f, 0x55, 0x4e, 0x53, 0x45, 0x54, 0x10, 0x00, 0x12, 0x06, 0x0a, 0x02, 0x4f, 0x4b, 0x10, 0x01, 0x12, 0x12, 0x0a, 0x0e, 0x49, 0x4e, 0x54, 0x45, 0x52, 0x4e, 0x41, 0x4c, 0x5f, 0x45, 0x52, 0x52, 0x4f, 0x52, 0x10, 0x02, 0x12, 0x0f, 0x0a, 0x0b, 0x4e, 0x4f, 0x5f, 0x52, 0x45, 0x53, 0x4f, 0x55, 0x52, 0x43, 0x45, 0x10, 0x05, 0x12, 0x0e, 0x0a, 0x0a, 0x49, 0x4e, 0x56, 0x41, 0x4c, 0x49, 0x44, 0x5f, 0x49, 0x44, 0x10, 0x08, 0x42, 0x2d, 0x0a, 0x15, 0x73, 0x61, 0x77, 0x74, 0x6f, 0x6f, 0x74, 0x68, 0x2e, 0x73, 0x64, 0x6b, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x50, 0x01, 0x5a, 0x12, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x5f, 0x72, 0x65, 0x63, 0x65, 0x69, 0x70, 0x74, 0x5f, 0x70, 0x62, 0x32, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( file_protobuf_client_receipt_pb2_client_receipt_proto_rawDescOnce sync.Once file_protobuf_client_receipt_pb2_client_receipt_proto_rawDescData = file_protobuf_client_receipt_pb2_client_receipt_proto_rawDesc ) func file_protobuf_client_receipt_pb2_client_receipt_proto_rawDescGZIP() []byte { file_protobuf_client_receipt_pb2_client_receipt_proto_rawDescOnce.Do(func() { file_protobuf_client_receipt_pb2_client_receipt_proto_rawDescData = protoimpl.X.CompressGZIP(file_protobuf_client_receipt_pb2_client_receipt_proto_rawDescData) }) return file_protobuf_client_receipt_pb2_client_receipt_proto_rawDescData } var file_protobuf_client_receipt_pb2_client_receipt_proto_enumTypes = make([]protoimpl.EnumInfo, 1) var file_protobuf_client_receipt_pb2_client_receipt_proto_msgTypes = make([]protoimpl.MessageInfo, 2) var file_protobuf_client_receipt_pb2_client_receipt_proto_goTypes = []interface{}{ (ClientReceiptGetResponse_Status)(0), // 0: ClientReceiptGetResponse.Status (*ClientReceiptGetRequest)(nil), // 1: ClientReceiptGetRequest (*ClientReceiptGetResponse)(nil), // 2: ClientReceiptGetResponse (*transaction_receipt_pb2.TransactionReceipt)(nil), // 3: TransactionReceipt } var file_protobuf_client_receipt_pb2_client_receipt_proto_depIdxs = []int32{ 0, // 0: ClientReceiptGetResponse.status:type_name -> ClientReceiptGetResponse.Status 3, // 1: ClientReceiptGetResponse.receipts:type_name -> TransactionReceipt 2, // [2:2] is the sub-list for method output_type 2, // [2:2] is the sub-list for method input_type 2, // [2:2] is the sub-list for extension type_name 2, // [2:2] is the sub-list for extension extendee 0, // [0:2] is the sub-list for field type_name } func init() { file_protobuf_client_receipt_pb2_client_receipt_proto_init() } func file_protobuf_client_receipt_pb2_client_receipt_proto_init() { if File_protobuf_client_receipt_pb2_client_receipt_proto != nil { return } if !protoimpl.UnsafeEnabled { file_protobuf_client_receipt_pb2_client_receipt_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ClientReceiptGetRequest); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_client_receipt_pb2_client_receipt_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ClientReceiptGetResponse); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: file_protobuf_client_receipt_pb2_client_receipt_proto_rawDesc, NumEnums: 1, NumMessages: 2, NumExtensions: 0, NumServices: 0, }, GoTypes: file_protobuf_client_receipt_pb2_client_receipt_proto_goTypes, DependencyIndexes: file_protobuf_client_receipt_pb2_client_receipt_proto_depIdxs, EnumInfos: file_protobuf_client_receipt_pb2_client_receipt_proto_enumTypes, MessageInfos: file_protobuf_client_receipt_pb2_client_receipt_proto_msgTypes, }.Build() File_protobuf_client_receipt_pb2_client_receipt_proto = out.File file_protobuf_client_receipt_pb2_client_receipt_proto_rawDesc = nil file_protobuf_client_receipt_pb2_client_receipt_proto_goTypes = nil file_protobuf_client_receipt_pb2_client_receipt_proto_depIdxs = nil } <|start_filename|>protobuf/client_peers_pb2/client_peers.pb.go<|end_filename|> // Copyright 2017 Intel Corporation // // 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. // ----------------------------------------------------------------------------- // Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.25.0-devel // protoc v3.14.0 // source: protobuf/client_peers_pb2/client_peers.proto package client_peer import ( protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" sync "sync" ) const ( // Verify that this generated code is sufficiently up-to-date. _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) // Verify that runtime/protoimpl is sufficiently up-to-date. _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) type ClientPeersGetResponse_Status int32 const ( ClientPeersGetResponse_STATUS_UNSET ClientPeersGetResponse_Status = 0 ClientPeersGetResponse_OK ClientPeersGetResponse_Status = 1 ClientPeersGetResponse_ERROR ClientPeersGetResponse_Status = 2 ) // Enum value maps for ClientPeersGetResponse_Status. var ( ClientPeersGetResponse_Status_name = map[int32]string{ 0: "STATUS_UNSET", 1: "OK", 2: "ERROR", } ClientPeersGetResponse_Status_value = map[string]int32{ "STATUS_UNSET": 0, "OK": 1, "ERROR": 2, } ) func (x ClientPeersGetResponse_Status) Enum() *ClientPeersGetResponse_Status { p := new(ClientPeersGetResponse_Status) *p = x return p } func (x ClientPeersGetResponse_Status) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (ClientPeersGetResponse_Status) Descriptor() protoreflect.EnumDescriptor { return file_protobuf_client_peers_pb2_client_peers_proto_enumTypes[0].Descriptor() } func (ClientPeersGetResponse_Status) Type() protoreflect.EnumType { return &file_protobuf_client_peers_pb2_client_peers_proto_enumTypes[0] } func (x ClientPeersGetResponse_Status) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use ClientPeersGetResponse_Status.Descriptor instead. func (ClientPeersGetResponse_Status) EnumDescriptor() ([]byte, []int) { return file_protobuf_client_peers_pb2_client_peers_proto_rawDescGZIP(), []int{1, 0} } type ClientPeersGetRequest struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields } func (x *ClientPeersGetRequest) Reset() { *x = ClientPeersGetRequest{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_client_peers_pb2_client_peers_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ClientPeersGetRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*ClientPeersGetRequest) ProtoMessage() {} func (x *ClientPeersGetRequest) ProtoReflect() protoreflect.Message { mi := &file_protobuf_client_peers_pb2_client_peers_proto_msgTypes[0] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ClientPeersGetRequest.ProtoReflect.Descriptor instead. func (*ClientPeersGetRequest) Descriptor() ([]byte, []int) { return file_protobuf_client_peers_pb2_client_peers_proto_rawDescGZIP(), []int{0} } type ClientPeersGetResponse struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Status ClientPeersGetResponse_Status `protobuf:"varint,1,opt,name=status,proto3,enum=ClientPeersGetResponse_Status" json:"status,omitempty"` Peers []string `protobuf:"bytes,2,rep,name=peers,proto3" json:"peers,omitempty"` } func (x *ClientPeersGetResponse) Reset() { *x = ClientPeersGetResponse{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_client_peers_pb2_client_peers_proto_msgTypes[1] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ClientPeersGetResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*ClientPeersGetResponse) ProtoMessage() {} func (x *ClientPeersGetResponse) ProtoReflect() protoreflect.Message { mi := &file_protobuf_client_peers_pb2_client_peers_proto_msgTypes[1] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ClientPeersGetResponse.ProtoReflect.Descriptor instead. func (*ClientPeersGetResponse) Descriptor() ([]byte, []int) { return file_protobuf_client_peers_pb2_client_peers_proto_rawDescGZIP(), []int{1} } func (x *ClientPeersGetResponse) GetStatus() ClientPeersGetResponse_Status { if x != nil { return x.Status } return ClientPeersGetResponse_STATUS_UNSET } func (x *ClientPeersGetResponse) GetPeers() []string { if x != nil { return x.Peers } return nil } var File_protobuf_client_peers_pb2_client_peers_proto protoreflect.FileDescriptor var file_protobuf_client_peers_pb2_client_peers_proto_rawDesc = []byte{ 0x0a, 0x2c, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x5f, 0x70, 0x65, 0x65, 0x72, 0x73, 0x5f, 0x70, 0x62, 0x32, 0x2f, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x5f, 0x70, 0x65, 0x65, 0x72, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0x17, 0x0a, 0x15, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x50, 0x65, 0x65, 0x72, 0x73, 0x47, 0x65, 0x74, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x22, 0x95, 0x01, 0x0a, 0x16, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x50, 0x65, 0x65, 0x72, 0x73, 0x47, 0x65, 0x74, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x36, 0x0a, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x1e, 0x2e, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x50, 0x65, 0x65, 0x72, 0x73, 0x47, 0x65, 0x74, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x2e, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x52, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, 0x14, 0x0a, 0x05, 0x70, 0x65, 0x65, 0x72, 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x09, 0x52, 0x05, 0x70, 0x65, 0x65, 0x72, 0x73, 0x22, 0x2d, 0x0a, 0x06, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, 0x10, 0x0a, 0x0c, 0x53, 0x54, 0x41, 0x54, 0x55, 0x53, 0x5f, 0x55, 0x4e, 0x53, 0x45, 0x54, 0x10, 0x00, 0x12, 0x06, 0x0a, 0x02, 0x4f, 0x4b, 0x10, 0x01, 0x12, 0x09, 0x0a, 0x05, 0x45, 0x52, 0x52, 0x4f, 0x52, 0x10, 0x02, 0x42, 0x26, 0x0a, 0x15, 0x73, 0x61, 0x77, 0x74, 0x6f, 0x6f, 0x74, 0x68, 0x2e, 0x73, 0x64, 0x6b, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x50, 0x01, 0x5a, 0x0b, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x5f, 0x70, 0x65, 0x65, 0x72, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( file_protobuf_client_peers_pb2_client_peers_proto_rawDescOnce sync.Once file_protobuf_client_peers_pb2_client_peers_proto_rawDescData = file_protobuf_client_peers_pb2_client_peers_proto_rawDesc ) func file_protobuf_client_peers_pb2_client_peers_proto_rawDescGZIP() []byte { file_protobuf_client_peers_pb2_client_peers_proto_rawDescOnce.Do(func() { file_protobuf_client_peers_pb2_client_peers_proto_rawDescData = protoimpl.X.CompressGZIP(file_protobuf_client_peers_pb2_client_peers_proto_rawDescData) }) return file_protobuf_client_peers_pb2_client_peers_proto_rawDescData } var file_protobuf_client_peers_pb2_client_peers_proto_enumTypes = make([]protoimpl.EnumInfo, 1) var file_protobuf_client_peers_pb2_client_peers_proto_msgTypes = make([]protoimpl.MessageInfo, 2) var file_protobuf_client_peers_pb2_client_peers_proto_goTypes = []interface{}{ (ClientPeersGetResponse_Status)(0), // 0: ClientPeersGetResponse.Status (*ClientPeersGetRequest)(nil), // 1: ClientPeersGetRequest (*ClientPeersGetResponse)(nil), // 2: ClientPeersGetResponse } var file_protobuf_client_peers_pb2_client_peers_proto_depIdxs = []int32{ 0, // 0: ClientPeersGetResponse.status:type_name -> ClientPeersGetResponse.Status 1, // [1:1] is the sub-list for method output_type 1, // [1:1] is the sub-list for method input_type 1, // [1:1] is the sub-list for extension type_name 1, // [1:1] is the sub-list for extension extendee 0, // [0:1] is the sub-list for field type_name } func init() { file_protobuf_client_peers_pb2_client_peers_proto_init() } func file_protobuf_client_peers_pb2_client_peers_proto_init() { if File_protobuf_client_peers_pb2_client_peers_proto != nil { return } if !protoimpl.UnsafeEnabled { file_protobuf_client_peers_pb2_client_peers_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ClientPeersGetRequest); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_client_peers_pb2_client_peers_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ClientPeersGetResponse); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: file_protobuf_client_peers_pb2_client_peers_proto_rawDesc, NumEnums: 1, NumMessages: 2, NumExtensions: 0, NumServices: 0, }, GoTypes: file_protobuf_client_peers_pb2_client_peers_proto_goTypes, DependencyIndexes: file_protobuf_client_peers_pb2_client_peers_proto_depIdxs, EnumInfos: file_protobuf_client_peers_pb2_client_peers_proto_enumTypes, MessageInfos: file_protobuf_client_peers_pb2_client_peers_proto_msgTypes, }.Build() File_protobuf_client_peers_pb2_client_peers_proto = out.File file_protobuf_client_peers_pb2_client_peers_proto_rawDesc = nil file_protobuf_client_peers_pb2_client_peers_proto_goTypes = nil file_protobuf_client_peers_pb2_client_peers_proto_depIdxs = nil } <|start_filename|>examples/xo_go/src/sawtooth_xo/handler/handler.go<|end_filename|> /** * Copyright 2017-2018 Intel Corporation * * 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 handler import ( "fmt" "github.com/hyperledger/sawtooth-sdk-go/examples/xo_go/src/sawtooth_xo/xo_payload" "github.com/hyperledger/sawtooth-sdk-go/examples/xo_go/src/sawtooth_xo/xo_state" "github.com/hyperledger/sawtooth-sdk-go/logging" "github.com/hyperledger/sawtooth-sdk-go/processor" "github.com/hyperledger/sawtooth-sdk-go/protobuf/processor_pb2" "strings" ) var logger *logging.Logger = logging.Get() type XoHandler struct { } func (self *XoHandler) FamilyName() string { return "xo" } func (self *XoHandler) FamilyVersions() []string { return []string{"1.0"} } func (self *XoHandler) Namespaces() []string { return []string{xo_state.Namespace} } func (self *XoHandler) Apply(request *processor_pb2.TpProcessRequest, context *processor.Context) error { // The xo player is defined as the signer of the transaction, so we unpack // the transaction header to obtain the signer's public key, which will be // used as the player's identity. header := request.GetHeader() player := header.GetSignerPublicKey() // The payload is sent to the transaction processor as bytes (just as it // appears in the transaction constructed by the transactor). We unpack // the payload into an XoPayload struct so we can access its fields. payload, err := xo_payload.FromBytes(request.GetPayload()) if err != nil { return err } xoState := xo_state.NewXoState(context) logger.Debugf("xo txn %v: player %v: payload: Name='%v', Action='%v', Space='%v'", request.Signature, player, payload.Name, payload.Action, payload.Space) switch payload.Action { case "create": err := validateCreate(xoState, payload.Name) if err != nil { return err } game := &xo_state.Game{ Board: "---------", State: "P1-NEXT", Player1: "", Player2: "", Name: payload.Name, } displayCreate(payload, player) return xoState.SetGame(payload.Name, game) case "delete": err := validateDelete(xoState, payload.Name) if err != nil { return err } return xoState.DeleteGame(payload.Name) case "take": err := validateTake(xoState, payload, player) if err != nil { return err } game, err := xoState.GetGame(payload.Name) if err != nil { return err } // Assign players if new game if game.Player1 == "" { game.Player1 = player } else if game.Player2 == "" { game.Player2 = player } if game.State == "P1-NEXT" && player == game.Player1 { boardRunes := []rune(game.Board) boardRunes[payload.Space-1] = 'X' game.Board = string(boardRunes) game.State = "P2-NEXT" } else if game.State == "P2-NEXT" && player == game.Player2 { boardRunes := []rune(game.Board) boardRunes[payload.Space-1] = 'O' game.Board = string(boardRunes) game.State = "P1-NEXT" } else { return &processor.InvalidTransactionError{ Msg: fmt.Sprintf("Not this player's turn: '%v'", player)} } if isWin(game.Board, 'X') { game.State = "P1-WIN" } else if isWin(game.Board, 'O') { game.State = "P2-WIN" } else if !strings.Contains(game.Board, "-") { game.State = "TIE" } displayTake(payload, player, game) return xoState.SetGame(payload.Name, game) default: return &processor.InvalidTransactionError{ Msg: fmt.Sprintf("Invalid Action : '%v'", payload.Action)} } } func validateCreate(xoState *xo_state.XoState, name string) error { game, err := xoState.GetGame(name) if err != nil { return err } if game != nil { return &processor.InvalidTransactionError{Msg: "Game already exists"} } return nil } func validateDelete(xoState *xo_state.XoState, name string) error { game, err := xoState.GetGame(name) if err != nil { return err } if game == nil { return &processor.InvalidTransactionError{Msg: "Delete requires an existing game"} } return nil } func validateTake(xoState *xo_state.XoState, payload *xo_payload.XoPayload, signer string) error { game, err := xoState.GetGame(payload.Name) if err != nil { return err } if game == nil { return &processor.InvalidTransactionError{Msg: "Take requires an existing game"} } if game.State == "P1-WIN" || game.State == "P2-WIN" || game.State == "TIE" { return &processor.InvalidTransactionError{Msg: "Game has ended"} } if game.State == "P1-WIN" || game.State == "P2-WIN" || game.State == "TIE" { return &processor.InvalidTransactionError{ Msg: "Invalid Action: Game has ended"} } if game.Board[payload.Space-1] != '-' { return &processor.InvalidTransactionError{Msg: "Space already taken"} } return nil } func isWin(board string, letter byte) bool { wins := [8][3]int{ {1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {1, 4, 7}, {2, 5, 8}, {3, 6, 9}, {1, 5, 9}, {3, 5, 7}, } for _, win := range wins { if board[win[0]-1] == letter && board[win[1]-1] == letter && board[win[2]-1] == letter { return true } } return false } func displayCreate(payload *xo_payload.XoPayload, signer string) { s := fmt.Sprintf("+ Player %s created game %s +", signer[:6], payload.Name) sLength := len(s) border := "+" + strings.Repeat("-", sLength-2) + "+" fmt.Println(border) fmt.Println(s) fmt.Println(border) } func displayTake(payload *xo_payload.XoPayload, signer string, game *xo_state.Game) { s := fmt.Sprintf("+ Player %s takes space %d +", signer[:6], payload.Space) sLength := len(s) border := "+" + strings.Repeat("-", sLength-2) + "+" blank := "+" + strings.Repeat(" ", sLength-2) + "+" g := center(fmt.Sprintf("%s: %s", "Game", game.Name), sLength) state := center(fmt.Sprintf("%s: %s", "State", game.State), sLength) p1 := center(fmt.Sprintf("%s: %s", "Player1", sliceIfLongEnough(game.Player1, 6)), sLength) p2 := center(fmt.Sprintf("%s: %s", "Player2", sliceIfLongEnough(game.Player2, 6)), sLength) space := strings.Repeat(" ", (sLength-2-11)/2) xoBoardLine := "+" + space + "---|---|---" + space + "+" xoBoardSpace := "+" + space + " %c | %c | %c " + space + "+\n" fmt.Println(border) fmt.Println(s) fmt.Println(blank) fmt.Println(g) fmt.Println(state) fmt.Println(p1) fmt.Println(p2) fmt.Printf(xoBoardSpace, blankify(game.Board[0]), blankify(game.Board[1]), blankify(game.Board[2])) fmt.Println(xoBoardLine) fmt.Printf(xoBoardSpace, blankify(game.Board[3]), blankify(game.Board[4]), blankify(game.Board[5])) fmt.Println(xoBoardLine) fmt.Printf(xoBoardSpace, blankify(game.Board[6]), blankify(game.Board[7]), blankify(game.Board[8])) fmt.Println(border) } func blankify(char byte) byte { if char == '-' { return ' ' } return char } func center(text string, width int) string { l := len(text) space := width - l - 2 if space%2 == 0 { s1 := strings.Repeat(" ", space/2) s2 := strings.Repeat(" ", space/2) return "+" + s1 + text + s2 + "+" } s1 := strings.Repeat(" ", space/2) s2 := strings.Repeat(" ", space/2+1) return "+" + s1 + text + s2 + "+" } func sliceIfLongEnough(text string, num int) string { if len(text) > num { return text[:num] } else if len(text) > 0 { return text[:len(text)-1] } return text } <|start_filename|>examples/intkey_go/src/sawtooth_intkey_client/list.go<|end_filename|> /** * Copyright 2018 Intel Corporation * * 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 main import ( "fmt" "github.com/jessevdk/go-flags" ) type List struct { Url string `long:"url" description:"Specify URL of REST API"` } func (args *List) Name() string { return "list" } func (args *List) KeyfilePassed() string { return "" } func (args *List) UrlPassed() string { return args.Url } func (args *List) Register(parent *flags.Command) error { _, err := parent.AddCommand(args.Name(), "Displays all intkey values", "Shows the values of all keys in intkey state.", args) if err != nil { return err } return nil } func (args *List) Run() error { // Construct client intkeyClient, err := GetClient(args, false) if err != nil { return err } pairs, err := intkeyClient.List() if err != nil { return err } for _, pair := range pairs { for k, v := range pair { fmt.Println(k, ": ", v) } } return nil } <|start_filename|>examples/intkey_go/src/sawtooth_intkey_client/constants.go<|end_filename|> /** * Copyright 2018 Intel Corporation * * 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 main const ( // String literals FAMILY_NAME string = "intkey" FAMILY_VERSION string = "1.0" DISTRIBUTION_NAME string = "sawtooth-intkey" DEFAULT_URL string = "http://127.0.0.1:8008" // Verbs VERB_SET string = "set" VERB_INC string = "inc" VERB_DEC string = "dec" // APIs BATCH_SUBMIT_API string = "batches" BATCH_STATUS_API string = "batch_statuses" STATE_API string = "state" // Content types CONTENT_TYPE_OCTET_STREAM string = "application/octet-stream" // Integer literals FAMILY_NAMESPACE_ADDRESS_LENGTH uint = 6 FAMILY_VERB_ADDRESS_LENGTH uint = 64 ) <|start_filename|>protobuf/client_list_control_pb2/client_list_control.pb.go<|end_filename|> // Copyright 2017 Intel Corporation // // 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. // ----------------------------------------------------------------------------- // Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.25.0-devel // protoc v3.14.0 // source: protobuf/client_list_control_pb2/client_list_control.proto package client_list_control_pb2 import ( protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" sync "sync" ) const ( // Verify that this generated code is sufficiently up-to-date. _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) // Verify that runtime/protoimpl is sufficiently up-to-date. _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) // Paging controls to be sent with List requests. // Attributes: // start: The id of a resource to start the page with // limit: The number of results per page, defaults to 100 and maxes out at 1000 type ClientPagingControls struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Start string `protobuf:"bytes,1,opt,name=start,proto3" json:"start,omitempty"` Limit int32 `protobuf:"varint,2,opt,name=limit,proto3" json:"limit,omitempty"` } func (x *ClientPagingControls) Reset() { *x = ClientPagingControls{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_client_list_control_pb2_client_list_control_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ClientPagingControls) String() string { return protoimpl.X.MessageStringOf(x) } func (*ClientPagingControls) ProtoMessage() {} func (x *ClientPagingControls) ProtoReflect() protoreflect.Message { mi := &file_protobuf_client_list_control_pb2_client_list_control_proto_msgTypes[0] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ClientPagingControls.ProtoReflect.Descriptor instead. func (*ClientPagingControls) Descriptor() ([]byte, []int) { return file_protobuf_client_list_control_pb2_client_list_control_proto_rawDescGZIP(), []int{0} } func (x *ClientPagingControls) GetStart() string { if x != nil { return x.Start } return "" } func (x *ClientPagingControls) GetLimit() int32 { if x != nil { return x.Limit } return 0 } // Information about the pagination used, sent back with List responses. // Attributes: // next: The id of the first resource in the next page // start: The id of the first resource in the returned page // limit: The number of results per page, defaults to 100 and maxes out at 1000 type ClientPagingResponse struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Next string `protobuf:"bytes,1,opt,name=next,proto3" json:"next,omitempty"` Start string `protobuf:"bytes,2,opt,name=start,proto3" json:"start,omitempty"` Limit int32 `protobuf:"varint,3,opt,name=limit,proto3" json:"limit,omitempty"` } func (x *ClientPagingResponse) Reset() { *x = ClientPagingResponse{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_client_list_control_pb2_client_list_control_proto_msgTypes[1] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ClientPagingResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*ClientPagingResponse) ProtoMessage() {} func (x *ClientPagingResponse) ProtoReflect() protoreflect.Message { mi := &file_protobuf_client_list_control_pb2_client_list_control_proto_msgTypes[1] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ClientPagingResponse.ProtoReflect.Descriptor instead. func (*ClientPagingResponse) Descriptor() ([]byte, []int) { return file_protobuf_client_list_control_pb2_client_list_control_proto_rawDescGZIP(), []int{1} } func (x *ClientPagingResponse) GetNext() string { if x != nil { return x.Next } return "" } func (x *ClientPagingResponse) GetStart() string { if x != nil { return x.Start } return "" } func (x *ClientPagingResponse) GetLimit() int32 { if x != nil { return x.Limit } return 0 } // Sorting controls to be sent with List requests. More than one can be sent. // If so, the first is used, and additional controls are tie-breakers. // Attributes: // keys: Nested set of keys to sort by (i.e. ['default, block_num']) // reverse: Whether or not to reverse the sort (i.e. descending order) type ClientSortControls struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Keys []string `protobuf:"bytes,1,rep,name=keys,proto3" json:"keys,omitempty"` Reverse bool `protobuf:"varint,2,opt,name=reverse,proto3" json:"reverse,omitempty"` } func (x *ClientSortControls) Reset() { *x = ClientSortControls{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_client_list_control_pb2_client_list_control_proto_msgTypes[2] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ClientSortControls) String() string { return protoimpl.X.MessageStringOf(x) } func (*ClientSortControls) ProtoMessage() {} func (x *ClientSortControls) ProtoReflect() protoreflect.Message { mi := &file_protobuf_client_list_control_pb2_client_list_control_proto_msgTypes[2] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ClientSortControls.ProtoReflect.Descriptor instead. func (*ClientSortControls) Descriptor() ([]byte, []int) { return file_protobuf_client_list_control_pb2_client_list_control_proto_rawDescGZIP(), []int{2} } func (x *ClientSortControls) GetKeys() []string { if x != nil { return x.Keys } return nil } func (x *ClientSortControls) GetReverse() bool { if x != nil { return x.Reverse } return false } var File_protobuf_client_list_control_pb2_client_list_control_proto protoreflect.FileDescriptor var file_protobuf_client_list_control_pb2_client_list_control_proto_rawDesc = []byte{ 0x0a, 0x3a, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x5f, 0x6c, 0x69, 0x73, 0x74, 0x5f, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x5f, 0x70, 0x62, 0x32, 0x2f, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x5f, 0x6c, 0x69, 0x73, 0x74, 0x5f, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0x42, 0x0a, 0x14, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x50, 0x61, 0x67, 0x69, 0x6e, 0x67, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x73, 0x12, 0x14, 0x0a, 0x05, 0x73, 0x74, 0x61, 0x72, 0x74, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x73, 0x74, 0x61, 0x72, 0x74, 0x12, 0x14, 0x0a, 0x05, 0x6c, 0x69, 0x6d, 0x69, 0x74, 0x18, 0x02, 0x20, 0x01, 0x28, 0x05, 0x52, 0x05, 0x6c, 0x69, 0x6d, 0x69, 0x74, 0x22, 0x56, 0x0a, 0x14, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x50, 0x61, 0x67, 0x69, 0x6e, 0x67, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x12, 0x0a, 0x04, 0x6e, 0x65, 0x78, 0x74, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x6e, 0x65, 0x78, 0x74, 0x12, 0x14, 0x0a, 0x05, 0x73, 0x74, 0x61, 0x72, 0x74, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x73, 0x74, 0x61, 0x72, 0x74, 0x12, 0x14, 0x0a, 0x05, 0x6c, 0x69, 0x6d, 0x69, 0x74, 0x18, 0x03, 0x20, 0x01, 0x28, 0x05, 0x52, 0x05, 0x6c, 0x69, 0x6d, 0x69, 0x74, 0x22, 0x42, 0x0a, 0x12, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x53, 0x6f, 0x72, 0x74, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x73, 0x12, 0x12, 0x0a, 0x04, 0x6b, 0x65, 0x79, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x09, 0x52, 0x04, 0x6b, 0x65, 0x79, 0x73, 0x12, 0x18, 0x0a, 0x07, 0x72, 0x65, 0x76, 0x65, 0x72, 0x73, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x08, 0x52, 0x07, 0x72, 0x65, 0x76, 0x65, 0x72, 0x73, 0x65, 0x42, 0x32, 0x0a, 0x15, 0x73, 0x61, 0x77, 0x74, 0x6f, 0x6f, 0x74, 0x68, 0x2e, 0x73, 0x64, 0x6b, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x50, 0x01, 0x5a, 0x17, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x5f, 0x6c, 0x69, 0x73, 0x74, 0x5f, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x5f, 0x70, 0x62, 0x32, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( file_protobuf_client_list_control_pb2_client_list_control_proto_rawDescOnce sync.Once file_protobuf_client_list_control_pb2_client_list_control_proto_rawDescData = file_protobuf_client_list_control_pb2_client_list_control_proto_rawDesc ) func file_protobuf_client_list_control_pb2_client_list_control_proto_rawDescGZIP() []byte { file_protobuf_client_list_control_pb2_client_list_control_proto_rawDescOnce.Do(func() { file_protobuf_client_list_control_pb2_client_list_control_proto_rawDescData = protoimpl.X.CompressGZIP(file_protobuf_client_list_control_pb2_client_list_control_proto_rawDescData) }) return file_protobuf_client_list_control_pb2_client_list_control_proto_rawDescData } var file_protobuf_client_list_control_pb2_client_list_control_proto_msgTypes = make([]protoimpl.MessageInfo, 3) var file_protobuf_client_list_control_pb2_client_list_control_proto_goTypes = []interface{}{ (*ClientPagingControls)(nil), // 0: ClientPagingControls (*ClientPagingResponse)(nil), // 1: ClientPagingResponse (*ClientSortControls)(nil), // 2: ClientSortControls } var file_protobuf_client_list_control_pb2_client_list_control_proto_depIdxs = []int32{ 0, // [0:0] is the sub-list for method output_type 0, // [0:0] is the sub-list for method input_type 0, // [0:0] is the sub-list for extension type_name 0, // [0:0] is the sub-list for extension extendee 0, // [0:0] is the sub-list for field type_name } func init() { file_protobuf_client_list_control_pb2_client_list_control_proto_init() } func file_protobuf_client_list_control_pb2_client_list_control_proto_init() { if File_protobuf_client_list_control_pb2_client_list_control_proto != nil { return } if !protoimpl.UnsafeEnabled { file_protobuf_client_list_control_pb2_client_list_control_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ClientPagingControls); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_client_list_control_pb2_client_list_control_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ClientPagingResponse); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_client_list_control_pb2_client_list_control_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ClientSortControls); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: file_protobuf_client_list_control_pb2_client_list_control_proto_rawDesc, NumEnums: 0, NumMessages: 3, NumExtensions: 0, NumServices: 0, }, GoTypes: file_protobuf_client_list_control_pb2_client_list_control_proto_goTypes, DependencyIndexes: file_protobuf_client_list_control_pb2_client_list_control_proto_depIdxs, MessageInfos: file_protobuf_client_list_control_pb2_client_list_control_proto_msgTypes, }.Build() File_protobuf_client_list_control_pb2_client_list_control_proto = out.File file_protobuf_client_list_control_pb2_client_list_control_proto_rawDesc = nil file_protobuf_client_list_control_pb2_client_list_control_proto_goTypes = nil file_protobuf_client_list_control_pb2_client_list_control_proto_depIdxs = nil } <|start_filename|>protobuf/processor_pb2/processor.pb.go<|end_filename|> // Copyright 2016 Intel Corporation // // 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. // ----------------------------------------------------------------------------- // Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.25.0-devel // protoc v3.14.0 // source: protobuf/processor_pb2/processor.proto package processor_pb2 import ( protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" transaction_pb2 "github.com/hyperledger/sawtooth-sdk-go/protobuf/transaction_pb2" reflect "reflect" sync "sync" ) const ( // Verify that this generated code is sufficiently up-to-date. _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) // Verify that runtime/protoimpl is sufficiently up-to-date. _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) type TpRegisterResponse_Status int32 const ( TpRegisterResponse_STATUS_UNSET TpRegisterResponse_Status = 0 TpRegisterResponse_OK TpRegisterResponse_Status = 1 TpRegisterResponse_ERROR TpRegisterResponse_Status = 2 ) // Enum value maps for TpRegisterResponse_Status. var ( TpRegisterResponse_Status_name = map[int32]string{ 0: "STATUS_UNSET", 1: "OK", 2: "ERROR", } TpRegisterResponse_Status_value = map[string]int32{ "STATUS_UNSET": 0, "OK": 1, "ERROR": 2, } ) func (x TpRegisterResponse_Status) Enum() *TpRegisterResponse_Status { p := new(TpRegisterResponse_Status) *p = x return p } func (x TpRegisterResponse_Status) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (TpRegisterResponse_Status) Descriptor() protoreflect.EnumDescriptor { return file_protobuf_processor_pb2_processor_proto_enumTypes[0].Descriptor() } func (TpRegisterResponse_Status) Type() protoreflect.EnumType { return &file_protobuf_processor_pb2_processor_proto_enumTypes[0] } func (x TpRegisterResponse_Status) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use TpRegisterResponse_Status.Descriptor instead. func (TpRegisterResponse_Status) EnumDescriptor() ([]byte, []int) { return file_protobuf_processor_pb2_processor_proto_rawDescGZIP(), []int{1, 0} } type TpUnregisterResponse_Status int32 const ( TpUnregisterResponse_STATUS_UNSET TpUnregisterResponse_Status = 0 TpUnregisterResponse_OK TpUnregisterResponse_Status = 1 TpUnregisterResponse_ERROR TpUnregisterResponse_Status = 2 ) // Enum value maps for TpUnregisterResponse_Status. var ( TpUnregisterResponse_Status_name = map[int32]string{ 0: "STATUS_UNSET", 1: "OK", 2: "ERROR", } TpUnregisterResponse_Status_value = map[string]int32{ "STATUS_UNSET": 0, "OK": 1, "ERROR": 2, } ) func (x TpUnregisterResponse_Status) Enum() *TpUnregisterResponse_Status { p := new(TpUnregisterResponse_Status) *p = x return p } func (x TpUnregisterResponse_Status) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (TpUnregisterResponse_Status) Descriptor() protoreflect.EnumDescriptor { return file_protobuf_processor_pb2_processor_proto_enumTypes[1].Descriptor() } func (TpUnregisterResponse_Status) Type() protoreflect.EnumType { return &file_protobuf_processor_pb2_processor_proto_enumTypes[1] } func (x TpUnregisterResponse_Status) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use TpUnregisterResponse_Status.Descriptor instead. func (TpUnregisterResponse_Status) EnumDescriptor() ([]byte, []int) { return file_protobuf_processor_pb2_processor_proto_rawDescGZIP(), []int{3, 0} } type TpProcessResponse_Status int32 const ( TpProcessResponse_STATUS_UNSET TpProcessResponse_Status = 0 TpProcessResponse_OK TpProcessResponse_Status = 1 TpProcessResponse_INVALID_TRANSACTION TpProcessResponse_Status = 2 TpProcessResponse_INTERNAL_ERROR TpProcessResponse_Status = 3 ) // Enum value maps for TpProcessResponse_Status. var ( TpProcessResponse_Status_name = map[int32]string{ 0: "STATUS_UNSET", 1: "OK", 2: "INVALID_TRANSACTION", 3: "INTERNAL_ERROR", } TpProcessResponse_Status_value = map[string]int32{ "STATUS_UNSET": 0, "OK": 1, "INVALID_TRANSACTION": 2, "INTERNAL_ERROR": 3, } ) func (x TpProcessResponse_Status) Enum() *TpProcessResponse_Status { p := new(TpProcessResponse_Status) *p = x return p } func (x TpProcessResponse_Status) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (TpProcessResponse_Status) Descriptor() protoreflect.EnumDescriptor { return file_protobuf_processor_pb2_processor_proto_enumTypes[2].Descriptor() } func (TpProcessResponse_Status) Type() protoreflect.EnumType { return &file_protobuf_processor_pb2_processor_proto_enumTypes[2] } func (x TpProcessResponse_Status) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use TpProcessResponse_Status.Descriptor instead. func (TpProcessResponse_Status) EnumDescriptor() ([]byte, []int) { return file_protobuf_processor_pb2_processor_proto_rawDescGZIP(), []int{5, 0} } // The registration request from the transaction processor to the // validator/executor type TpRegisterRequest struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // A settled upon name for the capabilities of the transaction processor. // For example: intkey, xo Family string `protobuf:"bytes,1,opt,name=family,proto3" json:"family,omitempty"` // The version supported. For example: // 1.0 for version 1.0 // 2.1 for version 2.1 Version string `protobuf:"bytes,2,opt,name=version,proto3" json:"version,omitempty"` // The namespaces this transaction processor expects to interact with // when processing transactions matching this specification; will be // enforced by the state API on the validator. Namespaces []string `protobuf:"bytes,4,rep,name=namespaces,proto3" json:"namespaces,omitempty"` // The maximum number of transactions that this transaction processor can // handle at once. MaxOccupancy uint32 `protobuf:"varint,5,opt,name=max_occupancy,json=maxOccupancy,proto3" json:"max_occupancy,omitempty"` } func (x *TpRegisterRequest) Reset() { *x = TpRegisterRequest{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_processor_pb2_processor_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *TpRegisterRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*TpRegisterRequest) ProtoMessage() {} func (x *TpRegisterRequest) ProtoReflect() protoreflect.Message { mi := &file_protobuf_processor_pb2_processor_proto_msgTypes[0] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use TpRegisterRequest.ProtoReflect.Descriptor instead. func (*TpRegisterRequest) Descriptor() ([]byte, []int) { return file_protobuf_processor_pb2_processor_proto_rawDescGZIP(), []int{0} } func (x *TpRegisterRequest) GetFamily() string { if x != nil { return x.Family } return "" } func (x *TpRegisterRequest) GetVersion() string { if x != nil { return x.Version } return "" } func (x *TpRegisterRequest) GetNamespaces() []string { if x != nil { return x.Namespaces } return nil } func (x *TpRegisterRequest) GetMaxOccupancy() uint32 { if x != nil { return x.MaxOccupancy } return 0 } // A response sent from the validator to the transaction processor // acknowledging the registration type TpRegisterResponse struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Status TpRegisterResponse_Status `protobuf:"varint,1,opt,name=status,proto3,enum=TpRegisterResponse_Status" json:"status,omitempty"` } func (x *TpRegisterResponse) Reset() { *x = TpRegisterResponse{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_processor_pb2_processor_proto_msgTypes[1] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *TpRegisterResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*TpRegisterResponse) ProtoMessage() {} func (x *TpRegisterResponse) ProtoReflect() protoreflect.Message { mi := &file_protobuf_processor_pb2_processor_proto_msgTypes[1] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use TpRegisterResponse.ProtoReflect.Descriptor instead. func (*TpRegisterResponse) Descriptor() ([]byte, []int) { return file_protobuf_processor_pb2_processor_proto_rawDescGZIP(), []int{1} } func (x *TpRegisterResponse) GetStatus() TpRegisterResponse_Status { if x != nil { return x.Status } return TpRegisterResponse_STATUS_UNSET } // The unregistration request from the transaction processor to the // validator/executor. The correct handlers are determined from the // zeromq identity of the tp, on the validator side. type TpUnregisterRequest struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields } func (x *TpUnregisterRequest) Reset() { *x = TpUnregisterRequest{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_processor_pb2_processor_proto_msgTypes[2] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *TpUnregisterRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*TpUnregisterRequest) ProtoMessage() {} func (x *TpUnregisterRequest) ProtoReflect() protoreflect.Message { mi := &file_protobuf_processor_pb2_processor_proto_msgTypes[2] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use TpUnregisterRequest.ProtoReflect.Descriptor instead. func (*TpUnregisterRequest) Descriptor() ([]byte, []int) { return file_protobuf_processor_pb2_processor_proto_rawDescGZIP(), []int{2} } // A response sent from the validator to the transaction processor // acknowledging the unregistration type TpUnregisterResponse struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Status TpUnregisterResponse_Status `protobuf:"varint,1,opt,name=status,proto3,enum=TpUnregisterResponse_Status" json:"status,omitempty"` } func (x *TpUnregisterResponse) Reset() { *x = TpUnregisterResponse{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_processor_pb2_processor_proto_msgTypes[3] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *TpUnregisterResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*TpUnregisterResponse) ProtoMessage() {} func (x *TpUnregisterResponse) ProtoReflect() protoreflect.Message { mi := &file_protobuf_processor_pb2_processor_proto_msgTypes[3] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use TpUnregisterResponse.ProtoReflect.Descriptor instead. func (*TpUnregisterResponse) Descriptor() ([]byte, []int) { return file_protobuf_processor_pb2_processor_proto_rawDescGZIP(), []int{3} } func (x *TpUnregisterResponse) GetStatus() TpUnregisterResponse_Status { if x != nil { return x.Status } return TpUnregisterResponse_STATUS_UNSET } // The request from the validator/executor of the transaction processor // to verify a transaction. type TpProcessRequest struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Header *transaction_pb2.TransactionHeader `protobuf:"bytes,1,opt,name=header,proto3" json:"header,omitempty"` // The transaction header Payload []byte `protobuf:"bytes,2,opt,name=payload,proto3" json:"payload,omitempty"` // The transaction payload Signature string `protobuf:"bytes,3,opt,name=signature,proto3" json:"signature,omitempty"` // The transaction header_signature ContextId string `protobuf:"bytes,4,opt,name=context_id,json=contextId,proto3" json:"context_id,omitempty"` // The context_id for state requests. } func (x *TpProcessRequest) Reset() { *x = TpProcessRequest{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_processor_pb2_processor_proto_msgTypes[4] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *TpProcessRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*TpProcessRequest) ProtoMessage() {} func (x *TpProcessRequest) ProtoReflect() protoreflect.Message { mi := &file_protobuf_processor_pb2_processor_proto_msgTypes[4] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use TpProcessRequest.ProtoReflect.Descriptor instead. func (*TpProcessRequest) Descriptor() ([]byte, []int) { return file_protobuf_processor_pb2_processor_proto_rawDescGZIP(), []int{4} } func (x *TpProcessRequest) GetHeader() *transaction_pb2.TransactionHeader { if x != nil { return x.Header } return nil } func (x *TpProcessRequest) GetPayload() []byte { if x != nil { return x.Payload } return nil } func (x *TpProcessRequest) GetSignature() string { if x != nil { return x.Signature } return "" } func (x *TpProcessRequest) GetContextId() string { if x != nil { return x.ContextId } return "" } // The response from the transaction processor to the validator/executor // used to respond about the validity of a transaction type TpProcessResponse struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Status TpProcessResponse_Status `protobuf:"varint,1,opt,name=status,proto3,enum=TpProcessResponse_Status" json:"status,omitempty"` // A message to include on responses in the cases where // status is either INVALID_TRANSACTION or INTERNAL_ERROR Message string `protobuf:"bytes,2,opt,name=message,proto3" json:"message,omitempty"` // Information that may be included with the response. // This information is an opaque, application-specific encoded block of // data that will be propagated back to the transaction submitter. ExtendedData []byte `protobuf:"bytes,3,opt,name=extended_data,json=extendedData,proto3" json:"extended_data,omitempty"` } func (x *TpProcessResponse) Reset() { *x = TpProcessResponse{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_processor_pb2_processor_proto_msgTypes[5] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *TpProcessResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*TpProcessResponse) ProtoMessage() {} func (x *TpProcessResponse) ProtoReflect() protoreflect.Message { mi := &file_protobuf_processor_pb2_processor_proto_msgTypes[5] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use TpProcessResponse.ProtoReflect.Descriptor instead. func (*TpProcessResponse) Descriptor() ([]byte, []int) { return file_protobuf_processor_pb2_processor_proto_rawDescGZIP(), []int{5} } func (x *TpProcessResponse) GetStatus() TpProcessResponse_Status { if x != nil { return x.Status } return TpProcessResponse_STATUS_UNSET } func (x *TpProcessResponse) GetMessage() string { if x != nil { return x.Message } return "" } func (x *TpProcessResponse) GetExtendedData() []byte { if x != nil { return x.ExtendedData } return nil } var File_protobuf_processor_pb2_processor_proto protoreflect.FileDescriptor var file_protobuf_processor_pb2_processor_proto_rawDesc = []byte{ 0x0a, 0x26, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x70, 0x72, 0x6f, 0x63, 0x65, 0x73, 0x73, 0x6f, 0x72, 0x5f, 0x70, 0x62, 0x32, 0x2f, 0x70, 0x72, 0x6f, 0x63, 0x65, 0x73, 0x73, 0x6f, 0x72, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x2a, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x70, 0x62, 0x32, 0x2f, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0x8a, 0x01, 0x0a, 0x11, 0x54, 0x70, 0x52, 0x65, 0x67, 0x69, 0x73, 0x74, 0x65, 0x72, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x16, 0x0a, 0x06, 0x66, 0x61, 0x6d, 0x69, 0x6c, 0x79, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, 0x66, 0x61, 0x6d, 0x69, 0x6c, 0x79, 0x12, 0x18, 0x0a, 0x07, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x12, 0x1e, 0x0a, 0x0a, 0x6e, 0x61, 0x6d, 0x65, 0x73, 0x70, 0x61, 0x63, 0x65, 0x73, 0x18, 0x04, 0x20, 0x03, 0x28, 0x09, 0x52, 0x0a, 0x6e, 0x61, 0x6d, 0x65, 0x73, 0x70, 0x61, 0x63, 0x65, 0x73, 0x12, 0x23, 0x0a, 0x0d, 0x6d, 0x61, 0x78, 0x5f, 0x6f, 0x63, 0x63, 0x75, 0x70, 0x61, 0x6e, 0x63, 0x79, 0x18, 0x05, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x0c, 0x6d, 0x61, 0x78, 0x4f, 0x63, 0x63, 0x75, 0x70, 0x61, 0x6e, 0x63, 0x79, 0x22, 0x77, 0x0a, 0x12, 0x54, 0x70, 0x52, 0x65, 0x67, 0x69, 0x73, 0x74, 0x65, 0x72, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x32, 0x0a, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x1a, 0x2e, 0x54, 0x70, 0x52, 0x65, 0x67, 0x69, 0x73, 0x74, 0x65, 0x72, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x2e, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x52, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x22, 0x2d, 0x0a, 0x06, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, 0x10, 0x0a, 0x0c, 0x53, 0x54, 0x41, 0x54, 0x55, 0x53, 0x5f, 0x55, 0x4e, 0x53, 0x45, 0x54, 0x10, 0x00, 0x12, 0x06, 0x0a, 0x02, 0x4f, 0x4b, 0x10, 0x01, 0x12, 0x09, 0x0a, 0x05, 0x45, 0x52, 0x52, 0x4f, 0x52, 0x10, 0x02, 0x22, 0x15, 0x0a, 0x13, 0x54, 0x70, 0x55, 0x6e, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x65, 0x72, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x22, 0x7b, 0x0a, 0x14, 0x54, 0x70, 0x55, 0x6e, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x65, 0x72, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x34, 0x0a, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x1c, 0x2e, 0x54, 0x70, 0x55, 0x6e, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x65, 0x72, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x2e, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x52, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x22, 0x2d, 0x0a, 0x06, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, 0x10, 0x0a, 0x0c, 0x53, 0x54, 0x41, 0x54, 0x55, 0x53, 0x5f, 0x55, 0x4e, 0x53, 0x45, 0x54, 0x10, 0x00, 0x12, 0x06, 0x0a, 0x02, 0x4f, 0x4b, 0x10, 0x01, 0x12, 0x09, 0x0a, 0x05, 0x45, 0x52, 0x52, 0x4f, 0x52, 0x10, 0x02, 0x22, 0x95, 0x01, 0x0a, 0x10, 0x54, 0x70, 0x50, 0x72, 0x6f, 0x63, 0x65, 0x73, 0x73, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x2a, 0x0a, 0x06, 0x68, 0x65, 0x61, 0x64, 0x65, 0x72, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x12, 0x2e, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x48, 0x65, 0x61, 0x64, 0x65, 0x72, 0x52, 0x06, 0x68, 0x65, 0x61, 0x64, 0x65, 0x72, 0x12, 0x18, 0x0a, 0x07, 0x70, 0x61, 0x79, 0x6c, 0x6f, 0x61, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x07, 0x70, 0x61, 0x79, 0x6c, 0x6f, 0x61, 0x64, 0x12, 0x1c, 0x0a, 0x09, 0x73, 0x69, 0x67, 0x6e, 0x61, 0x74, 0x75, 0x72, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, 0x73, 0x69, 0x67, 0x6e, 0x61, 0x74, 0x75, 0x72, 0x65, 0x12, 0x1d, 0x0a, 0x0a, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x78, 0x74, 0x5f, 0x69, 0x64, 0x18, 0x04, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x78, 0x74, 0x49, 0x64, 0x22, 0xd6, 0x01, 0x0a, 0x11, 0x54, 0x70, 0x50, 0x72, 0x6f, 0x63, 0x65, 0x73, 0x73, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x31, 0x0a, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x19, 0x2e, 0x54, 0x70, 0x50, 0x72, 0x6f, 0x63, 0x65, 0x73, 0x73, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x2e, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x52, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, 0x18, 0x0a, 0x07, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x12, 0x23, 0x0a, 0x0d, 0x65, 0x78, 0x74, 0x65, 0x6e, 0x64, 0x65, 0x64, 0x5f, 0x64, 0x61, 0x74, 0x61, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0c, 0x65, 0x78, 0x74, 0x65, 0x6e, 0x64, 0x65, 0x64, 0x44, 0x61, 0x74, 0x61, 0x22, 0x4f, 0x0a, 0x06, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, 0x10, 0x0a, 0x0c, 0x53, 0x54, 0x41, 0x54, 0x55, 0x53, 0x5f, 0x55, 0x4e, 0x53, 0x45, 0x54, 0x10, 0x00, 0x12, 0x06, 0x0a, 0x02, 0x4f, 0x4b, 0x10, 0x01, 0x12, 0x17, 0x0a, 0x13, 0x49, 0x4e, 0x56, 0x41, 0x4c, 0x49, 0x44, 0x5f, 0x54, 0x52, 0x41, 0x4e, 0x53, 0x41, 0x43, 0x54, 0x49, 0x4f, 0x4e, 0x10, 0x02, 0x12, 0x12, 0x0a, 0x0e, 0x49, 0x4e, 0x54, 0x45, 0x52, 0x4e, 0x41, 0x4c, 0x5f, 0x45, 0x52, 0x52, 0x4f, 0x52, 0x10, 0x03, 0x42, 0x28, 0x0a, 0x15, 0x73, 0x61, 0x77, 0x74, 0x6f, 0x6f, 0x74, 0x68, 0x2e, 0x73, 0x64, 0x6b, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x50, 0x01, 0x5a, 0x0d, 0x70, 0x72, 0x6f, 0x63, 0x65, 0x73, 0x73, 0x6f, 0x72, 0x5f, 0x70, 0x62, 0x32, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( file_protobuf_processor_pb2_processor_proto_rawDescOnce sync.Once file_protobuf_processor_pb2_processor_proto_rawDescData = file_protobuf_processor_pb2_processor_proto_rawDesc ) func file_protobuf_processor_pb2_processor_proto_rawDescGZIP() []byte { file_protobuf_processor_pb2_processor_proto_rawDescOnce.Do(func() { file_protobuf_processor_pb2_processor_proto_rawDescData = protoimpl.X.CompressGZIP(file_protobuf_processor_pb2_processor_proto_rawDescData) }) return file_protobuf_processor_pb2_processor_proto_rawDescData } var file_protobuf_processor_pb2_processor_proto_enumTypes = make([]protoimpl.EnumInfo, 3) var file_protobuf_processor_pb2_processor_proto_msgTypes = make([]protoimpl.MessageInfo, 6) var file_protobuf_processor_pb2_processor_proto_goTypes = []interface{}{ (TpRegisterResponse_Status)(0), // 0: TpRegisterResponse.Status (TpUnregisterResponse_Status)(0), // 1: TpUnregisterResponse.Status (TpProcessResponse_Status)(0), // 2: TpProcessResponse.Status (*TpRegisterRequest)(nil), // 3: TpRegisterRequest (*TpRegisterResponse)(nil), // 4: TpRegisterResponse (*TpUnregisterRequest)(nil), // 5: TpUnregisterRequest (*TpUnregisterResponse)(nil), // 6: TpUnregisterResponse (*TpProcessRequest)(nil), // 7: TpProcessRequest (*TpProcessResponse)(nil), // 8: TpProcessResponse (*transaction_pb2.TransactionHeader)(nil), // 9: TransactionHeader } var file_protobuf_processor_pb2_processor_proto_depIdxs = []int32{ 0, // 0: TpRegisterResponse.status:type_name -> TpRegisterResponse.Status 1, // 1: TpUnregisterResponse.status:type_name -> TpUnregisterResponse.Status 9, // 2: TpProcessRequest.header:type_name -> TransactionHeader 2, // 3: TpProcessResponse.status:type_name -> TpProcessResponse.Status 4, // [4:4] is the sub-list for method output_type 4, // [4:4] is the sub-list for method input_type 4, // [4:4] is the sub-list for extension type_name 4, // [4:4] is the sub-list for extension extendee 0, // [0:4] is the sub-list for field type_name } func init() { file_protobuf_processor_pb2_processor_proto_init() } func file_protobuf_processor_pb2_processor_proto_init() { if File_protobuf_processor_pb2_processor_proto != nil { return } if !protoimpl.UnsafeEnabled { file_protobuf_processor_pb2_processor_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*TpRegisterRequest); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_processor_pb2_processor_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*TpRegisterResponse); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_processor_pb2_processor_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*TpUnregisterRequest); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_processor_pb2_processor_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*TpUnregisterResponse); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_processor_pb2_processor_proto_msgTypes[4].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*TpProcessRequest); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_processor_pb2_processor_proto_msgTypes[5].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*TpProcessResponse); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: file_protobuf_processor_pb2_processor_proto_rawDesc, NumEnums: 3, NumMessages: 6, NumExtensions: 0, NumServices: 0, }, GoTypes: file_protobuf_processor_pb2_processor_proto_goTypes, DependencyIndexes: file_protobuf_processor_pb2_processor_proto_depIdxs, EnumInfos: file_protobuf_processor_pb2_processor_proto_enumTypes, MessageInfos: file_protobuf_processor_pb2_processor_proto_msgTypes, }.Build() File_protobuf_processor_pb2_processor_proto = out.File file_protobuf_processor_pb2_processor_proto_rawDesc = nil file_protobuf_processor_pb2_processor_proto_goTypes = nil file_protobuf_processor_pb2_processor_proto_depIdxs = nil } <|start_filename|>protobuf/genesis_pb2/genesis.pb.go<|end_filename|> // Copyright 2017 Intel Corporation // // 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. // ----------------------------------------------------------------------------- // Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.25.0-devel // protoc v3.14.0 // source: protobuf/genesis_pb2/genesis.proto package genesis_pb2 import ( protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" batch_pb2 "github.com/hyperledger/sawtooth-sdk-go/protobuf/batch_pb2" reflect "reflect" sync "sync" ) const ( // Verify that this generated code is sufficiently up-to-date. _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) // Verify that runtime/protoimpl is sufficiently up-to-date. _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) type GenesisData struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // The list of batches that will be applied during the genesis process Batches []*batch_pb2.Batch `protobuf:"bytes,1,rep,name=batches,proto3" json:"batches,omitempty"` } func (x *GenesisData) Reset() { *x = GenesisData{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_genesis_pb2_genesis_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *GenesisData) String() string { return protoimpl.X.MessageStringOf(x) } func (*GenesisData) ProtoMessage() {} func (x *GenesisData) ProtoReflect() protoreflect.Message { mi := &file_protobuf_genesis_pb2_genesis_proto_msgTypes[0] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use GenesisData.ProtoReflect.Descriptor instead. func (*GenesisData) Descriptor() ([]byte, []int) { return file_protobuf_genesis_pb2_genesis_proto_rawDescGZIP(), []int{0} } func (x *GenesisData) GetBatches() []*batch_pb2.Batch { if x != nil { return x.Batches } return nil } var File_protobuf_genesis_pb2_genesis_proto protoreflect.FileDescriptor var file_protobuf_genesis_pb2_genesis_proto_rawDesc = []byte{ 0x0a, 0x22, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x67, 0x65, 0x6e, 0x65, 0x73, 0x69, 0x73, 0x5f, 0x70, 0x62, 0x32, 0x2f, 0x67, 0x65, 0x6e, 0x65, 0x73, 0x69, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x1e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x62, 0x61, 0x74, 0x63, 0x68, 0x5f, 0x70, 0x62, 0x32, 0x2f, 0x62, 0x61, 0x74, 0x63, 0x68, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0x2f, 0x0a, 0x0b, 0x47, 0x65, 0x6e, 0x65, 0x73, 0x69, 0x73, 0x44, 0x61, 0x74, 0x61, 0x12, 0x20, 0x0a, 0x07, 0x62, 0x61, 0x74, 0x63, 0x68, 0x65, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x06, 0x2e, 0x42, 0x61, 0x74, 0x63, 0x68, 0x52, 0x07, 0x62, 0x61, 0x74, 0x63, 0x68, 0x65, 0x73, 0x42, 0x26, 0x0a, 0x15, 0x73, 0x61, 0x77, 0x74, 0x6f, 0x6f, 0x74, 0x68, 0x2e, 0x73, 0x64, 0x6b, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x50, 0x01, 0x5a, 0x0b, 0x67, 0x65, 0x6e, 0x65, 0x73, 0x69, 0x73, 0x5f, 0x70, 0x62, 0x32, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( file_protobuf_genesis_pb2_genesis_proto_rawDescOnce sync.Once file_protobuf_genesis_pb2_genesis_proto_rawDescData = file_protobuf_genesis_pb2_genesis_proto_rawDesc ) func file_protobuf_genesis_pb2_genesis_proto_rawDescGZIP() []byte { file_protobuf_genesis_pb2_genesis_proto_rawDescOnce.Do(func() { file_protobuf_genesis_pb2_genesis_proto_rawDescData = protoimpl.X.CompressGZIP(file_protobuf_genesis_pb2_genesis_proto_rawDescData) }) return file_protobuf_genesis_pb2_genesis_proto_rawDescData } var file_protobuf_genesis_pb2_genesis_proto_msgTypes = make([]protoimpl.MessageInfo, 1) var file_protobuf_genesis_pb2_genesis_proto_goTypes = []interface{}{ (*GenesisData)(nil), // 0: GenesisData (*batch_pb2.Batch)(nil), // 1: Batch } var file_protobuf_genesis_pb2_genesis_proto_depIdxs = []int32{ 1, // 0: GenesisData.batches:type_name -> Batch 1, // [1:1] is the sub-list for method output_type 1, // [1:1] is the sub-list for method input_type 1, // [1:1] is the sub-list for extension type_name 1, // [1:1] is the sub-list for extension extendee 0, // [0:1] is the sub-list for field type_name } func init() { file_protobuf_genesis_pb2_genesis_proto_init() } func file_protobuf_genesis_pb2_genesis_proto_init() { if File_protobuf_genesis_pb2_genesis_proto != nil { return } if !protoimpl.UnsafeEnabled { file_protobuf_genesis_pb2_genesis_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*GenesisData); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: file_protobuf_genesis_pb2_genesis_proto_rawDesc, NumEnums: 0, NumMessages: 1, NumExtensions: 0, NumServices: 0, }, GoTypes: file_protobuf_genesis_pb2_genesis_proto_goTypes, DependencyIndexes: file_protobuf_genesis_pb2_genesis_proto_depIdxs, MessageInfos: file_protobuf_genesis_pb2_genesis_proto_msgTypes, }.Build() File_protobuf_genesis_pb2_genesis_proto = out.File file_protobuf_genesis_pb2_genesis_proto_rawDesc = nil file_protobuf_genesis_pb2_genesis_proto_goTypes = nil file_protobuf_genesis_pb2_genesis_proto_depIdxs = nil } <|start_filename|>examples/intkey_go/src/sawtooth_intkey_client/set.go<|end_filename|> /** * Copyright 2018 Intel Corporation * * 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 main import ( "github.com/jessevdk/go-flags" "strconv" ) type Set struct { Args struct { Name string `positional-arg-name:"name" required:"true" description:"Name of key to set"` Value string `positional-arg-name:"value" required:"true" description:"Amount to set"` } `positional-args:"true"` Url string `long:"url" description:"Specify URL of REST API"` Keyfile string `long:"keyfile" description:"Identify file containing user's private key"` Wait uint `long:"wait" description:"Set time, in seconds, to wait for transaction to commit"` } func (args *Set) Name() string { return "set" } func (args *Set) KeyfilePassed() string { return args.Keyfile } func (args *Set) UrlPassed() string { return args.Url } func (args *Set) Register(parent *flags.Command) error { _, err := parent.AddCommand(args.Name(), "Sets an intkey value", "Sends an intkey transaction to set <name> to <value>.", args) if err != nil { return err } return nil } func (args *Set) Run() error { // Construct client name := args.Args.Name value, err := strconv.Atoi(args.Args.Value) if err != nil { return err } wait := args.Wait intkeyClient, err := GetClient(args, true) if err != nil { return err } _, err = intkeyClient.Set(name, uint(value), wait) return err } <|start_filename|>protobuf/authorization_pb2/authorization.pb.go<|end_filename|> // Copyright 2017 Intel Corporation // // 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. // ----------------------------------------------------------------------------- // Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.25.0-devel // protoc v3.14.0 // source: protobuf/authorization_pb2/authorization.proto package authorization_pb2 import ( protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" sync "sync" ) const ( // Verify that this generated code is sufficiently up-to-date. _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) // Verify that runtime/protoimpl is sufficiently up-to-date. _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) type RoleType int32 const ( RoleType_ROLE_TYPE_UNSET RoleType = 0 // A shorthand request for asking for all allowed roles. RoleType_ALL RoleType = 1 // Role defining validator to validator communication RoleType_NETWORK RoleType = 2 ) // Enum value maps for RoleType. var ( RoleType_name = map[int32]string{ 0: "ROLE_TYPE_UNSET", 1: "ALL", 2: "NETWORK", } RoleType_value = map[string]int32{ "ROLE_TYPE_UNSET": 0, "ALL": 1, "NETWORK": 2, } ) func (x RoleType) Enum() *RoleType { p := new(RoleType) *p = x return p } func (x RoleType) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (RoleType) Descriptor() protoreflect.EnumDescriptor { return file_protobuf_authorization_pb2_authorization_proto_enumTypes[0].Descriptor() } func (RoleType) Type() protoreflect.EnumType { return &file_protobuf_authorization_pb2_authorization_proto_enumTypes[0] } func (x RoleType) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use RoleType.Descriptor instead. func (RoleType) EnumDescriptor() ([]byte, []int) { return file_protobuf_authorization_pb2_authorization_proto_rawDescGZIP(), []int{0} } // Whether the connection can participate in authorization type ConnectionResponse_Status int32 const ( ConnectionResponse_STATUS_UNSET ConnectionResponse_Status = 0 ConnectionResponse_OK ConnectionResponse_Status = 1 ConnectionResponse_ERROR ConnectionResponse_Status = 2 ) // Enum value maps for ConnectionResponse_Status. var ( ConnectionResponse_Status_name = map[int32]string{ 0: "STATUS_UNSET", 1: "OK", 2: "ERROR", } ConnectionResponse_Status_value = map[string]int32{ "STATUS_UNSET": 0, "OK": 1, "ERROR": 2, } ) func (x ConnectionResponse_Status) Enum() *ConnectionResponse_Status { p := new(ConnectionResponse_Status) *p = x return p } func (x ConnectionResponse_Status) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (ConnectionResponse_Status) Descriptor() protoreflect.EnumDescriptor { return file_protobuf_authorization_pb2_authorization_proto_enumTypes[1].Descriptor() } func (ConnectionResponse_Status) Type() protoreflect.EnumType { return &file_protobuf_authorization_pb2_authorization_proto_enumTypes[1] } func (x ConnectionResponse_Status) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use ConnectionResponse_Status.Descriptor instead. func (ConnectionResponse_Status) EnumDescriptor() ([]byte, []int) { return file_protobuf_authorization_pb2_authorization_proto_rawDescGZIP(), []int{1, 0} } //Authorization Type required for the authorization procedure type ConnectionResponse_AuthorizationType int32 const ( ConnectionResponse_AUTHORIZATION_TYPE_UNSET ConnectionResponse_AuthorizationType = 0 ConnectionResponse_TRUST ConnectionResponse_AuthorizationType = 1 ConnectionResponse_CHALLENGE ConnectionResponse_AuthorizationType = 2 ) // Enum value maps for ConnectionResponse_AuthorizationType. var ( ConnectionResponse_AuthorizationType_name = map[int32]string{ 0: "AUTHORIZATION_TYPE_UNSET", 1: "TRUST", 2: "CHALLENGE", } ConnectionResponse_AuthorizationType_value = map[string]int32{ "AUTHORIZATION_TYPE_UNSET": 0, "TRUST": 1, "CHALLENGE": 2, } ) func (x ConnectionResponse_AuthorizationType) Enum() *ConnectionResponse_AuthorizationType { p := new(ConnectionResponse_AuthorizationType) *p = x return p } func (x ConnectionResponse_AuthorizationType) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (ConnectionResponse_AuthorizationType) Descriptor() protoreflect.EnumDescriptor { return file_protobuf_authorization_pb2_authorization_proto_enumTypes[2].Descriptor() } func (ConnectionResponse_AuthorizationType) Type() protoreflect.EnumType { return &file_protobuf_authorization_pb2_authorization_proto_enumTypes[2] } func (x ConnectionResponse_AuthorizationType) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use ConnectionResponse_AuthorizationType.Descriptor instead. func (ConnectionResponse_AuthorizationType) EnumDescriptor() ([]byte, []int) { return file_protobuf_authorization_pb2_authorization_proto_rawDescGZIP(), []int{1, 1} } type ConnectionRequest struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // This is the first message that must be sent to start off authorization. // The endpoint of the connection. Endpoint string `protobuf:"bytes,1,opt,name=endpoint,proto3" json:"endpoint,omitempty"` } func (x *ConnectionRequest) Reset() { *x = ConnectionRequest{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_authorization_pb2_authorization_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ConnectionRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*ConnectionRequest) ProtoMessage() {} func (x *ConnectionRequest) ProtoReflect() protoreflect.Message { mi := &file_protobuf_authorization_pb2_authorization_proto_msgTypes[0] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ConnectionRequest.ProtoReflect.Descriptor instead. func (*ConnectionRequest) Descriptor() ([]byte, []int) { return file_protobuf_authorization_pb2_authorization_proto_rawDescGZIP(), []int{0} } func (x *ConnectionRequest) GetEndpoint() string { if x != nil { return x.Endpoint } return "" } type ConnectionResponse struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Roles []*ConnectionResponse_RoleEntry `protobuf:"bytes,1,rep,name=roles,proto3" json:"roles,omitempty"` Status ConnectionResponse_Status `protobuf:"varint,2,opt,name=status,proto3,enum=ConnectionResponse_Status" json:"status,omitempty"` } func (x *ConnectionResponse) Reset() { *x = ConnectionResponse{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_authorization_pb2_authorization_proto_msgTypes[1] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ConnectionResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*ConnectionResponse) ProtoMessage() {} func (x *ConnectionResponse) ProtoReflect() protoreflect.Message { mi := &file_protobuf_authorization_pb2_authorization_proto_msgTypes[1] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ConnectionResponse.ProtoReflect.Descriptor instead. func (*ConnectionResponse) Descriptor() ([]byte, []int) { return file_protobuf_authorization_pb2_authorization_proto_rawDescGZIP(), []int{1} } func (x *ConnectionResponse) GetRoles() []*ConnectionResponse_RoleEntry { if x != nil { return x.Roles } return nil } func (x *ConnectionResponse) GetStatus() ConnectionResponse_Status { if x != nil { return x.Status } return ConnectionResponse_STATUS_UNSET } type AuthorizationTrustRequest struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // A set of requested RoleTypes Roles []RoleType `protobuf:"varint,1,rep,packed,name=roles,proto3,enum=RoleType" json:"roles,omitempty"` PublicKey string `protobuf:"bytes,2,opt,name=public_key,json=publicKey,proto3" json:"public_key,omitempty"` } func (x *AuthorizationTrustRequest) Reset() { *x = AuthorizationTrustRequest{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_authorization_pb2_authorization_proto_msgTypes[2] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *AuthorizationTrustRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*AuthorizationTrustRequest) ProtoMessage() {} func (x *AuthorizationTrustRequest) ProtoReflect() protoreflect.Message { mi := &file_protobuf_authorization_pb2_authorization_proto_msgTypes[2] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use AuthorizationTrustRequest.ProtoReflect.Descriptor instead. func (*AuthorizationTrustRequest) Descriptor() ([]byte, []int) { return file_protobuf_authorization_pb2_authorization_proto_rawDescGZIP(), []int{2} } func (x *AuthorizationTrustRequest) GetRoles() []RoleType { if x != nil { return x.Roles } return nil } func (x *AuthorizationTrustRequest) GetPublicKey() string { if x != nil { return x.PublicKey } return "" } type AuthorizationTrustResponse struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // The actual set the requester has access to Roles []RoleType `protobuf:"varint,1,rep,packed,name=roles,proto3,enum=RoleType" json:"roles,omitempty"` } func (x *AuthorizationTrustResponse) Reset() { *x = AuthorizationTrustResponse{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_authorization_pb2_authorization_proto_msgTypes[3] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *AuthorizationTrustResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*AuthorizationTrustResponse) ProtoMessage() {} func (x *AuthorizationTrustResponse) ProtoReflect() protoreflect.Message { mi := &file_protobuf_authorization_pb2_authorization_proto_msgTypes[3] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use AuthorizationTrustResponse.ProtoReflect.Descriptor instead. func (*AuthorizationTrustResponse) Descriptor() ([]byte, []int) { return file_protobuf_authorization_pb2_authorization_proto_rawDescGZIP(), []int{3} } func (x *AuthorizationTrustResponse) GetRoles() []RoleType { if x != nil { return x.Roles } return nil } type AuthorizationViolation struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // The Role the requester did not have access to Violation RoleType `protobuf:"varint,1,opt,name=violation,proto3,enum=RoleType" json:"violation,omitempty"` } func (x *AuthorizationViolation) Reset() { *x = AuthorizationViolation{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_authorization_pb2_authorization_proto_msgTypes[4] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *AuthorizationViolation) String() string { return protoimpl.X.MessageStringOf(x) } func (*AuthorizationViolation) ProtoMessage() {} func (x *AuthorizationViolation) ProtoReflect() protoreflect.Message { mi := &file_protobuf_authorization_pb2_authorization_proto_msgTypes[4] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use AuthorizationViolation.ProtoReflect.Descriptor instead. func (*AuthorizationViolation) Descriptor() ([]byte, []int) { return file_protobuf_authorization_pb2_authorization_proto_rawDescGZIP(), []int{4} } func (x *AuthorizationViolation) GetViolation() RoleType { if x != nil { return x.Violation } return RoleType_ROLE_TYPE_UNSET } type AuthorizationChallengeRequest struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields } func (x *AuthorizationChallengeRequest) Reset() { *x = AuthorizationChallengeRequest{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_authorization_pb2_authorization_proto_msgTypes[5] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *AuthorizationChallengeRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*AuthorizationChallengeRequest) ProtoMessage() {} func (x *AuthorizationChallengeRequest) ProtoReflect() protoreflect.Message { mi := &file_protobuf_authorization_pb2_authorization_proto_msgTypes[5] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use AuthorizationChallengeRequest.ProtoReflect.Descriptor instead. func (*AuthorizationChallengeRequest) Descriptor() ([]byte, []int) { return file_protobuf_authorization_pb2_authorization_proto_rawDescGZIP(), []int{5} } type AuthorizationChallengeResponse struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // Random payload that the connecting node must sign Payload []byte `protobuf:"bytes,1,opt,name=payload,proto3" json:"payload,omitempty"` } func (x *AuthorizationChallengeResponse) Reset() { *x = AuthorizationChallengeResponse{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_authorization_pb2_authorization_proto_msgTypes[6] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *AuthorizationChallengeResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*AuthorizationChallengeResponse) ProtoMessage() {} func (x *AuthorizationChallengeResponse) ProtoReflect() protoreflect.Message { mi := &file_protobuf_authorization_pb2_authorization_proto_msgTypes[6] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use AuthorizationChallengeResponse.ProtoReflect.Descriptor instead. func (*AuthorizationChallengeResponse) Descriptor() ([]byte, []int) { return file_protobuf_authorization_pb2_authorization_proto_rawDescGZIP(), []int{6} } func (x *AuthorizationChallengeResponse) GetPayload() []byte { if x != nil { return x.Payload } return nil } type AuthorizationChallengeSubmit struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // public key of node PublicKey string `protobuf:"bytes,1,opt,name=public_key,json=publicKey,proto3" json:"public_key,omitempty"` // signature derived from signing the challenge payload Signature string `protobuf:"bytes,3,opt,name=signature,proto3" json:"signature,omitempty"` // A set of requested Roles Roles []RoleType `protobuf:"varint,4,rep,packed,name=roles,proto3,enum=RoleType" json:"roles,omitempty"` } func (x *AuthorizationChallengeSubmit) Reset() { *x = AuthorizationChallengeSubmit{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_authorization_pb2_authorization_proto_msgTypes[7] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *AuthorizationChallengeSubmit) String() string { return protoimpl.X.MessageStringOf(x) } func (*AuthorizationChallengeSubmit) ProtoMessage() {} func (x *AuthorizationChallengeSubmit) ProtoReflect() protoreflect.Message { mi := &file_protobuf_authorization_pb2_authorization_proto_msgTypes[7] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use AuthorizationChallengeSubmit.ProtoReflect.Descriptor instead. func (*AuthorizationChallengeSubmit) Descriptor() ([]byte, []int) { return file_protobuf_authorization_pb2_authorization_proto_rawDescGZIP(), []int{7} } func (x *AuthorizationChallengeSubmit) GetPublicKey() string { if x != nil { return x.PublicKey } return "" } func (x *AuthorizationChallengeSubmit) GetSignature() string { if x != nil { return x.Signature } return "" } func (x *AuthorizationChallengeSubmit) GetRoles() []RoleType { if x != nil { return x.Roles } return nil } type AuthorizationChallengeResult struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // The approved roles for that connection Roles []RoleType `protobuf:"varint,1,rep,packed,name=roles,proto3,enum=RoleType" json:"roles,omitempty"` } func (x *AuthorizationChallengeResult) Reset() { *x = AuthorizationChallengeResult{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_authorization_pb2_authorization_proto_msgTypes[8] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *AuthorizationChallengeResult) String() string { return protoimpl.X.MessageStringOf(x) } func (*AuthorizationChallengeResult) ProtoMessage() {} func (x *AuthorizationChallengeResult) ProtoReflect() protoreflect.Message { mi := &file_protobuf_authorization_pb2_authorization_proto_msgTypes[8] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use AuthorizationChallengeResult.ProtoReflect.Descriptor instead. func (*AuthorizationChallengeResult) Descriptor() ([]byte, []int) { return file_protobuf_authorization_pb2_authorization_proto_rawDescGZIP(), []int{8} } func (x *AuthorizationChallengeResult) GetRoles() []RoleType { if x != nil { return x.Roles } return nil } type ConnectionResponse_RoleEntry struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // The role type for this role entry Role RoleType `protobuf:"varint,1,opt,name=role,proto3,enum=RoleType" json:"role,omitempty"` // The Authorization Type required for the above role AuthType ConnectionResponse_AuthorizationType `protobuf:"varint,2,opt,name=auth_type,json=authType,proto3,enum=ConnectionResponse_AuthorizationType" json:"auth_type,omitempty"` } func (x *ConnectionResponse_RoleEntry) Reset() { *x = ConnectionResponse_RoleEntry{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_authorization_pb2_authorization_proto_msgTypes[9] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ConnectionResponse_RoleEntry) String() string { return protoimpl.X.MessageStringOf(x) } func (*ConnectionResponse_RoleEntry) ProtoMessage() {} func (x *ConnectionResponse_RoleEntry) ProtoReflect() protoreflect.Message { mi := &file_protobuf_authorization_pb2_authorization_proto_msgTypes[9] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ConnectionResponse_RoleEntry.ProtoReflect.Descriptor instead. func (*ConnectionResponse_RoleEntry) Descriptor() ([]byte, []int) { return file_protobuf_authorization_pb2_authorization_proto_rawDescGZIP(), []int{1, 0} } func (x *ConnectionResponse_RoleEntry) GetRole() RoleType { if x != nil { return x.Role } return RoleType_ROLE_TYPE_UNSET } func (x *ConnectionResponse_RoleEntry) GetAuthType() ConnectionResponse_AuthorizationType { if x != nil { return x.AuthType } return ConnectionResponse_AUTHORIZATION_TYPE_UNSET } var File_protobuf_authorization_pb2_authorization_proto protoreflect.FileDescriptor var file_protobuf_authorization_pb2_authorization_proto_rawDesc = []byte{ 0x0a, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x61, 0x75, 0x74, 0x68, 0x6f, 0x72, 0x69, 0x7a, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x70, 0x62, 0x32, 0x2f, 0x61, 0x75, 0x74, 0x68, 0x6f, 0x72, 0x69, 0x7a, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0x2f, 0x0a, 0x11, 0x43, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x1a, 0x0a, 0x08, 0x65, 0x6e, 0x64, 0x70, 0x6f, 0x69, 0x6e, 0x74, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x65, 0x6e, 0x64, 0x70, 0x6f, 0x69, 0x6e, 0x74, 0x22, 0xe9, 0x02, 0x0a, 0x12, 0x43, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x33, 0x0a, 0x05, 0x72, 0x6f, 0x6c, 0x65, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x1d, 0x2e, 0x43, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x2e, 0x52, 0x6f, 0x6c, 0x65, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x52, 0x05, 0x72, 0x6f, 0x6c, 0x65, 0x73, 0x12, 0x32, 0x0a, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x1a, 0x2e, 0x43, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x2e, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x52, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x1a, 0x6e, 0x0a, 0x09, 0x52, 0x6f, 0x6c, 0x65, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x12, 0x1d, 0x0a, 0x04, 0x72, 0x6f, 0x6c, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x09, 0x2e, 0x52, 0x6f, 0x6c, 0x65, 0x54, 0x79, 0x70, 0x65, 0x52, 0x04, 0x72, 0x6f, 0x6c, 0x65, 0x12, 0x42, 0x0a, 0x09, 0x61, 0x75, 0x74, 0x68, 0x5f, 0x74, 0x79, 0x70, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x25, 0x2e, 0x43, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x2e, 0x41, 0x75, 0x74, 0x68, 0x6f, 0x72, 0x69, 0x7a, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x54, 0x79, 0x70, 0x65, 0x52, 0x08, 0x61, 0x75, 0x74, 0x68, 0x54, 0x79, 0x70, 0x65, 0x22, 0x2d, 0x0a, 0x06, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, 0x10, 0x0a, 0x0c, 0x53, 0x54, 0x41, 0x54, 0x55, 0x53, 0x5f, 0x55, 0x4e, 0x53, 0x45, 0x54, 0x10, 0x00, 0x12, 0x06, 0x0a, 0x02, 0x4f, 0x4b, 0x10, 0x01, 0x12, 0x09, 0x0a, 0x05, 0x45, 0x52, 0x52, 0x4f, 0x52, 0x10, 0x02, 0x22, 0x4b, 0x0a, 0x11, 0x41, 0x75, 0x74, 0x68, 0x6f, 0x72, 0x69, 0x7a, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x54, 0x79, 0x70, 0x65, 0x12, 0x1c, 0x0a, 0x18, 0x41, 0x55, 0x54, 0x48, 0x4f, 0x52, 0x49, 0x5a, 0x41, 0x54, 0x49, 0x4f, 0x4e, 0x5f, 0x54, 0x59, 0x50, 0x45, 0x5f, 0x55, 0x4e, 0x53, 0x45, 0x54, 0x10, 0x00, 0x12, 0x09, 0x0a, 0x05, 0x54, 0x52, 0x55, 0x53, 0x54, 0x10, 0x01, 0x12, 0x0d, 0x0a, 0x09, 0x43, 0x48, 0x41, 0x4c, 0x4c, 0x45, 0x4e, 0x47, 0x45, 0x10, 0x02, 0x22, 0x5b, 0x0a, 0x19, 0x41, 0x75, 0x74, 0x68, 0x6f, 0x72, 0x69, 0x7a, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x54, 0x72, 0x75, 0x73, 0x74, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x1f, 0x0a, 0x05, 0x72, 0x6f, 0x6c, 0x65, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0e, 0x32, 0x09, 0x2e, 0x52, 0x6f, 0x6c, 0x65, 0x54, 0x79, 0x70, 0x65, 0x52, 0x05, 0x72, 0x6f, 0x6c, 0x65, 0x73, 0x12, 0x1d, 0x0a, 0x0a, 0x70, 0x75, 0x62, 0x6c, 0x69, 0x63, 0x5f, 0x6b, 0x65, 0x79, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, 0x70, 0x75, 0x62, 0x6c, 0x69, 0x63, 0x4b, 0x65, 0x79, 0x22, 0x3d, 0x0a, 0x1a, 0x41, 0x75, 0x74, 0x68, 0x6f, 0x72, 0x69, 0x7a, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x54, 0x72, 0x75, 0x73, 0x74, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x1f, 0x0a, 0x05, 0x72, 0x6f, 0x6c, 0x65, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0e, 0x32, 0x09, 0x2e, 0x52, 0x6f, 0x6c, 0x65, 0x54, 0x79, 0x70, 0x65, 0x52, 0x05, 0x72, 0x6f, 0x6c, 0x65, 0x73, 0x22, 0x41, 0x0a, 0x16, 0x41, 0x75, 0x74, 0x68, 0x6f, 0x72, 0x69, 0x7a, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x56, 0x69, 0x6f, 0x6c, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x27, 0x0a, 0x09, 0x76, 0x69, 0x6f, 0x6c, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x09, 0x2e, 0x52, 0x6f, 0x6c, 0x65, 0x54, 0x79, 0x70, 0x65, 0x52, 0x09, 0x76, 0x69, 0x6f, 0x6c, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x22, 0x1f, 0x0a, 0x1d, 0x41, 0x75, 0x74, 0x68, 0x6f, 0x72, 0x69, 0x7a, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x43, 0x68, 0x61, 0x6c, 0x6c, 0x65, 0x6e, 0x67, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x22, 0x3a, 0x0a, 0x1e, 0x41, 0x75, 0x74, 0x68, 0x6f, 0x72, 0x69, 0x7a, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x43, 0x68, 0x61, 0x6c, 0x6c, 0x65, 0x6e, 0x67, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x18, 0x0a, 0x07, 0x70, 0x61, 0x79, 0x6c, 0x6f, 0x61, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x07, 0x70, 0x61, 0x79, 0x6c, 0x6f, 0x61, 0x64, 0x22, 0x7c, 0x0a, 0x1c, 0x41, 0x75, 0x74, 0x68, 0x6f, 0x72, 0x69, 0x7a, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x43, 0x68, 0x61, 0x6c, 0x6c, 0x65, 0x6e, 0x67, 0x65, 0x53, 0x75, 0x62, 0x6d, 0x69, 0x74, 0x12, 0x1d, 0x0a, 0x0a, 0x70, 0x75, 0x62, 0x6c, 0x69, 0x63, 0x5f, 0x6b, 0x65, 0x79, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, 0x70, 0x75, 0x62, 0x6c, 0x69, 0x63, 0x4b, 0x65, 0x79, 0x12, 0x1c, 0x0a, 0x09, 0x73, 0x69, 0x67, 0x6e, 0x61, 0x74, 0x75, 0x72, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, 0x73, 0x69, 0x67, 0x6e, 0x61, 0x74, 0x75, 0x72, 0x65, 0x12, 0x1f, 0x0a, 0x05, 0x72, 0x6f, 0x6c, 0x65, 0x73, 0x18, 0x04, 0x20, 0x03, 0x28, 0x0e, 0x32, 0x09, 0x2e, 0x52, 0x6f, 0x6c, 0x65, 0x54, 0x79, 0x70, 0x65, 0x52, 0x05, 0x72, 0x6f, 0x6c, 0x65, 0x73, 0x22, 0x3f, 0x0a, 0x1c, 0x41, 0x75, 0x74, 0x68, 0x6f, 0x72, 0x69, 0x7a, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x43, 0x68, 0x61, 0x6c, 0x6c, 0x65, 0x6e, 0x67, 0x65, 0x52, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x12, 0x1f, 0x0a, 0x05, 0x72, 0x6f, 0x6c, 0x65, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0e, 0x32, 0x09, 0x2e, 0x52, 0x6f, 0x6c, 0x65, 0x54, 0x79, 0x70, 0x65, 0x52, 0x05, 0x72, 0x6f, 0x6c, 0x65, 0x73, 0x2a, 0x35, 0x0a, 0x08, 0x52, 0x6f, 0x6c, 0x65, 0x54, 0x79, 0x70, 0x65, 0x12, 0x13, 0x0a, 0x0f, 0x52, 0x4f, 0x4c, 0x45, 0x5f, 0x54, 0x59, 0x50, 0x45, 0x5f, 0x55, 0x4e, 0x53, 0x45, 0x54, 0x10, 0x00, 0x12, 0x07, 0x0a, 0x03, 0x41, 0x4c, 0x4c, 0x10, 0x01, 0x12, 0x0b, 0x0a, 0x07, 0x4e, 0x45, 0x54, 0x57, 0x4f, 0x52, 0x4b, 0x10, 0x02, 0x42, 0x2c, 0x0a, 0x15, 0x73, 0x61, 0x77, 0x74, 0x6f, 0x6f, 0x74, 0x68, 0x2e, 0x73, 0x64, 0x6b, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x50, 0x01, 0x5a, 0x11, 0x61, 0x75, 0x74, 0x68, 0x6f, 0x72, 0x69, 0x7a, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x70, 0x62, 0x32, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( file_protobuf_authorization_pb2_authorization_proto_rawDescOnce sync.Once file_protobuf_authorization_pb2_authorization_proto_rawDescData = file_protobuf_authorization_pb2_authorization_proto_rawDesc ) func file_protobuf_authorization_pb2_authorization_proto_rawDescGZIP() []byte { file_protobuf_authorization_pb2_authorization_proto_rawDescOnce.Do(func() { file_protobuf_authorization_pb2_authorization_proto_rawDescData = protoimpl.X.CompressGZIP(file_protobuf_authorization_pb2_authorization_proto_rawDescData) }) return file_protobuf_authorization_pb2_authorization_proto_rawDescData } var file_protobuf_authorization_pb2_authorization_proto_enumTypes = make([]protoimpl.EnumInfo, 3) var file_protobuf_authorization_pb2_authorization_proto_msgTypes = make([]protoimpl.MessageInfo, 10) var file_protobuf_authorization_pb2_authorization_proto_goTypes = []interface{}{ (RoleType)(0), // 0: RoleType (ConnectionResponse_Status)(0), // 1: ConnectionResponse.Status (ConnectionResponse_AuthorizationType)(0), // 2: ConnectionResponse.AuthorizationType (*ConnectionRequest)(nil), // 3: ConnectionRequest (*ConnectionResponse)(nil), // 4: ConnectionResponse (*AuthorizationTrustRequest)(nil), // 5: AuthorizationTrustRequest (*AuthorizationTrustResponse)(nil), // 6: AuthorizationTrustResponse (*AuthorizationViolation)(nil), // 7: AuthorizationViolation (*AuthorizationChallengeRequest)(nil), // 8: AuthorizationChallengeRequest (*AuthorizationChallengeResponse)(nil), // 9: AuthorizationChallengeResponse (*AuthorizationChallengeSubmit)(nil), // 10: AuthorizationChallengeSubmit (*AuthorizationChallengeResult)(nil), // 11: AuthorizationChallengeResult (*ConnectionResponse_RoleEntry)(nil), // 12: ConnectionResponse.RoleEntry } var file_protobuf_authorization_pb2_authorization_proto_depIdxs = []int32{ 12, // 0: ConnectionResponse.roles:type_name -> ConnectionResponse.RoleEntry 1, // 1: ConnectionResponse.status:type_name -> ConnectionResponse.Status 0, // 2: AuthorizationTrustRequest.roles:type_name -> RoleType 0, // 3: AuthorizationTrustResponse.roles:type_name -> RoleType 0, // 4: AuthorizationViolation.violation:type_name -> RoleType 0, // 5: AuthorizationChallengeSubmit.roles:type_name -> RoleType 0, // 6: AuthorizationChallengeResult.roles:type_name -> RoleType 0, // 7: ConnectionResponse.RoleEntry.role:type_name -> RoleType 2, // 8: ConnectionResponse.RoleEntry.auth_type:type_name -> ConnectionResponse.AuthorizationType 9, // [9:9] is the sub-list for method output_type 9, // [9:9] is the sub-list for method input_type 9, // [9:9] is the sub-list for extension type_name 9, // [9:9] is the sub-list for extension extendee 0, // [0:9] is the sub-list for field type_name } func init() { file_protobuf_authorization_pb2_authorization_proto_init() } func file_protobuf_authorization_pb2_authorization_proto_init() { if File_protobuf_authorization_pb2_authorization_proto != nil { return } if !protoimpl.UnsafeEnabled { file_protobuf_authorization_pb2_authorization_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ConnectionRequest); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_authorization_pb2_authorization_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ConnectionResponse); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_authorization_pb2_authorization_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*AuthorizationTrustRequest); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_authorization_pb2_authorization_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*AuthorizationTrustResponse); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_authorization_pb2_authorization_proto_msgTypes[4].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*AuthorizationViolation); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_authorization_pb2_authorization_proto_msgTypes[5].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*AuthorizationChallengeRequest); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_authorization_pb2_authorization_proto_msgTypes[6].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*AuthorizationChallengeResponse); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_authorization_pb2_authorization_proto_msgTypes[7].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*AuthorizationChallengeSubmit); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_authorization_pb2_authorization_proto_msgTypes[8].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*AuthorizationChallengeResult); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_authorization_pb2_authorization_proto_msgTypes[9].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ConnectionResponse_RoleEntry); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: file_protobuf_authorization_pb2_authorization_proto_rawDesc, NumEnums: 3, NumMessages: 10, NumExtensions: 0, NumServices: 0, }, GoTypes: file_protobuf_authorization_pb2_authorization_proto_goTypes, DependencyIndexes: file_protobuf_authorization_pb2_authorization_proto_depIdxs, EnumInfos: file_protobuf_authorization_pb2_authorization_proto_enumTypes, MessageInfos: file_protobuf_authorization_pb2_authorization_proto_msgTypes, }.Build() File_protobuf_authorization_pb2_authorization_proto = out.File file_protobuf_authorization_pb2_authorization_proto_rawDesc = nil file_protobuf_authorization_pb2_authorization_proto_goTypes = nil file_protobuf_authorization_pb2_authorization_proto_depIdxs = nil } <|start_filename|>protobuf/setting_pb2/setting.pb.go<|end_filename|> // Copyright 2017 Intel Corporation // // 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. // ----------------------------------------------------------------------------- // Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.25.0-devel // protoc v3.14.0 // source: protobuf/setting_pb2/setting.proto package setting_pb2 import ( protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" sync "sync" ) const ( // Verify that this generated code is sufficiently up-to-date. _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) // Verify that runtime/protoimpl is sufficiently up-to-date. _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) // Setting Container for on-chain configuration key/value pairs type Setting struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // List of setting entries - more than one implies a state key collision Entries []*Setting_Entry `protobuf:"bytes,1,rep,name=entries,proto3" json:"entries,omitempty"` } func (x *Setting) Reset() { *x = Setting{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_setting_pb2_setting_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *Setting) String() string { return protoimpl.X.MessageStringOf(x) } func (*Setting) ProtoMessage() {} func (x *Setting) ProtoReflect() protoreflect.Message { mi := &file_protobuf_setting_pb2_setting_proto_msgTypes[0] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use Setting.ProtoReflect.Descriptor instead. func (*Setting) Descriptor() ([]byte, []int) { return file_protobuf_setting_pb2_setting_proto_rawDescGZIP(), []int{0} } func (x *Setting) GetEntries() []*Setting_Entry { if x != nil { return x.Entries } return nil } // Contains a setting entry (or entries, in the case of collisions). type Setting_Entry struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Key string `protobuf:"bytes,1,opt,name=key,proto3" json:"key,omitempty"` Value string `protobuf:"bytes,2,opt,name=value,proto3" json:"value,omitempty"` } func (x *Setting_Entry) Reset() { *x = Setting_Entry{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_setting_pb2_setting_proto_msgTypes[1] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *Setting_Entry) String() string { return protoimpl.X.MessageStringOf(x) } func (*Setting_Entry) ProtoMessage() {} func (x *Setting_Entry) ProtoReflect() protoreflect.Message { mi := &file_protobuf_setting_pb2_setting_proto_msgTypes[1] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use Setting_Entry.ProtoReflect.Descriptor instead. func (*Setting_Entry) Descriptor() ([]byte, []int) { return file_protobuf_setting_pb2_setting_proto_rawDescGZIP(), []int{0, 0} } func (x *Setting_Entry) GetKey() string { if x != nil { return x.Key } return "" } func (x *Setting_Entry) GetValue() string { if x != nil { return x.Value } return "" } var File_protobuf_setting_pb2_setting_proto protoreflect.FileDescriptor var file_protobuf_setting_pb2_setting_proto_rawDesc = []byte{ 0x0a, 0x22, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x73, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x5f, 0x70, 0x62, 0x32, 0x2f, 0x73, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0x64, 0x0a, 0x07, 0x53, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x12, 0x28, 0x0a, 0x07, 0x65, 0x6e, 0x74, 0x72, 0x69, 0x65, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x0e, 0x2e, 0x53, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x2e, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x52, 0x07, 0x65, 0x6e, 0x74, 0x72, 0x69, 0x65, 0x73, 0x1a, 0x2f, 0x0a, 0x05, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x12, 0x10, 0x0a, 0x03, 0x6b, 0x65, 0x79, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x6b, 0x65, 0x79, 0x12, 0x14, 0x0a, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x42, 0x26, 0x0a, 0x15, 0x73, 0x61, 0x77, 0x74, 0x6f, 0x6f, 0x74, 0x68, 0x2e, 0x73, 0x64, 0x6b, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x50, 0x01, 0x5a, 0x0b, 0x73, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x5f, 0x70, 0x62, 0x32, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( file_protobuf_setting_pb2_setting_proto_rawDescOnce sync.Once file_protobuf_setting_pb2_setting_proto_rawDescData = file_protobuf_setting_pb2_setting_proto_rawDesc ) func file_protobuf_setting_pb2_setting_proto_rawDescGZIP() []byte { file_protobuf_setting_pb2_setting_proto_rawDescOnce.Do(func() { file_protobuf_setting_pb2_setting_proto_rawDescData = protoimpl.X.CompressGZIP(file_protobuf_setting_pb2_setting_proto_rawDescData) }) return file_protobuf_setting_pb2_setting_proto_rawDescData } var file_protobuf_setting_pb2_setting_proto_msgTypes = make([]protoimpl.MessageInfo, 2) var file_protobuf_setting_pb2_setting_proto_goTypes = []interface{}{ (*Setting)(nil), // 0: Setting (*Setting_Entry)(nil), // 1: Setting.Entry } var file_protobuf_setting_pb2_setting_proto_depIdxs = []int32{ 1, // 0: Setting.entries:type_name -> Setting.Entry 1, // [1:1] is the sub-list for method output_type 1, // [1:1] is the sub-list for method input_type 1, // [1:1] is the sub-list for extension type_name 1, // [1:1] is the sub-list for extension extendee 0, // [0:1] is the sub-list for field type_name } func init() { file_protobuf_setting_pb2_setting_proto_init() } func file_protobuf_setting_pb2_setting_proto_init() { if File_protobuf_setting_pb2_setting_proto != nil { return } if !protoimpl.UnsafeEnabled { file_protobuf_setting_pb2_setting_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*Setting); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_setting_pb2_setting_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*Setting_Entry); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: file_protobuf_setting_pb2_setting_proto_rawDesc, NumEnums: 0, NumMessages: 2, NumExtensions: 0, NumServices: 0, }, GoTypes: file_protobuf_setting_pb2_setting_proto_goTypes, DependencyIndexes: file_protobuf_setting_pb2_setting_proto_depIdxs, MessageInfos: file_protobuf_setting_pb2_setting_proto_msgTypes, }.Build() File_protobuf_setting_pb2_setting_proto = out.File file_protobuf_setting_pb2_setting_proto_rawDesc = nil file_protobuf_setting_pb2_setting_proto_goTypes = nil file_protobuf_setting_pb2_setting_proto_depIdxs = nil } <|start_filename|>protobuf/client_transaction_pb2/client_transaction.pb.go<|end_filename|> // Copyright 2017 Intel Corporation // // 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. // ----------------------------------------------------------------------------- // Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.25.0-devel // protoc v3.14.0 // source: protobuf/client_transaction_pb2/client_transaction.proto package client_transaction_pb2 import ( protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" client_list_control_pb2 "github.com/hyperledger/sawtooth-sdk-go/protobuf/client_list_control_pb2" transaction_pb2 "github.com/hyperledger/sawtooth-sdk-go/protobuf/transaction_pb2" reflect "reflect" sync "sync" ) const ( // Verify that this generated code is sufficiently up-to-date. _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) // Verify that runtime/protoimpl is sufficiently up-to-date. _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) type ClientTransactionListResponse_Status int32 const ( ClientTransactionListResponse_STATUS_UNSET ClientTransactionListResponse_Status = 0 ClientTransactionListResponse_OK ClientTransactionListResponse_Status = 1 ClientTransactionListResponse_INTERNAL_ERROR ClientTransactionListResponse_Status = 2 ClientTransactionListResponse_NOT_READY ClientTransactionListResponse_Status = 3 ClientTransactionListResponse_NO_ROOT ClientTransactionListResponse_Status = 4 ClientTransactionListResponse_NO_RESOURCE ClientTransactionListResponse_Status = 5 ClientTransactionListResponse_INVALID_PAGING ClientTransactionListResponse_Status = 6 ClientTransactionListResponse_INVALID_SORT ClientTransactionListResponse_Status = 7 ClientTransactionListResponse_INVALID_ID ClientTransactionListResponse_Status = 8 ) // Enum value maps for ClientTransactionListResponse_Status. var ( ClientTransactionListResponse_Status_name = map[int32]string{ 0: "STATUS_UNSET", 1: "OK", 2: "INTERNAL_ERROR", 3: "NOT_READY", 4: "NO_ROOT", 5: "NO_RESOURCE", 6: "INVALID_PAGING", 7: "INVALID_SORT", 8: "INVALID_ID", } ClientTransactionListResponse_Status_value = map[string]int32{ "STATUS_UNSET": 0, "OK": 1, "INTERNAL_ERROR": 2, "NOT_READY": 3, "NO_ROOT": 4, "NO_RESOURCE": 5, "INVALID_PAGING": 6, "INVALID_SORT": 7, "INVALID_ID": 8, } ) func (x ClientTransactionListResponse_Status) Enum() *ClientTransactionListResponse_Status { p := new(ClientTransactionListResponse_Status) *p = x return p } func (x ClientTransactionListResponse_Status) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (ClientTransactionListResponse_Status) Descriptor() protoreflect.EnumDescriptor { return file_protobuf_client_transaction_pb2_client_transaction_proto_enumTypes[0].Descriptor() } func (ClientTransactionListResponse_Status) Type() protoreflect.EnumType { return &file_protobuf_client_transaction_pb2_client_transaction_proto_enumTypes[0] } func (x ClientTransactionListResponse_Status) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use ClientTransactionListResponse_Status.Descriptor instead. func (ClientTransactionListResponse_Status) EnumDescriptor() ([]byte, []int) { return file_protobuf_client_transaction_pb2_client_transaction_proto_rawDescGZIP(), []int{1, 0} } type ClientTransactionGetResponse_Status int32 const ( ClientTransactionGetResponse_STATUS_UNSET ClientTransactionGetResponse_Status = 0 ClientTransactionGetResponse_OK ClientTransactionGetResponse_Status = 1 ClientTransactionGetResponse_INTERNAL_ERROR ClientTransactionGetResponse_Status = 2 ClientTransactionGetResponse_NO_RESOURCE ClientTransactionGetResponse_Status = 5 ClientTransactionGetResponse_INVALID_ID ClientTransactionGetResponse_Status = 8 ) // Enum value maps for ClientTransactionGetResponse_Status. var ( ClientTransactionGetResponse_Status_name = map[int32]string{ 0: "STATUS_UNSET", 1: "OK", 2: "INTERNAL_ERROR", 5: "NO_RESOURCE", 8: "INVALID_ID", } ClientTransactionGetResponse_Status_value = map[string]int32{ "STATUS_UNSET": 0, "OK": 1, "INTERNAL_ERROR": 2, "NO_RESOURCE": 5, "INVALID_ID": 8, } ) func (x ClientTransactionGetResponse_Status) Enum() *ClientTransactionGetResponse_Status { p := new(ClientTransactionGetResponse_Status) *p = x return p } func (x ClientTransactionGetResponse_Status) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (ClientTransactionGetResponse_Status) Descriptor() protoreflect.EnumDescriptor { return file_protobuf_client_transaction_pb2_client_transaction_proto_enumTypes[1].Descriptor() } func (ClientTransactionGetResponse_Status) Type() protoreflect.EnumType { return &file_protobuf_client_transaction_pb2_client_transaction_proto_enumTypes[1] } func (x ClientTransactionGetResponse_Status) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use ClientTransactionGetResponse_Status.Descriptor instead. func (ClientTransactionGetResponse_Status) EnumDescriptor() ([]byte, []int) { return file_protobuf_client_transaction_pb2_client_transaction_proto_rawDescGZIP(), []int{3, 0} } // A request to return a list of txns from the validator. May include the id // of a particular block to be the `head` of the chain being requested. In that // case the list will include the txns from that block, and all txns // previous to that block on the chain. Filter with specific `transaction_ids`. type ClientTransactionListRequest struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields HeadId string `protobuf:"bytes,1,opt,name=head_id,json=headId,proto3" json:"head_id,omitempty"` TransactionIds []string `protobuf:"bytes,2,rep,name=transaction_ids,json=transactionIds,proto3" json:"transaction_ids,omitempty"` Paging *client_list_control_pb2.ClientPagingControls `protobuf:"bytes,3,opt,name=paging,proto3" json:"paging,omitempty"` Sorting []*client_list_control_pb2.ClientSortControls `protobuf:"bytes,4,rep,name=sorting,proto3" json:"sorting,omitempty"` } func (x *ClientTransactionListRequest) Reset() { *x = ClientTransactionListRequest{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_client_transaction_pb2_client_transaction_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ClientTransactionListRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*ClientTransactionListRequest) ProtoMessage() {} func (x *ClientTransactionListRequest) ProtoReflect() protoreflect.Message { mi := &file_protobuf_client_transaction_pb2_client_transaction_proto_msgTypes[0] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ClientTransactionListRequest.ProtoReflect.Descriptor instead. func (*ClientTransactionListRequest) Descriptor() ([]byte, []int) { return file_protobuf_client_transaction_pb2_client_transaction_proto_rawDescGZIP(), []int{0} } func (x *ClientTransactionListRequest) GetHeadId() string { if x != nil { return x.HeadId } return "" } func (x *ClientTransactionListRequest) GetTransactionIds() []string { if x != nil { return x.TransactionIds } return nil } func (x *ClientTransactionListRequest) GetPaging() *client_list_control_pb2.ClientPagingControls { if x != nil { return x.Paging } return nil } func (x *ClientTransactionListRequest) GetSorting() []*client_list_control_pb2.ClientSortControls { if x != nil { return x.Sorting } return nil } // A response that lists transactions from newest to oldest. // // Statuses: // * OK - everything worked as expected // * INTERNAL_ERROR - general error, such as protobuf failing to deserialize // * NOT_READY - the validator does not yet have a genesis block // * NO_ROOT - the head block specified was not found // * NO_RESOURCE - no txns were found with the parameters specified // * INVALID_PAGING - the paging controls were malformed or out of range // * INVALID_SORT - the sorting controls were malformed or invalid type ClientTransactionListResponse struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Status ClientTransactionListResponse_Status `protobuf:"varint,1,opt,name=status,proto3,enum=ClientTransactionListResponse_Status" json:"status,omitempty"` Transactions []*transaction_pb2.Transaction `protobuf:"bytes,2,rep,name=transactions,proto3" json:"transactions,omitempty"` HeadId string `protobuf:"bytes,3,opt,name=head_id,json=headId,proto3" json:"head_id,omitempty"` Paging *client_list_control_pb2.ClientPagingResponse `protobuf:"bytes,4,opt,name=paging,proto3" json:"paging,omitempty"` } func (x *ClientTransactionListResponse) Reset() { *x = ClientTransactionListResponse{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_client_transaction_pb2_client_transaction_proto_msgTypes[1] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ClientTransactionListResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*ClientTransactionListResponse) ProtoMessage() {} func (x *ClientTransactionListResponse) ProtoReflect() protoreflect.Message { mi := &file_protobuf_client_transaction_pb2_client_transaction_proto_msgTypes[1] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ClientTransactionListResponse.ProtoReflect.Descriptor instead. func (*ClientTransactionListResponse) Descriptor() ([]byte, []int) { return file_protobuf_client_transaction_pb2_client_transaction_proto_rawDescGZIP(), []int{1} } func (x *ClientTransactionListResponse) GetStatus() ClientTransactionListResponse_Status { if x != nil { return x.Status } return ClientTransactionListResponse_STATUS_UNSET } func (x *ClientTransactionListResponse) GetTransactions() []*transaction_pb2.Transaction { if x != nil { return x.Transactions } return nil } func (x *ClientTransactionListResponse) GetHeadId() string { if x != nil { return x.HeadId } return "" } func (x *ClientTransactionListResponse) GetPaging() *client_list_control_pb2.ClientPagingResponse { if x != nil { return x.Paging } return nil } // Fetches a specific txn by its id (header_signature) from the blockchain. type ClientTransactionGetRequest struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields TransactionId string `protobuf:"bytes,1,opt,name=transaction_id,json=transactionId,proto3" json:"transaction_id,omitempty"` } func (x *ClientTransactionGetRequest) Reset() { *x = ClientTransactionGetRequest{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_client_transaction_pb2_client_transaction_proto_msgTypes[2] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ClientTransactionGetRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*ClientTransactionGetRequest) ProtoMessage() {} func (x *ClientTransactionGetRequest) ProtoReflect() protoreflect.Message { mi := &file_protobuf_client_transaction_pb2_client_transaction_proto_msgTypes[2] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ClientTransactionGetRequest.ProtoReflect.Descriptor instead. func (*ClientTransactionGetRequest) Descriptor() ([]byte, []int) { return file_protobuf_client_transaction_pb2_client_transaction_proto_rawDescGZIP(), []int{2} } func (x *ClientTransactionGetRequest) GetTransactionId() string { if x != nil { return x.TransactionId } return "" } // A response that returns the txn specified by a ClientTransactionGetRequest. // // Statuses: // * OK - everything worked as expected, txn has been fetched // * INTERNAL_ERROR - general error, such as protobuf failing to deserialize // * NO_RESOURCE - no txn with the specified id exists type ClientTransactionGetResponse struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Status ClientTransactionGetResponse_Status `protobuf:"varint,1,opt,name=status,proto3,enum=ClientTransactionGetResponse_Status" json:"status,omitempty"` Transaction *transaction_pb2.Transaction `protobuf:"bytes,2,opt,name=transaction,proto3" json:"transaction,omitempty"` } func (x *ClientTransactionGetResponse) Reset() { *x = ClientTransactionGetResponse{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_client_transaction_pb2_client_transaction_proto_msgTypes[3] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ClientTransactionGetResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*ClientTransactionGetResponse) ProtoMessage() {} func (x *ClientTransactionGetResponse) ProtoReflect() protoreflect.Message { mi := &file_protobuf_client_transaction_pb2_client_transaction_proto_msgTypes[3] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ClientTransactionGetResponse.ProtoReflect.Descriptor instead. func (*ClientTransactionGetResponse) Descriptor() ([]byte, []int) { return file_protobuf_client_transaction_pb2_client_transaction_proto_rawDescGZIP(), []int{3} } func (x *ClientTransactionGetResponse) GetStatus() ClientTransactionGetResponse_Status { if x != nil { return x.Status } return ClientTransactionGetResponse_STATUS_UNSET } func (x *ClientTransactionGetResponse) GetTransaction() *transaction_pb2.Transaction { if x != nil { return x.Transaction } return nil } var File_protobuf_client_transaction_pb2_client_transaction_proto protoreflect.FileDescriptor var file_protobuf_client_transaction_pb2_client_transaction_proto_rawDesc = []byte{ 0x0a, 0x38, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x5f, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x70, 0x62, 0x32, 0x2f, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x5f, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x2a, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x70, 0x62, 0x32, 0x2f, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x3a, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x5f, 0x6c, 0x69, 0x73, 0x74, 0x5f, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x5f, 0x70, 0x62, 0x32, 0x2f, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x5f, 0x6c, 0x69, 0x73, 0x74, 0x5f, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0xbe, 0x01, 0x0a, 0x1c, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x4c, 0x69, 0x73, 0x74, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x17, 0x0a, 0x07, 0x68, 0x65, 0x61, 0x64, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, 0x68, 0x65, 0x61, 0x64, 0x49, 0x64, 0x12, 0x27, 0x0a, 0x0f, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x69, 0x64, 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x09, 0x52, 0x0e, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x49, 0x64, 0x73, 0x12, 0x2d, 0x0a, 0x06, 0x70, 0x61, 0x67, 0x69, 0x6e, 0x67, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x15, 0x2e, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x50, 0x61, 0x67, 0x69, 0x6e, 0x67, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x73, 0x52, 0x06, 0x70, 0x61, 0x67, 0x69, 0x6e, 0x67, 0x12, 0x2d, 0x0a, 0x07, 0x73, 0x6f, 0x72, 0x74, 0x69, 0x6e, 0x67, 0x18, 0x04, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x13, 0x2e, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x53, 0x6f, 0x72, 0x74, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x73, 0x52, 0x07, 0x73, 0x6f, 0x72, 0x74, 0x69, 0x6e, 0x67, 0x22, 0xf4, 0x02, 0x0a, 0x1d, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x4c, 0x69, 0x73, 0x74, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x3d, 0x0a, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x25, 0x2e, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x4c, 0x69, 0x73, 0x74, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x2e, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x52, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, 0x30, 0x0a, 0x0c, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x0c, 0x2e, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x0c, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x12, 0x17, 0x0a, 0x07, 0x68, 0x65, 0x61, 0x64, 0x5f, 0x69, 0x64, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, 0x68, 0x65, 0x61, 0x64, 0x49, 0x64, 0x12, 0x2d, 0x0a, 0x06, 0x70, 0x61, 0x67, 0x69, 0x6e, 0x67, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x15, 0x2e, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x50, 0x61, 0x67, 0x69, 0x6e, 0x67, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x52, 0x06, 0x70, 0x61, 0x67, 0x69, 0x6e, 0x67, 0x22, 0x99, 0x01, 0x0a, 0x06, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, 0x10, 0x0a, 0x0c, 0x53, 0x54, 0x41, 0x54, 0x55, 0x53, 0x5f, 0x55, 0x4e, 0x53, 0x45, 0x54, 0x10, 0x00, 0x12, 0x06, 0x0a, 0x02, 0x4f, 0x4b, 0x10, 0x01, 0x12, 0x12, 0x0a, 0x0e, 0x49, 0x4e, 0x54, 0x45, 0x52, 0x4e, 0x41, 0x4c, 0x5f, 0x45, 0x52, 0x52, 0x4f, 0x52, 0x10, 0x02, 0x12, 0x0d, 0x0a, 0x09, 0x4e, 0x4f, 0x54, 0x5f, 0x52, 0x45, 0x41, 0x44, 0x59, 0x10, 0x03, 0x12, 0x0b, 0x0a, 0x07, 0x4e, 0x4f, 0x5f, 0x52, 0x4f, 0x4f, 0x54, 0x10, 0x04, 0x12, 0x0f, 0x0a, 0x0b, 0x4e, 0x4f, 0x5f, 0x52, 0x45, 0x53, 0x4f, 0x55, 0x52, 0x43, 0x45, 0x10, 0x05, 0x12, 0x12, 0x0a, 0x0e, 0x49, 0x4e, 0x56, 0x41, 0x4c, 0x49, 0x44, 0x5f, 0x50, 0x41, 0x47, 0x49, 0x4e, 0x47, 0x10, 0x06, 0x12, 0x10, 0x0a, 0x0c, 0x49, 0x4e, 0x56, 0x41, 0x4c, 0x49, 0x44, 0x5f, 0x53, 0x4f, 0x52, 0x54, 0x10, 0x07, 0x12, 0x0e, 0x0a, 0x0a, 0x49, 0x4e, 0x56, 0x41, 0x4c, 0x49, 0x44, 0x5f, 0x49, 0x44, 0x10, 0x08, 0x22, 0x44, 0x0a, 0x1b, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x47, 0x65, 0x74, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x25, 0x0a, 0x0e, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0d, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x49, 0x64, 0x22, 0xe5, 0x01, 0x0a, 0x1c, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x47, 0x65, 0x74, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x3c, 0x0a, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x24, 0x2e, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x47, 0x65, 0x74, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x2e, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x52, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, 0x2e, 0x0a, 0x0b, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x0c, 0x2e, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x0b, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x22, 0x57, 0x0a, 0x06, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, 0x10, 0x0a, 0x0c, 0x53, 0x54, 0x41, 0x54, 0x55, 0x53, 0x5f, 0x55, 0x4e, 0x53, 0x45, 0x54, 0x10, 0x00, 0x12, 0x06, 0x0a, 0x02, 0x4f, 0x4b, 0x10, 0x01, 0x12, 0x12, 0x0a, 0x0e, 0x49, 0x4e, 0x54, 0x45, 0x52, 0x4e, 0x41, 0x4c, 0x5f, 0x45, 0x52, 0x52, 0x4f, 0x52, 0x10, 0x02, 0x12, 0x0f, 0x0a, 0x0b, 0x4e, 0x4f, 0x5f, 0x52, 0x45, 0x53, 0x4f, 0x55, 0x52, 0x43, 0x45, 0x10, 0x05, 0x12, 0x0e, 0x0a, 0x0a, 0x49, 0x4e, 0x56, 0x41, 0x4c, 0x49, 0x44, 0x5f, 0x49, 0x44, 0x10, 0x08, 0x42, 0x31, 0x0a, 0x15, 0x73, 0x61, 0x77, 0x74, 0x6f, 0x6f, 0x74, 0x68, 0x2e, 0x73, 0x64, 0x6b, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x50, 0x01, 0x5a, 0x16, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x5f, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x70, 0x62, 0x32, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( file_protobuf_client_transaction_pb2_client_transaction_proto_rawDescOnce sync.Once file_protobuf_client_transaction_pb2_client_transaction_proto_rawDescData = file_protobuf_client_transaction_pb2_client_transaction_proto_rawDesc ) func file_protobuf_client_transaction_pb2_client_transaction_proto_rawDescGZIP() []byte { file_protobuf_client_transaction_pb2_client_transaction_proto_rawDescOnce.Do(func() { file_protobuf_client_transaction_pb2_client_transaction_proto_rawDescData = protoimpl.X.CompressGZIP(file_protobuf_client_transaction_pb2_client_transaction_proto_rawDescData) }) return file_protobuf_client_transaction_pb2_client_transaction_proto_rawDescData } var file_protobuf_client_transaction_pb2_client_transaction_proto_enumTypes = make([]protoimpl.EnumInfo, 2) var file_protobuf_client_transaction_pb2_client_transaction_proto_msgTypes = make([]protoimpl.MessageInfo, 4) var file_protobuf_client_transaction_pb2_client_transaction_proto_goTypes = []interface{}{ (ClientTransactionListResponse_Status)(0), // 0: ClientTransactionListResponse.Status (ClientTransactionGetResponse_Status)(0), // 1: ClientTransactionGetResponse.Status (*ClientTransactionListRequest)(nil), // 2: ClientTransactionListRequest (*ClientTransactionListResponse)(nil), // 3: ClientTransactionListResponse (*ClientTransactionGetRequest)(nil), // 4: ClientTransactionGetRequest (*ClientTransactionGetResponse)(nil), // 5: ClientTransactionGetResponse (*client_list_control_pb2.ClientPagingControls)(nil), // 6: ClientPagingControls (*client_list_control_pb2.ClientSortControls)(nil), // 7: ClientSortControls (*transaction_pb2.Transaction)(nil), // 8: Transaction (*client_list_control_pb2.ClientPagingResponse)(nil), // 9: ClientPagingResponse } var file_protobuf_client_transaction_pb2_client_transaction_proto_depIdxs = []int32{ 6, // 0: ClientTransactionListRequest.paging:type_name -> ClientPagingControls 7, // 1: ClientTransactionListRequest.sorting:type_name -> ClientSortControls 0, // 2: ClientTransactionListResponse.status:type_name -> ClientTransactionListResponse.Status 8, // 3: ClientTransactionListResponse.transactions:type_name -> Transaction 9, // 4: ClientTransactionListResponse.paging:type_name -> ClientPagingResponse 1, // 5: ClientTransactionGetResponse.status:type_name -> ClientTransactionGetResponse.Status 8, // 6: ClientTransactionGetResponse.transaction:type_name -> Transaction 7, // [7:7] is the sub-list for method output_type 7, // [7:7] is the sub-list for method input_type 7, // [7:7] is the sub-list for extension type_name 7, // [7:7] is the sub-list for extension extendee 0, // [0:7] is the sub-list for field type_name } func init() { file_protobuf_client_transaction_pb2_client_transaction_proto_init() } func file_protobuf_client_transaction_pb2_client_transaction_proto_init() { if File_protobuf_client_transaction_pb2_client_transaction_proto != nil { return } if !protoimpl.UnsafeEnabled { file_protobuf_client_transaction_pb2_client_transaction_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ClientTransactionListRequest); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_client_transaction_pb2_client_transaction_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ClientTransactionListResponse); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_client_transaction_pb2_client_transaction_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ClientTransactionGetRequest); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_client_transaction_pb2_client_transaction_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ClientTransactionGetResponse); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: file_protobuf_client_transaction_pb2_client_transaction_proto_rawDesc, NumEnums: 2, NumMessages: 4, NumExtensions: 0, NumServices: 0, }, GoTypes: file_protobuf_client_transaction_pb2_client_transaction_proto_goTypes, DependencyIndexes: file_protobuf_client_transaction_pb2_client_transaction_proto_depIdxs, EnumInfos: file_protobuf_client_transaction_pb2_client_transaction_proto_enumTypes, MessageInfos: file_protobuf_client_transaction_pb2_client_transaction_proto_msgTypes, }.Build() File_protobuf_client_transaction_pb2_client_transaction_proto = out.File file_protobuf_client_transaction_pb2_client_transaction_proto_rawDesc = nil file_protobuf_client_transaction_pb2_client_transaction_proto_goTypes = nil file_protobuf_client_transaction_pb2_client_transaction_proto_depIdxs = nil } <|start_filename|>protobuf/merkle_pb2/merkle.pb.go<|end_filename|> // Copyright 2018 Intel Corporation // // 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. // ----------------------------------------------------------------------------- // Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.25.0-devel // protoc v3.14.0 // source: protobuf/merkle_pb2/merkle.proto package merkle_pb2 import ( protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" sync "sync" ) const ( // Verify that this generated code is sufficiently up-to-date. _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) // Verify that runtime/protoimpl is sufficiently up-to-date. _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) // An Entry in the change log for a given state root. type ChangeLogEntry struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // A root hash of a merkle trie this tree was based off. Parent []byte `protobuf:"bytes,1,opt,name=parent,proto3" json:"parent,omitempty"` // The hashes that were added for this root. These may be deleted during // pruning, if this root is being abandoned. Additions [][]byte `protobuf:"bytes,2,rep,name=additions,proto3" json:"additions,omitempty"` // The list of successors. Successors []*ChangeLogEntry_Successor `protobuf:"bytes,3,rep,name=successors,proto3" json:"successors,omitempty"` } func (x *ChangeLogEntry) Reset() { *x = ChangeLogEntry{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_merkle_pb2_merkle_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ChangeLogEntry) String() string { return protoimpl.X.MessageStringOf(x) } func (*ChangeLogEntry) ProtoMessage() {} func (x *ChangeLogEntry) ProtoReflect() protoreflect.Message { mi := &file_protobuf_merkle_pb2_merkle_proto_msgTypes[0] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ChangeLogEntry.ProtoReflect.Descriptor instead. func (*ChangeLogEntry) Descriptor() ([]byte, []int) { return file_protobuf_merkle_pb2_merkle_proto_rawDescGZIP(), []int{0} } func (x *ChangeLogEntry) GetParent() []byte { if x != nil { return x.Parent } return nil } func (x *ChangeLogEntry) GetAdditions() [][]byte { if x != nil { return x.Additions } return nil } func (x *ChangeLogEntry) GetSuccessors() []*ChangeLogEntry_Successor { if x != nil { return x.Successors } return nil } // A state root that succeed this root. type ChangeLogEntry_Successor struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // A root hash of a merkle trie based of off this root. Successor []byte `protobuf:"bytes,1,opt,name=successor,proto3" json:"successor,omitempty"` // The keys (i.e. hashes) that were replaced (i.e. deleted) by this // successor. These may be deleted during pruning. Deletions [][]byte `protobuf:"bytes,2,rep,name=deletions,proto3" json:"deletions,omitempty"` } func (x *ChangeLogEntry_Successor) Reset() { *x = ChangeLogEntry_Successor{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_merkle_pb2_merkle_proto_msgTypes[1] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ChangeLogEntry_Successor) String() string { return protoimpl.X.MessageStringOf(x) } func (*ChangeLogEntry_Successor) ProtoMessage() {} func (x *ChangeLogEntry_Successor) ProtoReflect() protoreflect.Message { mi := &file_protobuf_merkle_pb2_merkle_proto_msgTypes[1] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ChangeLogEntry_Successor.ProtoReflect.Descriptor instead. func (*ChangeLogEntry_Successor) Descriptor() ([]byte, []int) { return file_protobuf_merkle_pb2_merkle_proto_rawDescGZIP(), []int{0, 0} } func (x *ChangeLogEntry_Successor) GetSuccessor() []byte { if x != nil { return x.Successor } return nil } func (x *ChangeLogEntry_Successor) GetDeletions() [][]byte { if x != nil { return x.Deletions } return nil } var File_protobuf_merkle_pb2_merkle_proto protoreflect.FileDescriptor var file_protobuf_merkle_pb2_merkle_proto_rawDesc = []byte{ 0x0a, 0x20, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x6d, 0x65, 0x72, 0x6b, 0x6c, 0x65, 0x5f, 0x70, 0x62, 0x32, 0x2f, 0x6d, 0x65, 0x72, 0x6b, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0xca, 0x01, 0x0a, 0x0e, 0x43, 0x68, 0x61, 0x6e, 0x67, 0x65, 0x4c, 0x6f, 0x67, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x12, 0x16, 0x0a, 0x06, 0x70, 0x61, 0x72, 0x65, 0x6e, 0x74, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x06, 0x70, 0x61, 0x72, 0x65, 0x6e, 0x74, 0x12, 0x1c, 0x0a, 0x09, 0x61, 0x64, 0x64, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x0c, 0x52, 0x09, 0x61, 0x64, 0x64, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x12, 0x39, 0x0a, 0x0a, 0x73, 0x75, 0x63, 0x63, 0x65, 0x73, 0x73, 0x6f, 0x72, 0x73, 0x18, 0x03, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x43, 0x68, 0x61, 0x6e, 0x67, 0x65, 0x4c, 0x6f, 0x67, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x2e, 0x53, 0x75, 0x63, 0x63, 0x65, 0x73, 0x73, 0x6f, 0x72, 0x52, 0x0a, 0x73, 0x75, 0x63, 0x63, 0x65, 0x73, 0x73, 0x6f, 0x72, 0x73, 0x1a, 0x47, 0x0a, 0x09, 0x53, 0x75, 0x63, 0x63, 0x65, 0x73, 0x73, 0x6f, 0x72, 0x12, 0x1c, 0x0a, 0x09, 0x73, 0x75, 0x63, 0x63, 0x65, 0x73, 0x73, 0x6f, 0x72, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x09, 0x73, 0x75, 0x63, 0x63, 0x65, 0x73, 0x73, 0x6f, 0x72, 0x12, 0x1c, 0x0a, 0x09, 0x64, 0x65, 0x6c, 0x65, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x0c, 0x52, 0x09, 0x64, 0x65, 0x6c, 0x65, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x42, 0x25, 0x0a, 0x15, 0x73, 0x61, 0x77, 0x74, 0x6f, 0x6f, 0x74, 0x68, 0x2e, 0x73, 0x64, 0x6b, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x50, 0x01, 0x5a, 0x0a, 0x6d, 0x65, 0x72, 0x6b, 0x6c, 0x65, 0x5f, 0x70, 0x62, 0x32, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( file_protobuf_merkle_pb2_merkle_proto_rawDescOnce sync.Once file_protobuf_merkle_pb2_merkle_proto_rawDescData = file_protobuf_merkle_pb2_merkle_proto_rawDesc ) func file_protobuf_merkle_pb2_merkle_proto_rawDescGZIP() []byte { file_protobuf_merkle_pb2_merkle_proto_rawDescOnce.Do(func() { file_protobuf_merkle_pb2_merkle_proto_rawDescData = protoimpl.X.CompressGZIP(file_protobuf_merkle_pb2_merkle_proto_rawDescData) }) return file_protobuf_merkle_pb2_merkle_proto_rawDescData } var file_protobuf_merkle_pb2_merkle_proto_msgTypes = make([]protoimpl.MessageInfo, 2) var file_protobuf_merkle_pb2_merkle_proto_goTypes = []interface{}{ (*ChangeLogEntry)(nil), // 0: ChangeLogEntry (*ChangeLogEntry_Successor)(nil), // 1: ChangeLogEntry.Successor } var file_protobuf_merkle_pb2_merkle_proto_depIdxs = []int32{ 1, // 0: ChangeLogEntry.successors:type_name -> ChangeLogEntry.Successor 1, // [1:1] is the sub-list for method output_type 1, // [1:1] is the sub-list for method input_type 1, // [1:1] is the sub-list for extension type_name 1, // [1:1] is the sub-list for extension extendee 0, // [0:1] is the sub-list for field type_name } func init() { file_protobuf_merkle_pb2_merkle_proto_init() } func file_protobuf_merkle_pb2_merkle_proto_init() { if File_protobuf_merkle_pb2_merkle_proto != nil { return } if !protoimpl.UnsafeEnabled { file_protobuf_merkle_pb2_merkle_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ChangeLogEntry); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_merkle_pb2_merkle_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ChangeLogEntry_Successor); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: file_protobuf_merkle_pb2_merkle_proto_rawDesc, NumEnums: 0, NumMessages: 2, NumExtensions: 0, NumServices: 0, }, GoTypes: file_protobuf_merkle_pb2_merkle_proto_goTypes, DependencyIndexes: file_protobuf_merkle_pb2_merkle_proto_depIdxs, MessageInfos: file_protobuf_merkle_pb2_merkle_proto_msgTypes, }.Build() File_protobuf_merkle_pb2_merkle_proto = out.File file_protobuf_merkle_pb2_merkle_proto_rawDesc = nil file_protobuf_merkle_pb2_merkle_proto_goTypes = nil file_protobuf_merkle_pb2_merkle_proto_depIdxs = nil } <|start_filename|>examples/intkey_go/src/sawtooth_intkey_client/inc.go<|end_filename|> /** * Copyright 2018 Intel Corporation * * 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 main import ( "github.com/jessevdk/go-flags" "strconv" ) type Inc struct { Args struct { Name string `positional-arg-name:"name" required:"true" description:"Identify name of key to increment"` Value string `positional-arg-name:"value" required:"true" description:"Specify amount to increment"` } `positional-args:"true"` Url string `long:"url" description:"Specify URL of REST API"` Keyfile string `long:"keyfile" description:"Identify file containing user's private key"` Wait uint `long:"wait" description:"Set time, in seconds, to wait for transaction to commit"` } func (args *Inc) Name() string { return "inc" } func (args *Inc) KeyfilePassed() string { return args.Keyfile } func (args *Inc) UrlPassed() string { return args.Url } func (args *Inc) Register(parent *flags.Command) error { _, err := parent.AddCommand(args.Name(), "Increments an intkey value", "Sends an intkey transaction to increment <name> by <value>.", args) if err != nil { return err } return nil } func (args *Inc) Run() error { // Construct client name := args.Args.Name value, err := strconv.Atoi(args.Args.Value) if err != nil { return err } wait := args.Wait intkeyClient, err := GetClient(args, true) if err != nil { return err } _, err = intkeyClient.Inc(name, uint(value), wait) return err } <|start_filename|>protobuf/validator_pb2/validator.pb.go<|end_filename|> // Copyright 2016, 2017 Intel Corporation // // 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. // ----------------------------------------------------------------------------- // Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.25.0-devel // protoc v3.14.0 // source: protobuf/validator_pb2/validator.proto package validator_pb2 import ( protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" sync "sync" ) const ( // Verify that this generated code is sufficiently up-to-date. _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) // Verify that runtime/protoimpl is sufficiently up-to-date. _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) type Message_MessageType int32 const ( Message_DEFAULT Message_MessageType = 0 // Registration request from the transaction processor to the validator Message_TP_REGISTER_REQUEST Message_MessageType = 1 // Registration response from the validator to the // transaction processor Message_TP_REGISTER_RESPONSE Message_MessageType = 2 // Tell the validator that the transaction processor // won't take any more transactions Message_TP_UNREGISTER_REQUEST Message_MessageType = 3 // Response from the validator to the tp that it won't // send any more transactions Message_TP_UNREGISTER_RESPONSE Message_MessageType = 4 // Process Request from the validator/executor to the // transaction processor Message_TP_PROCESS_REQUEST Message_MessageType = 5 // Process response from the transaction processor to the validator/executor Message_TP_PROCESS_RESPONSE Message_MessageType = 6 // State get request from the transaction processor to validator/context_manager Message_TP_STATE_GET_REQUEST Message_MessageType = 7 // State get response from the validator/context_manager to the transaction processor Message_TP_STATE_GET_RESPONSE Message_MessageType = 8 // State set request from the transaction processor to the validator/context_manager Message_TP_STATE_SET_REQUEST Message_MessageType = 9 // State set response from the validator/context_manager to the transaction processor Message_TP_STATE_SET_RESPONSE Message_MessageType = 10 // State delete request from the transaction processor to the validator/context_manager Message_TP_STATE_DELETE_REQUEST Message_MessageType = 11 // State delete response from the validator/context_manager to the transaction processor Message_TP_STATE_DELETE_RESPONSE Message_MessageType = 12 // Message to append data to a transaction receipt Message_TP_RECEIPT_ADD_DATA_REQUEST Message_MessageType = 13 // Response from validator to tell transaction processor that data has been appended Message_TP_RECEIPT_ADD_DATA_RESPONSE Message_MessageType = 14 // Message to add event Message_TP_EVENT_ADD_REQUEST Message_MessageType = 15 // Response from validator to tell transaction processor that event has been created Message_TP_EVENT_ADD_RESPONSE Message_MessageType = 16 // Submission of a batchlist from the web api or another client to the validator Message_CLIENT_BATCH_SUBMIT_REQUEST Message_MessageType = 100 // Response from the validator to the web api/client that the submission was accepted Message_CLIENT_BATCH_SUBMIT_RESPONSE Message_MessageType = 101 // A request to list blocks from the web api/client to the validator Message_CLIENT_BLOCK_LIST_REQUEST Message_MessageType = 102 Message_CLIENT_BLOCK_LIST_RESPONSE Message_MessageType = 103 Message_CLIENT_BLOCK_GET_BY_ID_REQUEST Message_MessageType = 104 Message_CLIENT_BLOCK_GET_RESPONSE Message_MessageType = 105 Message_CLIENT_BATCH_LIST_REQUEST Message_MessageType = 106 Message_CLIENT_BATCH_LIST_RESPONSE Message_MessageType = 107 Message_CLIENT_BATCH_GET_REQUEST Message_MessageType = 108 Message_CLIENT_BATCH_GET_RESPONSE Message_MessageType = 109 Message_CLIENT_TRANSACTION_LIST_REQUEST Message_MessageType = 110 Message_CLIENT_TRANSACTION_LIST_RESPONSE Message_MessageType = 111 Message_CLIENT_TRANSACTION_GET_REQUEST Message_MessageType = 112 Message_CLIENT_TRANSACTION_GET_RESPONSE Message_MessageType = 113 // Client state request of the current state hash to be retrieved from the journal Message_CLIENT_STATE_CURRENT_REQUEST Message_MessageType = 114 // Response with the current state hash Message_CLIENT_STATE_CURRENT_RESPONSE Message_MessageType = 115 // A request of all the addresses under a particular prefix, for a state hash. Message_CLIENT_STATE_LIST_REQUEST Message_MessageType = 116 // The response of the addresses Message_CLIENT_STATE_LIST_RESPONSE Message_MessageType = 117 // Get the address:data entry at a particular address Message_CLIENT_STATE_GET_REQUEST Message_MessageType = 118 // The response with the entry Message_CLIENT_STATE_GET_RESPONSE Message_MessageType = 119 // A request for the status of a batch or batches Message_CLIENT_BATCH_STATUS_REQUEST Message_MessageType = 120 // A response with the batch statuses Message_CLIENT_BATCH_STATUS_RESPONSE Message_MessageType = 121 // A request for one or more transaction receipts Message_CLIENT_RECEIPT_GET_REQUEST Message_MessageType = 122 // A response with the receipts Message_CLIENT_RECEIPT_GET_RESPONSE Message_MessageType = 123 Message_CLIENT_BLOCK_GET_BY_NUM_REQUEST Message_MessageType = 124 // A request for a validator's peers Message_CLIENT_PEERS_GET_REQUEST Message_MessageType = 125 // A response with the validator's peers Message_CLIENT_PEERS_GET_RESPONSE Message_MessageType = 126 Message_CLIENT_BLOCK_GET_BY_TRANSACTION_ID_REQUEST Message_MessageType = 127 Message_CLIENT_BLOCK_GET_BY_BATCH_ID_REQUEST Message_MessageType = 128 // A request for a validator's status Message_CLIENT_STATUS_GET_REQUEST Message_MessageType = 129 // A response with the validator's status Message_CLIENT_STATUS_GET_RESPONSE Message_MessageType = 130 // Message types for events Message_CLIENT_EVENTS_SUBSCRIBE_REQUEST Message_MessageType = 500 Message_CLIENT_EVENTS_SUBSCRIBE_RESPONSE Message_MessageType = 501 Message_CLIENT_EVENTS_UNSUBSCRIBE_REQUEST Message_MessageType = 502 Message_CLIENT_EVENTS_UNSUBSCRIBE_RESPONSE Message_MessageType = 503 Message_CLIENT_EVENTS Message_MessageType = 504 Message_CLIENT_EVENTS_GET_REQUEST Message_MessageType = 505 Message_CLIENT_EVENTS_GET_RESPONSE Message_MessageType = 506 // Temp message types until a discussion can be had about gossip msg Message_GOSSIP_MESSAGE Message_MessageType = 200 Message_GOSSIP_REGISTER Message_MessageType = 201 Message_GOSSIP_UNREGISTER Message_MessageType = 202 Message_GOSSIP_BLOCK_REQUEST Message_MessageType = 205 Message_GOSSIP_BLOCK_RESPONSE Message_MessageType = 206 Message_GOSSIP_BATCH_BY_BATCH_ID_REQUEST Message_MessageType = 207 Message_GOSSIP_BATCH_BY_TRANSACTION_ID_REQUEST Message_MessageType = 208 Message_GOSSIP_BATCH_RESPONSE Message_MessageType = 209 Message_GOSSIP_GET_PEERS_REQUEST Message_MessageType = 210 Message_GOSSIP_GET_PEERS_RESPONSE Message_MessageType = 211 Message_GOSSIP_CONSENSUS_MESSAGE Message_MessageType = 212 Message_NETWORK_ACK Message_MessageType = 300 Message_NETWORK_CONNECT Message_MessageType = 301 Message_NETWORK_DISCONNECT Message_MessageType = 302 // Message types for Authorization Types Message_AUTHORIZATION_CONNECTION_RESPONSE Message_MessageType = 600 Message_AUTHORIZATION_VIOLATION Message_MessageType = 601 Message_AUTHORIZATION_TRUST_REQUEST Message_MessageType = 602 Message_AUTHORIZATION_TRUST_RESPONSE Message_MessageType = 603 Message_AUTHORIZATION_CHALLENGE_REQUEST Message_MessageType = 604 Message_AUTHORIZATION_CHALLENGE_RESPONSE Message_MessageType = 605 Message_AUTHORIZATION_CHALLENGE_SUBMIT Message_MessageType = 606 Message_AUTHORIZATION_CHALLENGE_RESULT Message_MessageType = 607 Message_PING_REQUEST Message_MessageType = 700 Message_PING_RESPONSE Message_MessageType = 701 // Consensus service messages Message_CONSENSUS_REGISTER_REQUEST Message_MessageType = 800 Message_CONSENSUS_REGISTER_RESPONSE Message_MessageType = 801 Message_CONSENSUS_SEND_TO_REQUEST Message_MessageType = 802 Message_CONSENSUS_SEND_TO_RESPONSE Message_MessageType = 803 Message_CONSENSUS_BROADCAST_REQUEST Message_MessageType = 804 Message_CONSENSUS_BROADCAST_RESPONSE Message_MessageType = 805 Message_CONSENSUS_INITIALIZE_BLOCK_REQUEST Message_MessageType = 806 Message_CONSENSUS_INITIALIZE_BLOCK_RESPONSE Message_MessageType = 807 Message_CONSENSUS_FINALIZE_BLOCK_REQUEST Message_MessageType = 808 Message_CONSENSUS_FINALIZE_BLOCK_RESPONSE Message_MessageType = 809 Message_CONSENSUS_SUMMARIZE_BLOCK_REQUEST Message_MessageType = 828 Message_CONSENSUS_SUMMARIZE_BLOCK_RESPONSE Message_MessageType = 829 Message_CONSENSUS_CANCEL_BLOCK_REQUEST Message_MessageType = 810 Message_CONSENSUS_CANCEL_BLOCK_RESPONSE Message_MessageType = 811 Message_CONSENSUS_CHECK_BLOCKS_REQUEST Message_MessageType = 812 Message_CONSENSUS_CHECK_BLOCKS_RESPONSE Message_MessageType = 813 Message_CONSENSUS_COMMIT_BLOCK_REQUEST Message_MessageType = 814 Message_CONSENSUS_COMMIT_BLOCK_RESPONSE Message_MessageType = 815 Message_CONSENSUS_IGNORE_BLOCK_REQUEST Message_MessageType = 816 Message_CONSENSUS_IGNORE_BLOCK_RESPONSE Message_MessageType = 817 Message_CONSENSUS_FAIL_BLOCK_REQUEST Message_MessageType = 818 Message_CONSENSUS_FAIL_BLOCK_RESPONSE Message_MessageType = 819 Message_CONSENSUS_SETTINGS_GET_REQUEST Message_MessageType = 820 Message_CONSENSUS_SETTINGS_GET_RESPONSE Message_MessageType = 821 Message_CONSENSUS_STATE_GET_REQUEST Message_MessageType = 822 Message_CONSENSUS_STATE_GET_RESPONSE Message_MessageType = 823 Message_CONSENSUS_BLOCKS_GET_REQUEST Message_MessageType = 824 Message_CONSENSUS_BLOCKS_GET_RESPONSE Message_MessageType = 825 Message_CONSENSUS_CHAIN_HEAD_GET_REQUEST Message_MessageType = 826 Message_CONSENSUS_CHAIN_HEAD_GET_RESPONSE Message_MessageType = 827 // Consensus notification messages Message_CONSENSUS_NOTIFY_PEER_CONNECTED Message_MessageType = 900 Message_CONSENSUS_NOTIFY_PEER_DISCONNECTED Message_MessageType = 901 Message_CONSENSUS_NOTIFY_PEER_MESSAGE Message_MessageType = 902 Message_CONSENSUS_NOTIFY_BLOCK_NEW Message_MessageType = 903 Message_CONSENSUS_NOTIFY_BLOCK_VALID Message_MessageType = 904 Message_CONSENSUS_NOTIFY_BLOCK_INVALID Message_MessageType = 905 Message_CONSENSUS_NOTIFY_BLOCK_COMMIT Message_MessageType = 906 Message_CONSENSUS_NOTIFY_ACK Message_MessageType = 999 ) // Enum value maps for Message_MessageType. var ( Message_MessageType_name = map[int32]string{ 0: "DEFAULT", 1: "TP_REGISTER_REQUEST", 2: "TP_REGISTER_RESPONSE", 3: "TP_UNREGISTER_REQUEST", 4: "TP_UNREGISTER_RESPONSE", 5: "TP_PROCESS_REQUEST", 6: "TP_PROCESS_RESPONSE", 7: "TP_STATE_GET_REQUEST", 8: "TP_STATE_GET_RESPONSE", 9: "TP_STATE_SET_REQUEST", 10: "TP_STATE_SET_RESPONSE", 11: "TP_STATE_DELETE_REQUEST", 12: "TP_STATE_DELETE_RESPONSE", 13: "TP_RECEIPT_ADD_DATA_REQUEST", 14: "TP_RECEIPT_ADD_DATA_RESPONSE", 15: "TP_EVENT_ADD_REQUEST", 16: "TP_EVENT_ADD_RESPONSE", 100: "CLIENT_BATCH_SUBMIT_REQUEST", 101: "CLIENT_BATCH_SUBMIT_RESPONSE", 102: "CLIENT_BLOCK_LIST_REQUEST", 103: "CLIENT_BLOCK_LIST_RESPONSE", 104: "CLIENT_BLOCK_GET_BY_ID_REQUEST", 105: "CLIENT_BLOCK_GET_RESPONSE", 106: "CLIENT_BATCH_LIST_REQUEST", 107: "CLIENT_BATCH_LIST_RESPONSE", 108: "CLIENT_BATCH_GET_REQUEST", 109: "CLIENT_BATCH_GET_RESPONSE", 110: "CLIENT_TRANSACTION_LIST_REQUEST", 111: "CLIENT_TRANSACTION_LIST_RESPONSE", 112: "CLIENT_TRANSACTION_GET_REQUEST", 113: "CLIENT_TRANSACTION_GET_RESPONSE", 114: "CLIENT_STATE_CURRENT_REQUEST", 115: "CLIENT_STATE_CURRENT_RESPONSE", 116: "CLIENT_STATE_LIST_REQUEST", 117: "CLIENT_STATE_LIST_RESPONSE", 118: "CLIENT_STATE_GET_REQUEST", 119: "CLIENT_STATE_GET_RESPONSE", 120: "CLIENT_BATCH_STATUS_REQUEST", 121: "CLIENT_BATCH_STATUS_RESPONSE", 122: "CLIENT_RECEIPT_GET_REQUEST", 123: "CLIENT_RECEIPT_GET_RESPONSE", 124: "CLIENT_BLOCK_GET_BY_NUM_REQUEST", 125: "CLIENT_PEERS_GET_REQUEST", 126: "CLIENT_PEERS_GET_RESPONSE", 127: "CLIENT_BLOCK_GET_BY_TRANSACTION_ID_REQUEST", 128: "CLIENT_BLOCK_GET_BY_BATCH_ID_REQUEST", 129: "CLIENT_STATUS_GET_REQUEST", 130: "CLIENT_STATUS_GET_RESPONSE", 500: "CLIENT_EVENTS_SUBSCRIBE_REQUEST", 501: "CLIENT_EVENTS_SUBSCRIBE_RESPONSE", 502: "CLIENT_EVENTS_UNSUBSCRIBE_REQUEST", 503: "CLIENT_EVENTS_UNSUBSCRIBE_RESPONSE", 504: "CLIENT_EVENTS", 505: "CLIENT_EVENTS_GET_REQUEST", 506: "CLIENT_EVENTS_GET_RESPONSE", 200: "GOSSIP_MESSAGE", 201: "GOSSIP_REGISTER", 202: "GOSSIP_UNREGISTER", 205: "GOSSIP_BLOCK_REQUEST", 206: "GOSSIP_BLOCK_RESPONSE", 207: "GOSSIP_BATCH_BY_BATCH_ID_REQUEST", 208: "GOSSIP_BATCH_BY_TRANSACTION_ID_REQUEST", 209: "GOSSIP_BATCH_RESPONSE", 210: "GOSSIP_GET_PEERS_REQUEST", 211: "GOSSIP_GET_PEERS_RESPONSE", 212: "GOSSIP_CONSENSUS_MESSAGE", 300: "NETWORK_ACK", 301: "NETWORK_CONNECT", 302: "NETWORK_DISCONNECT", 600: "AUTHORIZATION_CONNECTION_RESPONSE", 601: "AUTHORIZATION_VIOLATION", 602: "AUTHORIZATION_TRUST_REQUEST", 603: "AUTHORIZATION_TRUST_RESPONSE", 604: "AUTHORIZATION_CHALLENGE_REQUEST", 605: "AUTHORIZATION_CHALLENGE_RESPONSE", 606: "AUTHORIZATION_CHALLENGE_SUBMIT", 607: "AUTHORIZATION_CHALLENGE_RESULT", 700: "PING_REQUEST", 701: "PING_RESPONSE", 800: "CONSENSUS_REGISTER_REQUEST", 801: "CONSENSUS_REGISTER_RESPONSE", 802: "CONSENSUS_SEND_TO_REQUEST", 803: "CONSENSUS_SEND_TO_RESPONSE", 804: "CONSENSUS_BROADCAST_REQUEST", 805: "CONSENSUS_BROADCAST_RESPONSE", 806: "CONSENSUS_INITIALIZE_BLOCK_REQUEST", 807: "CONSENSUS_INITIALIZE_BLOCK_RESPONSE", 808: "CONSENSUS_FINALIZE_BLOCK_REQUEST", 809: "CONSENSUS_FINALIZE_BLOCK_RESPONSE", 828: "CONSENSUS_SUMMARIZE_BLOCK_REQUEST", 829: "CONSENSUS_SUMMARIZE_BLOCK_RESPONSE", 810: "CONSENSUS_CANCEL_BLOCK_REQUEST", 811: "CONSENSUS_CANCEL_BLOCK_RESPONSE", 812: "CONSENSUS_CHECK_BLOCKS_REQUEST", 813: "CONSENSUS_CHECK_BLOCKS_RESPONSE", 814: "CONSENSUS_COMMIT_BLOCK_REQUEST", 815: "CONSENSUS_COMMIT_BLOCK_RESPONSE", 816: "CONSENSUS_IGNORE_BLOCK_REQUEST", 817: "CONSENSUS_IGNORE_BLOCK_RESPONSE", 818: "CONSENSUS_FAIL_BLOCK_REQUEST", 819: "CONSENSUS_FAIL_BLOCK_RESPONSE", 820: "CONSENSUS_SETTINGS_GET_REQUEST", 821: "CONSENSUS_SETTINGS_GET_RESPONSE", 822: "CONSENSUS_STATE_GET_REQUEST", 823: "CONSENSUS_STATE_GET_RESPONSE", 824: "CONSENSUS_BLOCKS_GET_REQUEST", 825: "CONSENSUS_BLOCKS_GET_RESPONSE", 826: "CONSENSUS_CHAIN_HEAD_GET_REQUEST", 827: "CONSENSUS_CHAIN_HEAD_GET_RESPONSE", 900: "CONSENSUS_NOTIFY_PEER_CONNECTED", 901: "CONSENSUS_NOTIFY_PEER_DISCONNECTED", 902: "CONSENSUS_NOTIFY_PEER_MESSAGE", 903: "CONSENSUS_NOTIFY_BLOCK_NEW", 904: "CONSENSUS_NOTIFY_BLOCK_VALID", 905: "CONSENSUS_NOTIFY_BLOCK_INVALID", 906: "CONSENSUS_NOTIFY_BLOCK_COMMIT", 999: "CONSENSUS_NOTIFY_ACK", } Message_MessageType_value = map[string]int32{ "DEFAULT": 0, "TP_REGISTER_REQUEST": 1, "TP_REGISTER_RESPONSE": 2, "TP_UNREGISTER_REQUEST": 3, "TP_UNREGISTER_RESPONSE": 4, "TP_PROCESS_REQUEST": 5, "TP_PROCESS_RESPONSE": 6, "TP_STATE_GET_REQUEST": 7, "TP_STATE_GET_RESPONSE": 8, "TP_STATE_SET_REQUEST": 9, "TP_STATE_SET_RESPONSE": 10, "TP_STATE_DELETE_REQUEST": 11, "TP_STATE_DELETE_RESPONSE": 12, "TP_RECEIPT_ADD_DATA_REQUEST": 13, "TP_RECEIPT_ADD_DATA_RESPONSE": 14, "TP_EVENT_ADD_REQUEST": 15, "TP_EVENT_ADD_RESPONSE": 16, "CLIENT_BATCH_SUBMIT_REQUEST": 100, "CLIENT_BATCH_SUBMIT_RESPONSE": 101, "CLIENT_BLOCK_LIST_REQUEST": 102, "CLIENT_BLOCK_LIST_RESPONSE": 103, "CLIENT_BLOCK_GET_BY_ID_REQUEST": 104, "CLIENT_BLOCK_GET_RESPONSE": 105, "CLIENT_BATCH_LIST_REQUEST": 106, "CLIENT_BATCH_LIST_RESPONSE": 107, "CLIENT_BATCH_GET_REQUEST": 108, "CLIENT_BATCH_GET_RESPONSE": 109, "CLIENT_TRANSACTION_LIST_REQUEST": 110, "CLIENT_TRANSACTION_LIST_RESPONSE": 111, "CLIENT_TRANSACTION_GET_REQUEST": 112, "CLIENT_TRANSACTION_GET_RESPONSE": 113, "CLIENT_STATE_CURRENT_REQUEST": 114, "CLIENT_STATE_CURRENT_RESPONSE": 115, "CLIENT_STATE_LIST_REQUEST": 116, "CLIENT_STATE_LIST_RESPONSE": 117, "CLIENT_STATE_GET_REQUEST": 118, "CLIENT_STATE_GET_RESPONSE": 119, "CLIENT_BATCH_STATUS_REQUEST": 120, "CLIENT_BATCH_STATUS_RESPONSE": 121, "CLIENT_RECEIPT_GET_REQUEST": 122, "CLIENT_RECEIPT_GET_RESPONSE": 123, "CLIENT_BLOCK_GET_BY_NUM_REQUEST": 124, "CLIENT_PEERS_GET_REQUEST": 125, "CLIENT_PEERS_GET_RESPONSE": 126, "CLIENT_BLOCK_GET_BY_TRANSACTION_ID_REQUEST": 127, "CLIENT_BLOCK_GET_BY_BATCH_ID_REQUEST": 128, "CLIENT_STATUS_GET_REQUEST": 129, "CLIENT_STATUS_GET_RESPONSE": 130, "CLIENT_EVENTS_SUBSCRIBE_REQUEST": 500, "CLIENT_EVENTS_SUBSCRIBE_RESPONSE": 501, "CLIENT_EVENTS_UNSUBSCRIBE_REQUEST": 502, "CLIENT_EVENTS_UNSUBSCRIBE_RESPONSE": 503, "CLIENT_EVENTS": 504, "CLIENT_EVENTS_GET_REQUEST": 505, "CLIENT_EVENTS_GET_RESPONSE": 506, "GOSSIP_MESSAGE": 200, "GOSSIP_REGISTER": 201, "GOSSIP_UNREGISTER": 202, "GOSSIP_BLOCK_REQUEST": 205, "GOSSIP_BLOCK_RESPONSE": 206, "GOSSIP_BATCH_BY_BATCH_ID_REQUEST": 207, "GOSSIP_BATCH_BY_TRANSACTION_ID_REQUEST": 208, "GOSSIP_BATCH_RESPONSE": 209, "GOSSIP_GET_PEERS_REQUEST": 210, "GOSSIP_GET_PEERS_RESPONSE": 211, "GOSSIP_CONSENSUS_MESSAGE": 212, "NETWORK_ACK": 300, "NETWORK_CONNECT": 301, "NETWORK_DISCONNECT": 302, "AUTHORIZATION_CONNECTION_RESPONSE": 600, "AUTHORIZATION_VIOLATION": 601, "AUTHORIZATION_TRUST_REQUEST": 602, "AUTHORIZATION_TRUST_RESPONSE": 603, "AUTHORIZATION_CHALLENGE_REQUEST": 604, "AUTHORIZATION_CHALLENGE_RESPONSE": 605, "AUTHORIZATION_CHALLENGE_SUBMIT": 606, "AUTHORIZATION_CHALLENGE_RESULT": 607, "PING_REQUEST": 700, "PING_RESPONSE": 701, "CONSENSUS_REGISTER_REQUEST": 800, "CONSENSUS_REGISTER_RESPONSE": 801, "CONSENSUS_SEND_TO_REQUEST": 802, "CONSENSUS_SEND_TO_RESPONSE": 803, "CONSENSUS_BROADCAST_REQUEST": 804, "CONSENSUS_BROADCAST_RESPONSE": 805, "CONSENSUS_INITIALIZE_BLOCK_REQUEST": 806, "CONSENSUS_INITIALIZE_BLOCK_RESPONSE": 807, "CONSENSUS_FINALIZE_BLOCK_REQUEST": 808, "CONSENSUS_FINALIZE_BLOCK_RESPONSE": 809, "CONSENSUS_SUMMARIZE_BLOCK_REQUEST": 828, "CONSENSUS_SUMMARIZE_BLOCK_RESPONSE": 829, "CONSENSUS_CANCEL_BLOCK_REQUEST": 810, "CONSENSUS_CANCEL_BLOCK_RESPONSE": 811, "CONSENSUS_CHECK_BLOCKS_REQUEST": 812, "CONSENSUS_CHECK_BLOCKS_RESPONSE": 813, "CONSENSUS_COMMIT_BLOCK_REQUEST": 814, "CONSENSUS_COMMIT_BLOCK_RESPONSE": 815, "CONSENSUS_IGNORE_BLOCK_REQUEST": 816, "CONSENSUS_IGNORE_BLOCK_RESPONSE": 817, "CONSENSUS_FAIL_BLOCK_REQUEST": 818, "CONSENSUS_FAIL_BLOCK_RESPONSE": 819, "CONSENSUS_SETTINGS_GET_REQUEST": 820, "CONSENSUS_SETTINGS_GET_RESPONSE": 821, "CONSENSUS_STATE_GET_REQUEST": 822, "CONSENSUS_STATE_GET_RESPONSE": 823, "CONSENSUS_BLOCKS_GET_REQUEST": 824, "CONSENSUS_BLOCKS_GET_RESPONSE": 825, "CONSENSUS_CHAIN_HEAD_GET_REQUEST": 826, "CONSENSUS_CHAIN_HEAD_GET_RESPONSE": 827, "CONSENSUS_NOTIFY_PEER_CONNECTED": 900, "CONSENSUS_NOTIFY_PEER_DISCONNECTED": 901, "CONSENSUS_NOTIFY_PEER_MESSAGE": 902, "CONSENSUS_NOTIFY_BLOCK_NEW": 903, "CONSENSUS_NOTIFY_BLOCK_VALID": 904, "CONSENSUS_NOTIFY_BLOCK_INVALID": 905, "CONSENSUS_NOTIFY_BLOCK_COMMIT": 906, "CONSENSUS_NOTIFY_ACK": 999, } ) func (x Message_MessageType) Enum() *Message_MessageType { p := new(Message_MessageType) *p = x return p } func (x Message_MessageType) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (Message_MessageType) Descriptor() protoreflect.EnumDescriptor { return file_protobuf_validator_pb2_validator_proto_enumTypes[0].Descriptor() } func (Message_MessageType) Type() protoreflect.EnumType { return &file_protobuf_validator_pb2_validator_proto_enumTypes[0] } func (x Message_MessageType) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use Message_MessageType.Descriptor instead. func (Message_MessageType) EnumDescriptor() ([]byte, []int) { return file_protobuf_validator_pb2_validator_proto_rawDescGZIP(), []int{1, 0} } // A list of messages to be transmitted together. type MessageList struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Messages []*Message `protobuf:"bytes,1,rep,name=messages,proto3" json:"messages,omitempty"` } func (x *MessageList) Reset() { *x = MessageList{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_validator_pb2_validator_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *MessageList) String() string { return protoimpl.X.MessageStringOf(x) } func (*MessageList) ProtoMessage() {} func (x *MessageList) ProtoReflect() protoreflect.Message { mi := &file_protobuf_validator_pb2_validator_proto_msgTypes[0] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use MessageList.ProtoReflect.Descriptor instead. func (*MessageList) Descriptor() ([]byte, []int) { return file_protobuf_validator_pb2_validator_proto_rawDescGZIP(), []int{0} } func (x *MessageList) GetMessages() []*Message { if x != nil { return x.Messages } return nil } // The message passed between the validator and client, containing the // header fields and content. type Message struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // The type of message, used to determine how to 'route' the message // to the appropriate handler as well as how to deserialize the // content. MessageType Message_MessageType `protobuf:"varint,1,opt,name=message_type,json=messageType,proto3,enum=Message_MessageType" json:"message_type,omitempty"` // The identifier used to correlate response messages to their related // request messages. correlation_id should be set to a random string // for messages which are not responses to previously sent messages. For // response messages, correlation_id should be set to the same string as // contained in the request message. CorrelationId string `protobuf:"bytes,2,opt,name=correlation_id,json=correlationId,proto3" json:"correlation_id,omitempty"` // The content of the message, defined by message_type. In many // cases, this data has been serialized with Protocol Buffers or // CBOR. Content []byte `protobuf:"bytes,3,opt,name=content,proto3" json:"content,omitempty"` } func (x *Message) Reset() { *x = Message{} if protoimpl.UnsafeEnabled { mi := &file_protobuf_validator_pb2_validator_proto_msgTypes[1] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *Message) String() string { return protoimpl.X.MessageStringOf(x) } func (*Message) ProtoMessage() {} func (x *Message) ProtoReflect() protoreflect.Message { mi := &file_protobuf_validator_pb2_validator_proto_msgTypes[1] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use Message.ProtoReflect.Descriptor instead. func (*Message) Descriptor() ([]byte, []int) { return file_protobuf_validator_pb2_validator_proto_rawDescGZIP(), []int{1} } func (x *Message) GetMessageType() Message_MessageType { if x != nil { return x.MessageType } return Message_DEFAULT } func (x *Message) GetCorrelationId() string { if x != nil { return x.CorrelationId } return "" } func (x *Message) GetContent() []byte { if x != nil { return x.Content } return nil } var File_protobuf_validator_pb2_validator_proto protoreflect.FileDescriptor var file_protobuf_validator_pb2_validator_proto_rawDesc = []byte{ 0x0a, 0x26, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x76, 0x61, 0x6c, 0x69, 0x64, 0x61, 0x74, 0x6f, 0x72, 0x5f, 0x70, 0x62, 0x32, 0x2f, 0x76, 0x61, 0x6c, 0x69, 0x64, 0x61, 0x74, 0x6f, 0x72, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0x33, 0x0a, 0x0b, 0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x4c, 0x69, 0x73, 0x74, 0x12, 0x24, 0x0a, 0x08, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x08, 0x2e, 0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x52, 0x08, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x73, 0x22, 0xa5, 0x1f, 0x0a, 0x07, 0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x12, 0x37, 0x0a, 0x0c, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x5f, 0x74, 0x79, 0x70, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x14, 0x2e, 0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x2e, 0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x54, 0x79, 0x70, 0x65, 0x52, 0x0b, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x54, 0x79, 0x70, 0x65, 0x12, 0x25, 0x0a, 0x0e, 0x63, 0x6f, 0x72, 0x72, 0x65, 0x6c, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x69, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0d, 0x63, 0x6f, 0x72, 0x72, 0x65, 0x6c, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x49, 0x64, 0x12, 0x18, 0x0a, 0x07, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x07, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x22, 0x9f, 0x1e, 0x0a, 0x0b, 0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x54, 0x79, 0x70, 0x65, 0x12, 0x0b, 0x0a, 0x07, 0x44, 0x45, 0x46, 0x41, 0x55, 0x4c, 0x54, 0x10, 0x00, 0x12, 0x17, 0x0a, 0x13, 0x54, 0x50, 0x5f, 0x52, 0x45, 0x47, 0x49, 0x53, 0x54, 0x45, 0x52, 0x5f, 0x52, 0x45, 0x51, 0x55, 0x45, 0x53, 0x54, 0x10, 0x01, 0x12, 0x18, 0x0a, 0x14, 0x54, 0x50, 0x5f, 0x52, 0x45, 0x47, 0x49, 0x53, 0x54, 0x45, 0x52, 0x5f, 0x52, 0x45, 0x53, 0x50, 0x4f, 0x4e, 0x53, 0x45, 0x10, 0x02, 0x12, 0x19, 0x0a, 0x15, 0x54, 0x50, 0x5f, 0x55, 0x4e, 0x52, 0x45, 0x47, 0x49, 0x53, 0x54, 0x45, 0x52, 0x5f, 0x52, 0x45, 0x51, 0x55, 0x45, 0x53, 0x54, 0x10, 0x03, 0x12, 0x1a, 0x0a, 0x16, 0x54, 0x50, 0x5f, 0x55, 0x4e, 0x52, 0x45, 0x47, 0x49, 0x53, 0x54, 0x45, 0x52, 0x5f, 0x52, 0x45, 0x53, 0x50, 0x4f, 0x4e, 0x53, 0x45, 0x10, 0x04, 0x12, 0x16, 0x0a, 0x12, 0x54, 0x50, 0x5f, 0x50, 0x52, 0x4f, 0x43, 0x45, 0x53, 0x53, 0x5f, 0x52, 0x45, 0x51, 0x55, 0x45, 0x53, 0x54, 0x10, 0x05, 0x12, 0x17, 0x0a, 0x13, 0x54, 0x50, 0x5f, 0x50, 0x52, 0x4f, 0x43, 0x45, 0x53, 0x53, 0x5f, 0x52, 0x45, 0x53, 0x50, 0x4f, 0x4e, 0x53, 0x45, 0x10, 0x06, 0x12, 0x18, 0x0a, 0x14, 0x54, 0x50, 0x5f, 0x53, 0x54, 0x41, 0x54, 0x45, 0x5f, 0x47, 0x45, 0x54, 0x5f, 0x52, 0x45, 0x51, 0x55, 0x45, 0x53, 0x54, 0x10, 0x07, 0x12, 0x19, 0x0a, 0x15, 0x54, 0x50, 0x5f, 0x53, 0x54, 0x41, 0x54, 0x45, 0x5f, 0x47, 0x45, 0x54, 0x5f, 0x52, 0x45, 0x53, 0x50, 0x4f, 0x4e, 0x53, 0x45, 0x10, 0x08, 0x12, 0x18, 0x0a, 0x14, 0x54, 0x50, 0x5f, 0x53, 0x54, 0x41, 0x54, 0x45, 0x5f, 0x53, 0x45, 0x54, 0x5f, 0x52, 0x45, 0x51, 0x55, 0x45, 0x53, 0x54, 0x10, 0x09, 0x12, 0x19, 0x0a, 0x15, 0x54, 0x50, 0x5f, 0x53, 0x54, 0x41, 0x54, 0x45, 0x5f, 0x53, 0x45, 0x54, 0x5f, 0x52, 0x45, 0x53, 0x50, 0x4f, 0x4e, 0x53, 0x45, 0x10, 0x0a, 0x12, 0x1b, 0x0a, 0x17, 0x54, 0x50, 0x5f, 0x53, 0x54, 0x41, 0x54, 0x45, 0x5f, 0x44, 0x45, 0x4c, 0x45, 0x54, 0x45, 0x5f, 0x52, 0x45, 0x51, 0x55, 0x45, 0x53, 0x54, 0x10, 0x0b, 0x12, 0x1c, 0x0a, 0x18, 0x54, 0x50, 0x5f, 0x53, 0x54, 0x41, 0x54, 0x45, 0x5f, 0x44, 0x45, 0x4c, 0x45, 0x54, 0x45, 0x5f, 0x52, 0x45, 0x53, 0x50, 0x4f, 0x4e, 0x53, 0x45, 0x10, 0x0c, 0x12, 0x1f, 0x0a, 0x1b, 0x54, 0x50, 0x5f, 0x52, 0x45, 0x43, 0x45, 0x49, 0x50, 0x54, 0x5f, 0x41, 0x44, 0x44, 0x5f, 0x44, 0x41, 0x54, 0x41, 0x5f, 0x52, 0x45, 0x51, 0x55, 0x45, 0x53, 0x54, 0x10, 0x0d, 0x12, 0x20, 0x0a, 0x1c, 0x54, 0x50, 0x5f, 0x52, 0x45, 0x43, 0x45, 0x49, 0x50, 0x54, 0x5f, 0x41, 0x44, 0x44, 0x5f, 0x44, 0x41, 0x54, 0x41, 0x5f, 0x52, 0x45, 0x53, 0x50, 0x4f, 0x4e, 0x53, 0x45, 0x10, 0x0e, 0x12, 0x18, 0x0a, 0x14, 0x54, 0x50, 0x5f, 0x45, 0x56, 0x45, 0x4e, 0x54, 0x5f, 0x41, 0x44, 0x44, 0x5f, 0x52, 0x45, 0x51, 0x55, 0x45, 0x53, 0x54, 0x10, 0x0f, 0x12, 0x19, 0x0a, 0x15, 0x54, 0x50, 0x5f, 0x45, 0x56, 0x45, 0x4e, 0x54, 0x5f, 0x41, 0x44, 0x44, 0x5f, 0x52, 0x45, 0x53, 0x50, 0x4f, 0x4e, 0x53, 0x45, 0x10, 0x10, 0x12, 0x1f, 0x0a, 0x1b, 0x43, 0x4c, 0x49, 0x45, 0x4e, 0x54, 0x5f, 0x42, 0x41, 0x54, 0x43, 0x48, 0x5f, 0x53, 0x55, 0x42, 0x4d, 0x49, 0x54, 0x5f, 0x52, 0x45, 0x51, 0x55, 0x45, 0x53, 0x54, 0x10, 0x64, 0x12, 0x20, 0x0a, 0x1c, 0x43, 0x4c, 0x49, 0x45, 0x4e, 0x54, 0x5f, 0x42, 0x41, 0x54, 0x43, 0x48, 0x5f, 0x53, 0x55, 0x42, 0x4d, 0x49, 0x54, 0x5f, 0x52, 0x45, 0x53, 0x50, 0x4f, 0x4e, 0x53, 0x45, 0x10, 0x65, 0x12, 0x1d, 0x0a, 0x19, 0x43, 0x4c, 0x49, 0x45, 0x4e, 0x54, 0x5f, 0x42, 0x4c, 0x4f, 0x43, 0x4b, 0x5f, 0x4c, 0x49, 0x53, 0x54, 0x5f, 0x52, 0x45, 0x51, 0x55, 0x45, 0x53, 0x54, 0x10, 0x66, 0x12, 0x1e, 0x0a, 0x1a, 0x43, 0x4c, 0x49, 0x45, 0x4e, 0x54, 0x5f, 0x42, 0x4c, 0x4f, 0x43, 0x4b, 0x5f, 0x4c, 0x49, 0x53, 0x54, 0x5f, 0x52, 0x45, 0x53, 0x50, 0x4f, 0x4e, 0x53, 0x45, 0x10, 0x67, 0x12, 0x22, 0x0a, 0x1e, 0x43, 0x4c, 0x49, 0x45, 0x4e, 0x54, 0x5f, 0x42, 0x4c, 0x4f, 0x43, 0x4b, 0x5f, 0x47, 0x45, 0x54, 0x5f, 0x42, 0x59, 0x5f, 0x49, 0x44, 0x5f, 0x52, 0x45, 0x51, 0x55, 0x45, 0x53, 0x54, 0x10, 0x68, 0x12, 0x1d, 0x0a, 0x19, 0x43, 0x4c, 0x49, 0x45, 0x4e, 0x54, 0x5f, 0x42, 0x4c, 0x4f, 0x43, 0x4b, 0x5f, 0x47, 0x45, 0x54, 0x5f, 0x52, 0x45, 0x53, 0x50, 0x4f, 0x4e, 0x53, 0x45, 0x10, 0x69, 0x12, 0x1d, 0x0a, 0x19, 0x43, 0x4c, 0x49, 0x45, 0x4e, 0x54, 0x5f, 0x42, 0x41, 0x54, 0x43, 0x48, 0x5f, 0x4c, 0x49, 0x53, 0x54, 0x5f, 0x52, 0x45, 0x51, 0x55, 0x45, 0x53, 0x54, 0x10, 0x6a, 0x12, 0x1e, 0x0a, 0x1a, 0x43, 0x4c, 0x49, 0x45, 0x4e, 0x54, 0x5f, 0x42, 0x41, 0x54, 0x43, 0x48, 0x5f, 0x4c, 0x49, 0x53, 0x54, 0x5f, 0x52, 0x45, 0x53, 0x50, 0x4f, 0x4e, 0x53, 0x45, 0x10, 0x6b, 0x12, 0x1c, 0x0a, 0x18, 0x43, 0x4c, 0x49, 0x45, 0x4e, 0x54, 0x5f, 0x42, 0x41, 0x54, 0x43, 0x48, 0x5f, 0x47, 0x45, 0x54, 0x5f, 0x52, 0x45, 0x51, 0x55, 0x45, 0x53, 0x54, 0x10, 0x6c, 0x12, 0x1d, 0x0a, 0x19, 0x43, 0x4c, 0x49, 0x45, 0x4e, 0x54, 0x5f, 0x42, 0x41, 0x54, 0x43, 0x48, 0x5f, 0x47, 0x45, 0x54, 0x5f, 0x52, 0x45, 0x53, 0x50, 0x4f, 0x4e, 0x53, 0x45, 0x10, 0x6d, 0x12, 0x23, 0x0a, 0x1f, 0x43, 0x4c, 0x49, 0x45, 0x4e, 0x54, 0x5f, 0x54, 0x52, 0x41, 0x4e, 0x53, 0x41, 0x43, 0x54, 0x49, 0x4f, 0x4e, 0x5f, 0x4c, 0x49, 0x53, 0x54, 0x5f, 0x52, 0x45, 0x51, 0x55, 0x45, 0x53, 0x54, 0x10, 0x6e, 0x12, 0x24, 0x0a, 0x20, 0x43, 0x4c, 0x49, 0x45, 0x4e, 0x54, 0x5f, 0x54, 0x52, 0x41, 0x4e, 0x53, 0x41, 0x43, 0x54, 0x49, 0x4f, 0x4e, 0x5f, 0x4c, 0x49, 0x53, 0x54, 0x5f, 0x52, 0x45, 0x53, 0x50, 0x4f, 0x4e, 0x53, 0x45, 0x10, 0x6f, 0x12, 0x22, 0x0a, 0x1e, 0x43, 0x4c, 0x49, 0x45, 0x4e, 0x54, 0x5f, 0x54, 0x52, 0x41, 0x4e, 0x53, 0x41, 0x43, 0x54, 0x49, 0x4f, 0x4e, 0x5f, 0x47, 0x45, 0x54, 0x5f, 0x52, 0x45, 0x51, 0x55, 0x45, 0x53, 0x54, 0x10, 0x70, 0x12, 0x23, 0x0a, 0x1f, 0x43, 0x4c, 0x49, 0x45, 0x4e, 0x54, 0x5f, 0x54, 0x52, 0x41, 0x4e, 0x53, 0x41, 0x43, 0x54, 0x49, 0x4f, 0x4e, 0x5f, 0x47, 0x45, 0x54, 0x5f, 0x52, 0x45, 0x53, 0x50, 0x4f, 0x4e, 0x53, 0x45, 0x10, 0x71, 0x12, 0x20, 0x0a, 0x1c, 0x43, 0x4c, 0x49, 0x45, 0x4e, 0x54, 0x5f, 0x53, 0x54, 0x41, 0x54, 0x45, 0x5f, 0x43, 0x55, 0x52, 0x52, 0x45, 0x4e, 0x54, 0x5f, 0x52, 0x45, 0x51, 0x55, 0x45, 0x53, 0x54, 0x10, 0x72, 0x12, 0x21, 0x0a, 0x1d, 0x43, 0x4c, 0x49, 0x45, 0x4e, 0x54, 0x5f, 0x53, 0x54, 0x41, 0x54, 0x45, 0x5f, 0x43, 0x55, 0x52, 0x52, 0x45, 0x4e, 0x54, 0x5f, 0x52, 0x45, 0x53, 0x50, 0x4f, 0x4e, 0x53, 0x45, 0x10, 0x73, 0x12, 0x1d, 0x0a, 0x19, 0x43, 0x4c, 0x49, 0x45, 0x4e, 0x54, 0x5f, 0x53, 0x54, 0x41, 0x54, 0x45, 0x5f, 0x4c, 0x49, 0x53, 0x54, 0x5f, 0x52, 0x45, 0x51, 0x55, 0x45, 0x53, 0x54, 0x10, 0x74, 0x12, 0x1e, 0x0a, 0x1a, 0x43, 0x4c, 0x49, 0x45, 0x4e, 0x54, 0x5f, 0x53, 0x54, 0x41, 0x54, 0x45, 0x5f, 0x4c, 0x49, 0x53, 0x54, 0x5f, 0x52, 0x45, 0x53, 0x50, 0x4f, 0x4e, 0x53, 0x45, 0x10, 0x75, 0x12, 0x1c, 0x0a, 0x18, 0x43, 0x4c, 0x49, 0x45, 0x4e, 0x54, 0x5f, 0x53, 0x54, 0x41, 0x54, 0x45, 0x5f, 0x47, 0x45, 0x54, 0x5f, 0x52, 0x45, 0x51, 0x55, 0x45, 0x53, 0x54, 0x10, 0x76, 0x12, 0x1d, 0x0a, 0x19, 0x43, 0x4c, 0x49, 0x45, 0x4e, 0x54, 0x5f, 0x53, 0x54, 0x41, 0x54, 0x45, 0x5f, 0x47, 0x45, 0x54, 0x5f, 0x52, 0x45, 0x53, 0x50, 0x4f, 0x4e, 0x53, 0x45, 0x10, 0x77, 0x12, 0x1f, 0x0a, 0x1b, 0x43, 0x4c, 0x49, 0x45, 0x4e, 0x54, 0x5f, 0x42, 0x41, 0x54, 0x43, 0x48, 0x5f, 0x53, 0x54, 0x41, 0x54, 0x55, 0x53, 0x5f, 0x52, 0x45, 0x51, 0x55, 0x45, 0x53, 0x54, 0x10, 0x78, 0x12, 0x20, 0x0a, 0x1c, 0x43, 0x4c, 0x49, 0x45, 0x4e, 0x54, 0x5f, 0x42, 0x41, 0x54, 0x43, 0x48, 0x5f, 0x53, 0x54, 0x41, 0x54, 0x55, 0x53, 0x5f, 0x52, 0x45, 0x53, 0x50, 0x4f, 0x4e, 0x53, 0x45, 0x10, 0x79, 0x12, 0x1e, 0x0a, 0x1a, 0x43, 0x4c, 0x49, 0x45, 0x4e, 0x54, 0x5f, 0x52, 0x45, 0x43, 0x45, 0x49, 0x50, 0x54, 0x5f, 0x47, 0x45, 0x54, 0x5f, 0x52, 0x45, 0x51, 0x55, 0x45, 0x53, 0x54, 0x10, 0x7a, 0x12, 0x1f, 0x0a, 0x1b, 0x43, 0x4c, 0x49, 0x45, 0x4e, 0x54, 0x5f, 0x52, 0x45, 0x43, 0x45, 0x49, 0x50, 0x54, 0x5f, 0x47, 0x45, 0x54, 0x5f, 0x52, 0x45, 0x53, 0x50, 0x4f, 0x4e, 0x53, 0x45, 0x10, 0x7b, 0x12, 0x23, 0x0a, 0x1f, 0x43, 0x4c, 0x49, 0x45, 0x4e, 0x54, 0x5f, 0x42, 0x4c, 0x4f, 0x43, 0x4b, 0x5f, 0x47, 0x45, 0x54, 0x5f, 0x42, 0x59, 0x5f, 0x4e, 0x55, 0x4d, 0x5f, 0x52, 0x45, 0x51, 0x55, 0x45, 0x53, 0x54, 0x10, 0x7c, 0x12, 0x1c, 0x0a, 0x18, 0x43, 0x4c, 0x49, 0x45, 0x4e, 0x54, 0x5f, 0x50, 0x45, 0x45, 0x52, 0x53, 0x5f, 0x47, 0x45, 0x54, 0x5f, 0x52, 0x45, 0x51, 0x55, 0x45, 0x53, 0x54, 0x10, 0x7d, 0x12, 0x1d, 0x0a, 0x19, 0x43, 0x4c, 0x49, 0x45, 0x4e, 0x54, 0x5f, 0x50, 0x45, 0x45, 0x52, 0x53, 0x5f, 0x47, 0x45, 0x54, 0x5f, 0x52, 0x45, 0x53, 0x50, 0x4f, 0x4e, 0x53, 0x45, 0x10, 0x7e, 0x12, 0x2e, 0x0a, 0x2a, 0x43, 0x4c, 0x49, 0x45, 0x4e, 0x54, 0x5f, 0x42, 0x4c, 0x4f, 0x43, 0x4b, 0x5f, 0x47, 0x45, 0x54, 0x5f, 0x42, 0x59, 0x5f, 0x54, 0x52, 0x41, 0x4e, 0x53, 0x41, 0x43, 0x54, 0x49, 0x4f, 0x4e, 0x5f, 0x49, 0x44, 0x5f, 0x52, 0x45, 0x51, 0x55, 0x45, 0x53, 0x54, 0x10, 0x7f, 0x12, 0x29, 0x0a, 0x24, 0x43, 0x4c, 0x49, 0x45, 0x4e, 0x54, 0x5f, 0x42, 0x4c, 0x4f, 0x43, 0x4b, 0x5f, 0x47, 0x45, 0x54, 0x5f, 0x42, 0x59, 0x5f, 0x42, 0x41, 0x54, 0x43, 0x48, 0x5f, 0x49, 0x44, 0x5f, 0x52, 0x45, 0x51, 0x55, 0x45, 0x53, 0x54, 0x10, 0x80, 0x01, 0x12, 0x1e, 0x0a, 0x19, 0x43, 0x4c, 0x49, 0x45, 0x4e, 0x54, 0x5f, 0x53, 0x54, 0x41, 0x54, 0x55, 0x53, 0x5f, 0x47, 0x45, 0x54, 0x5f, 0x52, 0x45, 0x51, 0x55, 0x45, 0x53, 0x54, 0x10, 0x81, 0x01, 0x12, 0x1f, 0x0a, 0x1a, 0x43, 0x4c, 0x49, 0x45, 0x4e, 0x54, 0x5f, 0x53, 0x54, 0x41, 0x54, 0x55, 0x53, 0x5f, 0x47, 0x45, 0x54, 0x5f, 0x52, 0x45, 0x53, 0x50, 0x4f, 0x4e, 0x53, 0x45, 0x10, 0x82, 0x01, 0x12, 0x24, 0x0a, 0x1f, 0x43, 0x4c, 0x49, 0x45, 0x4e, 0x54, 0x5f, 0x45, 0x56, 0x45, 0x4e, 0x54, 0x53, 0x5f, 0x53, 0x55, 0x42, 0x53, 0x43, 0x52, 0x49, 0x42, 0x45, 0x5f, 0x52, 0x45, 0x51, 0x55, 0x45, 0x53, 0x54, 0x10, 0xf4, 0x03, 0x12, 0x25, 0x0a, 0x20, 0x43, 0x4c, 0x49, 0x45, 0x4e, 0x54, 0x5f, 0x45, 0x56, 0x45, 0x4e, 0x54, 0x53, 0x5f, 0x53, 0x55, 0x42, 0x53, 0x43, 0x52, 0x49, 0x42, 0x45, 0x5f, 0x52, 0x45, 0x53, 0x50, 0x4f, 0x4e, 0x53, 0x45, 0x10, 0xf5, 0x03, 0x12, 0x26, 0x0a, 0x21, 0x43, 0x4c, 0x49, 0x45, 0x4e, 0x54, 0x5f, 0x45, 0x56, 0x45, 0x4e, 0x54, 0x53, 0x5f, 0x55, 0x4e, 0x53, 0x55, 0x42, 0x53, 0x43, 0x52, 0x49, 0x42, 0x45, 0x5f, 0x52, 0x45, 0x51, 0x55, 0x45, 0x53, 0x54, 0x10, 0xf6, 0x03, 0x12, 0x27, 0x0a, 0x22, 0x43, 0x4c, 0x49, 0x45, 0x4e, 0x54, 0x5f, 0x45, 0x56, 0x45, 0x4e, 0x54, 0x53, 0x5f, 0x55, 0x4e, 0x53, 0x55, 0x42, 0x53, 0x43, 0x52, 0x49, 0x42, 0x45, 0x5f, 0x52, 0x45, 0x53, 0x50, 0x4f, 0x4e, 0x53, 0x45, 0x10, 0xf7, 0x03, 0x12, 0x12, 0x0a, 0x0d, 0x43, 0x4c, 0x49, 0x45, 0x4e, 0x54, 0x5f, 0x45, 0x56, 0x45, 0x4e, 0x54, 0x53, 0x10, 0xf8, 0x03, 0x12, 0x1e, 0x0a, 0x19, 0x43, 0x4c, 0x49, 0x45, 0x4e, 0x54, 0x5f, 0x45, 0x56, 0x45, 0x4e, 0x54, 0x53, 0x5f, 0x47, 0x45, 0x54, 0x5f, 0x52, 0x45, 0x51, 0x55, 0x45, 0x53, 0x54, 0x10, 0xf9, 0x03, 0x12, 0x1f, 0x0a, 0x1a, 0x43, 0x4c, 0x49, 0x45, 0x4e, 0x54, 0x5f, 0x45, 0x56, 0x45, 0x4e, 0x54, 0x53, 0x5f, 0x47, 0x45, 0x54, 0x5f, 0x52, 0x45, 0x53, 0x50, 0x4f, 0x4e, 0x53, 0x45, 0x10, 0xfa, 0x03, 0x12, 0x13, 0x0a, 0x0e, 0x47, 0x4f, 0x53, 0x53, 0x49, 0x50, 0x5f, 0x4d, 0x45, 0x53, 0x53, 0x41, 0x47, 0x45, 0x10, 0xc8, 0x01, 0x12, 0x14, 0x0a, 0x0f, 0x47, 0x4f, 0x53, 0x53, 0x49, 0x50, 0x5f, 0x52, 0x45, 0x47, 0x49, 0x53, 0x54, 0x45, 0x52, 0x10, 0xc9, 0x01, 0x12, 0x16, 0x0a, 0x11, 0x47, 0x4f, 0x53, 0x53, 0x49, 0x50, 0x5f, 0x55, 0x4e, 0x52, 0x45, 0x47, 0x49, 0x53, 0x54, 0x45, 0x52, 0x10, 0xca, 0x01, 0x12, 0x19, 0x0a, 0x14, 0x47, 0x4f, 0x53, 0x53, 0x49, 0x50, 0x5f, 0x42, 0x4c, 0x4f, 0x43, 0x4b, 0x5f, 0x52, 0x45, 0x51, 0x55, 0x45, 0x53, 0x54, 0x10, 0xcd, 0x01, 0x12, 0x1a, 0x0a, 0x15, 0x47, 0x4f, 0x53, 0x53, 0x49, 0x50, 0x5f, 0x42, 0x4c, 0x4f, 0x43, 0x4b, 0x5f, 0x52, 0x45, 0x53, 0x50, 0x4f, 0x4e, 0x53, 0x45, 0x10, 0xce, 0x01, 0x12, 0x25, 0x0a, 0x20, 0x47, 0x4f, 0x53, 0x53, 0x49, 0x50, 0x5f, 0x42, 0x41, 0x54, 0x43, 0x48, 0x5f, 0x42, 0x59, 0x5f, 0x42, 0x41, 0x54, 0x43, 0x48, 0x5f, 0x49, 0x44, 0x5f, 0x52, 0x45, 0x51, 0x55, 0x45, 0x53, 0x54, 0x10, 0xcf, 0x01, 0x12, 0x2b, 0x0a, 0x26, 0x47, 0x4f, 0x53, 0x53, 0x49, 0x50, 0x5f, 0x42, 0x41, 0x54, 0x43, 0x48, 0x5f, 0x42, 0x59, 0x5f, 0x54, 0x52, 0x41, 0x4e, 0x53, 0x41, 0x43, 0x54, 0x49, 0x4f, 0x4e, 0x5f, 0x49, 0x44, 0x5f, 0x52, 0x45, 0x51, 0x55, 0x45, 0x53, 0x54, 0x10, 0xd0, 0x01, 0x12, 0x1a, 0x0a, 0x15, 0x47, 0x4f, 0x53, 0x53, 0x49, 0x50, 0x5f, 0x42, 0x41, 0x54, 0x43, 0x48, 0x5f, 0x52, 0x45, 0x53, 0x50, 0x4f, 0x4e, 0x53, 0x45, 0x10, 0xd1, 0x01, 0x12, 0x1d, 0x0a, 0x18, 0x47, 0x4f, 0x53, 0x53, 0x49, 0x50, 0x5f, 0x47, 0x45, 0x54, 0x5f, 0x50, 0x45, 0x45, 0x52, 0x53, 0x5f, 0x52, 0x45, 0x51, 0x55, 0x45, 0x53, 0x54, 0x10, 0xd2, 0x01, 0x12, 0x1e, 0x0a, 0x19, 0x47, 0x4f, 0x53, 0x53, 0x49, 0x50, 0x5f, 0x47, 0x45, 0x54, 0x5f, 0x50, 0x45, 0x45, 0x52, 0x53, 0x5f, 0x52, 0x45, 0x53, 0x50, 0x4f, 0x4e, 0x53, 0x45, 0x10, 0xd3, 0x01, 0x12, 0x1d, 0x0a, 0x18, 0x47, 0x4f, 0x53, 0x53, 0x49, 0x50, 0x5f, 0x43, 0x4f, 0x4e, 0x53, 0x45, 0x4e, 0x53, 0x55, 0x53, 0x5f, 0x4d, 0x45, 0x53, 0x53, 0x41, 0x47, 0x45, 0x10, 0xd4, 0x01, 0x12, 0x10, 0x0a, 0x0b, 0x4e, 0x45, 0x54, 0x57, 0x4f, 0x52, 0x4b, 0x5f, 0x41, 0x43, 0x4b, 0x10, 0xac, 0x02, 0x12, 0x14, 0x0a, 0x0f, 0x4e, 0x45, 0x54, 0x57, 0x4f, 0x52, 0x4b, 0x5f, 0x43, 0x4f, 0x4e, 0x4e, 0x45, 0x43, 0x54, 0x10, 0xad, 0x02, 0x12, 0x17, 0x0a, 0x12, 0x4e, 0x45, 0x54, 0x57, 0x4f, 0x52, 0x4b, 0x5f, 0x44, 0x49, 0x53, 0x43, 0x4f, 0x4e, 0x4e, 0x45, 0x43, 0x54, 0x10, 0xae, 0x02, 0x12, 0x26, 0x0a, 0x21, 0x41, 0x55, 0x54, 0x48, 0x4f, 0x52, 0x49, 0x5a, 0x41, 0x54, 0x49, 0x4f, 0x4e, 0x5f, 0x43, 0x4f, 0x4e, 0x4e, 0x45, 0x43, 0x54, 0x49, 0x4f, 0x4e, 0x5f, 0x52, 0x45, 0x53, 0x50, 0x4f, 0x4e, 0x53, 0x45, 0x10, 0xd8, 0x04, 0x12, 0x1c, 0x0a, 0x17, 0x41, 0x55, 0x54, 0x48, 0x4f, 0x52, 0x49, 0x5a, 0x41, 0x54, 0x49, 0x4f, 0x4e, 0x5f, 0x56, 0x49, 0x4f, 0x4c, 0x41, 0x54, 0x49, 0x4f, 0x4e, 0x10, 0xd9, 0x04, 0x12, 0x20, 0x0a, 0x1b, 0x41, 0x55, 0x54, 0x48, 0x4f, 0x52, 0x49, 0x5a, 0x41, 0x54, 0x49, 0x4f, 0x4e, 0x5f, 0x54, 0x52, 0x55, 0x53, 0x54, 0x5f, 0x52, 0x45, 0x51, 0x55, 0x45, 0x53, 0x54, 0x10, 0xda, 0x04, 0x12, 0x21, 0x0a, 0x1c, 0x41, 0x55, 0x54, 0x48, 0x4f, 0x52, 0x49, 0x5a, 0x41, 0x54, 0x49, 0x4f, 0x4e, 0x5f, 0x54, 0x52, 0x55, 0x53, 0x54, 0x5f, 0x52, 0x45, 0x53, 0x50, 0x4f, 0x4e, 0x53, 0x45, 0x10, 0xdb, 0x04, 0x12, 0x24, 0x0a, 0x1f, 0x41, 0x55, 0x54, 0x48, 0x4f, 0x52, 0x49, 0x5a, 0x41, 0x54, 0x49, 0x4f, 0x4e, 0x5f, 0x43, 0x48, 0x41, 0x4c, 0x4c, 0x45, 0x4e, 0x47, 0x45, 0x5f, 0x52, 0x45, 0x51, 0x55, 0x45, 0x53, 0x54, 0x10, 0xdc, 0x04, 0x12, 0x25, 0x0a, 0x20, 0x41, 0x55, 0x54, 0x48, 0x4f, 0x52, 0x49, 0x5a, 0x41, 0x54, 0x49, 0x4f, 0x4e, 0x5f, 0x43, 0x48, 0x41, 0x4c, 0x4c, 0x45, 0x4e, 0x47, 0x45, 0x5f, 0x52, 0x45, 0x53, 0x50, 0x4f, 0x4e, 0x53, 0x45, 0x10, 0xdd, 0x04, 0x12, 0x23, 0x0a, 0x1e, 0x41, 0x55, 0x54, 0x48, 0x4f, 0x52, 0x49, 0x5a, 0x41, 0x54, 0x49, 0x4f, 0x4e, 0x5f, 0x43, 0x48, 0x41, 0x4c, 0x4c, 0x45, 0x4e, 0x47, 0x45, 0x5f, 0x53, 0x55, 0x42, 0x4d, 0x49, 0x54, 0x10, 0xde, 0x04, 0x12, 0x23, 0x0a, 0x1e, 0x41, 0x55, 0x54, 0x48, 0x4f, 0x52, 0x49, 0x5a, 0x41, 0x54, 0x49, 0x4f, 0x4e, 0x5f, 0x43, 0x48, 0x41, 0x4c, 0x4c, 0x45, 0x4e, 0x47, 0x45, 0x5f, 0x52, 0x45, 0x53, 0x55, 0x4c, 0x54, 0x10, 0xdf, 0x04, 0x12, 0x11, 0x0a, 0x0c, 0x50, 0x49, 0x4e, 0x47, 0x5f, 0x52, 0x45, 0x51, 0x55, 0x45, 0x53, 0x54, 0x10, 0xbc, 0x05, 0x12, 0x12, 0x0a, 0x0d, 0x50, 0x49, 0x4e, 0x47, 0x5f, 0x52, 0x45, 0x53, 0x50, 0x4f, 0x4e, 0x53, 0x45, 0x10, 0xbd, 0x05, 0x12, 0x1f, 0x0a, 0x1a, 0x43, 0x4f, 0x4e, 0x53, 0x45, 0x4e, 0x53, 0x55, 0x53, 0x5f, 0x52, 0x45, 0x47, 0x49, 0x53, 0x54, 0x45, 0x52, 0x5f, 0x52, 0x45, 0x51, 0x55, 0x45, 0x53, 0x54, 0x10, 0xa0, 0x06, 0x12, 0x20, 0x0a, 0x1b, 0x43, 0x4f, 0x4e, 0x53, 0x45, 0x4e, 0x53, 0x55, 0x53, 0x5f, 0x52, 0x45, 0x47, 0x49, 0x53, 0x54, 0x45, 0x52, 0x5f, 0x52, 0x45, 0x53, 0x50, 0x4f, 0x4e, 0x53, 0x45, 0x10, 0xa1, 0x06, 0x12, 0x1e, 0x0a, 0x19, 0x43, 0x4f, 0x4e, 0x53, 0x45, 0x4e, 0x53, 0x55, 0x53, 0x5f, 0x53, 0x45, 0x4e, 0x44, 0x5f, 0x54, 0x4f, 0x5f, 0x52, 0x45, 0x51, 0x55, 0x45, 0x53, 0x54, 0x10, 0xa2, 0x06, 0x12, 0x1f, 0x0a, 0x1a, 0x43, 0x4f, 0x4e, 0x53, 0x45, 0x4e, 0x53, 0x55, 0x53, 0x5f, 0x53, 0x45, 0x4e, 0x44, 0x5f, 0x54, 0x4f, 0x5f, 0x52, 0x45, 0x53, 0x50, 0x4f, 0x4e, 0x53, 0x45, 0x10, 0xa3, 0x06, 0x12, 0x20, 0x0a, 0x1b, 0x43, 0x4f, 0x4e, 0x53, 0x45, 0x4e, 0x53, 0x55, 0x53, 0x5f, 0x42, 0x52, 0x4f, 0x41, 0x44, 0x43, 0x41, 0x53, 0x54, 0x5f, 0x52, 0x45, 0x51, 0x55, 0x45, 0x53, 0x54, 0x10, 0xa4, 0x06, 0x12, 0x21, 0x0a, 0x1c, 0x43, 0x4f, 0x4e, 0x53, 0x45, 0x4e, 0x53, 0x55, 0x53, 0x5f, 0x42, 0x52, 0x4f, 0x41, 0x44, 0x43, 0x41, 0x53, 0x54, 0x5f, 0x52, 0x45, 0x53, 0x50, 0x4f, 0x4e, 0x53, 0x45, 0x10, 0xa5, 0x06, 0x12, 0x27, 0x0a, 0x22, 0x43, 0x4f, 0x4e, 0x53, 0x45, 0x4e, 0x53, 0x55, 0x53, 0x5f, 0x49, 0x4e, 0x49, 0x54, 0x49, 0x41, 0x4c, 0x49, 0x5a, 0x45, 0x5f, 0x42, 0x4c, 0x4f, 0x43, 0x4b, 0x5f, 0x52, 0x45, 0x51, 0x55, 0x45, 0x53, 0x54, 0x10, 0xa6, 0x06, 0x12, 0x28, 0x0a, 0x23, 0x43, 0x4f, 0x4e, 0x53, 0x45, 0x4e, 0x53, 0x55, 0x53, 0x5f, 0x49, 0x4e, 0x49, 0x54, 0x49, 0x41, 0x4c, 0x49, 0x5a, 0x45, 0x5f, 0x42, 0x4c, 0x4f, 0x43, 0x4b, 0x5f, 0x52, 0x45, 0x53, 0x50, 0x4f, 0x4e, 0x53, 0x45, 0x10, 0xa7, 0x06, 0x12, 0x25, 0x0a, 0x20, 0x43, 0x4f, 0x4e, 0x53, 0x45, 0x4e, 0x53, 0x55, 0x53, 0x5f, 0x46, 0x49, 0x4e, 0x41, 0x4c, 0x49, 0x5a, 0x45, 0x5f, 0x42, 0x4c, 0x4f, 0x43, 0x4b, 0x5f, 0x52, 0x45, 0x51, 0x55, 0x45, 0x53, 0x54, 0x10, 0xa8, 0x06, 0x12, 0x26, 0x0a, 0x21, 0x43, 0x4f, 0x4e, 0x53, 0x45, 0x4e, 0x53, 0x55, 0x53, 0x5f, 0x46, 0x49, 0x4e, 0x41, 0x4c, 0x49, 0x5a, 0x45, 0x5f, 0x42, 0x4c, 0x4f, 0x43, 0x4b, 0x5f, 0x52, 0x45, 0x53, 0x50, 0x4f, 0x4e, 0x53, 0x45, 0x10, 0xa9, 0x06, 0x12, 0x26, 0x0a, 0x21, 0x43, 0x4f, 0x4e, 0x53, 0x45, 0x4e, 0x53, 0x55, 0x53, 0x5f, 0x53, 0x55, 0x4d, 0x4d, 0x41, 0x52, 0x49, 0x5a, 0x45, 0x5f, 0x42, 0x4c, 0x4f, 0x43, 0x4b, 0x5f, 0x52, 0x45, 0x51, 0x55, 0x45, 0x53, 0x54, 0x10, 0xbc, 0x06, 0x12, 0x27, 0x0a, 0x22, 0x43, 0x4f, 0x4e, 0x53, 0x45, 0x4e, 0x53, 0x55, 0x53, 0x5f, 0x53, 0x55, 0x4d, 0x4d, 0x41, 0x52, 0x49, 0x5a, 0x45, 0x5f, 0x42, 0x4c, 0x4f, 0x43, 0x4b, 0x5f, 0x52, 0x45, 0x53, 0x50, 0x4f, 0x4e, 0x53, 0x45, 0x10, 0xbd, 0x06, 0x12, 0x23, 0x0a, 0x1e, 0x43, 0x4f, 0x4e, 0x53, 0x45, 0x4e, 0x53, 0x55, 0x53, 0x5f, 0x43, 0x41, 0x4e, 0x43, 0x45, 0x4c, 0x5f, 0x42, 0x4c, 0x4f, 0x43, 0x4b, 0x5f, 0x52, 0x45, 0x51, 0x55, 0x45, 0x53, 0x54, 0x10, 0xaa, 0x06, 0x12, 0x24, 0x0a, 0x1f, 0x43, 0x4f, 0x4e, 0x53, 0x45, 0x4e, 0x53, 0x55, 0x53, 0x5f, 0x43, 0x41, 0x4e, 0x43, 0x45, 0x4c, 0x5f, 0x42, 0x4c, 0x4f, 0x43, 0x4b, 0x5f, 0x52, 0x45, 0x53, 0x50, 0x4f, 0x4e, 0x53, 0x45, 0x10, 0xab, 0x06, 0x12, 0x23, 0x0a, 0x1e, 0x43, 0x4f, 0x4e, 0x53, 0x45, 0x4e, 0x53, 0x55, 0x53, 0x5f, 0x43, 0x48, 0x45, 0x43, 0x4b, 0x5f, 0x42, 0x4c, 0x4f, 0x43, 0x4b, 0x53, 0x5f, 0x52, 0x45, 0x51, 0x55, 0x45, 0x53, 0x54, 0x10, 0xac, 0x06, 0x12, 0x24, 0x0a, 0x1f, 0x43, 0x4f, 0x4e, 0x53, 0x45, 0x4e, 0x53, 0x55, 0x53, 0x5f, 0x43, 0x48, 0x45, 0x43, 0x4b, 0x5f, 0x42, 0x4c, 0x4f, 0x43, 0x4b, 0x53, 0x5f, 0x52, 0x45, 0x53, 0x50, 0x4f, 0x4e, 0x53, 0x45, 0x10, 0xad, 0x06, 0x12, 0x23, 0x0a, 0x1e, 0x43, 0x4f, 0x4e, 0x53, 0x45, 0x4e, 0x53, 0x55, 0x53, 0x5f, 0x43, 0x4f, 0x4d, 0x4d, 0x49, 0x54, 0x5f, 0x42, 0x4c, 0x4f, 0x43, 0x4b, 0x5f, 0x52, 0x45, 0x51, 0x55, 0x45, 0x53, 0x54, 0x10, 0xae, 0x06, 0x12, 0x24, 0x0a, 0x1f, 0x43, 0x4f, 0x4e, 0x53, 0x45, 0x4e, 0x53, 0x55, 0x53, 0x5f, 0x43, 0x4f, 0x4d, 0x4d, 0x49, 0x54, 0x5f, 0x42, 0x4c, 0x4f, 0x43, 0x4b, 0x5f, 0x52, 0x45, 0x53, 0x50, 0x4f, 0x4e, 0x53, 0x45, 0x10, 0xaf, 0x06, 0x12, 0x23, 0x0a, 0x1e, 0x43, 0x4f, 0x4e, 0x53, 0x45, 0x4e, 0x53, 0x55, 0x53, 0x5f, 0x49, 0x47, 0x4e, 0x4f, 0x52, 0x45, 0x5f, 0x42, 0x4c, 0x4f, 0x43, 0x4b, 0x5f, 0x52, 0x45, 0x51, 0x55, 0x45, 0x53, 0x54, 0x10, 0xb0, 0x06, 0x12, 0x24, 0x0a, 0x1f, 0x43, 0x4f, 0x4e, 0x53, 0x45, 0x4e, 0x53, 0x55, 0x53, 0x5f, 0x49, 0x47, 0x4e, 0x4f, 0x52, 0x45, 0x5f, 0x42, 0x4c, 0x4f, 0x43, 0x4b, 0x5f, 0x52, 0x45, 0x53, 0x50, 0x4f, 0x4e, 0x53, 0x45, 0x10, 0xb1, 0x06, 0x12, 0x21, 0x0a, 0x1c, 0x43, 0x4f, 0x4e, 0x53, 0x45, 0x4e, 0x53, 0x55, 0x53, 0x5f, 0x46, 0x41, 0x49, 0x4c, 0x5f, 0x42, 0x4c, 0x4f, 0x43, 0x4b, 0x5f, 0x52, 0x45, 0x51, 0x55, 0x45, 0x53, 0x54, 0x10, 0xb2, 0x06, 0x12, 0x22, 0x0a, 0x1d, 0x43, 0x4f, 0x4e, 0x53, 0x45, 0x4e, 0x53, 0x55, 0x53, 0x5f, 0x46, 0x41, 0x49, 0x4c, 0x5f, 0x42, 0x4c, 0x4f, 0x43, 0x4b, 0x5f, 0x52, 0x45, 0x53, 0x50, 0x4f, 0x4e, 0x53, 0x45, 0x10, 0xb3, 0x06, 0x12, 0x23, 0x0a, 0x1e, 0x43, 0x4f, 0x4e, 0x53, 0x45, 0x4e, 0x53, 0x55, 0x53, 0x5f, 0x53, 0x45, 0x54, 0x54, 0x49, 0x4e, 0x47, 0x53, 0x5f, 0x47, 0x45, 0x54, 0x5f, 0x52, 0x45, 0x51, 0x55, 0x45, 0x53, 0x54, 0x10, 0xb4, 0x06, 0x12, 0x24, 0x0a, 0x1f, 0x43, 0x4f, 0x4e, 0x53, 0x45, 0x4e, 0x53, 0x55, 0x53, 0x5f, 0x53, 0x45, 0x54, 0x54, 0x49, 0x4e, 0x47, 0x53, 0x5f, 0x47, 0x45, 0x54, 0x5f, 0x52, 0x45, 0x53, 0x50, 0x4f, 0x4e, 0x53, 0x45, 0x10, 0xb5, 0x06, 0x12, 0x20, 0x0a, 0x1b, 0x43, 0x4f, 0x4e, 0x53, 0x45, 0x4e, 0x53, 0x55, 0x53, 0x5f, 0x53, 0x54, 0x41, 0x54, 0x45, 0x5f, 0x47, 0x45, 0x54, 0x5f, 0x52, 0x45, 0x51, 0x55, 0x45, 0x53, 0x54, 0x10, 0xb6, 0x06, 0x12, 0x21, 0x0a, 0x1c, 0x43, 0x4f, 0x4e, 0x53, 0x45, 0x4e, 0x53, 0x55, 0x53, 0x5f, 0x53, 0x54, 0x41, 0x54, 0x45, 0x5f, 0x47, 0x45, 0x54, 0x5f, 0x52, 0x45, 0x53, 0x50, 0x4f, 0x4e, 0x53, 0x45, 0x10, 0xb7, 0x06, 0x12, 0x21, 0x0a, 0x1c, 0x43, 0x4f, 0x4e, 0x53, 0x45, 0x4e, 0x53, 0x55, 0x53, 0x5f, 0x42, 0x4c, 0x4f, 0x43, 0x4b, 0x53, 0x5f, 0x47, 0x45, 0x54, 0x5f, 0x52, 0x45, 0x51, 0x55, 0x45, 0x53, 0x54, 0x10, 0xb8, 0x06, 0x12, 0x22, 0x0a, 0x1d, 0x43, 0x4f, 0x4e, 0x53, 0x45, 0x4e, 0x53, 0x55, 0x53, 0x5f, 0x42, 0x4c, 0x4f, 0x43, 0x4b, 0x53, 0x5f, 0x47, 0x45, 0x54, 0x5f, 0x52, 0x45, 0x53, 0x50, 0x4f, 0x4e, 0x53, 0x45, 0x10, 0xb9, 0x06, 0x12, 0x25, 0x0a, 0x20, 0x43, 0x4f, 0x4e, 0x53, 0x45, 0x4e, 0x53, 0x55, 0x53, 0x5f, 0x43, 0x48, 0x41, 0x49, 0x4e, 0x5f, 0x48, 0x45, 0x41, 0x44, 0x5f, 0x47, 0x45, 0x54, 0x5f, 0x52, 0x45, 0x51, 0x55, 0x45, 0x53, 0x54, 0x10, 0xba, 0x06, 0x12, 0x26, 0x0a, 0x21, 0x43, 0x4f, 0x4e, 0x53, 0x45, 0x4e, 0x53, 0x55, 0x53, 0x5f, 0x43, 0x48, 0x41, 0x49, 0x4e, 0x5f, 0x48, 0x45, 0x41, 0x44, 0x5f, 0x47, 0x45, 0x54, 0x5f, 0x52, 0x45, 0x53, 0x50, 0x4f, 0x4e, 0x53, 0x45, 0x10, 0xbb, 0x06, 0x12, 0x24, 0x0a, 0x1f, 0x43, 0x4f, 0x4e, 0x53, 0x45, 0x4e, 0x53, 0x55, 0x53, 0x5f, 0x4e, 0x4f, 0x54, 0x49, 0x46, 0x59, 0x5f, 0x50, 0x45, 0x45, 0x52, 0x5f, 0x43, 0x4f, 0x4e, 0x4e, 0x45, 0x43, 0x54, 0x45, 0x44, 0x10, 0x84, 0x07, 0x12, 0x27, 0x0a, 0x22, 0x43, 0x4f, 0x4e, 0x53, 0x45, 0x4e, 0x53, 0x55, 0x53, 0x5f, 0x4e, 0x4f, 0x54, 0x49, 0x46, 0x59, 0x5f, 0x50, 0x45, 0x45, 0x52, 0x5f, 0x44, 0x49, 0x53, 0x43, 0x4f, 0x4e, 0x4e, 0x45, 0x43, 0x54, 0x45, 0x44, 0x10, 0x85, 0x07, 0x12, 0x22, 0x0a, 0x1d, 0x43, 0x4f, 0x4e, 0x53, 0x45, 0x4e, 0x53, 0x55, 0x53, 0x5f, 0x4e, 0x4f, 0x54, 0x49, 0x46, 0x59, 0x5f, 0x50, 0x45, 0x45, 0x52, 0x5f, 0x4d, 0x45, 0x53, 0x53, 0x41, 0x47, 0x45, 0x10, 0x86, 0x07, 0x12, 0x1f, 0x0a, 0x1a, 0x43, 0x4f, 0x4e, 0x53, 0x45, 0x4e, 0x53, 0x55, 0x53, 0x5f, 0x4e, 0x4f, 0x54, 0x49, 0x46, 0x59, 0x5f, 0x42, 0x4c, 0x4f, 0x43, 0x4b, 0x5f, 0x4e, 0x45, 0x57, 0x10, 0x87, 0x07, 0x12, 0x21, 0x0a, 0x1c, 0x43, 0x4f, 0x4e, 0x53, 0x45, 0x4e, 0x53, 0x55, 0x53, 0x5f, 0x4e, 0x4f, 0x54, 0x49, 0x46, 0x59, 0x5f, 0x42, 0x4c, 0x4f, 0x43, 0x4b, 0x5f, 0x56, 0x41, 0x4c, 0x49, 0x44, 0x10, 0x88, 0x07, 0x12, 0x23, 0x0a, 0x1e, 0x43, 0x4f, 0x4e, 0x53, 0x45, 0x4e, 0x53, 0x55, 0x53, 0x5f, 0x4e, 0x4f, 0x54, 0x49, 0x46, 0x59, 0x5f, 0x42, 0x4c, 0x4f, 0x43, 0x4b, 0x5f, 0x49, 0x4e, 0x56, 0x41, 0x4c, 0x49, 0x44, 0x10, 0x89, 0x07, 0x12, 0x22, 0x0a, 0x1d, 0x43, 0x4f, 0x4e, 0x53, 0x45, 0x4e, 0x53, 0x55, 0x53, 0x5f, 0x4e, 0x4f, 0x54, 0x49, 0x46, 0x59, 0x5f, 0x42, 0x4c, 0x4f, 0x43, 0x4b, 0x5f, 0x43, 0x4f, 0x4d, 0x4d, 0x49, 0x54, 0x10, 0x8a, 0x07, 0x12, 0x19, 0x0a, 0x14, 0x43, 0x4f, 0x4e, 0x53, 0x45, 0x4e, 0x53, 0x55, 0x53, 0x5f, 0x4e, 0x4f, 0x54, 0x49, 0x46, 0x59, 0x5f, 0x41, 0x43, 0x4b, 0x10, 0xe7, 0x07, 0x42, 0x28, 0x0a, 0x15, 0x73, 0x61, 0x77, 0x74, 0x6f, 0x6f, 0x74, 0x68, 0x2e, 0x73, 0x64, 0x6b, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x50, 0x01, 0x5a, 0x0d, 0x76, 0x61, 0x6c, 0x69, 0x64, 0x61, 0x74, 0x6f, 0x72, 0x5f, 0x70, 0x62, 0x32, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( file_protobuf_validator_pb2_validator_proto_rawDescOnce sync.Once file_protobuf_validator_pb2_validator_proto_rawDescData = file_protobuf_validator_pb2_validator_proto_rawDesc ) func file_protobuf_validator_pb2_validator_proto_rawDescGZIP() []byte { file_protobuf_validator_pb2_validator_proto_rawDescOnce.Do(func() { file_protobuf_validator_pb2_validator_proto_rawDescData = protoimpl.X.CompressGZIP(file_protobuf_validator_pb2_validator_proto_rawDescData) }) return file_protobuf_validator_pb2_validator_proto_rawDescData } var file_protobuf_validator_pb2_validator_proto_enumTypes = make([]protoimpl.EnumInfo, 1) var file_protobuf_validator_pb2_validator_proto_msgTypes = make([]protoimpl.MessageInfo, 2) var file_protobuf_validator_pb2_validator_proto_goTypes = []interface{}{ (Message_MessageType)(0), // 0: Message.MessageType (*MessageList)(nil), // 1: MessageList (*Message)(nil), // 2: Message } var file_protobuf_validator_pb2_validator_proto_depIdxs = []int32{ 2, // 0: MessageList.messages:type_name -> Message 0, // 1: Message.message_type:type_name -> Message.MessageType 2, // [2:2] is the sub-list for method output_type 2, // [2:2] is the sub-list for method input_type 2, // [2:2] is the sub-list for extension type_name 2, // [2:2] is the sub-list for extension extendee 0, // [0:2] is the sub-list for field type_name } func init() { file_protobuf_validator_pb2_validator_proto_init() } func file_protobuf_validator_pb2_validator_proto_init() { if File_protobuf_validator_pb2_validator_proto != nil { return } if !protoimpl.UnsafeEnabled { file_protobuf_validator_pb2_validator_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*MessageList); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_protobuf_validator_pb2_validator_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*Message); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: file_protobuf_validator_pb2_validator_proto_rawDesc, NumEnums: 1, NumMessages: 2, NumExtensions: 0, NumServices: 0, }, GoTypes: file_protobuf_validator_pb2_validator_proto_goTypes, DependencyIndexes: file_protobuf_validator_pb2_validator_proto_depIdxs, EnumInfos: file_protobuf_validator_pb2_validator_proto_enumTypes, MessageInfos: file_protobuf_validator_pb2_validator_proto_msgTypes, }.Build() File_protobuf_validator_pb2_validator_proto = out.File file_protobuf_validator_pb2_validator_proto_rawDesc = nil file_protobuf_validator_pb2_validator_proto_goTypes = nil file_protobuf_validator_pb2_validator_proto_depIdxs = nil }
SINTEF-Infosec/sawtooth-sdk-go
<|start_filename|>component.json<|end_filename|> { "name": "cleanslate", "version": "0.10.1", "repo": "premasagar/cleanslate", "description": "Extreme CSS reset stylesheet", "keywords": ["css", "widgets"], "dependencies": {}, "development": {}, "styles": [ "cleanslate.css" ], "license": "MIT" }
seriousben/cleanslate
<|start_filename|>src/index.js<|end_filename|> export default (node, props) => { Object.entries(props).forEach(([key, value]) => { node.style.setProperty(`--${key}`, value); }); return { update(new_props) { Object.entries(new_props).forEach(([key, value]) => { node.style.setProperty(`--${key}`, value); delete props[key]; }); Object.keys(props).forEach(name => node.style.removeProperty(`--${name}`), ); props = new_props; }, }; }; <|start_filename|>package.json<|end_filename|> { "name": "svelte-css-vars", "version": "0.0.2", "author": "<NAME> <<EMAIL>>", "main": "dist/index.js", "module": "dist/index.mjs", "types": "./index.d.ts", "files": [ "dist", "index.d.ts" ], "scripts": { "build": "rollup -c", "test": "jest --no-cache", "test:watch": "jest --no-cache --watchAll", "lint": "eslint \"src/**/*.js\"", "format": "prettier --loglevel silent --write \"src/**/*.js\" && eslint --fix \"src/**/*.js\"", "version": "npx conventional-changelog-cli -p angular -i CHANGELOG.md -s -r 0 && git add CHANGELOG.md", "tag": "git tag -a v$npm_package_version -m 'Release v$npm_package_version'", "release": "npm run build && npm run version && git add package.json && git commit -m \"chore: release v$npm_package_version\"", "prepublishOnly": "npm run release && npm run tag" }, "devDependencies": { "eslint": "^6.1.0", "eslint-config-kaisermann": "0.0.3", "jest": "^24.8.0", "prettier": "^1.18.2", "rollup": "^1.19.4", "rollup-plugin-terser": "^5.1.1" } }
9ParsonsB/svelte-css-vars
<|start_filename|>oshc/main/templates/contest_submission.html<|end_filename|> {% extends 'base.html' %} {% load static %} {% block content %} <div class="jumbotron text-xs-center"> <div class="container text-center vcenter"> <h1 class="display-3">Thank you!</h1> <p class="lead subtitle"><strong>Your contest has been submitted for review.</strong></p> <hr> <p class="lead"> <a class="btn btn-primary btn-sm" href="{% url 'home' %}" role="button">Continue to homepage</a> </p> </div> </div> {% endblock %} <|start_filename|>oshc/main/templates/journey.html<|end_filename|> {% extends 'base.html' %} {% load static %} {% block content %} <section class="timeline"> <body> <ul> {% if Journey %} {% for j in Journey %} <li> <div> {{j.start_date}}<br>{{j.title}} </div> </li> <!-- more list items here --> {% endfor %} {% else %} <li> <div> No journey available </div> </li> {% endif %} </ul> </body> </section> {% endblock %} <|start_filename|>oshc/main/static/main/js/script.js<|end_filename|> $(document).ready(function() { $("#toTop").click(function() { $("html, body").animate({ scrollTop: 0 }, 1000); }); // code for Password Strength Meter jQuery(document).ready(function() { "use strict"; var options = {}; options.ui = { container: "#form", showVerdictsInsideProgressBar: true, viewports: { progress: ".pwstrength_viewport_progress", verdict: ".pwstrength_viewport_verdict" }, progressBarExtraCssClasses: "progress-bar-striped active" }; options.common = { debug: true, zxcvbn: true, zxcvbnTerms: ['samurai', 'shogun', 'bushido', 'daisho', 'seppuku'], userInputs: ['#id_username', '#id_email'] }; options.rules = { activated: { wordTwoCharacterClasses: true, wordRepetitions: true } }; $('#id_password1').pwstrength(options); }); }); <|start_filename|>oshc/main/templates/500.html<|end_filename|> {% extends 'base.html' %} {% load static %} {% block content %} <section class="main-section"> <div class="container"> <div class="jumbotron text-center"> <h1>500</h1> <h4>Internal Server Error.</h4> <br /> <a href="#" onClick="history.go(-1); return false;" class="btn btn-default">Go Back</a> </div> </div> </section> {% endblock %} <|start_filename|>oshc/main/templates/profile.html<|end_filename|> {% extends "account/base.html" %} {% load i18n %} {% block head_title %}{% trans "Profile" %}{% endblock %} {% block content %} <section class="main-section"> <h1>{% trans "Welcome to Open Source Help Community" %}</h1> </section> {% endblock %} <|start_filename|>oshc/main/templates/account/signup.html<|end_filename|> {% extends "account/base.html" %} {% load static %} {% load i18n %} {% block head_title %}{% trans "Signup" %}{% endblock %} {% block content %} <section class="main-section"> <div class="container"> <div class="row"> <div class="col-sm-6 col-md-4 col-md-offset-4"> <h1 class="form-title text-center">{% trans 'Sign Up Here' %}</h1> <div class="account-wall"> <form class="signup" id="form" method="post" action="{% url 'account_signup' %}"> {% csrf_token %} <div class="form-registration"> <p class="required field-title"> {% if form.username.errors %} {% for error in form.username.errors %} <div style="font-size: 12px;" class="alert alert-danger alert-dismissible" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button> {{ error|escape }}</div> {% endfor %} {% endif %} <label class="required" for="id_username">{% trans 'Username:' %}</label> <input class="form-control" type="text" name="username" placeholder="Username" autofocus="autofocus" minlength="1" maxlength="150" required id="id_username" /> <span class="helptext">{% trans 'Required. 30 characters or fewer. Letters, digits and @/./+/-/_ only.' %}</span> </p> <p> {% if form.email.errors %} {% for error in form.email.errors %} <div style="font-size: 12px;" class="alert alert-danger alert-dismissible" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button> {{ error|escape }}</div> {% endfor %} {% endif %} <label class="required" for="id_email">{% trans 'E-mail:' %}</label> <input class="form-control" type="email" name="email" placeholder="E-mail address" id="id_email" /> </p> <p> {% if form.password.errors %} {% for error in form.password.errors %} <div class="alert alert-danger" role="alert">{{ error|escape }}</div> {% endfor %} {% endif %} <label class="required" for="id_password1">{% trans 'Password:' %}</label> <input class="form-control" type="password" name="password1" placeholder="Password" required id="id_password1" /> </p> <div class="pwstrength_viewport_progress"></div> <p> {% if form.password.errors %} {% for error in form.password.errors %} <div class="alert alert-danger" role="alert">{{ error|escape }}</div> {% endfor %} {% endif %} <label class="required" for="id_password2">{% trans 'Password (again):' %}</label> <input class="form-control" type="password" name="password2" placeholder="Password (again)" required id="id_password2" /> <span class="helptext">{% trans 'Enter the same password as before, for verification.' %}</span> </p> <button class="btn btn-lg btn-primary btn-block" type="submit">{% trans "Sign Up" %}</button> </div> </form> </div> <br> <p class="text-center">{% blocktrans %}Already have an account? Then please <a href="{{ login_url }}">sign in</a>.{% endblocktrans %}</p> </div> </div> </div> </section> {% endblock %} {% block javascript %} <script src="{% static "main/js/pwstrength.js" %}"></script> <script src="{% static "main/js/zxcvbn.js" %}"></script> {% endblock %} <|start_filename|>oshc/main/templates/account/password_change.html<|end_filename|> {% extends "account/base.html" %} {% load static %} {% load i18n %} {% block head_title %}{% trans "Change Password" %}{% endblock %} {% block content %} <section class="main-section"> <div class="container"> <div class="row"> <div class="col-sm-6 col-md-4 col-md-offset-4"> <h1 class="form-title text-center">{% trans "Change Password" %}</h1> <div class="account-wall"> <form class="login" id="form" method="post" action="{% url 'account_login' %}"> {% csrf_token %} <div class="form-registration"> <p> <label for="id_oldpassword">{% trans 'Current Password:' %}</label> <input class="form-control" type="password" name="oldpassword" placeholder="<PASSWORD>" required id="id_oldpassword" /> </p> <p> {% if form.password1.errors %} {% for error in form.password1.errors %} <div style="font-size: 12px;" class="alert alert-danger alert-dismissible" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button> {{ error|escape }} </div> {% endfor %} {% endif %} <label for="id_password1">{% trans 'New Password:' %}</label> <input class="form-control" type="password" name="password1" placeholder="<PASSWORD>" required id="id_password1" /></p> </p> <div class="pwstrength_viewport_progress"></div> <p> <label for="id_password2">{% trans 'New Password (again):' %}</label> <input class="form-control" type="password" name="password2" placeholder="<PASSWORD> (again)" required id="id_password2" /> </p> <button class="btn btn-lg btn-primary btn-block" type="submit" name="action">{% trans "Change Password" %}</button> </div> </form> </div> </div> </div> </div> </section> {% endblock %} {% block javascript %} <script src="{% static "main/js/pwstrength.js" %}"></script> <script src="{% static "main/js/zxcvbn.js" %}"></script> {% endblock %} <|start_filename|>oshc/main/templates/contests.html<|end_filename|> {% extends 'base.html' %} {% load static %} {% block content %} <style> h3 { text-align: center; } span { display: block; } </style> <section class="main-section"> <div class="container"> <h3>List of Upcoming Open Source Contests</h3> <div class="container-fluid"> <div class="row"> {% for contest in contest_list %} {% if contest.approved %} <div class="col-lg-4"> <div class="panel panel-default"> <div class="panel-heading" style="background-color: #0275d8;color:white">{{contest.name}}</div> <div class="panel-body"> <span><span class="glyphicon glyphicon-globe"></span> <a href="{{contest.link}}">{{contest.link}}</a></span> <span><span class="glyphicon glyphicon-time"></span> {{contest.start_date}}-{{contest.end_date}}</span> <span><span class="glyphicon glyphicon-info-sign"></span> {{contest.description}}</span> </div> </div> </div> {% endif %} {% endfor %} </div> </div> <div class="Button" align="center" style="margin-bottom:70px; margin-top:20px;"> <a href="{% url 'contest_new' %}" class="btn btn-default" style="background-color:#0275d8;color:white;">Submit a New Contest</a> </div> </div> </section> {% endblock %} <|start_filename|>oshc/main/static/main/css/app.css<|end_filename|> /* GLOBAL DEFINATIONS STARTS */ * { padding: 0; margin: 0; box-sizing: border-box; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; transition: opacity 0.7s ease-in-out; font-family: "Montserrat", sans-serif } html { position: relative; min-height: 100%; } body { overflow-x: hidden; margin-bottom: 120px; } a { cursor: pointer; color: #0275d8; text-decoration: none; } .line-gap-10px { height: 10px; } /* NAVBAR CSS STARTS */ .navbar { margin-bottom: 0; } .navbar-inverse .navbar-brand { color: #eee; } .navbar-inverse { background-color: #24292e; border-color: #24292e; } .vertical-align { display: block; align-items: center; margin: 0 auto; justify-content: center; float: none; } /* SECTION ONE STARTS */ .main-section { min-height: 70vh; height: auto; padding-top: 100px; background: white; background-color: white; position: relative; clear: both; width: 100%; } .logo-image { width: 200px; display: block; margin-left: auto; margin-right: auto } .jumbotron { background-color: white; word-wrap: break-word; display: block; } .jumbotron h1 { font-size: 60px; color: #0275d8; } .jumbotron h4 { color: #999; font-size: 18px; padding-top: 20px; } /* SECTION TWO START */ .section-two { height: auto; padding: 70px 0; background-color: #eee; word-wrap: break-word; display: block; } .section-two h3 { font-size: 30px; color: #444444; } .bi { text-align: center; font-style: italic; padding: 10px 0; font-size: 15px; } .section-two .intro { color: #666666; font-size: 18px; line-height: 35px; text-align: justify; } /* SECTION THREE START */ .section-three { height: auto; min-height: 500px; padding: 40px 0; } .left-session-info { padding: 30px 50px; } .sRegister { color: white; font-size: 15px; background-color: #0275d8; border-color: #0275d8; } .sRegister a { color: white; text-decoration: none; } .left-social-section { padding: 0 50px; } iframe { position: absolute; left: 0; right: 0; bottom: 0; top: 0; border: 0; } /* FOOTER CSS STARTS */ footer { height: auto; padding-top: 10px; background-color: #24292e; } .footer { position: absolute; bottom: 0; width: 100%; min-height: 120px; } footer .container { position: sticky; display: block; } .rectangle { height: 30px; line-height: 30px; margin-top: 15px; } .back-to-top { float: right; color: #999; } .back-to-top a { text-decoration: none; } .copyright { color: #fff; line-height: 30px; min-height: 30px; padding: 7px 0; } .social { color: #fff; line-height: 30px; min-height: 30px; padding: 7px 0; } .social .left-align { text-align: left; } .social .right-align { text-align: right; } .social ul { list-style: none; } .social ul li { width: 40px; height: 30px; color: #eee; font-size: 22px; display: inline-block; } .social a { color: #fff; } /*Media queries*/ @media (max-width: 320px) { .jumbotron h1 { font-size: 30px; } } @media (min-width: 321px) and (max-width: 480px) { .jumbotron h1 { font-size: 38px; } } @media (max-width: 768px) { .main-section { min-height: 50vh; height: auto; clear: both; } } @media (min-width: 769px) and (max-width: 1024px) { .main-section { min-height: 50vh; height: auto; clear: both; } } /*Registration CSS starts*/ .form-title { color: #555; font-size: 28px; font-weight: 400; display: block; } .account-wall { margin-top: 20px; padding: 40px 0px 20px 0px; background-color: #f7f7f7; -moz-box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3); -webkit-box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3); box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3); } .profile-img { width: 96px; height: 96px; margin: 0 auto 10px; display: block; -moz-border-radius: 50%; -webkit-border-radius: 50%; border-radius: 50%; } .form-registration { max-width: 330px; padding: 15px; margin: 0 auto; } .form-registration .field-title { font-weight: 400; color: #000000; font-size: 14px; display: block; } .form-registration .helptext { font-weight: 400; color: #607D8B; font-size: 12px; display: block; } .form-registration .form-registration-heading, .form-registration .checkbox { margin-bottom: 10px; } .form-registration .checkbox { font-weight: normal; } .form-registration .form-control { position: relative; font-size: 16px; height: auto; padding: 10px; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } .form-registration .form-control:focus { z-index: 2; } .form-registration input[type="text"] { margin-bottom: -1px; border-bottom-left-radius: 0; border-bottom-right-radius: 0; } .form-registration input[type="email"] { margin-bottom: -1px; border-bottom-left-radius: 0; border-bottom-right-radius: 0; } .form-registration input[type="password"] { margin-bottom: 10px; border-top-left-radius: 0; border-top-right-radius: 0; } .form-registration .forgot-password { margin-top: 10px; } .form-registration .new-account { display: block; margin-top: 10px; } .form-registration .btn { background: #0275d8; } .form-registration p:hover { color: #0275d8; } .form-registration button:hover { background: #ffffff; color: #0275d8; } .form-registration button:focus { background: #0275d8; } /*css for strength meter*/ .strength-wrapper { margin-top: -33px; } .strength-wrapper .strength { float:left; width:72px; height:3px; margin-right: 3px; } #passwordStrengthString { font-size: 0.8em; margin-left: -299px; font-weight: bold; } .zone { display:none; } /* CONTEST SUBMISSION PAGE CSS STARTS */ .vcenter { display: flex; flex-direction: column; align-content: center; justify-content: center; height: 90vh; z-index: -100; position: absolute; top: 0; left: 0; right: 0; } .subtitle { margin: 0 !important; } /* TIMELINE CHANGES */ body { background: #d4e5f7; } .timeline ul { background: #d4e5f7; padding: 50px 0; } .timeline ul li { list-style-type: none; position: relative; width: 0.5%; margin: 0 auto; padding-top: 50px; background: #ffffff; } .timeline ul li div { position: relative; bottom: 0; width: 5000%; padding: 15px; position: relative; background: #ffffff; } .timeline ul li div::before { content: ''; position: absolute; bottom: 7px; width: 0; height: 0; border-style: solid; } .timeline ul li:nth-child(odd) div { left: 500%; } .timeline ul li:nth-child(odd) div::before { left: -5%; border-width: 8px 16px 8px 0; border-color: transparent #ffffff transparent transparent; } .timeline ul li:nth-child(even) div { left: -5400%; } .timeline ul li:nth-child(even) div::before { right: -4.5%; border-width: 8px 0 8px 16px; border-color: transparent transparent transparent #ffffff; } <|start_filename|>oshc/main/templates/account/logout.html<|end_filename|> {% extends "account/base.html" %} {% load i18n %} {% block head_title %}{% trans "Sign Out" %}{% endblock %} {% block content %} <section class="main-section"> <div class="container"> <div class="row"> <div class="col-sm-6 col-md-4 col-md-offset-4"> <h1 class="text-center">{% trans "Sign Out" %}</h1> <div class="account-wall"> <h4 class="text-center">{% trans 'Are you sure you want to sign out?' %}</h4> <form class="form-registration" method="post" action="{% url 'account_logout' %}"> {% csrf_token %} {% if redirect_field_value %} <input type="hidden" name="{{ redirect_field_name }}" value="{{ redirect_field_value }}"/> {% endif %} <button class="btn btn-lg btn-primary btn-block" type="submit">{% trans 'Sign Out' %}</button> </form> </div> </div> </div> </div> </section> {% endblock %} <|start_filename|>oshc/main/templates/account/email.html<|end_filename|> {% extends "account/base.html" %} {% load i18n %} {% block head_title %}{% trans "Account" %}{% endblock %} {% block content %} <section class="main-section"> <h1 class="form-title text-center">{% trans "E-mail Addresses" %}</h1> {% if user.emailaddress_set.all %} <p class="text-center">{% trans 'The following e-mail addresses are associated with your account:' %}</p> <div class="container"> <div class="row"> <div class="col-sm-6 col-md-4 col-md-offset-4"> <div class="account-wall"> <form action="{% url 'account_email' %}" class="email_list" method="post"> {% csrf_token %} <div class="form-registration"> <fieldset class="blockLabels"> {% for emailaddress in user.emailaddress_set.all %} <div class="ctrlHolder radio"> <label for="email_radio_{{forloop.counter}}" class="{% if emailaddress.primary %}primary_email{%endif%}"> <input id="email_radio_{{forloop.counter}}" type="radio" name="email" {% if emailaddress.primary or user.emailaddress_set.count == 1 %}checked="checked"{%endif %} value="{{emailaddress.email}}"/> {{ emailaddress.email }} {% if emailaddress.verified %} <span class="label label-success verified">{% trans "Verified" %}</span> {% else %} <span class="label label-danger unverified">{% trans "Unverified" %}</span> {% endif %} {% if emailaddress.primary %}<span class="label label-primary primary">{% trans "Primary" %}</span>{% endif %} </label> </div> {% endfor %} <div class="buttonHolder"> <button class="btn btn-primary btn-lg btn-block secondaryAction" type="submit" name="action_primary" >{% trans 'Make Primary' %}</button> <button class="btn btn-primary btn-lg btn-block secondaryAction" type="submit" name="action_send" >{% trans 'Re-send Verification' %}</button> <button class="btn btn-primary btn-lg btn-block primaryAction" type="submit" name="action_remove" >{% trans 'Remove' %}</button> </div> </fieldset> </div> </form> </div> </div> </div> </div> {% else %} <p class="text-center"><strong>{% trans 'Warning:'%}</strong> {% trans "You currently do not have any e-mail address set up. You should really add an e-mail address so you can receive notifications, reset your password, etc." %}</p> {% endif %} <div class="container"> <div class="row"> <div class="col-sm-6 col-md-4 col-md-offset-4"> <h2>{% trans "Add E-mail Address" %}</h2> <div class="account-wall"> <form method="post" action="{% url 'account_email' %}" class="add_email form-registration"> {% csrf_token %} <p class="required field-title"> {% if form.email.errors %} {% for error in form.email.errors %} <div style="font-size: 12px;" class="alert alert-danger alert-dismissible" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button> {{ error|escape }}</div> {% endfor %} {% endif %} <label class="required" for="id_email">{% trans 'E-mail:' %}</label> <input class="form-control" type="email" name="email" size="30" placeholder="E-mail address" required id="id_email" /> </p> <button class="btn btn-lg btn-primary btn-block" name="action_add" type="submit">{% trans "Add E-mail" %}</button> </form> </div> </div> </div> </div> </section> {% endblock %} {% block javascript %} <script type="text/javascript"> (function() { var message = "{% trans 'Do you really want to remove the selected e-mail address?' %}"; var actions = document.getElementsByName('action_remove'); if (actions.length) { actions[0].addEventListener("click", function(e) { if (! confirm(message)) { e.preventDefault(); } }); } })(); </script> {% endblock %}
Joshua2504/OpenSourceHelpCommunity.github.io
<|start_filename|>build/gulp/shared.js<|end_filename|> const c = require('./config'); const exec = require('child_process').exec; module.exports = { haxe: function(hxml, cb) { let cmd = 'HXCWD="' + process.cwd() + '" haxe ' + hxml; if (c.isDev) { cmd += ' -debug'; } else { cmd += ' --no-traces'; } return exec(cmd, function (err, stdout, stderr) { if (stdout) { console.log(stdout); } if (stderr) { console.log(stderr); } cb(err); }); } };
YAL-Forks/fonthx
<|start_filename|>src/main/java/org/yeauty/support/MethodArgumentResolver.java<|end_filename|> package org.yeauty.support; import io.netty.channel.Channel; import org.springframework.core.MethodParameter; import org.springframework.lang.Nullable; public interface MethodArgumentResolver { /** * Whether the given {@linkplain MethodParameter method parameter} is * supported by this resolver. * @param parameter the method parameter to check * @return {@code true} if this resolver supports the supplied parameter; * {@code false} otherwise */ boolean supportsParameter(MethodParameter parameter); @Nullable Object resolveArgument(MethodParameter parameter, Channel channel,Object object) throws Exception; } <|start_filename|>src/main/java/org/yeauty/annotation/RequestParam.java<|end_filename|> package org.yeauty.annotation; import org.springframework.core.annotation.AliasFor; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target(ElementType.PARAMETER) @Retention(RetentionPolicy.RUNTIME) public @interface RequestParam { /** * Alias for {@link #name}. */ @AliasFor("name") String value() default ""; /** * The name of the request parameter to bind to. */ @AliasFor("value") String name() default ""; /** * Whether the parameter is required. * <p>Defaults to {@code true}, leading to an exception being thrown * if the parameter is missing in the request. Switch this to * {@code false} if you prefer a {@code null} value if the parameter is * not present in the request. * <p>Alternatively, provide a {@link #defaultValue}, which implicitly * sets this flag to {@code false}. */ boolean required() default true; /** * The default value to use as a fallback when the request parameter is * not provided or has an empty value. * <p>Supplying a default value implicitly sets {@link #required} to * {@code false}. */ String defaultValue() default "\n\t\t\n\t\t\n\uE000\uE001\uE002\n\t\t\t\t\n"; } <|start_filename|>src/main/java/org/yeauty/support/SessionMethodArgumentResolver.java<|end_filename|> package org.yeauty.support; import io.netty.channel.Channel; import org.springframework.core.MethodParameter; import org.yeauty.pojo.Session; import static org.yeauty.pojo.PojoEndpointServer.SESSION_KEY; public class SessionMethodArgumentResolver implements MethodArgumentResolver { @Override public boolean supportsParameter(MethodParameter parameter) { return Session.class.isAssignableFrom(parameter.getParameterType()); } @Override public Object resolveArgument(MethodParameter parameter, Channel channel, Object object) throws Exception { Session session = channel.attr(SESSION_KEY).get(); return session; } } <|start_filename|>src/main/java/org/yeauty/support/ThrowableMethodArgumentResolver.java<|end_filename|> package org.yeauty.support; import io.netty.channel.Channel; import org.springframework.core.MethodParameter; import org.yeauty.annotation.OnError; public class ThrowableMethodArgumentResolver implements MethodArgumentResolver { @Override public boolean supportsParameter(MethodParameter parameter) { return parameter.getMethod().isAnnotationPresent(OnError.class) && Throwable.class.isAssignableFrom(parameter.getParameterType()); } @Override public Object resolveArgument(MethodParameter parameter, Channel channel, Object object) throws Exception { if (object instanceof Throwable) { return object; } return null; } } <|start_filename|>src/main/java/org/yeauty/autoconfigure/NettyWebSocketAutoConfigure.java<|end_filename|> package org.yeauty.autoconfigure; import org.yeauty.annotation.EnableWebSocket; @EnableWebSocket public class NettyWebSocketAutoConfigure { }
hixio-mh/netty-websocket-spring-boot-starter
<|start_filename|>Makefile<|end_filename|> # Begin OS detection ifeq ($(OS),Windows_NT) # is Windows_NT on XP, 2000, 7, Vista, 10... OPERATING_SYSTEM := Windows PATH_SEPARATOR := ; else OPERATING_SYSTEM := $(shell uname) # same as "uname -s" PATH_SEPARATOR := : endif # This gives debug output in the C code and some debugger flags, useful for... Debugging. # See ext/fast_polylines/extconf.rb DEBUG = # 1 EXT_NAME = fast_polylines RUBY_FLAG = -I lib$(PATH_SEPARATOR)ext -r $(EXT_NAME) ALL_TARGETS = $(wildcard ext/$(EXT_NAME)/*.c) $(wildcard ext/$(EXT_NAME)/*.h) ##@ Utility FMT_TITLE='\\033[7\;1m' FMT_PRIMARY='\\033[36m' FMT_END='\\033[0m' .PHONY: help help: ## Shows this help menu. @printf -- " FAST-POLYLINES\n" @printf -- "---------------------------------------------------------------------------\n" @awk ' \ BEGIN {FS = ":.*##"; printf "Usage: make ${FMT_PRIMARY}<target>${FMT_END}\n"} \ /^[a-zA-Z0-9_-]+:.*?##/ { printf " $(FMT_PRIMARY)%-30s$(FMT_END) %s\n", $$1, $$2 } \ /^##@/ { printf "\n$(FMT_TITLE) %s $(FMT_END)\n", substr($$0, 5) } \ ' $(MAKEFILE_LIST) .PHONY: console console: ext ## Runs an irb console with fast-polylines irb $(RUBY_FLAG) .PHONY: test test: ext ## Runs tests bundle exec rspec .PHONY: rubocop rubocop: ## Checks ruby syntax bundle exec rubocop .PHONY: benchmark benchmark: ext ## Run the benchmark bundle exec ruby $(RUBY_FLAG) ./perf/benchmark.rb ext/$(EXT_NAME)/Makefile: ext/$(EXT_NAME)/extconf.rb cd ext/$(EXT_NAME) && ruby extconf.rb --vendor ext/$(EXT_NAME)/$(EXT_NAME).bundle: ext/$(EXT_NAME)/Makefile $(ALL_TARGETS) make -C ext/$(EXT_NAME) ##@ C extension .PHONY: ext ext: ext/$(EXT_NAME)/$(EXT_NAME).bundle ## Compiles the C extension .PHONY: clean clean: ## Cleans C stuff cd ext/$(EXT_NAME) && make clean rm ext/$(EXT_NAME)/Makefile
rahul342/fast-polylines
<|start_filename|>examples/coarse_grained/DNA_models/dsDNA/2strands/dsDNA_2beads=3bp_2019-10-19/measure_persistence_length/calc_stddev.awk<|end_filename|> #!/usr/bin/awk -f BEGIN{sum=0; sumsqd=0; n=0} {sum+=$1; sumsqd+=$1*$1; n++} END{print sum/n" "sqrt((sumsqd/n-(sum/n)*(sum/n))*(n/(n-1)))} <|start_filename|>moltemplate/scripts/pdb2crds.awk<|end_filename|> #!/usr/bin/awk -f # Extracts the x,y,z coordinates from ALL ATOM and HETATM records. # # Usage: # pdb2crds.awk < input_file.pdb > output_file.txt /^ATOM |^HETATM/{print substr($0,31,8)" "substr($0,39,8)" "substr($0,47,8)}
jsbtic/moltemplate
<|start_filename|>app.json<|end_filename|> { "name": "Daily Hunts News API", "description": "Unofficial API of Daily Hunt News", "keywords": [ "flask", "python", "news", "dailyhunt" ], "success_url": "https://t.me/alphaprojects" }
techraz-rishi/DailyHunt-NewsAPI
<|start_filename|>include/ba/bytearray.hpp<|end_filename|> #pragma once #include "bytearray_processor.hpp" namespace ba { /** * @brief Class, that implements byte array, that * holds std::vector object and has bytearray_processor * interface. * @tparam Allocator Allocator for std::vector. */ template <typename Allocator = std::allocator<std::byte>> class bytearray : public bytearray_processor<std::byte, Allocator>, private std::vector<std::byte, Allocator> { using vector = std::vector<std::byte, Allocator>; using processor = bytearray_processor<std::byte, Allocator>; public: using typename processor::size_type; using typename processor::value_type; using typename vector::const_iterator; using typename vector::const_reverse_iterator; using typename vector::iterator; using typename vector::reverse_iterator; /** * @brief Default constructor. */ bytearray() : processor(*static_cast<vector*>(this)) , vector() {} /** * @brief Move constructor. */ bytearray(bytearray<Allocator>&& rhs) noexcept : processor(*static_cast<vector*>(this)) , vector(std::move(rhs.container())) {} /** * @brief Default copy constructor. */ bytearray(const bytearray<Allocator>& rhs) : processor(*static_cast<vector*>(this)) , vector(rhs.container()) {} /** * @brief Constructor with initial size. */ explicit bytearray(size_type sizeValue) : processor(*static_cast<vector*>(this)) , vector(sizeValue) {} /** * @brief Initializer constructor. */ bytearray(const value_type* val, size_type amount) : processor(*static_cast<vector*>(this)) , vector(val, val + amount) {} /** * @brief Copy operator. */ bytearray<Allocator>& operator=(const bytearray<Allocator>& rhs) { vector::operator=(rhs.container()); return (*this); } /** * @brief Move operator. */ bytearray<Allocator>& operator=(bytearray<Allocator>&& rhs) noexcept { vector::operator=(std::move(rhs.container())); return (*this); } using vector::operator[]; using processor::insert; using processor::push_back; using vector::at; using vector::begin; using vector::capacity; using vector::cbegin; using vector::cend; using vector::clear; using vector::crbegin; using vector::crend; using vector::empty; using vector::end; using vector::rbegin; using vector::rend; using vector::reserve; using vector::size; }; } // namespace ba static inline ba::bytearray<> operator"" _ba(const char* str, std::size_t len) { ba::bytearray array{}; array.load_from_hex(std::string_view{str, len}); return array; } <|start_filename|>tests/SerializationTest.cpp<|end_filename|> #include <gtest/gtest.h> #include <ba/bytearray.hpp> TEST(Serialization, FromString) { std::string strict = "AABBCCDDEE1100"; uint8_t strict_expected[] = { 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0x11, 0x00 }; // Stricted { ba::bytearray v; ASSERT_NO_THROW(v.load_from_hex(strict)); ASSERT_EQ(v.size(), 7); for (ba::bytearray<>::size_type i = 0; i < v.size(); ++i) { ASSERT_EQ(strict_expected[i], static_cast<uint8_t>(v[i])); } } } <|start_filename|>tests/ConstructTest.cpp<|end_filename|> #include <gtest/gtest.h> #include <ba/bytearray.hpp> TEST(Constructors, Default) { ba::bytearray b{}; ASSERT_EQ(b.size(), 0); ASSERT_EQ(b.capacity(), 0); } TEST(Constructors, InitialFill) { ba::bytearray b(1024); ASSERT_EQ(b.size(), 1024); ASSERT_EQ(b.capacity(), 1024); } TEST(Constructors, InitialCapacity) { ba::bytearray b{}; b.reserve(1024); ASSERT_EQ(b.size(), 0); ASSERT_EQ(b.capacity(), 1024); } TEST(Constructors, FromByteArray) { uint8_t byteArray[32] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, }; ba::bytearray b(reinterpret_cast<std::byte*>(byteArray), 32); ASSERT_EQ(b.size(), 32); ASSERT_EQ(b.capacity(), 32); for (decltype(b)::size_type i = 0; i < b.size(); ++i) { ASSERT_EQ(byteArray[i], uint8_t(b[i])); } } TEST(Constructors, Copy) { uint8_t byteArray[32] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, }; ba::bytearray b(reinterpret_cast<std::byte*>(byteArray), 32); ba::bytearray copy = b; for (decltype(b)::size_type i = 0; i < b.size(); ++i) { ASSERT_EQ(b[i], copy[i]); } } TEST(Constructors, Move) { uint8_t byteArray[32] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, }; ba::bytearray m(reinterpret_cast<std::byte*>(byteArray), 32); auto b = std::move(m); ASSERT_EQ(b.size(), 32); ASSERT_EQ(b.capacity(), 32); for (decltype(b)::size_type i = 0; i < b.size(); ++i) { ASSERT_EQ(byteArray[i], uint8_t(b[i])); } } <|start_filename|>benchmark/InsertSpeed.cpp<|end_filename|> // No benchmarks here, sorry <|start_filename|>tests/UtilitiesTest.cpp<|end_filename|> #include <gtest/gtest.h> #include <ba/bytearray.hpp> #include <ba/bytearray_view.hpp> TEST(Utils, LoadFromHexString) { ba::bytearray array{}; uint8_t expect[] = { 0xAA, 0xFF, 0xEE, 0xDD }; ASSERT_TRUE(array.load_from_hex(std::string_view("AAFFEEDD"))); ASSERT_EQ(array.size(), 4); for (decltype(array)::size_type i = 0; i < array.size(); ++i) { ASSERT_EQ(uint8_t(array[i]), expect[i]); } ASSERT_TRUE(array.load_from_hex(std::string_view("AA FFEEDD"))); ASSERT_EQ(array.size(), 4); for (decltype(array)::size_type i = 0; i < array.size(); ++i) { ASSERT_EQ(uint8_t(array[i]), expect[i]); } ASSERT_TRUE(array.load_from_hex(std::string_view("AA FF EE DD"))); ASSERT_EQ(array.size(), 4); for (decltype(array)::size_type i = 0; i < array.size(); ++i) { ASSERT_EQ(uint8_t(array[i]), expect[i]); } ASSERT_FALSE(array.load_from_hex(std::string_view("AAFFEE WW"))); ASSERT_EQ(array.size(), 4); for (decltype(array)::size_type i = 0; i < array.size(); ++i) { ASSERT_EQ(uint8_t(array[i]), expect[i]); } } TEST(Utils, Literal) { auto ba = "DEADBEEF"_ba; uint8_t expect[] = { 0xDE, 0xAD, 0xBE, 0xEF }; ASSERT_EQ(ba.size(), 4); for (decltype(ba)::size_type i = 0; i < ba.size(); ++i) { ASSERT_EQ(uint8_t(ba[i]), expect[i]); } } TEST(Utils, ToString) { auto ba = "DEADBEEF"_ba; auto string = std::to_string(ba); ASSERT_EQ(string, "DEADBEEF"); } TEST(Utils, ViewToString) { auto ba = "DEADBEEF"_ba; ba::bytearray_view view(ba, 1, 2); auto string = std::to_string(view); ASSERT_EQ(string, "ADBE"); } <|start_filename|>benchmark/CreationAndCopy.cpp<|end_filename|> #include <benchmark/benchmark.h> #include <ba/bytearray.hpp> static void creationEmpty(benchmark::State& state) { for (auto _ : state) { benchmark::DoNotOptimize(ba::bytearray()); } } static void creationFromArrayOfBytes(benchmark::State& state) { auto size = state.range(0); auto* data = new std::byte[size]; for (auto _ : state) { benchmark::DoNotOptimize(ba::bytearray(data, size)); } delete[] data; state.SetComplexityN(size); } static void copyEmpty(benchmark::State& state) { ba::bytearray byteArray; for (auto _ : state) { benchmark::DoNotOptimize(ba::bytearray(byteArray)); } } static void copyWithData(benchmark::State& state) { auto size = static_cast<ba::bytearray<>::size_type>(state.range(0)); ba::bytearray byteArray(size); byteArray.push_back_multiple<uint8_t>(0x00, size); for (auto _ : state) { benchmark::DoNotOptimize(ba::bytearray(byteArray)); } state.SetComplexityN(size); } BENCHMARK(creationEmpty); BENCHMARK(creationFromArrayOfBytes) ->Range(1, 1 << 20) ->Complexity(); BENCHMARK(copyEmpty); BENCHMARK(copyWithData) ->Range(1, 1 << 20) ->Complexity(); <|start_filename|>tests/AppendTest.cpp<|end_filename|> #include <gtest/gtest.h> #include <ba/bytearray.hpp> TEST(Append, InitializerListUint8) { uint8_t data[8] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07 }; uint8_t expect[12] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0xDE, 0xAD, 0xBE, 0xEF }; { ba::bytearray b(reinterpret_cast<std::byte*>(data), 8); b.push_back_multiple<uint8_t>({ 0xDE, 0xAD, 0xBE, 0xEF }, ba::endianness::big); ASSERT_EQ(b.size(), 12); for (ba::bytearray<>::size_type i = 0; i < b.size(); ++i) { ASSERT_EQ(uint8_t(b[i]), expect[i]); } } { ba::bytearray b(reinterpret_cast<std::byte*>(data), 8); b.push_back_multiple<uint8_t>({ 0xDE, 0xAD, 0xBE, 0xEF }, ba::endianness::little); ASSERT_EQ(b.size(), 12); for (ba::bytearray<>::size_type i = 0; i < b.size(); ++i) { ASSERT_EQ(uint8_t(b[i]), expect[i]); } } } TEST(Append, InitializerListUint32) { uint8_t data[8] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07 }; uint8_t expect_be[16] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0xDE, 0xAD, 0xBE, 0xEF, 0xDE, 0xAD, 0xBE, 0xEF }; uint8_t expect_le[16] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0xEF, 0xBE, 0xAD, 0xDE, 0xEF, 0xBE, 0xAD, 0xDE }; { ba::bytearray b(reinterpret_cast<std::byte*>(data), 8); b.push_back_multiple<uint32_t>({ 0xDEADBEEF, 0xDEADBEEF }, ba::endianness::big); ASSERT_EQ(b.size(), 16); for (ba::bytearray<>::size_type i = 0; i < b.size(); ++i) { ASSERT_EQ(uint8_t(b[i]), expect_be[i]); } } { ba::bytearray b(reinterpret_cast<std::byte*>(data), 8); b.push_back_multiple<uint32_t>({ 0xDEADBEEF, 0xDEADBEEF }, ba::endianness::little); ASSERT_EQ(b.size(), 16); for (ba::bytearray<>::size_type i = 0; i < b.size(); ++i) { ASSERT_EQ(uint8_t(b[i]), expect_le[i]); } } } TEST(Append, Range) { uint8_t data[8] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, }; uint8_t appendable[4] = { 0xDE, 0xAD, 0xBE, 0xEF }; ba::bytearray b(reinterpret_cast<std::byte*>(data), 8); b.push_back_multiple(appendable, appendable + 4); ASSERT_EQ(b.size(), 12); for (ba::bytearray<>::size_type i = 0; i < b.size(); ++i) { if (i >= 8) { ASSERT_EQ(uint8_t(b[i]), appendable[i - 8]); } else { ASSERT_EQ(uint8_t(b[i]), data[i]); } } } TEST(Append, Number8bit) { uint8_t data[8] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, }; uint8_t expecting_be[9] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0xDE }; uint8_t expecting_le[9] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0xDE }; { ba::bytearray array(reinterpret_cast<std::byte*>(data), 8); array.push_back<uint8_t>(0xDE, ba::endianness::big); ASSERT_EQ(array.size(), 9); for (ba::bytearray<>::size_type i = 0; i < array.size(); ++i) { ASSERT_EQ(uint8_t(array[i]), expecting_be[i]); } } { ba::bytearray array(reinterpret_cast<std::byte*>(data), 8); array.push_back<uint8_t>(0xDE, ba::endianness::little); ASSERT_EQ(array.size(), 9); for (ba::bytearray<>::size_type i = 0; i < array.size(); ++i) { ASSERT_EQ(uint8_t(array[i]), expecting_le[i]); } } } TEST(Append, Number16bit) { uint8_t data[8] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, }; uint8_t expecting_be[10] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0xDE, 0xAD }; uint8_t expecting_le[10] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0xAD, 0xDE }; { ba::bytearray array(reinterpret_cast<std::byte*>(data), 8); array.push_back<uint16_t>(0xDEAD, ba::endianness::big); ASSERT_EQ(array.size(), 10); for (ba::bytearray<>::size_type i = 0; i < array.size(); ++i) { ASSERT_EQ(uint8_t(array[i]), expecting_be[i]); } } { ba::bytearray array(reinterpret_cast<std::byte*>(data), 8); array.push_back<uint16_t>(0xDEAD, ba::endianness::little); ASSERT_EQ(array.size(), 10); for (ba::bytearray<>::size_type i = 0; i < array.size(); ++i) { ASSERT_EQ(uint8_t(array[i]), expecting_le[i]); } } } TEST(Append, Number32bit) { uint8_t data[8] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, }; uint8_t expecting_be[12] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0xDE, 0xAD, 0xBE, 0xEF }; uint8_t expecting_le[12] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0xEF, 0xBE, 0xAD, 0xDE }; { ba::bytearray array(reinterpret_cast<std::byte*>(data), 8); array.push_back<uint32_t>(0xDEADBEEF, ba::endianness::big); ASSERT_EQ(array.size(), 12); for (ba::bytearray<>::size_type i = 0; i < array.size(); ++i) { ASSERT_EQ(uint8_t(array[i]), expecting_be[i]); } } { ba::bytearray array(reinterpret_cast<std::byte*>(data), 8); array.push_back<uint32_t>(0xDEADBEEF, ba::endianness::little); ASSERT_EQ(array.size(), 12); for (ba::bytearray<>::size_type i = 0; i < array.size(); ++i) { ASSERT_EQ(uint8_t(array[i]), expecting_le[i]); } } } TEST(Append, Number64bit) { uint8_t data[8] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, }; uint8_t expecting_be[16] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0xDE, 0xAD, 0xBE, 0xEF, 0xDE, 0xAD, 0xBE, 0xEF }; uint8_t expecting_le[16] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0xEF, 0xBE, 0xAD, 0xDE, 0xEF, 0xBE, 0xAD, 0xDE }; { ba::bytearray array(reinterpret_cast<std::byte*>(data), 8); array.push_back<uint64_t>(0xDEADBEEFDEADBEEF, ba::endianness::big); ASSERT_EQ(array.size(), 16); for (ba::bytearray<>::size_type i = 0; i < array.size(); ++i) { ASSERT_EQ(uint8_t(array[i]), expecting_be[i]); } } { ba::bytearray array(reinterpret_cast<std::byte*>(data), 8); array.push_back<uint64_t>(0xDEADBEEFDEADBEEF, ba::endianness::little); ASSERT_EQ(array.size(), 16); for (ba::bytearray<>::size_type i = 0; i < array.size(); ++i) { ASSERT_EQ(uint8_t(array[i]), expecting_le[i]); } } } <|start_filename|>benchmark/AppendSpeed.cpp<|end_filename|> #include <benchmark/benchmark.h> #include <ba/bytearray.hpp> template<typename T> static void append(benchmark::State& state) { auto resultSize = state.range(0); auto count = resultSize / sizeof(T); ba::bytearray array; for (auto _ : state) { array.clear(); for (int i = 0; i < count; ++i) { array.push_back<T>(T(0xAA)); } } state.SetComplexityN(resultSize); } template<typename T> static void appendMultiple(benchmark::State& state) { auto resultSize = state.range(0); auto count = resultSize / sizeof(T); ba::bytearray array; for (auto _ : state) { array.clear(); array.push_back_multiple<T>(T(0xAA), count); } state.SetComplexityN(resultSize); } static void appendByteArray(benchmark::State& state) { auto size = static_cast<size_t>(state.range(0)); std::vector<std::byte> data; data.resize(size, std::byte(0x00)); ba::bytearray array; for (auto _ : state) { array.clear(); array.push_back_multiple(data.begin(), data.end()); } state.SetComplexityN(size); } static void appendPart(benchmark::State& state) { uint64_t data = 0x1122334455667788; auto size = state.range(0); auto part = state.range(1); auto count = size / part; ba::bytearray array; for (auto _ : state) { array.clear(); for (auto i = 0; i < count; ++i) { array.push_back_part<uint64_t>(data, static_cast<std::size_t>(part)); } } state.SetComplexityN(count); } BENCHMARK_TEMPLATE(append, uint8_t) ->Range(1, 1 << 20) ->Complexity(); BENCHMARK_TEMPLATE(append, uint16_t) ->Range(1, 1 << 20) ->Complexity(); BENCHMARK_TEMPLATE(append, uint32_t) ->Range(1, 1 << 20) ->Complexity(); BENCHMARK_TEMPLATE(append, uint64_t) ->Range(1, 1 << 20) ->Complexity(); BENCHMARK_TEMPLATE(appendMultiple, uint8_t) ->Range(1, 1 << 20) ->Complexity(); BENCHMARK_TEMPLATE(appendMultiple, uint16_t) ->Range(1, 1 << 20) ->Complexity(); BENCHMARK_TEMPLATE(appendMultiple, uint32_t) ->Range(1, 1 << 20) ->Complexity(); BENCHMARK_TEMPLATE(appendMultiple, uint64_t) ->Range(1, 1 << 20) ->Complexity(); BENCHMARK(appendByteArray) ->Range(1, 1 << 20) ->Complexity(); BENCHMARK(appendPart) ->RangeMultiplier(2) ->Ranges({{1, 1 << 20}, {1, 8}}); <|start_filename|>benchmark/main.cpp<|end_filename|> #include <benchmark/benchmark.h> #include <ba/bytearray.hpp> #include <iostream> BENCHMARK_MAIN(); <|start_filename|>benchmark/MoveCopy.cpp<|end_filename|> #include <benchmark/benchmark.h> #include <ba/bytearray.hpp> static void copy(benchmark::State& state) { ba::bytearray array; auto resultSize = state.range(0); array.push_back_multiple( 0xFF, resultSize ); for (auto _ : state) { benchmark::DoNotOptimize(ba::bytearray<>(array)); } state.SetComplexityN(resultSize); } static void move(benchmark::State& state) { ba::bytearray array; auto resultSize = state.range(0); array.push_back_multiple( 0xFF, resultSize ); ba::bytearray copy; for (auto _ : state) { benchmark::DoNotOptimize(copy = std::move(array)); } state.SetComplexityN(resultSize); } BENCHMARK(copy) ->Range(1, 1 << 20) ->Complexity(); BENCHMARK(move) ->Range(1, 1 << 20) ->Complexity(); <|start_filename|>tests/ViewTest.cpp<|end_filename|> #include <gtest/gtest.h> #include <ba/bytearray.hpp> #include <ba/bytearray_view.hpp> TEST(View, ConstructorByteArray) { ba::bytearray array{}; ba::bytearray_view view(array); } TEST(View, ConstructorByteArrayProcessor) { std::vector<std::byte> container; ba::bytearray_processor processor(container); ba::bytearray_view view(processor); } TEST(View, IndexOperator) { ba::bytearray array{}; array.push_back<uint64_t>(0xDEADBEEFAABBCCDD); ba::bytearray_view view(array, 1, 6); // 0xADBEEFAABBCC uint8_t expect[] = { 0xAD, 0xBE, 0xEF, 0xAA, 0xBB, 0xCC }; ASSERT_EQ(view.size(), 6); for (decltype(view)::size_type i = 0; i < 6; ++i) { ASSERT_EQ(uint8_t(view[i]), expect[i]); } } TEST(View, Iterators) { ba::bytearray array{}; array.push_back<uint64_t>(0xDEADBEEFAABBCCDD); ba::bytearray_view view(array, 1, 6); // 0xADBEEFAABBCC uint8_t expect[] = { 0xAD, 0xBE, 0xEF, 0xAA, 0xBB, 0xCC }; ASSERT_EQ(view.size(), 6); for (auto iter = view.begin(), end = view.end(); iter != end; ++iter) { ASSERT_EQ(uint8_t(*iter), expect[std::distance(view.begin(), iter)]); } } TEST(View, ConstantIterators) { ba::bytearray array{}; array.push_back<uint64_t>(0xDEADBEEFAABBCCDD); const ba::bytearray_view view(array, 1, 6); // 0xADBEEFAABBCC uint8_t expect[] = { 0xAD, 0xBE, 0xEF, 0xAA, 0xBB, 0xCC }; ASSERT_EQ(view.size(), 6); for (auto iter = view.cbegin(), end = view.cend(); iter != end; ++iter) { ASSERT_EQ(uint8_t(*iter), expect[std::distance(view.cbegin(), iter)]); } } TEST(View, ReverseIterators) { ba::bytearray array{}; array.push_back<uint64_t>(0xDEADBEEFAABBCCDD); ba::bytearray_view view(array, 1, 6); // 0xADBEEFAABBCC uint8_t expect[] = { 0xCC, 0xBB, 0xAA, 0xEF, 0xBE, 0xAD }; ASSERT_EQ(view.size(), 6); for (auto iter = view.rbegin(), end = view.rend(); iter != end; ++iter) { ASSERT_EQ(uint8_t(*iter), expect[std::distance(view.rbegin(), iter)]); } } TEST(View, ConstantReverseIterators) { ba::bytearray array{}; array.push_back<uint64_t>(0xDEADBEEFAABBCCDD); const ba::bytearray_view view(array, 1, 6); // 0xADBEEFAABBCC uint8_t expect[] = { 0xCC, 0xBB, 0xAA, 0xEF, 0xBE, 0xAD }; ASSERT_EQ(view.size(), 6); for (auto iter = view.crbegin(), end = view.crend(); iter != end; ++iter) { ASSERT_EQ(uint8_t(*iter), expect[std::distance(view.crbegin(), iter)]); } } TEST(View, PushBackUint8) { ba::bytearray array{}; array.push_back<uint64_t>(0xDEADBEEFAABBCCDD); ba::bytearray_view view(array, 1, 6); uint8_t expect_view[] = { 0xAD, 0xBE, 0xEF, 0xAA, 0xBB, 0xCC, 0xFF }; uint8_t expect_array[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xAA, 0xBB, 0xCC, 0xFF, 0xDD }; view.push_back<uint8_t>(0xFF); ASSERT_EQ(view.size(), 7); ASSERT_EQ(array.size(), 9); for (decltype(view)::size_type i = 0; i < view.size(); ++i) { ASSERT_EQ(uint8_t(view[i]), expect_view[i]); } for (decltype(array)::size_type i = 0; i < array.size(); ++i) { ASSERT_EQ(uint8_t(array[i]), expect_array[i]); } } TEST(View, PushBackPart) { uint8_t init[] { 0xFF, 0xFF, 0xFF, 0xFF }; uint8_t expect_le[] = { 0xFF, 0xFF, 0xFF, 0xEF, 0xBE, 0xAD, 0xFF }; uint8_t expect_le_view[] = { 0xFF, 0xFF, 0xEF, 0xBE, 0xAD }; uint8_t expect_be[] = { 0xFF, 0xFF, 0xFF, 0xAD, 0xBE, 0xEF, 0xFF }; uint8_t expect_be_view[] = { 0xFF, 0xFF, 0xAD, 0xBE, 0xEF }; { ba::bytearray array(reinterpret_cast<const std::byte*>(init), 4); ba::bytearray_view view(array, 1, 2); view.push_back_part<uint32_t>(0xDEADBEEF, 3, ba::endianness::big); ASSERT_EQ(array.size(), 7); ASSERT_EQ(view.size(), 5); for (decltype(view)::size_type i = 0; i < view.size(); ++i) { ASSERT_EQ(uint8_t(view[i]), expect_be_view[i]); } for (decltype(array)::size_type i = 0; i < array.size(); ++i) { ASSERT_EQ(uint8_t(array[i]), expect_be[i]); } } { ba::bytearray array(reinterpret_cast<const std::byte*>(init), 4); ba::bytearray_view view(array, 1, 2); view.push_back_part<uint32_t>(0xDEADBEEF, 3, ba::endianness::little); ASSERT_EQ(array.size(), 7); ASSERT_EQ(view.size(), 5); for (decltype(view)::size_type i = 0; i < view.size(); ++i) { ASSERT_EQ(uint8_t(view[i]), expect_le_view[i]); } for (decltype(array)::size_type i = 0; i < array.size(); ++i) { ASSERT_EQ(uint8_t(array[i]), expect_le[i]); } } } TEST(View, PushBackMultiple1) { uint8_t init[] { 0xFF, 0xFF, 0xFF, 0xFF }; uint8_t expect_be[] = { 0xFF, 0xFF, 0xFF, 0xDE, 0xAD, 0xDE, 0xAD, 0xFF }; uint8_t expect_be_view[] = { 0xFF, 0xFF, 0xDE, 0xAD, 0xDE, 0xAD }; uint8_t expect_le[] = { 0xFF, 0xFF, 0xFF, 0xAD, 0xDE, 0xAD, 0xDE, 0xFF }; uint8_t expect_le_view[] = { 0xFF, 0xFF, 0xAD, 0xDE, 0xAD, 0xDE }; { ba::bytearray array(reinterpret_cast<const std::byte*>(init), 4); ba::bytearray_view view(array, 1, 2); view.push_back_multiple<uint16_t>( 0xDEAD, 2, ba::endianness::big ); ASSERT_EQ(array.size(), 8); ASSERT_EQ(view.size(), 6); for (decltype(array)::size_type i = 0; i < array.size(); ++i) { ASSERT_EQ(uint8_t(array[i]), expect_be[i]); } for (decltype(view)::size_type i = 0; i < view.size(); ++i) { ASSERT_EQ(uint8_t(view[i]), expect_be_view[i]); } } { ba::bytearray array(reinterpret_cast<const std::byte*>(init), 4); ba::bytearray_view view(array, 1, 2); view.push_back_multiple<uint16_t>( 0xDEAD, 2, ba::endianness::little ); ASSERT_EQ(array.size(), 8); ASSERT_EQ(view.size(), 6); for (decltype(array)::size_type i = 0; i < array.size(); ++i) { ASSERT_EQ(uint8_t(array[i]), expect_le[i]); } for (decltype(view)::size_type i = 0; i < view.size(); ++i) { ASSERT_EQ(uint8_t(view[i]), expect_le_view[i]); } } } TEST(View, Empty) { ba::bytearray array{}; ba::bytearray_view view(array); ASSERT_TRUE(view.empty()); view.push_back<uint8_t>(0xFF); ASSERT_FALSE(view.empty()); } TEST(View, Comparison) { ba::bytearray array1{}; ba::bytearray array2{}; ba::bytearray_view view1(array1); ba::bytearray_view view2(array2); ASSERT_TRUE(view1 == view2); view1.push_back<uint64_t>(0xDDEEAADDBBEEEEFF); view2.push_back<uint64_t>(0xDDEEAADDBBEEEEFF); ASSERT_TRUE(view1 == view2); auto tmp = view1[0]; view1[0] = std::byte(0xAA); ASSERT_FALSE(view1 == view2); view1[0] = tmp; ASSERT_TRUE(view1 == view2); view1.push_back<uint8_t>(0xAA); ASSERT_FALSE(view1 == view2); } TEST(View, InsertNormal) { uint8_t initial[] = { 0xFF, 0xFF, 0xFF, 0xFF }; uint8_t expect_le[] = { 0xFF, 0xEF, 0xBE, 0xAD, 0xDE, 0xFF }; uint8_t expect_be[] = { 0xFF, 0xDE, 0xAD, 0xBE, 0xEF, 0xFF }; { ba::bytearray array((std::byte*) initial, 4); ba::bytearray_view view(array, 1, 2); view.insert<uint32_t>(1, 0xDEADBEEF, ba::endianness::big); ASSERT_EQ(view.size(), 6); for (ba::bytearray<>::size_type i = 0; i < view.size(); ++i) { ASSERT_EQ(uint8_t(view[i]), expect_be[i]); } } { ba::bytearray array((std::byte*) initial, 4); ba::bytearray_view view(array, 1, 2); view.insert<uint32_t>(1, 0xDEADBEEF, ba::endianness::little); ASSERT_EQ(view.size(), 6); for (ba::bytearray<>::size_type i = 0; i < view.size(); ++i) { ASSERT_EQ(uint8_t(view[i]), expect_le[i]); } } } TEST(View, InsertPart) { uint8_t initial[] = { 0xFF, 0xFF, 0xFF, 0xFF }; uint8_t expect_le[] = { 0xFF, 0xEF, 0xBE, 0xAD, 0xFF }; uint8_t expect_be[] = { 0xFF, 0xAD, 0xBE, 0xEF, 0xFF }; { ba::bytearray array((std::byte*) initial, 4); ba::bytearray_view view(array, 1, 2); view.insert_part<uint32_t>(1, 0xDEADBEEF, 3, ba::endianness::big); ASSERT_EQ(view.size(), 5); for (ba::bytearray<>::size_type i = 0; i < view.size(); ++i) { ASSERT_EQ(uint8_t(view[i]), expect_be[i]); } } { ba::bytearray array((std::byte*) initial, 4); ba::bytearray_view view(array, 1, 2); view.insert_part<uint32_t>(1, 0xDEADBEEF, 3, ba::endianness::little); ASSERT_EQ(view.size(), 5); for (ba::bytearray<>::size_type i = 0; i < view.size(); ++i) { ASSERT_EQ(uint8_t(view[i]), expect_le[i]); } } } TEST(View, InsertMultiple1) { uint8_t initial[] = { 0xFF, 0xFF, 0xFF, 0xFF }; uint8_t expect_be[] = { 0xFF, 0xDE, 0xAD, 0xDE, 0xAD, 0xFF }; uint8_t expect_le[] = { 0xFF, 0xAD, 0xDE, 0xAD, 0xDE, 0xFF }; { ba::bytearray array(reinterpret_cast<const std::byte*>(initial), 4); ba::bytearray_view view(array, 1, 2); view.insert_multiple<uint16_t>( 1, 0xDEAD, 2, ba::endianness::big ); ASSERT_EQ(view.size(), 6); for (ba::bytearray<>::size_type i = 0; i < view.size(); ++i) { ASSERT_EQ(uint8_t(view[i]), expect_be[i]); } } { ba::bytearray array(reinterpret_cast<const std::byte*>(initial), 4); ba::bytearray_view view(array, 1, 2); view.insert_multiple<uint16_t>( 1, 0xDEAD, 2, ba::endianness::little ); ASSERT_EQ(view.size(), 6); for (ba::bytearray<>::size_type i = 0; i < view.size(); ++i) { ASSERT_EQ(uint8_t(view[i]), expect_le[i]); } } } TEST(View, InsertMultiple2) { uint8_t initial[] = { 0xFF, 0xFF, 0xFF, 0xFF }; uint8_t expect_be[] = { 0xFF, 0xDE, 0xAD, 0xDE, 0xAD, 0xFF }; uint8_t expect_le[] = { 0xFF, 0xAD, 0xDE, 0xAD, 0xDE, 0xFF }; std::vector<uint16_t> insertionData = { 0xDEAD, 0xDEAD }; { ba::bytearray array(reinterpret_cast<const std::byte*>(initial), 4); ba::bytearray_view view(array, 1, 2); view.insert_multiple( 1, insertionData.begin(), insertionData.end(), ba::endianness::big ); ASSERT_EQ(view.size(), 6); for (ba::bytearray<>::size_type i = 0; i < view.size(); ++i) { ASSERT_EQ(uint8_t(view[i]), expect_be[i]); } } { ba::bytearray array(reinterpret_cast<const std::byte*>(initial), 4); ba::bytearray_view view(array, 1, 2); view.insert_multiple( 1, insertionData.begin(), insertionData.end(), ba::endianness::little ); ASSERT_EQ(view.size(), 6); for (ba::bytearray<>::size_type i = 0; i < view.size(); ++i) { ASSERT_EQ(uint8_t(view[i]), expect_le[i]); } } } TEST(View, ReadUint8) { const uint8_t value = 0xDE; { ba::bytearray data{}; ba::bytearray_view view(data, 0, 0); view.push_back<uint8_t>(value, ba::endianness::big); ASSERT_EQ( view.read<uint8_t>(0, ba::endianness::big), value ); } { ba::bytearray data{}; ba::bytearray_view view(data, 0, 0); view.push_back<uint8_t>(value, ba::endianness::little); ASSERT_EQ( view.read<uint8_t>(0, ba::endianness::little), value ); } } TEST(View, ReadUint32) { const uint32_t value = 0xDEADBEEF; { ba::bytearray data{}; ba::bytearray_view view(data, 0, 0); view.push_back<uint32_t>(value, ba::endianness::big); ASSERT_EQ( view.read<uint32_t>(0, ba::endianness::big), value ); } { ba::bytearray data{}; ba::bytearray_view view(data, 0, 0); view.push_back<uint32_t>(value, ba::endianness::little); ASSERT_EQ( view.read<uint32_t>(0, ba::endianness::little), value ); } } TEST(View, ReadUint64) { const uint64_t value = 0xDEADBEEFFFEEFFEE; { ba::bytearray data{}; ba::bytearray_view view(data, 0, 0); view.push_back<uint64_t>(value, ba::endianness::big); ASSERT_EQ( view.read<uint64_t>(0, ba::endianness::big), value ); } { ba::bytearray data{}; ba::bytearray_view view(data, 0, 0); view.push_back<uint64_t>(value, ba::endianness::little); ASSERT_EQ( view.read<uint64_t>(0, ba::endianness::little), value ); } } TEST(View, ReadInt64) { const int64_t value = 0xDEADBEEFFFEEFFEE; { ba::bytearray data{}; ba::bytearray_view view(data, 0, 0); view.push_back<int64_t>(value, ba::endianness::big); ASSERT_EQ( view.read<int64_t>(0, ba::endianness::big), value ); } { ba::bytearray data{}; ba::bytearray_view view(data, 0, 0); view.push_back<int64_t>(value, ba::endianness::little); ASSERT_EQ( view.read<int64_t>(0, ba::endianness::little), value ); } } struct CustomStructBase { uint64_t a; uint32_t c; char z; char message[32]; }; struct CustomStructDerived : CustomStructBase { char additional[64]; bool operator==(const CustomStructDerived& rhs) { return rhs.a == a && rhs.c == c && rhs.z == z && memcmp(rhs.message, message, 32) == 0 && memcmp(rhs.additional, additional, 64) == 0; } }; TEST(View, ReadCustom) { CustomStructDerived value = {}; value.a = 0xDEADDEADBEEFBEEF; value.c = 0xFEEDBEEF; value.z = '%'; memcpy(value.message, "Sample message", 15); memcpy(value.additional, "Some actual long additional message", 35); { ba::bytearray data{}; ba::bytearray_view view(data, 0, 0); view.push_back(value, ba::endianness::big); ASSERT_TRUE( view.read<CustomStructDerived>(0, ba::endianness::big) == value ); } { ba::bytearray data{}; ba::bytearray_view view(data, 0, 0); view.push_back(value, ba::endianness::little); ASSERT_TRUE( view.read<CustomStructDerived>(0, ba::endianness::little) == value ); } } TEST(View, ReadPart) { uint64_t value = 0x00ADBEEFFFEEAABB; { ba::bytearray data{}; ba::bytearray_view view(data, 0, 0); view.push_back_part(value, 7, ba::endianness::big); ASSERT_EQ(value, view.read_part<uint64_t>(0, 7, ba::endianness::big)); } { ba::bytearray data{}; ba::bytearray_view view(data, 0, 0); view.push_back_part(value, 7, ba::endianness::little); ASSERT_EQ(value, view.read_part<uint64_t>(0, 7, ba::endianness::little)); } } <|start_filename|>tests/InsertTest.cpp<|end_filename|> #include <gtest/gtest.h> #include <ba/bytearray.hpp> TEST(Insert, Normal) { uint8_t initial[] = { 0xFF, 0xFF }; uint8_t expect_le[] = { 0xFF, 0xEF, 0xBE, 0xAD, 0xDE, 0xFF }; uint8_t expect_be[] = { 0xFF, 0xDE, 0xAD, 0xBE, 0xEF, 0xFF }; { ba::bytearray array((std::byte*) initial, 2); array.insert<uint32_t>(1, 0xDEADBEEF, ba::endianness::big); ASSERT_EQ(array.size(), 6); for (ba::bytearray<>::size_type i = 0; i < array.size(); ++i) { ASSERT_EQ(uint8_t(array[i]), expect_be[i]); } } { ba::bytearray array((std::byte*) initial, 2); array.insert<uint32_t>(1, 0xDEADBEEF, ba::endianness::little); ASSERT_EQ(array.size(), 6); for (ba::bytearray<>::size_type i = 0; i < array.size(); ++i) { ASSERT_EQ(uint8_t(array[i]), expect_le[i]); } } } TEST(Insert, Part) { uint8_t initial[] = { 0xFF, 0xFF }; uint8_t expect_le[] = { 0xFF, 0xEF, 0xBE, 0xAD, 0xFF }; uint8_t expect_be[] = { 0xFF, 0xAD, 0xBE, 0xEF, 0xFF }; { ba::bytearray array((std::byte*) initial, 2); array.insert_part<uint32_t>(1, 0xDEADBEEF, 3, ba::endianness::big); ASSERT_EQ(array.size(), 5); for (ba::bytearray<>::size_type i = 0; i < array.size(); ++i) { ASSERT_EQ(uint8_t(array[i]), expect_be[i]); } } { ba::bytearray array((std::byte*) initial, 2); array.insert_part<uint32_t>(1, 0xDEADBEEF, 3, ba::endianness::little); ASSERT_EQ(array.size(), 5); for (ba::bytearray<>::size_type i = 0; i < array.size(); ++i) { ASSERT_EQ(uint8_t(array[i]), expect_le[i]); } } } TEST(Insert, Multiple1) { uint8_t initial[] = { 0xFF, 0xFF }; uint8_t expect_be[] = { 0xFF, 0xDE, 0xAD, 0xDE, 0xAD, 0xFF }; uint8_t expect_le[] = { 0xFF, 0xAD, 0xDE, 0xAD, 0xDE, 0xFF }; { ba::bytearray array(reinterpret_cast<const std::byte*>(initial), 2); array.insert_multiple<uint16_t>( 1, 0xDEAD, 2, ba::endianness::big ); ASSERT_EQ(array.size(), 6); for (ba::bytearray<>::size_type i = 0; i < array.size(); ++i) { ASSERT_EQ(uint8_t(array[i]), expect_be[i]); } } { ba::bytearray array(reinterpret_cast<const std::byte*>(initial), 2); array.insert_multiple<uint16_t>( 1, 0xDEAD, 2, ba::endianness::little ); ASSERT_EQ(array.size(), 6); for (ba::bytearray<>::size_type i = 0; i < array.size(); ++i) { ASSERT_EQ(uint8_t(array[i]), expect_le[i]); } } } TEST(Insert, Multiple2) { uint8_t initial[] = { 0xFF, 0xFF }; uint8_t expect_be[] = { 0xFF, 0xDE, 0xAD, 0xDE, 0xAD, 0xFF }; uint8_t expect_le[] = { 0xFF, 0xAD, 0xDE, 0xAD, 0xDE, 0xFF }; std::vector<uint16_t> insertionData = { 0xDEAD, 0xDEAD }; { ba::bytearray array(reinterpret_cast<const std::byte*>(initial), 2); array.insert_multiple( 1, insertionData.begin(), insertionData.end(), ba::endianness::big ); ASSERT_EQ(array.size(), 6); for (ba::bytearray<>::size_type i = 0; i < array.size(); ++i) { ASSERT_EQ(uint8_t(array[i]), expect_be[i]); } } { ba::bytearray array(reinterpret_cast<const std::byte*>(initial), 2); array.insert_multiple( 1, insertionData.begin(), insertionData.end(), ba::endianness::little ); ASSERT_EQ(array.size(), 6); for (ba::bytearray<>::size_type i = 0; i < array.size(); ++i) { ASSERT_EQ(uint8_t(array[i]), expect_le[i]); } } } <|start_filename|>tests/SetTest.cpp<|end_filename|> #include <gtest/gtest.h> #include <ba/bytearray.hpp> uint8_t initialData[8] = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x01, 0x02 }; TEST(Set, UInt8) { uint8_t expect[8] = { 0x01, 0x02, 0xDE, 0x04, 0x05, 0x06, 0x01, 0x02 }; { ba::bytearray data(reinterpret_cast<std::byte*>(initialData), 8); data.set<uint8_t>(2, 0xDE, ba::endianness::big); ASSERT_EQ(data.size(), 8); for (ba::bytearray<>::size_type i = 0; i < data.size(); ++i) { ASSERT_EQ(uint8_t(data[i]), expect[i]); } } { ba::bytearray data(reinterpret_cast<std::byte*>(initialData), 8); data.set<uint8_t>(2, 0xDE, ba::endianness::little); ASSERT_EQ(data.size(), 8); for (ba::bytearray<>::size_type i = 0; i < data.size(); ++i) { ASSERT_EQ(uint8_t(data[i]), expect[i]); } } } TEST(Set, UInt16) { uint8_t expect_be[8] = { 0x01, 0x02, 0xDE, 0xAD, 0x05, 0x06, 0x01, 0x02 }; uint8_t expect_le[8] = { 0x01, 0x02, 0xAD, 0xDE, 0x05, 0x06, 0x01, 0x02 }; { ba::bytearray data(reinterpret_cast<std::byte*>(initialData), 8); data.set<uint16_t>(2, 0xDEAD, ba::endianness::big); ASSERT_EQ(data.size(), 8); for (ba::bytearray<>::size_type i = 0; i < data.size(); ++i) { ASSERT_EQ(uint8_t(data[i]), expect_be[i]); } } { ba::bytearray data(reinterpret_cast<std::byte*>(initialData), 8); data.set<uint16_t>(2, 0xDEAD, ba::endianness::little); ASSERT_EQ(data.size(), 8); for (ba::bytearray<>::size_type i = 0; i < data.size(); ++i) { ASSERT_EQ(uint8_t(data[i]), expect_le[i]); } } } TEST(Set, UInt32) { uint8_t expect_be[8] = { 0x01, 0x02, 0xDE, 0xAD, 0xBE, 0xEF, 0x01, 0x02 }; uint8_t expect_le[8] = { 0x01, 0x02, 0xEF, 0xBE, 0xAD, 0xDE, 0x01, 0x02 }; { ba::bytearray data(reinterpret_cast<std::byte*>(initialData), 8); data.set<uint32_t>(2, 0xDEADBEEF, ba::endianness::big); ASSERT_EQ(data.size(), 8); for (ba::bytearray<>::size_type i = 0; i < data.size(); ++i) { ASSERT_EQ(uint8_t(data[i]), expect_be[i]); } } { ba::bytearray data(reinterpret_cast<std::byte*>(initialData), 8); data.set<uint32_t>(2, 0xDEADBEEF, ba::endianness::little); ASSERT_EQ(data.size(), 8); for (ba::bytearray<>::size_type i = 0; i < data.size(); ++i) { ASSERT_EQ(uint8_t(data[i]), expect_le[i]); } } } TEST(Set, UInt64) { uint8_t expect_be[8] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xEE, 0xAA, 0xBB, 0xCC }; uint8_t expect_le[8] = { 0xCC, 0xBB, 0xAA, 0xEE, 0xEF, 0xBE, 0xAD, 0xDE }; { ba::bytearray data(reinterpret_cast<std::byte*>(initialData), 8); data.set<uint64_t>(0, 0xDEADBEEFEEAABBCC, ba::endianness::big); ASSERT_EQ(data.size(), 8); for (ba::bytearray<>::size_type i = 0; i < data.size(); ++i) { ASSERT_EQ(uint8_t(data[i]), expect_be[i]); } } { ba::bytearray data(reinterpret_cast<std::byte*>(initialData), 8); data.set<uint64_t>(0, 0xDEADBEEFEEAABBCC, ba::endianness::little); ASSERT_EQ(data.size(), 8); for (ba::bytearray<>::size_type i = 0; i < data.size(); ++i) { ASSERT_EQ(uint8_t(data[i]), expect_le[i]); } } } <|start_filename|>include/ba/bytearray_view.hpp<|end_filename|> #pragma once #include <ba/bytearray.hpp> namespace ba { /** * @brief Class, that describes * bytearray representation with different size * based values. * @tparam Allocator Allocator. */ template <typename ValueType, typename Allocator = std::allocator<ValueType> > class bytearray_view { using container = bytearray_processor<ValueType, Allocator>; /** * @brief Stream output function. */ friend std::ostream& operator<<(std::ostream& ostream, const bytearray_view& container) { // Printing header ostream << "ByteArray({" << std::endl; ostream << " #-------------#-------------#-------------#-------------#" << std::endl; ostream << " | 00 01 02 03 | 04 05 06 07 | 08 09 0A 0B | 0C 0D 0E 0F |" << std::endl; ostream << " #-------------#-------------#-------------#-------------#"; // Saving states auto oldFlags = ostream.flags(); auto oldPrec = ostream.precision(); auto oldFill = ostream.fill(); // Changing fill character ostream.fill('0'); // size_type index = 0; for (index = 0; index < container.size() + (16 - (container.size() % 16)); ++index) { if (!(index % 16)) { if (index) { ostream << "| "; } for (std::size_t asc = index - 16; asc < index; ++asc) { if (container[asc] >= ValueType(' ') && container[asc] <= ValueType('~')) { ostream << static_cast<char>(container[asc]); } else { ostream << '.'; } } ostream << std::endl << " 0x"; ostream.width(8); ostream << std::hex << index << ' '; } if (!(index % 4)) { ostream << "| "; } if (index < container.size()) { ostream.width(2); ostream << std::uppercase << std::hex << static_cast<int>(container[index]) << ' '; } else { ostream << " "; } } if (index) { ostream << "| "; } for (size_type asc = index - 16; asc < index; ++asc) { if (asc < container.size()) { if (container[asc] >= ValueType(' ') && container[asc] <= ValueType('~')) { ostream << static_cast<char>(container[asc]); } else { ostream << '.'; } } else { ostream << ' '; } } ostream << std::endl << std::nouppercase << " #-------------#-------------#-------------#-------------#" << std::endl << "}, Length: " << std::dec << container.size() << ')' << std::endl; ostream.flags(oldFlags); ostream.precision(oldPrec); ostream.fill(oldFill); return ostream; } public: using size_type = typename container::size_type; using value_type = typename container::value_type; /** * @brief Constructor. * @param bytearray Base byte array. */ explicit bytearray_view(container& bytearray) : m_byteArray(bytearray) , m_start(0) , m_size(m_byteArray.container().size()) {} /** * @brief Constructor with boundaries. * @param bytearray Initial byte array. * @param start Start position. * @param size Size. */ bytearray_view(container& bytearray, size_type start, size_type size) : m_byteArray(bytearray) , m_start(start) , m_size(size) { assert(start <= m_byteArray.container().size()); assert(start + size <= m_byteArray.container().size()); } /** * @brief Method for getting initial * byte array object. */ container& bytearray() { return m_byteArray; } /** * @brief Method for getting constant reference * to initial byte array object. */ const container& bytearray() const { return m_byteArray; } /** * @brief Method for getting begin of this * view. */ typename container::vector::iterator begin() { return m_byteArray.container().begin() + m_start; } /** * @brief Method for getting begin of this * view. */ typename container::vector::const_iterator begin() const { return cbegin(); } /** * @brief Method for getting end of this view. */ typename container::vector::iterator end() { return m_byteArray.container().begin() + (m_start + m_size); } /** * @brief Method for getting end of this view. */ typename container::vector::const_iterator end() const { return cend(); } /** * @brief Method for getting constant begin of this * view. */ typename container::vector::const_iterator cbegin() const { return m_byteArray.container().cbegin() + m_start; } /** * @brief Method for getting constant end of this * view. */ typename container::vector::const_iterator cend() const { return m_byteArray.container().cbegin() + (m_start + m_size); } /** * @brief Method for getting reverse begin of this * view. */ typename container::vector::reverse_iterator rbegin() { return m_byteArray.container().rbegin() + (m_byteArray.container().size() - (m_start + m_size)); } /** * @brief Method for getting reverse end of this view. */ typename container::vector::reverse_iterator rend() { return m_byteArray.container().rbegin() + (m_byteArray.container().size() - m_start); } /** * @brief Method for getting constant reverse begin of this view. */ typename container::vector::const_reverse_iterator crbegin() const { return m_byteArray.container().crbegin() + (m_byteArray.container().size() - (m_start + m_size)); } /** * @brief Method for getting constant reverse end of this view. */ typename container::vector::const_reverse_iterator crend() const { return m_byteArray.container().crbegin() + (m_byteArray.container().size() - m_start); } /** * @brief Method for getting view size. * @return Size in bytes. */ typename container::size_type size() const { return m_size; } /** * @brief Method for access to specified element. * @param i Index. * @return Reference to value. */ typename container::value_type& operator[](size_type i) { return m_byteArray.container()[m_start + i]; } /** * @brief Method for const access to specified element. * @param i Index. */ typename container::value_type operator[](size_type i) const { return m_byteArray.container()[m_start + i]; } /** * @brief Method for access to specified element with * bounds checking. * @param i Index. * @return Reference to value. */ typename container::value_type& at(size_type i) { return m_byteArray.container().at(i); } /** * @brief Method for const access to specified element with * bounds checking. * @param i Index. * @return Reference to value. */ typename container::value_type at(size_type i) const { return m_byteArray.container().at(i); } /** * @brief Method, that returns maximum number of * elements. */ typename container::size_type max_size() const { return std::numeric_limits<typename container::size_type>::max(); } /** * @brief Method for pushing back some trivially copyable type * with defined endianness. * @tparam T Type. * @param value Value. * @param order Endianness. */ template <typename T> typename std::enable_if<std::is_trivially_copyable<T>::value>::type push_back(T value, endianness order = endianness::big) { m_byteArray.template insert<T>(m_start + m_size, value, order); m_size += sizeof(T); } /** * @brief Method for pushing back some part of trivially copyable type * value with defined endianness. * @tparam T Type. * @param value Value. * @param size Amount of bytes. * @param order Endianness. */ template <typename T> typename std::enable_if<std::is_trivially_copyable<T>::value>::type push_back_part(T value, size_type size, endianness order = endianness::big) { assert(sizeof(T) >= size && "Can't push size bigger, than type."); m_byteArray.template insert_part<T>(m_start + m_size, value, size, order); m_size += size; } /** * @brief Method for pushing back multiple instances of some trivially * copyable type value with defined endiannes for each element. * @tparam T Type. * @param value Value. * @param amount Amount of elements. * @param order Endianness. */ template <typename T> typename std::enable_if<std::is_trivially_copyable<T>::value>::type push_back_multiple(T value, size_type amount, endianness order = endianness::big) { m_byteArray.template insert_multiple<T>(m_start + m_size, value, amount, order); m_size += amount * sizeof(T); } /** * @brief Method for insertion some trivially copyable type * with defined endianness. * @tparam T Type. * @param position Position. * @param value Value. * @param order Endianness. */ template <typename T> typename std::enable_if<std::is_trivially_copyable<T>::value>::type insert(size_type position, T value, endianness order = endianness::big) { assert(position <= m_size && "Position is out of bounds."); m_byteArray.template insert<T>(m_start + position, value, order); m_size += sizeof(T); } /** * @brief Method for insertion part of some trivially * copyable value with defined endianness. * @tparam T Type. * @param position Position. * @param value Value. * @param size Amount of bytes of value. * @param order Endianness. */ template <typename T> typename std::enable_if<std::is_trivially_copyable<T>::value>::type insert_part(size_type position, T value, size_type size, endianness order = endianness::big) { assert(position <= m_size && "Position is out of bounds."); m_byteArray.template insert_part<T>(m_start + position, value, size, order); m_size += size; } /** * @brief Method for insertion multiple same elements * with defined endianness. * @tparam T Type. * @param position Position. * @param value Value. * @param amount Amount of elements. * @param order Endianness. */ template <typename T> typename std::enable_if<std::is_trivially_copyable<T>::value>::type insert_multiple(size_type position, T value, size_type amount, endianness order = endianness::big) { assert(position <= m_size && "Position is out of bounds."); m_byteArray.template insert_multiple<T>(m_start + position, value, amount, order); m_size += sizeof(T) * amount; } /** * @brief Method for insertion multiple elements with * defined endianness. * @tparam InputIterator Iterator type. * @param position Position. * @param begin Begin iterator. * @param last Last iterator. * @param order Endianness. */ template <typename InputIterator> typename std::enable_if<std::is_trivially_copyable<typename std::iterator_traits<InputIterator>::value_type>::value>::type insert_multiple(size_type position, InputIterator begin, InputIterator last, endianness order = endianness::big) { m_byteArray.template insert_multiple(m_start + position, begin, last, order); m_size += sizeof(typename std::iterator_traits<InputIterator>::value_type) * std::distance(begin, last); } /** * @brief Method for setting value in byte array * container. * @tparam T Value type. * @param position Set position. * @param value Value. * @param order Byte order. */ template <typename T> typename std::enable_if<std::is_trivially_copyable<T>::value>::type set(size_type position, T value, endianness order = endianness::big) { assert(position + sizeof(T) <= size() && "Position + type size is out of bounds."); m_byteArray.template set<T>(m_start + position, value, order); } /** * @brief Method for performing translation of * byte array to some trivially copyable type. * @tparam T Type. * @param position Value position. * @param order Read order. * @return Read value. */ template <typename T> typename std::enable_if<std::is_trivially_copyable<T>::value, T>::type read(size_type position, endianness order = endianness::big) const { assert(position + sizeof(T) <= size() && "Position + type size if out of bounde."); return m_byteArray.template read<T>(m_start + position, order); } /** * @brief Method for performing translation of * byte array to some part of trivially copyable type. * @tparam T Type. * @param position Value position. * @param order Read order. * @return Read value. */ template <typename T> typename std::enable_if<std::is_trivially_copyable<T>::value, T>::type read_part(size_type position, size_type size, endianness order = endianness::big) const { assert(size <= sizeof(T) && "Size if bigger, than types size"); assert(position + size <= this->size() && "Position + size is out of bounds."); return m_byteArray.template read_part<T>(m_start + position, size, order); } /** * @brief Method for checking whether the view is empty. */ bool empty() const { return m_size == 0; } const ValueType* data() const { return m_byteArray.container().data() + m_start; } ValueType* data() { return m_byteArray.container().data() + m_start; } /** * @brief Method for comparison of different views. */ template <typename RhsAllocator> bool operator==(const bytearray_view<value_type, RhsAllocator>& rhs) { if (size() != rhs.size()) { return false; } for (size_type i = 0; i < size(); ++i) { if (operator[](i) != rhs[i]) { return false; } } return true; } private: container& m_byteArray; size_type m_start; size_type m_size; }; } // namespace ba // Allowed namespace std { template <typename ValueType, typename Allocator> std::string to_string(const ba::bytearray_view<ValueType, Allocator>& processor) { std::stringstream ss; for (auto&& b : processor) { ss << std::uppercase << std::setfill('0') << std::setw(2) << std::hex << int(b); } return ss.str(); } } // namespace std <|start_filename|>tests/ReadTest.cpp<|end_filename|> #include <gtest/gtest.h> #include <ba/bytearray.hpp> TEST(Read, Uint8) { const uint8_t value = 0xDE; { ba::bytearray data{}; data.push_back<uint8_t>(value, ba::endianness::big); ASSERT_EQ( data.read<uint8_t>(0, ba::endianness::big), value ); } { ba::bytearray data{}; data.push_back<uint8_t>(value, ba::endianness::little); ASSERT_EQ( data.read<uint8_t>(0, ba::endianness::little), value ); } } TEST(Read, Uint32) { const uint32_t value = 0xDEADBEEF; { ba::bytearray data{}; data.push_back<uint32_t>(value, ba::endianness::big); ASSERT_EQ( data.read<uint32_t>(0, ba::endianness::big), value ); } { ba::bytearray data{}; data.push_back<uint32_t>(value, ba::endianness::little); ASSERT_EQ( data.read<uint32_t>(0, ba::endianness::little), value ); } } TEST(Read, Uint64) { const uint64_t value = 0xDEADBEEFFFEEFFEE; { ba::bytearray data{}; data.push_back<uint64_t>(value, ba::endianness::big); ASSERT_EQ( data.read<uint64_t>(0, ba::endianness::big), value ); } { ba::bytearray data{}; data.push_back<uint64_t>(value, ba::endianness::little); ASSERT_EQ( data.read<uint64_t>(0, ba::endianness::little), value ); } } TEST(Read, Int64) { const int64_t value = 0xDEADBEEFFFEEFFEE; { ba::bytearray data{}; data.push_back<int64_t>(value, ba::endianness::big); ASSERT_EQ( data.read<int64_t>(0, ba::endianness::big), value ); } { ba::bytearray data{}; data.push_back<int64_t>(value, ba::endianness::little); ASSERT_EQ( data.read<int64_t>(0, ba::endianness::little), value ); } } struct CustomStructBase { uint64_t a; uint32_t c; char z; char message[32]; }; struct CustomStructDerived : CustomStructBase { char additional[64]; bool operator==(const CustomStructDerived& rhs) { return rhs.a == a && rhs.c == c && rhs.z == z && memcmp(rhs.message, message, 32) == 0 && memcmp(rhs.additional, additional, 64) == 0; } }; TEST(Read, Custom) { CustomStructDerived value = {}; value.a = 0xDEADDEADBEEFBEEF; value.c = 0xFEEDBEEF; value.z = '%'; memcpy(value.message, "Sample message", 15); memcpy(value.additional, "Some actual long additional message", 35); { ba::bytearray data{}; data.push_back(value, ba::endianness::big); ASSERT_TRUE( data.read<CustomStructDerived>(0, ba::endianness::big) == value ); } { ba::bytearray data{}; data.push_back(value, ba::endianness::little); ASSERT_TRUE( data.read<CustomStructDerived>(0, ba::endianness::little) == value ); } } TEST(Read, Part) { uint64_t value = 0x00ADBEEFFFEEAABB; { ba::bytearray data{}; data.push_back_part(value, 7, ba::endianness::big); ASSERT_EQ(value, data.read_part<uint64_t>(0, 7, ba::endianness::big)); } { ba::bytearray data{}; data.push_back_part(value, 7, ba::endianness::little); ASSERT_EQ(value, data.read_part<uint64_t>(0, 7, ba::endianness::little)); } }
Megaxela/ByteArray
<|start_filename|>gulpfile.js<|end_filename|> const concat = require('gulp-concat'); const contains = require('gulp-contains'); const del = require('del'); const eslint = require('gulp-eslint'); const expose = require('gulp-expose'); const gulp = require('gulp'); const rename = require("gulp-rename"); // Regex that looks for a populated client ID in the code. This is used to // catch cases where the client ID is accidentally committed in a sample. const CLIENT_ID_REGEX = /CLIENT_ID\s*=\s*'[^.']/; // String which if it appears in the source code bypasses the client ID check. // This is to allow samples that use a publicly-available demo client ID to // not trigger the error. const CLIENT_ID_BYPASS = <PASSWORD>'; gulp.task('clean', async function() { return del([ 'dist/*' ]); }); gulp.task('dist', gulp.series('clean', async function(){ return gulp.src('src/*.js') .pipe(concat('OAuth2.gs')) .pipe(expose('this', 'OAuth2')) .pipe(gulp.dest('dist')); })); gulp.task('lint', () => { return gulp.src(['src/*.js', 'samples/*.gs', 'test/**/*.js', '!node_modules/**']) .pipe(eslint()) .pipe(eslint.format()) .pipe(eslint.failAfterError()) .pipe(contains({ search: CLIENT_ID_REGEX, onFound: (string, file, cb) => { if (file.contents.toString().includes(CLIENT_ID_BYPASS)) { return false; } return cb(`Client ID found in file: "${file.relative}"`); } })); }); <|start_filename|>test/mocks/blob.js<|end_filename|> var MockBlob = function(buffer) { this.buffer = buffer; }; MockBlob.prototype.getDataAsString = function() { return this.buffer.toString(); }; module.exports = MockBlob;
squishynsmoo/apps-script-oauth2
<|start_filename|>generate_zip_for_botzone.bat<|end_filename|> @echo off git archive --format=zip -o ./data/Reversi-based_RL.zip HEAD echo Successfully generated zip for botzone! echo Press any key to continue. pause explorer .\data <|start_filename|>src/web/client/js/main.js<|end_filename|> "use strict"; /*棋盘类*/ function Chessboard() { var oo = this; var pieces; //棋子元素 var piecesnum; //黑白子数目显示元素 var side; //表示执棋方元素 oo.toDown = null; //下子 function bindEvent(td) { //绑定点击事件 for (var i = 0; i < 64; i++) (function (i) { td[i].onclick = function () { if (pieces[i].className == "prompt")//标签中可以走的位置已被标记 prompt oo.toDown(i);//下棋的指令 } })(i); td = undefined; } oo.create = function (toDown) { //创建棋盘,toDown 为下棋后触发的事件 oo.toDown = toDown; var obj = document.getElementById("reversi_chessboard"); var html = "<table>";//这个地方创建是通过改变html来创建的,使用table创建 for (var i = 0; i < 8; i++) { html += "<tr>"; for (var j = 0; j < 8; j++) html += "<td class='bg" + (j + i) % 2 + "'><div></div></td>"; html += "</tr>"; } html += "</table>"; obj.innerHTML = html; pieces = obj.getElementsByTagName("div"); bindEvent(obj.getElementsByTagName("td")); piecesnum = document.getElementById("reversi_console").getElementsByTagName("span"); side = { "1": document.getElementById("reversi_side1"), "-1": document.getElementById("reversi_side2") }; } oo.update = function (map) {//更新显示的棋盘 //给入map for (var i = 0; i < 64; i++) pieces[i].className = ["white", "", "black"][map[i] + 1]; for (var n in map.next) pieces[n].className = "prompt"; for (var i = 0; i < map.newRev.length; i++) pieces[map.newRev[i]].className += " reversal"; if (map.newPos != -1) pieces[map.newPos].className += " newest"; piecesnum[0].innerHTML = map.black; piecesnum[1].innerHTML = map.white; side[map.side].className = "cbox side"; side[-map.side].className = "cbox"; } } /* 棋盘逻辑类 */ function Othello() { var oo = this; // oo申明是类本身 var map = []; // 棋局数组 var history = []; // 历史记录,用于悔棋操作 oo.aiSide = 0; // 先行方:1: 电脑为黑棋, -1: 电脑为白棋, 0: 双人对战 2: 电脑自己对战 var aiRuning = false; //AI运算中... var aiRuningObj = document.getElementById("reversi_airuning"); // 也就是指示出现提示框 var passObj = document.getElementById("reversi_pass"); // 没有棋下的时候就返回这个 var timer; // 定时器id:局时 oo.play = function () { // 开始新棋局:所有的数据初始化都在这里,这个是 main if (aiRuning) { // 如果当前有 ai 在执行则跳出 return; } clearTimeout(timer);// 清空计时器 console.clear(); // 清空控制台下信息,用于调试方便 // 棋盘初始化 map = new Array(64).fill(0); // 空格为 0 map[28] = map[35] = 1; // 黑子为 1 map[27] = map[36] = -1; // 白子为 -1 map.black = map.white = 2; // 黑白棋子数目 map.space = 60; // 空格数目(64个格子,但是一开始4个是有东西的了) map.frontier = []; // 当前棋盘上所有棋子临近的空格子 var tk = [18, 19, 20, 21, 26, 29, 34, 37, 42, 43, 44, 45];//用于初始化的暂存数据 for (var i = 0; i < tk.length; i++) map.frontier[tk[i]] = true; map.side = 1; // 当前执棋方(1.黑棋 0.白棋) map.newPos = -1; // 最新下子的位置 map.newRev = []; // 最新反转棋子的位置 map.nextIndex = []; // 下一步可走棋的位置 map.next = {}; // 下一步可走棋的反转棋子 map.nextNum = 0; // 下一步可走棋的数目 map.prevNum = 0; // 上一步可走棋的数目 history = []; // 历史记录 update(); // update更新上面的初始化数据 } function update() { //每次更新棋盘:判断是否可走, // 如果 AI 是当前持子方或者是电脑自己对战时为 true var aiAuto = oo.aiSide == map.side || oo.aiSide == 2; oo.findLocation(map); setAIRunStatus(false);//不显示ai在计算 setPassStatus(false);//不显示pass board.update(map);//ai下棋:传入map,还有aiAuto函数 // console.log(map.nextIndex) if (map.space == 0 || map.nextNum == 0 && map.prevNum == 0) {//棋盘子满 或 双方都无棋可走 timer = setTimeout(gameOver, 450); return; } if (map.nextNum == 0) {//无棋可走pass timer = setTimeout(function () { oo.pass(map); update(); setPassStatus(true);//不显示pass }, 450); return; } if (aiAuto) {//也就是当aiAuto是真的时候开始执行 aiRuning = true;//这个是打一个条幅 timer = setTimeout(function () { setAIRunStatus(true);//AI开始运行 timer = setTimeout(reversiBasedRLAIRun, 50);//这个地方就是ai走棋了 }, 400); } } function reversiRandomAIRun() { // 一个随机的 AI,用于测试 oo.go(map.nextIndex[Math.floor(Math.random() * map.nextIndex.length)]); } function reversiBasedRLAIRun() { // 请求服务器获取基于 RL 的走法 var request = {}; var data = new Array(); for (var i = 0; i < 8; i++) { data.push(map.slice(i * 8, i * 8 + 8)); } request['mode'] = 'board'; request['data'] = JSON.stringify(data); request['color'] = map.side; // 发送数据 $.ajax({ type: "POST", url: 'http://localhost:9420', data: JSON.stringify(request), dataType: "json", async: true, timeout: 5000, success: function (data) { if (status == 0) { var result = data['response']; oo.go(result); console.log('Request data success, message = "' + data['message'] + '", result = ', result, ' (', Math.floor(result / 8), ',', result % 8, ')'); } else { console.log('Request data success, but status = 1'); } }, error: function (data) { alert('暂未开放AI服务,敬请期待……', data); } }) } function gameOver() {//终局的时候 setAIRunStatus(false);//不显示ai在计算 setPassStatus(false);//不显示pass alert("棋局结束\n\n黑棋: " + map.black + " 子\n白棋: " + map.white + " 子\n\n" + (map.black == map.white ? "平局!!!" : map.black > map.white ? "黑棋胜利!!!" : "白棋胜利!!!")); } oo.dire = (function () {//获取某一棋盘格某一方向的格子.超过边界返回64 var dr = [-8, -7, 1, 9, 8, 7, -1, -9]; var bk = [8, 0, 0, 0, 8, 7, 7, 7]; return function (i, d) { i += dr[d]; return (i & 64) != 0 || (i & 7) == bk[d] ? 64 : i; } })(); oo.findLocation = function (m) {//查找可走棋的位置 function is(i, j) { var lk = 0; while ((i = oo.dire(i, j)) != 64 && m[i] == -m.side) { ta[la++] = i; lk++; } if (i == 64 || m[i] != m.side) la -= lk; } m.nextIndex = []; m.next = []; for (var i = 0; i < 64; i++) { if (!m.frontier[i]) // 如果与已有棋子不相邻,则这一点一定不是解 continue; var ta = [], la = 0; for (var j = 0; j < 8; j++) is(i, j); if (la > 0) { if (la != ta.length) ta = ta.slice(0, la); m.next[i] = ta; // 存储棋子 i 所能转换的棋子 m.nextIndex.push(i); // 棋子 i 是可行走法 } } m.nextNum = m.nextIndex.length;//这个是为了pass使用 } oo.pass = function (m) {//一方无棋可走就pass m.side = -m.side;//下棋方 m.prevNum = m.nextNum;//历史记录次序往后一个 } oo.newMap = function (m, n) { //返回新的棋局 //m给入map,n给入下一步棋的位置 var nm = m.slice(0); nm[n] = m.side; nm.frontier = m.frontier.slice(0); //复制数组 nm.frontier[n] = false; for (var i = 0; i < 8; i++) { var k = oo.dire(n, i); if (k != 64 && nm[k] == 0) nm.frontier[k] = true; } var ne = m.next[n]; var l = ne.length; for (var i = 0; i < l; i++) { nm[ne[i]] = m.side; //反转的棋子 } //下面计算空格数、黑棋数、白棋数 if (m.side == 1) { nm.black = m.black + l + 1; nm.white = m.white - l; } else { nm.white = m.white + l + 1; nm.black = m.black - l; } nm.space = 64 - nm.black - nm.white; //空格数目 nm.side = -m.side; nm.prevNum = m.nextNum; return nm; } oo.goChess = function (n) {//走棋 history.push(map); oo.go(n); } oo.go = function (n) { //走棋,n 代表走棋的位置 aiRuning = false; var rev = map.next[n]; // rev 是走这一步翻转的棋子 map = oo.newMap(map, n); map.newRev = rev; map.newPos = n; update(); } oo.historyBack = function () {//悔棋功能 if (aiRuning || history.length == 0) return; clearTimeout(timer); map = history.pop(); update(); } function setAIRunStatus(t) {//设置AI运算状态 aiRuningObj.style.display = t ? "block" : "none"; } function setPassStatus(t) {//设置pass状态:无棋可下就pass passObj.style.display = t ? "block" : "none"; if (t) { passObj.innerHTML = map.side == 1 ? "白方无棋可下,黑方继续下子" : "黑方无棋可下,白方继续下子"; } } } /*main*/ var board = new Chessboard(); // 创建棋盘对象 var othe = new Othello(); // 创建逻辑控制对象 board.create(othe.goChess); // 棋盘创建,绑定下棋后的事件 document.getElementById("reversi_play").onclick = function () { // 开始 + 重新开始 document.getElementById("reversi_selectbox").style.display = "block"; }; document.getElementById("reversi_ok").onclick = function () { // 点击开始 -> 确定后 document.getElementById("reversi_selectbox").style.display = "none"; // 先隐藏选择框 var ro = document.getElementById("reversi_selectbox").getElementsByTagName("input"); // 获取选择的内容 if (ro[0].checked) { // 玩家先手 othe.aiSide = -1; } else if (ro[1].checked) { // 电脑先手 othe.aiSide = 1; } else if (ro[2].checked) { // 双人模式 othe.aiSide = 0; } else { // 观战模式 othe.aiSide = 2; } othe.play(); }; document.getElementById("reversi_cancel").onclick = function () {//取消 document.getElementById("reversi_selectbox").style.display = "none"; }; document.getElementById("reversi_back").onclick = function () {//悔棋 othe.historyBack(); }; document.getElementById("reversi_explain").onclick = function () {//最下面解释的弹窗控件 alert("\"王道之室中 不是普通的棋局\",\n" + "\"而是根据本门绝学精髓设计而成的墨攻棋阵\",\n" + "\"墨攻棋阵与围棋明显的不同就是\",\n" + "\"墨攻棋局中不会有任何棋子被杀死\",\n" + "\"当一方的棋子被另一方棋子前后围堵\",\n" + "\"那这些棋子就转化成另一方\",\n" + "\"当然 如果这些棋子又被围堵时\",\n" + "\"还可以再次转化\",\n" + "\"最后六十四格棋盘布满时就看双方谁的棋子数量多\",\n" + "\"哪一方就获胜\",\n" + "\"墨攻棋局 每一次落子必须要形成转换\",\n" + "\"如果对方没有可被转换的棋子时\",\n" + "\"这种情况 本方就只能放弃这一轮出手\",\n" + "\"能够把对手逼入这种困境 就叫作破阵 是最厉害的招数\","); }; document.getElementById("reversi_no3d").onclick = function () {//3D棋盘切换 var desk = document.getElementById("reversi_desk"); desk.className = desk.className == "reversi_fdd" ? "" : "reversi_fdd"; this.innerHTML = desk.className == "reversi_fdd" ? "2D" : "3D"; }; <|start_filename|>src/web/client/css/style.css<|end_filename|> body { background-image: url('../img/background.jpg'); font-family: "微软雅黑", "黑体", serif; margin: 0; padding: 0; } #reversi_desk { width: 750px; margin: 0px auto; } #reversi_console { float: left; width: 110px; padding: 10px 0px 0px 10px; } #reversi_desk h1 { margin: 10px 0px; color: black; font-size: 50px; line-height: 70px; font-weight: bold; text-shadow: 0px 0px 6px #A33D1B, 0px 7px 3px #754B35; } #reversi_desk h1 span { color: white; } #reversi_desk h3 { margin: 0px 20px; color: #330000; font-size: 25px; line-height: 30px; font-weight: bold; text-shadow: 0px 0px 4px #A33D1B, 0px 5px 2px #754B35; } #reversi_desk .button { margin: 15px 10px; font-size: 20px; width: 100px; line-height: 300%; box-shadow: 0px 4px 10px #482915; text-align: center; cursor: pointer; } #reversi_desk .button:hover { background: rgba(255, 255, 255, .6); box-shadow: 0px 6px 10px #482915; } #reversi_desk .button:active { background: rgba(255, 255, 255, .8); box-shadow: 0px 2px 5px #482915; position: relative; top: 2px; } #reversi_desk .cbox { border: 2px dotted transparent; border-radius: 10px; width: 100px; height: 56px; } #reversi_desk .side { border: 2px dotted #cc3333; } #reversi_desk .cbox span { float: right; font-size: 30px; line-height: 54px; font-weight: bold; color: #500; text-shadow: 0px 0px 3px #E8C488; padding-right: 7px; } #reversi_interface { position: relative; float: left; } #reversi_chessboard { margin: 15px 7px; -webkit-transform: perspective(740px) rotateX(0deg); transform: perspective(740px) rotateX(0deg); -webkit-transition: -webkit-transform 1s; transition: transform 1s; } #reversi_chessboard table { border-spacing: 2px; } #reversi_chessboard td { width: 70px; height: 70px; border: 1px solid black; } #reversi_chessboard td:hover { border: 1px dotted orange; background-color: rgba(255, 255, 255, .4); } #reversi_desk .black, .white { width: 10px; height: 10px; border-radius: 50%; margin: 0 auto; padding: 17px; box-shadow: 0px 0px 4px #482915; } .reversi_fdd #reversi_chessboard { -webkit-transform: perspective(800px) rotateX(35deg); transform: perspective(800px) rotateX(35deg); } .reversi_fdd td .black, .reversi_fdd td .white { margin: 0 auto; box-shadow: 0px 4px 4px #482915; } #reversi_desk .black { background: black; -webkit-transform: rotateY(0deg); transform: rotateY(0deg); } #reversi_desk .white { background: white; -webkit-transform: rotateY(180deg); transform: rotateY(180deg); } #reversi_desk .reversal { -webkit-transition: -webkit-transform 400ms ease-in-out, background 0ms 200ms; transition: transform 400ms ease-in-out, background 0ms 200ms; } #reversi_desk .newest:before, .reversal:before { content: ""; display: block; width: 10px; height: 10px; border-radius: 5px; } #reversi_desk .newest:before { background: #f00; } #reversi_desk .reversal:before { background: #66c; } #reversi_desk .prompt { width: 10px; height: 10px; border-radius: 100%; margin: 0 auto; padding: 0px; border: 1px solid #c32c1c; } #reversi_selectbox { position: absolute; top: 50px; left: 50%; margin-left: -200px; background: #ffffff; border: 3px solid #ffeee4; box-shadow: 0px 5px 15px #482915; padding: 10px 25px; color: #472E25; font-size: 20px; font-size: 22px; line-height: 1.5em; text-align: center; display: none; } #reversi_selectbox input:checked+span { color: #990000; text-shadow: 0px 0px 3px #FF9900; } #reversi_buttons { margin: 0 45px; } #reversi_buttons div { float: left; margin: 0px 10px; } #reversi_pass, #reversi_airuning { position: initial; margin: 0 auto; top: 12px; left: 50%; width: 300px; height: auto; border-radius: 13px; text-align: center; font-size: 18px; line-height: 26px; background: rgba(255, 255, 255, 0.6); color: #330000; text-shadow: 0px 0px 1px #900; display: none; } #reversi_airuning { width: 200px; } @media screen and (max-width: 750px) { #reversi_desk { width: 540px; } #title { width: 100%; padding: 0px; text-align: center; } #reversi_console { width: 96%; padding: 10px 2%; } #reversi_desk h1, h3 { display: inline-block; } #reversi_desk .cbox { float: left; } #reversi_console .button { float: left; margin: 0px 5px; width: 90px; } #reversi_no3d { display: none; } }
im0qianqian/Reversi-based-RL
<|start_filename|>Pods/JWPlayer-SDK/JWPlayer_iOS_SDK.framework/Headers/JWGoogimaDaiConfig.h<|end_filename|> // // JWGoogimaDaiConfig.h // JWPlayer-iOS-SDK // // Created by <NAME> on 1/26/20. // Copyright © 2020 JWPlayer. All rights reserved. // #import <Foundation/Foundation.h> NS_ASSUME_NONNULL_BEGIN /** Configuration settings for Google IMA DAI. */ @interface JWGoogimaDaiConfig : NSObject /** The stream request API key. This is used to verify applications attempting to access their content. */ @property (nonatomic, nullable, copy) NSString *apiKey; /** The video identifier for this stream. @note Used for VOD. */ @property (nonatomic, nullable, copy, readonly) NSString *videoID; /** The content source ID for this stream. @note Used for VOD. */ @property (nonatomic, nullable, copy, readonly) NSString *cmsID; /** The stream assetKey @note Used for live streams. */ @property (nonatomic, nullable, copy, readonly) NSString *assetKey; /** Initialize for VOD. */ - (instancetype)initWithVideoID:(NSString *)videoID cmsID:(NSString *)cmsID; /** Initialize for live stream. */ - (instancetype)initWithAssetKey:(NSString *)assetKey; @end NS_ASSUME_NONNULL_END <|start_filename|>Pods/JWPlayer-SDK/JWPlayer_iOS_SDK.framework/Headers/JWPlayerController.h<|end_filename|> // // JWPlayerViewController.h // JWPlayer-iOS-SDK // // Created by <NAME> on 8/14/14. // Copyright (c) 2014 JWPlayer. All rights reserved. // #import <UIKit/UIKit.h> #import "JWConfig.h" #import "JWPlayerDelegate.h" #import "JWAVPlayerAnalyticsDelegate.h" #import "JWCastController.h" #import "JWDrmDataSource.h" #import "JWExperimentalAPI.h" #import "JWFriendlyAdObstructions.h" #import "JWButton.h" #define JWPlayerAllNotification @"JWPlayerAllNotification" #define JWMetaDataAvailableNotification @"JWMetaDataAvailableNotification" #define JWPlayerStateChangedNotification @"JWPlayerStateChangedNotification" #define JWPlaybackPositionChangedNotification @"JWPlaybackPositionChangedNotification" #define JWFullScreenStateChangedNotification @"JWFullScreenStateChangedNotification" #define JWAdActivityNotification @"JWAdActivityNotification" #define JWAdPlaybackProgressNotification @"JWAdPlaybackProgressNotification" #define JWAdClickNotification @"JWAdClickNotification" #define JWErrorNotification @"JWErrorNotification" #define JWWarningNotification @"JWWarningNotification" #define JWCaptionsNotification @"JWCaptionsNotification" #define JWVideoQualityNotification @"JWVideoQualityNotification" #define JWPlaylistNotification @"JWPlaylistNotification" #define JWAudioTrackNotification @"JWAudioTrackNotification" #define JWRelatedActivityNotification @"JWRelatedActivityNotification" NS_ASSUME_NONNULL_BEGIN /** A class that encapsulates JW Player and provides control over the playback as well as holds the state of the player and notifies about status updates. */ @interface JWPlayerController : NSObject /* ========================================*/ /** @name Accessing Player Controller Attributes */ /** Player view. @note to be added to the application view hierarchy. */ @property (nonatomic, nullable, retain, readonly) UIView *view; /** The object that acts as the delegate of the jwPlayerController. @note The delegate must adopt the JWPlayerDelegate protocol. The delegate is not retained. @see JWPlayerDelegate */ @property (nonatomic, nullable, weak) id<JWPlayerDelegate> delegate; /** The object that acts as the analyticsDelegate of the JWPlayerController. Data provided by this object can be used by 3rd-party analytics libraries. @note The analyticsDelegate must adopt the JWAVPlayerAnalyticsDelegate protocol. The analyticsDelegate is not retained. @see JWAVPlayerAnalyticsDelegate */ @property (nonatomic, nullable, weak) id<JWAVPlayerAnalyticsDelegate> analyticsDelegate; /** The JWDrmDataSource is adopted by an object that mediates the application's data model and key server. The data source provides the JWPlayerController object with the data needed to reproduce encrypted content. @note The drmDataSource must adopt the JWDrmDataSource protocol. The drmDataSource is not retained. @see JWDrmDataSource */ @property (nonatomic, nullable, weak) id<JWDrmDataSource> drmDataSource; /** An interface for exposing experimental features. @note These features are very likely to be deprecated in the future, and will either be entirely dropped or replaced. */ @property (nonatomic, readonly) JWExperimentalAPI *experimentalAPI DEPRECATED_MSG_ATTRIBUTE("Use JWFriendlyAdObstructions class instead."); /** Returns the version of google IMA framework compatible with the JWPlayer SDK. */ @property (nonatomic, copy, readonly) NSString *googleIMAVersion; /** Returns the version of google ChromeCast framework compatible with the JWPlayer SDK. */ @property (nonatomic, copy, readonly) NSString *googleChromeCastVersion; /** Returns current state of the player. @note Can be idle, playing, paused and buffering, error, complete. */ @property (nonatomic, readonly) JWPlayerState state; /** Metadata associated with the current video. Usually includes dimensions and duration of the video. @note becomes available shortly after the video starts playing. There is a notification JWMetaDataAvailableNotification posted right after metadata is available. */ @property (nonatomic, nullable, retain, readonly) NSDictionary *metadata; /** Dimensions of the current video. Becomes available shortly after the video starts to play as a part of metadata. */ @property (nonatomic, readonly) CGSize naturalSize; /** JWConfig object that was used to setup the player. @note Check JWConfig documentation for more info. */ @property (nonatomic, retain, readonly) JWConfig *config; /** Returns the current PlaylistItem's filled buffer, as a percentage (0 to 100) of the total video's length. @note This only applies to progressive downloads of media (MP4/FLV/WebM and AAC/MP3/Vorbis); streaming media (HLS/RTMP/YouTube/DASH) do not expose this behavior. */ @property (nonatomic, readonly) NSUInteger buffer; /** Enable the built-in controls by setting them true, disable the controls by setting them false. */ @property (nonatomic) BOOL controls; /** When enabled, the user will be able to control playback of the current video (play, pause, and when applicable next/previous) from the device's Lock Screen and some information (title, playback position, duration, poster image) will be presented on the lockscreen. Defaults to YES. @note In order for the lock screen controls to appear, background audio must be enabled and the audio session must be set to AVAudioSessionCategoryPlayback. */ @property (nonatomic) BOOL displayLockScreenControls; /** Returns the region of the display not used by the controls. You can use this information to ensure your visual assets don't overlap with the controls. */ @property (nonatomic, readonly) CGRect safeRegion; /* ========================================*/ /** @name Managing Video Quality Levels */ /** The index of the object in quality levels list currently used by the player. */ @property (nonatomic) NSUInteger currentQuality; /** List of quality levels available for the current media. */ @property (nonatomic, retain, readonly) NSArray *qualityLevels; /* ========================================*/ /** @name Managing Closed Captions */ /** The index of the caption object in captions list currently used by the player. @note index 0 stands for no caption. @see captionsList */ @property (nonatomic) NSUInteger currentCaptions; /** List of all the captions supplied in the config @note Use currentCaptions to activate one of the captions programmatically. Object at index 0 is "off". @see currentCaptions */ @property (nonatomic, retain, readonly) NSArray <JWTrack *> *captionsList; /* ========================================*/ /** @name Managing Audio Tracks */ /** The index of the currently active audio track. */ @property (nonatomic) NSUInteger currentAudioTrack; /** Array with audio tracks from the player. */ @property (nonatomic, retain, readonly) NSArray *audioTracks; /* ========================================*/ /** @name Managing Playlists */ /** The index of the currently active item in the playlist. */ @property (nonatomic) NSInteger playlistIndex; /** Returns the playlist item at a specific index. */ - (JWPlaylistItem *)getPlaylistItem:(NSInteger)index; /** Returns the playlist. */ - (NSArray <JWPlaylistItem *> *)getPlaylist; /* ========================================*/ /** @name Initializing Player Controller Object */ /** Inits the player with config object in JWConfig format. @param config JWConfig object that is used to setup the player. */ - (nullable instancetype)initWithConfig:(JWConfig *)config; /** Inits the player with config object in JWConfig format and sets the object that acts as the delegate of the JWPlayerController. @param config JWConfig object that is used to setup the player. @param delegate The object that acts as the delegate of the jwPlayerController. @see JWPlayerDelegate */ - (nullable instancetype)initWithConfig:(JWConfig *)config delegate:(nullable id<JWPlayerDelegate>)delegate; /** Inits the player with a JWConfig object and sets the object that acts as a DRM data source, as well as the delegate of the JWPlayerController. @param config JWConfig object that is used to setup the player. @param delegate The object that acts as the delegate of the jwPlayerController. @param drmDataSource The object that acts as a data source for reproducing drm encrypted content. @see JWPlayerDelegate, JWDrmDataSource */ - (nullable instancetype)initWithConfig:(JWConfig *)config delegate:(nullable id<JWPlayerDelegate>)delegate drmDataSource:(nullable id<JWDrmDataSource>)drmDataSource NS_DESIGNATED_INITIALIZER; - (instancetype)init NS_UNAVAILABLE; /* ========================================*/ /** @name Managing Playback */ /** Starts to play video from current position. @note If there is a paused ad, this method will resume the ad playback. */ - (void)play; /** Pauses video. @note If there is an ad playing, this method will pause the ad playback. */ - (void)pause; /** Stops the player (returning it to the idle state) and unloads the currently playing media file. */ - (void)stop; /** Tells the player to immediately play the next playlist item. */ - (void)next; /** @param position Time in the video to seek to @see duration */ - (void)seek:(NSInteger)position; /** Playback position of the current video. @note gets updated as the video plays. JWPlaybackProgressNotification is posted every time position changes. KVO compliant. */ @property (nonatomic, readonly) CGFloat position; /** Duration of the current video. Becomes available shortly after the video starts to play as a part of metadata. */ @property (nonatomic, readonly) CGFloat duration; /** The volume of the JWPlayerController's audio. At 0.0 the player is muted, at 1.0 the player's volume is as loud as the device's volume. @note This property should be used to control the volume of the player (including Google IMA ads) relative to other audio output, not for volume control by viewers. This property will have no effect when casting. Viewers can control volume when casting by changing the device's volume. */ @property (nonatomic) CGFloat volume; /** The rate at which media is being reproduced. @note Setting this property to 1.0 will play the media at its natural rate. Ability to set a different value is limited to the rates supported by the media item; if an unsupported rate is requested, playbackRate will not change. Rates between 0.0 and 1.0 will slow forward, rates greater than 1.0 will fast forward, rates between 0.0 and -1.0 will slow reverse, and rates lower than -1.0 will fast reverse. This property will have no effect when ads are being played, or when casting. Cannot be set to 0; to pause playback, please call the pause method. */ @property (nonatomic) CGFloat playbackRate; /* ========================================*/ /** @name Managing Full Screen */ /** The setter toggles the player's fullscreen mode; the getter returns a boolean value that determines whether the video is in full screen. @warning *Note:* If your app uses fullscreen mode, and will run on iPads running iOS 11 or higher, select *Requires full screen* in the *General* tab of your target's settings to avoid unwanted triggering of [Split View](https://developer.apple.com/design/human-interface-guidelines/ios/views/split-views/) mode. */ @property (nonatomic) BOOL fullscreen; /** A Boolean value that determines whether the video should go to full screen mode when the device rotates to landscape. @note Make sure your app supports landscape to make this property work. */ @property (nonatomic) BOOL forceFullScreenOnLandscape; /** A Boolean value that determines whether the video should rotate to landscape when the fullscreen button is pressed. @note Make sure your app supports landscape to make this property work. */ @property (nonatomic) BOOL forceLandscapeOnFullScreen; /* ========================================*/ /** @name Custom Buttons */ /** Adds a custom button to the player's control bar. @note Buttons are added to the righthand-side grouping of icons in the control bar. Buttons are added all the way to the left of the grouping, except if there is a logo in the control bar. In this case, buttons will be added to the right of the logo. Multiple buttons are added from right to left in the order they are entered. @see JWButton */ - (void)addButton:(JWButton *)button; /** Removes a custom button from the control bar. @see JWButton */ - (void)removeButton:(JWButton *)button; /* ========================================*/ /** @name Loading New Media */ /** Loads a new playlist into the player. @param playlist An array containing playlist items. */ - (void)load:(NSArray <JWPlaylistItem *> *)playlist; /** Loads a new playlist feed into the player. @param feedUrl A URL referencing the location of an RSS/XML/JSON file */ - (void)loadFeed:(NSString *)feedUrl; /* ========================================*/ /** @name Injecting Ads */ /** Immediately starts to play an ad using the vast plugin. @param tag Xml file with info about the ad. @note Usually used to inject an ad in streams where you can't schedule an ad. If you wish to play the ad with the Google IMA Client, please use playAd:onClient: instead and specify JWAdClientGoogima as your ad client. */ - (void)playAd:(NSString *)tag; /** Immediately starts to play an ad. @param tag Xml file with info about the ad. @param adClient Set to JWAdClientGoogima if you wish to use google IMA; set to JWAdClientVast if not. Setting to nil defaults to vast. Note: Due to the fact that Google IMA's iOS SDK is still in Beta mode, we suggest using the vast plugin. @note Usually used to inject an ad in streams where you can't schedule an ad. @see JWAdClient */ - (void)playAd:(NSString *)tag onClient:(JWAdClient)adClient; /** Used to pause or resume ad playback. @param state Indicates whether or not the ad playback should be paused. @note If the state is YES, ad playback will be paused. */ - (void)pauseAd:(BOOL)state; /** If set to YES will open Safari after the user clicks the ad. */ @property (nonatomic) BOOL openSafariOnAdClick; /* ========================================*/ /** @name Related */ /** Opens the related overlay. This will pause content if it is currently playing. */ - (void)openRelatedOverlay; /** Closes the related plugin overlay. This will resume content. */ - (void)closeRelatedOverlay; /* ========================================*/ /** @name Accessing SDK Info */ /** Version of underlying web player */ @property (nonatomic, copy, readonly) NSString *playerVersion; /** Player edition based on the provided JW License key */ @property (nonatomic, copy, readonly) NSString *playerEdition; /** Version of the iOS SDK */ + (NSString *)SDKVersion; /** Version of the iOS SDK, truncated. (i.e.: if SDKVersion returns 1.001, SDKVersionToMinor returns 1.). */ + (NSString *)SDKVersionToMinor; /** Sets the Player Key programmatically instead of having to type it into the application's info.plist. We recommend setting the key in the AppDelegate's application:didFinishLaunchingWithOptions: method. @note If a different key is entered in the info.plist, the key set with this method will supersede. Use this method before instantiating the JWPlayerController, ideally in the AppDelegate's application:didFinishLaunchingWithOptions: method. */ + (void)setPlayerKey:(NSString *)key; @end NS_ASSUME_NONNULL_END <|start_filename|>Pods/JWPlayer-SDK/JWPlayer_iOS_SDK.framework/Headers/JWPlaylistItem.h<|end_filename|> // // JWPlaylistItem.h // JWPlayer-iOS-SDK // // Created by <NAME> on 12/8/14. // Copyright (c) 2014 JWPlayer. All rights reserved. // #import <Foundation/Foundation.h> @class JWConfig; @class JWSource; @class JWAdBreak; @class JWTrack; @class JWGoogimaDaiConfig; @class JWFreewheelConfig; NS_ASSUME_NONNULL_BEGIN /** An object providing info about playlist items. */ @interface JWPlaylistItem : NSObject /* ========================================*/ /** @name Accessing Playlist Item Attributes */ /** An array of JWSource objects representing multiple quality levels of a video. @see JWSource */ @property (nonatomic, nullable, retain) NSArray <JWSource *> *sources; /** Video URL to a single video file, to be played using JW Player. */ @property (nonatomic, nullable, copy) NSString *file; /** URL to a poster image. The image is displayed before and after playback, and in the listbar. For audio-only media, the poster image stays visible during playback. */ @property (nonatomic, nullable, copy) NSString *image; /** Title of the video. @note Shown in the listbar and in the play button container in the center of the screen before the video starts to play. */ @property (nonatomic, nullable, copy) NSString *title; /** A dictionary containing asset initialization options. */ @property (nonatomic, nullable) NSDictionary *assetOptions; /** An array of JWAdBreak objects that proivide info about ad breaks. @see JWAdBreak */ @property (nonatomic, nullable, retain) NSArray <JWAdBreak *> *adSchedule; /** The JWGoogimaDaiConfig class stores the Google IMA DAI settings. */ @property (nonatomic, nullable) JWGoogimaDaiConfig *googimaDaiSettings; /** The JWFreewheelConfig class stores the Freewheel SDK settings. The settings defined here will apply only to ads associated with this playlist item. @note When setting a Freewheel config, config.advertising.adClient should be set to JWAdClientFreewheel, where config is an instance of JWConfig. @note if nil, fallsback to config.advertising.freewheel. @note Properties that are nil will fallback to the equivalent in config.advertising.freewheel. You may therefore use config.advertising.freewheel to define common settings. */ @property (nonatomic, nullable) JWFreewheelConfig *freewheel; /** An array of JWTrack objects providing captions for different languages. @see JWTrack */ @property (nonatomic, nullable, retain) NSArray <JWTrack *> *tracks; /** Short description of the item. It is displayed in the listbar. */ @property (nonatomic, nullable, copy) NSString *desc; /** The playlist item's Media ID. */ @property (nonatomic, nullable, copy) NSString *mediaId; /** URL to a feed that contains related items for a particular playlist item. */ @property (nonatomic, nullable, copy) NSString *recommendations; /** Number of seconds from the start of a media asset when playback should begin. */ @property (nonatomic, assign) CGFloat startTime; /* ========================================*/ /** @name Creating Playlist Item Object */ /** Inits a JWPlaylistItem object with provided JWConfig. @param config configuration object. */ + (instancetype)playlistItemWithConfig:(JWConfig *)config; @end NS_ASSUME_NONNULL_END <|start_filename|>Pods/JWPlayer-SDK/JWPlayer_iOS_SDK.framework/Headers/JWAdEvent.h<|end_filename|> // // JWAdEvent.h // JWPlayer-iOS-SDK // // Created by karim on 5/16/18. // Copyright © 2018 JWPlayer. All rights reserved. // #import <Foundation/Foundation.h> #import "JWEvent.h" #import "JWAdConfig.h" #import "JWAdBreak.h" NS_ASSUME_NONNULL_BEGIN /** Base class for various ad event classes. Exposes specific information based on the derived class. */ @interface JWAdEvent : NSObject /** The ad tag that for which the event was fired. */ @property (nonatomic, copy) NSString *tag; @end /** Exposes additional details commonly found in ad events, and is a base class for other ad events. */ @protocol JWAdDetailEvent <NSObject> /** The type of ad that is being played. */ @property (nonatomic, copy) NSString *creativeType; /** The client that is currently being used, vast, googima or freewheel. */ @property (nonatomic) JWAdClient client; @end /** JWAdBreakEvent provides information for an ad break. */ @protocol JWAdBreakEvent <NSObject> /** The client that is currently being used, vast, googima or freewheel. */ @property (nonatomic) JWAdClient client; /** Whether an ad break is in a pre, mid, or post position. */ @property (nonatomic, copy) NSString *adPosition; @end /** JWAdRequestEvent provides information for a requested ad. */ @protocol JWAdRequestEvent <JWAdDetailEvent> /** Whether an ad is in a pre, mid, or post position. */ @property (nonatomic, copy) NSString *adPosition; /** An ad's position. Will return a number (in seconds) of a midroll's position */ @property (nonatomic, copy) NSString *offset; @end /** JWAdCompanionsEvent provides ad companion information for an ad. */ @protocol JWAdCompanionsEvent <NSObject> /** An array with available companion information. */ @property (nonatomic) NSArray <JWAdCompanion *> *companions; @end /** JWAdScheduleEvent provides scheduling information specific to the loaded VMAP tag. */ @protocol JWAdScheduleEvent <NSObject> /** An array containing the adBreaks of the VMAP schedule. */ @property (nonatomic) NSArray <JWAdBreak *> *adBreaks; /** The client that is currently being used, vast, googima or freewheel. */ @property (nonatomic) JWAdClient client; @end /** JWAdImpressionEvent provides ad impression information of an ad. */ @protocol JWAdImpressionEvent <JWAdDetailEvent> /** An ad's position (pre, mid, post). */ @property (nonatomic, copy) NSString *adPosition; /** AdSystem referenced inside of the VAST XML. */ @property (nonatomic, nullable, copy) NSString *adSystem; /** AdTitle referenced inside of the VAST XML. */ @property (nonatomic, nullable, copy) NSString *adTitle; /** GoogleIMA and Freewheel-only: AdId referenced inside of the VAST XML. @note Google IMA and Freewheel only. Not yet supported in VAST. */ @property (nonatomic, nullable, copy) NSString *adId; /** GoogleIMA only: creativeId referenced inside of the VAST XML. @note Google IMA only */ @property (nonatomic, nullable, copy) NSString *creativeAdId; /** GoogleIMA only: creativeId referenced inside of the VAST XML. @note Google IMA only */ @property (nonatomic, nullable, copy) NSString *creativeId; /** VAST-only: An array of the AdSystems specified in any utilized ad wrappers; index denotes level of wrapper. */ @property (nonatomic, nullable) NSArray *wrapper; /** The URL which will be opened if the ad is clicked. */ @property (nonatomic, copy) NSString *clickThroughUrl; /** The currently playing media item. */ @property (nonatomic, copy) NSString *mediaFile; /** VAST-only: The version of VAST referenced in the VAST XML. */ @property (nonatomic) CGFloat vastVersion; /** Wether the ad is linear or nonlinear. */ @property (nonatomic) JWAdType linear; /** Details of the VMAP schedule's adBreak that is currently playing. Available only for VMAP schedules on Vast. */ @property (nonatomic, nullable) NSDictionary *vmapInfo; @end /** JWAdStateChangeEvent describes the state change of the player. */ @protocol JWAdStateChangeEvent <JWAdDetailEvent, JWStateChangeEvent> /** The new state of the player. */ @property (nonatomic) JWPlayerState newState; @end /** JWAdTimeEvent denotes the sequence of the current ad. */ @protocol JWAdTimeEvent <JWAdDetailEvent, JWTimeEvent> /** Returns the sequence number the ad is a part of. */ @property (nonatomic) NSUInteger sequence; @end NS_ASSUME_NONNULL_END <|start_filename|>Pods/JWPlayer-SDK/JWPlayer_iOS_SDK.framework/Headers/JWAdConfig.h<|end_filename|> // // JWAdConfig.h // JWPlayer-iOS-SDK // // Created by <NAME> on 10/3/14. // Copyright (c) 2014 JWPlayer. All rights reserved. // #import <Foundation/Foundation.h> #import "JWAdRules.h" /** Type of ad provider to be used. */ typedef NS_ENUM(NSInteger, JWAdClient) { /// VAST ad provider JWAdClientVast = 0, /// Google IMA provider JWAdClientGoogima, /// Google IMA DAI provider JWAdClientGoogimaDAI, /// Freewheel ad provider JWAdClientFreewheel }; NS_ASSUME_NONNULL_BEGIN @class JWAdBreak, IMASettings, JWGoogimaDaiConfig, JWFreewheelConfig; /** An object providing information about the way ads are handled by the player. Describes adMessage, skipMessage, skipText and skipOffset. @note In the current implementation, an adConfig object can be added to config and propagates to all adBreaks. */ @interface JWAdConfig : NSObject /* ========================================*/ /** @name Accessing Ad Config Attributes */ /** The URL of the VAST tag to display, or the custom string of the Freewheel tag to display. @note can also specify Vast vmap file to use for ad breaks. @note ignore if schedule is set. */ @property (nonatomic, nullable, retain) NSString *tag; /** A message to be shown to the user in place of a seekbar while the ad is playing. @note 'xx' in the message is replaced with countdown timer until the end of the ad. */ @property (nonatomic, nullable, retain) NSString *adMessage; /** A message to be shown on the skip button during countdown to skip availablilty. @note 'xx' in the message is replaced with countdown timer until the moment skip becomes available. @see skipText */ @property (nonatomic, nullable, retain) NSString *skipMessage; /** A message to be shown on the skip button when the skip option becomes available. */ @property (nonatomic, nullable, retain) NSString *skipText; /** An integer representing the number of seconds before the ad can be skipped. */ @property (nonatomic) NSUInteger skipOffset; /** An array of JWAdBreak objects that proivides info about ad breaks. @note tag property is ignored if this property is not nil. @see JWAdBreak */ @property (nonatomic, nullable, retain) NSArray <JWAdBreak *> *schedule; /** Vast vmap file to use for ad breaks. @note schedule is ignored if this property is not nil. */ @property (nonatomic, nullable, retain) NSString *adVmap; /** Set to JWAdClientGoogima if you wish to use google IMA; set to JWAdClientVast if not. Setting to nil defaults to vast. @note Due to the fact that Google IMA's iOS SDK is still in Beta mode, we suggest using the vast plugin. */ @property (nonatomic) JWAdClient client; /** The IMASettings class stores the Google IMA SDK settings. @note When setting a custom imaSetting, the default value of enableBackgroundPlayback is NO. */ @property (nonatomic, nullable) IMASettings *googimaSettings; /** The JWGoogimaDaiConfig class stores the Google IMA DAI settings. */ @property (nonatomic, nullable) JWGoogimaDaiConfig *googimaDaiSettings; /** The JWFreewheelConfig class stores the Freewheel SDK settings. @note When setting Freewheel settings, the value of adClient should be set to JWAdClientFreewheel. */ @property (nonatomic, nullable) JWFreewheelConfig *freewheel; /** For forcing controls to show for VPAID ads. Default is false. @note If the VPAID creative has built-in controls, showing the controls may be redundant. */ @property (nonatomic) BOOL vpaidControls; /** Use to control the frequency of ad playback. @note Available only for the VAST adClient. */ @property (nonatomic, nullable, retain) JWAdRules *rules; @end NS_ASSUME_NONNULL_END <|start_filename|>Pods/JWPlayer-SDK/JWPlayer_iOS_SDK.framework/Headers/JWEvent.h<|end_filename|> // // JWEvent.h // JWPlayer-iOS-SDK // // Created by karim on 5/14/18. // Copyright © 2018 JWPlayer. All rights reserved. // #import <Foundation/Foundation.h> #import <CoreGraphics/CoreGraphics.h> /** Type of player state. */ typedef NS_ENUM(NSInteger, JWPlayerState) { /// Player is currently playing JWPlayerStatePlaying = 0, /// Player is currently paused JWPlayerStatePaused, /// Player is currently buffering JWPlayerStateBuffering, /// Player is currently idle JWPlayerStateIdle, /// Player has completed playback of content JWPlayerStateComplete, /// Player has encountered an unrecoverable error JWPlayerStateError }; /** Reason why player was paused */ typedef NS_ENUM(NSInteger, JWPlayerPauseReason) { /// Player is paused due to external api call JWPlayerPauseReasonExternal = 0, /// Player is paused due to user interaction JWPlayerPauseReasonInteraction, /// Player is paused due to a clickthrough JWPlayerPauseReasonClickthrough }; @class JWTrack, JWSource, JWPlaylistItem, JWPlayerError, JWAdCompanion; NS_ASSUME_NONNULL_BEGIN /** JWEvent is the base class for all events emitted by the player. */ @interface JWEvent : NSObject @end /** JWFirstFrameEvent is emitted after the first frame of the video is displayed. */ @protocol JWFirstFrameEvent <NSObject> /** The amount of time (In milliseconds) it takes for the player to transition from a play attempt to a firstFrame event. */ @property (nonatomic) NSUInteger loadTime; @end /** JWStateChangeEvent contains the state information before the state is changed. This is a base class for other events. */ @protocol JWStateChangeEvent <NSObject> /** The old state of the player. */ @property (nonatomic) JWPlayerState oldState; @end /** JWPauseEvent is emitted when the video is paused. */ @protocol JWPauseEvent <NSObject> /** Reason video playback has been paused */ @property (nonatomic) JWPlayerPauseReason pauseReason; @end /** JWBufferEvent is emitted when the video is buffering. */ @protocol JWBufferEvent <JWStateChangeEvent> /** The new state of the player. */ @property (nonatomic) JWPlayerState newState; /** The reason why a buffer event occurred. */ @property (nonatomic, copy) NSString *reason; @end /** JWReadyEvent is emitted when the player is ready to play. */ @protocol JWReadyEvent <NSObject> /** The amount of time (in milliseconds) for the player to go from setup to ready. */ @property (nonatomic) NSUInteger setupTime; @end /** JWTimeEvent is emitted perdiodically when the video is playing. */ @protocol JWTimeEvent <NSObject> /** Playback position in seconds. */ @property (nonatomic) CGFloat position; /** Duration of the current playlist item in seconds. */ @property (nonatomic) CGFloat duration; @end /** JWBufferChangeEvent is emitted periodically with a buffer percentage update. */ @protocol JWBufferChangeEvent <JWTimeEvent> /** Percentage between 0 and 100 of the current media that is buffered. */ @property (nonatomic) CGFloat bufferPercent; @end /** JWSeekEvent is emitted when a seek operation is requested. */ @protocol JWSeekEvent <NSObject> /** The user requested position to seek to (in seconds). Note the actual position the player will eventually seek to may differ. */ @property (nonatomic) CGFloat offset; /** The position of the player before the player seeks (in seconds). */ @property (nonatomic) CGFloat position; @end /** JWMetaEvent is emitted when metadata is retrieved from the current playlist item. */ @protocol JWMetaEvent <NSObject> /** An object containing the new metadata. This can be metadata hidden in the media or metadata broadcasted by the playback provider. The different types of metadata include: Date range metadata: Fired when playback enters the section of an HLS stream tagged with #EXT-X-DATERANGE. Its payload includes: metadata: Object containing all of the information relevant to the HLS #EXT-X-DATERANGE tag. attributes: (Array) EXT-X-DATERANGE attribute array. content: (String) Content following the HLS tag. duration: (Number) Duration of the EXT-X-DATERANGE. start: (Number) Start time of the cue in seconds, relative to currentTime of the stream. end: (Number) End time of the cue in seconds, relative to currentTime of the stream. startDate: (String) EXT-X-DATERANGE start date in UTC. endDate: (String) EXT-X-DATERANGE end date in UTC. tag: (String) Name of the HLS manifest tag. This is always EXT-X-DATERANGE for this event. metadataTime: (Number) Start time of the cue in seconds, relative to currentTime of the stream (same as 'start'). metadataType: (String) Subcategory of meta event. This is always 'date-range' for this event subcategory. type: (String) Category of player event. Either 'meta' or 'metadataCueParsed'. Program-date-time metadata. Fires when playback enters the section of an HLS stream tagged with #EXT-X-PROGRAM-DATE-TIME. Its payload includes: metadata: Object containing all of the information relevant to the HLS #EXT-X-PROGRAM-DATE-TIME tag. start: (Number) Start time of the cue in seconds, relative to currentTime of the stream. end: (Number) End time of the cue in seconds, relative to currentTime of the stream. programDateTime: (String) Date and time of the program metadata in UTC. metadataTime: (Number) Start time of the cue in seconds, relative to currentTime of the stream (same as 'start'). programDateTime: (String) Date and time of the program metadata in UTC. metadataType: (String) Subcategory of meta event. This is always 'program-date-time' for this event subcategory. type: (String) Category of player event. Either 'meta' or 'metadataCueParsed'. ID3 metadata. Fires when playback buffers a section of an HLS stream containing ID3 tags. Its payload includes: ID3: Object containing all the properties associated with an AVMetadataItem. The AVMetadataItem's properties are only included if they're not empty. Media metadata. Fires when the initial metadata of a video has loaded. Its payload includes: duration: (Number) Length of the media asset. height: (Number) Height dimension of the media asset. width: (Number) Width dimension of the media asset. frameRate: (Number) The number of frames per second for tracks that carry a full frame per media sample. seekRange: Object containing the time range representing how much video is available to buffer in live stream or for seeking in DVR. start: (Number) Start time of the time range in seconds, relative to currentTime of the stream. end: (Number) End time of the time range in seconds, relative to currentTime of the stream. Access log metadata. Fires when a new access log entry has been added for the player item. Its payload includes: observedBitrate: (Number) The empirical throughput across all media downloaded. Measured in bits per second. Value is negative if unknown. indicatedBitrate: (Number) The throughput required to play the stream, as advertised by the server. Measured in bits per second. Value is negative if unknown. droppedFrames: (Number) Number of dropped video frames. Value is negative if unknown. */ @property (nonatomic) NSDictionary *metadata; @end /** JWTrackChangeEvent is emitted when a new caption track is selected. */ @protocol JWTrackChangedEvent <NSObject> /** Index of the new active track. In the case of captions, currentTrack of 0 means captions are turned off. */ @property (nonatomic) NSUInteger currentTrack; @end /** JWCaptionsListEvent is emitted when a list of captions tracks are retrieved. */ @protocol JWCaptionsListEvent <NSObject> /** The full array of caption tracks. */ @property (nonatomic) NSArray <JWTrack *> *tracks; @end /** JWLevelsEvent is emitted when the qualify levels or audio tracks information are available. */ @protocol JWLevelsEvent <NSObject> /** The full array of quality levels in the case of onLevels. The full array of audio tracks in the case of onAudioTracks. Returns nil in the case of an HLS stream. */ @property (nonatomic) NSArray *levels; @end /** JWLevelsChangedEvent is emitted when the quality level is changed. */ @protocol JWLevelsChangedEvent <NSObject> /** Index of the new quality level in the player's qualityLevels array. */ @property (nonatomic) NSUInteger currentQuality; @end /** JWPlaylistEvent is emitted when a new playlist is loaded. */ @protocol JWPlaylistEvent <NSObject> /** The new playlist, an array of playlist items. */ @property (nonatomic) NSArray <JWPlaylistItem *> *playlist; @end /** JWPlaylistItemEvent is emitted when a new playlist item is started. */ @protocol JWPlaylistItemEvent <NSObject> /** The current playlist item. */ @property (nonatomic) JWPlaylistItem *item; /** Zero-based index into the playlist array (e.g. 0 is the first item). */ @property (nonatomic) NSUInteger index; @end /** JWFullScreenEvent is emitted when a transition occurs to and fro fullscreen. */ @protocol JWFullscreenEvent <NSObject> /** Whether or not video is in fullscreen mode. */ @property (nonatomic) BOOL fullscreen; @end /** JWRezieEvent is emitted when a resize of the player occurs. */ @protocol JWResizeEvent <NSObject> /** The new dimensions of the player. */ @property (nonatomic) CGSize size; @end /** JWControlEvent is emitted when the player controls are enabled or disabled. */ @protocol JWControlsEvent <NSObject> /** New state of the controls. */ @property (nonatomic) BOOL controls; @end /** JWPlaybackRateEvent is emitted when the playback rate of the player changes. */ @protocol JWPlaybackRateEvent <NSObject> /** New playback rate of the video. */ @property (nonatomic) CGFloat playbackRate; @end /** JWViewabilityEvent is emitted when the viewability status of the player changes */ @protocol JWViewabilityEvent <NSObject> /** Whether the player is viewable or not */ @property (nonatomic) BOOL viewable; @end /** JWErrorEvent is emitted when there is an unrecoverable error from the player. */ @protocol JWErrorEvent <NSObject> /** Object containing the error message under property localizedDescription. For onAdError, The following error messages are possible: -invalid ad tag (e.g. invalid XML, broken VAST) -ad tag empty (e.g. no ad available after chasing the wrappers) -no compatible creatives (e.g. only FLV video in HTML5) -error playing creative (e.g. a 404 on the MP4 video) -error loading ad tag (for all else) When applicable, the userInfo (NSDictionary) property of error will contain the ad tag that is currently playing (key: tag), and/or the vmap (key: vmap). If Google IMA is being used as the ad Client, the imaErrorType will be included (key: imaErrorType) and not the vmap. */ @property (nonatomic) JWPlayerError *error; @end NS_ASSUME_NONNULL_END
robu-weatherbug/jwplayer-sdk-ios-demo
<|start_filename|>docs/site/angular-auth-oidc-client/src/pages/index.js<|end_filename|> import { Redirect } from '@docusaurus/router'; import useDocusaurusContext from '@docusaurus/useDocusaurusContext'; import React from 'react'; export default function Home() { const { siteConfig } = useDocusaurusContext(); return <Redirect to={siteConfig.customFields.redirectOnStart} />; } <|start_filename|>projects/sample-code-flow-multi-Auth0-ID4/src/app/home/home.component.html<|end_filename|> <div>Welcome to home Route</div> <br /> UserData <pre>{{ userData$ | async | json }}</pre> <br /> IsAuthenticated <pre>{{ isAuthenticated$ | async | json }}</pre> <div> <h3>{{ configurations[0].configId }}</h3> <button (click)="login(configurations[0].configId)">Login with {{ configurations[0].configId }}</button> <button (click)="logout(configurations[0].configId)">Logout</button> <button (click)="logoffAndRevokeTokens(configurations[0].configId)">Logout and revoke tokens</button> <button (click)="revokeRefreshToken(configurations[0].configId)">Revoke refresh token</button> <button (click)="refreshSessionId4(configurations[0].configId)">Refresh session</button> <pre>{{ configurations[0] | json }}</pre> </div> <div> <h3>{{ configurations[1].configId }}</h3> <button (click)="login(configurations[1].configId)">Login with {{ configurations[1].configId }}</button> <button (click)="logout(configurations[1].configId)">Logout</button> <button (click)="logoffAndRevokeTokens(configurations[1].configId)">Logout and revoke tokens</button> <button (click)="revokeRefreshToken(configurations[1].configId)">Revoke refresh token</button> <button (click)="refreshSessionAuth0(configurations[1].configId)">Refresh session</button> <pre>{{ configurations[1] | json }}</pre> </div>
dopsonbr/angular-auth-oidc-client
<|start_filename|>demo/public/app.js<|end_filename|> const handleResponse = (response) => { const target = document.getElementById("result"); response.text().then((body) => { target.innerHTML = body; target.querySelector("svg").className = "ui fluid image"; }); }; const dataFromForm = () => { const form = document.forms[0]; return { pattern: form.pattern.value, value: form.value.value, }; }; const shouldSubmit = () => { const data = dataFromForm(); return data.pattern.trim().length > 0 && data.value.length > 0; }; const submit = () => { if (!shouldSubmit()) { return; } const config = { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(dataFromForm()), }; fetch("/", config).then(handleResponse); }; const attachEvents = () => { const form = document.forms[0]; const fields = ["pattern", "value"]; fields.forEach((field) => form[field].addEventListener("keyup", submit)); form.addEventListener("submit", () => false); }; document.addEventListener("DOMContentLoaded", attachEvents); document.addEventListener("DOMContentLoaded", submit); <|start_filename|>demo/public/app.css<|end_filename|> body > .grid { height: 100% } .column { max-width: 36% } #result svg { max-width: 100% }
Schwad/regular_expression
<|start_filename|>styles/tailwind.css<|end_filename|> @import "tailwindcss/base"; @import "tailwindcss/components"; @import "tailwindcss/utilities"; .grow { transition: all 0.2s ease-in-out; } .grow:hover { transform: scale(1.1); } .card--disabled { filter: blur(1px) grayscale(100%); } .card--active { transform: scale(1.2); } /* Sticky footer */ html, body, #__next { height: 100%; } #__next { display: flex; flex-direction: column; } .content { flex: 1 0 auto; } .footer { flex-shrink: 0; } .tooltip .tooltip-text { visibility: hidden; text-align: center; padding: 2px 6px; position: absolute; z-index: 100; } .tooltip:hover .tooltip-text { visibility: visible; } <|start_filename|>lib/helper.js<|end_filename|> export const getUrlParam = function getUrlParam(name) { name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]"); var regexS = "[\\?&]" + name + "=([^&#]*)"; var regex = new RegExp(regexS); var results = regex.exec(window.location.href); if (results == null) return null; else return results[1]; }; export const mapToJson = map => { return JSON.stringify([...map]); }; export const jsonToMap = jsonStr => { return new Map(JSON.parse(jsonStr)); }; <|start_filename|>next.config.js<|end_filename|> const isProduction = process.env.NODE_ENV !== "development"; module.exports = { exportPathMap: () => ({ "/": { page: "/" } }), assetPrefix: "", poweredByHeader: false, env: { ROOT_PATH: "/", DOMAIN: isProduction ? "http://judge-framework.starptech.de" : "http://localhost:3000" } }; <|start_filename|>pages/index.js<|end_filename|> import MQTT from "async-mqtt"; import { useClipboard } from "use-clipboard-copy"; import nanoid from "nanoid/generate"; import Head from "next/head"; import nolookalikes from "nanoid-dictionary/nolookalikes"; import { useEffect, useState, useRef } from "react"; import Card from "../components/card"; import allCards from "../lib/cards"; import { getUrlParam, mapToJson, jsonToMap } from "../lib/helper"; import { NextSeo } from "next-seo"; function genId() { return nanoid(nolookalikes, 12); } export default function Index() { const [cards, setCards] = useState(() => allCards); const [status, setStatus] = useState(""); const clipboard = useClipboard({ copiedTimeout: 2000 // timeout duration in milliseconds }); const groupIDRef = useRef(""); const isModeratorRef = useRef(false); const topicRef = useRef(""); const clientRef = useRef(null); const [decisionMap, setDecisionMap] = useState(() => new Map()); const [userVotesMap] = useState(() => new Map()); const [userId] = useState(() => genId()); const handleShare = () => { const link = `${process.env.DOMAIN}${process.env.ROOT_PATH}?g=${groupIDRef.current}`; clipboard.copy(link); localStorage.setItem("masterOfGroupVoteID", groupIDRef.current); }; useEffect(() => { isModeratorRef.current = localStorage.getItem("masterOfGroupVoteID") === getUrlParam("g") || !getUrlParam("g"); const client = MQTT.connect("ws://broker.hivemq.com:8000/mqtt"); const groupID = getUrlParam("g") || genId(); const topic = "judgeframework1.0/" + groupID; const updatesTopic = `${topic}/updates`; groupIDRef.current = groupID; topicRef.current = topic; const acceptDecisions = async () => { console.log("Starting"); try { await client.subscribe(topic, { qos: 1 }); await client.subscribe(updatesTopic, { qos: 1 }); console.log("Subscription created! Topic: " + topic); client.on("message", async (t, message) => { if (topic === t) { const [clientId, decision] = message.toString().split(";"); // check if client has already voted if (userVotesMap.has(clientId)) { console.log(`client with id ${clientId} has voted already!`); return; } const card = cards.find(c => c.title === decision); if (card) { console.log("New vote received", decision); const lastCount = (decisionMap.get(decision) || 0) + 1; decisionMap.set(decision, lastCount); userVotesMap.set(clientId, true); console.log("Participants", userVotesMap.keys()); } setCards([...cards]); // update all other clients and retain the message with the latest voting state // so all new clients will receive the last state await clientRef.current.publish( updatesTopic, mapToJson(decisionMap), { retain: true } ); } else if (t === updatesTopic) { const newDecisionMap = jsonToMap(message.toString()); console.log("Receive map update", newDecisionMap); // update map only when value has increased to be safe for out of order messages for (const [key, value] of newDecisionMap.entries()) { if (decisionMap.has(key)) { if (newDecisionMap.get(key) > decisionMap.get(key)) { decisionMap.set(newDecisionMap.get(key)); } } else { decisionMap.set(key, value); } } // update decision map to be up-to-date setDecisionMap(decisionMap); setCards([...cards]); } }); } catch (e) { setStatus("Error! Please refresh!"); console.log(e); } }; setStatus("Connecting..."); client.on("connect", a => { setStatus("Connected!"); acceptDecisions(); }); client.on("reconnect", () => { setStatus("Reconnecting..."); }); client.on("disconnect", () => { setStatus("Disconnected..."); }); client.on("close", () => { setStatus("Closed!"); }); client.on("error", err => { setStatus("Error! Please refresh!"); console.log(err); }); clientRef.current = client; }, []); const handleRangeClick = (start, end) => { for (let i = 0; i < cards.length; i++) { const card = cards[i]; if (i >= start && i <= end) { card.disabled = false; } else { card.disabled = true; } } setCards([...cards]); }; const handleCardClick = async current => { if (localStorage.getItem("lastGroupVoteID") === groupIDRef.current) { alert("You can't vote twice! Ask the moderator if it's done."); return; } for (let i = 0; i < cards.length; i++) { const card = cards[i]; if (card.title === current.title) { card.active = true; } else { card.active = false; } } setCards([...cards]); const r = confirm(`You want to select '${current.title}' ?`); if (r !== true) { return; } console.log(`Publish to topic ${topicRef.current}`); await clientRef.current.publish( topicRef.current, [userId, current.title].join(";") ); // await clientRef.current.unsubscribe(topicRef.current); localStorage.setItem("lastGroupVoteID", groupIDRef.current); }; return ( <> <NextSeo title="JUDGE - Just an Ultimate Decision Guide" description="JUDGE - Just an Ultimate Decision Guide" canonical={process.env.DOMAIN} /> <Head> <link href="https://use.fontawesome.com/releases/v5.12.1/css/all.css" rel="stylesheet" /> <link href="https://fonts.googleapis.com/css?family=Merriweather+Sans:400,700&display=swap" rel="stylesheet" /> {/*<!-- Global site tag (gtag.js) - Google Analytics -->*/} <script async src="https://www.googletagmanager.com/gtag/js?id=UA-159316068-1" /> <script dangerouslySetInnerHTML={{ __html: ` window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'UA-159316068-1'); ` }} /> </Head> <div className="content"> <header> <nav className="flex items-center justify-between flex-wrap bg-transparent p-6"> <div className="flex items-center flex-shrink-0 text-black mr-6"> <svg height="35pt" viewBox="-64 0 512 512" width="35pt" xmlns="http://www.w3.org/2000/svg" > <path d="m368.464844 512h-353.464844c-4.824219 0-9.351562-2.316406-12.167969-6.230469-2.8203122-3.910156-3.585937-8.9375-2.0625-13.511719l36.800781-110.402343c18.472657-55.417969 70.128907-92.65625 128.546876-92.65625h51.230468c58.417969 0 110.074219 37.238281 128.546875 92.65625l36.804688 110.402343c1.523437 4.574219.757812 9.601563-2.0625 13.511719-2.820313 3.914063-7.347657 6.230469-12.171875 6.230469zm0 0" fill="#324150" /> <path d="m380.632812 505.769531c2.820313-3.910156 3.585938-8.9375 2.0625-13.511719l-36.800781-110.402343c-18.472656-55.417969-70.128906-92.65625-128.546875-92.65625h-25.617187v222.800781h176.734375c4.824218 0 9.351562-2.316406 12.167968-6.230469zm0 0" fill="#23303c" /> <path d="m266.605469 357.859375-64.265625-64.265625c-5.859375-5.859375-15.355469-5.859375-21.214844 0l-64.265625 64.265625c-5.058594 5.054687-5.84375 12.980469-1.875 18.925781l32.132813 48.203125c2.492187 3.738281 6.53125 6.164063 11.003906 6.605469 4.476562.441406 8.90625-1.144531 12.082031-4.320312l21.527344-21.527344 21.527343 21.527344c3.179688 3.179687 7.609376 4.765624 12.085938 4.320312 4.472656-.441406 8.511719-2.867188 11.003906-6.605469l32.132813-48.203125c3.964843-5.945312 3.179687-13.871094-1.875-18.925781zm0 0" fill="#f0f2f4" /> <path d="m225.34375 431.59375c4.472656-.441406 8.511719-2.867188 11.003906-6.605469l32.132813-48.199219c3.964843-5.949218 3.179687-13.871093-1.875-18.929687l-64.265625-64.265625c-2.929688-2.929688-6.769532-4.394531-10.609375-4.394531v116.546875l21.527343 21.527344c3.179688 3.179687 7.609376 4.765624 12.085938 4.320312zm0 0" fill="#dee1e5" /> <path d="m63.199219 287.066406c-25.988281 0-47.132813-21.144531-47.132813-47.132812 0-25.988282 21.144532-47.132813 47.132813-47.132813s47.132812 21.144531 47.132812 47.132813c0 25.988281-21.144531 47.132812-47.132812 47.132812zm0 0" fill="#cbcfd7" /> <path d="m320.265625 287.066406c-25.988281 0-47.132813-21.144531-47.132813-47.132812 0-25.988282 21.144532-47.132813 47.132813-47.132813s47.132813 21.144531 47.132813 47.132813c0 25.988281-21.144532 47.132812-47.132813 47.132812zm0 0" fill="#b9bec8" /> <path d="m63.199219 222.800781c-25.988281 0-47.132813-21.144531-47.132813-47.132812s21.144532-47.136719 47.132813-47.136719 47.132812 21.148438 47.132812 47.136719-21.144531 47.132812-47.132812 47.132812zm0 0" fill="#dee1e5" /> <path d="m320.265625 222.800781c-25.988281 0-47.132813-21.144531-47.132813-47.132812s21.144532-47.136719 47.132813-47.136719 47.132813 21.148438 47.132813 47.136719-21.144532 47.132812-47.132813 47.132812zm0 0" fill="#cbcfd7" /> <path d="m191.730469 319.199219c-61.429688 0-111.398438-49.964844-111.398438-111.382813v-64.285156c0-8.28125 6.714844-15 15-15h192.800781c8.285157 0 15 6.71875 15 15v64.269531c0 61.515625-49.769531 111.398438-111.402343 111.398438zm0 0" fill="#ffdcc8" /> <path d="m303.132812 207.800781v-64.269531c0-8.28125-6.714843-15-15-15h-96.402343v190.667969c61.632812 0 111.402343-49.882813 111.402343-111.398438zm0 0" fill="#ffc3b4" /> <path d="m320.265625 158.53125h-257.066406c-8.285157 0-15-6.714844-15-15 0-79.140625 64.386719-143.53125 143.53125-143.53125 79.148437 0 143.535156 64.390625 143.535156 143.53125 0 8.285156-6.714844 15-15 15zm0 0" fill="#f0f2f4" /> <path d="m335.265625 143.53125c0-79.140625-64.390625-143.53125-143.535156-143.53125v158.53125h128.535156c8.285156 0 15-6.714844 15-15zm0 0" fill="#dee1e5" /> </svg> <span className="font-semibold text-xl tracking-tight text-gray-700 ml-3"> JUDGE Framework </span> </div> <div className="w-full flex-grow lg:flex lg:items-center lg:w-auto mt-3 lg:mt-0"> {isModeratorRef.current && ( <> <button className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded mt-3 lg:ml-3 lg:mt-0" onClick={() => (window.location = "/")} > <i className="far fa-file"></i> <span className="ml-2">New</span> </button> <button className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded mt-3 ml-3 lg:mt-0 tooltip" onClick={handleShare} > <i className="far fa-copy"></i> <span className="ml-2">Copy link</span> <span className="tooltip-text bg-gray-700 p-3 -mt-6 -ml-6 rounded"> You can share the link with your colleagues to get realtime evaluation of the voting. </span> </button> </> )} <div className="lg:flex-grow"> <span className="block mt-4 lg:inline-block lg:mt-0 text-green-500 ml-3"> {clipboard.copied ? "Copied!" : null} </span> {groupIDRef.current && ( <span className="block mt-4 lg:inline-block lg:mt-0 text-gray-700 lg:ml-3"> <i className="fas fa-users"></i> <b className="ml-2">Session:</b> {groupIDRef.current} </span> )} <span className="block mt-4 lg:inline-block lg:mt-0 text-gray-700 lg:ml-5"> <i className="fas fa-ethernet"></i> <b className="ml-2">State:</b> {status} </span> </div> <div className="lg:ml-3 mt-3 lg:mt-0"> <iframe src="https://ghbtns.com/github-btn.html?user=starptech&repo=judge-framework&type=star&count=true&size=large" frameBorder="0" scrolling="0" width="160px" height="30px" /> </div> </div> </nav> </header> {isModeratorRef.current && ( <div className="flex mb-6 pb-6 justify-center p-4"> <div className="bg-white border-t-4 border-teal rounded-b text-teal-darkest px-4 py-3 shadow-md my-2 max-w-2xl" role="alert" > <div className="flex"> <i className="far fa-question-circle text-teal mr-4 text-4xl"></i> <div> <p className="font-bold text-xl">What is JUDGE?</p> <div> JUDGE – Just an Ultimate Decision Guide <br /> is a tool to express your insecurity in a way that others can understand. <br /> <br /> <ul className="list-disc"> <li> <b>Consensus 0-2:</b> Does not require agreement, affirmation or even preference. </li> <li> <b>Consent 0-4:</b> Members don’t “block” decisions. </li> <li> <b>Decision is blocked 5-6:</b> Members can't follow the proposal or don't wish to attend. </li> </ul> <br /> <div className="text-right"> <a className="text-gray-600" target="_blank" href="http://mytoysdevblog.wpengine.com/index.php/2018/06/28/die-magie-von-gruppenentscheidungen/" > Blog post (German) </a> <span className="text-gray-600"> | </span> <a className="text-gray-600" target="_blank" href="https://www.youtube.com/watch?v=t4eVn_MxOUQ" > Video (German) </a> </div> </div> </div> </div> </div> </div> )} {isModeratorRef.current && ( <div className="flex mt-6 mb-6 pb-6 justify-center"> <ul className="flex justify-between text-xl flex-col sm:flex-row"> <li className="mr-2"> <a className="text-center block border border-white rounded hover:border-gray-200 text-gray-700 hover:bg-gray-200 py-2 px-4" href="#" onClick={() => handleRangeClick(0, 6)} > All </a> </li> <li className="mr-2"> <a className="text-center block border border-white rounded hover:border-gray-200 text-gray-700 hover:bg-gray-200 py-2 px-4" href="#" onClick={() => handleRangeClick(0, 2)} > 0-2 Consensus </a> </li> <li className="mr-2"> <a className="text-center block border border-white rounded hover:border-gray-200 text-gray-700 hover:bg-gray-200 py-2 px-4" href="#" onClick={() => handleRangeClick(0, 4)} > 0-4 Consent </a> </li> <li className="text-center"> <a className="text-center block border border-white rounded hover:border-gray-200 text-gray-700 hover:bg-gray-200 py-2 px-4" href="#" onClick={() => handleRangeClick(5, 6)} > 5-6 Decision is blocked </a> </li> </ul> </div> )} <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-7 gap-1"> {cards.map((card, index) => { const count = decisionMap.get(card.title); let total = 0; for (var value of decisionMap.values()) { total += value; } let val = 0; if (total > 0 && count > 0) { val = Math.round((100 / total) * count); } const cardStyle = { background: `linear-gradient(90deg, rgb(136, 136, 136), ${val}%, ${card.color} 0%)` }; if (total > 0) { cardStyle.background = `linear-gradient(90deg, ${card.color}, ${val}%, rgb(136, 136, 136) 0%)`; } return ( <Card key={card.title} onClick={handleCardClick} style={cardStyle} index={index} card={card} count={count} /> ); })} </div> </div> <footer className="footer p-4"> <div className="text-xs text-center text-teal-900 mt-5"> © 2020{" "} <a href="https://dynabase.de/" className="text-gray-800" target="_blank" > developed by dynabase </a>{" "} <div className="text-gray-500"> Icons created by{" "} <a href="https://www.flaticon.com/de/autoren/freepik" title="Freepik" > Freepik </a>{" "} from{" "} <a href="https://www.flaticon.com/de/" title="Flaticon"> www.flaticon.com </a> </div> </div> </footer> </> ); } <|start_filename|>components/card.js<|end_filename|> import { useEffect, useState } from "react"; import classNames from "classnames"; export default function Card({ card, index, onClick, style, count }) { const [isDisabled, setDisabled] = useState(false); const [isActive, setActive] = useState(false); const innerCardStyle = { transform: "scale(1.5)", opacity: 0.1 }; const { title, desc, className, disabled, color, active } = card; useEffect(() => { setDisabled(disabled); }, [disabled]); useEffect(() => { setActive(active); }, [active]); return ( <div onClick={() => onClick(card)} style={style} className={classNames( "m-6 relative overflow-hidden rounded-lg shadow-lg grow cursor-pointer", { "card--disabled": isDisabled, "card--active": isActive }, color, className )} > <svg className="absolute bottom-0 left-0 mb-8" viewBox="0 0 375 283" fill="none" style={innerCardStyle} > <rect x="159.52" y="175" width="152" height="152" rx="8" transform="rotate(-45 159.52 175)" fill="white" /> <rect y="107.48" width="152" height="152" rx="8" transform="rotate(-45 0 107.48)" fill="white" /> </svg> <div className={classNames( "h-32 w-full flex flex-col items-center justify-center text-white text-6xl" )} > <div>{index}</div> {count > 0 && ( <div className="text-sm">{count === 1 ? `(${count} Vote)` : `(${count} Votes)`}</div> )} </div> <div className="relative text-white px-6 pb-6 mt-6"> <div className="flex justify-between"> <span className="block font-bold text-2xl pt-3 pb-3">{title}</span> </div> <span className="block opacity-75 -mb-1 text-gray-200">{desc}</span> </div> </div> ); } <|start_filename|>tailwind.config.js<|end_filename|> module.exports = { theme: { fontFamily: { display: ["Merriweather Sans"], body: ["Merriweather Sans"], sans: ["Merriweather Sans", "Arial", "sans-serif"] }, extend: {} }, variants: {}, plugins: [] }; <|start_filename|>lib/cards.js<|end_filename|> export default [ { color: "#3182ce", title: "step aside", desc: "I step aside, I support the groups decision and don't need to be involved.", className: "border-b-4 border-solid border-blue-600" }, { color: "#68d391", title: "full support", desc: "I really like it. It's great and it works like a charm for me.", className: "border-b-4 border-solid border-green-300" }, { color: "#22543d", title: "slight concerns", desc: "I have some slight concerns but I can live with it. I'll support the group actively.", className: "border-b-4 border-solid border-green-800" }, { color: "#b83280", title: "severe concerns", desc: "Not perfect it's good enough. I disagree with a few points. But I'll support the group.", className: "border-b-4 border-solid border-pink-600" }, { color: "#ed8936", title: "step out", desc: "Disagreements are so serious that I'm not willing to support this decision actively. Group can still continue but without my involvement.", className: "border-b-4 border-solid border-orange-400" }, { color: "#b7791f", title: "need to talk", desc: "I don't understand the proposal and / or I need more discussion before I can support this decision.", className: "border-b-4 border-solid border-yellow-600" }, { color: "#c53030", title: "veto", desc: "I understand the proposal but do not support it! I can explain my concerns.", className: "border-b-4 border-solid border-red-700" } ];
StarpTech/judge-framework
<|start_filename|>vendor/github.com/influxdata/influxdb/models/statistic.go<|end_filename|> package models type Statistic struct { Name string `json:"name"` Tags Tags `json:"tags"` Values map[string]interface{} `json:"values"` } <|start_filename|>utils/netwrapper.go<|end_filename|> /*** Copyright 2014 Cisco Systems 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. */ package utils import ( "net" "sync" ) // ListenWrapper is a wrapper over net.Listener func ListenWrapper(l net.Listener) net.Listener { return &contivListener{ Listener: l, cond: sync.NewCond(&sync.Mutex{})} } type contivListener struct { net.Listener cond *sync.Cond refCnt int } func (s *contivListener) incrementRef() { s.cond.L.Lock() s.refCnt++ s.cond.L.Unlock() } func (s *contivListener) decrementRef() { s.cond.L.Lock() s.refCnt-- newRefs := s.refCnt s.cond.L.Unlock() if newRefs == 0 { s.cond.Broadcast() } } // Accept is a wrapper over regular Accept call // which also maintains the refCnt func (s *contivListener) Accept() (net.Conn, error) { s.incrementRef() defer s.decrementRef() return s.Listener.Accept() } // Close closes the contivListener. func (s *contivListener) Close() error { if err := s.Listener.Close(); err != nil { return err } s.cond.L.Lock() for s.refCnt > 0 { s.cond.Wait() } s.cond.L.Unlock() return nil } <|start_filename|>vendor/github.com/contiv/Godeps/_workspace/src/google.golang.org/grpc/grpclog/logger.go<|end_filename|> /* * * Copyright 2015, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /* Package grpclog defines logging for grpc. */ package grpclog import ( "log" "os" ) // Use golang's standard logger by default. var logger Logger = log.New(os.Stderr, "", log.LstdFlags) // Logger mimics golang's standard Logger as an interface. type Logger interface { Fatal(args ...interface{}) Fatalf(format string, args ...interface{}) Fatalln(args ...interface{}) Print(args ...interface{}) Printf(format string, args ...interface{}) Println(args ...interface{}) } // SetLogger sets the logger that is used in grpc. func SetLogger(l Logger) { logger = l } // Fatal is equivalent to Print() followed by a call to os.Exit() with a non-zero exit code. func Fatal(args ...interface{}) { logger.Fatal(args...) } // Fatalf is equivalent to Printf() followed by a call to os.Exit() with a non-zero exit code. func Fatalf(format string, args ...interface{}) { logger.Fatalf(format, args...) } // Fatalln is equivalent to Println() followed by a call to os.Exit()) with a non-zero exit code. func Fatalln(args ...interface{}) { logger.Fatalln(args...) } // Print prints to the logger. Arguments are handled in the manner of fmt.Print. func Print(args ...interface{}) { logger.Print(args...) } // Printf prints to the logger. Arguments are handled in the manner of fmt.Printf. func Printf(format string, args ...interface{}) { logger.Printf(format, args...) } // Println prints to the logger. Arguments are handled in the manner of fmt.Println. func Println(args ...interface{}) { logger.Println(args...) } <|start_filename|>utils/sysutils.go<|end_filename|> /*** Copyright 2014 Cisco Systems 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. */ package utils import ( "io/ioutil" "strings" log "github.com/Sirupsen/logrus" ) // Implement utilities to fetch System specific information and capabilities. // These capabilities could be used natively by netplugin or exported. // In most cases the os capabilities do not change over the course of uptime // of the system, however if it does, a registry mechanism should be used // to notify the interested threads // SystemAttributes enlist the system specific attributes and are read upon // the system start type SystemAttributes struct { OsType string TotalRAM int TotalDiskGB int TotalNetBw int } // SysAttrs are the exported system attributes var SysAttrs SystemAttributes // FetchSysAttrs would read the system attributes and store them in the // exported vars for the plugin to use; some of the attributes may need OS // spefici methods to fetch, thus the first attribute to fetch is the OS type func FetchSysAttrs() error { output, err := ioutil.ReadFile("/etc/os-release") if err != nil { log.Errorf("Error reading the /etc/os-release Error: %s Output: \n%s\n", err, output) return err } strOutput := string(output) if strings.Contains(strOutput, "CentOS") { SysAttrs.OsType = "centos" } else if strings.Contains(strOutput, "Ubuntu") { SysAttrs.OsType = "ubuntu" } else { SysAttrs.OsType = "unsupported" } // fetch the system memory, disk, and other attributes return err } <|start_filename|>netmaster/mastercfg/providerState_test.go<|end_filename|> /*** Copyright 2014 Cisco Systems 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. */ package mastercfg import ( "testing" "github.com/contiv/netplugin/core" ) const ( testSvcProviderID = "testSvcProvider" svcProviderCfgKey = svcProviderPathPrefix + testSvcProviderID ) type testSvcProviderStateDriver struct{} var svcProviderStateDriver = &testSvcProviderStateDriver{} func (d *testSvcProviderStateDriver) Init(instInfo *core.InstanceInfo) error { return core.Errorf("Shouldn't be called!") } func (d *testSvcProviderStateDriver) Deinit() { } func (d *testSvcProviderStateDriver) Write(key string, value []byte) error { return core.Errorf("Shouldn't be called!") } func (d *testSvcProviderStateDriver) Read(key string) ([]byte, error) { return []byte{}, core.Errorf("Shouldn't be called!") } func (d *testSvcProviderStateDriver) ReadAll(baseKey string) ([][]byte, error) { return [][]byte{}, core.Errorf("Shouldn't be called!") } func (d *testSvcProviderStateDriver) WatchAll(baseKey string, rsps chan [2][]byte) error { return core.Errorf("not supported") } func (d *testSvcProviderStateDriver) validateKey(key string) error { if key != svcProviderCfgKey { return core.Errorf("Unexpected key. recvd: %s expected: %s ", key, svcProviderCfgKey) } return nil } func (d *testSvcProviderStateDriver) ClearState(key string) error { return d.validateKey(key) } func (d *testSvcProviderStateDriver) ReadState(key string, value core.State, unmarshal func([]byte, interface{}) error) error { return d.validateKey(key) } func (d *testSvcProviderStateDriver) ReadAllState(key string, value core.State, unmarshal func([]byte, interface{}) error) ([]core.State, error) { return nil, core.Errorf("Shouldn't be called!") } func (d *testSvcProviderStateDriver) WatchAllState(baseKey string, sType core.State, unmarshal func([]byte, interface{}) error, rsps chan core.WatchState) error { return core.Errorf("not supported") } func (d *testSvcProviderStateDriver) WriteState(key string, value core.State, marshal func(interface{}) ([]byte, error)) error { return d.validateKey(key) } func TestSvcProviderRead(t *testing.T) { svcProviderCfg := &SvcProvider{} svcProviderCfg.StateDriver = svcProviderStateDriver err := svcProviderCfg.Read(testSvcProviderID) if err != nil { t.Fatalf("read config state failed. Error: %s", err) } } func TestSvcProviderWrite(t *testing.T) { svcProviderCfg := &SvcProvider{} svcProviderCfg.StateDriver = svcProviderStateDriver svcProviderCfg.ID = testSvcProviderID err := svcProviderCfg.Write() if err != nil { t.Fatalf("write config state failed. Error: %s", err) } } func TestSvcProviderClear(t *testing.T) { svcProviderCfg := &SvcProvider{} svcProviderCfg.StateDriver = svcProviderStateDriver svcProviderCfg.ID = testSvcProviderID err := svcProviderCfg.Clear() if err != nil { t.Fatalf("clear config state failed. Error: %s", err) } } <|start_filename|>netctl/http.go<|end_filename|> package netctl import ( "encoding/json" "fmt" "io/ioutil" "net/http" "os" "github.com/codegangsta/cli" ) var client = &http.Client{} func handleBasicError(ctx *cli.Context, err error) { if err != nil { errExit(ctx, exitRequest, err.Error(), false) } } func baseURL(ctx *cli.Context) string { return ctx.GlobalString("netmaster") } func versionURL(ctx *cli.Context) string { return fmt.Sprintf("%s/version", baseURL(ctx)) } func writeBody(resp *http.Response, ctx *cli.Context) { content, err := ioutil.ReadAll(resp.Body) if err != nil { errExit(ctx, exitIO, err.Error(), false) } os.Stderr.Write(content) } func getObject(ctx *cli.Context, url string, jdata interface{}) error { resp, err := client.Get(url) handleBasicError(ctx, err) respCheck(resp, ctx) content, err := ioutil.ReadAll(resp.Body) handleBasicError(ctx, err) handleBasicError(ctx, json.Unmarshal(content, jdata)) return nil } <|start_filename|>netmaster/resources/stateresourcemanager_test.go<|end_filename|> /*** Copyright 2014 Cisco Systems 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. */ package resources import ( "fmt" "reflect" "strings" "testing" "github.com/contiv/netplugin/core" "github.com/contiv/netplugin/state" ) const ( testResourceDesc = "testResourceDesc" testResourceID = "testResourceID" ) var ( gReadCtr int ) type TestResource struct { core.CommonState readCtr int } func (r *TestResource) Write() error { return core.Errorf("Shouldn't be called") } func (r *TestResource) Read(id string) error { return core.Errorf("Shouldn't be called") } func (r *TestResource) Clear() error { return core.Errorf("Shouldn't be called") } func (r *TestResource) ReadAll() ([]core.State, error) { if gReadCtr == 0 { gReadCtr = 1 return []core.State{}, nil } return []core.State{core.State(r)}, nil } func (r *TestResource) Init(rsrcCfg interface{}) error { return nil } func (r *TestResource) Reinit(rsrcCfg interface{}) error { return nil } func (r *TestResource) Deinit() { } func (r *TestResource) Description() string { return testResourceDesc } func (r *TestResource) GetList() (uint, string) { return 0, "" } func (r *TestResource) Allocate(reqValue interface{}) (interface{}, error) { return 0, nil } func (r *TestResource) Deallocate(value interface{}) error { return nil } var fakeDriver = &state.FakeStateDriver{} func TestStateResourceManagerNewSuccess(t *testing.T) { rm, err := NewStateResourceManager(fakeDriver) defer func() { ReleaseStateResourceManager() }() if err != nil { t.Fatalf("Resource manager instantiation failed. Error: %s", err) } if rm == nil { t.Fatalf("Resource manager instance is nil") } } func TestStateResourceManagerDuplicateNewFailure(t *testing.T) { _, err := NewStateResourceManager(fakeDriver) defer func() { ReleaseStateResourceManager() }() if err != nil { t.Fatalf("Resource manager instantiation failed. Error: %s", err) } _, err = NewStateResourceManager(fakeDriver) if err == nil { t.Fatalf("Resource manager double instantiation succeeded, expected to fail") } } func TestStateResourceManagerNonExistentGetFailure(t *testing.T) { _, err := GetStateResourceManager() if err == nil { t.Fatalf("Resource manager Get succeeded, expected to fail") } } func TestStateResourceManagerDefineResource(t *testing.T) { rm := &StateResourceManager{stateDriver: fakeDriver} resourceRegistry[testResourceDesc] = reflect.TypeOf(TestResource{}) defer func() { delete(resourceRegistry, testResourceDesc) }() gReadCtr = 0 err := rm.DefineResource(testResourceID, testResourceDesc, &TestResource{}) if err != nil { t.Fatalf("Resource definition failed. Error: %s", err) } } func TestStateResourceManagerDefineInvalidResource(t *testing.T) { rm := &StateResourceManager{stateDriver: fakeDriver} gReadCtr = 0 err := rm.DefineResource(testResourceID, testResourceDesc, &TestResource{}) if err == nil { t.Fatalf("Resource definition succeeded, expected to fail!") } if !strings.Contains(err.Error(), fmt.Sprintf("No resource found for description: %q", testResourceDesc)) { t.Fatalf("Unexpected error. Error: %s", err) } } func TestStateResourceManagerUndefineResource(t *testing.T) { rm := &StateResourceManager{stateDriver: fakeDriver} resourceRegistry[testResourceDesc] = reflect.TypeOf(TestResource{}) defer func() { delete(resourceRegistry, testResourceDesc) }() gReadCtr = 0 err := rm.DefineResource(testResourceID, testResourceDesc, &TestResource{}) if err != nil { t.Fatalf("Resource definition failed. Error: %s", err) } err = rm.UndefineResource(testResourceID, testResourceDesc) if err != nil { t.Fatalf("Resource un-definition failed. Error: %s", err) } } func TestStateResourceManagerUndefineInvalidResource(t *testing.T) { rm := &StateResourceManager{stateDriver: fakeDriver} gReadCtr = 0 err := rm.UndefineResource(testResourceID, testResourceDesc) if err == nil { t.Fatalf("Resource un-definition succeeded, expected to fail!") } if !strings.Contains(err.Error(), fmt.Sprintf("No resource found for description: %q", testResourceDesc)) { t.Fatalf("Unexpected error. Error: %s", err) } } func TestStateResourceManagerUndefineNonexistentResource(t *testing.T) { rm := &StateResourceManager{stateDriver: fakeDriver} resourceRegistry[testResourceDesc] = reflect.TypeOf(TestResource{}) defer func() { delete(resourceRegistry, testResourceDesc) }() gReadCtr = 0 err := rm.UndefineResource(testResourceID, testResourceDesc) if err == nil { t.Fatalf("Resource un-definition succeeded, expected to fail!") } if !strings.Contains(err.Error(), fmt.Sprintf("No resource found for description: %q and id: %q", testResourceDesc, testResourceID)) { t.Fatalf("Unexpected error. Error: %s", err) } } func TestStateResourceManagerAllocateResource(t *testing.T) { rm := &StateResourceManager{stateDriver: fakeDriver} resourceRegistry[testResourceDesc] = reflect.TypeOf(TestResource{}) defer func() { delete(resourceRegistry, testResourceDesc) }() gReadCtr = 0 err := rm.DefineResource(testResourceID, testResourceDesc, &TestResource{}) if err != nil { t.Fatalf("Resource definition failed. Error: %s", err) } _, err = rm.AllocateResourceVal(testResourceID, testResourceDesc, nil) if err != nil { t.Fatalf("Resource allocation failed. Error: %s", err) } } func TestStateResourceManagerAllocateInvalidResource(t *testing.T) { rm := &StateResourceManager{stateDriver: fakeDriver} gReadCtr = 0 _, err := rm.AllocateResourceVal(testResourceID, testResourceDesc, nil) if err == nil { t.Fatalf("Resource allocation succeeded, expected to fail!") } if !strings.Contains(err.Error(), fmt.Sprintf("No resource found for description: %q", testResourceDesc)) { t.Fatalf("Unexpected error. Error: %s", err) } } func TestStateResourceManagerAllocateiNonexistentResource(t *testing.T) { rm := &StateResourceManager{stateDriver: fakeDriver} resourceRegistry[testResourceDesc] = reflect.TypeOf(TestResource{}) defer func() { delete(resourceRegistry, testResourceDesc) }() gReadCtr = 0 _, err := rm.AllocateResourceVal(testResourceID, testResourceDesc, nil) if err == nil { t.Fatalf("Resource allocation succeeded, expected to fail!") } if !strings.Contains(err.Error(), fmt.Sprintf("No resource found for description: %q and id: %q", testResourceDesc, testResourceID)) { t.Fatalf("Unexpected error. Error: %s", err) } } func TestStateResourceManagerDeallocateResource(t *testing.T) { rm := &StateResourceManager{stateDriver: fakeDriver} resourceRegistry[testResourceDesc] = reflect.TypeOf(TestResource{}) defer func() { delete(resourceRegistry, testResourceDesc) }() gReadCtr = 0 err := rm.DefineResource(testResourceID, testResourceDesc, &TestResource{}) if err != nil { t.Fatalf("Resource definition failed. Error: %s", err) } _, err = rm.AllocateResourceVal(testResourceID, testResourceDesc, nil) if err != nil { t.Fatalf("Resource allocation failed. Error: %s", err) } err = rm.DeallocateResourceVal(testResourceID, testResourceDesc, 0) if err != nil { t.Fatalf("Resource deallocation failed. Error: %s", err) } } func TestStateResourceManagerDeallocateInvalidResource(t *testing.T) { rm := &StateResourceManager{stateDriver: fakeDriver} gReadCtr = 0 err := rm.DeallocateResourceVal(testResourceID, testResourceDesc, nil) if err == nil { t.Fatalf("Resource deallocation succeeded, expected to fail!") } if !strings.Contains(err.Error(), fmt.Sprintf("No resource found for description: %q", testResourceDesc)) { t.Fatalf("Unexpected error. Error: %s", err) } } func TestStateResourceManagerDeallocateiNonexistentResource(t *testing.T) { rm := &StateResourceManager{stateDriver: fakeDriver} resourceRegistry[testResourceDesc] = reflect.TypeOf(TestResource{}) defer func() { delete(resourceRegistry, testResourceDesc) }() gReadCtr = 0 err := rm.DeallocateResourceVal(testResourceID, testResourceDesc, nil) if err == nil { t.Fatalf("Resource allocation succeeded, expected to fail!") } if !strings.Contains(err.Error(), fmt.Sprintf("No resource found for description: %q and id: %q", testResourceDesc, testResourceID)) { t.Fatalf("Unexpected error. Error: %s", err) } } <|start_filename|>mgmtfn/mesosplugin/cniserver.go<|end_filename|> /*** Copyright 2016 Cisco Systems 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. */ package mesosplugin import ( "encoding/json" "fmt" log "github.com/Sirupsen/logrus" "github.com/contiv/netplugin/mgmtfn/mesosplugin/cniapi" "github.com/contiv/netplugin/netplugin/plugin" "github.com/gorilla/mux" "io/ioutil" "net" "net/http" "os" ) type cniServer struct { networkID string endpointID string endPointLabels map[string]string ipv4Addr string pluginArgs cniapi.CniCmdReqAttr cniSuccessResp cniapi.CniCmdSuccessResp } type httpAPIFunc func(httpBody []byte) ([]byte, error) var cniLog *log.Entry // HTTP wrapper func httpWrapper(handlerFunc httpAPIFunc) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { if httpBody, err := ioutil.ReadAll(r.Body); err == nil { cniLog.Infof("==== received new http req %s ======", string(httpBody)) jsonResp, hErr := handlerFunc(httpBody) if hErr != nil { cniLog.Infof("sending http Error response %s", string(jsonResp)) w.WriteHeader(http.StatusInternalServerError) } else { cniLog.Infof("sending http OK response %s", string(jsonResp)) w.WriteHeader(http.StatusOK) } w.Write(jsonResp) } else { errResp, _ := createCniErrorResponse(fmt.Errorf("failed to read http body: %s", err)) w.WriteHeader(http.StatusInternalServerError) w.Write(errResp) } w.Header().Set("Content-Type", "application/json") } } func createCniErrorResponse(errmsg error) ([]byte, error) { // CNI_ERROR_UNSUPPORTED is sent for all errors cniResp := cniapi.CniCmdErrorResp{CniVersion: cniapi.CniDefaultVersion, ErrCode: cniapi.CniStatusErrorUnsupportedField, ErrMsg: fmt.Sprintf("Contiv: %s", errmsg.Error())} cniLog.Infof("sending error response: %s", cniResp.ErrMsg) jsonResp, err := json.Marshal(&cniResp) if err != nil { cniLog.Errorf("failed to convert error response to JSON: %s ", err.Error()) return nil, err } return jsonResp, errmsg } func (cniReq *cniServer) createCniSuccessResponse() ([]byte, error) { jsonResp, err := json.Marshal(&cniReq.cniSuccessResp) if err != nil { cniLog.Errorf("failed to convert success response to JSON: %s ", err.Error()) return nil, err } return jsonResp, nil } // parse & save labels func (cniReq *cniServer) parseCniArgs(httpBody []byte) error { if err := json.Unmarshal(httpBody, &cniReq.pluginArgs); err != nil { return fmt.Errorf("failed to parse JSON req: %s", err.Error()) } cniLog.Debugf("parsed ifname: %s, netns: %s, container-id: %s,"+ "tenant: %s, network-name: %s, network-group: %s", cniReq.pluginArgs.CniIfname, cniReq.pluginArgs.CniNetns, cniReq.pluginArgs.CniContainerid, cniReq.pluginArgs.Labels.TenantName, cniReq.pluginArgs.Labels.NetworkName, cniReq.pluginArgs.Labels.NetworkGroup) // set defaults cniReq.endPointLabels = map[string]string{cniapi.LabelNetworkName: "default-net", cniapi.LabelTenantName: "default"} for _, label := range []string{cniapi.LabelTenantName, cniapi.LabelNetworkName, cniapi.LabelNetworkGroup} { switch label { case cniapi.LabelTenantName: if len(cniReq.pluginArgs.Labels.TenantName) > 0 { cniReq.endPointLabels[label] = cniReq.pluginArgs.Labels.TenantName } cniLog.Infof("netplugin label %s = %s", cniapi.LabelTenantName, cniReq.endPointLabels[label]) case cniapi.LabelNetworkName: if len(cniReq.pluginArgs.Labels.NetworkName) > 0 { cniReq.endPointLabels[label] = cniReq.pluginArgs.Labels.NetworkName } cniLog.Infof("netplugin label %s = %s", cniapi.LabelNetworkName, cniReq.endPointLabels[label]) case cniapi.LabelNetworkGroup: if len(cniReq.pluginArgs.Labels.NetworkGroup) > 0 { cniReq.endPointLabels[label] = cniReq.pluginArgs.Labels.NetworkGroup } cniLog.Infof("netplugin label %s = %s", cniapi.LabelNetworkGroup, cniReq.endPointLabels[label]) } } cniReq.networkID = cniReq.endPointLabels[cniapi.LabelNetworkName] + "." + cniReq.endPointLabels[cniapi.LabelTenantName] cniLog.Infof("network fdn %s", cniReq.networkID) cniReq.endpointID = cniReq.networkID + "-" + cniReq.pluginArgs.CniContainerid cniLog.Infof("endpoint fdn %s", cniReq.endpointID) return nil } func mesosNwIntfAdd(httpBody []byte) ([]byte, error) { addReq := cniServer{} cniLog.Infof("process intf add req ") if err := addReq.parseCniArgs(httpBody); err != nil { return createCniErrorResponse(err) } if err := addReq.createCniEndPoint(); err != nil { return createCniErrorResponse(err) } // success return addReq.createCniSuccessResponse() } func mesosNwIntfDel(httpBody []byte) ([]byte, error) { retSuccess := []byte("") delReq := cniServer{} cniLog.Infof("process intf delete req") if err := delReq.parseCniArgs(httpBody); err != nil { return createCniErrorResponse(err) } if err := delReq.deleteCniEndPoint(); err != nil { return createCniErrorResponse(err) } return retSuccess, nil } func unknownReq(w http.ResponseWriter, r *http.Request) { cniLog.Infof("unknown http request at %q", r.URL.Path) content, _ := ioutil.ReadAll(r.Body) cniLog.Debugf("received http body content: %s", string(content)) w.WriteHeader(http.StatusServiceUnavailable) } // InitPlugin registers REST endpoints to handle requests from Mesos CNI plugins func InitPlugin(netPlugin *plugin.NetPlugin) { cniLog = log.WithField("plugin", "mesos") cniLog.Infof("starting Mesos CNI server") router := mux.NewRouter() // register handlers for cni plugin subRtr := router.Headers("Content-Type", "application/json").Subrouter() subRtr.HandleFunc(cniapi.MesosNwIntfAdd, httpWrapper(mesosNwIntfAdd)).Methods("POST") subRtr.HandleFunc(cniapi.MesosNwIntfDel, httpWrapper(mesosNwIntfDel)).Methods("POST") router.HandleFunc("/{*}", unknownReq) sockFile := cniapi.ContivMesosSocket os.Remove(sockFile) os.MkdirAll(cniapi.PluginPath, 0700) cniDriverInit(netPlugin) go func() { lsock, err := net.ListenUnix("unix", &net.UnixAddr{Name: sockFile, Net: "unix"}) if err != nil { cniLog.Errorf("Mesos CNI server failed: %s", err) return } cniLog.Infof("Mesos CNI server is listening on %s", sockFile) http.Serve(lsock, router) lsock.Close() cniLog.Infof("Mesos CNI server socket %s closed ", sockFile) }() } <|start_filename|>vendor/github.com/contiv/Godeps/_workspace/src/golang.org/x/net/http2/client_conn_pool.go<|end_filename|> // Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Transport code's client connection pooling. package http2 import ( "net/http" "sync" ) // ClientConnPool manages a pool of HTTP/2 client connections. type ClientConnPool interface { GetClientConn(req *http.Request, addr string) (*ClientConn, error) MarkDead(*ClientConn) } type clientConnPool struct { t *Transport mu sync.Mutex // TODO: maybe switch to RWMutex // TODO: add support for sharing conns based on cert names // (e.g. share conn for googleapis.com and appspot.com) conns map[string][]*ClientConn // key is host:port dialing map[string]*dialCall // currently in-flight dials keys map[*ClientConn][]string } func (p *clientConnPool) GetClientConn(req *http.Request, addr string) (*ClientConn, error) { return p.getClientConn(req, addr, true) } func (p *clientConnPool) getClientConn(req *http.Request, addr string, dialOnMiss bool) (*ClientConn, error) { p.mu.Lock() for _, cc := range p.conns[addr] { if cc.CanTakeNewRequest() { p.mu.Unlock() return cc, nil } } if !dialOnMiss { p.mu.Unlock() return nil, ErrNoCachedConn } call := p.getStartDialLocked(addr) p.mu.Unlock() <-call.done return call.res, call.err } // dialCall is an in-flight Transport dial call to a host. type dialCall struct { p *clientConnPool done chan struct{} // closed when done res *ClientConn // valid after done is closed err error // valid after done is closed } // requires p.mu is held. func (p *clientConnPool) getStartDialLocked(addr string) *dialCall { if call, ok := p.dialing[addr]; ok { // A dial is already in-flight. Don't start another. return call } call := &dialCall{p: p, done: make(chan struct{})} if p.dialing == nil { p.dialing = make(map[string]*dialCall) } p.dialing[addr] = call go call.dial(addr) return call } // run in its own goroutine. func (c *dialCall) dial(addr string) { c.res, c.err = c.p.t.dialClientConn(addr) close(c.done) c.p.mu.Lock() delete(c.p.dialing, addr) if c.err == nil { c.p.addConnLocked(addr, c.res) } c.p.mu.Unlock() } func (p *clientConnPool) addConn(key string, cc *ClientConn) { p.mu.Lock() p.addConnLocked(key, cc) p.mu.Unlock() } // p.mu must be held func (p *clientConnPool) addConnLocked(key string, cc *ClientConn) { for _, v := range p.conns[key] { if v == cc { return } } if p.conns == nil { p.conns = make(map[string][]*ClientConn) } if p.keys == nil { p.keys = make(map[*ClientConn][]string) } p.conns[key] = append(p.conns[key], cc) p.keys[cc] = append(p.keys[cc], key) } func (p *clientConnPool) MarkDead(cc *ClientConn) { p.mu.Lock() defer p.mu.Unlock() for _, key := range p.keys[cc] { vv, ok := p.conns[key] if !ok { continue } newList := filterOutClientConn(vv, cc) if len(newList) > 0 { p.conns[key] = newList } else { delete(p.conns, key) } } delete(p.keys, cc) } func (p *clientConnPool) closeIdleConnections() { p.mu.Lock() defer p.mu.Unlock() // TODO: don't close a cc if it was just added to the pool // milliseconds ago and has never been used. There's currently // a small race window with the HTTP/1 Transport's integration // where it can add an idle conn just before using it, and // somebody else can concurrently call CloseIdleConns and // break some caller's RoundTrip. for _, vv := range p.conns { for _, cc := range vv { cc.closeIfIdle() } } } func filterOutClientConn(in []*ClientConn, exclude *ClientConn) []*ClientConn { out := in[:0] for _, v := range in { if v != exclude { out = append(out, v) } } // If we filtered it out, zero out the last item to prevent // the GC from seeing it. if len(in) != len(out) { in[len(in)-1] = nil } return out } <|start_filename|>netmaster/master/consts.go<|end_filename|> /*** Copyright 2014 Cisco Systems 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. */ package master const ( //GetVersionRESTEndpoint is the REST endpoint to get version info GetVersionRESTEndpoint = "version" // GetInfoRESTEndpoint is the REST endpoint to get netmaster info GetInfoRESTEndpoint = "info" //GetServiceRESTEndpoint is the REST endpoint to get service info of a service GetServiceRESTEndpoint = "service" //GetServicesRESTEndpoint is the REST endpoint to request info of all services GetServicesRESTEndpoint = "services" ) <|start_filename|>vendor/github.com/osrg/gobgp/server/bmp.go<|end_filename|> // Copyright (C) 2015-2016 Nippon Telegraph and Telephone Corporation. // // 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 server import ( "fmt" log "github.com/Sirupsen/logrus" "github.com/osrg/gobgp/config" "github.com/osrg/gobgp/packet/bgp" "github.com/osrg/gobgp/packet/bmp" "github.com/osrg/gobgp/table" "net" "strconv" "time" ) func (b *bmpClient) tryConnect() *net.TCPConn { interval := 1 for { log.WithFields(log.Fields{"Topic": "bmp"}).Debugf("Connecting BMP server:%s", b.host) conn, err := net.Dial("tcp", b.host) if err != nil { select { case <-b.dead: return nil default: } time.Sleep(time.Duration(interval) * time.Second) if interval < 30 { interval *= 2 } } else { log.WithFields(log.Fields{"Topic": "bmp"}).Infof("BMP server is connected:%s", b.host) return conn.(*net.TCPConn) } } } func (b *bmpClient) Stop() { close(b.dead) } func (b *bmpClient) loop() { for { conn := b.tryConnect() if conn == nil { break } if func() bool { ops := []WatchOption{WatchPeerState(true)} if b.typ != config.BMP_ROUTE_MONITORING_POLICY_TYPE_POST_POLICY { ops = append(ops, WatchUpdate(true)) } else if b.typ != config.BMP_ROUTE_MONITORING_POLICY_TYPE_PRE_POLICY { ops = append(ops, WatchPostUpdate(true)) } w := b.s.Watch(ops...) defer w.Stop() write := func(msg *bmp.BMPMessage) error { buf, _ := msg.Serialize() _, err := conn.Write(buf) if err != nil { log.Warnf("failed to write to bmp server %s", b.host) } return err } if err := write(bmp.NewBMPInitiation([]bmp.BMPTLV{})); err != nil { return false } for { select { case ev := <-w.Event(): switch msg := ev.(type) { case *WatchEventUpdate: info := &table.PeerInfo{ Address: msg.PeerAddress, AS: msg.PeerAS, ID: msg.PeerID, } if err := write(bmpPeerRoute(bmp.BMP_PEER_TYPE_GLOBAL, msg.PostPolicy, 0, info, msg.Timestamp.Unix(), msg.Payload)); err != nil { return false } case *WatchEventPeerState: info := &table.PeerInfo{ Address: msg.PeerAddress, AS: msg.PeerAS, ID: msg.PeerID, } if msg.State == bgp.BGP_FSM_ESTABLISHED { if err := write(bmpPeerUp(msg.LocalAddress.String(), msg.LocalPort, msg.PeerPort, msg.SentOpen, msg.RecvOpen, bmp.BMP_PEER_TYPE_GLOBAL, false, 0, info, msg.Timestamp.Unix())); err != nil { return false } } else { if err := write(bmpPeerDown(bmp.BMP_PEER_DOWN_REASON_UNKNOWN, bmp.BMP_PEER_TYPE_GLOBAL, false, 0, info, msg.Timestamp.Unix())); err != nil { return false } } } case <-b.dead: conn.Close() return true } } }() { return } } } type bmpClient struct { s *BgpServer dead chan struct{} host string typ config.BmpRouteMonitoringPolicyType } func bmpPeerUp(laddr string, lport, rport uint16, sent, recv *bgp.BGPMessage, t uint8, policy bool, pd uint64, peeri *table.PeerInfo, timestamp int64) *bmp.BMPMessage { ph := bmp.NewBMPPeerHeader(t, policy, pd, peeri.Address.String(), peeri.AS, peeri.ID.String(), float64(timestamp)) return bmp.NewBMPPeerUpNotification(*ph, laddr, lport, rport, sent, recv) } func bmpPeerDown(reason uint8, t uint8, policy bool, pd uint64, peeri *table.PeerInfo, timestamp int64) *bmp.BMPMessage { ph := bmp.NewBMPPeerHeader(t, policy, pd, peeri.Address.String(), peeri.AS, peeri.ID.String(), float64(timestamp)) return bmp.NewBMPPeerDownNotification(*ph, reason, nil, []byte{}) } func bmpPeerRoute(t uint8, policy bool, pd uint64, peeri *table.PeerInfo, timestamp int64, payload []byte) *bmp.BMPMessage { ph := bmp.NewBMPPeerHeader(t, policy, pd, peeri.Address.String(), peeri.AS, peeri.ID.String(), float64(timestamp)) m := bmp.NewBMPRouteMonitoring(*ph, nil) body := m.Body.(*bmp.BMPRouteMonitoring) body.BGPUpdatePayload = payload return m } func (b *bmpClientManager) addServer(c *config.BmpServerConfig) error { host := net.JoinHostPort(c.Address, strconv.Itoa(int(c.Port))) if _, y := b.clientMap[host]; y { return fmt.Errorf("bmp client %s is already configured", host) } b.clientMap[host] = &bmpClient{ s: b.s, dead: make(chan struct{}), host: host, typ: c.RouteMonitoringPolicy, } go b.clientMap[host].loop() return nil } func (b *bmpClientManager) deleteServer(c *config.BmpServerConfig) error { host := net.JoinHostPort(c.Address, strconv.Itoa(int(c.Port))) if c, y := b.clientMap[host]; !y { return fmt.Errorf("bmp client %s isn't found", host) } else { c.Stop() delete(b.clientMap, host) } return nil } type bmpClientManager struct { s *BgpServer clientMap map[string]*bmpClient } func newBmpClientManager(s *BgpServer) *bmpClientManager { return &bmpClientManager{ s: s, clientMap: make(map[string]*bmpClient), } } <|start_filename|>vendor/github.com/contiv/remotessh/Makefile<|end_filename|> all: stop start test make stop deps: go get github.com/tools/godep go get github.com/golang/lint/golint reflex-test: start reflex -r '\.go' make test test: deps start golint godep go test -v -tags vagrant ./... -check.v vagrant ssh host0 -c \ "export GOPATH=/vagrant/:/vagrant/Godeps/_workspace; \ if [ \"${http_proxy}\" != \"\" ]; then export http_proxy=${http_proxy}; fi; \ if [ \"${https_proxy}\" != \"\" ]; then export https_proxy=${https_proxy}; fi; \ cd /vagrant/; \ go test -v -tags baremetal ./... -check.v" golint: deps test -z "$$(golint ./... | tee /dev/stderr)" stop: vagrant destroy -f start: vagrant up --provider virtualbox <|start_filename|>vendor/github.com/osrg/gobgp/config/util.go<|end_filename|> // Copyright (C) 2015 Nippon Telegraph and Telephone Corporation. // // 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 config import ( "fmt" "github.com/osrg/gobgp/packet/bgp" ) func IsConfederationMember(g *Global, p *Neighbor) bool { if p.Config.PeerAs != g.Config.As { for _, member := range g.Confederation.Config.MemberAsList { if member == p.Config.PeerAs { return true } } } return false } func IsEBGPPeer(g *Global, p *Neighbor) bool { return p.Config.PeerAs != g.Config.As } type AfiSafis []AfiSafi func (c AfiSafis) ToRfList() ([]bgp.RouteFamily, error) { rfs := make([]bgp.RouteFamily, 0, len(c)) for _, rf := range c { k, err := bgp.GetRouteFamily(string(rf.Config.AfiSafiName)) if err != nil { return nil, fmt.Errorf("invalid address family: %s", rf.Config.AfiSafiName) } rfs = append(rfs, k) } return rfs, nil } func CreateRfMap(p *Neighbor) map[bgp.RouteFamily]bool { rfs, _ := AfiSafis(p.AfiSafis).ToRfList() rfMap := make(map[bgp.RouteFamily]bool) for _, rf := range rfs { rfMap[rf] = true } return rfMap } func GetAfiSafi(p *Neighbor, family bgp.RouteFamily) *AfiSafi { for _, a := range p.AfiSafis { if string(a.Config.AfiSafiName) == family.String() { return &a } } return nil } func CheckAfiSafisChange(x, y []AfiSafi) bool { if len(x) != len(y) { return true } m := make(map[string]bool) for _, e := range x { m[string(e.Config.AfiSafiName)] = true } for _, e := range y { if !m[string(e.Config.AfiSafiName)] { return true } } return false } <|start_filename|>vendor/github.com/osrg/gobgp/packet/bgp/constant.go<|end_filename|> // Copyright (C) 2014 Nippon Telegraph and Telephone Corporation. // // 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 bgp import ( "fmt" "strings" ) const AS_TRANS = 23456 const BGP_PORT = 179 type FSMState int const ( BGP_FSM_IDLE FSMState = iota BGP_FSM_CONNECT BGP_FSM_ACTIVE BGP_FSM_OPENSENT BGP_FSM_OPENCONFIRM BGP_FSM_ESTABLISHED ) // partially taken from http://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml type Protocol int const ( Unknown Protocol = iota ICMP = 0x01 IGMP = 0x02 TCP = 0x06 EGP = 0x08 IGP = 0x09 UDP = 0x11 RSVP = 0x2e GRE = 0x2f OSPF = 0x59 IPIP = 0x5e PIM = 0x67 SCTP = 0x84 ) var ProtocolNameMap = map[Protocol]string{ Unknown: "unknown", ICMP: "icmp", IGMP: "igmp", TCP: "tcp", EGP: "egp", IGP: "igp", UDP: "udp", RSVP: "rsvp", GRE: "gre", OSPF: "ospf", IPIP: "ipip", PIM: "pim", SCTP: "sctp", } var ProtocolValueMap = map[string]Protocol{ ProtocolNameMap[ICMP]: ICMP, ProtocolNameMap[IGMP]: IGMP, ProtocolNameMap[TCP]: TCP, ProtocolNameMap[EGP]: EGP, ProtocolNameMap[IGP]: IGP, ProtocolNameMap[UDP]: UDP, ProtocolNameMap[RSVP]: RSVP, ProtocolNameMap[GRE]: GRE, ProtocolNameMap[OSPF]: OSPF, ProtocolNameMap[IPIP]: IPIP, ProtocolNameMap[PIM]: PIM, ProtocolNameMap[SCTP]: SCTP, } func (p Protocol) String() string { name, ok := ProtocolNameMap[p] if !ok { return fmt.Sprintf("%d", p) } return name } type TCPFlag int const ( TCP_FLAG_FIN = 0x01 TCP_FLAG_SYN = 0x02 TCP_FLAG_RST = 0x04 TCP_FLAG_PUSH = 0x08 TCP_FLAG_ACK = 0x10 TCP_FLAG_URGENT = 0x20 ) var TCPFlagNameMap = map[TCPFlag]string{ TCP_FLAG_FIN: "fin", TCP_FLAG_SYN: "syn", TCP_FLAG_RST: "rst", TCP_FLAG_PUSH: "push", TCP_FLAG_ACK: "ack", TCP_FLAG_URGENT: "urgent", } var TCPFlagValueMap = map[string]TCPFlag{ TCPFlagNameMap[TCP_FLAG_FIN]: TCP_FLAG_FIN, TCPFlagNameMap[TCP_FLAG_SYN]: TCP_FLAG_SYN, TCPFlagNameMap[TCP_FLAG_RST]: TCP_FLAG_RST, TCPFlagNameMap[TCP_FLAG_PUSH]: TCP_FLAG_PUSH, TCPFlagNameMap[TCP_FLAG_ACK]: TCP_FLAG_ACK, TCPFlagNameMap[TCP_FLAG_URGENT]: TCP_FLAG_URGENT, } func (f TCPFlag) String() string { ss := make([]string, 0, 6) for _, v := range []TCPFlag{TCP_FLAG_FIN, TCP_FLAG_SYN, TCP_FLAG_RST, TCP_FLAG_PUSH, TCP_FLAG_ACK, TCP_FLAG_URGENT} { if f&v > 0 { ss = append(ss, TCPFlagNameMap[v]) } } return strings.Join(ss, "|") } type EthernetType int const ( IPv4 EthernetType = 0x0800 ARP EthernetType = 0x0806 RARP EthernetType = 0x8035 VMTP EthernetType = 0x805B APPLE_TALK EthernetType = 0x809B AARP EthernetType = 0x80F3 IPX EthernetType = 0x8137 SNMP EthernetType = 0x814C NET_BIOS EthernetType = 0x8191 XTP EthernetType = 0x817D IPv6 EthernetType = 0x86DD PPPoE_DISCOVERY EthernetType = 0x8863 PPPoE_SESSION EthernetType = 0x8864 LOOPBACK EthernetType = 0x9000 ) var EthernetTypeNameMap = map[EthernetType]string{ IPv4: "ipv4", ARP: "arp", RARP: "rarp", VMTP: "vmtp", APPLE_TALK: "apple-talk", AARP: "aarp", IPX: "ipx", SNMP: "snmp", NET_BIOS: "net-bios", XTP: "xtp", IPv6: "ipv6", PPPoE_DISCOVERY: "pppoe-discovery", PPPoE_SESSION: "pppoe-session", LOOPBACK: "loopback", } var EthernetTypeValueMap = map[string]EthernetType{ EthernetTypeNameMap[IPv4]: IPv4, EthernetTypeNameMap[ARP]: ARP, EthernetTypeNameMap[RARP]: RARP, EthernetTypeNameMap[VMTP]: VMTP, EthernetTypeNameMap[APPLE_TALK]: APPLE_TALK, EthernetTypeNameMap[AARP]: AARP, EthernetTypeNameMap[IPX]: IPX, EthernetTypeNameMap[SNMP]: SNMP, EthernetTypeNameMap[NET_BIOS]: NET_BIOS, EthernetTypeNameMap[XTP]: XTP, EthernetTypeNameMap[IPv6]: IPv6, EthernetTypeNameMap[PPPoE_DISCOVERY]: PPPoE_DISCOVERY, EthernetTypeNameMap[PPPoE_SESSION]: PPPoE_SESSION, EthernetTypeNameMap[LOOPBACK]: LOOPBACK, } func (t EthernetType) String() string { n, ok := EthernetTypeNameMap[t] if !ok { return fmt.Sprintf("%d", t) } return n } <|start_filename|>vendor/github.com/contiv/objdb/etcdService.go<|end_filename|> /*** Copyright 2014 Cisco Systems 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. */ package objdb import ( "encoding/json" "errors" "strconv" "strings" "time" "golang.org/x/net/context" log "github.com/Sirupsen/logrus" "github.com/coreos/etcd/client" ) // Service state type etcdServiceState struct { ServiceName string // Name of the service KeyName string // Service key name TTL time.Duration // TTL for the service HostAddr string // Host name or IP address where its running Port int // Port number where its listening Hostname string // Host name where its running // Channel to stop ttl refresh stopChan chan bool } // RegisterService Register a service // Service is registered with a ttl for 60sec and a goroutine is created // to refresh the ttl. func (ep *EtcdClient) RegisterService(serviceInfo ServiceInfo) error { keyName := "/contiv.io/service/" + serviceInfo.ServiceName + "/" + serviceInfo.HostAddr + ":" + strconv.Itoa(serviceInfo.Port) ttl := time.Duration(serviceInfo.TTL) * time.Second log.Infof("Registering service key: %s, value: %+v", keyName, serviceInfo) // if there is a previously registered service, stop refreshing it if ep.serviceDb[keyName] != nil { ep.serviceDb[keyName].stopChan <- true } // JSON format the object jsonVal, err := json.Marshal(serviceInfo) if err != nil { log.Errorf("Json conversion error. Err %v", err) return err } // create service state srvState := etcdServiceState{ ServiceName: serviceInfo.ServiceName, KeyName: keyName, TTL: ttl, HostAddr: serviceInfo.HostAddr, Port: serviceInfo.Port, stopChan: make(chan bool, 1), Hostname: serviceInfo.Hostname, } // Run refresh in background go ep.refreshService(&srvState, string(jsonVal[:])) // Store it in DB ep.serviceDb[keyName] = &srvState return nil } // GetService lists all end points for a service func (ep *EtcdClient) GetService(name string) ([]ServiceInfo, error) { keyName := "/contiv.io/service/" + name + "/" _, srvcList, err := ep.getServiceState(keyName) return srvcList, err } func (ep *EtcdClient) getServiceState(key string) (uint64, []ServiceInfo, error) { var srvcList []ServiceInfo retryCount := 0 // Get the object from etcd client resp, err := ep.kapi.Get(context.Background(), key, &client.GetOptions{Recursive: true, Sort: true}) for err != nil && err.Error() == client.ErrClusterUnavailable.Error() { // Retry after a delay retryCount++ if retryCount%16 == 0 { log.Warnf("%v -- Retrying...", err) } time.Sleep(time.Second) resp, err = ep.kapi.Get(context.Background(), key, &client.GetOptions{Recursive: true, Sort: true}) } if err != nil { if strings.Contains(err.Error(), "Key not found") { return 0, nil, nil } log.Errorf("Error getting key %s. Err: %v", key, err) return 0, nil, err } if !resp.Node.Dir { log.Errorf("Err. Response is not a directory: %+v", resp.Node) return 0, nil, errors.New("Invalid Response from etcd") } // Parse each node in the directory for _, node := range resp.Node.Nodes { var respSrvc ServiceInfo // Parse JSON response err = json.Unmarshal([]byte(node.Value), &respSrvc) if err != nil { log.Errorf("Error parsing object %s, Err %v", node.Value, err) return 0, nil, err } srvcList = append(srvcList, respSrvc) } watchIndex := resp.Index return watchIndex, srvcList, nil } // initServiceState reads the current state and injects it to the channel // additionally, it returns the next index to watch func (ep *EtcdClient) initServiceState(key string, eventCh chan WatchServiceEvent) (uint64, error) { mIndex, srvcList, err := ep.getServiceState(key) if err != nil { return mIndex, err } // walk each service and inject it as an add event for _, srvInfo := range srvcList { log.Debugf("Sending service add event: %+v", srvInfo) // Send Add event eventCh <- WatchServiceEvent{ EventType: WatchServiceEventAdd, ServiceInfo: srvInfo, } } return mIndex, nil } // WatchService Watch for a service func (ep *EtcdClient) WatchService(name string, eventCh chan WatchServiceEvent, stopCh chan bool) error { keyName := "/contiv.io/service/" + name + "/" // Create channels watchCh := make(chan *client.Response, 1) // Create watch context watchCtx, watchCancel := context.WithCancel(context.Background()) // Start the watch thread go func() { // Get current state and etcd index to watch watchIndex, err := ep.initServiceState(keyName, eventCh) if err != nil { log.Fatalf("Unable to watch service key: %s - %v", keyName, err) } log.Infof("Watching for service: %s at index %v", keyName, watchIndex) // Start the watch watcher := ep.kapi.Watcher(keyName, &client.WatcherOptions{AfterIndex: watchIndex, Recursive: true}) if watcher == nil { log.Errorf("Error watching service %s. Etcd returned invalid watcher", keyName) // Emit the event eventCh <- WatchServiceEvent{EventType: WatchServiceEventError} } // Keep getting next event for { // Block till next watch event etcdRsp, err := watcher.Next(watchCtx) if err != nil && err.Error() == client.ErrClusterUnavailable.Error() { log.Infof("Stopping watch on key %s", keyName) return } else if err != nil { log.Errorf("Error %v during watch. Watch thread exiting", err) return } // Send it to watch channel watchCh <- etcdRsp } }() // handle messages from watch service go func() { var srvMap = make(map[string]ServiceInfo) for { select { case watchResp := <-watchCh: var srvInfo ServiceInfo log.Debugf("Received event {%#v}\n Node: {%#v}\n PrevNade: {%#v}", watchResp, watchResp.Node, watchResp.PrevNode) // derive service info from key srvKey := strings.TrimPrefix(watchResp.Node.Key, "/contiv.io/service/") // We ignore all events except Set/Delete/Expire // Note that Set event doesnt exactly mean new service end point. // If a service restarts and re-registers before it expired, we'll // receive set again. receivers need to handle this case if _, ok := srvMap[srvKey]; !ok && watchResp.Action == "set" { // Parse JSON response err := json.Unmarshal([]byte(watchResp.Node.Value), &srvInfo) if err != nil { log.Errorf("Error parsing object %s, Err %v", watchResp.Node.Value, err) break } log.Infof("Sending service add event: %+v", srvInfo) // Send Add event eventCh <- WatchServiceEvent{ EventType: WatchServiceEventAdd, ServiceInfo: srvInfo, } // save it in cache srvMap[srvKey] = srvInfo } else if (watchResp.Action == "delete") || (watchResp.Action == "expire") { // Parse JSON response err := json.Unmarshal([]byte(watchResp.PrevNode.Value), &srvInfo) if err != nil { log.Errorf("Error parsing object %s, Err %v", watchResp.Node.Value, err) break } log.Infof("Sending service del event: %+v", srvInfo) // Send Delete event eventCh <- WatchServiceEvent{ EventType: WatchServiceEventDel, ServiceInfo: srvInfo, } // remove it from cache delete(srvMap, srvKey) } case stopReq := <-stopCh: if stopReq { // Stop watch and return log.Infof("Stopping watch on %s", keyName) watchCancel() return } } } }() return nil } // DeregisterService Deregister a service // This removes the service from the registry and stops the refresh groutine func (ep *EtcdClient) DeregisterService(serviceInfo ServiceInfo) error { keyName := "/contiv.io/service/" + serviceInfo.ServiceName + "/" + serviceInfo.HostAddr + ":" + strconv.Itoa(serviceInfo.Port) // Find it in the database srvState := ep.serviceDb[keyName] if srvState == nil { log.Errorf("Could not find the service in db %s", keyName) return errors.New("Service not found") } // stop the refresh thread and delete service srvState.stopChan <- true delete(ep.serviceDb, keyName) // Delete the service instance _, err := ep.kapi.Delete(context.Background(), keyName, nil) if err != nil { log.Errorf("Error deleting key %s. Err: %v", keyName, err) return err } return nil } // Keep refreshing the service every 30sec func (ep *EtcdClient) refreshService(srvState *etcdServiceState, keyVal string) { // Set it via etcd client _, err := ep.kapi.Set(context.Background(), srvState.KeyName, keyVal, &client.SetOptions{TTL: srvState.TTL}) if err != nil { log.Errorf("Error setting key %s, Err: %v", srvState.KeyName, err) } // Loop forever for { select { case <-time.After(srvState.TTL / 3): log.Debugf("Refreshing key: %s", srvState.KeyName) _, err := ep.kapi.Set(context.Background(), srvState.KeyName, keyVal, &client.SetOptions{TTL: srvState.TTL}) if err != nil { log.Errorf("Error setting key %s, Err: %v", srvState.KeyName, err) } case <-srvState.stopChan: log.Infof("Stop refreshing key: %s", srvState.KeyName) return } } } <|start_filename|>utils/sysutils_test.go<|end_filename|> /*** Copyright 2014 Cisco Systems 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. */ package utils import ( "testing" ) // InitSysAttrs tests fetching the system parameters func InitSysattrs(t *testing.T) { err := FetchSysAttrs() if err != nil { t.Fatalf("failed to fetch system attributes, err %s \n", err) } } // GetOsType tests getting os type from the system func GetOsType(t *testing.T) { if (SysAttrs.OsType == "unspecified") || (SysAttrs.OsType == "") { t.Fatalf("failed to get the proper os type \n") } } <|start_filename|>vendor/github.com/contiv/remotessh/baremetal.go<|end_filename|> /*** Copyright 2014 Cisco Systems 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. */ package remotessh import ( "fmt" log "github.com/Sirupsen/logrus" ) func unexpectedSetupArgError(exptdTypes string, rcvdArgs ...interface{}) error { rcvdTypes := "" for _, arg := range rcvdArgs { rcvdTypes = fmt.Sprintf("%s, %T", rcvdTypes, arg) } return fmt.Errorf("Unexpected args to Setup(). Expected: %s, Received: %s", rcvdTypes, exptdTypes) } // HostInfo contains host specific connectivity info for setting up testbed node type HostInfo struct { Name string SSHAddr string SSHPort string User string PrivKeyFile string Env []string } // Baremetal implements a host based testbed type Baremetal struct { nodes map[string]TestbedNode } // setup implement baremetal testbed specific initilization. It takes a list of // connectivity infos about the hosts and initilizes ssh client state used by tests. func (b *Baremetal) setup(hosts []HostInfo) error { b.nodes = make(map[string]TestbedNode) for _, h := range hosts { log.Infof("Adding node: %q(%s:%s:%s:%s)", h.Name, h.SSHAddr, h.SSHPort, h.User, h.PrivKeyFile) var ( node *SSHNode err error ) if node, err = NewSSHNode(h.Name, h.User, h.Env, h.SSHAddr, h.SSHPort, h.PrivKeyFile); err != nil { return err } b.nodes[node.GetName()] = TestbedNode(node) } return nil } // Setup initializes a baremetal testbed. func (b *Baremetal) Setup(args ...interface{}) error { if _, ok := args[0].([]HostInfo); !ok { return unexpectedSetupArgError("[]remotessh.HostInfo", args...) } return b.setup(args[0].([]HostInfo)) } // Teardown cleans up a baremetal testbed. func (b *Baremetal) Teardown() { for _, node := range b.nodes { vnode, ok := node.(*SSHNode) if !ok { log.Errorf("invalid node type encountered: %T", vnode) continue } vnode.Cleanup() } b.nodes = nil } // GetNode obtains a node by name. The name is the name of the host provided at // the time of testbed Setup. func (b *Baremetal) GetNode(name string) TestbedNode { return b.nodes[name] } // GetNodes returns the nodes in a baremetal setup, returned sequentially. func (b *Baremetal) GetNodes() []TestbedNode { var ret []TestbedNode for _, value := range b.nodes { ret = append(ret, value) } return ret } // IterateNodes walks each host and executes the function supplied. On error, // it waits for all hosts to complete before returning the error, if any. func (b *Baremetal) IterateNodes(fn func(TestbedNode) error) error { return iterateNodes(b, fn) } // SSHExecAllNodes will ssh into each host and run the specified command. func (b *Baremetal) SSHExecAllNodes(cmd string) error { return sshExecAllNodes(b, cmd) } <|start_filename|>vendor/github.com/samalba/dockerclient/tls.go<|end_filename|> package dockerclient import ( "crypto/tls" "crypto/x509" "errors" "io/ioutil" "path/filepath" ) // TLSConfigFromCertPath returns a configuration based on PEM files in the directory // // path is usually what is set by the environment variable `DOCKER_CERT_PATH`, // or `$HOME/.docker`. func TLSConfigFromCertPath(path string) (*tls.Config, error) { cert, err := ioutil.ReadFile(filepath.Join(path, "cert.pem")) if err != nil { return nil, err } key, err := ioutil.ReadFile(filepath.Join(path, "key.pem")) if err != nil { return nil, err } ca, err := ioutil.ReadFile(filepath.Join(path, "ca.pem")) if err != nil { return nil, err } tlsCert, err := tls.X509KeyPair(cert, key) if err != nil { return nil, err } tlsConfig := &tls.Config{Certificates: []tls.Certificate{tlsCert}} tlsConfig.RootCAs = x509.NewCertPool() if !tlsConfig.RootCAs.AppendCertsFromPEM(ca) { return nil, errors.New("Could not add RootCA pem") } return tlsConfig, nil } <|start_filename|>netmaster/mastercfg/bgpState_test.go<|end_filename|> /*** Copyright 2014 Cisco Systems 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. */ package mastercfg import ( "testing" "github.com/contiv/netplugin/core" ) const ( testhostID = "contivhost" bgpCfgKey = bgpConfigPathPrefix + testhostID ) type testBgpStateDriver struct{} var bgpStateDriver = &testBgpStateDriver{} func (d *testBgpStateDriver) Init(instInfo *core.InstanceInfo) error { return core.Errorf("Shouldn't be called!") } func (d *testBgpStateDriver) Deinit() { } func (d *testBgpStateDriver) Write(key string, value []byte) error { return core.Errorf("Shouldn't be called!") } func (d *testBgpStateDriver) Read(key string) ([]byte, error) { return []byte{}, core.Errorf("Shouldn't be called!") } func (d *testBgpStateDriver) ReadAll(baseKey string) ([][]byte, error) { return [][]byte{}, core.Errorf("Shouldn't be called!") } func (d *testBgpStateDriver) WatchAll(baseKey string, rsps chan [2][]byte) error { return core.Errorf("not supported") } func (d *testBgpStateDriver) validateKey(key string) error { if key != bgpCfgKey { return core.Errorf("Unexpected key. recvd: %s expected: %s ", key, bgpCfgKey) } return nil } func (d *testBgpStateDriver) ClearState(key string) error { return d.validateKey(key) } func (d *testBgpStateDriver) ReadState(key string, value core.State, unmarshal func([]byte, interface{}) error) error { return d.validateKey(key) } func (d *testBgpStateDriver) ReadAllState(key string, value core.State, unmarshal func([]byte, interface{}) error) ([]core.State, error) { return nil, core.Errorf("Shouldn't be called!") } func (d *testBgpStateDriver) WatchAllState(baseKey string, sType core.State, unmarshal func([]byte, interface{}) error, rsps chan core.WatchState) error { return core.Errorf("not supported") } func (d *testBgpStateDriver) WriteState(key string, value core.State, marshal func(interface{}) ([]byte, error)) error { return d.validateKey(key) } func TestCfgBgpStateRead(t *testing.T) { bgpCfg := &CfgBgpState{} bgpCfg.StateDriver = bgpStateDriver err := bgpCfg.Read(testhostID) if err != nil { t.Fatalf("read config state failed. Error: %s", err) } } func TestCfgBgpStateWrite(t *testing.T) { bgpCfg := &CfgBgpState{} bgpCfg.StateDriver = bgpStateDriver bgpCfg.Hostname = testhostID err := bgpCfg.Write() if err != nil { t.Fatalf("write config state failed. Error: %s", err) } } func TestCfgBgpStateClear(t *testing.T) { bgpCfg := &CfgBgpState{} bgpCfg.StateDriver = bgpStateDriver bgpCfg.Hostname = testhostID err := bgpCfg.Clear() if err != nil { t.Fatalf("clear config state failed. Error: %s", err) } } <|start_filename|>vendor/github.com/contiv/libovsdb/uuid.go<|end_filename|> package libovsdb import ( "encoding/json" "errors" "regexp" ) type UUID struct { GoUuid string `json:"uuid"` } // <set> notation requires special marshaling func (u UUID) MarshalJSON() ([]byte, error) { var uuidSlice []string err := u.validateUUID() if err == nil { uuidSlice = []string{"uuid", u.GoUuid} } else { uuidSlice = []string{"named-uuid", u.GoUuid} } return json.Marshal(uuidSlice) } func (u *UUID) UnmarshalJSON(b []byte) (err error) { var ovsUuid []string if err := json.Unmarshal(b, &ovsUuid); err == nil { u.GoUuid = ovsUuid[1] } return err } func (u UUID) validateUUID() error { if len(u.GoUuid) != 36 { return errors.New("uuid exceeds 36 characters") } var validUUID = regexp.MustCompile(`^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$`) if !validUUID.MatchString(u.GoUuid) { return errors.New("uuid does not match regexp") } return nil } <|start_filename|>vendor/github.com/contiv/remotessh/testbed.go<|end_filename|> /*** Copyright 2015 Cisco Systems 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. */ package remotessh // Testbed is a collection of test nodes type Testbed interface { Setup(args ...interface{}) error Teardown() GetNodes() []TestbedNode GetNode(name string) TestbedNode IterateNodes(fn func(TestbedNode) error) error } func iterateNodes(tb Testbed, fn func(TestbedNode) error) error { nodes := tb.GetNodes() errChan := make(chan error, len(nodes)) for _, node := range nodes { go func(node TestbedNode) { errChan <- fn(node) }(node) } var err error for range nodes { if chanerr := <-errChan; chanerr != nil { err = chanerr } } return err } func sshExecAllNodes(tb Testbed, cmd string) error { return tb.IterateNodes(func(node TestbedNode) error { return node.RunCommand(cmd) }) } <|start_filename|>core/state.go<|end_filename|> package core // State identifies data uniquely identifiable by 'id' and stored in a // (distributed) key-value store implemented by core.StateDriver. type State interface { Read(id string) error ReadAll() ([]State, error) Write() error Clear() error } // WatchableState allows for the rest of core.State, plus the WatchAll call // which allows the implementor to yield changes to a channel. type WatchableState interface { State WatchAll(rsps chan WatchState) error } // CommonState defines the fields common to all core.State implementations. // This struct shall be embedded as anonymous field in all structs that // implement core.State type CommonState struct { StateDriver StateDriver `json:"-"` ID string `json:"id"` } <|start_filename|>vendor/github.com/docker/engine-api/types/reference/image_reference.go<|end_filename|> package reference import ( distreference "github.com/docker/distribution/reference" ) // Parse parses the given references and return the repository and // tag (if present) from it. If there is an error during parsing, it will // return an error. func Parse(ref string) (string, string, error) { distributionRef, err := distreference.ParseNamed(ref) if err != nil { return "", "", err } tag := GetTagFromNamedRef(distributionRef) return distributionRef.Name(), tag, nil } // GetTagFromNamedRef returns a tag from the specified reference. // This function is necessary as long as the docker "server" api make the distinction between repository // and tags. func GetTagFromNamedRef(ref distreference.Named) string { var tag string switch x := ref.(type) { case distreference.Digested: tag = x.Digest().String() case distreference.NamedTagged: tag = x.Tag() } return tag } <|start_filename|>utils/lldp.go<|end_filename|> /*** Copyright 2015 Cisco Systems 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. */ package utils import ( "strings" log "github.com/Sirupsen/logrus" "github.com/contiv/netplugin/core" ) const ( invalidAttr = "" lldpadContainerName = "lldpad" ) // Implement utilities to fetch lldp information aobut connecting neighbors. // The lldp information can be used in non cloud environment to automate // networking configuration on the physical devices // LLDPNeighbor lists the neighbor attributes as learned by the host type LLDPNeighbor struct { SystemName string SystemDescription string PortID string PortDesc string CiscoACIPodID string CiscoACINodeID string } /* FIXME: Migrate this to samalba/dockerclient // FetchLLDPInfo reads the lldp information using lldptool // A native go lib could be done but it requires that lldpad daemon is // accessible natively on the lldp ipc path func FetchLLDPInfo(crt *crt.CRT, ifname string) (*LLDPNeighbor, error) { lldp := &LLDPNeighbor{} if crt.GetContainerID(lldpadContainerName) == "" { log.Errorf("Unable to fetch %q container information - please check if it is running", lldpadContainerName) return nil, core.Errorf("unable to fetch container %s info", lldpadContainerName) } cmdWithArgs := []string{"lldptool", "-n", "-t", "-i", ifname} output, err := crt.ExecContainer(lldpadContainerName, cmdWithArgs...) if err != nil { log.Errorf("Error reading lldp information. Error: %s Output: \n%s", err, output) return nil, err } err = parseLLDPArgs(string(output), lldp) return lldp, err } */ func parseLLDPArgs(lldpToolOutput string, lldp *LLDPNeighbor) error { var err error lines := strings.Split(lldpToolOutput, "\n") maxIdx := len(lines) - 1 for idx := 0; idx < maxIdx; { line := strings.Trim(lines[idx], "\n") idx++ if !strings.Contains(line, "TLV") || strings.Contains(line, "End of LLDPDU TLV") { continue } attrIdx := idx for !strings.Contains(lines[attrIdx], "TLV") && attrIdx <= maxIdx { lines[attrIdx] = strings.Trim(lines[attrIdx], "\n") attrIdx++ } tlvLines := lines[idx:attrIdx] idx = attrIdx err = nil switch { case strings.Contains(line, "System Name TLV"): lldp.SystemName, err = lldpReadSystemName(tlvLines) case strings.Contains(line, "System Description TLV"): lldp.SystemDescription, err = lldpReadSystemDescription(tlvLines) case strings.Contains(line, "Port ID TLV"): lldp.PortID, err = lldpReadPortID(tlvLines) case strings.Contains(line, "Port Description TLV"): lldp.PortDesc, err = lldpReadPortDescription(tlvLines) } if err != nil { log.Errorf("Error parsing lldp information. Error '%v'", err) } } err = deriveLLDPArgs(lldp) if err != nil { log.Errorf("Error parsing lldp information. Error '%v'", err) } return err } func deriveLLDPArgs(lldp *LLDPNeighbor) error { var err error lldp.CiscoACIPodID, err = lldpReadACIPodID(lldp.SystemDescription) if err != nil { log.Errorf("Error parsing lldp information. Error '%v'", err) } lldp.CiscoACINodeID, err = lldpReadACINodeID(lldp.SystemDescription) if err != nil { log.Errorf("Error parsing lldp information. Error '%v'", err) } return err } func lldpReadSystemName(attrLines []string) (string, error) { if len(attrLines) < 1 { return invalidAttr, core.Errorf("empty attributes") } return strings.Trim(attrLines[0], " "), nil } func lldpReadSystemDescription(attrLines []string) (string, error) { if len(attrLines) < 1 { return invalidAttr, core.Errorf("empty attributes") } return strings.Trim(attrLines[0], " "), nil } func lldpReadPortID(attrLines []string) (string, error) { if len(attrLines) < 1 { return invalidAttr, core.Errorf("empty attributes") } words := strings.Split(attrLines[0], ":") portID := "" if len(words) >= 2 { portID = strings.Trim(words[1], " ") } return portID, nil } func lldpReadPortDescription(attrLines []string) (string, error) { if len(attrLines) < 1 { return invalidAttr, core.Errorf("empty attributes") } return strings.Trim(attrLines[0], " "), nil } func lldpReadACIPodID(systemDesc string) (string, error) { if !strings.Contains(systemDesc, "pod-") { return invalidAttr, core.Errorf("unable to parse pod id from sysname") } words := strings.Split(systemDesc, "/") podID := "" if len(words) >= 2 { podID = strings.Split(words[1], "-")[1] } return podID, nil } func lldpReadACINodeID(systemDesc string) (string, error) { if !strings.Contains(systemDesc, "node-") { return invalidAttr, core.Errorf("unable to parse node id from sysname") } words := strings.Split(systemDesc, "/") nodeID := "" if len(words) >= 2 { nodeID = strings.Split(words[2], "-")[1] } return nodeID, nil } <|start_filename|>mgmtfn/mesosplugin/cniapi/cniapi.go<|end_filename|> /*** Copyright 2016 Cisco Systems 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. */ // CNI API definitions shared between the Mesos plugin and netplugin package cniapi // PluginPath : netplugin socket dir const PluginPath = "/run/contiv" // ContivMesosSocket : netplugin socket file const ContivMesosSocket = "/run/contiv/contiv-mesos.sock" // MesosNwIntfAdd : endpoint handling network interface add const MesosNwIntfAdd = "/MesosNwIntfAdd" // MesosNwIntfDel : endpoint handling network interface delete const MesosNwIntfDel = "/MesosNwIntfDel" // NetworkLabel : network labels from Mesos type NetworkLabel struct { Key string `json:"key,omitempty"` Value string `json:"value,omitempty"` } // NetpluginLabel : netplugin labels type NetpluginLabel struct { TenantName string `json:"io.contiv.tenant,omitempty"` NetworkName string `json:"io.contiv.network,omitempty"` NetworkGroup string `json:"io.contiv.net-group,omitempty"` } // CniCmdReqAttr contains CNI attributes passed to netplugin type CniCmdReqAttr struct { CniIfname string `json:"cni_ifname,omitempty"` CniNetns string `json:"cni_netns,omitempty"` CniContainerid string `json:"cni_containerid,omitempty"` Labels NetpluginLabel `json:"labels,omitempty"` } /* * based on CNI Spec https://github.com/containernetworking/cni/blob/master/SPEC.md * version: * @tomdee * SPEC: introduce "args" field and new error code * tomdee committed on Jun 13 */ const ( // CniStatusSuccess : success return code CniStatusSuccess = 0 // CniStatusErrorIncompatibleVersion : error return code CniStatusErrorIncompatibleVersion = 1 // CniStatusErrorUnsupportedField : error return code CniStatusErrorUnsupportedField = 2 // LabelTenantName : contiv tenant label LabelTenantName = "io.contiv.tenant" // LabelNetworkName : contiv network label LabelNetworkName = "io.contiv.network" // LabelNetworkGroup : contiv group label LabelNetworkGroup = "io.contiv.net-group" // CniDefaultVersion : CNI version CniDefaultVersion = "0.2" // EnvVarMesosAgent : MESOS env. variable EnvVarMesosAgent = "MESOS_AGENT_ENDPOINT" // CniCmdAdd : CNI commands CniCmdAdd = "ADD" // CniCmdDel : CNI commands CniCmdDel = "DEL" ) // CniIpaddr contains ip/gwy/route from netplugin type CniIpaddr struct { IPAddress string `json:"ip"` Gateway string `json:"gateway,omitempty"` Routes []string `json:"routes,omitempty"` } // CniDNS contains DNS information from netplugin type CniDNS struct { NameServers []string `json:"nameservers,omitempty"` Domain string `json:"domain,omitempty"` Search []string `json:"search,omitempty"` Options []string `json:"options,omitempty"` } // CniCmdErrorResp contains error message from netplugin type CniCmdErrorResp struct { CniVersion string `json:"cniVersion,omitempty"` ErrCode int32 `json:"code,omitempty"` ErrMsg string `json:"msg,omitempty"` ErrDetails string `json:"details,omitempty"` } // CniCmdSuccessResp contains the response from netplugin type CniCmdSuccessResp struct { CniVersion string `json:"cniVersion,omitempty"` IP4 CniIpaddr `json:"ip4"` IP6 CniIpaddr `json:"ip6"` DNS CniDNS `json:"dns,omitempty"` } <|start_filename|>netmaster/mastercfg/servicelbState.go<|end_filename|> /*** Copyright 2014 Cisco Systems 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. */ package mastercfg import ( "encoding/json" "fmt" "github.com/contiv/netplugin/core" "sync" ) const ( serviceLBConfigPathPrefix = StateConfigPath + "serviceLB/" serviceLBConfigPath = serviceLBConfigPathPrefix + "%s" ) //ServiceLBInfo holds service information type ServiceLBInfo struct { ServiceName string //Service name IPAddress string //Service IP Tenant string //Tenant name of the service Network string // service network Ports []string //Service_port:Provider_port:protocol Selectors map[string]string // selector labels associated with a service Providers map[string]*Provider //map of providers for a service keyed by provider ip } //ServiceLBDb is map of all services var ServiceLBDb = make(map[string]*ServiceLBInfo) //DB for all services keyed by servicename.tenant //SvcMutex is mutex for service transaction var SvcMutex sync.RWMutex // CfgServiceLBState is the service object configuration type CfgServiceLBState struct { core.CommonState ServiceName string `json:"servicename"` Tenant string `json:"tenantname"` Network string `json:"subnet"` Ports []string `json:"ports"` Selectors map[string]string `json:"selectors"` IPAddress string `json:"ipaddress"` Providers map[string]*Provider `json:"providers"` } // Write the state func (s *CfgServiceLBState) Write() error { key := fmt.Sprintf(serviceLBConfigPath, s.ID) err := s.StateDriver.WriteState(key, s, json.Marshal) return err } // Read the state in for a given ID. func (s *CfgServiceLBState) Read(id string) error { key := fmt.Sprintf(serviceLBConfigPath, id) err := s.StateDriver.ReadState(key, s, json.Unmarshal) return err } // ReadAll reads all the state for master bgp configurations and returns it. func (s *CfgServiceLBState) ReadAll() ([]core.State, error) { return s.StateDriver.ReadAllState(serviceLBConfigPathPrefix, s, json.Unmarshal) } // Clear removes the configuration from the state store. func (s *CfgServiceLBState) Clear() error { key := fmt.Sprintf(serviceLBConfigPath, s.ID) err := s.StateDriver.ClearState(key) return err } // WatchAll state transitions and send them through the channel. func (s *CfgServiceLBState) WatchAll(rsps chan core.WatchState) error { return s.StateDriver.WatchAllState(serviceLBConfigPathPrefix, s, json.Unmarshal, rsps) } <|start_filename|>netmaster/mastercfg/providerState.go<|end_filename|> /*** Copyright 2014 Cisco Systems 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. */ package mastercfg import ( "encoding/json" "fmt" "github.com/contiv/netplugin/core" ) const ( svcProviderPathPrefix = StateConfigPath + "provider/" svcProviderPath = svcProviderPathPrefix + "%s" ) //SvcProvider holds service information type SvcProvider struct { core.CommonState ServiceName string Providers []string } //ProviderDb is map of providers for a service keyed by provider ip var ProviderDb = make(map[string]*Provider) //Provider has providers info type Provider struct { IPAddress string // provider IP ContainerID string // container id Labels map[string]string // lables Tenant string Network string Services []string Container string //container endpoint id EpIDKey string } // Write the state func (s *SvcProvider) Write() error { key := fmt.Sprintf(svcProviderPath, s.ID) err := s.StateDriver.WriteState(key, s, json.Marshal) return err } // Read the state in for a given ID. func (s *SvcProvider) Read(id string) error { key := fmt.Sprintf(svcProviderPath, id) err := s.StateDriver.ReadState(key, s, json.Unmarshal) return err } // ReadAll reads all the state for master bgp configurations and returns it. func (s *SvcProvider) ReadAll() ([]core.State, error) { return s.StateDriver.ReadAllState(svcProviderPathPrefix, s, json.Unmarshal) } // Clear removes the configuration from the state store. func (s *SvcProvider) Clear() error { key := fmt.Sprintf(svcProviderPath, s.ID) err := s.StateDriver.ClearState(key) return err } // WatchAll state transitions and send them through the channel. func (s *SvcProvider) WatchAll(rsps chan core.WatchState) error { return s.StateDriver.WatchAllState(svcProviderPathPrefix, s, json.Unmarshal, rsps) } <|start_filename|>vagrant/mesos-cni/Makefile<|end_filename|> .PHONY : mesos-cni-demo mesos-cni-destroy mesos-cni-demo: mesos-cni-destroy vagrant up && vagrant ssh mesos-node1 -c 'cd /opt/gopath/src/github.com/contiv/netplugin && make host-restart' mesos-cni-destroy: vagrant destroy -f <|start_filename|>vendor/github.com/contiv/objdb/etcdLock.go<|end_filename|> package objdb import ( "strings" "sync" "time" "golang.org/x/net/context" log "github.com/Sirupsen/logrus" "github.com/coreos/etcd/client" ) // Lock object type etcdLock struct { name string myID string isAcquired bool isReleased bool holderID string ttl time.Duration timeout uint64 eventChan chan LockEvent stopChan chan bool watchCh chan *client.Response watchCtx context.Context watchCancel context.CancelFunc kapi client.KeysAPI mutex *sync.Mutex } // NewLock Create a new lock func (ep *EtcdClient) NewLock(name string, myID string, ttl uint64) (LockInterface, error) { watchCtx, watchCancel := context.WithCancel(context.Background()) // Create a lock return &etcdLock{ name: name, myID: myID, ttl: time.Duration(ttl) * time.Second, kapi: ep.kapi, eventChan: make(chan LockEvent, 1), stopChan: make(chan bool, 1), watchCh: make(chan *client.Response, 1), watchCtx: watchCtx, watchCancel: watchCancel, mutex: new(sync.Mutex), }, nil } // Acquire a lock func (lk *etcdLock) Acquire(timeout uint64) error { lk.mutex.Lock() defer lk.mutex.Unlock() lk.timeout = timeout // Acquire in background go lk.acquireLock() return nil } // Release a lock func (lk *etcdLock) Release() error { keyName := "/contiv.io/lock/" + lk.name lk.mutex.Lock() defer lk.mutex.Unlock() // Mark this as released lk.isReleased = true // Send stop signal on stop channel lk.stopChan <- true // If the lock was acquired, release it if lk.isAcquired { // Delete the lock entry resp, err := lk.kapi.Delete(context.Background(), keyName, &client.DeleteOptions{PrevValue: lk.myID}) if err != nil { log.Errorf("Error Deleting key. Err: %v", err) } else { log.Infof("Deleted key lock %s, Resp: %+v", keyName, resp) } lk.isAcquired = false } return nil } // Kill Stops a lock without releasing it. // Let the etcd TTL expiry release it // Note: This is for debug/test purposes only func (lk *etcdLock) Kill() error { lk.mutex.Lock() defer lk.mutex.Unlock() // Mark this as released lk.isReleased = true // Send stop signal on stop channel lk.stopChan <- true return nil } // EventChan Returns event channel func (lk *etcdLock) EventChan() <-chan LockEvent { lk.mutex.Lock() defer lk.mutex.Unlock() return lk.eventChan } // IsAcquired Checks if the lock is acquired func (lk *etcdLock) IsAcquired() bool { lk.mutex.Lock() defer lk.mutex.Unlock() return lk.isAcquired } // GetHolder Gets current lock holder's ID func (lk *etcdLock) GetHolder() string { lk.mutex.Lock() defer lk.mutex.Unlock() keyName := "/contiv.io/lock/" + lk.name // Get the current value resp, err := lk.kapi.Get(context.Background(), keyName, nil) if err != nil { log.Warnf("Could not get current holder for lock %s", lk.name) return "" } return resp.Node.Value } // *********************** Internal functions ************* // Try acquiring a lock. // This assumes its called in its own go routine func (lk *etcdLock) acquireLock() { keyName := "/contiv.io/lock/" + lk.name // Start a watch on the lock first so that we dont loose any notifications go lk.watchLock() // Wait in this loop forever till lock times out or released for { log.Infof("Getting the lock %s to see if its acquired", keyName) // Get the key and see if we or someone else has already acquired the lock resp, err := lk.kapi.Get(context.Background(), keyName, &client.GetOptions{Quorum: true}) if err != nil { if !client.IsKeyNotFound(err) { log.Errorf("Error getting the key %s. Err: %v", keyName, err) // Retry after a second in case of error time.Sleep(time.Second) continue } else { log.Infof("Lock %s does not exist. trying to acquire it", keyName) } // Try to acquire the lock resp, err := lk.kapi.Set(context.Background(), keyName, lk.myID, &client.SetOptions{PrevExist: client.PrevNoExist, TTL: lk.ttl}) if err != nil { if _, ok := err.(client.Error); ok && err.(client.Error).Code != client.ErrorCodeNodeExist { log.Errorf("Error creating key %s. Err: %v", keyName, err) } else { log.Infof("Lock %s acquired by someone else", keyName) } } else { log.Debugf("Acquired lock %s. Resp: %#v, Node: %+v", keyName, resp, resp.Node) lk.mutex.Lock() // Successfully acquired the lock lk.isAcquired = true lk.holderID = lk.myID lk.mutex.Unlock() // Send acquired message to event channel lk.eventChan <- LockEvent{EventType: LockAcquired} // refresh it lk.refreshLock() lk.mutex.Lock() // If lock is released, we are done, else go back and try to acquire it if lk.isReleased { lk.mutex.Unlock() return } lk.mutex.Unlock() } } else if resp.Node.Value == lk.myID { log.Debugf("Already Acquired key %s. Resp: %#v, Node: %+v", keyName, resp, resp.Node) lk.mutex.Lock() // We have already acquired the lock. just keep refreshing it lk.isAcquired = true lk.holderID = lk.myID lk.mutex.Unlock() // Send acquired message to event channel lk.eventChan <- LockEvent{EventType: LockAcquired} // Refresh lock lk.refreshLock() lk.mutex.Lock() // If lock is released, we are done, else go back and try to acquire it if lk.isReleased { lk.mutex.Unlock() return } lk.mutex.Unlock() } else if resp.Node.Value != lk.myID { log.Debugf("Lock already acquired by someone else. Resp: %+v, Node: %+v", resp, resp.Node) lk.mutex.Lock() // Set the current holder's ID lk.holderID = resp.Node.Value lk.mutex.Unlock() // Wait for changes on the lock lk.waitForLock() lk.mutex.Lock() if lk.isReleased { lk.mutex.Unlock() return } lk.mutex.Unlock() } } } // We couldnt acquire lock, Wait for changes on the lock func (lk *etcdLock) waitForLock() { // If timeout is not specified, set it to high value timeoutIntvl := time.Second * time.Duration(20000) if lk.timeout != 0 { timeoutIntvl = time.Second * time.Duration(lk.timeout) } log.Infof("Waiting to acquire lock (%s/%s)", lk.name, lk.myID) // Create a timer timer := time.NewTimer(timeoutIntvl) defer timer.Stop() // Wait for changes for { // wait on watch channel for holder to release the lock select { case <-timer.C: lk.mutex.Lock() if lk.timeout != 0 { lk.mutex.Unlock() log.Infof("Lock timeout on lock %s/%s", lk.name, lk.myID) lk.eventChan <- LockEvent{EventType: LockAcquireTimeout} log.Infof("Lock acquire timed out. Stopping lock") lk.watchCancel() // Release the lock lk.Release() return } lk.mutex.Unlock() case watchResp := <-lk.watchCh: if watchResp != nil { log.Debugf("Received watch notification(%s/%s): %+v", lk.name, lk.myID, watchResp) if watchResp.Action == "expire" || watchResp.Action == "delete" || watchResp.Action == "compareAndDelete" { log.Infof("Retrying to acquire lock") return } } case <-lk.stopChan: log.Infof("Stopping lock") lk.watchCancel() return } } } // Refresh lock func (lk *etcdLock) refreshLock() { // Refresh interval is 1/3rd of TTL refreshIntvl := lk.ttl / 3 keyName := "/contiv.io/lock/" + lk.name // Loop forever for { select { case <-time.After(refreshIntvl): // Update TTL on the lock resp, err := lk.kapi.Set(context.Background(), keyName, lk.myID, &client.SetOptions{PrevExist: client.PrevExist, PrevValue: lk.myID, TTL: lk.ttl}) if err != nil { log.Errorf("Error updating TTl. Err: %v", err) lk.mutex.Lock() // We are not master anymore lk.isAcquired = false lk.mutex.Unlock() // Send lock lost event lk.eventChan <- LockEvent{EventType: LockLost} return } log.Debugf("Refreshed TTL on lock %s, Resp: %+v", keyName, resp) case watchResp := <-lk.watchCh: // Since we already acquired the lock, nothing to do here if watchResp != nil { log.Debugf("Received watch notification for(%s/%s): %+v", lk.name, lk.myID, watchResp) // See if we lost the lock if string(watchResp.Node.Value) != lk.myID { log.Infof("Holder %s lost the lock %s", lk.myID, lk.name) lk.mutex.Lock() // We are not master anymore lk.isAcquired = false lk.mutex.Unlock() // Send lock lost event lk.eventChan <- LockEvent{EventType: LockLost} return } } case <-lk.stopChan: log.Infof("Stopping lock") lk.watchCancel() return } } } // Watch for changes on the lock func (lk *etcdLock) watchLock() { keyName := "/contiv.io/lock/" + lk.name watcher := lk.kapi.Watcher(keyName, nil) if watcher == nil { log.Errorf("Error creating the watcher") return } for { resp, err := watcher.Next(lk.watchCtx) if err != nil && (err.Error() == client.ErrClusterUnavailable.Error() || strings.Contains(err.Error(), "context canceled")) { log.Infof("Stopping watch on key %s", keyName) return } else if err != nil { log.Errorf("Error watching the key %s, Err %v.", keyName, err) } else { log.Debugf("Got Watch Resp: %+v", resp) // send the event to watch channel lk.watchCh <- resp } lk.mutex.Lock() // If the lock is released, we are done if lk.isReleased { lk.mutex.Unlock() return } lk.mutex.Unlock() } } <|start_filename|>vendor/github.com/osrg/gobgp/config/bgp_configs.go<|end_filename|> // DO NOT EDIT // generated by pyang using OpenConfig https://github.com/openconfig/public // // Copyright (C) 2014-2016 Nippon Telegraph and Telephone Corporation. // // 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 config import ( "bytes" "fmt" ) func mapkey(index int, name string) string { if name != "" { return name } return fmt.Sprintf("%v", index) } // typedef for typedef openconfig-types:std-regexp type StdRegexp string // typedef for typedef openconfig-types:percentage type Percentage uint8 // typedef for typedef bgp-types:rr-cluster-id-type type RrClusterIdType string // typedef for identity bgp-types:remove-private-as-option type RemovePrivateAsOption string const ( REMOVE_PRIVATE_AS_OPTION_ALL RemovePrivateAsOption = "all" REMOVE_PRIVATE_AS_OPTION_REPLACE RemovePrivateAsOption = "replace" ) var RemovePrivateAsOptionToIntMap = map[RemovePrivateAsOption]int{ REMOVE_PRIVATE_AS_OPTION_ALL: 0, REMOVE_PRIVATE_AS_OPTION_REPLACE: 1, } func (v RemovePrivateAsOption) ToInt() int { i, ok := RemovePrivateAsOptionToIntMap[v] if !ok { return -1 } return i } var IntToRemovePrivateAsOptionMap = map[int]RemovePrivateAsOption{ 0: REMOVE_PRIVATE_AS_OPTION_ALL, 1: REMOVE_PRIVATE_AS_OPTION_REPLACE, } func (v RemovePrivateAsOption) Validate() error { if _, ok := RemovePrivateAsOptionToIntMap[v]; !ok { return fmt.Errorf("invalid RemovePrivateAsOption: %s", v) } return nil } // typedef for typedef bgp-types:bgp-community-regexp-type type BgpCommunityRegexpType StdRegexp // typedef for identity bgp-types:community-type type CommunityType string const ( COMMUNITY_TYPE_STANDARD CommunityType = "standard" COMMUNITY_TYPE_EXTENDED CommunityType = "extended" COMMUNITY_TYPE_BOTH CommunityType = "both" COMMUNITY_TYPE_NONE CommunityType = "none" ) var CommunityTypeToIntMap = map[CommunityType]int{ COMMUNITY_TYPE_STANDARD: 0, COMMUNITY_TYPE_EXTENDED: 1, COMMUNITY_TYPE_BOTH: 2, COMMUNITY_TYPE_NONE: 3, } func (v CommunityType) ToInt() int { i, ok := CommunityTypeToIntMap[v] if !ok { return -1 } return i } var IntToCommunityTypeMap = map[int]CommunityType{ 0: COMMUNITY_TYPE_STANDARD, 1: COMMUNITY_TYPE_EXTENDED, 2: COMMUNITY_TYPE_BOTH, 3: COMMUNITY_TYPE_NONE, } func (v CommunityType) Validate() error { if _, ok := CommunityTypeToIntMap[v]; !ok { return fmt.Errorf("invalid CommunityType: %s", v) } return nil } // typedef for typedef bgp-types:bgp-ext-community-type type BgpExtCommunityType string // typedef for typedef bgp-types:bgp-std-community-type type BgpStdCommunityType string // typedef for identity bgp-types:peer-type type PeerType string const ( PEER_TYPE_INTERNAL PeerType = "internal" PEER_TYPE_EXTERNAL PeerType = "external" ) var PeerTypeToIntMap = map[PeerType]int{ PEER_TYPE_INTERNAL: 0, PEER_TYPE_EXTERNAL: 1, } func (v PeerType) ToInt() int { i, ok := PeerTypeToIntMap[v] if !ok { return -1 } return i } var IntToPeerTypeMap = map[int]PeerType{ 0: PEER_TYPE_INTERNAL, 1: PEER_TYPE_EXTERNAL, } func (v PeerType) Validate() error { if _, ok := PeerTypeToIntMap[v]; !ok { return fmt.Errorf("invalid PeerType: %s", v) } return nil } // typedef for identity bgp-types:bgp-session-direction type BgpSessionDirection string const ( BGP_SESSION_DIRECTION_INBOUND BgpSessionDirection = "inbound" BGP_SESSION_DIRECTION_OUTBOUND BgpSessionDirection = "outbound" ) var BgpSessionDirectionToIntMap = map[BgpSessionDirection]int{ BGP_SESSION_DIRECTION_INBOUND: 0, BGP_SESSION_DIRECTION_OUTBOUND: 1, } func (v BgpSessionDirection) ToInt() int { i, ok := BgpSessionDirectionToIntMap[v] if !ok { return -1 } return i } var IntToBgpSessionDirectionMap = map[int]BgpSessionDirection{ 0: BGP_SESSION_DIRECTION_INBOUND, 1: BGP_SESSION_DIRECTION_OUTBOUND, } func (v BgpSessionDirection) Validate() error { if _, ok := BgpSessionDirectionToIntMap[v]; !ok { return fmt.Errorf("invalid BgpSessionDirection: %s", v) } return nil } // typedef for identity bgp-types:bgp-origin-attr-type type BgpOriginAttrType string const ( BGP_ORIGIN_ATTR_TYPE_IGP BgpOriginAttrType = "igp" BGP_ORIGIN_ATTR_TYPE_EGP BgpOriginAttrType = "egp" BGP_ORIGIN_ATTR_TYPE_INCOMPLETE BgpOriginAttrType = "incomplete" ) var BgpOriginAttrTypeToIntMap = map[BgpOriginAttrType]int{ BGP_ORIGIN_ATTR_TYPE_IGP: 0, BGP_ORIGIN_ATTR_TYPE_EGP: 1, BGP_ORIGIN_ATTR_TYPE_INCOMPLETE: 2, } func (v BgpOriginAttrType) ToInt() int { i, ok := BgpOriginAttrTypeToIntMap[v] if !ok { return -1 } return i } var IntToBgpOriginAttrTypeMap = map[int]BgpOriginAttrType{ 0: BGP_ORIGIN_ATTR_TYPE_IGP, 1: BGP_ORIGIN_ATTR_TYPE_EGP, 2: BGP_ORIGIN_ATTR_TYPE_INCOMPLETE, } func (v BgpOriginAttrType) Validate() error { if _, ok := BgpOriginAttrTypeToIntMap[v]; !ok { return fmt.Errorf("invalid BgpOriginAttrType: %s", v) } return nil } // typedef for identity bgp-types:afi-safi-type type AfiSafiType string const ( AFI_SAFI_TYPE_IPV4_UNICAST AfiSafiType = "ipv4-unicast" AFI_SAFI_TYPE_IPV6_UNICAST AfiSafiType = "ipv6-unicast" AFI_SAFI_TYPE_IPV4_LABELLED_UNICAST AfiSafiType = "ipv4-labelled-unicast" AFI_SAFI_TYPE_IPV6_LABELLED_UNICAST AfiSafiType = "ipv6-labelled-unicast" AFI_SAFI_TYPE_L3VPN_IPV4_UNICAST AfiSafiType = "l3vpn-ipv4-unicast" AFI_SAFI_TYPE_L3VPN_IPV6_UNICAST AfiSafiType = "l3vpn-ipv6-unicast" AFI_SAFI_TYPE_L3VPN_IPV4_MULTICAST AfiSafiType = "l3vpn-ipv4-multicast" AFI_SAFI_TYPE_L3VPN_IPV6_MULTICAST AfiSafiType = "l3vpn-ipv6-multicast" AFI_SAFI_TYPE_L2VPN_VPLS AfiSafiType = "l2vpn-vpls" AFI_SAFI_TYPE_L2VPN_EVPN AfiSafiType = "l2vpn-evpn" AFI_SAFI_TYPE_IPV4_MULTICAST AfiSafiType = "ipv4-multicast" AFI_SAFI_TYPE_IPV6_MULTICAST AfiSafiType = "ipv6-multicast" AFI_SAFI_TYPE_RTC AfiSafiType = "rtc" AFI_SAFI_TYPE_IPV4_ENCAP AfiSafiType = "ipv4-encap" AFI_SAFI_TYPE_IPV6_ENCAP AfiSafiType = "ipv6-encap" AFI_SAFI_TYPE_IPV4_FLOWSPEC AfiSafiType = "ipv4-flowspec" AFI_SAFI_TYPE_L3VPN_IPV4_FLOWSPEC AfiSafiType = "l3vpn-ipv4-flowspec" AFI_SAFI_TYPE_IPV6_FLOWSPEC AfiSafiType = "ipv6-flowspec" AFI_SAFI_TYPE_L3VPN_IPV6_FLOWSPEC AfiSafiType = "l3vpn-ipv6-flowspec" AFI_SAFI_TYPE_L2VPN_FLOWSPEC AfiSafiType = "l2vpn-flowspec" AFI_SAFI_TYPE_OPAQUE AfiSafiType = "opaque" ) var AfiSafiTypeToIntMap = map[AfiSafiType]int{ AFI_SAFI_TYPE_IPV4_UNICAST: 0, AFI_SAFI_TYPE_IPV6_UNICAST: 1, AFI_SAFI_TYPE_IPV4_LABELLED_UNICAST: 2, AFI_SAFI_TYPE_IPV6_LABELLED_UNICAST: 3, AFI_SAFI_TYPE_L3VPN_IPV4_UNICAST: 4, AFI_SAFI_TYPE_L3VPN_IPV6_UNICAST: 5, AFI_SAFI_TYPE_L3VPN_IPV4_MULTICAST: 6, AFI_SAFI_TYPE_L3VPN_IPV6_MULTICAST: 7, AFI_SAFI_TYPE_L2VPN_VPLS: 8, AFI_SAFI_TYPE_L2VPN_EVPN: 9, AFI_SAFI_TYPE_IPV4_MULTICAST: 10, AFI_SAFI_TYPE_IPV6_MULTICAST: 11, AFI_SAFI_TYPE_RTC: 12, AFI_SAFI_TYPE_IPV4_ENCAP: 13, AFI_SAFI_TYPE_IPV6_ENCAP: 14, AFI_SAFI_TYPE_IPV4_FLOWSPEC: 15, AFI_SAFI_TYPE_L3VPN_IPV4_FLOWSPEC: 16, AFI_SAFI_TYPE_IPV6_FLOWSPEC: 17, AFI_SAFI_TYPE_L3VPN_IPV6_FLOWSPEC: 18, AFI_SAFI_TYPE_L2VPN_FLOWSPEC: 19, AFI_SAFI_TYPE_OPAQUE: 20, } func (v AfiSafiType) ToInt() int { i, ok := AfiSafiTypeToIntMap[v] if !ok { return -1 } return i } var IntToAfiSafiTypeMap = map[int]AfiSafiType{ 0: AFI_SAFI_TYPE_IPV4_UNICAST, 1: AFI_SAFI_TYPE_IPV6_UNICAST, 2: AFI_SAFI_TYPE_IPV4_LABELLED_UNICAST, 3: AFI_SAFI_TYPE_IPV6_LABELLED_UNICAST, 4: AFI_SAFI_TYPE_L3VPN_IPV4_UNICAST, 5: AFI_SAFI_TYPE_L3VPN_IPV6_UNICAST, 6: AFI_SAFI_TYPE_L3VPN_IPV4_MULTICAST, 7: AFI_SAFI_TYPE_L3VPN_IPV6_MULTICAST, 8: AFI_SAFI_TYPE_L2VPN_VPLS, 9: AFI_SAFI_TYPE_L2VPN_EVPN, 10: AFI_SAFI_TYPE_IPV4_MULTICAST, 11: AFI_SAFI_TYPE_IPV6_MULTICAST, 12: AFI_SAFI_TYPE_RTC, 13: AFI_SAFI_TYPE_IPV4_ENCAP, 14: AFI_SAFI_TYPE_IPV6_ENCAP, 15: AFI_SAFI_TYPE_IPV4_FLOWSPEC, 16: AFI_SAFI_TYPE_L3VPN_IPV4_FLOWSPEC, 17: AFI_SAFI_TYPE_IPV6_FLOWSPEC, 18: AFI_SAFI_TYPE_L3VPN_IPV6_FLOWSPEC, 19: AFI_SAFI_TYPE_L2VPN_FLOWSPEC, 20: AFI_SAFI_TYPE_OPAQUE, } func (v AfiSafiType) Validate() error { if _, ok := AfiSafiTypeToIntMap[v]; !ok { return fmt.Errorf("invalid AfiSafiType: %s", v) } return nil } // typedef for identity bgp-types:bgp-capability type BgpCapability string const ( BGP_CAPABILITY_MPBGP BgpCapability = "mpbgp" BGP_CAPABILITY_ROUTE_REFRESH BgpCapability = "route-refresh" BGP_CAPABILITY_ASN32 BgpCapability = "asn32" BGP_CAPABILITY_GRACEFUL_RESTART BgpCapability = "graceful-restart" BGP_CAPABILITY_ADD_PATHS BgpCapability = "add-paths" ) var BgpCapabilityToIntMap = map[BgpCapability]int{ BGP_CAPABILITY_MPBGP: 0, BGP_CAPABILITY_ROUTE_REFRESH: 1, BGP_CAPABILITY_ASN32: 2, BGP_CAPABILITY_GRACEFUL_RESTART: 3, BGP_CAPABILITY_ADD_PATHS: 4, } func (v BgpCapability) ToInt() int { i, ok := BgpCapabilityToIntMap[v] if !ok { return -1 } return i } var IntToBgpCapabilityMap = map[int]BgpCapability{ 0: BGP_CAPABILITY_MPBGP, 1: BGP_CAPABILITY_ROUTE_REFRESH, 2: BGP_CAPABILITY_ASN32, 3: BGP_CAPABILITY_GRACEFUL_RESTART, 4: BGP_CAPABILITY_ADD_PATHS, } func (v BgpCapability) Validate() error { if _, ok := BgpCapabilityToIntMap[v]; !ok { return fmt.Errorf("invalid BgpCapability: %s", v) } return nil } // typedef for identity bgp-types:bgp-well-known-std-community type BgpWellKnownStdCommunity string const ( BGP_WELL_KNOWN_STD_COMMUNITY_NO_EXPORT BgpWellKnownStdCommunity = "no_export" BGP_WELL_KNOWN_STD_COMMUNITY_NO_ADVERTISE BgpWellKnownStdCommunity = "no_advertise" BGP_WELL_KNOWN_STD_COMMUNITY_NO_EXPORT_SUBCONFED BgpWellKnownStdCommunity = "no_export_subconfed" BGP_WELL_KNOWN_STD_COMMUNITY_NOPEER BgpWellKnownStdCommunity = "nopeer" ) var BgpWellKnownStdCommunityToIntMap = map[BgpWellKnownStdCommunity]int{ BGP_WELL_KNOWN_STD_COMMUNITY_NO_EXPORT: 0, BGP_WELL_KNOWN_STD_COMMUNITY_NO_ADVERTISE: 1, BGP_WELL_KNOWN_STD_COMMUNITY_NO_EXPORT_SUBCONFED: 2, BGP_WELL_KNOWN_STD_COMMUNITY_NOPEER: 3, } func (v BgpWellKnownStdCommunity) ToInt() int { i, ok := BgpWellKnownStdCommunityToIntMap[v] if !ok { return -1 } return i } var IntToBgpWellKnownStdCommunityMap = map[int]BgpWellKnownStdCommunity{ 0: BGP_WELL_KNOWN_STD_COMMUNITY_NO_EXPORT, 1: BGP_WELL_KNOWN_STD_COMMUNITY_NO_ADVERTISE, 2: BGP_WELL_KNOWN_STD_COMMUNITY_NO_EXPORT_SUBCONFED, 3: BGP_WELL_KNOWN_STD_COMMUNITY_NOPEER, } func (v BgpWellKnownStdCommunity) Validate() error { if _, ok := BgpWellKnownStdCommunityToIntMap[v]; !ok { return fmt.Errorf("invalid BgpWellKnownStdCommunity: %s", v) } return nil } // typedef for identity ptypes:match-set-options-restricted-type type MatchSetOptionsRestrictedType string const ( MATCH_SET_OPTIONS_RESTRICTED_TYPE_ANY MatchSetOptionsRestrictedType = "any" MATCH_SET_OPTIONS_RESTRICTED_TYPE_INVERT MatchSetOptionsRestrictedType = "invert" ) var MatchSetOptionsRestrictedTypeToIntMap = map[MatchSetOptionsRestrictedType]int{ MATCH_SET_OPTIONS_RESTRICTED_TYPE_ANY: 0, MATCH_SET_OPTIONS_RESTRICTED_TYPE_INVERT: 1, } func (v MatchSetOptionsRestrictedType) ToInt() int { i, ok := MatchSetOptionsRestrictedTypeToIntMap[v] if !ok { return -1 } return i } var IntToMatchSetOptionsRestrictedTypeMap = map[int]MatchSetOptionsRestrictedType{ 0: MATCH_SET_OPTIONS_RESTRICTED_TYPE_ANY, 1: MATCH_SET_OPTIONS_RESTRICTED_TYPE_INVERT, } func (v MatchSetOptionsRestrictedType) Validate() error { if _, ok := MatchSetOptionsRestrictedTypeToIntMap[v]; !ok { return fmt.Errorf("invalid MatchSetOptionsRestrictedType: %s", v) } return nil } func (v MatchSetOptionsRestrictedType) Default() MatchSetOptionsRestrictedType { return MATCH_SET_OPTIONS_RESTRICTED_TYPE_ANY } func (v MatchSetOptionsRestrictedType) DefaultAsNeeded() MatchSetOptionsRestrictedType { if string(v) == "" { return v.Default() } return v } // typedef for identity ptypes:match-set-options-type type MatchSetOptionsType string const ( MATCH_SET_OPTIONS_TYPE_ANY MatchSetOptionsType = "any" MATCH_SET_OPTIONS_TYPE_ALL MatchSetOptionsType = "all" MATCH_SET_OPTIONS_TYPE_INVERT MatchSetOptionsType = "invert" ) var MatchSetOptionsTypeToIntMap = map[MatchSetOptionsType]int{ MATCH_SET_OPTIONS_TYPE_ANY: 0, MATCH_SET_OPTIONS_TYPE_ALL: 1, MATCH_SET_OPTIONS_TYPE_INVERT: 2, } func (v MatchSetOptionsType) ToInt() int { i, ok := MatchSetOptionsTypeToIntMap[v] if !ok { return -1 } return i } var IntToMatchSetOptionsTypeMap = map[int]MatchSetOptionsType{ 0: MATCH_SET_OPTIONS_TYPE_ANY, 1: MATCH_SET_OPTIONS_TYPE_ALL, 2: MATCH_SET_OPTIONS_TYPE_INVERT, } func (v MatchSetOptionsType) Validate() error { if _, ok := MatchSetOptionsTypeToIntMap[v]; !ok { return fmt.Errorf("invalid MatchSetOptionsType: %s", v) } return nil } func (v MatchSetOptionsType) Default() MatchSetOptionsType { return MATCH_SET_OPTIONS_TYPE_ANY } func (v MatchSetOptionsType) DefaultAsNeeded() MatchSetOptionsType { if string(v) == "" { return v.Default() } return v } // typedef for typedef ptypes:tag-type type TagType string // typedef for identity ptypes:install-protocol-type type InstallProtocolType string const ( INSTALL_PROTOCOL_TYPE_BGP InstallProtocolType = "bgp" INSTALL_PROTOCOL_TYPE_ISIS InstallProtocolType = "isis" INSTALL_PROTOCOL_TYPE_OSPF InstallProtocolType = "ospf" INSTALL_PROTOCOL_TYPE_OSPF3 InstallProtocolType = "ospf3" INSTALL_PROTOCOL_TYPE_STATIC InstallProtocolType = "static" INSTALL_PROTOCOL_TYPE_DIRECTLY_CONNECTED InstallProtocolType = "directly-connected" INSTALL_PROTOCOL_TYPE_LOCAL_AGGREGATE InstallProtocolType = "local-aggregate" ) var InstallProtocolTypeToIntMap = map[InstallProtocolType]int{ INSTALL_PROTOCOL_TYPE_BGP: 0, INSTALL_PROTOCOL_TYPE_ISIS: 1, INSTALL_PROTOCOL_TYPE_OSPF: 2, INSTALL_PROTOCOL_TYPE_OSPF3: 3, INSTALL_PROTOCOL_TYPE_STATIC: 4, INSTALL_PROTOCOL_TYPE_DIRECTLY_CONNECTED: 5, INSTALL_PROTOCOL_TYPE_LOCAL_AGGREGATE: 6, } func (v InstallProtocolType) ToInt() int { i, ok := InstallProtocolTypeToIntMap[v] if !ok { return -1 } return i } var IntToInstallProtocolTypeMap = map[int]InstallProtocolType{ 0: INSTALL_PROTOCOL_TYPE_BGP, 1: INSTALL_PROTOCOL_TYPE_ISIS, 2: INSTALL_PROTOCOL_TYPE_OSPF, 3: INSTALL_PROTOCOL_TYPE_OSPF3, 4: INSTALL_PROTOCOL_TYPE_STATIC, 5: INSTALL_PROTOCOL_TYPE_DIRECTLY_CONNECTED, 6: INSTALL_PROTOCOL_TYPE_LOCAL_AGGREGATE, } func (v InstallProtocolType) Validate() error { if _, ok := InstallProtocolTypeToIntMap[v]; !ok { return fmt.Errorf("invalid InstallProtocolType: %s", v) } return nil } // typedef for identity ptypes:attribute-comparison type AttributeComparison string const ( ATTRIBUTE_COMPARISON_ATTRIBUTE_EQ AttributeComparison = "attribute-eq" ATTRIBUTE_COMPARISON_ATTRIBUTE_GE AttributeComparison = "attribute-ge" ATTRIBUTE_COMPARISON_ATTRIBUTE_LE AttributeComparison = "attribute-le" ATTRIBUTE_COMPARISON_EQ AttributeComparison = "eq" ATTRIBUTE_COMPARISON_GE AttributeComparison = "ge" ATTRIBUTE_COMPARISON_LE AttributeComparison = "le" ) var AttributeComparisonToIntMap = map[AttributeComparison]int{ ATTRIBUTE_COMPARISON_ATTRIBUTE_EQ: 0, ATTRIBUTE_COMPARISON_ATTRIBUTE_GE: 1, ATTRIBUTE_COMPARISON_ATTRIBUTE_LE: 2, ATTRIBUTE_COMPARISON_EQ: 3, ATTRIBUTE_COMPARISON_GE: 4, ATTRIBUTE_COMPARISON_LE: 5, } func (v AttributeComparison) ToInt() int { i, ok := AttributeComparisonToIntMap[v] if !ok { return -1 } return i } var IntToAttributeComparisonMap = map[int]AttributeComparison{ 0: ATTRIBUTE_COMPARISON_ATTRIBUTE_EQ, 1: ATTRIBUTE_COMPARISON_ATTRIBUTE_GE, 2: ATTRIBUTE_COMPARISON_ATTRIBUTE_LE, 3: ATTRIBUTE_COMPARISON_EQ, 4: ATTRIBUTE_COMPARISON_GE, 5: ATTRIBUTE_COMPARISON_LE, } func (v AttributeComparison) Validate() error { if _, ok := AttributeComparisonToIntMap[v]; !ok { return fmt.Errorf("invalid AttributeComparison: %s", v) } return nil } // typedef for identity rpol:route-type type RouteType string const ( ROUTE_TYPE_NONE RouteType = "none" ROUTE_TYPE_INTERNAL RouteType = "internal" ROUTE_TYPE_EXTERNAL RouteType = "external" ROUTE_TYPE_LOCAL RouteType = "local" ) var RouteTypeToIntMap = map[RouteType]int{ ROUTE_TYPE_NONE: 0, ROUTE_TYPE_INTERNAL: 1, ROUTE_TYPE_EXTERNAL: 2, ROUTE_TYPE_LOCAL: 3, } func (v RouteType) ToInt() int { i, ok := RouteTypeToIntMap[v] if !ok { return -1 } return i } var IntToRouteTypeMap = map[int]RouteType{ 0: ROUTE_TYPE_NONE, 1: ROUTE_TYPE_INTERNAL, 2: ROUTE_TYPE_EXTERNAL, 3: ROUTE_TYPE_LOCAL, } func (v RouteType) Validate() error { if _, ok := RouteTypeToIntMap[v]; !ok { return fmt.Errorf("invalid RouteType: %s", v) } return nil } // typedef for identity rpol:default-policy-type type DefaultPolicyType string const ( DEFAULT_POLICY_TYPE_ACCEPT_ROUTE DefaultPolicyType = "accept-route" DEFAULT_POLICY_TYPE_REJECT_ROUTE DefaultPolicyType = "reject-route" ) var DefaultPolicyTypeToIntMap = map[DefaultPolicyType]int{ DEFAULT_POLICY_TYPE_ACCEPT_ROUTE: 0, DEFAULT_POLICY_TYPE_REJECT_ROUTE: 1, } func (v DefaultPolicyType) ToInt() int { i, ok := DefaultPolicyTypeToIntMap[v] if !ok { return -1 } return i } var IntToDefaultPolicyTypeMap = map[int]DefaultPolicyType{ 0: DEFAULT_POLICY_TYPE_ACCEPT_ROUTE, 1: DEFAULT_POLICY_TYPE_REJECT_ROUTE, } func (v DefaultPolicyType) Validate() error { if _, ok := DefaultPolicyTypeToIntMap[v]; !ok { return fmt.Errorf("invalid DefaultPolicyType: %s", v) } return nil } // typedef for identity bgp:session-state type SessionState string const ( SESSION_STATE_IDLE SessionState = "idle" SESSION_STATE_CONNECT SessionState = "connect" SESSION_STATE_ACTIVE SessionState = "active" SESSION_STATE_OPENSENT SessionState = "opensent" SESSION_STATE_OPENCONFIRM SessionState = "openconfirm" SESSION_STATE_ESTABLISHED SessionState = "established" ) var SessionStateToIntMap = map[SessionState]int{ SESSION_STATE_IDLE: 0, SESSION_STATE_CONNECT: 1, SESSION_STATE_ACTIVE: 2, SESSION_STATE_OPENSENT: 3, SESSION_STATE_OPENCONFIRM: 4, SESSION_STATE_ESTABLISHED: 5, } func (v SessionState) ToInt() int { i, ok := SessionStateToIntMap[v] if !ok { return -1 } return i } var IntToSessionStateMap = map[int]SessionState{ 0: SESSION_STATE_IDLE, 1: SESSION_STATE_CONNECT, 2: SESSION_STATE_ACTIVE, 3: SESSION_STATE_OPENSENT, 4: SESSION_STATE_OPENCONFIRM, 5: SESSION_STATE_ESTABLISHED, } func (v SessionState) Validate() error { if _, ok := SessionStateToIntMap[v]; !ok { return fmt.Errorf("invalid SessionState: %s", v) } return nil } // typedef for identity bgp:mode type Mode string const ( MODE_HELPER_ONLY Mode = "helper-only" MODE_BILATERAL Mode = "bilateral" MODE_REMOTE_HELPER Mode = "remote-helper" ) var ModeToIntMap = map[Mode]int{ MODE_HELPER_ONLY: 0, MODE_BILATERAL: 1, MODE_REMOTE_HELPER: 2, } func (v Mode) ToInt() int { i, ok := ModeToIntMap[v] if !ok { return -1 } return i } var IntToModeMap = map[int]Mode{ 0: MODE_HELPER_ONLY, 1: MODE_BILATERAL, 2: MODE_REMOTE_HELPER, } func (v Mode) Validate() error { if _, ok := ModeToIntMap[v]; !ok { return fmt.Errorf("invalid Mode: %s", v) } return nil } // typedef for typedef bgp-pol:bgp-next-hop-type type BgpNextHopType string // typedef for typedef bgp-pol:bgp-as-path-prepend-repeat type BgpAsPathPrependRepeat uint8 // typedef for typedef bgp-pol:bgp-set-med-type type BgpSetMedType string // typedef for identity bgp-pol:bgp-set-community-option-type type BgpSetCommunityOptionType string const ( BGP_SET_COMMUNITY_OPTION_TYPE_ADD BgpSetCommunityOptionType = "add" BGP_SET_COMMUNITY_OPTION_TYPE_REMOVE BgpSetCommunityOptionType = "remove" BGP_SET_COMMUNITY_OPTION_TYPE_REPLACE BgpSetCommunityOptionType = "replace" ) var BgpSetCommunityOptionTypeToIntMap = map[BgpSetCommunityOptionType]int{ BGP_SET_COMMUNITY_OPTION_TYPE_ADD: 0, BGP_SET_COMMUNITY_OPTION_TYPE_REMOVE: 1, BGP_SET_COMMUNITY_OPTION_TYPE_REPLACE: 2, } func (v BgpSetCommunityOptionType) ToInt() int { i, ok := BgpSetCommunityOptionTypeToIntMap[v] if !ok { return -1 } return i } var IntToBgpSetCommunityOptionTypeMap = map[int]BgpSetCommunityOptionType{ 0: BGP_SET_COMMUNITY_OPTION_TYPE_ADD, 1: BGP_SET_COMMUNITY_OPTION_TYPE_REMOVE, 2: BGP_SET_COMMUNITY_OPTION_TYPE_REPLACE, } func (v BgpSetCommunityOptionType) Validate() error { if _, ok := BgpSetCommunityOptionTypeToIntMap[v]; !ok { return fmt.Errorf("invalid BgpSetCommunityOptionType: %s", v) } return nil } // typedef for identity gobgp:bmp-route-monitoring-policy-type type BmpRouteMonitoringPolicyType string const ( BMP_ROUTE_MONITORING_POLICY_TYPE_PRE_POLICY BmpRouteMonitoringPolicyType = "pre-policy" BMP_ROUTE_MONITORING_POLICY_TYPE_POST_POLICY BmpRouteMonitoringPolicyType = "post-policy" BMP_ROUTE_MONITORING_POLICY_TYPE_BOTH BmpRouteMonitoringPolicyType = "both" ) var BmpRouteMonitoringPolicyTypeToIntMap = map[BmpRouteMonitoringPolicyType]int{ BMP_ROUTE_MONITORING_POLICY_TYPE_PRE_POLICY: 0, BMP_ROUTE_MONITORING_POLICY_TYPE_POST_POLICY: 1, BMP_ROUTE_MONITORING_POLICY_TYPE_BOTH: 2, } func (v BmpRouteMonitoringPolicyType) ToInt() int { i, ok := BmpRouteMonitoringPolicyTypeToIntMap[v] if !ok { return -1 } return i } var IntToBmpRouteMonitoringPolicyTypeMap = map[int]BmpRouteMonitoringPolicyType{ 0: BMP_ROUTE_MONITORING_POLICY_TYPE_PRE_POLICY, 1: BMP_ROUTE_MONITORING_POLICY_TYPE_POST_POLICY, 2: BMP_ROUTE_MONITORING_POLICY_TYPE_BOTH, } func (v BmpRouteMonitoringPolicyType) Validate() error { if _, ok := BmpRouteMonitoringPolicyTypeToIntMap[v]; !ok { return fmt.Errorf("invalid BmpRouteMonitoringPolicyType: %s", v) } return nil } // typedef for identity gobgp:mrt-type type MrtType string const ( MRT_TYPE_UPDATES MrtType = "updates" MRT_TYPE_TABLE MrtType = "table" ) var MrtTypeToIntMap = map[MrtType]int{ MRT_TYPE_UPDATES: 0, MRT_TYPE_TABLE: 1, } func (v MrtType) ToInt() int { i, ok := MrtTypeToIntMap[v] if !ok { return -1 } return i } var IntToMrtTypeMap = map[int]MrtType{ 0: MRT_TYPE_UPDATES, 1: MRT_TYPE_TABLE, } func (v MrtType) Validate() error { if _, ok := MrtTypeToIntMap[v]; !ok { return fmt.Errorf("invalid MrtType: %s", v) } return nil } // typedef for identity gobgp:rpki-validation-result-type type RpkiValidationResultType string const ( RPKI_VALIDATION_RESULT_TYPE_NONE RpkiValidationResultType = "none" RPKI_VALIDATION_RESULT_TYPE_NOT_FOUND RpkiValidationResultType = "not-found" RPKI_VALIDATION_RESULT_TYPE_VALID RpkiValidationResultType = "valid" RPKI_VALIDATION_RESULT_TYPE_INVALID RpkiValidationResultType = "invalid" ) var RpkiValidationResultTypeToIntMap = map[RpkiValidationResultType]int{ RPKI_VALIDATION_RESULT_TYPE_NONE: 0, RPKI_VALIDATION_RESULT_TYPE_NOT_FOUND: 1, RPKI_VALIDATION_RESULT_TYPE_VALID: 2, RPKI_VALIDATION_RESULT_TYPE_INVALID: 3, } func (v RpkiValidationResultType) ToInt() int { i, ok := RpkiValidationResultTypeToIntMap[v] if !ok { return -1 } return i } var IntToRpkiValidationResultTypeMap = map[int]RpkiValidationResultType{ 0: RPKI_VALIDATION_RESULT_TYPE_NONE, 1: RPKI_VALIDATION_RESULT_TYPE_NOT_FOUND, 2: RPKI_VALIDATION_RESULT_TYPE_VALID, 3: RPKI_VALIDATION_RESULT_TYPE_INVALID, } func (v RpkiValidationResultType) Validate() error { if _, ok := RpkiValidationResultTypeToIntMap[v]; !ok { return fmt.Errorf("invalid RpkiValidationResultType: %s", v) } return nil } //struct for container gobgp:state type CollectorState struct { // original -> gobgp:url Url string `mapstructure:"url"` // original -> gobgp:db-name DbName string `mapstructure:"db-name"` // original -> gobgp:table-dump-interval TableDumpInterval uint64 `mapstructure:"table-dump-interval"` } func (lhs *CollectorState) Equal(rhs *CollectorState) bool { if lhs == nil || rhs == nil { return false } if lhs.Url != rhs.Url { return false } if lhs.DbName != rhs.DbName { return false } if lhs.TableDumpInterval != rhs.TableDumpInterval { return false } return true } //struct for container gobgp:config type CollectorConfig struct { // original -> gobgp:url Url string `mapstructure:"url"` // original -> gobgp:db-name DbName string `mapstructure:"db-name"` // original -> gobgp:table-dump-interval TableDumpInterval uint64 `mapstructure:"table-dump-interval"` } func (lhs *CollectorConfig) Equal(rhs *CollectorConfig) bool { if lhs == nil || rhs == nil { return false } if lhs.Url != rhs.Url { return false } if lhs.DbName != rhs.DbName { return false } if lhs.TableDumpInterval != rhs.TableDumpInterval { return false } return true } //struct for container gobgp:collector type Collector struct { // original -> gobgp:collector-config Config CollectorConfig `mapstructure:"config"` // original -> gobgp:collector-state State CollectorState `mapstructure:"state"` } func (lhs *Collector) Equal(rhs *Collector) bool { if lhs == nil || rhs == nil { return false } if !lhs.Config.Equal(&(rhs.Config)) { return false } return true } //struct for container gobgp:state type ZebraState struct { // original -> gobgp:enabled //gobgp:enabled's original type is boolean Enabled bool `mapstructure:"enabled"` // original -> gobgp:url Url string `mapstructure:"url"` // original -> gobgp:redistribute-route-type RedistributeRouteTypeList []InstallProtocolType `mapstructure:"redistribute-route-type-list"` } func (lhs *ZebraState) Equal(rhs *ZebraState) bool { if lhs == nil || rhs == nil { return false } if lhs.Enabled != rhs.Enabled { return false } if lhs.Url != rhs.Url { return false } if len(lhs.RedistributeRouteTypeList) != len(rhs.RedistributeRouteTypeList) { return false } for idx, l := range lhs.RedistributeRouteTypeList { if l != rhs.RedistributeRouteTypeList[idx] { return false } } return true } //struct for container gobgp:config type ZebraConfig struct { // original -> gobgp:enabled //gobgp:enabled's original type is boolean Enabled bool `mapstructure:"enabled"` // original -> gobgp:url Url string `mapstructure:"url"` // original -> gobgp:redistribute-route-type RedistributeRouteTypeList []InstallProtocolType `mapstructure:"redistribute-route-type-list"` } func (lhs *ZebraConfig) Equal(rhs *ZebraConfig) bool { if lhs == nil || rhs == nil { return false } if lhs.Enabled != rhs.Enabled { return false } if lhs.Url != rhs.Url { return false } if len(lhs.RedistributeRouteTypeList) != len(rhs.RedistributeRouteTypeList) { return false } for idx, l := range lhs.RedistributeRouteTypeList { if l != rhs.RedistributeRouteTypeList[idx] { return false } } return true } //struct for container gobgp:zebra type Zebra struct { // original -> gobgp:zebra-config Config ZebraConfig `mapstructure:"config"` // original -> gobgp:zebra-state State ZebraState `mapstructure:"state"` } func (lhs *Zebra) Equal(rhs *Zebra) bool { if lhs == nil || rhs == nil { return false } if !lhs.Config.Equal(&(rhs.Config)) { return false } return true } //struct for container gobgp:config type MrtConfig struct { // original -> gobgp:dump-type DumpType MrtType `mapstructure:"dump-type"` // original -> gobgp:file-name FileName string `mapstructure:"file-name"` // original -> gobgp:table-name TableName string `mapstructure:"table-name"` // original -> gobgp:dump-interval DumpInterval uint64 `mapstructure:"dump-interval"` // original -> gobgp:rotation-interval RotationInterval uint64 `mapstructure:"rotation-interval"` } func (lhs *MrtConfig) Equal(rhs *MrtConfig) bool { if lhs == nil || rhs == nil { return false } if lhs.DumpType != rhs.DumpType { return false } if lhs.FileName != rhs.FileName { return false } if lhs.TableName != rhs.TableName { return false } if lhs.DumpInterval != rhs.DumpInterval { return false } if lhs.RotationInterval != rhs.RotationInterval { return false } return true } //struct for container gobgp:mrt type Mrt struct { // original -> gobgp:file-name // original -> gobgp:mrt-config Config MrtConfig `mapstructure:"config"` } func (lhs *Mrt) Equal(rhs *Mrt) bool { if lhs == nil || rhs == nil { return false } if !lhs.Config.Equal(&(rhs.Config)) { return false } return true } //struct for container gobgp:state type BmpServerState struct { } func (lhs *BmpServerState) Equal(rhs *BmpServerState) bool { if lhs == nil || rhs == nil { return false } return true } //struct for container gobgp:config type BmpServerConfig struct { // original -> gobgp:address //gobgp:address's original type is inet:ip-address Address string `mapstructure:"address"` // original -> gobgp:port Port uint32 `mapstructure:"port"` // original -> gobgp:route-monitoring-policy RouteMonitoringPolicy BmpRouteMonitoringPolicyType `mapstructure:"route-monitoring-policy"` } func (lhs *BmpServerConfig) Equal(rhs *BmpServerConfig) bool { if lhs == nil || rhs == nil { return false } if lhs.Address != rhs.Address { return false } if lhs.Port != rhs.Port { return false } if lhs.RouteMonitoringPolicy != rhs.RouteMonitoringPolicy { return false } return true } //struct for container gobgp:bmp-server type BmpServer struct { // original -> gobgp:address // original -> gobgp:bmp-server-config Config BmpServerConfig `mapstructure:"config"` // original -> gobgp:bmp-server-state State BmpServerState `mapstructure:"state"` } func (lhs *BmpServer) Equal(rhs *BmpServer) bool { if lhs == nil || rhs == nil { return false } if !lhs.Config.Equal(&(rhs.Config)) { return false } return true } //struct for container gobgp:rpki-received type RpkiReceived struct { // original -> gobgp:serial-notify SerialNotify int64 `mapstructure:"serial-notify"` // original -> gobgp:cache-reset CacheReset int64 `mapstructure:"cache-reset"` // original -> gobgp:cache-response CacheResponse int64 `mapstructure:"cache-response"` // original -> gobgp:ipv4-prefix Ipv4Prefix int64 `mapstructure:"ipv4-prefix"` // original -> gobgp:ipv6-prefix Ipv6Prefix int64 `mapstructure:"ipv6-prefix"` // original -> gobgp:end-of-data EndOfData int64 `mapstructure:"end-of-data"` // original -> gobgp:error Error int64 `mapstructure:"error"` } func (lhs *RpkiReceived) Equal(rhs *RpkiReceived) bool { if lhs == nil || rhs == nil { return false } if lhs.SerialNotify != rhs.SerialNotify { return false } if lhs.CacheReset != rhs.CacheReset { return false } if lhs.CacheResponse != rhs.CacheResponse { return false } if lhs.Ipv4Prefix != rhs.Ipv4Prefix { return false } if lhs.Ipv6Prefix != rhs.Ipv6Prefix { return false } if lhs.EndOfData != rhs.EndOfData { return false } if lhs.Error != rhs.Error { return false } return true } //struct for container gobgp:rpki-sent type RpkiSent struct { // original -> gobgp:serial-query SerialQuery int64 `mapstructure:"serial-query"` // original -> gobgp:reset-query ResetQuery int64 `mapstructure:"reset-query"` // original -> gobgp:error Error int64 `mapstructure:"error"` } func (lhs *RpkiSent) Equal(rhs *RpkiSent) bool { if lhs == nil || rhs == nil { return false } if lhs.SerialQuery != rhs.SerialQuery { return false } if lhs.ResetQuery != rhs.ResetQuery { return false } if lhs.Error != rhs.Error { return false } return true } //struct for container gobgp:rpki-messages type RpkiMessages struct { // original -> gobgp:rpki-sent RpkiSent RpkiSent `mapstructure:"rpki-sent"` // original -> gobgp:rpki-received RpkiReceived RpkiReceived `mapstructure:"rpki-received"` } func (lhs *RpkiMessages) Equal(rhs *RpkiMessages) bool { if lhs == nil || rhs == nil { return false } if !lhs.RpkiSent.Equal(&(rhs.RpkiSent)) { return false } if !lhs.RpkiReceived.Equal(&(rhs.RpkiReceived)) { return false } return true } //struct for container gobgp:state type RpkiServerState struct { // original -> gobgp:up //gobgp:up's original type is boolean Up bool `mapstructure:"up"` // original -> gobgp:serial-number SerialNumber uint32 `mapstructure:"serial-number"` // original -> gobgp:records-v4 RecordsV4 uint32 `mapstructure:"records-v4"` // original -> gobgp:records-v6 RecordsV6 uint32 `mapstructure:"records-v6"` // original -> gobgp:prefixes-v4 PrefixesV4 uint32 `mapstructure:"prefixes-v4"` // original -> gobgp:prefixes-v6 PrefixesV6 uint32 `mapstructure:"prefixes-v6"` // original -> gobgp:uptime Uptime int64 `mapstructure:"uptime"` // original -> gobgp:downtime Downtime int64 `mapstructure:"downtime"` // original -> gobgp:last-pdu-recv-time LastPduRecvTime int64 `mapstructure:"last-pdu-recv-time"` // original -> gobgp:rpki-messages RpkiMessages RpkiMessages `mapstructure:"rpki-messages"` } func (lhs *RpkiServerState) Equal(rhs *RpkiServerState) bool { if lhs == nil || rhs == nil { return false } if lhs.Up != rhs.Up { return false } if lhs.SerialNumber != rhs.SerialNumber { return false } if lhs.RecordsV4 != rhs.RecordsV4 { return false } if lhs.RecordsV6 != rhs.RecordsV6 { return false } if lhs.PrefixesV4 != rhs.PrefixesV4 { return false } if lhs.PrefixesV6 != rhs.PrefixesV6 { return false } if lhs.Uptime != rhs.Uptime { return false } if lhs.Downtime != rhs.Downtime { return false } if lhs.LastPduRecvTime != rhs.LastPduRecvTime { return false } if !lhs.RpkiMessages.Equal(&(rhs.RpkiMessages)) { return false } return true } //struct for container gobgp:config type RpkiServerConfig struct { // original -> gobgp:address //gobgp:address's original type is inet:ip-address Address string `mapstructure:"address"` // original -> gobgp:port Port uint32 `mapstructure:"port"` // original -> gobgp:refresh-time RefreshTime int64 `mapstructure:"refresh-time"` // original -> gobgp:hold-time HoldTime int64 `mapstructure:"hold-time"` // original -> gobgp:record-lifetime RecordLifetime int64 `mapstructure:"record-lifetime"` // original -> gobgp:preference Preference uint8 `mapstructure:"preference"` } func (lhs *RpkiServerConfig) Equal(rhs *RpkiServerConfig) bool { if lhs == nil || rhs == nil { return false } if lhs.Address != rhs.Address { return false } if lhs.Port != rhs.Port { return false } if lhs.RefreshTime != rhs.RefreshTime { return false } if lhs.HoldTime != rhs.HoldTime { return false } if lhs.RecordLifetime != rhs.RecordLifetime { return false } if lhs.Preference != rhs.Preference { return false } return true } //struct for container gobgp:rpki-server type RpkiServer struct { // original -> gobgp:address // original -> gobgp:rpki-server-config Config RpkiServerConfig `mapstructure:"config"` // original -> gobgp:rpki-server-state State RpkiServerState `mapstructure:"state"` } func (lhs *RpkiServer) Equal(rhs *RpkiServer) bool { if lhs == nil || rhs == nil { return false } if !lhs.Config.Equal(&(rhs.Config)) { return false } return true } //struct for container bgp:state type PeerGroupState struct { // original -> bgp:peer-as //bgp:peer-as's original type is inet:as-number PeerAs uint32 `mapstructure:"peer-as"` // original -> bgp:local-as //bgp:local-as's original type is inet:as-number LocalAs uint32 `mapstructure:"local-as"` // original -> bgp:peer-type PeerType PeerType `mapstructure:"peer-type"` // original -> bgp:auth-password AuthPassword string `mapstructure:"auth-password"` // original -> bgp:remove-private-as RemovePrivateAs RemovePrivateAsOption `mapstructure:"remove-private-as"` // original -> bgp:route-flap-damping //bgp:route-flap-damping's original type is boolean RouteFlapDamping bool `mapstructure:"route-flap-damping"` // original -> bgp:send-community SendCommunity CommunityType `mapstructure:"send-community"` // original -> bgp:description Description string `mapstructure:"description"` // original -> bgp:peer-group-name PeerGroupName string `mapstructure:"peer-group-name"` // original -> bgp-op:total-paths TotalPaths uint32 `mapstructure:"total-paths"` // original -> bgp-op:total-prefixes TotalPrefixes uint32 `mapstructure:"total-prefixes"` } func (lhs *PeerGroupState) Equal(rhs *PeerGroupState) bool { if lhs == nil || rhs == nil { return false } if lhs.PeerAs != rhs.PeerAs { return false } if lhs.LocalAs != rhs.LocalAs { return false } if lhs.PeerType != rhs.PeerType { return false } if lhs.AuthPassword != rhs.AuthPassword { return false } if lhs.RemovePrivateAs != rhs.RemovePrivateAs { return false } if lhs.RouteFlapDamping != rhs.RouteFlapDamping { return false } if lhs.SendCommunity != rhs.SendCommunity { return false } if lhs.Description != rhs.Description { return false } if lhs.PeerGroupName != rhs.PeerGroupName { return false } if lhs.TotalPaths != rhs.TotalPaths { return false } if lhs.TotalPrefixes != rhs.TotalPrefixes { return false } return true } //struct for container bgp:config type PeerGroupConfig struct { // original -> bgp:peer-as //bgp:peer-as's original type is inet:as-number PeerAs uint32 `mapstructure:"peer-as"` // original -> bgp:local-as //bgp:local-as's original type is inet:as-number LocalAs uint32 `mapstructure:"local-as"` // original -> bgp:peer-type PeerType PeerType `mapstructure:"peer-type"` // original -> bgp:auth-password AuthPassword string `mapstructure:"auth-password"` // original -> bgp:remove-private-as RemovePrivateAs RemovePrivateAsOption `mapstructure:"remove-private-as"` // original -> bgp:route-flap-damping //bgp:route-flap-damping's original type is boolean RouteFlapDamping bool `mapstructure:"route-flap-damping"` // original -> bgp:send-community SendCommunity CommunityType `mapstructure:"send-community"` // original -> bgp:description Description string `mapstructure:"description"` // original -> bgp:peer-group-name PeerGroupName string `mapstructure:"peer-group-name"` } func (lhs *PeerGroupConfig) Equal(rhs *PeerGroupConfig) bool { if lhs == nil || rhs == nil { return false } if lhs.PeerAs != rhs.PeerAs { return false } if lhs.LocalAs != rhs.LocalAs { return false } if lhs.PeerType != rhs.PeerType { return false } if lhs.AuthPassword != rhs.AuthPassword { return false } if lhs.RemovePrivateAs != rhs.RemovePrivateAs { return false } if lhs.RouteFlapDamping != rhs.RouteFlapDamping { return false } if lhs.SendCommunity != rhs.SendCommunity { return false } if lhs.Description != rhs.Description { return false } if lhs.PeerGroupName != rhs.PeerGroupName { return false } return true } //struct for container bgp:peer-group type PeerGroup struct { // original -> bgp:peer-group-name // original -> bgp:peer-group-config Config PeerGroupConfig `mapstructure:"config"` // original -> bgp:peer-group-state State PeerGroupState `mapstructure:"state"` // original -> bgp:timers Timers Timers `mapstructure:"timers"` // original -> bgp:transport Transport Transport `mapstructure:"transport"` // original -> bgp:error-handling ErrorHandling ErrorHandling `mapstructure:"error-handling"` // original -> bgp:logging-options LoggingOptions LoggingOptions `mapstructure:"logging-options"` // original -> bgp:ebgp-multihop EbgpMultihop EbgpMultihop `mapstructure:"ebgp-multihop"` // original -> bgp:route-reflector RouteReflector RouteReflector `mapstructure:"route-reflector"` // original -> bgp:as-path-options AsPathOptions AsPathOptions `mapstructure:"as-path-options"` // original -> bgp:add-paths AddPaths AddPaths `mapstructure:"add-paths"` // original -> bgp:afi-safis AfiSafis []AfiSafi `mapstructure:"afi-safis"` // original -> bgp:graceful-restart GracefulRestart GracefulRestart `mapstructure:"graceful-restart"` // original -> rpol:apply-policy ApplyPolicy ApplyPolicy `mapstructure:"apply-policy"` // original -> bgp-mp:use-multiple-paths UseMultiplePaths UseMultiplePaths `mapstructure:"use-multiple-paths"` // original -> gobgp:route-server RouteServer RouteServer `mapstructure:"route-server"` } func (lhs *PeerGroup) Equal(rhs *PeerGroup) bool { if lhs == nil || rhs == nil { return false } if !lhs.Config.Equal(&(rhs.Config)) { return false } if !lhs.Timers.Equal(&(rhs.Timers)) { return false } if !lhs.Transport.Equal(&(rhs.Transport)) { return false } if !lhs.ErrorHandling.Equal(&(rhs.ErrorHandling)) { return false } if !lhs.LoggingOptions.Equal(&(rhs.LoggingOptions)) { return false } if !lhs.EbgpMultihop.Equal(&(rhs.EbgpMultihop)) { return false } if !lhs.RouteReflector.Equal(&(rhs.RouteReflector)) { return false } if !lhs.AsPathOptions.Equal(&(rhs.AsPathOptions)) { return false } if !lhs.AddPaths.Equal(&(rhs.AddPaths)) { return false } if len(lhs.AfiSafis) != len(rhs.AfiSafis) { return false } { lmap := make(map[string]*AfiSafi) for i, l := range lhs.AfiSafis { lmap[mapkey(i, string(l.Config.AfiSafiName))] = &lhs.AfiSafis[i] } for i, r := range rhs.AfiSafis { if l, y := lmap[mapkey(i, string(r.Config.AfiSafiName))]; !y { return false } else if !r.Equal(l) { return false } } } if !lhs.GracefulRestart.Equal(&(rhs.GracefulRestart)) { return false } if !lhs.ApplyPolicy.Equal(&(rhs.ApplyPolicy)) { return false } if !lhs.UseMultiplePaths.Equal(&(rhs.UseMultiplePaths)) { return false } if !lhs.RouteServer.Equal(&(rhs.RouteServer)) { return false } return true } //struct for container gobgp:state type RouteServerState struct { // original -> gobgp:route-server-client //gobgp:route-server-client's original type is boolean RouteServerClient bool `mapstructure:"route-server-client"` } func (lhs *RouteServerState) Equal(rhs *RouteServerState) bool { if lhs == nil || rhs == nil { return false } if lhs.RouteServerClient != rhs.RouteServerClient { return false } return true } //struct for container gobgp:config type RouteServerConfig struct { // original -> gobgp:route-server-client //gobgp:route-server-client's original type is boolean RouteServerClient bool `mapstructure:"route-server-client"` } func (lhs *RouteServerConfig) Equal(rhs *RouteServerConfig) bool { if lhs == nil || rhs == nil { return false } if lhs.RouteServerClient != rhs.RouteServerClient { return false } return true } //struct for container gobgp:route-server type RouteServer struct { // original -> gobgp:route-server-config Config RouteServerConfig `mapstructure:"config"` // original -> gobgp:route-server-state State RouteServerState `mapstructure:"state"` } func (lhs *RouteServer) Equal(rhs *RouteServer) bool { if lhs == nil || rhs == nil { return false } if !lhs.Config.Equal(&(rhs.Config)) { return false } return true } //struct for container bgp-op:prefixes type Prefixes struct { // original -> bgp-op:received Received uint32 `mapstructure:"received"` // original -> bgp-op:sent Sent uint32 `mapstructure:"sent"` // original -> bgp-op:installed Installed uint32 `mapstructure:"installed"` } func (lhs *Prefixes) Equal(rhs *Prefixes) bool { if lhs == nil || rhs == nil { return false } if lhs.Received != rhs.Received { return false } if lhs.Sent != rhs.Sent { return false } if lhs.Installed != rhs.Installed { return false } return true } //struct for container bgp:state type AddPathsState struct { // original -> bgp:receive //bgp:receive's original type is boolean Receive bool `mapstructure:"receive"` // original -> bgp:send-max SendMax uint8 `mapstructure:"send-max"` } func (lhs *AddPathsState) Equal(rhs *AddPathsState) bool { if lhs == nil || rhs == nil { return false } if lhs.Receive != rhs.Receive { return false } if lhs.SendMax != rhs.SendMax { return false } return true } //struct for container bgp:config type AddPathsConfig struct { // original -> bgp:receive //bgp:receive's original type is boolean Receive bool `mapstructure:"receive"` // original -> bgp:send-max SendMax uint8 `mapstructure:"send-max"` } func (lhs *AddPathsConfig) Equal(rhs *AddPathsConfig) bool { if lhs == nil || rhs == nil { return false } if lhs.Receive != rhs.Receive { return false } if lhs.SendMax != rhs.SendMax { return false } return true } //struct for container bgp:add-paths type AddPaths struct { // original -> bgp:add-paths-config Config AddPathsConfig `mapstructure:"config"` // original -> bgp:add-paths-state State AddPathsState `mapstructure:"state"` } func (lhs *AddPaths) Equal(rhs *AddPaths) bool { if lhs == nil || rhs == nil { return false } if !lhs.Config.Equal(&(rhs.Config)) { return false } return true } //struct for container bgp:state type AsPathOptionsState struct { // original -> bgp:allow-own-as AllowOwnAs uint8 `mapstructure:"allow-own-as"` // original -> bgp:replace-peer-as //bgp:replace-peer-as's original type is boolean ReplacePeerAs bool `mapstructure:"replace-peer-as"` } func (lhs *AsPathOptionsState) Equal(rhs *AsPathOptionsState) bool { if lhs == nil || rhs == nil { return false } if lhs.AllowOwnAs != rhs.AllowOwnAs { return false } if lhs.ReplacePeerAs != rhs.ReplacePeerAs { return false } return true } //struct for container bgp:config type AsPathOptionsConfig struct { // original -> bgp:allow-own-as AllowOwnAs uint8 `mapstructure:"allow-own-as"` // original -> bgp:replace-peer-as //bgp:replace-peer-as's original type is boolean ReplacePeerAs bool `mapstructure:"replace-peer-as"` } func (lhs *AsPathOptionsConfig) Equal(rhs *AsPathOptionsConfig) bool { if lhs == nil || rhs == nil { return false } if lhs.AllowOwnAs != rhs.AllowOwnAs { return false } if lhs.ReplacePeerAs != rhs.ReplacePeerAs { return false } return true } //struct for container bgp:as-path-options type AsPathOptions struct { // original -> bgp:as-path-options-config Config AsPathOptionsConfig `mapstructure:"config"` // original -> bgp:as-path-options-state State AsPathOptionsState `mapstructure:"state"` } func (lhs *AsPathOptions) Equal(rhs *AsPathOptions) bool { if lhs == nil || rhs == nil { return false } if !lhs.Config.Equal(&(rhs.Config)) { return false } return true } //struct for container bgp:state type RouteReflectorState struct { // original -> bgp:route-reflector-cluster-id RouteReflectorClusterId RrClusterIdType `mapstructure:"route-reflector-cluster-id"` // original -> bgp:route-reflector-client //bgp:route-reflector-client's original type is boolean RouteReflectorClient bool `mapstructure:"route-reflector-client"` } func (lhs *RouteReflectorState) Equal(rhs *RouteReflectorState) bool { if lhs == nil || rhs == nil { return false } if lhs.RouteReflectorClusterId != rhs.RouteReflectorClusterId { return false } if lhs.RouteReflectorClient != rhs.RouteReflectorClient { return false } return true } //struct for container bgp:config type RouteReflectorConfig struct { // original -> bgp:route-reflector-cluster-id RouteReflectorClusterId RrClusterIdType `mapstructure:"route-reflector-cluster-id"` // original -> bgp:route-reflector-client //bgp:route-reflector-client's original type is boolean RouteReflectorClient bool `mapstructure:"route-reflector-client"` } func (lhs *RouteReflectorConfig) Equal(rhs *RouteReflectorConfig) bool { if lhs == nil || rhs == nil { return false } if lhs.RouteReflectorClusterId != rhs.RouteReflectorClusterId { return false } if lhs.RouteReflectorClient != rhs.RouteReflectorClient { return false } return true } //struct for container bgp:route-reflector type RouteReflector struct { // original -> bgp:route-reflector-config Config RouteReflectorConfig `mapstructure:"config"` // original -> bgp:route-reflector-state State RouteReflectorState `mapstructure:"state"` } func (lhs *RouteReflector) Equal(rhs *RouteReflector) bool { if lhs == nil || rhs == nil { return false } if !lhs.Config.Equal(&(rhs.Config)) { return false } return true } //struct for container bgp:state type EbgpMultihopState struct { // original -> bgp:enabled //bgp:enabled's original type is boolean Enabled bool `mapstructure:"enabled"` // original -> bgp:multihop-ttl MultihopTtl uint8 `mapstructure:"multihop-ttl"` } func (lhs *EbgpMultihopState) Equal(rhs *EbgpMultihopState) bool { if lhs == nil || rhs == nil { return false } if lhs.Enabled != rhs.Enabled { return false } if lhs.MultihopTtl != rhs.MultihopTtl { return false } return true } //struct for container bgp:config type EbgpMultihopConfig struct { // original -> bgp:enabled //bgp:enabled's original type is boolean Enabled bool `mapstructure:"enabled"` // original -> bgp:multihop-ttl MultihopTtl uint8 `mapstructure:"multihop-ttl"` } func (lhs *EbgpMultihopConfig) Equal(rhs *EbgpMultihopConfig) bool { if lhs == nil || rhs == nil { return false } if lhs.Enabled != rhs.Enabled { return false } if lhs.MultihopTtl != rhs.MultihopTtl { return false } return true } //struct for container bgp:ebgp-multihop type EbgpMultihop struct { // original -> bgp:ebgp-multihop-config Config EbgpMultihopConfig `mapstructure:"config"` // original -> bgp:ebgp-multihop-state State EbgpMultihopState `mapstructure:"state"` } func (lhs *EbgpMultihop) Equal(rhs *EbgpMultihop) bool { if lhs == nil || rhs == nil { return false } if !lhs.Config.Equal(&(rhs.Config)) { return false } return true } //struct for container bgp:state type LoggingOptionsState struct { // original -> bgp:log-neighbor-state-changes //bgp:log-neighbor-state-changes's original type is boolean LogNeighborStateChanges bool `mapstructure:"log-neighbor-state-changes"` } func (lhs *LoggingOptionsState) Equal(rhs *LoggingOptionsState) bool { if lhs == nil || rhs == nil { return false } if lhs.LogNeighborStateChanges != rhs.LogNeighborStateChanges { return false } return true } //struct for container bgp:config type LoggingOptionsConfig struct { // original -> bgp:log-neighbor-state-changes //bgp:log-neighbor-state-changes's original type is boolean LogNeighborStateChanges bool `mapstructure:"log-neighbor-state-changes"` } func (lhs *LoggingOptionsConfig) Equal(rhs *LoggingOptionsConfig) bool { if lhs == nil || rhs == nil { return false } if lhs.LogNeighborStateChanges != rhs.LogNeighborStateChanges { return false } return true } //struct for container bgp:logging-options type LoggingOptions struct { // original -> bgp:logging-options-config Config LoggingOptionsConfig `mapstructure:"config"` // original -> bgp:logging-options-state State LoggingOptionsState `mapstructure:"state"` } func (lhs *LoggingOptions) Equal(rhs *LoggingOptions) bool { if lhs == nil || rhs == nil { return false } if !lhs.Config.Equal(&(rhs.Config)) { return false } return true } //struct for container bgp:state type ErrorHandlingState struct { // original -> bgp:treat-as-withdraw //bgp:treat-as-withdraw's original type is boolean TreatAsWithdraw bool `mapstructure:"treat-as-withdraw"` // original -> bgp-op:erroneous-update-messages ErroneousUpdateMessages uint32 `mapstructure:"erroneous-update-messages"` } func (lhs *ErrorHandlingState) Equal(rhs *ErrorHandlingState) bool { if lhs == nil || rhs == nil { return false } if lhs.TreatAsWithdraw != rhs.TreatAsWithdraw { return false } if lhs.ErroneousUpdateMessages != rhs.ErroneousUpdateMessages { return false } return true } //struct for container bgp:config type ErrorHandlingConfig struct { // original -> bgp:treat-as-withdraw //bgp:treat-as-withdraw's original type is boolean TreatAsWithdraw bool `mapstructure:"treat-as-withdraw"` } func (lhs *ErrorHandlingConfig) Equal(rhs *ErrorHandlingConfig) bool { if lhs == nil || rhs == nil { return false } if lhs.TreatAsWithdraw != rhs.TreatAsWithdraw { return false } return true } //struct for container bgp:error-handling type ErrorHandling struct { // original -> bgp:error-handling-config Config ErrorHandlingConfig `mapstructure:"config"` // original -> bgp:error-handling-state State ErrorHandlingState `mapstructure:"state"` } func (lhs *ErrorHandling) Equal(rhs *ErrorHandling) bool { if lhs == nil || rhs == nil { return false } if !lhs.Config.Equal(&(rhs.Config)) { return false } return true } //struct for container bgp:state type TransportState struct { // original -> bgp:tcp-mss TcpMss uint16 `mapstructure:"tcp-mss"` // original -> bgp:mtu-discovery //bgp:mtu-discovery's original type is boolean MtuDiscovery bool `mapstructure:"mtu-discovery"` // original -> bgp:passive-mode //bgp:passive-mode's original type is boolean PassiveMode bool `mapstructure:"passive-mode"` // original -> bgp:local-address //bgp:local-address's original type is union LocalAddress string `mapstructure:"local-address"` // original -> bgp-op:local-port //bgp-op:local-port's original type is inet:port-number LocalPort uint16 `mapstructure:"local-port"` // original -> bgp-op:remote-address //bgp-op:remote-address's original type is inet:ip-address RemoteAddress string `mapstructure:"remote-address"` // original -> bgp-op:remote-port //bgp-op:remote-port's original type is inet:port-number RemotePort uint16 `mapstructure:"remote-port"` } func (lhs *TransportState) Equal(rhs *TransportState) bool { if lhs == nil || rhs == nil { return false } if lhs.TcpMss != rhs.TcpMss { return false } if lhs.MtuDiscovery != rhs.MtuDiscovery { return false } if lhs.PassiveMode != rhs.PassiveMode { return false } if lhs.LocalAddress != rhs.LocalAddress { return false } if lhs.LocalPort != rhs.LocalPort { return false } if lhs.RemoteAddress != rhs.RemoteAddress { return false } if lhs.RemotePort != rhs.RemotePort { return false } return true } //struct for container bgp:config type TransportConfig struct { // original -> bgp:tcp-mss TcpMss uint16 `mapstructure:"tcp-mss"` // original -> bgp:mtu-discovery //bgp:mtu-discovery's original type is boolean MtuDiscovery bool `mapstructure:"mtu-discovery"` // original -> bgp:passive-mode //bgp:passive-mode's original type is boolean PassiveMode bool `mapstructure:"passive-mode"` // original -> bgp:local-address //bgp:local-address's original type is union LocalAddress string `mapstructure:"local-address"` // original -> gobgp:remote-port //gobgp:remote-port's original type is inet:port-number RemotePort uint16 `mapstructure:"remote-port"` } func (lhs *TransportConfig) Equal(rhs *TransportConfig) bool { if lhs == nil || rhs == nil { return false } if lhs.TcpMss != rhs.TcpMss { return false } if lhs.MtuDiscovery != rhs.MtuDiscovery { return false } if lhs.PassiveMode != rhs.PassiveMode { return false } if lhs.LocalAddress != rhs.LocalAddress { return false } if lhs.RemotePort != rhs.RemotePort { return false } return true } //struct for container bgp:transport type Transport struct { // original -> bgp:transport-config Config TransportConfig `mapstructure:"config"` // original -> bgp:transport-state State TransportState `mapstructure:"state"` } func (lhs *Transport) Equal(rhs *Transport) bool { if lhs == nil || rhs == nil { return false } if !lhs.Config.Equal(&(rhs.Config)) { return false } return true } //struct for container bgp:state type TimersState struct { // original -> bgp:connect-retry //bgp:connect-retry's original type is decimal64 ConnectRetry float64 `mapstructure:"connect-retry"` // original -> bgp:hold-time //bgp:hold-time's original type is decimal64 HoldTime float64 `mapstructure:"hold-time"` // original -> bgp:keepalive-interval //bgp:keepalive-interval's original type is decimal64 KeepaliveInterval float64 `mapstructure:"keepalive-interval"` // original -> bgp:minimum-advertisement-interval //bgp:minimum-advertisement-interval's original type is decimal64 MinimumAdvertisementInterval float64 `mapstructure:"minimum-advertisement-interval"` // original -> bgp-op:uptime //bgp-op:uptime's original type is yang:timeticks Uptime int64 `mapstructure:"uptime"` // original -> bgp-op:negotiated-hold-time //bgp-op:negotiated-hold-time's original type is decimal64 NegotiatedHoldTime float64 `mapstructure:"negotiated-hold-time"` // original -> gobgp:idle-hold-time-after-reset //gobgp:idle-hold-time-after-reset's original type is decimal64 IdleHoldTimeAfterReset float64 `mapstructure:"idle-hold-time-after-reset"` // original -> gobgp:downtime //gobgp:downtime's original type is yang:timeticks Downtime int64 `mapstructure:"downtime"` // original -> gobgp:update-recv-time UpdateRecvTime int64 `mapstructure:"update-recv-time"` } func (lhs *TimersState) Equal(rhs *TimersState) bool { if lhs == nil || rhs == nil { return false } if lhs.ConnectRetry != rhs.ConnectRetry { return false } if lhs.HoldTime != rhs.HoldTime { return false } if lhs.KeepaliveInterval != rhs.KeepaliveInterval { return false } if lhs.MinimumAdvertisementInterval != rhs.MinimumAdvertisementInterval { return false } if lhs.Uptime != rhs.Uptime { return false } if lhs.NegotiatedHoldTime != rhs.NegotiatedHoldTime { return false } if lhs.IdleHoldTimeAfterReset != rhs.IdleHoldTimeAfterReset { return false } if lhs.Downtime != rhs.Downtime { return false } if lhs.UpdateRecvTime != rhs.UpdateRecvTime { return false } return true } //struct for container bgp:config type TimersConfig struct { // original -> bgp:connect-retry //bgp:connect-retry's original type is decimal64 ConnectRetry float64 `mapstructure:"connect-retry"` // original -> bgp:hold-time //bgp:hold-time's original type is decimal64 HoldTime float64 `mapstructure:"hold-time"` // original -> bgp:keepalive-interval //bgp:keepalive-interval's original type is decimal64 KeepaliveInterval float64 `mapstructure:"keepalive-interval"` // original -> bgp:minimum-advertisement-interval //bgp:minimum-advertisement-interval's original type is decimal64 MinimumAdvertisementInterval float64 `mapstructure:"minimum-advertisement-interval"` // original -> gobgp:idle-hold-time-after-reset //gobgp:idle-hold-time-after-reset's original type is decimal64 IdleHoldTimeAfterReset float64 `mapstructure:"idle-hold-time-after-reset"` } func (lhs *TimersConfig) Equal(rhs *TimersConfig) bool { if lhs == nil || rhs == nil { return false } if lhs.ConnectRetry != rhs.ConnectRetry { return false } if lhs.HoldTime != rhs.HoldTime { return false } if lhs.KeepaliveInterval != rhs.KeepaliveInterval { return false } if lhs.MinimumAdvertisementInterval != rhs.MinimumAdvertisementInterval { return false } if lhs.IdleHoldTimeAfterReset != rhs.IdleHoldTimeAfterReset { return false } return true } //struct for container bgp:timers type Timers struct { // original -> bgp:timers-config Config TimersConfig `mapstructure:"config"` // original -> bgp:timers-state State TimersState `mapstructure:"state"` } func (lhs *Timers) Equal(rhs *Timers) bool { if lhs == nil || rhs == nil { return false } if !lhs.Config.Equal(&(rhs.Config)) { return false } return true } //struct for container gobgp:Capabilities type Capabilities struct { // original -> gobgp:remote // original type is list of binary RemoteList [][]byte `mapstructure:"remote-list"` // original -> gobgp:local // original type is list of binary LocalList [][]byte `mapstructure:"local-list"` } func (lhs *Capabilities) Equal(rhs *Capabilities) bool { if lhs == nil || rhs == nil { return false } if len(lhs.RemoteList) != len(rhs.RemoteList) { return false } for idx, l := range lhs.RemoteList { if bytes.Compare(l, rhs.RemoteList[idx]) != 0 { return false } } if len(lhs.LocalList) != len(rhs.LocalList) { return false } for idx, l := range lhs.LocalList { if bytes.Compare(l, rhs.LocalList[idx]) != 0 { return false } } return true } //struct for container gobgp:adj-table type AdjTable struct { // original -> gobgp:ADVERTISED Advertised uint32 `mapstructure:"advertised"` // original -> gobgp:RECEIVED Received uint32 `mapstructure:"received"` // original -> gobgp:ACCEPTED Accepted uint32 `mapstructure:"accepted"` } func (lhs *AdjTable) Equal(rhs *AdjTable) bool { if lhs == nil || rhs == nil { return false } if lhs.Advertised != rhs.Advertised { return false } if lhs.Received != rhs.Received { return false } if lhs.Accepted != rhs.Accepted { return false } return true } //struct for container bgp:queues type Queues struct { // original -> bgp-op:input Input uint32 `mapstructure:"input"` // original -> bgp-op:output Output uint32 `mapstructure:"output"` } func (lhs *Queues) Equal(rhs *Queues) bool { if lhs == nil || rhs == nil { return false } if lhs.Input != rhs.Input { return false } if lhs.Output != rhs.Output { return false } return true } //struct for container bgp:received type Received struct { // original -> bgp-op:UPDATE Update uint64 `mapstructure:"update"` // original -> bgp-op:NOTIFICATION Notification uint64 `mapstructure:"notification"` // original -> gobgp:OPEN Open uint64 `mapstructure:"open"` // original -> gobgp:REFRESH Refresh uint64 `mapstructure:"refresh"` // original -> gobgp:KEEPALIVE Keepalive uint64 `mapstructure:"keepalive"` // original -> gobgp:DYNAMIC-CAP DynamicCap uint64 `mapstructure:"dynamic-cap"` // original -> gobgp:DISCARDED Discarded uint64 `mapstructure:"discarded"` // original -> gobgp:TOTAL Total uint64 `mapstructure:"total"` } func (lhs *Received) Equal(rhs *Received) bool { if lhs == nil || rhs == nil { return false } if lhs.Update != rhs.Update { return false } if lhs.Notification != rhs.Notification { return false } if lhs.Open != rhs.Open { return false } if lhs.Refresh != rhs.Refresh { return false } if lhs.Keepalive != rhs.Keepalive { return false } if lhs.DynamicCap != rhs.DynamicCap { return false } if lhs.Discarded != rhs.Discarded { return false } if lhs.Total != rhs.Total { return false } return true } //struct for container bgp:sent type Sent struct { // original -> bgp-op:UPDATE Update uint64 `mapstructure:"update"` // original -> bgp-op:NOTIFICATION Notification uint64 `mapstructure:"notification"` // original -> gobgp:OPEN Open uint64 `mapstructure:"open"` // original -> gobgp:REFRESH Refresh uint64 `mapstructure:"refresh"` // original -> gobgp:KEEPALIVE Keepalive uint64 `mapstructure:"keepalive"` // original -> gobgp:DYNAMIC-CAP DynamicCap uint64 `mapstructure:"dynamic-cap"` // original -> gobgp:DISCARDED Discarded uint64 `mapstructure:"discarded"` // original -> gobgp:TOTAL Total uint64 `mapstructure:"total"` } func (lhs *Sent) Equal(rhs *Sent) bool { if lhs == nil || rhs == nil { return false } if lhs.Update != rhs.Update { return false } if lhs.Notification != rhs.Notification { return false } if lhs.Open != rhs.Open { return false } if lhs.Refresh != rhs.Refresh { return false } if lhs.Keepalive != rhs.Keepalive { return false } if lhs.DynamicCap != rhs.DynamicCap { return false } if lhs.Discarded != rhs.Discarded { return false } if lhs.Total != rhs.Total { return false } return true } //struct for container bgp:messages type Messages struct { // original -> bgp:sent Sent Sent `mapstructure:"sent"` // original -> bgp:received Received Received `mapstructure:"received"` } func (lhs *Messages) Equal(rhs *Messages) bool { if lhs == nil || rhs == nil { return false } if !lhs.Sent.Equal(&(rhs.Sent)) { return false } if !lhs.Received.Equal(&(rhs.Received)) { return false } return true } //struct for container bgp:state type NeighborState struct { // original -> bgp:peer-as //bgp:peer-as's original type is inet:as-number PeerAs uint32 `mapstructure:"peer-as"` // original -> bgp:local-as //bgp:local-as's original type is inet:as-number LocalAs uint32 `mapstructure:"local-as"` // original -> bgp:peer-type PeerType PeerType `mapstructure:"peer-type"` // original -> bgp:auth-password AuthPassword string `mapstructure:"auth-password"` // original -> bgp:remove-private-as RemovePrivateAs RemovePrivateAsOption `mapstructure:"remove-private-as"` // original -> bgp:route-flap-damping //bgp:route-flap-damping's original type is boolean RouteFlapDamping bool `mapstructure:"route-flap-damping"` // original -> bgp:send-community SendCommunity CommunityType `mapstructure:"send-community"` // original -> bgp:description Description string `mapstructure:"description"` // original -> bgp:peer-group PeerGroup string `mapstructure:"peer-group"` // original -> bgp:neighbor-address //bgp:neighbor-address's original type is inet:ip-address NeighborAddress string `mapstructure:"neighbor-address"` // original -> bgp-op:session-state SessionState SessionState `mapstructure:"session-state"` // original -> bgp-op:supported-capabilities SupportedCapabilitiesList []BgpCapability `mapstructure:"supported-capabilities-list"` // original -> bgp:messages Messages Messages `mapstructure:"messages"` // original -> bgp:queues Queues Queues `mapstructure:"queues"` // original -> gobgp:adj-table AdjTable AdjTable `mapstructure:"adj-table"` // original -> gobgp:Capabilities Capabilities Capabilities `mapstructure:"capabilities"` // original -> gobgp:received-open-message //gobgp:received-open-message's original type is binary ReceivedOpenMessage []byte `mapstructure:"received-open-message"` // original -> gobgp:admin-down //gobgp:admin-down's original type is boolean AdminDown bool `mapstructure:"admin-down"` // original -> gobgp:admin-state AdminState string `mapstructure:"admin-state"` // original -> gobgp:established-count EstablishedCount uint32 `mapstructure:"established-count"` // original -> gobgp:flops Flops uint32 `mapstructure:"flops"` // original -> gobgp:neighbor-interface NeighborInterface string `mapstructure:"neighbor-interface"` // original -> gobgp:remote-router-id RemoteRouterId string `mapstructure:"remote-router-id"` } func (lhs *NeighborState) Equal(rhs *NeighborState) bool { if lhs == nil || rhs == nil { return false } if lhs.PeerAs != rhs.PeerAs { return false } if lhs.LocalAs != rhs.LocalAs { return false } if lhs.PeerType != rhs.PeerType { return false } if lhs.AuthPassword != rhs.AuthPassword { return false } if lhs.RemovePrivateAs != rhs.RemovePrivateAs { return false } if lhs.RouteFlapDamping != rhs.RouteFlapDamping { return false } if lhs.SendCommunity != rhs.SendCommunity { return false } if lhs.Description != rhs.Description { return false } if lhs.PeerGroup != rhs.PeerGroup { return false } if lhs.NeighborAddress != rhs.NeighborAddress { return false } if lhs.SessionState != rhs.SessionState { return false } if len(lhs.SupportedCapabilitiesList) != len(rhs.SupportedCapabilitiesList) { return false } for idx, l := range lhs.SupportedCapabilitiesList { if l != rhs.SupportedCapabilitiesList[idx] { return false } } if !lhs.Messages.Equal(&(rhs.Messages)) { return false } if !lhs.Queues.Equal(&(rhs.Queues)) { return false } if !lhs.AdjTable.Equal(&(rhs.AdjTable)) { return false } if !lhs.Capabilities.Equal(&(rhs.Capabilities)) { return false } if bytes.Compare(lhs.ReceivedOpenMessage, rhs.ReceivedOpenMessage) != 0 { return false } if lhs.AdminDown != rhs.AdminDown { return false } if lhs.AdminState != rhs.AdminState { return false } if lhs.EstablishedCount != rhs.EstablishedCount { return false } if lhs.Flops != rhs.Flops { return false } if lhs.NeighborInterface != rhs.NeighborInterface { return false } if lhs.RemoteRouterId != rhs.RemoteRouterId { return false } return true } //struct for container bgp:config type NeighborConfig struct { // original -> bgp:peer-as //bgp:peer-as's original type is inet:as-number PeerAs uint32 `mapstructure:"peer-as"` // original -> bgp:local-as //bgp:local-as's original type is inet:as-number LocalAs uint32 `mapstructure:"local-as"` // original -> bgp:peer-type PeerType PeerType `mapstructure:"peer-type"` // original -> bgp:auth-password AuthPassword string `mapstructure:"auth-password"` // original -> bgp:remove-private-as RemovePrivateAs RemovePrivateAsOption `mapstructure:"remove-private-as"` // original -> bgp:route-flap-damping //bgp:route-flap-damping's original type is boolean RouteFlapDamping bool `mapstructure:"route-flap-damping"` // original -> bgp:send-community SendCommunity CommunityType `mapstructure:"send-community"` // original -> bgp:description Description string `mapstructure:"description"` // original -> bgp:peer-group PeerGroup string `mapstructure:"peer-group"` // original -> bgp:neighbor-address //bgp:neighbor-address's original type is inet:ip-address NeighborAddress string `mapstructure:"neighbor-address"` // original -> gobgp:admin-down //gobgp:admin-down's original type is boolean AdminDown bool `mapstructure:"admin-down"` // original -> gobgp:neighbor-interface NeighborInterface string `mapstructure:"neighbor-interface"` } func (lhs *NeighborConfig) Equal(rhs *NeighborConfig) bool { if lhs == nil || rhs == nil { return false } if lhs.PeerAs != rhs.PeerAs { return false } if lhs.LocalAs != rhs.LocalAs { return false } if lhs.PeerType != rhs.PeerType { return false } if lhs.AuthPassword != rhs.AuthPassword { return false } if lhs.RemovePrivateAs != rhs.RemovePrivateAs { return false } if lhs.RouteFlapDamping != rhs.RouteFlapDamping { return false } if lhs.SendCommunity != rhs.SendCommunity { return false } if lhs.Description != rhs.Description { return false } if lhs.PeerGroup != rhs.PeerGroup { return false } if lhs.NeighborAddress != rhs.NeighborAddress { return false } if lhs.AdminDown != rhs.AdminDown { return false } if lhs.NeighborInterface != rhs.NeighborInterface { return false } return true } //struct for container bgp:neighbor type Neighbor struct { // original -> bgp:neighbor-address // original -> bgp:neighbor-config Config NeighborConfig `mapstructure:"config"` // original -> bgp:neighbor-state State NeighborState `mapstructure:"state"` // original -> bgp:timers Timers Timers `mapstructure:"timers"` // original -> bgp:transport Transport Transport `mapstructure:"transport"` // original -> bgp:error-handling ErrorHandling ErrorHandling `mapstructure:"error-handling"` // original -> bgp:logging-options LoggingOptions LoggingOptions `mapstructure:"logging-options"` // original -> bgp:ebgp-multihop EbgpMultihop EbgpMultihop `mapstructure:"ebgp-multihop"` // original -> bgp:route-reflector RouteReflector RouteReflector `mapstructure:"route-reflector"` // original -> bgp:as-path-options AsPathOptions AsPathOptions `mapstructure:"as-path-options"` // original -> bgp:add-paths AddPaths AddPaths `mapstructure:"add-paths"` // original -> bgp:afi-safis AfiSafis []AfiSafi `mapstructure:"afi-safis"` // original -> bgp:graceful-restart GracefulRestart GracefulRestart `mapstructure:"graceful-restart"` // original -> rpol:apply-policy ApplyPolicy ApplyPolicy `mapstructure:"apply-policy"` // original -> bgp-mp:use-multiple-paths UseMultiplePaths UseMultiplePaths `mapstructure:"use-multiple-paths"` // original -> gobgp:route-server RouteServer RouteServer `mapstructure:"route-server"` } func (lhs *Neighbor) Equal(rhs *Neighbor) bool { if lhs == nil || rhs == nil { return false } if !lhs.Config.Equal(&(rhs.Config)) { return false } if !lhs.Timers.Equal(&(rhs.Timers)) { return false } if !lhs.Transport.Equal(&(rhs.Transport)) { return false } if !lhs.ErrorHandling.Equal(&(rhs.ErrorHandling)) { return false } if !lhs.LoggingOptions.Equal(&(rhs.LoggingOptions)) { return false } if !lhs.EbgpMultihop.Equal(&(rhs.EbgpMultihop)) { return false } if !lhs.RouteReflector.Equal(&(rhs.RouteReflector)) { return false } if !lhs.AsPathOptions.Equal(&(rhs.AsPathOptions)) { return false } if !lhs.AddPaths.Equal(&(rhs.AddPaths)) { return false } if len(lhs.AfiSafis) != len(rhs.AfiSafis) { return false } { lmap := make(map[string]*AfiSafi) for i, l := range lhs.AfiSafis { lmap[mapkey(i, string(l.Config.AfiSafiName))] = &lhs.AfiSafis[i] } for i, r := range rhs.AfiSafis { if l, y := lmap[mapkey(i, string(r.Config.AfiSafiName))]; !y { return false } else if !r.Equal(l) { return false } } } if !lhs.GracefulRestart.Equal(&(rhs.GracefulRestart)) { return false } if !lhs.ApplyPolicy.Equal(&(rhs.ApplyPolicy)) { return false } if !lhs.UseMultiplePaths.Equal(&(rhs.UseMultiplePaths)) { return false } if !lhs.RouteServer.Equal(&(rhs.RouteServer)) { return false } return true } //struct for container gobgp:mpls-label-range type MplsLabelRange struct { // original -> gobgp:min-label MinLabel uint32 `mapstructure:"min-label"` // original -> gobgp:max-label MaxLabel uint32 `mapstructure:"max-label"` } func (lhs *MplsLabelRange) Equal(rhs *MplsLabelRange) bool { if lhs == nil || rhs == nil { return false } if lhs.MinLabel != rhs.MinLabel { return false } if lhs.MaxLabel != rhs.MaxLabel { return false } return true } //struct for container gobgp:state type RouteTargetMembershipState struct { // original -> gobgp:deferral-time DeferralTime uint16 `mapstructure:"deferral-time"` } func (lhs *RouteTargetMembershipState) Equal(rhs *RouteTargetMembershipState) bool { if lhs == nil || rhs == nil { return false } if lhs.DeferralTime != rhs.DeferralTime { return false } return true } //struct for container gobgp:config type RouteTargetMembershipConfig struct { // original -> gobgp:deferral-time DeferralTime uint16 `mapstructure:"deferral-time"` } func (lhs *RouteTargetMembershipConfig) Equal(rhs *RouteTargetMembershipConfig) bool { if lhs == nil || rhs == nil { return false } if lhs.DeferralTime != rhs.DeferralTime { return false } return true } //struct for container gobgp:route-target-membership type RouteTargetMembership struct { // original -> gobgp:route-target-membership-config Config RouteTargetMembershipConfig `mapstructure:"config"` // original -> gobgp:route-target-membership-state State RouteTargetMembershipState `mapstructure:"state"` } func (lhs *RouteTargetMembership) Equal(rhs *RouteTargetMembership) bool { if lhs == nil || rhs == nil { return false } if !lhs.Config.Equal(&(rhs.Config)) { return false } return true } //struct for container bgp-mp:l2vpn-evpn type L2vpnEvpn struct { // original -> bgp-mp:prefix-limit PrefixLimit PrefixLimit `mapstructure:"prefix-limit"` } func (lhs *L2vpnEvpn) Equal(rhs *L2vpnEvpn) bool { if lhs == nil || rhs == nil { return false } if !lhs.PrefixLimit.Equal(&(rhs.PrefixLimit)) { return false } return true } //struct for container bgp-mp:l2vpn-vpls type L2vpnVpls struct { // original -> bgp-mp:prefix-limit PrefixLimit PrefixLimit `mapstructure:"prefix-limit"` } func (lhs *L2vpnVpls) Equal(rhs *L2vpnVpls) bool { if lhs == nil || rhs == nil { return false } if !lhs.PrefixLimit.Equal(&(rhs.PrefixLimit)) { return false } return true } //struct for container bgp-mp:l3vpn-ipv6-multicast type L3vpnIpv6Multicast struct { // original -> bgp-mp:prefix-limit PrefixLimit PrefixLimit `mapstructure:"prefix-limit"` } func (lhs *L3vpnIpv6Multicast) Equal(rhs *L3vpnIpv6Multicast) bool { if lhs == nil || rhs == nil { return false } if !lhs.PrefixLimit.Equal(&(rhs.PrefixLimit)) { return false } return true } //struct for container bgp-mp:l3vpn-ipv4-multicast type L3vpnIpv4Multicast struct { // original -> bgp-mp:prefix-limit PrefixLimit PrefixLimit `mapstructure:"prefix-limit"` } func (lhs *L3vpnIpv4Multicast) Equal(rhs *L3vpnIpv4Multicast) bool { if lhs == nil || rhs == nil { return false } if !lhs.PrefixLimit.Equal(&(rhs.PrefixLimit)) { return false } return true } //struct for container bgp-mp:l3vpn-ipv6-unicast type L3vpnIpv6Unicast struct { // original -> bgp-mp:prefix-limit PrefixLimit PrefixLimit `mapstructure:"prefix-limit"` } func (lhs *L3vpnIpv6Unicast) Equal(rhs *L3vpnIpv6Unicast) bool { if lhs == nil || rhs == nil { return false } if !lhs.PrefixLimit.Equal(&(rhs.PrefixLimit)) { return false } return true } //struct for container bgp-mp:l3vpn-ipv4-unicast type L3vpnIpv4Unicast struct { // original -> bgp-mp:prefix-limit PrefixLimit PrefixLimit `mapstructure:"prefix-limit"` } func (lhs *L3vpnIpv4Unicast) Equal(rhs *L3vpnIpv4Unicast) bool { if lhs == nil || rhs == nil { return false } if !lhs.PrefixLimit.Equal(&(rhs.PrefixLimit)) { return false } return true } //struct for container bgp-mp:ipv6-labelled-unicast type Ipv6LabelledUnicast struct { // original -> bgp-mp:prefix-limit PrefixLimit PrefixLimit `mapstructure:"prefix-limit"` } func (lhs *Ipv6LabelledUnicast) Equal(rhs *Ipv6LabelledUnicast) bool { if lhs == nil || rhs == nil { return false } if !lhs.PrefixLimit.Equal(&(rhs.PrefixLimit)) { return false } return true } //struct for container bgp-mp:ipv4-labelled-unicast type Ipv4LabelledUnicast struct { // original -> bgp-mp:prefix-limit PrefixLimit PrefixLimit `mapstructure:"prefix-limit"` } func (lhs *Ipv4LabelledUnicast) Equal(rhs *Ipv4LabelledUnicast) bool { if lhs == nil || rhs == nil { return false } if !lhs.PrefixLimit.Equal(&(rhs.PrefixLimit)) { return false } return true } //struct for container bgp-mp:state type Ipv6UnicastState struct { // original -> bgp-mp:send-default-route //bgp-mp:send-default-route's original type is boolean SendDefaultRoute bool `mapstructure:"send-default-route"` } func (lhs *Ipv6UnicastState) Equal(rhs *Ipv6UnicastState) bool { if lhs == nil || rhs == nil { return false } if lhs.SendDefaultRoute != rhs.SendDefaultRoute { return false } return true } //struct for container bgp-mp:config type Ipv6UnicastConfig struct { // original -> bgp-mp:send-default-route //bgp-mp:send-default-route's original type is boolean SendDefaultRoute bool `mapstructure:"send-default-route"` } func (lhs *Ipv6UnicastConfig) Equal(rhs *Ipv6UnicastConfig) bool { if lhs == nil || rhs == nil { return false } if lhs.SendDefaultRoute != rhs.SendDefaultRoute { return false } return true } //struct for container bgp-mp:ipv6-unicast type Ipv6Unicast struct { // original -> bgp-mp:prefix-limit PrefixLimit PrefixLimit `mapstructure:"prefix-limit"` // original -> bgp-mp:ipv6-unicast-config Config Ipv6UnicastConfig `mapstructure:"config"` // original -> bgp-mp:ipv6-unicast-state State Ipv6UnicastState `mapstructure:"state"` } func (lhs *Ipv6Unicast) Equal(rhs *Ipv6Unicast) bool { if lhs == nil || rhs == nil { return false } if !lhs.PrefixLimit.Equal(&(rhs.PrefixLimit)) { return false } if !lhs.Config.Equal(&(rhs.Config)) { return false } return true } //struct for container bgp-mp:state type Ipv4UnicastState struct { // original -> bgp-mp:send-default-route //bgp-mp:send-default-route's original type is boolean SendDefaultRoute bool `mapstructure:"send-default-route"` } func (lhs *Ipv4UnicastState) Equal(rhs *Ipv4UnicastState) bool { if lhs == nil || rhs == nil { return false } if lhs.SendDefaultRoute != rhs.SendDefaultRoute { return false } return true } //struct for container bgp-mp:config type Ipv4UnicastConfig struct { // original -> bgp-mp:send-default-route //bgp-mp:send-default-route's original type is boolean SendDefaultRoute bool `mapstructure:"send-default-route"` } func (lhs *Ipv4UnicastConfig) Equal(rhs *Ipv4UnicastConfig) bool { if lhs == nil || rhs == nil { return false } if lhs.SendDefaultRoute != rhs.SendDefaultRoute { return false } return true } //struct for container bgp-mp:state type PrefixLimitState struct { // original -> bgp-mp:max-prefixes MaxPrefixes uint32 `mapstructure:"max-prefixes"` // original -> bgp-mp:shutdown-threshold-pct ShutdownThresholdPct Percentage `mapstructure:"shutdown-threshold-pct"` // original -> bgp-mp:restart-timer //bgp-mp:restart-timer's original type is decimal64 RestartTimer float64 `mapstructure:"restart-timer"` } func (lhs *PrefixLimitState) Equal(rhs *PrefixLimitState) bool { if lhs == nil || rhs == nil { return false } if lhs.MaxPrefixes != rhs.MaxPrefixes { return false } if lhs.ShutdownThresholdPct != rhs.ShutdownThresholdPct { return false } if lhs.RestartTimer != rhs.RestartTimer { return false } return true } //struct for container bgp-mp:config type PrefixLimitConfig struct { // original -> bgp-mp:max-prefixes MaxPrefixes uint32 `mapstructure:"max-prefixes"` // original -> bgp-mp:shutdown-threshold-pct ShutdownThresholdPct Percentage `mapstructure:"shutdown-threshold-pct"` // original -> bgp-mp:restart-timer //bgp-mp:restart-timer's original type is decimal64 RestartTimer float64 `mapstructure:"restart-timer"` } func (lhs *PrefixLimitConfig) Equal(rhs *PrefixLimitConfig) bool { if lhs == nil || rhs == nil { return false } if lhs.MaxPrefixes != rhs.MaxPrefixes { return false } if lhs.ShutdownThresholdPct != rhs.ShutdownThresholdPct { return false } if lhs.RestartTimer != rhs.RestartTimer { return false } return true } //struct for container bgp-mp:prefix-limit type PrefixLimit struct { // original -> bgp-mp:prefix-limit-config Config PrefixLimitConfig `mapstructure:"config"` // original -> bgp-mp:prefix-limit-state State PrefixLimitState `mapstructure:"state"` } func (lhs *PrefixLimit) Equal(rhs *PrefixLimit) bool { if lhs == nil || rhs == nil { return false } if !lhs.Config.Equal(&(rhs.Config)) { return false } return true } //struct for container bgp-mp:ipv4-unicast type Ipv4Unicast struct { // original -> bgp-mp:prefix-limit PrefixLimit PrefixLimit `mapstructure:"prefix-limit"` // original -> bgp-mp:ipv4-unicast-config Config Ipv4UnicastConfig `mapstructure:"config"` // original -> bgp-mp:ipv4-unicast-state State Ipv4UnicastState `mapstructure:"state"` } func (lhs *Ipv4Unicast) Equal(rhs *Ipv4Unicast) bool { if lhs == nil || rhs == nil { return false } if !lhs.PrefixLimit.Equal(&(rhs.PrefixLimit)) { return false } if !lhs.Config.Equal(&(rhs.Config)) { return false } return true } //struct for container rpol:state type ApplyPolicyState struct { // original -> rpol:import-policy ImportPolicyList []string `mapstructure:"import-policy-list"` // original -> rpol:default-import-policy DefaultImportPolicy DefaultPolicyType `mapstructure:"default-import-policy"` // original -> rpol:export-policy ExportPolicyList []string `mapstructure:"export-policy-list"` // original -> rpol:default-export-policy DefaultExportPolicy DefaultPolicyType `mapstructure:"default-export-policy"` // original -> gobgp:in-policy InPolicyList []string `mapstructure:"in-policy-list"` // original -> gobgp:default-in-policy DefaultInPolicy DefaultPolicyType `mapstructure:"default-in-policy"` } func (lhs *ApplyPolicyState) Equal(rhs *ApplyPolicyState) bool { if lhs == nil || rhs == nil { return false } if len(lhs.ImportPolicyList) != len(rhs.ImportPolicyList) { return false } for idx, l := range lhs.ImportPolicyList { if l != rhs.ImportPolicyList[idx] { return false } } if lhs.DefaultImportPolicy != rhs.DefaultImportPolicy { return false } if len(lhs.ExportPolicyList) != len(rhs.ExportPolicyList) { return false } for idx, l := range lhs.ExportPolicyList { if l != rhs.ExportPolicyList[idx] { return false } } if lhs.DefaultExportPolicy != rhs.DefaultExportPolicy { return false } if len(lhs.InPolicyList) != len(rhs.InPolicyList) { return false } for idx, l := range lhs.InPolicyList { if l != rhs.InPolicyList[idx] { return false } } if lhs.DefaultInPolicy != rhs.DefaultInPolicy { return false } return true } //struct for container rpol:config type ApplyPolicyConfig struct { // original -> rpol:import-policy ImportPolicyList []string `mapstructure:"import-policy-list"` // original -> rpol:default-import-policy DefaultImportPolicy DefaultPolicyType `mapstructure:"default-import-policy"` // original -> rpol:export-policy ExportPolicyList []string `mapstructure:"export-policy-list"` // original -> rpol:default-export-policy DefaultExportPolicy DefaultPolicyType `mapstructure:"default-export-policy"` // original -> gobgp:in-policy InPolicyList []string `mapstructure:"in-policy-list"` // original -> gobgp:default-in-policy DefaultInPolicy DefaultPolicyType `mapstructure:"default-in-policy"` } func (lhs *ApplyPolicyConfig) Equal(rhs *ApplyPolicyConfig) bool { if lhs == nil || rhs == nil { return false } if len(lhs.ImportPolicyList) != len(rhs.ImportPolicyList) { return false } for idx, l := range lhs.ImportPolicyList { if l != rhs.ImportPolicyList[idx] { return false } } if lhs.DefaultImportPolicy != rhs.DefaultImportPolicy { return false } if len(lhs.ExportPolicyList) != len(rhs.ExportPolicyList) { return false } for idx, l := range lhs.ExportPolicyList { if l != rhs.ExportPolicyList[idx] { return false } } if lhs.DefaultExportPolicy != rhs.DefaultExportPolicy { return false } if len(lhs.InPolicyList) != len(rhs.InPolicyList) { return false } for idx, l := range lhs.InPolicyList { if l != rhs.InPolicyList[idx] { return false } } if lhs.DefaultInPolicy != rhs.DefaultInPolicy { return false } return true } //struct for container rpol:apply-policy type ApplyPolicy struct { // original -> rpol:apply-policy-config Config ApplyPolicyConfig `mapstructure:"config"` // original -> rpol:apply-policy-state State ApplyPolicyState `mapstructure:"state"` } func (lhs *ApplyPolicy) Equal(rhs *ApplyPolicy) bool { if lhs == nil || rhs == nil { return false } if !lhs.Config.Equal(&(rhs.Config)) { return false } return true } //struct for container bgp-mp:state type AfiSafiState struct { // original -> bgp-mp:afi-safi-name AfiSafiName AfiSafiType `mapstructure:"afi-safi-name"` // original -> bgp-mp:enabled //bgp-mp:enabled's original type is boolean Enabled bool `mapstructure:"enabled"` // original -> bgp-op:total-paths TotalPaths uint32 `mapstructure:"total-paths"` // original -> bgp-op:total-prefixes TotalPrefixes uint32 `mapstructure:"total-prefixes"` } func (lhs *AfiSafiState) Equal(rhs *AfiSafiState) bool { if lhs == nil || rhs == nil { return false } if lhs.AfiSafiName != rhs.AfiSafiName { return false } if lhs.Enabled != rhs.Enabled { return false } if lhs.TotalPaths != rhs.TotalPaths { return false } if lhs.TotalPrefixes != rhs.TotalPrefixes { return false } return true } //struct for container bgp-mp:config type AfiSafiConfig struct { // original -> bgp-mp:afi-safi-name AfiSafiName AfiSafiType `mapstructure:"afi-safi-name"` // original -> bgp-mp:enabled //bgp-mp:enabled's original type is boolean Enabled bool `mapstructure:"enabled"` } func (lhs *AfiSafiConfig) Equal(rhs *AfiSafiConfig) bool { if lhs == nil || rhs == nil { return false } if lhs.AfiSafiName != rhs.AfiSafiName { return false } if lhs.Enabled != rhs.Enabled { return false } return true } //struct for container bgp-mp:state type MpGracefulRestartState struct { // original -> bgp-mp:enabled //bgp-mp:enabled's original type is boolean Enabled bool `mapstructure:"enabled"` // original -> bgp-op:received //bgp-op:received's original type is boolean Received bool `mapstructure:"received"` // original -> bgp-op:advertised //bgp-op:advertised's original type is boolean Advertised bool `mapstructure:"advertised"` // original -> gobgp:end-of-rib-received //gobgp:end-of-rib-received's original type is boolean EndOfRibReceived bool `mapstructure:"end-of-rib-received"` // original -> gobgp:end-of-rib-sent //gobgp:end-of-rib-sent's original type is boolean EndOfRibSent bool `mapstructure:"end-of-rib-sent"` } func (lhs *MpGracefulRestartState) Equal(rhs *MpGracefulRestartState) bool { if lhs == nil || rhs == nil { return false } if lhs.Enabled != rhs.Enabled { return false } if lhs.Received != rhs.Received { return false } if lhs.Advertised != rhs.Advertised { return false } if lhs.EndOfRibReceived != rhs.EndOfRibReceived { return false } if lhs.EndOfRibSent != rhs.EndOfRibSent { return false } return true } //struct for container bgp-mp:config type MpGracefulRestartConfig struct { // original -> bgp-mp:enabled //bgp-mp:enabled's original type is boolean Enabled bool `mapstructure:"enabled"` } func (lhs *MpGracefulRestartConfig) Equal(rhs *MpGracefulRestartConfig) bool { if lhs == nil || rhs == nil { return false } if lhs.Enabled != rhs.Enabled { return false } return true } //struct for container bgp-mp:graceful-restart type MpGracefulRestart struct { // original -> bgp-mp:mp-graceful-restart-config Config MpGracefulRestartConfig `mapstructure:"config"` // original -> bgp-mp:mp-graceful-restart-state State MpGracefulRestartState `mapstructure:"state"` } func (lhs *MpGracefulRestart) Equal(rhs *MpGracefulRestart) bool { if lhs == nil || rhs == nil { return false } if !lhs.Config.Equal(&(rhs.Config)) { return false } return true } //struct for container bgp-mp:afi-safi type AfiSafi struct { // original -> bgp-mp:afi-safi-name // original -> bgp-mp:mp-graceful-restart MpGracefulRestart MpGracefulRestart `mapstructure:"mp-graceful-restart"` // original -> bgp-mp:afi-safi-config Config AfiSafiConfig `mapstructure:"config"` // original -> bgp-mp:afi-safi-state State AfiSafiState `mapstructure:"state"` // original -> rpol:apply-policy ApplyPolicy ApplyPolicy `mapstructure:"apply-policy"` // original -> bgp-mp:ipv4-unicast Ipv4Unicast Ipv4Unicast `mapstructure:"ipv4-unicast"` // original -> bgp-mp:ipv6-unicast Ipv6Unicast Ipv6Unicast `mapstructure:"ipv6-unicast"` // original -> bgp-mp:ipv4-labelled-unicast Ipv4LabelledUnicast Ipv4LabelledUnicast `mapstructure:"ipv4-labelled-unicast"` // original -> bgp-mp:ipv6-labelled-unicast Ipv6LabelledUnicast Ipv6LabelledUnicast `mapstructure:"ipv6-labelled-unicast"` // original -> bgp-mp:l3vpn-ipv4-unicast L3vpnIpv4Unicast L3vpnIpv4Unicast `mapstructure:"l3vpn-ipv4-unicast"` // original -> bgp-mp:l3vpn-ipv6-unicast L3vpnIpv6Unicast L3vpnIpv6Unicast `mapstructure:"l3vpn-ipv6-unicast"` // original -> bgp-mp:l3vpn-ipv4-multicast L3vpnIpv4Multicast L3vpnIpv4Multicast `mapstructure:"l3vpn-ipv4-multicast"` // original -> bgp-mp:l3vpn-ipv6-multicast L3vpnIpv6Multicast L3vpnIpv6Multicast `mapstructure:"l3vpn-ipv6-multicast"` // original -> bgp-mp:l2vpn-vpls L2vpnVpls L2vpnVpls `mapstructure:"l2vpn-vpls"` // original -> bgp-mp:l2vpn-evpn L2vpnEvpn L2vpnEvpn `mapstructure:"l2vpn-evpn"` // original -> bgp-mp:route-selection-options RouteSelectionOptions RouteSelectionOptions `mapstructure:"route-selection-options"` // original -> bgp-mp:use-multiple-paths UseMultiplePaths UseMultiplePaths `mapstructure:"use-multiple-paths"` // original -> bgp-mp:prefix-limit PrefixLimit PrefixLimit `mapstructure:"prefix-limit"` // original -> gobgp:route-target-membership RouteTargetMembership RouteTargetMembership `mapstructure:"route-target-membership"` } func (lhs *AfiSafi) Equal(rhs *AfiSafi) bool { if lhs == nil || rhs == nil { return false } if !lhs.MpGracefulRestart.Equal(&(rhs.MpGracefulRestart)) { return false } if !lhs.Config.Equal(&(rhs.Config)) { return false } if !lhs.ApplyPolicy.Equal(&(rhs.ApplyPolicy)) { return false } if !lhs.Ipv4Unicast.Equal(&(rhs.Ipv4Unicast)) { return false } if !lhs.Ipv6Unicast.Equal(&(rhs.Ipv6Unicast)) { return false } if !lhs.Ipv4LabelledUnicast.Equal(&(rhs.Ipv4LabelledUnicast)) { return false } if !lhs.Ipv6LabelledUnicast.Equal(&(rhs.Ipv6LabelledUnicast)) { return false } if !lhs.L3vpnIpv4Unicast.Equal(&(rhs.L3vpnIpv4Unicast)) { return false } if !lhs.L3vpnIpv6Unicast.Equal(&(rhs.L3vpnIpv6Unicast)) { return false } if !lhs.L3vpnIpv4Multicast.Equal(&(rhs.L3vpnIpv4Multicast)) { return false } if !lhs.L3vpnIpv6Multicast.Equal(&(rhs.L3vpnIpv6Multicast)) { return false } if !lhs.L2vpnVpls.Equal(&(rhs.L2vpnVpls)) { return false } if !lhs.L2vpnEvpn.Equal(&(rhs.L2vpnEvpn)) { return false } if !lhs.RouteSelectionOptions.Equal(&(rhs.RouteSelectionOptions)) { return false } if !lhs.UseMultiplePaths.Equal(&(rhs.UseMultiplePaths)) { return false } if !lhs.PrefixLimit.Equal(&(rhs.PrefixLimit)) { return false } if !lhs.RouteTargetMembership.Equal(&(rhs.RouteTargetMembership)) { return false } return true } //struct for container bgp:state type GracefulRestartState struct { // original -> bgp:enabled //bgp:enabled's original type is boolean Enabled bool `mapstructure:"enabled"` // original -> bgp:restart-time RestartTime uint16 `mapstructure:"restart-time"` // original -> bgp:stale-routes-time //bgp:stale-routes-time's original type is decimal64 StaleRoutesTime float64 `mapstructure:"stale-routes-time"` // original -> bgp:helper-only //bgp:helper-only's original type is boolean HelperOnly bool `mapstructure:"helper-only"` // original -> bgp-op:peer-restart-time PeerRestartTime uint16 `mapstructure:"peer-restart-time"` // original -> bgp-op:peer-restarting //bgp-op:peer-restarting's original type is boolean PeerRestarting bool `mapstructure:"peer-restarting"` // original -> bgp-op:local-restarting //bgp-op:local-restarting's original type is boolean LocalRestarting bool `mapstructure:"local-restarting"` // original -> bgp-op:mode Mode Mode `mapstructure:"mode"` // original -> gobgp:deferral-time DeferralTime uint16 `mapstructure:"deferral-time"` } func (lhs *GracefulRestartState) Equal(rhs *GracefulRestartState) bool { if lhs == nil || rhs == nil { return false } if lhs.Enabled != rhs.Enabled { return false } if lhs.RestartTime != rhs.RestartTime { return false } if lhs.StaleRoutesTime != rhs.StaleRoutesTime { return false } if lhs.HelperOnly != rhs.HelperOnly { return false } if lhs.PeerRestartTime != rhs.PeerRestartTime { return false } if lhs.PeerRestarting != rhs.PeerRestarting { return false } if lhs.LocalRestarting != rhs.LocalRestarting { return false } if lhs.Mode != rhs.Mode { return false } if lhs.DeferralTime != rhs.DeferralTime { return false } return true } //struct for container bgp:config type GracefulRestartConfig struct { // original -> bgp:enabled //bgp:enabled's original type is boolean Enabled bool `mapstructure:"enabled"` // original -> bgp:restart-time RestartTime uint16 `mapstructure:"restart-time"` // original -> bgp:stale-routes-time //bgp:stale-routes-time's original type is decimal64 StaleRoutesTime float64 `mapstructure:"stale-routes-time"` // original -> bgp:helper-only //bgp:helper-only's original type is boolean HelperOnly bool `mapstructure:"helper-only"` // original -> gobgp:deferral-time DeferralTime uint16 `mapstructure:"deferral-time"` } func (lhs *GracefulRestartConfig) Equal(rhs *GracefulRestartConfig) bool { if lhs == nil || rhs == nil { return false } if lhs.Enabled != rhs.Enabled { return false } if lhs.RestartTime != rhs.RestartTime { return false } if lhs.StaleRoutesTime != rhs.StaleRoutesTime { return false } if lhs.HelperOnly != rhs.HelperOnly { return false } if lhs.DeferralTime != rhs.DeferralTime { return false } return true } //struct for container bgp:graceful-restart type GracefulRestart struct { // original -> bgp:graceful-restart-config Config GracefulRestartConfig `mapstructure:"config"` // original -> bgp:graceful-restart-state State GracefulRestartState `mapstructure:"state"` } func (lhs *GracefulRestart) Equal(rhs *GracefulRestart) bool { if lhs == nil || rhs == nil { return false } if !lhs.Config.Equal(&(rhs.Config)) { return false } return true } //struct for container bgp-mp:state type IbgpState struct { // original -> bgp-mp:maximum-paths MaximumPaths uint32 `mapstructure:"maximum-paths"` } func (lhs *IbgpState) Equal(rhs *IbgpState) bool { if lhs == nil || rhs == nil { return false } if lhs.MaximumPaths != rhs.MaximumPaths { return false } return true } //struct for container bgp-mp:config type IbgpConfig struct { // original -> bgp-mp:maximum-paths MaximumPaths uint32 `mapstructure:"maximum-paths"` } func (lhs *IbgpConfig) Equal(rhs *IbgpConfig) bool { if lhs == nil || rhs == nil { return false } if lhs.MaximumPaths != rhs.MaximumPaths { return false } return true } //struct for container bgp-mp:ibgp type Ibgp struct { // original -> bgp-mp:ibgp-config Config IbgpConfig `mapstructure:"config"` // original -> bgp-mp:ibgp-state State IbgpState `mapstructure:"state"` } func (lhs *Ibgp) Equal(rhs *Ibgp) bool { if lhs == nil || rhs == nil { return false } if !lhs.Config.Equal(&(rhs.Config)) { return false } return true } //struct for container bgp-mp:state type EbgpState struct { // original -> bgp-mp:allow-multiple-as //bgp-mp:allow-multiple-as's original type is boolean AllowMultipleAs bool `mapstructure:"allow-multiple-as"` // original -> bgp-mp:maximum-paths MaximumPaths uint32 `mapstructure:"maximum-paths"` } func (lhs *EbgpState) Equal(rhs *EbgpState) bool { if lhs == nil || rhs == nil { return false } if lhs.AllowMultipleAs != rhs.AllowMultipleAs { return false } if lhs.MaximumPaths != rhs.MaximumPaths { return false } return true } //struct for container bgp-mp:config type EbgpConfig struct { // original -> bgp-mp:allow-multiple-as //bgp-mp:allow-multiple-as's original type is boolean AllowMultipleAs bool `mapstructure:"allow-multiple-as"` // original -> bgp-mp:maximum-paths MaximumPaths uint32 `mapstructure:"maximum-paths"` } func (lhs *EbgpConfig) Equal(rhs *EbgpConfig) bool { if lhs == nil || rhs == nil { return false } if lhs.AllowMultipleAs != rhs.AllowMultipleAs { return false } if lhs.MaximumPaths != rhs.MaximumPaths { return false } return true } //struct for container bgp-mp:ebgp type Ebgp struct { // original -> bgp-mp:ebgp-config Config EbgpConfig `mapstructure:"config"` // original -> bgp-mp:ebgp-state State EbgpState `mapstructure:"state"` } func (lhs *Ebgp) Equal(rhs *Ebgp) bool { if lhs == nil || rhs == nil { return false } if !lhs.Config.Equal(&(rhs.Config)) { return false } return true } //struct for container bgp-mp:state type UseMultiplePathsState struct { // original -> bgp-mp:enabled //bgp-mp:enabled's original type is boolean Enabled bool `mapstructure:"enabled"` } func (lhs *UseMultiplePathsState) Equal(rhs *UseMultiplePathsState) bool { if lhs == nil || rhs == nil { return false } if lhs.Enabled != rhs.Enabled { return false } return true } //struct for container bgp-mp:config type UseMultiplePathsConfig struct { // original -> bgp-mp:enabled //bgp-mp:enabled's original type is boolean Enabled bool `mapstructure:"enabled"` } func (lhs *UseMultiplePathsConfig) Equal(rhs *UseMultiplePathsConfig) bool { if lhs == nil || rhs == nil { return false } if lhs.Enabled != rhs.Enabled { return false } return true } //struct for container bgp-mp:use-multiple-paths type UseMultiplePaths struct { // original -> bgp-mp:use-multiple-paths-config Config UseMultiplePathsConfig `mapstructure:"config"` // original -> bgp-mp:use-multiple-paths-state State UseMultiplePathsState `mapstructure:"state"` // original -> bgp-mp:ebgp Ebgp Ebgp `mapstructure:"ebgp"` // original -> bgp-mp:ibgp Ibgp Ibgp `mapstructure:"ibgp"` } func (lhs *UseMultiplePaths) Equal(rhs *UseMultiplePaths) bool { if lhs == nil || rhs == nil { return false } if !lhs.Config.Equal(&(rhs.Config)) { return false } if !lhs.Ebgp.Equal(&(rhs.Ebgp)) { return false } if !lhs.Ibgp.Equal(&(rhs.Ibgp)) { return false } return true } //struct for container bgp:state type ConfederationState struct { // original -> bgp:enabled //bgp:enabled's original type is boolean Enabled bool `mapstructure:"enabled"` // original -> bgp:identifier //bgp:identifier's original type is inet:as-number Identifier uint32 `mapstructure:"identifier"` // original -> bgp:member-as // original type is list of inet:as-number MemberAsList []uint32 `mapstructure:"member-as-list"` } func (lhs *ConfederationState) Equal(rhs *ConfederationState) bool { if lhs == nil || rhs == nil { return false } if lhs.Enabled != rhs.Enabled { return false } if lhs.Identifier != rhs.Identifier { return false } if len(lhs.MemberAsList) != len(rhs.MemberAsList) { return false } for idx, l := range lhs.MemberAsList { if l != rhs.MemberAsList[idx] { return false } } return true } //struct for container bgp:config type ConfederationConfig struct { // original -> bgp:enabled //bgp:enabled's original type is boolean Enabled bool `mapstructure:"enabled"` // original -> bgp:identifier //bgp:identifier's original type is inet:as-number Identifier uint32 `mapstructure:"identifier"` // original -> bgp:member-as // original type is list of inet:as-number MemberAsList []uint32 `mapstructure:"member-as-list"` } func (lhs *ConfederationConfig) Equal(rhs *ConfederationConfig) bool { if lhs == nil || rhs == nil { return false } if lhs.Enabled != rhs.Enabled { return false } if lhs.Identifier != rhs.Identifier { return false } if len(lhs.MemberAsList) != len(rhs.MemberAsList) { return false } for idx, l := range lhs.MemberAsList { if l != rhs.MemberAsList[idx] { return false } } return true } //struct for container bgp:confederation type Confederation struct { // original -> bgp:confederation-config Config ConfederationConfig `mapstructure:"config"` // original -> bgp:confederation-state State ConfederationState `mapstructure:"state"` } func (lhs *Confederation) Equal(rhs *Confederation) bool { if lhs == nil || rhs == nil { return false } if !lhs.Config.Equal(&(rhs.Config)) { return false } return true } //struct for container bgp:state type DefaultRouteDistanceState struct { // original -> bgp:external-route-distance ExternalRouteDistance uint8 `mapstructure:"external-route-distance"` // original -> bgp:internal-route-distance InternalRouteDistance uint8 `mapstructure:"internal-route-distance"` } func (lhs *DefaultRouteDistanceState) Equal(rhs *DefaultRouteDistanceState) bool { if lhs == nil || rhs == nil { return false } if lhs.ExternalRouteDistance != rhs.ExternalRouteDistance { return false } if lhs.InternalRouteDistance != rhs.InternalRouteDistance { return false } return true } //struct for container bgp:config type DefaultRouteDistanceConfig struct { // original -> bgp:external-route-distance ExternalRouteDistance uint8 `mapstructure:"external-route-distance"` // original -> bgp:internal-route-distance InternalRouteDistance uint8 `mapstructure:"internal-route-distance"` } func (lhs *DefaultRouteDistanceConfig) Equal(rhs *DefaultRouteDistanceConfig) bool { if lhs == nil || rhs == nil { return false } if lhs.ExternalRouteDistance != rhs.ExternalRouteDistance { return false } if lhs.InternalRouteDistance != rhs.InternalRouteDistance { return false } return true } //struct for container bgp:default-route-distance type DefaultRouteDistance struct { // original -> bgp:default-route-distance-config Config DefaultRouteDistanceConfig `mapstructure:"config"` // original -> bgp:default-route-distance-state State DefaultRouteDistanceState `mapstructure:"state"` } func (lhs *DefaultRouteDistance) Equal(rhs *DefaultRouteDistance) bool { if lhs == nil || rhs == nil { return false } if !lhs.Config.Equal(&(rhs.Config)) { return false } return true } //struct for container bgp-mp:state type RouteSelectionOptionsState struct { // original -> bgp-mp:always-compare-med //bgp-mp:always-compare-med's original type is boolean AlwaysCompareMed bool `mapstructure:"always-compare-med"` // original -> bgp-mp:ignore-as-path-length //bgp-mp:ignore-as-path-length's original type is boolean IgnoreAsPathLength bool `mapstructure:"ignore-as-path-length"` // original -> bgp-mp:external-compare-router-id //bgp-mp:external-compare-router-id's original type is boolean ExternalCompareRouterId bool `mapstructure:"external-compare-router-id"` // original -> bgp-mp:advertise-inactive-routes //bgp-mp:advertise-inactive-routes's original type is boolean AdvertiseInactiveRoutes bool `mapstructure:"advertise-inactive-routes"` // original -> bgp-mp:enable-aigp //bgp-mp:enable-aigp's original type is boolean EnableAigp bool `mapstructure:"enable-aigp"` // original -> bgp-mp:ignore-next-hop-igp-metric //bgp-mp:ignore-next-hop-igp-metric's original type is boolean IgnoreNextHopIgpMetric bool `mapstructure:"ignore-next-hop-igp-metric"` } func (lhs *RouteSelectionOptionsState) Equal(rhs *RouteSelectionOptionsState) bool { if lhs == nil || rhs == nil { return false } if lhs.AlwaysCompareMed != rhs.AlwaysCompareMed { return false } if lhs.IgnoreAsPathLength != rhs.IgnoreAsPathLength { return false } if lhs.ExternalCompareRouterId != rhs.ExternalCompareRouterId { return false } if lhs.AdvertiseInactiveRoutes != rhs.AdvertiseInactiveRoutes { return false } if lhs.EnableAigp != rhs.EnableAigp { return false } if lhs.IgnoreNextHopIgpMetric != rhs.IgnoreNextHopIgpMetric { return false } return true } //struct for container bgp-mp:config type RouteSelectionOptionsConfig struct { // original -> bgp-mp:always-compare-med //bgp-mp:always-compare-med's original type is boolean AlwaysCompareMed bool `mapstructure:"always-compare-med"` // original -> bgp-mp:ignore-as-path-length //bgp-mp:ignore-as-path-length's original type is boolean IgnoreAsPathLength bool `mapstructure:"ignore-as-path-length"` // original -> bgp-mp:external-compare-router-id //bgp-mp:external-compare-router-id's original type is boolean ExternalCompareRouterId bool `mapstructure:"external-compare-router-id"` // original -> bgp-mp:advertise-inactive-routes //bgp-mp:advertise-inactive-routes's original type is boolean AdvertiseInactiveRoutes bool `mapstructure:"advertise-inactive-routes"` // original -> bgp-mp:enable-aigp //bgp-mp:enable-aigp's original type is boolean EnableAigp bool `mapstructure:"enable-aigp"` // original -> bgp-mp:ignore-next-hop-igp-metric //bgp-mp:ignore-next-hop-igp-metric's original type is boolean IgnoreNextHopIgpMetric bool `mapstructure:"ignore-next-hop-igp-metric"` } func (lhs *RouteSelectionOptionsConfig) Equal(rhs *RouteSelectionOptionsConfig) bool { if lhs == nil || rhs == nil { return false } if lhs.AlwaysCompareMed != rhs.AlwaysCompareMed { return false } if lhs.IgnoreAsPathLength != rhs.IgnoreAsPathLength { return false } if lhs.ExternalCompareRouterId != rhs.ExternalCompareRouterId { return false } if lhs.AdvertiseInactiveRoutes != rhs.AdvertiseInactiveRoutes { return false } if lhs.EnableAigp != rhs.EnableAigp { return false } if lhs.IgnoreNextHopIgpMetric != rhs.IgnoreNextHopIgpMetric { return false } return true } //struct for container bgp-mp:route-selection-options type RouteSelectionOptions struct { // original -> bgp-mp:route-selection-options-config Config RouteSelectionOptionsConfig `mapstructure:"config"` // original -> bgp-mp:route-selection-options-state State RouteSelectionOptionsState `mapstructure:"state"` } func (lhs *RouteSelectionOptions) Equal(rhs *RouteSelectionOptions) bool { if lhs == nil || rhs == nil { return false } if !lhs.Config.Equal(&(rhs.Config)) { return false } return true } //struct for container bgp:state type GlobalState struct { // original -> bgp:as //bgp:as's original type is inet:as-number As uint32 `mapstructure:"as"` // original -> bgp:router-id //bgp:router-id's original type is inet:ipv4-address RouterId string `mapstructure:"router-id"` // original -> bgp-op:total-paths TotalPaths uint32 `mapstructure:"total-paths"` // original -> bgp-op:total-prefixes TotalPrefixes uint32 `mapstructure:"total-prefixes"` // original -> gobgp:port Port int32 `mapstructure:"port"` // original -> gobgp:local-address LocalAddressList []string `mapstructure:"local-address-list"` } func (lhs *GlobalState) Equal(rhs *GlobalState) bool { if lhs == nil || rhs == nil { return false } if lhs.As != rhs.As { return false } if lhs.RouterId != rhs.RouterId { return false } if lhs.TotalPaths != rhs.TotalPaths { return false } if lhs.TotalPrefixes != rhs.TotalPrefixes { return false } if lhs.Port != rhs.Port { return false } if len(lhs.LocalAddressList) != len(rhs.LocalAddressList) { return false } for idx, l := range lhs.LocalAddressList { if l != rhs.LocalAddressList[idx] { return false } } return true } //struct for container bgp:config type GlobalConfig struct { // original -> bgp:as //bgp:as's original type is inet:as-number As uint32 `mapstructure:"as"` // original -> bgp:router-id //bgp:router-id's original type is inet:ipv4-address RouterId string `mapstructure:"router-id"` // original -> gobgp:port Port int32 `mapstructure:"port"` // original -> gobgp:local-address LocalAddressList []string `mapstructure:"local-address-list"` } func (lhs *GlobalConfig) Equal(rhs *GlobalConfig) bool { if lhs == nil || rhs == nil { return false } if lhs.As != rhs.As { return false } if lhs.RouterId != rhs.RouterId { return false } if lhs.Port != rhs.Port { return false } if len(lhs.LocalAddressList) != len(rhs.LocalAddressList) { return false } for idx, l := range lhs.LocalAddressList { if l != rhs.LocalAddressList[idx] { return false } } return true } //struct for container bgp:global type Global struct { // original -> bgp:global-config Config GlobalConfig `mapstructure:"config"` // original -> bgp:global-state State GlobalState `mapstructure:"state"` // original -> bgp-mp:route-selection-options RouteSelectionOptions RouteSelectionOptions `mapstructure:"route-selection-options"` // original -> bgp:default-route-distance DefaultRouteDistance DefaultRouteDistance `mapstructure:"default-route-distance"` // original -> bgp:confederation Confederation Confederation `mapstructure:"confederation"` // original -> bgp-mp:use-multiple-paths UseMultiplePaths UseMultiplePaths `mapstructure:"use-multiple-paths"` // original -> bgp:graceful-restart GracefulRestart GracefulRestart `mapstructure:"graceful-restart"` // original -> bgp:afi-safis AfiSafis []AfiSafi `mapstructure:"afi-safis"` // original -> rpol:apply-policy ApplyPolicy ApplyPolicy `mapstructure:"apply-policy"` // original -> gobgp:mpls-label-range MplsLabelRange MplsLabelRange `mapstructure:"mpls-label-range"` } func (lhs *Global) Equal(rhs *Global) bool { if lhs == nil || rhs == nil { return false } if !lhs.Config.Equal(&(rhs.Config)) { return false } if !lhs.RouteSelectionOptions.Equal(&(rhs.RouteSelectionOptions)) { return false } if !lhs.DefaultRouteDistance.Equal(&(rhs.DefaultRouteDistance)) { return false } if !lhs.Confederation.Equal(&(rhs.Confederation)) { return false } if !lhs.UseMultiplePaths.Equal(&(rhs.UseMultiplePaths)) { return false } if !lhs.GracefulRestart.Equal(&(rhs.GracefulRestart)) { return false } if len(lhs.AfiSafis) != len(rhs.AfiSafis) { return false } { lmap := make(map[string]*AfiSafi) for i, l := range lhs.AfiSafis { lmap[mapkey(i, string(l.Config.AfiSafiName))] = &lhs.AfiSafis[i] } for i, r := range rhs.AfiSafis { if l, y := lmap[mapkey(i, string(r.Config.AfiSafiName))]; !y { return false } else if !r.Equal(l) { return false } } } if !lhs.ApplyPolicy.Equal(&(rhs.ApplyPolicy)) { return false } if !lhs.MplsLabelRange.Equal(&(rhs.MplsLabelRange)) { return false } return true } //struct for container bgp:bgp type Bgp struct { // original -> bgp:global Global Global `mapstructure:"global"` // original -> bgp:neighbors Neighbors []Neighbor `mapstructure:"neighbors"` // original -> bgp:peer-groups PeerGroups []PeerGroup `mapstructure:"peer-groups"` // original -> gobgp:rpki-servers RpkiServers []RpkiServer `mapstructure:"rpki-servers"` // original -> gobgp:bmp-servers BmpServers []BmpServer `mapstructure:"bmp-servers"` // original -> gobgp:mrt-dump MrtDump []Mrt `mapstructure:"mrt-dump"` // original -> gobgp:zebra Zebra Zebra `mapstructure:"zebra"` // original -> gobgp:collector Collector Collector `mapstructure:"collector"` } func (lhs *Bgp) Equal(rhs *Bgp) bool { if lhs == nil || rhs == nil { return false } if !lhs.Global.Equal(&(rhs.Global)) { return false } if len(lhs.Neighbors) != len(rhs.Neighbors) { return false } { lmap := make(map[string]*Neighbor) for i, l := range lhs.Neighbors { lmap[mapkey(i, string(l.Config.NeighborAddress))] = &lhs.Neighbors[i] } for i, r := range rhs.Neighbors { if l, y := lmap[mapkey(i, string(r.Config.NeighborAddress))]; !y { return false } else if !r.Equal(l) { return false } } } if len(lhs.PeerGroups) != len(rhs.PeerGroups) { return false } { lmap := make(map[string]*PeerGroup) for i, l := range lhs.PeerGroups { lmap[mapkey(i, string(l.Config.PeerGroupName))] = &lhs.PeerGroups[i] } for i, r := range rhs.PeerGroups { if l, y := lmap[mapkey(i, string(r.Config.PeerGroupName))]; !y { return false } else if !r.Equal(l) { return false } } } if len(lhs.RpkiServers) != len(rhs.RpkiServers) { return false } { lmap := make(map[string]*RpkiServer) for i, l := range lhs.RpkiServers { lmap[mapkey(i, string(l.Config.Address))] = &lhs.RpkiServers[i] } for i, r := range rhs.RpkiServers { if l, y := lmap[mapkey(i, string(r.Config.Address))]; !y { return false } else if !r.Equal(l) { return false } } } if len(lhs.BmpServers) != len(rhs.BmpServers) { return false } { lmap := make(map[string]*BmpServer) for i, l := range lhs.BmpServers { lmap[mapkey(i, string(l.Config.Address))] = &lhs.BmpServers[i] } for i, r := range rhs.BmpServers { if l, y := lmap[mapkey(i, string(r.Config.Address))]; !y { return false } else if !r.Equal(l) { return false } } } if len(lhs.MrtDump) != len(rhs.MrtDump) { return false } { lmap := make(map[string]*Mrt) for i, l := range lhs.MrtDump { lmap[mapkey(i, string(l.Config.FileName))] = &lhs.MrtDump[i] } for i, r := range rhs.MrtDump { if l, y := lmap[mapkey(i, string(r.Config.FileName))]; !y { return false } else if !r.Equal(l) { return false } } } if !lhs.Zebra.Equal(&(rhs.Zebra)) { return false } if !lhs.Collector.Equal(&(rhs.Collector)) { return false } return true } //struct for container bgp-pol:set-ext-community-method type SetExtCommunityMethod struct { // original -> bgp-pol:communities // original type is list of union CommunitiesList []string `mapstructure:"communities-list"` // original -> bgp-pol:ext-community-set-ref ExtCommunitySetRef string `mapstructure:"ext-community-set-ref"` } func (lhs *SetExtCommunityMethod) Equal(rhs *SetExtCommunityMethod) bool { if lhs == nil || rhs == nil { return false } if len(lhs.CommunitiesList) != len(rhs.CommunitiesList) { return false } for idx, l := range lhs.CommunitiesList { if l != rhs.CommunitiesList[idx] { return false } } if lhs.ExtCommunitySetRef != rhs.ExtCommunitySetRef { return false } return true } //struct for container bgp-pol:set-ext-community type SetExtCommunity struct { // original -> bgp-pol:set-ext-community-method SetExtCommunityMethod SetExtCommunityMethod `mapstructure:"set-ext-community-method"` // original -> bgp-pol:options //bgp-pol:options's original type is bgp-set-community-option-type Options string `mapstructure:"options"` } func (lhs *SetExtCommunity) Equal(rhs *SetExtCommunity) bool { if lhs == nil || rhs == nil { return false } if !lhs.SetExtCommunityMethod.Equal(&(rhs.SetExtCommunityMethod)) { return false } if lhs.Options != rhs.Options { return false } return true } //struct for container bgp-pol:set-community-method type SetCommunityMethod struct { // original -> bgp-pol:communities // original type is list of union CommunitiesList []string `mapstructure:"communities-list"` // original -> bgp-pol:community-set-ref CommunitySetRef string `mapstructure:"community-set-ref"` } func (lhs *SetCommunityMethod) Equal(rhs *SetCommunityMethod) bool { if lhs == nil || rhs == nil { return false } if len(lhs.CommunitiesList) != len(rhs.CommunitiesList) { return false } for idx, l := range lhs.CommunitiesList { if l != rhs.CommunitiesList[idx] { return false } } if lhs.CommunitySetRef != rhs.CommunitySetRef { return false } return true } //struct for container bgp-pol:set-community type SetCommunity struct { // original -> bgp-pol:set-community-method SetCommunityMethod SetCommunityMethod `mapstructure:"set-community-method"` // original -> bgp-pol:options //bgp-pol:options's original type is bgp-set-community-option-type Options string `mapstructure:"options"` } func (lhs *SetCommunity) Equal(rhs *SetCommunity) bool { if lhs == nil || rhs == nil { return false } if !lhs.SetCommunityMethod.Equal(&(rhs.SetCommunityMethod)) { return false } if lhs.Options != rhs.Options { return false } return true } //struct for container bgp-pol:set-as-path-prepend type SetAsPathPrepend struct { // original -> bgp-pol:repeat-n RepeatN uint8 `mapstructure:"repeat-n"` // original -> gobgp:as //gobgp:as's original type is union As string `mapstructure:"as"` } func (lhs *SetAsPathPrepend) Equal(rhs *SetAsPathPrepend) bool { if lhs == nil || rhs == nil { return false } if lhs.RepeatN != rhs.RepeatN { return false } if lhs.As != rhs.As { return false } return true } //struct for container bgp-pol:bgp-actions type BgpActions struct { // original -> bgp-pol:set-as-path-prepend SetAsPathPrepend SetAsPathPrepend `mapstructure:"set-as-path-prepend"` // original -> bgp-pol:set-community SetCommunity SetCommunity `mapstructure:"set-community"` // original -> bgp-pol:set-ext-community SetExtCommunity SetExtCommunity `mapstructure:"set-ext-community"` // original -> bgp-pol:set-route-origin SetRouteOrigin BgpOriginAttrType `mapstructure:"set-route-origin"` // original -> bgp-pol:set-local-pref SetLocalPref uint32 `mapstructure:"set-local-pref"` // original -> bgp-pol:set-next-hop SetNextHop BgpNextHopType `mapstructure:"set-next-hop"` // original -> bgp-pol:set-med SetMed BgpSetMedType `mapstructure:"set-med"` } func (lhs *BgpActions) Equal(rhs *BgpActions) bool { if lhs == nil || rhs == nil { return false } if !lhs.SetAsPathPrepend.Equal(&(rhs.SetAsPathPrepend)) { return false } if !lhs.SetCommunity.Equal(&(rhs.SetCommunity)) { return false } if !lhs.SetExtCommunity.Equal(&(rhs.SetExtCommunity)) { return false } if lhs.SetRouteOrigin != rhs.SetRouteOrigin { return false } if lhs.SetLocalPref != rhs.SetLocalPref { return false } if lhs.SetNextHop != rhs.SetNextHop { return false } if lhs.SetMed != rhs.SetMed { return false } return true } //struct for container rpol:igp-actions type IgpActions struct { // original -> rpol:set-tag SetTag TagType `mapstructure:"set-tag"` } func (lhs *IgpActions) Equal(rhs *IgpActions) bool { if lhs == nil || rhs == nil { return false } if lhs.SetTag != rhs.SetTag { return false } return true } //struct for container rpol:route-disposition type RouteDisposition struct { // original -> rpol:accept-route //rpol:accept-route's original type is empty AcceptRoute bool `mapstructure:"accept-route"` // original -> rpol:reject-route //rpol:reject-route's original type is empty RejectRoute bool `mapstructure:"reject-route"` } func (lhs *RouteDisposition) Equal(rhs *RouteDisposition) bool { if lhs == nil || rhs == nil { return false } if lhs.AcceptRoute != rhs.AcceptRoute { return false } if lhs.RejectRoute != rhs.RejectRoute { return false } return true } //struct for container rpol:actions type Actions struct { // original -> rpol:route-disposition RouteDisposition RouteDisposition `mapstructure:"route-disposition"` // original -> rpol:igp-actions IgpActions IgpActions `mapstructure:"igp-actions"` // original -> bgp-pol:bgp-actions BgpActions BgpActions `mapstructure:"bgp-actions"` } func (lhs *Actions) Equal(rhs *Actions) bool { if lhs == nil || rhs == nil { return false } if !lhs.RouteDisposition.Equal(&(rhs.RouteDisposition)) { return false } if !lhs.IgpActions.Equal(&(rhs.IgpActions)) { return false } if !lhs.BgpActions.Equal(&(rhs.BgpActions)) { return false } return true } //struct for container bgp-pol:as-path-length type AsPathLength struct { // original -> ptypes:operator Operator AttributeComparison `mapstructure:"operator"` // original -> ptypes:value Value uint32 `mapstructure:"value"` } func (lhs *AsPathLength) Equal(rhs *AsPathLength) bool { if lhs == nil || rhs == nil { return false } if lhs.Operator != rhs.Operator { return false } if lhs.Value != rhs.Value { return false } return true } //struct for container bgp-pol:community-count type CommunityCount struct { // original -> ptypes:operator Operator AttributeComparison `mapstructure:"operator"` // original -> ptypes:value Value uint32 `mapstructure:"value"` } func (lhs *CommunityCount) Equal(rhs *CommunityCount) bool { if lhs == nil || rhs == nil { return false } if lhs.Operator != rhs.Operator { return false } if lhs.Value != rhs.Value { return false } return true } //struct for container bgp-pol:match-as-path-set type MatchAsPathSet struct { // original -> bgp-pol:as-path-set AsPathSet string `mapstructure:"as-path-set"` // original -> rpol:match-set-options MatchSetOptions MatchSetOptionsType `mapstructure:"match-set-options"` } func (lhs *MatchAsPathSet) Equal(rhs *MatchAsPathSet) bool { if lhs == nil || rhs == nil { return false } if lhs.AsPathSet != rhs.AsPathSet { return false } if lhs.MatchSetOptions != rhs.MatchSetOptions { return false } return true } //struct for container bgp-pol:match-ext-community-set type MatchExtCommunitySet struct { // original -> bgp-pol:ext-community-set ExtCommunitySet string `mapstructure:"ext-community-set"` // original -> rpol:match-set-options MatchSetOptions MatchSetOptionsType `mapstructure:"match-set-options"` } func (lhs *MatchExtCommunitySet) Equal(rhs *MatchExtCommunitySet) bool { if lhs == nil || rhs == nil { return false } if lhs.ExtCommunitySet != rhs.ExtCommunitySet { return false } if lhs.MatchSetOptions != rhs.MatchSetOptions { return false } return true } //struct for container bgp-pol:match-community-set type MatchCommunitySet struct { // original -> bgp-pol:community-set CommunitySet string `mapstructure:"community-set"` // original -> rpol:match-set-options MatchSetOptions MatchSetOptionsType `mapstructure:"match-set-options"` } func (lhs *MatchCommunitySet) Equal(rhs *MatchCommunitySet) bool { if lhs == nil || rhs == nil { return false } if lhs.CommunitySet != rhs.CommunitySet { return false } if lhs.MatchSetOptions != rhs.MatchSetOptions { return false } return true } //struct for container bgp-pol:bgp-conditions type BgpConditions struct { // original -> bgp-pol:match-community-set MatchCommunitySet MatchCommunitySet `mapstructure:"match-community-set"` // original -> bgp-pol:match-ext-community-set MatchExtCommunitySet MatchExtCommunitySet `mapstructure:"match-ext-community-set"` // original -> bgp-pol:match-as-path-set MatchAsPathSet MatchAsPathSet `mapstructure:"match-as-path-set"` // original -> bgp-pol:med-eq MedEq uint32 `mapstructure:"med-eq"` // original -> bgp-pol:origin-eq OriginEq BgpOriginAttrType `mapstructure:"origin-eq"` // original -> bgp-pol:next-hop-in // original type is list of inet:ip-address NextHopInList []string `mapstructure:"next-hop-in-list"` // original -> bgp-pol:afi-safi-in AfiSafiInList []AfiSafiType `mapstructure:"afi-safi-in-list"` // original -> bgp-pol:local-pref-eq LocalPrefEq uint32 `mapstructure:"local-pref-eq"` // original -> bgp-pol:community-count CommunityCount CommunityCount `mapstructure:"community-count"` // original -> bgp-pol:as-path-length AsPathLength AsPathLength `mapstructure:"as-path-length"` // original -> bgp-pol:route-type RouteType RouteType `mapstructure:"route-type"` // original -> gobgp:rpki-validation-result RpkiValidationResult RpkiValidationResultType `mapstructure:"rpki-validation-result"` } func (lhs *BgpConditions) Equal(rhs *BgpConditions) bool { if lhs == nil || rhs == nil { return false } if !lhs.MatchCommunitySet.Equal(&(rhs.MatchCommunitySet)) { return false } if !lhs.MatchExtCommunitySet.Equal(&(rhs.MatchExtCommunitySet)) { return false } if !lhs.MatchAsPathSet.Equal(&(rhs.MatchAsPathSet)) { return false } if lhs.MedEq != rhs.MedEq { return false } if lhs.OriginEq != rhs.OriginEq { return false } if len(lhs.NextHopInList) != len(rhs.NextHopInList) { return false } for idx, l := range lhs.NextHopInList { if l != rhs.NextHopInList[idx] { return false } } if len(lhs.AfiSafiInList) != len(rhs.AfiSafiInList) { return false } for idx, l := range lhs.AfiSafiInList { if l != rhs.AfiSafiInList[idx] { return false } } if lhs.LocalPrefEq != rhs.LocalPrefEq { return false } if !lhs.CommunityCount.Equal(&(rhs.CommunityCount)) { return false } if !lhs.AsPathLength.Equal(&(rhs.AsPathLength)) { return false } if lhs.RouteType != rhs.RouteType { return false } if lhs.RpkiValidationResult != rhs.RpkiValidationResult { return false } return true } //struct for container rpol:igp-conditions type IgpConditions struct { } func (lhs *IgpConditions) Equal(rhs *IgpConditions) bool { if lhs == nil || rhs == nil { return false } return true } //struct for container rpol:match-tag-set type MatchTagSet struct { // original -> rpol:tag-set TagSet string `mapstructure:"tag-set"` // original -> rpol:match-set-options MatchSetOptions MatchSetOptionsRestrictedType `mapstructure:"match-set-options"` } func (lhs *MatchTagSet) Equal(rhs *MatchTagSet) bool { if lhs == nil || rhs == nil { return false } if lhs.TagSet != rhs.TagSet { return false } if lhs.MatchSetOptions != rhs.MatchSetOptions { return false } return true } //struct for container rpol:match-neighbor-set type MatchNeighborSet struct { // original -> rpol:neighbor-set NeighborSet string `mapstructure:"neighbor-set"` // original -> rpol:match-set-options MatchSetOptions MatchSetOptionsRestrictedType `mapstructure:"match-set-options"` } func (lhs *MatchNeighborSet) Equal(rhs *MatchNeighborSet) bool { if lhs == nil || rhs == nil { return false } if lhs.NeighborSet != rhs.NeighborSet { return false } if lhs.MatchSetOptions != rhs.MatchSetOptions { return false } return true } //struct for container rpol:match-prefix-set type MatchPrefixSet struct { // original -> rpol:prefix-set PrefixSet string `mapstructure:"prefix-set"` // original -> rpol:match-set-options MatchSetOptions MatchSetOptionsRestrictedType `mapstructure:"match-set-options"` } func (lhs *MatchPrefixSet) Equal(rhs *MatchPrefixSet) bool { if lhs == nil || rhs == nil { return false } if lhs.PrefixSet != rhs.PrefixSet { return false } if lhs.MatchSetOptions != rhs.MatchSetOptions { return false } return true } //struct for container rpol:conditions type Conditions struct { // original -> rpol:call-policy CallPolicy string `mapstructure:"call-policy"` // original -> rpol:match-prefix-set MatchPrefixSet MatchPrefixSet `mapstructure:"match-prefix-set"` // original -> rpol:match-neighbor-set MatchNeighborSet MatchNeighborSet `mapstructure:"match-neighbor-set"` // original -> rpol:match-tag-set MatchTagSet MatchTagSet `mapstructure:"match-tag-set"` // original -> rpol:install-protocol-eq InstallProtocolEq InstallProtocolType `mapstructure:"install-protocol-eq"` // original -> rpol:igp-conditions IgpConditions IgpConditions `mapstructure:"igp-conditions"` // original -> bgp-pol:bgp-conditions BgpConditions BgpConditions `mapstructure:"bgp-conditions"` } func (lhs *Conditions) Equal(rhs *Conditions) bool { if lhs == nil || rhs == nil { return false } if lhs.CallPolicy != rhs.CallPolicy { return false } if !lhs.MatchPrefixSet.Equal(&(rhs.MatchPrefixSet)) { return false } if !lhs.MatchNeighborSet.Equal(&(rhs.MatchNeighborSet)) { return false } if !lhs.MatchTagSet.Equal(&(rhs.MatchTagSet)) { return false } if lhs.InstallProtocolEq != rhs.InstallProtocolEq { return false } if !lhs.IgpConditions.Equal(&(rhs.IgpConditions)) { return false } if !lhs.BgpConditions.Equal(&(rhs.BgpConditions)) { return false } return true } //struct for container rpol:statement type Statement struct { // original -> rpol:name Name string `mapstructure:"name"` // original -> rpol:conditions Conditions Conditions `mapstructure:"conditions"` // original -> rpol:actions Actions Actions `mapstructure:"actions"` } func (lhs *Statement) Equal(rhs *Statement) bool { if lhs == nil || rhs == nil { return false } if lhs.Name != rhs.Name { return false } if !lhs.Conditions.Equal(&(rhs.Conditions)) { return false } if !lhs.Actions.Equal(&(rhs.Actions)) { return false } return true } //struct for container rpol:policy-definition type PolicyDefinition struct { // original -> rpol:name Name string `mapstructure:"name"` // original -> rpol:statements Statements []Statement `mapstructure:"statements"` } func (lhs *PolicyDefinition) Equal(rhs *PolicyDefinition) bool { if lhs == nil || rhs == nil { return false } if lhs.Name != rhs.Name { return false } if len(lhs.Statements) != len(rhs.Statements) { return false } { lmap := make(map[string]*Statement) for i, l := range lhs.Statements { lmap[mapkey(i, string(l.Name))] = &lhs.Statements[i] } for i, r := range rhs.Statements { if l, y := lmap[mapkey(i, string(r.Name))]; !y { return false } else if !r.Equal(l) { return false } } } return true } //struct for container bgp-pol:as-path-set type AsPathSet struct { // original -> bgp-pol:as-path-set-name AsPathSetName string `mapstructure:"as-path-set-name"` // original -> gobgp:as-path AsPathList []string `mapstructure:"as-path-list"` } func (lhs *AsPathSet) Equal(rhs *AsPathSet) bool { if lhs == nil || rhs == nil { return false } if lhs.AsPathSetName != rhs.AsPathSetName { return false } if len(lhs.AsPathList) != len(rhs.AsPathList) { return false } for idx, l := range lhs.AsPathList { if l != rhs.AsPathList[idx] { return false } } return true } //struct for container bgp-pol:ext-community-set type ExtCommunitySet struct { // original -> bgp-pol:ext-community-set-name ExtCommunitySetName string `mapstructure:"ext-community-set-name"` // original -> gobgp:ext-community ExtCommunityList []string `mapstructure:"ext-community-list"` } func (lhs *ExtCommunitySet) Equal(rhs *ExtCommunitySet) bool { if lhs == nil || rhs == nil { return false } if lhs.ExtCommunitySetName != rhs.ExtCommunitySetName { return false } if len(lhs.ExtCommunityList) != len(rhs.ExtCommunityList) { return false } for idx, l := range lhs.ExtCommunityList { if l != rhs.ExtCommunityList[idx] { return false } } return true } //struct for container bgp-pol:community-set type CommunitySet struct { // original -> bgp-pol:community-set-name CommunitySetName string `mapstructure:"community-set-name"` // original -> gobgp:community CommunityList []string `mapstructure:"community-list"` } func (lhs *CommunitySet) Equal(rhs *CommunitySet) bool { if lhs == nil || rhs == nil { return false } if lhs.CommunitySetName != rhs.CommunitySetName { return false } if len(lhs.CommunityList) != len(rhs.CommunityList) { return false } for idx, l := range lhs.CommunityList { if l != rhs.CommunityList[idx] { return false } } return true } //struct for container bgp-pol:bgp-defined-sets type BgpDefinedSets struct { // original -> bgp-pol:community-sets CommunitySets []CommunitySet `mapstructure:"community-sets"` // original -> bgp-pol:ext-community-sets ExtCommunitySets []ExtCommunitySet `mapstructure:"ext-community-sets"` // original -> bgp-pol:as-path-sets AsPathSets []AsPathSet `mapstructure:"as-path-sets"` } func (lhs *BgpDefinedSets) Equal(rhs *BgpDefinedSets) bool { if lhs == nil || rhs == nil { return false } if len(lhs.CommunitySets) != len(rhs.CommunitySets) { return false } { lmap := make(map[string]*CommunitySet) for i, l := range lhs.CommunitySets { lmap[mapkey(i, string(l.CommunitySetName))] = &lhs.CommunitySets[i] } for i, r := range rhs.CommunitySets { if l, y := lmap[mapkey(i, string(r.CommunitySetName))]; !y { return false } else if !r.Equal(l) { return false } } } if len(lhs.ExtCommunitySets) != len(rhs.ExtCommunitySets) { return false } { lmap := make(map[string]*ExtCommunitySet) for i, l := range lhs.ExtCommunitySets { lmap[mapkey(i, string(l.ExtCommunitySetName))] = &lhs.ExtCommunitySets[i] } for i, r := range rhs.ExtCommunitySets { if l, y := lmap[mapkey(i, string(r.ExtCommunitySetName))]; !y { return false } else if !r.Equal(l) { return false } } } if len(lhs.AsPathSets) != len(rhs.AsPathSets) { return false } { lmap := make(map[string]*AsPathSet) for i, l := range lhs.AsPathSets { lmap[mapkey(i, string(l.AsPathSetName))] = &lhs.AsPathSets[i] } for i, r := range rhs.AsPathSets { if l, y := lmap[mapkey(i, string(r.AsPathSetName))]; !y { return false } else if !r.Equal(l) { return false } } } return true } //struct for container rpol:tag type Tag struct { // original -> rpol:value Value TagType `mapstructure:"value"` } func (lhs *Tag) Equal(rhs *Tag) bool { if lhs == nil || rhs == nil { return false } if lhs.Value != rhs.Value { return false } return true } //struct for container rpol:tag-set type TagSet struct { // original -> rpol:tag-set-name TagSetName string `mapstructure:"tag-set-name"` // original -> rpol:tag TagList []Tag `mapstructure:"tag-list"` } func (lhs *TagSet) Equal(rhs *TagSet) bool { if lhs == nil || rhs == nil { return false } if lhs.TagSetName != rhs.TagSetName { return false } if len(lhs.TagList) != len(rhs.TagList) { return false } { lmap := make(map[string]*Tag) for i, l := range lhs.TagList { lmap[mapkey(i, string(l.Value))] = &lhs.TagList[i] } for i, r := range rhs.TagList { if l, y := lmap[mapkey(i, string(r.Value))]; !y { return false } else if !r.Equal(l) { return false } } } return true } //struct for container rpol:neighbor-set type NeighborSet struct { // original -> rpol:neighbor-set-name NeighborSetName string `mapstructure:"neighbor-set-name"` // original -> gobgp:neighbor-info // original type is list of inet:ip-address NeighborInfoList []string `mapstructure:"neighbor-info-list"` } func (lhs *NeighborSet) Equal(rhs *NeighborSet) bool { if lhs == nil || rhs == nil { return false } if lhs.NeighborSetName != rhs.NeighborSetName { return false } if len(lhs.NeighborInfoList) != len(rhs.NeighborInfoList) { return false } for idx, l := range lhs.NeighborInfoList { if l != rhs.NeighborInfoList[idx] { return false } } return true } //struct for container rpol:prefix type Prefix struct { // original -> rpol:ip-prefix //rpol:ip-prefix's original type is inet:ip-prefix IpPrefix string `mapstructure:"ip-prefix"` // original -> rpol:masklength-range MasklengthRange string `mapstructure:"masklength-range"` } func (lhs *Prefix) Equal(rhs *Prefix) bool { if lhs == nil || rhs == nil { return false } if lhs.IpPrefix != rhs.IpPrefix { return false } if lhs.MasklengthRange != rhs.MasklengthRange { return false } return true } //struct for container rpol:prefix-set type PrefixSet struct { // original -> rpol:prefix-set-name PrefixSetName string `mapstructure:"prefix-set-name"` // original -> rpol:prefix PrefixList []Prefix `mapstructure:"prefix-list"` } func (lhs *PrefixSet) Equal(rhs *PrefixSet) bool { if lhs == nil || rhs == nil { return false } if lhs.PrefixSetName != rhs.PrefixSetName { return false } if len(lhs.PrefixList) != len(rhs.PrefixList) { return false } { lmap := make(map[string]*Prefix) for i, l := range lhs.PrefixList { lmap[mapkey(i, string(l.IpPrefix+l.MasklengthRange))] = &lhs.PrefixList[i] } for i, r := range rhs.PrefixList { if l, y := lmap[mapkey(i, string(r.IpPrefix+r.MasklengthRange))]; !y { return false } else if !r.Equal(l) { return false } } } return true } //struct for container rpol:defined-sets type DefinedSets struct { // original -> rpol:prefix-sets PrefixSets []PrefixSet `mapstructure:"prefix-sets"` // original -> rpol:neighbor-sets NeighborSets []NeighborSet `mapstructure:"neighbor-sets"` // original -> rpol:tag-sets TagSets []TagSet `mapstructure:"tag-sets"` // original -> bgp-pol:bgp-defined-sets BgpDefinedSets BgpDefinedSets `mapstructure:"bgp-defined-sets"` } func (lhs *DefinedSets) Equal(rhs *DefinedSets) bool { if lhs == nil || rhs == nil { return false } if len(lhs.PrefixSets) != len(rhs.PrefixSets) { return false } { lmap := make(map[string]*PrefixSet) for i, l := range lhs.PrefixSets { lmap[mapkey(i, string(l.PrefixSetName))] = &lhs.PrefixSets[i] } for i, r := range rhs.PrefixSets { if l, y := lmap[mapkey(i, string(r.PrefixSetName))]; !y { return false } else if !r.Equal(l) { return false } } } if len(lhs.NeighborSets) != len(rhs.NeighborSets) { return false } { lmap := make(map[string]*NeighborSet) for i, l := range lhs.NeighborSets { lmap[mapkey(i, string(l.NeighborSetName))] = &lhs.NeighborSets[i] } for i, r := range rhs.NeighborSets { if l, y := lmap[mapkey(i, string(r.NeighborSetName))]; !y { return false } else if !r.Equal(l) { return false } } } if len(lhs.TagSets) != len(rhs.TagSets) { return false } { lmap := make(map[string]*TagSet) for i, l := range lhs.TagSets { lmap[mapkey(i, string(l.TagSetName))] = &lhs.TagSets[i] } for i, r := range rhs.TagSets { if l, y := lmap[mapkey(i, string(r.TagSetName))]; !y { return false } else if !r.Equal(l) { return false } } } if !lhs.BgpDefinedSets.Equal(&(rhs.BgpDefinedSets)) { return false } return true } //struct for container rpol:routing-policy type RoutingPolicy struct { // original -> rpol:defined-sets DefinedSets DefinedSets `mapstructure:"defined-sets"` // original -> rpol:policy-definitions PolicyDefinitions []PolicyDefinition `mapstructure:"policy-definitions"` } func (lhs *RoutingPolicy) Equal(rhs *RoutingPolicy) bool { if lhs == nil || rhs == nil { return false } if !lhs.DefinedSets.Equal(&(rhs.DefinedSets)) { return false } if len(lhs.PolicyDefinitions) != len(rhs.PolicyDefinitions) { return false } { lmap := make(map[string]*PolicyDefinition) for i, l := range lhs.PolicyDefinitions { lmap[mapkey(i, string(l.Name))] = &lhs.PolicyDefinitions[i] } for i, r := range rhs.PolicyDefinitions { if l, y := lmap[mapkey(i, string(r.Name))]; !y { return false } else if !r.Equal(l) { return false } } } return true } <|start_filename|>vendor/github.com/contiv/objdb/consulLock.go<|end_filename|> /*** Copyright 2014 Cisco Systems 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. */ package objdb import ( "fmt" "sync" "time" log "github.com/Sirupsen/logrus" "github.com/hashicorp/consul/api" ) // Lock object type consulLock struct { name string keyName string myID string isAcquired bool isReleased bool ttl string sessionID string eventChan chan LockEvent stopChan chan struct{} mutex *sync.Mutex client *api.Client } // NewLock returns a new lock instance func (cp *ConsulClient) NewLock(name string, myID string, ttl uint64) (LockInterface, error) { // Create a lock return &consulLock{ name: name, keyName: "contiv.io/lock/" + name, myID: myID, ttl: fmt.Sprintf("%ds", ttl), eventChan: make(chan LockEvent, 1), stopChan: make(chan struct{}, 1), mutex: new(sync.Mutex), client: cp.client, }, nil } // Acquire a lock func (lk *consulLock) Acquire(timeout uint64) error { // Create consul session err := lk.createSession() if err != nil { log.Errorf("Error Creating session for lock %s. Err: %v", lk.keyName, err) return err } // Refresh the session in background go lk.renewSession() // Watch for changes on the lock go lk.acquireLock() // Wait till timeout and see if we were able to acquire the lock if timeout != 0 { go func() { time.Sleep(time.Duration(timeout) * time.Second) if !lk.IsAcquired() { lk.eventChan <- LockEvent{EventType: LockAcquireTimeout} // release the lock lk.Release() } }() } return nil } // Release a lock func (lk *consulLock) Release() error { // Mark this as released lk.mutex.Lock() lk.isReleased = true lk.mutex.Unlock() // Send stop signal on stop channel close(lk.stopChan) // If the lock was acquired, release it if lk.IsAcquired() { lk.setAcquired(false) // Release it via consul client succ, _, err := lk.client.KV().Release(&api.KVPair{Key: lk.keyName, Value: []byte(lk.myID), Session: lk.sessionID}, nil) if err != nil { log.Errorf("Error releasing key %s/%s, Err: %v", lk.keyName, lk.myID, err) return err } if !succ { log.Warnf("Failed to release the lock %s/%s. !success", lk.name, lk.myID) } } return nil } // Kill Stops a lock without releasing it. // Let the consul TTL expiry release it // Note: This is for debug/test purposes only func (lk *consulLock) Kill() error { lk.mutex.Lock() defer lk.mutex.Unlock() // Send stop signal on stop channel close(lk.stopChan) // Mark this as released lk.isReleased = true return nil } // EventChan Returns event channel func (lk *consulLock) EventChan() <-chan LockEvent { lk.mutex.Lock() defer lk.mutex.Unlock() return lk.eventChan } // IsAcquired Checks if the lock is acquired func (lk *consulLock) IsAcquired() bool { lk.mutex.Lock() defer lk.mutex.Unlock() return lk.isAcquired } // IsReleased Checks if the lock is released func (lk *consulLock) IsReleased() bool { lk.mutex.Lock() defer lk.mutex.Unlock() return lk.isReleased } // GetHolder Gets current lock holder's ID func (lk *consulLock) GetHolder() string { lk.mutex.Lock() defer lk.mutex.Unlock() // Get the current value from consul client resp, _, err := lk.client.KV().Get(lk.keyName, &api.QueryOptions{RequireConsistent: true}) if err != nil { log.Errorf("Error getting key %s. Err: %v", lk.keyName, err) return "" } // return the current holder if exists if resp != nil { return string(resp.Value) } return "" } // *********************** Internal functions ************* // acquireLock watches for changes on a lock and tries to acquire it func (lk *consulLock) acquireLock() { // save the modified idx var waitIdx uint64 // loop forever for { // Get the object from consul client resp, meta, err := lk.client.KV().Get(lk.keyName, &api.QueryOptions{RequireConsistent: true, WaitIndex: waitIdx}) if err != nil { log.Errorf("Error getting key %s. Err: %v", lk.keyName, err) // sleep for a bit a continue time.Sleep(time.Second) continue } log.Debugf("Got lock(%s) watch Resp: %+v", lk.myID, resp) // exit the loop if lock is released if lk.IsReleased() { log.Infof("Lock is released. exiting watch") return } // check if we are holding the lock if lk.IsAcquired() { // check if we lost the lock if resp == nil || resp.Session != lk.sessionID || string(resp.Value) != lk.myID { // lock is released lk.setAcquired(false) log.Infof("Lost lock %s", lk.name, lk.myID) // Send lock lost event lk.eventChan <- LockEvent{EventType: LockLost} } else { log.Debugf("Lock %s is held by me(%s)", lk.name, lk.myID) } } else { if resp == nil || resp.Session == "" { // try to acquire the lock succ, _, err := lk.client.KV().Acquire(&api.KVPair{Key: lk.keyName, Value: []byte(lk.myID), Session: lk.sessionID}, nil) if err != nil || !succ { log.Warnf("Error acquiring key %s/%s, Err: %v, succ: %v", lk.keyName, lk.myID, err, succ) // sleep for a bit a continue time.Sleep(time.Millisecond * 100) continue } log.Infof("Acquired lock %s/%s", lk.name, lk.myID) // Mark the lock as acquired lk.setAcquired(true) // Send acquired message to event channel lk.eventChan <- LockEvent{EventType: LockAcquired} } else { log.Debugf("Lock %s is held by some one else: %s", resp.Key, string(resp.Value)) } } // use the last modified index waitIdx = meta.LastIndex } } // setAcquired marks the lock as acquired/not func (lk *consulLock) setAcquired(isAcquired bool) { lk.mutex.Lock() lk.isAcquired = isAcquired lk.mutex.Unlock() } // createSession creates a consul-session for the lock func (lk *consulLock) createSession() error { // session configuration sessCfg := api.SessionEntry{ Name: lk.keyName, Behavior: "delete", LockDelay: 10 * time.Millisecond, TTL: lk.ttl, } // Create consul session sessionID, _, err := lk.client.Session().CreateNoChecks(&sessCfg, nil) if err != nil { log.Errorf("Error Creating session for lock %s. Err: %v", lk.keyName, err) return err } log.Infof("Created session: %s for lock %s/%s", sessionID, lk.name, lk.myID) // save the session ID for later lk.mutex.Lock() lk.sessionID = sessionID lk.mutex.Unlock() return nil } // renewSession keeps the session alive.. If a session expires, it creates new one.. func (lk *consulLock) renewSession() { for { err := lk.client.Session().RenewPeriodic(lk.ttl, lk.sessionID, nil, lk.stopChan) if err == nil || lk.IsReleased() { // If lock was released, exit this go routine return } // Create new consul session err = lk.createSession() if err != nil { log.Errorf("Error Creating session for lock %s. Err: %v", lk.keyName, err) } } } <|start_filename|>vendor/github.com/coreos/etcd/client/auth_user.go<|end_filename|> // Copyright 2015 CoreOS, 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 client import ( "bytes" "encoding/json" "net/http" "net/url" "path" "golang.org/x/net/context" ) var ( defaultV2AuthPrefix = "/v2/auth" ) type User struct { User string `json:"user"` Password string `json:"password,omitempty"` Roles []string `json:"roles"` Grant []string `json:"grant,omitempty"` Revoke []string `json:"revoke,omitempty"` } type UserRoles struct { User string `json:"user"` Roles []Role `json:"roles"` } type userName struct { User string `json:"user"` } func v2AuthURL(ep url.URL, action string, name string) *url.URL { if name != "" { ep.Path = path.Join(ep.Path, defaultV2AuthPrefix, action, name) return &ep } ep.Path = path.Join(ep.Path, defaultV2AuthPrefix, action) return &ep } // NewAuthAPI constructs a new AuthAPI that uses HTTP to // interact with etcd's general auth features. func NewAuthAPI(c Client) AuthAPI { return &httpAuthAPI{ client: c, } } type AuthAPI interface { // Enable auth. Enable(ctx context.Context) error // Disable auth. Disable(ctx context.Context) error } type httpAuthAPI struct { client httpClient } func (s *httpAuthAPI) Enable(ctx context.Context) error { return s.enableDisable(ctx, &authAPIAction{"PUT"}) } func (s *httpAuthAPI) Disable(ctx context.Context) error { return s.enableDisable(ctx, &authAPIAction{"DELETE"}) } func (s *httpAuthAPI) enableDisable(ctx context.Context, req httpAction) error { resp, body, err := s.client.Do(ctx, req) if err != nil { return err } if err = assertStatusCode(resp.StatusCode, http.StatusOK, http.StatusCreated); err != nil { var sec authError err = json.Unmarshal(body, &sec) if err != nil { return err } return sec } return nil } type authAPIAction struct { verb string } func (l *authAPIAction) HTTPRequest(ep url.URL) *http.Request { u := v2AuthURL(ep, "enable", "") req, _ := http.NewRequest(l.verb, u.String(), nil) return req } type authError struct { Message string `json:"message"` Code int `json:"-"` } func (e authError) Error() string { return e.Message } // NewAuthUserAPI constructs a new AuthUserAPI that uses HTTP to // interact with etcd's user creation and modification features. func NewAuthUserAPI(c Client) AuthUserAPI { return &httpAuthUserAPI{ client: c, } } type AuthUserAPI interface { // AddUser adds a user. AddUser(ctx context.Context, username string, password string) error // RemoveUser removes a user. RemoveUser(ctx context.Context, username string) error // GetUser retrieves user details. GetUser(ctx context.Context, username string) (*User, error) // GrantUser grants a user some permission roles. GrantUser(ctx context.Context, username string, roles []string) (*User, error) // RevokeUser revokes some permission roles from a user. RevokeUser(ctx context.Context, username string, roles []string) (*User, error) // ChangePassword changes the user's password. ChangePassword(ctx context.Context, username string, password string) (*User, error) // ListUsers lists the users. ListUsers(ctx context.Context) ([]string, error) } type httpAuthUserAPI struct { client httpClient } type authUserAPIAction struct { verb string username string user *User } type authUserAPIList struct{} func (list *authUserAPIList) HTTPRequest(ep url.URL) *http.Request { u := v2AuthURL(ep, "users", "") req, _ := http.NewRequest("GET", u.String(), nil) req.Header.Set("Content-Type", "application/json") return req } func (l *authUserAPIAction) HTTPRequest(ep url.URL) *http.Request { u := v2AuthURL(ep, "users", l.username) if l.user == nil { req, _ := http.NewRequest(l.verb, u.String(), nil) return req } b, err := json.Marshal(l.user) if err != nil { panic(err) } body := bytes.NewReader(b) req, _ := http.NewRequest(l.verb, u.String(), body) req.Header.Set("Content-Type", "application/json") return req } func (u *httpAuthUserAPI) ListUsers(ctx context.Context) ([]string, error) { resp, body, err := u.client.Do(ctx, &authUserAPIList{}) if err != nil { return nil, err } if err = assertStatusCode(resp.StatusCode, http.StatusOK); err != nil { var sec authError err = json.Unmarshal(body, &sec) if err != nil { return nil, err } return nil, sec } var userList struct { Users []User `json:"users"` } if err = json.Unmarshal(body, &userList); err != nil { return nil, err } ret := make([]string, 0, len(userList.Users)) for _, u := range userList.Users { ret = append(ret, u.User) } return ret, nil } func (u *httpAuthUserAPI) AddUser(ctx context.Context, username string, password string) error { user := &User{ User: username, Password: password, } return u.addRemoveUser(ctx, &authUserAPIAction{ verb: "PUT", username: username, user: user, }) } func (u *httpAuthUserAPI) RemoveUser(ctx context.Context, username string) error { return u.addRemoveUser(ctx, &authUserAPIAction{ verb: "DELETE", username: username, }) } func (u *httpAuthUserAPI) addRemoveUser(ctx context.Context, req *authUserAPIAction) error { resp, body, err := u.client.Do(ctx, req) if err != nil { return err } if err = assertStatusCode(resp.StatusCode, http.StatusOK, http.StatusCreated); err != nil { var sec authError err = json.Unmarshal(body, &sec) if err != nil { return err } return sec } return nil } func (u *httpAuthUserAPI) GetUser(ctx context.Context, username string) (*User, error) { return u.modUser(ctx, &authUserAPIAction{ verb: "GET", username: username, }) } func (u *httpAuthUserAPI) GrantUser(ctx context.Context, username string, roles []string) (*User, error) { user := &User{ User: username, Grant: roles, } return u.modUser(ctx, &authUserAPIAction{ verb: "PUT", username: username, user: user, }) } func (u *httpAuthUserAPI) RevokeUser(ctx context.Context, username string, roles []string) (*User, error) { user := &User{ User: username, Revoke: roles, } return u.modUser(ctx, &authUserAPIAction{ verb: "PUT", username: username, user: user, }) } func (u *httpAuthUserAPI) ChangePassword(ctx context.Context, username string, password string) (*User, error) { user := &User{ User: username, Password: password, } return u.modUser(ctx, &authUserAPIAction{ verb: "PUT", username: username, user: user, }) } func (u *httpAuthUserAPI) modUser(ctx context.Context, req *authUserAPIAction) (*User, error) { resp, body, err := u.client.Do(ctx, req) if err != nil { return nil, err } if err = assertStatusCode(resp.StatusCode, http.StatusOK); err != nil { var sec authError err = json.Unmarshal(body, &sec) if err != nil { return nil, err } return nil, sec } var user User if err = json.Unmarshal(body, &user); err != nil { var userR UserRoles if urerr := json.Unmarshal(body, &userR); urerr != nil { return nil, err } user.User = userR.User for _, r := range userR.Roles { user.Roles = append(user.Roles, r.Role) } } return &user, nil } <|start_filename|>vendor/github.com/osrg/gobgp/packet/bgp/bgpcapabilitycode_string.go<|end_filename|> // generated by stringer -type=BGPCapabilityCode; DO NOT EDIT package bgp import "fmt" const ( _BGPCapabilityCode_name_0 = "BGP_CAP_MULTIPROTOCOLBGP_CAP_ROUTE_REFRESH" _BGPCapabilityCode_name_1 = "BGP_CAP_CARRYING_LABEL_INFO" _BGPCapabilityCode_name_2 = "BGP_CAP_GRACEFUL_RESTARTBGP_CAP_FOUR_OCTET_AS_NUMBER" _BGPCapabilityCode_name_3 = "BGP_CAP_ENHANCED_ROUTE_REFRESH" _BGPCapabilityCode_name_4 = "BGP_CAP_ROUTE_REFRESH_CISCO" ) var ( _BGPCapabilityCode_index_0 = [...]uint8{0, 21, 42} _BGPCapabilityCode_index_1 = [...]uint8{0, 27} _BGPCapabilityCode_index_2 = [...]uint8{0, 24, 52} _BGPCapabilityCode_index_3 = [...]uint8{0, 30} _BGPCapabilityCode_index_4 = [...]uint8{0, 27} ) func (i BGPCapabilityCode) String() string { switch { case 1 <= i && i <= 2: i -= 1 return _BGPCapabilityCode_name_0[_BGPCapabilityCode_index_0[i]:_BGPCapabilityCode_index_0[i+1]] case i == 4: return _BGPCapabilityCode_name_1 case 64 <= i && i <= 65: i -= 64 return _BGPCapabilityCode_name_2[_BGPCapabilityCode_index_2[i]:_BGPCapabilityCode_index_2[i+1]] case i == 70: return _BGPCapabilityCode_name_3 case i == 128: return _BGPCapabilityCode_name_4 default: return fmt.Sprintf("BGPCapabilityCode(%d)", i) } } <|start_filename|>vendor/github.com/osrg/gobgp/config/default_linux.go<|end_filename|> // Copyright (C) 2016 Nippon Telegraph and Telephone Corporation. // // 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. // +build linux package config import ( "fmt" "github.com/vishvananda/netlink" "net" ) func GetIPv6LinkLocalNeighborAddress(ifname string) (string, error) { ifi, err := net.InterfaceByName(ifname) if err != nil { return "", err } neighs, err := netlink.NeighList(ifi.Index, netlink.FAMILY_V6) if err != nil { return "", err } cnt := 0 var addr net.IP for _, neigh := range neighs { local, err := isLocalLinkLocalAddress(ifi.Index, neigh.IP) if err != nil { return "", err } if neigh.IP.IsLinkLocalUnicast() && !local { addr = neigh.IP cnt += 1 } } if cnt == 0 { return "", fmt.Errorf("no ipv6 link-local neighbor found") } else if cnt > 1 { return "", fmt.Errorf("found %d link-local neighbors. only support p2p link", cnt) } return fmt.Sprintf("%s%%%s", addr, ifname), nil } <|start_filename|>vendor/github.com/vishvananda/netlink/bpf_linux.go<|end_filename|> package netlink /* #include <asm/types.h> #include <asm/unistd.h> #include <errno.h> #include <stdio.h> #include <stdint.h> #include <unistd.h> static int load_simple_bpf(int prog_type) { #ifdef __NR_bpf // { return 1; } __u64 __attribute__((aligned(8))) insns[] = { 0x00000001000000b7ull, 0x0000000000000095ull, }; __u8 __attribute__((aligned(8))) license[] = "ASL2"; // Copied from a header file since libc is notoriously slow to update. // The call will succeed or fail and that will be our indication on // whether or not it is supported. struct { __u32 prog_type; __u32 insn_cnt; __u64 insns; __u64 license; __u32 log_level; __u32 log_size; __u64 log_buf; __u32 kern_version; } __attribute__((aligned(8))) attr = { .prog_type = prog_type, .insn_cnt = 2, .insns = (uintptr_t)&insns, .license = (uintptr_t)&license, }; return syscall(__NR_bpf, 5, &attr, sizeof(attr)); #else errno = EINVAL; return -1; #endif } */ import "C" type BpfProgType C.int const ( BPF_PROG_TYPE_UNSPEC BpfProgType = iota BPF_PROG_TYPE_SOCKET_FILTER BPF_PROG_TYPE_KPROBE BPF_PROG_TYPE_SCHED_CLS BPF_PROG_TYPE_SCHED_ACT ) // loadSimpleBpf loads a trivial bpf program for testing purposes func loadSimpleBpf(progType BpfProgType) (int, error) { fd, err := C.load_simple_bpf(C.int(progType)) return int(fd), err } <|start_filename|>vendor/github.com/osrg/gobgp/server/zclient.go<|end_filename|> // Copyright (C) 2015 Nippon Telegraph and Telephone Corporation. // // 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 server import ( "fmt" log "github.com/Sirupsen/logrus" "github.com/osrg/gobgp/packet/bgp" "github.com/osrg/gobgp/table" "github.com/osrg/gobgp/zebra" "net" "strconv" "strings" "time" ) func newIPRouteMessage(dst []*table.Path) *zebra.Message { paths := make([]*table.Path, 0, len(dst)) for _, path := range dst { if path == nil || path.IsFromExternal() { continue } paths = append(paths, path) } if len(paths) == 0 { return nil } path := paths[0] l := strings.SplitN(path.GetNlri().String(), "/", 2) var command zebra.API_TYPE var prefix net.IP nexthops := make([]net.IP, 0, len(paths)) switch path.GetRouteFamily() { case bgp.RF_IPv4_UC: if path.IsWithdraw == true { command = zebra.IPV4_ROUTE_DELETE } else { command = zebra.IPV4_ROUTE_ADD } prefix = net.ParseIP(l[0]).To4() for _, p := range paths { nexthops = append(nexthops, p.GetNexthop().To4()) } case bgp.RF_IPv6_UC: if path.IsWithdraw == true { command = zebra.IPV6_ROUTE_DELETE } else { command = zebra.IPV6_ROUTE_ADD } prefix = net.ParseIP(l[0]).To16() for _, p := range paths { nexthops = append(nexthops, p.GetNexthop().To16()) } default: return nil } flags := uint8(zebra.MESSAGE_NEXTHOP) plen, _ := strconv.Atoi(l[1]) med, err := path.GetMed() if err == nil { flags |= zebra.MESSAGE_METRIC } return &zebra.Message{ Header: zebra.Header{ Len: zebra.HEADER_SIZE, Marker: zebra.HEADER_MARKER, Version: zebra.VERSION, Command: command, }, Body: &zebra.IPRouteBody{ Type: zebra.ROUTE_BGP, SAFI: zebra.SAFI_UNICAST, Message: flags, Prefix: prefix, PrefixLength: uint8(plen), Nexthops: nexthops, Metric: med, }, } } func createPathFromIPRouteMessage(m *zebra.Message) *table.Path { header := m.Header body := m.Body.(*zebra.IPRouteBody) family := bgp.RF_IPv6_UC if header.Command == zebra.IPV4_ROUTE_ADD || header.Command == zebra.IPV4_ROUTE_DELETE { family = bgp.RF_IPv4_UC } var nlri bgp.AddrPrefixInterface pattr := make([]bgp.PathAttributeInterface, 0) var mpnlri *bgp.PathAttributeMpReachNLRI var isWithdraw bool = header.Command == zebra.IPV4_ROUTE_DELETE || header.Command == zebra.IPV6_ROUTE_DELETE origin := bgp.NewPathAttributeOrigin(bgp.BGP_ORIGIN_ATTR_TYPE_IGP) pattr = append(pattr, origin) log.WithFields(log.Fields{ "Topic": "Zebra", "RouteType": body.Type.String(), "Flag": body.Flags.String(), "Message": body.Message, "Prefix": body.Prefix, "PrefixLength": body.PrefixLength, "Nexthop": body.Nexthops, "IfIndex": body.Ifindexs, "Metric": body.Metric, "Distance": body.Distance, "api": header.Command.String(), }).Debugf("create path from ip route message.") switch family { case bgp.RF_IPv4_UC: nlri = bgp.NewIPAddrPrefix(body.PrefixLength, body.Prefix.String()) nexthop := bgp.NewPathAttributeNextHop(body.Nexthops[0].String()) pattr = append(pattr, nexthop) case bgp.RF_IPv6_UC: nlri = bgp.NewIPv6AddrPrefix(body.PrefixLength, body.Prefix.String()) mpnlri = bgp.NewPathAttributeMpReachNLRI(body.Nexthops[0].String(), []bgp.AddrPrefixInterface{nlri}) pattr = append(pattr, mpnlri) default: log.WithFields(log.Fields{ "Topic": "Zebra", }).Errorf("unsupport address family: %s", family) return nil } med := bgp.NewPathAttributeMultiExitDisc(body.Metric) pattr = append(pattr, med) path := table.NewPath(nil, nlri, isWithdraw, pattr, time.Now(), false) path.SetIsFromExternal(true) return path } type zebraClient struct { client *zebra.Client server *BgpServer dead chan struct{} } func (z *zebraClient) stop() { close(z.dead) } func (z *zebraClient) loop() { w := z.server.Watch(WatchBestPath()) defer func() { w.Stop() }() for { select { case <-z.dead: return case msg := <-z.client.Receive(): switch msg.Body.(type) { case *zebra.IPRouteBody: if p := createPathFromIPRouteMessage(msg); p != nil { if _, err := z.server.AddPath("", []*table.Path{p}); err != nil { log.Errorf("failed to add path from zebra: %s", p) } } } case ev := <-w.Event(): msg := ev.(*WatchEventBestPath) if table.UseMultiplePaths.Enabled { for _, dst := range msg.MultiPathList { if m := newIPRouteMessage(dst); m != nil { z.client.Send(m) } } } else { for _, path := range msg.PathList { if m := newIPRouteMessage([]*table.Path{path}); m != nil { z.client.Send(m) } } } } } } func newZebraClient(s *BgpServer, url string, protos []string) (*zebraClient, error) { l := strings.SplitN(url, ":", 2) if len(l) != 2 { return nil, fmt.Errorf("unsupported url: %s", url) } cli, err := zebra.NewClient(l[0], l[1], zebra.ROUTE_BGP) if err != nil { return nil, err } cli.SendHello() cli.SendRouterIDAdd() cli.SendInterfaceAdd() for _, typ := range protos { t, err := zebra.RouteTypeFromString(typ) if err != nil { return nil, err } cli.SendRedistribute(t) } w := &zebraClient{ dead: make(chan struct{}), client: cli, server: s, } go w.loop() return w, nil } <|start_filename|>utils/driverfactory_test.go<|end_filename|> package utils import ( "testing" "github.com/contiv/netplugin/core" ) func TestNewStateDriverValidConfig(t *testing.T) { drv, err := NewStateDriver("fakedriver", &core.InstanceInfo{}) defer func() { ReleaseStateDriver() }() if err != nil { t.Fatalf("failed to instantiate state driver. Error: %s", err) } if drv == nil { t.Fatalf("nil driver instance was returned") } } func TestNewStateDriverInvalidConfig(t *testing.T) { _, err := NewStateDriver("fakedriver", nil) if err == nil { t.Fatalf("state driver instantiation succeeded, expected to fail") } } func TestNewStateDriverInvalidDriverName(t *testing.T) { _, err := NewStateDriver("non-existent-name", &core.InstanceInfo{}) if err == nil { t.Fatalf("state driver instantiation succeeded, expected to fail") } } func TestNewStateDriverSecondCreate(t *testing.T) { _, err := NewStateDriver("fakedriver", &core.InstanceInfo{}) defer func() { ReleaseStateDriver() }() if err != nil { t.Fatalf("failed to instantiate state driver. Error: %s", err) } _, err = NewStateDriver("fakedriver", &core.InstanceInfo{}) if err == nil { t.Fatalf("second state driver instantiation succeeded, expected to fail") } } func TestGetStateDriverNonExistentStateDriver(t *testing.T) { _, err := GetStateDriver() if err == nil { t.Fatalf("getting state-driver succeeded, expected to fail") } } func TestNewNetworkDriverValidConfig(t *testing.T) { instInfo := &core.InstanceInfo{} drv, err := NewNetworkDriver("fakedriver", instInfo) if err != nil { t.Fatalf("failed to instantiate network driver. Error: %s", err) } if drv == nil { t.Fatalf("nil driver instance was returned") } } func TestNewNetworkDriverInvalidConfig(t *testing.T) { _, err := NewNetworkDriver("fakedriver", nil) if err == nil { t.Fatalf("network driver instantiation succeeded, expected to fail") } } func TestNewNetworkDriverInvalidDriverName(t *testing.T) { instInfo := &core.InstanceInfo{} _, err := NewNetworkDriver("non-existent-name", instInfo) if err == nil { t.Fatalf("network driver instantiation succeeded, expected to fail") } } <|start_filename|>vendor/github.com/osrg/gobgp/table/message.go<|end_filename|> // Copyright (C) 2014 Nippon Telegraph and Telephone Corporation. // // 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 table import ( "bytes" log "github.com/Sirupsen/logrus" "github.com/osrg/gobgp/packet/bgp" "hash/fnv" "reflect" ) func UpdatePathAttrs2ByteAs(msg *bgp.BGPUpdate) error { ps := msg.PathAttributes msg.PathAttributes = make([]bgp.PathAttributeInterface, len(ps)) copy(msg.PathAttributes, ps) var asAttr *bgp.PathAttributeAsPath idx := 0 for i, attr := range msg.PathAttributes { if a, ok := attr.(*bgp.PathAttributeAsPath); ok { asAttr = a idx = i break } } if asAttr == nil { return nil } as4Params := make([]*bgp.As4PathParam, 0, len(asAttr.Value)) as2Params := make([]bgp.AsPathParamInterface, 0, len(asAttr.Value)) mkAs4 := false for _, param := range asAttr.Value { as4Param := param.(*bgp.As4PathParam) as2Path := make([]uint16, 0, len(as4Param.AS)) for _, as := range as4Param.AS { if as > (1<<16)-1 { mkAs4 = true as2Path = append(as2Path, bgp.AS_TRANS) } else { as2Path = append(as2Path, uint16(as)) } } as2Params = append(as2Params, bgp.NewAsPathParam(as4Param.Type, as2Path)) // RFC 6793 4.2.2 Generating Updates // // Whenever the AS path information contains the AS_CONFED_SEQUENCE or // AS_CONFED_SET path segment, the NEW BGP speaker MUST exclude such // path segments from the AS4_PATH attribute being constructed. if as4Param.Type != bgp.BGP_ASPATH_ATTR_TYPE_CONFED_SEQ && as4Param.Type != bgp.BGP_ASPATH_ATTR_TYPE_CONFED_SET { as4Params = append(as4Params, as4Param) } } msg.PathAttributes[idx] = bgp.NewPathAttributeAsPath(as2Params) if mkAs4 { msg.PathAttributes = append(msg.PathAttributes, bgp.NewPathAttributeAs4Path(as4Params)) } return nil } func UpdatePathAttrs4ByteAs(msg *bgp.BGPUpdate) error { var asAttr *bgp.PathAttributeAsPath var as4Attr *bgp.PathAttributeAs4Path asAttrPos := 0 as4AttrPos := 0 for i, attr := range msg.PathAttributes { switch attr.(type) { case *bgp.PathAttributeAsPath: asAttr = attr.(*bgp.PathAttributeAsPath) for j, param := range asAttr.Value { as2Param, ok := param.(*bgp.AsPathParam) if ok { asPath := make([]uint32, 0, len(as2Param.AS)) for _, as := range as2Param.AS { asPath = append(asPath, uint32(as)) } as4Param := bgp.NewAs4PathParam(as2Param.Type, asPath) asAttr.Value[j] = as4Param } } asAttrPos = i msg.PathAttributes[i] = asAttr case *bgp.PathAttributeAs4Path: as4AttrPos = i as4Attr = attr.(*bgp.PathAttributeAs4Path) } } if as4Attr != nil { msg.PathAttributes = append(msg.PathAttributes[:as4AttrPos], msg.PathAttributes[as4AttrPos+1:]...) } if asAttr == nil || as4Attr == nil { return nil } asLen := 0 asConfedLen := 0 asParams := make([]*bgp.As4PathParam, 0, len(asAttr.Value)) for _, param := range asAttr.Value { asLen += param.ASLen() p := param.(*bgp.As4PathParam) switch p.Type { case bgp.BGP_ASPATH_ATTR_TYPE_CONFED_SET: asConfedLen += 1 case bgp.BGP_ASPATH_ATTR_TYPE_CONFED_SEQ: asConfedLen += len(p.AS) } asParams = append(asParams, p) } as4Len := 0 as4Params := make([]*bgp.As4PathParam, 0, len(as4Attr.Value)) if as4Attr != nil { for _, p := range as4Attr.Value { // RFC 6793 6. Error Handling // // the path segment types AS_CONFED_SEQUENCE and AS_CONFED_SET [RFC5065] // MUST NOT be carried in the AS4_PATH attribute of an UPDATE message. // A NEW BGP speaker that receives these path segment types in the AS4_PATH // attribute of an UPDATE message from an OLD BGP speaker MUST discard // these path segments, adjust the relevant attribute fields accordingly, // and continue processing the UPDATE message. // This case SHOULD be logged locally for analysis. switch p.Type { case bgp.BGP_ASPATH_ATTR_TYPE_CONFED_SEQ, bgp.BGP_ASPATH_ATTR_TYPE_CONFED_SET: typ := "CONFED_SEQ" if p.Type == bgp.BGP_ASPATH_ATTR_TYPE_CONFED_SET { typ = "CONFED_SET" } log.WithFields(log.Fields{ "Topic": "Table", }).Warnf("AS4_PATH contains %s segment %s. ignore", typ, p.String()) continue } as4Len += p.ASLen() as4Params = append(as4Params, p) } } if asLen+asConfedLen < as4Len { log.WithFields(log.Fields{ "Topic": "Table", }).Warn("AS4_PATH is longer than AS_PATH. ignore AS4_PATH") return nil } keepNum := asLen + asConfedLen - as4Len newParams := make([]*bgp.As4PathParam, 0, len(asAttr.Value)) for _, param := range asParams { if keepNum-param.ASLen() >= 0 { newParams = append(newParams, param) keepNum -= param.ASLen() } else { // only SEQ param reaches here param.AS = param.AS[:keepNum] newParams = append(newParams, param) keepNum = 0 } if keepNum <= 0 { break } } for _, param := range as4Params { lastParam := newParams[len(newParams)-1] if param.Type == lastParam.Type && param.Type == bgp.BGP_ASPATH_ATTR_TYPE_SEQ { if len(lastParam.AS)+len(param.AS) > 255 { lastParam.AS = append(lastParam.AS, param.AS[:255-len(lastParam.AS)]...) param.AS = param.AS[255-len(lastParam.AS):] newParams = append(newParams, param) } else { lastParam.AS = append(lastParam.AS, param.AS...) } } else { newParams = append(newParams, param) } } newIntfParams := make([]bgp.AsPathParamInterface, 0, len(asAttr.Value)) for _, p := range newParams { newIntfParams = append(newIntfParams, p) } msg.PathAttributes[asAttrPos] = bgp.NewPathAttributeAsPath(newIntfParams) return nil } func UpdatePathAggregator2ByteAs(msg *bgp.BGPUpdate) { as := uint32(0) var addr string for i, attr := range msg.PathAttributes { switch attr.(type) { case *bgp.PathAttributeAggregator: agg := attr.(*bgp.PathAttributeAggregator) addr = agg.Value.Address.String() if agg.Value.AS > (1<<16)-1 { as = agg.Value.AS msg.PathAttributes[i] = bgp.NewPathAttributeAggregator(uint16(bgp.AS_TRANS), addr) } else { msg.PathAttributes[i] = bgp.NewPathAttributeAggregator(uint16(agg.Value.AS), addr) } } } if as != 0 { msg.PathAttributes = append(msg.PathAttributes, bgp.NewPathAttributeAs4Aggregator(as, addr)) } } func UpdatePathAggregator4ByteAs(msg *bgp.BGPUpdate) error { var aggAttr *bgp.PathAttributeAggregator var agg4Attr *bgp.PathAttributeAs4Aggregator agg4AttrPos := 0 for i, attr := range msg.PathAttributes { switch attr.(type) { case *bgp.PathAttributeAggregator: attr := attr.(*bgp.PathAttributeAggregator) if attr.Value.Askind == reflect.Uint16 { aggAttr = attr aggAttr.Value.Askind = reflect.Uint32 } case *bgp.PathAttributeAs4Aggregator: agg4Attr = attr.(*bgp.PathAttributeAs4Aggregator) agg4AttrPos = i } } if aggAttr == nil && agg4Attr == nil { return nil } if aggAttr == nil && agg4Attr != nil { return bgp.NewMessageError(bgp.BGP_ERROR_UPDATE_MESSAGE_ERROR, bgp.BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, "AS4 AGGREGATOR attribute exists, but AGGREGATOR doesn't") } if agg4Attr != nil { msg.PathAttributes = append(msg.PathAttributes[:agg4AttrPos], msg.PathAttributes[agg4AttrPos+1:]...) aggAttr.Value.AS = agg4Attr.Value.AS } return nil } func createUpdateMsgFromPath(path *Path, msg *bgp.BGPMessage) *bgp.BGPMessage { rf := path.GetRouteFamily() if rf == bgp.RF_IPv4_UC { nlri := path.GetNlri().(*bgp.IPAddrPrefix) if path.IsWithdraw { if msg != nil { u := msg.Body.(*bgp.BGPUpdate) u.WithdrawnRoutes = append(u.WithdrawnRoutes, nlri) return nil } else { return bgp.NewBGPUpdateMessage([]*bgp.IPAddrPrefix{nlri}, nil, nil) } } else { if msg != nil { u := msg.Body.(*bgp.BGPUpdate) u.NLRI = append(u.NLRI, nlri) } else { pathAttrs := path.GetPathAttrs() return bgp.NewBGPUpdateMessage(nil, pathAttrs, []*bgp.IPAddrPrefix{nlri}) } } } else { if path.IsWithdraw { if msg != nil { u := msg.Body.(*bgp.BGPUpdate) for _, p := range u.PathAttributes { if p.GetType() == bgp.BGP_ATTR_TYPE_MP_UNREACH_NLRI { unreach := p.(*bgp.PathAttributeMpUnreachNLRI) unreach.Value = append(unreach.Value, path.GetNlri()) } } } else { var nlris []bgp.AddrPrefixInterface attr := path.getPathAttr(bgp.BGP_ATTR_TYPE_MP_REACH_NLRI) if attr == nil { // for bmp post-policy attr = path.getPathAttr(bgp.BGP_ATTR_TYPE_MP_UNREACH_NLRI) nlris = attr.(*bgp.PathAttributeMpUnreachNLRI).Value } else { nlris = []bgp.AddrPrefixInterface{path.GetNlri()} } clonedAttrs := path.GetPathAttrs() for i, a := range clonedAttrs { if a.GetType() == bgp.BGP_ATTR_TYPE_MP_UNREACH_NLRI || a.GetType() == bgp.BGP_ATTR_TYPE_MP_REACH_NLRI { clonedAttrs[i] = bgp.NewPathAttributeMpUnreachNLRI(nlris) break } } return bgp.NewBGPUpdateMessage(nil, clonedAttrs, nil) } } else { if msg != nil { u := msg.Body.(*bgp.BGPUpdate) for _, p := range u.PathAttributes { if p.GetType() == bgp.BGP_ATTR_TYPE_MP_REACH_NLRI { reach := p.(*bgp.PathAttributeMpReachNLRI) reach.Value = append(reach.Value, path.GetNlri()) } } } else { attrs := make([]bgp.PathAttributeInterface, 0, 8) for _, p := range path.GetPathAttrs() { if p.GetType() == bgp.BGP_ATTR_TYPE_MP_REACH_NLRI { attrs = append(attrs, bgp.NewPathAttributeMpReachNLRI(path.GetNexthop().String(), []bgp.AddrPrefixInterface{path.GetNlri()})) } else { attrs = append(attrs, p) } } // we don't need to clone here but we // might merge path to this message in // the future so let's clone anyway. return bgp.NewBGPUpdateMessage(nil, attrs, nil) } } } return nil } type bucket struct { attrs []byte paths []*Path } func CreateUpdateMsgFromPaths(pathList []*Path) []*bgp.BGPMessage { var msgs []*bgp.BGPMessage pathByAttrs := make(map[uint32][]*bucket) for _, path := range pathList { if path == nil { continue } else if path.IsEOR() { msgs = append(msgs, bgp.NewEndOfRib(path.GetRouteFamily())) continue } y := func(p *Path) bool { if p.GetRouteFamily() != bgp.RF_IPv4_UC { return false } if p.IsWithdraw { return false } return true }(path) if y { key, attrs := func(p *Path) (uint32, []byte) { h := fnv.New32() total := bytes.NewBuffer(make([]byte, 0)) for _, v := range p.GetPathAttrs() { b, _ := v.Serialize() total.Write(b) } h.Write(total.Bytes()) return h.Sum32(), total.Bytes() }(path) if bl, y := pathByAttrs[key]; y { found := false for _, b := range bl { if bytes.Compare(b.attrs, attrs) == 0 { b.paths = append(b.paths, path) found = true break } } if found == false { nb := &bucket{ attrs: attrs, paths: []*Path{path}, } pathByAttrs[key] = append(pathByAttrs[key], nb) } } else { nb := &bucket{ attrs: attrs, paths: []*Path{path}, } pathByAttrs[key] = []*bucket{nb} } } else { msg := createUpdateMsgFromPath(path, nil) msgs = append(msgs, msg) } } for _, bList := range pathByAttrs { for _, b := range bList { var msg *bgp.BGPMessage for i, path := range b.paths { if i == 0 { msg = createUpdateMsgFromPath(path, nil) msgs = append(msgs, msg) } else { msgLen := func(u *bgp.BGPUpdate) int { attrsLen := 0 for _, a := range u.PathAttributes { attrsLen += a.Len() } // Header + Update (WithdrawnRoutesLen + // TotalPathAttributeLen + attributes + maxlen of // NLRI). Note that we try to add one NLRI. return 19 + 2 + 2 + attrsLen + (len(u.NLRI)+1)*5 }(msg.Body.(*bgp.BGPUpdate)) if msgLen+32 > bgp.BGP_MAX_MESSAGE_LENGTH { // don't marge msg = createUpdateMsgFromPath(path, nil) msgs = append(msgs, msg) } else { createUpdateMsgFromPath(path, msg) } } } } } return msgs } <|start_filename|>vendor/github.com/samalba/dockerclient/utils.go<|end_filename|> package dockerclient import ( "crypto/tls" "net" "net/http" "net/url" "time" ) type tcpFunc func(*net.TCPConn, time.Duration) error func newHTTPClient(u *url.URL, tlsConfig *tls.Config, timeout time.Duration, setUserTimeout tcpFunc) *http.Client { httpTransport := &http.Transport{ TLSClientConfig: tlsConfig, } switch u.Scheme { default: httpTransport.Dial = func(proto, addr string) (net.Conn, error) { conn, err := net.DialTimeout(proto, addr, timeout) if tcpConn, ok := conn.(*net.TCPConn); ok && setUserTimeout != nil { // Sender can break TCP connection if the remote side doesn't // acknowledge packets within timeout setUserTimeout(tcpConn, timeout) } return conn, err } case "unix": socketPath := u.Path unixDial := func(proto, addr string) (net.Conn, error) { return net.DialTimeout("unix", socketPath, timeout) } httpTransport.Dial = unixDial // Override the main URL object so the HTTP lib won't complain u.Scheme = "http" u.Host = "unix.sock" u.Path = "" } return &http.Client{Transport: httpTransport} } <|start_filename|>vendor/github.com/shaleman/libOpenflow/protocol/dhcp.go<|end_filename|> package protocol import ( "bytes" "encoding/binary" "errors" "io" "math/rand" "net" ) const ( DHCP_MSG_BOOT_REQ byte = iota DHCP_MSG_BOOT_RES ) type DHCPOperation byte const ( DHCP_MSG_UNSPEC DHCPOperation = iota DHCP_MSG_DISCOVER DHCP_MSG_OFFER DHCP_MSG_REQUEST DHCP_MSG_DECLINE DHCP_MSG_ACK DHCP_MSG_NAK DHCP_MSG_RELEASE DHCP_MSG_INFORM ) var dhcpMagic uint32 = 0x63825363 type DHCP struct { Operation DHCPOperation HardwareType byte HardwareLen uint8 HardwareOpts uint8 Xid uint32 Secs uint16 Flags uint16 ClientIP net.IP YourIP net.IP ServerIP net.IP GatewayIP net.IP ClientHWAddr net.HardwareAddr ServerName [64]byte File [128]byte Options []DHCPOption } const ( DHCP_OPT_REQUEST_IP byte = iota + 50 // 0x32, 4, net.IP DHCP_OPT_LEASE_TIME // 0x33, 4, uint32 DHCP_OPT_EXT_OPTS // 0x34, 1, 1/2/3 DHCP_OPT_MESSAGE_TYPE // 0x35, 1, 1-7 DHCP_OPT_SERVER_ID // 0x36, 4, net.IP DHCP_OPT_PARAMS_REQUEST // 0x37, n, []byte DHCP_OPT_MESSAGE // 0x38, n, string DHCP_OPT_MAX_DHCP_SIZE // 0x39, 2, uint16 DHCP_OPT_T1 // 0x3a, 4, uint32 DHCP_OPT_T2 // 0x3b, 4, uint32 DHCP_OPT_CLASS_ID // 0x3c, n, []byte DHCP_OPT_CLIENT_ID // 0x3d, n >= 2, []byte ) const ( DHCP_HW_ETHERNET byte = 0x01 ) const ( DHCP_FLAG_BROADCAST uint16 = 0x80 // FLAG_BROADCAST_MASK uint16 = (1 << FLAG_BROADCAST) ) func NewDHCP(xid uint32, op DHCPOperation, hwtype byte) (*DHCP, error) { if xid == 0 { xid = rand.Uint32() } switch hwtype { case DHCP_HW_ETHERNET: break default: return nil, errors.New("Bad HardwareType") } d := &DHCP{ Operation: op, HardwareType: hwtype, Xid: xid, ClientIP: make([]byte, 4), YourIP: make([]byte, 4), ServerIP: make([]byte, 4), GatewayIP: make([]byte, 4), ClientHWAddr: make([]byte, 16), } return d, nil } func (d *DHCP) Len() (n uint16) { n += uint16(240) optend := false for _, opt := range d.Options { n += opt.Len() if opt.OptionType() == DHCP_OPT_END { optend = true } } if !optend { n += 1 } return } func (d *DHCP) Read(b []byte) (n int, err error) { buf := new(bytes.Buffer) binary.Write(buf, binary.BigEndian, d.Operation) n += 1 binary.Write(buf, binary.BigEndian, d.HardwareType) n += 1 binary.Write(buf, binary.BigEndian, d.HardwareLen) n += 1 binary.Write(buf, binary.BigEndian, d.HardwareOpts) n += 1 binary.Write(buf, binary.BigEndian, d.Xid) n += 4 binary.Write(buf, binary.BigEndian, d.Secs) n += 2 binary.Write(buf, binary.BigEndian, d.Flags) n += 2 binary.Write(buf, binary.BigEndian, d.ClientIP) n += 4 binary.Write(buf, binary.BigEndian, d.YourIP) n += 4 binary.Write(buf, binary.BigEndian, d.ServerIP) n += 4 binary.Write(buf, binary.BigEndian, d.GatewayIP) n += 4 clientHWAddr := make([]byte, 16) copy(clientHWAddr[0:], d.ClientHWAddr) binary.Write(buf, binary.BigEndian, clientHWAddr) n += 16 binary.Write(buf, binary.BigEndian, d.ServerName) n += 64 binary.Write(buf, binary.BigEndian, d.File) n += 128 binary.Write(buf, binary.BigEndian, dhcpMagic) n += 4 optend := false for _, opt := range d.Options { m, err := DHCPWriteOption(buf, opt) n += m if err != nil { return n, err } if opt.OptionType() == DHCP_OPT_END { optend = true } } if !optend { m, err := DHCPWriteOption(buf, DHCPNewOption(DHCP_OPT_END, nil)) n += m if err != nil { return n, err } } if n, err = buf.Read(b); n == 0 { return } return n, nil } func (d *DHCP) Write(b []byte) (n int, err error) { if len(b) < 240 { return 0, errors.New("ErrTruncated") } buf := bytes.NewBuffer(b) if err = binary.Read(buf, binary.BigEndian, &d.Operation); err != nil { return } n += 1 if err = binary.Read(buf, binary.BigEndian, &d.HardwareType); err != nil { return } n += 1 if err = binary.Read(buf, binary.BigEndian, &d.HardwareLen); err != nil { return } n += 1 if err = binary.Read(buf, binary.BigEndian, &d.HardwareOpts); err != nil { return } n += 1 if err = binary.Read(buf, binary.BigEndian, &d.Xid); err != nil { return } n += 4 if err = binary.Read(buf, binary.BigEndian, &d.Secs); err != nil { return } n += 2 if err = binary.Read(buf, binary.BigEndian, &d.Flags); err != nil { return } n += 2 d.ClientIP = make([]byte, 4) if err = binary.Read(buf, binary.BigEndian, &d.ClientIP); err != nil { return } n += 4 d.YourIP = make([]byte, 4) if err = binary.Read(buf, binary.BigEndian, &d.YourIP); err != nil { return } n += 4 d.ServerIP = make([]byte, 4) if err = binary.Read(buf, binary.BigEndian, &d.ServerIP); err != nil { return } n += 4 d.GatewayIP = make([]byte, 4) if err = binary.Read(buf, binary.BigEndian, &d.GatewayIP); err != nil { return } n += 4 clientHWAddr := make([]byte, 16) if err = binary.Read(buf, binary.BigEndian, &clientHWAddr); err != nil { return } d.ClientHWAddr = net.HardwareAddr(clientHWAddr[:d.HardwareLen]) n += 16 if err = binary.Read(buf, binary.BigEndian, &d.ServerName); err != nil { return } n += 64 if err = binary.Read(buf, binary.BigEndian, &d.File); err != nil { return } n += 128 var magic uint32 if err = binary.Read(buf, binary.BigEndian, &magic); err != nil { return } n += 4 if magic != dhcpMagic { return n, errors.New("Bad DHCP header") } optlen := buf.Len() opts := make([]byte, optlen) if err = binary.Read(buf, binary.BigEndian, &opts); err != nil { return } n += optlen if d.Options, err = DHCPParseOptions(opts); err != nil { return } return } // Standard options (RFC1533) const ( DHCP_OPT_PAD byte = iota DHCP_OPT_SUBNET_MASK // 0x01, 4, net.IP DHCP_OPT_TIME_OFFSET // 0x02, 4, int32 (signed seconds from UTC) DHCP_OPT_DEFAULT_GATEWAY // 0x03, n*4, [n]net.IP DHCP_OPT_TIME_SERVER // 0x04, n*4, [n]net.IP DHCP_OPT_NAME_SERVER // 0x05, n*4, [n]net.IP DHCP_OPT_DOMAIN_NAME_SERVERS // 0x06, n*4, [n]net.IP DHCP_OPT_LOG_SERVER // 0x07, n*4, [n]net.IP DHCP_OPT_COOKIE_SERVER // 0x08, n*4, [n]net.IP DHCP_OPT_LPR_SERVER // 0x09, n*4, [n]net.IP DHCP_OPT_IMPRESS_SERVER // 0x0a, n*4, [n]net.IP DHCP_OPT_RLSERVER // 0x0b, n*4, [n]net.IP DHCP_OPT_HOST_NAME // 0x0c, n, string DHCP_OPT_BOOTFILE_SIZE // 0x0d, 2, uint16 DHCP_OPT_MERIT_DUMP_FILE // 0x0e, >1, string DHCP_OPT_DOMAIN_NAME // 0x0f, n, string DHCP_OPT_SWAP_SERVER // 0x10, n*4, [n]net.IP DHCP_OPT_ROOT_PATH // 0x11, n, string DHCP_OPT_EXTENSIONS_PATH // 0x12, n, string DHCP_OPT_IP_FORWARDING // 0x13, 1, bool DHCP_OPT_SOURCE_ROUTING // 0x14, 1, bool DHCP_OPT_POLICY_FILTER // 0x15, 8*n, [n]{net.IP/net.IP} DHCP_OPT_DGRAM_MTU // 0x16, 2, uint16 DHCP_OPT_DEFAULT_TTL // 0x17, 1, byte DHCP_OPT_PATH_MTU_AGING_TIMEOUT // 0x18, 4, uint32 DHCP_OPT_PATH_PLATEU_TABLE_OPTION // 0x19, 2*n, []uint16 DHCP_OPT_INTERFACE_MTU //0x1a, 2, uint16 DHCP_OPT_ALL_SUBS_LOCAL // 0x1b, 1, bool DHCP_OPT_BROADCAST_ADDR // 0x1c, 4, net.IP DHCP_OPT_MASK_DISCOVERY // 0x1d, 1, bool DHCP_OPT_MASK_SUPPLIER // 0x1e, 1, bool DHCP_OPT_ROUTER_DISCOVERY // 0x1f, 1, bool DHCP_OPT_ROUTER_SOLICIT_ADDR // 0x20, 4, net.IP DHCP_OPT_STATIC_ROUTE // 0x21, n*8, [n]{net.IP/net.IP} -- note the 2nd is router not mask DHCP_OPT_ARP_TRAILERS // 0x22, 1, bool DHCP_OPT_ARP_TIMEOUT // 0x23, 4, uint32 DHCP_OPT_ETHERNET_ENCAP // 0x24, 1, bool DHCP_OPT_TCP_TTL // 0x25,1, byte DHCP_OPT_TCP_KEEPALIVE_INT // 0x26,4, uint32 DHCP_OPT_TCP_KEEPALIVE_GARBAGE // 0x27,1, bool DHCP_OPT_NIS_DOMAIN // 0x28,n, string DHCP_OPT_NIS_SERVERS // 0x29,4*n, [n]net.IP DHCP_OPT_NTP_SERVERS // 0x2a, 4*n, [n]net.IP DHCP_OPT_VENDOR_OPT // 0x2b, n, [n]byte // may be encapsulated. DHCP_OPT_NETBIOS_IPNS // 0x2c, 4*n, [n]net.IP DHCP_OPT_NETBIOS_DDS // 0x2d, 4*n, [n]net.IP DHCP_OPT_NETBIOS_NODE_TYPE // 0x2e, 1, magic byte DHCP_OPT_NETBIOS_SCOPE // 0x2f, n, string DHCP_OPT_X_FONT_SERVER // 0x30, n, string DHCP_OPT_X_DISPLAY_MANAGER // 0x31, n, string DHCP_OPT_SIP_SERVERS byte = 0x78 // 0x78!, n, url DHCP_OPT_END byte = 0xff ) // I'm amazed that this is syntactically valid. // cool though. var DHCPOptionTypeStrings = [256]string{ DHCP_OPT_PAD: "(padding)", DHCP_OPT_SUBNET_MASK: "SubnetMask", DHCP_OPT_TIME_OFFSET: "TimeOffset", DHCP_OPT_DEFAULT_GATEWAY: "DefaultGateway", DHCP_OPT_TIME_SERVER: "rfc868", // old time server protocol, stringified to dissuade confusion w. NTP DHCP_OPT_NAME_SERVER: "ien116", // obscure nameserver protocol, stringified to dissuade confusion w. DNS DHCP_OPT_DOMAIN_NAME_SERVERS: "DNS", DHCP_OPT_LOG_SERVER: "mitLCS", // MIT LCS server protocol, yada yada w. Syslog DHCP_OPT_COOKIE_SERVER: "OPT_COOKIE_SERVER", DHCP_OPT_LPR_SERVER: "OPT_LPR_SERVER", DHCP_OPT_IMPRESS_SERVER: "OPT_IMPRESS_SERVER", DHCP_OPT_RLSERVER: "OPT_RLSERVER", DHCP_OPT_HOST_NAME: "Hostname", DHCP_OPT_BOOTFILE_SIZE: "BootfileSize", DHCP_OPT_MERIT_DUMP_FILE: "OPT_MERIT_DUMP_FILE", DHCP_OPT_DOMAIN_NAME: "DomainName", DHCP_OPT_SWAP_SERVER: "OPT_SWAP_SERVER", DHCP_OPT_ROOT_PATH: "RootPath", DHCP_OPT_EXTENSIONS_PATH: "OPT_EXTENSIONS_PATH", DHCP_OPT_IP_FORWARDING: "OPT_IP_FORWARDING", DHCP_OPT_SOURCE_ROUTING: "OPT_SOURCE_ROUTING", DHCP_OPT_POLICY_FILTER: "OPT_POLICY_FILTER", DHCP_OPT_DGRAM_MTU: "OPT_DGRAM_MTU", DHCP_OPT_DEFAULT_TTL: "OPT_DEFAULT_TTL", DHCP_OPT_PATH_MTU_AGING_TIMEOUT: "OPT_PATH_MTU_AGING_TIMEOUT", DHCP_OPT_PATH_PLATEU_TABLE_OPTION: "OPT_PATH_PLATEU_TABLE_OPTION", DHCP_OPT_INTERFACE_MTU: "OPT_INTERFACE_MTU", DHCP_OPT_ALL_SUBS_LOCAL: "OPT_ALL_SUBS_LOCAL", DHCP_OPT_BROADCAST_ADDR: "OPT_BROADCAST_ADDR", DHCP_OPT_MASK_DISCOVERY: "OPT_MASK_DISCOVERY", DHCP_OPT_MASK_SUPPLIER: "OPT_MASK_SUPPLIER", DHCP_OPT_ROUTER_DISCOVERY: "OPT_ROUTER_DISCOVERY", DHCP_OPT_ROUTER_SOLICIT_ADDR: "OPT_ROUTER_SOLICIT_ADDR", DHCP_OPT_STATIC_ROUTE: "OPT_STATIC_ROUTE", DHCP_OPT_ARP_TRAILERS: "OPT_ARP_TRAILERS", DHCP_OPT_ARP_TIMEOUT: "OPT_ARP_TIMEOUT", DHCP_OPT_ETHERNET_ENCAP: "OPT_ETHERNET_ENCAP", DHCP_OPT_TCP_TTL: "OPT_TCP_TTL", DHCP_OPT_TCP_KEEPALIVE_INT: "OPT_TCP_KEEPALIVE_INT", DHCP_OPT_TCP_KEEPALIVE_GARBAGE: "OPT_TCP_KEEPALIVE_GARBAGE", DHCP_OPT_NIS_DOMAIN: "OPT_NIS_DOMAIN", DHCP_OPT_NIS_SERVERS: "OPT_NIS_SERVERS", DHCP_OPT_NTP_SERVERS: "OPT_NTP_SERVERS", DHCP_OPT_VENDOR_OPT: "OPT_VENDOR_OPT", DHCP_OPT_NETBIOS_IPNS: "OPT_NETBIOS_IPNS", DHCP_OPT_NETBIOS_DDS: "OPT_NETBIOS_DDS", DHCP_OPT_NETBIOS_NODE_TYPE: "OPT_NETBIOS_NODE_TYPE", DHCP_OPT_NETBIOS_SCOPE: "OPT_NETBIOS_SCOPE", DHCP_OPT_X_FONT_SERVER: "OPT_X_FONT_SERVER", DHCP_OPT_X_DISPLAY_MANAGER: "OPT_X_DISPLAY_MANAGER", DHCP_OPT_END: "(end)", DHCP_OPT_SIP_SERVERS: "SipServers", DHCP_OPT_REQUEST_IP: "RequestIP", DHCP_OPT_LEASE_TIME: "LeaseTime", DHCP_OPT_EXT_OPTS: "ExtOpts", DHCP_OPT_MESSAGE_TYPE: "MessageType", DHCP_OPT_SERVER_ID: "ServerID", DHCP_OPT_PARAMS_REQUEST: "ParamsRequest", DHCP_OPT_MESSAGE: "Message", DHCP_OPT_MAX_DHCP_SIZE: "MaxDHCPSize", DHCP_OPT_T1: "Timer1", DHCP_OPT_T2: "Timer2", DHCP_OPT_CLASS_ID: "ClassID", DHCP_OPT_CLIENT_ID: "ClientID", } type DHCPOption interface { OptionType() byte Bytes() []byte Len() uint16 } // Write an option to an io.Writer, including tag & length // (if length is appropriate to the tag type). // Utilizes the MarshalOption as the underlying serializer. func DHCPWriteOption(w io.Writer, a DHCPOption) (n int, err error) { out, err := DHCPMarshalOption(a) if err == nil { n, err = w.Write(out) } return } type dhcpoption struct { tag byte data []byte } // A more json.Marshal like version of WriteOption. func DHCPMarshalOption(o DHCPOption) (out []byte, err error) { switch o.OptionType() { case DHCP_OPT_PAD, DHCP_OPT_END: out = []byte{o.OptionType()} default: dlen := len(o.Bytes()) if dlen > 253 { err = errors.New("Data too long to marshal") } else { out = make([]byte, dlen+2) out[0], out[1] = o.OptionType(), byte(dlen) copy(out[2:], o.Bytes()) } } return } func (self dhcpoption) Len() uint16 { return uint16(len(self.data) + 2) } func (self dhcpoption) Bytes() []byte { return self.data } func (self dhcpoption) OptionType() byte { return self.tag } func DHCPNewOption(tag byte, data []byte) DHCPOption { return &dhcpoption{tag: tag, data: data} } // NB: We don't validate that you have /any/ IP's in the option here, // simply that if you do that they're valid. Most DHCP options are only // valid with 1(+|) values func DHCPIP4sOption(tag byte, ips []net.IP) (opt DHCPOption, err error) { var out []byte = make([]byte, 4*len(ips)) for i := range ips { ip := ips[i].To4() if ip == nil { err = errors.New("ip is not a valid IPv4 address") } else { copy(out[i*4:], []byte(ip)) } if err != nil { break } } opt = DHCPNewOption(tag, out) return } // NB: We don't validate that you have /any/ IP's in the option here, // simply that if you do that they're valid. Most DHCP options are only // valid with 1(+|) values func DHCPIP4Option(tag byte, ips net.IP) (opt DHCPOption, err error) { ips = ips.To4() if ips == nil { err = errors.New("ip is not a valid IPv4 address") return } opt = DHCPNewOption(tag, []byte(ips)) return } // NB: I'm not checking tag : min length here! func DHCPStringOption(tag byte, s string) (opt DHCPOption, err error) { opt = &dhcpoption{tag: tag, data: bytes.NewBufferString(s).Bytes()} return } func DHCPParseOptions(in []byte) (opts []DHCPOption, err error) { pos := 0 for pos < len(in) && err == nil { var tag = in[pos] pos++ switch tag { case DHCP_OPT_PAD: opts = append(opts, DHCPNewOption(tag, []byte{})) case DHCP_OPT_END: return default: if len(in)-pos >= 1 { _len := in[pos] pos++ opts = append(opts, DHCPNewOption(tag, in[pos:pos+int(_len)])) pos += int(_len) } } } return } func NewDHCPDiscover(xid uint32, hwAddr net.HardwareAddr) (d *DHCP, err error) { if d, err = NewDHCP(xid, DHCP_MSG_DISCOVER, DHCP_HW_ETHERNET); err != nil { return } d.HardwareLen = uint8(len(hwAddr)) d.ClientHWAddr = hwAddr d.Options = append(d.Options, DHCPNewOption(53, []byte{byte(DHCP_MSG_DISCOVER)})) d.Options = append(d.Options, DHCPNewOption(DHCP_OPT_CLIENT_ID, hwAddr)) return } func NewDHCPOffer(xid uint32, hwAddr net.HardwareAddr) (d *DHCP, err error) { if d, err = NewDHCP(xid, DHCP_MSG_OFFER, DHCP_HW_ETHERNET); err != nil { return } d.HardwareLen = uint8(len(hwAddr)) d.ClientHWAddr = hwAddr d.Options = append(d.Options, DHCPNewOption(53, []byte{byte(DHCP_MSG_OFFER)})) return } func NewDHCPRequest(xid uint32, hwAddr net.HardwareAddr) (d *DHCP, err error) { if d, err = NewDHCP(xid, DHCP_MSG_REQUEST, DHCP_HW_ETHERNET); err != nil { return } d.HardwareLen = uint8(len(hwAddr)) d.ClientHWAddr = hwAddr d.Options = append(d.Options, DHCPNewOption(53, []byte{byte(DHCP_MSG_REQUEST)})) return } func NewDHCPAck(xid uint32, hwAddr net.HardwareAddr) (d *DHCP, err error) { if d, err = NewDHCP(xid, DHCP_MSG_ACK, DHCP_HW_ETHERNET); err != nil { return } d.HardwareLen = uint8(len(hwAddr)) d.ClientHWAddr = hwAddr d.Options = append(d.Options, DHCPNewOption(53, []byte{byte(DHCP_MSG_ACK)})) return } func NewDHCPNak(xid uint32, hwAddr net.HardwareAddr) (d *DHCP, err error) { if d, err = NewDHCP(xid, DHCP_MSG_NAK, DHCP_HW_ETHERNET); err != nil { return } d.HardwareLen = uint8(len(hwAddr)) d.ClientHWAddr = hwAddr d.Options = append(d.Options, DHCPNewOption(53, []byte{byte(DHCP_MSG_NAK)})) return } <|start_filename|>vendor/github.com/contiv/ofnet/rpcHub/rpcHub.go<|end_filename|> /*** Copyright 2014 Cisco Systems 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. */ package rpcHub // Hub and spoke RPC implementation based on JSON RPC library import ( "errors" "fmt" "io" "net" "net/rpc" "net/rpc/jsonrpc" "strings" "sync" "time" log "github.com/Sirupsen/logrus" ) // Info for eahc client type RpcClient struct { servAddr string portNo uint16 client *rpc.Client conn net.Conn } // DB of all existing clients var clientDb map[string]*RpcClient = make(map[string]*RpcClient) var dbLock sync.RWMutex // Create a new RPC server func NewRpcServer(portNo uint16) (*rpc.Server, net.Listener) { server := rpc.NewServer() // Listens on a port l, e := net.Listen("tcp", fmt.Sprintf(":%d", portNo)) listener := ListenWrapper(l) if e != nil { log.Fatal("listen error:", e) } log.Infof("RPC Server is listening on %s\n", l.Addr()) // run in background go func() { for { conn, err := listener.Accept() if err != nil { // if listener closed, just exit the groutine if strings.Contains(err.Error(), "use of closed network connection") { return } log.Fatal(err) } log.Infof("Server accepted connection to %s from %s\n", conn.LocalAddr(), conn.RemoteAddr()) go server.ServeCodec(jsonrpc.NewServerCodec(conn)) } }() return server, listener } // Create a new client func dialRpcClient(servAddr string, portNo uint16) (*rpc.Client, net.Conn) { var client *rpc.Client var conn net.Conn var err error log.Infof("Connecting to RPC server: %s:%d", servAddr, portNo) // Retry connecting for 5sec and then give up for i := 0; i < 5; i++ { // Connect to the server conn, err = net.Dial("tcp", fmt.Sprintf("%s:%d", servAddr, portNo)) if err == nil { log.Infof("Connected to RPC server: %s:%d", servAddr, portNo) // Create an RPC client client = jsonrpc.NewClient(conn) break } log.Warnf("Error %v connecting to %s:%s. Retrying..", err, servAddr, portNo) // Sleep for a second and retry again time.Sleep(1 * time.Second) } // If we failed to connect, report error if client == nil { log.Errorf("Failed to connect to Rpc server %s:%d", servAddr, portNo) return nil, nil } return client, conn } // Get a client to the rpc server func Client(servAddr string, portNo uint16) *RpcClient { clientKey := fmt.Sprintf("%s:%d", servAddr, portNo) dbLock.Lock() defer dbLock.Unlock() // Return the client if it already exists if (clientDb[clientKey] != nil) && (clientDb[clientKey].conn != nil) { return clientDb[clientKey] } // Create a new client and add it to the DB client, conn := dialRpcClient(servAddr, portNo) rpcClient := RpcClient{ servAddr: servAddr, portNo: portNo, client: client, conn: conn, } clientDb[clientKey] = &rpcClient return &rpcClient } func DisconnectClient(portNo uint16, servAddr string) { clientKey := fmt.Sprintf("%s:%d", servAddr, portNo) dbLock.Lock() clientDb[clientKey] = nil dbLock.Unlock() } // Make an rpc call func (self *RpcClient) Call(serviceMethod string, args interface{}, reply interface{}) error { // Check if connectin failed if self.client == nil { log.Errorf("Error calling RPC: %s. Could not connect to server", serviceMethod) return errors.New("Could not connect to server") } // Perform RPC call. err := self.client.Call(serviceMethod, args, reply) if err == nil { return nil } // Check if we need to reconnect if err == rpc.ErrShutdown || err == io.ErrUnexpectedEOF { self.client, self.conn = dialRpcClient(self.servAddr, self.portNo) if self.client == nil { log.Errorf("Error calling RPC: %s. Could not connect to server", serviceMethod) return errors.New("Could not connect to server") } // Retry making the call return self.client.Call(serviceMethod, args, reply) } return err } // ListenWrapper is a wrapper over net.Listener func ListenWrapper(l net.Listener) net.Listener { return &contivListener{ Listener: l, cond: sync.NewCond(&sync.Mutex{})} } type contivListener struct { net.Listener cond *sync.Cond refCnt int } func (s *contivListener) incrementRef() { s.cond.L.Lock() s.refCnt++ s.cond.L.Unlock() } func (s *contivListener) decrementRef() { s.cond.L.Lock() s.refCnt-- newRefs := s.refCnt s.cond.L.Unlock() if newRefs == 0 { s.cond.Broadcast() } } // Accept is a wrapper over regular Accept call // which also maintains the refCnt func (s *contivListener) Accept() (net.Conn, error) { s.incrementRef() defer s.decrementRef() return s.Listener.Accept() } // Close closes the contivListener. func (s *contivListener) Close() error { if err := s.Listener.Close(); err != nil { return err } s.cond.L.Lock() for s.refCnt > 0 { s.cond.Wait() } s.cond.L.Unlock() return nil } <|start_filename|>vendor/github.com/osrg/gobgp/api/gobgp.pb.go<|end_filename|> // Code generated by protoc-gen-go. // source: gobgp.proto // DO NOT EDIT! /* Package gobgpapi is a generated protocol buffer package. It is generated from these files: gobgp.proto It has these top-level messages: GetNeighborRequest GetNeighborResponse Arguments AddPathRequest AddPathResponse DeletePathRequest DeletePathResponse AddNeighborRequest AddNeighborResponse DeleteNeighborRequest DeleteNeighborResponse ResetNeighborRequest ResetNeighborResponse SoftResetNeighborRequest SoftResetNeighborResponse ShutdownNeighborRequest ShutdownNeighborResponse EnableNeighborRequest EnableNeighborResponse DisableNeighborRequest DisableNeighborResponse EnableMrtRequest EnableMrtResponse DisableMrtRequest DisableMrtResponse InjectMrtRequest InjectMrtResponse AddBmpRequest AddBmpResponse DeleteBmpRequest DeleteBmpResponse RPKIConf RPKIState Rpki GetRpkiRequest GetRpkiResponse AddRpkiRequest AddRpkiResponse DeleteRpkiRequest DeleteRpkiResponse EnableRpkiRequest EnableRpkiResponse DisableRpkiRequest DisableRpkiResponse ResetRpkiRequest ResetRpkiResponse SoftResetRpkiRequest SoftResetRpkiResponse EnableZebraRequest EnableZebraResponse GetVrfRequest GetVrfResponse AddVrfRequest AddVrfResponse DeleteVrfRequest DeleteVrfResponse GetDefinedSetRequest GetDefinedSetResponse AddDefinedSetRequest AddDefinedSetResponse DeleteDefinedSetRequest DeleteDefinedSetResponse ReplaceDefinedSetRequest ReplaceDefinedSetResponse GetStatementRequest GetStatementResponse AddStatementRequest AddStatementResponse DeleteStatementRequest DeleteStatementResponse ReplaceStatementRequest ReplaceStatementResponse GetPolicyRequest GetPolicyResponse AddPolicyRequest AddPolicyResponse DeletePolicyRequest DeletePolicyResponse ReplacePolicyRequest ReplacePolicyResponse GetPolicyAssignmentRequest GetPolicyAssignmentResponse AddPolicyAssignmentRequest AddPolicyAssignmentResponse DeletePolicyAssignmentRequest DeletePolicyAssignmentResponse ReplacePolicyAssignmentRequest ReplacePolicyAssignmentResponse GetServerRequest GetServerResponse StartServerRequest StartServerResponse StopServerRequest StopServerResponse Path Destination Table GetRibRequest GetRibResponse ValidateRibRequest ValidateRibResponse Peer ApplyPolicy PrefixLimit PeerConf EbgpMultihop RouteReflector PeerState Messages Message Queues Timers TimersConfig TimersState Transport RouteServer Prefix DefinedSet MatchSet AsPathLength Conditions CommunityAction MedAction AsPrependAction NexthopAction LocalPrefAction Actions Statement Policy PolicyAssignment Roa GetRoaRequest GetRoaResponse Vrf Global */ package gobgpapi import proto "github.com/golang/protobuf/proto" import fmt "fmt" import math "math" import ( context "golang.org/x/net/context" grpc "google.golang.org/grpc" ) // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package type Resource int32 const ( Resource_GLOBAL Resource = 0 Resource_LOCAL Resource = 1 Resource_ADJ_IN Resource = 2 Resource_ADJ_OUT Resource = 3 Resource_VRF Resource = 4 ) var Resource_name = map[int32]string{ 0: "GLOBAL", 1: "LOCAL", 2: "ADJ_IN", 3: "ADJ_OUT", 4: "VRF", } var Resource_value = map[string]int32{ "GLOBAL": 0, "LOCAL": 1, "ADJ_IN": 2, "ADJ_OUT": 3, "VRF": 4, } func (x Resource) String() string { return proto.EnumName(Resource_name, int32(x)) } func (Resource) EnumDescriptor() ([]byte, []int) { return fileDescriptor0, []int{0} } type DefinedType int32 const ( DefinedType_PREFIX DefinedType = 0 DefinedType_NEIGHBOR DefinedType = 1 DefinedType_TAG DefinedType = 2 DefinedType_AS_PATH DefinedType = 3 DefinedType_COMMUNITY DefinedType = 4 DefinedType_EXT_COMMUNITY DefinedType = 5 ) var DefinedType_name = map[int32]string{ 0: "PREFIX", 1: "NEIGHBOR", 2: "TAG", 3: "AS_PATH", 4: "COMMUNITY", 5: "EXT_COMMUNITY", } var DefinedType_value = map[string]int32{ "PREFIX": 0, "NEIGHBOR": 1, "TAG": 2, "AS_PATH": 3, "COMMUNITY": 4, "EXT_COMMUNITY": 5, } func (x DefinedType) String() string { return proto.EnumName(DefinedType_name, int32(x)) } func (DefinedType) EnumDescriptor() ([]byte, []int) { return fileDescriptor0, []int{1} } type MatchType int32 const ( MatchType_ANY MatchType = 0 MatchType_ALL MatchType = 1 MatchType_INVERT MatchType = 2 ) var MatchType_name = map[int32]string{ 0: "ANY", 1: "ALL", 2: "INVERT", } var MatchType_value = map[string]int32{ "ANY": 0, "ALL": 1, "INVERT": 2, } func (x MatchType) String() string { return proto.EnumName(MatchType_name, int32(x)) } func (MatchType) EnumDescriptor() ([]byte, []int) { return fileDescriptor0, []int{2} } type AsPathLengthType int32 const ( AsPathLengthType_EQ AsPathLengthType = 0 AsPathLengthType_GE AsPathLengthType = 1 AsPathLengthType_LE AsPathLengthType = 2 ) var AsPathLengthType_name = map[int32]string{ 0: "EQ", 1: "GE", 2: "LE", } var AsPathLengthType_value = map[string]int32{ "EQ": 0, "GE": 1, "LE": 2, } func (x AsPathLengthType) String() string { return proto.EnumName(AsPathLengthType_name, int32(x)) } func (AsPathLengthType) EnumDescriptor() ([]byte, []int) { return fileDescriptor0, []int{3} } type RouteAction int32 const ( RouteAction_NONE RouteAction = 0 RouteAction_ACCEPT RouteAction = 1 RouteAction_REJECT RouteAction = 2 ) var RouteAction_name = map[int32]string{ 0: "NONE", 1: "ACCEPT", 2: "REJECT", } var RouteAction_value = map[string]int32{ "NONE": 0, "ACCEPT": 1, "REJECT": 2, } func (x RouteAction) String() string { return proto.EnumName(RouteAction_name, int32(x)) } func (RouteAction) EnumDescriptor() ([]byte, []int) { return fileDescriptor0, []int{4} } type CommunityActionType int32 const ( CommunityActionType_COMMUNITY_ADD CommunityActionType = 0 CommunityActionType_COMMUNITY_REMOVE CommunityActionType = 1 CommunityActionType_COMMUNITY_REPLACE CommunityActionType = 2 ) var CommunityActionType_name = map[int32]string{ 0: "COMMUNITY_ADD", 1: "COMMUNITY_REMOVE", 2: "COMMUNITY_REPLACE", } var CommunityActionType_value = map[string]int32{ "COMMUNITY_ADD": 0, "COMMUNITY_REMOVE": 1, "COMMUNITY_REPLACE": 2, } func (x CommunityActionType) String() string { return proto.EnumName(CommunityActionType_name, int32(x)) } func (CommunityActionType) EnumDescriptor() ([]byte, []int) { return fileDescriptor0, []int{5} } type MedActionType int32 const ( MedActionType_MED_MOD MedActionType = 0 MedActionType_MED_REPLACE MedActionType = 1 ) var MedActionType_name = map[int32]string{ 0: "MED_MOD", 1: "MED_REPLACE", } var MedActionType_value = map[string]int32{ "MED_MOD": 0, "MED_REPLACE": 1, } func (x MedActionType) String() string { return proto.EnumName(MedActionType_name, int32(x)) } func (MedActionType) EnumDescriptor() ([]byte, []int) { return fileDescriptor0, []int{6} } type PolicyType int32 const ( PolicyType_IN PolicyType = 0 PolicyType_IMPORT PolicyType = 1 PolicyType_EXPORT PolicyType = 2 ) var PolicyType_name = map[int32]string{ 0: "IN", 1: "IMPORT", 2: "EXPORT", } var PolicyType_value = map[string]int32{ "IN": 0, "IMPORT": 1, "EXPORT": 2, } func (x PolicyType) String() string { return proto.EnumName(PolicyType_name, int32(x)) } func (PolicyType) EnumDescriptor() ([]byte, []int) { return fileDescriptor0, []int{7} } type SoftResetNeighborRequest_SoftResetDirection int32 const ( SoftResetNeighborRequest_IN SoftResetNeighborRequest_SoftResetDirection = 0 SoftResetNeighborRequest_OUT SoftResetNeighborRequest_SoftResetDirection = 1 SoftResetNeighborRequest_BOTH SoftResetNeighborRequest_SoftResetDirection = 2 ) var SoftResetNeighborRequest_SoftResetDirection_name = map[int32]string{ 0: "IN", 1: "OUT", 2: "BOTH", } var SoftResetNeighborRequest_SoftResetDirection_value = map[string]int32{ "IN": 0, "OUT": 1, "BOTH": 2, } func (x SoftResetNeighborRequest_SoftResetDirection) String() string { return proto.EnumName(SoftResetNeighborRequest_SoftResetDirection_name, int32(x)) } func (SoftResetNeighborRequest_SoftResetDirection) EnumDescriptor() ([]byte, []int) { return fileDescriptor0, []int{13, 0} } type AddBmpRequest_MonitoringPolicy int32 const ( AddBmpRequest_PRE AddBmpRequest_MonitoringPolicy = 0 AddBmpRequest_POST AddBmpRequest_MonitoringPolicy = 1 AddBmpRequest_BOTH AddBmpRequest_MonitoringPolicy = 2 ) var AddBmpRequest_MonitoringPolicy_name = map[int32]string{ 0: "PRE", 1: "POST", 2: "BOTH", } var AddBmpRequest_MonitoringPolicy_value = map[string]int32{ "PRE": 0, "POST": 1, "BOTH": 2, } func (x AddBmpRequest_MonitoringPolicy) String() string { return proto.EnumName(AddBmpRequest_MonitoringPolicy_name, int32(x)) } func (AddBmpRequest_MonitoringPolicy) EnumDescriptor() ([]byte, []int) { return fileDescriptor0, []int{27, 0} } type Conditions_RouteType int32 const ( Conditions_ROUTE_TYPE_NONE Conditions_RouteType = 0 Conditions_ROUTE_TYPE_INTERNAL Conditions_RouteType = 1 Conditions_ROUTE_TYPE_EXTERNAL Conditions_RouteType = 2 Conditions_ROUTE_TYPE_LOCAL Conditions_RouteType = 3 ) var Conditions_RouteType_name = map[int32]string{ 0: "ROUTE_TYPE_NONE", 1: "ROUTE_TYPE_INTERNAL", 2: "ROUTE_TYPE_EXTERNAL", 3: "ROUTE_TYPE_LOCAL", } var Conditions_RouteType_value = map[string]int32{ "ROUTE_TYPE_NONE": 0, "ROUTE_TYPE_INTERNAL": 1, "ROUTE_TYPE_EXTERNAL": 2, "ROUTE_TYPE_LOCAL": 3, } func (x Conditions_RouteType) String() string { return proto.EnumName(Conditions_RouteType_name, int32(x)) } func (Conditions_RouteType) EnumDescriptor() ([]byte, []int) { return fileDescriptor0, []int{120, 0} } type GetNeighborRequest struct { } func (m *GetNeighborRequest) Reset() { *m = GetNeighborRequest{} } func (m *GetNeighborRequest) String() string { return proto.CompactTextString(m) } func (*GetNeighborRequest) ProtoMessage() {} func (*GetNeighborRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} } type GetNeighborResponse struct { Peers []*Peer `protobuf:"bytes,1,rep,name=peers" json:"peers,omitempty"` } func (m *GetNeighborResponse) Reset() { *m = GetNeighborResponse{} } func (m *GetNeighborResponse) String() string { return proto.CompactTextString(m) } func (*GetNeighborResponse) ProtoMessage() {} func (*GetNeighborResponse) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{1} } func (m *GetNeighborResponse) GetPeers() []*Peer { if m != nil { return m.Peers } return nil } type Arguments struct { Resource Resource `protobuf:"varint,1,opt,name=resource,enum=gobgpapi.Resource" json:"resource,omitempty"` Family uint32 `protobuf:"varint,2,opt,name=family" json:"family,omitempty"` Name string `protobuf:"bytes,3,opt,name=name" json:"name,omitempty"` } func (m *Arguments) Reset() { *m = Arguments{} } func (m *Arguments) String() string { return proto.CompactTextString(m) } func (*Arguments) ProtoMessage() {} func (*Arguments) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2} } type AddPathRequest struct { Resource Resource `protobuf:"varint,1,opt,name=resource,enum=gobgpapi.Resource" json:"resource,omitempty"` VrfId string `protobuf:"bytes,2,opt,name=vrf_id,json=vrfId" json:"vrf_id,omitempty"` Path *Path `protobuf:"bytes,3,opt,name=path" json:"path,omitempty"` } func (m *AddPathRequest) Reset() { *m = AddPathRequest{} } func (m *AddPathRequest) String() string { return proto.CompactTextString(m) } func (*AddPathRequest) ProtoMessage() {} func (*AddPathRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{3} } func (m *AddPathRequest) GetPath() *Path { if m != nil { return m.Path } return nil } type AddPathResponse struct { Uuid []byte `protobuf:"bytes,1,opt,name=uuid,proto3" json:"uuid,omitempty"` } func (m *AddPathResponse) Reset() { *m = AddPathResponse{} } func (m *AddPathResponse) String() string { return proto.CompactTextString(m) } func (*AddPathResponse) ProtoMessage() {} func (*AddPathResponse) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{4} } type DeletePathRequest struct { Resource Resource `protobuf:"varint,1,opt,name=resource,enum=gobgpapi.Resource" json:"resource,omitempty"` VrfId string `protobuf:"bytes,2,opt,name=vrf_id,json=vrfId" json:"vrf_id,omitempty"` Family uint32 `protobuf:"varint,3,opt,name=family" json:"family,omitempty"` Path *Path `protobuf:"bytes,4,opt,name=path" json:"path,omitempty"` Uuid []byte `protobuf:"bytes,5,opt,name=uuid,proto3" json:"uuid,omitempty"` } func (m *DeletePathRequest) Reset() { *m = DeletePathRequest{} } func (m *DeletePathRequest) String() string { return proto.CompactTextString(m) } func (*DeletePathRequest) ProtoMessage() {} func (*DeletePathRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{5} } func (m *DeletePathRequest) GetPath() *Path { if m != nil { return m.Path } return nil } type DeletePathResponse struct { } func (m *DeletePathResponse) Reset() { *m = DeletePathResponse{} } func (m *DeletePathResponse) String() string { return proto.CompactTextString(m) } func (*DeletePathResponse) ProtoMessage() {} func (*DeletePathResponse) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{6} } type AddNeighborRequest struct { Peer *Peer `protobuf:"bytes,1,opt,name=peer" json:"peer,omitempty"` } func (m *AddNeighborRequest) Reset() { *m = AddNeighborRequest{} } func (m *AddNeighborRequest) String() string { return proto.CompactTextString(m) } func (*AddNeighborRequest) ProtoMessage() {} func (*AddNeighborRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{7} } func (m *AddNeighborRequest) GetPeer() *Peer { if m != nil { return m.Peer } return nil } type AddNeighborResponse struct { } func (m *AddNeighborResponse) Reset() { *m = AddNeighborResponse{} } func (m *AddNeighborResponse) String() string { return proto.CompactTextString(m) } func (*AddNeighborResponse) ProtoMessage() {} func (*AddNeighborResponse) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{8} } type DeleteNeighborRequest struct { Peer *Peer `protobuf:"bytes,1,opt,name=peer" json:"peer,omitempty"` } func (m *DeleteNeighborRequest) Reset() { *m = DeleteNeighborRequest{} } func (m *DeleteNeighborRequest) String() string { return proto.CompactTextString(m) } func (*DeleteNeighborRequest) ProtoMessage() {} func (*DeleteNeighborRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{9} } func (m *DeleteNeighborRequest) GetPeer() *Peer { if m != nil { return m.Peer } return nil } type DeleteNeighborResponse struct { } func (m *DeleteNeighborResponse) Reset() { *m = DeleteNeighborResponse{} } func (m *DeleteNeighborResponse) String() string { return proto.CompactTextString(m) } func (*DeleteNeighborResponse) ProtoMessage() {} func (*DeleteNeighborResponse) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{10} } type ResetNeighborRequest struct { Address string `protobuf:"bytes,1,opt,name=address" json:"address,omitempty"` } func (m *ResetNeighborRequest) Reset() { *m = ResetNeighborRequest{} } func (m *ResetNeighborRequest) String() string { return proto.CompactTextString(m) } func (*ResetNeighborRequest) ProtoMessage() {} func (*ResetNeighborRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{11} } type ResetNeighborResponse struct { } func (m *ResetNeighborResponse) Reset() { *m = ResetNeighborResponse{} } func (m *ResetNeighborResponse) String() string { return proto.CompactTextString(m) } func (*ResetNeighborResponse) ProtoMessage() {} func (*ResetNeighborResponse) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{12} } type SoftResetNeighborRequest struct { Address string `protobuf:"bytes,1,opt,name=address" json:"address,omitempty"` Direction SoftResetNeighborRequest_SoftResetDirection `protobuf:"varint,2,opt,name=direction,enum=gobgpapi.SoftResetNeighborRequest_SoftResetDirection" json:"direction,omitempty"` } func (m *SoftResetNeighborRequest) Reset() { *m = SoftResetNeighborRequest{} } func (m *SoftResetNeighborRequest) String() string { return proto.CompactTextString(m) } func (*SoftResetNeighborRequest) ProtoMessage() {} func (*SoftResetNeighborRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{13} } type SoftResetNeighborResponse struct { } func (m *SoftResetNeighborResponse) Reset() { *m = SoftResetNeighborResponse{} } func (m *SoftResetNeighborResponse) String() string { return proto.CompactTextString(m) } func (*SoftResetNeighborResponse) ProtoMessage() {} func (*SoftResetNeighborResponse) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{14} } type ShutdownNeighborRequest struct { Address string `protobuf:"bytes,1,opt,name=address" json:"address,omitempty"` } func (m *ShutdownNeighborRequest) Reset() { *m = ShutdownNeighborRequest{} } func (m *ShutdownNeighborRequest) String() string { return proto.CompactTextString(m) } func (*ShutdownNeighborRequest) ProtoMessage() {} func (*ShutdownNeighborRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{15} } type ShutdownNeighborResponse struct { } func (m *ShutdownNeighborResponse) Reset() { *m = ShutdownNeighborResponse{} } func (m *ShutdownNeighborResponse) String() string { return proto.CompactTextString(m) } func (*ShutdownNeighborResponse) ProtoMessage() {} func (*ShutdownNeighborResponse) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{16} } type EnableNeighborRequest struct { Address string `protobuf:"bytes,1,opt,name=address" json:"address,omitempty"` } func (m *EnableNeighborRequest) Reset() { *m = EnableNeighborRequest{} } func (m *EnableNeighborRequest) String() string { return proto.CompactTextString(m) } func (*EnableNeighborRequest) ProtoMessage() {} func (*EnableNeighborRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{17} } type EnableNeighborResponse struct { } func (m *EnableNeighborResponse) Reset() { *m = EnableNeighborResponse{} } func (m *EnableNeighborResponse) String() string { return proto.CompactTextString(m) } func (*EnableNeighborResponse) ProtoMessage() {} func (*EnableNeighborResponse) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{18} } type DisableNeighborRequest struct { Address string `protobuf:"bytes,1,opt,name=address" json:"address,omitempty"` } func (m *DisableNeighborRequest) Reset() { *m = DisableNeighborRequest{} } func (m *DisableNeighborRequest) String() string { return proto.CompactTextString(m) } func (*DisableNeighborRequest) ProtoMessage() {} func (*DisableNeighborRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{19} } type DisableNeighborResponse struct { } func (m *DisableNeighborResponse) Reset() { *m = DisableNeighborResponse{} } func (m *DisableNeighborResponse) String() string { return proto.CompactTextString(m) } func (*DisableNeighborResponse) ProtoMessage() {} func (*DisableNeighborResponse) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{20} } type EnableMrtRequest struct { DumpType int32 `protobuf:"varint,1,opt,name=dump_type,json=dumpType" json:"dump_type,omitempty"` Filename string `protobuf:"bytes,2,opt,name=filename" json:"filename,omitempty"` Interval uint64 `protobuf:"varint,3,opt,name=interval" json:"interval,omitempty"` } func (m *EnableMrtRequest) Reset() { *m = EnableMrtRequest{} } func (m *EnableMrtRequest) String() string { return proto.CompactTextString(m) } func (*EnableMrtRequest) ProtoMessage() {} func (*EnableMrtRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{21} } type EnableMrtResponse struct { } func (m *EnableMrtResponse) Reset() { *m = EnableMrtResponse{} } func (m *EnableMrtResponse) String() string { return proto.CompactTextString(m) } func (*EnableMrtResponse) ProtoMessage() {} func (*EnableMrtResponse) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{22} } type DisableMrtRequest struct { } func (m *DisableMrtRequest) Reset() { *m = DisableMrtRequest{} } func (m *DisableMrtRequest) String() string { return proto.CompactTextString(m) } func (*DisableMrtRequest) ProtoMessage() {} func (*DisableMrtRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{23} } type DisableMrtResponse struct { } func (m *DisableMrtResponse) Reset() { *m = DisableMrtResponse{} } func (m *DisableMrtResponse) String() string { return proto.CompactTextString(m) } func (*DisableMrtResponse) ProtoMessage() {} func (*DisableMrtResponse) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{24} } type InjectMrtRequest struct { Resource Resource `protobuf:"varint,1,opt,name=resource,enum=gobgpapi.Resource" json:"resource,omitempty"` VrfId string `protobuf:"bytes,2,opt,name=vrf_id,json=vrfId" json:"vrf_id,omitempty"` Paths []*Path `protobuf:"bytes,3,rep,name=paths" json:"paths,omitempty"` } func (m *InjectMrtRequest) Reset() { *m = InjectMrtRequest{} } func (m *InjectMrtRequest) String() string { return proto.CompactTextString(m) } func (*InjectMrtRequest) ProtoMessage() {} func (*InjectMrtRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{25} } func (m *InjectMrtRequest) GetPaths() []*Path { if m != nil { return m.Paths } return nil } type InjectMrtResponse struct { } func (m *InjectMrtResponse) Reset() { *m = InjectMrtResponse{} } func (m *InjectMrtResponse) String() string { return proto.CompactTextString(m) } func (*InjectMrtResponse) ProtoMessage() {} func (*InjectMrtResponse) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{26} } type AddBmpRequest struct { Address string `protobuf:"bytes,1,opt,name=address" json:"address,omitempty"` Port uint32 `protobuf:"varint,2,opt,name=port" json:"port,omitempty"` Type AddBmpRequest_MonitoringPolicy `protobuf:"varint,3,opt,name=type,enum=gobgpapi.AddBmpRequest_MonitoringPolicy" json:"type,omitempty"` } func (m *AddBmpRequest) Reset() { *m = AddBmpRequest{} } func (m *AddBmpRequest) String() string { return proto.CompactTextString(m) } func (*AddBmpRequest) ProtoMessage() {} func (*AddBmpRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{27} } type AddBmpResponse struct { } func (m *AddBmpResponse) Reset() { *m = AddBmpResponse{} } func (m *AddBmpResponse) String() string { return proto.CompactTextString(m) } func (*AddBmpResponse) ProtoMessage() {} func (*AddBmpResponse) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{28} } type DeleteBmpRequest struct { Address string `protobuf:"bytes,1,opt,name=address" json:"address,omitempty"` Port uint32 `protobuf:"varint,2,opt,name=port" json:"port,omitempty"` } func (m *DeleteBmpRequest) Reset() { *m = DeleteBmpRequest{} } func (m *DeleteBmpRequest) String() string { return proto.CompactTextString(m) } func (*DeleteBmpRequest) ProtoMessage() {} func (*DeleteBmpRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{29} } type DeleteBmpResponse struct { } func (m *DeleteBmpResponse) Reset() { *m = DeleteBmpResponse{} } func (m *DeleteBmpResponse) String() string { return proto.CompactTextString(m) } func (*DeleteBmpResponse) ProtoMessage() {} func (*DeleteBmpResponse) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{30} } type RPKIConf struct { Address string `protobuf:"bytes,1,opt,name=address" json:"address,omitempty"` RemotePort string `protobuf:"bytes,2,opt,name=remote_port,json=remotePort" json:"remote_port,omitempty"` } func (m *RPKIConf) Reset() { *m = RPKIConf{} } func (m *RPKIConf) String() string { return proto.CompactTextString(m) } func (*RPKIConf) ProtoMessage() {} func (*RPKIConf) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{31} } type RPKIState struct { Uptime int64 `protobuf:"varint,1,opt,name=uptime" json:"uptime,omitempty"` Downtime int64 `protobuf:"varint,2,opt,name=downtime" json:"downtime,omitempty"` Up bool `protobuf:"varint,3,opt,name=up" json:"up,omitempty"` RecordIpv4 uint32 `protobuf:"varint,4,opt,name=record_ipv4,json=recordIpv4" json:"record_ipv4,omitempty"` RecordIpv6 uint32 `protobuf:"varint,5,opt,name=record_ipv6,json=recordIpv6" json:"record_ipv6,omitempty"` PrefixIpv4 uint32 `protobuf:"varint,6,opt,name=prefix_ipv4,json=prefixIpv4" json:"prefix_ipv4,omitempty"` PrefixIpv6 uint32 `protobuf:"varint,7,opt,name=prefix_ipv6,json=prefixIpv6" json:"prefix_ipv6,omitempty"` Serial uint32 `protobuf:"varint,8,opt,name=serial" json:"serial,omitempty"` ReceivedIpv4 int64 `protobuf:"varint,9,opt,name=received_ipv4,json=receivedIpv4" json:"received_ipv4,omitempty"` ReceivedIpv6 int64 `protobuf:"varint,10,opt,name=received_ipv6,json=receivedIpv6" json:"received_ipv6,omitempty"` SerialNotify int64 `protobuf:"varint,11,opt,name=serial_notify,json=serialNotify" json:"serial_notify,omitempty"` CacheReset int64 `protobuf:"varint,12,opt,name=cache_reset,json=cacheReset" json:"cache_reset,omitempty"` CacheResponse int64 `protobuf:"varint,13,opt,name=cache_response,json=cacheResponse" json:"cache_response,omitempty"` EndOfData int64 `protobuf:"varint,14,opt,name=end_of_data,json=endOfData" json:"end_of_data,omitempty"` Error int64 `protobuf:"varint,15,opt,name=error" json:"error,omitempty"` SerialQuery int64 `protobuf:"varint,16,opt,name=serial_query,json=serialQuery" json:"serial_query,omitempty"` ResetQuery int64 `protobuf:"varint,17,opt,name=reset_query,json=resetQuery" json:"reset_query,omitempty"` } func (m *RPKIState) Reset() { *m = RPKIState{} } func (m *RPKIState) String() string { return proto.CompactTextString(m) } func (*RPKIState) ProtoMessage() {} func (*RPKIState) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{32} } type Rpki struct { Conf *RPKIConf `protobuf:"bytes,1,opt,name=conf" json:"conf,omitempty"` State *RPKIState `protobuf:"bytes,2,opt,name=state" json:"state,omitempty"` } func (m *Rpki) Reset() { *m = Rpki{} } func (m *Rpki) String() string { return proto.CompactTextString(m) } func (*Rpki) ProtoMessage() {} func (*Rpki) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{33} } func (m *Rpki) GetConf() *RPKIConf { if m != nil { return m.Conf } return nil } func (m *Rpki) GetState() *RPKIState { if m != nil { return m.State } return nil } type GetRpkiRequest struct { Family uint32 `protobuf:"varint,1,opt,name=family" json:"family,omitempty"` } func (m *GetRpkiRequest) Reset() { *m = GetRpkiRequest{} } func (m *GetRpkiRequest) String() string { return proto.CompactTextString(m) } func (*GetRpkiRequest) ProtoMessage() {} func (*GetRpkiRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{34} } type GetRpkiResponse struct { Servers []*Rpki `protobuf:"bytes,1,rep,name=servers" json:"servers,omitempty"` } func (m *GetRpkiResponse) Reset() { *m = GetRpkiResponse{} } func (m *GetRpkiResponse) String() string { return proto.CompactTextString(m) } func (*GetRpkiResponse) ProtoMessage() {} func (*GetRpkiResponse) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{35} } func (m *GetRpkiResponse) GetServers() []*Rpki { if m != nil { return m.Servers } return nil } type AddRpkiRequest struct { Address string `protobuf:"bytes,1,opt,name=address" json:"address,omitempty"` Port uint32 `protobuf:"varint,2,opt,name=port" json:"port,omitempty"` Lifetime int64 `protobuf:"varint,3,opt,name=lifetime" json:"lifetime,omitempty"` } func (m *AddRpkiRequest) Reset() { *m = AddRpkiRequest{} } func (m *AddRpkiRequest) String() string { return proto.CompactTextString(m) } func (*AddRpkiRequest) ProtoMessage() {} func (*AddRpkiRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{36} } type AddRpkiResponse struct { } func (m *AddRpkiResponse) Reset() { *m = AddRpkiResponse{} } func (m *AddRpkiResponse) String() string { return proto.CompactTextString(m) } func (*AddRpkiResponse) ProtoMessage() {} func (*AddRpkiResponse) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{37} } type DeleteRpkiRequest struct { Address string `protobuf:"bytes,1,opt,name=address" json:"address,omitempty"` Port uint32 `protobuf:"varint,2,opt,name=port" json:"port,omitempty"` } func (m *DeleteRpkiRequest) Reset() { *m = DeleteRpkiRequest{} } func (m *DeleteRpkiRequest) String() string { return proto.CompactTextString(m) } func (*DeleteRpkiRequest) ProtoMessage() {} func (*DeleteRpkiRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{38} } type DeleteRpkiResponse struct { } func (m *DeleteRpkiResponse) Reset() { *m = DeleteRpkiResponse{} } func (m *DeleteRpkiResponse) String() string { return proto.CompactTextString(m) } func (*DeleteRpkiResponse) ProtoMessage() {} func (*DeleteRpkiResponse) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{39} } type EnableRpkiRequest struct { Address string `protobuf:"bytes,1,opt,name=address" json:"address,omitempty"` } func (m *EnableRpkiRequest) Reset() { *m = EnableRpkiRequest{} } func (m *EnableRpkiRequest) String() string { return proto.CompactTextString(m) } func (*EnableRpkiRequest) ProtoMessage() {} func (*EnableRpkiRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{40} } type EnableRpkiResponse struct { } func (m *EnableRpkiResponse) Reset() { *m = EnableRpkiResponse{} } func (m *EnableRpkiResponse) String() string { return proto.CompactTextString(m) } func (*EnableRpkiResponse) ProtoMessage() {} func (*EnableRpkiResponse) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{41} } type DisableRpkiRequest struct { Address string `protobuf:"bytes,1,opt,name=address" json:"address,omitempty"` } func (m *DisableRpkiRequest) Reset() { *m = DisableRpkiRequest{} } func (m *DisableRpkiRequest) String() string { return proto.CompactTextString(m) } func (*DisableRpkiRequest) ProtoMessage() {} func (*DisableRpkiRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{42} } type DisableRpkiResponse struct { } func (m *DisableRpkiResponse) Reset() { *m = DisableRpkiResponse{} } func (m *DisableRpkiResponse) String() string { return proto.CompactTextString(m) } func (*DisableRpkiResponse) ProtoMessage() {} func (*DisableRpkiResponse) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{43} } type ResetRpkiRequest struct { Address string `protobuf:"bytes,1,opt,name=address" json:"address,omitempty"` } func (m *ResetRpkiRequest) Reset() { *m = ResetRpkiRequest{} } func (m *ResetRpkiRequest) String() string { return proto.CompactTextString(m) } func (*ResetRpkiRequest) ProtoMessage() {} func (*ResetRpkiRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{44} } type ResetRpkiResponse struct { } func (m *ResetRpkiResponse) Reset() { *m = ResetRpkiResponse{} } func (m *ResetRpkiResponse) String() string { return proto.CompactTextString(m) } func (*ResetRpkiResponse) ProtoMessage() {} func (*ResetRpkiResponse) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{45} } type SoftResetRpkiRequest struct { Address string `protobuf:"bytes,1,opt,name=address" json:"address,omitempty"` } func (m *SoftResetRpkiRequest) Reset() { *m = SoftResetRpkiRequest{} } func (m *SoftResetRpkiRequest) String() string { return proto.CompactTextString(m) } func (*SoftResetRpkiRequest) ProtoMessage() {} func (*SoftResetRpkiRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{46} } type SoftResetRpkiResponse struct { } func (m *SoftResetRpkiResponse) Reset() { *m = SoftResetRpkiResponse{} } func (m *SoftResetRpkiResponse) String() string { return proto.CompactTextString(m) } func (*SoftResetRpkiResponse) ProtoMessage() {} func (*SoftResetRpkiResponse) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{47} } type EnableZebraRequest struct { Url string `protobuf:"bytes,1,opt,name=url" json:"url,omitempty"` RouteTypes []string `protobuf:"bytes,2,rep,name=route_types,json=routeTypes" json:"route_types,omitempty"` } func (m *EnableZebraRequest) Reset() { *m = EnableZebraRequest{} } func (m *EnableZebraRequest) String() string { return proto.CompactTextString(m) } func (*EnableZebraRequest) ProtoMessage() {} func (*EnableZebraRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{48} } type EnableZebraResponse struct { } func (m *EnableZebraResponse) Reset() { *m = EnableZebraResponse{} } func (m *EnableZebraResponse) String() string { return proto.CompactTextString(m) } func (*EnableZebraResponse) ProtoMessage() {} func (*EnableZebraResponse) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{49} } type GetVrfRequest struct { } func (m *GetVrfRequest) Reset() { *m = GetVrfRequest{} } func (m *GetVrfRequest) String() string { return proto.CompactTextString(m) } func (*GetVrfRequest) ProtoMessage() {} func (*GetVrfRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{50} } type GetVrfResponse struct { Vrfs []*Vrf `protobuf:"bytes,1,rep,name=vrfs" json:"vrfs,omitempty"` } func (m *GetVrfResponse) Reset() { *m = GetVrfResponse{} } func (m *GetVrfResponse) String() string { return proto.CompactTextString(m) } func (*GetVrfResponse) ProtoMessage() {} func (*GetVrfResponse) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{51} } func (m *GetVrfResponse) GetVrfs() []*Vrf { if m != nil { return m.Vrfs } return nil } type AddVrfRequest struct { Vrf *Vrf `protobuf:"bytes,1,opt,name=vrf" json:"vrf,omitempty"` } func (m *AddVrfRequest) Reset() { *m = AddVrfRequest{} } func (m *AddVrfRequest) String() string { return proto.CompactTextString(m) } func (*AddVrfRequest) ProtoMessage() {} func (*AddVrfRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{52} } func (m *AddVrfRequest) GetVrf() *Vrf { if m != nil { return m.Vrf } return nil } type AddVrfResponse struct { } func (m *AddVrfResponse) Reset() { *m = AddVrfResponse{} } func (m *AddVrfResponse) String() string { return proto.CompactTextString(m) } func (*AddVrfResponse) ProtoMessage() {} func (*AddVrfResponse) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{53} } type DeleteVrfRequest struct { Vrf *Vrf `protobuf:"bytes,1,opt,name=vrf" json:"vrf,omitempty"` } func (m *DeleteVrfRequest) Reset() { *m = DeleteVrfRequest{} } func (m *DeleteVrfRequest) String() string { return proto.CompactTextString(m) } func (*DeleteVrfRequest) ProtoMessage() {} func (*DeleteVrfRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{54} } func (m *DeleteVrfRequest) GetVrf() *Vrf { if m != nil { return m.Vrf } return nil } type DeleteVrfResponse struct { } func (m *DeleteVrfResponse) Reset() { *m = DeleteVrfResponse{} } func (m *DeleteVrfResponse) String() string { return proto.CompactTextString(m) } func (*DeleteVrfResponse) ProtoMessage() {} func (*DeleteVrfResponse) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{55} } type GetDefinedSetRequest struct { Type DefinedType `protobuf:"varint,1,opt,name=type,enum=gobgpapi.DefinedType" json:"type,omitempty"` } func (m *GetDefinedSetRequest) Reset() { *m = GetDefinedSetRequest{} } func (m *GetDefinedSetRequest) String() string { return proto.CompactTextString(m) } func (*GetDefinedSetRequest) ProtoMessage() {} func (*GetDefinedSetRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{56} } type GetDefinedSetResponse struct { Sets []*DefinedSet `protobuf:"bytes,1,rep,name=sets" json:"sets,omitempty"` } func (m *GetDefinedSetResponse) Reset() { *m = GetDefinedSetResponse{} } func (m *GetDefinedSetResponse) String() string { return proto.CompactTextString(m) } func (*GetDefinedSetResponse) ProtoMessage() {} func (*GetDefinedSetResponse) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{57} } func (m *GetDefinedSetResponse) GetSets() []*DefinedSet { if m != nil { return m.Sets } return nil } type AddDefinedSetRequest struct { Set *DefinedSet `protobuf:"bytes,1,opt,name=set" json:"set,omitempty"` } func (m *AddDefinedSetRequest) Reset() { *m = AddDefinedSetRequest{} } func (m *AddDefinedSetRequest) String() string { return proto.CompactTextString(m) } func (*AddDefinedSetRequest) ProtoMessage() {} func (*AddDefinedSetRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{58} } func (m *AddDefinedSetRequest) GetSet() *DefinedSet { if m != nil { return m.Set } return nil } type AddDefinedSetResponse struct { } func (m *AddDefinedSetResponse) Reset() { *m = AddDefinedSetResponse{} } func (m *AddDefinedSetResponse) String() string { return proto.CompactTextString(m) } func (*AddDefinedSetResponse) ProtoMessage() {} func (*AddDefinedSetResponse) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{59} } type DeleteDefinedSetRequest struct { Set *DefinedSet `protobuf:"bytes,1,opt,name=set" json:"set,omitempty"` All bool `protobuf:"varint,2,opt,name=all" json:"all,omitempty"` } func (m *DeleteDefinedSetRequest) Reset() { *m = DeleteDefinedSetRequest{} } func (m *DeleteDefinedSetRequest) String() string { return proto.CompactTextString(m) } func (*DeleteDefinedSetRequest) ProtoMessage() {} func (*DeleteDefinedSetRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{60} } func (m *DeleteDefinedSetRequest) GetSet() *DefinedSet { if m != nil { return m.Set } return nil } type DeleteDefinedSetResponse struct { } func (m *DeleteDefinedSetResponse) Reset() { *m = DeleteDefinedSetResponse{} } func (m *DeleteDefinedSetResponse) String() string { return proto.CompactTextString(m) } func (*DeleteDefinedSetResponse) ProtoMessage() {} func (*DeleteDefinedSetResponse) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{61} } type ReplaceDefinedSetRequest struct { Set *DefinedSet `protobuf:"bytes,1,opt,name=set" json:"set,omitempty"` } func (m *ReplaceDefinedSetRequest) Reset() { *m = ReplaceDefinedSetRequest{} } func (m *ReplaceDefinedSetRequest) String() string { return proto.CompactTextString(m) } func (*ReplaceDefinedSetRequest) ProtoMessage() {} func (*ReplaceDefinedSetRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{62} } func (m *ReplaceDefinedSetRequest) GetSet() *DefinedSet { if m != nil { return m.Set } return nil } type ReplaceDefinedSetResponse struct { } func (m *ReplaceDefinedSetResponse) Reset() { *m = ReplaceDefinedSetResponse{} } func (m *ReplaceDefinedSetResponse) String() string { return proto.CompactTextString(m) } func (*ReplaceDefinedSetResponse) ProtoMessage() {} func (*ReplaceDefinedSetResponse) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{63} } type GetStatementRequest struct { } func (m *GetStatementRequest) Reset() { *m = GetStatementRequest{} } func (m *GetStatementRequest) String() string { return proto.CompactTextString(m) } func (*GetStatementRequest) ProtoMessage() {} func (*GetStatementRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{64} } type GetStatementResponse struct { Statements []*Statement `protobuf:"bytes,1,rep,name=statements" json:"statements,omitempty"` } func (m *GetStatementResponse) Reset() { *m = GetStatementResponse{} } func (m *GetStatementResponse) String() string { return proto.CompactTextString(m) } func (*GetStatementResponse) ProtoMessage() {} func (*GetStatementResponse) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{65} } func (m *GetStatementResponse) GetStatements() []*Statement { if m != nil { return m.Statements } return nil } type AddStatementRequest struct { Statement *Statement `protobuf:"bytes,1,opt,name=statement" json:"statement,omitempty"` } func (m *AddStatementRequest) Reset() { *m = AddStatementRequest{} } func (m *AddStatementRequest) String() string { return proto.CompactTextString(m) } func (*AddStatementRequest) ProtoMessage() {} func (*AddStatementRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{66} } func (m *AddStatementRequest) GetStatement() *Statement { if m != nil { return m.Statement } return nil } type AddStatementResponse struct { } func (m *AddStatementResponse) Reset() { *m = AddStatementResponse{} } func (m *AddStatementResponse) String() string { return proto.CompactTextString(m) } func (*AddStatementResponse) ProtoMessage() {} func (*AddStatementResponse) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{67} } type DeleteStatementRequest struct { Statement *Statement `protobuf:"bytes,1,opt,name=statement" json:"statement,omitempty"` All bool `protobuf:"varint,2,opt,name=all" json:"all,omitempty"` } func (m *DeleteStatementRequest) Reset() { *m = DeleteStatementRequest{} } func (m *DeleteStatementRequest) String() string { return proto.CompactTextString(m) } func (*DeleteStatementRequest) ProtoMessage() {} func (*DeleteStatementRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{68} } func (m *DeleteStatementRequest) GetStatement() *Statement { if m != nil { return m.Statement } return nil } type DeleteStatementResponse struct { } func (m *DeleteStatementResponse) Reset() { *m = DeleteStatementResponse{} } func (m *DeleteStatementResponse) String() string { return proto.CompactTextString(m) } func (*DeleteStatementResponse) ProtoMessage() {} func (*DeleteStatementResponse) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{69} } type ReplaceStatementRequest struct { Statement *Statement `protobuf:"bytes,1,opt,name=statement" json:"statement,omitempty"` } func (m *ReplaceStatementRequest) Reset() { *m = ReplaceStatementRequest{} } func (m *ReplaceStatementRequest) String() string { return proto.CompactTextString(m) } func (*ReplaceStatementRequest) ProtoMessage() {} func (*ReplaceStatementRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{70} } func (m *ReplaceStatementRequest) GetStatement() *Statement { if m != nil { return m.Statement } return nil } type ReplaceStatementResponse struct { } func (m *ReplaceStatementResponse) Reset() { *m = ReplaceStatementResponse{} } func (m *ReplaceStatementResponse) String() string { return proto.CompactTextString(m) } func (*ReplaceStatementResponse) ProtoMessage() {} func (*ReplaceStatementResponse) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{71} } type GetPolicyRequest struct { } func (m *GetPolicyRequest) Reset() { *m = GetPolicyRequest{} } func (m *GetPolicyRequest) String() string { return proto.CompactTextString(m) } func (*GetPolicyRequest) ProtoMessage() {} func (*GetPolicyRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{72} } type GetPolicyResponse struct { Policies []*Policy `protobuf:"bytes,1,rep,name=policies" json:"policies,omitempty"` } func (m *GetPolicyResponse) Reset() { *m = GetPolicyResponse{} } func (m *GetPolicyResponse) String() string { return proto.CompactTextString(m) } func (*GetPolicyResponse) ProtoMessage() {} func (*GetPolicyResponse) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{73} } func (m *GetPolicyResponse) GetPolicies() []*Policy { if m != nil { return m.Policies } return nil } type AddPolicyRequest struct { Policy *Policy `protobuf:"bytes,1,opt,name=policy" json:"policy,omitempty"` // if this flag is set, gobgpd won't define new statements // but refer existing statements using statement's names in this arguments. ReferExistingStatements bool `protobuf:"varint,2,opt,name=refer_existing_statements,json=referExistingStatements" json:"refer_existing_statements,omitempty"` } func (m *AddPolicyRequest) Reset() { *m = AddPolicyRequest{} } func (m *AddPolicyRequest) String() string { return proto.CompactTextString(m) } func (*AddPolicyRequest) ProtoMessage() {} func (*AddPolicyRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{74} } func (m *AddPolicyRequest) GetPolicy() *Policy { if m != nil { return m.Policy } return nil } type AddPolicyResponse struct { } func (m *AddPolicyResponse) Reset() { *m = AddPolicyResponse{} } func (m *AddPolicyResponse) String() string { return proto.CompactTextString(m) } func (*AddPolicyResponse) ProtoMessage() {} func (*AddPolicyResponse) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{75} } type DeletePolicyRequest struct { Policy *Policy `protobuf:"bytes,1,opt,name=policy" json:"policy,omitempty"` // if this flag is set, gobgpd won't delete any statements // even if some statements get not used by any policy by this operation. PreserveStatements bool `protobuf:"varint,2,opt,name=preserve_statements,json=preserveStatements" json:"preserve_statements,omitempty"` All bool `protobuf:"varint,3,opt,name=all" json:"all,omitempty"` } func (m *DeletePolicyRequest) Reset() { *m = DeletePolicyRequest{} } func (m *DeletePolicyRequest) String() string { return proto.CompactTextString(m) } func (*DeletePolicyRequest) ProtoMessage() {} func (*DeletePolicyRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{76} } func (m *DeletePolicyRequest) GetPolicy() *Policy { if m != nil { return m.Policy } return nil } type DeletePolicyResponse struct { } func (m *DeletePolicyResponse) Reset() { *m = DeletePolicyResponse{} } func (m *DeletePolicyResponse) String() string { return proto.CompactTextString(m) } func (*DeletePolicyResponse) ProtoMessage() {} func (*DeletePolicyResponse) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{77} } type ReplacePolicyRequest struct { Policy *Policy `protobuf:"bytes,1,opt,name=policy" json:"policy,omitempty"` // if this flag is set, gobgpd won't define new statements // but refer existing statements using statement's names in this arguments. ReferExistingStatements bool `protobuf:"varint,2,opt,name=refer_existing_statements,json=referExistingStatements" json:"refer_existing_statements,omitempty"` // if this flag is set, gobgpd won't delete any statements // even if some statements get not used by any policy by this operation. PreserveStatements bool `protobuf:"varint,3,opt,name=preserve_statements,json=preserveStatements" json:"preserve_statements,omitempty"` } func (m *ReplacePolicyRequest) Reset() { *m = ReplacePolicyRequest{} } func (m *ReplacePolicyRequest) String() string { return proto.CompactTextString(m) } func (*ReplacePolicyRequest) ProtoMessage() {} func (*ReplacePolicyRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{78} } func (m *ReplacePolicyRequest) GetPolicy() *Policy { if m != nil { return m.Policy } return nil } type ReplacePolicyResponse struct { } func (m *ReplacePolicyResponse) Reset() { *m = ReplacePolicyResponse{} } func (m *ReplacePolicyResponse) String() string { return proto.CompactTextString(m) } func (*ReplacePolicyResponse) ProtoMessage() {} func (*ReplacePolicyResponse) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{79} } type GetPolicyAssignmentRequest struct { Assignment *PolicyAssignment `protobuf:"bytes,1,opt,name=assignment" json:"assignment,omitempty"` } func (m *GetPolicyAssignmentRequest) Reset() { *m = GetPolicyAssignmentRequest{} } func (m *GetPolicyAssignmentRequest) String() string { return proto.CompactTextString(m) } func (*GetPolicyAssignmentRequest) ProtoMessage() {} func (*GetPolicyAssignmentRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{80} } func (m *GetPolicyAssignmentRequest) GetAssignment() *PolicyAssignment { if m != nil { return m.Assignment } return nil } type GetPolicyAssignmentResponse struct { Assignment *PolicyAssignment `protobuf:"bytes,1,opt,name=assignment" json:"assignment,omitempty"` } func (m *GetPolicyAssignmentResponse) Reset() { *m = GetPolicyAssignmentResponse{} } func (m *GetPolicyAssignmentResponse) String() string { return proto.CompactTextString(m) } func (*GetPolicyAssignmentResponse) ProtoMessage() {} func (*GetPolicyAssignmentResponse) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{81} } func (m *GetPolicyAssignmentResponse) GetAssignment() *PolicyAssignment { if m != nil { return m.Assignment } return nil } type AddPolicyAssignmentRequest struct { Assignment *PolicyAssignment `protobuf:"bytes,1,opt,name=assignment" json:"assignment,omitempty"` } func (m *AddPolicyAssignmentRequest) Reset() { *m = AddPolicyAssignmentRequest{} } func (m *AddPolicyAssignmentRequest) String() string { return proto.CompactTextString(m) } func (*AddPolicyAssignmentRequest) ProtoMessage() {} func (*AddPolicyAssignmentRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{82} } func (m *AddPolicyAssignmentRequest) GetAssignment() *PolicyAssignment { if m != nil { return m.Assignment } return nil } type AddPolicyAssignmentResponse struct { } func (m *AddPolicyAssignmentResponse) Reset() { *m = AddPolicyAssignmentResponse{} } func (m *AddPolicyAssignmentResponse) String() string { return proto.CompactTextString(m) } func (*AddPolicyAssignmentResponse) ProtoMessage() {} func (*AddPolicyAssignmentResponse) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{83} } type DeletePolicyAssignmentRequest struct { Assignment *PolicyAssignment `protobuf:"bytes,1,opt,name=assignment" json:"assignment,omitempty"` All bool `protobuf:"varint,2,opt,name=all" json:"all,omitempty"` } func (m *DeletePolicyAssignmentRequest) Reset() { *m = DeletePolicyAssignmentRequest{} } func (m *DeletePolicyAssignmentRequest) String() string { return proto.CompactTextString(m) } func (*DeletePolicyAssignmentRequest) ProtoMessage() {} func (*DeletePolicyAssignmentRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{84} } func (m *DeletePolicyAssignmentRequest) GetAssignment() *PolicyAssignment { if m != nil { return m.Assignment } return nil } type DeletePolicyAssignmentResponse struct { } func (m *DeletePolicyAssignmentResponse) Reset() { *m = DeletePolicyAssignmentResponse{} } func (m *DeletePolicyAssignmentResponse) String() string { return proto.CompactTextString(m) } func (*DeletePolicyAssignmentResponse) ProtoMessage() {} func (*DeletePolicyAssignmentResponse) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{85} } type ReplacePolicyAssignmentRequest struct { Assignment *PolicyAssignment `protobuf:"bytes,1,opt,name=assignment" json:"assignment,omitempty"` } func (m *ReplacePolicyAssignmentRequest) Reset() { *m = ReplacePolicyAssignmentRequest{} } func (m *ReplacePolicyAssignmentRequest) String() string { return proto.CompactTextString(m) } func (*ReplacePolicyAssignmentRequest) ProtoMessage() {} func (*ReplacePolicyAssignmentRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{86} } func (m *ReplacePolicyAssignmentRequest) GetAssignment() *PolicyAssignment { if m != nil { return m.Assignment } return nil } type ReplacePolicyAssignmentResponse struct { } func (m *ReplacePolicyAssignmentResponse) Reset() { *m = ReplacePolicyAssignmentResponse{} } func (m *ReplacePolicyAssignmentResponse) String() string { return proto.CompactTextString(m) } func (*ReplacePolicyAssignmentResponse) ProtoMessage() {} func (*ReplacePolicyAssignmentResponse) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{87} } type GetServerRequest struct { } func (m *GetServerRequest) Reset() { *m = GetServerRequest{} } func (m *GetServerRequest) String() string { return proto.CompactTextString(m) } func (*GetServerRequest) ProtoMessage() {} func (*GetServerRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{88} } type GetServerResponse struct { Global *Global `protobuf:"bytes,1,opt,name=global" json:"global,omitempty"` } func (m *GetServerResponse) Reset() { *m = GetServerResponse{} } func (m *GetServerResponse) String() string { return proto.CompactTextString(m) } func (*GetServerResponse) ProtoMessage() {} func (*GetServerResponse) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{89} } func (m *GetServerResponse) GetGlobal() *Global { if m != nil { return m.Global } return nil } type StartServerRequest struct { Global *Global `protobuf:"bytes,1,opt,name=global" json:"global,omitempty"` } func (m *StartServerRequest) Reset() { *m = StartServerRequest{} } func (m *StartServerRequest) String() string { return proto.CompactTextString(m) } func (*StartServerRequest) ProtoMessage() {} func (*StartServerRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{90} } func (m *StartServerRequest) GetGlobal() *Global { if m != nil { return m.Global } return nil } type StartServerResponse struct { } func (m *StartServerResponse) Reset() { *m = StartServerResponse{} } func (m *StartServerResponse) String() string { return proto.CompactTextString(m) } func (*StartServerResponse) ProtoMessage() {} func (*StartServerResponse) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{91} } type StopServerRequest struct { } func (m *StopServerRequest) Reset() { *m = StopServerRequest{} } func (m *StopServerRequest) String() string { return proto.CompactTextString(m) } func (*StopServerRequest) ProtoMessage() {} func (*StopServerRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{92} } type StopServerResponse struct { } func (m *StopServerResponse) Reset() { *m = StopServerResponse{} } func (m *StopServerResponse) String() string { return proto.CompactTextString(m) } func (*StopServerResponse) ProtoMessage() {} func (*StopServerResponse) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{93} } type Path struct { Nlri []byte `protobuf:"bytes,1,opt,name=nlri,proto3" json:"nlri,omitempty"` Pattrs [][]byte `protobuf:"bytes,2,rep,name=pattrs,proto3" json:"pattrs,omitempty"` Age int64 `protobuf:"varint,3,opt,name=age" json:"age,omitempty"` Best bool `protobuf:"varint,4,opt,name=best" json:"best,omitempty"` IsWithdraw bool `protobuf:"varint,5,opt,name=is_withdraw,json=isWithdraw" json:"is_withdraw,omitempty"` Validation int32 `protobuf:"varint,6,opt,name=validation" json:"validation,omitempty"` NoImplicitWithdraw bool `protobuf:"varint,7,opt,name=no_implicit_withdraw,json=noImplicitWithdraw" json:"no_implicit_withdraw,omitempty"` Family uint32 `protobuf:"varint,8,opt,name=family" json:"family,omitempty"` SourceAsn uint32 `protobuf:"varint,9,opt,name=source_asn,json=sourceAsn" json:"source_asn,omitempty"` SourceId string `protobuf:"bytes,10,opt,name=source_id,json=sourceId" json:"source_id,omitempty"` Filtered bool `protobuf:"varint,11,opt,name=filtered" json:"filtered,omitempty"` Stale bool `protobuf:"varint,12,opt,name=stale" json:"stale,omitempty"` IsFromExternal bool `protobuf:"varint,13,opt,name=is_from_external,json=isFromExternal" json:"is_from_external,omitempty"` NeighborIp string `protobuf:"bytes,14,opt,name=neighbor_ip,json=neighborIp" json:"neighbor_ip,omitempty"` } func (m *Path) Reset() { *m = Path{} } func (m *Path) String() string { return proto.CompactTextString(m) } func (*Path) ProtoMessage() {} func (*Path) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{94} } type Destination struct { Prefix string `protobuf:"bytes,1,opt,name=prefix" json:"prefix,omitempty"` Paths []*Path `protobuf:"bytes,2,rep,name=paths" json:"paths,omitempty"` LongerPrefixes bool `protobuf:"varint,3,opt,name=longer_prefixes,json=longerPrefixes" json:"longer_prefixes,omitempty"` ShorterPrefixes bool `protobuf:"varint,4,opt,name=shorter_prefixes,json=shorterPrefixes" json:"shorter_prefixes,omitempty"` } func (m *Destination) Reset() { *m = Destination{} } func (m *Destination) String() string { return proto.CompactTextString(m) } func (*Destination) ProtoMessage() {} func (*Destination) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{95} } func (m *Destination) GetPaths() []*Path { if m != nil { return m.Paths } return nil } type Table struct { Type Resource `protobuf:"varint,1,opt,name=type,enum=gobgpapi.Resource" json:"type,omitempty"` Name string `protobuf:"bytes,2,opt,name=name" json:"name,omitempty"` Family uint32 `protobuf:"varint,3,opt,name=family" json:"family,omitempty"` Destinations []*Destination `protobuf:"bytes,4,rep,name=destinations" json:"destinations,omitempty"` PostPolicy bool `protobuf:"varint,5,opt,name=post_policy,json=postPolicy" json:"post_policy,omitempty"` } func (m *Table) Reset() { *m = Table{} } func (m *Table) String() string { return proto.CompactTextString(m) } func (*Table) ProtoMessage() {} func (*Table) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{96} } func (m *Table) GetDestinations() []*Destination { if m != nil { return m.Destinations } return nil } type GetRibRequest struct { Table *Table `protobuf:"bytes,1,opt,name=table" json:"table,omitempty"` } func (m *GetRibRequest) Reset() { *m = GetRibRequest{} } func (m *GetRibRequest) String() string { return proto.CompactTextString(m) } func (*GetRibRequest) ProtoMessage() {} func (*GetRibRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{97} } func (m *GetRibRequest) GetTable() *Table { if m != nil { return m.Table } return nil } type GetRibResponse struct { Table *Table `protobuf:"bytes,1,opt,name=table" json:"table,omitempty"` } func (m *GetRibResponse) Reset() { *m = GetRibResponse{} } func (m *GetRibResponse) String() string { return proto.CompactTextString(m) } func (*GetRibResponse) ProtoMessage() {} func (*GetRibResponse) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{98} } func (m *GetRibResponse) GetTable() *Table { if m != nil { return m.Table } return nil } type ValidateRibRequest struct { Type Resource `protobuf:"varint,1,opt,name=type,enum=gobgpapi.Resource" json:"type,omitempty"` Family uint32 `protobuf:"varint,2,opt,name=family" json:"family,omitempty"` Prefix string `protobuf:"bytes,3,opt,name=prefix" json:"prefix,omitempty"` } func (m *ValidateRibRequest) Reset() { *m = ValidateRibRequest{} } func (m *ValidateRibRequest) String() string { return proto.CompactTextString(m) } func (*ValidateRibRequest) ProtoMessage() {} func (*ValidateRibRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{99} } type ValidateRibResponse struct { } func (m *ValidateRibResponse) Reset() { *m = ValidateRibResponse{} } func (m *ValidateRibResponse) String() string { return proto.CompactTextString(m) } func (*ValidateRibResponse) ProtoMessage() {} func (*ValidateRibResponse) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{100} } type Peer struct { Families []uint32 `protobuf:"varint,1,rep,packed,name=families" json:"families,omitempty"` ApplyPolicy *ApplyPolicy `protobuf:"bytes,2,opt,name=apply_policy,json=applyPolicy" json:"apply_policy,omitempty"` Conf *PeerConf `protobuf:"bytes,3,opt,name=conf" json:"conf,omitempty"` EbgpMultihop *EbgpMultihop `protobuf:"bytes,4,opt,name=ebgp_multihop,json=ebgpMultihop" json:"ebgp_multihop,omitempty"` RouteReflector *RouteReflector `protobuf:"bytes,5,opt,name=route_reflector,json=routeReflector" json:"route_reflector,omitempty"` Info *PeerState `protobuf:"bytes,6,opt,name=info" json:"info,omitempty"` Timers *Timers `protobuf:"bytes,7,opt,name=timers" json:"timers,omitempty"` Transport *Transport `protobuf:"bytes,8,opt,name=transport" json:"transport,omitempty"` RouteServer *RouteServer `protobuf:"bytes,9,opt,name=route_server,json=routeServer" json:"route_server,omitempty"` } func (m *Peer) Reset() { *m = Peer{} } func (m *Peer) String() string { return proto.CompactTextString(m) } func (*Peer) ProtoMessage() {} func (*Peer) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{101} } func (m *Peer) GetApplyPolicy() *ApplyPolicy { if m != nil { return m.ApplyPolicy } return nil } func (m *Peer) GetConf() *PeerConf { if m != nil { return m.Conf } return nil } func (m *Peer) GetEbgpMultihop() *EbgpMultihop { if m != nil { return m.EbgpMultihop } return nil } func (m *Peer) GetRouteReflector() *RouteReflector { if m != nil { return m.RouteReflector } return nil } func (m *Peer) GetInfo() *PeerState { if m != nil { return m.Info } return nil } func (m *Peer) GetTimers() *Timers { if m != nil { return m.Timers } return nil } func (m *Peer) GetTransport() *Transport { if m != nil { return m.Transport } return nil } func (m *Peer) GetRouteServer() *RouteServer { if m != nil { return m.RouteServer } return nil } type ApplyPolicy struct { InPolicy *PolicyAssignment `protobuf:"bytes,1,opt,name=in_policy,json=inPolicy" json:"in_policy,omitempty"` ExportPolicy *PolicyAssignment `protobuf:"bytes,2,opt,name=export_policy,json=exportPolicy" json:"export_policy,omitempty"` ImportPolicy *PolicyAssignment `protobuf:"bytes,3,opt,name=import_policy,json=importPolicy" json:"import_policy,omitempty"` } func (m *ApplyPolicy) Reset() { *m = ApplyPolicy{} } func (m *ApplyPolicy) String() string { return proto.CompactTextString(m) } func (*ApplyPolicy) ProtoMessage() {} func (*ApplyPolicy) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{102} } func (m *ApplyPolicy) GetInPolicy() *PolicyAssignment { if m != nil { return m.InPolicy } return nil } func (m *ApplyPolicy) GetExportPolicy() *PolicyAssignment { if m != nil { return m.ExportPolicy } return nil } func (m *ApplyPolicy) GetImportPolicy() *PolicyAssignment { if m != nil { return m.ImportPolicy } return nil } type PrefixLimit struct { Family uint32 `protobuf:"varint,1,opt,name=family" json:"family,omitempty"` MaxPrefixes uint32 `protobuf:"varint,2,opt,name=max_prefixes,json=maxPrefixes" json:"max_prefixes,omitempty"` ShutdownThresholdPct uint32 `protobuf:"varint,3,opt,name=shutdown_threshold_pct,json=shutdownThresholdPct" json:"shutdown_threshold_pct,omitempty"` } func (m *PrefixLimit) Reset() { *m = PrefixLimit{} } func (m *PrefixLimit) String() string { return proto.CompactTextString(m) } func (*PrefixLimit) ProtoMessage() {} func (*PrefixLimit) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{103} } type PeerConf struct { AuthPassword string `protobuf:"bytes,1,opt,name=auth_password,json=authPassword" json:"auth_password,omitempty"` Description string `protobuf:"bytes,2,opt,name=description" json:"description,omitempty"` LocalAs uint32 `protobuf:"varint,3,opt,name=local_as,json=localAs" json:"local_as,omitempty"` NeighborAddress string `protobuf:"bytes,4,opt,name=neighbor_address,json=neighborAddress" json:"neighbor_address,omitempty"` PeerAs uint32 `protobuf:"varint,5,opt,name=peer_as,json=peerAs" json:"peer_as,omitempty"` PeerGroup string `protobuf:"bytes,6,opt,name=peer_group,json=peerGroup" json:"peer_group,omitempty"` PeerType uint32 `protobuf:"varint,7,opt,name=peer_type,json=peerType" json:"peer_type,omitempty"` RemovePrivateAs uint32 `protobuf:"varint,8,opt,name=remove_private_as,json=removePrivateAs" json:"remove_private_as,omitempty"` RouteFlapDamping bool `protobuf:"varint,9,opt,name=route_flap_damping,json=routeFlapDamping" json:"route_flap_damping,omitempty"` SendCommunity uint32 `protobuf:"varint,10,opt,name=send_community,json=sendCommunity" json:"send_community,omitempty"` RemoteCap [][]byte `protobuf:"bytes,11,rep,name=remote_cap,json=remoteCap,proto3" json:"remote_cap,omitempty"` LocalCap [][]byte `protobuf:"bytes,12,rep,name=local_cap,json=localCap,proto3" json:"local_cap,omitempty"` Id string `protobuf:"bytes,13,opt,name=id" json:"id,omitempty"` PrefixLimits []*PrefixLimit `protobuf:"bytes,14,rep,name=prefix_limits,json=prefixLimits" json:"prefix_limits,omitempty"` LocalAddress string `protobuf:"bytes,15,opt,name=local_address,json=localAddress" json:"local_address,omitempty"` NeighborInterface string `protobuf:"bytes,16,opt,name=neighbor_interface,json=neighborInterface" json:"neighbor_interface,omitempty"` } func (m *PeerConf) Reset() { *m = PeerConf{} } func (m *PeerConf) String() string { return proto.CompactTextString(m) } func (*PeerConf) ProtoMessage() {} func (*PeerConf) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{104} } func (m *PeerConf) GetPrefixLimits() []*PrefixLimit { if m != nil { return m.PrefixLimits } return nil } type EbgpMultihop struct { Enabled bool `protobuf:"varint,1,opt,name=enabled" json:"enabled,omitempty"` MultihopTtl uint32 `protobuf:"varint,2,opt,name=multihop_ttl,json=multihopTtl" json:"multihop_ttl,omitempty"` } func (m *EbgpMultihop) Reset() { *m = EbgpMultihop{} } func (m *EbgpMultihop) String() string { return proto.CompactTextString(m) } func (*EbgpMultihop) ProtoMessage() {} func (*EbgpMultihop) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{105} } type RouteReflector struct { RouteReflectorClient bool `protobuf:"varint,1,opt,name=route_reflector_client,json=routeReflectorClient" json:"route_reflector_client,omitempty"` RouteReflectorClusterId string `protobuf:"bytes,2,opt,name=route_reflector_cluster_id,json=routeReflectorClusterId" json:"route_reflector_cluster_id,omitempty"` } func (m *RouteReflector) Reset() { *m = RouteReflector{} } func (m *RouteReflector) String() string { return proto.CompactTextString(m) } func (*RouteReflector) ProtoMessage() {} func (*RouteReflector) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{106} } type PeerState struct { AuthPassword string `protobuf:"bytes,1,opt,name=auth_password,json=authPassword" json:"auth_password,omitempty"` Description string `protobuf:"bytes,2,opt,name=description" json:"description,omitempty"` LocalAs uint32 `protobuf:"varint,3,opt,name=local_as,json=localAs" json:"local_as,omitempty"` Messages *Messages `protobuf:"bytes,4,opt,name=messages" json:"messages,omitempty"` NeighborAddress string `protobuf:"bytes,5,opt,name=neighbor_address,json=neighborAddress" json:"neighbor_address,omitempty"` PeerAs uint32 `protobuf:"varint,6,opt,name=peer_as,json=peerAs" json:"peer_as,omitempty"` PeerGroup string `protobuf:"bytes,7,opt,name=peer_group,json=peerGroup" json:"peer_group,omitempty"` PeerType uint32 `protobuf:"varint,8,opt,name=peer_type,json=peerType" json:"peer_type,omitempty"` Queues *Queues `protobuf:"bytes,9,opt,name=queues" json:"queues,omitempty"` RemovePrivateAs uint32 `protobuf:"varint,10,opt,name=remove_private_as,json=removePrivateAs" json:"remove_private_as,omitempty"` RouteFlapDamping bool `protobuf:"varint,11,opt,name=route_flap_damping,json=routeFlapDamping" json:"route_flap_damping,omitempty"` SendCommunity uint32 `protobuf:"varint,12,opt,name=send_community,json=sendCommunity" json:"send_community,omitempty"` SessionState uint32 `protobuf:"varint,13,opt,name=session_state,json=sessionState" json:"session_state,omitempty"` SupportedCapabilities []string `protobuf:"bytes,14,rep,name=supported_capabilities,json=supportedCapabilities" json:"supported_capabilities,omitempty"` BgpState string `protobuf:"bytes,15,opt,name=bgp_state,json=bgpState" json:"bgp_state,omitempty"` AdminState string `protobuf:"bytes,16,opt,name=admin_state,json=adminState" json:"admin_state,omitempty"` Received uint32 `protobuf:"varint,17,opt,name=received" json:"received,omitempty"` Accepted uint32 `protobuf:"varint,18,opt,name=accepted" json:"accepted,omitempty"` Advertised uint32 `protobuf:"varint,19,opt,name=advertised" json:"advertised,omitempty"` OutQ uint32 `protobuf:"varint,20,opt,name=out_q,json=outQ" json:"out_q,omitempty"` Flops uint32 `protobuf:"varint,21,opt,name=flops" json:"flops,omitempty"` } func (m *PeerState) Reset() { *m = PeerState{} } func (m *PeerState) String() string { return proto.CompactTextString(m) } func (*PeerState) ProtoMessage() {} func (*PeerState) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{107} } func (m *PeerState) GetMessages() *Messages { if m != nil { return m.Messages } return nil } func (m *PeerState) GetQueues() *Queues { if m != nil { return m.Queues } return nil } type Messages struct { Received *Message `protobuf:"bytes,1,opt,name=received" json:"received,omitempty"` Sent *Message `protobuf:"bytes,2,opt,name=sent" json:"sent,omitempty"` } func (m *Messages) Reset() { *m = Messages{} } func (m *Messages) String() string { return proto.CompactTextString(m) } func (*Messages) ProtoMessage() {} func (*Messages) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{108} } func (m *Messages) GetReceived() *Message { if m != nil { return m.Received } return nil } func (m *Messages) GetSent() *Message { if m != nil { return m.Sent } return nil } type Message struct { NOTIFICATION uint64 `protobuf:"varint,1,opt,name=NOTIFICATION,json=nOTIFICATION" json:"NOTIFICATION,omitempty"` UPDATE uint64 `protobuf:"varint,2,opt,name=UPDATE,json=uPDATE" json:"UPDATE,omitempty"` OPEN uint64 `protobuf:"varint,3,opt,name=OPEN,json=oPEN" json:"OPEN,omitempty"` KEEPALIVE uint64 `protobuf:"varint,4,opt,name=KEEPALIVE,json=kEEPALIVE" json:"KEEPALIVE,omitempty"` REFRESH uint64 `protobuf:"varint,5,opt,name=REFRESH,json=rEFRESH" json:"REFRESH,omitempty"` DISCARDED uint64 `protobuf:"varint,6,opt,name=DISCARDED,json=dISCARDED" json:"DISCARDED,omitempty"` TOTAL uint64 `protobuf:"varint,7,opt,name=TOTAL,json=tOTAL" json:"TOTAL,omitempty"` } func (m *Message) Reset() { *m = Message{} } func (m *Message) String() string { return proto.CompactTextString(m) } func (*Message) ProtoMessage() {} func (*Message) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{109} } type Queues struct { Input uint32 `protobuf:"varint,1,opt,name=input" json:"input,omitempty"` Output uint32 `protobuf:"varint,2,opt,name=output" json:"output,omitempty"` } func (m *Queues) Reset() { *m = Queues{} } func (m *Queues) String() string { return proto.CompactTextString(m) } func (*Queues) ProtoMessage() {} func (*Queues) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{110} } type Timers struct { Config *TimersConfig `protobuf:"bytes,1,opt,name=config" json:"config,omitempty"` State *TimersState `protobuf:"bytes,2,opt,name=state" json:"state,omitempty"` } func (m *Timers) Reset() { *m = Timers{} } func (m *Timers) String() string { return proto.CompactTextString(m) } func (*Timers) ProtoMessage() {} func (*Timers) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{111} } func (m *Timers) GetConfig() *TimersConfig { if m != nil { return m.Config } return nil } func (m *Timers) GetState() *TimersState { if m != nil { return m.State } return nil } type TimersConfig struct { ConnectRetry uint64 `protobuf:"varint,1,opt,name=connect_retry,json=connectRetry" json:"connect_retry,omitempty"` HoldTime uint64 `protobuf:"varint,2,opt,name=hold_time,json=holdTime" json:"hold_time,omitempty"` KeepaliveInterval uint64 `protobuf:"varint,3,opt,name=keepalive_interval,json=keepaliveInterval" json:"keepalive_interval,omitempty"` MinimumAdvertisementInterval uint64 `protobuf:"varint,4,opt,name=minimum_advertisement_interval,json=minimumAdvertisementInterval" json:"minimum_advertisement_interval,omitempty"` } func (m *TimersConfig) Reset() { *m = TimersConfig{} } func (m *TimersConfig) String() string { return proto.CompactTextString(m) } func (*TimersConfig) ProtoMessage() {} func (*TimersConfig) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{112} } type TimersState struct { ConnectRetry uint64 `protobuf:"varint,1,opt,name=connect_retry,json=connectRetry" json:"connect_retry,omitempty"` HoldTime uint64 `protobuf:"varint,2,opt,name=hold_time,json=holdTime" json:"hold_time,omitempty"` KeepaliveInterval uint64 `protobuf:"varint,3,opt,name=keepalive_interval,json=keepaliveInterval" json:"keepalive_interval,omitempty"` MinimumAdvertisementInterval uint64 `protobuf:"varint,4,opt,name=minimum_advertisement_interval,json=minimumAdvertisementInterval" json:"minimum_advertisement_interval,omitempty"` NegotiatedHoldTime uint64 `protobuf:"varint,5,opt,name=negotiated_hold_time,json=negotiatedHoldTime" json:"negotiated_hold_time,omitempty"` Uptime uint64 `protobuf:"varint,6,opt,name=uptime" json:"uptime,omitempty"` Downtime uint64 `protobuf:"varint,7,opt,name=downtime" json:"downtime,omitempty"` } func (m *TimersState) Reset() { *m = TimersState{} } func (m *TimersState) String() string { return proto.CompactTextString(m) } func (*TimersState) ProtoMessage() {} func (*TimersState) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{113} } type Transport struct { LocalAddress string `protobuf:"bytes,1,opt,name=local_address,json=localAddress" json:"local_address,omitempty"` LocalPort uint32 `protobuf:"varint,2,opt,name=local_port,json=localPort" json:"local_port,omitempty"` MtuDiscovery bool `protobuf:"varint,3,opt,name=mtu_discovery,json=mtuDiscovery" json:"mtu_discovery,omitempty"` PassiveMode bool `protobuf:"varint,4,opt,name=passive_mode,json=passiveMode" json:"passive_mode,omitempty"` RemoteAddress string `protobuf:"bytes,5,opt,name=remote_address,json=remoteAddress" json:"remote_address,omitempty"` RemotePort uint32 `protobuf:"varint,6,opt,name=remote_port,json=remotePort" json:"remote_port,omitempty"` TcpMss uint32 `protobuf:"varint,7,opt,name=tcp_mss,json=tcpMss" json:"tcp_mss,omitempty"` } func (m *Transport) Reset() { *m = Transport{} } func (m *Transport) String() string { return proto.CompactTextString(m) } func (*Transport) ProtoMessage() {} func (*Transport) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{114} } type RouteServer struct { RouteServerClient bool `protobuf:"varint,1,opt,name=route_server_client,json=routeServerClient" json:"route_server_client,omitempty"` } func (m *RouteServer) Reset() { *m = RouteServer{} } func (m *RouteServer) String() string { return proto.CompactTextString(m) } func (*RouteServer) ProtoMessage() {} func (*RouteServer) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{115} } type Prefix struct { IpPrefix string `protobuf:"bytes,1,opt,name=ip_prefix,json=ipPrefix" json:"ip_prefix,omitempty"` MaskLengthMin uint32 `protobuf:"varint,2,opt,name=mask_length_min,json=maskLengthMin" json:"mask_length_min,omitempty"` MaskLengthMax uint32 `protobuf:"varint,3,opt,name=mask_length_max,json=maskLengthMax" json:"mask_length_max,omitempty"` } func (m *Prefix) Reset() { *m = Prefix{} } func (m *Prefix) String() string { return proto.CompactTextString(m) } func (*Prefix) ProtoMessage() {} func (*Prefix) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{116} } type DefinedSet struct { Type DefinedType `protobuf:"varint,1,opt,name=type,enum=gobgpapi.DefinedType" json:"type,omitempty"` Name string `protobuf:"bytes,2,opt,name=name" json:"name,omitempty"` List []string `protobuf:"bytes,3,rep,name=list" json:"list,omitempty"` Prefixes []*Prefix `protobuf:"bytes,4,rep,name=prefixes" json:"prefixes,omitempty"` } func (m *DefinedSet) Reset() { *m = DefinedSet{} } func (m *DefinedSet) String() string { return proto.CompactTextString(m) } func (*DefinedSet) ProtoMessage() {} func (*DefinedSet) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{117} } func (m *DefinedSet) GetPrefixes() []*Prefix { if m != nil { return m.Prefixes } return nil } type MatchSet struct { Type MatchType `protobuf:"varint,1,opt,name=type,enum=gobgpapi.MatchType" json:"type,omitempty"` Name string `protobuf:"bytes,2,opt,name=name" json:"name,omitempty"` } func (m *MatchSet) Reset() { *m = MatchSet{} } func (m *MatchSet) String() string { return proto.CompactTextString(m) } func (*MatchSet) ProtoMessage() {} func (*MatchSet) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{118} } type AsPathLength struct { Type AsPathLengthType `protobuf:"varint,1,opt,name=type,enum=gobgpapi.AsPathLengthType" json:"type,omitempty"` Length uint32 `protobuf:"varint,2,opt,name=length" json:"length,omitempty"` } func (m *AsPathLength) Reset() { *m = AsPathLength{} } func (m *AsPathLength) String() string { return proto.CompactTextString(m) } func (*AsPathLength) ProtoMessage() {} func (*AsPathLength) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{119} } type Conditions struct { PrefixSet *MatchSet `protobuf:"bytes,1,opt,name=prefix_set,json=prefixSet" json:"prefix_set,omitempty"` NeighborSet *MatchSet `protobuf:"bytes,2,opt,name=neighbor_set,json=neighborSet" json:"neighbor_set,omitempty"` AsPathLength *AsPathLength `protobuf:"bytes,3,opt,name=as_path_length,json=asPathLength" json:"as_path_length,omitempty"` AsPathSet *MatchSet `protobuf:"bytes,4,opt,name=as_path_set,json=asPathSet" json:"as_path_set,omitempty"` CommunitySet *MatchSet `protobuf:"bytes,5,opt,name=community_set,json=communitySet" json:"community_set,omitempty"` ExtCommunitySet *MatchSet `protobuf:"bytes,6,opt,name=ext_community_set,json=extCommunitySet" json:"ext_community_set,omitempty"` RpkiResult int32 `protobuf:"varint,7,opt,name=rpki_result,json=rpkiResult" json:"rpki_result,omitempty"` RouteType Conditions_RouteType `protobuf:"varint,8,opt,name=route_type,json=routeType,enum=gobgpapi.Conditions_RouteType" json:"route_type,omitempty"` } func (m *Conditions) Reset() { *m = Conditions{} } func (m *Conditions) String() string { return proto.CompactTextString(m) } func (*Conditions) ProtoMessage() {} func (*Conditions) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{120} } func (m *Conditions) GetPrefixSet() *MatchSet { if m != nil { return m.PrefixSet } return nil } func (m *Conditions) GetNeighborSet() *MatchSet { if m != nil { return m.NeighborSet } return nil } func (m *Conditions) GetAsPathLength() *AsPathLength { if m != nil { return m.AsPathLength } return nil } func (m *Conditions) GetAsPathSet() *MatchSet { if m != nil { return m.AsPathSet } return nil } func (m *Conditions) GetCommunitySet() *MatchSet { if m != nil { return m.CommunitySet } return nil } func (m *Conditions) GetExtCommunitySet() *MatchSet { if m != nil { return m.ExtCommunitySet } return nil } type CommunityAction struct { Type CommunityActionType `protobuf:"varint,1,opt,name=type,enum=gobgpapi.CommunityActionType" json:"type,omitempty"` Communities []string `protobuf:"bytes,2,rep,name=communities" json:"communities,omitempty"` } func (m *CommunityAction) Reset() { *m = CommunityAction{} } func (m *CommunityAction) String() string { return proto.CompactTextString(m) } func (*CommunityAction) ProtoMessage() {} func (*CommunityAction) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{121} } type MedAction struct { Type MedActionType `protobuf:"varint,1,opt,name=type,enum=gobgpapi.MedActionType" json:"type,omitempty"` Value int64 `protobuf:"varint,2,opt,name=value" json:"value,omitempty"` } func (m *MedAction) Reset() { *m = MedAction{} } func (m *MedAction) String() string { return proto.CompactTextString(m) } func (*MedAction) ProtoMessage() {} func (*MedAction) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{122} } type AsPrependAction struct { Asn uint32 `protobuf:"varint,1,opt,name=asn" json:"asn,omitempty"` Repeat uint32 `protobuf:"varint,2,opt,name=repeat" json:"repeat,omitempty"` UseLeftMost bool `protobuf:"varint,3,opt,name=use_left_most,json=useLeftMost" json:"use_left_most,omitempty"` } func (m *AsPrependAction) Reset() { *m = AsPrependAction{} } func (m *AsPrependAction) String() string { return proto.CompactTextString(m) } func (*AsPrependAction) ProtoMessage() {} func (*AsPrependAction) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{123} } type NexthopAction struct { Address string `protobuf:"bytes,1,opt,name=address" json:"address,omitempty"` Self bool `protobuf:"varint,2,opt,name=self" json:"self,omitempty"` } func (m *NexthopAction) Reset() { *m = NexthopAction{} } func (m *NexthopAction) String() string { return proto.CompactTextString(m) } func (*NexthopAction) ProtoMessage() {} func (*NexthopAction) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{124} } type LocalPrefAction struct { Value uint32 `protobuf:"varint,1,opt,name=value" json:"value,omitempty"` } func (m *LocalPrefAction) Reset() { *m = LocalPrefAction{} } func (m *LocalPrefAction) String() string { return proto.CompactTextString(m) } func (*LocalPrefAction) ProtoMessage() {} func (*LocalPrefAction) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{125} } type Actions struct { RouteAction RouteAction `protobuf:"varint,1,opt,name=route_action,json=routeAction,enum=gobgpapi.RouteAction" json:"route_action,omitempty"` Community *CommunityAction `protobuf:"bytes,2,opt,name=community" json:"community,omitempty"` Med *MedAction `protobuf:"bytes,3,opt,name=med" json:"med,omitempty"` AsPrepend *AsPrependAction `protobuf:"bytes,4,opt,name=as_prepend,json=asPrepend" json:"as_prepend,omitempty"` ExtCommunity *CommunityAction `protobuf:"bytes,5,opt,name=ext_community,json=extCommunity" json:"ext_community,omitempty"` Nexthop *NexthopAction `protobuf:"bytes,6,opt,name=nexthop" json:"nexthop,omitempty"` LocalPref *LocalPrefAction `protobuf:"bytes,7,opt,name=local_pref,json=localPref" json:"local_pref,omitempty"` } func (m *Actions) Reset() { *m = Actions{} } func (m *Actions) String() string { return proto.CompactTextString(m) } func (*Actions) ProtoMessage() {} func (*Actions) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{126} } func (m *Actions) GetCommunity() *CommunityAction { if m != nil { return m.Community } return nil } func (m *Actions) GetMed() *MedAction { if m != nil { return m.Med } return nil } func (m *Actions) GetAsPrepend() *AsPrependAction { if m != nil { return m.AsPrepend } return nil } func (m *Actions) GetExtCommunity() *CommunityAction { if m != nil { return m.ExtCommunity } return nil } func (m *Actions) GetNexthop() *NexthopAction { if m != nil { return m.Nexthop } return nil } func (m *Actions) GetLocalPref() *LocalPrefAction { if m != nil { return m.LocalPref } return nil } type Statement struct { Name string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` Conditions *Conditions `protobuf:"bytes,2,opt,name=conditions" json:"conditions,omitempty"` Actions *Actions `protobuf:"bytes,3,opt,name=actions" json:"actions,omitempty"` } func (m *Statement) Reset() { *m = Statement{} } func (m *Statement) String() string { return proto.CompactTextString(m) } func (*Statement) ProtoMessage() {} func (*Statement) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{127} } func (m *Statement) GetConditions() *Conditions { if m != nil { return m.Conditions } return nil } func (m *Statement) GetActions() *Actions { if m != nil { return m.Actions } return nil } type Policy struct { Name string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` Statements []*Statement `protobuf:"bytes,2,rep,name=statements" json:"statements,omitempty"` } func (m *Policy) Reset() { *m = Policy{} } func (m *Policy) String() string { return proto.CompactTextString(m) } func (*Policy) ProtoMessage() {} func (*Policy) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{128} } func (m *Policy) GetStatements() []*Statement { if m != nil { return m.Statements } return nil } type PolicyAssignment struct { Type PolicyType `protobuf:"varint,1,opt,name=type,enum=gobgpapi.PolicyType" json:"type,omitempty"` Resource Resource `protobuf:"varint,2,opt,name=resource,enum=gobgpapi.Resource" json:"resource,omitempty"` Name string `protobuf:"bytes,3,opt,name=name" json:"name,omitempty"` Policies []*Policy `protobuf:"bytes,4,rep,name=policies" json:"policies,omitempty"` Default RouteAction `protobuf:"varint,5,opt,name=default,enum=gobgpapi.RouteAction" json:"default,omitempty"` } func (m *PolicyAssignment) Reset() { *m = PolicyAssignment{} } func (m *PolicyAssignment) String() string { return proto.CompactTextString(m) } func (*PolicyAssignment) ProtoMessage() {} func (*PolicyAssignment) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{129} } func (m *PolicyAssignment) GetPolicies() []*Policy { if m != nil { return m.Policies } return nil } type Roa struct { As uint32 `protobuf:"varint,1,opt,name=as" json:"as,omitempty"` Prefixlen uint32 `protobuf:"varint,2,opt,name=prefixlen" json:"prefixlen,omitempty"` Maxlen uint32 `protobuf:"varint,3,opt,name=maxlen" json:"maxlen,omitempty"` Prefix string `protobuf:"bytes,4,opt,name=prefix" json:"prefix,omitempty"` Conf *RPKIConf `protobuf:"bytes,5,opt,name=conf" json:"conf,omitempty"` } func (m *Roa) Reset() { *m = Roa{} } func (m *Roa) String() string { return proto.CompactTextString(m) } func (*Roa) ProtoMessage() {} func (*Roa) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{130} } func (m *Roa) GetConf() *RPKIConf { if m != nil { return m.Conf } return nil } type GetRoaRequest struct { Family uint32 `protobuf:"varint,1,opt,name=family" json:"family,omitempty"` } func (m *GetRoaRequest) Reset() { *m = GetRoaRequest{} } func (m *GetRoaRequest) String() string { return proto.CompactTextString(m) } func (*GetRoaRequest) ProtoMessage() {} func (*GetRoaRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{131} } type GetRoaResponse struct { Roas []*Roa `protobuf:"bytes,1,rep,name=roas" json:"roas,omitempty"` } func (m *GetRoaResponse) Reset() { *m = GetRoaResponse{} } func (m *GetRoaResponse) String() string { return proto.CompactTextString(m) } func (*GetRoaResponse) ProtoMessage() {} func (*GetRoaResponse) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{132} } func (m *GetRoaResponse) GetRoas() []*Roa { if m != nil { return m.Roas } return nil } type Vrf struct { Name string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` Rd []byte `protobuf:"bytes,2,opt,name=rd,proto3" json:"rd,omitempty"` ImportRt [][]byte `protobuf:"bytes,3,rep,name=import_rt,json=importRt,proto3" json:"import_rt,omitempty"` ExportRt [][]byte `protobuf:"bytes,4,rep,name=export_rt,json=exportRt,proto3" json:"export_rt,omitempty"` } func (m *Vrf) Reset() { *m = Vrf{} } func (m *Vrf) String() string { return proto.CompactTextString(m) } func (*Vrf) ProtoMessage() {} func (*Vrf) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{133} } type Global struct { As uint32 `protobuf:"varint,1,opt,name=as" json:"as,omitempty"` RouterId string `protobuf:"bytes,2,opt,name=router_id,json=routerId" json:"router_id,omitempty"` ListenPort int32 `protobuf:"varint,3,opt,name=listen_port,json=listenPort" json:"listen_port,omitempty"` ListenAddresses []string `protobuf:"bytes,4,rep,name=listen_addresses,json=listenAddresses" json:"listen_addresses,omitempty"` Families []uint32 `protobuf:"varint,5,rep,packed,name=families" json:"families,omitempty"` MplsLabelMin uint32 `protobuf:"varint,6,opt,name=mpls_label_min,json=mplsLabelMin" json:"mpls_label_min,omitempty"` MplsLabelMax uint32 `protobuf:"varint,7,opt,name=mpls_label_max,json=mplsLabelMax" json:"mpls_label_max,omitempty"` UseMultiplePaths bool `protobuf:"varint,8,opt,name=use_multiple_paths,json=useMultiplePaths" json:"use_multiple_paths,omitempty"` } func (m *Global) Reset() { *m = Global{} } func (m *Global) String() string { return proto.CompactTextString(m) } func (*Global) ProtoMessage() {} func (*Global) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{134} } func init() { proto.RegisterType((*GetNeighborRequest)(nil), "gobgpapi.GetNeighborRequest") proto.RegisterType((*GetNeighborResponse)(nil), "gobgpapi.GetNeighborResponse") proto.RegisterType((*Arguments)(nil), "gobgpapi.Arguments") proto.RegisterType((*AddPathRequest)(nil), "gobgpapi.AddPathRequest") proto.RegisterType((*AddPathResponse)(nil), "gobgpapi.AddPathResponse") proto.RegisterType((*DeletePathRequest)(nil), "gobgpapi.DeletePathRequest") proto.RegisterType((*DeletePathResponse)(nil), "gobgpapi.DeletePathResponse") proto.RegisterType((*AddNeighborRequest)(nil), "gobgpapi.AddNeighborRequest") proto.RegisterType((*AddNeighborResponse)(nil), "gobgpapi.AddNeighborResponse") proto.RegisterType((*DeleteNeighborRequest)(nil), "gobgpapi.DeleteNeighborRequest") proto.RegisterType((*DeleteNeighborResponse)(nil), "gobgpapi.DeleteNeighborResponse") proto.RegisterType((*ResetNeighborRequest)(nil), "gobgpapi.ResetNeighborRequest") proto.RegisterType((*ResetNeighborResponse)(nil), "gobgpapi.ResetNeighborResponse") proto.RegisterType((*SoftResetNeighborRequest)(nil), "gobgpapi.SoftResetNeighborRequest") proto.RegisterType((*SoftResetNeighborResponse)(nil), "gobgpapi.SoftResetNeighborResponse") proto.RegisterType((*ShutdownNeighborRequest)(nil), "gobgpapi.ShutdownNeighborRequest") proto.RegisterType((*ShutdownNeighborResponse)(nil), "gobgpapi.ShutdownNeighborResponse") proto.RegisterType((*EnableNeighborRequest)(nil), "gobgpapi.EnableNeighborRequest") proto.RegisterType((*EnableNeighborResponse)(nil), "gobgpapi.EnableNeighborResponse") proto.RegisterType((*DisableNeighborRequest)(nil), "gobgpapi.DisableNeighborRequest") proto.RegisterType((*DisableNeighborResponse)(nil), "gobgpapi.DisableNeighborResponse") proto.RegisterType((*EnableMrtRequest)(nil), "gobgpapi.EnableMrtRequest") proto.RegisterType((*EnableMrtResponse)(nil), "gobgpapi.EnableMrtResponse") proto.RegisterType((*DisableMrtRequest)(nil), "gobgpapi.DisableMrtRequest") proto.RegisterType((*DisableMrtResponse)(nil), "gobgpapi.DisableMrtResponse") proto.RegisterType((*InjectMrtRequest)(nil), "gobgpapi.InjectMrtRequest") proto.RegisterType((*InjectMrtResponse)(nil), "gobgpapi.InjectMrtResponse") proto.RegisterType((*AddBmpRequest)(nil), "gobgpapi.AddBmpRequest") proto.RegisterType((*AddBmpResponse)(nil), "gobgpapi.AddBmpResponse") proto.RegisterType((*DeleteBmpRequest)(nil), "gobgpapi.DeleteBmpRequest") proto.RegisterType((*DeleteBmpResponse)(nil), "gobgpapi.DeleteBmpResponse") proto.RegisterType((*RPKIConf)(nil), "gobgpapi.RPKIConf") proto.RegisterType((*RPKIState)(nil), "gobgpapi.RPKIState") proto.RegisterType((*Rpki)(nil), "gobgpapi.Rpki") proto.RegisterType((*GetRpkiRequest)(nil), "gobgpapi.GetRpkiRequest") proto.RegisterType((*GetRpkiResponse)(nil), "gobgpapi.GetRpkiResponse") proto.RegisterType((*AddRpkiRequest)(nil), "gobgpapi.AddRpkiRequest") proto.RegisterType((*AddRpkiResponse)(nil), "gobgpapi.AddRpkiResponse") proto.RegisterType((*DeleteRpkiRequest)(nil), "gobgpapi.DeleteRpkiRequest") proto.RegisterType((*DeleteRpkiResponse)(nil), "gobgpapi.DeleteRpkiResponse") proto.RegisterType((*EnableRpkiRequest)(nil), "gobgpapi.EnableRpkiRequest") proto.RegisterType((*EnableRpkiResponse)(nil), "gobgpapi.EnableRpkiResponse") proto.RegisterType((*DisableRpkiRequest)(nil), "gobgpapi.DisableRpkiRequest") proto.RegisterType((*DisableRpkiResponse)(nil), "gobgpapi.DisableRpkiResponse") proto.RegisterType((*ResetRpkiRequest)(nil), "gobgpapi.ResetRpkiRequest") proto.RegisterType((*ResetRpkiResponse)(nil), "gobgpapi.ResetRpkiResponse") proto.RegisterType((*SoftResetRpkiRequest)(nil), "gobgpapi.SoftResetRpkiRequest") proto.RegisterType((*SoftResetRpkiResponse)(nil), "gobgpapi.SoftResetRpkiResponse") proto.RegisterType((*EnableZebraRequest)(nil), "gobgpapi.EnableZebraRequest") proto.RegisterType((*EnableZebraResponse)(nil), "gobgpapi.EnableZebraResponse") proto.RegisterType((*GetVrfRequest)(nil), "gobgpapi.GetVrfRequest") proto.RegisterType((*GetVrfResponse)(nil), "gobgpapi.GetVrfResponse") proto.RegisterType((*AddVrfRequest)(nil), "gobgpapi.AddVrfRequest") proto.RegisterType((*AddVrfResponse)(nil), "gobgpapi.AddVrfResponse") proto.RegisterType((*DeleteVrfRequest)(nil), "gobgpapi.DeleteVrfRequest") proto.RegisterType((*DeleteVrfResponse)(nil), "gobgpapi.DeleteVrfResponse") proto.RegisterType((*GetDefinedSetRequest)(nil), "gobgpapi.GetDefinedSetRequest") proto.RegisterType((*GetDefinedSetResponse)(nil), "gobgpapi.GetDefinedSetResponse") proto.RegisterType((*AddDefinedSetRequest)(nil), "gobgpapi.AddDefinedSetRequest") proto.RegisterType((*AddDefinedSetResponse)(nil), "gobgpapi.AddDefinedSetResponse") proto.RegisterType((*DeleteDefinedSetRequest)(nil), "gobgpapi.DeleteDefinedSetRequest") proto.RegisterType((*DeleteDefinedSetResponse)(nil), "gobgpapi.DeleteDefinedSetResponse") proto.RegisterType((*ReplaceDefinedSetRequest)(nil), "gobgpapi.ReplaceDefinedSetRequest") proto.RegisterType((*ReplaceDefinedSetResponse)(nil), "gobgpapi.ReplaceDefinedSetResponse") proto.RegisterType((*GetStatementRequest)(nil), "gobgpapi.GetStatementRequest") proto.RegisterType((*GetStatementResponse)(nil), "gobgpapi.GetStatementResponse") proto.RegisterType((*AddStatementRequest)(nil), "gobgpapi.AddStatementRequest") proto.RegisterType((*AddStatementResponse)(nil), "gobgpapi.AddStatementResponse") proto.RegisterType((*DeleteStatementRequest)(nil), "gobgpapi.DeleteStatementRequest") proto.RegisterType((*DeleteStatementResponse)(nil), "gobgpapi.DeleteStatementResponse") proto.RegisterType((*ReplaceStatementRequest)(nil), "gobgpapi.ReplaceStatementRequest") proto.RegisterType((*ReplaceStatementResponse)(nil), "gobgpapi.ReplaceStatementResponse") proto.RegisterType((*GetPolicyRequest)(nil), "gobgpapi.GetPolicyRequest") proto.RegisterType((*GetPolicyResponse)(nil), "gobgpapi.GetPolicyResponse") proto.RegisterType((*AddPolicyRequest)(nil), "gobgpapi.AddPolicyRequest") proto.RegisterType((*AddPolicyResponse)(nil), "gobgpapi.AddPolicyResponse") proto.RegisterType((*DeletePolicyRequest)(nil), "gobgpapi.DeletePolicyRequest") proto.RegisterType((*DeletePolicyResponse)(nil), "gobgpapi.DeletePolicyResponse") proto.RegisterType((*ReplacePolicyRequest)(nil), "gobgpapi.ReplacePolicyRequest") proto.RegisterType((*ReplacePolicyResponse)(nil), "gobgpapi.ReplacePolicyResponse") proto.RegisterType((*GetPolicyAssignmentRequest)(nil), "gobgpapi.GetPolicyAssignmentRequest") proto.RegisterType((*GetPolicyAssignmentResponse)(nil), "gobgpapi.GetPolicyAssignmentResponse") proto.RegisterType((*AddPolicyAssignmentRequest)(nil), "gobgpapi.AddPolicyAssignmentRequest") proto.RegisterType((*AddPolicyAssignmentResponse)(nil), "gobgpapi.AddPolicyAssignmentResponse") proto.RegisterType((*DeletePolicyAssignmentRequest)(nil), "gobgpapi.DeletePolicyAssignmentRequest") proto.RegisterType((*DeletePolicyAssignmentResponse)(nil), "gobgpapi.DeletePolicyAssignmentResponse") proto.RegisterType((*ReplacePolicyAssignmentRequest)(nil), "gobgpapi.ReplacePolicyAssignmentRequest") proto.RegisterType((*ReplacePolicyAssignmentResponse)(nil), "gobgpapi.ReplacePolicyAssignmentResponse") proto.RegisterType((*GetServerRequest)(nil), "gobgpapi.GetServerRequest") proto.RegisterType((*GetServerResponse)(nil), "gobgpapi.GetServerResponse") proto.RegisterType((*StartServerRequest)(nil), "gobgpapi.StartServerRequest") proto.RegisterType((*StartServerResponse)(nil), "gobgpapi.StartServerResponse") proto.RegisterType((*StopServerRequest)(nil), "gobgpapi.StopServerRequest") proto.RegisterType((*StopServerResponse)(nil), "gobgpapi.StopServerResponse") proto.RegisterType((*Path)(nil), "gobgpapi.Path") proto.RegisterType((*Destination)(nil), "gobgpapi.Destination") proto.RegisterType((*Table)(nil), "gobgpapi.Table") proto.RegisterType((*GetRibRequest)(nil), "gobgpapi.GetRibRequest") proto.RegisterType((*GetRibResponse)(nil), "gobgpapi.GetRibResponse") proto.RegisterType((*ValidateRibRequest)(nil), "gobgpapi.ValidateRibRequest") proto.RegisterType((*ValidateRibResponse)(nil), "gobgpapi.ValidateRibResponse") proto.RegisterType((*Peer)(nil), "gobgpapi.Peer") proto.RegisterType((*ApplyPolicy)(nil), "gobgpapi.ApplyPolicy") proto.RegisterType((*PrefixLimit)(nil), "gobgpapi.PrefixLimit") proto.RegisterType((*PeerConf)(nil), "gobgpapi.PeerConf") proto.RegisterType((*EbgpMultihop)(nil), "gobgpapi.EbgpMultihop") proto.RegisterType((*RouteReflector)(nil), "gobgpapi.RouteReflector") proto.RegisterType((*PeerState)(nil), "gobgpapi.PeerState") proto.RegisterType((*Messages)(nil), "gobgpapi.Messages") proto.RegisterType((*Message)(nil), "gobgpapi.Message") proto.RegisterType((*Queues)(nil), "gobgpapi.Queues") proto.RegisterType((*Timers)(nil), "gobgpapi.Timers") proto.RegisterType((*TimersConfig)(nil), "gobgpapi.TimersConfig") proto.RegisterType((*TimersState)(nil), "gobgpapi.TimersState") proto.RegisterType((*Transport)(nil), "gobgpapi.Transport") proto.RegisterType((*RouteServer)(nil), "gobgpapi.RouteServer") proto.RegisterType((*Prefix)(nil), "gobgpapi.Prefix") proto.RegisterType((*DefinedSet)(nil), "gobgpapi.DefinedSet") proto.RegisterType((*MatchSet)(nil), "gobgpapi.MatchSet") proto.RegisterType((*AsPathLength)(nil), "gobgpapi.AsPathLength") proto.RegisterType((*Conditions)(nil), "gobgpapi.Conditions") proto.RegisterType((*CommunityAction)(nil), "gobgpapi.CommunityAction") proto.RegisterType((*MedAction)(nil), "gobgpapi.MedAction") proto.RegisterType((*AsPrependAction)(nil), "gobgpapi.AsPrependAction") proto.RegisterType((*NexthopAction)(nil), "gobgpapi.NexthopAction") proto.RegisterType((*LocalPrefAction)(nil), "gobgpapi.LocalPrefAction") proto.RegisterType((*Actions)(nil), "gobgpapi.Actions") proto.RegisterType((*Statement)(nil), "gobgpapi.Statement") proto.RegisterType((*Policy)(nil), "gobgpapi.Policy") proto.RegisterType((*PolicyAssignment)(nil), "gobgpapi.PolicyAssignment") proto.RegisterType((*Roa)(nil), "gobgpapi.Roa") proto.RegisterType((*GetRoaRequest)(nil), "gobgpapi.GetRoaRequest") proto.RegisterType((*GetRoaResponse)(nil), "gobgpapi.GetRoaResponse") proto.RegisterType((*Vrf)(nil), "gobgpapi.Vrf") proto.RegisterType((*Global)(nil), "gobgpapi.Global") proto.RegisterEnum("gobgpapi.Resource", Resource_name, Resource_value) proto.RegisterEnum("gobgpapi.DefinedType", DefinedType_name, DefinedType_value) proto.RegisterEnum("gobgpapi.MatchType", MatchType_name, MatchType_value) proto.RegisterEnum("gobgpapi.AsPathLengthType", AsPathLengthType_name, AsPathLengthType_value) proto.RegisterEnum("gobgpapi.RouteAction", RouteAction_name, RouteAction_value) proto.RegisterEnum("gobgpapi.CommunityActionType", CommunityActionType_name, CommunityActionType_value) proto.RegisterEnum("gobgpapi.MedActionType", MedActionType_name, MedActionType_value) proto.RegisterEnum("gobgpapi.PolicyType", PolicyType_name, PolicyType_value) proto.RegisterEnum("gobgpapi.SoftResetNeighborRequest_SoftResetDirection", SoftResetNeighborRequest_SoftResetDirection_name, SoftResetNeighborRequest_SoftResetDirection_value) proto.RegisterEnum("gobgpapi.AddBmpRequest_MonitoringPolicy", AddBmpRequest_MonitoringPolicy_name, AddBmpRequest_MonitoringPolicy_value) proto.RegisterEnum("gobgpapi.Conditions_RouteType", Conditions_RouteType_name, Conditions_RouteType_value) } // Reference imports to suppress errors if they are not otherwise used. var _ context.Context var _ grpc.ClientConn // This is a compile-time assertion to ensure that this generated file // is compatible with the grpc package it is being compiled against. const _ = grpc.SupportPackageIsVersion3 // Client API for GobgpApi service type GobgpApiClient interface { StartServer(ctx context.Context, in *StartServerRequest, opts ...grpc.CallOption) (*StartServerResponse, error) StopServer(ctx context.Context, in *StopServerRequest, opts ...grpc.CallOption) (*StopServerResponse, error) GetServer(ctx context.Context, in *GetServerRequest, opts ...grpc.CallOption) (*GetServerResponse, error) AddNeighbor(ctx context.Context, in *AddNeighborRequest, opts ...grpc.CallOption) (*AddNeighborResponse, error) DeleteNeighbor(ctx context.Context, in *DeleteNeighborRequest, opts ...grpc.CallOption) (*DeleteNeighborResponse, error) GetNeighbor(ctx context.Context, in *GetNeighborRequest, opts ...grpc.CallOption) (*GetNeighborResponse, error) ResetNeighbor(ctx context.Context, in *ResetNeighborRequest, opts ...grpc.CallOption) (*ResetNeighborResponse, error) SoftResetNeighbor(ctx context.Context, in *SoftResetNeighborRequest, opts ...grpc.CallOption) (*SoftResetNeighborResponse, error) ShutdownNeighbor(ctx context.Context, in *ShutdownNeighborRequest, opts ...grpc.CallOption) (*ShutdownNeighborResponse, error) EnableNeighbor(ctx context.Context, in *EnableNeighborRequest, opts ...grpc.CallOption) (*EnableNeighborResponse, error) DisableNeighbor(ctx context.Context, in *DisableNeighborRequest, opts ...grpc.CallOption) (*DisableNeighborResponse, error) GetRib(ctx context.Context, in *GetRibRequest, opts ...grpc.CallOption) (*GetRibResponse, error) ValidateRib(ctx context.Context, in *ValidateRibRequest, opts ...grpc.CallOption) (*ValidateRibResponse, error) AddPath(ctx context.Context, in *AddPathRequest, opts ...grpc.CallOption) (*AddPathResponse, error) DeletePath(ctx context.Context, in *DeletePathRequest, opts ...grpc.CallOption) (*DeletePathResponse, error) MonitorRib(ctx context.Context, in *Table, opts ...grpc.CallOption) (GobgpApi_MonitorRibClient, error) MonitorPeerState(ctx context.Context, in *Arguments, opts ...grpc.CallOption) (GobgpApi_MonitorPeerStateClient, error) EnableMrt(ctx context.Context, in *EnableMrtRequest, opts ...grpc.CallOption) (*EnableMrtResponse, error) DisableMrt(ctx context.Context, in *DisableMrtRequest, opts ...grpc.CallOption) (*DisableMrtResponse, error) InjectMrt(ctx context.Context, opts ...grpc.CallOption) (GobgpApi_InjectMrtClient, error) AddBmp(ctx context.Context, in *AddBmpRequest, opts ...grpc.CallOption) (*AddBmpResponse, error) DeleteBmp(ctx context.Context, in *DeleteBmpRequest, opts ...grpc.CallOption) (*DeleteBmpResponse, error) GetRpki(ctx context.Context, in *GetRpkiRequest, opts ...grpc.CallOption) (*GetRpkiResponse, error) AddRpki(ctx context.Context, in *AddRpkiRequest, opts ...grpc.CallOption) (*AddRpkiResponse, error) DeleteRpki(ctx context.Context, in *DeleteRpkiRequest, opts ...grpc.CallOption) (*DeleteRpkiResponse, error) EnableRpki(ctx context.Context, in *EnableRpkiRequest, opts ...grpc.CallOption) (*EnableRpkiResponse, error) DisableRpki(ctx context.Context, in *DisableRpkiRequest, opts ...grpc.CallOption) (*DisableRpkiResponse, error) ResetRpki(ctx context.Context, in *ResetRpkiRequest, opts ...grpc.CallOption) (*ResetRpkiResponse, error) SoftResetRpki(ctx context.Context, in *SoftResetRpkiRequest, opts ...grpc.CallOption) (*SoftResetRpkiResponse, error) GetRoa(ctx context.Context, in *GetRoaRequest, opts ...grpc.CallOption) (*GetRoaResponse, error) EnableZebra(ctx context.Context, in *EnableZebraRequest, opts ...grpc.CallOption) (*EnableZebraResponse, error) AddVrf(ctx context.Context, in *AddVrfRequest, opts ...grpc.CallOption) (*AddVrfResponse, error) DeleteVrf(ctx context.Context, in *DeleteVrfRequest, opts ...grpc.CallOption) (*DeleteVrfResponse, error) GetVrf(ctx context.Context, in *GetVrfRequest, opts ...grpc.CallOption) (*GetVrfResponse, error) GetDefinedSet(ctx context.Context, in *GetDefinedSetRequest, opts ...grpc.CallOption) (*GetDefinedSetResponse, error) AddDefinedSet(ctx context.Context, in *AddDefinedSetRequest, opts ...grpc.CallOption) (*AddDefinedSetResponse, error) DeleteDefinedSet(ctx context.Context, in *DeleteDefinedSetRequest, opts ...grpc.CallOption) (*DeleteDefinedSetResponse, error) ReplaceDefinedSet(ctx context.Context, in *ReplaceDefinedSetRequest, opts ...grpc.CallOption) (*ReplaceDefinedSetResponse, error) GetStatement(ctx context.Context, in *GetStatementRequest, opts ...grpc.CallOption) (*GetStatementResponse, error) AddStatement(ctx context.Context, in *AddStatementRequest, opts ...grpc.CallOption) (*AddStatementResponse, error) DeleteStatement(ctx context.Context, in *DeleteStatementRequest, opts ...grpc.CallOption) (*DeleteStatementResponse, error) ReplaceStatement(ctx context.Context, in *ReplaceStatementRequest, opts ...grpc.CallOption) (*ReplaceStatementResponse, error) GetPolicy(ctx context.Context, in *GetPolicyRequest, opts ...grpc.CallOption) (*GetPolicyResponse, error) AddPolicy(ctx context.Context, in *AddPolicyRequest, opts ...grpc.CallOption) (*AddPolicyResponse, error) DeletePolicy(ctx context.Context, in *DeletePolicyRequest, opts ...grpc.CallOption) (*DeletePolicyResponse, error) ReplacePolicy(ctx context.Context, in *ReplacePolicyRequest, opts ...grpc.CallOption) (*ReplacePolicyResponse, error) GetPolicyAssignment(ctx context.Context, in *GetPolicyAssignmentRequest, opts ...grpc.CallOption) (*GetPolicyAssignmentResponse, error) AddPolicyAssignment(ctx context.Context, in *AddPolicyAssignmentRequest, opts ...grpc.CallOption) (*AddPolicyAssignmentResponse, error) DeletePolicyAssignment(ctx context.Context, in *DeletePolicyAssignmentRequest, opts ...grpc.CallOption) (*DeletePolicyAssignmentResponse, error) ReplacePolicyAssignment(ctx context.Context, in *ReplacePolicyAssignmentRequest, opts ...grpc.CallOption) (*ReplacePolicyAssignmentResponse, error) } type gobgpApiClient struct { cc *grpc.ClientConn } func NewGobgpApiClient(cc *grpc.ClientConn) GobgpApiClient { return &gobgpApiClient{cc} } func (c *gobgpApiClient) StartServer(ctx context.Context, in *StartServerRequest, opts ...grpc.CallOption) (*StartServerResponse, error) { out := new(StartServerResponse) err := grpc.Invoke(ctx, "/gobgpapi.GobgpApi/StartServer", in, out, c.cc, opts...) if err != nil { return nil, err } return out, nil } func (c *gobgpApiClient) StopServer(ctx context.Context, in *StopServerRequest, opts ...grpc.CallOption) (*StopServerResponse, error) { out := new(StopServerResponse) err := grpc.Invoke(ctx, "/gobgpapi.GobgpApi/StopServer", in, out, c.cc, opts...) if err != nil { return nil, err } return out, nil } func (c *gobgpApiClient) GetServer(ctx context.Context, in *GetServerRequest, opts ...grpc.CallOption) (*GetServerResponse, error) { out := new(GetServerResponse) err := grpc.Invoke(ctx, "/gobgpapi.GobgpApi/GetServer", in, out, c.cc, opts...) if err != nil { return nil, err } return out, nil } func (c *gobgpApiClient) AddNeighbor(ctx context.Context, in *AddNeighborRequest, opts ...grpc.CallOption) (*AddNeighborResponse, error) { out := new(AddNeighborResponse) err := grpc.Invoke(ctx, "/gobgpapi.GobgpApi/AddNeighbor", in, out, c.cc, opts...) if err != nil { return nil, err } return out, nil } func (c *gobgpApiClient) DeleteNeighbor(ctx context.Context, in *DeleteNeighborRequest, opts ...grpc.CallOption) (*DeleteNeighborResponse, error) { out := new(DeleteNeighborResponse) err := grpc.Invoke(ctx, "/gobgpapi.GobgpApi/DeleteNeighbor", in, out, c.cc, opts...) if err != nil { return nil, err } return out, nil } func (c *gobgpApiClient) GetNeighbor(ctx context.Context, in *GetNeighborRequest, opts ...grpc.CallOption) (*GetNeighborResponse, error) { out := new(GetNeighborResponse) err := grpc.Invoke(ctx, "/gobgpapi.GobgpApi/GetNeighbor", in, out, c.cc, opts...) if err != nil { return nil, err } return out, nil } func (c *gobgpApiClient) ResetNeighbor(ctx context.Context, in *ResetNeighborRequest, opts ...grpc.CallOption) (*ResetNeighborResponse, error) { out := new(ResetNeighborResponse) err := grpc.Invoke(ctx, "/gobgpapi.GobgpApi/ResetNeighbor", in, out, c.cc, opts...) if err != nil { return nil, err } return out, nil } func (c *gobgpApiClient) SoftResetNeighbor(ctx context.Context, in *SoftResetNeighborRequest, opts ...grpc.CallOption) (*SoftResetNeighborResponse, error) { out := new(SoftResetNeighborResponse) err := grpc.Invoke(ctx, "/gobgpapi.GobgpApi/SoftResetNeighbor", in, out, c.cc, opts...) if err != nil { return nil, err } return out, nil } func (c *gobgpApiClient) ShutdownNeighbor(ctx context.Context, in *ShutdownNeighborRequest, opts ...grpc.CallOption) (*ShutdownNeighborResponse, error) { out := new(ShutdownNeighborResponse) err := grpc.Invoke(ctx, "/gobgpapi.GobgpApi/ShutdownNeighbor", in, out, c.cc, opts...) if err != nil { return nil, err } return out, nil } func (c *gobgpApiClient) EnableNeighbor(ctx context.Context, in *EnableNeighborRequest, opts ...grpc.CallOption) (*EnableNeighborResponse, error) { out := new(EnableNeighborResponse) err := grpc.Invoke(ctx, "/gobgpapi.GobgpApi/EnableNeighbor", in, out, c.cc, opts...) if err != nil { return nil, err } return out, nil } func (c *gobgpApiClient) DisableNeighbor(ctx context.Context, in *DisableNeighborRequest, opts ...grpc.CallOption) (*DisableNeighborResponse, error) { out := new(DisableNeighborResponse) err := grpc.Invoke(ctx, "/gobgpapi.GobgpApi/DisableNeighbor", in, out, c.cc, opts...) if err != nil { return nil, err } return out, nil } func (c *gobgpApiClient) GetRib(ctx context.Context, in *GetRibRequest, opts ...grpc.CallOption) (*GetRibResponse, error) { out := new(GetRibResponse) err := grpc.Invoke(ctx, "/gobgpapi.GobgpApi/GetRib", in, out, c.cc, opts...) if err != nil { return nil, err } return out, nil } func (c *gobgpApiClient) ValidateRib(ctx context.Context, in *ValidateRibRequest, opts ...grpc.CallOption) (*ValidateRibResponse, error) { out := new(ValidateRibResponse) err := grpc.Invoke(ctx, "/gobgpapi.GobgpApi/ValidateRib", in, out, c.cc, opts...) if err != nil { return nil, err } return out, nil } func (c *gobgpApiClient) AddPath(ctx context.Context, in *AddPathRequest, opts ...grpc.CallOption) (*AddPathResponse, error) { out := new(AddPathResponse) err := grpc.Invoke(ctx, "/gobgpapi.GobgpApi/AddPath", in, out, c.cc, opts...) if err != nil { return nil, err } return out, nil } func (c *gobgpApiClient) DeletePath(ctx context.Context, in *DeletePathRequest, opts ...grpc.CallOption) (*DeletePathResponse, error) { out := new(DeletePathResponse) err := grpc.Invoke(ctx, "/gobgpapi.GobgpApi/DeletePath", in, out, c.cc, opts...) if err != nil { return nil, err } return out, nil } func (c *gobgpApiClient) MonitorRib(ctx context.Context, in *Table, opts ...grpc.CallOption) (GobgpApi_MonitorRibClient, error) { stream, err := grpc.NewClientStream(ctx, &_GobgpApi_serviceDesc.Streams[0], c.cc, "/gobgpapi.GobgpApi/MonitorRib", opts...) if err != nil { return nil, err } x := &gobgpApiMonitorRibClient{stream} if err := x.ClientStream.SendMsg(in); err != nil { return nil, err } if err := x.ClientStream.CloseSend(); err != nil { return nil, err } return x, nil } type GobgpApi_MonitorRibClient interface { Recv() (*Destination, error) grpc.ClientStream } type gobgpApiMonitorRibClient struct { grpc.ClientStream } func (x *gobgpApiMonitorRibClient) Recv() (*Destination, error) { m := new(Destination) if err := x.ClientStream.RecvMsg(m); err != nil { return nil, err } return m, nil } func (c *gobgpApiClient) MonitorPeerState(ctx context.Context, in *Arguments, opts ...grpc.CallOption) (GobgpApi_MonitorPeerStateClient, error) { stream, err := grpc.NewClientStream(ctx, &_GobgpApi_serviceDesc.Streams[1], c.cc, "/gobgpapi.GobgpApi/MonitorPeerState", opts...) if err != nil { return nil, err } x := &gobgpApiMonitorPeerStateClient{stream} if err := x.ClientStream.SendMsg(in); err != nil { return nil, err } if err := x.ClientStream.CloseSend(); err != nil { return nil, err } return x, nil } type GobgpApi_MonitorPeerStateClient interface { Recv() (*Peer, error) grpc.ClientStream } type gobgpApiMonitorPeerStateClient struct { grpc.ClientStream } func (x *gobgpApiMonitorPeerStateClient) Recv() (*Peer, error) { m := new(Peer) if err := x.ClientStream.RecvMsg(m); err != nil { return nil, err } return m, nil } func (c *gobgpApiClient) EnableMrt(ctx context.Context, in *EnableMrtRequest, opts ...grpc.CallOption) (*EnableMrtResponse, error) { out := new(EnableMrtResponse) err := grpc.Invoke(ctx, "/gobgpapi.GobgpApi/EnableMrt", in, out, c.cc, opts...) if err != nil { return nil, err } return out, nil } func (c *gobgpApiClient) DisableMrt(ctx context.Context, in *DisableMrtRequest, opts ...grpc.CallOption) (*DisableMrtResponse, error) { out := new(DisableMrtResponse) err := grpc.Invoke(ctx, "/gobgpapi.GobgpApi/DisableMrt", in, out, c.cc, opts...) if err != nil { return nil, err } return out, nil } func (c *gobgpApiClient) InjectMrt(ctx context.Context, opts ...grpc.CallOption) (GobgpApi_InjectMrtClient, error) { stream, err := grpc.NewClientStream(ctx, &_GobgpApi_serviceDesc.Streams[2], c.cc, "/gobgpapi.GobgpApi/InjectMrt", opts...) if err != nil { return nil, err } x := &gobgpApiInjectMrtClient{stream} return x, nil } type GobgpApi_InjectMrtClient interface { Send(*InjectMrtRequest) error CloseAndRecv() (*InjectMrtResponse, error) grpc.ClientStream } type gobgpApiInjectMrtClient struct { grpc.ClientStream } func (x *gobgpApiInjectMrtClient) Send(m *InjectMrtRequest) error { return x.ClientStream.SendMsg(m) } func (x *gobgpApiInjectMrtClient) CloseAndRecv() (*InjectMrtResponse, error) { if err := x.ClientStream.CloseSend(); err != nil { return nil, err } m := new(InjectMrtResponse) if err := x.ClientStream.RecvMsg(m); err != nil { return nil, err } return m, nil } func (c *gobgpApiClient) AddBmp(ctx context.Context, in *AddBmpRequest, opts ...grpc.CallOption) (*AddBmpResponse, error) { out := new(AddBmpResponse) err := grpc.Invoke(ctx, "/gobgpapi.GobgpApi/AddBmp", in, out, c.cc, opts...) if err != nil { return nil, err } return out, nil } func (c *gobgpApiClient) DeleteBmp(ctx context.Context, in *DeleteBmpRequest, opts ...grpc.CallOption) (*DeleteBmpResponse, error) { out := new(DeleteBmpResponse) err := grpc.Invoke(ctx, "/gobgpapi.GobgpApi/DeleteBmp", in, out, c.cc, opts...) if err != nil { return nil, err } return out, nil } func (c *gobgpApiClient) GetRpki(ctx context.Context, in *GetRpkiRequest, opts ...grpc.CallOption) (*GetRpkiResponse, error) { out := new(GetRpkiResponse) err := grpc.Invoke(ctx, "/gobgpapi.GobgpApi/GetRpki", in, out, c.cc, opts...) if err != nil { return nil, err } return out, nil } func (c *gobgpApiClient) AddRpki(ctx context.Context, in *AddRpkiRequest, opts ...grpc.CallOption) (*AddRpkiResponse, error) { out := new(AddRpkiResponse) err := grpc.Invoke(ctx, "/gobgpapi.GobgpApi/AddRpki", in, out, c.cc, opts...) if err != nil { return nil, err } return out, nil } func (c *gobgpApiClient) DeleteRpki(ctx context.Context, in *DeleteRpkiRequest, opts ...grpc.CallOption) (*DeleteRpkiResponse, error) { out := new(DeleteRpkiResponse) err := grpc.Invoke(ctx, "/gobgpapi.GobgpApi/DeleteRpki", in, out, c.cc, opts...) if err != nil { return nil, err } return out, nil } func (c *gobgpApiClient) EnableRpki(ctx context.Context, in *EnableRpkiRequest, opts ...grpc.CallOption) (*EnableRpkiResponse, error) { out := new(EnableRpkiResponse) err := grpc.Invoke(ctx, "/gobgpapi.GobgpApi/EnableRpki", in, out, c.cc, opts...) if err != nil { return nil, err } return out, nil } func (c *gobgpApiClient) DisableRpki(ctx context.Context, in *DisableRpkiRequest, opts ...grpc.CallOption) (*DisableRpkiResponse, error) { out := new(DisableRpkiResponse) err := grpc.Invoke(ctx, "/gobgpapi.GobgpApi/DisableRpki", in, out, c.cc, opts...) if err != nil { return nil, err } return out, nil } func (c *gobgpApiClient) ResetRpki(ctx context.Context, in *ResetRpkiRequest, opts ...grpc.CallOption) (*ResetRpkiResponse, error) { out := new(ResetRpkiResponse) err := grpc.Invoke(ctx, "/gobgpapi.GobgpApi/ResetRpki", in, out, c.cc, opts...) if err != nil { return nil, err } return out, nil } func (c *gobgpApiClient) SoftResetRpki(ctx context.Context, in *SoftResetRpkiRequest, opts ...grpc.CallOption) (*SoftResetRpkiResponse, error) { out := new(SoftResetRpkiResponse) err := grpc.Invoke(ctx, "/gobgpapi.GobgpApi/SoftResetRpki", in, out, c.cc, opts...) if err != nil { return nil, err } return out, nil } func (c *gobgpApiClient) GetRoa(ctx context.Context, in *GetRoaRequest, opts ...grpc.CallOption) (*GetRoaResponse, error) { out := new(GetRoaResponse) err := grpc.Invoke(ctx, "/gobgpapi.GobgpApi/GetRoa", in, out, c.cc, opts...) if err != nil { return nil, err } return out, nil } func (c *gobgpApiClient) EnableZebra(ctx context.Context, in *EnableZebraRequest, opts ...grpc.CallOption) (*EnableZebraResponse, error) { out := new(EnableZebraResponse) err := grpc.Invoke(ctx, "/gobgpapi.GobgpApi/EnableZebra", in, out, c.cc, opts...) if err != nil { return nil, err } return out, nil } func (c *gobgpApiClient) AddVrf(ctx context.Context, in *AddVrfRequest, opts ...grpc.CallOption) (*AddVrfResponse, error) { out := new(AddVrfResponse) err := grpc.Invoke(ctx, "/gobgpapi.GobgpApi/AddVrf", in, out, c.cc, opts...) if err != nil { return nil, err } return out, nil } func (c *gobgpApiClient) DeleteVrf(ctx context.Context, in *DeleteVrfRequest, opts ...grpc.CallOption) (*DeleteVrfResponse, error) { out := new(DeleteVrfResponse) err := grpc.Invoke(ctx, "/gobgpapi.GobgpApi/DeleteVrf", in, out, c.cc, opts...) if err != nil { return nil, err } return out, nil } func (c *gobgpApiClient) GetVrf(ctx context.Context, in *GetVrfRequest, opts ...grpc.CallOption) (*GetVrfResponse, error) { out := new(GetVrfResponse) err := grpc.Invoke(ctx, "/gobgpapi.GobgpApi/GetVrf", in, out, c.cc, opts...) if err != nil { return nil, err } return out, nil } func (c *gobgpApiClient) GetDefinedSet(ctx context.Context, in *GetDefinedSetRequest, opts ...grpc.CallOption) (*GetDefinedSetResponse, error) { out := new(GetDefinedSetResponse) err := grpc.Invoke(ctx, "/gobgpapi.GobgpApi/GetDefinedSet", in, out, c.cc, opts...) if err != nil { return nil, err } return out, nil } func (c *gobgpApiClient) AddDefinedSet(ctx context.Context, in *AddDefinedSetRequest, opts ...grpc.CallOption) (*AddDefinedSetResponse, error) { out := new(AddDefinedSetResponse) err := grpc.Invoke(ctx, "/gobgpapi.GobgpApi/AddDefinedSet", in, out, c.cc, opts...) if err != nil { return nil, err } return out, nil } func (c *gobgpApiClient) DeleteDefinedSet(ctx context.Context, in *DeleteDefinedSetRequest, opts ...grpc.CallOption) (*DeleteDefinedSetResponse, error) { out := new(DeleteDefinedSetResponse) err := grpc.Invoke(ctx, "/gobgpapi.GobgpApi/DeleteDefinedSet", in, out, c.cc, opts...) if err != nil { return nil, err } return out, nil } func (c *gobgpApiClient) ReplaceDefinedSet(ctx context.Context, in *ReplaceDefinedSetRequest, opts ...grpc.CallOption) (*ReplaceDefinedSetResponse, error) { out := new(ReplaceDefinedSetResponse) err := grpc.Invoke(ctx, "/gobgpapi.GobgpApi/ReplaceDefinedSet", in, out, c.cc, opts...) if err != nil { return nil, err } return out, nil } func (c *gobgpApiClient) GetStatement(ctx context.Context, in *GetStatementRequest, opts ...grpc.CallOption) (*GetStatementResponse, error) { out := new(GetStatementResponse) err := grpc.Invoke(ctx, "/gobgpapi.GobgpApi/GetStatement", in, out, c.cc, opts...) if err != nil { return nil, err } return out, nil } func (c *gobgpApiClient) AddStatement(ctx context.Context, in *AddStatementRequest, opts ...grpc.CallOption) (*AddStatementResponse, error) { out := new(AddStatementResponse) err := grpc.Invoke(ctx, "/gobgpapi.GobgpApi/AddStatement", in, out, c.cc, opts...) if err != nil { return nil, err } return out, nil } func (c *gobgpApiClient) DeleteStatement(ctx context.Context, in *DeleteStatementRequest, opts ...grpc.CallOption) (*DeleteStatementResponse, error) { out := new(DeleteStatementResponse) err := grpc.Invoke(ctx, "/gobgpapi.GobgpApi/DeleteStatement", in, out, c.cc, opts...) if err != nil { return nil, err } return out, nil } func (c *gobgpApiClient) ReplaceStatement(ctx context.Context, in *ReplaceStatementRequest, opts ...grpc.CallOption) (*ReplaceStatementResponse, error) { out := new(ReplaceStatementResponse) err := grpc.Invoke(ctx, "/gobgpapi.GobgpApi/ReplaceStatement", in, out, c.cc, opts...) if err != nil { return nil, err } return out, nil } func (c *gobgpApiClient) GetPolicy(ctx context.Context, in *GetPolicyRequest, opts ...grpc.CallOption) (*GetPolicyResponse, error) { out := new(GetPolicyResponse) err := grpc.Invoke(ctx, "/gobgpapi.GobgpApi/GetPolicy", in, out, c.cc, opts...) if err != nil { return nil, err } return out, nil } func (c *gobgpApiClient) AddPolicy(ctx context.Context, in *AddPolicyRequest, opts ...grpc.CallOption) (*AddPolicyResponse, error) { out := new(AddPolicyResponse) err := grpc.Invoke(ctx, "/gobgpapi.GobgpApi/AddPolicy", in, out, c.cc, opts...) if err != nil { return nil, err } return out, nil } func (c *gobgpApiClient) DeletePolicy(ctx context.Context, in *DeletePolicyRequest, opts ...grpc.CallOption) (*DeletePolicyResponse, error) { out := new(DeletePolicyResponse) err := grpc.Invoke(ctx, "/gobgpapi.GobgpApi/DeletePolicy", in, out, c.cc, opts...) if err != nil { return nil, err } return out, nil } func (c *gobgpApiClient) ReplacePolicy(ctx context.Context, in *ReplacePolicyRequest, opts ...grpc.CallOption) (*ReplacePolicyResponse, error) { out := new(ReplacePolicyResponse) err := grpc.Invoke(ctx, "/gobgpapi.GobgpApi/ReplacePolicy", in, out, c.cc, opts...) if err != nil { return nil, err } return out, nil } func (c *gobgpApiClient) GetPolicyAssignment(ctx context.Context, in *GetPolicyAssignmentRequest, opts ...grpc.CallOption) (*GetPolicyAssignmentResponse, error) { out := new(GetPolicyAssignmentResponse) err := grpc.Invoke(ctx, "/gobgpapi.GobgpApi/GetPolicyAssignment", in, out, c.cc, opts...) if err != nil { return nil, err } return out, nil } func (c *gobgpApiClient) AddPolicyAssignment(ctx context.Context, in *AddPolicyAssignmentRequest, opts ...grpc.CallOption) (*AddPolicyAssignmentResponse, error) { out := new(AddPolicyAssignmentResponse) err := grpc.Invoke(ctx, "/gobgpapi.GobgpApi/AddPolicyAssignment", in, out, c.cc, opts...) if err != nil { return nil, err } return out, nil } func (c *gobgpApiClient) DeletePolicyAssignment(ctx context.Context, in *DeletePolicyAssignmentRequest, opts ...grpc.CallOption) (*DeletePolicyAssignmentResponse, error) { out := new(DeletePolicyAssignmentResponse) err := grpc.Invoke(ctx, "/gobgpapi.GobgpApi/DeletePolicyAssignment", in, out, c.cc, opts...) if err != nil { return nil, err } return out, nil } func (c *gobgpApiClient) ReplacePolicyAssignment(ctx context.Context, in *ReplacePolicyAssignmentRequest, opts ...grpc.CallOption) (*ReplacePolicyAssignmentResponse, error) { out := new(ReplacePolicyAssignmentResponse) err := grpc.Invoke(ctx, "/gobgpapi.GobgpApi/ReplacePolicyAssignment", in, out, c.cc, opts...) if err != nil { return nil, err } return out, nil } // Server API for GobgpApi service type GobgpApiServer interface { StartServer(context.Context, *StartServerRequest) (*StartServerResponse, error) StopServer(context.Context, *StopServerRequest) (*StopServerResponse, error) GetServer(context.Context, *GetServerRequest) (*GetServerResponse, error) AddNeighbor(context.Context, *AddNeighborRequest) (*AddNeighborResponse, error) DeleteNeighbor(context.Context, *DeleteNeighborRequest) (*DeleteNeighborResponse, error) GetNeighbor(context.Context, *GetNeighborRequest) (*GetNeighborResponse, error) ResetNeighbor(context.Context, *ResetNeighborRequest) (*ResetNeighborResponse, error) SoftResetNeighbor(context.Context, *SoftResetNeighborRequest) (*SoftResetNeighborResponse, error) ShutdownNeighbor(context.Context, *ShutdownNeighborRequest) (*ShutdownNeighborResponse, error) EnableNeighbor(context.Context, *EnableNeighborRequest) (*EnableNeighborResponse, error) DisableNeighbor(context.Context, *DisableNeighborRequest) (*DisableNeighborResponse, error) GetRib(context.Context, *GetRibRequest) (*GetRibResponse, error) ValidateRib(context.Context, *ValidateRibRequest) (*ValidateRibResponse, error) AddPath(context.Context, *AddPathRequest) (*AddPathResponse, error) DeletePath(context.Context, *DeletePathRequest) (*DeletePathResponse, error) MonitorRib(*Table, GobgpApi_MonitorRibServer) error MonitorPeerState(*Arguments, GobgpApi_MonitorPeerStateServer) error EnableMrt(context.Context, *EnableMrtRequest) (*EnableMrtResponse, error) DisableMrt(context.Context, *DisableMrtRequest) (*DisableMrtResponse, error) InjectMrt(GobgpApi_InjectMrtServer) error AddBmp(context.Context, *AddBmpRequest) (*AddBmpResponse, error) DeleteBmp(context.Context, *DeleteBmpRequest) (*DeleteBmpResponse, error) GetRpki(context.Context, *GetRpkiRequest) (*GetRpkiResponse, error) AddRpki(context.Context, *AddRpkiRequest) (*AddRpkiResponse, error) DeleteRpki(context.Context, *DeleteRpkiRequest) (*DeleteRpkiResponse, error) EnableRpki(context.Context, *EnableRpkiRequest) (*EnableRpkiResponse, error) DisableRpki(context.Context, *DisableRpkiRequest) (*DisableRpkiResponse, error) ResetRpki(context.Context, *ResetRpkiRequest) (*ResetRpkiResponse, error) SoftResetRpki(context.Context, *SoftResetRpkiRequest) (*SoftResetRpkiResponse, error) GetRoa(context.Context, *GetRoaRequest) (*GetRoaResponse, error) EnableZebra(context.Context, *EnableZebraRequest) (*EnableZebraResponse, error) AddVrf(context.Context, *AddVrfRequest) (*AddVrfResponse, error) DeleteVrf(context.Context, *DeleteVrfRequest) (*DeleteVrfResponse, error) GetVrf(context.Context, *GetVrfRequest) (*GetVrfResponse, error) GetDefinedSet(context.Context, *GetDefinedSetRequest) (*GetDefinedSetResponse, error) AddDefinedSet(context.Context, *AddDefinedSetRequest) (*AddDefinedSetResponse, error) DeleteDefinedSet(context.Context, *DeleteDefinedSetRequest) (*DeleteDefinedSetResponse, error) ReplaceDefinedSet(context.Context, *ReplaceDefinedSetRequest) (*ReplaceDefinedSetResponse, error) GetStatement(context.Context, *GetStatementRequest) (*GetStatementResponse, error) AddStatement(context.Context, *AddStatementRequest) (*AddStatementResponse, error) DeleteStatement(context.Context, *DeleteStatementRequest) (*DeleteStatementResponse, error) ReplaceStatement(context.Context, *ReplaceStatementRequest) (*ReplaceStatementResponse, error) GetPolicy(context.Context, *GetPolicyRequest) (*GetPolicyResponse, error) AddPolicy(context.Context, *AddPolicyRequest) (*AddPolicyResponse, error) DeletePolicy(context.Context, *DeletePolicyRequest) (*DeletePolicyResponse, error) ReplacePolicy(context.Context, *ReplacePolicyRequest) (*ReplacePolicyResponse, error) GetPolicyAssignment(context.Context, *GetPolicyAssignmentRequest) (*GetPolicyAssignmentResponse, error) AddPolicyAssignment(context.Context, *AddPolicyAssignmentRequest) (*AddPolicyAssignmentResponse, error) DeletePolicyAssignment(context.Context, *DeletePolicyAssignmentRequest) (*DeletePolicyAssignmentResponse, error) ReplacePolicyAssignment(context.Context, *ReplacePolicyAssignmentRequest) (*ReplacePolicyAssignmentResponse, error) } func RegisterGobgpApiServer(s *grpc.Server, srv GobgpApiServer) { s.RegisterService(&_GobgpApi_serviceDesc, srv) } func _GobgpApi_StartServer_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(StartServerRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(GobgpApiServer).StartServer(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/gobgpapi.GobgpApi/StartServer", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(GobgpApiServer).StartServer(ctx, req.(*StartServerRequest)) } return interceptor(ctx, in, info, handler) } func _GobgpApi_StopServer_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(StopServerRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(GobgpApiServer).StopServer(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/gobgpapi.GobgpApi/StopServer", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(GobgpApiServer).StopServer(ctx, req.(*StopServerRequest)) } return interceptor(ctx, in, info, handler) } func _GobgpApi_GetServer_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(GetServerRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(GobgpApiServer).GetServer(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/gobgpapi.GobgpApi/GetServer", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(GobgpApiServer).GetServer(ctx, req.(*GetServerRequest)) } return interceptor(ctx, in, info, handler) } func _GobgpApi_AddNeighbor_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(AddNeighborRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(GobgpApiServer).AddNeighbor(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/gobgpapi.GobgpApi/AddNeighbor", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(GobgpApiServer).AddNeighbor(ctx, req.(*AddNeighborRequest)) } return interceptor(ctx, in, info, handler) } func _GobgpApi_DeleteNeighbor_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(DeleteNeighborRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(GobgpApiServer).DeleteNeighbor(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/gobgpapi.GobgpApi/DeleteNeighbor", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(GobgpApiServer).DeleteNeighbor(ctx, req.(*DeleteNeighborRequest)) } return interceptor(ctx, in, info, handler) } func _GobgpApi_GetNeighbor_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(GetNeighborRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(GobgpApiServer).GetNeighbor(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/gobgpapi.GobgpApi/GetNeighbor", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(GobgpApiServer).GetNeighbor(ctx, req.(*GetNeighborRequest)) } return interceptor(ctx, in, info, handler) } func _GobgpApi_ResetNeighbor_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(ResetNeighborRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(GobgpApiServer).ResetNeighbor(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/gobgpapi.GobgpApi/ResetNeighbor", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(GobgpApiServer).ResetNeighbor(ctx, req.(*ResetNeighborRequest)) } return interceptor(ctx, in, info, handler) } func _GobgpApi_SoftResetNeighbor_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(SoftResetNeighborRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(GobgpApiServer).SoftResetNeighbor(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/gobgpapi.GobgpApi/SoftResetNeighbor", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(GobgpApiServer).SoftResetNeighbor(ctx, req.(*SoftResetNeighborRequest)) } return interceptor(ctx, in, info, handler) } func _GobgpApi_ShutdownNeighbor_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(ShutdownNeighborRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(GobgpApiServer).ShutdownNeighbor(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/gobgpapi.GobgpApi/ShutdownNeighbor", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(GobgpApiServer).ShutdownNeighbor(ctx, req.(*ShutdownNeighborRequest)) } return interceptor(ctx, in, info, handler) } func _GobgpApi_EnableNeighbor_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(EnableNeighborRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(GobgpApiServer).EnableNeighbor(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/gobgpapi.GobgpApi/EnableNeighbor", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(GobgpApiServer).EnableNeighbor(ctx, req.(*EnableNeighborRequest)) } return interceptor(ctx, in, info, handler) } func _GobgpApi_DisableNeighbor_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(DisableNeighborRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(GobgpApiServer).DisableNeighbor(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/gobgpapi.GobgpApi/DisableNeighbor", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(GobgpApiServer).DisableNeighbor(ctx, req.(*DisableNeighborRequest)) } return interceptor(ctx, in, info, handler) } func _GobgpApi_GetRib_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(GetRibRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(GobgpApiServer).GetRib(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/gobgpapi.GobgpApi/GetRib", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(GobgpApiServer).GetRib(ctx, req.(*GetRibRequest)) } return interceptor(ctx, in, info, handler) } func _GobgpApi_ValidateRib_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(ValidateRibRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(GobgpApiServer).ValidateRib(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/gobgpapi.GobgpApi/ValidateRib", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(GobgpApiServer).ValidateRib(ctx, req.(*ValidateRibRequest)) } return interceptor(ctx, in, info, handler) } func _GobgpApi_AddPath_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(AddPathRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(GobgpApiServer).AddPath(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/gobgpapi.GobgpApi/AddPath", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(GobgpApiServer).AddPath(ctx, req.(*AddPathRequest)) } return interceptor(ctx, in, info, handler) } func _GobgpApi_DeletePath_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(DeletePathRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(GobgpApiServer).DeletePath(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/gobgpapi.GobgpApi/DeletePath", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(GobgpApiServer).DeletePath(ctx, req.(*DeletePathRequest)) } return interceptor(ctx, in, info, handler) } func _GobgpApi_MonitorRib_Handler(srv interface{}, stream grpc.ServerStream) error { m := new(Table) if err := stream.RecvMsg(m); err != nil { return err } return srv.(GobgpApiServer).MonitorRib(m, &gobgpApiMonitorRibServer{stream}) } type GobgpApi_MonitorRibServer interface { Send(*Destination) error grpc.ServerStream } type gobgpApiMonitorRibServer struct { grpc.ServerStream } func (x *gobgpApiMonitorRibServer) Send(m *Destination) error { return x.ServerStream.SendMsg(m) } func _GobgpApi_MonitorPeerState_Handler(srv interface{}, stream grpc.ServerStream) error { m := new(Arguments) if err := stream.RecvMsg(m); err != nil { return err } return srv.(GobgpApiServer).MonitorPeerState(m, &gobgpApiMonitorPeerStateServer{stream}) } type GobgpApi_MonitorPeerStateServer interface { Send(*Peer) error grpc.ServerStream } type gobgpApiMonitorPeerStateServer struct { grpc.ServerStream } func (x *gobgpApiMonitorPeerStateServer) Send(m *Peer) error { return x.ServerStream.SendMsg(m) } func _GobgpApi_EnableMrt_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(EnableMrtRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(GobgpApiServer).EnableMrt(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/gobgpapi.GobgpApi/EnableMrt", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(GobgpApiServer).EnableMrt(ctx, req.(*EnableMrtRequest)) } return interceptor(ctx, in, info, handler) } func _GobgpApi_DisableMrt_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(DisableMrtRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(GobgpApiServer).DisableMrt(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/gobgpapi.GobgpApi/DisableMrt", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(GobgpApiServer).DisableMrt(ctx, req.(*DisableMrtRequest)) } return interceptor(ctx, in, info, handler) } func _GobgpApi_InjectMrt_Handler(srv interface{}, stream grpc.ServerStream) error { return srv.(GobgpApiServer).InjectMrt(&gobgpApiInjectMrtServer{stream}) } type GobgpApi_InjectMrtServer interface { SendAndClose(*InjectMrtResponse) error Recv() (*InjectMrtRequest, error) grpc.ServerStream } type gobgpApiInjectMrtServer struct { grpc.ServerStream } func (x *gobgpApiInjectMrtServer) SendAndClose(m *InjectMrtResponse) error { return x.ServerStream.SendMsg(m) } func (x *gobgpApiInjectMrtServer) Recv() (*InjectMrtRequest, error) { m := new(InjectMrtRequest) if err := x.ServerStream.RecvMsg(m); err != nil { return nil, err } return m, nil } func _GobgpApi_AddBmp_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(AddBmpRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(GobgpApiServer).AddBmp(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/gobgpapi.GobgpApi/AddBmp", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(GobgpApiServer).AddBmp(ctx, req.(*AddBmpRequest)) } return interceptor(ctx, in, info, handler) } func _GobgpApi_DeleteBmp_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(DeleteBmpRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(GobgpApiServer).DeleteBmp(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/gobgpapi.GobgpApi/DeleteBmp", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(GobgpApiServer).DeleteBmp(ctx, req.(*DeleteBmpRequest)) } return interceptor(ctx, in, info, handler) } func _GobgpApi_GetRpki_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(GetRpkiRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(GobgpApiServer).GetRpki(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/gobgpapi.GobgpApi/GetRpki", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(GobgpApiServer).GetRpki(ctx, req.(*GetRpkiRequest)) } return interceptor(ctx, in, info, handler) } func _GobgpApi_AddRpki_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(AddRpkiRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(GobgpApiServer).AddRpki(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/gobgpapi.GobgpApi/AddRpki", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(GobgpApiServer).AddRpki(ctx, req.(*AddRpkiRequest)) } return interceptor(ctx, in, info, handler) } func _GobgpApi_DeleteRpki_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(DeleteRpkiRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(GobgpApiServer).DeleteRpki(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/gobgpapi.GobgpApi/DeleteRpki", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(GobgpApiServer).DeleteRpki(ctx, req.(*DeleteRpkiRequest)) } return interceptor(ctx, in, info, handler) } func _GobgpApi_EnableRpki_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(EnableRpkiRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(GobgpApiServer).EnableRpki(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/gobgpapi.GobgpApi/EnableRpki", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(GobgpApiServer).EnableRpki(ctx, req.(*EnableRpkiRequest)) } return interceptor(ctx, in, info, handler) } func _GobgpApi_DisableRpki_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(DisableRpkiRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(GobgpApiServer).DisableRpki(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/gobgpapi.GobgpApi/DisableRpki", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(GobgpApiServer).DisableRpki(ctx, req.(*DisableRpkiRequest)) } return interceptor(ctx, in, info, handler) } func _GobgpApi_ResetRpki_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(ResetRpkiRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(GobgpApiServer).ResetRpki(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/gobgpapi.GobgpApi/ResetRpki", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(GobgpApiServer).ResetRpki(ctx, req.(*ResetRpkiRequest)) } return interceptor(ctx, in, info, handler) } func _GobgpApi_SoftResetRpki_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(SoftResetRpkiRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(GobgpApiServer).SoftResetRpki(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/gobgpapi.GobgpApi/SoftResetRpki", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(GobgpApiServer).SoftResetRpki(ctx, req.(*SoftResetRpkiRequest)) } return interceptor(ctx, in, info, handler) } func _GobgpApi_GetRoa_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(GetRoaRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(GobgpApiServer).GetRoa(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/gobgpapi.GobgpApi/GetRoa", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(GobgpApiServer).GetRoa(ctx, req.(*GetRoaRequest)) } return interceptor(ctx, in, info, handler) } func _GobgpApi_EnableZebra_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(EnableZebraRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(GobgpApiServer).EnableZebra(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/gobgpapi.GobgpApi/EnableZebra", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(GobgpApiServer).EnableZebra(ctx, req.(*EnableZebraRequest)) } return interceptor(ctx, in, info, handler) } func _GobgpApi_AddVrf_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(AddVrfRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(GobgpApiServer).AddVrf(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/gobgpapi.GobgpApi/AddVrf", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(GobgpApiServer).AddVrf(ctx, req.(*AddVrfRequest)) } return interceptor(ctx, in, info, handler) } func _GobgpApi_DeleteVrf_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(DeleteVrfRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(GobgpApiServer).DeleteVrf(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/gobgpapi.GobgpApi/DeleteVrf", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(GobgpApiServer).DeleteVrf(ctx, req.(*DeleteVrfRequest)) } return interceptor(ctx, in, info, handler) } func _GobgpApi_GetVrf_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(GetVrfRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(GobgpApiServer).GetVrf(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/gobgpapi.GobgpApi/GetVrf", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(GobgpApiServer).GetVrf(ctx, req.(*GetVrfRequest)) } return interceptor(ctx, in, info, handler) } func _GobgpApi_GetDefinedSet_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(GetDefinedSetRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(GobgpApiServer).GetDefinedSet(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/gobgpapi.GobgpApi/GetDefinedSet", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(GobgpApiServer).GetDefinedSet(ctx, req.(*GetDefinedSetRequest)) } return interceptor(ctx, in, info, handler) } func _GobgpApi_AddDefinedSet_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(AddDefinedSetRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(GobgpApiServer).AddDefinedSet(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/gobgpapi.GobgpApi/AddDefinedSet", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(GobgpApiServer).AddDefinedSet(ctx, req.(*AddDefinedSetRequest)) } return interceptor(ctx, in, info, handler) } func _GobgpApi_DeleteDefinedSet_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(DeleteDefinedSetRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(GobgpApiServer).DeleteDefinedSet(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/gobgpapi.GobgpApi/DeleteDefinedSet", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(GobgpApiServer).DeleteDefinedSet(ctx, req.(*DeleteDefinedSetRequest)) } return interceptor(ctx, in, info, handler) } func _GobgpApi_ReplaceDefinedSet_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(ReplaceDefinedSetRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(GobgpApiServer).ReplaceDefinedSet(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/gobgpapi.GobgpApi/ReplaceDefinedSet", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(GobgpApiServer).ReplaceDefinedSet(ctx, req.(*ReplaceDefinedSetRequest)) } return interceptor(ctx, in, info, handler) } func _GobgpApi_GetStatement_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(GetStatementRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(GobgpApiServer).GetStatement(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/gobgpapi.GobgpApi/GetStatement", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(GobgpApiServer).GetStatement(ctx, req.(*GetStatementRequest)) } return interceptor(ctx, in, info, handler) } func _GobgpApi_AddStatement_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(AddStatementRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(GobgpApiServer).AddStatement(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/gobgpapi.GobgpApi/AddStatement", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(GobgpApiServer).AddStatement(ctx, req.(*AddStatementRequest)) } return interceptor(ctx, in, info, handler) } func _GobgpApi_DeleteStatement_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(DeleteStatementRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(GobgpApiServer).DeleteStatement(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/gobgpapi.GobgpApi/DeleteStatement", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(GobgpApiServer).DeleteStatement(ctx, req.(*DeleteStatementRequest)) } return interceptor(ctx, in, info, handler) } func _GobgpApi_ReplaceStatement_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(ReplaceStatementRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(GobgpApiServer).ReplaceStatement(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/gobgpapi.GobgpApi/ReplaceStatement", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(GobgpApiServer).ReplaceStatement(ctx, req.(*ReplaceStatementRequest)) } return interceptor(ctx, in, info, handler) } func _GobgpApi_GetPolicy_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(GetPolicyRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(GobgpApiServer).GetPolicy(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/gobgpapi.GobgpApi/GetPolicy", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(GobgpApiServer).GetPolicy(ctx, req.(*GetPolicyRequest)) } return interceptor(ctx, in, info, handler) } func _GobgpApi_AddPolicy_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(AddPolicyRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(GobgpApiServer).AddPolicy(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/gobgpapi.GobgpApi/AddPolicy", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(GobgpApiServer).AddPolicy(ctx, req.(*AddPolicyRequest)) } return interceptor(ctx, in, info, handler) } func _GobgpApi_DeletePolicy_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(DeletePolicyRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(GobgpApiServer).DeletePolicy(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/gobgpapi.GobgpApi/DeletePolicy", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(GobgpApiServer).DeletePolicy(ctx, req.(*DeletePolicyRequest)) } return interceptor(ctx, in, info, handler) } func _GobgpApi_ReplacePolicy_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(ReplacePolicyRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(GobgpApiServer).ReplacePolicy(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/gobgpapi.GobgpApi/ReplacePolicy", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(GobgpApiServer).ReplacePolicy(ctx, req.(*ReplacePolicyRequest)) } return interceptor(ctx, in, info, handler) } func _GobgpApi_GetPolicyAssignment_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(GetPolicyAssignmentRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(GobgpApiServer).GetPolicyAssignment(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/gobgpapi.GobgpApi/GetPolicyAssignment", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(GobgpApiServer).GetPolicyAssignment(ctx, req.(*GetPolicyAssignmentRequest)) } return interceptor(ctx, in, info, handler) } func _GobgpApi_AddPolicyAssignment_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(AddPolicyAssignmentRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(GobgpApiServer).AddPolicyAssignment(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/gobgpapi.GobgpApi/AddPolicyAssignment", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(GobgpApiServer).AddPolicyAssignment(ctx, req.(*AddPolicyAssignmentRequest)) } return interceptor(ctx, in, info, handler) } func _GobgpApi_DeletePolicyAssignment_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(DeletePolicyAssignmentRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(GobgpApiServer).DeletePolicyAssignment(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/gobgpapi.GobgpApi/DeletePolicyAssignment", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(GobgpApiServer).DeletePolicyAssignment(ctx, req.(*DeletePolicyAssignmentRequest)) } return interceptor(ctx, in, info, handler) } func _GobgpApi_ReplacePolicyAssignment_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(ReplacePolicyAssignmentRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(GobgpApiServer).ReplacePolicyAssignment(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/gobgpapi.GobgpApi/ReplacePolicyAssignment", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(GobgpApiServer).ReplacePolicyAssignment(ctx, req.(*ReplacePolicyAssignmentRequest)) } return interceptor(ctx, in, info, handler) } var _GobgpApi_serviceDesc = grpc.ServiceDesc{ ServiceName: "gobgpapi.GobgpApi", HandlerType: (*GobgpApiServer)(nil), Methods: []grpc.MethodDesc{ { MethodName: "StartServer", Handler: _GobgpApi_StartServer_Handler, }, { MethodName: "StopServer", Handler: _GobgpApi_StopServer_Handler, }, { MethodName: "GetServer", Handler: _GobgpApi_GetServer_Handler, }, { MethodName: "AddNeighbor", Handler: _GobgpApi_AddNeighbor_Handler, }, { MethodName: "DeleteNeighbor", Handler: _GobgpApi_DeleteNeighbor_Handler, }, { MethodName: "GetNeighbor", Handler: _GobgpApi_GetNeighbor_Handler, }, { MethodName: "ResetNeighbor", Handler: _GobgpApi_ResetNeighbor_Handler, }, { MethodName: "SoftResetNeighbor", Handler: _GobgpApi_SoftResetNeighbor_Handler, }, { MethodName: "ShutdownNeighbor", Handler: _GobgpApi_ShutdownNeighbor_Handler, }, { MethodName: "EnableNeighbor", Handler: _GobgpApi_EnableNeighbor_Handler, }, { MethodName: "DisableNeighbor", Handler: _GobgpApi_DisableNeighbor_Handler, }, { MethodName: "GetRib", Handler: _GobgpApi_GetRib_Handler, }, { MethodName: "ValidateRib", Handler: _GobgpApi_ValidateRib_Handler, }, { MethodName: "AddPath", Handler: _GobgpApi_AddPath_Handler, }, { MethodName: "DeletePath", Handler: _GobgpApi_DeletePath_Handler, }, { MethodName: "EnableMrt", Handler: _GobgpApi_EnableMrt_Handler, }, { MethodName: "DisableMrt", Handler: _GobgpApi_DisableMrt_Handler, }, { MethodName: "AddBmp", Handler: _GobgpApi_AddBmp_Handler, }, { MethodName: "DeleteBmp", Handler: _GobgpApi_DeleteBmp_Handler, }, { MethodName: "GetRpki", Handler: _GobgpApi_GetRpki_Handler, }, { MethodName: "AddRpki", Handler: _GobgpApi_AddRpki_Handler, }, { MethodName: "DeleteRpki", Handler: _GobgpApi_DeleteRpki_Handler, }, { MethodName: "EnableRpki", Handler: _GobgpApi_EnableRpki_Handler, }, { MethodName: "DisableRpki", Handler: _GobgpApi_DisableRpki_Handler, }, { MethodName: "ResetRpki", Handler: _GobgpApi_ResetRpki_Handler, }, { MethodName: "SoftResetRpki", Handler: _GobgpApi_SoftResetRpki_Handler, }, { MethodName: "GetRoa", Handler: _GobgpApi_GetRoa_Handler, }, { MethodName: "EnableZebra", Handler: _GobgpApi_EnableZebra_Handler, }, { MethodName: "AddVrf", Handler: _GobgpApi_AddVrf_Handler, }, { MethodName: "DeleteVrf", Handler: _GobgpApi_DeleteVrf_Handler, }, { MethodName: "GetVrf", Handler: _GobgpApi_GetVrf_Handler, }, { MethodName: "GetDefinedSet", Handler: _GobgpApi_GetDefinedSet_Handler, }, { MethodName: "AddDefinedSet", Handler: _GobgpApi_AddDefinedSet_Handler, }, { MethodName: "DeleteDefinedSet", Handler: _GobgpApi_DeleteDefinedSet_Handler, }, { MethodName: "ReplaceDefinedSet", Handler: _GobgpApi_ReplaceDefinedSet_Handler, }, { MethodName: "GetStatement", Handler: _GobgpApi_GetStatement_Handler, }, { MethodName: "AddStatement", Handler: _GobgpApi_AddStatement_Handler, }, { MethodName: "DeleteStatement", Handler: _GobgpApi_DeleteStatement_Handler, }, { MethodName: "ReplaceStatement", Handler: _GobgpApi_ReplaceStatement_Handler, }, { MethodName: "GetPolicy", Handler: _GobgpApi_GetPolicy_Handler, }, { MethodName: "AddPolicy", Handler: _GobgpApi_AddPolicy_Handler, }, { MethodName: "DeletePolicy", Handler: _GobgpApi_DeletePolicy_Handler, }, { MethodName: "ReplacePolicy", Handler: _GobgpApi_ReplacePolicy_Handler, }, { MethodName: "GetPolicyAssignment", Handler: _GobgpApi_GetPolicyAssignment_Handler, }, { MethodName: "AddPolicyAssignment", Handler: _GobgpApi_AddPolicyAssignment_Handler, }, { MethodName: "DeletePolicyAssignment", Handler: _GobgpApi_DeletePolicyAssignment_Handler, }, { MethodName: "ReplacePolicyAssignment", Handler: _GobgpApi_ReplacePolicyAssignment_Handler, }, }, Streams: []grpc.StreamDesc{ { StreamName: "MonitorRib", Handler: _GobgpApi_MonitorRib_Handler, ServerStreams: true, }, { StreamName: "MonitorPeerState", Handler: _GobgpApi_MonitorPeerState_Handler, ServerStreams: true, }, { StreamName: "InjectMrt", Handler: _GobgpApi_InjectMrt_Handler, ClientStreams: true, }, }, Metadata: fileDescriptor0, } func init() { proto.RegisterFile("gobgp.proto", fileDescriptor0) } var fileDescriptor0 = []byte{ // 5371 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x09, 0x6e, 0x88, 0x02, 0xff, 0xd4, 0x3c, 0x4d, 0x73, 0x1b, 0x57, 0x72, 0x04, 0x01, 0x92, 0x40, 0x03, 0x20, 0xc1, 0x11, 0x29, 0x41, 0x90, 0x25, 0x5b, 0xb3, 0xeb, 0xb5, 0xac, 0xb5, 0xe5, 0xb5, 0x6c, 0xcb, 0x9b, 0xf5, 0x7a, 0xb3, 0x30, 0x09, 0x49, 0x58, 0xf3, 0x03, 0x1e, 0x42, 0x8a, 0xbd, 0xf9, 0x98, 0x8c, 0x80, 0x01, 0x39, 0x31, 0x80, 0x99, 0x9d, 0x19, 0xc8, 0x52, 0xa5, 0x2a, 0xa9, 0x4a, 0x6e, 0xf9, 0x38, 0xe7, 0xb2, 0x55, 0xb9, 0x6f, 0x92, 0x73, 0xaa, 0x72, 0x4e, 0xaa, 0x92, 0x5f, 0x91, 0x53, 0xfe, 0x43, 0x8e, 0xe9, 0xee, 0xf7, 0x66, 0xe6, 0xcd, 0x07, 0x28, 0x4a, 0x51, 0x92, 0xca, 0x89, 0x78, 0xdd, 0xfd, 0xfa, 0x7d, 0xf5, 0xd7, 0xeb, 0x37, 0x4d, 0xa8, 0x9f, 0xba, 0x4f, 0x4e, 0xbd, 0x3b, 0x9e, 0xef, 0x86, 0xae, 0x56, 0xe5, 0x86, 0xe5, 0x39, 0xfa, 0x0e, 0x68, 0x0f, 0xec, 0xf0, 0xc8, 0x76, 0x4e, 0xcf, 0x9e, 0xb8, 0xbe, 0x61, 0xff, 0x6a, 0x61, 0x07, 0xa1, 0xfe, 0x19, 0x5c, 0x4a, 0x41, 0x03, 0xcf, 0x9d, 0x07, 0xb6, 0xf6, 0x7d, 0x58, 0xf3, 0x6c, 0xdb, 0x0f, 0xda, 0xa5, 0xb7, 0xca, 0xb7, 0xea, 0x77, 0x37, 0xef, 0x44, 0x6c, 0xee, 0x0c, 0x10, 0x6c, 0x08, 0xa4, 0x7e, 0x0a, 0xb5, 0xae, 0x7f, 0xba, 0x98, 0xd9, 0xf3, 0x30, 0xd0, 0xee, 0x40, 0xd5, 0xb7, 0x03, 0x77, 0xe1, 0x8f, 0x6c, 0xec, 0x55, 0xba, 0xb5, 0x79, 0x57, 0x4b, 0x7a, 0x19, 0x12, 0x63, 0xc4, 0x34, 0xda, 0x65, 0x58, 0x9f, 0x58, 0x33, 0x67, 0xfa, 0xbc, 0xbd, 0x8a, 0xd4, 0x4d, 0x43, 0xb6, 0x34, 0x0d, 0x2a, 0x73, 0x6b, 0x66, 0xb7, 0xcb, 0x08, 0xad, 0x19, 0xfc, 0x5b, 0xff, 0x63, 0xd8, 0xec, 0x8e, 0xc7, 0x03, 0x2b, 0x3c, 0x93, 0xf3, 0x7e, 0xe9, 0xd1, 0x76, 0x61, 0xfd, 0xa9, 0x3f, 0x31, 0x9d, 0x31, 0x8f, 0x56, 0x33, 0xd6, 0xb0, 0xd5, 0x1f, 0x6b, 0x3a, 0x54, 0x3c, 0xe4, 0xca, 0x83, 0xa5, 0x97, 0x49, 0x63, 0x31, 0x4e, 0x7f, 0x1b, 0xb6, 0xe2, 0xc1, 0xe5, 0xf6, 0xe0, 0x1c, 0x17, 0x0b, 0xe4, 0x45, 0x23, 0x37, 0x0c, 0xfe, 0xad, 0xff, 0xa6, 0x04, 0xdb, 0xfb, 0xf6, 0xd4, 0x0e, 0xed, 0xff, 0x81, 0x79, 0x26, 0x9b, 0x55, 0x4e, 0x6d, 0x56, 0x34, 0xff, 0xca, 0xf2, 0xf9, 0xc7, 0x93, 0x5d, 0x53, 0x26, 0x8b, 0xc2, 0xa0, 0xce, 0x55, 0x2c, 0x4b, 0xff, 0x31, 0x68, 0xb8, 0xd2, 0x8c, 0x88, 0xf0, 0x18, 0x78, 0xdc, 0x3c, 0xfd, 0xbc, 0x28, 0x30, 0x4e, 0xdf, 0x85, 0x4b, 0xa9, 0x9e, 0x92, 0xe1, 0x67, 0xb0, 0x2b, 0x86, 0x79, 0x15, 0x9e, 0x6d, 0xb8, 0x9c, 0xed, 0x2c, 0xd9, 0xfe, 0x08, 0x76, 0xf0, 0x77, 0x4e, 0x98, 0xb5, 0x36, 0x6c, 0x58, 0xe3, 0x31, 0xee, 0x65, 0xc0, 0x8c, 0x6b, 0x46, 0xd4, 0xd4, 0xaf, 0xc0, 0x6e, 0xa6, 0x87, 0x64, 0xf5, 0x4f, 0x25, 0x68, 0x9f, 0xb8, 0x93, 0xf0, 0xe5, 0xf8, 0x69, 0x27, 0x50, 0x1b, 0x3b, 0xbe, 0x3d, 0x0a, 0x1d, 0x77, 0xce, 0x27, 0xb5, 0x79, 0xf7, 0x93, 0x64, 0x11, 0xcb, 0x18, 0x26, 0x88, 0xfd, 0xa8, 0xb3, 0x91, 0xf0, 0xd1, 0x3f, 0x00, 0x2d, 0x4f, 0xa0, 0xad, 0xc3, 0x6a, 0xff, 0xa8, 0xb5, 0xa2, 0x6d, 0x40, 0xf9, 0xf8, 0xd1, 0xb0, 0x55, 0xd2, 0xaa, 0x50, 0xf9, 0xe2, 0x78, 0xf8, 0xb0, 0xb5, 0xaa, 0x5f, 0x83, 0xab, 0x05, 0x43, 0xc9, 0x95, 0x7d, 0x04, 0x57, 0x4e, 0xce, 0x16, 0xe1, 0xd8, 0xfd, 0x6e, 0x7e, 0xf1, 0x7d, 0xea, 0xe0, 0x6e, 0xe4, 0x3a, 0x49, 0x86, 0x1f, 0xc2, 0x6e, 0x6f, 0x6e, 0x3d, 0x99, 0xda, 0x17, 0x67, 0x87, 0x47, 0x98, 0xed, 0x22, 0x99, 0xdd, 0xc5, 0xc3, 0x75, 0x82, 0x97, 0xe3, 0x76, 0x15, 0xae, 0xe4, 0xfa, 0x48, 0x76, 0xa7, 0xd0, 0x12, 0x03, 0x1d, 0xfa, 0x61, 0xc4, 0xe8, 0x1a, 0x9e, 0xd1, 0x62, 0xe6, 0x99, 0xe1, 0x73, 0x4f, 0xe8, 0xde, 0x9a, 0x51, 0x25, 0xc0, 0x10, 0xdb, 0x5a, 0x07, 0xaa, 0x13, 0x67, 0x6a, 0xb3, 0xa5, 0x11, 0x9a, 0x16, 0xb7, 0x09, 0xe7, 0xcc, 0x43, 0xdb, 0x7f, 0x6a, 0x4d, 0x59, 0xdd, 0x2a, 0x46, 0xdc, 0xd6, 0x2f, 0xc1, 0xb6, 0x32, 0x90, 0x1c, 0x1d, 0x81, 0x72, 0x62, 0xc9, 0xf0, 0xac, 0x62, 0x0a, 0x50, 0x92, 0xfe, 0x29, 0xb4, 0xfa, 0xf3, 0x3f, 0xc2, 0xa3, 0x55, 0x26, 0xfa, 0x9a, 0x6c, 0x04, 0xd9, 0x6c, 0xd4, 0xe6, 0x00, 0xe7, 0x5c, 0x2e, 0x30, 0x06, 0x02, 0x49, 0x73, 0x55, 0x26, 0x20, 0x67, 0xf5, 0xf7, 0x25, 0x68, 0xa2, 0xfe, 0x7e, 0x31, 0xf3, 0x5e, 0x2c, 0xfa, 0x68, 0x4e, 0x3c, 0xd7, 0x0f, 0xa5, 0xd5, 0xe6, 0xdf, 0xda, 0x4f, 0xa1, 0xc2, 0xbb, 0x5c, 0xe6, 0xd9, 0xdf, 0x4a, 0x46, 0x4e, 0x31, 0xbd, 0x73, 0xe8, 0xce, 0x9d, 0xd0, 0xf5, 0x9d, 0xf9, 0xe9, 0xc0, 0x9d, 0x3a, 0xa3, 0xe7, 0x06, 0xf7, 0x42, 0xb9, 0x6f, 0x65, 0x31, 0x24, 0xed, 0x03, 0xa3, 0x87, 0x62, 0x8f, 0xd2, 0x3e, 0x38, 0x3e, 0x49, 0xcb, 0x7d, 0x8b, 0xdd, 0x01, 0x33, 0x96, 0x0b, 0xf8, 0x39, 0xb4, 0x84, 0xad, 0x78, 0xd5, 0x25, 0xf0, 0x19, 0x26, 0x1c, 0x24, 0xdb, 0x1e, 0x54, 0x8d, 0xc1, 0x97, 0xfd, 0x3d, 0x77, 0x3e, 0x39, 0x87, 0xdd, 0x9b, 0x50, 0xf7, 0xed, 0x99, 0x1b, 0xda, 0x66, 0xcc, 0xb5, 0x66, 0x80, 0x00, 0x0d, 0x88, 0xf7, 0xaf, 0x2b, 0x50, 0x23, 0x3e, 0x27, 0xa1, 0x15, 0xb2, 0xe3, 0x5b, 0x78, 0xa1, 0x33, 0x13, 0x87, 0x5d, 0x36, 0x64, 0x8b, 0xc4, 0x8e, 0xf4, 0x8e, 0x31, 0xab, 0x8c, 0x89, 0xdb, 0xda, 0x26, 0xac, 0x2e, 0x3c, 0xde, 0xde, 0xaa, 0x81, 0xbf, 0xc4, 0x90, 0x23, 0xd7, 0x1f, 0x9b, 0x8e, 0xf7, 0xf4, 0x63, 0x36, 0xff, 0x4d, 0x1a, 0x92, 0x40, 0x7d, 0x84, 0xa4, 0x09, 0xee, 0xb1, 0xed, 0x57, 0x09, 0xee, 0x11, 0x81, 0xe7, 0xdb, 0x13, 0xe7, 0x99, 0xe0, 0xb0, 0x2e, 0x08, 0x04, 0x28, 0xe2, 0x90, 0x10, 0xdc, 0x6b, 0x6f, 0x64, 0x08, 0xee, 0xd1, 0x3a, 0x02, 0xdb, 0x77, 0x50, 0x49, 0xaa, 0xc2, 0x27, 0x89, 0x96, 0xf6, 0x3d, 0x68, 0xe2, 0x38, 0xb6, 0xf3, 0xd4, 0x96, 0xb3, 0xab, 0xf1, 0x62, 0x1a, 0x11, 0x90, 0xb9, 0x67, 0x88, 0xee, 0xb5, 0x21, 0x47, 0x74, 0x8f, 0x88, 0x04, 0x4f, 0x73, 0xee, 0x86, 0xce, 0xe4, 0x79, 0xbb, 0x2e, 0x88, 0x04, 0xf0, 0x88, 0x61, 0x34, 0xcf, 0x91, 0x35, 0x3a, 0xb3, 0x4d, 0x9f, 0xcc, 0x60, 0xbb, 0xc1, 0x24, 0xc0, 0x20, 0x36, 0x8c, 0xda, 0xdb, 0xb0, 0x19, 0x13, 0xf0, 0xb1, 0xb6, 0x9b, 0x4c, 0xd3, 0x8c, 0x68, 0x84, 0x4f, 0xbf, 0x01, 0x75, 0x7b, 0x3e, 0x36, 0xdd, 0x89, 0x39, 0xb6, 0x42, 0xab, 0xbd, 0xc9, 0x34, 0x35, 0x04, 0x1d, 0x4f, 0xf6, 0x11, 0xa0, 0xed, 0xc0, 0x9a, 0xed, 0xfb, 0xae, 0xdf, 0xde, 0x62, 0x8c, 0x68, 0x68, 0x37, 0x41, 0xce, 0xc6, 0x44, 0xa1, 0xf3, 0x9f, 0xb7, 0x5b, 0x8c, 0xac, 0x0b, 0xd8, 0x57, 0x04, 0x12, 0x47, 0x81, 0x13, 0x91, 0x14, 0xdb, 0x62, 0x82, 0x0c, 0x62, 0x02, 0xfd, 0x1b, 0xa8, 0x18, 0xde, 0xb7, 0x8e, 0xf6, 0x03, 0xa8, 0x8c, 0x50, 0xd2, 0xa4, 0x53, 0x54, 0x6d, 0x80, 0x94, 0x41, 0x83, 0xf1, 0xda, 0xbb, 0xb0, 0x16, 0x90, 0x24, 0xb1, 0x94, 0xd4, 0xef, 0x5e, 0x4a, 0x13, 0xb2, 0x90, 0x19, 0x82, 0x42, 0xbf, 0x05, 0x9b, 0x18, 0xde, 0x11, 0xf7, 0x48, 0x2b, 0x92, 0x48, 0xa2, 0xa4, 0x46, 0x12, 0xe8, 0xaa, 0xb7, 0x62, 0x4a, 0xb9, 0x23, 0xb7, 0x60, 0x03, 0xd7, 0xf1, 0xb4, 0x30, 0x0c, 0x64, 0xc2, 0x08, 0xad, 0xff, 0x92, 0x15, 0x52, 0x1d, 0xe6, 0xe5, 0xec, 0x07, 0x8a, 0xfe, 0xd4, 0x99, 0xd8, 0x2c, 0xfa, 0x65, 0x21, 0xfa, 0x51, 0x5b, 0xdf, 0xe6, 0xf0, 0x4b, 0x9d, 0x98, 0xde, 0x8d, 0x74, 0xf5, 0x95, 0x47, 0x4c, 0x02, 0xa0, 0x14, 0xe3, 0xf7, 0x23, 0xeb, 0x7e, 0x21, 0xc6, 0xc4, 0x44, 0x25, 0x97, 0x4c, 0xee, 0xc4, 0x86, 0xff, 0x62, 0x5c, 0x30, 0x76, 0x4a, 0xd1, 0x4b, 0x36, 0xef, 0x41, 0x8b, 0xe5, 0xf7, 0x62, 0x4c, 0xd0, 0x7c, 0x29, 0xd4, 0x49, 0x9c, 0x14, 0xc7, 0x07, 0x17, 0x63, 0x83, 0x71, 0x52, 0xa6, 0x87, 0x64, 0xf5, 0x20, 0x5a, 0xea, 0x2f, 0xed, 0x27, 0xbe, 0x15, 0x31, 0x6a, 0x41, 0x79, 0xe1, 0x4f, 0x25, 0x13, 0xfa, 0xc9, 0xc2, 0xee, 0x2e, 0xd0, 0x14, 0x92, 0x65, 0x0f, 0x70, 0xcb, 0xcb, 0x6c, 0x0b, 0x09, 0x44, 0x7e, 0x97, 0x57, 0x9b, 0x62, 0x24, 0xf9, 0x6f, 0x41, 0x13, 0xc5, 0xef, 0xb1, 0x3f, 0x89, 0xdc, 0xe7, 0x47, 0x2c, 0xb9, 0x0c, 0x90, 0xe2, 0x78, 0x13, 0x2a, 0xe8, 0xe8, 0x22, 0x59, 0x6c, 0x26, 0xb2, 0x48, 0x44, 0x8c, 0xc2, 0x05, 0x93, 0x1b, 0x4b, 0xb8, 0xe0, 0x74, 0xca, 0x88, 0x90, 0x1a, 0x95, 0xe9, 0x42, 0x18, 0xe9, 0x4a, 0x94, 0x61, 0x70, 0x60, 0xe9, 0x4a, 0x5e, 0x86, 0x4d, 0xec, 0x3d, 0x54, 0x4e, 0x5d, 0xd8, 0xc1, 0x25, 0xec, 0xa3, 0xc1, 0x9c, 0xdb, 0xe3, 0x13, 0x3b, 0xf6, 0xf7, 0xef, 0x4a, 0x6f, 0x29, 0x7c, 0xfd, 0x6e, 0xc2, 0x4e, 0x92, 0xd2, 0x46, 0x49, 0xd7, 0xd8, 0x85, 0xdd, 0x0c, 0x8b, 0x58, 0x37, 0x2b, 0x78, 0x44, 0xd1, 0x66, 0xec, 0xe4, 0x78, 0x10, 0x2d, 0x53, 0xe8, 0x3f, 0x83, 0x1d, 0x5c, 0x61, 0x7e, 0x16, 0x3f, 0x80, 0x32, 0xd9, 0x4b, 0xb1, 0xa6, 0x62, 0x06, 0x44, 0x40, 0x22, 0x91, 0xe9, 0x2f, 0x97, 0x77, 0x82, 0xe1, 0x18, 0xaf, 0xf9, 0x95, 0x79, 0x93, 0xfc, 0x58, 0xd3, 0x29, 0x2b, 0x66, 0xd5, 0xa0, 0x9f, 0x14, 0x80, 0xe6, 0x99, 0xca, 0x01, 0xbf, 0x80, 0xb6, 0x61, 0x7b, 0x53, 0x6b, 0xf4, 0xea, 0x23, 0x52, 0xc8, 0x5c, 0xc0, 0x43, 0x0e, 0xb0, 0xcb, 0x97, 0x61, 0x36, 0xa0, 0x74, 0xa7, 0x8d, 0x44, 0xf1, 0x4b, 0x3e, 0x47, 0x05, 0x2c, 0xcf, 0xe0, 0x23, 0x80, 0x20, 0x02, 0x46, 0x27, 0xa1, 0x18, 0xe3, 0xa4, 0x83, 0x42, 0xa6, 0x3f, 0xe4, 0x9b, 0x52, 0x76, 0x0c, 0xed, 0x43, 0xa8, 0xc5, 0x44, 0x72, 0x15, 0x85, 0xac, 0x12, 0x2a, 0xfd, 0x32, 0x1f, 0x6c, 0x6e, 0x5a, 0xfa, 0xef, 0x47, 0xf7, 0xa6, 0xd7, 0x30, 0x48, 0xc1, 0x09, 0x5d, 0x8d, 0x8e, 0x3d, 0x3f, 0xf2, 0x01, 0x5c, 0x91, 0x9b, 0xfb, 0x3a, 0xd6, 0xd7, 0x89, 0x8f, 0x3b, 0x3f, 0x92, 0x06, 0x2d, 0x3c, 0x12, 0x19, 0x45, 0xca, 0x63, 0x42, 0xaf, 0xa0, 0xc0, 0xe4, 0x19, 0xbd, 0x07, 0x55, 0x8f, 0x20, 0x8e, 0x1d, 0x9d, 0x50, 0x4b, 0x89, 0x8b, 0x05, 0x6d, 0x4c, 0xa1, 0x3f, 0x83, 0x16, 0x5d, 0xf5, 0x55, 0xb6, 0xa8, 0x69, 0xeb, 0x8c, 0x7f, 0x2e, 0xa7, 0x9d, 0xef, 0x2f, 0xf1, 0xda, 0x4f, 0xe0, 0x2a, 0x46, 0x47, 0xb6, 0x6f, 0xda, 0xcf, 0x9c, 0x20, 0xc4, 0x58, 0xd6, 0x54, 0xc4, 0x43, 0xec, 0xe0, 0x15, 0x26, 0xe8, 0x49, 0xfc, 0x49, 0x22, 0x16, 0x68, 0x40, 0x94, 0x91, 0xe5, 0x2a, 0xff, 0xac, 0x84, 0xae, 0x41, 0x5c, 0xd3, 0x5f, 0x71, 0x4a, 0x1f, 0xc0, 0x25, 0x8f, 0x22, 0x0d, 0x74, 0xd3, 0xf9, 0xc9, 0x68, 0x11, 0x2a, 0x99, 0x47, 0x74, 0xde, 0xe5, 0xe4, 0xbc, 0x51, 0xcc, 0xd2, 0x73, 0x90, 0x93, 0xfb, 0x87, 0x12, 0xdd, 0xc2, 0xf9, 0x7c, 0xfe, 0x0f, 0x36, 0x6c, 0xd9, 0xca, 0xca, 0xcb, 0x56, 0x26, 0x52, 0x00, 0xa9, 0xe9, 0xca, 0x85, 0x7c, 0x0d, 0x9d, 0x58, 0x6e, 0xba, 0x41, 0xe0, 0x9c, 0xce, 0x55, 0xc1, 0xfd, 0x09, 0x80, 0x15, 0x03, 0xe5, 0x8a, 0x3a, 0xd9, 0x15, 0x29, 0xdd, 0x14, 0x6a, 0x0c, 0xec, 0xae, 0x15, 0x72, 0x96, 0xb2, 0xf9, 0xdf, 0x61, 0x8d, 0x93, 0x8e, 0xe5, 0xe5, 0xf5, 0x4e, 0xfa, 0x3a, 0x5c, 0x2b, 0xe4, 0x2c, 0x77, 0x6b, 0x06, 0xd7, 0x55, 0x71, 0x78, 0xad, 0x63, 0x17, 0x58, 0x9b, 0xb7, 0xe0, 0xc6, 0xb2, 0xe1, 0xe4, 0x84, 0x7e, 0x0f, 0x6e, 0xa4, 0xce, 0xf5, 0xf5, 0xee, 0xc6, 0x4d, 0x78, 0x73, 0x29, 0xf7, 0x94, 0x2d, 0x3a, 0xe1, 0x50, 0x38, 0xb2, 0x45, 0x9f, 0xb3, 0x2d, 0x8a, 0x60, 0xb1, 0xcf, 0x5e, 0x3f, 0x9d, 0xba, 0x4f, 0xac, 0x69, 0x5e, 0x31, 0x1e, 0x30, 0xdc, 0x90, 0x78, 0xf4, 0xd9, 0x1a, 0x4a, 0xae, 0x9f, 0x66, 0xfa, 0x12, 0xfd, 0xd1, 0x91, 0xa5, 0xfa, 0x27, 0x79, 0x8a, 0x93, 0xd0, 0xf5, 0xd2, 0x53, 0xdd, 0xa1, 0xb1, 0x12, 0xa0, 0x24, 0xfd, 0x75, 0x19, 0xef, 0xdd, 0x32, 0x7b, 0x38, 0x9f, 0xfa, 0x4e, 0x94, 0xea, 0xa4, 0xdf, 0x74, 0x87, 0xf0, 0xac, 0x30, 0xf4, 0x45, 0x7c, 0xd7, 0x30, 0x64, 0x8b, 0x8f, 0xef, 0x34, 0x8a, 0xe0, 0xe9, 0x27, 0xf5, 0x7e, 0x82, 0x83, 0xf0, 0x05, 0xb5, 0x6a, 0xf0, 0x6f, 0x0a, 0x11, 0x9d, 0xc0, 0xfc, 0xce, 0x09, 0xcf, 0xc6, 0xbe, 0xf5, 0x1d, 0x5f, 0x4d, 0xab, 0x06, 0x38, 0xc1, 0xef, 0x48, 0x08, 0xde, 0xc4, 0xe0, 0xa9, 0x35, 0x75, 0xf0, 0x1a, 0x46, 0xd9, 0xb5, 0x75, 0xce, 0xdc, 0x28, 0x10, 0x0d, 0xc3, 0xda, 0xb9, 0x6b, 0x3a, 0x33, 0x8f, 0xac, 0x76, 0x98, 0x70, 0xda, 0x10, 0xba, 0x3f, 0x77, 0xfb, 0x12, 0x15, 0x73, 0x4c, 0x2e, 0x3d, 0xd5, 0x54, 0xfa, 0xf4, 0x3a, 0x7a, 0x70, 0xce, 0xa9, 0x98, 0x56, 0x30, 0xe7, 0x7b, 0x6a, 0x13, 0x3d, 0x10, 0x43, 0xba, 0xc1, 0x9c, 0x32, 0x48, 0x12, 0xed, 0x8c, 0xf9, 0x82, 0x5a, 0x33, 0xaa, 0x02, 0xd0, 0x1f, 0xcb, 0x0c, 0x52, 0x68, 0xfb, 0xf6, 0x98, 0xef, 0xa5, 0x55, 0x23, 0x6e, 0xd3, 0x5d, 0x11, 0x6d, 0xd2, 0xd4, 0xe6, 0xdb, 0x68, 0xd5, 0x10, 0x0d, 0x3c, 0xbf, 0x16, 0x2e, 0x7c, 0xe2, 0xbb, 0x33, 0x34, 0x78, 0x48, 0x38, 0xc7, 0x93, 0x6c, 0x32, 0xc1, 0xa6, 0x13, 0xdc, 0x47, 0x70, 0x4f, 0x42, 0x69, 0x8b, 0xe6, 0x32, 0xc5, 0x85, 0xb7, 0x63, 0xbe, 0x8b, 0x62, 0x14, 0x1d, 0x81, 0xfa, 0x9e, 0xfe, 0xb7, 0x25, 0xa8, 0xef, 0xdb, 0x64, 0x13, 0xc5, 0x96, 0xd0, 0x89, 0xf0, 0xcd, 0x5c, 0xc6, 0xe2, 0xb2, 0x95, 0xe4, 0x84, 0x56, 0xcf, 0xc9, 0x09, 0x69, 0xef, 0xc0, 0xd6, 0xd4, 0x9d, 0x9f, 0xa2, 0x21, 0x16, 0xdd, 0xec, 0xc8, 0x8e, 0x6e, 0x0a, 0xf0, 0x40, 0x42, 0x31, 0x72, 0x6d, 0x05, 0x67, 0x78, 0x7d, 0x52, 0x29, 0xc5, 0xd1, 0x6e, 0x49, 0x78, 0x44, 0xaa, 0xff, 0x63, 0x09, 0xd6, 0x86, 0x14, 0xe7, 0xd3, 0xb5, 0x56, 0x09, 0x77, 0x8b, 0x52, 0x5b, 0x8c, 0x8f, 0x13, 0xff, 0xab, 0x49, 0xe2, 0x7f, 0x69, 0xde, 0xfb, 0xb7, 0xa0, 0x31, 0x4e, 0x96, 0x4f, 0x93, 0xa0, 0xe5, 0xa5, 0x42, 0xe9, 0x18, 0x6b, 0xa4, 0x48, 0x39, 0xaf, 0xe1, 0x06, 0xa1, 0x29, 0x7d, 0x94, 0x14, 0x3f, 0x02, 0x09, 0x0d, 0xd7, 0xef, 0xf1, 0x55, 0xc4, 0x70, 0x9e, 0x44, 0x7a, 0xf7, 0x36, 0xac, 0x85, 0xb4, 0x12, 0xa9, 0x76, 0x5b, 0xc9, 0x28, 0xbc, 0x40, 0x43, 0x60, 0xf5, 0x4f, 0xc5, 0x5d, 0x9b, 0xfa, 0x49, 0x85, 0xbf, 0x60, 0xc7, 0x29, 0x68, 0x8f, 0x85, 0x74, 0xdb, 0xca, 0xa8, 0x17, 0xdd, 0xb6, 0x65, 0xef, 0x28, 0x89, 0x48, 0x94, 0x55, 0x91, 0x20, 0xdb, 0x90, 0x1a, 0x4d, 0x2a, 0xfc, 0x3f, 0x93, 0xc2, 0xdb, 0xb6, 0xcf, 0x72, 0x4d, 0x1c, 0xa2, 0x88, 0xa9, 0x69, 0xc4, 0x6d, 0xed, 0xc7, 0xd0, 0xb0, 0x3c, 0x6f, 0xfa, 0x3c, 0xda, 0x3c, 0x91, 0x80, 0x50, 0xb6, 0xbd, 0x4b, 0x58, 0xe9, 0x5f, 0xeb, 0x56, 0xd2, 0x88, 0x73, 0x1b, 0xe5, 0x6c, 0x6e, 0x83, 0xc6, 0x54, 0x72, 0x1b, 0x9f, 0x41, 0xd3, 0x46, 0x8c, 0x39, 0x5b, 0x4c, 0x43, 0xe7, 0xcc, 0xf5, 0xe4, 0xcb, 0xc6, 0xe5, 0xa4, 0x43, 0x0f, 0xff, 0x1e, 0x4a, 0xac, 0xd1, 0xb0, 0x95, 0x96, 0xd6, 0x85, 0x2d, 0x71, 0xf9, 0xc4, 0x95, 0x4e, 0xed, 0x51, 0xe8, 0xfa, 0x7c, 0xbc, 0xf5, 0xbb, 0x6d, 0x65, 0xf7, 0x88, 0xc0, 0x88, 0xf0, 0xc6, 0xa6, 0x9f, 0x6a, 0xa3, 0x2a, 0x54, 0x9c, 0xf9, 0xc4, 0x65, 0xab, 0x93, 0x0a, 0x51, 0x69, 0x9e, 0x22, 0xb5, 0xc2, 0x04, 0x64, 0x8c, 0x29, 0x3d, 0x81, 0x36, 0x70, 0x23, 0x6b, 0x8c, 0x87, 0x0c, 0x37, 0x24, 0x9e, 0x42, 0xdf, 0xd0, 0xb7, 0xe6, 0x01, 0xe7, 0x20, 0xaa, 0x59, 0xbe, 0xc3, 0x08, 0x65, 0x24, 0x54, 0xb4, 0xcf, 0x62, 0x21, 0x22, 0xc1, 0xc2, 0x96, 0x29, 0xb5, 0xcf, 0xbc, 0x0a, 0x69, 0xb2, 0xc5, 0x85, 0x5b, 0x34, 0xf4, 0x7f, 0x45, 0xc3, 0xa0, 0x1c, 0x82, 0xf6, 0x29, 0xd4, 0x9c, 0xb9, 0x99, 0x8a, 0xc7, 0xce, 0x73, 0x7d, 0x55, 0x67, 0x2e, 0x3b, 0xfe, 0x36, 0x1e, 0xc4, 0x33, 0x9a, 0x4c, 0xfa, 0xac, 0xcf, 0xeb, 0xdc, 0x10, 0x1d, 0x12, 0x06, 0x68, 0xa2, 0x15, 0x06, 0xe5, 0x17, 0x33, 0x10, 0x1d, 0xa4, 0x1e, 0xfe, 0x09, 0xd4, 0x85, 0x35, 0x39, 0x70, 0x66, 0xce, 0xd2, 0xc4, 0x15, 0x65, 0xe0, 0x66, 0xd6, 0xb3, 0xc4, 0x1e, 0x09, 0x2d, 0xa8, 0x23, 0x2c, 0x36, 0x5b, 0x1f, 0xc3, 0xe5, 0x40, 0xbe, 0x6a, 0x98, 0xe1, 0x19, 0x86, 0x86, 0x67, 0xee, 0x74, 0x6c, 0x7a, 0xa3, 0x50, 0x5a, 0x95, 0x9d, 0x08, 0x3b, 0x8c, 0x90, 0x83, 0x51, 0xa8, 0xff, 0x5b, 0x05, 0xaa, 0x91, 0x74, 0x52, 0x2a, 0xd2, 0x5a, 0x84, 0x67, 0xa6, 0x87, 0xb1, 0xc1, 0x77, 0xae, 0x3f, 0x96, 0x76, 0xb6, 0x41, 0xc0, 0x81, 0x84, 0x69, 0x6f, 0x41, 0x1d, 0x4d, 0xcd, 0xc8, 0x77, 0xbc, 0xf8, 0x5d, 0xa8, 0x66, 0xa8, 0x20, 0xed, 0x2a, 0x54, 0xa7, 0xee, 0xc8, 0x9a, 0xa2, 0xbf, 0x91, 0x63, 0x6f, 0x70, 0xbb, 0xcb, 0xb6, 0x35, 0xb6, 0xf9, 0x51, 0x76, 0xa6, 0xc2, 0x1c, 0xb6, 0x22, 0x78, 0x57, 0x26, 0xb4, 0xae, 0xc0, 0x06, 0xbd, 0x90, 0x11, 0x13, 0x91, 0xd8, 0x5d, 0xa7, 0x26, 0xf2, 0x40, 0x7f, 0xc6, 0x88, 0x53, 0x14, 0x09, 0x8f, 0x65, 0xb8, 0x66, 0xd4, 0x08, 0xf2, 0x80, 0x00, 0xe4, 0xcf, 0x18, 0xcd, 0x76, 0x45, 0x24, 0x74, 0xab, 0x04, 0xe0, 0x17, 0x91, 0xdb, 0xb0, 0x4d, 0x29, 0x6b, 0x0c, 0xa7, 0x3d, 0xdf, 0x79, 0x8a, 0x82, 0x4e, 0xec, 0x85, 0xbb, 0xdc, 0x12, 0x88, 0x81, 0x80, 0xe3, 0x38, 0xef, 0x81, 0x26, 0xe4, 0x73, 0x32, 0xb5, 0x3c, 0x73, 0x6c, 0xcd, 0x3c, 0x0c, 0xce, 0x59, 0x4a, 0xab, 0x46, 0x8b, 0x31, 0xf7, 0x11, 0xb1, 0x2f, 0xe0, 0x94, 0x80, 0x0d, 0x28, 0xb5, 0x3a, 0x72, 0x67, 0xb3, 0xc5, 0xdc, 0x09, 0x9f, 0xb3, 0x2f, 0x6d, 0x1a, 0x4d, 0x82, 0xee, 0x45, 0x40, 0x9a, 0xbc, 0x4c, 0xa3, 0x8f, 0x2c, 0x0f, 0x5d, 0x2a, 0x45, 0x16, 0x35, 0x01, 0xd9, 0xb3, 0x78, 0xf2, 0x62, 0xeb, 0x08, 0xdb, 0x60, 0xac, 0xd8, 0x4b, 0x42, 0x6e, 0xc2, 0x2a, 0xba, 0xe8, 0x26, 0x2f, 0x18, 0x7f, 0x61, 0xc8, 0xd7, 0x94, 0xc9, 0xeb, 0x29, 0x09, 0x4f, 0x80, 0x2e, 0x34, 0xe3, 0x20, 0x14, 0xd1, 0x32, 0x1a, 0x5e, 0xd2, 0x08, 0xe8, 0xa8, 0xe5, 0x19, 0xc9, 0x53, 0xd8, 0x12, 0x47, 0x2d, 0x0e, 0x4a, 0x1e, 0xc1, 0xfb, 0xa0, 0x25, 0x1e, 0x9a, 0x1e, 0x87, 0x26, 0x18, 0x22, 0x72, 0xf6, 0xb7, 0x66, 0x6c, 0xc7, 0x8e, 0x3a, 0x42, 0xe8, 0x5f, 0x42, 0x43, 0xb5, 0x5b, 0x94, 0x81, 0xb3, 0x39, 0x0b, 0x26, 0x04, 0xa9, 0x6a, 0x44, 0x4d, 0x16, 0x67, 0x49, 0x65, 0x86, 0xe1, 0x34, 0x16, 0x67, 0x09, 0x1b, 0x86, 0x53, 0xfd, 0xcf, 0x4b, 0xb0, 0x99, 0x36, 0x63, 0x24, 0xe1, 0x19, 0xcb, 0x67, 0x8e, 0xd0, 0x62, 0xcb, 0x70, 0xb7, 0x6a, 0xec, 0xa4, 0xcd, 0xdc, 0x1e, 0xe3, 0xd0, 0xd8, 0x76, 0xf2, 0xbd, 0x16, 0x01, 0xb9, 0xf7, 0xf8, 0x71, 0xe9, 0x4a, 0xb6, 0x27, 0xe3, 0xfb, 0x63, 0xfd, 0x3f, 0xd6, 0xa0, 0x16, 0x1b, 0xc5, 0xff, 0x05, 0xfd, 0xb8, 0x03, 0xd5, 0x19, 0xee, 0x3c, 0x46, 0x95, 0x81, 0x74, 0x0a, 0x8a, 0x17, 0x39, 0x94, 0x18, 0x23, 0xa6, 0x29, 0xd4, 0xa7, 0xb5, 0x17, 0xea, 0xd3, 0xfa, 0x39, 0xfa, 0xb4, 0x71, 0xae, 0x3e, 0x55, 0x33, 0xfa, 0x84, 0x0e, 0x02, 0x1d, 0x39, 0xba, 0x72, 0x69, 0xbd, 0x15, 0x07, 0xf1, 0x15, 0xc3, 0x0d, 0x89, 0x2f, 0xd6, 0x3c, 0x78, 0x19, 0xcd, 0xab, 0x5f, 0x58, 0xf3, 0x1a, 0x45, 0x9a, 0xc7, 0xef, 0x2c, 0x68, 0x86, 0xdd, 0xb9, 0xb8, 0x4a, 0xb3, 0x22, 0x35, 0xe9, 0x9d, 0x85, 0x81, 0xe2, 0x84, 0x3f, 0x41, 0x23, 0xba, 0xf0, 0xc8, 0x3e, 0xdb, 0x63, 0xd2, 0x41, 0xeb, 0x09, 0xc6, 0x04, 0x21, 0x45, 0x09, 0x9b, 0x9c, 0xe4, 0xdd, 0x8d, 0xb1, 0x7b, 0x0a, 0x92, 0xf6, 0x88, 0xfc, 0xb9, 0xe0, 0x2b, 0x34, 0xa9, 0x8a, 0x00, 0xc1, 0x13, 0x63, 0x31, 0x6b, 0x3c, 0x73, 0xa2, 0x61, 0x85, 0xfa, 0x00, 0x83, 0x04, 0x41, 0x87, 0x9e, 0x46, 0xc5, 0x8b, 0x10, 0x3f, 0x9c, 0x34, 0x8d, 0xb8, 0x4d, 0x38, 0x6b, 0x34, 0xb2, 0x3d, 0x1c, 0xb1, 0xad, 0x09, 0x5c, 0xd4, 0xa6, 0x2b, 0x84, 0x35, 0x46, 0x7f, 0x18, 0x3a, 0x01, 0x62, 0x2f, 0x89, 0xb7, 0xab, 0x04, 0xa2, 0x5d, 0x82, 0x35, 0xdc, 0x2b, 0xf3, 0x57, 0xed, 0x1d, 0xf1, 0x26, 0x80, 0x8d, 0xaf, 0x28, 0x6a, 0x9f, 0x4c, 0x5d, 0x2f, 0x68, 0xef, 0x32, 0x50, 0x34, 0xf4, 0x3f, 0x84, 0x6a, 0x24, 0x5d, 0xa8, 0xf5, 0xc9, 0x74, 0x84, 0x33, 0xdd, 0xce, 0xc9, 0xa0, 0x32, 0xc3, 0xb7, 0x29, 0x49, 0x3b, 0x0f, 0xa5, 0xeb, 0x2c, 0x20, 0x65, 0xb4, 0xfe, 0x2f, 0x25, 0xd8, 0x90, 0x10, 0x4d, 0x87, 0xc6, 0xd1, 0xf1, 0xb0, 0x7f, 0xbf, 0xbf, 0xd7, 0x1d, 0xf6, 0x8f, 0x8f, 0x78, 0x94, 0x8a, 0xd1, 0x98, 0x2b, 0x30, 0xf2, 0x84, 0x8f, 0x06, 0xfb, 0xdd, 0x61, 0x8f, 0x19, 0x57, 0x8c, 0xf5, 0x05, 0xb7, 0x28, 0x80, 0x3e, 0x1e, 0xf4, 0x8e, 0xe4, 0x9b, 0x75, 0xc5, 0xc5, 0xdf, 0xda, 0x1b, 0x50, 0xfb, 0xb2, 0xd7, 0x1b, 0x74, 0x0f, 0xfa, 0x8f, 0x7b, 0xac, 0x36, 0x15, 0xa3, 0xf6, 0x6d, 0x04, 0x20, 0x33, 0x64, 0xf4, 0xee, 0x1b, 0xbd, 0x93, 0x87, 0xac, 0x1a, 0x15, 0x63, 0xc3, 0x17, 0x4d, 0xea, 0xb7, 0xdf, 0x3f, 0xd9, 0xeb, 0x1a, 0xfb, 0xbd, 0x7d, 0x56, 0x0a, 0xec, 0x37, 0x8e, 0x00, 0xb4, 0x53, 0xc3, 0xe3, 0x61, 0xf7, 0x80, 0x55, 0xa2, 0x82, 0x71, 0x2c, 0x35, 0x30, 0x70, 0x5e, 0x17, 0x92, 0x4d, 0x78, 0x67, 0xee, 0x2d, 0x42, 0xe9, 0xaa, 0x45, 0x83, 0xe6, 0x8d, 0xfb, 0x4c, 0x60, 0x19, 0xa9, 0x8a, 0x96, 0x6e, 0xc3, 0xba, 0x08, 0x99, 0x50, 0xc7, 0xd7, 0x29, 0x0a, 0x74, 0x4e, 0xe5, 0xee, 0x5e, 0xce, 0x06, 0x55, 0x7b, 0x8c, 0x35, 0x24, 0x95, 0xf6, 0xc3, 0xf4, 0x4b, 0xd8, 0x6e, 0x96, 0x3c, 0xf5, 0x16, 0x86, 0xdb, 0xdc, 0x50, 0xb9, 0x90, 0xd8, 0x23, 0x9f, 0x39, 0xda, 0x35, 0x34, 0x80, 0xa1, 0xff, 0x3c, 0xda, 0x6c, 0x09, 0x34, 0x08, 0x46, 0xf2, 0xcb, 0xd1, 0x42, 0xfc, 0x2c, 0x5b, 0x31, 0xaa, 0x04, 0x20, 0x4e, 0xe4, 0x05, 0xbe, 0xb5, 0x6d, 0x0f, 0xc3, 0x69, 0x54, 0xde, 0xcc, 0x37, 0x03, 0xdb, 0x31, 0xa6, 0x2f, 0x11, 0xda, 0x3e, 0xdc, 0x40, 0xc9, 0x76, 0x66, 0x8b, 0x99, 0x19, 0xcb, 0x22, 0x05, 0x3e, 0x49, 0x57, 0x71, 0x42, 0x6f, 0x48, 0xaa, 0xae, 0x4a, 0x14, 0x71, 0xd1, 0x7f, 0xb3, 0x0a, 0x75, 0x65, 0x79, 0xff, 0x4f, 0x97, 0xc1, 0xb7, 0x78, 0xfb, 0xd4, 0x0d, 0x1d, 0x8b, 0x0c, 0x4a, 0x32, 0x39, 0x21, 0x88, 0x5a, 0x82, 0x7b, 0x18, 0x4d, 0x33, 0x79, 0x38, 0x5f, 0x97, 0x72, 0x9f, 0x7f, 0x38, 0x17, 0x02, 0x19, 0xb7, 0xf5, 0xff, 0x2c, 0x41, 0x2d, 0x0e, 0xb1, 0xf3, 0xae, 0xbd, 0x54, 0xe0, 0xda, 0xd1, 0xe8, 0x0b, 0x22, 0xe5, 0xd1, 0x50, 0x84, 0x1e, 0x03, 0xc9, 0x63, 0x16, 0x2e, 0xcc, 0xb1, 0x13, 0x8c, 0xd0, 0x32, 0xfb, 0xcf, 0xe5, 0x55, 0xb9, 0x81, 0xc0, 0xfd, 0x08, 0x46, 0x5e, 0x9c, 0x3c, 0x21, 0xed, 0xe7, 0xcc, 0x1d, 0xdb, 0xf2, 0x92, 0x5c, 0x97, 0xb0, 0x43, 0x04, 0x91, 0x6d, 0x96, 0xe1, 0x4e, 0xda, 0x3b, 0x35, 0x05, 0xb4, 0x5b, 0xfc, 0x71, 0xc1, 0x7a, 0xf4, 0x90, 0x1f, 0x7d, 0x5c, 0x40, 0xce, 0x2b, 0x1c, 0xe1, 0x85, 0x29, 0x08, 0x64, 0x48, 0xb7, 0x8e, 0xcd, 0xc3, 0x20, 0xd0, 0x3f, 0x87, 0xba, 0x72, 0x4d, 0x40, 0xdd, 0xba, 0xa4, 0xde, 0x29, 0xd2, 0xf1, 0xc1, 0xb6, 0x72, 0x87, 0x10, 0xc1, 0x81, 0xbe, 0x80, 0x75, 0x11, 0x23, 0x91, 0xec, 0x38, 0x9e, 0x99, 0xca, 0x2f, 0x54, 0x1d, 0x4f, 0x22, 0x7f, 0x00, 0x5b, 0x33, 0x2b, 0xf8, 0xd6, 0x9c, 0xda, 0xf3, 0x53, 0xf4, 0xff, 0x78, 0xe4, 0x72, 0xcb, 0x9a, 0x04, 0x3e, 0x60, 0xe8, 0xa1, 0x33, 0xcf, 0xd1, 0x59, 0xcf, 0xa4, 0x83, 0x57, 0xe9, 0xac, 0x67, 0xfa, 0x5f, 0x97, 0x00, 0x92, 0xa7, 0x99, 0x97, 0x78, 0x2b, 0x2b, 0xcc, 0x1f, 0x20, 0x6c, 0xea, 0x04, 0x21, 0x7f, 0x12, 0x83, 0x30, 0xfa, 0xcd, 0x4f, 0x02, 0x49, 0xf2, 0x22, 0xfb, 0x24, 0xc0, 0x18, 0x23, 0xa6, 0xd0, 0x1f, 0xa0, 0xf9, 0xb7, 0xc2, 0xd1, 0x19, 0x4d, 0xe6, 0x9d, 0xd4, 0x64, 0x94, 0x4b, 0x1c, 0x53, 0x9c, 0x3f, 0x15, 0xfd, 0x31, 0x34, 0xba, 0x01, 0x65, 0x5d, 0xc4, 0x5a, 0xf1, 0x3c, 0x54, 0x66, 0xca, 0xb5, 0x48, 0xa5, 0x52, 0x78, 0xa2, 0xf4, 0x8b, 0xbd, 0x8b, 0xac, 0xa7, 0x68, 0xe9, 0x7f, 0x57, 0x01, 0x40, 0x83, 0x36, 0x76, 0x44, 0x7a, 0xe3, 0x43, 0x90, 0xdf, 0x68, 0x98, 0xc9, 0x7b, 0x98, 0x96, 0x99, 0x29, 0xbd, 0x79, 0xd5, 0x04, 0x15, 0x2d, 0xeb, 0x13, 0x68, 0xc4, 0x91, 0x12, 0x75, 0x5a, 0x5d, 0xda, 0x29, 0xce, 0x4a, 0x51, 0xb7, 0x9f, 0xc2, 0xa6, 0x15, 0x98, 0x94, 0x41, 0x92, 0x87, 0x2a, 0x6f, 0x78, 0x97, 0x8b, 0x97, 0x82, 0xb1, 0xa0, 0xba, 0xfc, 0xbb, 0xe8, 0xfa, 0x65, 0x6f, 0x1a, 0xb3, 0xb2, 0x7c, 0xa2, 0xa2, 0x1b, 0x8d, 0xf8, 0x29, 0x59, 0x3a, 0x19, 0xb4, 0x70, 0xaf, 0xb5, 0xa5, 0xbd, 0x1a, 0x31, 0x21, 0x75, 0xfc, 0x19, 0x6c, 0xdb, 0xcf, 0x42, 0x33, 0xdd, 0x79, 0x7d, 0x69, 0xe7, 0x2d, 0x24, 0xde, 0x53, 0xfb, 0x93, 0x12, 0x7a, 0xdf, 0x3a, 0xf4, 0x05, 0x09, 0xc6, 0xe1, 0xac, 0x67, 0x6b, 0xa8, 0x84, 0xe2, 0x81, 0x1c, 0x21, 0xda, 0xe7, 0x00, 0xc9, 0xb3, 0x37, 0x87, 0x82, 0x9b, 0x77, 0x6f, 0x24, 0x9c, 0x93, 0xf3, 0x11, 0x37, 0x77, 0x3e, 0xd6, 0x5a, 0xfc, 0x2a, 0xae, 0x9f, 0x41, 0x2d, 0x86, 0x63, 0x6c, 0xb2, 0x65, 0x1c, 0x3f, 0x1a, 0xf6, 0xcc, 0xe1, 0x37, 0x83, 0x9e, 0x79, 0x74, 0x7c, 0x44, 0x9f, 0x41, 0x5d, 0x81, 0x4b, 0x0a, 0xb0, 0x7f, 0x34, 0xec, 0x19, 0x47, 0xdd, 0x83, 0x56, 0x29, 0x83, 0xe8, 0x7d, 0x2d, 0x11, 0xab, 0xe8, 0x83, 0x5b, 0x0a, 0xe2, 0xe0, 0x78, 0x0f, 0xa1, 0x65, 0x7d, 0x02, 0x5b, 0xf1, 0xca, 0xba, 0xe2, 0x03, 0xc3, 0x0f, 0x53, 0x82, 0x78, 0x5d, 0x9d, 0x75, 0x8a, 0x50, 0x91, 0x45, 0x0c, 0xe4, 0xa3, 0xbd, 0x74, 0xe2, 0x57, 0x7e, 0x15, 0xa4, 0x1f, 0x41, 0xed, 0xd0, 0x1e, 0xcb, 0x11, 0x7e, 0x98, 0x1a, 0xe1, 0x8a, 0x1a, 0x07, 0x8d, 0x73, 0xbc, 0x31, 0x76, 0x40, 0xf7, 0xb0, 0x88, 0xbe, 0x81, 0x12, 0x0d, 0xdd, 0x84, 0x2d, 0x14, 0x26, 0xdf, 0xf6, 0x30, 0x70, 0x95, 0x5c, 0x29, 0xdb, 0x1c, 0xcc, 0x65, 0x88, 0x41, 0x3f, 0x49, 0x45, 0x88, 0xc2, 0x8a, 0x03, 0x0c, 0xd1, 0xc2, 0xa0, 0xaa, 0xb9, 0x08, 0x6c, 0x94, 0xd2, 0x49, 0x88, 0xe6, 0x38, 0x08, 0xa5, 0xc9, 0xae, 0x23, 0xf0, 0x00, 0x61, 0x87, 0x2e, 0x67, 0xec, 0x9b, 0x47, 0x78, 0xec, 0x78, 0xc5, 0x92, 0xec, 0xcf, 0xfd, 0x9e, 0x24, 0xb0, 0xa7, 0x13, 0xf9, 0x4c, 0xc1, 0xbf, 0xf5, 0x77, 0x60, 0xeb, 0x80, 0x5d, 0x04, 0x6a, 0x95, 0x64, 0x10, 0x2f, 0x44, 0x06, 0x41, 0x62, 0x21, 0x7f, 0x51, 0x86, 0x0d, 0x41, 0x10, 0x24, 0x69, 0x1e, 0x4b, 0x7c, 0x48, 0x9a, 0x33, 0x72, 0x2c, 0x14, 0x82, 0x5a, 0xa6, 0x79, 0x24, 0xef, 0x4f, 0xa1, 0x96, 0xc4, 0xf4, 0x42, 0x5f, 0xaf, 0x2e, 0x3d, 0x38, 0x23, 0xa1, 0x45, 0xaf, 0x53, 0x9e, 0x61, 0xf0, 0x5a, 0xce, 0xa6, 0xa1, 0xe2, 0x93, 0x30, 0x08, 0x8f, 0x33, 0x03, 0xd2, 0x4e, 0xb1, 0xdf, 0x52, 0x39, 0xaf, 0xa6, 0xf4, 0x5a, 0x3d, 0x0a, 0xd6, 0x51, 0x01, 0x40, 0x55, 0x6b, 0xa6, 0x54, 0x4d, 0xea, 0xe8, 0x39, 0xb3, 0x6b, 0xa8, 0xda, 0x86, 0xd2, 0xb8, 0x31, 0x17, 0xe7, 0x20, 0x15, 0x54, 0x11, 0x97, 0xd4, 0x01, 0x19, 0x11, 0x1d, 0x4d, 0x56, 0x3a, 0x6c, 0xdc, 0x7c, 0x99, 0x8e, 0x53, 0xc6, 0xcb, 0x9c, 0x4b, 0xe4, 0xcb, 0x11, 0x40, 0x0f, 0xac, 0xb5, 0xf8, 0x89, 0x30, 0xb6, 0xda, 0x25, 0xc5, 0x81, 0x7c, 0x0c, 0x30, 0x8a, 0x95, 0x57, 0xee, 0xf4, 0x4e, 0x91, 0x62, 0x1b, 0x0a, 0x1d, 0x0a, 0xfc, 0x86, 0x38, 0xd2, 0x40, 0xee, 0xb4, 0x12, 0xfb, 0xcb, 0xc3, 0x37, 0x22, 0x0a, 0xfd, 0x2b, 0x74, 0xb4, 0x22, 0x65, 0x56, 0x34, 0x81, 0xf4, 0x47, 0x06, 0xab, 0x17, 0xfb, 0xc8, 0xe0, 0xdf, 0x4b, 0xd0, 0xca, 0x66, 0xd7, 0xe8, 0x93, 0x11, 0x45, 0x0b, 0x77, 0xb2, 0x79, 0x38, 0x45, 0x05, 0xd5, 0x0f, 0x52, 0x57, 0x2f, 0xf0, 0x41, 0x6a, 0xc1, 0x27, 0xfb, 0xa9, 0x87, 0xf7, 0xca, 0x8b, 0x1e, 0xde, 0xb5, 0x0f, 0x60, 0x63, 0x6c, 0x4f, 0x2c, 0x32, 0xae, 0x6b, 0xe7, 0x29, 0x41, 0x44, 0xa5, 0xff, 0x65, 0x09, 0xca, 0x86, 0x6b, 0x51, 0xe2, 0xc7, 0x0a, 0xa4, 0x86, 0xe1, 0x2f, 0xba, 0xb7, 0x08, 0xc7, 0x86, 0x2e, 0x29, 0x8a, 0xdd, 0x62, 0x00, 0x19, 0x08, 0x0c, 0x3c, 0x08, 0x25, 0x9f, 0x13, 0x44, 0x4b, 0xc9, 0x95, 0x57, 0x52, 0xcf, 0x27, 0x51, 0xd6, 0x7a, 0xed, 0xfc, 0x2f, 0xf2, 0x50, 0xfb, 0xf9, 0xc9, 0xc0, 0xb5, 0x5e, 0xf4, 0x95, 0x9d, 0xf8, 0xaa, 0x89, 0x09, 0x93, 0xaf, 0x9a, 0x7c, 0xd7, 0x2a, 0xf8, 0xaa, 0x89, 0x88, 0x18, 0xa5, 0x8f, 0xa0, 0xfc, 0xd8, 0x9f, 0x14, 0x4a, 0x07, 0x2e, 0xdf, 0x17, 0x99, 0x9a, 0x86, 0x81, 0xbf, 0x38, 0x54, 0x13, 0x49, 0x57, 0x5f, 0x04, 0x3d, 0x0d, 0x0c, 0xd5, 0x18, 0x60, 0xf0, 0x07, 0xd1, 0x32, 0xa5, 0xeb, 0x87, 0x7c, 0x26, 0x88, 0x14, 0x00, 0x23, 0xd4, 0xff, 0x66, 0x15, 0xd6, 0xc5, 0x2b, 0x62, 0x6e, 0x4f, 0xb1, 0x1f, 0xdb, 0x1e, 0x25, 0x2b, 0x54, 0x15, 0x80, 0xfe, 0x98, 0x5c, 0x23, 0x45, 0x55, 0xf6, 0x5c, 0xc4, 0xa7, 0x65, 0xe1, 0x1a, 0x05, 0x88, 0xe3, 0xd3, 0x77, 0xa1, 0x25, 0x09, 0xa4, 0xfd, 0x94, 0x02, 0x51, 0x33, 0xb6, 0x04, 0xbc, 0x1b, 0x81, 0x53, 0x4f, 0x0f, 0x6b, 0x99, 0xa7, 0x87, 0xef, 0xc3, 0xe6, 0xcc, 0x9b, 0x06, 0xe6, 0xd4, 0x7a, 0x62, 0x4f, 0x39, 0xcc, 0x14, 0xa1, 0x70, 0x83, 0xa0, 0x07, 0x04, 0xa4, 0x28, 0x33, 0x43, 0x85, 0x41, 0xe6, 0x46, 0x96, 0xca, 0x7a, 0x46, 0x49, 0x14, 0xf2, 0x07, 0x9c, 0x53, 0xf3, 0xa6, 0xb6, 0x29, 0x9e, 0xc8, 0xaa, 0x22, 0x89, 0x82, 0x98, 0x43, 0x89, 0xa0, 0xb8, 0x23, 0xb8, 0xbd, 0x07, 0xd5, 0x48, 0xe6, 0x35, 0xc0, 0x4d, 0x3a, 0x38, 0xfe, 0x02, 0x5d, 0xe9, 0x8a, 0x56, 0x83, 0x35, 0xe1, 0x55, 0x4b, 0x04, 0xee, 0xee, 0xff, 0x02, 0xdd, 0x32, 0xfa, 0xdd, 0x3a, 0xda, 0x77, 0xfc, 0x4d, 0xdf, 0xea, 0x97, 0xe9, 0x33, 0xe6, 0xc7, 0xc6, 0xfd, 0x56, 0xe5, 0xb6, 0x49, 0xef, 0x75, 0x71, 0xc4, 0x4a, 0x1d, 0x06, 0x78, 0xf3, 0xee, 0x7f, 0x8d, 0x7c, 0x1a, 0x50, 0x3d, 0xea, 0xf5, 0x1f, 0x3c, 0xfc, 0xe2, 0xd8, 0x40, 0x56, 0xd8, 0x63, 0xd8, 0x7d, 0x20, 0xf9, 0x9c, 0x98, 0x83, 0xee, 0xf0, 0x21, 0xf2, 0x69, 0x42, 0x6d, 0xef, 0xf8, 0xf0, 0xf0, 0xd1, 0x51, 0x7f, 0xf8, 0x4d, 0xab, 0xa2, 0x6d, 0x43, 0x13, 0x3d, 0xbd, 0x99, 0x80, 0xd6, 0x6e, 0xbf, 0x8b, 0x0e, 0x37, 0x8a, 0x42, 0x89, 0x49, 0xf7, 0xe8, 0x1b, 0x51, 0x34, 0xd0, 0x3d, 0x90, 0x33, 0xec, 0x1f, 0x3d, 0xee, 0x19, 0xc3, 0xd6, 0xea, 0xed, 0xdb, 0xd0, 0xca, 0xc6, 0x98, 0x54, 0x65, 0xd0, 0xfb, 0x0a, 0x3b, 0xe0, 0xdf, 0x07, 0x3d, 0xa4, 0xc7, 0xbf, 0x07, 0x3d, 0xa4, 0xfd, 0x40, 0x5e, 0x22, 0xa4, 0xdf, 0xa9, 0x42, 0x45, 0x06, 0x24, 0xb4, 0xe4, 0xbd, 0xbd, 0xde, 0x60, 0x28, 0x98, 0x1b, 0xbd, 0x5f, 0xf4, 0xf6, 0x88, 0xf9, 0x23, 0xb8, 0x54, 0x10, 0x37, 0xd0, 0x8c, 0xe3, 0xd9, 0x9a, 0xdd, 0xfd, 0x7d, 0xe4, 0x80, 0x01, 0x4a, 0x02, 0x32, 0x7a, 0x87, 0xc7, 0x8f, 0x69, 0xe0, 0x5d, 0xd8, 0x56, 0xa1, 0x83, 0x83, 0xee, 0x1e, 0xcd, 0xe3, 0x7d, 0x68, 0xa6, 0x82, 0x05, 0xda, 0x9e, 0xc3, 0xde, 0xbe, 0x79, 0x78, 0x4c, 0xac, 0xb6, 0xa0, 0x4e, 0x8d, 0x88, 0xbc, 0x74, 0xfb, 0x3d, 0x80, 0xc4, 0xaa, 0xc5, 0x25, 0x14, 0xb4, 0x09, 0x87, 0x83, 0x63, 0x43, 0xce, 0xb9, 0xf7, 0x35, 0xff, 0x5e, 0xbd, 0xfb, 0x57, 0x6f, 0x42, 0xf5, 0x01, 0xe9, 0x5d, 0xd7, 0x73, 0xb4, 0x03, 0xa8, 0x2b, 0x6f, 0xe7, 0xda, 0x1b, 0x29, 0x5b, 0x9b, 0x79, 0x92, 0xef, 0x5c, 0x5f, 0x82, 0x95, 0x8f, 0x6a, 0x2b, 0x5a, 0x1f, 0x20, 0x79, 0x5d, 0xd7, 0xae, 0xa9, 0xe4, 0x99, 0x87, 0xf8, 0xce, 0x1b, 0xc5, 0xc8, 0x98, 0xd5, 0x7d, 0xa8, 0xc5, 0xdf, 0x14, 0x68, 0xca, 0x7d, 0x21, 0xfb, 0xf1, 0x41, 0xe7, 0x5a, 0x21, 0x2e, 0xe6, 0x83, 0x0b, 0x54, 0x6a, 0x75, 0xd4, 0x05, 0xe6, 0x8b, 0x7f, 0xd4, 0x05, 0x16, 0x15, 0xf8, 0xac, 0x68, 0x8f, 0x60, 0x33, 0x5d, 0xa5, 0xa3, 0xbd, 0xa9, 0x5e, 0xd2, 0x0a, 0x8a, 0x7f, 0x3a, 0x6f, 0x2d, 0x27, 0x50, 0x27, 0xa9, 0xd4, 0xa5, 0xa9, 0x93, 0xcc, 0x17, 0xb1, 0xa9, 0x93, 0x2c, 0x28, 0x66, 0x43, 0x6e, 0x06, 0x34, 0x53, 0x45, 0x32, 0xda, 0x8d, 0x94, 0x3f, 0xcb, 0x73, 0x7c, 0x73, 0x29, 0x3e, 0xe6, 0xf9, 0x07, 0xb0, 0x9d, 0x2b, 0xbe, 0xd1, 0xf4, 0x17, 0x17, 0x01, 0x75, 0xbe, 0x77, 0x2e, 0x4d, 0xcc, 0xff, 0x77, 0xa1, 0x95, 0x2d, 0xc5, 0xd1, 0x6e, 0x2a, 0x5d, 0x8b, 0x6b, 0x7b, 0x3a, 0xfa, 0x79, 0x24, 0xea, 0xa9, 0xa5, 0x0b, 0x73, 0xd4, 0x53, 0x2b, 0xac, 0xf2, 0x51, 0x4f, 0x6d, 0x49, 0x4d, 0xcf, 0x8a, 0xf6, 0x35, 0x6c, 0x65, 0x2a, 0x74, 0x34, 0xf5, 0xb0, 0x0b, 0x0b, 0x7e, 0x3a, 0x37, 0xcf, 0xa1, 0x88, 0x39, 0x7f, 0x8e, 0x86, 0x97, 0x1f, 0xd7, 0xb5, 0x2b, 0xa9, 0xc3, 0x4e, 0x1e, 0xcc, 0x3b, 0xed, 0x3c, 0x42, 0x15, 0x27, 0xe5, 0xd1, 0x5b, 0x15, 0xa7, 0xfc, 0xcb, 0xbb, 0x2a, 0x4e, 0x45, 0x2f, 0xe5, 0x2b, 0xda, 0xcf, 0xd1, 0x34, 0x8b, 0x8a, 0x40, 0xad, 0x9d, 0xd2, 0x0f, 0xa5, 0xf2, 0xaf, 0x73, 0xb5, 0x00, 0xa3, 0x9a, 0x85, 0xa4, 0xfe, 0x4e, 0x35, 0x0b, 0xb9, 0x0a, 0x42, 0xd5, 0x2c, 0x14, 0x94, 0xec, 0xad, 0x50, 0xf4, 0x2b, 0xab, 0x67, 0x68, 0x65, 0xd9, 0x6f, 0x0c, 0x3a, 0xc5, 0xdf, 0x44, 0xe8, 0x2b, 0x3f, 0x2a, 0x69, 0x9f, 0xc5, 0x75, 0x37, 0xc9, 0x3b, 0x8e, 0x12, 0x5a, 0xc6, 0xa5, 0x9d, 0x9d, 0x4c, 0x7d, 0x1e, 0x77, 0x46, 0x6b, 0x14, 0x17, 0x42, 0xa9, 0xd6, 0x28, 0x5b, 0x86, 0xa5, 0x5a, 0xa3, 0x7c, 0xe5, 0x94, 0xd8, 0x89, 0xb8, 0x4c, 0x2a, 0xb5, 0x13, 0xd9, 0x8a, 0xaa, 0xd4, 0x4e, 0xe4, 0x2b, 0xab, 0x56, 0xb4, 0x87, 0x50, 0x8b, 0x4b, 0x9b, 0xd4, 0x29, 0x65, 0x0b, 0xae, 0xd4, 0x29, 0xe5, 0x6b, 0xa1, 0x56, 0x6e, 0x95, 0x48, 0xda, 0x44, 0x81, 0x91, 0x2a, 0x6d, 0xa9, 0x5a, 0xa6, 0x4e, 0x3b, 0x8f, 0x50, 0x2d, 0x75, 0x5c, 0x4b, 0xa4, 0x4e, 0x24, 0x5b, 0xa2, 0xd4, 0xb9, 0x56, 0x88, 0x53, 0xe5, 0x4c, 0xd6, 0x64, 0x68, 0x19, 0xe1, 0x4e, 0x3e, 0xe6, 0x57, 0xe5, 0x2c, 0x53, 0xc0, 0x11, 0x4b, 0x6a, 0x96, 0x43, 0xba, 0x56, 0x23, 0x23, 0xa9, 0x19, 0x0e, 0xb1, 0xa4, 0x32, 0x93, 0xdc, 0x84, 0x55, 0x3e, 0x6f, 0x14, 0x23, 0x55, 0x56, 0x49, 0xb9, 0x84, 0x96, 0x93, 0x8b, 0x25, 0xac, 0x0a, 0x2a, 0x2c, 0x58, 0x9f, 0x95, 0x9a, 0x09, 0x2d, 0x2f, 0x19, 0x2a, 0xb3, 0xeb, 0x4b, 0xb0, 0xea, 0x79, 0xc5, 0x15, 0x0f, 0xea, 0x79, 0x65, 0x0b, 0x27, 0xd4, 0xf3, 0xca, 0x97, 0x48, 0xb0, 0x9b, 0x49, 0x55, 0x4f, 0xa8, 0x6e, 0xa6, 0xa8, 0x10, 0x43, 0x75, 0x33, 0xc5, 0x65, 0x17, 0xb1, 0xe1, 0xc3, 0xab, 0x4e, 0xc6, 0xf0, 0xc5, 0x97, 0x8d, 0xac, 0xe1, 0x4b, 0x2e, 0x17, 0x62, 0xa3, 0x94, 0x72, 0x0b, 0x2d, 0xb7, 0xaf, 0x6a, 0x39, 0x87, 0xba, 0x51, 0x45, 0x35, 0x1a, 0x2b, 0x52, 0x2f, 0xe8, 0x32, 0x92, 0xd6, 0x8b, 0xa4, 0x54, 0x22, 0xa3, 0x17, 0x6a, 0x39, 0x84, 0xa2, 0x17, 0xc4, 0x21, 0xa7, 0x17, 0x0a, 0x93, 0x6b, 0x85, 0xb8, 0xcc, 0x9e, 0x64, 0xa6, 0x91, 0x2a, 0x1f, 0xc9, 0xec, 0x49, 0xba, 0xbb, 0xc1, 0xb7, 0x35, 0x25, 0xc9, 0x7c, 0x23, 0x45, 0x9c, 0x2b, 0x2e, 0x50, 0x8f, 0xa9, 0xb0, 0x1a, 0x43, 0xf0, 0x4c, 0x55, 0x49, 0xa8, 0x3c, 0x8b, 0xca, 0x2f, 0x54, 0x9e, 0xc5, 0xe5, 0x15, 0x1c, 0x01, 0x64, 0x6b, 0x21, 0xd4, 0x08, 0x60, 0x49, 0xf1, 0x85, 0x1a, 0x01, 0x2c, 0x2d, 0xa5, 0xe0, 0xf0, 0x25, 0x57, 0x08, 0xa1, 0x86, 0x2f, 0xcb, 0x2a, 0x2d, 0xd4, 0xf0, 0x65, 0x79, 0x25, 0xc5, 0x8a, 0x76, 0x0c, 0x0d, 0xb5, 0x68, 0x42, 0x4b, 0xc7, 0x68, 0xd9, 0xfa, 0x80, 0xce, 0x8d, 0x65, 0x68, 0x95, 0xa1, 0x5a, 0xee, 0xa0, 0xa5, 0x23, 0xd3, 0xf3, 0x18, 0x16, 0x56, 0x49, 0x88, 0x60, 0x25, 0x5d, 0xc8, 0xa0, 0xe5, 0x22, 0xd3, 0x1c, 0xdb, 0x9b, 0xe7, 0x50, 0xa8, 0x07, 0x97, 0xad, 0x5c, 0x50, 0x0f, 0x6e, 0x49, 0x8d, 0x44, 0x47, 0x3f, 0x8f, 0x24, 0x73, 0x0d, 0x90, 0x19, 0xa3, 0xf4, 0x35, 0x20, 0xf5, 0x1d, 0x7e, 0xe6, 0x1a, 0x90, 0xf9, 0xe8, 0x9d, 0xf9, 0xc4, 0xdf, 0x79, 0xab, 0x7c, 0xb2, 0x05, 0x10, 0x2a, 0x9f, 0x7c, 0x89, 0x02, 0x9f, 0x8b, 0xfa, 0x85, 0xb6, 0x7a, 0x2e, 0x05, 0xb5, 0x0b, 0xea, 0xb9, 0x14, 0x96, 0x15, 0xc8, 0x60, 0x5d, 0xf9, 0xe4, 0x3a, 0x1d, 0xac, 0xe7, 0x0b, 0x0e, 0xd2, 0xc1, 0x7a, 0xd1, 0x17, 0xfe, 0x2b, 0xda, 0x98, 0x2b, 0x7b, 0x72, 0x29, 0xb1, 0xef, 0x17, 0x6c, 0x51, 0xee, 0xfb, 0xf1, 0xce, 0xdb, 0x2f, 0xa0, 0x52, 0x47, 0x29, 0xf8, 0x74, 0x5e, 0x1d, 0x65, 0xf9, 0x37, 0xfb, 0xea, 0x28, 0xe7, 0x7d, 0x7f, 0xbf, 0xa2, 0xcd, 0xa2, 0xfa, 0x9e, 0xdc, 0x40, 0xef, 0x14, 0xef, 0x6d, 0x7e, 0xac, 0x5b, 0x2f, 0x26, 0x8c, 0x87, 0xf3, 0xe2, 0xa2, 0x9e, 0x7c, 0x46, 0x71, 0xc9, 0xc6, 0xe7, 0x07, 0x7c, 0xf7, 0x02, 0x94, 0xd1, 0x88, 0x4f, 0xd6, 0xf9, 0x5f, 0x97, 0x7c, 0xf4, 0x5f, 0x01, 0x00, 0x00, 0xff, 0xff, 0x80, 0xb9, 0xdd, 0x3c, 0xc9, 0x44, 0x00, 0x00, } <|start_filename|>netmaster/mastercfg/servicelbState_test.go<|end_filename|> /*** Copyright 2014 Cisco Systems 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. */ package mastercfg import ( "testing" "github.com/contiv/netplugin/core" ) const ( testSvcID = "testServiceLB" serviceLBCfgKey = serviceLBConfigPathPrefix + testSvcID ) type testServiceLBStateDriver struct{} var serviceLBStateDriver = &testServiceLBStateDriver{} func (d *testServiceLBStateDriver) Init(instInfo *core.InstanceInfo) error { return core.Errorf("Shouldn't be called!") } func (d *testServiceLBStateDriver) Deinit() { } func (d *testServiceLBStateDriver) Write(key string, value []byte) error { return core.Errorf("Shouldn't be called!") } func (d *testServiceLBStateDriver) Read(key string) ([]byte, error) { return []byte{}, core.Errorf("Shouldn't be called!") } func (d *testServiceLBStateDriver) ReadAll(baseKey string) ([][]byte, error) { return [][]byte{}, core.Errorf("Shouldn't be called!") } func (d *testServiceLBStateDriver) WatchAll(baseKey string, rsps chan [2][]byte) error { return core.Errorf("not supported") } func (d *testServiceLBStateDriver) validateKey(key string) error { if key != serviceLBCfgKey { return core.Errorf("Unexpected key. recvd: %s expected: %s ", key, serviceLBCfgKey) } return nil } func (d *testServiceLBStateDriver) ClearState(key string) error { return d.validateKey(key) } func (d *testServiceLBStateDriver) ReadState(key string, value core.State, unmarshal func([]byte, interface{}) error) error { return d.validateKey(key) } func (d *testServiceLBStateDriver) ReadAllState(key string, value core.State, unmarshal func([]byte, interface{}) error) ([]core.State, error) { return nil, core.Errorf("Shouldn't be called!") } func (d *testServiceLBStateDriver) WatchAllState(baseKey string, sType core.State, unmarshal func([]byte, interface{}) error, rsps chan core.WatchState) error { return core.Errorf("not supported") } func (d *testServiceLBStateDriver) WriteState(key string, value core.State, marshal func(interface{}) ([]byte, error)) error { return d.validateKey(key) } func TestCfgServiceLBStateRead(t *testing.T) { serviceLBCfg := &CfgServiceLBState{} serviceLBCfg.StateDriver = serviceLBStateDriver err := serviceLBCfg.Read(testSvcID) if err != nil { t.Fatalf("read config state failed. Error: %s", err) } } func TestServiceLBStateWrite(t *testing.T) { serviceLBCfg := &CfgServiceLBState{} serviceLBCfg.StateDriver = serviceLBStateDriver serviceLBCfg.ID = testSvcID err := serviceLBCfg.Write() if err != nil { t.Fatalf("write config state failed. Error: %s", err) } } func TestServiceLBStateClear(t *testing.T) { serviceLBCfg := &CfgServiceLBState{} serviceLBCfg.StateDriver = serviceLBStateDriver serviceLBCfg.ID = testSvcID err := serviceLBCfg.Clear() if err != nil { t.Fatalf("clear config state failed. Error: %s", err) } } <|start_filename|>vendor/github.com/contiv/libovsdb/Makefile<|end_filename|> all: build test build: go build -v test: go test -covermode=count -coverprofile=coverage.out -test.short -v test-all: go test -covermode=count -coverprofile=coverage.out -v <|start_filename|>utils/lldp_test.go<|end_filename|> /*** Copyright 2014 Cisco Systems 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. */ package utils import ( "testing" ) func TestSystemName(t *testing.T) { attrLines := []string{" contiv-aci-leaf2"} sysName, err := lldpReadSystemName(attrLines) if err != nil || sysName != "contiv-aci-leaf2" { t.Fatalf("failed to get parse lldp system name\n") } } func TestSystemDescription(t *testing.T) { attrLines := []string{" topology/pod-1/node-102"} sysDesc, err := lldpReadSystemDescription(attrLines) if err != nil || sysDesc != "topology/pod-1/node-102" { t.Fatalf("failed to get parse lldp system description\n") } } func TestPortDesc(t *testing.T) { attrLines := []string{" topology/pod-1/paths-102/pathep-[eth1/11]"} portDesc, err := lldpReadPortDescription(attrLines) if err != nil || portDesc != "topology/pod-1/paths-102/pathep-[eth1/11]" { t.Fatalf("failed to get parse lldp port description\n") } } func TestPortID(t *testing.T) { attrLines := []string{" Local: Eth1/11"} portID, err := lldpReadPortID(attrLines) if err != nil || portID != "Eth1/11" { t.Fatalf("failed to get parse lldp port id\n") } } func TestACIInfo(t *testing.T) { podID, err := lldpReadACIPodID("topology/pod-2/node-103") if err != nil || podID != "2" { t.Fatalf("failed to parse lldp system description for pod id\n") } nodeID, err := lldpReadACINodeID("topology/pod-2/node-103") if err != nil || nodeID != "103" { t.Fatalf("failed to parse system info for node id\n") } } func TestLLDPAttrs(t *testing.T) { lldpToolOutput := ` Chassis ID TLV MAC: a4:6c:2a:1e:0c:b9 Port ID TLV Local: Eth1/11 Time to Live TLV 120 Port Description TLV topology/pod-1/paths-102/pathep-[eth1/11] System Name TLV contiv-aci-leaf2 System Description TLV topology/pod-1/node-102 System Capabilities TLV System capabilities: Bridge, Router Enabled capabilities: Bridge, Router Management Address TLV MAC: a4:6c:2a:1e:0c:b9 Ifindex: 83886080 Unidentified Org Specific TLV OUI: 0x000142, Subtype: 201, Info: 02 Unidentified Org Specific TLV OUI: 0x000142, Subtype: 212, Info: 53414c3139313845394e46 Unidentified Org Specific TLV OUI: 0x000142, Subtype: 210, Info: 6e393030302d31312e3128312e32353229 Unidentified Org Specific TLV OUI: 0x000142, Subtype: 202, Info: 01 Unidentified Org Specific TLV OUI: 0x000142, Subtype: 205, Info: 0001 Unidentified Org Specific TLV OUI: 0x000142, Subtype: 208, Info: 0a00505d Unidentified Org Specific TLV OUI: 0x000142, Subtype: 203, Info: 00000066 Unidentified Org Specific TLV OUI: 0x000142, Subtype: 206, Info: 636f6e7469762d616369 Unidentified Org Specific TLV OUI: 0x000142, Subtype: 207, Info: 010a00000139653462313438362d313939392 End of LLDPDU TLV` var parsedInfo LLDPNeighbor err := parseLLDPArgs(lldpToolOutput, &parsedInfo) if err != nil { t.Fatalf("failed to parse lldp attributes\n") } if parsedInfo.SystemDescription != "topology/pod-1/node-102" || parsedInfo.SystemName != "contiv-aci-leaf2" || parsedInfo.CiscoACIPodID != "1" || parsedInfo.CiscoACINodeID != "102" || parsedInfo.PortDesc != "topology/pod-1/paths-102/pathep-[eth1/11]" || parsedInfo.PortID != "Eth1/11" { t.Fatalf("parsed params invalid %v \n", parsedInfo) } } <|start_filename|>vendor/github.com/osrg/gobgp/zebra/safi_string.go<|end_filename|> // generated by stringer --type SAFI,API_TYPE,ROUTE_TYPE,NEXTHOP_FLAG; DO NOT EDIT package zebra import "fmt" const _SAFI_name = "SAFI_UNICASTSAFI_MULTICASTSAFI_RESERVED_3SAFI_MPLS_VPNSAFI_MAX" var _SAFI_index = [...]uint8{0, 12, 26, 41, 54, 62} func (i SAFI) String() string { i -= 1 if i+1 >= SAFI(len(_SAFI_index)) { return fmt.Sprintf("SAFI(%d)", i+1) } return _SAFI_name[_SAFI_index[i]:_SAFI_index[i+1]] } const _API_TYPE_name = "INTERFACE_ADDINTERFACE_DELETEINTERFACE_ADDRESS_ADDINTERFACE_ADDRESS_DELETEINTERFACE_UPINTERFACE_DOWNIPV4_ROUTE_ADDIPV4_ROUTE_DELETEIPV6_ROUTE_ADDIPV6_ROUTE_DELETEREDISTRIBUTE_ADDREDISTRIBUTE_DELETEREDISTRIBUTE_DEFAULT_ADDREDISTRIBUTE_DEFAULT_DELETEIPV4_NEXTHOP_LOOKUPIPV6_NEXTHOP_LOOKUPIPV4_IMPORT_LOOKUPIPV6_IMPORT_LOOKUPINTERFACE_RENAMEROUTER_ID_ADDROUTER_ID_DELETEROUTER_ID_UPDATEHELLOMESSAGE_MAX" var _API_TYPE_index = [...]uint16{0, 13, 29, 50, 74, 86, 100, 114, 131, 145, 162, 178, 197, 221, 248, 267, 286, 304, 322, 338, 351, 367, 383, 388, 399} func (i API_TYPE) String() string { i -= 1 if i+1 >= API_TYPE(len(_API_TYPE_index)) { return fmt.Sprintf("API_TYPE(%d)", i+1) } return _API_TYPE_name[_API_TYPE_index[i]:_API_TYPE_index[i+1]] } const _ROUTE_TYPE_name = "ROUTE_SYSTEMROUTE_KERNELROUTE_CONNECTROUTE_STATICROUTE_RIPROUTE_RIPNGROUTE_OSPFROUTE_OSPF6ROUTE_ISISROUTE_BGPROUTE_HSLSROUTE_OLSRROUTE_BABELROUTE_MAX" var _ROUTE_TYPE_index = [...]uint8{0, 12, 24, 37, 49, 58, 69, 79, 90, 100, 109, 119, 129, 140, 149} func (i ROUTE_TYPE) String() string { if i+1 >= ROUTE_TYPE(len(_ROUTE_TYPE_index)) { return fmt.Sprintf("ROUTE_TYPE(%d)", i) } return _ROUTE_TYPE_name[_ROUTE_TYPE_index[i]:_ROUTE_TYPE_index[i+1]] } const _NEXTHOP_FLAG_name = "NEXTHOP_IFINDEXNEXTHOP_IFNAMENEXTHOP_IPV4NEXTHOP_IPV4_IFINDEXNEXTHOP_IPV4_IFNAMENEXTHOP_IPV6NEXTHOP_IPV6_IFINDEXNEXTHOP_IPV6_IFNAMENEXTHOP_BLACKHOLE" var _NEXTHOP_FLAG_index = [...]uint8{0, 15, 29, 41, 61, 80, 92, 112, 131, 148} func (i NEXTHOP_FLAG) String() string { i -= 1 if i+1 >= NEXTHOP_FLAG(len(_NEXTHOP_FLAG_index)) { return fmt.Sprintf("NEXTHOP_FLAG(%d)", i+1) } return _NEXTHOP_FLAG_name[_NEXTHOP_FLAG_index[i]:_NEXTHOP_FLAG_index[i+1]] } <|start_filename|>vendor/github.com/osrg/gobgp/server/collector.go<|end_filename|> // Copyright (C) 2016 Nippon Telegraph and Telephone Corporation. // // 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 server import ( "fmt" log "github.com/Sirupsen/logrus" "github.com/influxdata/influxdb/client/v2" "github.com/osrg/gobgp/packet/bgp" "github.com/osrg/gobgp/table" "time" ) type Collector struct { s *BgpServer url string dbName string interval uint64 client client.Client } const ( MEATUREMENT_UPDATE = "update" MEATUREMENT_PEER = "peer" MEATUREMENT_TABLE = "table" ) func (c *Collector) writePoints(points []*client.Point) error { bp, _ := client.NewBatchPoints(client.BatchPointsConfig{ Database: c.dbName, Precision: "ms", }) bp.AddPoints(points) return c.client.Write(bp) } func (c *Collector) writePeer(msg *WatchEventPeerState) error { var state string switch msg.State { case bgp.BGP_FSM_ESTABLISHED: state = "Established" case bgp.BGP_FSM_IDLE: state = "Idle" default: return fmt.Errorf("unexpected fsm state %v", msg.State) } tags := map[string]string{ "PeerAddress": msg.PeerAddress.String(), "PeerAS": fmt.Sprintf("%v", msg.PeerAS), "State": state, } fields := map[string]interface{}{ "PeerID": msg.PeerID.String(), } pt, err := client.NewPoint(MEATUREMENT_PEER, tags, fields, msg.Timestamp) if err != nil { return err } return c.writePoints([]*client.Point{pt}) } func path2data(path *table.Path) (map[string]interface{}, map[string]string) { fields := map[string]interface{}{ "RouterID": path.GetSource().ID, } if asPath := path.GetAsPath(); asPath != nil { fields["ASPath"] = asPath.String() } if origin, err := path.GetOrigin(); err == nil { typ := "-" switch origin { case bgp.BGP_ORIGIN_ATTR_TYPE_IGP: typ = "i" case bgp.BGP_ORIGIN_ATTR_TYPE_EGP: typ = "e" case bgp.BGP_ORIGIN_ATTR_TYPE_INCOMPLETE: typ = "?" } fields["Origin"] = typ } if med, err := path.GetMed(); err == nil { fields["Med"] = med } tags := map[string]string{ "PeerAddress": path.GetSource().Address.String(), "PeerAS": fmt.Sprintf("%v", path.GetSource().AS), "Timestamp": path.GetTimestamp().String(), } if nexthop := path.GetNexthop(); len(nexthop) > 0 { fields["NextHop"] = nexthop.String() } if originAS := path.GetSourceAs(); originAS != 0 { fields["OriginAS"] = fmt.Sprintf("%v", originAS) } if err := bgp.FlatUpdate(tags, path.GetNlri().Flat()); err != nil { log.WithFields(log.Fields{"Type": "collector", "Error": err}).Error("NLRI FlatUpdate failed") } for _, p := range path.GetPathAttrs() { if err := bgp.FlatUpdate(tags, p.Flat()); err != nil { log.WithFields(log.Fields{"Type": "collector", "Error": err}).Error("PathAttr FlatUpdate failed") } } return fields, tags } func (c *Collector) writeUpdate(msg *WatchEventUpdate) error { if len(msg.PathList) == 0 { // EOR return nil } now := time.Now() points := make([]*client.Point, 0, len(msg.PathList)) for _, path := range msg.PathList { fields, tags := path2data(path) tags["Withdraw"] = fmt.Sprintf("%v", path.IsWithdraw) pt, err := client.NewPoint(MEATUREMENT_UPDATE, tags, fields, now) if err != nil { return fmt.Errorf("failed to write update, %v", err) } points = append(points, pt) } return c.writePoints(points) } func (c *Collector) writeTable(msg *WatchEventAdjIn) error { now := time.Now() points := make([]*client.Point, 0, len(msg.PathList)) for _, path := range msg.PathList { fields, tags := path2data(path) pt, err := client.NewPoint(MEATUREMENT_TABLE, tags, fields, now) if err != nil { return fmt.Errorf("failed to write table, %v", err) } points = append(points, pt) } return c.writePoints(points) } func (c *Collector) loop() { w := c.s.Watch(WatchPeerState(true), WatchUpdate(false)) defer w.Stop() ticker := func() *time.Ticker { if c.interval == 0 { return &time.Ticker{} } return time.NewTicker(time.Second * time.Duration(c.interval)) }() for { select { case <-ticker.C: w.Generate(WATCH_EVENT_TYPE_PRE_UPDATE) case ev := <-w.Event(): switch msg := ev.(type) { case *WatchEventUpdate: if err := c.writeUpdate(msg); err != nil { log.WithFields(log.Fields{"Type": "collector", "Error": err}).Error("Failed to write update event message") } case *WatchEventPeerState: if err := c.writePeer(msg); err != nil { log.WithFields(log.Fields{"Type": "collector", "Error": err}).Error("Failed to write state changed event message") } case *WatchEventAdjIn: if err := c.writeTable(msg); err != nil { log.WithFields(log.Fields{"Type": "collector", "Error": err}).Error("Failed to write Adj-In event message") } } } } } func NewCollector(s *BgpServer, url, dbName string, interval uint64) (*Collector, error) { c, err := client.NewHTTPClient(client.HTTPConfig{ Addr: url, }) if err != nil { return nil, err } _, _, err = c.Ping(0) if err != nil { log.Error("can not connect to InfluxDB") log.WithFields(log.Fields{"Type": "collector", "Error": err}).Error("Failed to connect to InfluxDB") return nil, err } q := client.NewQuery("CREATE DATABASE "+dbName, "", "") if response, err := c.Query(q); err != nil || response.Error() != nil { log.WithFields(log.Fields{"Type": "collector", "Error": err}).Errorf("Failed to create database:%s", dbName) return nil, err } collector := &Collector{ s: s, url: url, dbName: dbName, interval: interval, client: c, } go collector.loop() return collector, nil } <|start_filename|>vendor/github.com/osrg/gobgp/server/peer.go<|end_filename|> // Copyright (C) 2014-2016 Nippon Telegraph and Telephone Corporation. // // 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 server import ( "fmt" log "github.com/Sirupsen/logrus" "github.com/eapache/channels" "github.com/osrg/gobgp/config" "github.com/osrg/gobgp/packet/bgp" "github.com/osrg/gobgp/table" "net" "time" ) const ( FLOP_THRESHOLD = time.Second * 30 MIN_CONNECT_RETRY = 10 ) type Peer struct { tableId string fsm *FSM adjRibIn *table.AdjRib adjRibOut *table.AdjRib outgoing *channels.InfiniteChannel policy *table.RoutingPolicy localRib *table.TableManager prefixLimitWarned map[bgp.RouteFamily]bool } func NewPeer(g *config.Global, conf *config.Neighbor, loc *table.TableManager, policy *table.RoutingPolicy) *Peer { peer := &Peer{ outgoing: channels.NewInfiniteChannel(), localRib: loc, policy: policy, fsm: NewFSM(g, conf, policy), prefixLimitWarned: make(map[bgp.RouteFamily]bool), } if peer.isRouteServerClient() { peer.tableId = conf.Config.NeighborAddress } else { peer.tableId = table.GLOBAL_RIB_NAME } rfs, _ := config.AfiSafis(conf.AfiSafis).ToRfList() peer.adjRibIn = table.NewAdjRib(peer.ID(), rfs) peer.adjRibOut = table.NewAdjRib(peer.ID(), rfs) return peer } func (peer *Peer) ID() string { return peer.fsm.pConf.Config.NeighborAddress } func (peer *Peer) TableID() string { return peer.tableId } func (peer *Peer) isIBGPPeer() bool { return peer.fsm.pConf.Config.PeerAs == peer.fsm.gConf.Config.As } func (peer *Peer) isRouteServerClient() bool { return peer.fsm.pConf.RouteServer.Config.RouteServerClient } func (peer *Peer) isRouteReflectorClient() bool { return peer.fsm.pConf.RouteReflector.Config.RouteReflectorClient } func (peer *Peer) isGracefulRestartEnabled() bool { return peer.fsm.pConf.GracefulRestart.State.Enabled } func (peer *Peer) recvedAllEOR() bool { for _, a := range peer.fsm.pConf.AfiSafis { if s := a.MpGracefulRestart.State; s.Enabled && !s.EndOfRibReceived { return false } } return true } func (peer *Peer) configuredRFlist() []bgp.RouteFamily { rfs, _ := config.AfiSafis(peer.fsm.pConf.AfiSafis).ToRfList() return rfs } func (peer *Peer) forwardingPreservedFamilies() ([]bgp.RouteFamily, []bgp.RouteFamily) { list := []bgp.RouteFamily{} for _, a := range peer.fsm.pConf.AfiSafis { if s := a.MpGracefulRestart.State; s.Enabled && s.Received { f, _ := bgp.GetRouteFamily(string(a.Config.AfiSafiName)) list = append(list, f) } } preserved := []bgp.RouteFamily{} notPreserved := []bgp.RouteFamily{} for _, f := range peer.configuredRFlist() { p := true for _, g := range list { if f == g { p = false preserved = append(preserved, f) } } if p { notPreserved = append(notPreserved, f) } } return preserved, notPreserved } func (peer *Peer) getAccepted(rfList []bgp.RouteFamily) []*table.Path { return peer.adjRibIn.PathList(rfList, true) } func (peer *Peer) filterpath(path *table.Path, withdrawals []*table.Path) *table.Path { // special handling for RTC nlri // see comments in (*Destination).Calculate() if path != nil && path.GetRouteFamily() == bgp.RF_RTC_UC && !path.IsWithdraw { // if we already sent the same nlri, ignore this if peer.adjRibOut.Exists(path) { return nil } dst := peer.localRib.GetDestination(path) path = nil // we send a path even if it is not a best path for _, p := range dst.GetKnownPathList(peer.TableID()) { // just take care not to send back it if peer.ID() != p.GetSource().Address.String() { path = p break } } } if path = filterpath(peer, path, withdrawals); path == nil { return nil } path = path.Clone(path.IsWithdraw) path.UpdatePathAttrs(peer.fsm.gConf, peer.fsm.pConf) options := &table.PolicyOptions{ Info: peer.fsm.peerInfo, } path = peer.policy.ApplyPolicy(peer.TableID(), table.POLICY_DIRECTION_EXPORT, path, options) // remove local-pref attribute // we should do this after applying export policy since policy may // set local-preference if path != nil && peer.fsm.pConf.Config.PeerType == config.PEER_TYPE_EXTERNAL { path.RemoveLocalPref() } return path } func (peer *Peer) getBestFromLocal(rfList []bgp.RouteFamily) ([]*table.Path, []*table.Path) { pathList := []*table.Path{} filtered := []*table.Path{} for _, path := range peer.localRib.GetBestPathList(peer.TableID(), rfList) { if p := peer.filterpath(path, nil); p != nil { pathList = append(pathList, p) } else { filtered = append(filtered, path) } } if peer.isGracefulRestartEnabled() { for _, family := range rfList { pathList = append(pathList, table.NewEOR(family)) } } return pathList, filtered } func (peer *Peer) processOutgoingPaths(paths, withdrawals []*table.Path) []*table.Path { if peer.fsm.state != bgp.BGP_FSM_ESTABLISHED { return nil } if peer.fsm.pConf.GracefulRestart.State.LocalRestarting { log.WithFields(log.Fields{ "Topic": "Peer", "Key": peer.fsm.pConf.Config.NeighborAddress, }).Debug("now syncing, suppress sending updates") return nil } outgoing := make([]*table.Path, 0, len(paths)) for _, path := range paths { if p := peer.filterpath(path, withdrawals); p != nil { outgoing = append(outgoing, p) } } peer.adjRibOut.Update(outgoing) return outgoing } func (peer *Peer) handleRouteRefresh(e *FsmMsg) []*table.Path { m := e.MsgData.(*bgp.BGPMessage) rr := m.Body.(*bgp.BGPRouteRefresh) rf := bgp.AfiSafiToRouteFamily(rr.AFI, rr.SAFI) if _, ok := peer.fsm.rfMap[rf]; !ok { log.WithFields(log.Fields{ "Topic": "Peer", "Key": peer.ID(), "Data": rf, }).Warn("Route family isn't supported") return nil } if _, ok := peer.fsm.capMap[bgp.BGP_CAP_ROUTE_REFRESH]; !ok { log.WithFields(log.Fields{ "Topic": "Peer", "Key": peer.ID(), }).Warn("ROUTE_REFRESH received but the capability wasn't advertised") return nil } rfList := []bgp.RouteFamily{rf} peer.adjRibOut.Drop(rfList) accepted, filtered := peer.getBestFromLocal(rfList) peer.adjRibOut.Update(accepted) for _, path := range filtered { path.IsWithdraw = true accepted = append(accepted, path) } return accepted } func (peer *Peer) doPrefixLimit(k bgp.RouteFamily, c *config.PrefixLimitConfig) *bgp.BGPMessage { if maxPrefixes := int(c.MaxPrefixes); maxPrefixes > 0 { count := peer.adjRibIn.Count([]bgp.RouteFamily{k}) pct := int(c.ShutdownThresholdPct) if pct > 0 && !peer.prefixLimitWarned[k] && count > (maxPrefixes*pct/100) { peer.prefixLimitWarned[k] = true log.WithFields(log.Fields{ "Topic": "Peer", "Key": peer.ID(), "AddressFamily": k.String(), }).Warnf("prefix limit %d%% reached", pct) } if count > maxPrefixes { log.WithFields(log.Fields{ "Topic": "Peer", "Key": peer.ID(), "AddressFamily": k.String(), }).Warnf("prefix limit reached") return bgp.NewBGPNotificationMessage(bgp.BGP_ERROR_CEASE, bgp.BGP_ERROR_SUB_MAXIMUM_NUMBER_OF_PREFIXES_REACHED, nil) } } return nil } func (peer *Peer) updatePrefixLimitConfig(c []config.AfiSafi) error { x := peer.fsm.pConf.AfiSafis y := c if len(x) != len(y) { return fmt.Errorf("changing supported afi-safi is not allowed") } m := make(map[bgp.RouteFamily]config.PrefixLimitConfig) for _, e := range x { k, err := bgp.GetRouteFamily(string(e.Config.AfiSafiName)) if err != nil { return err } m[k] = e.PrefixLimit.Config } for _, e := range y { k, err := bgp.GetRouteFamily(string(e.Config.AfiSafiName)) if err != nil { return err } if p, ok := m[k]; !ok { return fmt.Errorf("changing supported afi-safi is not allowed") } else if !p.Equal(&e.PrefixLimit.Config) { log.WithFields(log.Fields{ "Topic": "Peer", "Key": peer.ID(), "AddressFamily": e.Config.AfiSafiName, "OldMaxPrefixes": p.MaxPrefixes, "NewMaxPrefixes": e.PrefixLimit.Config.MaxPrefixes, "OldShutdownThresholdPct": p.ShutdownThresholdPct, "NewShutdownThresholdPct": e.PrefixLimit.Config.ShutdownThresholdPct, }).Warnf("update prefix limit configuration") peer.prefixLimitWarned[k] = false if msg := peer.doPrefixLimit(k, &e.PrefixLimit.Config); msg != nil { sendFsmOutgoingMsg(peer, nil, msg, true) } } } peer.fsm.pConf.AfiSafis = c return nil } func (peer *Peer) handleUpdate(e *FsmMsg) ([]*table.Path, []bgp.RouteFamily, *bgp.BGPMessage) { m := e.MsgData.(*bgp.BGPMessage) update := m.Body.(*bgp.BGPUpdate) log.WithFields(log.Fields{ "Topic": "Peer", "Key": peer.fsm.pConf.Config.NeighborAddress, "nlri": update.NLRI, "withdrawals": update.WithdrawnRoutes, "attributes": update.PathAttributes, }).Debug("received update") peer.fsm.pConf.Timers.State.UpdateRecvTime = time.Now().Unix() if len(e.PathList) > 0 { peer.adjRibIn.Update(e.PathList) for _, family := range peer.fsm.pConf.AfiSafis { k, _ := bgp.GetRouteFamily(string(family.Config.AfiSafiName)) if msg := peer.doPrefixLimit(k, &family.PrefixLimit.Config); msg != nil { return nil, nil, msg } } paths := make([]*table.Path, 0, len(e.PathList)) eor := []bgp.RouteFamily{} for _, path := range e.PathList { if path.IsEOR() { family := path.GetRouteFamily() log.WithFields(log.Fields{ "Topic": "Peer", "Key": peer.ID(), "AddressFamily": family, }).Debug("EOR received") eor = append(eor, family) continue } if path.Filtered(peer.ID()) != table.POLICY_DIRECTION_IN { paths = append(paths, path) } } return paths, eor, nil } return nil, nil, nil } func (peer *Peer) startFSMHandler(incoming *channels.InfiniteChannel, stateCh chan *FsmMsg) { peer.fsm.h = NewFSMHandler(peer.fsm, incoming, stateCh, peer.outgoing) } func (peer *Peer) StaleAll(rfList []bgp.RouteFamily) { peer.adjRibIn.StaleAll(rfList) } func (peer *Peer) PassConn(conn *net.TCPConn) { select { case peer.fsm.connCh <- conn: default: conn.Close() log.WithFields(log.Fields{ "Topic": "Peer", "Key": peer.ID(), }).Warn("accepted conn is closed to avoid be blocked") } } func (peer *Peer) ToConfig() *config.Neighbor { // create copy which can be access to without mutex conf := *peer.fsm.pConf conf.AfiSafis = make([]config.AfiSafi, len(peer.fsm.pConf.AfiSafis)) for i := 0; i < len(peer.fsm.pConf.AfiSafis); i++ { conf.AfiSafis[i] = peer.fsm.pConf.AfiSafis[i] } remoteCap := make([][]byte, 0, len(peer.fsm.capMap)) for _, c := range peer.fsm.capMap { for _, m := range c { buf, _ := m.Serialize() remoteCap = append(remoteCap, buf) } } conf.State.Capabilities.RemoteList = remoteCap caps := capabilitiesFromConfig(peer.fsm.pConf) localCap := make([][]byte, 0, len(caps)) for _, c := range caps { buf, _ := c.Serialize() localCap = append(localCap, buf) } conf.State.Capabilities.LocalList = localCap conf.State.RemoteRouterId = peer.fsm.peerInfo.ID.To4().String() conf.State.SessionState = config.IntToSessionStateMap[int(peer.fsm.state)] conf.State.AdminState = peer.fsm.adminState.String() if peer.fsm.state == bgp.BGP_FSM_ESTABLISHED { rfList := peer.configuredRFlist() conf.State.AdjTable.Advertised = uint32(peer.adjRibOut.Count(rfList)) conf.State.AdjTable.Received = uint32(peer.adjRibIn.Count(rfList)) conf.State.AdjTable.Accepted = uint32(peer.adjRibIn.Accepted(rfList)) conf.Transport.State.LocalAddress, conf.Transport.State.LocalPort = peer.fsm.LocalHostPort() _, conf.Transport.State.RemotePort = peer.fsm.RemoteHostPort() conf.State.ReceivedOpenMessage, _ = peer.fsm.recvOpen.Serialize() } return &conf } func (peer *Peer) DropAll(rfList []bgp.RouteFamily) { peer.adjRibIn.Drop(rfList) peer.adjRibOut.Drop(rfList) } <|start_filename|>netmaster/mastercfg/bgpState.go<|end_filename|> /*** Copyright 2014 Cisco Systems 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. */ package mastercfg import ( "encoding/json" "fmt" "github.com/contiv/netplugin/core" ) const ( bgpConfigPathPrefix = StateConfigPath + "bgp/" bgpConfigPath = bgpConfigPathPrefix + "%s" ) // CfgBgpState is the router Bgp configuration for the host type CfgBgpState struct { core.CommonState Hostname string `json:"hostname"` RouterIP string `json:"router-ip"` As string `json:"as"` NeighborAs string `json:"neighbor-as"` Neighbor string `json:"neighbor"` } // Write the state func (s *CfgBgpState) Write() error { key := fmt.Sprintf(bgpConfigPath, s.Hostname) return s.StateDriver.WriteState(key, s, json.Marshal) } // Read the state in for a given ID. func (s *CfgBgpState) Read(id string) error { key := fmt.Sprintf(bgpConfigPath, id) return s.StateDriver.ReadState(key, s, json.Unmarshal) } // ReadAll reads all the state for master bgp configurations and returns it. func (s *CfgBgpState) ReadAll() ([]core.State, error) { return s.StateDriver.ReadAllState(bgpConfigPathPrefix, s, json.Unmarshal) } // Clear removes the configuration from the state store. func (s *CfgBgpState) Clear() error { key := fmt.Sprintf(bgpConfigPath, s.Hostname) return s.StateDriver.ClearState(key) } // WatchAll state transitions and send them through the channel. func (s *CfgBgpState) WatchAll(rsps chan core.WatchState) error { return s.StateDriver.WatchAllState(bgpConfigPathPrefix, s, json.Unmarshal, rsps) }
dseevr-contiv/netplugin
<|start_filename|>src/Android/NavigatorUrlSchemeBuilder.java<|end_filename|> /* COPYRIGHT 2016 ESRI This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.esri.urlschemedemo; import android.content.Intent; import android.net.Uri; import android.support.annotation.FloatRange; import android.support.annotation.NonNull; import android.text.TextUtils; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.ArrayList; import java.util.List; public class NavigatorUrlSchemeBuilder { //region public inner classes / interfaces /** * This may be used to constrain the value passed to {@link #setTravelMode(String)} to one of the * default Esri travel modes if you're not using a custom travel mode. */ public static class EsriTravelMode { public static final String DRIVING_TIME = "Driving Time"; public static final String DRIVING_DISTANCE = "Driving Distance"; public static final String TRUCKING_TIME = "Trucking Time"; public static final String TRUCKING_DISTANCE = "Trucking Distance"; public static final String WALKING_TIME = "Walking Time"; public static final String WALKING_DISTANCE = "Walking Distance"; } //endregion public classes / interfaces //region constants private static final String NAVIGATOR_SCHEME = "arcgis-navigator"; private static final String CHARSET = "UTF-8"; private static final String STOP_PARAM = "stop"; private static final String STOP_NAME_PARAM = "stopname"; private static final String START_PARAM = "start"; private static final String START_NAME_PARAM = "startname"; private static final String OPTIMIZE_PARAM = "optimize"; private static final String TRAVEL_MODE_PARAM = "travelmode"; private static final String NAVIGATE_PARAM = "navigate"; private static final String CALLBACK_URI_PARAM = "callback"; private static final String CALLBACK_PROMPT_PARAM = "callbackprompt"; //endregion constants //region properties private List<Stop> mStops; private Stop mStart; private Boolean mOptimize; private String mTravelMode; private Boolean mNavigate; private String mCallbackUri; private String mCallbackPrompt; //endregion properties //region constructors public NavigatorUrlSchemeBuilder() { mStops = new ArrayList<>(); } //endregion constructors //region public methods /** * Adds stop with WGS84 coordinates * * @param latitude the latitude coordinate * @param longitude the longitude coordinate * @param name the optional name, may be {@code null} * @return this NavigatorUrlSchemeBuilder object to allow for chaining of method calls */ public NavigatorUrlSchemeBuilder addStop( @FloatRange(from = -90, to = 90) double latitude, @FloatRange(from = -180, to = 180) double longitude, String name) { mStops.add(new Wgs84Stop(latitude, longitude, name)); return this; } /** * Adds stop with address * * @param address the address * @param name the optional name, may be {@code null} * @return this NavigatorUrlSchemeBuilder object to allow for chaining of method calls */ public NavigatorUrlSchemeBuilder addStop(@NonNull String address, String name) { mStops.add(new AddressStop(address, name)); return this; } /** * Sets start with WGS84 coordinates * * @param latitude the latitude coordinate * @param longitude the longitude coordinate * @param name the optional name, may be {@code null} * @return this NavigatorUrlSchemeBuilder object to allow for chaining of method calls */ public NavigatorUrlSchemeBuilder setStart( @FloatRange(from = -90, to = 90) double latitude, @FloatRange(from = -180, to = 180) double longitude, String name) { mStart = new Wgs84Stop(latitude, longitude, name); return this; } /** * Sets start with address * * @param address the address * @param name the optional name, may be {@code null} * @return this NavigatorUrlSchemeBuilder object to allow for chaining of method calls */ public NavigatorUrlSchemeBuilder setStart(@NonNull String address, String name) { mStart = new AddressStop(address, name); return this; } /** * Sets the optimize flag * * @param optimize {@code true} if stops should be re-ordered optimally, {@code false} otherwise * @return this NavigatorUrlSchemeBuilder object to allow for chaining of method calls */ public NavigatorUrlSchemeBuilder setOptimize(boolean optimize) { mOptimize = optimize; return this; } /** * Sets the travel mode - this may be one of the static {@link EsriTravelMode} properties, or it * can be a custom value if the map's transportation network supports it. * * @param travelMode the travel mode name * @return this NavigatorUrlSchemeBuilder object to allow for chaining of method calls */ public NavigatorUrlSchemeBuilder setTravelMode(String travelMode) { mTravelMode = travelMode; return this; } /** * Sets the navigate flag * * @param navigate {@code true} if Navigator should automatically start navigating, {@code false} otherwise * @return this NavigatorUrlSchemeBuilder object to allow for chaining of method calls */ public NavigatorUrlSchemeBuilder setNavigate(boolean navigate) { mNavigate = navigate; return this; } /** * Sets the callback, which should be registered as the {@code data} node of an activity's * {@code intent-filter} in the manifest. * * @param callbackUri the callback * @return this NavigatorUrlSchemeBuilder object to allow for chaining of method calls */ public NavigatorUrlSchemeBuilder setCallbackUri(String callbackUri) { mCallbackUri = callbackUri; return this; } /** * Sets the callback prompt which will be shown when navigation completes. * * @param callbackPrompt the callback prompt * @return this NavigatorUrlSchemeBuilder object to allow for chaining of method calls */ public NavigatorUrlSchemeBuilder setCallbackPrompt(String callbackPrompt) { mCallbackPrompt = callbackPrompt; return this; } /** * Creates a Uri object which has query parameters based on the values that have been previously * passed to this builder. * * @return the Uri */ public Uri buildUri() { Uri.Builder builder = new Uri.Builder() .scheme(NAVIGATOR_SCHEME) .authority(""); if (mStart != null) { builder.appendQueryParameter(START_PARAM, encode(mStart.getValue())); String name = mStart.getName(); if (name != null) { builder.appendQueryParameter(START_NAME_PARAM, encode(name)); } } if (!mStops.isEmpty()) { for (Stop stop : mStops) { builder.appendQueryParameter(STOP_PARAM, encode(stop.getValue())); String name = stop.getName(); if (name != null) { builder.appendQueryParameter(STOP_NAME_PARAM, encode(name)); } } } else { throw new RuntimeException("Must have at least one stop!"); } if (mOptimize != null) { builder.appendQueryParameter(OPTIMIZE_PARAM, Boolean.toString(mOptimize)); } if (mTravelMode != null) { mTravelMode = mTravelMode.trim(); if (!TextUtils.isEmpty(mTravelMode)) { builder.appendQueryParameter(TRAVEL_MODE_PARAM, encode(mTravelMode)); } } if (mNavigate != null) { builder.appendQueryParameter(NAVIGATE_PARAM, Boolean.toString(mNavigate)); } if (mCallbackUri != null) { builder.appendQueryParameter(CALLBACK_URI_PARAM, encode(mCallbackUri)); } if (mCallbackPrompt != null) { builder.appendQueryParameter(CALLBACK_PROMPT_PARAM, encode(mCallbackPrompt)); } return builder.build(); } public Intent buildIntent() { Uri uri = buildUri(); return new Intent(Intent.ACTION_VIEW, uri); } //endregion public methods //region private methods private static String encode(String value) { try { return URLEncoder.encode(value, CHARSET); } catch (UnsupportedEncodingException e) { return Uri.encode(value); } } //endregion private methods //region private inner classes abstract private class Stop { private String mName; abstract String getValue(); public Stop(String name) { mName = name; } public String getName() { return mName; } } private class Wgs84Stop extends Stop { private double mLatitude; private double mLongitude; public Wgs84Stop( @FloatRange(from = -90, to = 90) double latitude, @FloatRange(from = -180, to = 180) double longitude, String name) { super(name); mLatitude = latitude; mLongitude = longitude; } @Override String getValue() { return Double.toString(mLatitude) + "," + Double.toString(mLongitude); } } private class AddressStop extends Stop { private String mAddress; public AddressStop(@NonNull String address, String name) { super(name); mAddress = address; } @Override public String getValue() { return mAddress; } } //endregion private inner classes }
JoelWhitney/navigator-integration
<|start_filename|>Toon/ToonLight.cs<|end_filename|> using System.Collections; using System.Collections.Generic; using UnityEngine; // Add script to lighting source // Updates toon shadows for toon shader public class ToonLight : MonoBehaviour { private Light light = null; private void OnEnable() { light = this.GetComponent<Light>(); } void Update() { Shader.SetGlobalVector("_ToonLightDirection", -this.transform.forward); } }
Kattarin/Shader-Graph-Examples
<|start_filename|>.release-it.json<|end_filename|> { "hooks": { "before:bump": "sed -E -i '' 's/^const buildVersion = .*$/const buildVersion = \"${version}\"/' cmd/docker-ipv6nat/main.go", "after:bump": "./push.sh ${version}", "after:release": "rm -Rf dist/" }, "git": { "commitMessage": "Release v${version}", "tagName": "v${version}", "tagAnnotation": "docker-ipv6nat v${version}" }, "github": { "release": true, "releaseName": "${version}", "draft": true, "assets": [ "dist/*" ] } }
justinsane-code/docker-ipv6nat
<|start_filename|>js/package.json<|end_filename|> { "name": "@confio/ics23", "version": "0.6.5", "description": "Merkle proof verification library - implements Cosmos ICS23 Spec", "main": "build/index.js", "types": "build/index.d.ts", "repository": { "type": "git", "url": "https://github.com/confio/ics23/tree/master/js" }, "publishConfig": { "access": "public", "registry": "https://registry.npmjs.org/" }, "author": "<NAME>", "license": "Apache-2.0", "private": false, "files": [ "build/**", "yarn.lock" ], "scripts": { "lint": "tslint -t verbose --project .", "format": "prettier --write --loglevel warn \"./src/**/*.ts\"", "prebuild": "yarn lint && yarn format", "prepublish": "yarn build", "test": "yarn -s build && node jasmine-testrunner.js", "build": "shx rm -rf ./build && tsc && shx cp -r src/generated build/generated", "pack-proto": "pbjs -t static-module -w commonjs -o src/generated/codecimpl.js ../proofs.proto", "define-proto": "pbts src/generated/codecimpl.js -o src/generated/codecimpl.d.ts", "protoc": "yarn pack-proto && yarn define-proto && yarn format" }, "devDependencies": { "@types/jasmine": "^3.5.0", "@types/ripemd160": "^2.0.0", "@types/sha.js": "^2.4.0", "jasmine": "^3.5.0", "jasmine-console-reporter": "^3.1.0", "prettier": "^1.17.0", "shx": "^0.3.2", "source-map-support": "^0.5.16", "tslint": "^5.8.0", "tslint-config-prettier": "^1.18.0", "tslint-immutable": "^6.0.1", "typescript": "^3.8.3" }, "dependencies": { "protobufjs": "^6.8.8", "ripemd160": "^2.0.2", "sha.js": "^2.4.11", "js-sha512": "^0.8.0" } }
yito88/ics23
<|start_filename|>public/stylesheets/ui/docs.css<|end_filename|> #docs { position: static; padding: 20px 25px 30px 50px; color: #555; background: #fff; font: 14px/18px Helvetica, Arial; } #docs h1, #docs h2, #docs h3 { font: 25px/50px Helvetica, Arial; color: #222; margin: 40px 0 10px 0; } #docs h2 { font: 18px/40px Helvetica, Arial; } #docs h3 { margin-top: 25px; font: 14px Helvetica, Arial; } #docs p, #docs form, #docs pre { position: relative; margin: 0 0 20px 0; width: 600px; } #docs ul { list-style: disc; padding-left: 20px; } #docs li { margin-bottom: 10px; width: 580px; } #docs table { margin: 20px 0 20px 0; width: 600px; border-top: 1px solid #bbb; border-left: 1px solid #bbb; } #docs th { text-transform: uppercase; font: 10px Helvetica, Arial; color: #222; } #docs th, #docs td { padding: 5px 20px 5px 10px; border-bottom: 1px solid #bbb; border-right: 1px solid #bbb; vertical-align: middle; line-height: 16px; } #docs td { font-size: 12px; background: #f0fafa; } #docs .alt > td { background: #f4f4f4; } #docs .param { font-weight: bold; } #docs .desc { font: italic 11px Helvetica, Arial; color: #555; } #docs table col.parameter { font-weight: bold; } #docs a { color: #000; text-decoration: underline; } #docs label { font: 12px/12px Helvetica, Arial; } #docs pre, #docs tt, #docs #search_results { font: 12px/18px "Monaco", monospace; } #docs #search_results { margin: 35px 0 0 0; } #docs .text_input { position: absolute; display: block; margin: 0 0 0 140px; width: 380px; } #docs .minibutton { position: absolute; right: 5px; margin-top: 3px; } <|start_filename|>public/javascripts/editor/reorder_pages_editor.js<|end_filename|> dc.ui.ReorderPagesEditor = dc.ui.EditorToolbar.extend({ id : 'reorder_pages_container', events : { 'click .reorder_pages_confirm_input' : 'confirmReorderPages', 'click .close_editor' : 'close' }, initialize : function(options) { this.editor = options.editor; }, findSelectors : function() { this.$s = { guide : $('#edit_reorder_pages_guide'), guideButton: $('.edit_reorder_pages'), page : $('.DV-page,.DV-thumbnail'), thumbnails : $('.DV-thumbnails'), pages : $('.DV-pages'), viewerContainer : $('.DV-docViewer-Container'), header : $('#reorder_pages_container'), container : null, saveButton : $('.reorder_pages_confirm_input') }; }, open : function() { $(this.el).show(); this.findSelectors(); this.setMode('is', 'open'); this.viewer.api.enterReorderPagesMode(); this.viewer.api.resetReorderedPages(); this.render(); this.orderChanged = false; this.$s.guide.fadeIn('fast'); this.$s.guideButton.addClass('open'); this.$s.saveButton.setMode('not', 'enabled'); this.hideSelectedThumbnail(); }, render : function() { $(this.el).html(JST['reorder_pages']({})); this.$s.viewerContainer.append(this.el); this.findSelectors(); if (this.viewer.state != 'ViewThumbnails') { this.viewer.open('ViewThumbnails'); } this.$s.pages.addClass('reorder_pages_viewer'); this.$s.container = $(this.el); $('.DV-currentPageImage', this.$s.thumbnails).removeClass('DV-currentPageImage') .addClass('DV-currentPageImage-disabled'); this.handleEvents(); this.initialOrder = this.serializePageOrder(); }, handleEvents : function() { var $thumbnails = this.$s.thumbnails; $('.DV-thumbnail', $thumbnails).each(function(i) { $(this).attr('data-pageNumber', i+1); }); $('.DV-currentPageImage', $thumbnails).removeClass('DV-currentPageImage').addClass('DV-currentPageImage-disabled'); jQuery('.DV-thumbnails').sortable({ containment: '.DV-thumbnails', items: '.DV-thumbnail', handle: '.DV-thumbnail-page', cursor: 'move', scrollSensitivity: 80, scrollSpeed: 15, tolerance: 'pointer', zIndex: 10, stop: _.bind(function(e, ui) { this.refreshHeader(); }, this) }); }, refreshHeader : function() { var changed = !_.isEqual(this.serializePageOrder(), this.initialOrder); this.orderChanged = changed; this.$s.saveButton.setMode(changed ? 'is' : 'not', 'enabled'); this.editor.setSaveState(changed); }, confirmReorderPages : function() { if (!this.orderChanged) return; dc.ui.Dialog.confirm("You've reordered the pages in this document. The document will close while it's being rebuilt. Are you sure you're ready to proceed?", _.bind(function() { $('input.reorder_pages_confirm_input', this.el).val('Reordering...').attr('disabled', true); this.save(); return true; }, this)); }, serializePageOrder : function() { var pageOrder = []; $('.DV-thumbnail', this.$s.thumbnails).each(function() { pageOrder.push(parseInt($(this).attr('data-pageNumber'), 10)); }); return pageOrder; }, save : function() { dc.ui.Dialog.progress("Reordering Pages&hellip;"); var pageOrder = this.serializePageOrder(); var modelId = this.viewer.api.getModelId(); $.ajax({ url : '/documents/' + modelId + '/reorder_pages', type : 'POST', data : { page_order : pageOrder }, dataType : 'json', success : function(resp) { try { window.opener && window.opener.Documents && window.opener.Documents.get(modelId).set(resp); } catch (e) { // It's alright. } window.close(); _.defer(dc.ui.Dialog.alert, "The pages are being reordered. Please close this document."); } }); }, close : function() { if (this.modes.open == 'is') { this.editor.setSaveState(); $('.DV-currentPageImage-disabled', this.$s.page).addClass('DV-currentPageImage').removeClass('DV-currentPageImage-disabled'); this.setMode('not', 'open'); jQuery('.DV-thumbnails').sortable('destroy'); this.$s.guide.hide(); this.$s.guideButton.removeClass('open'); this.$s.pages.removeClass('reorder_pages_viewer'); $(this.el).hide(); this.viewer.api.leaveReorderPagesMode(); } } }); <|start_filename|>public/javascripts/ui/workspace/sidebar.js<|end_filename|> // The Sidebar. Switches contexts between different subviews. dc.ui.Sidebar = Backbone.View.extend({ id : 'sidebar', render : function() { $(this.el).html(JST['workspace/sidebar']({})); this.content = this.$('#sidebar_content'); dc.app.scroller = (new dc.ui.Scroll(this.content)).render(); return this; }, add : function(containerName, view) { this.$('#' + containerName + '_container').append(view); } }); <|start_filename|>public/javascripts/model/access.js<|end_filename|> // Keep this file in sync with lib/dc/access.rb dc.access = { DELETED : 0, // The document was deleted, and will be removed soon. PRIVATE : 1, // The document is only visible to it's owner. ORGANIZATION : 2, // Visible to both the owner and her organization. EXCLUSIVE : 3, // Published, but exclusive to the owner's organization. PUBLIC : 4, // Free and public to all. PENDING : 5, // The document is being processed (acts as disabled). INVISIBLE : 6, // The document has been taken down (perhaps temporary). ERROR : 7, // The document is broken, or failed to import. // The inverse mapping, from access levels back to strings. NAMES : { 0 : 'deleted', 1 : 'private', 2 : 'organization', 3 : 'exclusive', 4 : 'public', 5 : 'pending', 6 : 'invisible', 7 : 'error' } }; <|start_filename|>public/javascripts/lib/core/restful_set.js<|end_filename|> // RESTful sets must specify a 'resource'. // create => POST /resource // destroy => DELETE /resource/id // update => PUT /resource/id // populate => GET /resource dc.model.RESTfulSet = dc.Set.extend({ populated : false, constructor : function() { if (!this.resource) throw new Error('dc.model.RESTfulSet: Unspecified resource'); this.base(); }, // Create a model on the server and add it to the set. // When the server returns a JSON representation of the model, we update it // on the client. create : function(model, attributes, options) { options = options || {}; if (attributes) model.set(attributes); if (!this.include(model)) this.add(model); $.ajax({ url : '/' + this.resource, type : 'POST', data : {json : JSON.stringify(model.attributes())}, dataType : 'json', success : _.bind(this._handleSuccess, this, model, options.success), error : _.bind(this._handleError, this, model, options.error, null) }); }, // Destroy a model on the server and remove it from the set. destroy : function(model, options) { options = options || {}; this.remove(model); $.ajax({ url : '/' + this.resource + '/' + model.id, type : 'POST', data : {_method : 'delete'}, dataType : 'json', success : function(resp) { if (options.success) options.success(model, resp); }, error : _.bind(function(resp) { this.add(model); this._handleError(model, options.error, null, resp); }, this) }); }, // Update a model on the server and (optionally) the client. // Pass only a model to persist its current attributes to the server. update : function(model, attributes, options) { options = options || {}; var previous = attributes ? model.attributes() : null; if (attributes) model.set(attributes); $.ajax({ url : '/' + this.resource + '/' + model.id, type : 'POST', data : {json : JSON.stringify(model.attributes()), _method : 'put'}, dataType : 'json', success : _.bind(this._handleSuccess, this, model, options.success), error : _.bind(this._handleError, this, model, options.error, previous) }); }, // Initialize the client-side set of models with its default contents. // Pass in the array of models in order to populate directly. populate : function(options) { options = options || {}; var me = this; var onSuccess = function(resp) { var models = _.map(resp[me.resource] || resp, function(attrs) { return new me.model(attrs); }); me.refresh(models); if (options.success) options.success(); }; this.populated = true; if (_.isArray(options)) return onSuccess(options); $.ajax({ url : '/' + this.resource, type : 'GET', dataType : 'json', success : onSuccess, error : function(req, textStatus, errorThrown) { if (req.status == 403) { Accounts.forceLogout(); } } }); }, _handleSuccess : function(model, callback, resp) { if (callback) return callback(model, resp); model.set(resp); }, _handleError : function(model, callback, previous, resp) { var json = JSON.parse(resp.responseText); if (callback) return callback(model, json); if (previous) model.set(previous); dc.ui.notifier.show({text : json.errors[0]}); } }); <|start_filename|>public/javascripts/app/editor.js<|end_filename|> // Main controller for the in-viewer document editor. Orchestrates subviews. dc.app.editor = new Backbone.View(); _.extend(dc.app.editor, { // Initializes the workspace, binding it to <body>. initialize : function(docId, options) { this.setElement('body'); this.docId = docId; this.options = options; _.bindAll(this, 'closeAllEditors', 'confirmStateChange'); dc.app.hotkeys.initialize(); this.createSubViews(); this.renderSubViews(); currentDocument.api.onChangeState(this.closeAllEditors); }, confirmStateChange : function(continuation) { if (this._openDialog) return; this._openDialog = dc.ui.Dialog.confirm('You have unsaved changes. Are you sure you want to leave without saving them?', continuation, {onClose : _.bind(function() { this._openDialog = null; }, this)}); }, setSaveState : function(unsaved) { this.unsavedChanges = unsaved; var confirmation = unsaved ? this.confirmStateChange : null; currentDocument.api.setConfirmStateChange(confirmation); }, // Create all of the requisite subviews. createSubViews : function() { dc.ui.notifier = new dc.ui.Notifier(); this.controlPanel = new dc.ui.ViewerControlPanel(); this.sectionEditor = new dc.ui.SectionEditor(); this.annotationEditor = new dc.ui.AnnotationEditor(); this.removePagesEditor = new dc.ui.RemovePagesEditor({editor : this}); this.reorderPagesEditor = new dc.ui.ReorderPagesEditor({editor : this}); this.editPageTextEditor = new dc.ui.EditPageTextEditor({editor : this}); this.replacePagesEditor = new dc.ui.ReplacePagesEditor({editor : this}); }, // Render all of the existing subviews and place them in the DOM. renderSubViews : function() { var access = 'DV-isContributor'; if (this.options.isReviewer) access = 'DV-isReviewer'; if (this.options.isOwner) access = 'DV-isOwner'; $('.DV-docViewer').addClass(access); $('.DV-well').append(this.controlPanel.render().el); $('.DV-logo').hide(); $('.DV-thumbnailsView').show(); currentDocument.api.roundTabCorners(); var supp = $('.DV-supplemental'); if (supp.hasClass('DV-noNavigation')) { supp.removeClass('DV-noNavigation').addClass('DV-noNavigationMargin'); } }, closeAllEditors : function() { this.removePagesEditor.close(); this.reorderPagesEditor.close(); this.replacePagesEditor.close(); this.editPageTextEditor.close(); return true; } }); <|start_filename|>public/stylesheets/pages/admin.css<|end_filename|> body { background: #fff; } #admin_actions { position: absolute; top: 8px; right: 35px; } #statistics { margin: 35px 0 35px 35px; } #statistics .download_csv { margin-left: 12px; } #statistics .float_right.text_link { padding-left: 8px; } #statistics table { width: 100%; } #statistics td { color: #222; padding: 0 35px 0 0; } #statistics .data td { } #statistics .number { font-size: 50px; border-bottom: 1px solid #131b1d; } #statistics .chart_col { position: relative; padding-bottom: 10px; height: 180px; } #statistics .chart { position: absolute; left: 0; right: 0; height: 180px; padding-bottom: 10px; border-bottom: 1px solid #131b1d; } #statistics .labels td, #statistics .data thead tr td { font-size: 10px; text-transform: uppercase; padding: 5px 35px 5px 0; } #statistics .labels td { padding: 5px 35px 50px 0; } #statistics .labels.top_documents_label_year { display: none; } #statistics td .sort { cursor: pointer; } #statistics td .sort.active { font-weight: bold; } #statistics td .sort:hover { text-decoration: underline; } #statistics .data table { border-bottom: 1px solid #131b1d; } #statistics .data table thead td { border-bottom: 1px solid #131b1d; } #statistics .data table tr { background: transparent; } #statistics .data tr td { color: #222; white-space: nowrap; font-size: 12px; } #statistics .data tbody tr td { padding: 5px 35px 5px 0; height: 25px; border-bottom: 1px solid #bbb; } #statistics #instances tbody tr td { line-height: 25px; } #statistics #numbers tbody tr td { line-height: 50px; font-size: 25px; padding-right: 75px; } #statistics #numbers td.first { font-size: 12px; } #statistics .data table tr td.first { padding-right: 0; vertical-align: top; } #statistics .data table tr td.last { width: 100%; } #statistics .data table img.avatar { margin: 1px 15px 1px 4px; border: 0; } #statistics .data table a { text-decoration: underline; } #statistics .data table .document_count .private { color: #844; } #statistics .documents tbody tr td { line-height: 45px; } #statistics .documents td.first { width: 30px; padding: 7px 0 7px 0; } #statistics .documents .doc { width: 30px; height: 37.5px; } #statistics .login_as .minibutton { display: none; } #statistics .display_view:hover .login_as .minibutton { display: block; } #statistics .notes tbody tr td { line-height: 20px; vertical-align: middle; padding-top: 8px; padding-bottom: 8px; } #statistics .data .searches tbody td { padding-top: 8px; padding-bottom: 8px; height: auto; line-height: 20px; vertical-align: middle; } .icon.minus { position: absolute; margin-top: 5px; cursor: pointer; } <|start_filename|>public/stylesheets/ui/entities.css<|end_filename|> /* Spark Entities inside of Document Tiles ---------------------------------------*/ .document .entities { overflow: hidden; position: relative; margin: 20px -50px 0 -20px; padding-left: 20px; } .document .entities .cancel_search { float: left; cursor: pointer; margin: 1px 7px 0 0; } .document .entity_group { margin: 0 50px 25px 0; float: left; } .document .entity_group_header { margin-bottom: 8px; } .document .entity_group_title { margin-right: 10px; font-weight: bold; } .document .entity_line { line-height: 19px; padding: 5px 0; } .document .entity_line_title { width: 112px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; color: #333; position: absolute; } .document .entity_buckets { position: relative; margin-left: 120px; height: 19px; overflow: hidden; } .document .entity_rule { position: absolute; background: #eee; width: 100%; top: 9px; left: 0; height: 1px; } .document .entity_bucket_wrap { position: relative; display: block; float: left; width: 3px; height: 19px; padding-right: 1px; cursor: pointer; } .document .entity_bucket { position: absolute; top: 50%; width: 3px; background: #ccc; background: rgba(0,0,0,0.3); } .document .entity_bucket_wrap.active .entity_bucket { background: #999; background: rgba(0,0,0,0.5); } .document .entity_list { line-height: 18px; } .document .entities .arrow.left { top: 1px; margin-left: 2px; } <|start_filename|>public/javascripts/editor/edit_page_text_editor.js<|end_filename|> dc.ui.EditPageTextEditor = dc.ui.EditorToolbar.extend({ id : 'edit_page_text_container', events : { 'click .edit_page_text_confirm_input' : 'confirmEditPageText', 'click .document_page_tile_remove' : 'resetPage', 'click .close_editor' : 'close' }, initialize : function(opts) { this.editor = opts.editor; _.bindAll(this, 'cachePageText'); }, _resetState : function() { this.originalPageText = {}; this.pageText = {}; }, findSelectors : function() { this.$s = { guide : $('#edit_page_text_guide'), guideButton: $('.edit_page_text.button'), page : $('.DV-text'), pages : $('.DV-pages'), viewerContainer : $('.DV-docViewer-Container'), header : $('#edit_page_text_container'), container : null, saveButton : $('.edit_page_text_confirm_input', this.el), headerTiles : $('.document_page_tiles', this.el) }; }, open : function() { $(this.el).show(); this.findSelectors(); this._resetState(); this.setMode('is', 'open'); this.viewer.api.enterEditPageTextMode(); this.render(); }, render : function() { $(this.el).html(JST['edit_page_text']({})); this.$s.viewerContainer.append(this.el); if (this.viewer.state != 'ViewText') { this.viewer.open('ViewText'); } this.$s.pages.addClass('edit_page_text_viewer'); this.$s.container = $(this.el); this.findSelectors(); this.$s.guideButton.addClass('open'); this.$s.guide.fadeIn('fast'); this.$s.saveButton.setMode('not', 'enabled'); this.$s.header.removeClass('active'); this.handleEvents(); }, handleEvents : function() { $('.DV-textContents').parent().delegate('.DV-textContents', 'keyup', this.cachePageText).delegate('.DV-textContents', 'change', this.cachePageText); }, getPageNumber : function() { return this.viewer.api.currentPage(); }, getPageText : function(pageNumber) { pageNumber = pageNumber || this.getPageNumber(); return this.viewer.api.getPageText(pageNumber); }, confirmEditPageText : function() { var modifiedPages = this.getChangedPageTextPages(); var documentId = this.viewer.api.getModelId(); var dialog = dc.ui.Dialog.progress("Saving text edits&hellip;"); $.ajax({ url : '/documents/' + documentId + '/save_page_text', type : 'POST', data : { modified_pages : JSON.stringify(modifiedPages) }, dataType : 'json', success : _.bind(function(resp) { try { window.opener && window.opener.Documents && window.opener.Documents.get(documentId).set(resp); } catch (e) { // It's cool. } window.close(); dialog.close(); this.viewer.api.resetPageText(true); _.defer(dc.ui.Dialog.alert, "The page text is being saved. Please close this document."); }, this) }); }, setSaveState : function() { this.editor.setSaveState(!!_.keys(this.pageText).length); }, cachePageText : function() { var pageNumber = this.getPageNumber(); var pageText = dc.inflector.trim($('.DV-textContents').textWithNewlines()); if (!(pageNumber in this.originalPageText)) { this.originalPageText[pageNumber] = $.trim(this.getPageText(pageNumber)); } if (pageText != this.originalPageText[pageNumber]) { if (!(pageNumber in this.pageText)) { this.redrawHeader(); } this.pageText[pageNumber] = pageText; } else { delete this.originalPageText[pageNumber]; delete this.pageText[pageNumber]; this.redrawHeader(); } this.setSaveState(); this.viewer.api.setPageText(pageText, pageNumber); }, resetPage : function(e) { var pageNumber = $(e.currentTarget).parents('.document_page_tile').attr('data-pageNumber'); this.viewer.api.setPageText(this.originalPageText[pageNumber], pageNumber); this.viewer.api.enterEditPageTextMode(); delete this.originalPageText[pageNumber]; delete this.pageText[pageNumber]; this.setSaveState(); this.redrawHeader(); }, redrawHeader : function() { var saveText; var editedPages = _.keys(this.originalPageText); var pageCount = editedPages.length; editedPages = editedPages.sort(function(a, b) { return a - b; }); $('.document_page_tile', this.$s.headerTiles).empty().remove(); if (pageCount == 0) { this.$s.header.removeClass('active'); this.$s.saveButton.setMode('not', 'enabled'); } else { this.$s.header.addClass('active'); this.$s.saveButton.setMode('is', 'enabled'); } // Create each page tile and add it to the page holder _.each(editedPages, _.bind(function(pageNumber) { var url = this.imageUrl; url = url.replace(/\{size\}/, 'thumbnail'); url = url.replace(/\{page\}/, pageNumber); var $thumbnail = $(JST['document_page_tile']({ url : url, pageNumber : pageNumber })); $thumbnail.attr('data-pageNumber', pageNumber); this.$s.headerTiles.append($thumbnail); }, this)); // Update remove button's text if (pageCount == 0) { saveText = 'Save page text'; } else { saveText = 'Save ' + pageCount + dc.inflector.pluralize(' page', pageCount); } $('.edit_page_text_confirm_input', this.el).val(saveText); // Set width of container for side-scrolling var width = $('.document_page_tile').length * $('.document_page_tile').eq(0).outerWidth(true); var confirmWidth = $('.editor_toolbar_controls', this.el).outerWidth(true); this.$s.headerTiles.width(width + confirmWidth + 10); Backbone.View.prototype.delegateEvents.call(this); }, getChangedPageTextPages : function() { var modifiedPages = {}; _.each(this.pageText, _.bind(function(pageText, pageNumber) { if (this.originalPageText[pageNumber] != pageText) { modifiedPages[pageNumber] = pageText; } }, this)); return modifiedPages; }, close : function() { if (this.modes.open == 'is') { this._resetState(); this.setSaveState(); this.setMode('not', 'open'); this.$s.guideButton.removeClass('open'); this.$s.guide.hide(); this.$s.pages.removeClass('edit_page_text_viewer'); $('.DV-textContents').attr('contentEditable', false).removeClass('DV-editing'); $(this.el).hide(); this.viewer.api.leaveEditPageTextMode(); } } }); <|start_filename|>public/javascripts/ui/workspace/panel.js<|end_filename|> // The main central panel. Switches contexts between different subviews. dc.ui.Panel = Backbone.View.extend({ className : 'panel_container', initialize : function() { _.bindAll(this, '_setMinHeight'); }, render : function() { $(this.el).html(JST['workspace/panel']({})); this.content = this.$('.panel_content'); $(window).resize(this._setMinHeight); _.defer(this._setMinHeight); return this; }, add : function(containerName, view) { this.$('#' + containerName + '_container').append(view); }, _setMinHeight : function() { $(this.el).css({"min-height": $(window).height() - 100}); } }); <|start_filename|>public/stylesheets/pages/static.css<|end_filename|> body { font-family: Arial, sans-serif; background: white; } a { cursor: pointer; color: #536eac; text-decoration: none; } a:hover { color: #000055; } h1, h2, h3, h4, h5, h6 { font-size: 16px; line-height: 22px; margin: 22px 0 11px 0; font-weight: bold; } h1, #content.static #help h1 { font-size: 20px; margin: 30px 0 22px 0; } h2, #content.static #help h2 { font-size: 16px; margin: 22px 0 11px 0; } h3, #content.static #help h3 { font-size: 15px; } small { font-size: 12px; line-height: 22px; } small.up { font: 10px Arial, sans-serif; text-transform: uppercase; } #container { position: relative; width: 700px; margin: 20px auto 0; padding: 0 0 50px 175px; color: black; } #content { padding-bottom: 50px; font: 15px/22px 'Palatino Linotype', 'Book Antiqua', Palatino, FreeSerif, serif; } #content p, #content.static #help p { margin: 22px 0; } #content p.intro { font-size: 18px; } #content #login { border: 1px solid #536eac; background: #EEE; float: right; width: 140px; padding: 10px; margin: 0 5px; } #content #login p { margin: 5px 0; } #content ul, #content.static #help ul { margin: 0 0 0 22px; list-style-type: circle; color: #555; } #content ol { padding-left: 20px; } #content ol.decimal { list-style-type: decimal; } #content ol.lower_alpha { list-style-type: lower-alpha; } #content ol.lower_roman { list-style-type: lower-roman; } #content li, #content.static #help li { margin: 11px 0; } #content .home_splash { margin-top: 30px; font-size: 18px; line-height: 22px; } #content .screenshot { margin: 22px 0; position: relative; left: -20px; } #content img.framed { border: 8px solid #ddd; -ms-interpolation-mode: bicubic; } #content img.headshot { border: 3px solid #ddd; float: right; margin: 0 20px 20px 20px; } #sidebar { position: absolute; width: 155px; min-height: 500px; left: 0; } #cloud_edge { position: absolute; top: 3px; left: 80px; width: 67px; height: 30px; background: url(/images/embed/ui/cloud_edge.png) no-repeat; } #wordmark { left: 18px; position: absolute; color: #566eaa; font-size: 15px; top: 17px; } #navigation { height: 40px; margin-bottom: 20px; font-size: 15px; line-height: 50px; border-bottom: 1px solid #e2e2e2; } #navigation a { margin-right: 15px; } #navigation .active { color: #005; } #footer { font-size: 11px; line-height: 14px; color: #555; } #extras { margin: 44px 0 22px 0; } #blogposts { width: 400px; } #twitter { float: right; } #twitter .twtr-ft div * { display: none; } #content #help #help_navigation { margin: 0; padding: 0; position: absolute; left: 12px; width: 150px; } #content.static #help_navigation li { list-style: none; line-height: 18px; margin: 0 0 15px 0; } #help #help_navigation li.active a { color: black; text-decoration: none; } #content.static #help { font: inherit; display: block; padding: 0; max-width: inherit; color: #000; } #content.static #help ul { margin-left: 0; padding-left: 15px; color: #000; } #content.static #help ul li { padding-left: 5px; } #content.static #help h1 { font-size: 18px; } #content.static #help a { color: #536eac; } #content.static #help a:hover { color: #000055; text-decoration: none; } #content.static #help table td, #help table th { font-size: 14px; } #content.static #help .ajax_only { display: none; } #content.static #help .static_only { display: inline; } <|start_filename|>public/stylesheets/ui/print.css<|end_filename|> /* Print Notes Page ---------------------------------------*/ body.print_notes { background: #fff; margin: 0; } body.print_notes #document_list { width: 800px; margin: 0 auto; padding: 20px; background: #fff; border-radius: 4px; -moz-border-radius: 4px; -webkit-border-radius: 4px; } body.print_notes #document_list .document { padding-left: 0; } body.print_notes #document_list .select, body.print_notes #document_list .icon, body.print_notes #document_list .datalines, body.print_notes #document_list .show_notes { display: none; } body.print_notes #document_list .title { font-size: 20px; line-height: 28px; } body.print_notes .edit_glyph, body.print_notes .cancel_search { display: none !important; } <|start_filename|>public/javascripts/lib/selectable.js<|end_filename|> // Mixin for collections which should be made selectable. dc.model.Selectable = { firstSelection : null, selectedCount : 0, selectAll : function() { this.each(function(m){ m.set({selected : true}); }); }, deselectAll : function() { this.each(function(m){ m.set({selected : false}); }); }, selected : function() { return this.select(function(m){ return m.get('selected'); }); }, firstSelected : function() { return this.detect(function(m){ return m.get('selected'); }); }, selectedIds : function() { return _.pluck(this.selected(), 'id'); }, _resetSelection : function() { this.firstSelection = null; this.selectedCount = 0; }, _add : function(model, options) { var attrs = model.attributes || model; if (attrs.selected == null) attrs.selected = false; model = Backbone.Collection.prototype._add.call(this, model, options); if (model.get('selected')) this.selectedCount += 1; }, _remove : function(model, options) { model = Backbone.Collection.prototype._remove.call(this, model, options); if (this.selectedCount > 0 && model.get('selected')) this.selectedCount -= 1; }, // We override "_onModelEvent" to fire selection changed events when models // change their selected state. _onModelEvent : function(ev, model, error) { Backbone.Collection.prototype._onModelEvent.call(this, ev, model, error); if (ev != 'change') return; if (model.hasChanged('selected')) { var selected = model.get('selected'); if (selected && this.selectedCount == 0) { this.firstSelection = model; } else if (!selected && this.firstSelection == model) { this.firstSelection = null; } this.selectedCount += selected ? 1 : -1; _.defer(_(this.trigger).bind(this, 'select', this)); } } }; <|start_filename|>config/server/secrets/pixel_ping/development.json<|end_filename|> { "port": "9187", "host": "dev.dcloud.org", "interval": 5, "endpoint": "http://dev.dcloud.org/admin/save_analytics", "secret": "DocumentCloud" } <|start_filename|>public/javascripts/lib/inflector.js<|end_filename|> // Naive English transformations on words. window.dc || (window.dc = {}); dc.inflector = { small : "(a|an|and|as|at|but|by|en|for|if|in|of|on|or|the|to|v[.]?|via|vs[.]?)", punct : "([!\"#$%&'()*+,./:;<=>?@[\\\\\\]^_`{|}~-]*)", // Titleize function by <NAME> after <NAME>. MIT Licensed. titleize : function(s) { s = s.replace(/[-.\/_]/g, ' ').replace(/\s+/gm, ' '); var cap = this.capitalize; var parts = [], split = /[:.;?!] |(?: |^)["Ò]/g, index = 0; while (true) { var m = split.exec(s); parts.push( s.substring(index, m ? m.index : s.length) .replace(/\b([A-Za-z][a-z.'Õ]*)\b/g, function(all){ return (/[A-Za-z]\.[A-Za-z]/).test(all) ? all : cap(all); }) .replace(RegExp("\\b" + this.small + "\\b", "ig"), this.lowercase) .replace(RegExp("^" + this.punct + this.small + "\\b", "ig"), function(all, punct, word) { return punct + cap(word); }) .replace(RegExp("\\b" + this.small + this.punct + "$", "ig"), cap)); index = split.lastIndex; if ( m ) parts.push( m[0] ); else break; } return parts.join("").replace(/ V(s?)\. /ig, " v$1. ") .replace(/(['Õ])S\b/ig, "$1s") .replace(/\b(AT&T|Q&A)\b/ig, function(all){ return all.toUpperCase(); }); }, // Delegate to the ECMA5 String.prototype.trim function, if available. trim : function(s) { return s.trim ? s.trim() : s.replace(/^\s+|\s+$/g, ''); }, // Remove runs of whitespace. squeeze : function(s) { return s.replace(/\s+/g, ' '); }, // Trim leading and trailing non-whitespace characters, and add ellipses. // Try to find natural breaks in the sentence, and avoid breaking HTML fragments. trimExcerpt : function(s) { s = s.replace(/^([^<>]{0,100}?[.,!]|[^<>\s]+)/g, ''); s = s.replace(/(([.,!]\s?)[^<>]{0,100}?|[^<>\s]+)$/g, '$2'); return '&hellip;' + s + '&hellip;'; }, camelize : function(s) { var parts = s.split('-'), len = parts.length; if (len == 1) return parts[0]; var camelized = s.charAt(0) == '-' ? parts[0].charAt(0).toUpperCase() + parts[0].substring(1) : parts[0]; for (var i = 1; i < len; i++) camelized += parts[i].charAt(0).toUpperCase() + parts[i].substring(1); return camelized; }, lowercase : function(s) { return s.toLowerCase(); }, capitalize : function(s) { return s.charAt(0).toUpperCase() + s.substring(1).toLowerCase(); }, underscore : function(s) { return s.replace(/::/g, '/').replace(/([A-Z]+)([A-Z][a-z])/g,'$1_$2').replace(/([a-z\d])([A-Z])/g,'$1_$2').replace(/-/g,'_').toLowerCase(); }, spacify : function(s) { return s.replace(/_/g, ' '); }, dasherize : function(s) { return s.replace(/_/g,'-'); }, singularize : function(s) { return s.replace(/s$/, ''); }, // Only works for words that pluralize by adding an 's', end in a 'y', or // that we've special-cased. Not comprehensive. pluralize : function(s, count) { if (count == 1) return s; if (s == 'this') return 'these'; if (s == 'person') return 'people'; if (s.match(/day$/i)) return s.replace(/day$/i, 'days'); if (s.match(/y$/i)) return s.replace(/y$/i, 'ies'); return s + 's'; }, classify : function(s) { return this.camelize(this.capitalize(this.dasherize(this.singularize(s)))); }, possessivize : function(s) { var endsInS = s.charAt(s.length - 1) == 's'; return s + (endsInS ? "'" : "'s"); }, truncate : function(s, length, truncation) { length = length || 30; truncation = truncation == null ? '...' : truncation; return s.length > length ? s.slice(0, length - truncation.length) + truncation : s; }, truncateWords : function(s, length, truncation) { length = length || 30; truncation = truncation == null ? '...' : truncation; if (s.length > length) { var reversedString = s.substr(0, length).split('').reverse().join(''); var indexWordBoundary = reversedString.search(/\W\w/); if (indexWordBoundary != -1) { s = s.substr(0, length-indexWordBoundary-1) + truncation; } else { s = this.truncate(s, length, truncation); } } return s; }, // Convert a string (usually a title), to something appropriate for use in a URL. // Apostrophes and quotes are removed, non-word-chars become spaces, whitespace // is trimmed, lowercased, and spaces become dashes. sluggify : function(s) { return this.trim(s.replace(/['"]+/g, '').replace(/\W+/g, ' ')).toLowerCase().replace(/\s+/g, '-'); }, commify : function(list, options) { var words = []; for (var i = 0, l = list.length; i < l; i++) { var word = list[i]; if (options.quote) word = '"' + word + '"'; words.push(word); var end = i == list.length - 1 ? '' : (i == list.length - 2) && options.conjunction ? ', ' + options.conjunction + ' ' : ', '; words.push(end); } return words.join(''); }, // Autolink URLs and (optionally) @twitter ids. autolink : function(text, twitter) { text = text.replace(/(https?:\/\/([a-z0-9]([-a-z0-9]*[a-z0-9])?\.)+([a-zA-z]{2,6})(\/[a-zA-Z0-9$_.+!#*(),;\/?:@&~=%-]*)?)/g, '<a href="$1">$1</a>'); if (twitter) text = text.replace(/(^|\s)@(\w{1,15})/g, '$1<a href="http://twitter.com/$2">@$2</a>'); return text; }, // Convert bytes into KB or MB bytesToMB : function(bytes) { var byteSize = Math.round(bytes / 1024 * 100) * 0.01; var suffix = 'KB'; if (byteSize > 1000) { byteSize = Math.round(byteSize * 0.001 * 100) * 0.01; suffix = 'MB'; } var sizeParts = byteSize.toString().split('.'); byteSize = sizeParts[0] + (sizeParts.length > 1 ? '.' + sizeParts[1].substr(0,1) : ''); return byteSize + ' ' + suffix; }, // Normalize an entered-by-hand url, trimming and adding the protocol, if missing. normalizeUrl : function(s) { s = dc.inflector.trim(s); if (!s) return null; return (/^https?:\/\//).test(s) ? s : 'http://' + s; }, // From Prototype.js. Strip out HTML tags. stripTags : function(s) { return s.replace(/<\w+(\s*("[^"]*"|'[^']*'|[^>])+)?>|<\/\w+>/gi, ''); }, escapeRegExp : function(s) { return s.replace(/([.*+?^${}()|[\]\/\\])/g, '\\$1'); }, escapeHTML : function(s) { return s.replace(/&(?!\w+;)/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;'); } }; <|start_filename|>public/stylesheets/ui/timeline.css<|end_filename|> /*------------------------------ TIMELINE ---------------------------------*/ #timeline_dialog { max-width: none; width: 800px; } #timeline_dialog .text { padding: 3px 3px 20px 3px; } #timeline_dialog .cancel { display: none; } #timeline_dialog .timeline_plot { width: 800px; cursor: default; } #timeline_dialog .tickLabel { font-size: 11px; color: #ccc; } #timeline_dialog .zoom_out { width: 80px; } <|start_filename|>public/javascripts/app/preferences.js<|end_filename|> // Read and write preferences for the browser, using a cookie. dc.app.cookies = { // Read a cookie by name. get : function(name) { var matcher = new RegExp("\\s*" + name + "=(.*)$"); var list = document.cookie.split(';'); var cookie = _.detect(list, function(c) { return c.match(matcher); }); return cookie ? decodeURIComponent(cookie.match(matcher)[1]) : null; }, // Write a cookie's value, and keep it only for the session (default), or // forever (2 years). set : function(name, value, keep) { var expiration = keep ? new Date() : null; if (expiration) keep == 'remove' ? expiration.setYear(expiration.getFullYear() - 1) : expiration.setYear(expiration.getFullYear() + 2); var date = expiration ? '; expires=' + expiration.toUTCString() : ''; document.cookie = name + '=' + encodeURIComponent(value) + '; path=/' + date; }, // Remove a cookie. remove : function(name) { this.set(name, this.get(name), 'remove'); } }; dc.app.preferences = { get : function(name, valid) { var value = this._prefs()[name]; return (!value || (valid && !_.include(valid, value))) ? null : value; }, set : function(obj) { this._setPrefs(_.extend(this._prefs(), obj)); }, remove : function(name) { var prefs = this._prefs(); delete prefs[name]; this._setPrefs(prefs); }, _prefs : function() { return JSON.parse(dc.app.cookies.get('document_cloud_preferences') || '{}'); }, _setPrefs : function(obj) { dc.app.cookies.set('document_cloud_preferences', JSON.stringify(obj), true); } }; <|start_filename|>public/javascripts/editor/editor_toolbar.js<|end_filename|> dc.ui.EditorToolbar = Backbone.View.extend({ className : 'editor_toolbar interface', constructor: function() { Backbone.View.apply(this, arguments); this.modes = {}; this.viewer = currentDocument; this.imageUrl = this.viewer.schema.document.resources.page.image; }, toggle : function() { if (this.modes.open == 'is') { this.close(); this.showSelectedThumbnail(); } else { dc.app.editor.closeAllEditors(); this.open(); } }, showSelectedThumbnail : function() { $('.DV-thumbnail.DV-originallySelected').removeClass('DV-originallySelected').addClass('DV-selected'); }, hideSelectedThumbnail : function() { $('.DV-thumbnail.DV-selected').removeClass('DV-selected').addClass('DV-originallySelected'); } }); <|start_filename|>public/javascripts/dev/dev.js<|end_filename|> if (!window.console || !window.console.log) { window.console = {}; var _$ied; window.console.log = function(msg) { if (_.isArray(msg)) { var message = msg[0]; var vars = _.map(msg.slice(1), function(arg) { return JSON.stringify(arg); }).join(' - '); } if(!_$ied){ _$ied = $('<div><ol></ol></div>').css({ 'position': 'fixed', 'bottom': 10, 'left': 10, 'zIndex': 20000, 'width': $('body').width() - 80, 'border': '1px solid #000', 'padding': '10px', 'backgroundColor': '#fff', 'fontFamily': 'arial,helvetica,sans-serif', 'fontSize': '11px' }); $('body').append(_$ied); } var $message = $('<li>'+message+' - '+vars+'</li>').css({ 'borderBottom': '1px solid #999999' }); _$ied.find('ol').append($message); _.delay(function() { $message.fadeOut(500); }, 2000); }; } <|start_filename|>public/stylesheets/pages/embedded_login.css<|end_filename|> div.full_page_background { position: absolute; top: 41px; bottom: 0; left: 0; right: 0; background: #f1f1f1; background: -webkit-gradient(radial, center top, 0, 0 0, 1500, from(rgb(250,250,250)), to(rgb(200,200,200))); background: -moz-radial-gradient(center top, circle cover, rgb(250,250,250) 0%, rgb(200,200,200) 100%); overflow: hidden; } #logo #wordmark { cursor: default; } #additional_information h3{ font-size: 1.2em; text-align: center; font-weight: strong; } #additional_information .minibutton { font-size: 16px; height: 22px; margin-top: 0; padding: 0 20px; position: relative; top: 10px; left: 30%; } #additional_information label { text-align: left; margin: 10px 0; } #login_form, #additional_information { width: 300px; margin: 0 auto; } #login_form .text_input { margin: 0.3em; } #login_form #login_button { margin: 10px 0; display: inline-block; } #login_form .login_services { margin: 5px 0; text-align: center; } #login_flash h1 { text-align: center; color: #566eaa; font: bold 24px Arial; text-shadow: 0px 1px 1px #fff; margin-top: 2em; } /* overrides for workspace css in order to work better on small window */ #full_screen_form { top: 8px; } #full_screen_form form { padding: 0; } #full_screen_form .line { width: 100%; margin: 10px auto; height: 30px; } #full_screen_form h1 { font-size: 18px; } #full_screen_form label { padding-top: 8px; width: 125px; } .full_page_background .example.long { margin-left: 140px; } #full_screen_form .text_input { margin: 0 0 0 135px; width: 250px; } #full_screen_form .minibutton { left: 100px; top: 15px; } .full_page_background .example.long { margin-left: 40px; } .full_page_background .example { display: none; } #full_screen_form .login_services { left: 180px; top: -30px; } <|start_filename|>public/javascripts/embed/embedded_login.js<|end_filename|> // a collection of functions // that are called by the various stages // of the iframe login sequence (function(window, document, $, undefined) { window.EmbeddedLogin = { // called from inner_iframe. Opens a popup window instead of // attempting to load third party auth pages inside iframe since most // services prevent that using X-Frame-Options headers attachPopupHandler: function(ev){ $('.login_services a').click( function(ev){ ev.preventDefault(); var POPUP_HEIGHT = 450, POPUP_WIDTH = 400, left = (screen.width/2)-( POPUP_WIDTH / 2 ), top = (screen.height/2)-( POPUP_HEIGHT / 2 ); var url = '/auth/omniauth_start_popup?service='+$(this).attr("href"); var win = window.open( url, 'IFrameLoginPopup', "menubar=no,toolbar=no,status=no,width="+ POPUP_WIDTH+",height="+POPUP_HEIGHT+ ",toolbar=no,left="+left+",top="+top ); if ( win.focus ) { win.focus(); } } ); }, // called from an omniauth powered popup window once // a third party login is complete. onPopupCompletion: function() { // load success page in iframe. It will handle informing the // xdm socket of the success // If IE fails here while complaining that window.opener is null, check security zones and // Make sure the site isn't 'trusted'. // http://stackoverflow.com/questions/6190879/window-opener-becomes-null-in-internet-explorer-after-security-zone-change // the Timeout is another IE compatability hack. Without it postmessage fails with XDM setTimeout( function(){ window.opener.location.href= '/auth/iframe_success'; window.close(); }, 1 ); }, // These are called from inner iframe pages. // They communicate across the parent iframe's xdm RPC socket setLoginStatus: function( status, data ){ window.parent.socket.loggedInStatus({ status: status, data: data }); }, setIFrameSrc: function(url){ var iframe = document.getElementById('services_login'); // show something immediatly while page is loading iframe.contentDocument.write('<body style="background: radial-gradient(circle farthest-corner at center top , #FAFAFA 0%, #C8C8C8 100%) repeat scroll 0 0 transparent;"></body>'); iframe.src = url; }, // this is called from the outer iframe. establishSocket: function(){ // is deliberately global so child iframe can access it to send messages window.socket = new easyXDM.Rpc({},{ remote: { // these are stubs of functions that are defined on the remote side loggedInStatus: {} }, local: { logout: function( document_id, successFn, errorFn ){ EmbeddedLogin.setIFrameSrc("/auth/iframe_logout?document_id=" + document_id); }, loadLoginStartingPage: function( document_id, successFn, errorFn ){ EmbeddedLogin.setIFrameSrc("/auth/inner_iframe?document_id=" + document_id); }, getRemoteData: function(document_id,successFn,errorFn){ $.ajax('/auth/remote_data/' + document_id, { success: successFn, error: errorFn }); } } }); } }; })(window, document, jQuery); <|start_filename|>public/stylesheets/pages/empty.css<|end_filename|> body.empty #container { position: absolute; top: 0; left: 0; right: 0; bottom: 0; background: #e9e9e9; overflow-y: auto; } body.empty #content { position: absolute; top: 40%; left: 50%; margin: -66px 0 0 -195px; height: 132px; width: 390px; text-align: center; } body.empty #logo { width: 390px; margin: 0 auto; } body.empty #search_container { margin-top: 5px; } body.empty #quick_links { margin-top: 30px; font: 12px Arial; color: #3656ab; } <|start_filename|>public/javascripts/ui/organizer/project.js<|end_filename|> dc.ui.Project = Backbone.View.extend({ className : 'project box', events : { 'click' : 'showDocuments', 'click .edit_glyph' : 'editProject' }, constructor : function(options) { Backbone.View.call(this, options); _.bindAll(this, 'render'); this.model.bind('change', this.render); this.model.view = this; }, render : function() { var data = _.extend(this.model.toJSON(), {statistics : this.model.statistics()}); $(this.el).html(JST['organizer/project'](data)); $(this.el).attr({id : "project_" + this.model.cid, 'data-project-cid' : this.model.cid}); this.setMode(this.model.get('selected') ? 'is' : 'not', 'selected'); return this; }, showDocuments : function(e) { if ($(e.target).hasClass('edit_glyph')) return false; this.model.open(); }, editProject : function(e) { this.model.edit(); return false; } }); <|start_filename|>public/javascripts/ui/common/spinner.js<|end_filename|> // There's only a single global instance of the Spinner. show() it, passing in // a message, and hide() it when the corresponding action has finished. dc.ui.spinner = { show : function(message) { this.ensureElement(); message = message || "Loading"; this.el.stop(true, true).fadeIn('fast'); }, hide : function() { this.ensureElement(); this.el.stop(true, true).fadeOut('fast', function(){ $(this).css({display : 'none'}); }); }, ensureElement : function() { this.el || (this.el = $('#spinner')); } }; _.bindAll(dc.ui.spinner, 'show', 'hide'); <|start_filename|>public/javascripts/ui/common/notifier.js<|end_filename|> dc.ui.Notifier = Backbone.View.extend({ id : 'notifier', events : { 'click': 'hide' }, options : { position : 'center center', text : 'ok', left : 0, top : 0, duration : 2000, leaveOpen : false, mode : 'warn' }, constructor : function(options) { Backbone.View.call(this, options); $(document.body).append(this.el); _.bindAll(this, 'show', 'hide'); }, // Display the notifier with a message, positioned relative to an optional // anchor element. show : function(options) { options = _.extend({}, this.options, options); this.setMode(options.mode, 'style'); $(this.el).html(options.text).fadeIn('fast'); $(this.el).show(); if (this.timeout) clearTimeout(this.timeout); if (!options.leaveOpen) this.timeout = setTimeout(this.hide, options.duration); }, hide : function(immediate) { this.timeout = null; immediate === true ? $(this.el).hide() : $(this.el).fadeOut('fast'); } });
DavidLemayian/documentcloud
<|start_filename|>server/game/components/player.js<|end_filename|> export class Player extends Phaser.Physics.Arcade.Sprite { constructor(scene, playerId, x = 200, y = 200, dummy = false) { super(scene, x, y, '') scene.add.existing(this) scene.physics.add.existing(this) this.scene = scene this.prevX = -1 this.prevY = -1 this.dead = false this.prevDead = false this.playerId = playerId this.move = {} this.setDummy(dummy) this.body.setSize(32, 48) this.prevNoMovement = true this.setCollideWorldBounds(true) scene.events.on('update', this.update, this) } setDummy(dummy) { if (dummy) { this.body.setBounce(1) this.scene.time.addEvent({ delay: Phaser.Math.RND.integerInRange(45, 90) * 1000, callback: () => this.kill() }) } else { this.body.setBounce(0) } } kill() { this.dead = true this.setActive(false) } revive(playerId, dummy) { this.playerId = playerId this.dead = false this.setActive(true) this.setDummy(dummy) this.setVelocity(0) } setMove(data) { let int = parseInt(data, 36) let move = { left: int === 1 || int === 5, right: int === 2 || int === 6, up: int === 4 || int === 6 || int === 5, none: int === 8 } this.move = move } update() { if (this.move.left) this.setVelocityX(-160) else if (this.move.right) this.setVelocityX(160) else this.setVelocityX(0) if (this.move.up && this.body.onFloor()) this.setVelocityY(-550) } postUpdate() { this.prevX = this.x this.prevY = this.y this.prevDead = this.dead } } <|start_filename|>server/game/config.js<|end_filename|> import '@geckos.io/phaser-on-nodejs' import Phaser from 'phaser' import { GameScene } from './gameScene.js' export const config = { type: Phaser.HEADLESS, parent: 'phaser-game', width: 896, height: 504, banner: false, audio: false, scene: [GameScene], physics: { default: 'arcade', arcade: { gravity: { y: 1200 } } } } <|start_filename|>server/game/game.js<|end_filename|> import { config } from './config.js' export class PhaserGame extends Phaser.Game { constructor(server) { super(config) this.server = server } } <|start_filename|>client/components/fullscreenButton.js<|end_filename|> const FullscreenButton = scene => { let button = scene.add .image(scene.cameras.main.width - 20, 20, 'fullscreen', 0) .setOrigin(1, 0) .setInteractive() .setScrollFactor(0) .setDepth(100) .setAlpha(0.2) button.on('pointerup', () => { if (scene.scale.isFullscreen) { button.setFrame(0) scene.scale.stopFullscreen() } else { button.setFrame(1) scene.scale.startFullscreen() } }) return button } export default FullscreenButton
asaucedo777/phaser3-multiplayer-game-example
<|start_filename|>static/languages/es.json<|end_filename|> { "I18N": { "LANGUAGE": "Español", "MAINTAINERS": "@Viriato139ac#0342" }, "Bellows": { "ImportPlaylist": { "Title": "Importar Lista de Reproducción de YouTube", "Notes": "Introduzca la dirección de una Lista de Reproducción de YouTube o el ID de una Lista de Reproducción y haga clic en el botón de importar para que comience el proceso.", "Buttons": { "Import": "Importar", "Submit": "Guardar" }, "Messages": { "AlreadyWorking": "La Lista de Reproducción se está importando. Por favor, espere", "InvalidKey": "Por favor, introduzca la dirección de una Lista de Reproducción de YouTube válida (debe tener la palabra list en la cadena de consulta) o el ID de una Lista de Reproducción válida", "Error": "Error al importar la Lista de Reproducción - consulte los detalles en la consola", "KeyNotFound": "No existe la Lista de Reproducción con la clave {playlistKey} - compruebe la dirección o el ID e inténtelo de nuevo", "ImportComplete": "La Lista de Reproducción {playlistName} ha sido importada con éxito" }, "Labels": { "Name": "Nombre de la Lista de Reproducción", "Volume": "Volumen por defecto" } }, "PlaylistConfig": { "Labels": { "Streamed": "Streamed", "StreamType": "Stream Type", "AudioUrl": "Stream Url or Id" }, "Selects": { "StreamTypes": { "Youtube": "Youtube" } }, "Errors": { "InvalidUri": "an invalid URI was provided" } } } } <|start_filename|>static/languages/en.json<|end_filename|> { "Bellows": { "ImportPlaylist": { "Title": "Import YouTube Playlist", "Notes": "Enter a youtube playlist url or playlist ID below and click the import button next to it to get started.", "Buttons": { "Import": "Import", "Submit": "Save" }, "Messages": { "AlreadyWorking": "Playlist is currently being imported, please wait", "InvalidKey": "Please enter a valid youtube playlist url (with list in the querystring) or a playlist ID", "Error": "Error importing playlist - check the console for details", "KeyNotFound": "Playlist with key {playlistKey} does not exist - check the url or id and try again", "ImportComplete": "Playlist {playlistName} has been successfully imported" }, "Labels": { "Name": "Playlist name", "Volume": "Default volume" } }, "PlaylistConfig": { "Labels": { "Streamed": "Streamed", "StreamType": "Stream Type", "AudioUrl": "Stream Url or Id" }, "Selects": { "StreamTypes": { "Youtube": "Youtube" } }, "Errors": { "InvalidUri": "an invalid URI was provided" } } } } <|start_filename|>static/languages/ja.json<|end_filename|> { "Bellows": { "ImportPlaylist": { "Title": "YouTubeのプレイリストを読み込む", "Notes": "YouTubeのプレイリストURL、またはIDを入力してください。隣のインポートボタンを押すと開始します。", "Buttons": { "Import": "インポート", "Submit": "保存" }, "Messages": { "AlreadyWorking": "プレイリストをインポートしています。しばらくお待ちください。", "InvalidKey": "有効なYouTubeのプレイリストURL(クエリ文字列を含む)、またはプレイリストIDを入力してください。", "Error": "プレイリスト読込エラー:詳細はコンソールを確認してください。", "KeyNotFound": "キー {playlistKey} を持つプレイリストが存在しません。URLやIDを確認し再試行してください。", "ImportComplete": "プレイリスト {playlistName} が正常にインポートされました。" }, "Labels": { "Name": "プレイリスト名", "Volume": "デフォルト音量" } }, "PlaylistConfig": { "Labels": { "Streamed": "ストリーム", "StreamType": "ストリームタイプ", "AudioUrl": "ストリームURL/Id" }, "Selects": { "StreamTypes": { "Youtube": "YouTube" } }, "Errors": { "InvalidUri": "無効なURIが指定されました" } } } }
anoverga17/Bellows
<|start_filename|>static/js/modules/submenu.js<|end_filename|> define(['jquery', 'lodash', 'enquire', 'velocity', 'velocityUI', 'scrollMagic'], function ($, _, enquire, Velocity, velocityUI, ScrollMagic) { $(document).ready(function() { 'use strict'; var subMenuModule = { init: function() { console.log('starting submenu function'); $(this.variables.menuAnchorSelector).velocity('transition.fadeIn', 1000 ); enquire.register('screen and (max-width: 480px)', { //match: _.bind(this.resultsBindMobile, this) }); enquire.register('screen and (min-width: 481px)', { match: _.bind(this.subMenuEvent, this) }); }, variables : { topHeaderSelector: '.topheader', heroSectionBackgroundSelector: '.background', menuAnchorSelector: '#menuAnchor' }, subMenuEvent: function() { this.pinFiltersBar(); this.smothscrollToggleActive(); }, pinFiltersBar: function() { var controller = new ScrollMagic.Controller(); var scene = new ScrollMagic.Scene({ triggerElement: this.variables.menuAnchorSelector, triggerHook:0, offset:-90 }) .setPin(this.variables.menuAnchorSelector) .setClassToggle('.nav', 'no-shadow') .addTo(controller); }, smothscrollToggleActive: function() { $('a[href^="#"]:not([data-toggle="collapse"])').click(function(event) { var id = $(this).attr('href'); var target = $(id).offset().top - 200; $('html, body').animate({scrollTop:target}, 500); event.preventDefault(); }); function getTargetTop(elem){ var id = elem.attr('href'); var offset = 60; return $(id).offset().top - offset; } $(window).scroll(function(e){ isSelected($(window).scrollTop()); }); var sections = $('a[href^="#"]'); function isSelected(scrolledTo){ var threshold = 100; var i; for (i = 0; i < sections.length; i++) { var section = $(sections[i]); var target = getTargetTop(section); if (scrolledTo > target - threshold && scrolledTo < target + threshold) { sections.removeClass('active'); section.addClass('active'); } } } } }; subMenuModule.init(); }); }); <|start_filename|>static/js/modules/cookieconsent.js<|end_filename|> define(['jquery'], function ($, _, enquire, Velocity, velocityUI, ScrollMagic) { $(document).ready(function(){ var sCookieName = "cookiewarning"; function createCookie(name, value, days) { if (days) { var date = new Date(); date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000)); var expires = "; expires=" + date.toGMTString(); } else var expires = ""; document.cookie = name + "=" + value + expires + "; path=/"; } function readCookie(name) { var nameEQ = name + "="; var ca = document.cookie.split(';'); for (var i = 0; i < ca.length; i++) { var c = ca[i]; while (c.charAt(0) == ' ') c = c.substring(1, c.length); if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length); } return null; } // actually give cookie warning if (readCookie(sCookieName) != 1) { setTimeout(function () { $("#cookieConsent").fadeIn(500); }, 2000); } $("#closeCookieConsent, .cookieConsentOK").click(function() { $("#cookieConsent").fadeOut(200); createCookie(sCookieName, 1, 365) }); }); }); <|start_filename|>setup.cmd<|end_filename|> @echo off set WIN32PATH=%CD%\win32 set PATH=%PATH%;%WIN32PATH% set OLDDIR=%CD% set TMPDIR=%TEMP%\sphinx-install if defined ProgramFiles(x86) ( set msi="python-2.7.6.amd64.msi" ) else ( set msi="python-2.7.6.msi" ) set PYTHONURL="http://www.python.org/ftp/python/2.7.6/%msi%" set EZSETUPURL="http://bitbucket.org/pypa/setuptools/raw/bootstrap/ez_setup.py" set EASY_INSTALL="C:\Python27\Scripts\easy_install" rmdir /s /q %TMPDIR% mkdir %TMPDIR% cd %TMPDIR% echo Fetching Python... wget %PYTHONURL% echo Fetching Python Easy Setup... wget --ca-certificate=%WIN32PATH%\ca-bundle.crt %EZSETUPURL% echo Fetching RST2PDF... wget --ca-certificate=%WIN32PATH%\ca-bundle.crt %RST2PDFURL% echo Installing Python... msiexec /i %msi% /qb ADDLOCAL="Extensions" ADDLOCAL="Tools" ALLUSERS=1 echo Installing Python Easy Setup... C:\Python27\python.exe ez_setup.py echo Installing Sphinx... %EASY_INSTALL% -U sphinx echo Installing RST2PDF... %EASY_INSTALL% -U rst2pdf echo Installing Sphinx PHP Domain... %EASY_INSTALL% -U sphinxcontrib-phpdomain echo Setting SPHINXBUILD variable... setx SPHINXBUILD C:\Python27\Scripts\sphinx-build.exe echo Removing temporary directory... cd %OLDDIR% rmdir /s /q %TMPDIR% echo Done! pause <|start_filename|>_shared_assets/static/custom.css<|end_filename|> /** * FIX THE DESIGN OF THE RTD THEME */ /* NC blue */ .wy-side-nav-search { background-color: #0082c9; } /* Reduce size of logo in top left */ .wy-side-nav-search > a img.logo { max-width: 180px; } /* Remove unwanted background on top left logo on hover */ .wy-side-nav-search > a:hover { background: none; } /* Remove unwanted data on the bottom left sidebar */ .rst-versions.shift-up .rst-other-versions > dl:not(:nth-child(1)), .rst-versions.shift-up .rst-other-versions > a, .rst-versions.shift-up .rst-other-versions > hr { display:none } .rst-versions.shift-up .rst-other-versions { color: transparent; font-size: 0px; } .rst-versions.shift-up .rst-other-versions dt,.rst-versions.shift-up .rst-other-versions dl { color: #808080; font-size: 15px; } /* Remove readthedocs title in the sidebar bottom left section */ .rst-versions .rst-current-version .fa-book { display: none; } .rst-versions .rst-current-version:before { content: 'Nextcloud'; margin-right: auto; } .rst-versions .rst-current-version { display: flex; align-items: center; color: #0082c9; } .rst-versions .rst-current-version .fa-caret-down { margin-left: 5px; } /* Code blocks */ .highlight { /* nc blue */ background: rgba(0, 130, 201, 0.1) } /* ICONS LIST */ div#list-of-available-icons > blockquote { margin: 0; } div#list-of-available-icons > blockquote > div { display: flex; flex-wrap: wrap; justify-content: space-around; } div#list-of-available-icons > blockquote > div > div { width: 120px; display: flex; flex-direction: column; align-items: center; margin-bottom: 30px; } div#list-of-available-icons > blockquote > div > div > a { border-radius: 50%; display: flex; justify-content: center; align-items: center; width: 60px; height: 60px; } div#list-of-available-icons > blockquote > div > div > a.white-icon { background-color: #343131; } div#list-of-available-icons > blockquote > div > div > p { margin-top: 5px; font-size: 90%; font-style: normal; text-align: center; } <|start_filename|>static/js/require.config.js<|end_filename|> requirejs.config({ waitSeconds : 0, baseURL: 'js/', paths: { jquery: ['https://code.jquery.com/jquery-3.4.1.min', '../../node_modules/jquery/dist/jquery.min'], modernizr: ['https://cdnjs.cloudflare.com/ajax/libs/modernizr/2.8.3/modernizr.min', 'old/vendor/modernizr-2.7.0.min'], waypoints: ['https://cdnjs.cloudflare.com/ajax/libs/waypoints/4.0.1/noframework.waypoints.min', '../../node_modules/waypoints/lib/jquery.waypoints.min'], enquire: ['https://cdnjs.cloudflare.com/ajax/libs/enquire.js/2.1.6/enquire.min', 'old/vendor/enquire.min'], bodymovin: ['https://cdnjs.cloudflare.com/ajax/libs/bodymovin/4.7.0/bodymovin.min', 'old/vendor/bodymovin.min'], headroom: ['https://cdnjs.cloudflare.com/ajax/libs/headroom/0.9.3/headroom.min', 'old/vendor/headroom.min'], headroomJquery: ['https://cdnjs.cloudflare.com/ajax/libs/headroom/0.9.3/jQuery.headroom.min', 'old/vendor/jQuery.headroom.min'], lodash: ['https://cdn.jsdelivr.net/lodash/4.17.4/lodash.core.min', '../../node_modules/lodash/core.min'], TweenLite: ['https://cdnjs.cloudflare.com/ajax/libs/gsap/1.13.1/TweenLite.min', '../../node_modules/gsap/src/minified/TweenLite.min'], TimelineLite: ['https://cdnjs.cloudflare.com/ajax/libs/gsap/1.13.1/TimelineLite.min', '../../node_modules/gsap/src/minified/TimelineLite.min'], TimelineMax: ['https://cdnjs.cloudflare.com/ajax/libs/gsap/1.13.1/TimelineMax.min', '../../node_modules/gsap/src/minified/TimelineMax.min'], TweenMax: ['https://cdnjs.cloudflare.com/ajax/libs/gsap/1.13.1/TweenMax.min', '../../node_modules/gsap/src/minified/TweenMax.min'], velocity: ['https://cdnjs.cloudflare.com/ajax/libs/velocity/1.5.0/velocity.min', 'old/vendor/velocity.min'], velocityUI: ['https://cdnjs.cloudflare.com/ajax/libs/velocity/1.5.0/velocity.ui.min', 'old/vendor/velocity.ui.min'], scrollMagic: ['https://cdnjs.cloudflare.com/ajax/libs/ScrollMagic/2.0.5/ScrollMagic.min', 'old/vendor/ScrollMagic.min'], hammer: ['https://cdnjs.cloudflare.com/ajax/libs/hammer.js/2.0.8/hammer.min', 'old/vendor/hammer.min'], inview: ['https://cdnjs.cloudflare.com/ajax/libs/protonet-jquery.inview/1.1.2/jquery.inview.min', 'old/vendor/jquery.inview.min'], plyr: ['https://cdnjs.cloudflare.com/ajax/libs/plyr/2.0.18/plyr', '../../node_modules/plyr/dist/plyr'], bootstrap: ['https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min', '../../node_modules/bootstrap-sass/assets/javascripts/bootstrap.min'], highlight: ['https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/highlight.min', '../../node_modules/highliht.js/lib/highlight'], }, shim: { headroomJquery: { deps: ['jquery', 'headroom'] }, enquire: { deps: ['jquery'] }, bodymovin: { deps: ['jquery'] }, velocity: { deps: ['jquery'] }, waypoints: { deps: ['jquery', 'bodymovin'] }, velocityUI: { deps: ['velocity'] }, bootstrap: { deps: ['jquery'] } } }); <|start_filename|>static/js/modules/youtubePlayer.js<|end_filename|> // This use the plyr plugin, for more information use the link above // https://github.com/sampotts/plyr define(['jquery', 'lodash', 'plyr'], function ($, _, plyr) { $(document).ready(function() { 'use strict'; var YoutubePlayer = { init: function() { this.startPlayer(); this.getCss(); }, getCss: function() { $('head').append('<link>'); var css = $('head').children(':last'); css.attr({ rel: 'stylesheet', type: 'text/css', href: 'https://cdn.plyr.io/2.0.13/plyr.css' }); }, startPlayer: function() { plyr.setup({ //Pass extra options here if needed }); } }; YoutubePlayer.init(); }); }); <|start_filename|>static/js/modules/codeHighlights.js<|end_filename|> // This use the highlight,js plugin, for more information use the link above // https://highlightjs.org/ // TODO Use workers for better performance define(['jquery', 'lodash', 'highlight'], function ($, _, hljs) { $(document).ready(function() { 'use strict'; var codeHighlight = { init: function() { hljs.initHighlightingOnLoad(); }, }; codeHighlight.init(); }); }); <|start_filename|>static/js/modules/slideshow.js<|end_filename|> define(['jquery', 'lodash', 'enquire', 'scrollMagic', 'hammer', 'inview'], function ($, _, enquire, ScrollMagic, Hammer, isInView) { $(document).ready(function() { 'use strict'; var slideshow = { init: function() { enquire.register('screen and (max-width: 991px)', { match: _.bind(this.modulesBindMobile, this), unmatch: _.bind(this.cleanModulesMobile, this) }); enquire.register('screen and (min-width: 992px)', { match: _.bind(this.modulesBindDesktop, this), unmatch: _.bind(this.cleanModulesDesktop, this) }); }, variables : { buttonDropdownSelector: $('.button--dropdown'), buttonDropdownContentSelector: $('.dropdown-content'), SlideshowTextTriggerSelector: $('.textTrigger'), spriteSlideshowSelector: $('.image-top-container'), slideshowContentSelector: '.slideshow', slideshowIndicatorsSelector: '.indicators', slideshowImageOnTopSelector: '.image-top', textTriggerSelector: '.textTrigger', indicatorSlideshow: 'btn_carousel', visibleClass : 'visible', activeClass: 'active' }, modulesBindDesktop: function() { this.slideshowDesktop(); this.updateSlideshowImageSizes(); $(window).resize(_.bind(this.updateSlideshowImageSizes, this)); }, modulesBindMobile: function() { this.slideshowMobile(); }, cleanModulesDesktop: function() { this.destroyMagicScrollOnMobile(); }, cleanModulesMobile: function() { this.removeInlineCssOnDesktop(); this.removeInlineCssOnMobile(); }, slideshowTablet: function() { $('.image__mobile').hide(); $(window).resize(_.bind(this.updateSlideshowImageSizes, this)); }, smoothScroll: function() { $('a[href*="#"]:not([href="#"]):not([data-toggle="collapse"])').click(function() { if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) { var target = $(this.hash); target = target.length ? target : $('[name=' + this.hash.slice(1) +']'); if (target.length) { $('html, body').animate({ scrollTop: target.offset().top }, 1000); return false; } } }); }, indicatorSlideshow: function() { var visibleElement = $(this.variables.textTriggerSelector).parent(); $(visibleElement).on('inview', function(event, isInView) { if (isInView) { var currentSlide = $(event.currentTarget).data('slide'); var $indicator = $('.btn_carousel:nth-child(' + (parseInt(currentSlide) + 1)+')'); var $active = $('.btn_carousel.active'); var imageFeatures = $('.image-top'); $active.removeClass('active'); $indicator.addClass('active'); } }); }, slideshowImagePosition: function(currentSlide) { var visibleElement = $(this.variables.textTriggerSelector).parent(); $(visibleElement).on('inview', function(event, isInView) { if (isInView) { var currentSlide = $(event.currentTarget).data('slide'); var imageFeatures = $('.image-top'); var currentHeight = $('.image-top').height() / 4; if (currentSlide === 1) { imageFeatures.css({ 'top': '0' + 'px', }); } if (currentSlide === 2) { imageFeatures.css({ 'top': '-' + currentHeight + 'px' }); } if (currentSlide === 3) { imageFeatures.css({ 'top': '-' + currentHeight * 2 + 'px' }); } if (currentSlide === 4) { imageFeatures.css({ 'top': '-' + currentHeight * 3 + 'px' }); } } }); }, slideshowDesktop : function () { this.indicatorSlideshow(); this.slideshowImagePosition(); this.slideshowChangeImageDesktop(); this.controller = new ScrollMagic.Controller(); this.variables.SlideshowTextTriggerSelector.each(function() { var imageFeatures = $('.image-top'); var animateImage = new ScrollMagic.Scene ({ triggerElement: this, offset: '100%', reverse: true, triggerHook: 1 }) .addTo(this.controller); }); var imagePin = new ScrollMagic.Scene ({ triggerElement: '#imageTrigger', duration: '300%', triggerHook: 0 }) .setPin('#imageTrigger') .setClassToggle('.indicators', 'active') // add indicators to scene .addTo(this.controller); }, slideshowMobile: function() { $(this.variables.slideshowIndicatorsSelector).addClass(this.variables.activeClass); this.slideshowImagePositionMobile(); this.slideshowChangeImageMobile(); this.indicatorSlideshow(); this.updateSlideshowImageSizes(); this.toggleTextSlideshowMobile(); $(window).resize(_.bind(this.updateSlideshowImageSizes, this)); $(this.variables.slideshowIndicatorsSelector).addClass(this.variables.activeClass); var sectionHeadingheight = $('#slideshow').find('.section--heading-1').height(); var currentImageDevice = $('.image-back').height() + sectionHeadingheight + 200; $(this.variables.slideshowIndicatorsSelector).css({ 'top': currentImageDevice + 'px' }); $(this.variables.indicatorSlideshow).on('click', _.bind(this.indicatorsAnchorMobile, this)); }, indicatorsAnchorMobile: function(event) { event.prevent; }, updateSlideshowImageSizes: function() { var imageDeviceWidth = $('.image-back').width() * '0.9376733', // Using proportions to do the math imageDeviceHeight = $('.image-back').height() * '0.722727273', // Using proportions to do the math imageOnTopMargins = $('.image-back').width() * '0.0314'; // Using proportions to do the math $('.image-top-container').css({ 'width': imageDeviceWidth + 'px', 'height': imageDeviceHeight + 'px', 'top': imageOnTopMargins + 'px', 'left': imageOnTopMargins + 'px' }); }, slideshowChangeImageMobile: function() { $('.image-top-container').find('.image__desktop').hide(); $('.image-top-container').find('.image__mobile').show(); }, slideshowChangeImageDesktop: function() { $('.image-top-container').find('.image__desktop').show(); $('.image-top-container').find('.image__mobile').hide(); }, toggleTextSlideshowMobile: function() { var firstText = $('.right-text-grey').first(); firstText.addClass(this.variables.activeClass); var element = document.getElementById('slideshow'); Hammer(element).on('swipeleft', _.bind(this.showNextTextSlideshow, this)); Hammer(element).on('swiperight', _.bind(this.showPreviousTextSlideshow, this)); }, showNextTextSlideshow: function(event) { var lastElement = $('.right-text-grey').last(), visibleElement = $('.textTrigger').parent(), slidesCount = $('.right-text-grey').last().data('slide'), currentSlide = $('.right-text-grey.active').data('slide'); if (slidesCount > currentSlide) { var currentText = $('.right-text-grey.active'); var nextText = $('.right-text-grey.active').next(); nextText.addClass('swipeleft active'); currentText.removeClass('active'); setTimeout(function() { nextText.removeClass('swipeleft'); }, 200 ); } else { nextText = $('.right-text-grey').first(); var currentText = $('.right-text-grey.active'); nextText.addClass('swipeleft active'); currentText.removeClass('active'); setTimeout(function() { nextText.removeClass('swipeleft'); }, 200 ); } }, showPreviousTextSlideshow: function(event) { var currentText = $('.right-text-grey.active'), previousText = $('.right-text-grey.active').prev(), lastElement = $('.right-text-grey').last(), visibleElement = $('.textTrigger').parent(), slidesCount = $('.right-text-grey').first().data('slide'), NoMoreSlides = $('.right-text-grey.active').data('slide'); if (slidesCount < NoMoreSlides) { var currentText = $('.right-text-grey.active'), previousText = $('.right-text-grey.active').prev(); previousText.addClass('swiperight active'); currentText.removeClass('active'); setTimeout(function() { previousText.removeClass('swiperight'); }, 200 ); } else { previousText = $('.right-text-grey').last(); currentText = $('.right-text-grey.active'); previousText.addClass('active'); currentText.removeClass('active'); setTimeout(function() { previousText.removeClass('swiperight'); }, 200 ); } }, slideshowImagePositionMobile: function() { var visibleElement = $('.textTrigger').parent(); $(visibleElement).on('inview', function(event, isInView) { if (isInView) { var currentSlide = $(event.currentTarget).data('slide'), imageFeatures = $('.image-top'), slidesCount = $('.right-text-grey').last().data('slide'), imageTopHeight = $('.image__mobile').width() / slidesCount; if (currentSlide === 1) { imageFeatures.css({ 'left': '0' + 'px' }); } if (currentSlide === 2) { imageFeatures.css({ 'left': - imageTopHeight + 'px' }); } if (currentSlide === 3) { imageFeatures.css({ 'left': - imageTopHeight * 2 + 'px' }); } if (currentSlide === 4) { imageFeatures.css({ 'left': - imageTopHeight * 3 + 'px' }); } } }); }, destroyMagicScrollOnMobile: function(event, slideshowDesktop) { this.controller.destroy(true); this.controller = null; this.slideshowDesktopCss = $('.scrollmagic-pin-spacer').attr('style'); $('.scrollmagic-pin-spacer').removeAttr('style'); }, removeInlineCssOnDesktop: function(destroyMagicScrollOnMobile) { $('.image__desktop').removeAttr('style'); $('.scrollmagic-pin-spacer').css('style'); }, removeInlineCssOnMobile: function() { $(this.variables.slideshowIndicatorsSelector).removeAttr('style'); $(this.variables.slideshowIndicatorsSelector).css('style'); } }; slideshow.init(); }); }); <|start_filename|>static/js/navigation.js<|end_filename|> $(document).ready(function() { 'use strict'; var HeaderApp = { init: function() { this.didScroll = false; this.menuOpened = false; this.enquireInitializedMobile = false; //Fade In animation $(this.variables.navigationId).velocity('transition.fadeIn', 1000 ); this.animatedLogoSprite(); enquire.register('screen and (max-width: 992px)', { match: _.bind(this.mobileEvent, this) }); enquire.register('screen and (max-height: 700px)', { match: _.bind(this.showAndHideHeader, this) }); enquire.register('screen and (min-width: 993px)', { match: _.bind(this.desktopDropdownEvent, this) }); }, variables : { toggleSelector: '#toggle', navigationId: '#nav', navigationSelector: '.nav', subMenuSelector: '#menuAnchor', sectionsSelector: '.nav__sections', sectionsContainerSelector: '.nav__sections-wrapper', sectionSelector: '.nav__section', navBackgroundSelector: '.nav__bg', navBackgroundWrapper: '.nav__bg-wrapper', rightNavigationSelector: '.right-buttons', linksSelector: '.nav__links', logoSelector: '.logo', mobileClass: 'mobile', activeClass: 'active', scrolledClass:'scrolled', backgroundAnimationClass: 'is-animatable', linksVisibleClass: 'is-visible', mobileBackgroundSelector: '.mobile-bg', mobileMenuClass: 'menu-open', showNavigationClass:'nav-down', hideNavigationClass: 'nav-up', playOnHoverClass: 'hoverPlay', stopAnimationClass: 'stopedAnimation', mobileBackgroundContainerSelector: '.mobile-bg-container', }, toggleMobileMenu: function(event) { $(this.variables.linksSelector).hide().removeClass(this.variables.activeClass); //hide all submenus without animation $(event.currentTarget).toggleClass(this.variables.activeClass); $(this.variables.mobileBackgroundSelector).toggleClass(this.variables.activeClass); $(this.variables.sectionsSelector).toggleClass(this.variables.activeClass); $(this.variables.rightNavigationSelector).toggleClass(this.variables.activeClass); $(this.variables.logoSelector).toggleClass(this.variables.mobileMenuClass); $(this.variables.mobileBackgroundContainerSelector).toggleClass(this.variables.backgroundAnimationClass); }, resetMobile: function() { $(this.variables.navigationId).removeClass(this.variables.mobileClass); $(this.variables.toggleSelector).off('click'); $(this.variables.sectionSelector).off('click'); $(this.variables.linksSelector).css('display', 'inherit').removeClass(this.variables.activeClass); }, resetDesktop: function() { $(this.variables.sectionSelector).off('mouseover'); $(this.variables.sectionSelector).off('mouseleave'); $(this.variables.linksSelector).hide(); }, showSubMenu: function(event) { if ($(event.currentTarget).find(this.variables.linksSelector).hasClass(this.variables.activeClass)) { $(this.variables.linksSelector).slideUp().removeClass(this.variables.activeClass); return; } $(this.variables.linksSelector).slideUp().removeClass(this.variables.activeClass); $(event.currentTarget).find(this.variables.linksSelector).slideToggle().addClass(this.variables.activeClass); }, mobileBgAnimation: function() { var windowDiameter = ($(window).width() * 2) * $(window).height() * 2, returnBiggest = (Math.sqrt(windowDiameter)) * 1.5; $(this.variables.mobileBackgroundSelector).css({ 'top': - returnBiggest / 2+ 'px', 'right': - returnBiggest / 2 + 'px', 'width': returnBiggest + 'px', 'height': returnBiggest + 'px' }); }, showAndHideHeader: function(variables) { var myElement = document.querySelector('.nav'); //I should pass the variable object inside the headroom this.headroom = new Headroom(myElement, { offset: 510, tolerance : { up : 20, down : 20 }, onTop: function(variables) { $('#nav').removeClass('scrolled'); $('.logo').removeClass('scrolled'); $('.mobile-bg-container').addClass('visible'); }, onPin: function() { $('.menu').removeClass('hidedPrincipalNavigation'); $('#nav').addClass('scrolled'); $('.logo').addClass('scrolled'); }, onNotTop : function() { $('.mobile-bg-container').addClass('visible'); }, onUnpin: function() { $('.menu').addClass('hidedPrincipalNavigation'); $('.mobile-bg-container').addClass('visible'); } }); this.headroom.init(); }, mobileEvent: function() { this.resetDesktop(); if (!this.enquireInitializedMobile) { this.enquireInitializedMobile = true; this.createMenuButton(); } $(window).on('resize', _.bind(this.mobileBgAnimation, this)); this.mobileBgAnimation(); $(this.variables.navigationId).addClass(this.variables.mobileClass); $(this.variables.toggleSelector).click(_.bind(this.toggleMobileMenu, this)); $(this.variables.sectionSelector).click(_.bind(this.showSubMenu, this)); }, setBackgroundDropdown: function(bg) { bg.addClass(this.variables.backgroundAnimationClass); }, backgroundDropdown: function(event) { var cssPadding = 30, bg = $(this.variables.navBackgroundSelector), bgWrapper = $(this.variables.navBackgroundWrapper), selectedDropdown = $(event.currentTarget).find(this.variables.linksSelector), height = selectedDropdown.innerHeight(), width = selectedDropdown.innerWidth(), windowWidth = $(this.variables.navigationSelector).outerWidth(), navigationWidth = $('.nav .container').outerWidth(), marginNavigation = (windowWidth - navigationWidth) / 2, backgroundDropdownPosition = $(event.currentTarget).offset().left + cssPadding + ($(event.currentTarget).innerWidth() - cssPadding) /2 - width/2 - marginNavigation; setTimeout(_.bind(this.setBackgroundDropdown, this, bg)); bgWrapper.addClass(this.variables.linksVisibleClass); bg.css({ '-moz-transform': 'translateX(' + backgroundDropdownPosition + 'px)', '-webkit-transform': 'translateX(' + backgroundDropdownPosition + 'px)', '-ms-transform': 'translateX(' + backgroundDropdownPosition + 'px)', '-o-transform': 'translateX(' + backgroundDropdownPosition + 'px)', 'transform': 'translateX(' + backgroundDropdownPosition + 'px)', 'width': width + 'px', 'height': height + 'px' }); }, desktopDropdownEvent: function() { this.resetMobile(); $(this.variables.sectionSelector).on('mouseover', _.bind(this.backgroundDropdown, this)); $(this.variables.sectionSelector).on('mouseleave', _.bind(this.destroyDropdown, this)); this.showAndHideHeader(); }, // Clear dropdowns in mouse leave destroyDropdown: function(event) { var bg = $(this.variables.navBackgroundSelector), bgWrapper = $(this.variables.navBackgroundWrapper); setTimeout(_.bind(function() { bg.removeClass(this.variables.backgroundAnimationClass); },this)); var bgWrapper = $(this.variables.navBackgroundWrapper); bgWrapper.removeClass(this.variables.linksVisibleClass); }, //Bodymovin menu Animation createMenuButton: function() { var menuAnimation, animContainer = document.querySelectorAll('.container button')[0], params = { container: animContainer, renderer: 'svg', loop: false, autoplay: false, autoloadSegments: true, path: templateUrl + '/assets/img/menu/data.json' }; menuAnimation = bodymovin.loadAnimation(params); menuAnimation.stop(); $('.container button').click(function () { if(this.menuOpened) { menuAnimation.setDirection(-1); } else { menuAnimation.setDirection(0); } menuAnimation.play(); this.menuOpened = !this.menuOpened; }); }, //Listen to scroll to change header opacity class toggleScrolledClass: function() { var bodyScrollTop = document.documentElement.scrollTop || document.body.scrollTop; if (bodyScrollTop !== 0) { $(this.variables.navigationId).addClass(this.variables.scrolledClass); $(this.variables.logoSelector).addClass(this.variables.scrolledClass); } else { $(this.variables.navigationId).removeClass(this.variables.scrolledClass); $(this.variables.logoSelector).removeClass(this.variables.scrolledClass); } }, checkScroll: function() { if ($(this.variables.navigationId).length > 0) { $(window).on('scroll load resize', _.bind(this.toggleScrolledClass, this)); } }, animatedLogoSprite: function() { this.hoverLogo(); $(this.variables.logoSelector).on('mouseover', _.bind(this.hoverLogo, this)); }, hoverLogo: function () { $(this.variables.logoSelector).removeClass(this.variables.stopAnimationClass); $(this.variables.logoSelector).addClass(this.variables.playOnHoverClass); setTimeout(_.bind(this.stopLogoAnimation, this), 2000); }, stopLogoAnimation: function() { $(this.variables.logoSelector).removeClass(this.variables.playOnHoverClass); $(this.variables.logoSelector).addClass(this.variables.stopAnimationClass); } }; HeaderApp.init(); }); <|start_filename|>static/js/main.js<|end_filename|> define(['jquery', 'lodash', 'enquire', 'TweenMax', 'velocity'], function ($, _, enquire, TweenMax) { $(document).ready(function() { 'use strict'; var main = { init: function() { this.variables.buttonDropdownSelector.on('click', _.bind(this.buttonDropdown, this)); $(window).on('scroll.fadeOnce', _.bind(this.revealOnScroll, this)); this.animationOnLoadPage(); this.removeRevealOnScroll(); this.consoleMessage(); }, variables: { topHeaderSelector: '.topheader', heroHeading: '.topheader h1', heroSubtitle: '.topheader h2', heroSectionBackgroundSelector: '.background', buttonDropdownSelector: $('.button--dropdown'), buttonDropdownContentSelector: $('.dropdown-content'), SlideshowTextTriggerSelector: $('.textTrigger'), spriteSlideshowSelector: $('.image-top-container'), slideshowContentSelector: '.slideshow', slideshowIndicatorsSelector: '.indicators', slideshowImageOnTopSelector: '.image-top', textTriggerSelector: '.textTrigger', indicatorSlideshow: 'btn_carousel', visibleClass : 'visible', activeClass: 'active' }, consoleMessage: function() { console.log('%c\nNextcloud, A safe home for all your data', 'font-size:20px'); console.log( '%c', 'font-size: 100px; background: white url(' + window.location + 'wp-content/themes/next/assets/img/logo/logo_nextcloud_blue.png) no-repeat left bottom; background-repeat: no-repeat; background-size: 100px 64px;' ); }, checkScrollPosition: function() { var currentScrollPosition = $(document).scrollTop().valueOf(); if (currentScrollPosition > 500) { $('.revealOnScroll:not(.fade-in)').each(_.bind(this.removeRevealOnScroll, this)); } else { return; } }, removeRevealOnScroll: function(index, element) { $(element).addClass('fade-in'); }, buttonDropdown: function() { this.variables.buttonDropdownSelector.toggleClass(this.variables.activeClass); this.variables.buttonDropdownContentSelector.toggleClass(this.variables.visibleClass); }, animationOnLoadPage: function() { var animationOnLoadPageTimeline = new TimelineMax (); animationOnLoadPageTimeline.to($(this.variables.topHeaderSelector), 1, {autoAlpha: 1}); animationOnLoadPageTimeline.to($(this.variables.heroSectionBackgroundSelector), 1, {autoAlpha: 1}); animationOnLoadPageTimeline.to($(this.variables.heroHeading), 1, {y:0 , autoAlpha: 1}); animationOnLoadPageTimeline.to($(this.variables.heroSubtitle), 1, {y:0 , autoAlpha: 1}, '-= 0.6'); }, smoothScroll: function() { $('a[href*="#"]:not([href="#"]):not([data-toggle="collapse"])').click(function() { if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) { var target = $(this.hash); target = target.length ? target : $('[name=' + this.hash.slice(1) +']'); if (target.length) { $('html, body').animate({ scrollTop: target.offset().top }, 1000); return false; } } }); }, revealOnScroll: function(event) { var scrollTop = $(window).scrollTop(); $('.revealOnScroll:not(.fade-in)').each(function(index, element) { var selectorOffset = $(element).offset(); if (scrollTop + window.innerHeight - 100 > selectorOffset.top) { $(element).addClass('fade-in').velocity('transition.slideUpIn'); } }); }, }; main.init(); }); });
FlorentPoinsaut/documentation
<|start_filename|>samples/Samples.Mvc5/App_Start/FilterConfig.cs<|end_filename|> using System.Web.Mvc; using StackExchange.Profiling.Mvc; namespace Samples.Mvc5 { public static class FilterConfig { public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new HandleErrorAttribute()); filters.Add(new ProfilingActionFilter()); } } } <|start_filename|>samples/Samples.AspNetCore/Views/Home/Index.RightPanel.cshtml<|end_filename|> <div class="col-md-6"> <div class="panel panel-default"> <div class="panel-heading">Results from ajax requests</div> <div class="panel-body ajax-results"> </div> </div> @Html.Partial("Index.ProfilerInfo") </div> <|start_filename|>samples/Samples.Mvc5/Content/Site.css<|end_filename|> .navbar { margin-bottom: 0; } .glyphicon.spinning { margin-left: 5px; font-size: 0.6em; animation: spin 0.6s infinite linear; } @keyframes spin { from { transform: scale(1) rotate(0deg); } to { transform: scale(1) rotate(360deg); } } <|start_filename|>src/MiniProfiler.Shared/RenderPosition.cs<|end_filename|> namespace StackExchange.Profiling { /// <summary> /// Dictates on which side of the page the profiler popup button is displayed; defaults to top left. /// </summary> public enum RenderPosition { /// <summary> /// Profiler popup button is displayed on the top left. /// </summary> Left = 0, /// <summary> /// Profiler popup button is displayed on the top right. /// </summary> Right = 1, /// <summary> /// Profiler popup button is displayed on the bottom left. /// </summary> BottomLeft = 2, /// <summary> /// Profiler popup button is displayed on the bottom right. /// </summary> BottomRight = 3 } } <|start_filename|>samples/Samples.Mvc5/Views/Shared/_Layout.cshtml<|end_filename|> @using StackExchange.Profiling; @using StackExchange.Profiling.Mvc @{ // allows us to test out starting a profiler hidden - use ALT + P to toggle display of results var startHidden = !string.IsNullOrEmpty(Request.QueryString["startHidden"]); } <!DOCTYPE html> <html> <head> @this.InitClientTimings() @this.TimeScript("jQuery 3.1.1", @<script src="http://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>) @using (MiniProfiler.Current.Step("<head> rendering")) { <title>@ViewBag.Title - MVC MiniProfiler Demo</title> @(this.TimeScript("Our CSS", @Styles.Render("~/Content/css"))); @Scripts.Render("~/bundles/bootstrap") @RenderSection("head", required: false) } </head> <body> <header> <nav class="navbar navbar-default"> <div class="container-fluid"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="#">MiniProfiler Demo</a> </div> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <ul class="nav navbar-nav"> <li>@Html.ActionLink("Home", "Index", "Home")</li> <li>@Html.ActionLink("About", "About", "Home")</li> <li>@Html.ActionLink("Results Authorization", "ResultsAuthorization", "Home")</li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">Position <span class="caret"></span></a> <ul class="dropdown-menu" role="menu"> <li>@Html.ActionLink("Top Left", "TopLeft", "Home")</li> <li>@Html.ActionLink("Top Right", "Index", "Home")</li> <li>@Html.ActionLink("Bottom Left", "BottomLeft", "Home")</li> <li>@Html.ActionLink("Bottom Right", "BottomRight", "Home")</li> </ul> </li> </ul> </div> </div> </nav> </header> <div> @RenderBody() </div> @* renders our UI's css and javascript - best put it in the bottom so it does not effect perf *@ @if (ViewBag.Orientation != null) { var position = (RenderPosition)ViewBag.Orientation; @MiniProfiler.Current.RenderIncludes(position: position, showTrivial: false, showTimeWithChildren: false, startHidden: startHidden) } else { @MiniProfiler.Current.RenderIncludes(position: RenderPosition.Right, showTrivial: false, showTimeWithChildren: false, startHidden: startHidden) } </body> </html> <|start_filename|>samples/Samples.Mvc5/EFCodeFirst/Person.cs<|end_filename|> namespace Samples.Mvc5.EFCodeFirst { /// <summary> /// The person. /// </summary> public class Person { /// <summary> /// Gets or sets the id. /// </summary> public int Id { get; set; } /// <summary> /// Gets or sets the name. /// </summary> public string Name { get; set; } } } <|start_filename|>samples/Samples.AspNetCore/Views/_ViewImports.cshtml<|end_filename|> @using Samples.AspNetCore @using StackExchange.Profiling @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers @addTagHelper *, MiniProfiler.AspNetCore.Mvc <|start_filename|>samples/Samples.AspNetCore/Views/Home/Index.ProfilerInfo.cshtml<|end_filename|> @using StackExchange.Profiling @functions{ public string GetVal(object o) => o?.ToString().Replace("StackExchange.Profiling.", string.Empty); } <div class="panel panel-default"> <div class="panel-heading">MiniProfiler Info</div> <div class="panel-body"> <ul> <li><label>Version</label>: @GetVal(MiniProfiler.Settings.Version)</li> <li><label>Path</label>: @GetVal(MiniProfiler.Settings.RouteBasePath)</li> <li><label>Provider</label>: @GetVal(MiniProfiler.Settings.ProfilerProvider)</li> <li><label>Storage</label>: @GetVal(MiniProfiler.Settings.Storage)</li> <li><label>SQL Formatter</label>: @GetVal(MiniProfiler.Settings.SqlFormatter)</li> <li><label>Trivial Threshold (ms)</label>: @GetVal(MiniProfiler.Settings.TrivialDurationThresholdMilliseconds)</li> <li><label>Toggle Shortcut</label>: @GetVal(MiniProfiler.Settings.PopupToggleKeyboardShortcut)</li> </ul> </div> </div> <|start_filename|>samples/Samples.AspNetCore/Views/Test/ForLoop.cshtml<|end_filename|> @{ Layout = null; } @using (MiniProfiler.Current.Step("For Loop - using()")) { int dontCare = 0; for (var i = 0; i < 10000000; i++) { dontCare++; } @:@dontCare <code>using</code> loops complete. } <br/> <profile name="For Loop - <profile> Tag"> @{ int stillDontCare = 0; for (var i = 0; i < 10000000; i++) { stillDontCare++; } } <span>@stillDontCare <code>&lt;profile&gt;</code> loops complete.</span> </profile> <|start_filename|>samples/Samples.Mvc5/Views/Home/About.cshtml<|end_filename|> @{ ViewBag.Title = "About Us"; } <div class="col-md-12"> <div class="page-header"> <h2>About</h2> </div> <p> We explictly stopped profiling on this route: <pre><code>public ActionResult About() { // prevent this specific route from being profiled MiniProfiler.Stop(discardResults: true); return View(); }</code></pre> </p> </div>
HydAu/MiniProfilerDotNet
<|start_filename|>eCommerce/eCommerce/ViewModel/categoriesViewModel.cs<|end_filename|> using eCommerce.Views; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Runtime.CompilerServices; using System.Text; using System.Threading.Tasks; using System.Windows.Input; using Xamarin.Forms; namespace eCommerce.Model { public class categoriesViewModel : INotifyPropertyChanged { readonly IList<FeaturedBrands> source1; public ObservableCollection<FeaturedBrands> featuredItemPreview { get; private set; } readonly IList<ItemsPreview> source; public ObservableCollection<ItemsPreview> itemPreview { get; private set; } public ICommand FeaturedTapCommand { get; set; } public ICommand ItemTapCommand { get; set; } public categoriesViewModel() { source = new List<ItemsPreview>(); source1 = new List<FeaturedBrands>(); CreateItemCollection(); CreateFeaturedItemCollection(); ItemTapCommand = new Command<ItemsPreview>(items => { Xamarin.Forms.Application.Current.MainPage.Navigation.PushModalAsync((new ProductPage())); }); FeaturedTapCommand = new Command<FeaturedBrands>(brand => { string selBrand = brand.brand; Xamarin.Forms.Application.Current.MainPage.Navigation.PushModalAsync(new NavigationPage(new BrandPage(selBrand))); }); } void CreateItemCollection() { source.Add(new ItemsPreview { ImageUrl = "Image3", Name = "Smart Bluetooth Speaker", brand = "Google LLC", price = "$90" }); source.Add(new ItemsPreview { ImageUrl = "Image5", Name = "Smart Luggage", brand = "Smart Inc", price = "$450" }); source.Add(new ItemsPreview { ImageUrl = "Image6", Name = "Wireless Remote", brand = "Tesla Inc", price = "$790" }); source.Add(new ItemsPreview { ImageUrl = "Image4", Name = "Airpods", brand = "Apple Inc", price = "$120" }); itemPreview = new ObservableCollection<ItemsPreview>(source); } void CreateFeaturedItemCollection() { source1.Add(new FeaturedBrands { ImageUrl = "Icon_Apple", brand = "Apple Inc", details = "5693 Products" }); source1.Add(new FeaturedBrands { ImageUrl = "beats", brand = "Beats", details = "1124 Products" }); source1.Add(new FeaturedBrands { ImageUrl = "Icon_Bo", brand = "B&o", details = "5693 Products" }); featuredItemPreview = new ObservableCollection<FeaturedBrands>(source1); } #region INotifyPropertyChanged public event PropertyChangedEventHandler PropertyChanged; void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } #endregion } } <|start_filename|>eCommerce/eCommerce/ViewModel/ItemPreviewViewModel.cs<|end_filename|> using eCommerce.Views; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Runtime.CompilerServices; using System.Text; using System.Threading.Tasks; using System.Windows.Input; using Xamarin.Forms; namespace eCommerce.Model { class ItemPreviewViewModel : INotifyPropertyChanged { readonly IList<ItemsPreview> source; public ObservableCollection<ItemsPreview> itemPreview { get; private set; } readonly IList<FeaturedBrands> source1; public ObservableCollection<FeaturedBrands> featuredItemPreview { get; private set; } readonly IList<Category> source2; public ObservableCollection<Category> categories { get; private set; } public ICommand FeaturedTapCommand { get; set; } public ICommand ItemTapCommand { get; set; } public ICommand CatTapCommand { get; set; } public ItemPreviewViewModel() { source = new List<ItemsPreview>(); source1 = new List<FeaturedBrands>(); source2 = new List<Category>(); CreateItemCollection(); CreateFeaturedItemCollection(); CreateCategoriesCollection(); ItemTapCommand = new Command<ItemsPreview>(items => { Xamarin.Forms.Application.Current.MainPage.Navigation.PushModalAsync((new ProductPage())); }); CatTapCommand = new Command<Category>(items => { string selcate = items.title; Xamarin.Forms.Application.Current.MainPage.Navigation.PushModalAsync(new categoriesPage(selcate)); }); FeaturedTapCommand = new Command<FeaturedBrands>(brand => { string selBrand = brand.brand; Xamarin.Forms.Application.Current.MainPage.Navigation.PushModalAsync(new NavigationPage(new BrandPage(selBrand))); }); } void CreateCategoriesCollection() { source2.Add(new Category { image = "Icon_Mens_Shoe", title = "Men", link = "5693 Products" }); source2.Add(new Category { image = "women_shoe", title = "Women", link = "1124 Products" }); source2.Add(new Category { image = "devices", title = "Devices", link = "5693 Products" }); source2.Add(new Category { image = "headphone", title = "Gadgets", link = "5693 Products" }); source2.Add(new Category { image = "Icon_Gaming", title = "Gaming", link = "5693 Products" }); categories = new ObservableCollection<Category>(source2); } void CreateFeaturedItemCollection() { source1.Add(new FeaturedBrands { ImageUrl = "Icon_Bo", brand = "B&o", details = "5693 Products" }); source1.Add(new FeaturedBrands { ImageUrl = "beats", brand = "Beats", details = "1124 Products" }); source1.Add(new FeaturedBrands { ImageUrl = "Icon_Apple", brand = "Apple Inc", details = "5693 Products" }); featuredItemPreview = new ObservableCollection<FeaturedBrands>(source1); } void CreateItemCollection() { source.Add(new ItemsPreview { ImageUrl = "Image1", Name= "BeoPlay Speaker", brand= "Bang and Olufsen", price= "$755" }); source.Add(new ItemsPreview { ImageUrl = "Image2", Name = "<NAME>", brand = "Tag Heuer", price = "$450" }); source.Add(new ItemsPreview { ImageUrl = "Image3", Name = "Smart Bluetooth Speaker", brand = "Google LLC", price = "$9000" }); source.Add(new ItemsPreview { ImageUrl = "Image4", Name = "Smart Luggage", brand = "Smart Inc", price = "$1200" }); itemPreview = new ObservableCollection<ItemsPreview>(source); } #region INotifyPropertyChanged public event PropertyChangedEventHandler PropertyChanged; void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } #endregion } } <|start_filename|>eCommerce/eCommerce.Android/MyPickerDroid.cs<|end_filename|> using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.Graphics.Drawables; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using eCommerce; using eCommerce.Droid; using Xamarin.Forms; using Xamarin.Forms.Platform.Android; using PickerRenderer = Xamarin.Forms.Platform.Android.AppCompat.PickerRenderer; [assembly: ExportRenderer(typeof(CustomPicker), typeof(CustomPickerRenderer))] namespace eCommerce.Droid { class CustomPickerRenderer : PickerRenderer { public CustomPickerRenderer(Context context) : base(context) { } protected override void OnElementChanged(ElementChangedEventArgs<Picker> e) { base.OnElementChanged(e); if (Control != null) { GradientDrawable gd = new GradientDrawable(); gd.SetStroke(0, Android.Graphics.Color.Transparent); Control.SetBackground(gd); //Control.SetTextColor(Android.Graphics.Color.White); } } } } <|start_filename|>eCommerce/eCommerce.iOS/MyPickerIos.cs<|end_filename|> using System; using System.Collections.Generic; using System.Linq; using System.Text; using eCommerce; using Foundation; using UIKit; using Xamarin.Forms; using Xamarin.Forms.Platform.iOS; [assembly: ExportRenderer(typeof(CustomPicker), typeof(PickerRenderer))] namespace eCommerce.iOS { public class BorderPickerRenderer : PickerRenderer { protected override void OnElementChanged(ElementChangedEventArgs<Picker> e) { base.OnElementChanged(e); var view = e.NewElement as CustomPicker; this.Control.BorderStyle = UITextBorderStyle.None; } } } <|start_filename|>eCommerce/eCommerce/CustomEntry.cs<|end_filename|> using Xamarin.Forms; namespace eCommerce { public class CustomEntry : Entry { } } <|start_filename|>eCommerce/eCommerce/Views/categoriesPage.xaml.cs<|end_filename|> using eCommerce.Model; using Rg.Plugins.Popup.Services; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace eCommerce.Views { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class categoriesPage : ContentPage { public categoriesPage(string titleName) { InitializeComponent(); title.Text = titleName; } private async void TapGestureRecognizer_Tapped(object sender, EventArgs e) { await Navigation.PopModalAsync(); } private async void TapGestureRecognizer_Tapped_1(object sender, EventArgs e) { await PopupNavigation.Instance.PushAsync(new Filter()); } } } <|start_filename|>eCommerce/eCommerce/Model/DeliverySteps.cs<|end_filename|> using System; using System.Collections.Generic; using System.Text; using Xamarin.Forms; namespace eCommerce.Model { public class DeliverySteps { public string Name { get; set; } public string Location { get; set; } public string dateMon { get; set; } public string tim { get; set; } public Color colorFrame { get; set; } public Color colorLine { get; set; } } } <|start_filename|>eCommerce/eCommerce.Android/CustomEntryRenderer.cs<|end_filename|> using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.Content; using Android.Content.Res; using Android.Graphics.Drawables; using eCommerce; using eCommerce.Droid; using Xamarin.Forms; using Xamarin.Forms.Platform.Android; [assembly: ExportRenderer(typeof(CustomEntry), typeof(CustomEntryRenderer))] namespace eCommerce.Droid { public class CustomEntryRenderer : EntryRenderer { public CustomEntryRenderer(Context context) : base(context) { } protected override void OnElementChanged(ElementChangedEventArgs<Entry> e) { base.OnElementChanged(e); if (Control != null) { Control.SetBackgroundColor(Android.Graphics.Color.Transparent); } } } } <|start_filename|>eCommerce/eCommerce/Views/TrackOrder.xaml.cs<|end_filename|> using eCommerce.Model; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace eCommerce.Views { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class TrackOrder : ContentPage { public TrackOrder() { InitializeComponent(); BindingContext = new TrackViewModel(); } private async void TapGestureRecognizer_Tapped(object sender, EventArgs e) { await Navigation.PopModalAsync(); } async void OnItemSelected(object sender, SelectionChangedEventArgs e) { await Navigation.PushModalAsync(new StepView()); } } } <|start_filename|>eCommerce/eCommerce/Model/TrakGroup.cs<|end_filename|> using System; using System.Collections.Generic; using System.Text; namespace eCommerce.Model { public class TrakGroup : List<Track> { public string Date { get; private set; } public TrakGroup(string date, List<Track> tracks) : base(tracks) { Date = date; } public override string ToString() { return Date; } } } <|start_filename|>eCommerce/eCommerce/Views/HomePage.xaml.cs<|end_filename|> using eCommerce.Model; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace eCommerce.Views { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class HomePage : ContentPage { public HomePage() { InitializeComponent(); } private async void TapGestureRecognizer_Tapped(object sender, EventArgs e) { await Navigation.PushModalAsync(new BrandPage("Recommended")); } private async void TapGestureRecognizer_Tapped_1(object sender, EventArgs e) { await Navigation.PushModalAsync(new NavigationPage(new BrandPage("Best Selling"))); } private async void TapGestureRecognizer_Tapped_2(object sender, EventArgs e) { await Navigation.PushModalAsync(new Cart()); } private async void TapGestureRecognizer_Tapped_3(object sender, EventArgs e) { await Navigation.PushModalAsync(new Account()); } protected override bool OnBackButtonPressed() { return false; } } } <|start_filename|>eCommerce/eCommerce/Model/FeaturedBrands.cs<|end_filename|> using System; using System.Collections.Generic; using System.Text; namespace eCommerce.Model { public class FeaturedBrands { public string ImageUrl { get; set; } public string brand { get; set; } public string details { get; set; } } } <|start_filename|>eCommerce/eCommerce/Model/Reviews.cs<|end_filename|> using System; using System.Collections.Generic; using System.Text; namespace eCommerce.Model { public class Reviews { public string image { get; set; } public string name { get; set; } public string review { get; set; } public string rating { get; set; } } } <|start_filename|>eCommerce/eCommerce/Views/BrandPage.xaml.cs<|end_filename|> using eCommerce.Model; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace eCommerce.Views { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class BrandPage : TabbedPage { public BrandPage(String name) { InitializeComponent(); title.Text = name; this.ItemsSource = new MainClass[] { new MainClass ("All",new List<ItemsPreview>(){ new ItemsPreview {ImageUrl = "Image1",Name = "Smart Bluetooth Speaker", brand = "Bang and Olufsen",price = "$90"}, new ItemsPreview { ImageUrl = "Image7", Name = "B&o Desk Lamp", brand = "Bang and Olufsen", price = "$450" },new ItemsPreview { ImageUrl = "Image8", Name = "BeoPlay Stand Speaker", brand = "Bang and Olufsen", price = "$300" } }), new MainClass ("Headphones",new List<ItemsPreview>(){ new ItemsPreview {ImageUrl = "Image1",Name = "Smart Bluetooth Speaker", brand = "Bang and Olufsen",price = "$90"}, new ItemsPreview { ImageUrl = "Image7", Name = "B&o Desk Lamp", brand = "Bang and Olufsen", price = "$450" },new ItemsPreview { ImageUrl = "Image8", Name = "BeoPlay Stand Speaker", brand = "Bang and Olufsen", price = "$300" } }), new MainClass ("Speakers",new List<ItemsPreview>(){ new ItemsPreview {ImageUrl = "Image1",Name = "Smart Bluetooth Speaker", brand = "Bang and Olufsen",price = "$90"}, new ItemsPreview { ImageUrl = "Image7", Name = "B&o Desk Lamp", brand = "Bang and Olufsen", price = "$450" },new ItemsPreview { ImageUrl = "Image8", Name = "BeoPlay Stand Speaker", brand = "Bang and Olufsen", price = "$300" } }), new MainClass ("Microphones",new List<ItemsPreview>(){ new ItemsPreview {ImageUrl = "Image1",Name = "Smart Bluetooth Speaker", brand = "Bang and Olufsen",price = "$90"}, new ItemsPreview { ImageUrl = "Image7", Name = "B&o Desk Lamp", brand = "Bang and Olufsen", price = "$450" },new ItemsPreview { ImageUrl = "Image8", Name = "BeoPlay Stand Speaker", brand = "Bang and Olufsen", price = "$300" } }), }; } class MainClass { public MainClass(string name, IList<ItemsPreview> list) { this.Name = name; this.list = list; } public string Name { private set; get; } public IList<ItemsPreview> list { private set; get; } public override string ToString() { return Name; } } private async void TapGestureRecognizer_Tapped(object sender, EventArgs e) { await Navigation.PopModalAsync(); } async void OnItemSelected(object sender, SelectionChangedEventArgs e) { await Navigation.PushModalAsync(new ProductPage()); } } } <|start_filename|>eCommerce/eCommerce/ViewModel/BrandViewModel.cs<|end_filename|> using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Runtime.CompilerServices; using System.Text; using System.Windows.Input; namespace eCommerce.Model { public class BrandViewModel : INotifyPropertyChanged { readonly IList<BrandsItems> source; readonly IList<ItemsPreview> source1; public ObservableCollection<BrandsItems> itemList{ get; private set; } public ObservableCollection<ItemsPreview> itemPreview { get; private set; } ICommand tapCommand; public BrandViewModel() { source = new List<BrandsItems>(); source1 = new List<ItemsPreview>(); CreateMenuCollection(); CreateItemCollection(); } public ICommand TapCommand { get { return tapCommand; } } void CreateItemCollection() { source1.Add(new ItemsPreview { ImageUrl = "Image1", Name = "Smart Bluetooth Speaker", brand = "Bang and Olufsen", price = "$90" }); source1.Add(new ItemsPreview { ImageUrl = "Image7", Name = "B&o Desk Lamp", brand = "Bang and Olufsen", price = "$450" }); source1.Add(new ItemsPreview { ImageUrl = "Image8", Name = "BeoPlay Stand Speaker", brand = "Bang and Olufsen", price = "$300" }); source1.Add(new ItemsPreview { ImageUrl = "Image9", Name = "Airpods", brand = "B&o Phone Case", price = "$30" }); itemPreview = new ObservableCollection<ItemsPreview>(source1); } void CreateMenuCollection() { source.Add(new BrandsItems { brand = "Bang and Olufsen", itemName = "All" }); source.Add(new BrandsItems { brand = "Bang and Olufsen", itemName = "Headphones" }); source.Add(new BrandsItems { brand = "Bang and Olufsen", itemName = "Speakers" }); source.Add(new BrandsItems { brand = "Bang and Olufsen", itemName = "Microphones" }); itemList = new ObservableCollection<BrandsItems>(source); } #region INotifyPropertyChanged public event PropertyChangedEventHandler PropertyChanged; void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } #endregion } } <|start_filename|>eCommerce/eCommerce/ViewModel/ProductViewModel.cs<|end_filename|> using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Runtime.CompilerServices; using System.Text; namespace eCommerce.Model { public class ProductViewModel: INotifyPropertyChanged { readonly IList<Reviews> source; public ObservableCollection<Reviews> itemPreview { get; private set; } public ProductViewModel() { source = new List<Reviews>(); CreateItemCollection(); } void CreateItemCollection() { source.Add(new Reviews { image = "user1", name = "<NAME>", review = "Wonderful jean, perfect gift for my girl for our anniversary!", rating = "4" }); source.Add(new Reviews { image = "user2", name = "<NAME>", review = "I love this, paired it with a nice blouse and all eyes on me.", rating = "3" }); source.Add(new Reviews { image = "user1", name = "<NAME>", review = "Wonderful jean, perfect gift for my girl for our anniversary!", rating = "4" }); source.Add(new Reviews { image = "user2", name = "<NAME>", review = "I love this, paired it with a nice blouse and all eyes on me.", rating = "3" }); itemPreview = new ObservableCollection<Reviews>(source); } #region INotifyPropertyChanged public event PropertyChangedEventHandler PropertyChanged; void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } #endregion } } <|start_filename|>eCommerce/eCommerce/ViewModel/TrackViewModel.cs<|end_filename|> using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Runtime.CompilerServices; using System.Text; namespace eCommerce.Model { public class TrackViewModel { // bool includeEmptyGroups; public List<TrakGroup> track { get; private set; } = new List<TrakGroup>(); public TrackViewModel(bool emptyGroups = false) { // includeEmptyGroups = emptyGroups; CreateTrackCollection(); } void CreateTrackCollection() { track.Add(new TrakGroup("Sept 23, 2018", new List<Track> { new Track { orderId = "OD - 424923192 - N", price = "$4500", status = "Delivered", numberofItems = 5 }, })); track.Add(new TrakGroup("Sept 23, 2018", new List<Track> { new Track { orderId = "OD - 424923192 - N", price = "$500", status = "Delivered", numberofItems = 5 }, new Track { orderId = "OD - 424923192 - N", price = "$700", status = "Delivered", numberofItems = 5 } })); track.Add(new TrakGroup("Sept 22, 2018", new List<Track> { new Track { orderId = "OD - 424923192 - N", price = "$1500", status = "Delivered", numberofItems = 5 }, new Track { orderId = "OD - 424923192 - N", price = "$2700", status = "Delivered", numberofItems = 5 } })); } } } <|start_filename|>eCommerce/eCommerce/AssemblyInfo.cs<|end_filename|> using Xamarin.Forms; using Xamarin.Forms.Xaml; [assembly: XamlCompilation(XamlCompilationOptions.Compile)] [assembly: ExportFont("materialdesignicons-webfont.ttf", Alias = "MaterialFontFamily")] <|start_filename|>eCommerce/eCommerce/Views/ProductPage.xaml.cs<|end_filename|> using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace eCommerce.Views { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class ProductPage : ContentPage { double lastScrollIndex; double currentScrollIndex; public ProductPage() { InitializeComponent(); review.HeightRequest = 4 * 90; } private void ScrollView_Scrolled(object sender, ScrolledEventArgs e) { currentScrollIndex = e.ScrollY; if (currentScrollIndex > lastScrollIndex) { footer.IsVisible = false; } else { footer.IsVisible = true; } lastScrollIndex = currentScrollIndex; } private async void TapGestureRecognizer_Tapped(object sender, EventArgs e) { await Navigation.PopModalAsync(); } private async void TapGestureRecognizer_Tapped_1(object sender, EventArgs e) { string action = await DisplayActionSheet("Select Size", "Cancel", null, "X", "XL", "XXL"); size.Text = action; } } } <|start_filename|>eCommerce/eCommerce/ViewModel/DeliveryStepsViewModel.cs<|end_filename|> using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Drawing; using System.Text; using Xamarin.Forms; namespace eCommerce.Model { public class DeliveryStepsViewModel { readonly IList<DeliverySteps> source; public ObservableCollection<DeliverySteps> delList { get; private set; } int currentFlag = 3; //Starts from 0 List<tempData> tempData = new List<tempData>() { new tempData { Name="Order Signed", Location="Lagos State, Nigeria", dateMon="20/18", tim="10:00 AM" }, new tempData { Name="Order Signed", Location="Lagos State, Nigeria", dateMon="20/18", tim="10:00 AM" }, new tempData { Name="Order Signed", Location="Lagos State, Nigeria", dateMon="20/18", tim="10:00 AM" }, new tempData { Name="Order Signed", Location="Lagos State, Nigeria", dateMon="20/18", tim="10:00 AM" }, new tempData { Name="Order Signed", Location="Lagos State, Nigeria", dateMon="20/18", tim="10:00 AM" } }; public DeliveryStepsViewModel() { source = new List<DeliverySteps>(); CreateCollection(); } void CreateCollection() { Xamarin.Forms.Color frColor = Xamarin.Forms.Color.FromHex("#00C569"); Xamarin.Forms.Color linColor = Xamarin.Forms.Color.FromHex("#00C569"); for (int i=0;i< tempData.Count;i++) { if (i == (tempData.Count - 1)) { linColor = Xamarin.Forms.Color.Transparent; } else { if (i<currentFlag) { frColor = Xamarin.Forms.Color.FromHex("#00C569"); linColor = Xamarin.Forms.Color.FromHex("#00C569"); } else { frColor = Xamarin.Forms.Color.Transparent; linColor = Xamarin.Forms.Color.FromHex("#DDDDDD"); } } source.Add(new DeliverySteps { Name = tempData[i].Name, Location = tempData[i].Location, dateMon = tempData[i].dateMon, tim = tempData[i].tim, colorFrame = frColor, colorLine = linColor }); } delList = new ObservableCollection<DeliverySteps>(source); } } public class tempData { public string Name { get; set; } public string Location { get; set; } public string dateMon { get; set; } public string tim { get; set; } } } <|start_filename|>eCommerce/eCommerce/Model/Track.cs<|end_filename|> using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Text; namespace eCommerce.Model { public class Track { public string orderId { get; set; } public string price { get; set; } public string status { get; set; } public int numberofItems { get; set; } public override string ToString() { return orderId; } } } <|start_filename|>eCommerce/eCommerce/Views/Cart.xaml.cs<|end_filename|> using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace eCommerce.Views { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class Cart : ContentPage { public Cart() { InitializeComponent(); } async void OnDeleteSwipeItemInvoked(object sender, EventArgs e) { await DisplayAlert("SwipeView", "Delete invoked.", "OK"); } async void OnFavoriteSwipeItemInvoked(object sender, EventArgs e) { await DisplayAlert("SwipeView", "Favorite invoked.", "OK"); } private async void TapGestureRecognizer_Tapped(object sender, EventArgs e) { await Navigation.PushModalAsync(new HomePage()); } private async void TapGestureRecognizer_Tapped_1(object sender, EventArgs e) { await Navigation.PushModalAsync(new Account()); } } } <|start_filename|>eCommerce/eCommerce/ViewModel/CardViewModel.cs<|end_filename|> using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Runtime.CompilerServices; using System.Text; using System.Windows.Input; using Xamarin.Forms; namespace eCommerce.Model { public class CardViewModel : INotifyPropertyChanged { readonly IList<CartModel> source; public ObservableCollection<CartModel> itemPreview { get; private set; } public ICommand DeleteCommand => new Command<CartModel>(RemoveCart); public CardViewModel() { source = new List<CartModel>(); CreateItemCollection(); } void RemoveCart(CartModel cart) { if (itemPreview.Contains(cart)) { itemPreview.Remove(cart); } } void CreateItemCollection() { source.Add(new CartModel { image = "Item1", name = "<NAME>", price = "$2400", numbers = 1 }); source.Add(new CartModel { image = "Item2", name = "<NAME>", price = "$4400", numbers = 1 }); source.Add(new CartModel { image = "Item3", name = "Electric Kettle", price = "$400", numbers = 1 }); source.Add(new CartModel { image = "Item4", name = "Bang & <NAME>", price = "$4500", numbers = 1 }); itemPreview = new ObservableCollection<CartModel>(source); } #region INotifyPropertyChanged public event PropertyChangedEventHandler PropertyChanged; void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } #endregion } } <|start_filename|>eCommerce/eCommerce/CustomPicker.cs<|end_filename|> using System; using System.Collections.Generic; using System.Text; using Xamarin.Forms; namespace eCommerce { public class CustomPicker : Picker { } } <|start_filename|>eCommerce/eCommerce/Model/CartModel.cs<|end_filename|> using System; using System.ComponentModel; using Xamarin.Forms; namespace eCommerce.Model { public class CartModel : INotifyPropertyChanged { public string image { get; set; } public string name { get; set; } public string price { get; set; } public int numbers { get; set; } public event PropertyChangedEventHandler PropertyChanged; protected virtual void OnPropertyChanged(string propertyName) { var changed = PropertyChanged; if (changed != null) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } public Command DecreseTapCommand { get { return new Command(val => { var modelObj = (CartModel)val; if (modelObj.numbers >= 2) { numbers = (modelObj.numbers - 1); OnPropertyChanged("numbers"); } }); } } public Command IncreaseTapCommand { get { return new Command(val => { numbers = (Int16.Parse(val.ToString()) + 1); OnPropertyChanged("numbers"); }); } } } } <|start_filename|>eCommerce/eCommerce/Model/Category.cs<|end_filename|> using System; using System.Collections.Generic; using System.Text; namespace eCommerce.Model { public class Category { public string image { get; set; } public string title { get; set; } public string link { get; set; } } }
pqhcker/ecommerceXF
<|start_filename|>package.json<|end_filename|> { "name": "web-ext-translator-monorepo", "private": true, "workspaces": [ "packages/wet-shared", "packages/wet-layer", "packages/wet-online", "packages/wet-cli" ], "scripts": { "build": "yarn workspaces run build", "lint": "yarn run lint:es && yarn run lint:css && yarn run lint:package && yarn run lint:style", "lint:css": "stylelint --ignore-path .prettierignore 'packages/*/src/**/*.css'", "lint:css:fix": "yarn run lint:css --fix", "lint:es": "eslint 'packages/*/src/**/*.{ts,tsx}' --ext .ts,.tsx --ignore-path .prettierignore", "lint:es:fix": "yarn run lint:es --fix", "lint:fix": "yarn run lint:es:fix && yarn run lint:css:fix && yarn run lint:package:fix && yarn run lint:style:fix", "lint:package": "yarn run lint:package:fix --check", "lint:package:fix": "sort-package-json package.json 'packages/*/package.json'", "lint:style": "yarn run lint:style:base --check", "lint:style:base": "prettier 'packages/*/src/**/*.{ts,tsx,js,json,css}' 'packages/*/*.{ts,tsx,js,json,css}'", "lint:style:fix": "yarn run lint:style:base --write", "release": "lerna publish", "prepack": "yarn run build", "start": "yarn workspace web-ext-translator-online start", "start:cli": "yarn workspace web-ext-translator start" }, "devDependencies": { "@lusito/eslint-config-react": "^1.6.1", "@lusito/prettier-config": "^1.6.0", "@lusito/stylelint-config": "^1.6.0", "lerna": "^4.0.0", "sort-package-json": "^1.50.0" } } <|start_filename|>packages/wet-online/src/components/TranslationTable/TranslationTableSection/style.css<|end_filename|> .translation-table-section { display: flex; } .translation-table-section__cell:first-child { color: #ec7a30; padding-top: 10px; border-bottom: 1px solid #ec7a30; font-family: monospace; flex-grow: 1; width: 100%; margin-top: 3px; vertical-align: top; position: relative; word-break: break-all; } .translation-table-section__cell:nth-child(2) { width: auto; padding-top: 10px; padding-left: 3px; border-bottom: 1px solid #ec7a30; } <|start_filename|>packages/wet-online/src/components/TranslationTable/TranslationTableBody/style.css<|end_filename|> .translation-table-body { position: relative; flex-grow: 1; padding: 10px; overflow-x: auto; overflow-y: scroll; box-sizing: border-box; } <|start_filename|>packages/wet-online/src/components/TranslationTable/TranslationTableHead/style.css<|end_filename|> .translation-table-head { flex-grow: 0; flex-shrink: 0; padding: 5px 10px; box-sizing: border-box; padding-right: 27px; display: flex; flex-direction: row; } .translation-table-head__cell { flex-grow: 1; width: calc(100% / 3); margin-left: 3px; } .translation-table-head__cell:first-child { text-align: left; border-bottom: 1px solid #313131; font-weight: bold; margin-left: 0; } <|start_filename|>.eslintrc.js<|end_filename|> const utils = require("@lusito/eslint-config/utils"); module.exports = { extends: ["@lusito/eslint-config-react"], rules: { ...utils.getA11yOffRules(), // just for now "import/no-cycle": "off", // fixme "react/require-default-props": "off", }, env: { browser: true, }, }; <|start_filename|>packages/wet-shared/package.json<|end_filename|> { "name": "web-ext-translator-shared", "version": "4.0.0", "description": "Shared interfaces for the web-ext-translator project", "keywords": [ "Web-Extensions", "Translation", "Translator" ], "homepage": "https://github.com/Lusito/web-ext-translator", "bugs": { "url": "https://github.com/Lusito/web-ext-translator/issues" }, "repository": { "type": "git", "url": "https://github.com/Lusito/web-ext-translator.git" }, "license": "Zlib", "author": "<NAME>", "main": "dist/index.js", "files": [ "dist" ], "scripts": { "build": "rimraf dist && tsc" }, "devDependencies": { "rimraf": "^3.0.2", "typescript": "^4.1.2" }, "gitHead": "54b13a25ee2181d31142181a8b3f651af35f892e" } <|start_filename|>packages/wet-online/src/components/TranslationTable/TranslationTablePlus/style.css<|end_filename|> .translation-table-plus { width: auto; height: 24px; text-align: center; color: black; background: #dddddd; border: 1px solid rgb(41, 41, 41); margin: 0 2px; padding: 2px 15px; } .translation-table-plus:hover { background: #4ea2ff; color: white; border-color: #bbbbbb; } .translation-table-plus:focus { border: 1px solid #0075ad; outline: none; } <|start_filename|>packages/wet-online/src/components/TranslationTable/TranslationTableRow/style.css<|end_filename|> .translation-table-row { display: flex; } .translation-table-row__cell { flex-grow: 1; width: calc(100% / 3); margin-left: 3px; margin-top: 3px; position: relative; } .translation-table-row__cell:first-child { word-break: break-all; margin-left: 0; } .translation-table-row__cell:nth-child(2), .translation-table-row__cell:nth-child(3) { min-width: 100px; padding: 5px; background: #333333; cursor: text; } .translation-table-row__cell:nth-child(4) { width: auto; } .translation-table-row__cell:first-child { border-bottom: 1px solid #313131; font-family: monospace; } <|start_filename|>packages/wet-layer/package.json<|end_filename|> { "name": "wet-layer", "version": "4.0.0", "description": "A layer between web-extensions and i18n to allow for the live apply feature of the web-ext-translator.", "keywords": [ "TypeScript", "web-extension", "web-ext-translator" ], "homepage": "https://github.com/Lusito/web-ext-translator", "bugs": { "url": "https://github.com/Lusito/web-ext-translator/issues" }, "repository": { "type": "git", "url": "https://github.com/Lusito/web-ext-translator.git" }, "license": "Zlib", "author": "<NAME>", "main": "dist/index.js", "types": "dist/index.d.ts", "files": [ "dist/" ], "scripts": { "build": "rimraf dist && tsc" }, "dependencies": { "rimraf": "^3.0.2", "web-ext-translator-shared": "^4.0.0" }, "devDependencies": { "@types/webextension-polyfill": "^0.8.0", "typescript": "^4.3.5", "webextension-polyfill": "^0.8.0" }, "peerDependencies": { "webextension-polyfill": "^0.8.0" }, "gitHead": "54b13a25ee2181d31142181a8b3f651af35f892e" } <|start_filename|>packages/wet-online/src/components/Toolbar/style.css<|end_filename|> .toolbar { display: flex; flex-direction: row; margin: 0; padding: 10px; flex-shrink: 0; box-sizing: border-box; position: relative; } .toolbar__title { margin: 2px 0 0 0; } .icon-button.icon-button--toolbar { width: 30px; height: 30px; background-size: 24px; margin-right: 10px; } .icon-button.icon-button--toolbar:last-child { margin-left: auto; } .icon-button.icon-button--toolbar:first-child:before { margin-left: -20px; } .icon-button.icon-button--toolbar:last-child:before { margin-left: -90px; } .icon-button.icon-button--toolbar:not(:disabled):hover { background-size: 30px; } .toolbar__separator { height: 28px; margin-right: 10px; border-right: 2px solid rgba(255, 255, 255, 0.6); }
Lusito/web-ext-translator
<|start_filename|>example/src/androidTest/java/com/github/paolorotolo/appintroexample/SwipeLockTest.java<|end_filename|> package com.github.paolorotolo.appintroexample; import android.support.test.espresso.Espresso; import android.support.test.rule.ActivityTestRule; import android.support.test.runner.AndroidJUnit4; import android.support.v4.view.ViewPager; import android.view.View; import com.github.paolorotolo.appintroexample.util.ViewPagerIdlingResource; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import static android.support.test.espresso.Espresso.onView; import static android.support.test.espresso.action.ViewActions.click; import static android.support.test.espresso.action.ViewActions.swipeLeft; import static android.support.test.espresso.action.ViewActions.swipeRight; import static android.support.test.espresso.assertion.ViewAssertions.matches; import static android.support.test.espresso.matcher.ViewMatchers.Visibility; import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed; import static android.support.test.espresso.matcher.ViewMatchers.isRoot; import static android.support.test.espresso.matcher.ViewMatchers.withEffectiveVisibility; import static android.support.test.espresso.matcher.ViewMatchers.withId; import static android.support.test.espresso.matcher.ViewMatchers.withText; import static com.github.paolorotolo.appintroexample.util.OrientationChangeAction.orientationLandscape; import static com.github.paolorotolo.appintroexample.util.OrientationChangeAction.orientationPortrait; import static org.hamcrest.CoreMatchers.allOf; @RunWith(AndroidJUnit4.class) public class SwipeLockTest { private ViewPagerIdlingResource viewPagerIdlingResource; private int viewPagerResId; private int btnSkipResId; private int btnNextResId; private int btnDoneResId; @Rule public ActivityTestRule<DisableSwipeIntro1> mActivityRule = new ActivityTestRule(DisableSwipeIntro1.class); @Before public void registerIntentServiceIdlingResource() { viewPagerResId = R.id.view_pager; btnSkipResId = R.id.skip; btnNextResId = R.id.next; btnDoneResId = R.id.done; View testRootView = mActivityRule.getActivity().findViewById(android.R.id.content); ViewPager testViewPager = (ViewPager) testRootView.findViewById(viewPagerResId); viewPagerIdlingResource = new ViewPagerIdlingResource(testViewPager, "ViewPager"); Espresso.registerIdlingResources(viewPagerIdlingResource); } @After public void unregisterIntentServiceIdlingResource() { if (viewPagerIdlingResource != null) { Espresso.unregisterIdlingResources(viewPagerIdlingResource); } } @Test public void skipButtonHiding() { // hide button onView(allOf(withId(btnSkipResId), isDisplayed())).check(matches(withEffectiveVisibility(Visibility.VISIBLE))); onView(allOf(withId(R.id.button_disable_skip), isDisplayed())).perform(click()); checkButtonVisibility(btnSkipResId, Visibility.INVISIBLE); checkButtonVisibilityOnPageSwipe(viewPagerResId, btnSkipResId, Visibility.INVISIBLE); checkButtonVisibilityOnRotation(btnSkipResId, Visibility.INVISIBLE); // show button onView(allOf(withId(R.id.button_disable_skip), isDisplayed())).perform(click()); checkButtonVisibilityOnPageSwipe(viewPagerResId, btnSkipResId, Visibility.VISIBLE); } @Test public void nextButtonHiding() { // hide button onView(allOf(withId(btnNextResId), isDisplayed())).check(matches(withEffectiveVisibility(Visibility.VISIBLE))); onView(allOf(withId(R.id.button_disable_progress), isDisplayed())).perform(click()); checkButtonVisibility(btnNextResId, Visibility.INVISIBLE); checkButtonVisibilityOnPageSwipe(viewPagerResId, btnNextResId, Visibility.INVISIBLE); checkButtonVisibilityOnRotation(btnNextResId, Visibility.INVISIBLE); // check that prior progress button visibility state is maintained when toggling swipe locking onView(allOf(withId(R.id.button_disable_swipe), isDisplayed())).perform(click()); onView(allOf(withId(R.id.button_disable_swipe), isDisplayed())).perform(click()); checkButtonVisibility(btnNextResId, Visibility.INVISIBLE); onView(allOf(withId(R.id.button_disable_next_swipe), isDisplayed())).perform(click()); onView(allOf(withId(R.id.button_disable_next_swipe), isDisplayed())).perform(click()); checkButtonVisibility(btnNextResId, Visibility.INVISIBLE); // show button onView(allOf(withId(R.id.button_disable_progress), isDisplayed())).perform(click()); checkButtonVisibilityOnPageSwipe(viewPagerResId, btnNextResId, Visibility.VISIBLE); } @Test public void doneButtonHiding() { onView(withId(viewPagerResId)).perform(swipeLeft()); onView(withId(viewPagerResId)).perform(swipeLeft()); // hide button onView(allOf(withId(btnDoneResId), isDisplayed())).check(matches(withEffectiveVisibility(Visibility.VISIBLE))); onView(allOf(withId(R.id.button_disable_progress), isDisplayed())).perform(click()); checkButtonVisibility(btnDoneResId, Visibility.INVISIBLE); checkButtonVisibilityOnPageSwipe(viewPagerResId, btnDoneResId, Visibility.INVISIBLE); checkButtonVisibilityOnRotation(btnDoneResId, Visibility.INVISIBLE); // show button onView(allOf(withId(R.id.button_disable_progress), isDisplayed())).perform(click()); onView(allOf(withId(btnDoneResId), isDisplayed())).check(matches(withEffectiveVisibility(Visibility.VISIBLE))); } @Test public void swipeLock() { onView(withId(viewPagerResId)).perform(swipeLeft()); // lock, test button hidden onView(allOf(withId(btnNextResId), isDisplayed())).check(matches(withEffectiveVisibility(Visibility.VISIBLE))); onView(allOf(withId(R.id.button_disable_swipe), isDisplayed())).perform(click()); oneShotSwipeLock(); onView(withId(viewPagerResId)).perform(swipeRight()); onView(allOf(withId(R.id.button_disable_swipe), isDisplayed())).perform(click()); onView(isRoot()).perform(orientationLandscape()); oneShotSwipeLock(); } private void oneShotSwipeLock() { checkButtonVisibility(btnNextResId, Visibility.INVISIBLE); // test swiping is locked and buttons are hidden checkButtonVisibilityOnPageSwipeLeft(viewPagerResId, btnNextResId, Visibility.INVISIBLE); onView(withText("Slide 2 title")).check(matches(isDisplayed())); checkButtonVisibilityOnPageSwipeRight(viewPagerResId, btnNextResId, Visibility.INVISIBLE); onView(withText("Slide 2 title")).check(matches(isDisplayed())); checkButtonVisibility(btnNextResId, Visibility.INVISIBLE); // test swiping is unlocked and buttons are shown onView(allOf(withId(R.id.button_disable_swipe), isDisplayed())).perform(click()); checkButtonVisibility(btnNextResId, Visibility.VISIBLE); checkButtonVisibilityOnPageSwipeRight(viewPagerResId, btnNextResId, Visibility.VISIBLE); onView(withText("Slide 1 title")).check(matches(isDisplayed())); checkButtonVisibilityOnPageSwipeLeft(viewPagerResId, btnNextResId, Visibility.VISIBLE); checkButtonVisibilityOnPageSwipeLeft(viewPagerResId, btnDoneResId, Visibility.VISIBLE); onView(withText("Slide 3 title")).check(matches(isDisplayed())); } @Test public void nextPageSwipeLock() { onView(withId(viewPagerResId)).perform(swipeLeft()); // lock, test button hidden onView(allOf(withId(btnNextResId), isDisplayed())).check(matches(withEffectiveVisibility(Visibility.VISIBLE))); onView(allOf(withId(R.id.button_disable_next_swipe), isDisplayed())).perform(click()); oneShotNextPageSwipeLock(); onView(allOf(withId(R.id.button_disable_next_swipe), isDisplayed())).perform(click()); onView(isRoot()).perform(orientationLandscape()); oneShotNextPageSwipeLock(); } private void oneShotNextPageSwipeLock() { checkButtonVisibility(btnNextResId, Visibility.INVISIBLE); // test swiping left is locked and buttons are hidden, restored on swipe right checkButtonVisibilityOnPageSwipeLeft(viewPagerResId, btnNextResId, Visibility.INVISIBLE); onView(withText("Slide 2 title")).check(matches(isDisplayed())); checkButtonVisibilityOnPageSwipeRight(viewPagerResId, btnNextResId, Visibility.VISIBLE); checkButtonVisibilityOnPageSwipeLeft(viewPagerResId, btnNextResId, Visibility.VISIBLE); onView(withText("Slide 2 title")).check(matches(isDisplayed())); } private void checkButtonVisibilityOnPageSwipe(int viewPagerResId, int btnResId, Visibility btnVisibility) { // check visibility state maintained between pages, assumes > 1 pages if (mActivityRule.getActivity().getPager().getCurrentItem() == mActivityRule.getActivity().getPager().getChildCount()) { checkButtonVisibilityOnPageSwipeRight(viewPagerResId, btnResId, btnVisibility); checkButtonVisibilityOnPageSwipeLeft(viewPagerResId, btnResId, btnVisibility); } else { checkButtonVisibilityOnPageSwipeLeft(viewPagerResId, btnResId, btnVisibility); checkButtonVisibilityOnPageSwipeRight(viewPagerResId, btnResId, btnVisibility); } } private void checkButtonVisibilityOnPageSwipeLeft(int viewPagerResId, int btnResId, Visibility btnVisibility) { onView(withId(viewPagerResId)).perform(swipeLeft()); checkButtonVisibility(btnResId, btnVisibility); } private void checkButtonVisibilityOnPageSwipeRight(int viewPagerResId, int btnResId, Visibility btnVisibility) { onView(withId(viewPagerResId)).perform(swipeRight()); checkButtonVisibility(btnResId, btnVisibility); } private void checkButtonVisibilityOnRotation(int btnResId, Visibility btnVisibility) { checkButtonVisibility(btnResId, btnVisibility); // check visibility state maintained between rotation onView(isRoot()).perform(orientationLandscape()); checkButtonVisibility(btnResId, btnVisibility); onView(isRoot()).perform(orientationPortrait()); checkButtonVisibility(btnResId, btnVisibility); } private void checkButtonVisibility(int btnResId, Visibility btnVisibility) { onView(withId(btnResId)).check(matches(withEffectiveVisibility(btnVisibility))); } } <|start_filename|>example/src/main/java/com/github/paolorotolo/appintroexample/animations/BaseAppIntro.java<|end_filename|> package com.github.paolorotolo.appintroexample.animations; import android.view.Menu; import android.view.MenuItem; import com.github.paolorotolo.appintro.AppIntro; import com.github.paolorotolo.appintroexample.R; /** * Created by julio on 20/10/15. */ public abstract class BaseAppIntro extends AppIntro { private int mScrollDurationFactor = 1; @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_base_intro, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()){ case R.id.action_factor1: mScrollDurationFactor = 1; break; case R.id.action_factor2: mScrollDurationFactor = 2; break; case R.id.action_factor4: mScrollDurationFactor = 4; break; case R.id.action_factor6: mScrollDurationFactor = 6; break; } setScrollDurationFactor(mScrollDurationFactor); return super.onOptionsItemSelected(item); } } <|start_filename|>library/src/main/java/com/github/paolorotolo/appintro/AppIntroFragment.java<|end_filename|> package com.github.paolorotolo.appintro; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.content.ContextCompat; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; public class AppIntroFragment extends Fragment { private static final String ARG_TITLE = "title"; private static final String ARG_DESC = "desc"; private static final String ARG_DRAWABLE = "drawable"; private static final String ARG_BG_COLOR = "bg_color"; private static final String ARG_TITLE_COLOR = "title_color"; private static final String ARG_DESC_COLOR = "desc_color"; public static AppIntroFragment newInstance(CharSequence title, CharSequence description, int imageDrawable, int bgColor) { return newInstance(title, description, imageDrawable, bgColor, 0, 0); } public static AppIntroFragment newInstance(CharSequence title, CharSequence description, int imageDrawable, int bgColor, int titleColor, int descColor) { AppIntroFragment sampleSlide = new AppIntroFragment(); Bundle args = new Bundle(); args.putCharSequence(ARG_TITLE, title); args.putCharSequence(ARG_DESC, description); args.putInt(ARG_DRAWABLE, imageDrawable); args.putInt(ARG_BG_COLOR, bgColor); args.putInt(ARG_TITLE_COLOR, titleColor); args.putInt(ARG_DESC_COLOR, descColor); sampleSlide.setArguments(args); return sampleSlide; } private int drawable, bgColor, titleColor, descColor; private CharSequence title, description; public AppIntroFragment() { } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null && getArguments().size() != 0) { drawable = getArguments().getInt(ARG_DRAWABLE); title = getArguments().getCharSequence(ARG_TITLE); description = getArguments().getCharSequence(ARG_DESC); bgColor = getArguments().getInt(ARG_BG_COLOR); titleColor = getArguments().containsKey(ARG_TITLE_COLOR) ? getArguments().getInt(ARG_TITLE_COLOR) : 0; descColor = getArguments().containsKey(ARG_DESC_COLOR) ? getArguments().getInt(ARG_DESC_COLOR) : 0; } } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_intro, container, false); TextView t = (TextView) v.findViewById(R.id.title); TextView d = (TextView) v.findViewById(R.id.description); ImageView i = (ImageView) v.findViewById(R.id.image); LinearLayout m = (LinearLayout) v.findViewById(R.id.main); t.setText(title); if (titleColor != 0) { t.setTextColor(titleColor); } d.setText(description); if (descColor != 0) { d.setTextColor(descColor); } i.setImageDrawable(ContextCompat.getDrawable(getActivity(), drawable)); m.setBackgroundColor(bgColor); return v; } } <|start_filename|>example/src/main/java/com/github/paolorotolo/appintroexample/animations/ZoomAnimation.java<|end_filename|> package com.github.paolorotolo.appintroexample.animations; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Toast; import com.github.paolorotolo.appintroexample.MainActivity; import com.github.paolorotolo.appintroexample.R; import com.github.paolorotolo.appintroexample.SampleSlide; /** * Created by rohit on 22/7/15. */ public class ZoomAnimation extends BaseAppIntro { @Override public void init(Bundle savedInstanceState) { addSlide(SampleSlide.newInstance(R.layout.intro)); addSlide(SampleSlide.newInstance(R.layout.intro2)); addSlide(SampleSlide.newInstance(R.layout.intro3)); addSlide(SampleSlide.newInstance(R.layout.intro4)); setZoomAnimation(); } private void loadMainActivity(){ Intent intent = new Intent(this, MainActivity.class); startActivity(intent); } @Override public void onSkipPressed() { loadMainActivity(); Toast.makeText(getApplicationContext(), getString(R.string.skip), Toast.LENGTH_SHORT).show(); } @Override public void onNextPressed() { } @Override public void onDonePressed() { loadMainActivity(); } @Override public void onSlideChanged() { } public void getStarted(View v){ loadMainActivity(); } } <|start_filename|>example/src/main/java/com/github/paolorotolo/appintroexample/IntroWithBackground.java<|end_filename|> package com.github.paolorotolo.appintroexample; import android.content.Intent; import android.graphics.Color; import android.os.Bundle; import android.text.Html; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.ImageView; import com.github.paolorotolo.appintro.AppIntro2; import com.github.paolorotolo.appintro.AppIntroFragment; public class IntroWithBackground extends AppIntro2 { @Override public void init(Bundle savedInstanceState) { addSlide(AppIntroFragment.newInstance("Title here", "Description here...\nYeah, I've added this fragment programmatically", R.drawable.ic_slide1, Color.TRANSPARENT)); addSlide(AppIntroFragment.newInstance("HTML Description", Html.fromHtml("<b>Description bold...</b><br><i>Description italic...</i>"), R.drawable.ic_slide1, Color.TRANSPARENT)); ImageView imageView = new ImageView(this); imageView.setImageResource(android.R.drawable.ic_dialog_email); imageView.setBackgroundColor(Color.BLACK); imageView.setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); setBackgroundView(imageView); setVibrate(true); setVibrateIntensity(30); } private void loadMainActivity(){ Intent intent = new Intent(this, MainActivity.class); startActivity(intent); } @Override public void onNextPressed() { } @Override public void onDonePressed() { loadMainActivity(); } @Override public void onSlideChanged() { } public void getStarted(View v){ loadMainActivity(); } } <|start_filename|>example/src/main/java/com/github/paolorotolo/appintroexample/DisableSwipeIntro1.java<|end_filename|> package com.github.paolorotolo.appintroexample; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Toast; import com.github.paolorotolo.appintro.AppIntro; import com.github.paolorotolo.appintro.AppIntroViewPager; public class DisableSwipeIntro1 extends AppIntro { @Override public void init(Bundle savedInstanceState) { addSlide(SampleSlide.newInstance(R.layout.intro_disable)); addSlide(SampleSlide.newInstance(R.layout.intro2_disable)); addSlide(SampleSlide.newInstance(R.layout.intro3_disable)); } private void loadMainActivity(){ Intent intent = new Intent(this, MainActivity.class); startActivity(intent); } @Override public void onSkipPressed() { loadMainActivity(); Toast.makeText(getApplicationContext(),getString(R.string.skip),Toast.LENGTH_SHORT).show(); } @Override public void onNextPressed() { } @Override public void onDonePressed() { loadMainActivity(); } @Override public void onSlideChanged() { } public void getStarted(View v){ loadMainActivity(); } public void toggleNextPageSwipeLock(View v) { AppIntroViewPager pager = getPager(); boolean pagingState = pager.isNextPagingEnabled(); setNextPageSwipeLock(pagingState); } public void toggleSwipeLock(View v) { AppIntroViewPager pager = getPager(); boolean pagingState = pager.isPagingEnabled(); setSwipeLock(pagingState); } public void toggleProgressButton(View v) { boolean progressButtonState = isProgressButtonEnabled(); progressButtonState = !progressButtonState; setProgressButtonEnabled(progressButtonState); } public void toggleSkipButton(View v) { boolean skipButtonState = isSkipButtonEnabled(); skipButtonState = !skipButtonState; showSkipButton(skipButtonState); } }
NovaInteracao/AppIntro
<|start_filename|>src/main/java/com/github/rutledgepaulv/qbuilders/nodes/ComparisonNode.java<|end_filename|> /* * * * com.github.rutledgepaulv.qbuilders.nodes.ComparisonNode * * * * * * Copyright (C) 2016 <NAME> <<EMAIL>> * * * * * * This software may be modified and distributed under the terms * * * of the MIT license. See the LICENSE file for details. * * * */ package com.github.rutledgepaulv.qbuilders.nodes; import com.github.rutledgepaulv.qbuilders.operators.ComparisonOperator; import com.github.rutledgepaulv.qbuilders.structures.FieldPath; import java.util.Collection; public final class ComparisonNode extends AbstractNode { private FieldPath path; private ComparisonOperator operator; private Collection<?> values; public ComparisonNode(LogicalNode parent) { super(parent); } public FieldPath getField() { return path; } public void setField(FieldPath field) { this.path = field; } public ComparisonOperator getOperator() { return operator; } public void setOperator(ComparisonOperator operator) { this.operator = operator; } public Collection<?> getValues() { return values; } public void setValues(Collection<?> values) { this.values = values; } } <|start_filename|>src/main/java/com/github/rutledgepaulv/qbuilders/structures/FieldPath.java<|end_filename|> /* * * * com.github.rutledgepaulv.qbuilders.structures.FieldPath * * * * * * Copyright (C) 2016 <NAME> <<EMAIL>> * * * * * * This software may be modified and distributed under the terms * * * of the MIT license. See the LICENSE file for details. * * * */ package com.github.rutledgepaulv.qbuilders.structures; import org.apache.commons.lang3.StringUtils; import java.util.*; import java.util.stream.*; import static java.util.stream.Collectors.*; public class FieldPath implements Iterable<FieldPath.FieldNamespace> { private List<FieldNamespace> chain = new LinkedList<>(); public FieldPath(String raw) { chain.add(new FieldNamespace(raw)); } public FieldPath(List<FieldNamespace> namespaces) { chain.addAll(namespaces); } @Override public Iterator<FieldNamespace> iterator() { return chain.iterator(); } public Stream<FieldNamespace> stream() { return streamIter(this); } public Optional<FieldPath> getParentPath() { if (chain.size() > 1) { return Optional.of(new FieldPath(chain.subList(0, chain.size() - 1))); } else { return Optional.empty(); } } public FieldPath append(String... path) { List<FieldNamespace> chain = new LinkedList<>(); chain.addAll(this.chain); chain.addAll(Arrays.stream(path).map(FieldNamespace::new).collect(Collectors.toList())); return new FieldPath(chain); } public FieldPath append(FieldPath... path) { List<FieldNamespace> newChain = new LinkedList<>(); newChain.addAll(this.chain); newChain.addAll(Arrays.stream(path).flatMap($ -> $.chain.stream()).collect(Collectors.toList())); return new FieldPath(newChain); } public FieldPath prepend(String path) { List<FieldNamespace> chain = new LinkedList<>(); chain.add(new FieldNamespace(path)); chain.addAll(this.chain); return new FieldPath(chain); } public FieldPath prepend(FieldPath path) { List<FieldNamespace> chain = new LinkedList<>(); chain.addAll(path.chain); chain.addAll(this.chain); return new FieldPath(chain); } public String asFullyQualifiedKey() { return stream().map(Objects::toString).collect(joining(".")); } public String asFullyQualifiedPrefix() { return stream().map(Objects::toString).collect(joining(".", "", ".")); } public String asKey() { return chain.get(chain.size() - 1).toString(); } public String asPrefix() { return chain.get(chain.size() - 1).toString() + "."; } @Override public String toString() { return asFullyQualifiedKey(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof FieldPath)) { return false; } FieldPath that = (FieldPath) o; return Objects.equals(chain, that.chain); } @Override public int hashCode() { return Objects.hash(chain); } public static class FieldNamespace implements Iterable<String> { private String raw; private FieldNamespace(String raw) { this.raw = strip(raw); } @Override public Iterator<String> iterator() { return Arrays.stream(StringUtils.split(raw, ".")).iterator(); } public Stream<String> stream() { return StreamSupport.stream(spliterator(), false); } @Override public String toString() { return raw; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof FieldNamespace)) { return false; } FieldNamespace strings = (FieldNamespace) o; return Objects.equals(raw, strings.raw); } @Override public int hashCode() { return Objects.hash(raw); } } private static String strip(String value) { return StringUtils.strip(value, "."); } private static <T> Stream<T> streamIter(Iterable<T> iterable) { return StreamSupport.stream(iterable.spliterator(), false); } } <|start_filename|>src/main/java/com/github/rutledgepaulv/qbuilders/visitors/ElasticsearchVisitor.java<|end_filename|> /* * * * com.github.rutledgepaulv.qbuilders.visitors.ElasticsearchVisitor * * * * * * Copyright (C) 2016 <NAME> <<EMAIL>> * * * * * * This software may be modified and distributed under the terms * * * of the MIT license. See the LICENSE file for details. * * * */ package com.github.rutledgepaulv.qbuilders.visitors; import com.github.rutledgepaulv.qbuilders.nodes.*; import com.github.rutledgepaulv.qbuilders.operators.ComparisonOperator; import org.elasticsearch.index.query.BoolQueryBuilder; import org.elasticsearch.index.query.QueryBuilder; import java.util.Collection; import java.util.function.Function; import java.util.stream.Collectors; import static org.elasticsearch.index.query.QueryBuilders.*; @SuppressWarnings("WeakerAccess") public class ElasticsearchVisitor extends ContextualNodeVisitor<QueryBuilder, ElasticsearchVisitor.Context> { public static class Context { private boolean originatedAsNestedQuery = false; public Context(){} public Context(boolean originatedAsNestedQuery) { this.originatedAsNestedQuery = originatedAsNestedQuery; } } protected final Function<Object, Object> normalizer; public ElasticsearchVisitor() { this(Function.identity()); } public ElasticsearchVisitor(Function<Object, Object> normalizer) { this.normalizer = normalizer; } @Override protected QueryBuilder visit(AndNode node, Context context) { BoolQueryBuilder parent = boolQuery(); node.getChildren().stream().map(child -> visitAny(child, context)).forEach(parent::must); return parent; } @Override protected QueryBuilder visit(OrNode node, Context context) { BoolQueryBuilder parent = boolQuery(); node.getChildren().stream().map(child -> visitAny(child, context)).forEach(parent::should); return parent; } @Override protected QueryBuilder visit(ComparisonNode node, Context context) { ComparisonOperator operator = node.getOperator(); Collection<?> values = node.getValues().stream().map(normalizer).collect(Collectors.toList()); String field = context.originatedAsNestedQuery ? node.getField().asFullyQualifiedKey() : node.getField().asKey(); if (ComparisonOperator.EQ.equals(operator)) { return termQuery(field, single(values)); } else if (ComparisonOperator.NE.equals(operator)) { return boolQuery().mustNot(termQuery(field, single(values))); } else if (ComparisonOperator.EX.equals(operator)) { if (single(values).equals(true)) { return existsQuery(field); } else { return boolQuery().mustNot(existsQuery(field)); } } else if (ComparisonOperator.GT.equals(operator)) { return rangeQuery(field).gt(single(values)); } else if (ComparisonOperator.LT.equals(operator)) { return rangeQuery(field).lt(single(values)); } else if (ComparisonOperator.GTE.equals(operator)) { return rangeQuery(field).gte(single(values)); } else if (ComparisonOperator.LTE.equals(operator)) { return rangeQuery(field).lte(single(values)); } else if (ComparisonOperator.IN.equals(operator)) { return termsQuery(field, values); } else if (ComparisonOperator.NIN.equals(operator)) { return boolQuery().mustNot(termsQuery(field, values)); } else if (ComparisonOperator.RE.equals(operator)) { return regexpQuery(field, (String) single(values)); } else if (ComparisonOperator.SUB_CONDITION_ANY.equals(operator)) { return nestedQuery(field, condition(node, new Context(true))); } throw new UnsupportedOperationException("This visitor does not support the operator " + operator + "."); } } <|start_filename|>src/main/java/com/github/rutledgepaulv/qbuilders/delegates/virtual/Delegate.java<|end_filename|> /* * * * com.github.rutledgepaulv.qbuilders.delegates.virtual.Delegate * * * * * * Copyright (C) 2016 <NAME> <<EMAIL>> * * * * * * This software may be modified and distributed under the terms * * * of the MIT license. See the LICENSE file for details. * * * */ package com.github.rutledgepaulv.qbuilders.delegates.virtual; import com.github.rutledgepaulv.qbuilders.builders.QBuilder; public abstract class Delegate<T extends QBuilder<T>> extends QBuilder<T> { private T canonical; protected Delegate(T canonical) { this.canonical = canonical; } @Override protected final T self() { return canonical; } } <|start_filename|>src/test/java/com/github/rutledgepaulv/qbuilders/visitors/RSQLVisitorTest.java<|end_filename|> /* * * * com.github.rutledgepaulv.qbuilders.visitors.RSQLVisitorTest * * * * * * Copyright (C) 2016 <NAME> <<EMAIL>> * * * * * * This software may be modified and distributed under the terms * * * of the MIT license. See the LICENSE file for details. * * * */ package com.github.rutledgepaulv.qbuilders.visitors; import com.github.rutledgepaulv.qbuilders.conditions.Condition; import com.github.rutledgepaulv.testsupport.QBuilderTestBase; import com.github.rutledgepaulv.testsupport.QueryModel; import cz.jirutka.rsql.parser.RSQLParser; import cz.jirutka.rsql.parser.ast.AndNode; import cz.jirutka.rsql.parser.ast.ComparisonNode; import cz.jirutka.rsql.parser.ast.Node; import cz.jirutka.rsql.parser.ast.RSQLOperators; import org.junit.Test; import java.util.HashSet; import java.util.Set; import static com.github.rutledgepaulv.testsupport.QueryModel.QueryModelPredef.*; import static org.junit.Assert.assertEquals; public class RSQLVisitorTest extends QBuilderTestBase<RSQLVisitor, String, Void> { public RSQLVisitorTest() { Enum_EQ = "myEnum==\"VALUE1\""; Enum_NE = "myEnum!=\"VALUE1\""; Enum_EX = "myEnum=ex=\"true\""; Enum_DNE = "myEnum=ex=\"false\""; Enum_IN = "myEnum=in=(\"VALUE1\",\"VALUE2\",\"VALUE3\")"; Enum_NIN = "myEnum=out=(\"VALUE1\",\"VALUE2\",\"VALUE3\")"; String_EQ = "myString==\"abcdefg\""; String_NE = "myString!=\"abcdefg\""; String_LT = "myString=lt=\"abcdefg\""; String_GT = "myString=gt=\"abcdefg\""; String_EX = "myString=ex=\"true\""; String_DNE = "myString=ex=\"false\""; String_IN = "myString=in=(\"a\",\"b\",\"c\")"; String_NIN = "myString=out=(\"d\",\"e\",\"f\")"; String_LTE = "myString=le=\"abcdefg\""; String_GTE = "myString=ge=\"abcdefg\""; String_RE = "myString=re=\"(abc|def)\""; Boolean_TRUE = "myBoolean==\"true\""; Boolean_FALSE = "myBoolean==\"false\""; Boolean_EX = "myBoolean=ex=\"true\""; Boolean_DNE = "myBoolean=ex=\"false\""; Short_EQ = "myShort==\"100\""; Short_NE = "myShort!=\"100\""; Short_LT = "myShort=lt=\"100\""; Short_GT = "myShort=gt=\"100\""; Short_LTE = "myShort=le=\"100\""; Short_GTE = "myShort=ge=\"100\""; Short_EX = "myShort=ex=\"true\""; Short_DNE = "myShort=ex=\"false\""; Short_IN = "myShort=in=(\"98\",\"99\",\"100\")"; Short_NIN = "myShort=out=(\"101\",\"102\",\"103\")"; Integer_EQ = "myInteger==\"100\""; Integer_NE = "myInteger!=\"100\""; Integer_LT = "myInteger=lt=\"100\""; Integer_GT = "myInteger=gt=\"100\""; Integer_LTE = "myInteger=le=\"100\""; Integer_GTE = "myInteger=ge=\"100\""; Integer_EX = "myInteger=ex=\"true\""; Integer_DNE = "myInteger=ex=\"false\""; Integer_IN = "myInteger=in=(\"98\",\"99\",\"100\")"; Integer_NIN = "myInteger=out=(\"101\",\"102\",\"103\")"; Long_EQ = "myLong==\"100\""; Long_NE = "myLong!=\"100\""; Long_LT = "myLong=lt=\"100\""; Long_GT = "myLong=gt=\"100\""; Long_LTE = "myLong=le=\"100\""; Long_GTE = "myLong=ge=\"100\""; Long_EX = "myLong=ex=\"true\""; Long_DNE = "myLong=ex=\"false\""; Long_IN = "myLong=in=(\"98\",\"99\",\"100\")"; Long_NIN = "myLong=out=(\"101\",\"102\",\"103\")"; Float_EQ = "myFloat==\"100.0\""; Float_NE = "myFloat!=\"100.0\""; Float_LT = "myFloat=lt=\"100.0\""; Float_GT = "myFloat=gt=\"100.0\""; Float_LTE = "myFloat=le=\"100.0\""; Float_GTE = "myFloat=ge=\"100.0\""; Float_EX = "myFloat=ex=\"true\""; Float_DNE = "myFloat=ex=\"false\""; Float_IN = "myFloat=in=(\"98.0\",\"99.0\",\"100.0\")"; Float_NIN = "myFloat=out=(\"101.0\",\"102.0\",\"103.0\")"; Double_EQ = "myDouble==\"100.0\""; Double_NE = "myDouble!=\"100.0\""; Double_LT = "myDouble=lt=\"100.0\""; Double_GT = "myDouble=gt=\"100.0\""; Double_LTE = "myDouble=le=\"100.0\""; Double_GTE = "myDouble=ge=\"100.0\""; Double_EX = "myDouble=ex=\"true\""; Double_DNE = "myDouble=ex=\"false\""; Double_IN = "myDouble=in=(\"98.0\",\"99.0\",\"100.0\")"; Double_NIN = "myDouble=out=(\"101.0\",\"102.0\",\"103.0\")"; DateTime_EQ = "myDateTime==\"1970-01-01T00:00:00Z\""; DateTime_NE = "myDateTime!=\"1970-01-01T00:00:00Z\""; DateTime_LT = "myDateTime=lt=\"1971-01-01T00:00:00Z\""; DateTime_LTE = "myDateTime=le=\"1971-01-01T00:00:00Z\""; DateTime_GT = "myDateTime=gt=\"1970-01-01T00:00:00Z\""; DateTime_GTE = "myDateTime=ge=\"1970-01-01T00:00:00Z\""; DateTime_EX = "myDateTime=ex=\"true\""; DateTime_DNE = "myDateTime=ex=\"false\""; DateTime_BETWEEN = "(myDateTime=ge=\"1970-01-01T00:00:00Z\";myDateTime=le=\"1971-01-01T00:00:00Z\")"; INLINE_ANDING = "myString==\"Thing\";myLong=ex=\"false\""; INLINE_ORING = "myString==\"Thing\",myLong=ex=\"false\""; LIST_ANDING = "(myString==\"Thing\";myLong=ex=\"false\")"; LIST_ORING = "(myString==\"Thing\",myLong=ex=\"false\")"; LIST_ORING_OF_INLINE_ANDING = "((myString==\"Thing\";myLong=ex=\"false\"),(myString!=\"Cats\";myLong=gt=\"30\"))"; LIST_ANDING_OF_INLINE_ORING = "((myString==\"Thing\",myLong=ex=\"false\");(myString!=\"Cats\",myLong=gt=\"30\"))"; LIST_ANDING_OR_LIST_ORING = "((myString==\"Thing\",myLong=ex=\"false\");(myString!=\"Cats\",myLong=gt=\"30\"))," + "((myString==\"Thing\";myLong=ex=\"false\"),(myString!=\"Cats\";myLong=gt=\"30\"))"; LIST_ORING_AND_LIST_ANDING = "((myString==\"Thing\";myLong=ex=\"false\"),(myString!=\"Cats\";myLong=gt=\"30\"));" + "((myString==\"Thing\",myLong=ex=\"false\");(myString!=\"Cats\",myLong=gt=\"30\"))"; CHAINED_ORS = "myString==\"thing\",myInteger=gt=\"0\",myInteger=lt=\"5\",myLong=in=(\"0\",\"1\",\"2\")," + "myDouble=le=\"2.9\",myBoolean==\"false\",myDateTime=ex=\"false\""; CHAINED_ANDS = "myString==\"thing\";myInteger=gt=\"0\";myInteger=lt=\"5\";" + "myLong=in=(\"0\",\"1\",\"2\");myDouble=le=\"2.9\";myBoolean==\"false\";myDateTime=ex=\"false\""; CHAINED_ANDS_AND_ORS = "(((myString==\"thing\";myInteger=gt=\"0\"),myInteger=lt=\"5\",myLong=in=(\"0\",\"1\",\"2\"));" + "myDouble=le=\"2.9\";myBoolean==\"false\"),myDateTime=ex=\"false\""; CHAINED_ORS_AND_ANDS = "(((myString==\"thing\",myInteger=gt=\"0\");myInteger=lt=\"5\";" + "myLong=in=(\"0\",\"1\",\"2\")),myDouble=le=\"2.9\",myBoolean==\"false\");myDateTime=ex=\"false\""; SUB_QUERY = "mySubList=q='myString==\"Thing\";myLong=ex=\"false\"';myBoolean==\"true\""; NULL_EQUALITY = "myString=ex=\"false\""; NULL_INEQUALITY = "myString=ex=\"true\""; } @Test public void testDoubleAndSingleQuoteWithEscapeCharacterEscaping() { Condition<QueryModel> q = myString().eq("people's \\of \\the world").and().myBoolean() .isTrue().and().myListOfStrings().in("\"cats", "'demo'\"", "\"test"); compare("myString==\"people's \\\\of \\\\the world\";myBoolean==\"true\";" + "myListOfStrings=in=('\"cats',\"'demo'\\\"\",'\"test')", q); } @Test public void testWithBackslashesInValue() { String value = "'\\something \\with \\\"some\" \\backslashes'"; Condition<QueryModel> query = myString().eq(value); compare("myString==\"'\\\\something \\\\with \\\\\\\"some\\\" \\\\backslashes'\"", query); ComparisonNode node = (ComparisonNode) parse(query.query(new RSQLVisitor())); assertEquals("myString", node.getSelector()); assertEquals("==", node.getOperator().getSymbol()); assertEquals(value, node.getArguments().get(0)); } @Test public void testUsingSingleQuoteButNoDoubleQuote() { String value = "'cats'"; Condition<QueryModel> query = myString().eq(value); compare("myString==\"'cats'\"", query); ComparisonNode node = (ComparisonNode) parse(query.query(new RSQLVisitor())); assertEquals("myString", node.getSelector()); assertEquals("==", node.getOperator().getSymbol()); assertEquals(value, node.getArguments().get(0)); } @Test public void testUsingDoubleQuoteButNoSingleQuote() { String value = "\"cats\""; Condition<QueryModel> query = myString().eq(value); compare("myString=='\"cats\"'", query); ComparisonNode node = (ComparisonNode) parse(query.query(new RSQLVisitor())); assertEquals("myString", node.getSelector()); assertEquals("==", node.getOperator().getSymbol()); assertEquals(value, node.getArguments().get(0)); } @Test public void testEscapingOfBothKindsOfQuotesInSingleQueryValue() { String stringWithApostropheAndQuotation = "Paul's friend said \"Let's run off and escape together!\""; Condition<QueryModel> query = myString().eq(stringWithApostropheAndQuotation); compare("myString==\"Paul's friend said \\\"Let's run off and escape together!\\\"\"", query); ComparisonNode node = (ComparisonNode) parse(query.query(new RSQLVisitor())); assertEquals("myString", node.getSelector()); assertEquals("==", node.getOperator().getSymbol()); assertEquals(stringWithApostropheAndQuotation, node.getArguments().get(0)); } @Test public void testEscapingOfBothKindsOfQuotesInMultiQueryValue() { String val1 = "Paul said \"Okay, but only if we can take a giant peach!\""; String val2 = "'Fine.' grumbled the friend. We can take the \"giant\" peach."; Condition<QueryModel> query = myString().in(val1, val2); compare("myString=in=('Paul said \"Okay, but only if we can take a giant peach!\"'," + "\"'Fine.' grumbled the friend. We can take the \\\"giant\\\" peach.\")", query); ComparisonNode node = (ComparisonNode) parse(query.query(new RSQLVisitor())); assertEquals("myString", node.getSelector()); assertEquals("=in=", node.getOperator().getSymbol()); assertEquals(val1, node.getArguments().get(0)); assertEquals(val2, node.getArguments().get(1)); } @Test public void testEscapingOfBothKindsOfQuotesInSubqueryQueryValue() { String val1 = "\"Off to the peach we go!\" Hi ho' Hi ho' Hi ho'"; String val2 = "'Rawwwwrrrrrrrrr' I'm a dinosawr'"; Condition<QueryModel> subquery = mySubList().any(and(myString().eq(val1), myString().eq(val2))); compare("mySubList=q=\"(myString==\\\"\\\\\\\"Off to the peach we go!\\\\\\\" " + "Hi ho' Hi ho' Hi ho'\\\";myString==\\\"'Rawwwwrrrrrrrrr' I'm a dinosawr'\\\")\"", subquery); cz.jirutka.rsql.parser.ast.ComparisonNode node = ( cz.jirutka.rsql.parser.ast.ComparisonNode ) parse(subquery.query(new RSQLVisitor())); assertEquals("=q=", node.getOperator().getSymbol()); assertEquals("mySubList", node.getSelector()); AndNode and = (AndNode) parse(node.getArguments().get(0)); cz.jirutka.rsql.parser.ast.ComparisonNode left = (ComparisonNode) and.getChildren().get(0); cz.jirutka.rsql.parser.ast.ComparisonNode right = (ComparisonNode) and.getChildren().get(1); assertEquals("myString", left.getSelector()); assertEquals(val1, left.getArguments().get(0)); assertEquals("myString", right.getSelector()); assertEquals(val2, right.getArguments().get(0)); } protected Node parse(String rsql) { Set<cz.jirutka.rsql.parser.ast.ComparisonOperator> ops = new HashSet<>(); ops.addAll(RSQLOperators.defaultOperators()); ops.add(new cz.jirutka.rsql.parser.ast.ComparisonOperator("=q=", false)); ops.add(new cz.jirutka.rsql.parser.ast.ComparisonOperator("=ex=", false)); ops.add(new cz.jirutka.rsql.parser.ast.ComparisonOperator("=re=", false)); return new RSQLParser(ops).parse(rsql); } @Override protected RSQLVisitor getVisitor() { return new RSQLVisitor(); } @Override protected void compare(String expected, String converted) { // make sure it's parseable parse(converted); assertEquals(expected, converted); } } <|start_filename|>src/main/java/com/github/rutledgepaulv/qbuilders/properties/concrete/ConditionProperty.java<|end_filename|> /* * * * com.github.rutledgepaulv.qbuilders.properties.concrete.ConditionProperty * * * * * * Copyright (C) 2016 <NAME> <<EMAIL>> * * * * * * This software may be modified and distributed under the terms * * * of the MIT license. See the LICENSE file for details. * * * */ package com.github.rutledgepaulv.qbuilders.properties.concrete; import com.github.rutledgepaulv.qbuilders.builders.QBuilder; import com.github.rutledgepaulv.qbuilders.conditions.Condition; import com.github.rutledgepaulv.qbuilders.properties.virtual.Property; /** * A property view for multi-value fields containing objects who themselves * may have additional fields. * * @param <T> The type of the final builder. */ public interface ConditionProperty<T extends QBuilder<T>, S extends QBuilder<S>> extends Property<T> { /** * Mandates that at least one of the elements of the multi-valued fields must match the * provided condition exactly. * * @param condition The condition that should be imposed individually against each element * in the multi valued field. * * @return The logically complete condition. */ Condition<T> any(Condition<S> condition); } <|start_filename|>src/main/java/com/github/rutledgepaulv/qbuilders/delegates/concrete/DoublePropertyDelegate.java<|end_filename|> /* * * * com.github.rutledgepaulv.qbuilders.delegates.concrete.DoublePropertyDelegate * * * * * * Copyright (C) 2016 <NAME> <<EMAIL>> * * * * * * This software may be modified and distributed under the terms * * * of the MIT license. See the LICENSE file for details. * * * */ package com.github.rutledgepaulv.qbuilders.delegates.concrete; import com.github.rutledgepaulv.qbuilders.builders.QBuilder; import com.github.rutledgepaulv.qbuilders.delegates.virtual.NumberPropertyDelegate; import com.github.rutledgepaulv.qbuilders.properties.concrete.DoubleProperty; import com.github.rutledgepaulv.qbuilders.structures.FieldPath; public final class DoublePropertyDelegate<T extends QBuilder<T>> extends NumberPropertyDelegate<T, Double> implements DoubleProperty<T> { public DoublePropertyDelegate(FieldPath field, T canonical) { super(field, canonical); } } <|start_filename|>src/test/java/com/github/rutledgepaulv/testsupport/FieldUtil.java<|end_filename|> /* * * * com.github.rutledgepaulv.testsupport.FieldUtil * * * * * * Copyright (C) 2016 <NAME> <<EMAIL>> * * * * * * This software may be modified and distributed under the terms * * * of the MIT license. See the LICENSE file for details. * * * */ package com.github.rutledgepaulv.testsupport; import java.lang.reflect.Method; public class FieldUtil { private static Method m; static { try { m = Throwable.class.getDeclaredMethod("getStackTraceElement", int.class); m.setAccessible(true); } catch (Exception e) { e.printStackTrace(); } } public static String getMethodName(final int depth) { try { StackTraceElement element = (StackTraceElement) m.invoke(new Throwable(), depth + 1); return element.getMethodName(); } catch (Exception e) { e.printStackTrace(); return null; } } public static String getCurrentMethodName() { return getMethodName(1); } } <|start_filename|>src/main/java/com/github/rutledgepaulv/qbuilders/properties/concrete/InstantProperty.java<|end_filename|> /* * * * com.github.rutledgepaulv.qbuilders.properties.concrete.InstantProperty * * * * * * Copyright (C) 2016 <NAME> <<EMAIL>> * * * * * * This software may be modified and distributed under the terms * * * of the MIT license. See the LICENSE file for details. * * * */ package com.github.rutledgepaulv.qbuilders.properties.concrete; import com.github.rutledgepaulv.qbuilders.builders.QBuilder; import com.github.rutledgepaulv.qbuilders.properties.virtual.InstantLikeProperty; import java.time.Instant; /** * A property view for fields with {@link Instant} values. * * @param <T> The type of the final builder. */ public interface InstantProperty<T extends QBuilder<T>> extends InstantLikeProperty<T, Instant> {} <|start_filename|>src/main/java/com/github/rutledgepaulv/qbuilders/delegates/concrete/InstantPropertyDelegate.java<|end_filename|> /* * * * com.github.rutledgepaulv.qbuilders.delegates.concrete.InstantPropertyDelegate * * * * * * Copyright (C) 2016 <NAME> <<EMAIL>> * * * * * * This software may be modified and distributed under the terms * * * of the MIT license. See the LICENSE file for details. * * * */ package com.github.rutledgepaulv.qbuilders.delegates.concrete; import com.github.rutledgepaulv.qbuilders.builders.QBuilder; import com.github.rutledgepaulv.qbuilders.delegates.virtual.InstantLikePropertyDelegate; import com.github.rutledgepaulv.qbuilders.properties.concrete.InstantProperty; import com.github.rutledgepaulv.qbuilders.structures.FieldPath; import java.time.Instant; public final class InstantPropertyDelegate<T extends QBuilder<T>> extends InstantLikePropertyDelegate<T, Instant> implements InstantProperty<T> { public InstantPropertyDelegate(FieldPath field, T canonical) { super(field, canonical); } @Override protected Instant normalize(Instant instant) { return instant; } } <|start_filename|>src/main/java/com/github/rutledgepaulv/qbuilders/conditions/Condition.java<|end_filename|> /* * * * com.github.rutledgepaulv.qbuilders.conditions.Condition * * * * * * Copyright (C) 2016 <NAME> <<EMAIL>> * * * * * * This software may be modified and distributed under the terms * * * of the MIT license. See the LICENSE file for details. * * * */ package com.github.rutledgepaulv.qbuilders.conditions; import com.github.rutledgepaulv.qbuilders.builders.QBuilder; import com.github.rutledgepaulv.qbuilders.nodes.AndNode; import com.github.rutledgepaulv.qbuilders.nodes.ComparisonNode; import com.github.rutledgepaulv.qbuilders.nodes.OrNode; import com.github.rutledgepaulv.qbuilders.visitors.ContextualNodeVisitor; import java.util.List; /** * A logically complete condition that can either be met or not met by an object. * Intended to be composed into more complex conditions, or built into a query * that can be executed against a set of objects to determine those things * which satisfy the criteria. * * @param <T> The final type of the builder, used for a fluid chaining interface. */ public interface Condition<T extends QBuilder<T>> { /** * Prepare to append another condition onto the current node in the condition tree * in such a way that both the preceeding condition AND the next condition * specified must be met in order to match an object. * * If more flexibility surrounding precedence is needed than what chaining provides, * please see {@link Partial#and(List)} and {@link Partial#or(List)}. * * @return The beginnings of another condition. */ T and(); /** * Prepare to append another condition onto the current node in the condition tree * in such a way that both the preceeding condition OR the next condition * specified must be met in order to match an object. * * If more flexibility surrounding precedence is needed than what chaining provides, * please see {@link Partial#and(List)} and {@link Partial#or(List)}. * * @return The beginnings of another condition. */ T or(); /** * Given this logically complete condition, execute a node visitor against the * underlying condition tree in order to build a query or predicate against which * objects can be queried / tested. * * @param visitor The visitor which specifies how to traverse the nodes in the visitor tree. * Nodes can be {@link AndNode}s or {@link OrNode}s or {@link ComparisonNode}s. * @param <Q> The type of the results returned from visiting any node in the tree. * @return The result of the visitor's execution. */ <Q> Q query(ContextualNodeVisitor<Q, Void> visitor); /** * Given this logically complete condition, execute a node visitor against the * underlying condition tree in order to build a query or predicate against which * objects can be queried / tested. * * @param visitor The visitor which specifies how to traverse the nodes in the visitor tree. * Nodes can be {@link AndNode}s or {@link OrNode}s or {@link ComparisonNode}s. * @param <Q> The type of the results returned from visiting any node in the tree. * @return The result of the visitor's execution. */ <Q, S> Q query(ContextualNodeVisitor<Q, S> visitor, S context); } <|start_filename|>src/main/java/com/github/rutledgepaulv/qbuilders/properties/concrete/BooleanProperty.java<|end_filename|> /* * * * com.github.rutledgepaulv.qbuilders.properties.concrete.BooleanProperty * * * * * * Copyright (C) 2016 <NAME> <<EMAIL>> * * * * * * This software may be modified and distributed under the terms * * * of the MIT license. See the LICENSE file for details. * * * */ package com.github.rutledgepaulv.qbuilders.properties.concrete; import com.github.rutledgepaulv.qbuilders.builders.QBuilder; import com.github.rutledgepaulv.qbuilders.conditions.Condition; import com.github.rutledgepaulv.qbuilders.properties.virtual.ExistentialProperty; /** * A property view for fields with {@link Boolean} values. * * @param <T> The type of the final builder. */ public interface BooleanProperty<T extends QBuilder<T>> extends ExistentialProperty<T> { /** * Mandates that the boolean field must be true to match the query. * @return The logically complete condition. */ Condition<T> isTrue(); /** * Mandates that the boolean field must be false to match the query. * @return The logically complete condition. */ Condition<T> isFalse(); } <|start_filename|>src/main/java/com/github/rutledgepaulv/qbuilders/delegates/concrete/BooleanPropertyDelegate.java<|end_filename|> /* * * * com.github.rutledgepaulv.qbuilders.delegates.concrete.BooleanPropertyDelegate * * * * * * Copyright (C) 2016 <NAME> <<EMAIL>> * * * * * * This software may be modified and distributed under the terms * * * of the MIT license. See the LICENSE file for details. * * * */ package com.github.rutledgepaulv.qbuilders.delegates.concrete; import com.github.rutledgepaulv.qbuilders.builders.QBuilder; import com.github.rutledgepaulv.qbuilders.conditions.Condition; import com.github.rutledgepaulv.qbuilders.delegates.virtual.ExistentialPropertyDelegate; import com.github.rutledgepaulv.qbuilders.operators.ComparisonOperator; import com.github.rutledgepaulv.qbuilders.properties.concrete.BooleanProperty; import com.github.rutledgepaulv.qbuilders.structures.FieldPath; import java.util.Collections; public final class BooleanPropertyDelegate<T extends QBuilder<T>> extends ExistentialPropertyDelegate<T> implements BooleanProperty<T> { public BooleanPropertyDelegate(FieldPath field, T canonical) { super(field, canonical); } public final Condition<T> isTrue() { return condition(getField(), ComparisonOperator.EQ, Collections.singletonList(true)); } public final Condition<T> isFalse() { return condition(getField(), ComparisonOperator.EQ, Collections.singletonList(false)); } } <|start_filename|>src/test/java/com/github/rutledgepaulv/testsupport/DomainModel.java<|end_filename|> /* * * * com.github.rutledgepaulv.testsupport.DomainModel * * * * * * Copyright (C) 2016 <NAME> <<EMAIL>> * * * * * * This software may be modified and distributed under the terms * * * of the MIT license. See the LICENSE file for details. * * * */ package com.github.rutledgepaulv.testsupport; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; public class DomainModel { public enum MyEnum { VALUE1, VALUE2, VALUE3 } private MyEnum myEnum; private Byte myByte; private Float myFloat; private Double myDouble; private Long myLong; private Integer myInteger; private Short myShort; private String myString; private String myString2; private Character myCharacter; private List<DomainModel> mySubList = new ArrayList<>(); private List<String> myListOfStrings = new ArrayList<>(); public Byte getMyByte() { return myByte; } public void setMyByte(Byte myByte) { this.myByte = myByte; } public Float getMyFloat() { return myFloat; } public void setMyFloat(Float myFloat) { this.myFloat = myFloat; } public Double getMyDouble() { return myDouble; } public void setMyDouble(Double myDouble) { this.myDouble = myDouble; } public Long getMyLong() { return myLong; } public void setMyLong(Long myLong) { this.myLong = myLong; } public Integer getMyInteger() { return myInteger; } public void setMyInteger(Integer myInteger) { this.myInteger = myInteger; } public Short getMyShort() { return myShort; } public void setMyShort(Short myShort) { this.myShort = myShort; } public String getMyString() { return myString; } public void setMyString(String myString) { this.myString = myString; } public Character getMyCharacter() { return myCharacter; } public void setMyCharacter(Character myCharacter) { this.myCharacter = myCharacter; } public List<String> getMyListOfStrings() { return myListOfStrings; } public void setMyListOfStrings(List<String> myListOfStrings) { this.myListOfStrings = myListOfStrings; } public MyEnum getMyEnum() { return myEnum; } public void setMyEnum(MyEnum myEnum) { this.myEnum = myEnum; } public String getMyString2() { return myString2; } public void setMyString2(String myString2) { this.myString2 = myString2; } public List<DomainModel> getMySubList() { return mySubList; } public void setMySubList(List<DomainModel> mySubList) { this.mySubList = mySubList; } public DomainModel copy() { DomainModel domainModel = new DomainModel(); domainModel.setMyEnum(getMyEnum()); domainModel.setMyByte(getMyByte()); domainModel.setMyCharacter(getMyCharacter()); domainModel.setMyDouble(getMyDouble()); domainModel.setMyFloat(getMyFloat()); domainModel.setMyInteger(getMyInteger()); domainModel.setMyListOfStrings(getMyListOfStrings().stream().collect(Collectors.toList())); domainModel.setMyLong(getMyLong()); domainModel.setMyShort(getMyShort()); domainModel.setMyString(getMyString()); domainModel.setMyString2(getMyString2()); domainModel.setMySubList(getMySubList().stream().map(DomainModel::copy).collect(Collectors.toList())); return domainModel; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } DomainModel domainModel = (DomainModel) o; return Objects.equals(myByte, domainModel.myByte) && Objects.equals(myFloat, domainModel.myFloat) && Objects.equals(myDouble, domainModel.myDouble) && Objects.equals(myLong, domainModel.myLong) && Objects.equals(myInteger, domainModel.myInteger) && Objects.equals(myShort, domainModel.myShort) && Objects.equals(myString, domainModel.myString) && Objects.equals(myString2, domainModel.myString2) && Objects.equals(myCharacter, domainModel.myCharacter) && Objects.equals(mySubList, domainModel.mySubList) && Objects.equals(myEnum, domainModel.myEnum) && Objects.equals(myListOfStrings, domainModel.myListOfStrings); } @Override public int hashCode() { return Objects.hash(myByte, myFloat, myDouble, myEnum, myLong, myInteger, myShort, myString, myString2, myCharacter, mySubList, myListOfStrings); } } <|start_filename|>src/main/java/com/github/rutledgepaulv/qbuilders/visitors/RSQLVisitor.java<|end_filename|> /* * * * com.github.rutledgepaulv.qbuilders.visitors.RSQLVisitor * * * * * * Copyright (C) 2016 <NAME> <<EMAIL>> * * * * * * This software may be modified and distributed under the terms * * * of the MIT license. See the LICENSE file for details. * * * */ package com.github.rutledgepaulv.qbuilders.visitors; import com.github.rutledgepaulv.qbuilders.nodes.AbstractNode; import com.github.rutledgepaulv.qbuilders.nodes.AndNode; import com.github.rutledgepaulv.qbuilders.nodes.ComparisonNode; import com.github.rutledgepaulv.qbuilders.nodes.OrNode; import com.github.rutledgepaulv.qbuilders.operators.ComparisonOperator; import java.util.Objects; import java.util.function.Function; import static java.util.stream.Collectors.joining; @SuppressWarnings("WeakerAccess") public class RSQLVisitor extends AbstractVoidContextNodeVisitor<String> { private final Function<Object, String> serializer; public RSQLVisitor() { this(DefaultSerializationStrategy.INSTANCE); } public RSQLVisitor(Function<Object, String> serializationStrategy) { this.serializer = serializationStrategy; } @Override protected String visit(AndNode node) { String body = node.getChildren().stream().map(this::visitAny).collect(joining(";")); return nodeBelongsToParentExpression(node) ? "(" + body + ")" : body; } @Override protected String visit(OrNode node) { String body = node.getChildren().stream().map(this::visitAny).collect(joining(",")); return nodeBelongsToParentExpression(node) ? "(" + body + ")" : body; } @Override protected String visit(ComparisonNode node) { ComparisonOperator operator = node.getOperator(); if(ComparisonOperator.EQ.equals(operator)) { return single(node, "=="); } else if(ComparisonOperator.NE.equals(operator)) { return single(node, "!="); } else if (ComparisonOperator.EX.equals(operator)) { return single(node, "=ex="); } else if (ComparisonOperator.GT.equals(operator)) { return single(node, "=gt="); } else if (ComparisonOperator.LT.equals(operator)) { return single(node, "=lt="); } else if (ComparisonOperator.GTE.equals(operator)) { return single(node, "=ge="); } else if (ComparisonOperator.LTE.equals(operator)) { return single(node, "=le="); } else if (ComparisonOperator.IN.equals(operator)) { return list(node, "=in="); } else if (ComparisonOperator.NIN.equals(operator)) { return list(node, "=out="); } else if (ComparisonOperator.RE.equals(operator)) { return single(node, "=re="); } else if (ComparisonOperator.SUB_CONDITION_ANY.equals(operator)) { return node.getField().asKey() + "=q=" + serialize(condition(node)); } throw new UnsupportedOperationException("This visitor does not support the operator " + operator + "."); } protected boolean nodeBelongsToParentExpression(AbstractNode node) { return node.getParent() != null; } protected String single(ComparisonNode node, String op) { return node.getField().asKey() + op + serialize(single(node.getValues())); } protected String list(ComparisonNode node, String op) { return node.getField().asKey() + op + node.getValues().stream() .map(this::serialize).collect(joining(",", "(", ")")); } protected String serialize(Object value) { return this.serializer.apply(value); } protected static class DefaultSerializationStrategy implements Function<Object ,String> { protected final static DefaultSerializationStrategy INSTANCE = new DefaultSerializationStrategy(); private static final CharSequence DOUBLE_QUOTE = "\""; private static final CharSequence SINGLE_QUOTE = "\'"; @Override public String apply(Object value) { String string = Objects.toString(value); if(string.contains("\\")) { string = string.replaceAll("\\\\","\\\\\\\\"); } boolean containsDoubleQuotes = string.contains("\""); boolean containsSingleQuotes = string.contains("'"); if(!containsDoubleQuotes) { return DOUBLE_QUOTE + string + DOUBLE_QUOTE; } else if (!containsSingleQuotes) { return SINGLE_QUOTE + string + SINGLE_QUOTE; } else { string = string.replaceAll("\"", "\\\\\""); return DOUBLE_QUOTE + string + DOUBLE_QUOTE; } } } } <|start_filename|>src/main/java/com/github/rutledgepaulv/qbuilders/properties/virtual/InstantLikeProperty.java<|end_filename|> /* * * * com.github.rutledgepaulv.qbuilders.properties.virtual.InstantLikeProperty * * * * * * Copyright (C) 2016 <NAME> <<EMAIL>> * * * * * * This software may be modified and distributed under the terms * * * of the MIT license. See the LICENSE file for details. * * * */ package com.github.rutledgepaulv.qbuilders.properties.virtual; import com.github.rutledgepaulv.qbuilders.builders.QBuilder; import com.github.rutledgepaulv.qbuilders.conditions.Condition; /** * For date-like properties * * @param <T> The final type of the builder. * @param <S> The type of the date that the property supports. */ public interface InstantLikeProperty<T extends QBuilder<T>, S> extends EquitableProperty<T, S> { /** * Mandates that the date-like field must be before the provided date * * @param dateTime The date-like representation that it should occur before. * @param exclusive True if the query should not match the provided date, false if it should. * @return The logically complete condition. */ Condition<T> before(S dateTime, boolean exclusive); /** * Mandates that the date-like field must be after the provided date * * @param dateTime The date-like representation that it should occur after. * @param exclusive True if the query should not match the provided date, false if it should. * @return The logically complete condition. */ Condition<T> after(S dateTime, boolean exclusive); /** * Mandates that the date-like field must be within the provided range. * * @param after The date-like representation that it should occur after. * @param exclusiveAfter True if the query should not match the provided date, false if it should. * @param before The date-like representation that it should occur before. * @param exclusiveBefore True if the query should not match the provided date, false if it should. * @return The logically complete condition. */ Condition<T> between(S after, boolean exclusiveAfter, S before, boolean exclusiveBefore); } <|start_filename|>src/main/java/com/github/rutledgepaulv/qbuilders/properties/concrete/StringProperty.java<|end_filename|> /* * * * com.github.rutledgepaulv.qbuilders.properties.concrete.StringProperty * * * * * * Copyright (C) 2016 <NAME> <<EMAIL>> * * * * * * This software may be modified and distributed under the terms * * * of the MIT license. See the LICENSE file for details. * * * */ package com.github.rutledgepaulv.qbuilders.properties.concrete; import com.github.rutledgepaulv.qbuilders.builders.QBuilder; import com.github.rutledgepaulv.qbuilders.conditions.Condition; import com.github.rutledgepaulv.qbuilders.properties.virtual.EquitableProperty; import com.github.rutledgepaulv.qbuilders.properties.virtual.ListableProperty; /** * A property view for fields with {@link String} values. * * @param <T> The type of the final builder. */ public interface StringProperty<T extends QBuilder<T>> extends EquitableProperty<T, String>, ListableProperty<T, String> { /** * Mandates that the value of the field must occur after the provided value * when sorted lexicographically. * * @param value The string that the value must occur after. * @return The logically complete condition. */ Condition<T> lexicallyAfter(String value); /** * Mandates that the value of the field must occur before the provided value * when sorted lexicographically. * * @param value The string that the value must occur before. * @return The logically complete condition. */ Condition<T> lexicallyBefore(String value); /** * Mandates that the value of the field must be equal to or occur before the provided value * when sorted lexicographically. * * @param value The string that the value must occur before or be equal to. * @return The logically complete condition. */ Condition<T> lexicallyNotAfter(String value); /** * Mandates that the value of the field must be equal to or occur after the provided value * when sorted lexicographically. * * @param value The string that the value must occur after or be equal to. * @return The logically complete condition. */ Condition<T> lexicallyNotBefore(String value); /** * Mandates that the value of the field must match the regular expression provided * in the form of a string pattern. The particular regex implementation is determined * by the backend visitor that is used. No normalization is done in order to ensure * that the regex string works across each backend the same way, so you'll need to take * care to use the right pattern against the right backend. * * @param pattern The regular expression to used, expressed as a string in the format expected * by whichever backend visitor you plan to use to build the query. * @return The logically complete condition. */ Condition<T> pattern(String pattern); } <|start_filename|>src/main/java/com/github/rutledgepaulv/qbuilders/nodes/AndNode.java<|end_filename|> /* * * * com.github.rutledgepaulv.qbuilders.nodes.AndNode * * * * * * Copyright (C) 2016 <NAME> <<EMAIL>> * * * * * * This software may be modified and distributed under the terms * * * of the MIT license. See the LICENSE file for details. * * * */ package com.github.rutledgepaulv.qbuilders.nodes; import java.util.List; public final class AndNode extends LogicalNode { public AndNode() {} public AndNode(LogicalNode parent) { super(parent); } public AndNode(LogicalNode parent, List<AbstractNode> children) { super(parent, children); } } <|start_filename|>src/main/java/com/github/rutledgepaulv/qbuilders/conditions/Partial.java<|end_filename|> /* * * * com.github.rutledgepaulv.qbuilders.conditions.Partial * * * * * * Copyright (C) 2016 <NAME> <<EMAIL>> * * * * * * This software may be modified and distributed under the terms * * * of the MIT license. See the LICENSE file for details. * * * */ package com.github.rutledgepaulv.qbuilders.conditions; import com.github.rutledgepaulv.qbuilders.builders.QBuilder; import com.github.rutledgepaulv.qbuilders.properties.concrete.*; import java.util.List; /** * Represents the starting point of a logical condition. It can be brought to * completion by specifying a field and specifying a constraint against that field, * or by logically composing conditions into a new logically complete condition. * * @param <T> The final type of the builder, used for a fluid chaining interface. */ public interface Partial<T extends QBuilder<T>> { /** * For usage when the field is known to contain values of an enum type. * * @param field The name of the field. * * @return The property interface so that a constraint can be set against the field. */ <S extends Enum<S>> EnumProperty<T,S> enumeration(String field); /** * For usage when the field is known to contain values of a boolean type. * * @param field The name of the field. * * @return The property interface so that a constraint can be set against the field. */ BooleanProperty<T> bool(String field); /** * For usage when the field is known to contain values of a string type. * * @param field The name of the field. * * @return The property interface so that a constraint can be set against the field. */ StringProperty<T> string(String field); /** * For usage when the field is known to contain values of a long type. * * @param field The name of the field. * * @return The property interface so that a constraint can be set against the field. */ LongProperty<T> longNum(String field); /** * For usage when the field is known to contain values of an integer type. * * @param field The name of the field. * * @return The property interface so that a constraint can be set against the field. */ IntegerProperty<T> intNum(String field); /** * For usage when the field is known to contain values of a numerical short type. * * @param field The name of the field. * * @return The property interface so that a constraint can be set against the field. */ ShortProperty<T> shortNum(String field); /** * For usage when the field is known to contain values of a numerical float type. * * @param field The name of the field. * * @return The property interface so that a constraint can be set against the field. */ FloatProperty<T> floatNum(String field); /** * For usage when the field is known to contain values of a numerical double type. * * @param field The name of the field. * * @return The property interface so that a constraint can be set against the field. */ DoubleProperty<T> doubleNum(String field); /** * For usage when the field is known to contain values of a point-in-time type. * * @param field The name of the field. * * @return The property interface so that a constraint can be set against the field. */ InstantProperty<T> instant(String field); /** * For usage when the field is a multivalued field of objects who themselves can * be tested against a condition. * * @param field The name of the multivalued field. * @param <S> The kind of the subquery condition.. * * @return The property interface so that a condition constraint can be set against the field. */ <S extends QBuilder<S>> ConditionProperty<T,S> condition(String field); /** * Allows for composing a list of conditions in a "any match" fashion. * * @param conditions The list of conditions to combine. * * @return The logical condition that represents the composition of the list. */ Condition<T> or(List<Condition<T>> conditions); /** * Allows for composing a list of conditions in a "all match" fashion. * * @param conditions The list of conditions to combine. * * @return The logical condition that represents the composition of the list. */ Condition<T> and(List<Condition<T>> conditions); /** * Allows for composing a list of conditions in a "any match" fashion. * * @param c1 The first condition to combine. * @param c2 The second condition to combine. * @param cn Any other conditions to combine. * * @return The logical condition that represents the composition of the list. */ Condition<T> or(Condition<T> c1, Condition<T> c2, Condition<T>... cn); /** * Allows for composing a list of conditions in a "all match" fashion. * * @param c1 The first condition to combine. * @param c2 The second condition to combine. * @param cn Any other conditions to combine. * * @return The logical condition that represents the composition of the list. */ Condition<T> and(Condition<T> c1, Condition<T> c2, Condition<T>... cn); } <|start_filename|>src/main/java/com/github/rutledgepaulv/qbuilders/nodes/AbstractNode.java<|end_filename|> /* * * * com.github.rutledgepaulv.qbuilders.nodes.AbstractNode * * * * * * Copyright (C) 2016 <NAME> <<EMAIL>> * * * * * * This software may be modified and distributed under the terms * * * of the MIT license. See the LICENSE file for details. * * * */ package com.github.rutledgepaulv.qbuilders.nodes; import com.github.rutledgepaulv.qbuilders.visitors.ContextualNodeVisitor; public abstract class AbstractNode implements Visitable { private LogicalNode parent; public AbstractNode() {} public AbstractNode(LogicalNode parent) { this.parent = parent; } public LogicalNode getParent() { return parent; } public void setParent(LogicalNode parent) { this.parent = parent; } @Override public <T, S> T visit(ContextualNodeVisitor<T, S> visitor, S context) { return visitor.visitAny(this, context); } } <|start_filename|>src/main/java/com/github/rutledgepaulv/qbuilders/delegates/virtual/InstantLikePropertyDelegate.java<|end_filename|> /* * * * com.github.rutledgepaulv.qbuilders.delegates.virtual.InstantLikePropertyDelegate * * * * * * Copyright (C) 2016 <NAME> <<EMAIL>> * * * * * * This software may be modified and distributed under the terms * * * of the MIT license. See the LICENSE file for details. * * * */ package com.github.rutledgepaulv.qbuilders.delegates.virtual; import com.github.rutledgepaulv.qbuilders.builders.QBuilder; import com.github.rutledgepaulv.qbuilders.conditions.Condition; import com.github.rutledgepaulv.qbuilders.operators.ComparisonOperator; import com.github.rutledgepaulv.qbuilders.properties.virtual.InstantLikeProperty; import com.github.rutledgepaulv.qbuilders.structures.FieldPath; import java.time.Instant; import java.util.Collections; @SuppressWarnings("unchecked") public abstract class InstantLikePropertyDelegate<T extends QBuilder<T>, S> extends EquitablePropertyDelegate<T, S> implements InstantLikeProperty<T, S> { public InstantLikePropertyDelegate(FieldPath field, T canonical) { super(field, canonical); } @Override public final Condition<T> before(S dateTime, boolean exclusive) { return condition(getField(), exclusive ? ComparisonOperator.LT : ComparisonOperator.LTE, Collections.singletonList(normalize(dateTime))); } @Override public final Condition<T> after(S dateTime, boolean exclusive) { return condition(getField(), exclusive ? ComparisonOperator.GT : ComparisonOperator.GTE, Collections.singletonList(normalize(dateTime))); } @Override public final Condition<T> between(S after, boolean exclusiveAfter, S before, boolean exclusiveBefore) { Condition<T> afterCondition = new QBuilder().instant(getField().asKey()).after(after, exclusiveAfter); Condition<T> beforeCondition = new QBuilder().instant(getField().asKey()).before(before, exclusiveBefore); return and(afterCondition, beforeCondition); } protected abstract Instant normalize(S dateTime); } <|start_filename|>src/test/java/com/github/rutledgepaulv/qbuilders/visitors/DemonstrateCustomVisitor.java<|end_filename|> /* * * * com.github.rutledgepaulv.qbuilders.visitors.DemonstrateCustomVisitor * * * * * * Copyright (C) 2016 <NAME> <<EMAIL>> * * * * * * This software may be modified and distributed under the terms * * * of the MIT license. See the LICENSE file for details. * * * */ package com.github.rutledgepaulv.qbuilders.visitors; import com.github.rutledgepaulv.qbuilders.builders.QBuilder; import com.github.rutledgepaulv.qbuilders.conditions.Condition; import com.github.rutledgepaulv.qbuilders.nodes.ComparisonNode; import com.github.rutledgepaulv.qbuilders.structures.FieldPath; import org.elasticsearch.index.query.QueryBuilder; import org.junit.Test; import static org.junit.Assert.assertEquals; public class DemonstrateCustomVisitor { public static class DemonstrateTypeThing extends QBuilder<DemonstrateTypeThing> { } public static class VariableFieldElasticsearchVisitor extends ElasticsearchVisitor { @Override protected QueryBuilder visit(ComparisonNode node, Context context) { if ("value".equals(node.getField().asKey())) { node.setField(new FieldPath(node.getField().asKey() + "_" + determineSuffix(single(node.getValues())))); } return super.visit(node, context); } private String determineSuffix(Object value) { if (value instanceof Number) { return "number"; } else if (value instanceof String) { return "text"; } else if (value instanceof Boolean) { return "bool"; } return ""; } } @Test public void test() { Condition<DemonstrateTypeThing> numQuery = new DemonstrateTypeThing().intNum("value").eq(2); Condition<DemonstrateTypeThing> textQuery = new DemonstrateTypeThing().string("value").eq("dadad"); Condition<DemonstrateTypeThing> boolQuery = new DemonstrateTypeThing().bool("value").isTrue(); assertEquals("{\n" + " \"term\" : {\n" + " \"value_number\" : 2\n" + " }\n" + "}", numQuery.query(new VariableFieldElasticsearchVisitor(), new ElasticsearchVisitor.Context()).toString()); assertEquals("{\n" + " \"term\" : {\n" + " \"value_text\" : \"dadad\"\n" + " }\n" + "}", textQuery.query(new VariableFieldElasticsearchVisitor(), new ElasticsearchVisitor.Context()).toString()); assertEquals("{\n" + " \"term\" : {\n" + " \"value_bool\" : true\n" + " }\n" + "}", boolQuery.query(new VariableFieldElasticsearchVisitor(), new ElasticsearchVisitor.Context()).toString()); } } <|start_filename|>src/main/java/com/github/rutledgepaulv/qbuilders/delegates/concrete/EnumPropertyDelegate.java<|end_filename|> /* * * * com.github.rutledgepaulv.qbuilders.delegates.concrete.EnumPropertyDelegate * * * * * * Copyright (C) 2016 <NAME> <<EMAIL>> * * * * * * This software may be modified and distributed under the terms * * * of the MIT license. See the LICENSE file for details. * * * */ package com.github.rutledgepaulv.qbuilders.delegates.concrete; import com.github.rutledgepaulv.qbuilders.builders.QBuilder; import com.github.rutledgepaulv.qbuilders.delegates.virtual.ListablePropertyDelegate; import com.github.rutledgepaulv.qbuilders.properties.concrete.EnumProperty; import com.github.rutledgepaulv.qbuilders.structures.FieldPath; public final class EnumPropertyDelegate<T extends QBuilder<T>, S extends Enum<S>> extends ListablePropertyDelegate<T,S> implements EnumProperty<T,S> { public EnumPropertyDelegate(FieldPath field, T canonical) { super(field, canonical); } } <|start_filename|>src/test/java/com/github/rutledgepaulv/qbuilders/visitors/MongoVisitorTest.java<|end_filename|> /* * * * com.github.rutledgepaulv.qbuilders.visitors.MongoVisitorTest * * * * * * Copyright (C) 2016 <NAME> <<EMAIL>> * * * * * * This software may be modified and distributed under the terms * * * of the MIT license. See the LICENSE file for details. * * * */ package com.github.rutledgepaulv.qbuilders.visitors; import com.github.rutledgepaulv.testsupport.CriteriaSerializer; import com.github.rutledgepaulv.testsupport.QBuilderTestBase; import org.springframework.data.mongodb.core.query.Criteria; import static org.junit.Assert.assertEquals; public class MongoVisitorTest extends QBuilderTestBase<MongoVisitor, Criteria, Void> { public MongoVisitorTest() { Enum_EQ = "{ \"myEnum\" : \"VALUE1\"}"; Enum_NE = "{ \"myEnum\" : { \"$ne\" : \"VALUE1\"}}"; Enum_EX = "{ \"myEnum\" : { \"$exists\" : true}}"; Enum_DNE = "{ \"myEnum\" : { \"$exists\" : false}}"; Enum_IN = "{ \"myEnum\" : { \"$in\" : [ \"VALUE1\" , \"VALUE2\" , \"VALUE3\"]}}"; Enum_NIN = "{ \"myEnum\" : { \"$nin\" : [ \"VALUE1\" , \"VALUE2\" , \"VALUE3\"]}}"; String_EQ = "{ \"myString\" : \"abcdefg\"}"; String_NE = "{ \"myString\" : { \"$ne\" : \"abcdefg\"}}"; String_LT = "{ \"myString\" : { \"$lt\" : \"abcdefg\"}}"; String_GTE = "{ \"myString\" : { \"$gte\" : \"abcdefg\"}}"; String_GT = "{ \"myString\" : { \"$gt\" : \"abcdefg\"}}"; String_LTE = "{ \"myString\" : { \"$lte\" : \"abcdefg\"}}"; String_EX = "{ \"myString\" : { \"$exists\" : true}}"; String_DNE = "{ \"myString\" : { \"$exists\" : false}}"; String_IN = "{ \"myString\" : { \"$in\" : [ \"a\" , \"b\" , \"c\"]}}"; String_NIN = "{ \"myString\" : { \"$nin\" : [ \"d\" , \"e\" , \"f\"]}}"; String_RE = "{ \"myString\" : { \"$regex\" : \"(abc|def)\"}}"; Boolean_TRUE = "{ \"myBoolean\" : true}"; Boolean_FALSE = "{ \"myBoolean\" : false}"; Boolean_EX = "{ \"myBoolean\" : { \"$exists\" : true}}"; Boolean_DNE = "{ \"myBoolean\" : { \"$exists\" : false}}"; Short_EQ = "{ \"myShort\" : 100}"; Short_NE = "{ \"myShort\" : { \"$ne\" : 100}}"; Short_LT = "{ \"myShort\" : { \"$lt\" : 100}}"; Short_GT = "{ \"myShort\" : { \"$gt\" : 100}}"; Short_LTE = "{ \"myShort\" : { \"$lte\" : 100}}"; Short_GTE = "{ \"myShort\" : { \"$gte\" : 100}}"; Short_EX = "{ \"myShort\" : { \"$exists\" : true}}"; Short_DNE = "{ \"myShort\" : { \"$exists\" : false}}"; Short_IN = "{ \"myShort\" : { \"$in\" : [ 98 , 99 , 100]}}"; Short_NIN = "{ \"myShort\" : { \"$nin\" : [ 101 , 102 , 103]}}"; Integer_EQ = "{ \"myInteger\" : 100}"; Integer_NE = "{ \"myInteger\" : { \"$ne\" : 100}}"; Integer_LT = "{ \"myInteger\" : { \"$lt\" : 100}}"; Integer_GT = "{ \"myInteger\" : { \"$gt\" : 100}}"; Integer_LTE = "{ \"myInteger\" : { \"$lte\" : 100}}"; Integer_GTE = "{ \"myInteger\" : { \"$gte\" : 100}}"; Integer_EX = "{ \"myInteger\" : { \"$exists\" : true}}"; Integer_DNE = "{ \"myInteger\" : { \"$exists\" : false}}"; Integer_IN = "{ \"myInteger\" : { \"$in\" : [ 98 , 99 , 100]}}"; Integer_NIN = "{ \"myInteger\" : { \"$nin\" : [ 101 , 102 , 103]}}"; Long_EQ = "{ \"myLong\" : 100}"; Long_NE = "{ \"myLong\" : { \"$ne\" : 100}}"; Long_LT = "{ \"myLong\" : { \"$lt\" : 100}}"; Long_GT = "{ \"myLong\" : { \"$gt\" : 100}}"; Long_LTE = "{ \"myLong\" : { \"$lte\" : 100}}"; Long_GTE = "{ \"myLong\" : { \"$gte\" : 100}}"; Long_EX = "{ \"myLong\" : { \"$exists\" : true}}"; Long_DNE = "{ \"myLong\" : { \"$exists\" : false}}"; Long_IN = "{ \"myLong\" : { \"$in\" : [ 98 , 99 , 100]}}"; Long_NIN = "{ \"myLong\" : { \"$nin\" : [ 101 , 102 , 103]}}"; Float_EQ = "{ \"myFloat\" : 100.0}"; Float_NE = "{ \"myFloat\" : { \"$ne\" : 100.0}}"; Float_LT = "{ \"myFloat\" : { \"$lt\" : 100.0}}"; Float_GT = "{ \"myFloat\" : { \"$gt\" : 100.0}}"; Float_LTE = "{ \"myFloat\" : { \"$lte\" : 100.0}}"; Float_GTE = "{ \"myFloat\" : { \"$gte\" : 100.0}}"; Float_EX = "{ \"myFloat\" : { \"$exists\" : true}}"; Float_DNE = "{ \"myFloat\" : { \"$exists\" : false}}"; Float_IN = "{ \"myFloat\" : { \"$in\" : [ 98.0 , 99.0 , 100.0]}}"; Float_NIN = "{ \"myFloat\" : { \"$nin\" : [ 101.0 , 102.0 , 103.0]}}"; Double_EQ = "{ \"myDouble\" : 100.0}"; Double_NE = "{ \"myDouble\" : { \"$ne\" : 100.0}}"; Double_LT = "{ \"myDouble\" : { \"$lt\" : 100.0}}"; Double_GT = "{ \"myDouble\" : { \"$gt\" : 100.0}}"; Double_LTE = "{ \"myDouble\" : { \"$lte\" : 100.0}}"; Double_GTE = "{ \"myDouble\" : { \"$gte\" : 100.0}}"; Double_EX = "{ \"myDouble\" : { \"$exists\" : true}}"; Double_DNE = "{ \"myDouble\" : { \"$exists\" : false}}"; Double_IN = "{ \"myDouble\" : { \"$in\" : [ 98.0 , 99.0 , 100.0]}}"; Double_NIN = "{ \"myDouble\" : { \"$nin\" : [ 101.0 , 102.0 , 103.0]}}"; DateTime_EQ = "{ \"myDateTime\" : { \"$date\" : \"1970-01-01T00:00:00.000Z\"}}"; DateTime_NE = "{ \"myDateTime\" : { \"$ne\" : { \"$date\" : \"1970-01-01T00:00:00.000Z\"}}}"; DateTime_LT = "{ \"myDateTime\" : { \"$lt\" : { \"$date\" : \"1971-01-01T00:00:00.000Z\"}}}"; DateTime_LTE = "{ \"myDateTime\" : { \"$lte\" : { \"$date\" : \"1971-01-01T00:00:00.000Z\"}}}"; DateTime_GT = "{ \"myDateTime\" : { \"$gt\" : { \"$date\" : \"1970-01-01T00:00:00.000Z\"}}}"; DateTime_GTE = "{ \"myDateTime\" : { \"$gte\" : { \"$date\" : \"1970-01-01T00:00:00.000Z\"}}}"; DateTime_EX = "{ \"myDateTime\" : { \"$exists\" : true}}"; DateTime_DNE = "{ \"myDateTime\" : { \"$exists\" : false}}"; DateTime_BETWEEN = "{ \"$and\" : [ { \"myDateTime\" : { \"$gte\" : { \"$date\" : \"1970-01-01T00:00:00.000Z\"}}} , " + "{ \"myDateTime\" : { \"$lte\" : { \"$date\" : \"1971-01-01T00:00:00.000Z\"}}}]}"; INLINE_ANDING = "{ \"$and\" : [ { \"myString\" : \"Thing\"} , { \"myLong\" : { \"$exists\" : false}}]}"; INLINE_ORING = "{ \"$or\" : [ { \"myString\" : \"Thing\"} , { \"myLong\" : { \"$exists\" : false}}]}"; LIST_ANDING = "{ \"$and\" : [ { \"myString\" : \"Thing\"} , { \"myLong\" : { \"$exists\" : false}}]}"; LIST_ORING = "{ \"$or\" : [ { \"myString\" : \"Thing\"} , { \"myLong\" : { \"$exists\" : false}}]}"; LIST_ORING_OF_INLINE_ANDING = "{ \"$or\" : [ { \"$and\" : [ { \"myString\" : \"Thing\"} , " + "{ \"myLong\" : { \"$exists\" : false}}]} , { \"$and\" : [ { \"myString\" : { \"$ne\" : \"Cats\"}} ," + " { \"myLong\" : { \"$gt\" : 30}}]}]}"; LIST_ANDING_OF_INLINE_ORING = "{ \"$and\" : [ { \"$or\" : [ { \"myString\" : \"Thing\"} , " + "{ \"myLong\" : { \"$exists\" : false}}]} , { \"$or\" : [ { \"myString\" : { \"$ne\" : \"Cats\"}} ," + " { \"myLong\" : { \"$gt\" : 30}}]}]}"; LIST_ANDING_OR_LIST_ORING = "{ \"$or\" : [ { \"$and\" : [ { \"$or\" : [ { \"myString\" : \"Thing\"} ," + " { \"myLong\" : { \"$exists\" : false}}]} , { \"$or\" : [ { \"myString\" : { \"$ne\" : \"Cats\"}} ," + " { \"myLong\" : { \"$gt\" : 30}}]}]} , { \"$or\" : [ { \"$and\" : [ { \"myString\" : \"Thing\"} ," + " { \"myLong\" : { \"$exists\" : false}}]} , { \"$and\" : [ { \"myString\" : { \"$ne\" : \"Cats\"}} ," + " { \"myLong\" : { \"$gt\" : 30}}]}]}]}"; LIST_ORING_AND_LIST_ANDING = "{ \"$and\" : [ { \"$or\" : [ { \"$and\" : [ { \"myString\" : \"Thing\"} , " + "{ \"myLong\" : { \"$exists\" : false}}]} , { \"$and\" : [ { \"myString\" : { \"$ne\" : \"Cats\"}} ," + " { \"myLong\" : { \"$gt\" : 30}}]}]} , { \"$and\" : [ { \"$or\" : [ { \"myString\" : \"Thing\"} , " + "{ \"myLong\" : { \"$exists\" : false}}]} , { \"$or\" : [ { \"myString\" : { \"$ne\" : \"Cats\"}} , " + "{ \"myLong\" : { \"$gt\" : 30}}]}]}]}"; CHAINED_ORS = "{ \"$or\" : [ { \"myString\" : \"thing\"} , { \"myInteger\" : { \"$gt\" : 0}} ," + " { \"myInteger\" : { \"$lt\" : 5}} , { \"myLong\" : { \"$in\" : [ 0 , 1 , 2]}} ," + " { \"myDouble\" : { \"$lte\" : 2.9}} , { \"myBoolean\" : false} ," + " { \"myDateTime\" : { \"$exists\" : false}}]}"; CHAINED_ANDS_AND_ORS = "{ \"$or\" : [ { \"$and\" : [ { \"$or\" : [ { \"$and\" : [ { \"myString\" : \"thing\"} ," + " { \"myInteger\" : { \"$gt\" : 0}}]} , { \"myInteger\" : { \"$lt\" : 5}} , { \"myLong\" : { \"$in\" :" + " [ 0 , 1 , 2]}}]} , { \"myDouble\" : { \"$lte\" : 2.9}} , { \"myBoolean\" : false}]} , { \"myDateTime\" " + ": { \"$exists\" : false}}]}"; CHAINED_ANDS = "{ \"$and\" : [ { \"myString\" : \"thing\"} , { \"myInteger\" : { \"$gt\" : 0}} ," + " { \"myInteger\" : { \"$lt\" : 5}} , { \"myLong\" : { \"$in\" : [ 0 , 1 , 2]}} ," + " { \"myDouble\" : { \"$lte\" : 2.9}} , { \"myBoolean\" : false} , { \"myDateTime\" :" + " { \"$exists\" : false}}]}"; CHAINED_ORS_AND_ANDS = "{ \"$and\" : [ { \"$or\" : [ { \"$and\" : [ { \"$or\" : [ { \"myString\" :" + " \"thing\"} , { \"myInteger\" : { \"$gt\" : 0}}]} , { \"myInteger\" : { \"$lt\" : 5}} ," + " { \"myLong\" : { \"$in\" : [ 0 , 1 , 2]}}]} , { \"myDouble\" : { \"$lte\" : 2.9}} , " + "{ \"myBoolean\" : false}]} , { \"myDateTime\" : { \"$exists\" : false}}]}"; SUB_QUERY = "{ \"$and\" : [ { \"mySubList\" : { \"$elemMatch\" : { \"$and\" : [ { \"myString\" : \"Thing\"} , " + "{ \"myLong\" : { \"$exists\" : false}}]}}} , { \"myBoolean\" : true}]}"; NULL_EQUALITY = "{ \"myString\" : { \"$exists\" : false}}"; NULL_INEQUALITY = "{ \"myString\" : { \"$exists\" : true}}"; } @Override protected MongoVisitor getVisitor() { return new MongoVisitor(); } @Override protected void compare(String expected, Criteria converted) { assertEquals(expected, new CriteriaSerializer().apply(converted)); } } <|start_filename|>src/main/java/com/github/rutledgepaulv/qbuilders/operators/ComparisonOperator.java<|end_filename|> /* * * * com.github.rutledgepaulv.qbuilders.operators.ComparisonOperator * * * * * * Copyright (C) 2016 <NAME> <<EMAIL>> * * * * * * This software may be modified and distributed under the terms * * * of the MIT license. See the LICENSE file for details. * * * */ package com.github.rutledgepaulv.qbuilders.operators; import java.util.Objects; public final class ComparisonOperator { private String representation; public ComparisonOperator(String representation) { this.representation = representation; } public static final ComparisonOperator EQ = new ComparisonOperator("EQ"); public static final ComparisonOperator NE = new ComparisonOperator("NE"); public static final ComparisonOperator GT = new ComparisonOperator("GT"); public static final ComparisonOperator LT = new ComparisonOperator("LT"); public static final ComparisonOperator GTE = new ComparisonOperator("GTE"); public static final ComparisonOperator LTE = new ComparisonOperator("LTE"); public static final ComparisonOperator IN = new ComparisonOperator("IN"); public static final ComparisonOperator NIN = new ComparisonOperator("NIN"); public static final ComparisonOperator EX = new ComparisonOperator("EX"); public static final ComparisonOperator RE = new ComparisonOperator("RE"); public static final ComparisonOperator SUB_CONDITION_ANY = new ComparisonOperator("SUB_CONDITION_ANY"); @Override public final boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ComparisonOperator that = (ComparisonOperator) o; return Objects.equals(representation, that.representation); } @Override public final int hashCode() { return Objects.hash(representation); } } <|start_filename|>src/main/java/com/github/rutledgepaulv/qbuilders/delegates/virtual/ExistentialPropertyDelegate.java<|end_filename|> /* * * * com.github.rutledgepaulv.qbuilders.delegates.virtual.ExistentialPropertyDelegate * * * * * * Copyright (C) 2016 <NAME> <<EMAIL>> * * * * * * This software may be modified and distributed under the terms * * * of the MIT license. See the LICENSE file for details. * * * */ package com.github.rutledgepaulv.qbuilders.delegates.virtual; import com.github.rutledgepaulv.qbuilders.builders.QBuilder; import com.github.rutledgepaulv.qbuilders.conditions.Condition; import com.github.rutledgepaulv.qbuilders.operators.ComparisonOperator; import com.github.rutledgepaulv.qbuilders.properties.virtual.ExistentialProperty; import com.github.rutledgepaulv.qbuilders.structures.FieldPath; import java.util.Collections; public abstract class ExistentialPropertyDelegate<T extends QBuilder<T>> extends PropertyDelegate<T> implements ExistentialProperty<T> { protected ExistentialPropertyDelegate(FieldPath field, T canonical) { super(field, canonical); } public final Condition<T> exists() { return condition(getField(), ComparisonOperator.EX, Collections.singletonList(true)); } public final Condition<T> doesNotExist() { return condition(getField(), ComparisonOperator.EX, Collections.singletonList(false)); } } <|start_filename|>src/main/java/com/github/rutledgepaulv/qbuilders/nodes/LogicalNode.java<|end_filename|> /* * * * com.github.rutledgepaulv.qbuilders.nodes.LogicalNode * * * * * * Copyright (C) 2016 <NAME> <<EMAIL>> * * * * * * This software may be modified and distributed under the terms * * * of the MIT license. See the LICENSE file for details. * * * */ package com.github.rutledgepaulv.qbuilders.nodes; import java.util.LinkedList; import java.util.List; public abstract class LogicalNode extends AbstractNode { private List<AbstractNode> children = new LinkedList<>(); public LogicalNode() {} public LogicalNode(LogicalNode parent) { super(parent); } public LogicalNode(LogicalNode parent, List<AbstractNode> children) { super(parent); setChildren(children); } public List<AbstractNode> getChildren() { return children; } public void setChildren(List<AbstractNode> children) { this.children = children; children.forEach(child -> child.setParent(this)); } } <|start_filename|>src/main/java/com/github/rutledgepaulv/qbuilders/delegates/virtual/PropertyDelegate.java<|end_filename|> /* * * * com.github.rutledgepaulv.qbuilders.delegates.virtual.PropertyDelegate * * * * * * Copyright (C) 2016 <NAME> <<EMAIL>> * * * * * * This software may be modified and distributed under the terms * * * of the MIT license. See the LICENSE file for details. * * * */ package com.github.rutledgepaulv.qbuilders.delegates.virtual; import com.github.rutledgepaulv.qbuilders.builders.QBuilder; import com.github.rutledgepaulv.qbuilders.properties.virtual.Property; import com.github.rutledgepaulv.qbuilders.structures.FieldPath; public abstract class PropertyDelegate<T extends QBuilder<T>> extends Delegate<T> implements Property<T> { private FieldPath field; protected PropertyDelegate(FieldPath field, T canonical) { super(canonical); this.field = field; } protected final FieldPath getField() { return field; } } <|start_filename|>src/main/java/com/github/rutledgepaulv/qbuilders/delegates/virtual/EquitablePropertyDelegate.java<|end_filename|> /* * * * com.github.rutledgepaulv.qbuilders.delegates.virtual.EquitablePropertyDelegate * * * * * * Copyright (C) 2016 <NAME> <<EMAIL>> * * * * * * This software may be modified and distributed under the terms * * * of the MIT license. See the LICENSE file for details. * * * */ package com.github.rutledgepaulv.qbuilders.delegates.virtual; import com.github.rutledgepaulv.qbuilders.builders.QBuilder; import com.github.rutledgepaulv.qbuilders.conditions.Condition; import com.github.rutledgepaulv.qbuilders.operators.ComparisonOperator; import com.github.rutledgepaulv.qbuilders.properties.virtual.EquitableProperty; import com.github.rutledgepaulv.qbuilders.structures.FieldPath; import java.util.Collections; public abstract class EquitablePropertyDelegate<T extends QBuilder<T>, S> extends ExistentialPropertyDelegate<T> implements EquitableProperty<T,S> { protected EquitablePropertyDelegate(FieldPath field, T canonical) { super(field, canonical); } public final Condition<T> eq(S value) { if(value == null) { return condition(getField(), ComparisonOperator.EX, Collections.singleton(false)); } return condition(getField(), ComparisonOperator.EQ, Collections.singletonList(value)); } public final Condition<T> ne(S value) { if(value == null) { return condition(getField(), ComparisonOperator.EX, Collections.singleton(true)); } return condition(getField(), ComparisonOperator.NE, Collections.singletonList(value)); } } <|start_filename|>src/test/java/com/github/rutledgepaulv/qbuilders/visitors/PredicateVisitorTest.java<|end_filename|> /* * * * com.github.rutledgepaulv.qbuilders.visitors.PredicateVisitorTest * * * * * * Copyright (C) 2016 <NAME> <<EMAIL>> * * * * * * This software may be modified and distributed under the terms * * * of the MIT license. See the LICENSE file for details. * * * */ package com.github.rutledgepaulv.qbuilders.visitors; import com.github.rutledgepaulv.qbuilders.builders.QBuilder; import com.github.rutledgepaulv.qbuilders.conditions.Condition; import com.github.rutledgepaulv.qbuilders.properties.concrete.ConditionProperty; import com.github.rutledgepaulv.qbuilders.properties.concrete.EnumProperty; import com.github.rutledgepaulv.qbuilders.properties.concrete.StringProperty; import com.github.rutledgepaulv.testsupport.DomainModel; import com.github.rutledgepaulv.testsupport.QueryModel; import org.junit.Before; import org.junit.Test; import java.util.*; import java.util.function.Predicate; import java.util.stream.Collectors; import static com.github.rutledgepaulv.testsupport.QueryModel.QueryModelPredef.*; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; public class PredicateVisitorTest { private Set<DomainModel> actual = new HashSet<>(); private DomainModel AAA = get((byte) 7, (short) 5, 4, 0, 3, 2, 'a', "testing1", "test_a", "a"); private DomainModel ABA = get((byte) 5, (short) 3, 6, 2, 1, 4, 'c', "testing3", "test_b", "ab", "a"); private DomainModel AAB = get((byte) 6, (short) 4, 5, 1, 2, 3, 'b', "testing2", "test_c", "abc", "ab", "a"); private DomainModel BAA = get((byte) 4, (short) 2, 7, 3, 0, 5, 'd', null, "test_d", "abcd", "abc", "ab", "a"); private DomainModel BAB = get((byte) 3, (short) 1, 0, 4, 7, 6, 'e', "testing5", "test_e", "abcde", "abcd", "abc", "ab", "a"); private DomainModel BBA = get((byte) 2, (short) 0, 1, 5, 6, 7, 'f', "testing6", "test_f"); private DomainModel ABB = get((byte) 1, (short) 7, 2, 6, 5, 0, 'g', null, "test_g"); private DomainModel BBB = get((byte) 0, (short) 6, 3, 7, 4, 1, 'h', "testing8", "test_h"); @Before public void setUp() { actual.clear(); actual.addAll(Arrays.asList(AAA, AAB, ABA, BBA, BAA, BAB, ABB, BBB)); Set<DomainModel> clones = actual.stream().map(DomainModel::copy).collect(Collectors.toSet()); actual.forEach(entry -> entry.getMySubList().addAll(clones.stream() .filter(thing -> !thing.equals(entry)) .collect(Collectors.toList()))); } @Test public void testRegex() { compare(myListOfStrings().pattern(".*cd$"), BAA, BAB); } @Test public void subquery(){ compare(mySubList().any(myLong().gt(4L).and().myString().doesNotExist()), AAA, ABA, AAB, BAA, BAB, BBA, BBB); } @Test public void testEquality() { compare(myLong().eq(4L), BAB); } @Test public void testEqualityListField() { compare(myListOfStrings().eq("abcd"), BAA, BAB); } @Test public void testInequality() { compare(myLong().ne(4L), AAA, AAB, ABA, BAA, BBA, ABB, BBB); } @Test public void testInequalityListField() { compare(myListOfStrings().ne("abcd"), AAA, AAB, ABA, BBA, ABB, BBB); } @Test public void testGreaterThan() { compare(myLong().gt(5L), ABB, BBB); compare(myString2().lexicallyAfter("test_a"), AAB, ABA, BBA, BAA, BAB, ABB, BBB); } @Test public void testGreaterThanOrEqualTo() { compare(myLong().gte(5L), BBA, ABB, BBB); compare(myString2().lexicallyNotBefore("test_a"), AAA, AAB, ABA, BBA, BAA, BAB, ABB, BBB); } @Test public void testLessThan() { compare(myLong().lt(5L), AAA, AAB, ABA, BAA, BAB); compare(myString2().lexicallyBefore("test_h"), AAA, AAB, ABA, BBA, BAA, BAB, ABB); } @Test public void testLessThanOrEqualTo() { compare(myLong().lte(5L), AAA, AAB, ABA, BAA, BAB, BBA); compare(myString2().lexicallyNotAfter("test_h"), AAA, AAB, ABA, BBA, BAA, BAB, ABB, BBB); } @Test public void exists() { compare(myString().exists(), AAA, AAB, ABA, BAB, BBA, BBB); } @Test public void existsListField() { compare(myListOfStrings().exists(), AAA, AAB, ABA, BBA, BAA, BAB, ABB, BBB); } @Test public void doesNotExist() { compare(myString().doesNotExist(), BAA, ABB); } @Test public void testDoesNotExistListField() { compare(myListOfStrings().doesNotExist()); } @Test public void inNonListField() { compare(myString().in("testing6", "testing5"), BAB, BBA); } @Test public void inListField() { compare(myListOfStrings().in("abcd", "abc"), BAB, BAA, AAB); } @Test public void ninNonListField() { compare(myString().nin("testing6", "testing5"), AAA, AAB, ABA, BAA, ABB, BBB); } @Test public void ninListField() { compare(myListOfStrings().nin("abcd", "abc"), AAA, ABA, BBA, ABB, BBB); } @Test public void inNonListFieldArray() { compare(myString().in(Arrays.asList("testing6", "testing5")), BAB, BBA); } @Test public void inListFieldArray() { compare(myListOfStrings().in(Arrays.asList("abcd", "abc")), BAB, BAA, AAB); } @Test public void ninNonListFieldArray() { compare(myString().nin(Arrays.asList("testing6", "testing5")), AAA, AAB, ABA, BAA, ABB, BBB); } @Test public void ninListFieldArray() { compare(myListOfStrings().nin(Arrays.asList("abcd", "abc")), AAA, ABA, BBA, ABB, BBB); } @Test public void testAnding() { compare(myString().doesNotExist().and().myLong().eq(6L), ABB); } @Test public void testOring() { compare(myString().doesNotExist().or().myString().eq("testing8"), BAA, ABB, BBB); } public enum Icecream { GINGER_ROOT(), GOBLIN_BLOOD() } public class User { private String firstName; public String middleName; private String lastName; private Icecream favouriteFlavor; private List<User> friends = new LinkedList<>(); private User[] neighbors = new User[2]; private User bestFriend; public User withFriends(User... newFriends) { Collections.addAll(friends, newFriends); return this; } public User firstName(String paul) { firstName = paul; return this; } public User lastName(String paul) { lastName = paul; return this; } public User bestFriend(User paul) { bestFriend = paul; return this; } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } public List<User> getFriends() { return friends; } public User[] getNeighbors() { return neighbors; } public User getBestFriend() { return bestFriend; } public Icecream getFavouriteFlavor() { return favouriteFlavor; } } @SuppressWarnings("WeakerAccess") public class UserQuery extends QBuilder<UserQuery> { public StringProperty<UserQuery> firstName() { return string("firstName"); } public StringProperty<UserQuery> middleName() { return string("middleName"); } public StringProperty<UserQuery> lastName() { return string("lastName"); } public ConditionProperty<UserQuery, UserQuery> bestFriend() { return condition("bestFriend"); } public ConditionProperty<UserQuery, UserQuery> friends() { return condition("friends"); } public ConditionProperty<UserQuery, UserQuery> neighbors() { return condition("neighbors"); } public EnumProperty<UserQuery, Icecream> favouriteFlavor() { return enumeration("favouriteFlavor"); } } public class Bruiser extends User { public String cruiser; public Optional<String> getCruiser() { return Optional.ofNullable(cruiser); } } @Test public void regularQueryTest() { List<User> people = new LinkedList<>(); people.add(new User().withFriends(new User().firstName("James"), new User().firstName("Paul"))); people.add(new User().withFriends(new User().firstName("Bob"))); Condition<UserQuery> condition = new UserQuery().friends().any(new UserQuery().firstName().eq("Paul")); Predicate<User> query = condition.query(new PredicateVisitor<>()); assertEquals(people.get(0), people.stream().filter(query).findFirst().get()); assertEquals(1, people.stream().filter(query).count()); } @Test public void regularQueryNoGetterTest() { List<User> people = new LinkedList<>(); User paul = new User(); paul.middleName = "Paul"; people.add(new User().withFriends(new User().firstName("James"), paul)); people.add(new User().withFriends(new User().firstName("Bob"))); Condition<UserQuery> condition = new UserQuery().friends().any(new UserQuery().middleName().eq("Paul")); Predicate<User> query = condition.query(new PredicateVisitor<>()); assertEquals(people.get(0), people.stream().filter(query).findFirst().get()); assertEquals(1, people.stream().filter(query).count()); } @Test public void regularQueryNoGetterSuperclassTest() { List<User> people = new LinkedList<>(); Bruiser paul = new Bruiser(); paul.middleName = "Braul"; people.add(new User().withFriends(new User().firstName("James"), paul)); people.add(new User().withFriends(new User().firstName("Bob"))); Condition<UserQuery> condition = new UserQuery().friends().any(new UserQuery().middleName().eq("Braul")); Predicate<User> query = condition.query(new PredicateVisitor<>()); assertEquals(people.get(0), people.stream().filter(query).findFirst().get()); assertEquals(1, people.stream().filter(query).count()); } @Test public void stringQueryTest() { List<User> people = new LinkedList<>(); people.add(new User().firstName("James").withFriends(new User().firstName("Paul"))); people.add(new User().firstName("Paul")); Condition<UserQuery> condition = new UserQuery().string("firstName").eq("Paul"); Predicate<User> query = condition.query(new PredicateVisitor<>()); assertEquals(people.get(1), people.stream().filter(query).findFirst().get()); assertEquals(1, people.stream().filter(query).count()); } @Test public void stringQueryMultipleLevelsTest() { List<User> people = new LinkedList<>(); people.add(new User().bestFriend(new User().firstName("Geraldo")).firstName("Kanye")); people.add(new User().bestFriend(new User().firstName("James")).firstName("Kim")); people.add(new User().bestFriend(new User().firstName("Geraldo")).firstName("James")); Condition<UserQuery> condition = new UserQuery().string("bestFriend.firstName").eq("Geraldo"); Predicate<User> query = condition.query(new PredicateVisitor<>()); assertEquals(people.get(0), people.stream().filter(query).findFirst().get()); assertEquals(2, people.stream().filter(query).count()); } @Test public void stringQueryListTest() { List<User> people = new LinkedList<>(); people.add(new User().withFriends(new User().firstName("Paul")).firstName("Dan")); people.add(new User().withFriends(new User().firstName("Durande")).firstName("Don")); Condition<UserQuery> condition = new UserQuery().string("friends.firstName").eq("Durande"); Predicate<User> query = condition.query(new PredicateVisitor<>()); assertEquals(people.get(1), people.stream().filter(query).findFirst().get()); assertEquals(1, people.stream().filter(query).count()); } @Test public void stringQueryMultipleListTest() { List<User> people = new LinkedList<>(); people.add(new User().withFriends(new User().withFriends(new User().firstName("Durande")))); people.add(new User().withFriends(new User().withFriends(new User().firstName("Paul")))); people.add(new User().withFriends(new User().firstName("Durande"))); Condition<UserQuery> condition = new UserQuery().string("friends.friends.firstName").eq("Durande"); Predicate<User> query = condition.query(new PredicateVisitor<>()); assertEquals(people.get(0), people.stream().filter(query).findFirst().get()); assertEquals(1, people.stream().filter(query).count()); } @Test public void stringQueryArrayTest() { List<User> people = new LinkedList<>(); User person1 = new User().firstName("Gumbo"); person1.neighbors[0] = new User().firstName("Durande"); person1.neighbors[1] = new User().firstName("KangarooCat"); people.add(person1); User person2 = new User().firstName("Mendy"); person2.neighbors[0] = new User().firstName("<NAME>"); person2.neighbors[1] = new User().firstName("KangarooCat"); people.add(person2); Condition<UserQuery> condition = new UserQuery().string("neighbors.firstName").eq("Durande"); Predicate<User> query = condition.query(new PredicateVisitor<>()); assertEquals(people.get(0), people.stream().filter(query).findFirst().get()); assertEquals(1, people.stream().filter(query).count()); } @Test public void stringQueryNullTest() { List<User> people = new LinkedList<>(); people.add(new User().withFriends(null, null)); Condition<UserQuery> condition = new UserQuery().string("friends.firstName").eq("Durande"); Predicate<User> query = condition.query(new PredicateVisitor<>()); Object nothing = people.stream().filter(query).findAny(); assertEquals(Optional.empty(), nothing); } @Test public void stringQueryNullMiddleTest() { List<User> people = new LinkedList<>(); people.add(new User().bestFriend(null)); Condition<UserQuery> condition = new UserQuery().string("friends.bestFriend.firstName").eq("Durande"); Predicate<User> query = condition.query(new PredicateVisitor<>()); Object nothing = people.stream().filter(query).findAny(); assertEquals(Optional.empty(), nothing); } @Test public void stringQueryLogicTest() { Condition<UserQuery> ev = new UserQuery().string("firstName").eq("Geraldo").and().string("lastName").eq("Neumann"); Condition<UserQuery> condition = new UserQuery().friends().any(ev); Predicate<User> query = condition.query(new PredicateVisitor<>()); List<User> people = new LinkedList<>(); people.add(new User().withFriends(new User().firstName("Geraldo").lastName("Neumann"))); people.add(new User().withFriends(new User().firstName("Geraldo").lastName("<NAME>")).firstName("Geraldo") .lastName("Neumann")); assertEquals(people.get(0), people.stream().filter(query).findFirst().get()); assertEquals(1, people.stream().filter(query).count()); } @Test public void enumTest() { User user = new User(); user.favouriteFlavor = Icecream.GOBLIN_BLOOD; user.firstName = "Geraldo"; Condition<UserQuery> query = new UserQuery().favouriteFlavor().eq(Icecream.GOBLIN_BLOOD); assertTrue(query.query(new PredicateVisitor<>()).test(user)); } @Test public void existsTest() { User user = new User(); user.favouriteFlavor = Icecream.GOBLIN_BLOOD; user.firstName = "Geraldo"; Condition<UserQuery> query = new UserQuery().favouriteFlavor().exists(); assertTrue(query.query(new PredicateVisitor<>()).test(user)); } private void compare(Condition<QueryModel> query, DomainModel... expected) { Predicate<DomainModel> pred = query.query(new PredicateVisitor<>()); Set<DomainModel> ex = new HashSet<>(Arrays.asList(expected)); Set<DomainModel> ac = actual.stream().filter(pred).collect(Collectors.toSet()); assertEquals(ex, ac); } private DomainModel get(byte val1, short val2, int val3, long val4, float val5, double val6, char val7, String val8, String val9, String... myStrings) { DomainModel domainModel = new DomainModel(); domainModel.setMyByte(val1); domainModel.setMyShort(val2); domainModel.setMyInteger(val3); domainModel.setMyLong(val4); domainModel.setMyFloat(val5); domainModel.setMyDouble(val6); domainModel.setMyCharacter(val7); domainModel.setMyString(val8); domainModel.setMyString2(val9); domainModel.setMyListOfStrings(Arrays.asList(myStrings)); return domainModel; } } <|start_filename|>src/main/java/com/github/rutledgepaulv/qbuilders/delegates/concrete/ConditionPropertyDelegate.java<|end_filename|> /* * * * com.github.rutledgepaulv.qbuilders.delegates.concrete.ConditionPropertyDelegate * * * * * * Copyright (C) 2016 <NAME> <<EMAIL>> * * * * * * This software may be modified and distributed under the terms * * * of the MIT license. See the LICENSE file for details. * * * */ package com.github.rutledgepaulv.qbuilders.delegates.concrete; import com.github.rutledgepaulv.qbuilders.builders.QBuilder; import com.github.rutledgepaulv.qbuilders.conditions.Condition; import com.github.rutledgepaulv.qbuilders.delegates.virtual.PropertyDelegate; import com.github.rutledgepaulv.qbuilders.nodes.*; import com.github.rutledgepaulv.qbuilders.operators.ComparisonOperator; import com.github.rutledgepaulv.qbuilders.properties.concrete.ConditionProperty; import com.github.rutledgepaulv.qbuilders.structures.FieldPath; import com.github.rutledgepaulv.qbuilders.visitors.AbstractVoidContextNodeVisitor; import java.util.Collections; public final class ConditionPropertyDelegate<T extends QBuilder<T>, S extends QBuilder<S>> extends PropertyDelegate<T> implements ConditionProperty<T, S> { public ConditionPropertyDelegate(FieldPath field, T canonical) { super(field, canonical); } @Override public Condition<T> any(Condition<S> condition) { final LogicalNode root = ((ConditionDelegate) condition).getRootNode(); // prepend this field to all of the fields in the subtree root.visit(new NamespacingVisitor(getField())); return condition(getField(), ComparisonOperator.SUB_CONDITION_ANY, Collections.singleton(condition)); } private class NamespacingVisitor extends AbstractVoidContextNodeVisitor<Void> { private FieldPath parent; public NamespacingVisitor(FieldPath parent) { this.parent = parent; } @Override protected Void visit(AndNode node) { node.getChildren().stream().forEach(this::visitAny); return null; } @Override protected Void visit(OrNode node) { node.getChildren().stream().forEach(this::visitAny); return null; } @Override protected Void visit(ComparisonNode node) { node.setField(node.getField().prepend(parent)); return null; } } } <|start_filename|>src/test/java/com/github/rutledgepaulv/testsupport/QueryModel.java<|end_filename|> /* * * * com.github.rutledgepaulv.testsupport.QueryModel * * * * * * Copyright (C) 2016 <NAME> <<EMAIL>> * * * * * * This software may be modified and distributed under the terms * * * of the MIT license. See the LICENSE file for details. * * * */ package com.github.rutledgepaulv.testsupport; import com.github.rutledgepaulv.qbuilders.builders.QBuilder; import com.github.rutledgepaulv.qbuilders.conditions.Condition; import com.github.rutledgepaulv.qbuilders.properties.concrete.*; import static com.github.rutledgepaulv.testsupport.FieldUtil.getCurrentMethodName; public class QueryModel extends QBuilder<QueryModel> { public static class QueryModelPredef { @SafeVarargs public static Condition<QueryModel> and(Condition<QueryModel> c1, Condition<QueryModel> c2, Condition<QueryModel>... cn) { return new QueryModel().and(c1, c2, cn); } @SafeVarargs public static Condition<QueryModel> or(Condition<QueryModel> c1, Condition<QueryModel> c2, Condition<QueryModel>... cn) { return new QueryModel().or(c1, c2, cn); } public static BooleanProperty<QueryModel> myBoolean() { return new QueryModel().myBoolean(); } public static StringProperty<QueryModel> myString() { return new QueryModel().myString(); } public static StringProperty<QueryModel> myString2() { return new QueryModel().myString2(); } public static LongProperty<QueryModel> myLong() { return new QueryModel().myLong(); } public static DoubleProperty<QueryModel> myDouble() { return new QueryModel().myDouble(); } public static IntegerProperty<QueryModel> myInteger() { return new QueryModel().myInteger(); } public static ShortProperty<QueryModel> myShort() { return new QueryModel().myShort(); } public static FloatProperty<QueryModel> myFloat() { return new QueryModel().myFloat(); } public static StringProperty<QueryModel> myListOfStrings() { return new QueryModel().myListOfStrings(); } public static InstantProperty<QueryModel> myDateTime() { return new QueryModel().myDateTime(); } public static ConditionProperty<QueryModel, QueryModel> mySubList() { return new QueryModel().mySubList(); } public static EnumProperty<QueryModel, DomainModel.MyEnum> myEnum() { return new QueryModel().myEnum(); } } public EnumProperty<QueryModel, DomainModel.MyEnum> myEnum() { return enumeration(getCurrentMethodName()); } private StringProperty<QueryModel> myString2() { return string(getCurrentMethodName()); } public BooleanProperty<QueryModel> myBoolean() { return bool(getCurrentMethodName()); } public StringProperty<QueryModel> myString() { return string(getCurrentMethodName()); } public LongProperty<QueryModel> myLong() { return longNum(getCurrentMethodName()); } public DoubleProperty<QueryModel> myDouble() { return doubleNum(getCurrentMethodName()); } public IntegerProperty<QueryModel> myInteger() { return intNum(getCurrentMethodName()); } public ShortProperty<QueryModel> myShort() { return shortNum(getCurrentMethodName()); } public FloatProperty<QueryModel> myFloat() { return floatNum(getCurrentMethodName()); } public StringProperty<QueryModel> myListOfStrings() { return string(getCurrentMethodName()); } public InstantProperty<QueryModel> myDateTime() { return instant(getCurrentMethodName()); } public ConditionProperty<QueryModel, QueryModel> mySubList() { return condition(getCurrentMethodName()); } } <|start_filename|>src/main/java/com/github/rutledgepaulv/qbuilders/properties/virtual/ExistentialProperty.java<|end_filename|> /* * * * com.github.rutledgepaulv.qbuilders.properties.virtual.ExistentialProperty * * * * * * Copyright (C) 2016 <NAME> <<EMAIL>> * * * * * * This software may be modified and distributed under the terms * * * of the MIT license. See the LICENSE file for details. * * * */ package com.github.rutledgepaulv.qbuilders.properties.virtual; import com.github.rutledgepaulv.qbuilders.builders.QBuilder; import com.github.rutledgepaulv.qbuilders.conditions.Condition; /** * For properties that may or may not exist. * * @param <T> The final type of the builder. */ public interface ExistentialProperty<T extends QBuilder<T>> extends Property<T> { /** * Specifies that the selected field must exist (and be non-null). * * @return The logically complete condition */ Condition<T> exists(); /** * Specifies that the selected field must not exist (or be equal to null). * * @return The logically complete condition */ Condition<T> doesNotExist(); } <|start_filename|>src/main/java/com/github/rutledgepaulv/qbuilders/delegates/virtual/ListablePropertyDelegate.java<|end_filename|> /* * * * com.github.rutledgepaulv.qbuilders.delegates.virtual.ListablePropertyDelegate * * * * * * Copyright (C) 2016 <NAME> <<EMAIL>> * * * * * * This software may be modified and distributed under the terms * * * of the MIT license. See the LICENSE file for details. * * * */ package com.github.rutledgepaulv.qbuilders.delegates.virtual; import com.github.rutledgepaulv.qbuilders.builders.QBuilder; import com.github.rutledgepaulv.qbuilders.conditions.Condition; import com.github.rutledgepaulv.qbuilders.operators.ComparisonOperator; import com.github.rutledgepaulv.qbuilders.properties.virtual.ListableProperty; import com.github.rutledgepaulv.qbuilders.structures.FieldPath; import java.util.Collection; import static java.util.Arrays.asList; public abstract class ListablePropertyDelegate<T extends QBuilder<T>, S> extends EquitablePropertyDelegate<T, S> implements ListableProperty<T, S> { protected ListablePropertyDelegate(FieldPath field, T canonical) { super(field, canonical); } @SafeVarargs public final Condition<T> in(S... values) { return condition(getField(), ComparisonOperator.IN, asList(values)); } public final Condition<T> in(Collection<S> values) { return condition(getField(), ComparisonOperator.IN, values); } @SafeVarargs public final Condition<T> nin(S... values) { return condition(getField(), ComparisonOperator.NIN, asList(values)); } public final Condition<T> nin(Collection<S> values) { return condition(getField(), ComparisonOperator.NIN, values); } } <|start_filename|>src/main/java/com/github/rutledgepaulv/qbuilders/builders/GeneralQueryBuilder.java<|end_filename|> /* * * * com.github.rutledgepaulv.qbuilders.builders.GeneralQueryBuilder * * * * * * Copyright (C) 2016 <NAME> <<EMAIL>> * * * * * * This software may be modified and distributed under the terms * * * of the MIT license. See the LICENSE file for details. * * * */ package com.github.rutledgepaulv.qbuilders.builders; import com.github.rutledgepaulv.qbuilders.conditions.Condition; import com.github.rutledgepaulv.qbuilders.nodes.ComparisonNode; public class GeneralQueryBuilder extends QBuilder<GeneralQueryBuilder> { public Condition<GeneralQueryBuilder> passThrough(ComparisonNode node) { return condition(node.getField(), node.getOperator(), node.getValues()); } } <|start_filename|>src/main/java/com/github/rutledgepaulv/qbuilders/visitors/MongoVisitor.java<|end_filename|> /* * * * com.github.rutledgepaulv.qbuilders.visitors.MongoVisitor * * * * * * Copyright (C) 2016 <NAME> <<EMAIL>> * * * * * * This software may be modified and distributed under the terms * * * of the MIT license. See the LICENSE file for details. * * * */ package com.github.rutledgepaulv.qbuilders.visitors; import com.github.rutledgepaulv.qbuilders.nodes.AndNode; import com.github.rutledgepaulv.qbuilders.nodes.ComparisonNode; import com.github.rutledgepaulv.qbuilders.nodes.OrNode; import com.github.rutledgepaulv.qbuilders.operators.ComparisonOperator; import org.springframework.data.mongodb.core.query.Criteria; import java.sql.Date; import java.time.Instant; import java.util.Collection; import java.util.List; import java.util.function.Function; import java.util.stream.Collectors; import static org.springframework.data.mongodb.core.query.Criteria.where; @SuppressWarnings("WeakerAccess") public class MongoVisitor extends AbstractVoidContextNodeVisitor<Criteria> { protected final Function<Object, Object> normalizer; public MongoVisitor() { this(new DefaultNormalizer()); } public MongoVisitor(Function<Object, Object> normalizer) { this.normalizer = normalizer; } @Override protected Criteria visit(AndNode node) { Criteria criteria = new Criteria(); List<Criteria> children = node.getChildren().stream() .map(this::visitAny).collect(Collectors.toList()); return criteria.andOperator(children.toArray(new Criteria[children.size()])); } @Override protected Criteria visit(OrNode node) { Criteria criteria = new Criteria(); List<Criteria> children = node.getChildren().stream() .map(this::visitAny).collect(Collectors.toList()); return criteria.orOperator(children.toArray(new Criteria[children.size()])); } @Override protected Criteria visit(ComparisonNode node) { ComparisonOperator operator = node.getOperator(); Collection<?> values = node.getValues().stream().map(normalizer).collect(Collectors.toList()); String field = node.getField().asKey(); if(ComparisonOperator.EQ.equals(operator)) { return where(field).is(single(values)); } else if(ComparisonOperator.NE.equals(operator)) { return where(field).ne(single(values)); } else if (ComparisonOperator.EX.equals(operator)) { return where(field).exists((Boolean)single(values)); } else if (ComparisonOperator.GT.equals(operator)) { return where(field).gt(single(values)); } else if (ComparisonOperator.LT.equals(operator)) { return where(field).lt(single(values)); } else if (ComparisonOperator.GTE.equals(operator)) { return where(field).gte(single(values)); } else if (ComparisonOperator.LTE.equals(operator)) { return where(field).lte(single(values)); } else if (ComparisonOperator.IN.equals(operator)) { return where(field).in(values); } else if (ComparisonOperator.NIN.equals(operator)) { return where(field).nin(values); } else if (ComparisonOperator.RE.equals(operator)) { return where(field).regex((String)single(values)); } else if (ComparisonOperator.SUB_CONDITION_ANY.equals(operator)) { return where(field).elemMatch(condition(node)); } throw new UnsupportedOperationException("This visitor does not support the operator " + operator + "."); } protected static class DefaultNormalizer implements Function<Object, Object> { @Override public Object apply(Object o) { if(o instanceof Instant) { return Date.from((Instant) o); } return o; } } } <|start_filename|>src/main/java/com/github/rutledgepaulv/qbuilders/visitors/ContextualNodeVisitor.java<|end_filename|> /* * * * com.github.rutledgepaulv.qbuilders.visitors.ContextualNodeVisitor * * * * * * Copyright (C) 2016 <NAME> <<EMAIL>> * * * * * * This software may be modified and distributed under the terms * * * of the MIT license. See the LICENSE file for details. * * * */ package com.github.rutledgepaulv.qbuilders.visitors; import com.github.rutledgepaulv.qbuilders.conditions.Condition; import com.github.rutledgepaulv.qbuilders.nodes.*; import com.github.rutledgepaulv.qbuilders.operators.ComparisonOperator; import java.util.Collection; @SuppressWarnings("ConstantConditions") public abstract class ContextualNodeVisitor<T,S> { protected abstract T visit(AndNode node, S context); protected abstract T visit(OrNode node, S context); protected abstract T visit(ComparisonNode node, S context); /** * Build a comparison node value into a visited value so that * it can be composed into the larger query being built. * * @param node The node with a condition argument to build into a visited value. * * @return The visited value. */ protected T condition(ComparisonNode node,S context) { if(!node.getOperator().equals(ComparisonOperator.SUB_CONDITION_ANY)) { throw new IllegalArgumentException("You can only build a condition for sub-condition operator nodes."); } Object sub = node.getValues().iterator().next(); // support either submitting a tree node in which case handle visiting it for // them, or submit a Condition representing a wrapper around that tree in which // case visit it with this visitor if(sub instanceof AbstractNode) { return visitAny((AbstractNode) sub, context); } else if (sub instanceof Condition<?>) { return ((Condition<?>) sub).query(this, context); } else { throw new IllegalArgumentException("Unknown node value type for subquery."); } } protected Object single(Collection<?> values) { if(!values.isEmpty()) { return values.iterator().next(); } else { throw new IllegalArgumentException("You must provide a non-null query value for the condition."); } } public final T visitAny(AbstractNode node, S context) { // skip straight to the children if it's a logical node with one member if(node instanceof LogicalNode) { LogicalNode logical = (LogicalNode) node; if(logical.getChildren().size() == 1) { return visitAny(logical.getChildren().get(0), context); } } if(node instanceof AndNode){ return visit((AndNode)node, context); } else if (node instanceof OrNode){ return visit((OrNode)node, context); } else { return visit((ComparisonNode)node, context); } } } <|start_filename|>src/test/java/com/github/rutledgepaulv/testsupport/QBuilderTestBase.java<|end_filename|> /* * * * com.github.rutledgepaulv.testsupport.QBuilderTestBase * * * * * * Copyright (C) 2016 <NAME> <<EMAIL>> * * * * * * This software may be modified and distributed under the terms * * * of the MIT license. See the LICENSE file for details. * * * */ package com.github.rutledgepaulv.testsupport; import com.github.rutledgepaulv.qbuilders.conditions.Condition; import com.github.rutledgepaulv.qbuilders.visitors.ContextualNodeVisitor; import org.junit.Test; import java.time.OffsetDateTime; import java.time.ZoneOffset; import static com.github.rutledgepaulv.testsupport.DomainModel.MyEnum.VALUE1; import static com.github.rutledgepaulv.testsupport.DomainModel.MyEnum.VALUE2; import static com.github.rutledgepaulv.testsupport.DomainModel.MyEnum.VALUE3; import static com.github.rutledgepaulv.testsupport.QueryModel.QueryModelPredef.*; public abstract class QBuilderTestBase<T extends ContextualNodeVisitor<S,U>, S, U> { protected abstract T getVisitor(); protected abstract void compare(String expected, S converted); protected interface Simple { interface String { Condition<QueryModel> EQ = myString().eq("abcdefg"); Condition<QueryModel> NE = myString().ne("abcdefg"); Condition<QueryModel> LT = myString().lexicallyBefore("abcdefg"); Condition<QueryModel> GT = myString().lexicallyAfter("abcdefg"); Condition<QueryModel> GTE = myString().lexicallyNotBefore("abcdefg"); Condition<QueryModel> LTE = myString().lexicallyNotAfter("abcdefg"); Condition<QueryModel> EX = myString().exists(); Condition<QueryModel> DNE = myString().doesNotExist(); Condition<QueryModel> IN = myString().in("a", "b", "c"); Condition<QueryModel> NIN = myString().nin("d", "e", "f"); Condition<QueryModel> RE = myString().pattern("(abc|def)"); } interface Enum { Condition<QueryModel> EQ = myEnum().eq(VALUE1); Condition<QueryModel> NE = myEnum().ne(VALUE1); Condition<QueryModel> EX = myEnum().exists(); Condition<QueryModel> DNE = myEnum().doesNotExist(); Condition<QueryModel> IN = myEnum().in(VALUE1, VALUE2, VALUE3); Condition<QueryModel> NIN = myEnum().nin(VALUE1, VALUE2, VALUE3); } interface Boolean { Condition<QueryModel> TRUE = myBoolean().isTrue(); Condition<QueryModel> FALSE = myBoolean().isFalse(); Condition<QueryModel> EX = myBoolean().exists(); Condition<QueryModel> DNE = myBoolean().doesNotExist(); } interface Short { Condition<QueryModel> EQ = myShort().eq((short) 100); Condition<QueryModel> NE = myShort().ne((short) 100); Condition<QueryModel> GT = myShort().gt((short) 100); Condition<QueryModel> LT = myShort().lt((short) 100); Condition<QueryModel> GTE = myShort().gte((short) 100); Condition<QueryModel> LTE = myShort().lte((short) 100); Condition<QueryModel> EX = myShort().exists(); Condition<QueryModel> DNE = myShort().doesNotExist(); Condition<QueryModel> IN = myShort().in((short) 98, (short) 99, (short) 100); Condition<QueryModel> NIN = myShort().nin((short) 101, (short) 102, (short) 103); } interface Integer { Condition<QueryModel> EQ = myInteger().eq(100); Condition<QueryModel> NE = myInteger().ne(100); Condition<QueryModel> GT = myInteger().gt(100); Condition<QueryModel> LT = myInteger().lt(100); Condition<QueryModel> GTE = myInteger().gte(100); Condition<QueryModel> LTE = myInteger().lte(100); Condition<QueryModel> EX = myInteger().exists(); Condition<QueryModel> DNE = myInteger().doesNotExist(); Condition<QueryModel> IN = myInteger().in(98, 99, 100); Condition<QueryModel> NIN = myInteger().nin(101, 102, 103); } interface Long { Condition<QueryModel> EQ = myLong().eq(100L); Condition<QueryModel> NE = myLong().ne(100L); Condition<QueryModel> GT = myLong().gt(100L); Condition<QueryModel> LT = myLong().lt(100L); Condition<QueryModel> GTE = myLong().gte(100L); Condition<QueryModel> LTE = myLong().lte(100L); Condition<QueryModel> EX = myLong().exists(); Condition<QueryModel> DNE = myLong().doesNotExist(); Condition<QueryModel> IN = myLong().in(98L, 99L, 100L); Condition<QueryModel> NIN = myLong().nin(101L, 102L, 103L); } interface Float { Condition<QueryModel> EQ = myFloat().eq(100f); Condition<QueryModel> NE = myFloat().ne(100f); Condition<QueryModel> GT = myFloat().gt(100f); Condition<QueryModel> LT = myFloat().lt(100f); Condition<QueryModel> GTE = myFloat().gte(100f); Condition<QueryModel> LTE = myFloat().lte(100f); Condition<QueryModel> EX = myFloat().exists(); Condition<QueryModel> DNE = myFloat().doesNotExist(); Condition<QueryModel> IN = myFloat().in(98f, 99f, 100f); Condition<QueryModel> NIN = myFloat().nin(101f, 102f, 103f); } interface Double { Condition<QueryModel> EQ = myDouble().eq(100.0); Condition<QueryModel> NE = myDouble().ne(100.0); Condition<QueryModel> GT = myDouble().gt(100.0); Condition<QueryModel> LT = myDouble().lt(100.0); Condition<QueryModel> GTE = myDouble().gte(100.0); Condition<QueryModel> LTE = myDouble().lte(100.0); Condition<QueryModel> EX = myDouble().exists(); Condition<QueryModel> DNE = myDouble().doesNotExist(); Condition<QueryModel> IN = myDouble().in(98.0, 99.0, 100.0); Condition<QueryModel> NIN = myDouble().nin(101.0, 102.0, 103.0); } interface Instant { java.time.Instant epoch = OffsetDateTime.of(1970, 1, 1, 0, 0, 0, 0, ZoneOffset.ofHours(0)) .toInstant(); java.time.Instant yearAfterEpoch = OffsetDateTime.of(1970, 1, 1, 0, 0, 0, 0, ZoneOffset.ofHours(0)) .plusYears(1).toInstant(); Condition<QueryModel> EQ = myDateTime().eq(epoch); Condition<QueryModel> NE = myDateTime().ne(epoch); Condition<QueryModel> GT = myDateTime().after(epoch, true); Condition<QueryModel> GTE = myDateTime().after(epoch, false); Condition<QueryModel> LT = myDateTime().before(yearAfterEpoch, true); Condition<QueryModel> LTE = myDateTime().before(yearAfterEpoch, false); Condition<QueryModel> BETWEEN = myDateTime().between(epoch, false, yearAfterEpoch, false); Condition<QueryModel> EX = myDateTime().exists(); Condition<QueryModel> DNE = myDateTime().doesNotExist(); } } protected interface Logical { Condition<QueryModel> INLINE_ANDING = myString().eq("Thing").and().myLong().doesNotExist(); Condition<QueryModel> INLINE_ORING = myString().eq("Thing").or().myLong().doesNotExist(); Condition<QueryModel> LIST_ANDING = QueryModel.QueryModelPredef .and(myString().eq("Thing"), myLong().doesNotExist()); Condition<QueryModel> LIST_ORING = QueryModel.QueryModelPredef .or(myString().eq("Thing"), myLong().doesNotExist()); Condition<QueryModel> LIST_ORING_OF_INLINE_ANDING = QueryModel.QueryModelPredef .or(myString().eq("Thing").and().myLong().doesNotExist(), myString().ne("Cats").and().myLong().gt(30L)); Condition<QueryModel> LIST_ANDING_OF_INLINE_ORING = QueryModel.QueryModelPredef .and(myString().eq("Thing").or().myLong().doesNotExist(), myString().ne("Cats").or().myLong().gt(30L)); Condition<QueryModel> LIST_ANDING_OR_LIST_ORING = QueryModel.QueryModelPredef .and(myString().eq("Thing").or().myLong().doesNotExist(), myString().ne("Cats").or().myLong().gt(30L)).or() .or(myString().eq("Thing").and().myLong().doesNotExist(), myString().ne("Cats").and().myLong().gt(30L)); Condition<QueryModel> LIST_ORING_ANDLIST_ANDING = QueryModel.QueryModelPredef .or(myString().eq("Thing").and().myLong().doesNotExist(), myString().ne("Cats").and().myLong().gt(30L)).and() .and(myString().eq("Thing").or().myLong().doesNotExist(), myString().ne("Cats").or().myLong().gt(30L)); } protected interface Chained { Condition<QueryModel> CHAINED_ANDS = myString().eq("thing").and().myInteger().gt(0) .and().myInteger().lt(5).and().myLong().in(0L, 1L, 2L).and().myDouble().lte(2.9) .and().myBoolean().isFalse().and().myDateTime().doesNotExist(); Condition<QueryModel> CHAINED_ORS = myString().eq("thing").or().myInteger().gt(0).or() .myInteger().lt(5).or().myLong().in(0L, 1L, 2L).or().myDouble().lte(2.9).or() .myBoolean().isFalse().or().myDateTime().doesNotExist(); Condition<QueryModel> CHAINED_ANDS_AND_ORS = myString().eq("thing").and().myInteger() .gt(0).or().myInteger().lt(5).or().myLong().in(0L, 1L, 2L).and().myDouble() .lte(2.9).and().myBoolean().isFalse().or().myDateTime().doesNotExist(); Condition<QueryModel> CHAINED_ORS_AND_ANDS = myString().eq("thing").or().myInteger() .gt(0).and().myInteger().lt(5).and().myLong().in(0L, 1L, 2L).or().myDouble() .lte(2.9).or().myBoolean().isFalse().and().myDateTime().doesNotExist(); } protected interface Composed { Condition<QueryModel> SUB_QUERY = mySubList().any(Logical.INLINE_ANDING).and().myBoolean().isTrue(); } protected interface VariedInputs { Condition<QueryModel> NULL_EQUALITY = myString().eq(null); Condition<QueryModel> NULL_INEQUALITY = myString().ne(null); } protected String Enum_EQ; protected String Enum_NE; protected String Enum_EX; protected String Enum_DNE; protected String Enum_IN; protected String Enum_NIN; @Test public void simple_Enum() { compare(Enum_EQ, Simple.Enum.EQ); compare(Enum_NE, Simple.Enum.NE); compare(Enum_EX, Simple.Enum.EX); compare(Enum_DNE, Simple.Enum.DNE); compare(Enum_IN, Simple.Enum.IN); compare(Enum_NIN, Simple.Enum.NIN); } protected String String_EQ; protected String String_NE; protected String String_LT; protected String String_GT; protected String String_LTE; protected String String_GTE; protected String String_EX; protected String String_DNE; protected String String_IN; protected String String_NIN; protected String String_RE; @Test public void simple_String() { compare(String_EQ, Simple.String.EQ); compare(String_NE, Simple.String.NE); compare(String_LT, Simple.String.LT); compare(String_GT, Simple.String.GT); compare(String_LTE, Simple.String.LTE); compare(String_GTE, Simple.String.GTE); compare(String_EX, Simple.String.EX); compare(String_DNE, Simple.String.DNE); compare(String_IN, Simple.String.IN); compare(String_NIN, Simple.String.NIN); compare(String_RE, Simple.String.RE); } protected String Boolean_TRUE; protected String Boolean_FALSE; protected String Boolean_EX; protected String Boolean_DNE; @Test public void simple_Boolean() { compare(Boolean_TRUE, Simple.Boolean.TRUE); compare(Boolean_FALSE, Simple.Boolean.FALSE); compare(Boolean_EX, Simple.Boolean.EX); compare(Boolean_DNE, Simple.Boolean.DNE); } protected String Short_EQ; protected String Short_NE; protected String Short_LT; protected String Short_GT; protected String Short_LTE; protected String Short_GTE; protected String Short_EX; protected String Short_DNE; protected String Short_IN; protected String Short_NIN; @Test public void simple_Short() { compare(Short_EQ, Simple.Short.EQ); compare(Short_NE, Simple.Short.NE); compare(Short_LT, Simple.Short.LT); compare(Short_LTE, Simple.Short.LTE); compare(Short_GT, Simple.Short.GT); compare(Short_GTE, Simple.Short.GTE); compare(Short_EX, Simple.Short.EX); compare(Short_DNE, Simple.Short.DNE); compare(Short_IN, Simple.Short.IN); compare(Short_NIN, Simple.Short.NIN); } protected String Integer_EQ; protected String Integer_NE; protected String Integer_LT; protected String Integer_GT; protected String Integer_LTE; protected String Integer_GTE; protected String Integer_EX; protected String Integer_DNE; protected String Integer_IN; protected String Integer_NIN; @Test public void simple_Integer() { compare(Integer_EQ, Simple.Integer.EQ); compare(Integer_NE, Simple.Integer.NE); compare(Integer_LT, Simple.Integer.LT); compare(Integer_LTE, Simple.Integer.LTE); compare(Integer_GT, Simple.Integer.GT); compare(Integer_GTE, Simple.Integer.GTE); compare(Integer_EX, Simple.Integer.EX); compare(Integer_DNE, Simple.Integer.DNE); compare(Integer_IN, Simple.Integer.IN); compare(Integer_NIN, Simple.Integer.NIN); } protected String Long_EQ; protected String Long_NE; protected String Long_LT; protected String Long_GT; protected String Long_LTE; protected String Long_GTE; protected String Long_EX; protected String Long_DNE; protected String Long_IN; protected String Long_NIN; @Test public void simple_Long() { compare(Long_EQ, Simple.Long.EQ); compare(Long_NE, Simple.Long.NE); compare(Long_LT, Simple.Long.LT); compare(Long_LTE, Simple.Long.LTE); compare(Long_GT, Simple.Long.GT); compare(Long_GTE, Simple.Long.GTE); compare(Long_EX, Simple.Long.EX); compare(Long_DNE, Simple.Long.DNE); compare(Long_IN, Simple.Long.IN); compare(Long_NIN, Simple.Long.NIN); } protected String Float_EQ; protected String Float_NE; protected String Float_LT; protected String Float_GT; protected String Float_LTE; protected String Float_GTE; protected String Float_EX; protected String Float_DNE; protected String Float_IN; protected String Float_NIN; @Test public void simple_Float() { compare(Float_EQ, Simple.Float.EQ); compare(Float_NE, Simple.Float.NE); compare(Float_LT, Simple.Float.LT); compare(Float_LTE, Simple.Float.LTE); compare(Float_GT, Simple.Float.GT); compare(Float_GTE, Simple.Float.GTE); compare(Float_EX, Simple.Float.EX); compare(Float_DNE, Simple.Float.DNE); compare(Float_IN, Simple.Float.IN); compare(Float_NIN, Simple.Float.NIN); } protected String Double_EQ; protected String Double_NE; protected String Double_LT; protected String Double_GT; protected String Double_LTE; protected String Double_GTE; protected String Double_EX; protected String Double_DNE; protected String Double_IN; protected String Double_NIN; @Test public void simple_Double() { compare(Double_EQ, Simple.Double.EQ); compare(Double_NE, Simple.Double.NE); compare(Double_LT, Simple.Double.LT); compare(Double_LTE, Simple.Double.LTE); compare(Double_GT, Simple.Double.GT); compare(Double_GTE, Simple.Double.GTE); compare(Double_EX, Simple.Double.EX); compare(Double_DNE, Simple.Double.DNE); compare(Double_IN, Simple.Double.IN); compare(Double_NIN, Simple.Double.NIN); } protected String DateTime_EQ; protected String DateTime_NE; protected String DateTime_LT; protected String DateTime_GT; protected String DateTime_LTE; protected String DateTime_GTE; protected String DateTime_EX; protected String DateTime_DNE; protected String DateTime_BETWEEN; @Test public void simple_DateTime() { compare(DateTime_EQ, Simple.Instant.EQ); compare(DateTime_NE, Simple.Instant.NE); compare(DateTime_LT, Simple.Instant.LT); compare(DateTime_LTE, Simple.Instant.LTE); compare(DateTime_GT, Simple.Instant.GT); compare(DateTime_GTE, Simple.Instant.GTE); compare(DateTime_EX, Simple.Instant.EX); compare(DateTime_DNE, Simple.Instant.DNE); compare(DateTime_BETWEEN, Simple.Instant.BETWEEN); } protected String INLINE_ANDING; @Test public void inline_Anding() { compare(INLINE_ANDING, Logical.INLINE_ANDING); } protected String INLINE_ORING; @Test public void inline_Oring() { compare(INLINE_ORING, Logical.INLINE_ORING); } protected String LIST_ANDING; @Test public void list_Anding() { compare(LIST_ANDING, Logical.LIST_ANDING); } protected String LIST_ORING; @Test public void list_Oring() { compare(LIST_ORING, Logical.LIST_ORING); } protected String LIST_ORING_OF_INLINE_ANDING; @Test public void listOringOfInlineAnding() { compare(LIST_ORING_OF_INLINE_ANDING, Logical.LIST_ORING_OF_INLINE_ANDING); } protected String LIST_ANDING_OF_INLINE_ORING; @Test public void listAndingOfInlineOring() { compare(LIST_ANDING_OF_INLINE_ORING, Logical.LIST_ANDING_OF_INLINE_ORING); } protected String LIST_ANDING_OR_LIST_ORING; @Test public void listAndingOrListOring() { compare(LIST_ANDING_OR_LIST_ORING, Logical.LIST_ANDING_OR_LIST_ORING); } protected String LIST_ORING_AND_LIST_ANDING; @Test public void listOringAndListAnding() { compare(LIST_ORING_AND_LIST_ANDING, Logical.LIST_ORING_ANDLIST_ANDING); } protected String CHAINED_ANDS; @Test public void chainedAnds() { compare(CHAINED_ANDS, Chained.CHAINED_ANDS); } protected String CHAINED_ORS; @Test public void chainedOrs() { compare(CHAINED_ORS, Chained.CHAINED_ORS); } protected String CHAINED_ANDS_AND_ORS; @Test public void chainedAndsAndOrs() { compare(CHAINED_ANDS_AND_ORS, Chained.CHAINED_ANDS_AND_ORS); } protected String CHAINED_ORS_AND_ANDS; @Test public void chainedOrsAndAnds() { compare(CHAINED_ORS_AND_ANDS, Chained.CHAINED_ORS_AND_ANDS); } protected String SUB_QUERY; @Test public void subquery() { compare(SUB_QUERY, Composed.SUB_QUERY); } protected String NULL_EQUALITY; protected String NULL_INEQUALITY; @Test public void variedInputs() { compare(NULL_EQUALITY, VariedInputs.NULL_EQUALITY); compare(NULL_INEQUALITY, VariedInputs.NULL_INEQUALITY); } protected U getContext() { return null; } protected void compare(String expected, Condition<QueryModel> condition) { T visitor = getVisitor(); compare(expected, condition.query(visitor, getContext())); } } <|start_filename|>src/main/java/com/github/rutledgepaulv/qbuilders/delegates/virtual/NumberPropertyDelegate.java<|end_filename|> /* * * * com.github.rutledgepaulv.qbuilders.delegates.virtual.NumberPropertyDelegate * * * * * * Copyright (C) 2016 <NAME> <<EMAIL>> * * * * * * This software may be modified and distributed under the terms * * * of the MIT license. See the LICENSE file for details. * * * */ package com.github.rutledgepaulv.qbuilders.delegates.virtual; import com.github.rutledgepaulv.qbuilders.builders.QBuilder; import com.github.rutledgepaulv.qbuilders.conditions.Condition; import com.github.rutledgepaulv.qbuilders.operators.ComparisonOperator; import com.github.rutledgepaulv.qbuilders.properties.virtual.NumberProperty; import com.github.rutledgepaulv.qbuilders.structures.FieldPath; import java.util.Collections; public abstract class NumberPropertyDelegate<T extends QBuilder<T>, S extends Number> extends ListablePropertyDelegate<T, S> implements NumberProperty<T, S> { protected NumberPropertyDelegate(FieldPath field, T canonical) { super(field, canonical); } public final Condition<T> gt(S number) { return condition(getField(), ComparisonOperator.GT, Collections.singletonList(number)); } public final Condition<T> lt(S number) { return condition(getField(), ComparisonOperator.LT, Collections.singletonList(number)); } public final Condition<T> gte(S number) { return condition(getField(), ComparisonOperator.GTE, Collections.singletonList(number)); } public final Condition<T> lte(S number) { return condition(getField(), ComparisonOperator.LTE, Collections.singletonList(number)); } } <|start_filename|>src/main/java/com/github/rutledgepaulv/qbuilders/properties/concrete/EnumProperty.java<|end_filename|> /* * * * com.github.rutledgepaulv.qbuilders.properties.concrete.EnumProperty * * * * * * Copyright (C) 2016 <NAME> <<EMAIL>> * * * * * * This software may be modified and distributed under the terms * * * of the MIT license. See the LICENSE file for details. * * * */ package com.github.rutledgepaulv.qbuilders.properties.concrete; import com.github.rutledgepaulv.qbuilders.builders.QBuilder; import com.github.rutledgepaulv.qbuilders.properties.virtual.EquitableProperty; import com.github.rutledgepaulv.qbuilders.properties.virtual.ListableProperty; /** * A property view for fields with {@link Enum} values. * * @param <T> The type of the final builder. */ public interface EnumProperty<T extends QBuilder<T>, S extends Enum<S>> extends ListableProperty<T,S>, EquitableProperty<T, S> {} <|start_filename|>src/main/java/com/github/rutledgepaulv/qbuilders/delegates/concrete/StringPropertyDelegate.java<|end_filename|> /* * * * com.github.rutledgepaulv.qbuilders.delegates.concrete.StringPropertyDelegate * * * * * * Copyright (C) 2016 <NAME> <<EMAIL>> * * * * * * This software may be modified and distributed under the terms * * * of the MIT license. See the LICENSE file for details. * * * */ package com.github.rutledgepaulv.qbuilders.delegates.concrete; import com.github.rutledgepaulv.qbuilders.builders.QBuilder; import com.github.rutledgepaulv.qbuilders.conditions.Condition; import com.github.rutledgepaulv.qbuilders.delegates.virtual.ListablePropertyDelegate; import com.github.rutledgepaulv.qbuilders.operators.ComparisonOperator; import com.github.rutledgepaulv.qbuilders.properties.concrete.StringProperty; import com.github.rutledgepaulv.qbuilders.structures.FieldPath; import java.util.Collections; public final class StringPropertyDelegate<T extends QBuilder<T>> extends ListablePropertyDelegate<T, String> implements StringProperty<T> { public StringPropertyDelegate(FieldPath field, T canonical) { super(field, canonical); } public final Condition<T> lexicallyAfter(String value) { return condition(getField(), ComparisonOperator.GT, Collections.singletonList(value)); } public final Condition<T> lexicallyBefore(String value) { return condition(getField(), ComparisonOperator.LT, Collections.singletonList(value)); } public final Condition<T> lexicallyNotAfter(String value) { return condition(getField(), ComparisonOperator.LTE, Collections.singletonList(value)); } public final Condition<T> lexicallyNotBefore(String value) { return condition(getField(), ComparisonOperator.GTE, Collections.singletonList(value)); } public Condition<T> pattern(String pattern) { return condition(getField(), ComparisonOperator.RE, Collections.singletonList(pattern)); } } <|start_filename|>src/main/java/com/github/rutledgepaulv/qbuilders/utilities/ObjectUtils.java<|end_filename|> /* * * * com.github.rutledgepaulv.qbuilders.utilities.ObjectUtils * * * * * * Copyright (C) 2016 <NAME> <<EMAIL>> * * * * * * This software may be modified and distributed under the terms * * * of the MIT license. See the LICENSE file for details. * * * */ package com.github.rutledgepaulv.qbuilders.utilities; import java.lang.reflect.InvocationTargetException; import java.util.Arrays; import java.util.Objects; import java.util.stream.IntStream; @SuppressWarnings({"unchecked", "Convert2MethodRef"}) public final class ObjectUtils { /** * Instantiate a class for the provided constructor arguments. * * @param clazz The class to instantiate * * @param args The arguments for the constructor. * The constructor used will be determined from the arguments provided. * * @param <T> The type of the provided class and resulting instance. * * @return The new instance. */ public static <T> T init(Class<T> clazz, Object... args) { try { final Object[] arguments = args != null ? args : new Object[]{}; return (T) Arrays.stream(clazz.getConstructors()) .filter(construct -> Objects.equals(arguments.length, construct.getParameterCount())) .filter(construct -> IntStream.range(0, arguments.length) .allMatch(val -> construct.getParameterTypes()[val].isAssignableFrom(arguments[val].getClass()))) .findFirst().orElseThrow(() -> new InstantiationException("Could not find compatible constructor.")) .newInstance(arguments); } catch (InstantiationException | InvocationTargetException | IllegalAccessException e) { throw new RuntimeException("Could not instantiate class for provided arguments.", e); } } } <|start_filename|>src/main/java/com/github/rutledgepaulv/qbuilders/delegates/concrete/ShortPropertyDelegate.java<|end_filename|> /* * * * com.github.rutledgepaulv.qbuilders.delegates.concrete.ShortPropertyDelegate * * * * * * Copyright (C) 2016 <NAME> <<EMAIL>> * * * * * * This software may be modified and distributed under the terms * * * of the MIT license. See the LICENSE file for details. * * * */ package com.github.rutledgepaulv.qbuilders.delegates.concrete; import com.github.rutledgepaulv.qbuilders.builders.QBuilder; import com.github.rutledgepaulv.qbuilders.delegates.virtual.NumberPropertyDelegate; import com.github.rutledgepaulv.qbuilders.properties.concrete.ShortProperty; import com.github.rutledgepaulv.qbuilders.structures.FieldPath; public final class ShortPropertyDelegate<T extends QBuilder<T>> extends NumberPropertyDelegate<T, Short> implements ShortProperty<T> { public ShortPropertyDelegate(FieldPath field, T canonical) { super(field, canonical); } } <|start_filename|>src/test/java/com/github/rutledgepaulv/qbuilders/utilities/ObjectUtilsTest.java<|end_filename|> /* * * * com.github.rutledgepaulv.qbuilders.utilities.ObjectUtilsTest * * * * * * Copyright (C) 2016 <NAME> <<EMAIL>> * * * * * * This software may be modified and distributed under the terms * * * of the MIT license. See the LICENSE file for details. * * * */ package com.github.rutledgepaulv.qbuilders.utilities; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; public class ObjectUtilsTest { private static class WithNoVisibleConstructor { private WithNoVisibleConstructor(){} } public static class SinglePlainArgument { public SinglePlainArgument(String value) { } } @Test public void noVisibleConstructor() throws Exception { expect("Could not instantiate class for provided arguments.", () -> ObjectUtils.init(WithNoVisibleConstructor.class)); } @Test public void noArgumentsProvided() throws Exception { expect("Could not instantiate class for provided arguments.", () -> ObjectUtils.init(SinglePlainArgument.class)); } @Test public void wrongArgumentTypesProvided() throws Exception { expect("Could not instantiate class for provided arguments.", () -> ObjectUtils.init(SinglePlainArgument.class, (Integer) 55)); } @Test public void correctTypeProvided() throws Exception { SinglePlainArgument instance = ObjectUtils.init(SinglePlainArgument.class, "stuff"); assertNotNull(instance); } private void expect(String message, Runnable runnable) { try { runnable.run(); } catch(Exception e) { assertTrue(e instanceof RuntimeException); assertEquals(message, e.getMessage()); } } } <|start_filename|>src/main/java/com/github/rutledgepaulv/qbuilders/visitors/AbstractVoidContextNodeVisitor.java<|end_filename|> /* * * * com.github.rutledgepaulv.qbuilders.visitors.AbstractVoidContextNodeVisitor * * * * * * Copyright (C) 2016 <NAME> <<EMAIL>> * * * * * * This software may be modified and distributed under the terms * * * of the MIT license. See the LICENSE file for details. * * * */ package com.github.rutledgepaulv.qbuilders.visitors; import com.github.rutledgepaulv.qbuilders.nodes.*; @SuppressWarnings("ConstantConditions") public abstract class AbstractVoidContextNodeVisitor<T> extends ContextualNodeVisitor<T, Void> { @Override protected final T visit(AndNode node, Void context) { return visit(node); } @Override protected final T visit(OrNode node, Void context) { return visit(node); } @Override protected final T visit(ComparisonNode node, Void context) { return visit(node); } protected abstract T visit(AndNode node); protected abstract T visit(OrNode node); protected abstract T visit(ComparisonNode node); protected T condition(ComparisonNode node) { return condition(node, null); } public final T visitAny(AbstractNode node) { return visitAny(node, null); } } <|start_filename|>src/main/java/com/github/rutledgepaulv/qbuilders/properties/virtual/NumberProperty.java<|end_filename|> /* * * * com.github.rutledgepaulv.qbuilders.properties.virtual.NumberProperty * * * * * * Copyright (C) 2016 <NAME> <<EMAIL>> * * * * * * This software may be modified and distributed under the terms * * * of the MIT license. See the LICENSE file for details. * * * */ package com.github.rutledgepaulv.qbuilders.properties.virtual; import com.github.rutledgepaulv.qbuilders.builders.QBuilder; import com.github.rutledgepaulv.qbuilders.conditions.Condition; /** * For numerical fields. * * @param <T> The final type of the builder. * @param <S> The type of the numbers that the property supports. */ public interface NumberProperty<T extends QBuilder<T>, S extends Number> extends ListableProperty<T, S>, EquitableProperty<T, S> { /** * Specifies that the field's value must be greater than the provided value. * @param number The value that the field's value must be greater than. * @return The logically complete condition. */ Condition<T> gt(S number); /** * Specifies that the field's value must be less than the provided value. * @param number The value that the field's value must be less than. * @return The logically complete condition. */ Condition<T> lt(S number); /** * Specifies that the field's value must be greater than or equal to the provided value. * @param number The value that the field's value must be greater than or equal to. * @return The logically complete condition. */ Condition<T> gte(S number); /** * Specifies that the field's value must be less than or equal to the provided value. * @param number The value that the field's value must be less than or equal to. * @return The logically complete condition. */ Condition<T> lte(S number); } <|start_filename|>src/main/java/com/github/rutledgepaulv/qbuilders/properties/virtual/ListableProperty.java<|end_filename|> /* * * * com.github.rutledgepaulv.qbuilders.properties.virtual.ListableProperty * * * * * * Copyright (C) 2016 <NAME> <<EMAIL>> * * * * * * This software may be modified and distributed under the terms * * * of the MIT license. See the LICENSE file for details. * * * */ package com.github.rutledgepaulv.qbuilders.properties.virtual; import com.github.rutledgepaulv.qbuilders.builders.QBuilder; import com.github.rutledgepaulv.qbuilders.conditions.Condition; import java.util.Collection; /** * For acting against a field via a list of values. */ public interface ListableProperty<T extends QBuilder<T>, S> extends Property<T> { /** * Specifies that the field's value must occur at least once in the list of provided values. * * @param values The values that make up the set of things that the field's value must occur in. * @return The logically complete condition. */ Condition<T> in(S... values); /** * Specifies that the field's value must occur at least once in the list of provided values. * * @param values The values that make up the set of things that the field's value must occur in. * @return The logically complete condition. */ Condition<T> in(Collection<S> values); /** * Specifies that the field's value must never occur in the list of provided values. * * @param values The values that make up the set of things that the field's value must never occur in. * @return The logically complete condition. */ Condition<T> nin(S... values); /** * Specifies that the field's value must never occur in the list of provided values. * * @param values The values that make up the set of things that the field's value must never occur in. * @return The logically complete condition. */ Condition<T> nin(Collection<S> values); } <|start_filename|>src/test/java/com/github/rutledgepaulv/qbuilders/operators/ComparisonOperatorTest.java<|end_filename|> /* * * * com.github.rutledgepaulv.qbuilders.operators.ComparisonOperatorTest * * * * * * Copyright (C) 2016 <NAME> <<EMAIL>> * * * * * * This software may be modified and distributed under the terms * * * of the MIT license. See the LICENSE file for details. * * * */ package com.github.rutledgepaulv.qbuilders.operators; import com.github.rutledgepaulv.qbuilders.operators.ComparisonOperator; import org.junit.Test; import static org.junit.Assert.assertNotEquals; public class ComparisonOperatorTest { @Test public void testEquals() throws Exception { ComparisonOperator operator1 = new ComparisonOperator(null); ComparisonOperator operator2 = new ComparisonOperator("dogs"); assertNotEquals(operator1, operator2); } @Test public void testHashCodes() { ComparisonOperator operator1 = new ComparisonOperator(null); ComparisonOperator operator2 = new ComparisonOperator("cats"); assertNotEquals(operator1.hashCode(), operator2.hashCode()); } } <|start_filename|>src/main/java/com/github/rutledgepaulv/qbuilders/nodes/Visitable.java<|end_filename|> /* * * * com.github.rutledgepaulv.qbuilders.nodes.Visitable * * * * * * Copyright (C) 2016 <NAME> <<EMAIL>> * * * * * * This software may be modified and distributed under the terms * * * of the MIT license. See the LICENSE file for details. * * * */ package com.github.rutledgepaulv.qbuilders.nodes; import com.github.rutledgepaulv.qbuilders.visitors.ContextualNodeVisitor; public interface Visitable { default <T> T visit(ContextualNodeVisitor<T,Void> visitor) { return visit(visitor, null); } <T,S> T visit(ContextualNodeVisitor<T,S> visitor, S context); } <|start_filename|>src/main/java/com/github/rutledgepaulv/qbuilders/builders/QBuilder.java<|end_filename|> /* * * * com.github.rutledgepaulv.qbuilders.builders.QBuilder * * * * * * Copyright (C) 2016 <NAME> <<EMAIL>> * * * * * * This software may be modified and distributed under the terms * * * of the MIT license. See the LICENSE file for details. * * * */ package com.github.rutledgepaulv.qbuilders.builders; import com.github.rutledgepaulv.qbuilders.conditions.Condition; import com.github.rutledgepaulv.qbuilders.conditions.Partial; import com.github.rutledgepaulv.qbuilders.delegates.concrete.*; import com.github.rutledgepaulv.qbuilders.delegates.virtual.Delegate; import com.github.rutledgepaulv.qbuilders.delegates.virtual.PropertyDelegate; import com.github.rutledgepaulv.qbuilders.nodes.*; import com.github.rutledgepaulv.qbuilders.operators.ComparisonOperator; import com.github.rutledgepaulv.qbuilders.properties.concrete.*; import com.github.rutledgepaulv.qbuilders.properties.virtual.Property; import com.github.rutledgepaulv.qbuilders.structures.FieldPath; import com.github.rutledgepaulv.qbuilders.utilities.ObjectUtils; import com.github.rutledgepaulv.qbuilders.visitors.ContextualNodeVisitor; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.stream.Collectors; import static java.util.Arrays.asList; /** * The single class that can be used to construct an abstract representation of a query. Designed * to be extended for each domain model that might be queried against, with each field exposed as * a property condition builder. * * @param <T> The final type of the builder, used for a fluid chaining interface. */ @SuppressWarnings("unchecked") public class QBuilder<T extends QBuilder<T>> implements Partial<T> { protected LogicalNode root; protected LogicalNode current; public QBuilder() { root = current = new OrNode(); } public final <S extends Enum<S>> EnumProperty<T,S> enumeration(String field) { return prop(field, EnumPropertyDelegate.class, EnumProperty.class); } public final BooleanProperty<T> bool(String field) { return prop(field, BooleanPropertyDelegate.class, BooleanProperty.class); } public final StringProperty<T> string(String field) { return prop(field, StringPropertyDelegate.class, StringProperty.class); } public final ShortProperty<T> shortNum(String field) { return prop(field, ShortPropertyDelegate.class, ShortProperty.class); } public final IntegerProperty<T> intNum(String field) { return prop(field, IntegerPropertyDelegate.class, IntegerProperty.class); } public final LongProperty<T> longNum(String field) { return prop(field, LongPropertyDelegate.class, LongProperty.class); } public final FloatProperty<T> floatNum(String field) { return prop(field, FloatPropertyDelegate.class, FloatProperty.class); } public final DoubleProperty<T> doubleNum(String field) { return prop(field, DoublePropertyDelegate.class, DoubleProperty.class); } public final InstantProperty<T> instant(String field) { return prop(field, InstantPropertyDelegate.class, InstantProperty.class); } public final <S extends QBuilder<S>> ConditionProperty<T, S> condition(String field) { return prop(field, ConditionPropertyDelegate.class, ConditionProperty.class); } protected final <S extends PropertyDelegate<T>, Q extends Property<T>> Q prop(String field, Class<S> delegate, Class<Q> inter) { if(!inter.isAssignableFrom(delegate)) { throw new IllegalArgumentException("Must provide a delegate that implements the interface to be returned."); } return (Q) ObjectUtils.init(delegate, new FieldPath(field), self()); } @SafeVarargs public final Condition<T> and(Condition<T> c1, Condition<T> c2, Condition<T>... cn) { List<Condition<T>> conditions = new ArrayList<>(); conditions.addAll(asList(c1,c2)); conditions.addAll(asList(cn)); return and(conditions); } @SafeVarargs public final Condition<T> or(Condition<T> c1, Condition<T> c2, Condition<T>... cn) { List<Condition<T>> conditions = new ArrayList<>(); conditions.addAll(asList(c1,c2)); conditions.addAll(asList(cn)); return or(conditions); } public final Condition<T> and(List<Condition<T>> conditions) { return combine(conditions, AndNode.class); } public final Condition<T> or(List<Condition<T>> conditions) { return combine(conditions, OrNode.class); } private <S extends LogicalNode> Condition<T> combine(List<Condition<T>> conditions, Class<S> type) { List<AbstractNode> children = conditions.stream() .map(condition -> ((QBuilder<T>) condition).self().current) .collect(Collectors.toList()); S node = ObjectUtils.init(type, self().current, children); self().current.getChildren().add(node); return new ConditionDelegate(self()); } /** * Call this method to add a condition to the current logical node of the underlying query tree. * * @param field The field that this condition belongs to. * @param operator The operator indicating how the values provided should be interpreted against the field. * @param values The values to use in the comparison against the value of the field. * * @return A completed {@link Condition} that can be built into a query or logically composed into other conditions. */ protected final Condition<T> condition(FieldPath field, ComparisonOperator operator, Collection<?> values) { ComparisonNode node = new ComparisonNode(self().current); node.setField(field); node.setOperator(operator); node.setValues(values); self().current.getChildren().add(node); return new ConditionDelegate(self()); } /** * Since we have delegate classes that extend this class but not its potential end-user imposed subclasses * we instead pass the original instance of whatever the final QBuilder class is around as * a delegate which each view calls for any operations instead of calling 'this' thereby providing type safe * compatibility with extensions. * * @return The instance that should be modified on actions. */ protected T self() { return (T) this; } /** * A delegate view of this builder that represents a logically complete condition. A logically complete * condition can either be directly built into a query or it can be composed with other conditions in * the form of 'AND' or 'OR' */ protected final class ConditionDelegate extends Delegate<T> implements Condition<T> { private ConditionDelegate(T canonical) { super(canonical); } public final T and() { QBuilder<T> self = self(); LogicalNode current = self.current; if(!(current instanceof AndNode)) { List<AbstractNode> children = new ArrayList<>(); children.add(current); AndNode node = new AndNode(current.getParent(), children); // referential comparison intended. if (current == self.root) { self.root = node; } self.current = node; } return (T) self; } public final T or() { QBuilder<T> self = self(); LogicalNode current = self.current; if(!(current instanceof OrNode)) { List<AbstractNode> children = new ArrayList<>(); children.add(current); OrNode node = new OrNode(current.getParent(), children); // referential comparison intended. if (current == self.root) { self.root = node; } self.current = node; } return (T) self; } public final <Q> Q query(ContextualNodeVisitor<Q,Void> visitor) { QBuilder<T> self = self(); return self.root.visit(visitor); } public final <Q,S> Q query(ContextualNodeVisitor<Q,S> visitor, S context) { QBuilder<T> self = self(); return self.root.visit(visitor, context); } public final LogicalNode getRootNode() { return self().root; } } } <|start_filename|>src/main/java/com/github/rutledgepaulv/qbuilders/properties/virtual/Property.java<|end_filename|> /* * * * com.github.rutledgepaulv.qbuilders.properties.virtual.Property * * * * * * Copyright (C) 2016 <NAME> <<EMAIL>> * * * * * * This software may be modified and distributed under the terms * * * of the MIT license. See the LICENSE file for details. * * * */ package com.github.rutledgepaulv.qbuilders.properties.virtual; import com.github.rutledgepaulv.qbuilders.builders.QBuilder; /** * A marker interface for properties that have been defined. Properties * represent queryable field types and expose mechanisms to define the * constraints against hte field for the query. * * @param <T> The final type of the builder. */ @SuppressWarnings("unused") public interface Property<T extends QBuilder<T>> { } <|start_filename|>src/test/java/com/github/rutledgepaulv/qbuilders/structures/FieldPathTest.java<|end_filename|> /* * * * com.github.rutledgepaulv.qbuilders.structures.FieldPathTest * * * * * * Copyright (C) 2016 <NAME> <<EMAIL>> * * * * * * This software may be modified and distributed under the terms * * * of the MIT license. See the LICENSE file for details. * * * */ package com.github.rutledgepaulv.qbuilders.structures; import org.junit.Test; import java.util.List; import static java.util.stream.Collectors.*; import static org.junit.Assert.*; public class FieldPathTest { private FieldPath it = new FieldPath("com.github.rutledgepaulv.myList"); @Test public void iterator() throws Exception { List<String> segments = it.stream().flatMap(FieldPath.FieldNamespace::stream).collect(toList()); assertEquals("com", segments.get(0)); assertEquals("github", segments.get(1)); assertEquals("rutledgepaulv", segments.get(2)); assertEquals("myList", segments.get(3)); } @Test public void append_String() throws Exception { FieldPath oneMore = it.append("name"); assertEquals("com.github.rutledgepaulv.myList.name", oneMore.asFullyQualifiedKey()); assertEquals("name", oneMore.asKey()); FieldPath twoMore = it.append("name", "again"); assertEquals("com.github.rutledgepaulv.myList.name.again", twoMore.asFullyQualifiedKey()); assertEquals("again", twoMore.asKey()); } @Test public void append_Path() throws Exception { FieldPath oneMore = it.append(new FieldPath("name")); assertEquals("com.github.rutledgepaulv.myList.name", oneMore.asFullyQualifiedKey()); assertEquals("name", oneMore.asKey()); } @Test public void prepend_String() throws Exception { FieldPath oneMore = it.prepend("name"); assertEquals("name.com.github.rutledgepaulv.myList", oneMore.asFullyQualifiedKey()); assertEquals("com.github.rutledgepaulv.myList", oneMore.asKey()); } @Test public void prepend_Path() throws Exception { FieldPath oneMore = it.prepend(new FieldPath("name")); assertEquals("name.com.github.rutledgepaulv.myList", oneMore.asFullyQualifiedKey()); assertEquals("com.github.rutledgepaulv.myList", oneMore.asKey()); } @Test public void asFullyQualifiedPrefix() throws Exception { FieldPath oneMore = it.append("name"); assertEquals("com.github.rutledgepaulv.myList.", it.asFullyQualifiedPrefix()); assertEquals("com.github.rutledgepaulv.myList.name.", oneMore.asFullyQualifiedPrefix()); } @Test public void asFullyQualifiedKey() throws Exception { FieldPath oneMore = it.append("name"); assertEquals("com.github.rutledgepaulv.myList", it.asFullyQualifiedKey()); assertEquals("com.github.rutledgepaulv.myList.name", oneMore.asFullyQualifiedKey()); } @Test public void asShortKey() throws Exception { FieldPath oneMore = it.append("name"); assertEquals("name", oneMore.asKey()); } @Test public void asShortPrefix() throws Exception { FieldPath oneMore = it.append("name"); assertEquals("name.", oneMore.asPrefix()); } @Test public void test_toString() throws Exception { FieldPath oneMore = it.append("name"); assertEquals("com.github.rutledgepaulv.myList.name", oneMore.toString()); } @Test public void testEquals() { FieldPath path = new FieldPath("test"); assertTrue(path.equals(path)); assertFalse(path.equals("cats")); assertFalse(path.equals(new FieldPath("bats"))); assertTrue(path.equals(new FieldPath("test"))); } @Test public void testHashCode() { FieldPath path = new FieldPath("test"); assertEquals(path.hashCode(), path.hashCode()); assertNotEquals(path.hashCode(), new FieldPath("badgers").hashCode()); } @Test public void testGetParentPath() { FieldPath path = it.append("name"); assertTrue(path.getParentPath().isPresent()); assertEquals("com.github.rutledgepaulv.myList", path.getParentPath().get().asFullyQualifiedKey()); } }
RutledgePaulV/q-builders
<|start_filename|>examples/gallery_usa_multi/gallery.json<|end_filename|> { "images_data_file": "./images_data.json", "public_path": "./public", "templates_path": "./templates", "images_path": "./public/images/photos", "thumbnails_path": "./public/images/thumbnails", "title": "USA Trip 2019", "description": "We took a road trip with an RV through California in May 2019. We visited many places, like Los Angeles, Joshua Tree National Park, Palm Springs, Sequoia and King's Canyon National Park, Fresno, Sacramento and San Francisco.", "thumbnail_height": 156, "background_photo": "usa-170.jpg", "url": "https://www.haltakov.net/gallery_usa_multi/CUPcTB5AcbutK3vyLQ26", "background_photo_offset": 20 } <|start_filename|>simplegallery/data/public/js/main.js<|end_filename|> var slides = {} function createSlides() { $("a.gallery-photo").each(function (photo_id, photo) { var slide = { w: photo.getAttribute('data-width'), h: photo.getAttribute('data-height'), msrc: photo.getElementsByTagName('img')[0].getAttribute('src'), title: photo.getElementsByTagName('img')[0].getAttribute('alt'), date: photo.getAttribute('data-date'), }; if (photo.getAttribute('data-type') == 'image') slide['src'] = photo.getAttribute('href'); else slide['html'] = '<video style="margin: 0px auto; height: 100%; max-width: 100%; max-height: 100%; display: block" data-index="' + photo.getAttribute('data-index') + '" controls><source src="' + photo.getAttribute('href') + '" type="video/mp4"></video>'; var gallery_id = photo.getAttribute('data-gallery'); if (!(gallery_id in slides)) slides[gallery_id] = []; slides[gallery_id].push(slide); }); } function getThumbBounds(gallery, index) { var thumbnail = $('div.gallery a[data-gallery="'+gallery+'"][data-index="'+index+'"]')[0]; var pageYScroll = window.pageYOffset || document.documentElement.scrollTop; var rect = thumbnail.getBoundingClientRect(); return {x: rect.left, y: rect.top + pageYScroll, w: rect.width}; } function addCaptionHTML(item, captionEl, isFake) { if(!item.title && !item.date) { captionEl.children[0].innerText = ''; return false; } captionEl.children[0].innerHTML = item.title; if (item.date) { captionEl.children[0].innerHTML += '<p class="caption-date">' + item.date + '</p>'; } return true; } function openPhotoSwipe() { var index = parseInt($(this).attr('data-index')) var gallery_id = $(this).attr('data-gallery') var options = { index: index, getThumbBoundsFn: function (id) { return getThumbBounds(gallery_id, id) }, addCaptionHTMLFn: addCaptionHTML, preload: [2,5], zoomEl: false, shareEl: true, barsSize: {top:0, bottom:0}, bgOpacity: 1, loop: false, mainClass: 'pswp--minimal--dark', shareButtons: [ {id:'download', label:'Download image', url:'{{raw_image_url}}', download:true} ], }; var gallery = new PhotoSwipe( $('.pswp')[0], PhotoSwipeUI_Default, slides[gallery_id], options); gallery.listen('initialZoomOut', function() { if (this.currItem.html) { var videos = $('div.pswp__item video[data-index='+this.getCurrentIndex()+']') if (videos.length > 0) videos[0].pause() } }); gallery.listen('afterChange', function() { var videos = $('div.pswp__item video') for (var i=0; i<videos.length; ++i) videos[i].pause() if (this.currItem.html) { var videos = $('div.pswp__item video[data-index='+this.getCurrentIndex()+']') if (videos.length > 0) videos[0].play() } }); gallery.init(); return false; } $( document ).ready(function() { createSlides() $('div.gallery a').on('click', openPhotoSwipe) }); <|start_filename|>examples/gallery_usa_simple/gallery.json<|end_filename|> { "images_data_file": "./images_data.json", "public_path": "./public", "templates_path": "./templates", "images_path": "./public/images/photos", "thumbnails_path": "./public/images/thumbnails", "title": "San Francisco 2019", "description": "We visited San Francisco for a couple of days in May 2019 as part of our California trip.", "thumbnail_height": 156, "background_photo": "usa-494.jpg", "url": "https://www.haltakov.net/gallery_usa_simple/qn3Sj4RidXdq2SqpCgJk", "background_photo_offset": 50 } <|start_filename|>simplegallery/data/public/css/main.css<|end_filename|> body { background-color: #eee; font-family: 'Source Sans Pro', sans-serif; } .gallery { display: flex; flex-wrap: wrap; } .gallery>a, .gallery::after { flex-basis: var(--w); } .gallery>a { margin: 0.25rem; flex-grow: calc(var(--w) / var(--h) * 100); width: calc(var(--w) * 1px); } .gallery::after { --w: 2; --h: 1; content: ''; flex-grow: 1000000; } .gallery>a>img { display: block; width: 100%; } .header-image { height: 400px; color: #eeeeee; padding: 0px; } .header-info { background-color: rgba(0, 0, 0, 0.5); width: 100%; height: 100%; padding-top: 100px; text-align: center; } .header-info-details h1 { font-size: 56px; } .header-info-details { border-top: 1px solid #eee; width: 80%; margin: 50px auto 0px; padding-top: 50px; font-size: 20px; } .gallery-section h2 { text-align: center; margin-top: 30px; } .gallery-section h2 a { visibility: hidden; color: #aaaaaa; } .gallery-section h2 a:hover { color: #0056b3; } .gallery-section:hover h2 a { visibility: visible; } .gallery-section h2 a svg { height: 1.2rem } .gallery-section p { width: 70%; margin: 0px auto 20px; } .caption-date { font-size: 15px; font-weight: normal; margin-top: 3px; margin-bottom: 0px; } footer { margin-top: 30px; }
kroesche/simple-photo-gallery
<|start_filename|>package.json<|end_filename|> { "name": "grids", "version": "0.0.1-alpha", "description": "A standard for grids comparison", "scripts": { "compile": "babel src -d --out-dir es5 --presets es2015", "test": "npm run compile && node es5/test.js", "render": "npm run compile && node es5/render.js" }, "repository": { "type": "git", "url": "git+https://github.com/AmitMY/grids.git" }, "keywords": [], "author": "AmitMY", "license": "MIT", "bugs": { "url": "https://github.com/AmitMY/grids/issues" }, "homepage": "https://github.com/AmitMY/grids#readme", "devDependencies": { "babel-cli": "latest", "babel-preset-es2015": "latest", "fs": "0.0.1-security", "js-prototypes": "latest", "sync-request": "^4.0.1", "tape": "latest" } } <|start_filename|>src/test.js<|end_filename|> import test from "tape"; import fs from "fs"; import {isURL} from "./helper"; const gridsFolder = "grids"; fs.readdir(gridsFolder, (err, files) => { let grids = []; files.forEach(file => { fs.readFile(gridsFolder + "/" + file, (err, data) => { grids.push(new GridFile(file, JSON.parse(data))); if (grids.length == files.length) grids.forEach(grid => grid.test()); }); }); }); const allowedFrameworks = ["Javascript", "jQuery", "Angular1", "Angular2", "React", "Aurelia", "Web Components", "Vue"]; const allowedFormats = ["CSV", "XLS", "XLSX", "PDF", "TSV", "JSON", "XML"]; const allowedFilters = ["Text", "Number", "Date", "Set", "Custom"]; const allowedAggregation = ["Sum", "Average", "Min", "Max", "First", "Last", "Custom"]; const allowedKeyboardKeys = ["Arrows", "Enter", "Tab", "Page", "Home", "End", "UNDO/REDO"]; const allowedVisualisations = ["Bubble", "Line", "Bar", "Candlestick", "Donut", "Funnel", "H-Bar", "Map", "OHLC", "Progress", "Pie", "Polar", "Waterfall", "Radar", "Scatter", "Spider", "Custom"]; class GridFile { constructor(file, data) { this.file = file; this.data = data; } test() { test(this.file + " is global information valid", (assert) => { assert.equal(typeof this.data.lastEditor.user, "string", "Grid's lastEditor.user must be a string"); assert.equal(typeof this.data.lastEditor.rank, "string", "Grid's lastEditor.rank must be a string"); assert.end(); }); this.testInfo(); this.testFeatures(); } testInfo() { let info = this.data.info; test(this.file + " Information should have all properties with the correct types", (assert) => { assert.equal(typeof info, "object", "Grid's info must be a string"); // Global information assert.equal(typeof info.name, "string", "Grid's info name must be a string"); if (info.logo !== null) { assert.equal(typeof info.logo, "string", "Grid's info logo must be a string"); assert.ok(isURL(info.logo), "Grid's info logo must be a URL"); } assert.equal(typeof info.description, "string", "Grid's info description must be a string"); assert.equal(typeof info.license, "string", "Grid's info license must be a string"); assert.equal(typeof info.price, "string", "Grid's info price must be a string"); assert.equal(typeof info.techSupport, "boolean", "Grid's info techSupport must be a boolean"); // Repository information if (info.repository !== null) { assert.equal(typeof info.repository, "string", "Grid's info repository link must be a string"); // TODO test if it is a valid github repo } // Website information if (info.website !== null) { assert.equal(typeof info.website, "object", "Grid's info website must be a object or null"); assert.equal(typeof info.website.link, "string", "Grid's info website link must be a string"); assert.ok(isURL(info.website.link), "Grid's info website link must be a URL"); assert.equal(typeof info.website.demo, "string", "Grid's info website demo must be a string"); assert.ok(isURL(info.website.demo), "Grid's info website demo must be a URL"); } // Frameworks assert.equal(Array.isArray(info.frameworks), true, "Grid's info frameworks must be an array"); info.frameworks.forEach(framework => { assert.notEqual(allowedFrameworks.indexOf(framework), -1, framework + " must be a familiar framework"); }); // Layouts if (info.layoutThemes !== null) assert.equal(Array.isArray(info.layoutThemes), true, "Grid's info layoutThemes must be an array"); assert.end(); }); } validateBooleansLinks(name, obj, booleans, assert) { const validBullLink = (val, nullable = false) => { if (nullable && val === null) return true; if (typeof val == "boolean") return true; return typeof val == "string" && isURL(val); }; // All booleans Object.keys(booleans).forEach(key => { if (!booleans[key]) { if (obj[key] !== null) assert.ok(validBullLink(obj[key]), "Grid's " + name + " " + key + " must be a boolean, a url or null"); } else assert.ok(validBullLink(obj[key]), "Grid's " + name + " " + key + " must be a boolean or a url"); }); } testFeatures() { let features = this.data.features; const booleans = { animations: false, customIcons: false, customOverlays: false, globalSearch: true, internationalisation: false, masterSlave: true, pagination: true, pivoting: true, print: true, RTLSupport: false, statusBar: true, touchSupport: true, virtualPagination: true }; test(this.file + " Features should have all properties with the correct types", (assert) => { assert.equal(typeof features, "object", "Grid's features must be a string"); this.validateBooleansLinks("features", features, booleans, assert); // Export if (features.export !== null) { assert.equal(Array.isArray(features.export), true, "Grid's features export must be an array"); features.export.forEach(format => { assert.notEqual(allowedFormats.indexOf(format), -1, format + " must be a familiar export format"); }); } // Visualisation if (features.visualisation !== null) { assert.equal(Array.isArray(features.visualisation), true, "Grid's features visualisation must be an array or null"); features.visualisation.forEach(chart => { assert.notEqual(allowedVisualisations.indexOf(chart), -1, chart + " must be a familiar chart type"); }); } assert.end(); }); this.testColumns(); this.testRows(); this.testCells(); } testColumns() { let columns = this.data.features.columns; const booleans = { menu: true, filtering: true, grouping: true, headerRendering: false, pinning: true, reorder: true, resizing: true, selection: true, sorting: true }; test(this.file + " Features columns should have all properties with the correct types", (assert) => { assert.equal(typeof columns, "object", "Grid's features columns must be a string"); this.validateBooleansLinks("columns", columns, booleans, assert); // Filters if (columns.filterTypes !== null) { assert.equal(Array.isArray(columns.filterTypes), true, "Grid's features columns filterTypes must be an array"); columns.filterTypes.forEach(filter => { assert.notEqual(allowedFilters.indexOf(filter), -1, filter + " must be a familiar filter type"); }); } // Aggregation if (columns.aggregation !== null) { assert.equal(Array.isArray(columns.aggregation), true, "Grid's features columns aggregation must be an array or null"); columns.aggregation.forEach(func => { assert.notEqual(allowedAggregation.indexOf(func), -1, func + " must be a familiar aggregation function"); }); } assert.end(); }); } testRows() { let rows = this.data.features.rows; const booleans = { contextMenu: true, dynamicHeight: true, dynamicInsert: true, dynamicRemove: true, floating: true, fullWidth: true, grouping: true, numbering: true, selection: true, virtualization: true }; test(this.file + " Features rows should have all properties with the correct types", (assert) => { assert.equal(typeof rows, "object", "Grid's features rows must be a string"); this.validateBooleansLinks("rows", rows, booleans, assert); assert.end(); }); } testCells() { let cells = this.data.features.cells; const booleans = { clipboard: true, customRendering: true, editing: true, formula: false, merge: true, validation: true, rangeSelection: true, styling: true }; test(this.file + " Features cells should have all properties with the correct types", (assert) => { assert.equal(typeof cells, "object", "Grid's features cells must be a string"); this.validateBooleansLinks("cells", cells, booleans, assert); // Aggregation if (cells.keyboardNavigation !== null) { assert.equal(Array.isArray(cells.keyboardNavigation), true, "Grid's features cells aggregation must be an array or null"); cells.keyboardNavigation.forEach(key => { assert.notEqual(allowedKeyboardKeys.indexOf(key), -1, key + " must be a familiar keyboard key/key-set"); }); } assert.end(); }); } } <|start_filename|>grids/ag-grid.json<|end_filename|> { "lastEditor": { "user": "AmitMY", "rank": "User" }, "info": { "name": "ag-Grid", "logo": "https://www.ag-grid.com/images/logo.png", "description": "Advanced Data Grid / Data Table", "license": "MIT", "repository": "ceolter/ag-grid", "website": { "link": "https://www.ag-grid.com/", "demo": "https://www.ag-grid.com/example.php" }, "price": "Free", "frameworks": [ "Javascript", "Angular1", "Angular2", "React", "Aurelia", "Web Components", "Vue" ], "layoutThemes": [ "Fresh", "Blue", "Dark", "Material", "Bootstrap", "Custom" ], "techSupport": false }, "features": { "animations": "https://www.ag-grid.com/javascript-grid-animation/#gsc.tab=0", "customIcons": "https://www.ag-grid.com/javascript-grid-icons/#gsc.tab=0", "customOverlays": "https://www.ag-grid.com/javascript-grid-overlays/#gsc.tab=0", "export": [ "CSV", "XLS" ], "globalSearch": "https://www.ag-grid.com/javascript-grid-filtering/#gsc.tab=0", "internationalisation": "https://www.ag-grid.com/javascript-grid-internationalisation/#gsc.tab=0", "masterSlave": "https://www.ag-grid.com/javascript-grid-master-slave/#gsc.tab=0", "pagination": "https://www.ag-grid.com/javascript-grid-pagination/#gsc.tab=0", "pivoting": false, "print": "https://www.ag-grid.com/javascript-grid-for-print/", "RTLSupport": "https://www.ag-grid.com/javascript-grid-rtl/", "statusBar": false, "touchSupport": "https://www.ag-grid.com/javascript-grid-touch/#gsc.tab=0", "virtualPagination": "https://www.ag-grid.com/javascript-grid-virtual-paging/#gsc.tab=0", "visualisation": null, "columns": { "aggregation": null, "collapsible": true, "menu": false, "filterTypes": [ "Text", "Number", "Date", "Custom" ], "filtering": "https://www.ag-grid.com/javascript-grid-filtering/#gsc.tab=0", "grouping": "https://www.ag-grid.com/javascript-grid-grouping-headers/", "headerRendering": "https://www.ag-grid.com/javascript-grid-header-rendering/", "pinning": "https://www.ag-grid.com/javascript-grid-pinning/", "reorder": true, "resizing": "https://www.ag-grid.com/javascript-grid-resizing/#gsc.tab=0", "selection": false, "sorting": "https://www.ag-grid.com/javascript-grid-sorting/" }, "rows": { "contextMenu": "https://www.ag-grid.com/javascript-grid-context-menu/#gsc.tab=0", "dynamicHeight": "https://www.ag-grid.com/javascript-grid-row-height/", "dynamicInsert": "https://www.ag-grid.com/javascript-grid-insert-remove/#gsc.tab=0", "dynamicRemove": "https://www.ag-grid.com/javascript-grid-insert-remove/#gsc.tab=0", "floating": "https://www.ag-grid.com/javascript-grid-floating/#gsc.tab=0", "fullWidth": "https://www.ag-grid.com/javascript-grid-master-detail/", "grouping": false, "numbering": false, "reorder": false, "selection": "https://www.ag-grid.com/javascript-grid-selection/#gsc.tab=0", "virtualization": true }, "cells": { "clipboard": false, "customRendering": "https://www.ag-grid.com/javascript-grid-cell-rendering/#gsc.tab=0", "editing": "https://www.ag-grid.com/javascript-grid-cell-editing/#gsc.tab=0", "formula": "https://www.ag-grid.com/javascript-grid-cell-expressions/#gsc.tab=0", "keyboardNavigation": [ "Arrows", "Enter", "Tab" ], "merge": false, "validation": false, "rangeSelection": false, "styling": "https://www.ag-grid.com/javascript-grid-cell-styling/#gsc.tab=0" } } } <|start_filename|>grids/jqxGrid.json<|end_filename|> { "lastEditor": { "user": "vvidolov", "rank": "JQWidgets Sales" }, "info": { "name": "jqxGrid", "logo": "http://www.jqwidgets.com/wp-content/design/i/logo-jqwidgets.svg", "description": "Advanced Data Grid ", "license": "https://www.jqwidgets.com/license/", "repository": "jqwidgets/jQWidgets", "website": { "link": "https://www.jqwidgets.com/", "demo": "https://www.jqwidgets.com/jquery-widgets-demo/demos/jqxgrid/index.htm" }, "price": " https://www.jqwidgets.com/license/", "frameworks": [ "jQuery", "Angular1", "Angular2", "React" ], "layoutThemes": [ "More than 20, including theme builder" ], "techSupport": true }, "features": { "animations": true, "customIcons": true, "customOverlays": true, "export": [ "CSV", "XLS", "PDF", "TSV", "JSON" ], "globalSearch": "https://www.jqwidgets.com/jquery-widgets-demo/demos/jqxgrid/filtering.htm", "internationalisation": "https://www.jqwidgets.com/jquery-widgets-demo/demos/jqxgrid/localization.htm", "masterSlave": "https://www.jqwidgets.com/jquery-widgets-demo/demos/jqxgrid/masterdetails.htm", "pagination": "https://www.jqwidgets.com/jquery-widgets-demo/demos/jqxgrid/defaultfunctionality.htm", "pivoting": false, "print": "https://www.jqwidgets.com/jquery-widgets-demo/demos/jqxgrid/printing.htm", "RTLSupport": "https://www.jqwidgets.com/jquery-widgets-demo/demos/jqxgrid/rtl.htm", "statusBar": "https://www.jqwidgets.com/jquery-widgets-demo/demos/jqxgrid/statusbar.htm", "touchSupport": "https://www.jqwidgets.com/jquery-widgets-demo/mobiledemos/jqxgrid/responsive-data-grid.htm", "virtualPagination": "https://www.jqwidgets.com/jquery-widgets-demo/demos/jqxgrid/deferredscrollinglargedata.htm", "visualisation": ["Line", "Bar", "H-Bar", "Waterfall", "OHLC", "Candlestick", "Pie", "Donut", "Polar", "Spider", "Bubble", "Scatter", "Funnel"], "columns": { "aggregation": ["Sum", "Average", "Min", "Max", "First", "Last", "Custom"], "collapsible": true, "menu": true, "filterTypes": [ "Text", "Number", "Date", "Custom" ], "filtering": "https://www.jqwidgets.com/jquery-widgets-demo/demos/jqxgrid/filtering-menu-column-types.htm", "grouping": "https://www.jqwidgets.com/jquery-widgets-demo/demos/jqxgrid/grouping.htm", "headerRendering": false, "pinning": "https://www.jqwidgets.com/jquery-widgets-demo/demos/jqxgrid/pinnedcolumns.htm", "reorder": "https://www.jqwidgets.com/jquery-widgets-demo/demos/jqxgrid/reordercolumns.htm", "resizing": "https://www.jqwidgets.com/jquery-widgets-demo/demos/jqxgrid/columnsresizing.htm", "selection": true, "sorting": "https://www.jqwidgets.com/jquery-widgets-demo/demos/jqxgrid/sorting.htm" }, "rows": { "contextMenu": "https://www.jqwidgets.com/jquery-widgets-demo/demos/jqxgrid/contextmenu.htm", "dynamicHeight": "https://www.jqwidgets.com/jquery-widgets-demo/demos/jqxgrid/autorowheight.htm", "dynamicInsert": false, "dynamicRemove": false, "floating": false, "fullWidth": false, "grouping": true, "numbering": true, "reorder": true, "selection": "https://www.jqwidgets.com/jquery-widgets-demo/demos/jqxgrid/rowselection.htm", "virtualization": true }, "cells": { "clipboard": true, "customRendering": false, "editing": "https://www.jqwidgets.com/jquery-widgets-demo/demos/jqxgrid/cellediting.htm", "formula": false, "keyboardNavigation": [ "Arrows", "Enter", "Tab", "Page", "Home" ], "merge": false, "validation": true, "rangeSelection": true, "styling": "https://www.jqwidgets.com/jquery-widgets-demo/demos/jqxgrid/gridcellclass.htm" } } } <|start_filename|>src/render.js<|end_filename|> import fs from "fs"; import {equals, isURL} from "./helper"; import request from "sync-request"; function getProp(grid, field = "") { let fields = field.split("."); let param = grid; while (fields.length != 0) if (typeof param === "object" && param !== null) param = param[fields.shift()]; else return undefined; return param; } function getRepository(repository) { try { let res = request("GET", "https://api.github.com/repos/" + repository, { "headers": { "user-agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36." } }); return JSON.parse(res.getBody('utf8')); } catch (ex) { return null; } } class Render { static link(str, title = "Link") { return "[" + title + "](" + str + ")"; } static image(str, title = "Image") { if (str === null) return ""; return "![" + title + "](" + str + ")"; } static repository(repository) { return Render.link("https://github.com/" + repository); } static stars(stars) { return Number(stars).toLocaleString() + " :star:"; } static framework(str) { return Render.image("https://raw.githubusercontent.com/AmitMY/grids/master/assets/frameworks/" + encodeURIComponent(str.toLowerCase()) + ".png", str); } static format(str) { if (["XLS", "XLSX", "PDF", "XML", "CSV"].indexOf(str) != -1) return Render.image("https://raw.githubusercontent.com/teambox/Free-file-icons/master/32px/" + str.toLowerCase() + ".png", str); return str; } static array(mapper = null, join = ",") { return (arr) => { if (arr === null) return Render.boolLinkNull(false); if (mapper !== null) arr = arr.map(mapper); return arr.join(join + " "); }; } static owner(lastEditor) { return Render.link("https://github.com/" + lastEditor.user, lastEditor.user) + " (" + lastEditor.rank + ")"; } static color(color) { let c; switch (color) { case "green": c = "c5f015"; break; case "red": c = "f03c15"; break; default: c = "1589F0"; } return "![" + color + "](http://placehold.it/23/" + c + "/000000?text=+)" } static boolLinkNull(any) { if (typeof any === "string") return Render.color("green") + " " + Render.link(any, ":book:"); if (any === null) return Render.color("blue"); if (any === true) return Render.color("green"); return Render.color("red"); } } let clearRow = (title = "-") => new Object({ title: title, mandatory: true, renderer: () => "" }); const rows = [ { title: "Logo", field: "info.logo", renderer: Render.image },{ title: "Last Editor", field: "lastEditor", renderer: Render.owner }, { title: "Frameworks", field: "info.frameworks", renderer: Render.array(Render.framework, "") }, { title: "Description", field: "info.description" }, { title: "License", field: "info.license" }, { title: "Price", field: "info.price" }, { title: "Repository", field: "info.repository.html_url", renderer: Render.link }, { title: "Stars", field: "info.repository.stargazers_count", renderer: Render.stars }, { title: "Themes", field: "info.layoutThemes", renderer: Render.array() }, { title: "Website", field: "info.website.link", renderer: Render.link }, { title: "Demo", field: "info.website.demo", renderer: Render.link }, { title: "Tech Support", field: "info.techSupport", renderer: Render.boolLinkNull }, clearRow(), clearRow("General"), { title: "Pivot Mode", field: "features.pivoting", renderer: Render.boolLinkNull }, { title: "Print Mode", field: "features.print", renderer: Render.boolLinkNull }, { title: "Export", field: "features.export", renderer: Render.array(Render.format) }, { title: "Pagination", field: "features.pagination", renderer: Render.boolLinkNull }, { title: "Virtual Pagination", field: "features.virtualPagination", renderer: Render.boolLinkNull }, clearRow(), clearRow("Rows"), { title: "Rows Grouping", field: "features.rows.grouping", renderer: Render.boolLinkNull }, { title: "Floating Rows", field: "features.rows.floating", renderer: Render.boolLinkNull }, { title: "Context Menu", field: "features.rows.contextMenu", renderer: Render.boolLinkNull }, { title: "Full Width Rows", field: "features.rows.fullWidth", renderer: Render.boolLinkNull }, { title: "Rows Numbering", field: "features.rows.numbering", renderer: Render.boolLinkNull }, { title: "Rows Selection", field: "features.rows.selection", renderer: Render.boolLinkNull }, { title: "Virtualization", field: "features.rows.virtualization", renderer: Render.boolLinkNull }, { title: "Dynamic Add Rows", field: "features.rows.dynamicInsert", renderer: Render.boolLinkNull }, { title: "Dynamic Remove Rows", field: "features.rows.dynamicRemove", renderer: Render.boolLinkNull }, { title: "Dynamic Row Height", field: "features.rows.dynamicHeight", renderer: Render.boolLinkNull }, clearRow(), clearRow("Columns"), { title: "Filtering", field: "features.columns.filtering", renderer: Render.boolLinkNull }, { title: "Filters", field: "features.columns.filterTypes", renderer: Render.array() }, { title: "Sorting", field: "features.columns.sorting", renderer: Render.boolLinkNull }, { title: "Pinning", field: "features.columns.pinning", renderer: Render.boolLinkNull }, { title: "Reordering", field: "features.columns.reorder", renderer: Render.boolLinkNull }, { title: "Resizing", field: "features.columns.resizing", renderer: Render.boolLinkNull }, { title: "Header Grouping", field: "features.columns.grouping", renderer: Render.boolLinkNull }, { title: "Selection", field: "features.columns.selection", renderer: Render.boolLinkNull }, { title: "Column Menu", field: "features.columns.menu", renderer: Render.boolLinkNull }, { title: "Aggregation", field: "features.columns.aggregation", renderer: Render.array() }, { title: "Header Rendering", field: "features.columns.headerRendering", renderer: Render.boolLinkNull }, clearRow(), clearRow("Cells"), { title: "Custom Rendering", field: "features.cells.customRendering", renderer: Render.boolLinkNull }, { title: "Formula Support", field: "features.cells.formula", renderer: Render.boolLinkNull }, { title: "Inline Editing", field: "features.cells.editing", renderer: Render.boolLinkNull }, { title: "Validation", field: "features.cells.validation", renderer: Render.boolLinkNull }, { title: "Custom styling", field: "features.cells.styling", renderer: Render.boolLinkNull }, { title: "Clipboard", field: "features.cells.clipboard", renderer: Render.boolLinkNull }, { title: "Keyboard Navigation", field: "features.cells.keyboardNavigation", renderer: Render.array() }, { title: "Range Selection", field: "features.cells.rangeSelection", renderer: Render.boolLinkNull }, { title: "Merge Cells", field: "features.cells.merge", renderer: Render.boolLinkNull }, clearRow(), clearRow("Nice To Have"), { title: "Animations", field: "features.animations", renderer: Render.boolLinkNull }, { title: "Custom Icons", field: "features.customIcons", renderer: Render.boolLinkNull }, { title: "Custom Overlays", field: "features.customOverlays", renderer: Render.boolLinkNull }, { title: "Global Search", field: "features.globalSearch", renderer: Render.boolLinkNull }, { title: "Internationalisation", field: "features.internationalisation", renderer: Render.boolLinkNull }, { title: "Master/Slave", field: "features.masterSlave", renderer: Render.boolLinkNull }, { title: "RTL Support", field: "features.RTLSupport", renderer: Render.boolLinkNull }, { title: "Footer", field: "features.statusBar", renderer: Render.boolLinkNull }, { title: "Touch support", field: "features.touchSupport", renderer: Render.boolLinkNull } ]; function createRow(array, title = "") { return "|**" + title + "**|" + array.join("|") + "|"; } function createTable(data) { let table = []; // Sort by name data = data.sort((a, b) => a.info.name.localeCompare(b.info.name)); table.push(createRow(data.map(grid => grid.info.name), "/")); table.push(Array.from(table[0]).map(c => (c == "|") ? "|" : "-").join("")); rows.forEach(param => { let rowData = data.map(grid => getProp(grid, param.field)); let parsedRowData = (param.renderer == Render.boolLinkNull) ? rowData.map(item => (typeof item == "string") ? true : item) : rowData; // Skip equal rows if (!param.mandatory && parsedRowData.every(item => equals(item, parsedRowData[0]))) return; let row = createRow(rowData.map((item) => { if (item === undefined) return ""; if (param.renderer) return param.renderer(item, param.title); if (isURL(item)) return Render.link(item, param.title); return item; }), param.title); table.push(row); }); return table.join("\n"); } function writeMainTable(str) { fs.readFile("README-header.md", (err, data) => { fs.writeFile("README.md", data + "\n\n" + str); }); } function createTables(grids) { grids.forEach(grid => { if(grid.info.repository !== null) grid.info.repository = getRepository(grid.info.repository); }); fs.writeFile("public/data.json", JSON.stringify(grids)); writeMainTable(createTable(grids)); for (let i = 0; i < grids.length; i++) for (let j = i + 1; j < grids.length; j++) { let data = [grids[i], grids[j]]; let name = grids[i].info.name + "." + grids[j].info.name; fs.writeFile("differences/" + name + ".md", createTable(data)); } } const gridsFolder = "grids"; fs.readdir(gridsFolder, (err, files) => { let grids = []; files.forEach(file => { fs.readFile(gridsFolder + "/" + file, (err, data) => { grids.push(JSON.parse(data)); if (grids.length == files.length) createTables(grids); }); }); }); <|start_filename|>src/helper.js<|end_filename|> import {ArrayPrototypes, ObjectPrototypes} from "js-prototypes"; ArrayPrototypes.equals(); ObjectPrototypes.equals(); function equals(a, b) { if(Array.isArray(a)) return a.equals(b); if(typeof a === "object" && a != null) return Object.equals(a, b); return a == b; } function isURL(str) { let pattern = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/; return pattern.test(str); } export {equals, isURL};
shalevy1/grids
<|start_filename|>firstDemoForCocoaPodsDemo/Pods/Local Podspecs/firstDemoForCocoaPods.podspec.json<|end_filename|> { "name": "firstDemoForCocoaPods", "version": "1.0.0", "summary": "创建cocoaPods测试", "description": "firstDemoForCocoaPods \n创建cocoaPods测试", "homepage": "https://github.com/yirenyiyi/firstDemoForCocoaPods", "license": "MIT", "authors": { "wangxin": "<EMAIL>" }, "platforms": { "ios": "7.0" }, "source": { "git": "https://github.com/yirenyiyi/firstDemoForCocoaPods.git", "tag": "1.0.0" }, "source_files": "firstDemoForCocoaPods/*.{h,m}", "exclude_files": "Classes/Exclude" }
yirenyiyi/firstDemoForCocoaPods
<|start_filename|>SampleSkeleton/Utils/Editor/ScriptableObjectInstantiator.cs<|end_filename|> using System; using UnityEditor; using UnityEngine; // Adds buttons to the Inspector to instantiate assets from a ScriptableObject // See https://docs.unity3d.com/Manual/RunningEditorCodeOnLaunch.html [InitializeOnLoadAttribute] public class ScriptableObjectInstantiator : Editor { static ScriptableObjectInstantiator() { Editor.finishedDefaultHeaderGUI += ScriptableObjectInstantiator.DisplayGUI; } private static void DisplayGUI(Editor editor) { if (!(editor.target is MonoScript target) || !target.GetClass().IsSubclassOf(typeof(ScriptableObject))) return; Type type = target.GetClass(); if (GUILayout.Button($"Instantiate {type.Name} asset")) ScriptableObjectInstantiator.InstantiateScriptableObject(type, "Assets"); // Add a second button to instantiate in the currently selected (parent) folder string path = AssetDatabase.GetAssetPath(Selection.activeObject); if (String.IsNullOrEmpty(path)) return; if (!AssetDatabase.IsValidFolder(path)) path = path.Substring(0, path.LastIndexOf('/')); if (!AssetDatabase.IsValidFolder(path)) return; if (GUILayout.Button($"Instantiate {type.Name} asset in\n{path}")) ScriptableObjectInstantiator.InstantiateScriptableObject(type, path); } private static void InstantiateScriptableObject(Type type, string path) { ScriptableObject instance = ScriptableObject.CreateInstance(type); path = AssetDatabase.GenerateUniqueAssetPath($"{path}/{type.Name}.asset"); AssetDatabase.CreateAsset(instance, path); EditorGUIUtility.PingObject(instance); } } <|start_filename|>Graphics/MaliCompilerReport/Assets/Editor/MaliShaderReport.cs<|end_filename|> using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEditor; using UnityEditor.Rendering; using UnityEngine.Windows; using System.Text; using System; using System.Diagnostics; using Debug = UnityEngine.Debug; public class MaliShaderReport : EditorWindow { static class Content { public static readonly GUIContent targetContent = new GUIContent("Shader", "Shader to be Analyzed."); public static readonly GUIContent compilerContent = new GUIContent("Mali Compiler", "Compiler to use"); public static readonly GUIContent allKeywords = new GUIContent("All Keywords", "All keywords that can be used in this shader"); public static readonly GUIContent[] compileOptions = new GUIContent[] { new GUIContent("Arm Studio - Malioc (PATH)", "Mali Offline Compiler Arm Studio"), new GUIContent("Offline Compiler - Malisc (PATH)", "Mali Offline Compiler Legacy Install"), new GUIContent("Custom Location", "Custom Location") }; public static readonly GUIContent[] shaderTypes = new GUIContent[] { new GUIContent("Vertex Shader", "Vertex shader report"), new GUIContent("Geometry Shader", "Geometry shader report"), new GUIContent("Fragment Shader", "Fragment shader report"), }; } // NOTE: Keep this the same as Content.shaderTypes private readonly ShaderType[] k_ReportOrder = new ShaderType[] { ShaderType.Vertex, ShaderType.Geometry, ShaderType.Fragment }; // Compilers supported enum CompilerTarget { Malioc, // ARM Studio (Latest) Mali Offline compiler (https://developer.arm.com/tools-and-software/graphics-and-gaming/arm-mobile-studio/components/mali-offline-compiler) Malisc, // ARM Mali Compiler Legacy (6.4 and lower) (https://developer.arm.com/tools-and-software/graphics-and-gaming/mali-offline-compiler/downloads) Custom, // Just point to the executable to use } // Compiler Info private CompilerTarget m_Compiler = CompilerTarget.Malioc; private string m_CompilerPath; // Shader and pass private Shader m_Target = null; private int m_SelectedPass = -1; // Keywords and pass names private List<string> m_Keywords = new List<string>(); private string[] m_PassNames = null; // Scrolling Vector2 m_KeywordScroll = new Vector2(); Vector2 m_PassKeywordScroll = new Vector2(); Vector2 m_ReportScroll = new Vector2(); // Message for when a combination has no keys applied private const string k_NA = "No keyword applied"; private const int k_MaxHintLength = 18; // Simple class to contain pass information // this is then shown to the user via the pass dropdown class PassInfo { public int subShader; public List<List<string>> keywords; public List<string> keywordHint; public string name; public ShaderData.Pass pass; public PassInfo() { subShader = 0; keywords = new List<List<string>>(); keywordHint = new List<string>(); name = ""; pass = null; } } private List<PassInfo> m_Passes = new List<PassInfo>(); private PassInfo defaultPassInfo = new PassInfo(); private List<int> m_SelectedKeywords = new List<int>(); private StringBuilder m_CompilerOutput = new StringBuilder(); private int m_lines = 0; private Dictionary<ShaderType, string> m_Report = new Dictionary<ShaderType, string>(); // Add menu named "My Window" to the Window menu [MenuItem("Shader/Mali Offline Compiler")] static void Init() { // Get existing open window or if none, make a new one: MaliShaderReport window = (MaliShaderReport)EditorWindow.GetWindow(typeof(MaliShaderReport)); window.Show(); } void OnGUI() { // Choose the compiler m_Compiler = (CompilerTarget)EditorGUILayout.Popup(Content.compilerContent, (int)m_Compiler, Content.compileOptions); if (m_Compiler == CompilerTarget.Custom) { EditorGUILayout.BeginHorizontal(); m_CompilerPath = EditorGUILayout.TextField(m_CompilerPath); if (GUILayout.Button("...")) { #if UNITY_STANDALONE_WIN m_CompilerPath = EditorUtility.OpenFilePanel("Mali Offline Compiler", "", "exe"); #else m_CompilerPath = EditorUtility.OpenFilePanel("Mali Offline Compiler", "", ""); #endif } EditorGUILayout.EndHorizontal(); } // Select the shader Shader s = EditorGUILayout.ObjectField(Content.targetContent, m_Target, typeof(Shader), true) as Shader; // Go through and setup the data needed to compile a shader // we only do this once when a shader is selected. ProcessShader(s); // Display the keywords { GUILayout.Label(Content.allKeywords, EditorStyles.boldLabel); EditorGUILayout.BeginVertical(GUILayout.MaxHeight(40.0f)); m_KeywordScroll = EditorGUILayout.BeginScrollView(m_KeywordScroll); EditorGUILayout.BeginHorizontal(); for (int i = 0; i < m_Keywords.Count; i++) { GUILayout.Label(m_Keywords[i], EditorStyles.label); } EditorGUILayout.EndHorizontal(); EditorGUILayout.EndScrollView(); EditorGUILayout.EndVertical(); } // Select Pass to investigate GUILayout.Label("Pass:", EditorStyles.boldLabel); if (m_PassNames != null) { SetSelectedPass(EditorGUILayout.Popup(m_SelectedPass, m_PassNames)); } PassInfo info; if (m_SelectedPass >= 0 && m_SelectedPass < m_Passes.Count) { info = m_Passes[m_SelectedPass]; } else { info = defaultPassInfo; } // there is a chance we have a valid selected pass but the keyword count doesnt match // if that happens we need to reinitialise (usually only happens due to a recompile of the c#) if (m_SelectedKeywords.Count != info.keywords.Count) { SetSelectedPass(m_SelectedPass, true); } EditorGUILayout.BeginVertical(); // Pass Keyword selection { EditorGUILayout.BeginHorizontal(); GUILayout.Label("Pass Name:"); GUILayout.Label(info.name); EditorGUILayout.EndHorizontal(); GUILayout.Label("Pass Keywords:"); m_PassKeywordScroll = EditorGUILayout.BeginScrollView(m_PassKeywordScroll); EditorGUILayout.BeginVertical(); for (int i = 0; i < m_SelectedKeywords.Count; i++) { string[] options = info.keywords[i].ToArray(); if (options.Length == 0) continue; if (options[0].Length == 0) { options[0] = k_NA; } m_SelectedKeywords[i] = EditorGUILayout.Popup(info.keywordHint[i], Mathf.Clamp(m_SelectedKeywords[i], 0, options.Length), options); } EditorGUILayout.EndVertical(); EditorGUILayout.EndScrollView(); } // Report section { m_ReportScroll = EditorGUILayout.BeginScrollView(m_ReportScroll); EditorGUILayout.BeginVertical(); string value = null; for (int i = 0; i < k_ReportOrder.Length; i++) { if (m_Report.TryGetValue(k_ReportOrder[i], out value)) { EditorGUILayout.BeginHorizontal(); GUILayout.Label(Content.shaderTypes[i]); if (GUILayout.Button("Copy text")) { EditorGUIUtility.systemCopyBuffer = value; } EditorGUILayout.EndHorizontal(); GUILayout.Box(value, EditorStyles.helpBox); } } EditorGUILayout.EndVertical(); EditorGUILayout.EndScrollView(); } EditorGUILayout.EndVertical(); EditorGUILayout.BeginHorizontal(); GUI.enabled = info != defaultPassInfo; if (GUILayout.Button("Compile & Report")) { CompileAndReport(); } GUI.enabled = true; if (GUILayout.Button("Refresh Shader")) { // preprocess the shader ProcessShader(s, true); } if (GUILayout.Button("Clear Report")) { m_Report.Clear(); } EditorGUILayout.EndHorizontal(); } void CompileAndReport() { ShaderType[] types = new ShaderType[] { ShaderType.Vertex, ShaderType.Geometry, ShaderType.Fragment }; string shader = FileUtil.GetUniqueTempPathInProject() + ".shader"; string[] keywords = GenerateKeywords(); bool bCompiled = CompileShaderToFile(shader, keywords); List<ShaderType> supported = new List<ShaderType>(); for (int i = 0; i < types.Length; i++) { if (m_Passes[m_SelectedPass].pass.HasShaderStage(types[i])) { supported.Add(types[i]); } } Report(shader, supported); } string[] GenerateKeywords() { if (m_SelectedKeywords.Count == 0) { return new string[0]; } List<string> used = new List<string>(); for (int i = 0; i < m_SelectedKeywords.Count; i++) { string keyword = m_Passes[m_SelectedPass].keywords[i][m_SelectedKeywords[i]]; if (keyword.Length == 0) continue; used.Add(keyword); } return used.ToArray(); } bool CompileShaderToFile(string path, string[] keywords) { Debug.Log("Compiling " + path + " with " + keywords.Length + " keywords"); ShaderData.VariantCompileInfo result = m_Passes[m_SelectedPass].pass.CompileVariant(ShaderType.Vertex, keywords, ShaderCompilerPlatform.GLES3x, BuildTarget.Android); if (result.Success) { // Convert a byte array to a C# string. string code = Encoding.ASCII.GetString(result.ShaderData); code = code.Replace("#version 310 es", "").Replace("#version 300 es", "").Insert(0, "#version 310 es\n"); byte[] data = Encoding.ASCII.GetBytes(code); File.WriteAllBytes(path, data); //Debug.Log("Compiled, Bytes:"+ result.ShaderData.Length); return true; } Debug.Log("Compile Failed"); return false; } string GetCompiler() { switch (m_Compiler) { case CompilerTarget.Malioc: return "malioc.exe"; case CompilerTarget.Malisc: return "malisc.exe"; case CompilerTarget.Custom: return m_CompilerPath; } return ""; } void Report(string path, List<ShaderType> supported) { m_Report.Clear(); string log; foreach (ShaderType type in supported) { if (Report(path, type, out log)) { m_Report.Add(type, log); } //Debug.Log(log); } } bool Report(string path, ShaderType target, out string report) { bool bSuccess = false; try { m_lines = 0; m_CompilerOutput.Clear(); Process compiler = new Process(); compiler.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; compiler.StartInfo.CreateNoWindow = true; compiler.StartInfo.UseShellExecute = false; compiler.StartInfo.FileName = GetCompiler(); compiler.StartInfo.RedirectStandardOutput = true; compiler.OutputDataReceived += Compiler_OutputDataReceived; switch (target) { case ShaderType.Vertex: compiler.StartInfo.Arguments = "-v " + path + " -D VERTEX"; break; case ShaderType.Fragment: compiler.StartInfo.Arguments = "-f " + path + " -D FRAGMENT"; break; case ShaderType.Geometry: compiler.StartInfo.Arguments = "-g " + path + " -D GEOMETRY"; break; } compiler.EnableRaisingEvents = true; compiler.Start(); compiler.BeginOutputReadLine(); compiler.WaitForExit(); int ExitCode = compiler.ExitCode; report = m_CompilerOutput.ToString(); bSuccess = true; } catch (Exception e) { report = e.ToString(); Debug.LogException(e); switch (m_Compiler) { case CompilerTarget.Malioc: EditorUtility.DisplayDialog("Unable to call Malioc", "Do you have ARM Mobile Studio Installed and included in the path?", "OK"); break; case CompilerTarget.Malisc: EditorUtility.DisplayDialog("Unable to call Malisc", "Do you have the Mali Offline Compiler installed and included in the path?", "OK"); break; case CompilerTarget.Custom: EditorUtility.DisplayDialog("Unable to call the compiler", "Have you set the compilers location?", "OK"); break; } } return bSuccess; } private void Compiler_OutputDataReceived(object sender, DataReceivedEventArgs e) { if (!String.IsNullOrEmpty(e.Data)) { m_lines++; m_CompilerOutput.Append(e.Data); m_CompilerOutput.Append('\n'); } } // TODO: Extract the shader compiled hlsl to glsl for the shader and include that in the report void ExtractCode(string path, ShaderType type) { } void ProcessShader(Shader target, bool force = false) { // Reset if (target == null) { m_Keywords.Clear(); m_Passes.Clear(); m_SelectedPass = -1; m_Target = null; m_PassNames = null; } else if (target != m_Target || force) { m_Keywords.Clear(); m_Passes.Clear(); if (!force) { m_SelectedPass = 0; } m_Target = target; ShaderData data = ShaderUtil.GetShaderData(target); List<string> names = new List<string>(); StringBuilder sb = new StringBuilder(k_MaxHintLength * 3); for (int sub = 0; sub < data.SubshaderCount; sub++) { ShaderData.Subshader subshader = data.GetSubshader(sub); for (int p = 0; p < subshader.PassCount; p++) { PassInfo passInfo = new PassInfo(); passInfo.subShader = sub; passInfo.pass = subshader.GetPass(p); passInfo.name = passInfo.pass.Name; ParseKeywords(passInfo.pass.SourceCode, ref passInfo.keywords); // Create some label hints for (int i = 0; i < passInfo.keywords.Count; i++) { for (int j = 0; j < passInfo.keywords[i].Count; j++) { if (passInfo.keywords[i][j].Length > 0) { sb.Append(passInfo.keywords[i][j]); if (sb.Length > k_MaxHintLength) { sb.Remove(k_MaxHintLength, sb.Length - k_MaxHintLength); sb[15] = '.'; sb[16] = '.'; sb[17] = '.'; break; } else if (sb.Length == k_MaxHintLength) { break; } else if (j < passInfo.keywords[i].Count - 1) { sb.Append(','); } } } passInfo.keywordHint.Add(sb.ToString()); sb.Clear(); } m_Passes.Add(passInfo); names.Add(passInfo.name); } } if (m_SelectedPass < 0) m_SelectedPass = 0; else if (m_SelectedPass >= m_Passes.Count) { m_SelectedPass = m_Passes.Count - 1; } SetSelectedPass(m_SelectedPass, true); m_PassNames = names.ToArray(); } } void SetSelectedPass(int index, bool init = false) { if (init || index != m_SelectedPass) { m_SelectedPass = index; m_SelectedKeywords.Clear(); if (m_SelectedPass >= 0 && m_SelectedPass < m_Passes.Count) { PassInfo info = m_Passes[m_SelectedPass]; for (int i = 0; i < info.keywords.Count; i++) { m_SelectedKeywords.Add(0); } } } } struct Range { public int startIndex; public int endIndex; } int FindNextValidMultiLineStart(string code, int index) { int possibleIndex = code.IndexOf("/*", index); // early out if (possibleIndex == -1) return -1; // determine if its hidden by a single comment int previousLineIndex = code.LastIndexOf('\n', possibleIndex - 1, possibleIndex); int commentStart = code.IndexOf("//", previousLineIndex, possibleIndex - previousLineIndex); if(commentStart != -1) { return FindNextValidMultiLineStart(code, possibleIndex + 2); } return possibleIndex; } int FindNextValidMultiLineEnd(string code, int index) { // there is no checking to be done as if were in a valid multi line comment it doesnt end till those 2 characters are found int possibleIndex = code.IndexOf("*/", index); return possibleIndex; } string StripMultilineComments(string code) { List<Range> ranges = new List<Range>(); int index = FindNextValidMultiLineStart(code, 0); Range range = new Range(); while (index != -1) { range.startIndex = index; index = FindNextValidMultiLineEnd(code, index + 2); range.endIndex = index + 2; index = FindNextValidMultiLineStart(code, range.endIndex); ranges.Add(range); } if (ranges.Count == 0) return code; StringBuilder sb = new StringBuilder(code.Length); int startIndex = 0; int stringIndex = 0; if (ranges[0].startIndex == 0) { startIndex++; stringIndex = ranges[0].endIndex; } int len = 0; for (int idx = startIndex; idx < ranges.Count; idx++) { len = ranges[idx].startIndex - stringIndex; sb.Append(code, stringIndex, len); stringIndex = ranges[idx].endIndex; } if (stringIndex < code.Length - 1) { len = code.Length - stringIndex; sb.Append(code, stringIndex, len); } return sb.ToString(); } int FindNextValidPragma(int start, string code) { // early out if (start >= code.Length) return -1; int possibleIndex = code.IndexOf("#pragma", start); // early out if (possibleIndex == -1) return -1; // is it the start of the string? if so we can early out if (possibleIndex == 0) return possibleIndex; // determine if its hidden by a single comment int previousLineIndex = Mathf.Max( code.LastIndexOf('\n', possibleIndex - 1, possibleIndex), 0); int commentStart = code.IndexOf("//", previousLineIndex, possibleIndex - previousLineIndex); // if we're at a single line comment just start the search again on the next line if (commentStart != -1) { // determine the end of the string int endOfLineIndex = code.IndexOf('\n', possibleIndex); if (endOfLineIndex == -1) { endOfLineIndex = code.Length - 1; } return FindNextValidPragma(endOfLineIndex, code); } return possibleIndex; } void ParseKeywords(string code, ref List<List<string>> keywords) { keywords.Clear(); // find and strip any multi line comments code = StripMultilineComments(code); // we now just search the code string int pragmaIndex = FindNextValidPragma(0, code); while (pragmaIndex != -1) { int endOfLine = code.IndexOf('\n', pragmaIndex); ParsePragmaString(code, ref keywords, pragmaIndex, endOfLine - pragmaIndex); pragmaIndex = FindNextValidPragma(endOfLine + 1, code); } } void ParsePragmaString(string code, ref List<List<string>> outkeywords, int index, int length) { // lets remove any single comment from this line int commentStart = code.IndexOf("//", index, length); if (commentStart != -1) { length = commentStart - index; } // Handle a multi_compile and its variants int indexStart = code.IndexOf("multi_compile", index, length); if (indexStart != -1) { List<string> keys = new List<string>(); indexStart = code.IndexOf(' ', indexStart, length - (indexStart - index)); if (indexStart == -1) return; int substringLength = length - ((indexStart - index) + 1); // we still do a substring here as it makes the spliting easy but at least its only one substring now code = code.Substring(indexStart + 1, substringLength); string[] keywords = code.Split(' '); for (int i = 0; i < keywords.Length; i++) { if (keywords[i].Equals("_")) { keys.Add(""); } else { keys.Add(keywords[i]); if (!m_Keywords.Contains(keywords[i])) { m_Keywords.Add(keywords[i]); } } } if (keys.Count > 0) { outkeywords.Add(keys); } } // Handle a shader_feature and its variants else { indexStart = code.IndexOf("shader_feature", index, length); if (indexStart != -1) { List<string> keys = new List<string>(); indexStart = code.IndexOf(' ', indexStart, length - (indexStart - index)); if (indexStart == -1) return; int substringLength = length - ((indexStart - index) + 1); // we still do a substring here as it makes the spliting easy but at least its only one substring now code = code.Substring(indexStart + 1, substringLength); string[] keywords = code.Split(' '); for (int i = 0; i < keywords.Length; i++) { if (keywords[i].Equals("_")) { keys.Add(""); } else { keys.Add(keywords[i]); if (!m_Keywords.Contains(keywords[i])) { m_Keywords.Add(keywords[i]); } } } if (keywords.Length == 1) { keys.Insert(0, ""); } if (keys.Count > 0) { outkeywords.Add(keys); } } } } } <|start_filename|>Graphics/CameraPerformance/CameraPerformance-URP/Assets/Scripts/Spinner.cs<|end_filename|> using System; using UnityEngine; using Random = UnityEngine.Random; public class Spinner : MonoBehaviour { [SerializeField] float m_DegreesPerSecond; Vector3 m_RotationAxis; void Awake() { m_RotationAxis = Random.insideUnitSphere.normalized; } void Update() { transform.Rotate(m_RotationAxis, m_DegreesPerSecond * Time.deltaTime); } } <|start_filename|>AssetManagement/LockableFolders/Assets/Editor/LockableFolder.cs<|end_filename|> using System.Collections; using System.Collections.Generic; using UnityEditor; using UnityEngine; // https://docs.unity3d.com/Manual/RunningEditorCodeOnLaunch.html [InitializeOnLoadAttribute] public class LockableFolder { const string k_LockPrefix = "locked="; static GUIContent s_ToggleText; static LockableFolder() { s_ToggleText = new GUIContent("Locked", "Check this to prevent adding or removing assets from this folder."); // Event raised while drawing the header of the Inspector window, after the default header items have been drawn. Editor.finishedDefaultHeaderGUI += DisplayGUI; } static void DisplayGUI(Editor editor) { // TODO: support multi-object editing // Add a checkbox in the Inspector to folders to "lock" them var path = AssetDatabase.GetAssetPath(editor.target); if (AssetDatabase.IsValidFolder(path)) { var folderAsset = AssetImporter.GetAtPath(path); bool isLocked = folderAsset.userData.StartsWith(k_LockPrefix); bool toggleState = EditorGUILayout.Toggle(s_ToggleText, isLocked); if (toggleState != isLocked) { Undo.RecordObject(folderAsset, "Lock"); if (toggleState) { var childrenAssets = AssetDatabase.FindAssets(null, new string[] { path }); folderAsset.userData = k_LockPrefix + string.Join(",", childrenAssets); } else { folderAsset.userData = null; } folderAsset.SaveAndReimport(); } } } // Validates asset changes against the locked folders class LockableFolderValidator : AssetPostprocessor { static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths) { bool hasError = false; foreach (string assetPath in importedAssets) { var errorString = "Cannot add asset \"{0}\" to folder \"{1}\""; if (CheckViolatedLockedFolder(assetPath, assetPath, errorString)) { hasError = true; } } foreach (string assetPath in deletedAssets) { var errorString = "Cannot delete asset \"{0}\" from folder \"{1}\""; if (CheckViolatedLockedFolder(assetPath, assetPath, errorString, true)) { hasError = true; } } for (int i = 0; i < movedFromAssetPaths.Length; ++i) { var errorString = "Cannot move asset \"{0}\" to folder \"{1}\""; if (CheckViolatedLockedFolder(movedAssets[i], movedAssets[i], errorString)) { hasError = true; } errorString = "Cannot move asset \"{0}\" from folder \"{1}\""; if (CheckViolatedLockedFolder(movedAssets[i], movedFromAssetPaths[i], errorString, true)) { hasError = true; } } if (hasError) { EditorUtility.DisplayDialog("Locked folder violation", "Oy! A locked folder's content has been modified! Don't do that! Check the logs for details...", "Whoops!"); } } static bool CheckViolatedLockedFolder(string assetPath, string searchPath, string errorString, bool removingAsset = false) { var guid = AssetDatabase.AssetPathToGUID(assetPath); if (guid == null) { Debug.LogWarningFormat("Asset GUID not found for asset at path \"{0}\"", assetPath); return false; } var violatedLockedFolder = FindViolatedLockedParentFolder(searchPath, guid, removingAsset); if (violatedLockedFolder != null) { var assetName = assetPath.Substring(assetPath.LastIndexOf('/') + 1); Debug.LogErrorFormat("[LockableFolder] " + errorString, assetName, violatedLockedFolder); return true; } return false; } static string FindViolatedLockedParentFolder(string searchPath, string assetGuid, bool removingAsset = false) { var parentFolderPath = searchPath; int lastSlashIndex; while ((lastSlashIndex = parentFolderPath.LastIndexOf('/')) > 0) { parentFolderPath = parentFolderPath.Substring(0, lastSlashIndex); // parentFolderAsset can be null when adding an asset to ProjectSettings, deleting parent folders, etc. var parentFolderAsset = AssetImporter.GetAtPath(parentFolderPath); if (parentFolderAsset != null && parentFolderAsset.userData.StartsWith(k_LockPrefix)) { return parentFolderAsset.userData.Contains(assetGuid) == removingAsset ? parentFolderPath : null; } } return null; } } } <|start_filename|>Lighting/ImportLightProbes/Assets/Editor/ProbeActions.cs<|end_filename|> using System.Collections.Generic; using System.IO; using System.Text; using UnityEditor; using UnityEditor.SceneManagement; using UnityEngine; using UnityEngine.Rendering; public class ProbeActions : Object { const string k_ProbesFile = "probes.txt"; static readonly Vector3[] k_DefaultPositions = new Vector3[] { new Vector3(1.0f, 1.0f, 1.0f), new Vector3(1.0f, 1.0f, -1.0f), new Vector3(1.0f, -1.0f, 1.0f), new Vector3(1.0f, -1.0f, -1.0f), new Vector3(-1.0f, 1.0f, 1.0f), new Vector3(-1.0f, 1.0f, -1.0f), new Vector3(-1.0f, -1.0f, 1.0f), new Vector3(-1.0f, -1.0f, -1.0f), }; [MenuItem("Light Probes/Import external probe data")] public static void ImportProbes() { try { EditorUtility.DisplayProgressBar("Importing external probe data", "Parsing data", 0); DoImportProbePositions(); EditorUtility.DisplayProgressBar("Importing external probe data", "Dummy bake job", 0.25f); Lightmapping.bakeCompleted -= OnBakeCompleted; Lightmapping.bakeCompleted += OnBakeCompleted; Lightmapping.BakeAsync(); } catch { Debug.LogError("Light probe import failed"); EditorUtility.ClearProgressBar(); throw; } } [MenuItem("Light Probes/[1] Import probe positions")] public static void ImportProbePositions() { DoImportProbePositions(); } [MenuItem("Light Probes/[2] Trigger light bake")] public static void TriggerBake() { Lightmapping.Bake(); } [MenuItem("Light Probes/[3] Import coefficients")] public static void ImportCoefficients() { DoImportCoefficients(); } // Log all currently baked probe data in the format expected by ParseProbeData() [MenuItem("Light Probes/Log light probe data")] public static void LogProbeData() { if (LightmapSettings.lightProbes == null) { Debug.LogError("Light baking must be done at least once."); return; } var bakedProbes = LightmapSettings.lightProbes.bakedProbes; var probePositions = LightmapSettings.lightProbes.positions; var probeCount = LightmapSettings.lightProbes.count; var builder = new StringBuilder(); for (int i = 0; i < probeCount; i++) { builder.Append($"{probePositions[i].x}, {probePositions[i].y}, {probePositions[i].z}"); for (int coefficient = 0; coefficient < 9; coefficient++) { for (int rgb = 0; rgb < 3; rgb++) { builder.Append($", {bakedProbes[i][rgb, coefficient]}"); } } builder.Append("\n"); } Debug.Log(builder); } [MenuItem("Light Probes/Reset light probes")] public static void ResetPositions() { var group = FindObjectOfType<LightProbeGroup>(); group.probePositions = k_DefaultPositions; EditorUtility.SetDirty(group); } [MenuItem("Light Probes/Clear baked data")] public static void ClearBakedData() { Lightmapping.ClearLightingDataAsset(); Lightmapping.Clear(); } static void OnBakeCompleted() { Lightmapping.bakeCompleted -= OnBakeCompleted; try { EditorUtility.DisplayProgressBar("Importing external probe data", "Applying SH coefficients", 0.75f); DoImportCoefficients(); } finally { EditorUtility.ClearProgressBar(); } } static void DoImportProbePositions() { var probeData = ParseProbeData(k_ProbesFile); // The (world) light probe positions need to be converted to the local CS of the LightProbeGroup var group = FindObjectOfType<LightProbeGroup>(); var worldToLocalMatrix = group.transform.worldToLocalMatrix; var probePositions = new Vector3[probeData.Count]; for (int i = 0; i < probeData.Count; i++) { probePositions[i] = worldToLocalMatrix.MultiplyPoint3x4(probeData[i].Position); } group.probePositions = probePositions; } static void DoImportCoefficients() { var probeData = ParseProbeData(k_ProbesFile); var bakedProbes = LightmapSettings.lightProbes.bakedProbes; var probePositions = LightmapSettings.lightProbes.positions; var probeCount = LightmapSettings.lightProbes.count; // This is O(n^2) and should probably be adapted for a large number of light probes int nbImported = 0; foreach (var data in probeData) { for (int i = 0; i < probeCount; i++) { // Don't assume anything about the ordering of light probes and compare the positions instead. if (probePositions[i] == data.Position) { nbImported += 1; data.ApplyTo(ref bakedProbes[i]); } } } LightmapSettings.lightProbes.bakedProbes = bakedProbes; if (nbImported == probeData.Count) { Debug.Log($"Imported {nbImported} light probes from {k_ProbesFile}."); } else { var nbNotImported = probeData.Count - nbImported; Debug.LogWarning($"Imported {nbImported} light probes from {k_ProbesFile}, but {nbNotImported} light probes were not found."); } EditorUtility.SetDirty(Lightmapping.lightingDataAsset); EditorSceneManager.MarkSceneDirty(EditorSceneManager.GetActiveScene()); } static List<LightProbeData> ParseProbeData(string path) { var probeData = new List<LightProbeData>(); foreach (var line in File.ReadLines(path)) { if (line.Length == 0) continue; // Expected data layout is csv of: // - position: 3 floats // - coefficients: 9 * 3 floats var coords = line.Split(','); if (coords.Length != 3 + 9 * 3) { throw new System.ArgumentException($"{path} does not contain valid positions and coefficients"); } var item = new LightProbeData(); item.Position = new Vector3(float.Parse(coords[0]), float.Parse(coords[1]), float.Parse(coords[2])); for (int i = 0; i < 9; i++) { int offset = 3 + i * 3; item.Coefficients[i].Set( float.Parse(coords[offset + 0]), float.Parse(coords[offset + 1]), float.Parse(coords[offset + 2]) ); } probeData.Add(item); } return probeData; } class LightProbeData { public Vector3 Position; public Vector3[] Coefficients = new Vector3[9]; public void ApplyTo(ref SphericalHarmonicsL2 probeCoefficients) { for (int i = 0; i < Coefficients.Length; i++) { probeCoefficients[0, i] = Coefficients[i].x; probeCoefficients[1, i] = Coefficients[i].y; probeCoefficients[2, i] = Coefficients[i].z; } } } } <|start_filename|>Graphics/CameraPerformance/CameraPerformance-URP/Assets/Scripts/Manager.cs<|end_filename|> using System; using System.Collections.Generic; using UnityEngine; using UnityEngine.Rendering.Universal; using UnityEngine.SceneManagement; using UnityEngine.UI; public class Manager : MonoBehaviour { [SerializeField] Dropdown m_SceneSelector; [SerializeField] [Tooltip("Prefab for increasing the scene load factor")] GameObject m_LoadFactorPrefab; [SerializeField] [Tooltip("World position center of the first load factor group")] Vector3 m_LoadFactorBasePosition; [SerializeField] [Min(1)] [Tooltip("Each load factor group is a grid of NxN Prefabs")] uint m_LoadFactorGridSize = 1; [SerializeField] [Tooltip("Distance between individual Prefabs in a load factor group")] float m_LoadFactorGridOffset; [SerializeField] [Tooltip("Distance between load factor groups")] Vector3 m_LoadFactorGroupOffset; [SerializeField] Text m_LoadFactorText; int m_ActiveUIScene = -1; int m_LoadFactor; List<GameObject> m_LoadFactorGroups = new List<GameObject>(); int m_NbUIScenes; List<Camera> m_CameraStack; void Start() { m_CameraStack = Camera.main.GetUniversalAdditionalCameraData().cameraStack; // Exclude the first scene which is the main scene m_NbUIScenes = SceneManager.sceneCountInBuildSettings - 1; PopulateSceneDropdown(); UpdateLoadFactorUI(); LoadScene(0); } public void OnIncLoadFactor() { m_LoadFactor += 1; if (m_LoadFactor > m_LoadFactorGroups.Count) { var loadGroup = new GameObject("Load Group"); m_LoadFactorGroups.Add(loadGroup); var basePosition = m_LoadFactorBasePosition + (m_LoadFactor - 1) * m_LoadFactorGroupOffset; loadGroup.transform.position = basePosition; float x = -0.5f * (m_LoadFactorGridSize - 1) * m_LoadFactorGridOffset; for (int i = 0; i < m_LoadFactorGridSize; i++) { float y = -0.5f * (m_LoadFactorGridSize - 1) * m_LoadFactorGridOffset; for (int j = 0; j < m_LoadFactorGridSize; j++) { Instantiate(m_LoadFactorPrefab, basePosition + new Vector3(x, y, 0), Quaternion.identity, loadGroup.transform); y += m_LoadFactorGridOffset; } x += m_LoadFactorGridOffset; } } else { m_LoadFactorGroups[m_LoadFactor - 1].SetActive(true); } UpdateLoadFactorUI(); } public void OnDecLoadFactor() { if (m_LoadFactor > 0) { m_LoadFactor -= 1; m_LoadFactorGroups[m_LoadFactor].SetActive(false); } UpdateLoadFactorUI(); } void UpdateLoadFactorUI() { m_LoadFactorText.text = $"Load factor: {m_LoadFactor}"; } void PopulateSceneDropdown() { var sceneLabels = new List<string>(m_NbUIScenes); for (int i = 0; i < m_NbUIScenes; i++) { var scenePath = SceneUtility.GetScenePathByBuildIndex(GetUISceneBuildIndex(i)); var start = scenePath.LastIndexOf('/') + 1; scenePath = scenePath.Substring(start, scenePath.LastIndexOf(".") - start); sceneLabels.Add(scenePath); } m_SceneSelector.ClearOptions(); m_SceneSelector.AddOptions(sceneLabels); m_SceneSelector.onValueChanged.AddListener(OnChangeScene); } void OnChangeScene(int index) { LoadScene(index); } void LoadScene(int uiScene) { if (m_ActiveUIScene != uiScene) { if (m_ActiveUIScene >= 0) { SceneManager.UnloadSceneAsync(GetUISceneBuildIndex(m_ActiveUIScene)); } m_CameraStack.Clear(); SceneManager.LoadSceneAsync(GetUISceneBuildIndex(uiScene), LoadSceneMode.Additive).completed += OnSceneLoaded; m_ActiveUIScene = uiScene; } } void OnSceneLoaded(AsyncOperation _) { // Need to dynamically add the Cameras from the additive Scene to the main Camera stack. var scene = SceneManager.GetSceneByBuildIndex(GetUISceneBuildIndex(m_ActiveUIScene)); foreach (var rootObject in scene.GetRootGameObjects()) { var additionalCamera = rootObject.GetComponent<Camera>(); if (additionalCamera) { m_CameraStack.Add(additionalCamera); } } } static int GetUISceneBuildIndex(int uiScene) { // The first scene in the build is the main scene return uiScene + 1; } } <|start_filename|>AssetManagement/URPShaderAssetBundles/Assets/Editor/BundleBuilder.cs<|end_filename|> using System; using System.Collections; using System.Collections.Generic; using System.IO; using UnityEditor; using UnityEditor.Build.Content; using UnityEditor.Build.Pipeline; using UnityEngine; public static class BundleBuilder { private const string k_OutputBasePath = "Build/AssetBundles/"; const string k_UrpBundleName = "urp_shaders"; [MenuItem("AssetBundles/Build with built-in pipeline (duplicated URP shaders)")] public static void BuildAssetBundles() { var outputPath = k_OutputBasePath + "standard"; PrepareOutputPath(outputPath); BuildPipeline.BuildAssetBundles(outputPath, BuildAssetBundleOptions.None, EditorUserBuildSettings.activeBuildTarget); } [MenuItem("AssetBundles/Build with built-in pipeline (separate URP shader bundle)")] public static void BuildAssetBundlesWithShaderBundle() { AssetBundleBuild[] content = SetupBundles(); var outputPath = k_OutputBasePath + "urp_bundle_builtin"; PrepareOutputPath(outputPath); BuildPipeline.BuildAssetBundles(outputPath, content, BuildAssetBundleOptions.None, EditorUserBuildSettings.activeBuildTarget); } [MenuItem("AssetBundles/Build with SRP Compatibility (separate URP shader bundle)")] public static void BuildAssetBundlesWithShaderBundleSRPCompat() { AssetBundleBuild[] content = SetupBundles(); var outputPath = k_OutputBasePath + "urp_bundle_srp_compat"; PrepareOutputPath(outputPath); CompatibilityBuildPipeline.BuildAssetBundles(outputPath, content, BuildAssetBundleOptions.None, EditorUserBuildSettings.activeBuildTarget); } static AssetBundleBuild[] SetupBundles() { var content = ContentBuildInterface.GenerateAssetBundleBuilds(); // Add another AssetBundle with the URP shaders Array.Resize(ref content, content.Length + 1); content[content.Length - 1].assetBundleName = k_UrpBundleName; // Only include the Lit shader for faster builds content[content.Length - 1].assetNames = new string[] { "Packages/com.unity.render-pipelines.universal/Shaders/Lit.shader" }; // Uncomment these lines to include all shaders from URP //var urpShaders = AssetDatabase.FindAssets("t:shader", new string[] { "Packages/com.unity.render-pipelines.universal/Shaders" }); //var shaderAssetNames = new List<String>(); //foreach (var guid in urpShaders) //{ // shaderAssetNames.Add(AssetDatabase.GUIDToAssetPath(guid)); //} //content[content.Length - 1].assetNames = shaderAssetNames.ToArray(); return content; } static void PrepareOutputPath(string outputPath) { if (Directory.Exists(outputPath)) Directory.Delete(outputPath, true); Directory.CreateDirectory(outputPath); } }
isabella232/sol-games-unity-samples
<|start_filename|>js/localization.js<|end_filename|> var Localization = function() { this.languages = { "af" : { lang : "Afrikaans", encoding : [ "iso-8859-1", "windows-1252" ] }, "sq" : { lang : "Albanian", encoding : [ "iso-8859-1", "windows-1252" ] }, "ar" : { lang : "Arabic", encoding : [ "iso-8859-6", "windows-1256" ] }, "bat" : { lang : "Baltic", encoding : [ "iso-8859-4", "iso-8859-13", "windows-1257" ] }, "eu" : { lang : "Basque", encoding : [ "iso-8859-1", "windows-1252" ] }, "pb" : { lang : "Brazillian", encoding : [ "iso-8859-1" ] }, "bg" : { lang : "Bulgarian", encoding : [ "iso-8859-5" ] }, "be" : { lang : "Byelorussian", encoding : [ "iso-8859-6" ] }, "ca" : { lang : "Catalan", encoding : [ "iso-8859-1", "windows-1252" ] }, "hr" : { lang : "Croatian", encoding : [ "iso-8859-2", "windows-1250" ] }, "cs" : { lang : "Czech", encoding : [ "iso-8859-2" ] }, "da" : { lang : "Danish", encoding : [ "iso-8859-1", "windows-1252" ] }, "nl" : { lang : "Dutch", encoding : [ "iso-8859-1", "windows-1252" ] }, "en" : { lang : "English", encoding : [ "iso-8859-1", "windows-1252" ] }, "eo" : { lang : "Esperanto", encoding : [ "iso-8859-3" ] }, "et" : { lang : "Estonian", encoding : [ "iso-8859-15" ] }, "fo" : { lang : "Faroese", encoding : [ "iso-8859-1", "windows-1252" ] }, "fi" : { lang : "Finnish", encoding : [ "iso-8859-1", "windows-1252" ] }, "fr" : { lang : "French", encoding : [ "iso-8859-1", "windows-1252" ] }, "gl" : { lang : "Galician", encoding : [ "iso-8859-1", "windows-1252" ] }, "de" : { lang : "German", encoding : [ "iso-8859-1", "windows-1252" ] }, "el" : { lang : "Greek", encoding : [ "iso-8859-7", "windows-1253" ] }, "iw" : { lang : "Hebrew", encoding : [ "iso-8859-8", "windows-1255" ] }, "hu" : { lang : "Hungarian", encoding : [ "iso-8859-2" ] }, "is" : { lang : "Icelandic", encoding : [ "iso-8859-1", "windows-1252" ] }, "ga" : { lang : "Irish", encoding : [ "iso-8859-1", "windows-1252" ] }, "it" : { lang : "Italian", encoding : [ "iso-8859-1", "windows-1252" ] }, "ja" : { lang : "Japanese", encoding : [ "shift_jis", "iso-2022-jp", "euc-jp" ] }, "ko" : { lang : "Korean", encoding : [ "euc-kr" ] }, "lv" : { lang : "Latvian", encoding : [ "iso-8859-13", "windows-1257" ] }, "lt" : { lang : "Lithuanian", encoding : [ "iso-8859-13", "windows-1257" ] }, "mk" : { lang : "Macedonian", encoding : [ "iso-8859-5", "windows-1251" ] }, "mt" : { lang : "Maltese", encoding : [ "iso-8859-3" ] }, "no" : { lang : "Norwegian", encoding : [ "iso-8859-1", "windows-1252" ] }, "pl" : { lang : "Polish", encoding : [ "iso-8859-2" ] }, "pt" : { lang : "Portuguese", encoding : [ "iso-8859-1", "windows-1252" ] }, "ro" : { lang : "Romanian", encoding : [ "iso-8859-16" ] }, "ru" : { lang : "Russian", encoding : [ "koi8-r", "iso-8859-5" ] }, "gd" : { lang : "Scottish", encoding : [ "iso-8859-1", "windows-1252" ] }, "sr" : { lang : "Serbian cyrillic", encoding : [ "windows-1251", "iso-8859-5" ] }, "sr" : { lang : "Serbian latin", encoding : [ "iso-8859-2", "windows-1250" ] }, "sk" : { lang : "Slovak", encoding : [ "iso-8859-2" ] }, "sl" : { lang : "Slovenian", encoding : [ "iso-8859-2", "windows-1250" ] }, "es" : { lang : "Spanish", encoding : [ "iso-8859-1", "windows-1252" ] }, "sv" : { lang : "Swedish", encoding : [ "iso-8859-1", "windows-1252" ] }, "tr" : { lang : "Turkish", encoding : [ "iso-8859-9", "windows-1254" ] }, "uk" : { lang : "Ukrainian", encoding : [ "iso-8859-5" ] } } } module.exports = new Localization(); <|start_filename|>Gruntfile.js<|end_filename|> module.exports = function (grunt) { grunt.initConfig({ nodewebkit: { options: { keep_nw: true, build_dir: './builds', // Where the build version of my node-webkit app is saved mac: true, // We want to build it for mac win: true, // We want to build it for win linux32: true, // We don't need linux32 linux64: true, // We don't need linux64 mac_icns: './src/images/flixtor-ico.icns' }, src: ['./src/frames/**', './src/fonts/**', './src/images/**', './src/js/**', './src/node_modules/**', './src/styles/**', './src/package.json'] // Your node-wekit app }, copy: { main: { files: [ { src: './librairies/win/ffmpegsumo.dll', dest: './builds/releases/Flixtor/win/Flixtor/ffmpegsumo.dll', flatten: true }, { src: './librairies/win/ffmpegsumo.dll', dest: './builds/cache/win/<%= nodewebkit.options.version %>/ffmpegsumo.dll', flatten: true }, { src: './librairies/mac/ffmpegsumo.so', dest: './builds/releases/Flixtor/mac/Flixtor.app/Contents/Frameworks/node-webkit Framework.framework/Libraries/ffmpegsumo.so', flatten: true }, { src: './librairies/mac/ffmpegsumo.so', dest: './builds/cache/mac/<%= nodewebkit.options.version %>/node-webkit.app/Contents/Frameworks/node-webkit Framework.framework/Libraries/ffmpegsumo.so', flatten: true }, { src: './librairies/linux64/libffmpegsumo.so', dest: './builds/releases/Flixtor/linux64/Flixtor/libffmpegsumo.so', flatten: true }, { src: './librairies/linux64/libffmpegsumo.so', dest: './builds/cache/linux64/<%= nodewebkit.options.version %>/libffmpegsumo.so', flatten: true }, { src: './librairies/linux32/libffmpegsumo.so', dest: './builds/releases/Flixtor/linux32/Flixtor/libffmpegsumo.so', flatten: true }, { src: './librairies/linux32/libffmpegsumo.so', dest: './builds/cache/linux32/<%= nodewebkit.options.version %>/libffmpegsumo.so', flatten: true } ] } } }); grunt.loadNpmTasks('grunt-contrib-copy'); grunt.loadNpmTasks('grunt-node-webkit-builder'); grunt.registerTask('default', ['nodewebkit', 'copy']); } <|start_filename|>js/callwcf.js<|end_filename|> var utilities = require('../js/utilities.js'); //External functions var searchTable = function (tableName, searchKey, searchValue, ext, sorColumn, sortReverse, sortTypeId, randomSort, randomSeed, skip, max, callback) { $ = window.$; if (!ext) { ext = ""; } var input = parseSearch(searchKey, searchValue); var BasicHttpBinding = require('wcf.js').BasicHttpBinding, Proxy = require('wcf.js').Proxy, binding = new BasicHttpBinding({ SecurityMode: "None" }), proxy = new Proxy(binding, "http://www.torrentlookup.com/services/v4/services/extensionservices/searchservice.svc"), message = "<Envelope xmlns='http://schemas.xmlsoap.org/soap/envelope/'>" + "<Header />" + "<Body>" + "<JSONSearch xmlns='http://tempuri.org/'>" + "<tableName>" + tableName + "</tableName>" + "<input>" + input + " " + ext + "</input>" + "<skip>" + skip + "</skip>" + "<max>" + max + "</max>" + "<total>0</total>" + "<sortColumn>" + sorColumn + "</sortColumn>" + "<sortReverse>" + sortReverse + "</sortReverse>" + "<sortType>" + sortTypeId + "</sortType>" + "<randomSort>" + randomSort + "</randomSort>" + "<randomSeed>" + randomSeed + "</randomSeed>" + "</JSONSearch>" + "</Body>" + "</Envelope>" proxy.send(message, "http://tempuri.org/ISearchService/JSONSearch", function (response, ctx) { try{ var results = $(response).find("JSONSearchResult").text(); var total = $(response).find("Total").text(); results = results.replace(/(\r\n|\n|\r)/gm, ""); var jsonResult = JSON.parse(results); jsonResult.Total = total; callback(jsonResult); }catch(error) { utilities.showMsg("Error","Flixtor services are unavailable at the moment, please try again later. You can follow us on facebook to find out when the service will be online. <a target='blank' href='http://www.facebook.com/flixtorapp'>http://www.facebook.com/flixtorapp</a>"); callback("error"); } }); } var getSimpleTopSerieTorrents = function (serieId, callback) { $ = window.$; var BasicHttpBinding = require('wcf.js').BasicHttpBinding, Proxy = require('wcf.js').Proxy, binding = new BasicHttpBinding({ SecurityMode: "None" }), proxy = new Proxy(binding, "http://www.torrentlookup.com/services/v4/services/torrentservices/torrentservice.svc"), message = "<Envelope xmlns='http://schemas.xmlsoap.org/soap/envelope/'>" + "<Header />" + "<Body>" + "<JSONSimpleTopSerieTorrents xmlns='http://tempuri.org/'>" + "<serieId>" + serieId + "</serieId>" + "</JSONSimpleTopSerieTorrents>" + "</Body>" + "</Envelope>"; proxy.send(message, "http://tempuri.org/ITorrentService/JSONSimpleTopSerieTorrents", function (response, ctx) { var results = $(response).find("JSONSimpleTopSerieTorrentsResult").text(); results = results.replace(/(\r\n|\n|\r)/gm, ""); var jsonResult = JSON.parse(results); callback(jsonResult); }); } var parseSearch = function (key, search) { if (search) { search = search.replace("[^\w\s_]", " ").replace("_", " "); var terms = search.trim().split(' '); $(terms).each(function (index) { terms[index] = "+" + key + ":" + terms[index].trim() + "*"; }); return terms.join(" "); } return ""; } var getGenres = function (id) { $ = window.$; $.getJSON("http://www.torrentlookup.com/services/v4/services/mediaservices/mediadataservice.svc/Genres?$format=json", function (data) { var items = []; $.each(data.d.results, function (key, val) { if (val.Name.indexOf("&") == -1) { $('#' + id).append("<li><a onclick=\"changeFilterGenre('" + val.Name + "');\">" + val.Name + "</a></li>"); } //items.push( "<li id='" + key + "'>" + val + "</li>" ); }); }); } var getEpisodeTorrents = function (episodeId, max, callback) { $ = window.$; var BasicHttpBinding = require('wcf.js').BasicHttpBinding, Proxy = require('wcf.js').Proxy, binding = new BasicHttpBinding({ SecurityMode: "None" }), proxy = new Proxy(binding, "http://www.torrentlookup.com/services/v4/services/torrentservices/torrentservice.svc"), message = "<Envelope xmlns='http://schemas.xmlsoap.org/soap/envelope/'>" + "<Header />" + "<Body>" + "<JSONEpisodeTorrents xmlns='http://tempuri.org/'>" + "<episodeId>" + episodeId + "</episodeId>" + "<max>" + max + "</max>" + "</JSONEpisodeTorrents>" + "</Body>" + "</Envelope>"; proxy.send(message, "http://tempuri.org/ITorrentService/JSONEpisodeTorrents", function (response, ctx) { var results = $(response).find("JSONEpisodeTorrentsResult").text(); results = results.replace(/(\r\n|\n|\r)/gm, ""); var jsonResult = JSON.parse(results); callback(jsonResult); }); } //Exports module.exports.getGenres = getGenres; module.exports.parseSearch = parseSearch; module.exports.getSimpleTopSerieTorrents = getSimpleTopSerieTorrents; module.exports.getEpisodeTorrents = getEpisodeTorrents; module.exports.searchTable = searchTable; <|start_filename|>js/subtitle.js<|end_filename|> //External modules var openSubs = require('opensubtitles-client'); //Max 200 srt download per day :S var http = require('http'); var zlib = require('zlib'); var path = require('path'); var request = require('request'); var url = require('url'); var fs = require('fs'); var charset = require('jschardet'); var iconv = require('iconv-lite'); var localization = require('../js/localization.js'); var SubManager = function(port) { //Initialization //Load the http server var manager = {}; manager.server = http.createServer(); manager.server.listen(port); //Assign variables manager.list = []; manager.config = { size: 30, color: '#ffff00' } //Return the subtitle when a request is sent to the subManager server. Ex: http://127.0.0.1:3550/en.srt manager.server.on('request', function(req, res) { var u = url.parse(req.url); if (u.pathname === '/favicon.ico') return res.end(); var filename = path.basename(u.pathname, '.srt'); var sub = manager.get(filename); if(sub) { if(sub.isDownloaded) { if(sub.data) { res.end(manager.decode(sub.data, sub.iso639)); } }else { sub.download(function (data) { res.end(manager.decode(data, sub.iso639)); }); } } }); //Search for subtitle with the torrent name manager.searchSubtitles = function (value, cb) { manager.list = []; //Clear the subtitle list openSubs.api.login().done( function(token){ openSubs.api.search(token, 'all', value).done( function(results){ for(var i=0; i < results.length; i++) { var result = results[i]; if(result.SubFormat === 'srt') { var found = false; for(var a = 0; a < manager.list.length; a++) { if (manager.list[a].iso639 == result.ISO639) { found = true; break; } } if(!found) { var subtitle = new Subtitle(result.LanguageName, result.ISO639, result.SubDownloadLink); manager.list.push(subtitle); } } } console.log(manager.list); openSubs.api.logout(token); cb(true); } ); } ); //If an error occurs show it in the console openSubs.api.on('error', function(e){ console.log(e); cb(false); }); } manager.hasSubtitles = function() { if(manager.list) { if(manager.list.length > 0) { return true; } } return false; } //Get the subtitle from the current subManager manager.get = function(lang) { if(manager.hasSubtitles) { for(i = 0; i < manager.list.length; i++) { if(manager.list[i].iso639 === lang) { return manager.list[i]; } } } } //Decode a specific subtitle Iconv-lite is fucking awesome manager.decode = function(data, iso639) { var charsetData = charset.detect(data); var detecdedEncoding = charsetData.encoding; var targetEncoding = 'utf8'; //Charset is not detecting the good encoding for certain language like pt-br (WTF I get IBM855 when choosing brazillian :O) if(detecdedEncoding == 'IBM855' || detecdedEncoding == 'windows-1250' || detecdedEncoding == 'windows-1251' || detecdedEncoding == 'windows-1252' || detecdedEncoding == 'windows-1254' || detecdedEncoding == 'windows-1255') { if(iso639) { var lang = localization.languages[iso639]; if(lang) { detecdedEncoding = lang.encoding[0]; //We take the true real encoding now! console.log(detecdedEncoding); } } } //We don't need to convert UTF-8 if(detecdedEncoding != 'utf-8') { data = iconv.encode(iconv.decode(data, detecdedEncoding), targetEncoding); } return data.toString('utf-8'); } //Load saved subtitle config manager.loadConfig = function() { if (window.localStorage.getItem('subtitleConfig')) { manager.config = JSON.parse(window.localStorage.getItem('subtitleConfig')); } else { window.localStorage.setItem('subtitleConfig', JSON.stringify(manager.config)); } } //Reset subtitle config manager.resetConfig = function() { window.localStorage.removeItem('subtitleConfig'); } //Save subtitle config manager.saveConfig = function() { window.localStorage.setItem('subtitleConfig', JSON.stringify(manager.config)); } return manager; } var Subtitle = function(lang, iso639, subLink) { var sub = {}; sub.iso639 = iso639; sub.languageName = lang; sub.downloadLink = subLink; sub.isDownloaded = false; sub.data; //Save subtitle to a file sub.save = function(filePath) { if(!sub.isDownloaded) { sub.download(); } //Save var wstream = fs.createWriteStream(filePath); sub.data.pipe(wstream); } //Download & decompress the subtitle sub.download = function(cb) { //Download var req = request.get(subLink); req.on('response', function (res) { var chunks = []; res.on('data', function (chunk) { chunks.push(chunk); }); res.on('end', function () { var buffer = Buffer.concat(chunks); //Decompress zlib.gunzip(buffer, function (err, decoded) { sub.data = decoded; sub.isDownloaded = true; cb(decoded); }); }); }); req.on('error', function (err) { console.log(err); }); } //Add delay to the subtitle of your choice TODO!! sub.addDelay = function(value) { } //Remove delay to the subtitle of your choice TODO!! sub.removeDelay = function(value) { } return sub; } module.exports = SubManager; <|start_filename|>js/main.js<|end_filename|> //External modules var address = require('network-address'); var http = require('http'); var fs = require('fs'); var peerflix = require('peerflix'); var request = require('request'); var gui = window.require('nw.gui'); var win = gui.Window.get(); var requestManager = require('request'); var path = require('path'); var NA = require('nodealytics'); var os = require('os'); //Internal modules var subtitle = require('../js/subtitle.js'); var utilities = require('../js/utilities.js'); var localization = require('../js/localization.js'); //Global variables var engine, subManager, enginePort, subPort; NA.initialize('UA-42435534-2', 'www.flixtor.com', function () {}); NA.trackPage('Torrents', '/fixtorapp/open/', function (err, resp) {}); //Track when user is opening the application var playTorrent = function (infoHash) { var torrent; enginePort = 3549 //popcorn-time use 8888 so let's change it to 3549 which means [flix] in telephone numbers :P subPort = 3550 var randPort = Math.floor(Math.random() * (65535 - 49152 + 1)) + 49152; //Choose port between 49152 and 65535 if (engine) { if (!engine.swarm._destroyed) { console.log("The engine is already starded!"); return; } } engine = peerflix( "magnet:?xt=urn:btih:" + infoHash, { connections: os.cpus().length > 1 ? 100 : 30, path: './data', port: enginePort }); var started = Date.now(); var wires = engine.swarm.wires; var swarm = engine.swarm; engine.on('ready', function() { console.log(engine.torrent); console.log(engine.tracker); subManager = subtitle(subPort); subManager.searchSubtitles(engine.torrent.name, function (success) { if(!success) { engine.skipSubtitles = true; } engine.langFound = success; }); NA.trackEvent('Player', 'Play torrent', engine.torrent.infoHash + " - " + engine.torrent.name, function (err, resp) {}); }); engine.server.on('listening', function () { if (!engine.server.address()) return; var port = engine.server.address().port; console.log(port); var href = 'http://' + address() + ':' + port + '/'; console.log('Server is listening on ' + href); }); var statsLog = function () { var runtime = Math.floor((Date.now() - started) / 1000); console.log(utilities.toBytes(swarm.downloaded) + " - " + runtime + " - " + swarm.queued); if (!swarm._destroyed) { setTimeout(statsLog, 500); } }; statsLog(); engine.server.once('error', function (err) { engine.server.listen(0); console.log(err); }); //engine.server.listen(enginePort); } var rmDir = function(dirPath) { try { var files = fs.readdirSync(dirPath); } catch(e) { return; } if (files.length > 0) { for (var i = 0; i < files.length; i++) { var filePath = dirPath + '/' + files[i]; if (fs.statSync(filePath).isFile()) fs.unlinkSync(filePath); } } }; var stopDownload = function () { if (engine) { try { engine.destroy(); engine.server.listen(0); engine.server.close(); if(subManager) { subManager.server.close(); } } catch (e) { console.log(e); } console.log("Download has stopped!"); rmDir("./data"); console.log("Data has been deleted!"); return true; } return false; } var stopPlayer = function (backCount) { stopDownload(); window.history.go(-backCount); } var closeApp = function () { stopDownload(); var $ = window.$; //Disable prompt if VLC because VLC is always in front of every element. if($("#VLC").length) { gui.App.closeAllWindows(); return; } //Ask the user if he really want to close the app utilities.showPrompt("Confirm close","You are about to close the application. Are you sure you want to continue?", "question", function (answer) { if(answer) { gui.App.closeAllWindows(); } }); } var getEngine = function() { return engine; } var getSubManager = function () { return subManager; } function toggleFullScreen() { if (win.isFullscreen) { win.leaveFullscreen(); } else { win.enterFullscreen(); } win.focus(); } function minimize() { win.minimize(); } function goBack() { if(engine) { stopDownload(); } if(window.sessionStorage.history) { var historyList = JSON.parse(window.sessionStorage.history); if(historyList.length > 0) { window.location = historyList[(historyList.length - 1)]; var index = historyList.indexOf(historyList.length - 1); historyList.splice(index, 1); window.sessionStorage.history = JSON.stringify(historyList); } } } //url must be absolute function go(url) { window.location = url; saveHistory(url); } function changeFrame (frame) { var url = frame + ".html"; window.location = url; saveHistory(url); } function saveHistory(url) { var url = window.location.href; if(window.location.href == path) return; var historyList = []; if(window.sessionStorage.history) { historyList = JSON.parse(window.sessionStorage.history); //check for back duplicate if(historyList.length > 0) { if(historyList[(historyList.length - 1)] == url) { return; } } } historyList.push(url); window.sessionStorage.history = JSON.stringify(historyList); } //Disable file drop over window.addEventListener("dragover", function (e) { e = e || event; e.preventDefault(); }, false); //Disable file drop over the application window.addEventListener("drop", function (e) { e = e || event; e.preventDefault(); }, false); //Disable file drap window.addEventListener("dragstart", function (e) { e = e || event; e.preventDefault(); }, false); win.on("loaded", function (e) { //Check for internet connection on startup utilities.hasInternetConnection(function (hasInternet) { if (!hasInternet) { utilities.showPrompt("No internet access", "You don't have access to internet, please check your connection and try again.", "ok", function(answer) { gui.App.closeAllWindows(); }); } }); //$(".top-titlebar-back-button").removeClass("hide"); }); var getPlatform = function() { return process.platform; } //Force the app to focus on startup win.focus(); //Exports module.exports.minimize = minimize; module.exports.toggleFullScreen = toggleFullScreen; module.exports.stopDownload = stopDownload; module.exports.stopPlayer = stopPlayer; module.exports.closeApp = closeApp; module.exports.playTorrent = playTorrent; module.exports.changeFrame = changeFrame; module.exports.NA = NA; module.exports.getEngine = getEngine; module.exports.getSubManager = getSubManager; module.exports.goBack = goBack; module.exports.go = go; process.on('uncaughtException', function (err) { //Logging with google analytics //If internet connection is available we log the error utilities.hasInternetConnection(function (hasInternet) { if (hasInternet) { NA.trackEvent('FlixtorApp', 'Error Occured', err.message + " -> " + err.stack, function (err, resp) {}); } }); utilities.showPrompt("An uncaughtException was found", "Error: <span class='text-danger'>" + err.message.toString() + "</span><br/>The program will end.", "ok", function(answer) { process.exit(1); }); }); <|start_filename|>js/videojsButtons.js<|end_filename|> //Available buttons var fontsize, fontcolor; //Font size button videojs.FontSize = videojs.Button.extend({ /** @constructor */ init: function(player, options){ videojs.Button.call(this, player, options); this.on('click', this.onClick); } }); videojs.FontSize.prototype.onClick = function() { }; var createFontSizeButton = function() { var props = { className: 'vjs-fontsize-button vjs-menu-button vjs-control', innerHTML: '<div class="vjs-control-content"><span class="vjs-control-text">Set font size</span></div><div class="vjs-menu"><ul class="vjs-menu-content"><li class="vjs-menu-item" data-val="100">Huge [100]</li><li class="vjs-menu-item" data-val="50">Bigger [50]</li><li class="vjs-menu-item" data-val="40">Big [40]</li><li class="vjs-menu-item" data-val="30">Medium [30]</li><li class="vjs-menu-item" data-val="20">Small [20]</li><li class="vjs-menu-item" data-val="16">Smaller [16]</li></ul></div>', role: 'button' }; return videojs.Component.prototype.createEl(null, props); }; videojs.plugin('fontsize', function() { var options = { 'el' : createFontSizeButton() }; fontsize = new videojs.FontSize(this, options); this.controlBar.el().appendChild(fontsize.el()); }); //Font color button videojs.FontColor = videojs.Button.extend({ /** @constructor */ init: function(player, options){ videojs.Button.call(this, player, options); this.on('click', this.onClick); } }); videojs.FontColor.prototype.onClick = function() { }; var createFontColorButton = function() { var props = { className: 'vjs-fontcolor-button vjs-menu-button vjs-control', innerHTML: '<div class="vjs-control-content"><span class="vjs-control-text">Set font color</span></div><div class="vjs-menu"><ul class="vjs-menu-content"><li class="vjs-menu-item" data-val="#ffffff">White</li><li class="vjs-menu-item" data-val="#ffff00">yellow</li><li class="vjs-menu-item" data-val="#ff0000">red</li><li class="vjs-menu-item" data-val="rainbow">rainbow</li></ul></div>', role: 'button' }; return videojs.Component.prototype.createEl(null, props); }; videojs.plugin('fontcolor', function() { var options = { 'el' : createFontColorButton() }; fontcolor = new videojs.FontColor(this, options); this.controlBar.el().appendChild(fontcolor.el()); }); <|start_filename|>styles/bootly.css<|end_filename|> body{ overflow: hidden; background: url('../images/bg-flixtor.jpg') no-repeat center center fixed; -webkit-background-size: cover; background-size: cover; color: #e9e9e9; } a { cursor: pointer; } #content-wrapper { margin-top: 38px; } /* Top bar */ #top-bar { background-color: #efefef; height: 40px; z-index: 999999; color:#333333; position:fixed; top:0; width: 100%; -webkit-user-select: none; -webkit-app-region: drag; border-bottom:thin solid black; -moz-box-shadow: 0 0 20px 5px black; -webkit-box-shadow: 0 0 20px 5px black; box-shadow: 0 0 20px 5px black; } .top-titlebar-text { text-align: center; line-height: 40px; } .top-titlebar-close-button { position: absolute; right: 10px; margin-top: 10px; -webkit-app-region: no-drag; cursor: pointer; } .top-titlebar-settings-button { position: absolute; right: 40px; margin-top: 10px; -webkit-app-region: no-drag; cursor: pointer; } .top-titlebar-minimize-button { position: absolute; right: 70px; margin-top: 14px; -webkit-app-region: no-drag; cursor: pointer; } .top-titlebar-fullscreen-button { position: absolute; right: 40px; margin-top: 10px; -webkit-app-region: no-drag; cursor: pointer; } .top-titlebar-back-button { position: absolute; left: 10px; margin-top: 10px; -webkit-app-region: no-drag; cursor: pointer; -webkit-transform: rotate(180deg); -webkit-transform: scale(-1, 1); } .top-titlebar-close-button:hover, .top-titlebar-settings-button:hover { opacity: 0.8; } /* Side bar */ .side-bar{ position: fixed; margin-top: 2px; height: 100%; border-right: thin solid black; padding-top: 10px; background: rgba(0, 0, 0, 0.6); -webkit-animation: slide 0.5s forwards; } #side-bar-full { width: 150px; left:-150px;s } #side-bar-small { width: 35px; left:-35px; } @-webkit-keyframes slide { 100% { left: 0; } } .side-bar ul { padding: 0; list-style: none; } #side-bar-full ul li { margin: 10px 0 10px 10px; padding: 5px 10px; cursor: pointer; } #side-bar-full ul li:hover, #side-bar-full ul li.on { border-right: 3px solid #e9e9e9; } #side-bar-small ul li { padding: 5px 10px; cursor: pointer; } #side-bar-small ul li:hover, #side-bar-small ul li.on { background: rgba(0,0,0,0.8); } .side-bar ul li:hover a, .side-bar ul li.on a { color:white; } .side-bar ul li a { text-decoration: none; color: #e9e9e9; } /* Content */ #content { margin-left: 150px; padding-top: 2px; } @media all and (max-width:768px) { #content { margin-left: 35px; } } /* Tables */ .table-light th{font-weight:bold;padding:5px 10px;border-bottom:thin solid #ccc;} .table-light td{padding:5px;} .table-normal th{padding:5px 10px; font-weight: normal;} .table-normal td{padding:2px;color:#c7c7c7} .table-box{border:thin solid #ccc;padding:5px;} .table-box th{font-weight:bold;padding:10px;border-bottom:1px dashed #ccc;} .table-box td{padding:5px;border-bottom:1px solid #e6e6e6;} .table-header-left th{text-align:left;padding-left:0;} .table-fixed{table-layout:fixed;} .table-float tr td{float:left;margin:10px 0 0 10px;} .table-align-middle tr td{vertical-align:middle;} /* Helpers */ .width-100{width:100%;} .box {background-color: #eee; border:thin solid #D9D9D9} .pt-5{padding-top:5px;} .mt-5{margin-top:5px;} .pt-10{padding-top:10px;} .mt-10{margin-top:10px;} .pt-20{padding-top:20px;} .mt-20{margin-top:20px;} .pt-30{padding-top:30px;} .mt-30{margin-top:30px;} .pb-5{padding-bottom:5px;} .mb-5{margin-bottom:5px;} .pb-10{padding-bottom:10px;} .mb-10{margin-bottom:10px;} .pb-20{padding-bottom:20px;} .mb-20{margin-bottom:20px;} .pb-30{padding-bottom:30px;} .mb-30{margin-bottom:30px;} .pl-5{padding-left:5px;} .ml-5{margin-left:5px;} .pl-10{padding-left:10px;} .ml-10{margin-left:10px;} .pl-20{padding-left:20px;} .ml-20{margin-left:20px;} .pl-30{padding-left:30px;} .ml-30{margin-left:30px;} .pr-5{padding-right:5px;} .mr-5{margin-right:5px;} .pr-10{padding-right:10px;} .mr-10{margin-right:10px;} .pr-20{padding-right:20px;} .mr-20{margin-right:20px;} .pr-30{padding-right:30px;} .mr-30{margin-right:30px;} .p-0{padding:0 !important;} .p-5{padding:5px;} .p-10{padding:10px;} .p-20{padding:20px;} .p-30{padding:30px;} .m-5{margin:5px;} .m-10{margin:10px;} .m-20{margin:20px;} .m-30{margin:30px;} .ptb-5{padding:5px 0;} .ptb-10{padding:10px 0;} .ptb-20{padding:20px 0;} .ptb-30{padding:30px 0;} .mtb-5{margin:5px 0;} .mtb-10{margin:10px 0;} .mtb-20{margin:20px 0;} .mtb-30{margin:30px 0;} .font-10{font-size:10px;} .font-12{font-size:12px;} .font-14{font-size:14px;} .font-16{font-size:16px;} .font-18{font-size:18px;} .font-20{font-size:20px;} .font-22{font-size:22px;} .font-24{font-size:24px;} .text-ellipsis { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } .color-light-black{color:#333333;} .color-blue{color:#176ca7;} .color-light-blue{color:#31b0d5;} .color-green{color:#1B8F54;} .color-gray{color:#707070;} .color-red{color:#D12828;} .color-white{color:#FFFFFF;} .color-orange{color:#e99002;} .float-clear{clear:both;} .float-left{float:left;} .float-right{float:right;} .text-center{text-align:center;} .text-left{text-align:left;} .text-right{text-align:right;} .img-box-contour { padding: 4px; background-color: #fff; border: 1px solid #ccc; border: 1px solid rgba(0, 0, 0, 0.2); -webkit-box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1); -moz-box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1); box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1); } textarea:hover, input:hover, textarea:active, input:active, textarea:focus, input:focus, button:focus, button:active, button:hover { outline:none; } a:hover { color: inherit; opacity: 0.7; } .black-input:hover { outline:none !important; -webkit-appearance:none !important; box-shadow: none !important; -webkit-box-shadow: 0 0 1px 1px rgba(0,0,0,1) !important ; border:none !important; } .black-input { background: rgba(255,255,255,0.3); color:#D5D5D5; border: none; border-radius: 0; } .header { border-bottom: 1px solid #dddddd; } /* bootstrap overrides */ .badge{ color:#3B5999; background-color:#fff; } .badge:hover, .badge-inverse{ background-color:#3B5999; color:#fff; } .page-header { margin-top: 55px; padding-top: 9px; border-top:1px solid #eeeeee; font-weight:700; text-transform:uppercase; letter-spacing:2px; } .panel-default .panel-heading { background-color:#f9fafb; color:#555555; } .modal-header, .modal-footer { background-color:#f2f2f2; font-weight:800; font-size:12px; } .modal-footer { margin-top: 0; } .modal-footer i, .well i { font-size:20px; color:#c0c0c0; } .modal-body { padding:0px; } .modal-body textarea.form-control { resize: none; border:0; box-shadow:0 0 0; } .modal { overflow-y: hidden; top:50px; } small.text-muted { font-family:courier,courier-new,monospace; } .alert { margin-bottom: 0; } ::-webkit-scrollbar-track { -webkit-box-shadow: inset 0 0 6px rgba(0,0,0,0.3); background-color: #ccc; } ::-webkit-scrollbar { width: 6px; background-color: #F5F5F5; } ::-webkit-scrollbar-thumb { background-color: #626262; } div.spinner-overlay { position: fixed; z-index: 1050; width: 100%; height: 100%; left:0; top: 0; bottom:0; background: rgba(0,0,0,0.5); background-image:url(../images/spinner.GIF); background-position: center; background-repeat: no-repeat; background-size:40px; } .stars-template { background: url('../images/tiny-star.png'); height: 14px; width: 69px; } .current-rating { background: url('../images/tiny-star-filled.png'); height: 14px; width: 72.45%; }
jakop345/Flixtor
<|start_filename|>app/Main.hs<|end_filename|> {-# LANGUAGE OverloadedStrings #-} module Main where import Control.Monad import DBus.Client import Data.Int import Data.Maybe import Data.Ratio import Data.Semigroup ((<>)) import qualified Data.Text as T import Data.Version (showVersion) import qualified GI.Gdk as Gdk import qualified GI.Gtk as Gtk import Graphics.UI.GIGtkStrut import Options.Applicative import qualified StatusNotifier.Host.Service as Host import StatusNotifier.TransparentWindow import StatusNotifier.Tray import System.Log.Logger import System.Posix.Process import Text.Printf import Paths_gtk_sni_tray (version) positionP :: Parser StrutPosition positionP = fromMaybe TopPos <$> optional ( flag' TopPos ( long "top" <> help "Position the bar at the top of the screen" ) <|> flag' BottomPos ( long "bottom" <> help "Position the bar at the bottom of the screen" ) <|> flag' LeftPos ( long "left" <> help "Position the bar on the left side of the screen" ) <|> flag' RightPos ( long "right" <> help "Position the bar on the right side of the screen" )) alignmentP :: Parser StrutAlignment alignmentP = fromMaybe Center <$> optional ( flag' Beginning ( long "beginning" <> help "Use beginning alignment" ) <|> flag' Center ( long "center" <> help "Use center alignment" ) <|> flag' End ( long "end" <> help "Use end alignment" )) sizeP :: Parser Int32 sizeP = option auto ( long "size" <> short 's' <> help "Set the size of the bar" <> value 30 <> metavar "SIZE" ) paddingP :: Parser Int32 paddingP = option auto ( long "padding" <> short 'p' <> help "Set the padding of the bar" <> value 0 <> metavar "PADDING" ) monitorNumberP :: Parser [Int32] monitorNumberP = many $ option auto ( long "monitor" <> short 'm' <> help "Display a tray bar on the given monitor" <> metavar "MONITOR" ) logP :: Parser Priority logP = option auto ( long "log-level" <> short 'l' <> help "Set the log level" <> metavar "LEVEL" <> value WARNING ) colorP :: Parser (Maybe String) colorP = optional $ strOption ( long "color" <> short 'c' <> help "Set the background color of the tray; See https://developer.gnome.org/gdk3/stable/gdk3-RGBA-Colors.html#gdk-rgba-parse for acceptable values" <> metavar "COLOR" ) expandP :: Parser Bool expandP = switch ( long "expand" <> help "Let icons expand into the space allocated to the tray" <> short 'e' ) startWatcherP :: Parser Bool startWatcherP = switch ( long "watcher" <> short 'w' <> help "Start a Watcher to handle SNI registration if one does not exist" ) noStrutP :: Parser Bool noStrutP = switch ( long "no-strut" <> help "Do not set strut properties for the gtk window" ) barLengthP :: Parser Rational barLengthP = option auto ( long "length" <> help "Set the proportion of the screen that the tray bar should occupy -- values are parsed as haskell rationals (e.g. 1 % 2)" <> value 1 ) overlayScaleP :: Parser Rational overlayScaleP = option auto ( long "overlay-scale" <> short 'o' <> help "The proportion of the tray icon's size that should be set for overlay icons." <> value (5 % 7) ) getColor colorString = do rgba <- Gdk.newZeroRGBA colorParsed <- Gdk.rGBAParse rgba (T.pack colorString) unless colorParsed $ do logM "StatusNotifier.Tray" WARNING "Failed to parse provided color" void $ Gdk.rGBAParse rgba "#000000" return rgba buildWindows :: StrutPosition -> StrutAlignment -> Int32 -> Int32 -> [Int32] -> Priority -> Maybe String -> Bool -> Bool -> Bool -> Rational -> Rational -> IO () buildWindows pos align size padding monitors priority maybeColorString expand startWatcher noStrut length overlayScale = do Gtk.init Nothing logger <- getLogger "StatusNotifier" saveGlobalLogger $ setLevel priority logger client <- connectSession logger <- getRootLogger pid <- getProcessID -- Okay to use a forced pattern here because we want to die if this fails anyway Just host <- Host.build Host.defaultParams { Host.dbusClient = Just client , Host.uniqueIdentifier = printf "standalone-%s" $ show pid , Host.startWatcher = startWatcher } let c1 = defaultStrutConfig { strutPosition = pos , strutAlignment = align , strutXPadding = padding , strutYPadding = padding } defaultRatio = ScreenRatio length configBase = case pos of TopPos -> c1 {strutHeight = ExactSize size, strutWidth = defaultRatio} BottomPos -> c1 {strutHeight = ExactSize size, strutWidth = defaultRatio} RightPos -> c1 {strutHeight = defaultRatio, strutWidth = ExactSize size} LeftPos -> c1 {strutHeight = defaultRatio, strutWidth = ExactSize size} buildWithConfig config = do let orientation = case strutPosition config of TopPos -> Gtk.OrientationHorizontal BottomPos -> Gtk.OrientationHorizontal _ -> Gtk.OrientationVertical tray <- buildTray host client TrayParams { trayOrientation = orientation , trayImageSize = Expand , trayIconExpand = expand , trayAlignment = align , trayOverlayScale = overlayScale , trayLeftClickAction = Activate , trayMiddleClickAction = SecondaryActivate , trayRightClickAction = PopupMenu } window <- Gtk.windowNew Gtk.WindowTypeToplevel when (not noStrut) $ setupStrutWindow config window maybe (makeWindowTransparent window) (getColor >=> Gtk.widgetOverrideBackgroundColor window [Gtk.StateFlagsNormal] . Just) maybeColorString Gtk.containerAdd window tray Gtk.widgetShowAll window runForMonitor monitor = buildWithConfig configBase {strutMonitor = Just monitor} if null monitors then buildWithConfig configBase else mapM_ runForMonitor monitors Gtk.main parser :: Parser (IO ()) parser = buildWindows <$> positionP <*> alignmentP <*> sizeP <*> paddingP <*> monitorNumberP <*> logP <*> colorP <*> expandP <*> startWatcherP <*> noStrutP <*> barLengthP <*> overlayScaleP versionOption :: Parser (a -> a) versionOption = infoOption (printf "gtk-sni-tray-standalone %s" $ showVersion version) ( long "version" <> help "Show the version number of gtk-sni-tray" ) main :: IO () main = join $ execParser $ info (helper <*> versionOption <*> parser) ( fullDesc <> progDesc "Run a standalone StatusNotifierItem/AppIndicator tray" )
taffybar/gtk-sni-tray
<|start_filename|>sample/src/main/java/com/warnyul/android/fastvideoview/sample/MainActivity.java<|end_filename|> /* * Copyright (C) 2014 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.warnyul.android.fastvideoview.sample; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import com.warnyul.android.fastvideoview.R; import com.warnyul.android.fastvideoview.sample.screens.AlphaSampleActivity; import com.warnyul.android.fastvideoview.sample.screens.RotatedSampleActivity; import com.warnyul.android.fastvideoview.sample.screens.VideoSampleActivity; /** * Activity for listing VideoView samples. */ public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button videoSample = (Button)findViewById(R.id.video_sample_button); Button rotatedSample = (Button)findViewById(R.id.rotated_sample_button); Button alphaSample = (Button)findViewById(R.id.alpha_sample_button); videoSample.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startVideoSample(); } }); rotatedSample.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startRotatedSample(); } }); alphaSample.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startAlphaSample(); } }); } /** * Starts the simple video sample activity. */ private void startVideoSample() { Intent intent = new Intent(this, VideoSampleActivity.class); startActivity(intent); } /** * Starts the rotated video sample activity. */ private void startRotatedSample() { Intent intent = new Intent(this, RotatedSampleActivity.class); startActivity(intent); } /** * Starts the alpha video sample activity. */ private void startAlphaSample() { Intent intent = new Intent(this, AlphaSampleActivity.class); startActivity(intent); } } <|start_filename|>sample/src/main/java/com/warnyul/android/fastvideoview/sample/screens/AlphaSampleActivity.java<|end_filename|> /* * Copyright (C) 2014 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.warnyul.android.fastvideoview.sample.screens; import android.os.Bundle; import android.widget.MediaController; import com.warnyul.android.fastvideoview.R; import com.warnyul.android.fastvideoview.sample.BaseSampleActivity; import com.warnyul.android.widget.FastVideoView; /** * Sample Activity for VideoView class transparent usage. */ public class AlphaSampleActivity extends BaseSampleActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_alpha_sample); FastVideoView videoView = (FastVideoView) findViewById(R.id.video); videoView.setMediaController(new MediaController(this)); videoView.setVideoURI(getVideoUri()); // Uncomment this line, when you want to set alpha from code. // videoView.setAlpha(0.5f); videoView.start(); } } <|start_filename|>video/src/main/java/com/warnyul/android/widget/FastVideoView.java<|end_filename|> /* * Copyright (C) 2014 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.warnyul.android.widget; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.res.Resources; import android.graphics.Canvas; import android.graphics.Rect; import android.graphics.SurfaceTexture; import android.media.AudioManager; import android.media.MediaPlayer; import android.net.Uri; import android.os.Handler; import android.os.Message; import android.util.AttributeSet; import android.util.Log; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.Surface; import android.view.SurfaceHolder; import android.view.TextureView; import android.view.View; import android.view.accessibility.AccessibilityEvent; import android.view.accessibility.AccessibilityNodeInfo; import android.widget.MediaController; import java.io.IOException; import java.util.Map; /** * <p>Displays a video file. The FastVideoView class * can load images from various sources (such as resources or content * providers), takes care of computing its measurement from the video so that * it can be used in any layout manager, and provides various display options * such as scaling and tinting. * </p> * <p><em>Note: FastVideoView does not retain its full state when going into the * background.</em> In particular, it does not restore the current play state, * play position, selected tracks. Applications should * save and restore these on their own in * {@link android.app.Activity#onSaveInstanceState} and * {@link android.app.Activity#onRestoreInstanceState}.</p> * <p>Also note that the audio session id (from {@link #getAudioSessionId}) may * change from its previously returned value when the FastVideoView is restored.</p> */ public class FastVideoView extends TextureView implements MediaController.MediaPlayerControl { private static final String TAG = FastVideoView.class.getSimpleName(); private static final int KEEP_SCREEN_ON_MSG = 1; // settable by the client private Uri mUri; private Map<String, String> mHeaders; // all possible internal states private static final int STATE_ERROR = -1; private static final int STATE_IDLE = 0; private static final int STATE_PREPARING = 1; private static final int STATE_PREPARED = 2; private static final int STATE_PLAYING = 3; private static final int STATE_PAUSED = 4; private static final int STATE_PLAYBACK_COMPLETED = 5; // mCurrentState is a VideoView object's current state. // mTargetState is the state that a method caller intends to reach. // For instance, regardless the VideoView object's current state, // calling pause() intends to bring the object to a target state // of STATE_PAUSED. private int mCurrentState = STATE_IDLE; private int mTargetState = STATE_IDLE; // All the stuff we need for playing and showing a video private Surface mSurface = null; private MediaPlayer mMediaPlayer = null; private int mAudioSession; private int mVideoWidth; private int mVideoHeight; private int mSurfaceWidth; private int mSurfaceHeight; private MediaController mMediaController; private MediaPlayer.OnCompletionListener mOnCompletionListener; private MediaPlayer.OnPreparedListener mOnPreparedListener; private MediaPlayer.OnErrorListener mOnErrorListener; private MediaPlayer.OnInfoListener mOnInfoListener; private SurfaceTextureListener mOnSurfaceTextureListener; private int mCurrentBufferPercentage; private int mSeekWhenPrepared; // recording the seek position while preparing private boolean mCanPause; private boolean mCanSeekBack; private boolean mCanSeekForward; private Rect mSurfaceFrame = new Rect(); private MediaPlayer.OnBufferingUpdateListener mOnBufferingUpdateListener; public FastVideoView(Context context) { super(context); initVideoView(); } public FastVideoView(Context context, AttributeSet attrs) { super(context, attrs); initVideoView(); } public FastVideoView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); initVideoView(); } @Override protected void onMeasure(final int widthMeasureSpec, final int heightMeasureSpec) { int width = getDefaultSize(mVideoWidth, widthMeasureSpec); int height = getDefaultSize(mVideoHeight, heightMeasureSpec); if (mVideoWidth > 0 && mVideoHeight > 0) { int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec); int widthSpecSize = MeasureSpec.getSize(widthMeasureSpec); int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec); int heightSpecSize = MeasureSpec.getSize(heightMeasureSpec); if (widthSpecMode == MeasureSpec.EXACTLY && heightSpecMode == MeasureSpec.EXACTLY) { // the size is fixed width = widthSpecSize; height = heightSpecSize; // for compatibility, we adjust size based on aspect ratio if (mVideoWidth * height < width * mVideoHeight) { //Log.i("@@@", "image too wide, correcting"); width = height * mVideoWidth / mVideoHeight; } else if (mVideoWidth * height > width * mVideoHeight) { //Log.i("@@@", "image too tall, correcting"); height = width * mVideoHeight / mVideoWidth; } } else if (widthSpecMode == MeasureSpec.EXACTLY) { // only the width is fixed, adjust the height to match aspect ratio if possible width = widthSpecSize; height = width * mVideoHeight / mVideoWidth; if (heightSpecMode == MeasureSpec.AT_MOST && height > heightSpecSize) { // couldn't match aspect ratio within the constraints height = heightSpecSize; } } else if (heightSpecMode == MeasureSpec.EXACTLY) { // only the height is fixed, adjust the width to match aspect ratio if possible height = heightSpecSize; width = height * mVideoWidth / mVideoHeight; if (widthSpecMode == MeasureSpec.AT_MOST && width > widthSpecSize) { // couldn't match aspect ratio within the constraints width = widthSpecSize; } } else { // neither the width nor the height are fixed, try to use actual video size width = mVideoWidth; height = mVideoHeight; if (heightSpecMode == MeasureSpec.AT_MOST && height > heightSpecSize) { // too tall, decrease both width and height height = heightSpecSize; width = height * mVideoWidth / mVideoHeight; } if (widthSpecMode == MeasureSpec.AT_MOST && width > widthSpecSize) { // too wide, decrease both width and height width = widthSpecSize; height = width * mVideoHeight / mVideoWidth; } } } else { // no size yet, just adopt the given spec sizes } setMeasuredDimension(width, height); } @Override public void onInitializeAccessibilityEvent(AccessibilityEvent event) { super.onInitializeAccessibilityEvent(event); event.setClassName(FastVideoView.class.getName()); } @Override public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) { super.onInitializeAccessibilityNodeInfo(info); info.setClassName(FastVideoView.class.getName()); } @Override public void setSurfaceTextureListener(SurfaceTextureListener listener) { mOnSurfaceTextureListener = listener; } public int resolveAdjustedSize(int desiredSize, int measureSpec) { return getDefaultSize(desiredSize, measureSpec); } private void initVideoView() { mVideoWidth = 0; mVideoHeight = 0; // setSurfaceTextureListener has been overwritten, and it is not call the super. super.setSurfaceTextureListener(mSurfaceTextureListener); setFocusable(true); setFocusableInTouchMode(true); requestFocus(); mCurrentState = STATE_IDLE; mTargetState = STATE_IDLE; } public void setVideoPath(String path) { setVideoURI(Uri.parse(path)); } public void setVideoURI(Uri uri) { setVideoURI(uri, null); } public void setVideoURI(Uri uri, Map<String, String> headers) { mUri = uri; mHeaders = headers; mSeekWhenPrepared = 0; openVideo(); requestLayout(); invalidate(); } public void stopPlayback() { if (mMediaPlayer != null) { mMediaPlayer.stop(); mMediaPlayer.release(); mMediaPlayer = null; mCurrentState = STATE_IDLE; mTargetState = STATE_IDLE; } } private void openVideo() { if (mUri == null || mSurface == null) { // not ready for playback just yet, will try again later return; } Context context = getContext(); // Tell the music playback service to pause Intent i = new Intent("com.android.music.musicservicecommand"); i.putExtra("command", "pause"); context.sendBroadcast(i); // we shouldn't clear the target state, because somebody might have // called start() previously release(false); try { mMediaPlayer = new MediaPlayer(); if (mAudioSession != 0) { mMediaPlayer.setAudioSessionId(mAudioSession); } else { mAudioSession = mMediaPlayer.getAudioSessionId(); } mMediaPlayer.setOnPreparedListener(mPreparedListener); mMediaPlayer.setOnVideoSizeChangedListener(mSizeChangedListener); mMediaPlayer.setOnCompletionListener(mCompletionListener); mMediaPlayer.setOnErrorListener(mErrorListener); mMediaPlayer.setOnBufferingUpdateListener(mBufferingUpdateListener); mCurrentBufferPercentage = 0; mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); mMediaPlayer.setDataSource(context, mUri, mHeaders); mMediaPlayer.setDisplay(mSurfaceHolder); mMediaPlayer.setScreenOnWhilePlaying(true); mMediaPlayer.prepareAsync(); // we don't set the target state here either, but preserve the // target state that was there before. mCurrentState = STATE_PREPARING; attachMediaController(); } catch (IOException ex) { Log.w(String.format("Unable to open content: %s", mUri), ex); mCurrentState = STATE_ERROR; mTargetState = STATE_ERROR; mErrorListener.onError(mMediaPlayer, MediaPlayer.MEDIA_ERROR_UNKNOWN, 0); return; } catch (IllegalArgumentException ex) { Log.w(String.format("Unable to open content: %s", mUri), ex); mCurrentState = STATE_ERROR; mTargetState = STATE_ERROR; mErrorListener.onError(mMediaPlayer, MediaPlayer.MEDIA_ERROR_UNKNOWN, 0); return; } } public void setMediaController(MediaController controller) { if (mMediaController != null) { mMediaController.hide(); } mMediaController = controller; attachMediaController(); } private void attachMediaController() { if (mMediaPlayer != null && mMediaController != null) { mMediaController.setMediaPlayer(this); View anchorView = this.getParent() instanceof View ? (View) this.getParent() : this; mMediaController.setAnchorView(anchorView); mMediaController.setEnabled(isInPlaybackState()); } } private void setFixedSize(int width, int height) { mSurfaceHolder.setFixedSize(width, height); } private boolean hasValidSize() { final float surfaceRatio = Math.round((mSurfaceWidth / (float) mSurfaceHeight) * 10.0f) / 10.0f; final float videoRatio = Math.round((mVideoWidth / (float) mVideoHeight) * 10.0f) / 10.0f; return (surfaceRatio == videoRatio); } MediaPlayer.OnVideoSizeChangedListener mSizeChangedListener = new MediaPlayer.OnVideoSizeChangedListener() { @Override public void onVideoSizeChanged(MediaPlayer mp, int width, int height) { mVideoWidth = mp.getVideoWidth(); mVideoHeight = mp.getVideoHeight(); if (mVideoWidth != 0 && mVideoHeight != 0) { setFixedSize(mVideoWidth, mVideoHeight); requestLayout(); } } }; MediaPlayer.OnPreparedListener mPreparedListener = new MediaPlayer.OnPreparedListener() { @Override public void onPrepared(MediaPlayer mp) { // briefly show the mediacontroller mCurrentState = STATE_PREPARED; // Get the capabilities of the player for this stream MetadataUtils.init(mp); if (MetadataUtils.isInitialized()) { mCanPause = !MetadataUtils.has(MetadataUtils.PAUSE_AVAILABLE) || MetadataUtils.getBoolean(MetadataUtils.PAUSE_AVAILABLE); mCanSeekBack = !MetadataUtils.has(MetadataUtils.SEEK_BACKWARD_AVAILABLE) || MetadataUtils.getBoolean(MetadataUtils.SEEK_BACKWARD_AVAILABLE); mCanSeekForward = !MetadataUtils.has(MetadataUtils.SEEK_FORWARD_AVAILABLE) || MetadataUtils.getBoolean(MetadataUtils.SEEK_FORWARD_AVAILABLE); } else { mCanPause = mCanSeekBack = mCanSeekForward = true; } if (mOnPreparedListener != null) { mOnPreparedListener.onPrepared(mMediaPlayer); } if (mMediaController != null) { mMediaController.setEnabled(true); } int seekToPosition = mSeekWhenPrepared; // mSeekWhenPrepared may be changed after seekTo() call if (seekToPosition != 0) { seekTo(seekToPosition); } if (mVideoWidth != 0 && mVideoHeight != 0) { //Log.i("@@@@", "video size: " + mVideoWidth +"/"+ mVideoHeight); setFixedSize(mVideoWidth, mVideoHeight); if (hasValidSize()) { // We didn't actually change the size (it was already at the size // we need), so we won't get a "surface changed" callback, so // start the video here instead of in the callback. if (mTargetState == STATE_PLAYING) { start(); if (mMediaController != null) { mMediaController.show(); } } else if (!isPlaying() && (seekToPosition != 0 || getCurrentPosition() > 0)) { if (mMediaController != null) { // Show the media controls when we're paused into a video and make 'em stick. mMediaController.show(0); } } } } else { // We don't know the video size yet, but should start anyway. // The video size might be reported to us later. if (mTargetState == STATE_PLAYING) { start(); } } } }; private MediaPlayer.OnCompletionListener mCompletionListener = new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { mCurrentState = STATE_PLAYBACK_COMPLETED; mTargetState = STATE_PLAYBACK_COMPLETED; if (mMediaController != null) { mMediaController.hide(); } if (mOnCompletionListener != null) { mOnCompletionListener.onCompletion(mMediaPlayer); } } }; private MediaPlayer.OnInfoListener mInfoListener = new MediaPlayer.OnInfoListener() { public boolean onInfo(MediaPlayer mp, int arg1, int arg2) { if (mOnInfoListener != null) { mOnInfoListener.onInfo(mp, arg1, arg2); } return true; } }; private MediaPlayer.OnErrorListener mErrorListener = new MediaPlayer.OnErrorListener() { @Override public boolean onError(MediaPlayer mp, int frameworkErr, int implErr) { mCurrentState = STATE_ERROR; mTargetState = STATE_ERROR; if (mMediaController != null) { mMediaController.hide(); } if (mOnErrorListener != null) { if (mOnErrorListener.onError(mp, frameworkErr, implErr)) { return true; } } /* Otherwise, pop up an error dialog so the user knows that * something bad has happened. Only try and pop up the dialog * if we're attached to a window. When we're going away and no * longer have a window, don't bother showing the user an error. */ if (getWindowToken() != null) { Resources r = getContext().getResources(); int messageId; if (frameworkErr == MediaPlayer.MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK) { messageId = android.R.string.VideoView_error_text_invalid_progressive_playback; } else { messageId = android.R.string.VideoView_error_text_unknown; } new AlertDialog.Builder(getContext()) .setMessage(messageId) .setPositiveButton(android.R.string.VideoView_error_button, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { /* If we get here, there is no onError listener, so * at least inform them that the video is over. */ if (mOnCompletionListener != null) { mOnCompletionListener.onCompletion(mMediaPlayer); } } } ) .setCancelable(false) .show(); } return true; } }; private MediaPlayer.OnBufferingUpdateListener mBufferingUpdateListener = new MediaPlayer.OnBufferingUpdateListener() { @Override public void onBufferingUpdate(MediaPlayer mp, int percent) { mCurrentBufferPercentage = percent; if (mOnBufferingUpdateListener != null) { mOnBufferingUpdateListener.onBufferingUpdate(mp, percent); } } }; /** * Register a callback to be invoked when the media file * is loaded and ready to go. * * @param l The callback that will be run */ public void setOnPreparedListener(MediaPlayer.OnPreparedListener l) { mOnPreparedListener = l; } /** * Register a callback to be invoked when the end of a media file * has been reached during playback. * * @param l The callback that will be run */ public void setOnCompletionListener(MediaPlayer.OnCompletionListener l) { mOnCompletionListener = l; } /** * Register a callback to be invoked when an error occurs * during playback or setup. If no listener is specified, * or if the listener returned false, VideoView will inform * the user of any errors. * * @param l The callback that will be run */ public void setOnErrorListener(MediaPlayer.OnErrorListener l) { mOnErrorListener = l; } /** * Register a callback to be invoked when an informational event * occurs during playback or setup. * * @param l The callback that will be run */ public void setOnInfoListener(MediaPlayer.OnInfoListener l) { mOnInfoListener = l; } private SurfaceTextureListener mSurfaceTextureListener = new SurfaceTextureListener() { @Override public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) { if (mOnSurfaceTextureListener != null) { mOnSurfaceTextureListener.onSurfaceTextureAvailable(surface, width, height); } mSurfaceWidth = width; mSurfaceHeight = height; mSurface = new Surface(surface); openVideo(); } @Override public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) { if (mOnSurfaceTextureListener != null) { mOnSurfaceTextureListener.onSurfaceTextureSizeChanged(surface, width, height); } mSurfaceWidth = width; mSurfaceHeight = height; boolean isValidState = (mTargetState == STATE_PLAYING); if (mMediaPlayer != null && isValidState && hasValidSize()) { if (mSeekWhenPrepared != 0) { seekTo(mSeekWhenPrepared); } start(); } } @Override public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) { if (mMediaController != null) { mMediaController.hide(); } release(true); if (mOnSurfaceTextureListener != null) { if (mOnSurfaceTextureListener.onSurfaceTextureDestroyed(surface)) return true; } if (mSurface != null) { mSurface.release(); mSurface = null; } return true; } @Override public void onSurfaceTextureUpdated(SurfaceTexture surface) { if (mOnSurfaceTextureListener != null) { mOnSurfaceTextureListener.onSurfaceTextureUpdated(surface); } } }; /* * release the media player in any state */ private void release(boolean cleartargetstate) { if (mMediaPlayer != null) { mMediaPlayer.reset(); mMediaPlayer.release(); mMediaPlayer = null; mCurrentState = STATE_IDLE; if (cleartargetstate) { mTargetState = STATE_IDLE; } } } @Override public boolean onTouchEvent(MotionEvent event) { if (isInPlaybackState() && mMediaController != null) { toggleMediaControlsVisibility(); } return false; } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { boolean isKeyCodeSupported = keyCode != KeyEvent.KEYCODE_BACK && keyCode != KeyEvent.KEYCODE_VOLUME_UP && keyCode != KeyEvent.KEYCODE_VOLUME_DOWN && keyCode != KeyEvent.KEYCODE_VOLUME_MUTE && keyCode != KeyEvent.KEYCODE_MENU && keyCode != KeyEvent.KEYCODE_CALL && keyCode != KeyEvent.KEYCODE_ENDCALL; if (isInPlaybackState() && isKeyCodeSupported && mMediaController != null) { if (keyCode == KeyEvent.KEYCODE_HEADSETHOOK || keyCode == KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE) { if (mMediaPlayer.isPlaying()) { pause(); mMediaController.show(); } else { start(); mMediaController.hide(); } return true; } else if (keyCode == KeyEvent.KEYCODE_MEDIA_PLAY) { if (!mMediaPlayer.isPlaying()) { start(); mMediaController.hide(); } return true; } else if (keyCode == KeyEvent.KEYCODE_MEDIA_STOP || keyCode == KeyEvent.KEYCODE_MEDIA_PAUSE) { if (mMediaPlayer.isPlaying()) { pause(); mMediaController.show(); } return true; } else { toggleMediaControlsVisibility(); } } return super.onKeyDown(keyCode, event); } private void toggleMediaControlsVisibility() { if (mMediaController.isShowing()) { mMediaController.hide(); } else { mMediaController.show(); } } @Override public void start() { if (isInPlaybackState()) { mMediaPlayer.start(); mCurrentState = STATE_PLAYING; } mTargetState = STATE_PLAYING; } @Override public void pause() { if (isInPlaybackState()) { if (mMediaPlayer.isPlaying()) { mMediaPlayer.pause(); mCurrentState = STATE_PAUSED; } } mTargetState = STATE_PAUSED; } public void suspend() { release(false); } public void resume() { openVideo(); } @Override public int getDuration() { if (isInPlaybackState()) { return mMediaPlayer.getDuration(); } return -1; } @Override public int getCurrentPosition() { if (isInPlaybackState()) { return mMediaPlayer.getCurrentPosition(); } return 0; } @Override public void seekTo(int msec) { if (isInPlaybackState()) { mMediaPlayer.seekTo(msec); mSeekWhenPrepared = 0; } else { mSeekWhenPrepared = msec; } } @Override public boolean isPlaying() { return isInPlaybackState() && mMediaPlayer.isPlaying(); } @Override public int getBufferPercentage() { if (mMediaPlayer != null) { return mCurrentBufferPercentage; } return 0; } private boolean isInPlaybackState() { return (mMediaPlayer != null && mCurrentState != STATE_ERROR && mCurrentState != STATE_IDLE && mCurrentState != STATE_PREPARING); } @Override public boolean canPause() { return mCanPause; } @Override public boolean canSeekBackward() { return mCanSeekBack; } @Override public boolean canSeekForward() { return mCanSeekForward; } /** * Get the audio session id for the player used by this VideoView. This can be used to apply audio effects to the audio track of a video. * * @return The audio session, or 0 if there was an error. */ @Override public int getAudioSessionId() { if (mAudioSession == 0) { MediaPlayer foo = new MediaPlayer(); mAudioSession = foo.getAudioSessionId(); foo.release(); } return mAudioSession; } final Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case KEEP_SCREEN_ON_MSG: { setKeepScreenOn(msg.arg1 != 0); } break; } } }; private final SurfaceHolder mSurfaceHolder = new SurfaceHolder() { @Override public void addCallback(Callback callback) { } @Override public void removeCallback(Callback callback) { } @Override public boolean isCreating() { return (mSurface != null); } @Override public void setType(int type) { } @Override public void setFixedSize(int width, int height) { if (getWidth() != width || getHeight() != height) { requestLayout(); } } @Override public void setSizeFromLayout() { } @Override public void setFormat(int format) { } @Override public void setKeepScreenOn(boolean screenOn) { Message msg = mHandler.obtainMessage(KEEP_SCREEN_ON_MSG); msg.arg1 = screenOn ? 1 : 0; mHandler.sendMessage(msg); } @Override public Canvas lockCanvas() { return null; } @Override public Canvas lockCanvas(Rect dirty) { return null; } @Override public void unlockCanvasAndPost(Canvas canvas) { } @Override public Rect getSurfaceFrame() { mSurfaceFrame.set(0, 0, mVideoWidth, mVideoHeight); return mSurfaceFrame; } @Override public Surface getSurface() { return mSurface; } }; } <|start_filename|>video/src/main/java/com/warnyul/android/widget/MetadataUtils.java<|end_filename|> package com.warnyul.android.widget; import android.media.MediaPlayer; import android.text.TextUtils; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; /** * @author <NAME> */ class MetadataUtils { public static final boolean METADATA_ALL = false; public static final boolean BYPASS_METADATA_FILTER = false; // Playback capabilities. /** * Indicate whether the media can be paused */ public static final int PAUSE_AVAILABLE = 1; // Boolean /** * Indicate whether the media can be backward seeked */ public static final int SEEK_BACKWARD_AVAILABLE = 2; // Boolean /** * Indicate whether the media can be forward seeked */ public static final int SEEK_FORWARD_AVAILABLE = 3; // Boolean /** * Indicate whether the media can be seeked */ public static final int SEEK_AVAILABLE = 4; // Boolean private static Object data; private MetadataUtils() { throw new RuntimeException("Not allowed instances"); } public static void init(MediaPlayer mp) { Method method = getMediadataMethod(); method.setAccessible(true); try { data = method.invoke(mp, METADATA_ALL, BYPASS_METADATA_FILTER); } catch (IllegalAccessException e) { e.printStackTrace(); data = null; } catch (InvocationTargetException e) { e.printStackTrace(); data = null; } } public static boolean isInitialized() { return data != null; } public static boolean has(int key) { Method method = getHasMethod(data.getClass()); try { return (Boolean) method.invoke(data, key); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } return false; } public static boolean getBoolean(int key) { Method method = getBooleanMethod(data.getClass()); try { return (Boolean) method.invoke(data, key); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } return false; } private static Method getBooleanMethod(Class clazz) { Method[] methods = clazz.getDeclaredMethods(); for (Method method : methods) { if (TextUtils.equals(method.getName(), "getBoolean")) { return method; } } return null; } private static Method getHasMethod(Class clazz) { Method[] methods = clazz.getDeclaredMethods(); for (Method method : methods) { if (TextUtils.equals(method.getName(), "has")) { return method; } } return null; } private static Method getMediadataMethod() { Method[] methods = MediaPlayer.class.getDeclaredMethods(); for (Method method : methods) { if (TextUtils.equals(method.getName(), "getMetadata")) { return method; } } return null; } }
greg6614/fast-video-view
<|start_filename|>riskparityportfolio/vanilla.cpp<|end_filename|> #include <pybind11/pybind11.h> #include <pybind11/eigen.h> using namespace Eigen; using namespace std; // Cyclical coordinate descent for Spinu's formulation // of the risk parity portfolio problem Eigen::VectorXd risk_parity_portfolio_ccd_spinu(const Eigen::MatrixXd& Sigma, const Eigen::VectorXd& b, const double tol = 1E-8, const unsigned int maxiter = 50) { double aux, x_diff, xk_sum; const unsigned int n = b.size(); Eigen::VectorXd xk = (1 / Sigma.diagonal().array().sqrt()).matrix(); Eigen::VectorXd x_star(n), Sigma_xk(n), rc(n); Sigma_xk = Sigma * xk; for (unsigned int k = 0; k < maxiter; ++k) { for (unsigned int i = 0; i < n; ++i) { // compute update for the portfolio weights x aux = xk(i) * Sigma(i, i) - Sigma_xk(i); x_star(i) = (.5 / Sigma(i, i)) * (aux + std::sqrt(aux * aux + 4 * Sigma(i, i) * b(i))); // update auxiliary terms x_diff = x_star(i) - xk(i); Sigma_xk += (Sigma.col(i).array() * x_diff).matrix(); xk(i) = x_star(i); } xk_sum = xk.sum(); rc = (xk.array() * (Sigma_xk).array() / (xk_sum * xk_sum)).matrix(); if ((rc.array() / rc.sum() - b.array()).abs().maxCoeff() < tol) break; } return x_star / xk_sum; } namespace py = pybind11; PYBIND11_MODULE(vanilla, m) { m.doc() = "design of risk parity portfolios"; m.def("design", &risk_parity_portfolio_ccd_spinu, py::arg("Sigma"), py::arg("b"), py::arg("tol") = 1E-8, py::arg("maxiter") = 50, R"pbdoc( A function to design vanilla risk parity (budgeting) portfolios. This is an implementation of the risk formulation proposed by Spinu (2013). The algorithm was inspired by the cyclical coordinate descent proposed by Griveau-Billion (2013). Parameters ---------- Sigma : numpy.ndarray n x n covariance matrix of the assets b : numpy.ndarray n x 1 risk budgeting vector tol : float tolerance on the risk contributions convergence. Default value is 1e-8 maxiter : int maximum number of iterations. Default value is 50 Example ------- >>> import numpy as np >>> import riskparityportfolio as rpp >>> np.random.seed(42) # creates a correlation matrix from time-series of five assets >>> x = np.random.normal(size=1000).reshape((5, -1)) >>> corr = x @ x.T # create the desired risk budgeting vector >>> b = np.ones(len(corr)) / len(corr) # design the portfolio >>> w = rpp.design(corr, b) >>> w array([ 0.21075375, 0.21402865, 0.20205399, 0.16994639, 0.20321721]) # compute the risk budgeting >>> rc = w @ (corr * w) >>> rc / np.sum(rc) array([ 0.2, 0.2, 0.2, 0.2, 0.2]) # let's try a different budget >>> b = np.array([0.01, 0.09, .1, .1, .7]) >>> w = rpp.design(corr, b) >>> w array([ 0.06178354, 0.19655744, 0.16217134, 0.12808275, 0.45140493]) >>> rc = w @ (corr * w) >>> rc / np.sum(rc) array([ 0.01, 0.09, 0.1 , 0.1 , 0.7 ]) References ---------- [1] <NAME> (2013). An Algorithm for Computing Risk Parity Weights. https://dx.doi.org/10.2139/ssrn.2297383 [2] <NAME> et. al. (2013). A fast algorithm for computing High-dimensional risk parity portfolios. https://arxiv.org/pdf/1311.4057.pdf Notes ----- To get the risk parity portfolio, set `b` as the 1/n uniform vector. )pbdoc" ); #ifdef VERSION_INFO m.attr("__version__") = VERSION_INFO; #else m.attr("__version__") = "dev"; #endif }
vishalbelsare/riskparity.py
<|start_filename|>internal/util/log.go<|end_filename|> /* * Copyright 2020 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package util import ( "fmt" "github.com/op/go-logging" ) // Package-wide Logger instance var log = logging.MustGetLogger("util") // errCheck logs a warning if the error is not nil. func errCheck(err error, message string) bool { if err != nil { log.Warning(fmt.Errorf("%v: %v", message, err)) return true } return false }
orangeturtle739/ymuse
<|start_filename|>data_types.f90<|end_filename|> type input_file use sizes logical :: tinker, pdb, xyz, moldy integer :: nlines character(len=strl), allocatable :: line(:) character(len=strl), allocatable :: keyword(:,:) end type input_file <|start_filename|>getinp.f90<|end_filename|> ! ! Written by <NAME>, 2009-2011. ! Copyright (c) 2009-2018, <NAME>, <NAME>, ! <NAME>. ! ! Subroutine getinp: subroutine that reads the input file ! subroutine getinp() use sizes use compute_data, only : ntype, natoms, idfirst, nmols, ityperest, coor, restpars use input use usegencan implicit none integer :: i, k, ii, iarg, iline, idatom, iatom, in, lixo, irest, itype, itest,& imark, ioerr, nloop0, iread, idfirstatom double precision :: clen character(len=strl) :: record, blank logical :: inside_structure ! Clearing the blank character arrays do i = 1, strl blank(i:i) = ' ' end do ! Getting random seed and optional optimization parameters if set seed = 1234567 randini = .false. check = .false. chkgrad = .false. iprint1 = 2 iprint2 = 2 discale = 1.1d0 writeout = 10 maxit = 20 nloop = 0 nloop0 = 0 movefrac = 0.05 movebadrandom = .false. precision = 1.d-2 writebad = .false. add_amber_ter = .false. add_box_sides = .false. add_sides_fix = 0.d0 sidemax = 1000.d0 ioerr = 0 avoidoverlap = .true. packall = .false. use_short_tol = .false. crd = .false. inside_structure = .false. do i = 1, nlines if ( keyword(i,1).eq.'structure') inside_structure = .true. if ( keyword(i,1).eq.'end' .and. & keyword(i,2).eq.'structure') inside_structure = .false. if(keyword(i,1).eq.'seed') then read(keyword(i,2),*,iostat=ioerr) seed if ( ioerr /= 0 ) exit if ( seed == -1 ) call seed_from_time(seed) else if(keyword(i,1).eq.'randominitialpoint') then randini = .true. else if(keyword(i,1).eq.'check') then check = .true. else if(keyword(i,1).eq.'writebad') then writebad = .true. else if(keyword(i,1).eq.'precision') then read(keyword(i,2),*,iostat=ioerr) precision if ( ioerr /= 0 ) exit write(*,*) ' Optional precision set: ', precision else if(keyword(i,1).eq.'movefrac') then read(keyword(i,2),*,iostat=ioerr) movefrac if ( ioerr /= 0 ) exit write(*,*) ' Optional movefrac set: ', movefrac else if(keyword(i,1).eq.'movebadrandom') then movebadrandom = .true. write(*,*) ' Will move randomly bad molecues (movebadrandom) ' else if(keyword(i,1).eq.'chkgrad') then chkgrad = .true. else if(keyword(i,1).eq.'writeout') then read(keyword(i,2),*,iostat=ioerr) writeout if ( ioerr /= 0 ) exit write(*,*) ' Output frequency: ', writeout else if(keyword(i,1).eq.'maxit') then read(keyword(i,2),*,iostat=ioerr) maxit if ( ioerr /= 0 ) exit write(*,*) ' User defined GENCAN number of iterations: ', maxit else if(keyword(i,1).eq.'nloop') then if( .not. inside_structure ) then read(keyword(i,2),*,iostat=ioerr) nloop if ( ioerr /= 0 ) exit end if else if(keyword(i,1).eq.'nloop0') then if( .not. inside_structure ) then read(keyword(i,2),*,iostat=ioerr) nloop0 if ( ioerr /= 0 ) exit end if else if(keyword(i,1).eq.'discale') then read(keyword(i,2),*,iostat=ioerr) discale if ( ioerr /= 0 ) exit write(*,*) ' Optional initial tolerance scale: ', discale else if(keyword(i,1).eq.'sidemax') then read(keyword(i,2),*,iostat=ioerr) sidemax if ( ioerr /= 0 ) exit write(*,*) ' User set maximum system dimensions: ', sidemax else if(keyword(i,1).eq.'fbins') then read(keyword(i,2),*,iostat=ioerr) fbins if ( ioerr /= 0 ) exit write(*,*) ' User set linked-cell bin parameter: ', fbins else if(keyword(i,1).eq.'add_amber_ter') then add_amber_ter = .true. write(*,*) ' Will add the TER flag between molecules. ' else if(keyword(i,1).eq.'avoid_overlap') then if ( keyword(i,2).eq.'yes') then avoidoverlap = .true. write(*,*) ' Will avoid overlap to fixed molecules at initial point. ' else avoidoverlap = .false. write(*,*) ' Will NOT avoid overlap to fixed molecules at initial point. ' end if else if(keyword(i,1).eq.'packall') then packall = .true. write(*,*) ' Will pack all molecule types from the beginning. ' else if(keyword(i,1).eq.'use_short_tol') then use_short_tol = .true. write(*,*) ' Will use a short distance penalty for all atoms. ' else if(keyword(i,1).eq.'writecrd') then crd = .true. write(*,*) ' Will write output also in CRD format ' read(keyword(i,2),*,iostat=ioerr) crdfile else if(keyword(i,1).eq.'add_box_sides') then add_box_sides = .true. write(*,*) ' Will print BOX SIDE informations. ' read(keyword(i,2),*,iostat=ioerr) add_sides_fix if ( ioerr /= 0 ) then ioerr = 0 cycle end if write(*,*) ' Will sum ', add_sides_fix,' to each side length on print' else if(keyword(i,1).eq.'iprint1') then read(keyword(i,2),*,iostat=ioerr) iprint1 if ( ioerr /= 0 ) exit write(*,*) ' Optional printvalue 1 set: ', iprint1 else if(keyword(i,1).eq.'iprint2') then read(keyword(i,2),*,iostat=ioerr) iprint2 if ( ioerr /= 0 ) exit write(*,*) ' Optional printvalue 2 set: ', iprint2 else if( keyword(i,1) /= 'tolerance' .and. & keyword(i,1) /= 'short_tol_dist' .and. & keyword(i,1) /= 'short_tol_scale' .and. & keyword(i,1) /= 'structure' .and. & keyword(i,1) /= 'end' .and. & keyword(i,1) /= 'atoms' .and. & keyword(i,1) /= 'output' .and. & keyword(i,1) /= 'filetype' .and. & keyword(i,1) /= 'number' .and. & keyword(i,1) /= 'inside' .and. & keyword(i,1) /= 'outside' .and. & keyword(i,1) /= 'fixed' .and. & keyword(i,1) /= 'center' .and. & keyword(i,1) /= 'centerofmass' .and. & keyword(i,1) /= 'over' .and. & keyword(i,1) /= 'above' .and. & keyword(i,1) /= 'below' .and. & keyword(i,1) /= 'constrain_rotation' .and. & keyword(i,1) /= 'radius' .and. & keyword(i,1) /= 'fscale' .and. & keyword(i,1) /= 'short_radius' .and. & keyword(i,1) /= 'short_radius_scale' .and. & keyword(i,1) /= 'resnumbers' .and. & keyword(i,1) /= 'connect' .and. & keyword(i,1) /= 'changechains' .and. & keyword(i,1) /= 'chain' .and. & keyword(i,1) /= 'discale' .and. & keyword(i,1) /= 'maxit' .and. & keyword(i,1) /= 'movebadrandom' .and. & keyword(i,1) /= 'maxmove' .and. & keyword(i,1) /= 'add_amber_ter' .and. & keyword(i,1) /= 'sidemax' .and. & keyword(i,1) /= 'seed' .and. & keyword(i,1) /= 'randominitialpoint' .and. & keyword(i,1) /= 'restart_from' .and. & keyword(i,1) /= 'restart_to' .and. & keyword(i,1) /= 'nloop' .and. & keyword(i,1) /= 'nloop0' .and. & keyword(i,1) /= 'writeout' .and. & keyword(i,1) /= 'writebad' .and. & keyword(i,1) /= 'check' .and. & keyword(i,1) /= 'iprint1' .and. & keyword(i,1) /= 'iprint2' .and. & keyword(i,1) /= 'writecrd' .and. & keyword(i,1) /= 'segid' .and. & keyword(i,1) /= 'chkgrad' ) then write(*,*) ' ERROR: Keyword not recognized: ', trim(keyword(i,1)) stop end if end do if ( ioerr /= 0 ) then write(*,*) ' ERROR: Some optional keyword was not used correctly: ', trim(keyword(i,1)) stop end if write(*,*) ' Seed for random number generator: ', seed call init_random_number(seed) ! Checking for the name of the output file to be created xyzout = '####' do iline = 1, nlines if(keyword(iline,1).eq.'output') then xyzout = keyword(iline,2) xyzout = trim(adjustl(xyzout)) end if end do if(xyzout(1:4) == '####') then write(*,*)' ERROR: Output file not (correctly?) specified. ' stop end if write(*,*)' Output file: ', trim(adjustl(xyzout)) ! Reading structure files itype = 0 do iline = 1, nlines if(keyword(iline,1).eq.'structure') then itype = itype + 1 record = keyword(iline,2) write(*,*) ' Reading coordinate file: ', trim(adjustl(record)) ! Reading pdb input files if(pdb) then name(itype) = trim(adjustl(record)) record = keyword(iline,2) pdbfile(itype) = trim(record) idfirst(itype) = 1 idfirstatom = 0 do ii = itype - 1, 1, -1 idfirst(itype) = idfirst(itype) + natoms(ii) end do open(10,file=keyword(iline,2),status='old',iostat=ioerr) if ( ioerr /= 0 ) call failopen(keyword(iline,2)) ! Read coordinates record(1:6) = '######' do while(record(1:4).ne.'ATOM'.and.record(1:6).ne.'HETATM') read(10,str_format) record end do idatom = idfirst(itype) - 1 do while(idatom.lt.natoms(itype)+idfirst(itype)-1) if(record(1:4).eq.'ATOM'.or.record(1:6).eq.'HETATM') then idatom = idatom + 1 amass(idatom) = 1.d0 maxcon(idatom) = 0 ! Read the index of the first atom, to adjust connectivities, if any if(idfirstatom == 0) read(record(7:11),*,iostat=ioerr) idfirstatom read(record,"( t31,f8.3,t39,f8.3,t47,f8.3 )",iostat=ioerr) & (coor(idatom,k),k=1,3) if( ioerr /= 0 ) then record = keyword(iline,2) write(*,*) ' ERROR: Failed to read coordinates from', & ' file: ', trim(adjustl(record)) write(*,*) ' Probably the coordinates are not in', & ' standard PDB file format. ' write(*,*) ' Standard PDB format specifications', & ' can be found at: ' write(*,*) ' www.rcsb.org/pdb ' stop end if ! This only tests if residue numbers can be read, they are used ! only for output read(record(23:26),*,iostat=ioerr) itest if( ioerr /= 0 ) then record = pdbfile(itype) write(*,*) ' ERROR: Failed reading residue number',& ' from PDB file: ', trim(adjustl(record)) write(*,*) ' Residue numbers are integers that',& ' must be within columns 23 and 26. ' write(*,*) ' Other characters within these columns',& ' will cause input/output errors. ' write(*,*) ' Standard PDB format specifications',& ' can be found at: ' write(*,*) ' www.rcsb.org/pdb ' stop end if end if read(10,str_format,iostat=ioerr) record end do ! ! Read connectivity, if there is any specified ! do while(.true.) if ( ioerr /= 0 ) exit if(record(1:6).eq.'CONECT') then iread = 7 read(record(iread:iread+4),*,iostat=ioerr) iatom iatom = iatom - idfirstatom + 1 idatom = idfirst(itype) - 1 + iatom if(ioerr /= 0) then write(*,*) " ERROR: Could not read atom index from CONECT line: " write(*,*) trim(adjustl(record)) stop end if iread = iread + 5 read(record(iread:iread+4),*,iostat=ioerr) nconnect(idatom,1) if(ioerr /= 0) then write(*,*) " ERROR: Could not read any connection index from CONECT line: " write(*,*) trim(adjustl(record)) stop end if nconnect(idatom,1) = nconnect(idatom,1) - idfirstatom + 1 maxcon(idatom) = 1 do while(.true.) iread = iread + 5 read(record(iread:iread+4),*,iostat=ioerr) nconnect(idatom,maxcon(idatom)+1) if(ioerr == 0) then maxcon(idatom) = maxcon(idatom) + 1 nconnect(idatom,maxcon(idatom)) = nconnect(idatom,maxcon(idatom)) - idfirstatom + 1 else exit end if end do end if read(10,str_format,iostat=ioerr) record end do close(10) end if ! Reading tinker input files if(tinker) then open(10,file=keyword(iline,2),status='old',iostat=ioerr) if ( ioerr /= 0 ) call failopen(keyword(iline,2)) idfirst(itype) = 1 do ii = itype - 1, 1, -1 idfirst(itype) = idfirst(itype) + natoms(ii) end do record = keyword(iline,2) call setcon(record(1:64),idfirst(itype)) open(10,file = keyword(iline,2), status = 'old') record = blank do while(record.le.blank) read(10,str_format) record end do i = 1 do while(record(i:i).le.' ') i = i + 1 if ( i > strl ) exit end do iarg = i if ( i < strl ) then do while(record(i:i).gt.' ') i = i + 1 if ( i > strl ) exit end do end if read(record(iarg:i-1),*) natoms(itype) if ( i < strl ) then do while(record(i:i).le.' ') i = i + 1 if ( i > strl ) exit end do end if iarg = i if ( i < strl ) then do while(record(i:i).gt.' ') i = i + 1 if ( i > strl ) exit end do end if read(record(iarg:i-1),str_format) name(itype) record = name(itype) name(itype) = trim(adjustl(record)) if(name(itype).lt.' ') name(itype) = 'Without_title' idatom = idfirst(itype) - 1 do iatom = 1, natoms(itype) idatom = idatom + 1 record = blank do while(record.le.blank) read(10,str_format) record end do i = 1 do while(record(i:i).le.' ') i = i + 1 if ( i > strl ) exit end do iarg = i if ( i < strl ) then do while(record(i:i).gt.' ') i = i + 1 if ( i > strl ) exit end do end if read(record(iarg:i-1),*) in if ( i < strl ) then do while(record(i:i).le.' ') i = i + 1 if ( i > strl ) exit end do end if iarg = i if ( i < strl ) then do while(record(i:i).gt.' ') i = i + 1 if ( i > strl ) exit end do end if read(record(iarg:i-1),*) ele(idatom) read(record(i:strl),*) (coor(idatom,k), k = 1, 3),& (nconnect(idatom, k), k = 1, maxcon(idatom)) amass(idatom) = 1.d0 end do close(10) end if ! Reading xyz input files if(xyz) then open(10,file=keyword(iline,2),status='old',iostat=ioerr) if ( ioerr /= 0 ) call failopen(keyword(iline,2)) read(10,*) natoms(itype) read(10,str_format) name(itype) if(name(itype).lt.' ') name(itype) = 'Without_title' idfirst(itype) = 1 do ii = itype - 1, 1, -1 idfirst(itype) = idfirst(itype) + natoms(ii) end do idatom = idfirst(itype) - 1 do iatom = 1, natoms(itype) idatom = idatom + 1 record = blank read(10,str_format) record read(record,*) ele(idatom), (coor(idatom,k),k=1,3) amass(idatom) = 1.d0 end do close(10) end if ! Reading moldy input files if(moldy) then open(10,file=keyword(iline,2), status ='old',iostat=ioerr) if ( ioerr /= 0 ) call failopen(keyword(iline,2)) read(10,*) name(itype), nmols(itype) natoms(itype) = 0 do while(.true.) read(10,str_format,iostat=ioerr) record if ( ioerr /= 0 ) exit if(record.gt.' '.and.record(1:3).ne.'end') & natoms(itype) = natoms(itype) + 1 end do close(10) idfirst(itype) = 1 do ii = itype - 1, 1, -1 idfirst(itype) = idfirst(itype) + natoms(ii) end do open(10,file=keyword(iline,2),status='old') read(10,str_format) record idatom = idfirst(itype) - 1 do iatom = 1, natoms(itype) idatom = idatom + 1 read(10,str_format) record read(record,*) lixo, (coor(idatom,k), k = 1, 3),& amass(idatom), charge(idatom), ele(idatom) end do close(10) end if end if end do ntype = itype write(*,*) ' Number of independent structures: ', ntype write(*,*) ' The structures are: ' do itype = 1, ntype record = name(itype) write(*,*) ' Structure ', itype, ':', trim(adjustl(record)),& '(',natoms(itype),' atoms)' end do ! Setting the vectors for the number of GENCAN loops if(nloop.eq.0) then nloop_all = 200*ntype nloop = nloop_all else nloop_all = nloop end if write(*,*) ' Maximum number of GENCAN loops for all molecule packing: ', nloop_all do itype = 1, ntype if ( nloop_type(itype) == 0 ) then nloop_type(itype) = nloop_all else write(*,*) ' Maximum number of GENCAN loops for type: ', itype, ': ', nloop_type(itype) end if end do ! nloop0 are the number of loops for the initial phase packing if(nloop0.eq.0) then nloop0 = 20*ntype else write(*,*) ' Maximum number of GENCAN loops-0 for all molecule packing: ', nloop0 end if do itype = 1, ntype if ( nloop0_type(itype) == 0 ) then nloop0_type(itype) = nloop0 else write(*,*) ' Maximum number of GENCAN loops-0 for type: ', itype, ': ', nloop0_type(itype) end if end do ! Reading the restrictions that were set irest = 0 ioerr = 0 do iline = 1, nlines if(keyword(iline,1).eq.'fixed') then irest = irest + 1 irestline(irest) = iline ityperest(irest) = 1 read(keyword(iline,2),*,iostat=ioerr) restpars(irest,1) read(keyword(iline,3),*,iostat=ioerr) restpars(irest,2) read(keyword(iline,4),*,iostat=ioerr) restpars(irest,3) read(keyword(iline,5),*,iostat=ioerr) restpars(irest,4) read(keyword(iline,6),*,iostat=ioerr) restpars(irest,5) read(keyword(iline,7),*,iostat=ioerr) restpars(irest,6) end if if(keyword(iline,1).eq.'inside') then irest = irest + 1 irestline(irest) = iline if(keyword(iline,2).eq.'cube') then ityperest(irest) = 2 read(keyword(iline,3),*,iostat=ioerr) restpars(irest,1) read(keyword(iline,4),*,iostat=ioerr) restpars(irest,2) read(keyword(iline,5),*,iostat=ioerr) restpars(irest,3) read(keyword(iline,6),*,iostat=ioerr) restpars(irest,4) else if(keyword(iline,2).eq.'box') then ityperest(irest) = 3 read(keyword(iline,3),*,iostat=ioerr) restpars(irest,1) read(keyword(iline,4),*,iostat=ioerr) restpars(irest,2) read(keyword(iline,5),*,iostat=ioerr) restpars(irest,3) read(keyword(iline,6),*,iostat=ioerr) restpars(irest,4) read(keyword(iline,7),*,iostat=ioerr) restpars(irest,5) read(keyword(iline,8),*,iostat=ioerr) restpars(irest,6) else if(keyword(iline,2).eq.'sphere') then ityperest(irest) = 4 read(keyword(iline,3),*,iostat=ioerr) restpars(irest,1) read(keyword(iline,4),*,iostat=ioerr) restpars(irest,2) read(keyword(iline,5),*,iostat=ioerr) restpars(irest,3) read(keyword(iline,6),*,iostat=ioerr) restpars(irest,4) else if(keyword(iline,2).eq.'ellipsoid') then ityperest(irest) = 5 read(keyword(iline,3),*,iostat=ioerr) restpars(irest,1) read(keyword(iline,4),*,iostat=ioerr) restpars(irest,2) read(keyword(iline,5),*,iostat=ioerr) restpars(irest,3) read(keyword(iline,6),*,iostat=ioerr) restpars(irest,4) read(keyword(iline,7),*,iostat=ioerr) restpars(irest,5) read(keyword(iline,8),*,iostat=ioerr) restpars(irest,6) read(keyword(iline,9),*,iostat=ioerr) restpars(irest,7) else if(keyword(iline,2).eq.'cylinder') then ityperest(irest) = 12 read(keyword(iline,3),*,iostat=ioerr) restpars(irest,1) read(keyword(iline,4),*,iostat=ioerr) restpars(irest,2) read(keyword(iline,5),*,iostat=ioerr) restpars(irest,3) read(keyword(iline,6),*,iostat=ioerr) restpars(irest,4) read(keyword(iline,7),*,iostat=ioerr) restpars(irest,5) read(keyword(iline,8),*,iostat=ioerr) restpars(irest,6) read(keyword(iline,9),*,iostat=ioerr) restpars(irest,7) read(keyword(iline,10),*,iostat=ioerr) restpars(irest,9) restpars(irest,8) = restpars(irest,4)**2 + & restpars(irest,5)**2 + & restpars(irest,6)**2 if(restpars(irest,8).lt.1.d-10) then write(*,*) ' ERROR: The norm of the director vector', & ' of the cylinder constraint cannot be zero.' ioerr = 1 else clen = dsqrt(restpars(irest,8)) restpars(irest,4) = restpars(irest,4) / clen restpars(irest,5) = restpars(irest,5) / clen restpars(irest,6) = restpars(irest,6) / clen end if else ioerr = 1 end if end if if(keyword(iline,1).eq.'outside') then irest = irest + 1 irestline(irest) = iline if(keyword(iline,2).eq.'cube') then ityperest(irest) = 6 read(keyword(iline,3),*,iostat=ioerr) restpars(irest,1) read(keyword(iline,4),*,iostat=ioerr) restpars(irest,2) read(keyword(iline,5),*,iostat=ioerr) restpars(irest,3) read(keyword(iline,6),*,iostat=ioerr) restpars(irest,4) else if(keyword(iline,2).eq.'box') then ityperest(irest) = 7 read(keyword(iline,3),*,iostat=ioerr) restpars(irest,1) read(keyword(iline,4),*,iostat=ioerr) restpars(irest,2) read(keyword(iline,5),*,iostat=ioerr) restpars(irest,3) read(keyword(iline,6),*,iostat=ioerr) restpars(irest,4) read(keyword(iline,7),*,iostat=ioerr) restpars(irest,5) read(keyword(iline,8),*,iostat=ioerr) restpars(irest,6) else if(keyword(iline,2).eq.'sphere') then ityperest(irest) = 8 read(keyword(iline,3),*,iostat=ioerr) restpars(irest,1) read(keyword(iline,4),*,iostat=ioerr) restpars(irest,2) read(keyword(iline,5),*,iostat=ioerr) restpars(irest,3) read(keyword(iline,6),*,iostat=ioerr) restpars(irest,4) else if(keyword(iline,2).eq.'ellipsoid') then ityperest(irest) = 9 read(keyword(iline,3),*,iostat=ioerr) restpars(irest,1) read(keyword(iline,4),*,iostat=ioerr) restpars(irest,2) read(keyword(iline,5),*,iostat=ioerr) restpars(irest,3) read(keyword(iline,6),*,iostat=ioerr) restpars(irest,4) read(keyword(iline,7),*,iostat=ioerr) restpars(irest,5) read(keyword(iline,8),*,iostat=ioerr) restpars(irest,6) read(keyword(iline,9),*,iostat=ioerr) restpars(irest,7) else if(keyword(iline,2).eq.'cylinder') then ityperest(irest) = 13 read(keyword(iline,3),*,iostat=ioerr) restpars(irest,1) read(keyword(iline,4),*,iostat=ioerr) restpars(irest,2) read(keyword(iline,5),*,iostat=ioerr) restpars(irest,3) read(keyword(iline,6),*,iostat=ioerr) restpars(irest,4) read(keyword(iline,7),*,iostat=ioerr) restpars(irest,5) read(keyword(iline,8),*,iostat=ioerr) restpars(irest,6) read(keyword(iline,9),*,iostat=ioerr) restpars(irest,7) read(keyword(iline,10),*,iostat=ioerr) restpars(irest,9) restpars(irest,8) = restpars(irest,4)**2 + & restpars(irest,5)**2 + & restpars(irest,6)**2 if(restpars(irest,8).lt.1.d-10) then write(*,*) ' ERROR: The norm of the director vector',& ' of the cylinder constraint cannot be zero.' ioerr = 1 else clen = dsqrt(restpars(irest,8)) restpars(irest,4) = restpars(irest,4) / clen restpars(irest,5) = restpars(irest,5) / clen restpars(irest,6) = restpars(irest,6) / clen end if else ioerr = 1 end if end if if(keyword(iline,1).eq.'over' .or. keyword(iline,1).eq.'above') then irest = irest + 1 irestline(irest) = iline ityperest(irest) = 10 read(keyword(iline,3),*,iostat=ioerr) restpars(irest,1) read(keyword(iline,4),*,iostat=ioerr) restpars(irest,2) read(keyword(iline,5),*,iostat=ioerr) restpars(irest,3) read(keyword(iline,6),*,iostat=ioerr) restpars(irest,4) if(keyword(iline,2).ne.'plane') ioerr = 1 end if if(keyword(iline,1).eq.'below') then irest = irest + 1 irestline(irest) = iline ityperest(irest) = 11 read(keyword(iline,3),*,iostat=ioerr) restpars(irest,1) read(keyword(iline,4),*,iostat=ioerr) restpars(irest,2) read(keyword(iline,5),*,iostat=ioerr) restpars(irest,3) read(keyword(iline,6),*,iostat=ioerr) restpars(irest,4) if(keyword(iline,2).ne.'plane') ioerr = 1 end if if ( ioerr /= 0 ) then write(*,*) ' ERROR: Some restriction is not set correctly. ' stop end if end do nrest = irest write(*,*) ' Total number of restrictions: ', nrest ! Getting the tolerance ioerr = 1 dism = -1.d0 do iline = 1, nlines if(keyword(iline,1).eq.'tolerance') then read(keyword(iline,2),*,iostat=ioerr) dism if ( ioerr /= 0 ) then write(*,*) ' ERROR: Failed reading tolerance. ' stop end if exit end if end do if ( ioerr /= 0 ) then write(*,*) ' ERROR: Overall tolerance not set. Use, for example: tolerance 2.0 ' stop end if write(*,*) ' Distance tolerance: ', dism ! Reading, if defined, the short distance penalty parameters ioerr = 1 short_tol_dist = dism/2.d0 ! Reading short_tol_dist do iline = 1, nlines if(keyword(iline,1).eq.'short_tol_dist') then read(keyword(iline,2),*,iostat=ioerr) short_tol_dist if ( ioerr /= 0 ) then write(*,*) ' ERROR: Failed reading short_tol_dist. ' stop end if if ( short_tol_dist > dism ) then write(*,*) ' ERROR: The short_tol_dist parameter must be smaller than the tolerance. ' stop end if write(*,*) ' User defined short tolerance distance: ', short_tol_dist short_tol_dist = short_tol_dist**2 exit end if end do ! Reading short_tol_scale short_tol_scale = 3.d0 do iline = 1, nlines if(keyword(iline,1).eq.'short_tol_scale') then read(keyword(iline,2),*,iostat=ioerr) short_tol_scale if ( ioerr /= 0 ) then write(*,*) ' ERROR: Failed reading short_tol_scale. ' stop end if if ( short_tol_dist <= 0.d0 ) then write(*,*) ' ERROR: The short_tol_scale parameter must be positive. ' stop end if write(*,*) ' User defined short tolerance scale: ', short_tol_scale exit end if end do ! Assigning the input lines that correspond to each structure itype = 0 iline = 0 do while(iline < nlines) iline = iline + 1 if(keyword(iline,1).eq.'structure') then itype = itype + 1 linestrut(itype,1) = iline iline = iline + 1 do while(keyword(iline,1).ne.'end'.or.& keyword(iline,2).ne.'structure') if(keyword(iline,1) == 'structure'.or.& iline == nlines) then write(*,*) ' ERROR: Structure specification not ending with "end structure"' stop end if iline = iline + 1 end do linestrut(itype,2) = iline end if end do ! If pdb files, get the type of residue numbering output for each ! molecule if(pdb) then do itype = 1, ntype connect(itype) = .true. resnumbers(itype) = -1 changechains(itype) = .false. chain(itype) = "#" segid(itype) = "" maxmove(itype) = nmols(itype) do iline = 1, nlines if(iline.gt.linestrut(itype,1).and.& iline.lt.linestrut(itype,2)) then if(keyword(iline,1).eq.'changechains') then changechains(itype) = .true. end if if(keyword(iline,1).eq.'maxmove') then read(keyword(iline,2),*) maxmove(itype) end if if(keyword(iline,1).eq.'resnumbers') then read(keyword(iline,2),*) resnumbers(itype) end if if(keyword(iline,1).eq.'connect') then if(keyword(iline,2) == "no") then connect(itype) = .false. end if end if if(keyword(iline,1).eq.'chain') then read(keyword(iline,2),*) chain(itype) end if if(keyword(iline,1).eq.'segid') then read(keyword(iline,2),*) segid(itype) end if end if end do if (crd) then if (itype.gt.1 .and. segid(itype)=="") then if (segid(itype-1) /= "") then write(*,*) ' Warning: Type of segid not defined for ', itype,'. Keeping it same as previous' endif segid(itype) = segid(itype-1) endif endif if ( resnumbers(itype) == -1 ) then write(*,*) ' Warning: Type of residue numbering not',& ' set for structure ',itype call setrnum(pdbfile(itype),imark) if(imark.eq.1) resnumbers(itype) = 0 if(imark.gt.1) resnumbers(itype) = 1 end if write(*,*) ' Residue numbering set for structure ',itype,':',& resnumbers(itype) write(*,*) ' Swap chains of molecules of structure ',& itype,':', changechains(itype) if ( chain(itype) /= "#" ) then write(*,*) ' Specific chain identifier set for structure ',itype,':',chain(itype) end if if ( chain(itype) /= "#" .and. changechains(itype) ) then write(*,*) " ERROR: 'changechains' and 'chain' input parameters are not compatible " write(*,*) " for a single structure. " stop end if end do end if ! Write the number of molecules of each type do itype = 1, ntype write(*,*) ' Number of molecules of type ', itype, ': ', nmols(itype) if(pdb.and.nmols(itype).gt.9999) then write(*,*) ' Warning: There will be more than 9999 molecules of type ',itype if (.not. crd) write(*,*) ' Residue numbering is reset after 9999. ' if (crd) write(*,*) ' Residue numbering is reset after 9999 in pdb but not in crd. ' if ( chain(itype) == "#" ) then write(*,*) ' Each set be will be assigned a different chain in the PDB output file. ' end if end if if(crd.and.nmols(itype).gt.99999999) then write(*,*) ' Warning: There will be more than 99999999 molecules of type ',itype write(*,*) ' Residue numbering is reset after 99999999 in crd. ' endif end do ! Checking if restart files will be used for each structure or for the whole system restart_from(0) = "none" restart_to(0) = "none" do itype = 1, ntype restart_from(itype) = "none" restart_to(itype) = "none" end do lines: do iline = 1, nlines if ( keyword(iline,1) == 'restart_from' ) then do itype = 1, ntype if(iline.gt.linestrut(itype,1).and.& iline.lt.linestrut(itype,2)) then restart_from(itype) = keyword(iline,2) cycle lines end if end do if( restart_from(0) == 'none' ) then restart_from(0) = keyword(iline,2) else write(*,*) ' ERROR: More than one definition of restart_from file for all system. ' stop end if end if if ( keyword(iline,1) == 'restart_to' ) then do itype = 1, ntype if(iline.gt.linestrut(itype,1).and.& iline.lt.linestrut(itype,2)) then restart_to(itype) = keyword(iline,2) cycle lines end if end do if( restart_to(0) == 'none' ) then restart_to(0) = keyword(iline,2) else write(*,*) ' ERROR: More than one definition of restart_to file for all system. ' stop end if end if end do lines return end subroutine getinp ! ! Subroutine that stops if failed to open file ! subroutine failopen(record) use sizes character(len=strl) :: record write(*,*) write(*,*) ' ERROR: Could not open file. ' write(*,*) ' Could not find file: ',trim(record) write(*,*) ' Please check if all the input and structure ' write(*,*) ' files are in the current directory or if the' write(*,*) ' correct paths are provided.' write(*,*) stop end subroutine failopen ! ! Subroutine that checks if a pdb structure has one or more than ! one residue ! subroutine setrnum(file,nres) use sizes implicit none integer :: iread, ires, ireslast, nres, ioerr character(len=strl) :: file character(len=strl) :: record open(10,file=file,status='old') iread = 0 nres = 1 do while(nres.eq.1) read(10,str_format,iostat=ioerr) record if ( ioerr /= 0 ) exit if(record(1:4).eq.'ATOM'.or.record(1:6).eq.'HETATM') then read(record(23:26),*,iostat=ioerr) ires if ( ioerr /= 0 ) cycle iread = iread + 1 if(iread.gt.1) then if(ires.ne.ireslast) then nres = 2 close(10) return end if end if ireslast = ires end if end do close(10) return end subroutine setrnum ! ! Subroutine that computes de number of connections of each atom ! for tinker xyz files ! subroutine setcon(xyzfile,idfirst) use sizes use input, only : maxcon implicit none integer :: idfirst integer :: natoms, idatom, iatom, ic, i character(len=64) :: xyzfile character(len=120) :: record open(10, file = xyzfile, status='old') read(10,*) natoms idatom = idfirst - 1 do iatom = 1, natoms idatom = idatom + 1 read(10,"( a120 )") record ic = 0 do i = 1, 119 if(record(i:i).gt.' '.and.record(i+1:i+1).le.' ') ic = ic + 1 end do maxcon(idatom) = ic - 5 end do close(10) return end subroutine setcon ! ! Subroutine getkeywords: gets keywords and values from the input ! file in a more robust way ! subroutine getkeywords() use sizes use input, only : keyword, nlines, inputfile, forbidden_char implicit none character(len=strl) :: record integer :: iline, i, j, k, ilast, ival, ioerr ! Clearing keyword array do i = 1, nlines do j = 1, maxkeywords keyword(i,j) = 'none' end do end do ! Filling keyword array do iline = 1, nlines read(inputfile(iline),str_format,iostat=ioerr) record if ( ioerr /= 0 ) exit i = 0 ival = 0 do while(i < strl) i = i + 1 ilast = i do while(record(i:i) > ' '.and. i < strl) i = i + 1 end do if(i.gt.ilast) then ival = ival + 1 keyword(iline,ival) = record(ilast:i) end if end do end do ! Remove quotes and the forbidden_char from keywords do i = 1, nlines do j = 1, maxkeywords record = keyword(i,j) do k = 1,strl if (record(k:k) == forbidden_char .or. record(k:k) == '"') then record(k:k) = " " end if end do keyword(i,j) = trim(adjustl(record)) end do end do return end subroutine getkeywords ! Subroutine that returns the chain character given an index subroutine chainc(i,chain) implicit none integer :: i character :: chain if(i.eq.0) chain = ' ' if(i.eq.1) chain = 'A' if(i.eq.2) chain = 'B' if(i.eq.3) chain = 'C' if(i.eq.4) chain = 'D' if(i.eq.5) chain = 'E' if(i.eq.6) chain = 'F' if(i.eq.7) chain = 'G' if(i.eq.8) chain = 'H' if(i.eq.9) chain = 'I' if(i.eq.10) chain = 'J' if(i.eq.11) chain = 'K' if(i.eq.12) chain = 'L' if(i.eq.13) chain = 'M' if(i.eq.14) chain = 'N' if(i.eq.15) chain = 'O' if(i.eq.16) chain = 'P' if(i.eq.17) chain = 'Q' if(i.eq.18) chain = 'R' if(i.eq.19) chain = 'S' if(i.eq.20) chain = 'T' if(i.eq.21) chain = 'U' if(i.eq.22) chain = 'V' if(i.eq.23) chain = 'W' if(i.eq.24) chain = 'X' if(i.eq.25) chain = 'Y' if(i.eq.26) chain = 'Z' if(i.eq.27) chain = '1' if(i.eq.28) chain = '2' if(i.eq.29) chain = '3' if(i.eq.30) chain = '4' if(i.eq.31) chain = '5' if(i.eq.32) chain = '6' if(i.eq.33) chain = '7' if(i.eq.34) chain = '8' if(i.eq.35) chain = '9' if(i.eq.36) chain = '0' if(i.gt.36) chain = '#' return end subroutine chainc ! Subroutine that clears a character variable subroutine clear(record) use sizes integer :: i character(len=strl) :: record do i = 1, strl record(i:i) = ' ' end do return end subroutine clear <|start_filename|>sizes.f90<|end_filename|> ! ! Written by <NAME>, 2009-2011. ! Copyright (c) 2009-2018, <NAME>, <NAME>, ! <NAME>. ! ! ! sizes.i: Define the maximum dimensions of the problems ! ! maxrest: Maximum number of restrictions ! mrperatom: Maximum number of restrictions per atom ! maxtry: Number of tries for building the initial point ! nbp: Maximum number of boxes for fast function evaluation (nbp**3) ! nn: Maximum number of variables ! (at least the number of molecules*6) ! maxkeywords: Maximum number of keywords in input file ! module sizes integer :: maxrest integer :: mrperatom integer :: maxtry integer :: nbp integer :: nn integer :: maxkeywords integer, parameter :: strl = 1000 character(len=*), parameter :: str_format = "( a1000 )" end module sizes <|start_filename|>Makefile<|end_filename|> # # Makefile for Packmol: Read the comments if you have some # problem while compiling. # # You may use the ./configure script to search automatically for # some fortran compiler. # # This make file will try to compile packmol with the default # fortran compiler, defined by the FC directive. For doing this, # just type # # make # # If you want to compile with some specific fortran compiler, you must # change the line below to the path of your fortran compiler. # FORTRAN=/usr/bin/gfortran # # Change the flags of the compilation if you want: # FLAGS= -O3 --fast-math -march=native -funroll-loops ################################################################### # # # Generally no modifications are required after this. # # # ################################################################### # # Flags for compiling development version # GENCANFLAGS := $(FLAGS) ifeq ($(MAKECMDGOALS),devel) FLAGS = -Wall -fcheck=bounds -g -fbacktrace -ffpe-trap=zero,overflow,underflow GENCANFLAGS = -fcheck=bounds -g -fbacktrace -ffpe-trap=zero,overflow,underflow endif ifeq ($(MAKECMDGOALS),perf) FLAGS = -g -pg GENCANFLAGS = -g -pg endif ifeq ($(MAKECMDGOALS),static) FLAGS = -O3 --fast-math -static GENCANFLAGS = -O3 --fast-math -static endif # # Files required # oall = cenmass.o \ gencan.o \ pgencan.o \ initial.o \ title.o \ setsizes.o \ getinp.o \ strlength.o \ output.o \ checkpoint.o \ writesuccess.o \ fparc.o \ gparc.o \ gwalls.o \ comprest.o \ comparegrad.o \ packmol.o \ polartocart.o \ resetboxes.o \ tobar.o \ setijk.o \ setibox.o \ restmol.o \ swaptype.o \ swaptypemod.o \ ahestetic.o \ heuristics.o \ flashsort.o \ jacobi.o \ random.o \ sizes.o \ usegencan.o \ compute_data.o \ flashmod.o \ computef.o \ computeg.o \ input.o # # Linking # all : $(oall) @echo " ------------------------------------------------------ " @echo " Compiling packmol with $(FORTRAN) " @echo " Flags: $(FLAGS) " @echo " ------------------------------------------------------ " @$(FORTRAN) -o packmol $(oall) $(FLAGS) @\rm -f *.mod *.o @echo " ------------------------------------------------------ " @echo " Packmol succesfully built." @echo " ------------------------------------------------------ " # # Compiling with flags for development # static : devel perf : devel devel : $(oall) @echo " ------------------------------------------------------ " @echo " Compiling packmol with $(FORTRAN) " @echo " Flags: $(FLAGS)" @echo " ------------------------------------------------------ " @$(FORTRAN) -o packmol $(oall) $(FLAGS) @echo " ------------------------------------------------------ " @echo " Packmol succesfully built. " @echo " ------------------------------------------------------ " # # Modules # modules = sizes.o compute_data.o usegencan.o input.o flashmod.o swaptypemod.o ahestetic.o sizes.o : sizes.f90 @$(FORTRAN) $(FLAGS) -c sizes.f90 compute_data.o : compute_data.f90 sizes.o @$(FORTRAN) $(FLAGS) -c compute_data.f90 input.o : input.f90 sizes.o @$(FORTRAN) $(FLAGS) -c input.f90 flashmod.o : flashmod.f90 sizes.o @$(FORTRAN) $(FLAGS) -c flashmod.f90 usegencan.o : usegencan.f90 sizes.o @$(FORTRAN) $(FLAGS) -c usegencan.f90 swaptypemod.o : swaptypemod.f90 @$(FORTRAN) $(FLAGS) -c swaptypemod.f90 ahestetic.o : ahestetic.f90 @$(FORTRAN) $(FLAGS) -c ahestetic.f90 # # Code compiled only for all versions # cenmass.o : cenmass.f90 $(modules) @$(FORTRAN) $(FLAGS) -c cenmass.f90 initial.o : initial.f90 $(modules) @$(FORTRAN) $(FLAGS) -c initial.f90 title.o : title.f90 $(modules) @$(FORTRAN) $(FLAGS) -c title.f90 setsizes.o : setsizes.f90 $(modules) @$(FORTRAN) $(FLAGS) -c setsizes.f90 getinp.o : getinp.f90 $(modules) @$(FORTRAN) $(FLAGS) -c getinp.f90 strlength.o : strlength.f90 @$(FORTRAN) $(FLAGS) -c strlength.f90 output.o : output.f90 $(modules) @$(FORTRAN) $(FLAGS) -c output.f90 checkpoint.o : checkpoint.f90 $(modules) @$(FORTRAN) $(FLAGS) -c checkpoint.f90 writesuccess.o : writesuccess.f90 $(modules) @$(FORTRAN) $(FLAGS) -c writesuccess.f90 fparc.o : fparc.f90 $(modules) @$(FORTRAN) $(FLAGS) -c fparc.f90 gparc.o : gparc.f90 $(modules) @$(FORTRAN) $(FLAGS) -c gparc.f90 gwalls.o : gwalls.f90 $(modules) @$(FORTRAN) $(FLAGS) -c gwalls.f90 comprest.o : comprest.f90 $(modules) @$(FORTRAN) $(FLAGS) -c comprest.f90 comparegrad.o : comparegrad.f90 $(modules) @$(FORTRAN) $(FLAGS) -c comparegrad.f90 packmol.o : packmol.f90 $(modules) @$(FORTRAN) $(FLAGS) -c packmol.f90 polartocart.o : polartocart.f90 $(modules) @$(FORTRAN) $(FLAGS) -c polartocart.f90 resetboxes.o : resetboxes.f90 $(modules) @$(FORTRAN) $(FLAGS) -c resetboxes.f90 tobar.o : tobar.f90 $(modules) @$(FORTRAN) $(FLAGS) -c tobar.f90 setijk.o : setijk.f90 $(modules) @$(FORTRAN) $(FLAGS) -c setijk.f90 setibox.o : setibox.f90 $(modules) @$(FORTRAN) $(FLAGS) -c setibox.f90 restmol.o : restmol.f90 $(modules) @$(FORTRAN) $(FLAGS) -c restmol.f90 swaptype.o : swaptype.f90 $(modules) @$(FORTRAN) $(FLAGS) -c swaptype.f90 heuristics.o : heuristics.f90 $(modules) @$(FORTRAN) $(FLAGS) -c heuristics.f90 flashsort.o : flashsort.f90 $(modules) @$(FORTRAN) $(FLAGS) -c flashsort.f90 jacobi.o : jacobi.f90 @$(FORTRAN) $(FLAGS) -c jacobi.f90 pgencan.o : pgencan.f90 $(modules) @$(FORTRAN) $(FLAGS) -c pgencan.f90 gencan.o : gencan.f @$(FORTRAN) $(GENCANFLAGS) -c gencan.f random.o : random.f90 @$(FORTRAN) $(FLAGS) -c random.f90 computef.o : computef.f90 $(modules) @$(FORTRAN) $(FLAGS) -c computef.f90 computeg.o : computeg.f90 $(modules) @$(FORTRAN) $(FLAGS) -c computeg.f90 # # Clean build files # clean: @\rm -f ./*.o ./*.mod # # Remove all build and executable files to upload to git # cleanall: @\rm -f ./packmol ./*.o ./*.mod <|start_filename|>strlength.f90<|end_filename|> ! ! Written by <NAME>, 2009-2011. ! Copyright (c) 2009-2018, <NAME>, <NAME>, ! <NAME>. ! ! Function that determines the length of a string (better than ! intrinsic "len" because considers tabs as empty characters) ! function strlength(string) use sizes implicit none integer :: strlength character(len=strl) :: string logical empty_char strlength = strl do while(empty_char(string(strlength:strlength))) strlength = strlength - 1 if ( strlength == 0 ) exit end do end function strlength ! ! Function that determines if a character is empty (empty, space, or tab) ! (nice suggestion from <NAME> -IanH0073- at github) ! function empty_char(ch) character :: ch logical empty_char empty_char = .false. if ( ch == '' .or. & ch == achar(9) .or. & ch == achar(32) ) then empty_char = .true. end if end function empty_char ! ! Function that replaces all non-space empty characters by spaces ! function alltospace(record) use sizes implicit none integer :: i logical :: empty_char character(len=strl) :: alltospace, record do i = 1, strl if ( empty_char(record(i:i)) ) then alltospace(i:i) = " " else alltospace(i:i) = record(i:i) end if end do end function alltospace subroutine parse_spaces(record) use input, only : forbidden_char use sizes implicit none integer :: i, strlength character(len=strl) :: record ! Replace spaces within quotes by ~ i = 0 do while(i < strlength(record)) i = i + 1 if ( record(i:i) == '"' ) then i = i + 1 do while(record(i:i) /= '"') i = i + 1 if( i > strlength(record) ) then write(*,*) ' ERROR: Could not find ending quotes in line: ', trim(record) stop end if if(record(i:i) == " ") then record(i:i) = forbidden_char end if end do end if end do ! Replace spaces after \ by the forbidden_char and remove the \ i = 0 do while(i < strlength(record)-1) i = i + 1 if (record(i:i) == "\" .and. record(i+1:i+1) == " ") then record(i:i) = forbidden_char record = record(1:i)//record(i+2:strlength(record)) end if end do end
leandromartinez98/Packmol
<|start_filename|>citrus-support/src/main/java/com/github/yiuman/citrus/support/crud/view/impl/SimpleTreeView.java<|end_filename|> package com.github.yiuman.citrus.support.crud.view.impl; import com.github.yiuman.citrus.support.crud.view.TreeView; import com.github.yiuman.citrus.support.model.Button; import com.github.yiuman.citrus.support.model.Tree; import com.github.yiuman.citrus.support.widget.Inputs; import com.github.yiuman.citrus.support.widget.Widget; import java.util.ArrayList; import java.util.List; /** * CRUD操作时显示的页面树形结构以及页面组件 * * @param <T> 树形视图的树形实体类型 * @author yiuman * @date 2020/5/13 */ public class SimpleTreeView<T extends Tree<?>> extends BaseActionableView implements TreeView<T> { private boolean displayRoot = true; private boolean lazy; /** * 实体的主键 */ private String itemKey = "id"; /** * 显示的名称 */ private String itemText = "name"; /** * 顶部的控件集合 */ private List<Object> widgets = new ArrayList<>(); private T tree; /** * 顶部按钮 */ private List<Button> buttons = new ArrayList<>(); /** * 列的按钮,列的事件,行内操作 * 此处可用El表达式 */ private List<Button> actions = new ArrayList<>(); public SimpleTreeView() { } public SimpleTreeView(boolean displayRoot) { this.displayRoot = displayRoot; } @Override public boolean isDisplayRoot() { return displayRoot; } public void setDisplayRoot(boolean displayRoot) { this.displayRoot = displayRoot; } @Override public boolean isLazy() { return lazy; } public void setLazy(boolean lazy) { this.lazy = lazy; } @Override public String getItemKey() { return itemKey; } @Override public void setItemKey(String itemKey) { this.itemKey = itemKey; } @Override public String getItemText() { return itemText; } @Override public void setItemText(String itemText) { this.itemText = itemText; } @Override public List<Object> getWidgets() { return widgets; } @Override public void setWidgets(List<Object> widgets) { this.widgets = widgets; } @Override public T getTree() { return tree; } @Override public void setTree(T tree) { this.tree = tree; } @Override public List<Button> getButtons() { return buttons; } @Override public void setButtons(List<Button> buttons) { this.buttons = buttons; } @Override public List<Button> getActions() { return actions; } @Override public void setActions(List<Button> actions) { this.actions = actions; } @Override public <W extends Widget<?>> void addWidget(W widget) { addWidget(widget, false); } @Override public void addWidget(String text, String fieldName) { Inputs inputs = new Inputs(text, fieldName); addWidget(inputs); } @Override public <W extends Widget<?>> void addWidget(W widget, boolean refresh) { if (refresh || !widgets.contains(widget)) { int indexOf = widgets.indexOf(widget); if (indexOf != -1) { widgets.set(indexOf, widget); } else { widgets.add(widget); } } } @Override public void addButton(Button button) { buttons.add(button); } public void addButton(List<Button> buttons) { buttons.forEach(this::addButton); } @Override public void addAction(Button button) { actions.add(button); } public void addAction(String text, String action) { Button button = new Button(text, action); button.setScript(true); actions.add(button); } } <|start_filename|>citrus-support/src/main/java/com/github/yiuman/citrus/support/utils/ValidateUtils.java<|end_filename|> package com.github.yiuman.citrus.support.utils; import com.baomidou.mybatisplus.core.toolkit.CollectionUtils; import com.baomidou.mybatisplus.core.toolkit.StringUtils; import javax.validation.ConstraintViolation; import javax.validation.Validation; import javax.validation.Validator; import javax.validation.groups.Default; import java.text.MessageFormat; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.function.Function; /** * 检验工具 * * @author yiuman * @date 2020/4/3 */ public final class ValidateUtils { private ValidateUtils() { } /** * 验证器 */ private static final Validator VALIDATOR = Validation.buildDefaultValidatorFactory().getValidator(); /** * 校验实体,返回实体所有属性的校验结果 */ public static <T> ValidationResult validateEntity(T obj) { //解析校验结果 Set<ConstraintViolation<T>> validateSet = VALIDATOR.validate(obj, Default.class); return buildValidationResult(validateSet); } /** * 校验实体,返回实体所有属性的校验结果 */ public static <T> void defaultValidateEntity(T obj) { //解析校验结果 validateEntityAndThrows(obj, result -> new RuntimeException(result.getMessage())); } /** * 校验指定实体的指定属性是否存在异常 */ public static <T> ValidationResult validateProperty(T obj, String propertyName) { Set<ConstraintViolation<T>> validateSet = VALIDATOR.validateProperty(obj, propertyName, Default.class); return buildValidationResult(validateSet); } public static <T, E extends Exception> void validateEntityAndThrows(T obj, Function<ValidationResult, E> func) throws E { ValidationResult validationResult = validateEntity(obj); if (validationResult.isHasErrors()) { throw func.apply(validationResult); } } /** * 将异常结果封装返回 */ private static <T> ValidationResult buildValidationResult(Set<ConstraintViolation<T>> validateSet) { ValidationResult validationResult = new ValidationResult(); if (CollectionUtils.isNotEmpty(validateSet)) { validationResult.setHasErrors(true); Map<String, String> errorMsgMap = new HashMap<>(validateSet.size()); for (ConstraintViolation<T> constraintViolation : validateSet) { errorMsgMap.put(constraintViolation.getPropertyPath().toString(), constraintViolation.getMessage()); } validationResult.setErrorMsg(errorMsgMap); } return validationResult; } public static class ValidationResult { /** * 是否有异常 */ private boolean hasErrors; /** * 异常消息记录 */ private Map<String, String> errorMsg; /** * 获取异常消息组装 */ public String getMessage() { if (errorMsg == null || errorMsg.isEmpty()) { return StringUtils.EMPTY; } StringBuilder message = new StringBuilder(); errorMsg.forEach((key, value) -> message.append(MessageFormat.format("{0}:{1} \r\n", key, value))); return message.toString(); } public boolean isHasErrors() { return hasErrors; } public void setHasErrors(boolean hasErrors) { this.hasErrors = hasErrors; } public Map<String, String> getErrorMsg() { return errorMsg; } public void setErrorMsg(Map<String, String> errorMsg) { this.errorMsg = errorMsg; } } } <|start_filename|>citrus-workflow/src/main/java/com/github/yiuman/citrus/workflow/service/impl/BaseWorkflowService.java<|end_filename|> package com.github.yiuman.citrus.workflow.service.impl; import com.baomidou.mybatisplus.core.toolkit.StringUtils; import com.github.yiuman.citrus.support.utils.LambdaUtils; import com.github.yiuman.citrus.support.utils.SpringUtils; import com.github.yiuman.citrus.workflow.cmd.JumpTaskCmd; import com.github.yiuman.citrus.workflow.exception.WorkflowException; import com.github.yiuman.citrus.workflow.model.ProcessPersonalModel; import com.github.yiuman.citrus.workflow.model.StartProcessModel; import com.github.yiuman.citrus.workflow.model.TaskCompleteModel; import com.github.yiuman.citrus.workflow.model.impl.TaskCompleteModelImpl; import com.github.yiuman.citrus.workflow.model.impl.WorkflowContextImpl; import com.github.yiuman.citrus.workflow.resolver.TaskCandidateResolver; import com.github.yiuman.citrus.workflow.service.WorkflowEngineGetter; import com.github.yiuman.citrus.workflow.service.WorkflowService; import org.activiti.bpmn.model.BpmnModel; import org.activiti.bpmn.model.FlowElement; import org.activiti.bpmn.model.UserTask; import org.activiti.engine.ProcessEngine; import org.activiti.engine.RepositoryService; import org.activiti.engine.RuntimeService; import org.activiti.engine.TaskService; import org.activiti.engine.repository.ProcessDefinition; import org.activiti.engine.runtime.ProcessInstance; import org.activiti.engine.task.Task; import org.springframework.util.Assert; import org.springframework.util.CollectionUtils; import java.util.*; /** * 流程处理抽象类<br/> * 开启流程、完成任务、签收任务、挂起、激活 * * @author yiuman * @date 2020/12/11 */ public abstract class BaseWorkflowService implements WorkflowService { private WorkflowEngineGetter workflowEngineGetter; private TaskCandidateResolver taskCandidateResolver; @Override public ProcessEngine getProcessEngine() { workflowEngineGetter = Optional.ofNullable(workflowEngineGetter) .orElse(SpringUtils.getBean(WorkflowEngineGetterImpl.class, true)); return workflowEngineGetter.getProcessEngine(); } public TaskCandidateResolver getTaskCandidateResolver() { return taskCandidateResolver = Optional.ofNullable(taskCandidateResolver) .orElse(SpringUtils.getBean(TaskCandidateResolver.class, true)); } @Override public ProcessInstance starProcess(StartProcessModel model) { String processDefineId = model.getProcessDefineKey(); //找到流程定义 ProcessDefinition definition = Optional.ofNullable( getProcessEngine().getRepositoryService() .createProcessDefinitionQuery() .processDefinitionKey(processDefineId) .latestVersion() .singleResult() ).orElseThrow(() -> new IllegalArgumentException(String.format("can not find ProcessDefinition for key:[%s]", processDefineId))); //开起流程 Map<String, Object> processInstanceVars = model.getVariables(); ProcessInstance processInstance = getProcessEngine().getRuntimeService().startProcessInstanceById( definition.getId(), model.getBusinessKey(), processInstanceVars ); //1.找到当前流程的任务节点。 //2.若任务处理人与申请人一致,则自动完成任务,直接进入下一步 //如请假申请为流程的第一步,则此任务自动完成 if (StringUtils.isNotBlank(model.getUserId())) { TaskService taskService = getProcessEngine().getTaskService(); Task applyUserTask = taskService.createTaskQuery() .processInstanceId(processInstance.getId()) .taskCandidateOrAssigned(model.getUserId()) .active() .singleResult(); if (Objects.nonNull(applyUserTask)) { complete(TaskCompleteModelImpl.builder() .taskId(applyUserTask.getId()) .taskVariables(processInstanceVars) .userId(model.getUserId()) .candidateOrAssigned(model.getCandidateOrAssigned()) .build()); } } return processInstance; } @Override public void complete(TaskCompleteModel model) { Assert.notNull(model.getTaskId(), "The taskId of the process can not be empty!"); TaskService taskService = getProcessEngine().getTaskService(); //扎到相关任务 Task task = Optional.ofNullable(taskService.createTaskQuery() .taskId(model.getTaskId()) .active() .singleResult()) .orElseThrow(() -> new WorkflowException(String.format("cannot find Task for taskId:[%s]", model.getTaskId()))); //1.找到任务的处理人,若任务未签收(没有处理人),则抛出异常 //2.若处理人与任务模型的用户不匹配也抛出异常 String assignee = task.getAssignee(); Assert.notNull(assignee, String.format("Task for taskId:[%s] did not claimed", task.getId())); if (!assignee.equals(model.getUserId())) { throw new WorkflowException(String.format("Task for taskId:[%s] can not complete by user:[%s]", task.getId(), model.getUserId())); } taskService.setVariables(task.getId(), model.getVariables()); taskService.setVariablesLocal(task.getId(), model.getTaskVariables()); task.getBusinessKey(); taskService.complete(task.getId()); //如果有设置目标任务关键字则进行任务跳转 if (StringUtils.isNotBlank(model.getTargetTaskKey())) { jump(task.getId(), model.getTargetTaskKey()); } //完成此环节后,检查有没下个环节,有的话且是未设置办理人或候选人的情况下,使用模型进行设置 List<Task> taskList = taskService.createTaskQuery() .processInstanceId(task.getProcessInstanceId()) .active() .list(); if (!taskList.isEmpty()) { //设置任务的候选人 taskList.forEach(LambdaUtils.consumerWrapper(nextTask -> setCandidateOrAssigned(nextTask, model))); } } /** * 设置候选人或处理人 * * @param task 当前的任务 * @param model 流程人员模型 */ protected void setCandidateOrAssigned(Task task, ProcessPersonalModel model) throws Exception { task.getProcessInstanceId(); TaskService taskService = getProcessEngine().getTaskService(); //查询当前任务是否已经有候选人或办理人 RepositoryService repositoryService = getProcessEngine().getRepositoryService(); BpmnModel bpmnModel = repositoryService.getBpmnModel(task.getProcessDefinitionId()); FlowElement flowElement = bpmnModel.getFlowElement(task.getTaskDefinitionKey()); if (flowElement instanceof UserTask) { UserTask userTask = (UserTask) flowElement; List<String> taskCandidateUsersDefine = userTask.getCandidateUsers(); //没有负责人,则用解析器解析流程任务定义的候选人或参数传入来的候选人 if (StringUtils.isBlank(task.getAssignee())) { List<String> allCandidateOrAssigned = new ArrayList<>(); List<String> modelCandidateOrAssigned = model.getCandidateOrAssigned(); if (!CollectionUtils.isEmpty(modelCandidateOrAssigned)) { allCandidateOrAssigned.addAll(modelCandidateOrAssigned); } allCandidateOrAssigned.addAll(taskCandidateUsersDefine); //删除任务候选人 allCandidateOrAssigned.forEach(candidateDefine -> taskService.deleteCandidateUser(task.getId(), candidateDefine)); RuntimeService runtimeService = getProcessEngine().getRuntimeService(); WorkflowContextImpl workflowContext = WorkflowContextImpl.builder() .processEngine(getProcessEngine()) .processInstance( runtimeService .createProcessInstanceQuery() .processInstanceId(task.getProcessInstanceId()) .singleResult() ) .task(task) .flowElement(flowElement) .currentUserId(model.getUserId()) .build(); //解析器解析完成后,把真正的候选人添加到任务中去 Optional.ofNullable(getTaskCandidateResolver().resolve(workflowContext, allCandidateOrAssigned)) .ifPresent(resolvedCandidates -> { if (resolvedCandidates.size() == 1) { taskService.setAssignee(task.getId(), resolvedCandidates.get(1)); } else { resolvedCandidates.stream().filter(Objects::nonNull).forEach(realUserId -> taskService.addCandidateUser(task.getId(), realUserId)); } }); } } } @Override public void claim(String taskId, String userId) { TaskService taskService = getProcessEngine().getTaskService(); Task task = Optional.ofNullable(taskService.createTaskQuery() .taskId(taskId) .taskCandidateOrAssigned(userId) .singleResult()) .orElseThrow(() -> new WorkflowException(String.format("can not claim Task for taskId:[%s]", taskId))); String assignee = task.getAssignee(); if (StringUtils.isNotBlank(assignee)) { throw new WorkflowException(String.format("Task for taskId:[%s] has been claimed", taskId)); } taskService.claim(taskId, userId); } @Override public void jump(String taskId, String targetTaskKey) { TaskService taskService = getProcessEngine().getTaskService(); Task task = Optional.ofNullable(taskService.createTaskQuery().taskId(taskId).singleResult()) .orElseThrow(() -> new WorkflowException(String.format("cannot find Task for taskId:[%s]", taskId))); Optional.ofNullable(getProcessEngine().getRuntimeService() .createProcessInstanceQuery() .processInstanceId(task.getProcessInstanceId()). active().singleResult()).orElseThrow(() -> new WorkflowException("This ProcessInstance is not active,cannot do jump")); //构建跳转命令并执行 getProcessEngine().getManagementService().executeCommand(JumpTaskCmd.builder() .executionId(task.getExecutionId()) .targetTaskKey(targetTaskKey) .build()); } @Override public void suspend(String instanceId) { getProcessEngine().getRuntimeService().suspendProcessInstanceById(instanceId); } @Override public void activate(String instanceId) { getProcessEngine().getRuntimeService().activateProcessInstanceById(instanceId); } } <|start_filename|>citrus-support/src/main/java/com/github/yiuman/citrus/support/crud/rest/BaseRestful.java<|end_filename|> package com.github.yiuman.citrus.support.crud.rest; import com.baomidou.mybatisplus.core.toolkit.ReflectionKit; import com.github.yiuman.citrus.support.crud.CrudHelper; import com.github.yiuman.citrus.support.crud.service.CrudService; import lombok.extern.slf4j.Slf4j; import java.io.Serializable; /** * 最顶层Restful基类,用于定义、实现最通用的属性与方法 * * @param <T> 实体类型 * @param <K> 主键类型 * @author yiuman * @date 2020/10/1 */ @Slf4j public abstract class BaseRestful<T, K extends Serializable> { /** * 模型类型 */ protected Class<T> modelClass = currentModelClass(); protected Class<K> keyClass = currentKeyClass(); public BaseRestful() { } @SuppressWarnings("unchecked") private Class<T> currentModelClass() { return (Class<T>) ReflectionKit.getSuperClassGenericType(getClass(), 0); } @SuppressWarnings("unchecked") private Class<K> currentKeyClass() { return (Class<K>) ReflectionKit.getSuperClassGenericType(getClass(), 1); } /** * 获取CRUD逻辑层服务类 * * @return 实现了 CrudService的逻辑层 */ protected CrudService<T, K> getService() { return CrudHelper.getCrudService(modelClass, keyClass); } } <|start_filename|>citrus-security/src/main/java/com/github/yiuman/citrus/security/authorize/AuthorizeConfigManagerImpl.java<|end_filename|> package com.github.yiuman.citrus.security.authorize; import org.springframework.lang.Nullable; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.builders.WebSecurity; import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer; import java.util.List; /** * 授权信息管理器实现 * 用于收集系统中所有 AuthorizeConfigProvider 并加载其配置 * * @author yiuman * @date 2020/3/23 */ public class AuthorizeConfigManagerImpl implements AuthorizeConfigManager { private final List<AuthorizeConfigProvider> authorizeConfigProviders; private final List<WebSecurityConfigProvider> webSecurityConfigProviders; public AuthorizeConfigManagerImpl(List<AuthorizeConfigProvider> authorizeConfigProviders, @Nullable List<WebSecurityConfigProvider> webSecurityConfigProviders) { this.authorizeConfigProviders = authorizeConfigProviders; this.webSecurityConfigProviders = webSecurityConfigProviders; } @Override public void config(ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry config) { boolean existAnyRequestConfig = false; String existAnyRequestConfigName = null; for (AuthorizeConfigProvider authorizeConfigProvider : authorizeConfigProviders) { boolean currentIsAnyRequestConfig = authorizeConfigProvider.config(config); if (existAnyRequestConfig && currentIsAnyRequestConfig) { String tips = String .format("Duplicate configuration for org.springframework.security.config.annotation.web.AbstractRequestMatcherRegistry.anyRequest:%s,%s", existAnyRequestConfigName, authorizeConfigProvider.getClass().getName()); throw new RuntimeException(tips); } else if (currentIsAnyRequestConfig) { existAnyRequestConfig = true; existAnyRequestConfigName = authorizeConfigProvider.getClass().getSimpleName(); } } if (!existAnyRequestConfig) { config.anyRequest().authenticated(); } } @Override public void config(WebSecurity webSecurity) { webSecurityConfigProviders.forEach(provider -> provider.config(webSecurity)); } } <|start_filename|>citrus-security/src/main/java/com/github/yiuman/citrus/security/authenticate/AuthenticateProcessorImpl.java<|end_filename|> package com.github.yiuman.citrus.security.authenticate; import com.github.yiuman.citrus.security.jwt.JwtToken; import com.github.yiuman.citrus.security.jwt.JwtUtils; import io.jsonwebtoken.Claims; import lombok.extern.slf4j.Slf4j; import org.springframework.security.authentication.AuthenticationServiceException; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.stereotype.Service; import org.springframework.util.Assert; import org.springframework.util.StringUtils; import org.springframework.web.multipart.support.AbstractMultipartHttpServletRequest; import javax.servlet.http.HttpServletRequest; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; /** * 认证处理器实现 * * @author yiuman * @date 2020/4/3 */ @Service @Slf4j public class AuthenticateProcessorImpl implements AuthenticateProcessor { /** * 认证模式参数KEY */ private static final String AUTHENTICATION_MODE_PARAMETER_KEY = "mode"; /** * 认证服务类 */ private final List<AuthenticateService> authenticateServices; public AuthenticateProcessorImpl(List<AuthenticateService> authenticateServices) { Assert.notNull(authenticateServices, "AuthenticateService must not be null"); this.authenticateServices = authenticateServices; } @Override public AuthenticateService findByMode(String mode) throws AuthenticationException { if (!StringUtils.hasText(mode)) { throw new AuthenticationServiceException("The Authenticate's parameter 'model' must not be null"); } //找到对应模式的认证服务类 return authenticateServices.parallelStream() .filter(authenticateService -> mode.equals(authenticateService.supportMode())) .findFirst() .orElseThrow(() -> new AuthenticationServiceException(String.format("Cannot found Authenticate's model of %s", mode))); } @Override public Authentication authenticate(HttpServletRequest request) throws AuthenticationException { return findByMode(request.getParameter(AUTHENTICATION_MODE_PARAMETER_KEY)).authenticate(request); } @Override public JwtToken token(HttpServletRequest request) { HttpServletRequest actualRequest = request; if (!(request instanceof AbstractMultipartHttpServletRequest)) { try { //此处非Multipart就构造一个Json的RequestWrapper 用与适配多种请求方式 actualRequest = new JsonServletRequestWrapper(request); } catch (Exception e) { throw new AuthenticationServiceException("BAD REQUEST"); } } Map<String, Object> claims = new HashMap<>(16); claims.put(AUTHENTICATION_MODE_PARAMETER_KEY, actualRequest.getParameter(AUTHENTICATION_MODE_PARAMETER_KEY)); Authentication authenticate = authenticate(actualRequest); return JwtUtils.generateToken((String) authenticate.getCredentials(), claims); } @Override public Optional<Authentication> resolve(HttpServletRequest request) { String token = JwtUtils.resolveToken(request); if (StringUtils.hasText(token) && JwtUtils.validateToken(token)) { Claims claims = JwtUtils.getClaims(token); String mode = (String) claims.get(AUTHENTICATION_MODE_PARAMETER_KEY); String identity = (String) claims.get(JwtUtils.getIdentityKey()); try { AuthenticateService service = findByMode(mode); return service.resolve(token, identity); } catch (Exception e) { return Optional.empty(); } } return Optional.empty(); } @Override public void logout(HttpServletRequest request) { String token = JwtUtils.resolveToken(request); if (StringUtils.hasText(token) && JwtUtils.validateToken(token)) { Claims claims = JwtUtils.getClaims(token); String mode = (String) claims.get(AUTHENTICATION_MODE_PARAMETER_KEY); String identity = (String) claims.get(JwtUtils.getIdentityKey()); try { AuthenticateService service = findByMode(mode); Optional<Authentication> authentication = service.resolve(token, identity); authentication.ifPresent(service::logout); } catch (Exception e) { log.error("logout exception", e); } } } } <|start_filename|>citrus-support/src/main/java/com/github/yiuman/citrus/support/crud/query/Query.java<|end_filename|> package com.github.yiuman.citrus.support.crud.query; import com.github.yiuman.citrus.support.model.SortBy; import java.util.ArrayList; import java.util.List; /** * 查询对象 * * @author yiuman * @date 2021/8/15 */ @SuppressWarnings({"unused", "RedundantSuppression"}) public class Query { private List<ConditionInfo> conditions = new ArrayList<>(); private List<SortBy> sorts = new ArrayList<>(); public Query() { } public List<ConditionInfo> getConditions() { return conditions; } public void setConditions(List<ConditionInfo> conditions) { this.conditions = conditions; } public List<SortBy> getSorts() { return sorts; } public void setSorts(List<SortBy> sorts) { this.sorts = sorts; } public static Query create() { return new Query(); } public void addConditionInfo(String parameter, Object value, Operations operations) { conditions.add(ConditionInfo.builder() .operator(operations.getType()) .parameter(parameter) .mapping(parameter) .value(value) .type(value.getClass()) .build()); } } <|start_filename|>citrus-support/src/main/java/com/github/yiuman/citrus/support/crud/view/impl/PageTableView.java<|end_filename|> package com.github.yiuman.citrus.support.crud.view.impl; import com.github.yiuman.citrus.support.crud.view.EditableView; /** * 页面中有编辑器的表格视图 * * @param <T> 实体类型 * @author yiuman * @date 2021/1/20 */ public class PageTableView<T> extends SimpleTableView<T> implements EditableView { /** * 编辑器,用于实例的编辑(新增、修改) */ private Object editableView; public PageTableView() { } public PageTableView(boolean checkable) { super(checkable); } @Override public Object getEditableView() { return editableView; } @Override public void setEditableView(Object editableView) { this.editableView = editableView; } } <|start_filename|>citrus-support/src/main/java/com/github/yiuman/citrus/support/crud/rest/BaseQueryController.java<|end_filename|> package com.github.yiuman.citrus.support.crud.rest; import com.github.yiuman.citrus.support.http.ResponseEntity; import com.github.yiuman.citrus.support.model.Page; import org.springframework.aop.framework.AopContext; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.Serializable; import java.util.Optional; /** * 基本查询控制器 * * @param <T> 实体类型 * @param <K> 主键类型 * @author yiuman * @date 2020/10/1 */ public abstract class BaseQueryController<T, K extends Serializable> extends BaseQueryRestful<T, K> { @SuppressWarnings("unchecked") @GetMapping public ResponseEntity<Page<T>> getPageList(HttpServletRequest request) throws Exception { BaseQueryController<T, K> currentProxy = Optional.ofNullable((BaseQueryController<T, K>) AopContext.currentProxy()).orElse(this); return ResponseEntity.ok(currentProxy.page(request)); } @GetMapping(Operations.GET) public ResponseEntity<T> getByKey(@PathVariable K key) { return ResponseEntity.ok(get(key)); } /** * 导出 */ @GetMapping(value = Operations.EXPORT) public void export(HttpServletRequest request, HttpServletResponse response) throws Exception { exp(request, response); } }
BigEmptyCup/citrus
<|start_filename|>IdentityServer/Config.cs<|end_filename|>  using System.Collections.Generic; using IdentityServer4.Models; namespace IdentityServer { public class Config { private const string ClientUsername = "WidgetClient"; private const string ClientPassword = "<PASSWORD>"; private const string ClientResource = "widgetapi"; // scopes define the API resources in your system public static IEnumerable<ApiResource> GetApiResources() { return new List<ApiResource> { new ApiResource(ClientResource, "WidgetApi") }; } // clients want to access resources (aka scopes) public static IEnumerable<Client> GetClients() { // client credentials client return new List<Client> { new Client { ClientId = ClientUsername, AllowedGrantTypes = GrantTypes.ClientCredentials, ClientSecrets = { new Secret(ClientPassword.Sha256()) }, AllowedScopes = { ClientResource } } }; } } } <|start_filename|>WidgetApi/Models/Widget.cs<|end_filename|> namespace WidgetApi.Models { public class Widget { public int ID { get; set; } public string Name { get; set; } public string Shape { get; set; } } }
nibro7778/identity-server4
<|start_filename|>FSharp.Json.Tests/Map.fs<|end_filename|> namespace FSharp.Json module Map = open System open NUnit.Framework [<Test>] let ``Map<string,string> serialization`` () = let expected = """{"key":"value"}""" let value = Map.ofList [("key", "value")] let actual = Json.serializeU value Assert.AreEqual(expected, actual) [<Test>] let ``Map<string,string> deserialization`` () = let json = """{"key":"value"}""" let expected = Map.ofList [("key", "value")] let actual = Json.deserialize<Map<string, string>> json Assert.AreEqual(expected, actual) [<Test>] let ``Map<string,obj> serialization`` () = let expected = """{"key1":"value","key2":123}""" let value = Map.ofList [("key1", "value" :> obj); ("key2", 123 :> obj)] let actual = Json.serializeU value Assert.AreEqual(expected, actual) [<Test>] let ``Map<string,obj> deserialization`` () = let json = """{"key1":"value","key2":123}""" let expected = Map.ofList [("key1", "value" :> obj); ("key2", 123 :> obj)] let config = JsonConfig.create(allowUntyped = true) let actual = Json.deserializeEx<Map<string, obj>> config json Assert.AreEqual(expected, actual) <|start_filename|>FSharp.Json/Reflection.fs<|end_filename|> namespace FSharp.Json module internal Reflection = open System open System.Reflection open System.Collections.Concurrent open Microsoft.FSharp.Reflection let isOption_ (t: Type): bool = t.IsGenericType && t.GetGenericTypeDefinition() = typedefof<option<_>> let getOptionType_ (t: Type): Type = t.GetGenericArguments().[0] let isArray_ (t: Type) = t.IsArray let isList_ (t: Type) = t.IsGenericType && t.GetGenericTypeDefinition() = typedefof<List<_>> let getListType_ (itemType: Type) = typedefof<List<_>>.MakeGenericType([| itemType |]) let getListItemType_ (t: Type) = t.GetGenericArguments().[0] let getListConstructor_ (t: Type) = t.GetMethod ("Cons") let getListEmptyProperty_ (t: Type) = t.GetProperty("Empty") let isMap_ (t: Type) = t.IsGenericType && t.GetGenericTypeDefinition() = typedefof<Map<_,_>> let getMapKeyType_ (t: Type) = t.GetGenericArguments().[0] let getMapValueType_ (t: Type) = t.GetGenericArguments().[1] let getMapKvpTupleType_ (t: Type) = t.GetGenericArguments() |> FSharpType.MakeTupleType let cacheResult (theFunction:'P -> 'R) = let theFunction = new Func<_, _>(theFunction) let cache = new ConcurrentDictionary<'P, 'R>() fun parameter -> cache.GetOrAdd(parameter, theFunction) let isRecord: Type -> bool = FSharpType.IsRecord |> cacheResult let getRecordFields: Type -> PropertyInfo [] = FSharpType.GetRecordFields |> cacheResult let isUnion: Type -> bool = FSharpType.IsUnion |> cacheResult let getUnionCases: Type -> UnionCaseInfo [] = FSharpType.GetUnionCases |> cacheResult let isTuple: Type -> bool = FSharpType.IsTuple |> cacheResult let getTupleElements: Type -> Type [] = FSharpType.GetTupleElements |> cacheResult let isOption: Type -> bool = isOption_ |> cacheResult let getOptionType: Type -> Type = getOptionType_ |> cacheResult let isArray: Type -> bool = isArray_ |> cacheResult let isList: Type -> bool = isList_ |> cacheResult let getListType: Type -> Type = getListType_ |> cacheResult let getListItemType: Type -> Type = getListItemType_ |> cacheResult let getListConstructor: Type -> MethodInfo = getListConstructor_ |> cacheResult let getListEmptyProperty: Type -> PropertyInfo = getListEmptyProperty_ |> cacheResult let isMap: Type -> bool = isMap_ |> cacheResult let getMapKeyType: Type -> Type = getMapKeyType_ |> cacheResult let getMapValueType: Type -> Type = getMapValueType_ |> cacheResult let getMapKvpTupleType: Type -> Type = getMapKvpTupleType_ |> cacheResult let unwrapOption (t: Type) (value: obj): obj option = let _, fields = FSharpValue.GetUnionFields(value, t) match fields.Length with | 1 -> Some fields.[0] | _ -> None let optionNone (t: Type): obj = let casesInfos = getUnionCases t FSharpValue.MakeUnion(casesInfos.[0], Array.empty) let optionSome (t: Type) (value: obj): obj = let casesInfos = getUnionCases t FSharpValue.MakeUnion(casesInfos.[1], [| value |]) let createList (itemType: Type) (items: obj list) = let listType = getListType itemType let theConstructor = getListConstructor listType let addItem item list = theConstructor.Invoke (null, [| item; list |]) let theList = (getListEmptyProperty listType).GetValue(null) List.foldBack addItem items theList let KvpKey (value: obj): obj = let keyProperty = value.GetType().GetProperty("Key") keyProperty.GetValue(value, null) let KvpValue (value: obj): obj = let valueProperty = value.GetType().GetProperty("Value") valueProperty.GetValue(value, null) let CreateMap (mapType: Type) (items: (string*obj) list) = let theConstructor = mapType.GetConstructors().[0] let tupleType = getMapKvpTupleType mapType let listItems = items |> List.map (fun item -> FSharpValue.MakeTuple([|fst item; snd item|], tupleType)) let theList = createList tupleType listItems theConstructor.Invoke([|theList|])
AntoineGagne/FSharp.Json
<|start_filename|>app/src/main/java/com/egoriku/motionlayoutandroidacademy/App.kt<|end_filename|> @file:Suppress("unused") package com.egoriku.motionlayoutandroidacademy import android.app.Application import android.content.Intent import android.view.View import androidx.constraintlayout.motion.widget.MotionLayout import com.egoriku.motionlayoutandroidacademy.activity.MotionActivity import com.egoriku.motionlayoutandroidacademy.common.LAYOUT_ID import com.egoriku.motionlayoutandroidacademy.common.visible import com.pandulapeter.beagle.Beagle import com.pandulapeter.beagleCore.configuration.Trick import com.pandulapeter.beagleCore.contracts.BeagleListItemContract class App : Application() { override fun onCreate() { super.onCreate() Beagle.imprint(this) Beagle.learn( Trick.Header(title = getString(R.string.app_name)), Trick.Button( text = "Enable Coordinator", onButtonPressed = { Beagle.currentActivity?.run { findViewById<View>(R.id.appbarLayout)?.visible() } } ), Trick.SimpleList( title = "Debug mode", isInitiallyExpanded = true, items = listOf( DebugOptions(name = "NO_DEBUG", value = 0), DebugOptions(name = "SHOW_PROGRESS", value = 1), DebugOptions(name = "SHOW_PATH", value = 2), DebugOptions(name = "SHOW_ALL", value = 3) ), onItemSelected = { Beagle.currentActivity?.run { findViewById<MotionLayout>(R.id.motionLayout)?.setDebugMode(it.value) Beagle.dismiss() } } ), Trick.SimpleList( title = "Basic animations", isInitiallyExpanded = true, items = listOf( DebugOptions(name = "Click", value = R.layout.activity_basic_click), DebugOptions(name = "Transform", value = R.layout.activity_basic_transform), DebugOptions(name = "Custom Attribute", value = R.layout.activity_basic_custom_attribute), DebugOptions(name = "Swipe", value = R.layout.activity_basic_swipe), DebugOptions(name = "ImageFilterView", value = R.layout.activity_basic_imagefilter), DebugOptions(name = "ImageFilterView Saturation", value = R.layout.activity_basic_imagefilter_saturation), DebugOptions(name = "PropertySet", value = R.layout.activity_basic_property_set), DebugOptions(name = "KeyPosition", value = R.layout.activity_basic_keyposition), DebugOptions(name = "KeyAttribute", value = R.layout.activity_basic_keyattribute), DebugOptions(name = "Motion", value = R.layout.activity_basic_motion), DebugOptions(name = "KeyCycle", value = R.layout.activity_basic_key_cycle), DebugOptions(name = "KeyTimeCycle", value = R.layout.activity_basic_key_time_cycle), DebugOptions(name = "KeyTrigger", value = R.layout.activity_basic_key_trigger) ), onItemSelected = { Beagle.currentActivity?.run { startActivity(Intent(this, MotionActivity::class.java).apply { putExtra(LAYOUT_ID, it.value) }) } } ) ) } } data class DebugOptions( override val name: String, val value: Int ) : BeagleListItemContract <|start_filename|>app/src/main/java/com/egoriku/motionlayoutandroidacademy/common/Ext.kt<|end_filename|> package com.egoriku.motionlayoutandroidacademy.common import android.content.Context import android.os.Bundle import android.view.View import android.widget.Toast import kotlin.properties.ReadWriteProperty import kotlin.reflect.KProperty const val LAYOUT_ID = "layout_id" sealed class BundleDelegate<T>(protected val key: String) : ReadWriteProperty<Bundle, T> { class Int(key: String) : BundleDelegate<kotlin.Int>(key) { override fun getValue(thisRef: Bundle, property: KProperty<*>) = thisRef.getInt(key) override fun setValue(thisRef: Bundle, property: KProperty<*>, value: kotlin.Int) = thisRef.putInt(key, value) } } fun View.visible() { if (visibility != View.VISIBLE) visibility = View.VISIBLE } fun Context.toast(text: String, duration: Int = Toast.LENGTH_SHORT) = Toast.makeText(this, text, duration).show() <|start_filename|>app/src/main/java/com/egoriku/motionlayoutandroidacademy/activity/MainActivity.kt<|end_filename|> package com.egoriku.motionlayoutandroidacademy.activity import android.content.Intent import android.os.Bundle import android.os.Handler import androidx.annotation.LayoutRes import androidx.appcompat.app.AppCompatActivity import com.egoriku.motionlayoutandroidacademy.R import com.egoriku.motionlayoutandroidacademy.activity.todo.CoordinatorActivityTodo import com.egoriku.motionlayoutandroidacademy.activity.todo.MotionActivityTodo import com.egoriku.motionlayoutandroidacademy.common.LAYOUT_ID import com.google.android.material.appbar.AppBarLayout import com.pandulapeter.beagle.Beagle import kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity(R.layout.activity_main) { private var isAppBarExpanded = true override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) step_1.setOnClickListener { startMotionActivity(R.layout.step_1) } step_1_todo.setOnClickListener { startMotionActivity(R.layout.step_1_todo) } step_2.setOnClickListener { startMotionActivity(R.layout.step_2) } step_2_todo.setOnClickListener { startMotionActivity(R.layout.step_2_todo) } step_3.setOnClickListener { startMotionActivity(R.layout.step_3) } step_3_todo.setOnClickListener { startMotionActivity(R.layout.step_3_todo) } step_4.setOnClickListener { startMotionActivity(R.layout.step_4) } step_4_todo.setOnClickListener { startMotionActivity(R.layout.step_4_todo) } step_5.setOnClickListener { startMotionActivity(R.layout.step_5) } step_5_todo.setOnClickListener { startMotionActivity(R.layout.step_5_todo) } step_6.setOnClickListener { startMotionActivity(R.layout.step_6) } step_6_todo.setOnClickListener { startMotionActivity(R.layout.step_6_todo) } step_7.setOnClickListener { startMotionActivity(R.layout.step_7) } step_7_todo.setOnClickListener { startMotionActivity(R.layout.step_7_todo) } step_8.setOnClickListener { startMotionActivity(R.layout.step_8) } step_8_todo.setOnClickListener { startMotionActivity(R.layout.step_8_todo) } step_9.setOnClickListener { startMotionActivity(R.layout.step_9) } step_9_todo.setOnClickListener { startActivity(Intent(this, MotionActivityTodo::class.java)) } step_10_todo.setOnClickListener { startActivity(Intent(this, CoordinatorActivityTodo::class.java)) } initCoordinatorWithMotion() } private fun startMotionActivity(@LayoutRes layoutId: Int) = startActivity( Intent(this, MotionActivity::class.java).apply { putExtra(LAYOUT_ID, layoutId) } ) private fun initCoordinatorWithMotion() { val listener = AppBarLayout.OnOffsetChangedListener { _, verticalOffset -> val scrollPosition = -verticalOffset / appbarLayout.totalScrollRange.toFloat() isAppBarExpanded = verticalOffset == 0 motionLayout.progress = scrollPosition } appbarLayout.addOnOffsetChangedListener(listener) appLogo.setOnClickListener { appbarLayout.setExpanded(!isAppBarExpanded) } } } <|start_filename|>app/src/main/java/com/egoriku/motionlayoutandroidacademy/activity/MotionActivity.kt<|end_filename|> package com.egoriku.motionlayoutandroidacademy.activity import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import androidx.constraintlayout.motion.widget.MotionLayout import androidx.constraintlayout.motion.widget.TransitionAdapter import com.egoriku.motionlayoutandroidacademy.R import com.egoriku.motionlayoutandroidacademy.common.BundleDelegate import com.egoriku.motionlayoutandroidacademy.common.LAYOUT_ID import com.egoriku.motionlayoutandroidacademy.common.toast import kotlinx.android.synthetic.main.step_9.* class MotionActivity : AppCompatActivity() { private val Bundle.layoutId: Int by BundleDelegate.Int(LAYOUT_ID) private var completedId: Int = R.id.start override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val layoutId = intent.extras?.layoutId ?: throw Exception("Where is layout??") setContentView(layoutId) if (layoutId == R.layout.step_9) { login_text.setOnClickListener { when (completedId) { R.id.start -> toast("Perform Login") else -> motionLayout.transitionToStart() } } sign_up_text.setOnClickListener { when (completedId) { R.id.end -> toast("Perform Sign Up") else -> motionLayout.transitionToEnd() } } motionLayout.setTransitionListener(object : TransitionAdapter() { override fun onTransitionCompleted(motionLayout: MotionLayout?, currentId: Int) { completedId = currentId } }) } } } <|start_filename|>app/src/main/java/com/egoriku/motionlayoutandroidacademy/common/DisappearingImageView.kt<|end_filename|> package com.egoriku.motionlayoutandroidacademy.common import android.content.Context import android.util.AttributeSet import android.view.animation.ScaleAnimation import androidx.appcompat.widget.AppCompatImageView import androidx.interpolator.view.animation.FastOutLinearInInterpolator class DisappearingImageView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : AppCompatImageView(context, attrs, defStyleAttr) { fun hide() = animateView(isAppear = false) fun show() = animateView(isAppear = true) private fun animateView(isAppear: Boolean) { if (animation?.hasEnded() == false) { return } if (isAppear) { ScaleAnimation( 0.0f, 1.0f, 0.0f, 1.0f, ScaleAnimation.RELATIVE_TO_SELF, 0.5f, ScaleAnimation.RELATIVE_TO_SELF, 0.5f ) } else { ScaleAnimation( 1.0f, 0.0f, 1.0f, 0.0f, ScaleAnimation.RELATIVE_TO_SELF, 0.5f, ScaleAnimation.RELATIVE_TO_SELF, 0.5f ) }.run { fillAfter = true duration = 200 interpolator = FastOutLinearInInterpolator() startAnimation(this) } } }
webanimal/AndroidAcademyMinsk_motionLayWorkshop
<|start_filename|>main.go<|end_filename|> package main import ( "context" "encoding/json" "fmt" "github.com/bytelang/kplayer/types/config" errortypes "github.com/bytelang/kplayer/types/error" "github.com/go-playground/validator/v10" "io/ioutil" "os" "runtime" "github.com/bytelang/kplayer/app" "github.com/bytelang/kplayer/cmd" "github.com/bytelang/kplayer/module" "github.com/bytelang/kplayer/server" kptypes "github.com/bytelang/kplayer/types" log "github.com/sirupsen/logrus" "github.com/spf13/cobra" "github.com/spf13/viper" ) func init() { log.SetOutput(os.Stdout) log.SetReportCaller(true) log.SetLevel(log.TraceLevel) logFormat := &log.TextFormatter{ TimestampFormat: "2006-01-02 15:04:05", DisableColors: false, FullTimestamp: true, CallerPrettyfier: func(f *runtime.Frame) (function string, file string) { return "", fmt.Sprintf("%s:%d", f.File, f.Line) }, } log.SetFormatter(logFormat) } func main() { rootCmd := cmd.NewRootCmd() if err := Execute(rootCmd, app.DefaultConfigFilePath, app.DefaultConfigFileName); err != nil { switch e := err.(type) { case kptypes.ErrorCode: os.Exit(e.Code) default: os.Exit(1) } } } // Execute execute from flags and commands func Execute(rootCmd *cobra.Command, defaultHome string, defaultFile string) error { rootCmd.PersistentFlags().String(kptypes.FlagLogLevel, log.InfoLevel.String(), "The logging level (trace|debug|info|warn|error|fatal|panic)") rootCmd.PersistentFlags().String(kptypes.FlagLogFormat, "plain", "The logging format (json|plain)") rootCmd.PersistentFlags().StringP(kptypes.FlagHome, "", defaultHome, "directory for config and data") rootCmd.PersistentFlags().StringP(kptypes.FlagConfigFileName, "c", defaultFile, "config file name") rootCmd.PersistentPreRunE = func(cmd *cobra.Command, args []string) error { // set home path homePath, err := cmd.Flags().GetString(kptypes.FlagHome) if err != nil { return err } if homePath != "" { if err := os.Chdir(homePath); err != nil { log.WithField("error", err).Fatal("chdir failed") } } // init context InitGlobalContextConfig(cmd) return nil } ctx := context.Background() ctx = context.WithValue(ctx, kptypes.ClientContextKey, kptypes.DefaultClientContext()) ctx = context.WithValue(ctx, kptypes.ModuleManagerContextKey, app.ModuleManager) ctx = context.WithValue(ctx, kptypes.ServerCreatorContextKey, server.NewJsonRPCServer()) return kptypes.SetCommandContextAndExecute(rootCmd, ctx) } func InitGlobalContextConfig(cmd *cobra.Command) { mm := cmd.Context().Value(kptypes.ModuleManagerContextKey).(module.ModuleManager) clientCtx := cmd.Context().Value(kptypes.ClientContextKey).(*kptypes.ClientContext) configFileName, err := kptypes.GetConfigFileName(cmd) if err != nil { log.Fatal(err) } // set log level logLevel, err := kptypes.GetLogLevel(cmd) if err != nil { log.Fatal(err) } log.SetLevel(logLevel) if logLevel == log.InfoLevel { log.SetReportCaller(false) } // viper v := viper.New() v.AddConfigPath(".") v.SetConfigType("json") v.SetConfigName(configFileName) // skip on init stage if cmd.Parent().Use == "init" { return } // load config context in file if err := v.ReadInConfig(); err != nil { log.Fatal(err) } // set default value setDefaultConfig(v) clientCtx.Viper = v if err := v.Unmarshal(clientCtx.Config); err != nil { log.Fatal(err) } // validate global config if err := ValidateConfig(clientCtx.Config); err != nil { log.Fatal(err) } // init module for _, item := range mm.OrderInitConfig { m := mm.GetModule(item) // init config and set default value d, err := json.Marshal(v.AllSettings()[m.GetModuleName()]) if err != nil { log.Fatal(err) } modifyData, err := m.InitConfig(clientCtx, d) if err != nil { log.Fatal(err) } // validator validate := validator.New() if err := validate.Struct(modifyData); err != nil { log.Fatal(err) } // set modify data v.Set(m.GetModuleName(), modifyData) // validate config if err := m.ValidateConfig(); err != nil { log.Fatal(err) } } // set context before module modify if err := v.Unmarshal(clientCtx.Config); err != nil { log.Fatal(err) } } func ValidateConfig(config *config.KPConfig) error { if config.Version != app.ConfigVersion { return errortypes.VersionInvalidMainError } // load user token file if config.TokenPath != "" { if !kptypes.FileExists(config.TokenPath) { return errortypes.TokenFileNotFoundMainError } fileContent, err := ioutil.ReadFile(config.TokenPath) if err != nil { return err } if err := kptypes.LoadClientToken(string(fileContent)); err != nil { log.Fatal(err) } } return nil } func setDefaultConfig(v *viper.Viper) { v.SetDefault("play.start_point", 1) v.SetDefault("play.play_model", "list") v.SetDefault("play.encode_model", "rtmp") v.SetDefault("play.cache_on", false) v.SetDefault("play.cache_uncheck", false) v.SetDefault("play.skip_invalid_resource", false) v.SetDefault("play.delay_queue_size", 50) v.SetDefault("play.fill_strategy", "tile") v.SetDefault("play.rpc.on", true) v.SetDefault("play.rpc.port", kptypes.DefaultRPCPort) v.SetDefault("play.rpc.address", kptypes.DefaultRPCAddress) v.SetDefault("play.encode.video_width", 780) v.SetDefault("play.encode.video_height", 480) v.SetDefault("play.encode.video_fps", 30) v.SetDefault("play.encode.audio_channel_layout", 3) v.SetDefault("play.encode.audio_channels", 2) v.SetDefault("play.encode.audio_sample_rate", 48000) v.SetDefault("play.encode.bit_rate", 0) v.SetDefault("play.encode.avg_quality", 0) } <|start_filename|>module/play/provider/command.go<|end_filename|> package provider import ( "fmt" "github.com/bytelang/kplayer/types/client" "github.com/bytelang/kplayer/types/config" "io" "io/ioutil" "os" "path/filepath" "strconv" "strings" "syscall" "time" "github.com/bytelang/kplayer/module" kptypes "github.com/bytelang/kplayer/types" kpserver "github.com/bytelang/kplayer/types/server" "github.com/sevlyar/go-daemon" "github.com/bytelang/kplayer/core" log "github.com/sirupsen/logrus" "github.com/spf13/cobra" ) const ( pidFilePath = "log/kplayer.pid" logFilePath = "log/kplayer.log" ) func GetCommand() *cobra.Command { cmd := &cobra.Command{ Use: ModuleName, Short: "Play category", Long: `App management commands. control kplayer basic status`, } cmd.AddCommand(startCommand()) cmd.AddCommand(stopCommand()) cmd.AddCommand(statusCommand()) cmd.AddCommand(durationCommand()) cmd.AddCommand(pauseCommand()) cmd.AddCommand(continueCommand()) cmd.AddCommand(skipCommand()) cmd.AddCommand(versionCommand()) return cmd } func statusCommand() *cobra.Command { cmd := &cobra.Command{ Use: "status", Short: "Print kplayer status", Long: "Get the kplayer application running status", RunE: func(cmd *cobra.Command, args []string) error { pid, err := getPID() if err != nil { log.WithField("status", "off").Info("kplayer not running on daemon mode") return nil } log.WithFields(log.Fields{"status": "on", "pid": pid}).Info("kplayer active running on daemon mode") return nil }, } return cmd } func durationCommand() *cobra.Command { cmd := &cobra.Command{ Use: "duration", Short: "get player duration status", RunE: func(cmd *cobra.Command, args []string) error { // get client ctx clientCtx := kptypes.GetClientContextFromCommand(cmd) reply := &kpserver.PlayDurationReply{} if err := client.ClientRequest(clientCtx.Config.Play.Rpc, "Play.Duration", &kpserver.PlayDurationArgs{}, reply); err != nil { log.Error(err) return nil } yaml, err := kptypes.FormatYamlProtoMessage(reply) if err != nil { return err } fmt.Print(yaml) return nil }, } return cmd } func pauseCommand() *cobra.Command { cmd := &cobra.Command{ Use: "pause", Short: "pause player", RunE: func(cmd *cobra.Command, args []string) error { // get client ctx clientCtx := kptypes.GetClientContextFromCommand(cmd) reply := &kpserver.PlayPauseReply{} if err := client.ClientRequest(clientCtx.Config.Play.Rpc, "Play.Pause", &kpserver.PlayPauseArgs{}, reply); err != nil { log.Error(err) return nil } yaml, err := kptypes.FormatYamlProtoMessage(reply) if err != nil { return err } fmt.Print(yaml) return nil }, } return cmd } func continueCommand() *cobra.Command { cmd := &cobra.Command{ Use: "continue", Short: "continue player", RunE: func(cmd *cobra.Command, args []string) error { // get client ctx clientCtx := kptypes.GetClientContextFromCommand(cmd) reply := &kpserver.PlayPauseReply{} if err := client.ClientRequest(clientCtx.Config.Play.Rpc, "Play.Pause", &kpserver.PlayPauseArgs{}, reply); err != nil { log.Error(err) return nil } yaml, err := kptypes.FormatYamlProtoMessage(reply) if err != nil { return err } fmt.Print(yaml) return nil }, } return cmd } func skipCommand() *cobra.Command { cmd := &cobra.Command{ Use: "skip", Short: "skip play current resource", RunE: func(cmd *cobra.Command, args []string) error { // get client ctx clientCtx := kptypes.GetClientContextFromCommand(cmd) reply := &kpserver.PlaySkipReply{} if err := client.ClientRequest(clientCtx.Config.Play.Rpc, "Play.Skip", &kpserver.PlaySkipArgs{}, reply); err != nil { log.Error(err) return nil } yaml, err := kptypes.FormatYamlProtoMessage(reply) if err != nil { return err } fmt.Print(yaml) return nil }, } return cmd } func versionCommand() *cobra.Command { cmd := &cobra.Command{ Use: "info", Short: "get Information play", RunE: func(cmd *cobra.Command, args []string) error { // get client ctx clientCtx := kptypes.GetClientContextFromCommand(cmd) reply := &kpserver.PlayInformationReply{} if err := client.ClientRequest(clientCtx.Config.Play.Rpc, "Play.Information", &kpserver.PlayInformationArgs{}, reply); err != nil { log.Error(err) return nil } yaml, err := kptypes.FormatYamlProtoMessage(reply) if err != nil { return err } fmt.Print(yaml) return nil }, } return cmd } func stopCommand() *cobra.Command { cmd := &cobra.Command{ Use: "stop", Short: "Start kplayer", Long: "Stop the kplayer application. only effective in daemon mode", RunE: func(cmd *cobra.Command, args []string) error { pid, err := getPID() if err != nil { log.WithField("error", err).Error("stop failed") return nil } // kill process if err := syscall.Kill(pid, syscall.SIGKILL); err != nil { log.WithField("error", err).Error("kill process failed") return err } log.Info("kplayer stop success") return nil }, } return cmd } func startCommand() *cobra.Command { cmd := &cobra.Command{ Use: "start", Short: "Start kplayer", Long: "Start the kplayer application, use '-g' support the daemon mode. on daemon mode, kplayer with creating PID file and same directory only run once.", PreRunE: func(cmd *cobra.Command, args []string) error { return kptypes.MkDir("log") }, RunE: func(cmd *cobra.Command, args []string) error { // daemon mode var daemonProc *os.Process if cmd.Flag(FlagDaemonMode).Value.String() == FlagYesValue { var err error if pid, err := getPID(); err == nil { log.WithField("pid", pid).Error("kplayer start failed. kplayer is running") return nil } cntxt := &daemon.Context{ PidFileName: pidFilePath, PidFilePerm: 0644, LogFileName: logFilePath, LogFilePerm: 0644, WorkDir: "./", Env: os.Environ(), Args: cmd.Flags().Args(), Umask: 027, } daemonProc, err = cntxt.Reborn() if err != nil { log.WithField("error", err).Fatal("execute daemon mode failed") } if daemonProc != nil { log.Info("kplayer start success on daemon mode") return nil } } else { // not daemon mode // write pid to file _ = os.Mkdir(filepath.Dir(pidFilePath), os.ModePerm) f, err := os.OpenFile(pidFilePath, os.O_CREATE|os.O_RDWR, 0666) if err != nil { log.WithField("error", err).Fatal("open pid file failed") return nil } if _, err := io.WriteString(f, strconv.Itoa(os.Getpid())); err != nil { log.WithField("error", err).Fatal("write pid file failed") } } defer func() { if daemonProc != nil { _ = daemonProc.Release() } }() // get module manager var mm module.ModuleManager if ptr, err := kptypes.GetCommandContext(cmd, kptypes.ModuleManagerContextKey); err != nil { log.Fatal(err) } else { mm = ptr.(module.ModuleManager) } // get client ctx var clientCtx *kptypes.ClientContext if ptr, err := kptypes.GetCommandContext(cmd, kptypes.ClientContextKey); err != nil { log.Fatal(err) } else { clientCtx = ptr.(*kptypes.ClientContext) } // get server creator svrCreator, err := kptypes.GetCommandContext(cmd, kptypes.ServerCreatorContextKey) if err != nil { log.Fatal(err) } cfg := clientCtx.Config // override only generate cache config if cmd.Flag(FlagGenerateCache).Value.String() == FlagYesValue { cfg.Play.PlayModel = config.PLAY_FILL_STRATEGY_name[int32(config.PLAY_MODEL_LIST)] cfg.Play.EncodeModel = config.ENCODE_MODEL_name[int32(config.ENCODE_MODEL_FILE)] cfg.Play.CacheOn = true cfg.Play.DelayQueueSize = 500 cfg.Play.SkipInvalidResource = false log.Info("running on generate cache model") } coreKplayer := core.GetLibKplayerInstance() if err := coreKplayer.SetOptions(cfg.Play.EncodeModel, cfg.Play.Encode.VideoWidth, cfg.Play.Encode.VideoHeight, cfg.Play.Encode.BitRate, cfg.Play.Encode.AvgQuality, cfg.Play.Encode.VideoFps, cfg.Play.Encode.AudioSampleRate, cfg.Play.Encode.AudioChannelLayout, cfg.Play.Encode.AudioChannels, cfg.Play.DelayQueueSize, config.PLAY_FILL_STRATEGY_value[strings.ToUpper(cfg.Play.FillStrategy)]); err != nil { log.Fatal(err) } coreKplayer.SetCacheOn(cfg.Play.CacheOn) coreKplayer.SetSkipInvalidResource(cfg.Play.SkipInvalidResource) serverStopChan := make(chan bool) var coreLogLevel int = 0 level, err := cmd.Flags().GetString(kptypes.FlagLogLevel) if err != nil { log.Fatal(err) } logLevel, err := log.ParseLevel(level) switch logLevel { case log.TraceLevel: coreLogLevel = 2 case log.DebugLevel: coreLogLevel = 1 default: coreLogLevel = 0 } // module option moduleOptions := []module.ModuleOption{} if cmd.Flag(FlagGenerateCache).Value.String() == FlagYesValue { moduleOptions = append(moduleOptions, module.ModuleOptionGenerateCache) } // knock api timeTicker := time.NewTicker(time.Second * (KnockIntervalMinutes * 60)) defer timeTicker.Stop() go func() { maxRetriesCount := KnockMaxRetries currentRetriesCount := 0 for { if currentRetriesCount > maxRetriesCount { log.Fatal("knock failed. cannot connection api server on max retries") } <-timeTicker.C if err := kptypes.Knock(); err != nil { currentRetriesCount = currentRetriesCount + 1 continue } log.Debug("knock success") currentRetriesCount = 0 } }() go func() { (svrCreator).(kpserver.ServerCreator).StartServer(serverStopChan, mm) }() // start core { coreKplayer.SetLogLevel("log/core.log", coreLogLevel) // initialize coreKplayer.Initialization() // begin running for _, m := range mm.Modules { m.BeginRunning(moduleOptions...) } defer func() { for _, m := range mm.Modules { m.EndRunning() } }() // start core coreKplayer.Run() serverStopChan <- true } return nil }, } cmd.PersistentFlags().BoolP(FlagDaemonMode, "d", false, "use daemon mode run kplayer") cmd.PersistentFlags().BoolP(FlagGenerateCache, "g", false, "only generate file cache. not push to output") return cmd } func getPID() (int, error) { pidFile, err := os.Open(pidFilePath) if err != nil { return 0, fmt.Errorf("can not found pid file. error: %s", err) } defer pidFile.Close() data, err := ioutil.ReadAll(pidFile) if err != nil { return 0, fmt.Errorf("read pid file failed. error: %s", err) } pid, err := strconv.Atoi(string(data)) if err != nil { return 0, fmt.Errorf("pid invalid. error: %s", err) } process, err := os.FindProcess(pid) if err != nil { return 0, fmt.Errorf("kplayer not running on daemon mode") } if err := process.Signal(syscall.Signal(0)); err != nil { return 0, fmt.Errorf("kplayer not running on daemon mode") } return pid, nil } <|start_filename|>core/kplayer.go<|end_filename|> package core // #cgo LDFLAGS: -lkplayer -lkpcodec -lkputil -lkpadapter -lkpplugin // #include "extra.h" // void goCallBackMessage(int, char*); import "C" import ( "bytes" "fmt" kpprompt "github.com/bytelang/kplayer/types/core/proto/prompt" "github.com/golang/protobuf/jsonpb" "strings" "unsafe" kpproto "github.com/bytelang/kplayer/types/core/proto" "github.com/golang/protobuf/proto" log "github.com/sirupsen/logrus" ) //export goCallBackMessage // goCallBackMessage define libkplayer callback function func goCallBackMessage(action C.int, msgRaw *C.char) { msg := C.GoString(msgRaw) ac := int(action) libKplayerInstance.callbackFn(ac, msg) } var libKplayerInstance *libKplayer = &libKplayer{ callbackFn: func(action int, message string) {}, } // libKplayer type libKplayer struct { // basic params protocol string video_width uint32 video_height uint32 video_bitrate uint32 video_qulity uint32 video_fps uint32 audio_sample_rate uint32 audio_channel_layout uint32 audio_channels uint32 // options cache_on bool skip_invalid_resource bool // event message receiver callbackFn func(action int, message string) // delay queue size delay_queue_size uint16 // fill strategy fill_strategy int32 } // GetLibKplayer return singleton LibKplayer instance func GetLibKplayerInstance() *libKplayer { return libKplayerInstance } // SetOptions set basic options func (lb *libKplayer) SetOptions(protocol string, video_width uint32, video_height uint32, video_bitrate uint32, video_qulity uint32, video_fps uint32, audio_sample_rate uint32, audio_channel_layout uint32, audio_channels uint32, delay_queue_size uint32, fill_strategy int32) error { libKplayerInstance.protocol = strings.ToLower(protocol) libKplayerInstance.video_width = video_width libKplayerInstance.video_height = video_height libKplayerInstance.video_bitrate = video_bitrate libKplayerInstance.video_qulity = video_qulity libKplayerInstance.video_fps = video_fps libKplayerInstance.audio_sample_rate = audio_sample_rate libKplayerInstance.audio_channel_layout = audio_channel_layout libKplayerInstance.audio_channels = audio_channels // other params libKplayerInstance.delay_queue_size = uint16(delay_queue_size) libKplayerInstance.fill_strategy = fill_strategy return nil } func (lb *libKplayer) SetCallBackMessage(fn func(action int, message string)) { lb.callbackFn = fn } func (lb *libKplayer) GetInformation() *kpproto.Information { infoMemorySize := 2000 str := make([]byte, infoMemorySize) cs := (*C.char)(unsafe.Pointer(&str[0])) C.GetInformation(cs, C.int(infoMemorySize)) str = bytes.Trim(str, "\x00") info := &kpproto.Information{} if err := jsonpb.UnmarshalString(string(str), info); err != nil { log.Fatalf("error: %s", err) } return info } func (lb *libKplayer) SendPrompt(action kpproto.EventPromptAction, body proto.Message) error { m := jsonpb.Marshaler{} str, err := m.MarshalToString(body) if err != nil { return err } cs := C.CString(str) defer C.free(unsafe.Pointer(cs)) C.PromptMessage(C.int(action), cs) log.WithFields(log.Fields{"action": kpproto.EventPromptAction_name[int32(action)]}).Debug("send prompt message") return nil } func (lb *libKplayer) Run() { // start stopChan := make(chan bool) go func() { defer func() { stopChan <- true }() log.Info("core start up success") result := C.Run() if int(result) < 0 { log.WithFields(log.Fields{"code": int(result), "error": C.GoString(C.GetError())}).Error("core return error") } }() <-stopChan log.Info("core shut down success") } func (lb *libKplayer) SetCacheOn(c bool) { lb.cache_on = c } func (lb *libKplayer) SetSkipInvalidResource(s bool) { lb.skip_invalid_resource = s } func (lb *libKplayer) SetLogLevel(path string, level int) { logPath := C.CString(path) C.SetLogLevel(logPath, C.int(level)) defer C.free(unsafe.Pointer(logPath)) } func (lb *libKplayer) Initialization() { if lb.cache_on { C.SetCacheOn(C.int(1)) } if lb.skip_invalid_resource { C.SetSkipInvalidResource(C.int(1)) } C.ReceiveMessage(C.MessageCallBack(C.goCallBackMessage)) C.Initialization(C.CString(lb.protocol), C.int(lb.video_width), C.int(lb.video_height), C.int(lb.video_bitrate), C.int(lb.video_qulity), C.int(lb.video_fps), C.int(lb.audio_sample_rate), C.int(lb.audio_channel_layout), C.int(lb.audio_channels), C.short(lb.delay_queue_size), C.int(lb.fill_strategy)) } func (lb *libKplayer) AddOutput(body *kpprompt.EventPromptOutputAdd) error { m := jsonpb.Marshaler{} str, err := m.MarshalToString(body) if err != nil { return err } cs := C.CString(str) defer C.free(unsafe.Pointer(cs)) resultCode := C.AddOutput(cs) if resultCode != 0 { return fmt.Errorf("add output failed. result code: %d", resultCode) } return nil } func (lb *libKplayer) AddPlugin(body *kpprompt.EventPromptPluginAdd) error { m := jsonpb.Marshaler{} str, err := m.MarshalToString(body) if err != nil { return err } cs := C.CString(str) defer C.free(unsafe.Pointer(cs)) resultCode := C.AddPlugin(cs) if resultCode != 0 { return fmt.Errorf("add plugin failed. result code: %d", resultCode) } return nil } <|start_filename|>types/core.go<|end_filename|> package types import ( "github.com/bytelang/kplayer/core" "strings" ) // GetCorePluginVersion func GetCorePluginVersion() string { coreKplayer := core.GetLibKplayerInstance() version := coreKplayer.GetInformation().PluginVersion versionArr := strings.Split(version, ".") for key, item := range versionArr { if len(item) == 1 && key != 0 { versionArr[key] = "0" + item } } return strings.Join(versionArr, "") } <|start_filename|>types/api.go<|end_filename|> package types import ( "encoding/json" "fmt" "github.com/bytelang/kplayer/types/api" "github.com/golang/protobuf/proto" "io/ioutil" "net/http" "net/url" "time" ) var ( ApiScheme string = "https" ApiHost string = "" ApiPort string = "" ApiVersion string = "" ) type ApiError string func (ae ApiError) Error() string { return string(ae) } func GetTlsHttpClient() *http.Client { config, err := GetTlsClientConfig() if err != nil { panic(err) } transPort := &http.Transport{ TLSClientConfig: config, } return &http.Client{Transport: transPort, Timeout: time.Second * 10} } func GetApiRequestUrl(path string) string { return fmt.Sprintf("%s://%s:%s/%s%s", ApiScheme, ApiHost, ApiPort, ApiVersion, path) } func RequestHttpGet(host string, params proto.Message, message proto.Message) error { d, err := json.Marshal(params) if err != nil { return err } mapping := make(map[string]string) if err := json.Unmarshal(d, &mapping); err != nil { return err } var query string for key, item := range mapping { query = query + fmt.Sprintf("%s=%s&", url.QueryEscape(key), url.QueryEscape(item)) } // request resp, err := GetTlsHttpClient().Get(fmt.Sprintf("%s?%s", host, query)) if err != nil { return err } defer resp.Body.Close() respBody, err := ioutil.ReadAll(resp.Body) if err != nil { return err } if resp.StatusCode != http.StatusOK { if resp.StatusCode == http.StatusNotFound { return fmt.Errorf("response status code: %d. message: %s", resp.StatusCode, TrimCRLF(string(respBody))) } return ApiError(fmt.Sprintf("response status code: %d. message: %s", resp.StatusCode, TrimCRLF(string(respBody)))) } // unmarshal if err := json.Unmarshal(respBody, message); err != nil { return err } return nil } // plugin func GetPlugin(request *api.PluginInformationRequest) (*api.PluginInformationResponse, error) { resp := &api.PluginInformationResponse{} if err := RequestHttpGet(GetApiRequestUrl("/plugin/info"), request, resp); err != nil { return nil, err } return resp, nil } // resource func GetResource(request *api.ResourceInformationRequest) (*api.ResourceInformationResponse, error) { resp := &api.ResourceInformationResponse{} if err := RequestHttpGet(GetApiRequestUrl("/resource/info"), request, resp); err != nil { return nil, err } return resp, nil } // knock func Knock() error { return RequestHttpGet(GetApiRequestUrl("/status/knock"), &api.StatusKnockRequest{}, &api.StatusKnockResponse{}) } <|start_filename|>module/play/provider/provider.go<|end_filename|> package provider import ( "github.com/bytelang/kplayer/module" kptypes "github.com/bytelang/kplayer/types" "github.com/bytelang/kplayer/types/config" kpproto "github.com/bytelang/kplayer/types/core/proto" svrproto "github.com/bytelang/kplayer/types/server" log "github.com/sirupsen/logrus" "strings" "time" ) type ProviderI interface { GetStartPoint() uint32 GetPlayModel() config.PLAY_MODEL GetRPCParams() config.Rpc PlayStop(args *svrproto.PlayStopArgs) (*svrproto.PlayStopReply, error) PlayPause(args *svrproto.PlayPauseArgs) (*svrproto.PlayPauseReply, error) PlaySkip(args *svrproto.PlaySkipArgs) (*svrproto.PlaySkipReply, error) PlayContinue(args *svrproto.PlayContinueArgs) (*svrproto.PlayContinueReply, error) PlayDuration(args *svrproto.PlayDurationArgs) (*svrproto.PlayDurationReply, error) PlayInformation(args *svrproto.PlayInformationArgs) (*svrproto.PlayInformationReply, error) } var _ ProviderI = &Provider{} // Provider play module provider type Provider struct { module.ModuleKeeper // config startPoint uint32 playMode config.PLAY_MODEL rpc config.Rpc // module member startTime time.Time // empty resource list for generate cache only GenerateCacheFlag bool } // NewProvider return provider func NewProvider() *Provider { return &Provider{} } // InitConfig set module config on kplayer started func (p *Provider) InitModule(ctx *kptypes.ClientContext, cfg *config.Play) { // set provider attribute p.startPoint = cfg.StartPoint playModel, ok := config.PLAY_MODEL_value[strings.ToUpper(cfg.PlayModel)] if !ok { log.Fatal("play model invalid") } p.playMode = config.PLAY_MODEL(playModel) p.rpc = *cfg.Rpc } func (p *Provider) ParseMessage(message *kpproto.KPMessage) { switch message.Action { case kpproto.EVENT_MESSAGE_ACTION_PLAYER_STARTED: log.Info("kplayer start success") p.startTime = time.Now() } } func (p *Provider) ValidateConfig() error { return nil } func (p *Provider) GetStartPoint() uint32 { return p.startPoint } func (p *Provider) GetPlayModel() config.PLAY_MODEL { if p.GenerateCacheFlag { return config.PLAY_MODEL_LIST } return p.playMode }
bytelang/kplayer-go
<|start_filename|>lib/upcoming_screen/upcoming_screen_presenter.dart<|end_filename|> import 'package:fluvies/base/screen_presenter.dart'; import 'package:fluvies/base/screen_view.dart'; abstract class UpcomingScreenView extends ScreenView { } class UpcomingScreenPresenter extends ScreenPresenter<UpcomingScreenView> { UpcomingScreenPresenter(ScreenView view, String tag) : super(view, tag); @override void loadMovies() { super.loadMovies(); networkData.fetchUpcomingMovies().then((list) { view.onMoviesLoaded(list); dbHelper.insertMovies(list, tag).then((dynamic) { print("Db updated with new $tag movies"); }); }); } } <|start_filename|>lib/popular_screen/popular_screen_presenter.dart<|end_filename|> import 'package:fluvies/base/screen_presenter.dart'; import 'package:fluvies/base/screen_view.dart'; abstract class PopularScreenView extends ScreenView { } class PopularScreenPresenter extends ScreenPresenter<PopularScreenView> { PopularScreenPresenter(ScreenView view, String tag) : super(view, tag); @override void loadMovies() { super.loadMovies(); networkData.fetchPopularMovies().then((list) { view.onMoviesLoaded(list); dbHelper.insertMovies(list, tag).then((dynamic) { print("Db updated with new $tag movies"); }); }); } } <|start_filename|>lib/data/models/Movie.dart<|end_filename|> class Movie { final int id; final String name; final String poster; final String backdrop; final String desc; Movie({this.id, this.name, this.poster, this.backdrop, this.desc}); Movie.map(Map<String, dynamic> map) : id = map['id'], name = map['original_title'], poster = "http://image.tmdb.org/t/p/w342" + map['poster_path'], backdrop = "http://image.tmdb.org/t/p/w500" + map['backdrop_path'], desc = map['overview']; Movie.fromDb(Map<String, dynamic> map) : id = map['id'], name = map['name'], poster = map['poster'], backdrop = map['backdrop'], desc = map['desc']; } <|start_filename|>lib/base/screen_presenter.dart<|end_filename|> import 'package:fluvies/base/screen_view.dart'; import 'package:fluvies/data/db_helper.dart'; import 'package:fluvies/Injector.dart'; import 'package:fluvies/data/network/network_data.dart'; abstract class ScreenPresenter<T extends ScreenView> { T _view; Injector _injector; DbHelper _dbHelper; NetworkData _networkData; String _tag; ScreenPresenter(this._view, this._tag) { _injector = new Injector(); _dbHelper = _injector.dbHelper; _networkData = _injector.networkData; } void loadMovies() { _dbHelper.getMovies(_tag).then((list){ if (list.length > 0 && list != null) { _view.onMoviesLoaded(list); } }); } String get tag => _tag; NetworkData get networkData => _networkData; DbHelper get dbHelper => _dbHelper; T get view => _view; } <|start_filename|>lib/movie_details_screen.dart<|end_filename|> import 'dart:async'; import 'dart:io'; import 'package:flutter/material.dart'; import 'package:fluvies/Injector.dart'; import 'package:fluvies/custom_widgets/photo_hero.dart'; import 'package:fluvies/data/db_helper.dart'; import 'package:fluvies/data/models/Movie.dart'; class MovieDetails extends StatefulWidget { Movie _movie; MovieDetails(Movie movie) { this._movie = movie; } @override State<StatefulWidget> createState() => new MovieDetailsState(_movie); } class MovieDetailsState extends State<MovieDetails> { Movie _movie; final double _appBarHeight = 256.0; MovieDetailsState(this._movie); bool isMovieSaved = true; DbHelper _dbHelper; final String _tag = "liked"; Future searchMovie() async { isMovieSaved = await _dbHelper.checkMovie(_movie.id, _tag); setState((){ // refresh ui }); } @override void initState() { super.initState(); _dbHelper = new Injector().dbHelper; } @override Widget build(BuildContext context) { final TextTheme textTheme = Theme.of(context).textTheme; searchMovie(); return new Scaffold( body: new Column( children: <Widget>[ new PhotoHero( photo: _movie.backdrop, onTap: () { Navigator.of(context).pop(); }, ), new Container( padding: const EdgeInsets.all(16.0), child: new Row( children: <Widget>[ new Flexible( child: new Text(_movie.name, style: textTheme.headline), ), new IconButton( icon: new Icon(Icons.favorite), onPressed: () async { if (isMovieSaved) { await _dbHelper.delete(_movie.id, _tag); } else { await _dbHelper.insert(_movie, _tag); } searchMovie(); }, color: isMovieSaved ? Colors.red : null, ), ] ), ), new Container( padding: const EdgeInsets.fromLTRB(16.0, 0.0, 16.0, 16.0), child: new Text(_movie.desc, style: textTheme.subhead) ), ], ) ); } } <|start_filename|>lib/data/db_helper.dart<|end_filename|> import 'dart:async'; import 'dart:io'; import 'package:fluvies/data/db_path.dart'; import 'package:fluvies/data/models/Movie.dart'; import 'package:sqflite/sqflite.dart'; class DbHelper { Database _db; final String tbName = "movies"; final String autoIncrementId = "autoIncrementId"; final String id = "id"; final String name = "name"; final String poster = "poster"; final String backdrop = "backdrop"; final String desc = "desc"; final String tag = "tag"; static final DbHelper dbHelper = new DbHelper._helper(); factory DbHelper() { return dbHelper; } DbHelper._helper() { print("opening"); _open(new DbPath().path); } Future _open(String path) async { _db = await openDatabase(path, version: 1, onCreate: (Database db, int ver) async { await db.execute('''create table $tbName ( $autoIncrementId integer primary key autoincrement, $id integer , $name text not null, $poster text not null, $backdrop text not null, $desc text not null, $tag text not null)'''); }); } Map toMap(Movie movie, String movieTag) { Map map = {id : movie.id, name : movie.name, poster: movie.poster, backdrop : movie.backdrop, desc : movie.desc, tag : movieTag}; return map; } Future insert(Movie movie, String movieTag) async { await _db.insert(tbName, toMap(movie, movieTag)); } Future insertMovies(List<Movie> movies, String movieTag) async { await _db.delete(tbName, where: "$tag = ?", whereArgs: [movieTag]); Batch batch = _db.batch(); for (Movie movie in movies) { batch.insert(tbName, toMap(movie, movieTag)); } await batch.commit(); } Future<List<Movie>> getAllMovies() async { List<Map> movies = await _db.query(tbName , orderBy: "$autoIncrementId"); return movies.map((mapped) => new Movie.fromDb(mapped)).toList(); } Future<List<Movie>> getMovies(String movieTag) async { List<Map> movies = await _db.query(tbName, where: "$tag = ?", whereArgs: [movieTag], orderBy: "$autoIncrementId"); return movies.map((mapped) => new Movie.fromDb(mapped)).toList(); } Future<bool> checkMovie(int movieId, String movieTag) async { List<Map> movies = await _db.query(tbName, where: "$tag = ? and $id = ?", whereArgs: [movieTag, movieId]); return movies.isNotEmpty; } Future<int> delete(int movieId, String movieTag) async { return await _db.delete(tbName, where: "$tag = ? and $id = ?", whereArgs: [movieTag, movieId]); } } <|start_filename|>lib/liked_screen/liked_screen_presenter.dart<|end_filename|> import 'package:fluvies/base/screen_presenter.dart'; import 'package:fluvies/base/screen_view.dart'; abstract class LikedScreenView extends ScreenView { } class LikedScreenPresenter extends ScreenPresenter<LikedScreenView> { LikedScreenPresenter(ScreenView view, String tag) : super(view, tag); @override void loadMovies() { super.loadMovies(); //nothing to fetch } } <|start_filename|>lib/main.dart<|end_filename|> import 'dart:async'; import 'dart:io'; import 'package:flutter/material.dart'; import 'package:fluvies/Injector.dart'; import 'package:fluvies/data/db_path.dart'; import 'package:fluvies/data/models/Movie.dart'; import 'package:fluvies/liked_screen/liked_screen.dart'; import 'package:fluvies/popular_screen/popular_screen.dart'; import 'package:fluvies/upcoming_screen/upcoming_screen.dart'; import 'package:path/path.dart'; import 'package:path_provider/path_provider.dart'; void main() => runApp( new MaterialApp( title: "Fluvies", theme: new ThemeData( primarySwatch: Colors.teal, accentColor: Colors.tealAccent, backgroundColor: Colors.grey[100] ), home: new HomePage(), ) ); class HomePage extends StatefulWidget { @override State<StatefulWidget> createState() => new HomeStatePage(); } class HomeStatePage extends State<HomePage> { int _page = 0; Future<Directory> _documentsDirectory; void _getDocumentDirectory() { setState(() { _documentsDirectory = getApplicationDocumentsDirectory(); }); } void _onBottomBarTapped(int indexClicked) { setState((){ _page = indexClicked; }); } Widget _loadPage(BuildContext context, AsyncSnapshot<Directory> snapshot) { Widget widget = new Container(width: 0.0, height: 0.0); if (snapshot.connectionState == ConnectionState.done && !snapshot.hasError) { switch (_page) { case 0: widget = new PopularScreen(); break; case 1: widget = new UpcomingScreen(); break; case 2: widget = new LikedScreen(); break; } } return widget; } @override Widget build(BuildContext context) { _getDocumentDirectory(); return new Scaffold( appBar: new AppBar( title: new Text("Fluvies"), elevation: 2.0, ), body: new FutureBuilder( builder: _loadPage, future: _documentsDirectory.then((directory) async { String path = join(directory.path, "movies.db"); if (!await new Directory(dirname(path)).exists()) { try { await new Directory(dirname(path)).create(recursive: true); } catch (e) { print(e); } } new DbPath().path = path; }), ), bottomNavigationBar: new BottomNavigationBar( currentIndex: _page, onTap: _onBottomBarTapped, type: BottomNavigationBarType.fixed, items: [ new BottomNavigationBarItem( icon: new Icon(Icons.new_releases), title: new Text("Popular"), ), new BottomNavigationBarItem( icon: new Icon(Icons.update), title: new Text("Upcoming") ), new BottomNavigationBarItem( icon: new Icon(Icons.favorite), title: new Text("Liked") ), ] ), ); } } <|start_filename|>lib/custom_widgets/movies_grid.dart<|end_filename|> import 'package:flutter/material.dart'; import 'package:fluvies/custom_widgets/photo_hero.dart'; import 'package:fluvies/data/models/Movie.dart'; import 'package:fluvies/movie_details_screen.dart'; import 'package:meta/meta.dart'; import 'package:fluvies/Injector.dart'; Widget getMoviesGrid({@required List<Movie> movies, @required BuildContext context, @required int crossAxisCount, Axis scroll = Axis.vertical }) { if (movies.length == 0) { return new Container( child: new Center( child: new Text("No Movies found") ), ); } return new GridView.count( crossAxisCount: crossAxisCount, scrollDirection: scroll, mainAxisSpacing: 2.0, crossAxisSpacing: 2.0, padding: const EdgeInsets.all(4.0), children: movies.map((movie) => new Card( child: new GridTile( child: new PhotoHero( photo: movie.backdrop, onTap: () { Navigator.push(context, new MaterialPageRoute(builder: (context) { return new MovieDetails(movie); })); }, ), footer: new GridTileBar( backgroundColor: Colors.black45, title: new FittedBox( fit: BoxFit.scaleDown, alignment: Alignment.centerLeft, child: new Text(movie.name), ) ) ), )). toList()); } <|start_filename|>lib/Injector.dart<|end_filename|> import 'dart:async'; import 'package:fluvies/data/db_helper.dart'; import 'package:fluvies/data/models/Movie.dart'; import 'package:fluvies/data/network/network_data.dart'; class Injector { static final Injector injector = new Injector._injector(); NetworkData _networkData; DbHelper _dbHelper; Injector._injector(){ _networkData = new NetworkData(); _dbHelper = new DbHelper(); } factory Injector() { return injector; } NetworkData get networkData => _networkData; DbHelper get dbHelper => _dbHelper; } <|start_filename|>lib/base/screen_view.dart<|end_filename|> import 'package:fluvies/data/models/Movie.dart'; abstract class ScreenView { void onMoviesLoaded(List<Movie> movies); void onError(String msg); } <|start_filename|>lib/data/db_path.dart<|end_filename|> import 'package:fluvies/Injector.dart'; class DbPath { static final DbPath dbPath = new DbPath._init(); String _path; DbPath._init(); factory DbPath() { return dbPath; } String get path => _path; set path(String value) { _path = value; new Injector(); } } <|start_filename|>lib/popular_screen/popular_screen.dart<|end_filename|> import 'dart:async'; import 'dart:io'; import 'package:flutter/material.dart'; import 'package:fluvies/data/models/Movie.dart'; import 'package:fluvies/custom_widgets/movies_grid.dart'; import 'package:fluvies/popular_screen/popular_screen_presenter.dart'; class PopularScreen extends StatefulWidget { @override State createState() => new PopularScreenState(); } class PopularScreenState extends State<PopularScreen> implements PopularScreenView { bool _isLoading = true; List<Movie> movies; PopularScreenPresenter _presenter; @override void initState() { super.initState(); movies = new List(); _presenter = new PopularScreenPresenter(this, "popular"); _presenter.loadMovies(); } @override void onError(String msg) { print(msg); } @override void onMoviesLoaded(List<Movie> list) { setState((){ _isLoading = false; movies = list; }); } @override Widget build(BuildContext context) { Widget widget; if (_isLoading) { widget = new Center( child: new CircularProgressIndicator() ); } else { return getMoviesGrid(movies: movies, context: context, crossAxisCount: 2); } return widget; } } <|start_filename|>lib/data/network/network_data.dart<|end_filename|> import 'package:fluvies/data/network/network_util.dart'; import 'dart:async'; import 'package:fluvies/data/models/Movie.dart'; class NetworkData { NetworkUtil _networkUtil; final String apiKey = "PLACE_YOUR_API_KEY_HERE"; NetworkData() { _networkUtil = new NetworkUtil(); } Future<List<Movie>> fetchPopularMovies() => _networkUtil.request("https://api.themoviedb.org/3/movie/popular?" "api_key=$apiKey&language=en-US&page=1") .then((dynamic res) { List data = res['results']; return data.map((obj) => new Movie.map(obj)).toList(); }); Future<List<Movie>> fetchUpcomingMovies() => _networkUtil.request("https://api.themoviedb.org/3/movie/upcoming?" "api_key=$apiKey&language=en-US&page=1") .then((dynamic res) { List data = res['results']; List<Movie> movies = data.map((obj) { try { return new Movie.map(obj); } catch (ex) { return null; } }).toList(); movies.removeWhere((movie) => movie == null); return movies; }); }
dilpreet96/Fluvies
<|start_filename|>src/main/java/me/dinowernli/grpc/prometheus/GrpcMethod.java<|end_filename|> // Copyright 2016 <NAME>. All Rights Reserved. See LICENSE for licensing terms. package me.dinowernli.grpc.prometheus; import io.grpc.MethodDescriptor; import io.grpc.MethodDescriptor.MethodType; /** Knows how to extract information about a single grpc method. */ class GrpcMethod { private final String serviceName; private final String methodName; private final MethodType type; static GrpcMethod of(MethodDescriptor<?, ?> method) { String serviceName = MethodDescriptor.extractFullServiceName(method.getFullMethodName()); // Full method names are of the form: "full.serviceName/MethodName". We extract the last part. String methodName = method.getFullMethodName().substring(serviceName.length() + 1); return new GrpcMethod(serviceName, methodName, method.getType()); } private GrpcMethod(String serviceName, String methodName, MethodType type) { this.serviceName = serviceName; this.methodName = methodName; this.type = type; } String serviceName() { return serviceName; } String methodName() { return methodName; } String type() { return type.toString(); } boolean streamsRequests() { return type == MethodType.CLIENT_STREAMING || type == MethodType.BIDI_STREAMING; } boolean streamsResponses() { return type == MethodType.SERVER_STREAMING || type == MethodType.BIDI_STREAMING; } }
dadadom/java-grpc-prometheus
<|start_filename|>emacs/early-init.el<|end_filename|> ;;; -*- lexical-binding: t; -*- ;; Defer garbage collection further back in the startup process (setq gc-cons-threshold most-positive-fixnum) ;; ;;; Global Constants (defconst IS-MAC (eq system-type 'darwin)) (defconst IS-LINUX (eq system-type 'gnu/linux)) (defconst IS-WINDOWS (memq system-type '(cygwin windows-nt ms-dos))) ;; Doom currently uses 16 MiB and Spacemacs is using 100 MB. I'm going to try 64 ;; MiB to see how it goes. (defconst GC-CONS-THRESHOLD 67108860) ;; Work around to a crippling performance issue I reported affecting Emacs 28 ;; after cario was made the default: https://debbugs.gnu.org/db/40/40733.html (add-to-list 'face-ignored-fonts "Adobe Blank") ;; Prevent the glimpse of un-styled Emacs by disabling these UI elements early. (push '(menu-bar-lines . 0) default-frame-alist) (push '(tool-bar-lines . 0) default-frame-alist) (push '(vertical-scroll-bars) default-frame-alist) ;; Set default font (set-face-attribute 'default nil :family "Fira Mono" :height 100 :weight 'normal :width 'normal) ;; Resizing the Emacs frame can be a terribly expensive part of changing the ;; font. By inhibiting this, we easily halve startup times with fonts that are ;; larger than the system default. (setq frame-inhibit-implied-resize t) ;; Ignore X resources; its settings would be redundant with the other settings ;; in this file and can conflict with later config (particularly where the ;; cursor color is concerned). (advice-add #'x-apply-session-resources :override #'ignore) (add-to-list 'load-path (expand-file-name "src/" user-emacs-directory)) (require 'early-init-package) ;; Set `doom-themes' early to prevent non-stylized UI flash. (use-package doom-themes :config ;; Apply `doom-theme' (load-theme 'doom-moonlight t)) ;; Set `doom-modeline' early to prevent non-stylized UI flash. ;; Note: `doom-modeline' requires M-x all-the-icons-install-fonts. (use-package doom-modeline :config (setq doom-modeline-icon t doom-modeline-major-mode-color-icon t doom-modeline-buffer-file-name-style 'truncate-upto-root) (doom-modeline-mode 1) (size-indication-mode 1) (column-number-mode 1)) ;; A dependency that dashboard has. (use-package page-break-lines) (use-package dashboard :init (setq initial-buffer-choice (lambda () (get-buffer "*dashboard*"))) :config (let ((art "~/code/external/nixos-artwork/logo/nix-snowflake.svg")) (setq dashboard-startup-banner (if (file-exists-p art) art 3))) (setq dashboard-banner-logo-title nil dashboard-set-heading-icons t dashboard-set-file-icons t dashboard-items '((recents . 5) (projects . 5))) ;; This is the default icon, but it doesn't always show up when running Emacs ;; as a daemon. So I set it explicitly here to fix the issue. (setq dashboard-footer-icon #("" 0 1 (rear-nonsticky t display (raise -0.06) font-lock-face #1=(:family "file-icons" :height 1.32 :inherit font-lock-keyword-face) face #1#))) (dashboard-setup-startup-hook)) <|start_filename|>emacs/src/init-markup-languages.el<|end_filename|> ;;; -*- lexical-binding: t; -*- ;; ;;; Org mode (use-package org :ensure nil ;; Org is included in Emacs. :commands (org-mode org-agenda org-capture) :custom ;; I don't want to see the status of the org-clock in the mode line because I ;; typically clock in/out with org-pomodoro and it updates the mode line in a ;; less verbose way. (org-clock-clocked-in-display nil) :config (add-hook 'org-mode-hook (lambda () (setq show-trailing-whitespace t))) (general-unbind :keymaps 'org-mode-map ;; collides with a edwina keybindings "<M-S-return>" "<M-return>" "M-RET" "M-S-RET") (general-def :states '(normal visual) :keymaps 'org-mode-map :major-modes t "TAB" 'org-cycle "RET" 'org-return) (general-def :prefix "," :states 'normal :keymaps 'org-mode-map :major-modes t "RET" 'org-meta-return "t" 'org-insert-todo-heading "e" 'org-move-subtree-up "i" 'org-do-demote "m" 'org-do-promote "n" 'org-move-subtree-down "d" '(:ignore t :wk "org-download") "dc" 'org-download-clipboard "dd" 'org-download-delete "de" 'org-download-edit "di" 'org-download-image "dr" 'org-download-rename-at-point "dR" 'org-download-rename-last-file "ds" 'org-download-screenshot "dy" 'org-download-yank) ;; Allows me to set the width of an inline image. ;; #+ATTR_ORG: :width 100 ;; [[~/images/example.jpg]] (setq org-image-actual-width nil) (setq org-catch-invisible-edits 'show-and-error) (setq org-list-demote-modify-bullet '(("+" . "-") ("-" . "+") ("*" . "+"))) (setq org-src-window-setup 'current-window org-log-done 'time) (setq org-todo-keywords '((sequence "TODO(t)" "WAITING(w)" "|" "DONE(d)" "CANCELED(c)"))) (setq org-agenda-span 30 org-agenda-start-on-weekday nil org-agenda-start-day "-3d") ;; Set my agenda files to includes all my org files that are not hidden,; ;; auto-save, or backups. (let ((my-org-notes "~/org")) (when (file-directory-p my-org-notes) (setq org-agenda-files (directory-files-recursively my-org-notes ;; ^ match beginning of string ;; [^.#] do not match . or # characters ;; .* match anything ;; \\.org\\' match .org literally at the end of the string "^[^.#].*\\.org\\'" nil ;; A predicate that signals to `directory-files-recursively' whether to ;; recursively search a directory or not. (lambda (dir) (let ((name (file-name-nondirectory dir))) (not (or ;; These are the directories I want to exclude: (string= ".git" name) (string= "archive" name) (string= "docs" name))))))))) (setq org-capture-templates '(("w" "work project") ("wt" "Tasks [work]" entry (file+headline "~/org/work/tasks.org" "Tasks [Work Project]") "* TODO %i%?") ("ws" "Someday [work]" entry (file+headline "~/org/work/someday.org" "Someday [Work Project]") "* TODO %i%?") ("wT" "Tickler [work]" entry (file+headline "~/org/work/tickler.org" "Tickler [Work Project]") "* TODO %i%? \n %U") ("p" "play project") ("pt" "Tasks [play]" entry (file+headline "~/org/play/tasks.org" "Tasks [Play Project]") "* TODO %i%?") ("ps" "Someday [play]" entry (file+headline "~/org/play/someday.org" "Someday [Play Project]") "* TODO %i%?") ("pT" "Tickler [play]" entry (file+headline "~/org/play/tickler.org" "Tickler [Play Project]") "* TODO %i%? \n %U") ("r" "rest project") ("rt" "Tasks [rest]" entry (file+headline "~/org/rest/tasks.org" "Tasks [Rest Project]") "* TODO %i%?") ("rs" "Someday [rest]" entry (file+headline "~/org/rest/someday.org" "Someday [Rest Project]") "* TODO %i%?") ("rT" "Tickler [rest]" entry (file+headline "~/org/tasks/tickler.org" "Tickler [Rest Project]") "* TODO %i%? \n %U"))) (setq org-refile-targets '((nil :maxlevel . 3) (org-agenda-files :maxlevel . 3))) (setq org-outline-path-complete-in-steps nil) ; Refile in a single go (setq org-refile-use-outline-path t) ;; Show full paths for refiling ;; Puts archive files into a relative path to an archive folder with ;; the year in the file name. See doc string for info on special ;; format string syntax (setq org-archive-location (concat "archive/" (format-time-string "%Y" (current-time)) "-%s_archive::"))) (use-package org-download ;; without deferring like this package adds 0.1 sec to startup time Ideally ;; I'd like to add `(add-hook 'dired-mode-hook 'org-download-enable)' to ;; enable dragging and dropping an image directly into dired. However, I want ;; `dired' to start up as fast as possible and loading this package on initial ;; opening of dired creates a noticeable delay. :commands (org-download-enable org-download-edit org-download-yank org-download-image org-download-delete org-download-clipboard ;; depends on xclip org-download-screenshot ;; depends on gnome-screenshot org-download-rename-at-point org-download-rename-last-file)) (use-package org-pomodoro :commands org-pomodoro :custom (org-pomodoro-audio-player "mpv") (org-pomodoro-start-sound-p t) (org-pomodoro-start-sound "~/sync/sounds/mario/powerup.wav") (org-pomodoro-start-sound-args "-volume 80") (org-pomodoro-finished-sound-p t) (org-pomodoro-finished-sound "~/sync/sounds/mario/1up.wav") (org-pomodoro-finished-sound-args "-volume 80") ;; plays when short break is finished. (org-pomodoro-short-break-sound-p t) (org-pomodoro-short-break-sound "~/sync/sounds/mario/coin.wav") (org-pomodoro-short-break-sound-args "-volume 80") ;; plays when long break is finished. (org-pomodoro-long-break-sound-p t) (org-pomodoro-long-break-sound "~/sync/sounds/mario/coin.wav") (org-pomodoro-long-break-sound-args "-volume 80") (org-pomodoro-killed-sound-p t) (org-pomodoro-killed-sound "~/sync/sounds/mario/die.wav") (org-pomodoro-killed-sound-args "-volume 80") (org-pomodoro-overtime-sound-p t) (org-pomodoro-overtime-sound "~/sync/sounds/star-fox/fox.wav") (org-pomodoro-overtime-sound-args "-volume 80")) (use-package toc-org :hook (org-mode . toc-org-mode)) ;; ;;; Markdown (use-package markdown-mode :commands (markdown-mode gfm-mode) :mode (("README\\.md\\'" . gfm-mode) ("\\.md\\'" . markdown-mode) ("\\.markdown\\'" . markdown-mode)) :init (setq markdown-command '("pandoc" "--from=markdown" "--to=html5")) (add-hook 'markdown-mode-hook (lambda () (setq show-trailing-whitespace t)))) (use-package markdown-toc :after markdown-mode) ;; ;;; Org and Markdown related tools (use-package pandoc-mode :hook ((markdown-mode . pandoc-mode) (org-mode . pandoc-mode) (pandoc-mode . pandoc-load-default-settings)) :config (general-def :prefix "," :states 'normal :keymaps 'pandoc-mode-map "p" 'pandoc-main-hydra/body)) (provide 'init-markup-languages) <|start_filename|>emacs/src/init-languages.el<|end_filename|> ;;; -*- lexical-binding: t; -*- ;; ;;; A file for other language packages / settings that are too simple to be in ;;; their own file. (use-package rustic :mode ("\\.rs\\'" . rustic-mode)) (use-package racket-mode :mode "\\.rkt\\'") (use-package mips-mode :mode "\\.mips$") ;; CSS / JavaScript (build in modes) indention level (setq-default css-indent-offset 2) (setq-default js-indent-level 2) (use-package powershell :mode ("\\.ps[dm]?1\\'" . powershell-mode) :commands (powershell-mode powershell)) (use-package yaml-mode :mode ("\\.yaml\\'" . yaml-mode)) (use-package vimrc-mode :mode (("\\.vim\\(rc\\)?\\'" . vimrc-mode) ("\\vimrc\\'" . vimrc-mode))) ;; ;;; Nix (use-package nix-sandbox :commands (nix-shell-command nix-shell nix-compile nix-find-sandbox nix-current-sandbox nix-executable-find nix-find-sandbox)) (use-package nix-update :commands nix-update-fetch) (use-package nixpkgs-fmt :commands nixpkgs-fmt :hook (nix-mode . nixpkgs-fmt-on-save-mode)) (use-package nix-mode :mode "\\.nix\\'" :config (general-def :prefix "," :states '(normal visual) :keymaps 'nix-mode-map "u" 'nix-update-fetch "f" '(nixpkgs-fmt :wk "format file"))) (use-package prolog-mode :mode "\\.pl\\'") (provide 'init-languages) <|start_filename|>emacs/src/init-haskell.el<|end_filename|> ;;; -*- lexical-binding: t; -*- (use-package haskell-mode :mode "\\.hs\\'" :init (add-hook 'haskell-mode-hook (lambda () (progn ;; For some reason haskell-mode doesn't respect global ;; tab-width. It uses 8 by default. (setq-local tab-width 2) (set (make-local-variable 'company-backends) ;; Adding `company-capf' to the end of the list because ;; something else is adding it to the front of the list if ;; I don't. ;; Note that `company-lsp' is also something to consider ;; using instead of `company-capf'. However, since it ;; hasn't seen any activity in a year on their Github ;; repository, I'm reluctant to use it. '((company-capf :with company-tabnine) company-tabnine company-capf))))) :config ;; I'm not sure what, but something calls a function provided by `haskell-doc.el' ;; and doesn't properly require it before doing so. requiring haskell-doc here ;; this fixes the void function error. (require 'haskell-doc) ;; Use `hasktags' to regenerate `etags' on save. Using `hasktags' is a good ;; fall back to `lsp-mode' and it's fast. (setq haskell-tags-on-save t) ;; Auto inserts `module Foo where' and a comment block for a new Foo.hs file. (add-hook 'haskell-mode-hook 'haskell-auto-insert-module-template) ;; This scan mode is needed to give support to imenu and anything that depends on imenu. ;; It enables the use of which-func-mode and speedbar. (add-hook 'haskell-mode-hook 'haskell-decl-scan-mode) ;; `which-function-mode' is just a nicety that shows the current function the ;; point is in on the mode line. (add-hook 'haskell-mode-hook 'which-function-mode) ;; fix the haskell-indentation-mode-map for evil-mode. For example, it would ;; insert a comma in normal mode when haskell-indentation-mode was enabled. (general-unbind 'haskell-indentation-mode-map ")" "," ";" "<backtab>" "RET" "]" "}") (general-def :states '(insert) :keymaps 'haskell-indentation-mode-map ")" 'haskell-indentation-common-electric-command "," 'haskell-indentation-common-electric-command ";" 'haskell-indentation-common-electric-command "<backtab>" 'haskell-indentation-indent-backwards "RET" 'haskell-indentation-newline-and-indent "]" 'haskell-indentation-common-electric-command "}" 'haskell-indentation-common-electric-command) ;; rebind `evil-goto-definition' for Haskell mode. (general-def :states 'normal :keymaps 'haskell-mode-map "gd" 'xref-find-definitions) (general-def :prefix "," :states '(normal visual) :keymaps 'haskell-mode-map "." 'lsp-describe-thing-at-point "F" '(:ignore t :wk "workspace folders") "c" '(:ignore t :wk "check") "d" '(:ignore t :wk "document") "f" '(:ignore t :wk "find") "p" '(:ignore t :wk "peek") "r" '(:ignore t :wk "refactor") "s" '(:ignore t :wk "lsp session") "t" '(:ignore t :wk "toggle")) (general-def :prefix ", F" :states '(normal visual) :keymaps 'haskell-mode-map "a" 'lsp-workspace-folders-add "b" 'lsp-workspace-blacklist-remove "r" 'lsp-workspace-folders-remove) (general-def :prefix ", d" :states '(normal visual) :keymaps 'haskell-mode-map "g" 'lsp-ui-doc-glance) (general-def :prefix ", c" :states '(normal visual) :keymaps 'haskell-mode-map "L" 'flycheck-list-errors "b" 'flycheck-buffer "c" 'flycheck-clear "l" 'lsp-ui-flycheck-list "n" 'flycheck-next-error "p" 'flycheck-previous-error) (general-def :prefix ", f" :states '(normal visual) :keymaps 'haskell-mode-map "d" 'lsp-find-definition "i" 'lsp-find-implementation "n" 'lsp-ui-find-next-reference "p" 'lsp-ui-find-prev-reference "r" 'lsp-find-references "t" 'lsp-find-type-definition) (general-def :prefix ", p" :states '(normal visual) :keymaps 'haskell-mode-map "d" 'lsp-ui-peek-find-definitions "i" 'lsp-ui-peek-find-implementation "r" 'lsp-ui-peek-find-references) (general-def :prefix ", r" :states '(normal visual) :keymaps 'haskell-mode-map "B" 'lsp-format-buffer "R" 'lsp-rename "a" 'lsp-execute-code-action "b" 'format-all-buffer "f" 'lsp-format-region "o" 'lsp-organize-imports "r" 'my/brittany-format-region) (general-def :prefix ", s" :states '(normal visual) :keymaps 'haskell-mode-map "D" 'lsp-disconnect "d" 'lsp-describe-session "q" 'lsp-workspace-shutdown "r" 'lsp-workspace-restart "s" 'lsp) (general-def :prefix ", t" :states '(normal visual) :keymaps 'haskell-mode-map "D" 'lsp-signature-toggle-full-docs "F" 'lsp-toggle-on-type-formatting "S" 'lsp-ui-sideline-mode "a" 'lsp-toggle-signature-auto-activate "d" 'lsp-ui-doc-mode "h" 'lsp-toggle-symbol-highlight "m" 'lsp-ui-imenu "s" 'lsp-ui-sideline-toggle-symbols-info "t" 'lsp-toggle-trace-io "u" 'lsp-ui-mode)) (use-package lsp-haskell :after (haskell-mode lsp-mode) :config ;; Comment/uncomment this line to see interactions between lsp client/server. (setq lsp-log-io t) ;; the following does not work: (lsp-haskell-set-formatter :brittany) ;; see https://github.com/emacs-lsp/lsp-haskell/issues/75 (defun lsp-haskell-set-formatter-brittany () "Use brittany." (interactive) (lsp-haskell-set-formatter "brittany") (lsp-haskell--set-configuration)) (defun lsp-haskell-set-formatter-floskell () "Use floskell." (interactive) (lsp-haskell-set-formatter "floskell") (lsp-haskell--set-configuration)) (defun lsp-haskell-set-formatter-ormolu () "Use ormolu." (interactive) (lsp-haskell-set-formatter "ormolu") (lsp-haskell--set-configuration)) (setq lsp-haskell-process-path-hie "haskell-language-server-wrapper" lsp-haskell-process-args-hie '())) ;; HLS provides format providers, but I'm going to keep this around until I'm ;; sure they're dependable. ;;;###autoload (defun my/brittany-format-region (start end) "Uses Brittany to format a region of Haskell code." (interactive "r") (let ((cmd "brittany") (out-buffer "*Brittany Command Output*") (err-buffer "*Brittany Command Error*")) (shell-command-on-region start end cmd out-buffer t err-buffer t nil))) (provide 'init-haskell) <|start_filename|>emacs/src/init-completion.el<|end_filename|> ;;; -*- lexical-binding: t; -*- ;; Keep track of recently opened files (use-package recentf :hook (after-init . recentf-mode) :ensure nil ;; is included in Emacs. :config (defun my/recent-file-truename (file) (if (or (file-remote-p file nil t) (not (file-remote-p file))) (file-truename file) file)) (setq recentf-filename-handlers '(substring-no-properties ;; strip out lingering text properties my/recent-file-truename ;; resolve symlinks of local files abbreviate-file-name) ;; replace $HOME with ~ recentf-save-file (expand-file-name "recentf" user-emacs-directory) recentf-auto-cleanup 'never recentf-max-menu-items 0 recentf-max-saved-items 1000) (add-hook 'dired-mode-hook (lambda () (recentf-add-file default-directory))) (add-hook 'kill-emacs-hook #'recentf-cleanup)) (use-package ivy :defer 0.1 :config ;; Silence warning (:defer causes byte compile warnings) (declare-function ivy-mode "ivy") (setq ivy-use-virtual-buffers t) (setq ivy-display-style 'fancy) (ivy-mode 1)) (use-package all-the-icons-ivy :after ivy :config ;; Silence warning (ivy's :defer causes byte compile warnings) (declare-function all-the-icons-ivy-setup "all-the-icons-ivy-setup") (all-the-icons-ivy-setup)) (use-package counsel :after ivy :config ;; Silence warning (ivy's :defer causes byte compile warnings) (declare-function counsel-mode "counsel") (setq counsel-describe-function-function #'helpful-callable counsel-describe-variable-function #'helpful-variable) (setq counsel-git-cmd "rg --files" counsel-grep-base-command "rg --column --line-number --no-heading --smart-case --no-ignore --hidden --follow --color never %s %s" counsel-rg-base-command "rg --column --line-number --no-heading --smart-case --no-ignore --hidden --follow --color never %s .") (counsel-mode 1)) (use-package ivy-prescient :after counsel :config (ivy-prescient-mode 1) (prescient-persist-mode 1)) (use-package company :defer 0.1 :config ;; Silence warning (:defer causes byte compile warnings) (declare-function global-company-mode "company") (setq company-idle-delay 0.1 company-minimum-prefix-length 2 company-show-numbers t) (global-company-mode 1)) (use-package company-tabnine :after company :config ;; Silence warning (company's :defer causes byte compile warnings) (declare-function company-tabnine "company-tabnine") (add-to-list 'company-backends #'company-tabnine)) (use-package counsel-projectile :defer 0.1 :config ;; Silence warning (:defer causes byte compile warnings) (declare-function counsel-projectile-switch-project "counsel-projectile") (declare-function counsel-projectile-mode "counsel-projectile") ;; This can also be accomplished by invoking ;; `counsel-projectile-switch-project' then `M-o D', but I want to make it ;; easier. (defun my/counsel-projectile-switch-project-dired () "Switches to a projectile project's root in dired mode." (interactive) (counsel-projectile-switch-project "D")) (general-def :keymaps 'projectile-command-map "P" 'my/counsel-projectile-switch-project-dired ;; Was bound to P. Rebind it. "Z" 'projectile-test-project) ;; `counsel-projectile-mode' enables `projectile-mode' (counsel-projectile-mode 1)) (use-package projectile :commands projectile-mode :config ;; The default uses Emacs Lisp in Windows, which way too slow for large ;; projects. (setq projectile-indexing-method 'alien projectile-completion-system 'ivy) ;; Make these indexing methods safe as file-local variables (dolist (method '((projectile-indexing-method . alien) (projectile-indexing-method . hybrid) (projectile-indexing-method . native))) (add-to-list 'safe-local-variable-values method))) (use-package fd-dired :commands fd-dired) (provide 'init-completion) <|start_filename|>emacs/src/funcs.el<|end_filename|> ;;; -*- lexical-binding: t; -*- (require 'cl-lib) ;; silence warning (declare-function evil-visual-state-p "evil-states") ;; ;;; Text manipulation related functions: ;;;###autoload (defun my/sort-lines-by-column (&optional reverse) "Sort lines by the selected column. A non-nil argument sorts in reverse order." (interactive "P") (let* ((region-active (or (region-active-p) (evil-visual-state-p))) (beg (if region-active (region-beginning) (point-min))) (end (if region-active (region-end) (point-max)))) (sort-columns reverse beg end))) ;;;###autoload (defun my/sort-lines-by-column-reverse () "Sort lines by the selected column in reverse order." (interactive) (my/sort-lines-by-column -1)) ;;;###autoload (defun my/sort-lines (&optional reverse) "Sort lines in a region or the current buffer. A non-nil argument sorts in reverse order." (interactive "P") (let* ((region-active (or (region-active-p) (evil-visual-state-p))) (beg (if region-active (region-beginning) (point-min))) (end (if region-active (region-end) (point-max)))) (sort-lines reverse beg end))) ;;;###autoload (defun my/sort-lines-reverse () "Sort lines in reverse order, in a region or the current buffer." (interactive) (my/sort-lines -1)) ;;;###autoload (defun my/uniquify-lines () "Remove duplicate adjacent lines in a region or the current buffer" (interactive) (save-excursion (save-restriction (let* ((region-active (or (region-active-p) (evil-visual-state-p))) (beg (if region-active (region-beginning) (point-min))) (end (if region-active (region-end) (point-max)))) (goto-char beg) (while (re-search-forward "^\\(.*\n\\)\\1+" end t) (replace-match "\\1")))))) ;;;###autoload (defun my/randomize-words (beg end) "Randomize the order of words in region." (interactive "*r") (let ((all (mapcar (lambda (w) (if (string-match "\\w" w) ;; Randomize words, (cons (random) w) ;; keep everything else in order. (cons -1 w))) (split-string (delete-and-extract-region beg end) "\\b"))) words sorted) (mapc (lambda (x) ;; Words are numbers >= 0. (unless (> 0 (car x)) (setq words (cons x words)))) all) ;; Random sort! (setq sorted (sort words (lambda (a b) (< (car a) (car b))))) (mapc 'insert ;; Insert using original list, `all', ;; but pull *words* from randomly-sorted list, `sorted'. (mapcar (lambda (x) (if (> 0 (car x)) (cdr x) (prog1 (cdar sorted) (setq sorted (cdr sorted))))) all)))) ;;;###autoload (defun my/randomize-lines (beg end) "Randomize lines in region from BEG to END." (interactive "*r") (let ((lines (split-string (delete-and-extract-region beg end) "\n"))) (when (string-equal "" (car (last lines 1))) (setq lines (butlast lines 1))) (apply 'insert (mapcar 'cdr (sort (mapcar (lambda (x) (cons (random) (concat x "\n"))) lines) (lambda (a b) (< (car a) (car b)))))))) ;; from Spacemacs which took from http://www.emacswiki.org/emacs/WordCount ;;;###autoload (defun my/analyze-word-count (start end) "Count how many times each word is used in the region. Punctuation is ignored." (interactive "r") (let (words (formatted "") (overview (call-interactively 'count-words))) (save-excursion (goto-char start) (while (re-search-forward "\\w+" end t) (let* ((word (intern (match-string 0))) (cell (assq word words))) (if cell (setcdr cell (1+ (cdr cell))) (setq words (cons (cons word 1) words)))))) (defun alist_words_compare (a b) "Compare elements from an associative list of words count. Compare them on count first,and in case of tie sort them alphabetically." (let ((a_key (car a)) (a_val (cdr a)) (b_key (car b)) (b_val (cdr b))) (if (eq a_val b_val) (string-lessp a_key b_key) (> a_val b_val)))) (setq words (cl-sort words 'alist_words_compare)) (while words (let* ((word (pop words)) (name (car word)) (count (cdr word))) (setq formatted (concat formatted (format "[%s: %d], " name count))))) (when (called-interactively-p 'interactive) (if (> (length formatted) 2) (message (format "%s\nWord count: %s" overview (substring formatted 0 -2))) (message "No words."))) words)) ;;;###autoload (defun my/dos2unix () "Convert the current buffer to a Unix file encoding." (interactive) (set-buffer-file-coding-system 'utf-8-unix nil)) ;;;###autoload (defun my/unix2dos () "Convert the current buffer to a DOS file encoding." (interactive) (set-buffer-file-coding-system 'utf-8-dos nil)) ;; window / buffer related functions: ;;;###autoload (defun my/kill-all-buffers () "kill all buffers" (interactive) (mapc 'kill-buffer (buffer-list))) ;;;###autoload (defun my/switch-to-messages () "Switch to *Messages* buffer." (interactive) (switch-to-buffer "*Messages*")) ;;;###autoload (defun my/switch-to-scratch () "Switch to *scratch* buffer." (interactive) (switch-to-buffer "*scratch*")) ;;;###autoload (defun my/switch-to-dashboard () "Switch to *dashboard* (creates if needed)" (interactive) (when (not (get-buffer dashboard-buffer-name)) (generate-new-buffer dashboard-buffer-name)) (dashboard-refresh-buffer)) ;;;###autoload (defun my/kill-all-buffers-then-switch-to-dashboard () "Kills all buffers then switches to *dashboard* (creates if needed)" (interactive) (progn (my/kill-all-buffers) (my/switch-to-dashboard) (cd "~/"))) ;;;###autoload (defun my/kill-this-buffer () "Kill the current buffer." (interactive) (if (window-minibuffer-p) (abort-recursive-edit) (kill-buffer))) ;;;###autoload (defun my/kill-other-windows-buffers () "Kill all other windows and buffers" (interactive) (progn (mapc 'kill-buffer (delq (current-buffer) (buffer-list))) (delete-other-windows))) ;; http://camdez.com/blog/2013/11/14/emacs-show-buffer-file-name/ ;;;###autoload (defun my/yank-and-show-buffer-full-path () "Yank (i.e. copy) and show the full path to the current file in the minibuffer." (interactive) ;; list-buffers-directory is the variable set in dired buffers (let ((file-name (or (buffer-file-name) list-buffers-directory))) (if file-name (message (kill-new file-name)) (error "Buffer not visiting a file")))) ;;;###autoload (defun my/toggle-maximize-window () "Toggle between maximizing the window and restoring previous window setup." (interactive) (if (and (= 1 (length (window-list))) (assoc ?_ register-alist)) (jump-to-register ?_) (window-configuration-to-register ?_) (delete-other-windows))) ;; depends on https://elpa.gnu.org/packages/adaptive-wrap.html ;;;###autoload (defun my/toggle-adaptive-visual-fill-column () "Toggles visual-fill-column-mode and adaptive-wrap-prefix-mode on or off" (interactive) (if (bound-and-true-p visual-fill-column-mode) (progn (visual-fill-column-mode -1) (adaptive-wrap-prefix-mode -1) (message "visual-fill-column and adaptive-wrap-prefix mode disabled")) (visual-fill-column-mode 1) (adaptive-wrap-prefix-mode 1) (message "visual-fill-column and adaptive-wrap-prefix mode enabled"))) ;;;###autoload (defun my/open-shell () "Opens my prefered shell for the current operating system." (interactive) (if IS-WINDOWS (call-interactively 'eshell) (vterm))) ;; ;;; MISC functions: ;; https://stackoverflow.com/questions/3480173/show-keys-in-emacs-keymap-value ;;;###autoload (defun my/describe-keymap (keymap) "Describe a keymap." (interactive (list (completing-read "Keymap: " (let (maps) (mapatoms (lambda (sym) (and (boundp sym) (keymapp (symbol-value sym)) (push sym maps)))) maps) nil t))) (with-output-to-temp-buffer (format "*keymap: %s*" keymap) (princ (format "%s\n\n" keymap)) (princ (substitute-command-keys (format "\\{%s}" keymap))) (with-current-buffer standard-output ;; temp buffer (setq help-xref-stack-item (list #'my/describe-keymap keymap))))) ;;;###autoload (defun my/revert-buffer-no-confirm () "Revert buffer without confirmation." (interactive) (revert-buffer :ignore-auto :noconfirm)) ;;;###autoload (defun my/gopass-generate-xkcd-passwords () "Use gopass to generate xkcd style passwords to a shell buffer" (interactive) (my/gopass--generate-passwords "gopass pwgen --xkcd")) ;;;###autoload (defun my/gopass-generate-passwords () "Use gopass to generate passwords to a shell buffer" (interactive) (my/gopass--generate-passwords "gopass pwgen --one-per-line")) ;;;###autoload (defun my/gopass--generate-passwords (command) (let* ((buf-name "*gopass passwords*") (buf (get-buffer-create buf-name))) (async-shell-command command buf) (when (not (string-equal buf-name (buffer-name (current-buffer)))) (switch-to-buffer-other-window buf)))) (provide 'funcs)
willbush/system
<|start_filename|>packages/cli-plugin-generator/tests/copy.js<|end_filename|> // FIXME: this file should be placed otherwise const fs = require('fs-extra'); const path = require('path'); fs.removeSync(path.resolve(__dirname, './fixtures/base')); fs.copySync( path.resolve(__dirname, './fixtures/source'), path.resolve(__dirname, './fixtures/base') ); <|start_filename|>packages/cli-plugin-build/test/fixtures/bundle/package.json<|end_filename|> { "name": "test-bundle", "version": "1.0.3", "description": "icejs & midway hooks", "dependencies": { "@midwayjs/decorator": "^2.0.0" } } <|start_filename|>packages/cli-plugin-dev/js/esbuild-register.js<|end_filename|> const { register } = require('esbuild-register/dist/node'); register({ extensions: ['.ts', '.tsx'], }); <|start_filename|>packages/cli/bin/cli.js<|end_filename|> 'use strict'; const cli = async argv => { require('source-map-support/register'); const { CLI, checkUpdate, findNpm } = require('../dist'); if (!argv.npm) { argv.npm = findNpm(argv).cmd; } // 检查更新 checkUpdate(argv.npm); const cli = new CLI(argv); cli .start() .then(() => { process.exit(); }) .catch(e => { console.log('\n\n\n'); console.log( 'Error! You can try adding the -V parameter for more information output.' ); console.log('\n\n\n'); console.error(e); process.exitCode = 1; process.exit(1); }); }; module.exports = { cli, }; <|start_filename|>.eslintrc.json<|end_filename|> { "extends": "./node_modules/mwts/", "ignorePatterns": ["node_modules", "dist", "fixtures"], "rules": { "no-async-promise-executor": "off", "node/no-extraneous-require": "off" }, "env": { "mocha": true }, "plugins": ["jest"] }
zhyupe/cli
<|start_filename|>lib/writers/console.js<|end_filename|> 'use strict' require('console.table') const key = 'writer-console' /** * @param {Array} results Data that should be written to the console * @returns {Promise} Resolves when everything was written */ const write = async results => console.table(results) module.exports = { key, write } <|start_filename|>lib/logger.js<|end_filename|> 'use strict' const colors = require('colors') const notTest = process.env.NODE_ENV !== 'testing' module.exports = { log: (...args) => notTest && console.log('[info]', ...args), warn: (...args) => notTest && console.log('[warn]', colors.yellow(...args)), error: (...args) => notTest && console.error('[error]', colors.red(...args)) } <|start_filename|>lib/modules/files-contents/index.js<|end_filename|> 'use strict' const path = require('path') const ModuleResults = require('../../results') const patterns = require('./data') const key = __dirname.split(path.sep).pop() module.exports = { key, description: 'Scans for suspicious file contents that are likely to contain secrets', enabled: true, handles: async () => true, run: async fm => fm.languageFiles .map(file => ({ file, content: fm.readFileSync(file) })) .map(({ file, content }) => patterns.map(pattern => checkFileWithPattern(pattern, file, content))) .reduce((flatmap, next) => flatmap.concat(next), []) .filter(result => !!result) .reduce((results, res) => results[res.level](res), new ModuleResults(key)) } const checkFileWithPattern = ({ code, level, description, regex }, file, content) => { const result = regex.exec(content) if (!result) return const line = content.split(result[0])[0].split('\n').length return { code: `${file}-${code}`, offender: file, description, level, mitigation: `Check line number: ${line}` } } <|start_filename|>lib/modules/rust-cargoaudit/index.js<|end_filename|> 'use strict' const path = require('path') const fs = require('fs') const ModuleResults = require('../../results') const exec = require('../../exec') const logger = require('../../logger') const key = __dirname.split(path.sep).pop() module.exports = { key, description: 'Checks Rust projects for dependencies with known vulnerabilities', enabled: true, handles: async fm => { const isRustProject = fs.existsSync(path.join(fm.target, 'Cargo.toml')) const hasCommand = await exec.exists('cargo') if (isRustProject && !hasCommand) { logger.warn('Cargo.lock found but cargo was not found in $PATH') logger.warn(`${key} scan will not run unless you install cargo`) return false } return isRustProject }, run: async fm => { let lockFileWasGeneratedByTheModule = false try { if (!fs.existsSync(path.join(fm.target, 'Cargo.lock'))) { await exec.command('cargo generate-lockfile', { cwd: fm.target }) lockFileWasGeneratedByTheModule = true } const { stdout } = await exec.command('cargo audit --json', { cwd: fm.target }) const report = JSON.parse(stdout) const vulnerabilities = report.vulnerabilities.list return vulnerabilities .map(v => { const adv = v.advisory const pkg = v.package const patchedVersionsText = adv.patched_versions.join(', ') return { offender: `${pkg.name}=${pkg.version}`, code: adv.id, description: `${adv.title} (${adv.url})`, mitigation: `Update "${adv.package}" crate to one of the following versions: ${patchedVersionsText}` } }) .reduce((results, v) => results.critical(v), new ModuleResults(key)) } finally { if (lockFileWasGeneratedByTheModule) { fs.unlinkSync(path.join(fm.target, 'Cargo.lock')) } } } } <|start_filename|>lib/writers/__tests__/http-unit.js<|end_filename|> 'use strict' const nock = require('nock') const { write } = require('../http') const host = 'http://host.foobar' const path = '/collector' const opts = { url: host + path } describe('Writer', () => { it('should send to collector', async () => { const payload1 = { module: 'files-ccnumber', level: 'critical', code: 'files-secrets-47', offender: 'testfile1.yml', description: 'Contains word: password', mitigation: 'Check contents of the file' } const payload2 = { module: 'files-ccnumber', level: 'critical', code: 'files-secrets-47', offender: 'testfile2.yml', description: 'Contains word: password', mitigation: 'Check contents of the file' } const payload3 = { module: 'files-contents', level: 'critical', code: 'files-contents-2', offender: 'testfile3.yml', description: 'Private key in file', mitigation: 'Check line number: 3' } nock(host, { reqheaders: { 'User-Agent': 'hawkeye' } }) .post(path, payload1) .reply(200) .post(path, payload2) .reply(200) .post(path, payload3) .reply(200) await write([payload1, payload2, payload3], opts) }) }) <|start_filename|>lib/modules/files-ccnumber/index.js<|end_filename|> 'use strict' /* eslint-disable no-cond-assign */ const path = require('path') const ModuleResults = require('../../results') const patterns = require('./data') const MAX_FILE_LENGTH = 400 const key = __dirname.split(path.sep).pop() module.exports = { key, description: 'Scans for suspicious file contents that are likely to contain credit card numbers', enabled: true, handles: async () => true, run: async fm => fm.languageFiles .map(file => ({ file, content: fm.readFileSync(file) })) .map(({ file, content }) => patterns.map(pattern => checkFileWithPattern(pattern, file, content))) .reduce((flatmap, next) => flatmap.concat(next), []) .filter(result => !!result) // filter empty results .reduce((results, res) => results.high(res), new ModuleResults(key)) } const checkFileWithPattern = ({ code, description, regex }, file, content) => { if (content.length > MAX_FILE_LENGTH) return const strippedContent = content .replace(/(\d+)([ -])(\d+)/g, '$1$3') .replace(/(\d+)([ -])(\d+)/g, '$1$3') .replace(/(\d+)([ -])(\d+)/g, '$1$3') .replace(/(\D)(\d{15,})/g, '$1 $2') .replace(/(\d{15,})(\D)/g, '$1 $2') const match = regex.exec(strippedContent) if (!match) return if (!luhn(match[0])) return const line = content.split(match[0])[0].split('\n').length return { code: `${file}-${code}`, offender: file, description, mitigation: 'Check line number: ' + line } } /** * Basic check whether a credit card number is valid. * * @see https://en.wikipedia.org/wiki/Luhn_algorithm * * @param {String} ccNum Potential credit card number * @returns {Boolean} true if number is potentially valid credit card, otherwise false */ function luhn (ccNum) { const arr = [0, 2, 4, 6, 8, 1, 3, 5, 7, 9] let len = ccNum.length let bit = 1 let sum = 0 while (len) { const val = parseInt(ccNum.charAt(--len), 10) sum += (bit ^= 1) ? arr[val] : val } return sum && sum % 10 === 0 } <|start_filename|>testutils.js<|end_filename|> const chai = require('chai') const sinon = require('sinon') const sinonChai = require('sinon-chai') const chaiAsPromised = require('chai-as-promised') chai.use(sinonChai) chai.use(chaiAsPromised) global.expect = chai.expect global.sinon = sinon global.request = chai.request afterEach(() => { sinon.verifyAndRestore() }) <|start_filename|>lib/modules/files-entropy/index.js<|end_filename|> 'use strict' /* eslint-disable no-cond-assign */ const path = require('path') const ModuleResults = require('../../results') const description = 'High entropy string detected in file' const key = __dirname.split(path.sep).pop() module.exports = { key, description: 'Scans files for strings with high entropy that are likely to contain passwords', enabled: false, handles: () => true, run: async fm => fm.languageFiles .map(file => ({ file, content: fm.readFileSync(file) })) .map(({ file, content }) => { const re = /\w{10,}/g let m while (m = re.exec(content)) { if (shannon(m[0]) > 4.5) { const line = content.split(m[0])[0].split('\n').length return { code: `${file}-${line}`, offender: file, description, mitigation: `Check line number: ${line}` } } } }) .filter(result => !!result) .reduce((results, res) => results.low(res), new ModuleResults(key)) } // https://gist.github.com/ppseprus/afab8500dec6394c401734cb6922d220 const shannon = str => [...new Set(str)] .map(chr => str.match(new RegExp(chr, 'g')).length) .reduce((sum, frequency) => { const p = frequency / str.length return sum + p * Math.log2(1 / p) }, 0) <|start_filename|>lib/modules/php-security-checker/__tests__/php-security-checker-unit.js<|end_filename|> 'use strict' /* eslint-disable no-unused-expressions */ const path = require('path') const exec = require('../../../exec') const FileManager = require('../../../file-manager') const { handles, run } = require('..') const sample = require('./sample/securitychecker.json') describe('PHP Security Checker Module', () => { let fm const target = path.join(__dirname, 'sample') beforeEach(() => { sinon.stub(exec, 'exists').resolves(true) sinon.stub(exec, 'command').resolves({ stdout: JSON.stringify(sample) }) fm = new FileManager({ target }) }) it('should handle project', async () => { expect(await handles(fm)).to.be.true }) it('should not run on missing executable', async () => { exec.exists.resolves(false) expect(await handles(fm)).to.be.false }) it('should execute checker without excludes', async () => { await run(fm) expect(exec.command).to.have.been.calledWith('security-checker.phar security:check --format json', { cwd: target }) }) it('should log high severity issues', async () => { const { results } = await run(fm) expect(results.high).to.deep.equal([{ code: 'php-security-checker-CVE-2018-1234567890', offender: 'firebase/php-jwt', description: 'Critical vulnerabilities in JSON Web Token libraries', mitigation: 'https://auth0.com/blog/2015/03/31/critical-vulnerabilities-in-json-web-token-libraries/' }]) }) }) <|start_filename|>lib/modules/files-ccnumber/data.js<|end_filename|> 'use strict' module.exports = [ { code: 1, regex: /(?:3[47][0-9]{13})/, description: 'Potential American Express card number in file' }, { code: 2, regex: /(?:3(?:0[0-5]|[68][0-9])[0-9]{11})/, description: 'Potential Diners Club card number in file' }, { code: 3, regex: /^65[4-9][0-9]{13}|64[4-9][0-9]{13}|6011[0-9]{12}|(622(?:12[6-9]|1[3-9][0-9]|[2-8][0-9][0-9]|9[01][0-9]|92[0-5])[0-9]{10})$/, description: 'Potential Discover card number in file' }, { code: 4, regex: /^(?:2131|1800|35\d{3})\d{11}$/, description: 'Potential JCB card number in file' }, { code: 5, regex: /(?:(?:5[0678]\\d\\d|6304|6390|67\\d\\d)\\d{8,15})/, description: 'Potential Maestro card number in file' }, { code: 6, regex: /(?:(?:5[1-5][0-9]{2}|222[1-9]|22[3-9][0-9]|2[3-6][0-9]{2}|27[01][0-9]|2720)[0-9]{12})/, description: 'Potential Mastercard card number in file' }, { code: 7, regex: /((?:4[0-9]{12})(?:[0-9]{3})?)/, description: 'Potential Visa card number in file' } ] <|start_filename|>lib/results.js<|end_filename|> 'use strict' module.exports = class ModuleResults { constructor (key) { this.key = key this.data = { high: [], medium: [], low: [], critical: [] } } critical ({ code, offender, description, mitigation }) { this.data.critical.push({ code: `${this.key}-${code}`, offender, description, mitigation }) return this } high ({ code, offender, description, mitigation }) { this.data.high.push({ code: `${this.key}-${code}`, offender, description, mitigation }) return this } medium ({ code, offender, description, mitigation }) { this.data.medium.push({ code: `${this.key}-${code}`, offender, description, mitigation }) return this } low ({ code, offender, description, mitigation }) { this.data.low.push({ code: `${this.key}-${code}`, offender, description, mitigation }) return this } get results () { return this.data } } <|start_filename|>lib/modules/python-piprot/__tests__/piprot-unit.js<|end_filename|> 'use strict' /* eslint-disable no-unused-expressions */ const fs = require('fs') const path = require('path') const exec = require('../../../exec') const FileManager = require('../../../file-manager') const { handles, run } = require('..') describe('Python piprot Module', () => { const target = path.join(__dirname, 'sample') let fm beforeEach(() => { sinon.stub(exec, 'exists').resolves(true) sinon.stub(exec, 'command').resolves({ stdout: fs.readFileSync(path.join(__dirname, 'sample', 'piprot.txt'), 'utf-8') }) fm = new FileManager({ target }) }) it('should handle python projects', async () => { expect(await handles(fm)).to.be.true }) it('should not run on missing executable', async () => { exec.exists.resolves(false) expect(await handles(fm)).to.be.false }) it('should execute piprot', async () => { await run(fm) expect(exec.command).to.have.been.calledWith('piprot -o', { cwd: target }) }) it('should log low severity issues', async () => { const { results } = await run(fm) expect(results.low).to.deep.equal([{ code: 'python-piprot-3', description: 'Module is one or more patch versions out of date', mitigation: 'Upgrade to v1.0.3 (Current: v1.0.2)', offender: 'email_validator' }]) }) it('should log medium severity issues', async () => { const { results } = await run(fm) expect(results.medium).to.deep.equal([{ code: 'python-piprot-2', description: 'Module is one or more minor versions out of date', mitigation: 'Upgrade to v3.2.3 (Current: v3.0.7)', offender: 'pytest' }]) }) it('should log high severity issues', async () => { const { results } = await run(fm) expect(results.high).to.deep.equal([{ code: 'python-piprot-1', description: 'Module is one or more major versions out of date', mitigation: 'Upgrade to v2.1.2 (Current: v1.8.1)', offender: 'cryptography' }]) }) }) <|start_filename|>lib/modules/php-security-checker/index.js<|end_filename|> 'use strict' const path = require('path') const fs = require('fs') const ModuleResults = require('../../results') const exec = require('../../exec') const logger = require('../../logger') const key = __dirname.split(path.sep).pop() module.exports = { key, description: 'Checks whether the composer.lock contains dependencies with known vulnerabilities using security-checker', enabled: true, handles: async fm => { const composerLock = fs.existsSync(path.join(fm.target, 'composer.lock')) const command = await exec.exists('security-checker.phar') if (composerLock && !command) { logger.warn('composer.lock found but security-checker.phar not found in $PATH') logger.warn(`${key} will not run unless you install security-checker.phar`) logger.warn('Please see: https://github.com/sensiolabs/security-checker') return false } return composerLock }, run: async fm => { const { stdout } = await exec.command('security-checker.phar security:check --format json', { cwd: fm.target }) const report = JSON.parse(stdout || '{}') return Object.keys(report) .map(dep => { const { advisories } = report[dep] return Object.keys(advisories).map(adv => { const { cve, title, link } = advisories[adv] return { code: cve, offender: dep, description: title, mitigation: link } }) }) .reduce((flatmap, next) => flatmap.concat(next), []) .reduce((results, res) => results.high(res), new ModuleResults(key)) } } <|start_filename|>lib/exec.js<|end_filename|> 'use strict' const { spawn, spawnSync } = require('child_process') const commandExists = require('command-exists') const command = (command, options = {}) => new Promise(function (resolve, reject) { const [root, ...args] = (command instanceof Array) ? command : command.split(' ') let stdout = '' let stderr = '' const proc = spawn(root, args, options) if (proc.stdout) { // when stout is flagged 'ignored' in the options, proc.stdout is null proc.stdout.on('data', data => { stdout += data.toString() }) } proc.stderr.on('data', data => { stderr += data.toString() }) proc.on('error', err => { err.code = 255 err.stdout = stdout.trim() err.stderr = stderr.trim() reject(err) }) proc.on('exit', code => { resolve({ code, stdout: stdout.trim(), stderr: stderr.trim() }) }) }) const commandSync = (command, options = {}) => { const [root, ...args] = (command instanceof Array) ? command : command.split(' ') const cwd = options.cwd let { error, stdout, stderr, status: code } = spawnSync(root, args, { cwd }) stdout = (stdout || '').toString().trim() stderr = (stderr || '').toString().trim() if (error) { error.code = 255 error.stdout = stdout error.stderr = stderr throw error } return { code, stdout, stderr } } const exists = async cmd => { let hasCommand try { await commandExists(cmd) hasCommand = true } catch (e) { hasCommand = false } return hasCommand } module.exports = { command, commandSync, exists } <|start_filename|>lib/scan.js<|end_filename|> 'use strict' const FileManager = require('./file-manager') const modules = require('./modules') const logger = require('./logger') const _ = require('lodash') const { ScanResults } = require('./scan-results.js') require('colors') module.exports = async (rc = {}) => { logger.log('Target for scan:', rc.target) const fm = new FileManager(rc) const allModules = modules() const knownModules = _.isEqual(rc.modules, ['all']) ? allModules.filter(m => m.enabled) : allModules.filter(m => rc.modules.indexOf(m.key) > -1) const unknownModules = _.isEqual(rc.modules, ['all']) ? [] : _.difference(rc.modules, allModules.map(m => m.key)) unknownModules.forEach(key => logger.warn('Unknown module:'.bold, key)) if (!knownModules.length) { throw new Error('No available modules to scan with!') } const activeModules = [] const inactiveModules = [] for (const module of knownModules) { logger.log(`Checking ${module.key} for applicability`) const isActive = await module.handles(fm) ;(isActive ? activeModules : inactiveModules).push(module) } inactiveModules.forEach(module => logger.log('Skipping module'.bold, module.key)) if (!activeModules.length) { throw new Error('We found no modules that would run on the target folder') } const moduleResultsList = await activeModules .reduce((prom, { key, run }) => prom.then(async allRes => { logger.log('Running module'.bold, key) try { const res = await run(fm) return allRes.concat(res) } catch (e) { logger.error(key, 'returned an error!', e.message) return allRes } }), Promise.resolve([])) const scanResults = ScanResults.fromModuleResultsList(moduleResultsList) .allWithLevelAtLeast(rc.failOn) .filter(res => !rc.isExcluded(res.code)) .map(res => rc.showCode ? res : _.omit(res, ['code'])) logger.log(`Scan complete, ${scanResults.length} issues found`) for (const { key, write, opts } of rc.writers) { logger.log(`Writing to: ${key}`) await write(scanResults, opts) } return scanResults.length ? 1 : 0 } <|start_filename|>lib/modules/php-security-checker/__tests__/sample/composer.json<|end_filename|> { "name": "hawkeye/php", "description": "A sample PHP project for Hawkeye", "type": "project", "require": { "firebase/php-jwt": "1.0.0" } } <|start_filename|>lib/writers/__tests__/console-unit.js<|end_filename|> 'use strict' /* eslint-disable no-unused-expressions */ const { write } = require('../console') describe('Writer', () => { it('should write to console', async () => { sinon.stub(console, 'table') const payload = [{ module: 'files-ccnumber', level: 'critical', code: 'files-secrets-47', offender: 'testfile1.yml', description: 'Contains word: password', mitigation: 'Check contents of the file' }, { module: 'files-ccnumber', level: 'critical', code: 'files-secrets-47', offender: 'testfile2.yml', description: 'Contains word: password', mitigation: 'Check contents of the file' }, { module: 'files-contents', level: 'critical', code: 'files-contents-2', offender: 'testfile3.yml', description: 'Private key in file', mitigation: 'Check line number: 3' }] await write(payload) expect(console.table).to.have.been.calledOnce expect(console.table).to.have.been.calledWith(payload) }) }) <|start_filename|>lib/writers/__tests__/json-unit.js<|end_filename|> 'use strict' const { write } = require('../json') const path = require('path') const { readFileSync, unlinkSync } = require('fs') const metadata = { file: path.join(__dirname, 'testfile.json') } describe('JSON Writer', () => { it('should write JSON to a file', async () => { const findings = [{ key: 'value' }] const expected = JSON.stringify({ findings }) await write(findings, metadata) expect(readFileSync(metadata.file).toString()).to.equal(expected) unlinkSync(metadata.file) }) }) <|start_filename|>lib/__tests__/util-unit.js<|end_filename|> 'use strict' /* eslint-disable no-unused-expressions */ const util = require('../util') describe('Util', () => { describe('Null or Undefined', () => { it('should detect null', () => { expect(util.isEmpty(null)).to.equal(true) }) it('should detect undefined', () => { expect(util.isEmpty(undefined)).to.equal(true) }) it('should not false detect', () => { expect(util.isEmpty('')).to.equal(false) }) }) }) <|start_filename|>lib/modules/files-secrets/index.js<|end_filename|> 'use strict' const path = require('path') const items = require('./data') const ModuleResults = require('../../results') const key = __dirname.split(path.sep).pop() module.exports = { key, description: 'Scans for suspicious filenames that are likely to contain secrets', enabled: true, handles: () => true, run: fm => { const results = new ModuleResults(key) const checkers = items.map(item => { const matcher = (item.type === 'regex') ? makeRegexMatcher(item.pattern) : makeExactMatcher(item.pattern) return file => { const data = extractData(item.part, file) if (matcher(data)) { results[item.level]({ code: `${file}-${item.code}`, offender: file, description: item.caption, mitigation: item.description || 'Check contents of the file' }) } } }) fm.all().forEach(file => checkers.forEach(checker => checker(file))) return results } } const makeExactMatcher = pattern => file => file === pattern const makeRegexMatcher = pattern => file => !!pattern.exec(file) const extractData = (part, file) => { const filename = path.basename(file) const extension = filename.split('.').pop() switch (part) { case 'filename': return filename case 'extension': return extension case 'path': return file default: return '' } } <|start_filename|>lib/modules/rust-cargoaudit/__tests__/cargoaudit-unit.js<|end_filename|> 'use strict' const path = require('path') const { handles, run } = require('..') const exec = require('../../../exec') const FileManager = require('../../../file-manager') const auditReport = require('./sample/auditreport.json') const fs = require('fs') /* eslint-disable no-unused-expressions */ describe('cargo audit Module', () => { const targetWithLockFile = path.join(__dirname, 'sample', 'default') const targetNoLock = path.join(__dirname, 'sample', 'no-lock-file') let fmWithLockFile let fmNoLock function givenCargoInstalled () { sinon.stub(exec, 'exists').withArgs('cargo').resolves(true) } function givenCargoAuditReturnsReport (auditReport) { exec.command.withArgs('cargo audit --json').resolves({ stdout: JSON.stringify(auditReport) }) } function givenCargoCanGenerateLockFile () { exec.command.withArgs('cargo generate-lockfile').resolves({ stdout: '' }) } function givenModuleCanRemoveLockFile () { fs.unlinkSync.withArgs('Cargo.lock').returns(undefined) } beforeEach(() => { sinon.stub(exec, 'command') sinon.stub(fs, 'unlinkSync') givenCargoInstalled() fmWithLockFile = new FileManager({ target: targetWithLockFile }) fmNoLock = new FileManager({ target: targetNoLock }) }) it('should handle Rust projects with Cargo.lock file', async () => { expect(await handles(fmWithLockFile)).to.be.true }) it('should handle Rust projects with NO Cargo.lock file', async () => { expect(await handles(fmNoLock)).to.be.true }) it('should execute cargo generate-lockfile if no lock file present', async () => { givenCargoAuditReturnsReport(auditReport) givenCargoCanGenerateLockFile() givenModuleCanRemoveLockFile() await run(fmNoLock) expect(exec.command.withArgs('cargo generate-lockfile')).to.have.been.calledOnce }) it('should remove lock file after execution if no lock file present', async () => { givenCargoAuditReturnsReport(auditReport) givenCargoCanGenerateLockFile() givenModuleCanRemoveLockFile() await run(fmNoLock) expect(fs.unlinkSync.withArgs(path.join(fmNoLock.target, 'Cargo.lock'))).to.have.been.calledAfter(exec.command.withArgs('cargo audit --json')) }) it('should NOT remove lock file after execution if lock file IS present', async () => { givenCargoAuditReturnsReport(auditReport) givenModuleCanRemoveLockFile() await run(fmWithLockFile) expect(fs.unlinkSync.withArgs('Cargo.lock')).to.have.not.been.called }) it('should report critical severity vulnerabilities', async () => { givenCargoAuditReturnsReport(auditReport) const { results } = await run(fmWithLockFile) expect(results.critical).to.have.length(1) expect(results.critical[0]).to.deep.equal({ code: 'rust-cargoaudit-RUSTSEC-2018-0002', description: 'Links in archives can overwrite any existing file (https://github.com/alexcrichton/tar-rs/pull/156)', mitigation: 'Update "tar" crate to one of the following versions: >= 0.4.16', offender: 'tar=0.4.5' }) }) }) <|start_filename|>lib/writers/http.js<|end_filename|> 'use strict' const superagent = require('superagent') const key = 'writer-http' /** * * @param {Array} results Data that should be written to sumologic * @param {Object} metadata Specific information needed by this writer * @param {String} metadata.url The collector's url * @returns {Promise} Resolves when everything was be posted, throws otherwise */ const write = (results, metadata) => results .reduce((promise, result) => promise.then(() => superagent .post(metadata.url) .send(result) .set('User-Agent', 'hawkeye')), Promise.resolve()) module.exports = { key, write } <|start_filename|>lib/modules/files-secrets/__tests__/files-unit.js<|end_filename|> 'use strict' /* eslint-disable no-unused-expressions */ const path = require('path') const { handles, run } = require('..') const FileManager = require('../../../file-manager') describe('Files Module', () => { const target = path.join(__dirname, 'sample') let fm beforeEach(() => { fm = new FileManager({ target }) }) it('should handle anything', () => { expect(handles()).to.be.true }) it('should match RSA private keys', async () => { const results = await run(fm) expect(results.results.critical[0]).to.deep.equal({ code: 'files-secrets-some-file-with-private-key-in.asc-11', description: 'Potential cryptographic key bundle', mitigation: 'Check contents of the file', offender: 'some-file-with-private-key-in.asc' }) }) }) <|start_filename|>lib/modules/python-safety/__tests__/safety-unit.js<|end_filename|> 'use strict' /* eslint-disable no-unused-expressions */ const fs = require('fs') const path = require('path') const exec = require('../../../exec') const FileManager = require('../../../file-manager') const { handles, run } = require('..') const logger = require('../../../logger') describe('Python safety Module', () => { let fm const target = path.join(__dirname, 'sample') const sample = fs.readFileSync(path.join(__dirname, 'sample', 'safety.json'), 'utf-8') beforeEach(() => { sinon.stub(exec, 'exists').resolves(true) sinon.stub(exec, 'command').resolves({ stdout: sample }) fm = new FileManager({ target }) sinon.spy(logger, 'warn') }) it('should handle python projects', async () => { expect(await handles(fm)).to.be.true }) it('should not run on missing executable', async () => { exec.exists.resolves(false) expect(await handles(fm)).to.be.false }) it('should execute command', async () => { await run(fm) expect(exec.command).to.have.been.calledWith('safety check --json -r requirements.txt', { cwd: target }) }) it('should log unpinned dependencies', async () => { await run(fm) expect(logger.warn).to.have.been.calledThrice expect(logger.warn).to.have.been.calledWith('Warning: unpinned requirement \'requests\' found, unable to check.') expect(logger.warn).to.have.been.calledWith('Warning: unpinned requirement \'cryptography\' found, unable to check.') expect(logger.warn).to.have.been.calledWith('Warning: unpinned requirement \'django\' found, unable to check.') }) it('should log vulns as critical severity issues', async () => { const { results } = await run(fm) expect(results.critical).to.deep.equal([{ code: 'python-safety-25853', description: 'This is an insecure package with lots of exploitable security vulnerabilities.', mitigation: 'Versions <0.2.0 are vulnerable. Update to a non vulnerable version.', offender: 'insecure-package 0.1' }]) }) }) <|start_filename|>lib/modules/index.js<|end_filename|> 'use strict' const glob = require('glob') const path = require('path') module.exports = () => glob.sync(path.join(__dirname, '*', 'index.js')).map(require) <|start_filename|>lib/modules/python-bandit/index.js<|end_filename|> 'use strict' const path = require('path') const logger = require('../../logger') const ModuleResults = require('../../results') const _ = require('lodash') const exec = require('../../exec') const key = __dirname.split(path.sep).pop() module.exports = { key, description: 'Scans for common security issues in Python code with bandit.', enabled: true, handles: async fm => { const isPythonProject = fm.all().some(file => file.endsWith('.py')) const hasCommand = await exec.exists('bandit') if (isPythonProject && !hasCommand) { logger.warn('Python files were found but bandit was not found in $PATH') logger.warn(`${key} will not run unless you install bandit`) logger.warn('Please see: https://github.com/openstack/bandit') return false } return isPythonProject }, run: async fm => { let banditCommand = 'bandit -r . -f json' if (fm.excluded && fm.excluded.length > 0) { banditCommand = banditCommand + ' -x ' + fm.excluded } const { stdout } = await exec.command(banditCommand, { cwd: fm.target }) const report = JSON.parse(stdout || '{}') return _.get(report, 'results', []) .map(error => ({ code: error.test_id, offender: `${error.filename} lines ${error.line_range}`, description: `${error.test_name} ${error.test_id}`, mitigation: `${error.issue_text} Review the file and fix the issue.`, level: error.issue_severity.toLowerCase() })) .reduce((results, res) => results[res.level](res), new ModuleResults(key)) } } <|start_filename|>lib/util.js<|end_filename|> 'use strict' const fs = require('fs') const istext = require('istextorbinary') require('colors') module.exports = { isEmpty: function (value) { return (value === undefined || value === null) }, readFileSync: function (absolute) { const stat = fs.statSync(absolute) if (stat.size > 1000000) { console.warn(('[warn] File which exceeds 1MB limited detected: ' + absolute).yellow) return '' } const buffer = fs.readFileSync(absolute) if (!istext.isTextSync(absolute, buffer)) { console.warn(('[warn] Binary file detected when expected text: ' + absolute).yellow) return '' } const contents = buffer.toString().trim() return contents } } <|start_filename|>lib/modules/python-bandit/__tests__/bandit-unit.js<|end_filename|> 'use strict' /* eslint-disable no-unused-expressions */ const path = require('path') const FileManager = require('../../../file-manager') const exec = require('../../../exec') const { handles, run } = require('..') const sample = require('./sample/bandit.json') describe('Python Bandit Module', () => { let fm const target = path.join(__dirname, 'sample') beforeEach(() => { sinon.stub(exec, 'exists').resolves(true) sinon.stub(exec, 'command').resolves({ stdout: JSON.stringify(sample) }) fm = new FileManager({ target }) }) it('should handle python projects', async () => { expect(await handles(fm)).to.be.true }) it('should not run on missing executable', async () => { exec.exists.resolves(false) expect(await handles(fm)).to.be.false }) it('should execute bandit without excludes', async () => { await run(fm) expect(exec.command).to.have.been.calledWith('bandit -r . -f json', { cwd: target }) }) it('should execute bandit with excludes', async () => { const fm = new FileManager({ target, exclude: [/^ignoredir\//] }) await run(fm) expect(exec.command).to.have.been.calledWith('bandit -r . -f json -x ignoredir/bar.py,ignoredir/foo.py', { cwd: target }) }) it('should log high severity issues', async () => { const { results } = await run(fm) expect(results.high).to.deep.equal([{ code: 'python-bandit-B201', offender: 'app.py lines 43', description: 'flask_debug_true B201', mitigation: 'A Flask app appears to be run with debug=True, which exposes the Werkzeug debugger and allows the execution of arbitrary code. Review the file and fix the issue.' }]) }) it('should log low severity issues', async () => { const { results } = await run(fm) expect(results.low).to.deep.equal([{ code: 'python-bandit-B101', offender: 'somefile.py lines 186', description: 'assert_used B101', mitigation: 'Use of assert detected. The enclosed code will be removed when compiling to optimised byte code. Review the file and fix the issue.' }]) }) it('should log medium severity issues', async () => { const { results } = await run(fm) expect(results.medium).to.deep.equal([{ code: 'python-bandit-B104', offender: 'app.py lines 43', description: 'hardcoded_bind_all_interfaces B104', mitigation: 'Possible binding to all interfaces. Review the file and fix the issue.' }]) }) it('should log high severity issues', async () => { const { results } = await run(fm) expect(results.high).to.deep.equal([{ code: 'python-bandit-B201', offender: 'app.py lines 43', description: 'flask_debug_true B201', mitigation: 'A Flask app appears to be run with debug=True, which exposes the Werkzeug debugger and allows the execution of arbitrary code. Review the file and fix the issue.' }]) }) }) <|start_filename|>lib/modules/node-npmoutdated/__tests__/npmoutdated-unit.js<|end_filename|> 'use strict' /* eslint-disable no-unused-expressions */ const path = require('path') const { handles, run } = require('..') const exec = require('../../../exec') const FileManager = require('../../../file-manager') const report = require('./sample/outdatedreport.json') describe('npm outdated Module', () => { const target = path.join(__dirname, 'sample') let fm beforeEach(() => { sinon.stub(exec, 'exists').resolves(true) sinon.stub(exec, 'command').resolves({ stdout: JSON.stringify(report) }) fm = new FileManager({ target }) }) it('should handle node projects', async () => { expect(await handles(fm)).to.be.true }) it('should execute npm outdated --json', async () => { await run(fm) expect(exec.command).to.have.been.calledWith('npm outdated --json') }) it('should report low severity vulnerabilities', async () => { const { results } = await run(fm) expect(results.low).to.deep.equal([{ code: 'node-npmoutdated-crossenv-3', description: 'Module is one or more patch versions out of date', mitigation: 'Upgrade to v0.0.4 (Current: v0.0.2)', offender: 'crossenv' }]) }) it('should report medium severity vulnerabilities', async () => { const { results } = await run(fm) expect(results.medium).to.deep.equal([{ code: 'node-npmoutdated-mysqljs-2', description: 'Module is one or more minor versions out of date', mitigation: 'Upgrade to v0.1.0 (Current: v0.0.2)', offender: 'mysqljs' }]) }) it('should report high severity vulnerabilities', async () => { const { results } = await run(fm) expect(results.high).to.deep.equal([{ code: 'node-npmoutdated-async-1', description: 'Module is one or more major versions out of date', mitigation: 'Upgrade to v3.0.0 (Current: v2.1.2)', offender: 'async' }]) }) it('should not report when things are up to date', async () => { exec.command.resolves({ stdout: '' }) const { results } = await run(fm) expect(results.low).to.be.empty expect(results.medium).to.be.empty expect(results.high).to.be.empty expect(results.critical).to.be.empty }) }) <|start_filename|>lib/modules/ruby-bundler-scan/index.js<|end_filename|> 'use strict' const path = require('path') const fs = require('fs') const ModuleResults = require('../../results') const exec = require('../../exec') const logger = require('../../logger') const key = __dirname.split(path.sep).pop() module.exports = { key, description: 'Scan for Ruby gems with known vulnerabilities using bundler', enabled: true, handles: async fm => { const isRubyProject = fs.existsSync(path.join(fm.target, 'Gemfile.lock')) const hasCommand = await exec.exists('bundle-audit') if (isRubyProject && !hasCommand) { logger.warn('Gemfile.lock found but bundle-audit not found in $PATH') logger.warn(`${key} will not run unless you install bundle-audit`) logger.warn('Please see: https://github.com/rubysec/bundler-audit') return false } return isRubyProject }, run: async fm => { logger.log('Updating bundler-audit database...') const { stdout } = await exec.command('bundle-audit', { cwd: fm.target, shell: '/bin/bash' }) const regex = { name: /Name: /, title: /Title: /, criticality: /Criticality: /, extraInfo: /Solution: /, code: /Advisory: /, url: /URL: / } const insecureSourceMessage = 'Insecure Source URI' const results = new ModuleResults(key) const lines = stdout.split('\n') let vulnerability = {} lines.forEach(line => { for (const key of Object.keys(regex)) { const matchingLine = line.match(regex[key]) if (matchingLine) { vulnerability[key] = line.split(matchingLine)[1] } } if (Object.keys(vulnerability).length === 6) { const criticality = vulnerability.criticality.toLowerCase() const item = { code: vulnerability.code.toLowerCase(), offender: vulnerability.name, description: vulnerability.title, mitigation: vulnerability.url } ;(results[criticality] || results.low).bind(results)(item) vulnerability = {} } if (line.indexOf(insecureSourceMessage) > -1) { const item = { code: 1, offender: 'Gemfile', description: 'Insecure Source URI', mitigation: 'Use a https:// gem source' } results.low(item) } }) return results } } <|start_filename|>lib/scan-results.js<|end_filename|> const _ = require('lodash') const threshold = { low: 1, medium: 2, high: 3, critical: 4 } /** * @typedef ScanResult * @type {Object} * @property {String} module * @property {String} level * @property {String} code * @property {String} offender * @property {String} description * @property {String} mitigation */ class ScanResults { /** * @param {Array} results */ constructor (results) { this.results = results } /** * @param {ModuleResult[]} moduleResultList * @return {ScanResults} */ static fromModuleResultsList (moduleResultList) { const results = moduleResultList .map(({ key, data }) => { const result = [] for (const level in threshold) { data[level].forEach(item => { const filteredItem = _.pick(item, ['code', 'offender', 'description', 'mitigation']) result.push({ module: key, level, ...filteredItem }) }) } return result }) return new ScanResults(_.flatMap(results)) } /** * @param {string} level * @return {ScanResult[]} */ allWithLevelAtLeast (level) { return this.results.filter(r => { return threshold[r.level] >= threshold[level] }) } } module.exports = { ScanResults }
derwent-m/scanner-cli
<|start_filename|>cmd/ipod/general.go<|end_filename|> package main import ( "bytes" "fmt" "github.com/davecgh/go-spew/spew" "github.com/oandrew/ipod" general "github.com/oandrew/ipod/lingo-general" "github.com/fullsailor/pkcs7" ) type DevGeneral struct { uimode general.UIMode tokens []general.FIDTokenValue } var _ general.DeviceGeneral = &DevGeneral{} func (d *DevGeneral) UIMode() general.UIMode { return d.uimode } func (d *DevGeneral) SetUIMode(mode general.UIMode) { d.uimode = mode } func (d *DevGeneral) Name() string { return "ipod-gadget" } func (d *DevGeneral) SoftwareVersion() (major uint8, minor uint8, rev uint8) { return 7, 1, 2 } func (d *DevGeneral) SerialNum() string { return "abcd1234" } func (d *DevGeneral) LingoProtocolVersion(lingo uint8) (major uint8, minor uint8) { switch lingo { case ipod.LingoGeneralID: return 1, 9 case ipod.LingoDisplayRemoteID: return 1, 5 case ipod.LingoExtRemoteID: return 1, 12 case ipod.LingoDigitalAudioID: return 1, 2 default: return 1, 1 } } func (d *DevGeneral) LingoOptions(lingo uint8) uint64 { switch lingo { case ipod.LingoGeneralID: return 0x000000063DEF73FF default: return 0 } } func (d *DevGeneral) PrefSettingID(classID uint8) uint8 { return 0 } func (d *DevGeneral) SetPrefSettingID(classID uint8, settingID uint8, restoreOnExit bool) { } func (d *DevGeneral) SetEventNotificationMask(mask uint64) { } func (d *DevGeneral) EventNotificationMask() uint64 { return 0 } func (d *DevGeneral) SupportedEventNotificationMask() uint64 { return 0 } func (d *DevGeneral) CancelCommand(lingo uint8, cmd uint16, transaction uint16) { } func (d *DevGeneral) MaxPayload() uint16 { return 65535 } func (d *DevGeneral) StartIDPS() { d.tokens = make([]general.FIDTokenValue, 0) } func (d *DevGeneral) SetToken(token general.FIDTokenValue) error { d.tokens = append(d.tokens, token) return nil } func (d *DevGeneral) EndIDPS(status general.AccEndIDPSStatus) { var buf bytes.Buffer fmt.Fprintf(&buf, "Tokens:\n") for _, token := range d.tokens { fmt.Fprintf(&buf, "* Token: %T\n", token.Token) //log.Printf("New token: %T", token.Token) switch t := token.Token.(type) { case *general.FIDIdentifyToken: case *general.FIDAccCapsToken: for _, c := range general.AccCaps { if t.AccCapsBitmask&uint64(c) != 0 { fmt.Fprintf(&buf, "Capability: %v\n", c) } } case *general.FIDAccInfoToken: key := general.AccInfoType(t.AccInfoType).String() fmt.Fprintf(&buf, "%s: %s\n", key, spew.Sdump(t.Value)) case *general.FIDiPodPreferenceToken: case *general.FIDEAProtocolToken: case *general.FIDBundleSeedIDPrefToken: case *general.FIDScreenInfoToken: case *general.FIDEAProtocolMetadataToken: case *general.FIDMicrophoneCapsToken: } } log.Print(buf.String()) } func (d *DevGeneral) AccAuthCert(cert []byte) { pkcs, err := pkcs7.Parse(cert) if err != nil { log.Error(err) return } if len(pkcs.Certificates) >= 1 { cn := pkcs.Certificates[0].Subject.CommonName log.Infof("cert: CN=%s", cn) } } <|start_filename|>cmd_test.go<|end_filename|> package ipod_test import ( "bytes" "encoding/binary" "reflect" "testing" "github.com/oandrew/ipod" audio "github.com/oandrew/ipod/lingo-audio" ) type CustomPayload struct { V uint32 } var TestLingoID uint8 = 0xaa var TestLingos struct { CustomPayload `id:"0x01"` } func (p *CustomPayload) UnmarshalBinary(data []byte) error { return binary.Read(bytes.NewReader(data), binary.BigEndian, &p.V) } func (p *CustomPayload) MarshalBinary() ([]byte, error) { buf := bytes.Buffer{} err := binary.Write(&buf, binary.BigEndian, p.V) return buf.Bytes(), err } func TestCommand_MarshalBinary(t *testing.T) { tests := []struct { name string cmd ipod.Command want []byte wantErr bool }{ {"no-tr-no-payload", ipod.Command{ipod.NewLingoCmdID(0x01, 0x01), nil, nil}, nil, true}, {"no-tr-with-simple-payload", ipod.Command{ipod.NewLingoCmdID(0x01, 0x02), nil, uint32(0x03)}, []byte{0x01, 0x02, 0x00, 0x00, 0x00, 0x03}, false}, {"no-tr-with-custom-payload", ipod.Command{ipod.NewLingoCmdID(0x01, 0x02), nil, &CustomPayload{0x03}}, []byte{0x01, 0x02, 0x00, 0x00, 0x00, 0x03}, false}, {"with-tr-with-simple-payload", ipod.Command{ipod.NewLingoCmdID(0x01, 0x02), ipod.NewTransaction(0x01), uint32(0x03)}, []byte{0x01, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x03}, false}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { serde := ipod.CommandSerde{ TrxEnabled: tt.cmd.Transaction != nil, } got, err := serde.MarshalCmd(&tt.cmd) if (err != nil) != tt.wantErr { t.Errorf("Command.MarshalBinary() error = %v, wantErr %v", err, tt.wantErr) return } if !reflect.DeepEqual(got, tt.want) { t.Errorf("Command.MarshalBinary() = %v, want %v", got, tt.want) } }) } } func TestCommand_UnmarshalBinary(t *testing.T) { ipod.RegisterLingos(TestLingoID, TestLingos) tests := []struct { name string data []byte want ipod.Command wantErr bool }{ {"no-tr-unknown-payload", []byte{0xee, 0x01}, ipod.Command{ipod.NewLingoCmdID(0xee, 0x01), nil, ipod.UnknownPayload{}}, true}, {"with-tr-unknown-payload", []byte{0xee, 0x01, 0x00, 0x03}, ipod.Command{ipod.NewLingoCmdID(0xee, 0x01), nil, ipod.UnknownPayload{0x00, 0x03}}, true}, {"no-tr-known-payload", []byte{0xaa, 0x01, 0x00, 0x00, 0x00, 0x03}, ipod.Command{ipod.NewLingoCmdID(0xaa, 0x01), nil, &CustomPayload{V: 0x03}}, false}, {"with-tr-known-payload", []byte{0xaa, 0x01, 0x00, 0x02, 0x00, 0x00, 0x00, 0x03}, ipod.Command{ipod.NewLingoCmdID(0xaa, 0x01), ipod.NewTransaction(0x02), &CustomPayload{V: 0x03}}, false}, {"no-tr-known-payload-short", []byte{0xaa, 0x01, 0x00, 0x00, 0x03}, ipod.Command{ipod.NewLingoCmdID(0xaa, 0x01), ipod.NewTransaction(0x00), nil}, true}, {"with-tr-known-payload-short", []byte{0xaa, 0x01, 0x00, 0x02, 0x00, 0x00, 0x03}, ipod.Command{ipod.NewLingoCmdID(0xaa, 0x01), ipod.NewTransaction(0x02), nil}, true}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { serde := ipod.CommandSerde{ TrxEnabled: tt.want.Transaction != nil, } got, err := serde.UnmarshalCmd(tt.data) if (err != nil) != tt.wantErr { t.Errorf("Command.UnmarshalBinary() error = %v, wantErr %v", err, tt.wantErr) } if !reflect.DeepEqual(got, &tt.want) { t.Errorf("Command.UnmarshalBinary() = %v, want %v", got, &tt.want) } }) } } func BenchmarkCommand_MarshalBinary(b *testing.B) { serde := ipod.CommandSerde{} cmd := ipod.Command{ ID: ipod.NewLingoCmdID(0x0a, 0x03), Transaction: ipod.NewTransaction(0x03e7), Payload: audio.RetAccSampleRateCaps{ SampleRates: []uint32{8000, 11025, 12000, 16000, 22050, 24000, 32000, 44100, 48000}, }, } for i := 0; i < b.N; i++ { serde.MarshalCmd(&cmd) } } func BenchmarkCommand_UnmarshalBinary(b *testing.B) { serde := ipod.CommandSerde{} packet := []byte{ 0x0a, 0x03, 0x03, 0xe7, 0x00, 0x00, 0x1f, 0x40, 0x00, 0x00, 0x2b, 0x11, 0x00, 0x00, 0x2e, 0xe0, 0x00, 0x00, 0x3e, 0x80, 0x00, 0x00, 0x56, 0x22, 0x00, 0x00, 0x5d, 0xc0, 0x00, 0x00, 0x7d, 0x00, 0x00, 0x00, 0xac, 0x44, 0x00, 0x00, 0xbb, 0x80, } for i := 0; i < b.N; i++ { serde.UnmarshalCmd(packet) } } <|start_filename|>cmd/ipod/formatter.go<|end_filename|> package main import ( "bytes" "fmt" "io" "os" "sort" "strings" "time" "github.com/sirupsen/logrus" "golang.org/x/crypto/ssh/terminal" ) const ( nocolor = 0 red = 31 green = 32 yellow = 33 blue = 36 gray = 37 ) var ( baseTimestamp time.Time ) func init() { baseTimestamp = time.Now() } func checkIfTerminal(w io.Writer) bool { switch v := w.(type) { case *os.File: return terminal.IsTerminal(int(v.Fd())) default: return false } } type TextFormatter struct { Colored bool } func (f *TextFormatter) Format(entry *logrus.Entry) ([]byte, error) { var b *bytes.Buffer keys := make([]string, 0, len(entry.Data)) for k := range entry.Data { keys = append(keys, k) } sort.Strings(keys) if entry.Buffer != nil { b = entry.Buffer } else { b = &bytes.Buffer{} } f.print(b, entry, keys) b.WriteByte('\n') return b.Bytes(), nil } func (f *TextFormatter) colored() bool { return f.Colored } func (f *TextFormatter) print(b *bytes.Buffer, entry *logrus.Entry, keys []string) { levelText := strings.ToUpper(entry.Level.String())[0:4] ts := entry.Time.Sub(baseTimestamp) tsText := fmt.Sprintf("%04d.%06d", ts/time.Second, (ts%time.Second)/time.Microsecond) if f.colored() { var levelColor int switch entry.Level { case logrus.DebugLevel: levelColor = gray case logrus.WarnLevel: levelColor = yellow case logrus.ErrorLevel, logrus.FatalLevel, logrus.PanicLevel: levelColor = red default: levelColor = blue } fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m[%s] %-44s ", levelColor, levelText, tsText, entry.Message) for _, k := range keys { v := entry.Data[k] fmt.Fprintf(b, " \x1b[%dm%s\x1b[0m=%v", levelColor, k, v) } } else { fmt.Fprintf(b, "%s[%s] %-44s ", levelText, tsText, entry.Message) for _, k := range keys { v := entry.Data[k] fmt.Fprintf(b, " %s=%v", k, v) } } } <|start_filename|>cmd/ipod/main.go<|end_filename|> package main import ( "fmt" "io" "io/ioutil" "time" "os" "github.com/davecgh/go-spew/spew" "github.com/sirupsen/logrus" "github.com/urfave/cli" "github.com/oandrew/ipod" "github.com/oandrew/ipod/hid" audio "github.com/oandrew/ipod/lingo-audio" dispremote "github.com/oandrew/ipod/lingo-dispremote" extremote "github.com/oandrew/ipod/lingo-extremote" general "github.com/oandrew/ipod/lingo-general" _ "github.com/oandrew/ipod/lingo-simpleremote" "github.com/oandrew/ipod/trace" ) var log = logrus.StandardLogger() func openDevice(path string) (*os.File, error) { f, err := os.OpenFile(path, os.O_RDWR, os.ModePerm) if err != nil { return nil, err } stat, _ := f.Stat() if stat.Mode()&os.ModeCharDevice != os.ModeCharDevice { return nil, fmt.Errorf("not a char device") } return f, nil } func openTraceFile(path string) (*os.File, error) { f, err := os.Open(path) if err != nil { return nil, err } return f, nil } func newTraceFile(path string) (*os.File, error) { return os.OpenFile(path, os.O_RDWR|os.O_CREATE, os.ModePerm) } type UsageError struct { error } var hidReportDefs = hid.DefaultReportDefs func main() { logOut := os.Stdout log.Formatter = &TextFormatter{ Colored: checkIfTerminal(logOut), } log.Out = logOut spew.Config.DisablePointerAddresses = true app := cli.NewApp() app.Name = "ipod" app.Authors = []cli.Author{ cli.Author{ Name: "<NAME>", }, } app.Usage = "ipod accessory protocol client" app.HideVersion = true app.ErrWriter = os.Stderr app.Flags = []cli.Flag{ cli.BoolFlag{ Name: "debug, d", Usage: "verbose logging", }, cli.BoolFlag{ Name: "legacy, l", Usage: "use legacy hid descriptor", }, } app.ExitErrHandler = func(c *cli.Context, err error) { if err != nil { if _, ok := err.(UsageError); ok { fmt.Fprintf(c.App.ErrWriter, "usage error: %v\n\n", err) cli.ShowCommandHelp(c, c.Command.Name) } else { fmt.Fprintf(c.App.ErrWriter, "error: %v\n\n", err) } os.Exit(1) } } app.Before = func(c *cli.Context) error { if c.GlobalBool("debug") { log.SetLevel(logrus.DebugLevel) } if c.GlobalBool("legacy") { hidReportDefs = hid.LegacyReportDefs } return nil } app.Commands = []cli.Command{ { Name: "lingos", Usage: "print all lingos/commands/ids", Action: func(c *cli.Context) error { fmt.Println("Registered lingos:") fmt.Println(ipod.DumpLingos()) return nil }, }, { Name: "serve", Aliases: []string{"s"}, ArgsUsage: "<dev>", Usage: "respond to requests from a char device i.e. /dev/iap0", Flags: []cli.Flag{ cli.StringFlag{ Name: "write-trace, w", Usage: "Write trace to a `file`", }, }, Action: func(c *cli.Context) error { path := c.Args().First() if path == "" { return UsageError{fmt.Errorf("device path is missing")} } f, err := openDevice(path) le := log.WithField("path", path) if err != nil { le.WithError(err).Errorf("could not open the device") return err } le.Info("device opened") var rw io.ReadWriter = f if tracePath := c.String("write-trace"); tracePath != "" { traceFile, err := newTraceFile(tracePath) le := log.WithField("path", tracePath) if err != nil { le.WithError(err).Errorf("could not create a trace file") return err } le.Warningf("writing trace") rw = trace.NewTracer(traceFile, f) } reportR, reportW := hid.NewReportReader(rw), hid.NewReportWriter(rw) frameTransport := hid.NewTransport(reportR, reportW, hidReportDefs) processFrames(frameTransport) return nil }, }, { Name: "replay", Aliases: []string{"r"}, Usage: "respond to requests from a trace file", Action: func(c *cli.Context) error { path := c.Args().First() if path == "" { return UsageError{cli.NewExitError("trace file path is missing", 1)} } f, err := openTraceFile(path) le := log.WithField("path", path) if err != nil { le.WithError(err).Errorf("could not open the trace file") return err } le.Warningf("trace file opened") tr := trace.NewReader(f) tdr := trace.NewTraceDirReader(tr, trace.DirIn) reportR, reportW := hid.NewReportReader(tdr), hid.NewReportWriter(ioutil.Discard) frameTransport := hid.NewTransport(reportR, reportW, hidReportDefs) processFrames(frameTransport) return nil }, }, { Name: "view", Aliases: []string{"v"}, Usage: "view a trace file", Action: func(c *cli.Context) error { path := c.Args().First() if path == "" { return UsageError{cli.NewExitError("trace file path is missing", 1)} } f, err := openTraceFile(path) le := log.WithField("path", path) if err != nil { le.WithError(err).Errorf("could not open the trace file") return err } le.Warningf("trace file opened") tr := trace.NewReader(f) dumpTrace(tr) return nil }, }, { Name: "send", Flags: []cli.Flag{ cli.StringFlag{ Name: "write-trace, w", Usage: "Write trace to a `file`", }, }, Usage: "acc mode / send accessory requests from a trace file", Action: func(c *cli.Context) error { path := c.Args().Get(0) if path == "" { return UsageError{fmt.Errorf("device path is missing")} } f, err := openDevice(path) le := log.WithField("path", path) if err != nil { le.WithError(err).Errorf("could not open the device") return err } le.Info("device opened") tpath := c.Args().Get(1) if tpath == "" { return UsageError{cli.NewExitError("trace file path is missing", 1)} } tf, err := openTraceFile(tpath) tle := log.WithField("path", tpath) if err != nil { tle.WithError(err).Errorf("could not open the trace file") return err } tle.Warningf("trace file opened") tr := trace.NewReader(tf) tdr := trace.NewTraceDirReader(tr, trace.DirIn) var rw io.ReadWriter = f if tracePath := c.String("write-trace"); tracePath != "" { traceFile, err := newTraceFile(tracePath) le := log.WithField("path", tracePath) if err != nil { le.WithError(err).Errorf("could not create a trace file") return err } le.Warningf("writing trace") rw = trace.NewTracer(traceFile, f) } reportR, reportW := hid.NewReportReader(rw), hid.NewReportWriter(rw) dummyW := hid.NewReportWriter(ioutil.Discard) traceR := hid.NewReportReader(tdr) frameTransport := hid.NewTransport(reportR, dummyW, hidReportDefs) go processFrames(frameTransport) for { report, err := traceR.ReadReport() if err != nil { break } reportW.WriteReport(report) log.Infof("writing report\n%s", spew.Sdump(report)) time.Sleep(1000 * time.Millisecond) } select {} return nil }, }, } app.Setup() app.Run(os.Args) } func logFrame(frame []byte, err error, msg string) { le := FrameLogEntry(logrus.NewEntry(log), frame) if err != nil { le.WithError(err).Errorf(msg) return } le.Infof(msg) if log.Level == logrus.DebugLevel { spew.Fdump(log.Out, frame) } } func logPacket(pkt []byte, err error, msg string) { //le := PacketLogEntry(logrus.NewEntry(log), frame) le := log.WithField("len", len(pkt)) if err != nil { le.WithError(err).Errorf(msg) return } le.Infof(msg) if log.Level == logrus.DebugLevel { spew.Fdump(log.Out, pkt) } } func logCmd(cmd *ipod.Command, err error, msg string) { le := CommandLogEntry(logrus.NewEntry(log), cmd) if err != nil { le.WithError(err).Errorf(msg) return } le.Infof(msg) if log.Level == logrus.DebugLevel { spew.Fdump(log.Out, cmd) } } func processFrames(frameTransport ipod.FrameReadWriter) { serde := ipod.CommandSerde{} for { inFrame, err := frameTransport.ReadFrame() if err == io.EOF { break } logFrame(inFrame, err, "<< FRAME") if err != nil { continue } packetReader := ipod.NewPacketReader(inFrame) inCmdBuf := ipod.CmdBuffer{} for { inPacket, err := packetReader.ReadPacket() if err == io.EOF { break } logPacket(inPacket, err, "<< PACKET") if err != nil { continue } inCmd, err := serde.UnmarshalCmd(inPacket) logCmd(inCmd, err, "<< CMD") inCmdBuf.WriteCommand(inCmd) } outCmdBuf := ipod.CmdBuffer{} for i := range inCmdBuf.Commands { //todo: check return error handlePacket(&outCmdBuf, inCmdBuf.Commands[i]) } for i := range outCmdBuf.Commands { outCmd := outCmdBuf.Commands[i] logCmd(outCmd, nil, ">> CMD") outPacket, err := serde.MarshalCmd(outCmd) logPacket(outPacket, err, ">> PACKET") packetWriter := ipod.NewPacketWriter() packetWriter.WritePacket(outPacket) outFrame := packetWriter.Bytes() outFrameErr := frameTransport.WriteFrame(outFrame) logFrame(outFrame, outFrameErr, ">> FRAME") } } log.Warnf("EOF") } var devGeneral = &DevGeneral{} func handlePacket(cmdWriter ipod.CommandWriter, cmd *ipod.Command) { switch cmd.ID.LingoID() { case ipod.LingoGeneralID: if auth, ok := cmd.Payload.(*general.RetDevAuthenticationInfo); ok { if auth.Major >= 2 && auth.CertCurrentSection >= auth.CertMaxSection || auth.Major < 2 { audio.Start(cmdWriter) } } general.HandleGeneral(cmd, cmdWriter, devGeneral) case ipod.LingoSimpleRemoteID: //todo log.Warn("Lingo SimpleRemote is not supported yet") case ipod.LingoDisplayRemoteID: dispremote.HandleDispRemote(cmd, cmdWriter, nil) case ipod.LingoExtRemoteID: extremote.HandleExtRemote(cmd, cmdWriter, nil) case ipod.LingoDigitalAudioID: audio.HandleAudio(cmd, cmdWriter, nil) } } func dirPrefix(dir trace.Dir, text string) string { switch dir { case trace.DirIn: return "<< " + text case trace.DirOut: return ">> " + text default: return "?? " + text } } func dumpTrace(tr *trace.Reader) { q := trace.Queue{} for { var msg trace.Msg err := tr.ReadMsg(&msg) if err == io.EOF { break } if err != nil { log.Fatal(err) } q.Enqueue(&msg) } serde := ipod.CommandSerde{} for { head := q.Head() if head == nil { break } dir := head.Dir tdr := trace.NewQueueDirReader(&q, dir) d := hid.NewDecoder(hid.NewReportReader(tdr), hidReportDefs) frame, err := d.ReadFrame() if err == io.EOF { break } logFrame(frame, err, dirPrefix(dir, "FRAME")) if err != nil { continue } packetReader := ipod.NewPacketReader(frame) for { packet, err := packetReader.ReadPacket() if err == io.EOF { break } logPacket(packet, err, dirPrefix(dir, "PACKET")) if err != nil { continue } cmd, err := serde.UnmarshalCmd(packet) logCmd(cmd, err, dirPrefix(dir, "CMD")) } } log.Warnf("EOF") } <|start_filename|>lingo-audio/handler.go<|end_filename|> package audio import ( "github.com/oandrew/ipod" ) type DeviceAudio interface { } // func ackSuccess(req ipod.Packet) ACK { // return ACK{Status: ACKStatusSuccess, CmdID: uint8(req.ID.CmdID())} // } // func ackPending(req ipod.Packet, maxWait uint32) ACKPending { // return ACKPending{Status: ACKStatusPending, CmdID: uint8(req.ID.CmdID()), MaxWait: maxWait} // } func Start(tr ipod.CommandWriter) { ipod.Send(tr, &GetAccSampleRateCaps{}) } func HandleAudio(req *ipod.Command, tr ipod.CommandWriter, dev DeviceAudio) error { switch msg := req.Payload.(type) { case *AccAck: case *RetAccSampleRateCaps: ipod.Respond(req, tr, &TrackNewAudioAttributes{ SampleRate: 44100, }) default: _ = msg } return nil } <|start_filename|>cmd.go<|end_filename|> package ipod import ( "bytes" "encoding" "encoding/binary" "errors" "fmt" "sync/atomic" "log" "github.com/sirupsen/logrus" ) // UnknownPayload is a payload that represents an unknown command type UnknownPayload []byte type CommandReader interface { ReadCommand() (*Command, error) } type CommandWriter interface { WriteCommand(*Command) error } // Command represents iap packet payload type Command struct { ID LingoCmdID //Optional Transaction *Transaction Payload interface{} } type Transaction uint16 func NewTransaction(t uint16) *Transaction { tr := Transaction(t) return &tr } func (tr Transaction) GoString() string { return fmt.Sprintf("%#04x", tr) } func (tr Transaction) String() string { return fmt.Sprintf("%#04x", uint16(tr)) } func (tr *Transaction) Copy() *Transaction { if tr != nil { ctr := Transaction(*tr) return &ctr } return nil } func (tr *Transaction) Delta(d int) *Transaction { if tr != nil { return NewTransaction(uint16(int(*tr) + d)) } return nil } type CommandSerde struct { TrxEnabled bool } func (s *CommandSerde) handleCmdID(cmdID LingoCmdID) { prev := s.TrxEnabled switch cmdID { // RequestIdentify case NewLingoCmdID(LingoGeneralID, 0x00): s.TrxEnabled = false // IdentifyDeviceLingoes case NewLingoCmdID(LingoGeneralID, 0x13): s.TrxEnabled = false // StartIDPS case NewLingoCmdID(LingoGeneralID, 0x38): s.TrxEnabled = true } if prev != s.TrxEnabled { if s.TrxEnabled { logrus.Warn("Enabling transaction support") } else { logrus.Warn("Disabling transaction support") } } } func (s *CommandSerde) MarshalCmd(cmd *Command) ([]byte, error) { pktBuf := &bytes.Buffer{} if err := marshalLingoCmdID(pktBuf, cmd.ID); err != nil { return nil, fmt.Errorf("ipod.Command marshal: %v", err) } s.handleCmdID(cmd.ID) if s.TrxEnabled && cmd.Transaction != nil { binary.Write(pktBuf, binary.BigEndian, *cmd.Transaction) } if cmd.Payload == nil { return nil, fmt.Errorf("ipod.Command marshal: nil payload") } if d, ok := cmd.Payload.(encoding.BinaryMarshaler); ok { payload, err := d.MarshalBinary() if err != nil { return nil, fmt.Errorf("ipod.Command marshal: BinaryMarshaler: %v", err) } pktBuf.Write(payload) } else { err := binary.Write(pktBuf, binary.BigEndian, cmd.Payload) if err != nil { return nil, fmt.Errorf("ipod.Command marshal: binary.Write: %v", err) } } return pktBuf.Bytes(), nil } func (s *CommandSerde) UnmarshalCmd(pkt []byte) (*Command, error) { var cmd Command pktBuf := bytes.NewBuffer(pkt) if err := unmarshalLingoCmdID(pktBuf, &cmd.ID); err != nil { return &cmd, fmt.Errorf("ipod.Command unmarshal: %v", err) } s.handleCmdID(cmd.ID) lookup, ok := Lookup(cmd.ID, pktBuf.Len(), s.TrxEnabled) if !ok { cmd.Payload = UnknownPayload(pktBuf.Bytes()) return &cmd, fmt.Errorf("ipod.Command unmarshal: unknown cmd %v", cmd.ID) } if lookup.Transaction { var tr Transaction err := binary.Read(pktBuf, binary.BigEndian, &tr) if err != nil { return &cmd, err } cmd.Transaction = &tr } if d, ok := lookup.Payload.(encoding.BinaryUnmarshaler); ok { err := d.UnmarshalBinary(pktBuf.Bytes()) if err != nil { return &cmd, fmt.Errorf("ipod.Command unmarshal: BinaryUnmarshaler: %v", err) } } else { err := binary.Read(pktBuf, binary.BigEndian, lookup.Payload) if err != nil { return &cmd, fmt.Errorf("ipod.Command unmarshal: binary.Read: %v", err) } } //cmd.Payload = reflect.Indirect(reflect.ValueOf(lookup.Payload)).Interface() cmd.Payload = lookup.Payload return &cmd, nil } func BuildCommand(payload interface{}) (*Command, error) { id, ok := LookupID(payload) if !ok { return nil, errors.New("payload not known") } return &Command{ ID: id, Payload: payload, }, nil } func Respond(req *Command, pw CommandWriter, payload interface{}) { cmd, err := BuildCommand(payload) if err != nil { log.Printf("BuildCommand err: %v", err) return } cmd.Transaction = req.Transaction.Copy() pw.WriteCommand(cmd) } var trxCounter uint32 func TrxReset() { atomic.StoreUint32(&trxCounter, 0) } func TrxNext() *Transaction { trx := atomic.AddUint32(&trxCounter, 1) return NewTransaction(uint16(trx)) } func Send(pw CommandWriter, payload interface{}) { cmd, err := BuildCommand(payload) if err != nil { return } cmd.Transaction = TrxNext() pw.WriteCommand(cmd) } type CmdBuffer struct { Commands []*Command } func (cbuf *CmdBuffer) WriteCommand(cmd *Command) error { cbuf.Commands = append(cbuf.Commands, cmd) return nil } <|start_filename|>lingo-dispremote/dispremote.go<|end_filename|> package dispremote import ( "bytes" "encoding/binary" "errors" "github.com/oandrew/ipod" ) func init() { ipod.RegisterLingos(ipod.LingoDisplayRemoteID, Lingos) } var Lingos struct { ACK `id:"0x00"` GetCurrentEQProfileIndex `id:"0x01"` RetCurrentEQProfileIndex `id:"0x02"` SetCurrentEQProfileIndex `id:"0x03"` GetNumEQProfiles `id:"0x04"` RetNumEQProfiles `id:"0x05"` GetIndexedEQProfileName `id:"0x06"` RetIndexedEQProfileName `id:"0x07"` SetRemoteEventNotification `id:"0x08"` RemoteEventNotification `id:"0x09"` GetRemoteEventStatus `id:"0x0A"` RetRemoteEventStatus `id:"0x0B"` GetiPodStateInfo `id:"0x0C"` RetiPodStateInfo `id:"0x0D"` SetiPodStateInfo `id:"0x0E"` GetPlayStatus `id:"0x0F"` RetPlayStatus `id:"0x10"` SetCurrentPlayingTrack `id:"0x11"` GetIndexedPlayingTrackInfo `id:"0x12"` RetIndexedPlayingTrackInfo `id:"0x13"` GetNumPlayingTracks `id:"0x14"` RetNumPlayingTracks `id:"0x15"` GetArtworkFormats `id:"0x16"` RetArtworkFormats `id:"0x17"` GetTrackArtworkData `id:"0x18"` RetTrackArtworkData `id:"0x19"` GetPowerBatteryState `id:"0x1A"` RetPowerBatteryState `id:"0x1B"` GetSoundCheckState `id:"0x1C"` RetSoundCheckState `id:"0x1D"` SetSoundCheckState `id:"0x1E"` GetTrackArtworkTimes `id:"0x1F"` RetTrackArtworkTimes `id:"0x20"` } type ACKStatus uint8 const ( ACKStatusSuccess ACKStatus = 0x00 ACKStatusPending ACKStatus = 0x06 ) type ACK struct { Status ACKStatus CmdID uint8 } type GetCurrentEQProfileIndex struct { } type RetCurrentEQProfileIndex struct { CurrentEQIndex uint32 } type SetCurrentEQProfileIndex struct { CurrentEQIndex uint32 RestoreOnExit bool } type GetNumEQProfiles struct { } type RetNumEQProfiles struct { NumEQProfiles uint32 } type GetIndexedEQProfileName struct { EQProfileIndex uint32 } type RetIndexedEQProfileName struct { EQProfileName []byte } type SetRemoteEventNotification struct { EventMask uint32 } type RemoteEventNotification struct { EventNum byte EventData []byte } type GetRemoteEventStatus struct { } type RetRemoteEventStatus struct { EventStatus uint32 } //go:generate stringer -type=InfoType type InfoType uint8 const ( InfoTypeTrackPositionMs InfoType = iota InfoTypeTrackIndex InfoTypeChapterIndex InfoTypePlayStatus InfoTypeVolume InfoTypePower InfoTypeEqualizer InfoTypeShuffle InfoTypeRepeat InfoTypeDateTime _ //InfoTypeAlarm InfoTypeBacklight InfoTypeHoldSwitch InfoTypeSoundCheck InfoTypeAudiobookSpeed InfoTypeTrackPositionSec InfoTypeVolume2 ) type InfoTrackPositionMs struct { TrackPositionMs uint32 } type InfoTrackIndex struct { TrackIndex uint32 } type InfoChapterIndex struct { TrackIndex uint32 ChapterCount uint16 ChapterIndex uint16 } //go:generate stringer -type=PlayStatusType type PlayStatusType uint8 const ( PlayStatusStopped PlayStatusType = iota PlayStatusPlaying PlayStatusPaused PlayStatusFF PlayStatusREW PlayStatusEndFFREW ) type InfoPlayStatus struct { PlayStatus PlayStatusType } type InfoVolume struct { MuteState uint8 UIVolumeLevel uint8 } type InfoPower struct { PowerState uint8 BatteryLevel uint8 } type InfoEqualizer struct { EqIndex uint32 } type InfoShuffle struct { ShuffleState uint8 } type InfoRepeat struct { RepeatState uint8 } type InfoDateTime struct { Year uint16 Month uint8 Day uint8 Hour uint8 Minute uint8 } type InfoBacklight struct { BacklightLevel uint8 } type InfoHoldSwitch struct { HoldSwitchState uint8 } type InfoSoundCheck struct { SoundCheckState uint8 } type InfoAudiobookSpeed struct { PlaybackSpeed uint8 } type InfoTrackPositionSec struct { TrackPositionSec uint16 } type InfoVolume2 struct { MuteState uint8 UIVolumeLevel uint8 AbsoluteVolumeLevel uint8 } type GetiPodStateInfo struct { InfoType InfoType } type RetiPodStateInfo struct { InfoType InfoType InfoData interface{} } func (t *RetiPodStateInfo) MarshalBinary() ([]byte, error) { buf := bytes.Buffer{} binary.Write(&buf, binary.BigEndian, t.InfoType) binary.Write(&buf, binary.BigEndian, t.InfoData) return buf.Bytes(), nil } func (t *RetiPodStateInfo) UnmarshalBinary(data []byte) error { r := bytes.NewReader(data) binary.Read(r, binary.BigEndian, &t.InfoType) switch t.InfoType { case InfoTypeTrackPositionMs: t.InfoData = &InfoTrackPositionMs{} case InfoTypeTrackIndex: t.InfoData = &InfoTrackIndex{} case InfoTypeChapterIndex: t.InfoData = &InfoChapterIndex{} case InfoTypePlayStatus: t.InfoData = &InfoPlayStatus{} case InfoTypeVolume: t.InfoData = &InfoVolume{} case InfoTypePower: t.InfoData = &InfoPower{} case InfoTypeEqualizer: t.InfoData = &InfoEqualizer{} case InfoTypeShuffle: t.InfoData = &InfoShuffle{} case InfoTypeRepeat: t.InfoData = &InfoRepeat{} case InfoTypeDateTime: t.InfoData = &InfoDateTime{} case InfoTypeBacklight: t.InfoData = &InfoBacklight{} case InfoTypeHoldSwitch: t.InfoData = &InfoHoldSwitch{} case InfoTypeSoundCheck: t.InfoData = &InfoSoundCheck{} case InfoTypeAudiobookSpeed: t.InfoData = &InfoAudiobookSpeed{} case InfoTypeTrackPositionSec: t.InfoData = &InfoTrackPositionSec{} case InfoTypeVolume2: t.InfoData = &InfoVolume2{} default: return errors.New("unknown info type") } return binary.Read(r, binary.BigEndian, t.InfoData) } type SetiPodStateInfo struct { InfoType byte InfoData byte // todo } type GetPlayStatus struct { } type RetPlayStatus struct { PlayState byte TrackIndex uint32 TrackLength uint32 TrackPos uint32 } type SetCurrentPlayingTrack struct { TrackIndex uint32 } //go:generate stringer -type=TrackInfoType type TrackInfoType uint8 const ( TrackInfoTypeCaps TrackInfoType = iota TrackInfoTypeChapterTimeName TrackInfoTypeArtist TrackInfoTypeAlbum TrackInfoTypeGenre TrackInfoTypeTrack TrackInfoTypeComposer TrackInfoTypeLyrics TrackInfoTypeArtworkCount ) type GetIndexedPlayingTrackInfo struct { InfoType TrackInfoType TrackIndex uint32 ChapterIndex uint16 } type TrackInfoCaps struct { Caps uint32 TrackTotalMs uint32 ChapterCount uint16 } type TrackInfoChapterTimeName struct { ChapterTime uint32 ChapterName []byte } type TrackInfoArtist struct { Name []byte } type TrackInfoAlbum struct { Name []byte } type TrackInfoGenre struct { Name []byte } type TrackInfoTrack struct { Title []byte } type TrackInfoComposer struct { Name []byte } type TrackInfoLyrics struct { Flags uint8 PacketIndex uint16 Lyrics []byte } type TrackInfoArtworkCount struct { None byte // empty = 0x08 } type RetIndexedPlayingTrackInfo struct { InfoType TrackInfoType InfoData interface{} } func (t *RetIndexedPlayingTrackInfo) MarshalBinary() ([]byte, error) { buf := bytes.Buffer{} binary.Write(&buf, binary.BigEndian, t.InfoType) binary.Write(&buf, binary.BigEndian, t.InfoData) return buf.Bytes(), nil } func (t *RetIndexedPlayingTrackInfo) UnmarshalBinary(data []byte) error { r := bytes.NewReader(data) binary.Read(r, binary.BigEndian, &t.InfoType) switch t.InfoType { case TrackInfoTypeCaps: t.InfoData = &TrackInfoCaps{} case TrackInfoTypeChapterTimeName: t.InfoData = &TrackInfoChapterTimeName{ ChapterTime: 0, ChapterName: make([]byte, 0), } case TrackInfoTypeArtist: t.InfoData = &TrackInfoArtist{ Name: make([]byte, 0), } case TrackInfoTypeAlbum: t.InfoData = &TrackInfoAlbum{ Name: make([]byte, 0), } case TrackInfoTypeGenre: t.InfoData = &TrackInfoGenre{ Name: make([]byte, 0), } case TrackInfoTypeTrack: t.InfoData = &TrackInfoTrack{ Title: make([]byte, 0), } case TrackInfoTypeComposer: t.InfoData = &TrackInfoComposer{ Name: make([]byte, 0), } case TrackInfoTypeLyrics: t.InfoData = &TrackInfoLyrics{ Flags: 0x00, PacketIndex: 0, Lyrics: make([]byte, 0), } case TrackInfoTypeArtworkCount: t.InfoData = &TrackInfoArtworkCount{} default: return errors.New("unknown info type") } return binary.Read(r, binary.BigEndian, t.InfoData) } type GetNumPlayingTracks struct { } type RetNumPlayingTracks struct { NumPlayTracks uint32 } type GetArtworkFormats struct { } type ArtworkFormat struct { FormatID uint16 PixelFormat uint8 ImageWidth uint16 ImageHeight uint16 } type RetArtworkFormats struct { Formats []ArtworkFormat } type GetTrackArtworkData struct { TrackIndex uint32 FormatID uint16 TimeOffset uint32 } type RetTrackArtworkData struct { //todo } type GetPowerBatteryState struct { } type RetPowerBatteryState struct { PowerState byte BatteryLevel uint8 } type GetSoundCheckState struct { } type RetSoundCheckState struct { Enabled bool } type SetSoundCheckState struct { Enabled bool RestoreOnExit bool } type GetTrackArtworkTimes struct { TrackIndex uint32 FormatID uint16 ArtworkIndex uint16 ArtworkCount uint16 } type RetTrackArtworkTimes struct { TimeOffset []uint32 } <|start_filename|>cmd/ipod/doc.go<|end_filename|> /* ipod talks to an ipod accessory using iap protocol. # with debug logging ./ipod -d serve /dev/iap0 # save a trace file ./ipod -d serve -w ipod.trace /dev/iap0 # simulate incoming requests from a trace file ./ipod -d replay ./ipod.trace # view a trace file ./ipod -d view ./ipod.trace Each line of a trace file starts with a '< ' for incoming requests '> ' for outgoing responses followed by the hex dump of the data i.e. a trace file < 00 01 02 > 02 01 00 represents an incoming request byte sequence from the accessory 0x00,0x01,0x02 and an outgoing response byte sequence from the ipod 0x02,0x01,0x00 */ package main <|start_filename|>lingo-extremote/extremote.go<|end_filename|> package extremote import ( "bytes" "encoding/binary" "io" "github.com/oandrew/ipod" ) func init() { ipod.RegisterLingos(ipod.LingoExtRemoteID, Lingos) } var Lingos struct { ACK `id:"0x0001"` GetCurrentPlayingTrackChapterInfo `id:"0x0002"` ReturnCurrentPlayingTrackChapterInfo `id:"0x0003"` SetCurrentPlayingTrackChapter `id:"0x0004"` GetCurrentPlayingTrackChapterPlayStatus `id:"0x0005"` ReturnCurrentPlayingTrackChapterPlayStatus `id:"0x0006"` GetCurrentPlayingTrackChapterName `id:"0x0007"` ReturnCurrentPlayingTrackChapterName `id:"0x0008"` GetAudiobookSpeed `id:"0x0009"` ReturnAudiobookSpeed `id:"0x000A"` SetAudiobookSpeed `id:"0x000B"` GetIndexedPlayingTrackInfo `id:"0x000C"` ReturnIndexedPlayingTrackInfo `id:"0x000D"` GetArtworkFormats `id:"0x000E"` RetArtworkFormats `id:"0x000F"` GetTrackArtworkData `id:"0x0010"` RetTrackArtworkData `id:"0x0011"` ResetDBSelection `id:"0x0016"` SelectDBRecord `id:"0x0017"` GetNumberCategorizedDBRecords `id:"0x0018"` ReturnNumberCategorizedDBRecords `id:"0x0019"` RetrieveCategorizedDatabaseRecords `id:"0x001A"` ReturnCategorizedDatabaseRecord `id:"0x001B"` GetPlayStatus `id:"0x001C"` ReturnPlayStatus `id:"0x001D"` GetCurrentPlayingTrackIndex `id:"0x001E"` ReturnCurrentPlayingTrackIndex `id:"0x001F"` GetIndexedPlayingTrackTitle `id:"0x0020"` ReturnIndexedPlayingTrackTitle `id:"0x0021"` GetIndexedPlayingTrackArtistName `id:"0x0022"` ReturnIndexedPlayingTrackArtistName `id:"0x0023"` GetIndexedPlayingTrackAlbumName `id:"0x0024"` ReturnIndexedPlayingTrackAlbumName `id:"0x0025"` SetPlayStatusChangeNotification `id:"0x0026"` SetPlayStatusChangeNotificationShort `id:"0x0026"` PlayStatusChangeNotification `id:"0x0027"` PlayCurrentSelection `id:"0x0028"` PlayControl `id:"0x0029"` GetTrackArtworkTimes `id:"0x002A"` RetTrackArtworkTimes `id:"0x002B"` GetShuffle `id:"0x002C"` ReturnShuffle `id:"0x002D"` SetShuffle `id:"0x002E"` GetRepeat `id:"0x002F"` ReturnRepeat `id:"0x0030"` SetRepeat `id:"0x0031"` SetDisplayImage `id:"0x0032"` GetMonoDisplayImageLimits `id:"0x0033"` ReturnMonoDisplayImageLimits `id:"0x0034"` GetNumPlayingTracks `id:"0x0035"` ReturnNumPlayingTracks `id:"0x0036"` SetCurrentPlayingTrack `id:"0x0037"` SelectSortDBRecord `id:"0x0038"` GetColorDisplayImageLimits `id:"0x0039"` ReturnColorDisplayImageLimits `id:"0x003A"` ResetDBSelectionHierarchy `id:"0x003B"` GetDBiTunesInfo `id:"0x003C"` RetDBiTunesInfo `id:"0x003D"` GetUIDTrackInfo `id:"0x003E"` RetUIDTrackInfo `id:"0x003F"` GetDBTrackInfo `id:"0x0040"` RetDBTrackInfo `id:"0x0041"` GetPBTrackInfo `id:"0x0042"` RetPBTrackInfo `id:"0x0043"` } type ACKStatus uint8 const ( ACKStatusSuccess ACKStatus = 0x00 ACKStatusFailed ACKStatus = 0x02 ) type ACK struct { Status ACKStatus CmdID uint16 } type GetCurrentPlayingTrackChapterInfo struct { } type ReturnCurrentPlayingTrackChapterInfo struct { CurrentChapterIndex int32 ChapterCount int32 } type SetCurrentPlayingTrackChapter struct { ChapterIndex int32 } type GetCurrentPlayingTrackChapterPlayStatus struct { CurrentChapterIndex int32 } type ReturnCurrentPlayingTrackChapterPlayStatus struct { ChapterLength uint32 ChapterPosition uint32 } type GetCurrentPlayingTrackChapterName struct { ChapterIndex int32 } type ReturnCurrentPlayingTrackChapterName struct { ChapterName []byte } type GetAudiobookSpeed struct { } type ReturnAudiobookSpeed struct { Speed byte //add enums } type SetAudiobookSpeed struct { Speed byte //add enums } type TrackInfoType byte const ( TrackInfoCaps TrackInfoType = 0x00 TrackInfoPodcastName TrackInfoType = 0x01 TrackInfoReleaseDate TrackInfoType = 0x02 TrackInfoDescription TrackInfoType = 0x03 TrackInfoLyrics TrackInfoType = 0x04 TrackInfoGenre TrackInfoType = 0x05 TrackInfoComposer TrackInfoType = 0x06 TrackInfoArtworkCount TrackInfoType = 0x07 ) type TrackCaps struct { Caps uint32 TrackLength uint32 ChapterCount uint16 } type TrackReleaseDate struct { Pad uint64 } type TrackLongText struct { Flags byte PacketIndex uint16 Text byte // string } type GetIndexedPlayingTrackInfo struct { InfoType TrackInfoType TrackIndex int32 ChapterIndex int16 } type ReturnIndexedPlayingTrackInfo struct { InfoType TrackInfoType Info interface{} } func (s ReturnIndexedPlayingTrackInfo) MarshalBinary() ([]byte, error) { w := bytes.Buffer{} if err := binary.Write(&w, binary.BigEndian, s.InfoType); err != nil { return nil, err } if err := binary.Write(&w, binary.BigEndian, s.Info); err != nil { return nil, err } return w.Bytes(), nil } func (s *ReturnIndexedPlayingTrackInfo) UnmarshalBinary(data []byte) error { r := bytes.NewReader(data) if err := binary.Read(r, binary.BigEndian, &s.InfoType); err != nil { return err } switch s.InfoType { case TrackInfoCaps: s.Info = &TrackCaps{} case TrackInfoDescription, TrackInfoLyrics: s.Info = &TrackLongText{} default: s.Info = &struct{}{} } if err := binary.Read(r, binary.BigEndian, s.Info); err != nil { return err } return nil } type GetArtworkFormats struct { } type ArtworkFormat struct { FormatID uint16 PixelFormat byte ImageWidth uint16 ImageHeight uint16 } type RetArtworkFormats struct { Formats []ArtworkFormat } func (s RetArtworkFormats) MarshalBinary() ([]byte, error) { buf := bytes.Buffer{} for i := range s.Formats { binary.Write(&buf, binary.BigEndian, s.Formats[i]) } return buf.Bytes(), nil } func (s *RetArtworkFormats) UnmarshalBinary(data []byte) error { r := bytes.NewReader(data) for { var f ArtworkFormat err := binary.Read(r, binary.BigEndian, &f) if err == io.EOF { break } if err != nil { return err } s.Formats = append(s.Formats, f) } return nil } type GetTrackArtworkData struct { TrackIndex int32 FormatID uint16 Offset uint32 } type RetTrackArtworkData struct { PacketIndex uint16 PixelFormat byte ImageWidth uint16 ImageHeight uint16 TopLeftX uint16 TopLeftY uint16 BottomRightX uint16 BottomRightY uint16 RowSize uint32 Data []byte } //ack type ResetDBSelection struct { } type DBCategoryType byte const ( DbCategoryPlaylist DBCategoryType = 0x01 DbCategoryArtist DBCategoryType = 0x02 DbCategoryAlbum DBCategoryType = 0x03 DbCategoryGenre DBCategoryType = 0x04 DbCategoryTrack DBCategoryType = 0x05 DbCategoryComposer DBCategoryType = 0x06 DbCategoryAudiobook DBCategoryType = 0x07 DbCategoryPodcast DBCategoryType = 0x08 DbCategoryNestedPlaylist DBCategoryType = 0x09 ) type SelectDBRecord struct { CategoryType DBCategoryType RecordIndex int32 } type GetNumberCategorizedDBRecords struct { CategoryType DBCategoryType } type ReturnNumberCategorizedDBRecords struct { RecordCount int32 } type RetrieveCategorizedDatabaseRecords struct { CategoryType DBCategoryType Offset uint32 Count int32 } type ReturnCategorizedDatabaseRecord struct { RecordCategoryIndex uint32 String [16]byte //fix length } type GetPlayStatus struct { } type PlayerState byte const ( PlayerStateStopped PlayerState = 0x00 PlayerStatePlaying PlayerState = 0x01 PlayerStatePaused PlayerState = 0x02 PlayerStateError PlayerState = 0xff ) type ReturnPlayStatus struct { TrackLength uint32 TrackPosition uint32 State PlayerState } type GetCurrentPlayingTrackIndex struct { } type ReturnCurrentPlayingTrackIndex struct { TrackIndex int32 } type GetIndexedPlayingTrackTitle struct { TrackIndex int32 } type ReturnIndexedPlayingTrackTitle struct { Title []byte } func (s ReturnIndexedPlayingTrackTitle) MarshalBinary() ([]byte, error) { return s.Title, nil } func (s *ReturnIndexedPlayingTrackTitle) UnmarshalBinary(data []byte) error { s.Title = make([]byte, len(data)) copy(s.Title, data) return nil } type GetIndexedPlayingTrackArtistName struct { TrackIndex int32 } type ReturnIndexedPlayingTrackArtistName struct { ArtistName []byte } func (s ReturnIndexedPlayingTrackArtistName) MarshalBinary() ([]byte, error) { return s.ArtistName, nil } func (s *ReturnIndexedPlayingTrackArtistName) UnmarshalBinary(data []byte) error { s.ArtistName = make([]byte, len(data)) copy(s.ArtistName, data) return nil } type GetIndexedPlayingTrackAlbumName struct { TrackIndex int32 } type ReturnIndexedPlayingTrackAlbumName struct { AlbumName []byte } func (s ReturnIndexedPlayingTrackAlbumName) MarshalBinary() ([]byte, error) { return s.AlbumName, nil } func (s *ReturnIndexedPlayingTrackAlbumName) UnmarshalBinary(data []byte) error { s.AlbumName = make([]byte, len(data)) copy(s.AlbumName, data) return nil } type SetPlayStatusChangeNotification struct { EventMask uint32 } // SetPlayStatusChangeNotificationShort is another possible version of SetPlayStatusChangeNotification, // that uses a single bit instead of a bitmask to enable/disable all play-status-change notifications type SetPlayStatusChangeNotificationShort struct { Enabled bool } type PlayStatusChangeNotification struct { Status byte // finish } type PlayCurrentSelection struct { SelectedTrackIndex int32 } type PlayControlCmd byte const ( PlayControlToggle PlayControlCmd = 0x01 PlayControlStop PlayControlCmd = 0x02 PlayControlNextTrack PlayControlCmd = 0x03 PlayControlPrevTrack PlayControlCmd = 0x04 PlayControlStartFF PlayControlCmd = 0x05 PlayControlStartRew PlayControlCmd = 0x06 PlayControlEndFFRew PlayControlCmd = 0x07 PlayControlNext PlayControlCmd = 0x08 PlayControlPrev PlayControlCmd = 0x09 PlayControlPlay PlayControlCmd = 0x0a PlayControlPause PlayControlCmd = 0x0b PlayControlNextChapter PlayControlCmd = 0x0c PlayControlPrevChapter PlayControlCmd = 0x0d ) type PlayControl struct { Cmd PlayControlCmd } type GetTrackArtworkTimes struct { TrackIndex int32 FormatID uint16 ArtworkIndex uint16 ArtworkCount int16 } type RetTrackArtworkTimes struct { // empty for now } type ShuffleMode byte const ( ShuffleOff ShuffleMode = 0x00 ShuffleTracks ShuffleMode = 0x01 ShuffleAlbums ShuffleMode = 0x02 ) type GetShuffle struct { } type ReturnShuffle struct { Mode ShuffleMode } type SetShuffle struct { Mode ShuffleMode //restore on exit } type RepeatMode byte const ( RepeatOff RepeatMode = 0x00 RepeatOne RepeatMode = 0x01 RepeatAll RepeatMode = 0x02 ) type GetRepeat struct { } type ReturnRepeat struct { Mode RepeatMode } type SetRepeat struct { Mode RepeatMode //restore on exit } type SetDisplayImage struct { //todo } type GetMonoDisplayImageLimits struct { } type ReturnMonoDisplayImageLimits struct { MaxWidth uint16 MaxHeight uint16 PixelFormat byte } type GetNumPlayingTracks struct { } type ReturnNumPlayingTracks struct { NumTracks uint32 } type SetCurrentPlayingTrack struct { TrackIndex int32 } type SelectSortDBRecord struct { CategoryType DBCategoryType RecordIndex int32 SortType byte // add enum } type GetColorDisplayImageLimits struct { } type ReturnColorDisplayImageLimits struct { MaxWidth uint16 MaxHeight uint16 PixelFormat byte } type ResetDBSelectionHierarchy struct { Selection byte } type GetDBiTunesInfo struct { } type RetDBiTunesInfo struct { } type GetUIDTrackInfo struct { } type RetUIDTrackInfo struct { } type GetDBTrackInfo struct { } type RetDBTrackInfo struct { } type GetPBTrackInfo struct { } type RetPBTrackInfo struct { } <|start_filename|>lingo-dispremote/playstatustype_string.go<|end_filename|> // Code generated by "stringer -type=PlayStatusType"; DO NOT EDIT. package dispremote import "strconv" func _() { // An "invalid array index" compiler error signifies that the constant values have changed. // Re-run the stringer command to generate them again. var x [1]struct{} _ = x[PlayStatusStopped-0] _ = x[PlayStatusPlaying-1] _ = x[PlayStatusPaused-2] _ = x[PlayStatusFF-3] _ = x[PlayStatusREW-4] _ = x[PlayStatusEndFFREW-5] } const _PlayStatusType_name = "PlayStatusStoppedPlayStatusPlayingPlayStatusPausedPlayStatusFFPlayStatusREWPlayStatusEndFFREW" var _PlayStatusType_index = [...]uint8{0, 17, 34, 50, 62, 75, 93} func (i PlayStatusType) String() string { if i >= PlayStatusType(len(_PlayStatusType_index)-1) { return "PlayStatusType(" + strconv.FormatInt(int64(i), 10) + ")" } return _PlayStatusType_name[_PlayStatusType_index[i]:_PlayStatusType_index[i+1]] } <|start_filename|>lingo-general/lingobit_string.go<|end_filename|> // Code generated by "stringer -type=LingoBit"; DO NOT EDIT. package general import "strconv" func _() { // An "invalid array index" compiler error signifies that the constant values have changed. // Re-run the stringer command to generate them again. var x [1]struct{} _ = x[LingoGeneralBit-1] _ = x[LingoSimpleRemoteBit-4] _ = x[LingoDisplayRemoteBit-8] _ = x[LingoExtRemoteBit-16] _ = x[LingoUSBHostBit-64] _ = x[LingoRFTunerBit-128] _ = x[LingoEqBit-256] _ = x[LingoSportsBit-512] _ = x[LingoDigitalAudioBit-1024] _ = x[LingoStorageBit-4096] } const ( _LingoBit_name_0 = "LingoGeneralBit" _LingoBit_name_1 = "LingoSimpleRemoteBit" _LingoBit_name_2 = "LingoDisplayRemoteBit" _LingoBit_name_3 = "LingoExtRemoteBit" _LingoBit_name_4 = "LingoUSBHostBit" _LingoBit_name_5 = "LingoRFTunerBit" _LingoBit_name_6 = "LingoEqBit" _LingoBit_name_7 = "LingoSportsBit" _LingoBit_name_8 = "LingoDigitalAudioBit" _LingoBit_name_9 = "LingoStorageBit" ) func (i LingoBit) String() string { switch { case i == 1: return _LingoBit_name_0 case i == 4: return _LingoBit_name_1 case i == 8: return _LingoBit_name_2 case i == 16: return _LingoBit_name_3 case i == 64: return _LingoBit_name_4 case i == 128: return _LingoBit_name_5 case i == 256: return _LingoBit_name_6 case i == 512: return _LingoBit_name_7 case i == 1024: return _LingoBit_name_8 case i == 4096: return _LingoBit_name_9 default: return "LingoBit(" + strconv.FormatInt(int64(i), 10) + ")" } } <|start_filename|>lingo-general/accinfotype_string.go<|end_filename|> // Code generated by "stringer -type=AccInfoType"; DO NOT EDIT. package general import "strconv" func _() { // An "invalid array index" compiler error signifies that the constant values have changed. // Re-run the stringer command to generate them again. var x [1]struct{} _ = x[AccInfoName-1] _ = x[AccInfoFirmware-4] _ = x[AccInfoHardware-5] _ = x[AccInfoMfr-6] _ = x[AccInfoModel-7] _ = x[AccInfoSerial-8] _ = x[AccInfoMaxPayload-9] } const ( _AccInfoType_name_0 = "AccInfoName" _AccInfoType_name_1 = "AccInfoFirmwareAccInfoHardwareAccInfoMfrAccInfoModelAccInfoSerialAccInfoMaxPayload" ) var ( _AccInfoType_index_1 = [...]uint8{0, 15, 30, 40, 52, 65, 82} ) func (i AccInfoType) String() string { switch { case i == 1: return _AccInfoType_name_0 case 4 <= i && i <= 9: i -= 4 return _AccInfoType_name_1[_AccInfoType_index_1[i]:_AccInfoType_index_1[i+1]] default: return "AccInfoType(" + strconv.FormatInt(int64(i), 10) + ")" } } <|start_filename|>lingo-dispremote/infotype_string.go<|end_filename|> // Code generated by "stringer -type=InfoType"; DO NOT EDIT. package dispremote import "strconv" func _() { // An "invalid array index" compiler error signifies that the constant values have changed. // Re-run the stringer command to generate them again. var x [1]struct{} _ = x[InfoTypeTrackPositionMs-0] _ = x[InfoTypeTrackIndex-1] _ = x[InfoTypeChapterIndex-2] _ = x[InfoTypePlayStatus-3] _ = x[InfoTypeVolume-4] _ = x[InfoTypePower-5] _ = x[InfoTypeEqualizer-6] _ = x[InfoTypeShuffle-7] _ = x[InfoTypeRepeat-8] _ = x[InfoTypeDateTime-9] _ = x[InfoTypeBacklight-11] _ = x[InfoTypeHoldSwitch-12] _ = x[InfoTypeSoundCheck-13] _ = x[InfoTypeAudiobookSpeed-14] _ = x[InfoTypeTrackPositionSec-15] _ = x[InfoTypeVolume2-16] } const ( _InfoType_name_0 = "InfoTypeTrackPositionMsInfoTypeTrackIndexInfoTypeChapterIndexInfoTypePlayStatusInfoTypeVolumeInfoTypePowerInfoTypeEqualizerInfoTypeShuffleInfoTypeRepeatInfoTypeDateTime" _InfoType_name_1 = "InfoTypeBacklightInfoTypeHoldSwitchInfoTypeSoundCheckInfoTypeAudiobookSpeedInfoTypeTrackPositionSecInfoTypeVolume2" ) var ( _InfoType_index_0 = [...]uint8{0, 23, 41, 61, 79, 93, 106, 123, 138, 152, 168} _InfoType_index_1 = [...]uint8{0, 17, 35, 53, 75, 99, 114} ) func (i InfoType) String() string { switch { case i <= 9: return _InfoType_name_0[_InfoType_index_0[i]:_InfoType_index_0[i+1]] case 11 <= i && i <= 16: i -= 11 return _InfoType_name_1[_InfoType_index_1[i]:_InfoType_index_1[i+1]] default: return "InfoType(" + strconv.FormatInt(int64(i), 10) + ")" } } <|start_filename|>crc_test.go<|end_filename|> package ipod_test import ( "testing" "github.com/oandrew/ipod" ) func TestChecksum(t *testing.T) { type args struct { payload []byte } tests := []struct { name string payload []byte wantCrc byte }{ {"empty", []byte{}, 0x00}, {"zero crc", []byte{0x00, 0x00}, 0x00}, {"simple overflow", []byte{0xfe, 0x01}, 0x01}, {"overflow", []byte{0xff, 0xff, 0x02}, 0x00}, {"random", []byte{0x04, 0x00, 0x11, 0x00, 0x01}, 0xea}, {"long", []byte{0x0d, 0x00, 0x4c, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x06, 0x3d, 0xef, 0x73, 0xff}, 0xff}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { if got := ipod.Checksum(tt.payload); got != tt.wantCrc { t.Errorf("checksum() = %v, want %v", got, tt.wantCrc) } }) } } <|start_filename|>hid/hid.go<|end_filename|> // Package hid implements iap over hid transport package hid import ( "bytes" ) type Report struct { ID byte LinkControl LinkControl Data []byte } type LinkControl byte const ( LinkControlDone LinkControl = 0x00 LinkControlContinue LinkControl = 0x01 LinkControlMoreToFollow LinkControl = 0x02 ) type Encoder struct { reportDefs ReportDefs w ReportWriter } func min(a, b int) int { if a < b { return a } return b } func (e *Encoder) WriteFrame(data []byte) error { offset := 0 bytesLeft := len(data) for bytesLeft > 0 { reportDef, err := e.reportDefs.Pick(bytesLeft, ReportDirAccIn) if err != nil { return err } payloadLen := bytesLeft linkControl := LinkControlDone if bytesLeft > reportDef.MaxPayload() { payloadLen = reportDef.MaxPayload() if offset == 0 { linkControl = LinkControlMoreToFollow } else { linkControl = LinkControlContinue | LinkControlMoreToFollow } } else if offset > 0 { linkControl = LinkControlContinue } reportData := make([]byte, reportDef.MaxPayload()) copy(reportData, data[offset:offset+payloadLen]) report := Report{ ID: byte(reportDef.ID), LinkControl: linkControl, Data: reportData, } if err := e.w.WriteReport(report); err != nil { return err } bytesLeft -= payloadLen offset += payloadLen } return nil } func NewEncoder(w ReportWriter, defs ReportDefs) *Encoder { return &Encoder{ reportDefs: defs, w: w, } } func NewEncoderDefault(w ReportWriter) *Encoder { return NewEncoder(w, DefaultReportDefs) } type Decoder struct { reportDefs ReportDefs r ReportReader buf bytes.Buffer } func (e *Decoder) ReadFrame() ([]byte, error) { buf := &e.buf buf.Reset() done := false for !done { report, err := e.r.ReadReport() if err != nil { return nil, err } reportDef, err := e.reportDefs.Find(int(report.ID)) if err != nil { return nil, err } n := min(len(report.Data), reportDef.MaxPayload()) reportData := report.Data[:n] switch report.LinkControl { case LinkControlDone: buf.Reset() buf.Write(reportData) done = true case LinkControlMoreToFollow: buf.Reset() buf.Write(reportData) case LinkControlContinue | LinkControlMoreToFollow: buf.Write(reportData) case LinkControlContinue: buf.Write(reportData) done = true } } return buf.Bytes(), nil } func NewDecoder(r ReportReader, defs ReportDefs) *Decoder { return &Decoder{ r: r, reportDefs: defs, } } func NewDecoderDefault(r ReportReader) *Decoder { return NewDecoder(r, DefaultReportDefs) } type Transport struct { *Decoder *Encoder } func NewTransport(r ReportReader, w ReportWriter, defs ReportDefs) *Transport { return &Transport{ Decoder: NewDecoder(r, defs), Encoder: NewEncoder(w, defs), } } <|start_filename|>lingo-audio/audio.go<|end_filename|> package audio import ( "bytes" "encoding/binary" "github.com/oandrew/ipod" ) func init() { ipod.RegisterLingos(ipod.LingoDigitalAudioID, Lingos) } var Lingos struct { AccAck `id:"0x00"` iPodAck `id:"0x01"` GetAccSampleRateCaps `id:"0x02"` RetAccSampleRateCaps `id:"0x03"` TrackNewAudioAttributes `id:"0x04"` SetVideoDelay `id:"0x05"` } type ACKStatus uint8 const ( ACKStatusSuccess ACKStatus = 0x00 ) type AccAck struct { Status ACKStatus CmdID uint8 } type iPodAck struct { Status ACKStatus CmdID uint8 } type GetAccSampleRateCaps struct { } type RetAccSampleRateCaps struct { SampleRates []uint32 } func (s *RetAccSampleRateCaps) UnmarshalBinary(data []byte) error { s.SampleRates = make([]uint32, len(data)/4) return binary.Read(bytes.NewReader(data), binary.BigEndian, s.SampleRates) } func (s *RetAccSampleRateCaps) MarshalBinary() ([]byte, error) { var buf bytes.Buffer err := binary.Write(&buf, binary.BigEndian, s.SampleRates) return buf.Bytes(), err } type TrackNewAudioAttributes struct { SampleRate uint32 SoundCheckValue uint32 VolumeAdjustment uint32 } type SetVideoDelay struct { Delay uint32 } <|start_filename|>lingo-simpleremote/contextbuttonbit_string.go<|end_filename|> // Code generated by "stringer -type=ContextButtonBit"; DO NOT EDIT. package simpleremote import "strconv" func _() { // An "invalid array index" compiler error signifies that the constant values have changed. // Re-run the stringer command to generate them again. var x [1]struct{} _ = x[ContextButtonPlayPause-1] _ = x[ContextButtonVolumeUp-2] _ = x[ContextButtonVolumeDown-4] _ = x[ContextButtonNextTrack-8] _ = x[ContextButtonPreviousTrack-16] _ = x[ContextButtonNextAlbum-32] _ = x[ContextButtonPreviousAlbum-64] _ = x[ContextButtonStop-128] _ = x[ContextButtonPlayResume-256] _ = x[ContextButtonPause-512] _ = x[ContextButtonMuteToggle-1024] _ = x[ContextButtonNextChapter-2048] _ = x[ContextButtonPreviousChapter-4096] _ = x[ContextButtonNextPlaylist-8192] _ = x[ContextButtonPreviousPlaylist-16384] _ = x[ContextButtonShuffleSettingAdvance-32768] _ = x[ContextButtonRepeatSettingAdvance-65536] _ = x[ContextButtonPowerOn-131072] _ = x[ContextButtonPowerOff-262144] _ = x[ContextButtonBacklightfor30Seconds-524288] _ = x[ContextButtonBeginFastForward-1048576] _ = x[ContextButtonBeginRewind-2097152] _ = x[ContextButtonMenu-4194304] _ = x[ContextButtonSelect-8388608] _ = x[ContextButtonUpArrow-16777216] _ = x[ContextButtonDownArrow-33554432] _ = x[ContextButtonBacklightOff-67108864] } const _ContextButtonBit_name = "ContextButtonPlayPauseContextButtonVolumeUpContextButtonVolumeDownContextButtonNextTrackContextButtonPreviousTrackContextButtonNextAlbumContextButtonPreviousAlbumContextButtonStopContextButtonPlayResumeContextButtonPauseContextButtonMuteToggleContextButtonNextChapterContextButtonPreviousChapterContextButtonNextPlaylistContextButtonPreviousPlaylistContextButtonShuffleSettingAdvanceContextButtonRepeatSettingAdvanceContextButtonPowerOnContextButtonPowerOffContextButtonBacklightfor30SecondsContextButtonBeginFastForwardContextButtonBeginRewindContextButtonMenuContextButtonSelectContextButtonUpArrowContextButtonDownArrowContextButtonBacklightOff" var _ContextButtonBit_map = map[ContextButtonBit]string{ 1: _ContextButtonBit_name[0:22], 2: _ContextButtonBit_name[22:43], 4: _ContextButtonBit_name[43:66], 8: _ContextButtonBit_name[66:88], 16: _ContextButtonBit_name[88:114], 32: _ContextButtonBit_name[114:136], 64: _ContextButtonBit_name[136:162], 128: _ContextButtonBit_name[162:179], 256: _ContextButtonBit_name[179:202], 512: _ContextButtonBit_name[202:220], 1024: _ContextButtonBit_name[220:243], 2048: _ContextButtonBit_name[243:267], 4096: _ContextButtonBit_name[267:295], 8192: _ContextButtonBit_name[295:320], 16384: _ContextButtonBit_name[320:349], 32768: _ContextButtonBit_name[349:383], 65536: _ContextButtonBit_name[383:416], 131072: _ContextButtonBit_name[416:436], 262144: _ContextButtonBit_name[436:457], 524288: _ContextButtonBit_name[457:491], 1048576: _ContextButtonBit_name[491:520], 2097152: _ContextButtonBit_name[520:544], 4194304: _ContextButtonBit_name[544:561], 8388608: _ContextButtonBit_name[561:580], 16777216: _ContextButtonBit_name[580:600], 33554432: _ContextButtonBit_name[600:622], 67108864: _ContextButtonBit_name[622:647], } func (i ContextButtonBit) String() string { if str, ok := _ContextButtonBit_map[i]; ok { return str } return "ContextButtonBit(" + strconv.FormatInt(int64(i), 10) + ")" } <|start_filename|>util.go<|end_filename|> package ipod func BoolToByte(b bool) byte { if b { return 0x01 } return 0x00 } func ByteToBool(b byte) bool { return b == 0x01 } // StringToBytes convers a string to a null-terminated byte slice func StringToBytes(s string) []byte { return append([]byte(s), 0x00) } <|start_filename|>hid/report_def.go<|end_filename|> package hid import ( "errors" "fmt" ) // ReportDir is the report direction type ReportDir uint8 const ( // Device to host (ipod->accessory) ReportDirAccIn ReportDir = 0 // Host to device (accessory->ipod) ReportDirAccOut ReportDir = 1 ) // ReportDef represents a hid report type from the descriptor type ReportDef struct { // id ID int // lenth of the report not including the id. Len int // direction Dir ReportDir } // MaxPayload returns the maximum payload that a report can fit func (def ReportDef) MaxPayload() int { return def.Len - 1 } // ReportDefs is a collection of ReportDef type ReportDefs []ReportDef // DefaultReportDefs is a default set of report types // for use with ipod-gadget var DefaultReportDefs = ReportDefs{ ReportDef{ID: 0x01, Len: 12, Dir: ReportDirAccIn}, ReportDef{ID: 0x02, Len: 14, Dir: ReportDirAccIn}, ReportDef{ID: 0x03, Len: 20, Dir: ReportDirAccIn}, ReportDef{ID: 0x04, Len: 63, Dir: ReportDirAccIn}, ReportDef{ID: 0x05, Len: 8, Dir: ReportDirAccIn}, ReportDef{ID: 0x06, Len: 10, Dir: ReportDirAccIn}, ReportDef{ID: 0x07, Len: 14, Dir: ReportDirAccIn}, ReportDef{ID: 0x08, Len: 20, Dir: ReportDirAccIn}, ReportDef{ID: 0x09, Len: 63, Dir: ReportDirAccIn}, } var LegacyReportDefs = ReportDefs{ ReportDef{ID: 0x01, Len: 5, Dir: ReportDirAccIn}, ReportDef{ID: 0x02, Len: 9, Dir: ReportDirAccIn}, ReportDef{ID: 0x03, Len: 13, Dir: ReportDirAccIn}, ReportDef{ID: 0x04, Len: 17, Dir: ReportDirAccIn}, ReportDef{ID: 0x05, Len: 25, Dir: ReportDirAccIn}, ReportDef{ID: 0x06, Len: 49, Dir: ReportDirAccIn}, ReportDef{ID: 0x07, Len: 95, Dir: ReportDirAccIn}, ReportDef{ID: 0x08, Len: 193, Dir: ReportDirAccIn}, ReportDef{ID: 0x09, Len: 257, Dir: ReportDirAccIn}, ReportDef{ID: 0x0A, Len: 385, Dir: ReportDirAccIn}, ReportDef{ID: 0x0B, Len: 513, Dir: ReportDirAccIn}, ReportDef{ID: 0x0C, Len: 767, Dir: ReportDirAccIn}, ReportDef{ID: 0x0D, Len: 5, Dir: ReportDirAccOut}, ReportDef{ID: 0x0E, Len: 9, Dir: ReportDirAccOut}, ReportDef{ID: 0x0F, Len: 13, Dir: ReportDirAccOut}, ReportDef{ID: 0x10, Len: 17, Dir: ReportDirAccOut}, ReportDef{ID: 0x11, Len: 25, Dir: ReportDirAccOut}, ReportDef{ID: 0x12, Len: 49, Dir: ReportDirAccOut}, ReportDef{ID: 0x13, Len: 95, Dir: ReportDirAccOut}, ReportDef{ID: 0x14, Len: 193, Dir: ReportDirAccOut}, ReportDef{ID: 0x15, Len: 255, Dir: ReportDirAccOut}, } // Pick finds the best matching report type func (defs ReportDefs) Pick(payloadSize int, dir ReportDir) (ReportDef, error) { var def *ReportDef for i := range defs { if defs[i].Dir == dir { def = &defs[i] if defs[i].MaxPayload() >= payloadSize { break } } } if def == nil { return ReportDef{}, errors.New("no matching report found") } else { return *def, nil } } // Find finds the report type based on id func (defs ReportDefs) Find(id int) (ReportDef, error) { for i := range defs { if defs[i].ID == id { return defs[i], nil } } return ReportDef{}, fmt.Errorf("report id no found: %#v", id) } <|start_filename|>trace/trace.go<|end_filename|> package trace import ( "bufio" "bytes" "container/list" "fmt" "io" ) const ( DirIn Dir = iota DirOut ) type Dir byte func (d Dir) MarshalText() ([]byte, error) { switch d { case DirIn: return []byte{'<'}, nil case DirOut: return []byte{'>'}, nil } return nil, fmt.Errorf("bad dir: %v", d) } func (d *Dir) UnmarshalText(text []byte) error { if len(text) != 1 { return fmt.Errorf("trace dir unmarshal: bad value %v", text) } switch text[0] { case '<': *d = DirIn return nil case '>': *d = DirOut return nil } return fmt.Errorf("trace dir unmarshal: unknown symbol '%c'", text[0]) } type Msg struct { Dir Dir TS uint Data []byte } func (m Msg) MarshalText() ([]byte, error) { dt, err := m.Dir.MarshalText() if err != nil { return nil, err } if len(m.Data) == 0 { return nil, fmt.Errorf("trace marshal: no data") } t := fmt.Sprintf("%c % 02X", dt[0], m.Data) return []byte(t), nil } func (m *Msg) UnmarshalText(text []byte) error { if len(text) < 4 { return fmt.Errorf("trace unmarshal: short msg") } if err := m.Dir.UnmarshalText(text[0:1]); err != nil { return err } h := bytes.Join(bytes.Split(text[2:], []byte{' '}), []byte{}) var data []byte _, err := fmt.Sscanf(string(h), "%x", &data) if err != nil { return fmt.Errorf("trace unmarshal: bad data") } m.Data = data[:] return nil } type Reader struct { s *bufio.Scanner err error ts uint } func NewReader(r io.Reader) *Reader { return &Reader{ s: bufio.NewScanner(r), } } func (r *Reader) ReadMsg(m *Msg) error { if r.err != nil { return r.err } for r.s.Scan() { text := r.s.Bytes() if len(text) == 0 { continue } err := m.UnmarshalText(text) if err == nil { m.TS = r.ts r.ts++ } return err } r.err = r.s.Err() if r.err == nil { r.err = io.EOF } return r.err } type Writer struct { w io.Writer } func NewWriter(w io.Writer) *Writer { return &Writer{ w: w, } } func (w *Writer) WriteMsg(m *Msg) error { t, err := m.MarshalText() if err != nil { return err } t = append(t, '\n') n, err := w.w.Write(t) _ = n return err } type tracer struct { tw *Writer rw io.ReadWriter } func (t *tracer) Write(p []byte) (n int, err error) { n, err = t.rw.Write(p) if err == nil { t.tw.WriteMsg(&Msg{Dir: DirOut, Data: p[:n]}) } return } func (t *tracer) Read(p []byte) (n int, err error) { n, err = t.rw.Read(p) if err == nil { t.tw.WriteMsg(&Msg{Dir: DirIn, Data: p[:n]}) } return } func NewTracer(tw io.Writer, rw io.ReadWriter) io.ReadWriter { return &tracer{ tw: NewWriter(tw), rw: rw, } } type traceDirReader struct { r *Reader dir Dir } func NewTraceDirReader(r *Reader, dir Dir) io.Reader { return &traceDirReader{ r: r, dir: dir, } } func (tdr *traceDirReader) Read(p []byte) (n int, err error) { for { var m Msg if err := tdr.r.ReadMsg(&m); err != nil { return 0, err } if m.Dir != tdr.dir { continue } return copy(p, m.Data), nil } } type queueItem struct { msg *Msg allE, dirE *list.Element } type Queue struct { all list.List in, out list.List } func (q *Queue) dirList(dir Dir) *list.List { switch dir { case DirIn: return &q.in case DirOut: return &q.out } panic("bad dir") } func (q *Queue) Enqueue(msg *Msg) { qi := &queueItem{msg: msg} qi.allE = q.all.PushBack(qi) qi.dirE = q.dirList(msg.Dir).PushBack(qi) } func (q *Queue) Head() *Msg { qie := q.all.Front() if qie == nil { return nil } qi, ok := qie.Value.(*queueItem) if !ok { return nil } return qi.msg } func (q *Queue) Dequeue() *Msg { qie := q.all.Front() if qie == nil { return nil } qi, ok := qie.Value.(*queueItem) if !ok { return nil } q.all.Remove(qi.allE) q.dirList(qi.msg.Dir).Remove(qi.dirE) return qi.msg } func (q *Queue) DequeueDir(dir Dir) *Msg { qie := q.dirList(dir).Front() if qie == nil { return nil } qi, ok := qie.Value.(*queueItem) if !ok { return nil } q.all.Remove(qi.allE) q.dirList(qi.msg.Dir).Remove(qi.dirE) return qi.msg } type queueDirReader struct { q *Queue dir Dir } func NewQueueDirReader(q *Queue, dir Dir) io.Reader { return &queueDirReader{ q: q, dir: dir, } } func (qdr *queueDirReader) Read(p []byte) (n int, err error) { msg := qdr.q.DequeueDir(qdr.dir) if msg == nil { return 0, io.EOF } return copy(p, msg.Data), nil } <|start_filename|>packet_test.go<|end_filename|> package ipod_test import ( "bytes" "reflect" "testing" "github.com/oandrew/ipod" _ "github.com/oandrew/ipod/lingo-general" ) func TestPacketWriter_WritePacket(t *testing.T) { largeData := bytes.Repeat([]byte{0xee}, 255) tests := []struct { name string data []byte want []byte wantErr bool }{ {"no-data", []byte{}, nil, true}, {"with-data", []byte{0x01, 0x02, 0xfd}, []byte{0x55, 0x03, 0x01, 0x02, 0xfd, 0xfd}, false}, {"large-with-data", append([]byte{0x1, 0x02}, largeData...), append([]byte{0x55, 0x00, 0x01, 0x01, 0x1, 0x02}, append(largeData, 0xe9)...), false}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { w := ipod.NewPacketWriter() err := w.WritePacket(tt.data) got := w.Bytes() if (err != nil) != tt.wantErr { t.Errorf("PacketWriter.WritePacket() error = %v, wantErr %v", err, tt.wantErr) return } if !bytes.Equal(got, tt.want) { t.Errorf("PacketWriter.WritePacket() = %v, want %v", got, tt.want) } }) } } func TestPacketReader_ReadPacket(t *testing.T) { largeData := bytes.Repeat([]byte{0xee}, 255) tests := []struct { name string data []byte want []byte wantErr bool }{ {"no-data", []byte{0x55, 0x02, 0x01, 0x02, 256 - 0x05}, []byte{0x01, 0x02}, false}, {"with-data", []byte{0x55, 0x03, 0x01, 0x02, 0xfd, 0xfd}, []byte{0x01, 0x02, 0xfd}, false}, {"bad-crc", []byte{0x55, 0x03, 0x01, 0x02, 0xfd, 0x22}, nil, true}, {"wrong-start-byte", []byte{0xff, 0x03, 0x01, 0x02, 0xfd, 0xfd}, nil, true}, {"large-with-data", append([]byte{0x55, 0x00, 0x01, 0x01, 0x1, 0x02}, append(largeData, 0xe9)...), append([]byte{0x1, 0x02}, largeData...), false}, {"large-with-data-short", append([]byte{0x55, 0x00, 0x01, 0x02, 0x1, 0x02}, append(largeData, 0xe9)...), nil, true}, {"large-bad-crc", append([]byte{0x55, 0x00, 0x01, 0x01, 0x1, 0x02}, append(largeData, 0x22)...), nil, true}, {"short-packet", []byte{0x55}, nil, true}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { r := ipod.NewPacketReader(tt.data) got, err := r.ReadPacket() if (err != nil) != tt.wantErr { t.Errorf("PacketReader.ReadPacket() error = %v, wantErr %v", err, tt.wantErr) return } if tt.want != nil && !reflect.DeepEqual(got, tt.want) { t.Errorf("PacketReader.ReadPacket() = %v, want %v", got, tt.want) } }) } } func TestPacketRoundtrip(t *testing.T) { pw := [][]byte{ []byte("packet1"), []byte("_packet2"), } w := ipod.NewPacketWriter() for i := range pw { w.WritePacket(pw[i]) } r := ipod.NewPacketReader(w.Bytes()) for i := range pw { pr, err := r.ReadPacket() if err != nil { t.Error(err) } if !bytes.Equal(pr, pw[i]) { t.Fail() } } } func BenchmarkPacketReader(b *testing.B) { frame := []byte{ 0x55, 0x28, 0x0a, 0x03, 0x03, 0xe7, 0x00, 0x00, 0x1f, 0x40, 0x00, 0x00, 0x2b, 0x11, 0x00, 0x00, 0x2e, 0xe0, 0x00, 0x00, 0x3e, 0x80, 0x00, 0x00, 0x56, 0x22, 0x00, 0x00, 0x5d, 0xc0, 0x00, 0x00, 0x7d, 0x00, 0x00, 0x00, 0xac, 0x44, 0x00, 0x00, 0xbb, 0x80, 0x3d, 0x00, 0x00, 0x00, 0x00, } for i := 0; i < b.N; i++ { r := ipod.NewPacketReader(frame) r.ReadPacket() } } func BenchmarkPacketWriter(b *testing.B) { packet := []byte{ 0x0a, 0x03, 0x03, 0xe7, 0x00, 0x00, 0x1f, 0x40, 0x00, 0x00, 0x2b, 0x11, 0x00, 0x00, 0x2e, 0xe0, 0x00, 0x00, 0x3e, 0x80, 0x00, 0x00, 0x56, 0x22, 0x00, 0x00, 0x5d, 0xc0, 0x00, 0x00, 0x7d, 0x00, 0x00, 0x00, 0xac, 0x44, 0x00, 0x00, 0xbb, 0x80, } for i := 0; i < b.N; i++ { pw := ipod.NewPacketWriter() pw.WritePacket(packet) } } <|start_filename|>lingo-simpleremote/simpleremote.go<|end_filename|> package simpleremote import ( "encoding/binary" "errors" "math/bits" "strings" "github.com/oandrew/ipod" ) func init() { ipod.RegisterLingos(ipod.LingoSimpleRemoteID, Lingos) } var Lingos struct { ContextButtonStatus `id:"0x00"` ACK `id:"0x01"` VideoButtonStatus `id:"0x03"` AudioButtonStatus `id:"0x04"` iPodOutButtonStatus `id:"0x0B"` RotationInputStatus `id:"0x0C"` RadioButtonStatus `id:"0x0D"` CameraButtonStatus `id:"0x0E"` RegisterDescriptor `id:"0x0F"` SendHIDReportToiPod `id:"0x10"` SendHIDReportToAcc `id:"0x11"` UnregisterDescriptor `id:"0x12"` AccessibilityEvent `id:"0x13"` GetAccessibilityParameter `id:"0x14"` RetAccessibilityParameter `id:"0x15"` SetAccessibilityParameter `id:"0x16"` GetCurrentItemProperty `id:"0x17"` RetCurrentItemProperty `id:"0x18"` SetContext `id:"0x19"` AccParameterChanged `id:"0x1A"` DevACK `id:"0x81"` } type ButtonStates struct { ButtonStates uint32 // force binary.Size() == -1 _ []byte } func (s *ButtonStates) MarshalBinary() ([]byte, error) { var mask [4]byte binary.LittleEndian.PutUint32(mask[:], s.ButtonStates) byteLen := (bits.Len32(s.ButtonStates) + 7) / 8 if byteLen == 0 { byteLen = 1 } return mask[:byteLen], nil } func (s *ButtonStates) UnmarshalBinary(data []byte) error { var mask [4]byte switch copy(mask[:], data) { case 1, 2, 3, 4: s.ButtonStates = binary.LittleEndian.Uint32(mask[:]) return nil default: return errors.New("invalid data") } } //go:generate stringer -type=ContextButtonBit type ContextButtonBit uint32 const ( // byte 0 ContextButtonPlayPause ContextButtonBit = 1 << iota ContextButtonVolumeUp ContextButtonVolumeDown ContextButtonNextTrack ContextButtonPreviousTrack ContextButtonNextAlbum ContextButtonPreviousAlbum ContextButtonStop // byte 1 ContextButtonPlayResume ContextButtonPause ContextButtonMuteToggle ContextButtonNextChapter ContextButtonPreviousChapter ContextButtonNextPlaylist ContextButtonPreviousPlaylist ContextButtonShuffleSettingAdvance // byte 2 ContextButtonRepeatSettingAdvance ContextButtonPowerOn ContextButtonPowerOff ContextButtonBacklightfor30Seconds ContextButtonBeginFastForward ContextButtonBeginRewind ContextButtonMenu ContextButtonSelect // byte 3 ContextButtonUpArrow ContextButtonDownArrow ContextButtonBacklightOff ) type ContextButtonMask uint32 func (m ContextButtonMask) String() string { labels := make([]string, 0, 32) for i := 0; i < 32; i++ { bit := uint32(1 << i) if uint32(m)&bit != 0 { labels = append(labels, ContextButtonBit(bit).String()) } } return strings.Join(labels, " | ") } type ContextButtonStatus struct { State ContextButtonMask _ []byte } func (s *ContextButtonStatus) MarshalBinary() ([]byte, error) { tmp := ButtonStates{ButtonStates: uint32(s.State)} return tmp.MarshalBinary() } func (s *ContextButtonStatus) UnmarshalBinary(data []byte) error { var tmp ButtonStates if err := tmp.UnmarshalBinary(data); err != nil { return err } s.State = ContextButtonMask(tmp.ButtonStates) return nil } type ACK struct{} type VideoButtonStatus struct { ButtonStates } type AudioButtonStatus struct { ButtonStates } type iPodOutButtonStatus struct { ButtonSource byte // add ButtonStates } type RotationInputStatus struct{} type RadioButtonStatus struct{} type CameraButtonStatus struct{} type RegisterDescriptor struct{} type SendHIDReportToiPod struct{} type SendHIDReportToAcc struct{} type UnregisterDescriptor struct{} type AccessibilityEvent struct{} type GetAccessibilityParameter struct{} type RetAccessibilityParameter struct{} type SetAccessibilityParameter struct{} type GetCurrentItemProperty struct{} type RetCurrentItemProperty struct{} type SetContext struct{} type AccParameterChanged struct{} type DevACK struct{} <|start_filename|>hid/report_transport.go<|end_filename|> package hid import ( "bytes" "io" ) type ReportReader interface { ReadReport() (Report, error) } type ReportWriter interface { WriteReport(Report) error } type SingleReport []byte func (s SingleReport) ReadReport() (Report, error) { return Report{ ID: s[0], LinkControl: LinkControl(s[1]), Data: s[2:], }, nil } const maxRawSize = 1024 type rawReportReader struct { r io.Reader buf []byte } func (rr *rawReportReader) ReadReport() (Report, error) { n, err := rr.r.Read(rr.buf) if err != nil { return Report{}, err } if n < 3 { return Report{}, io.ErrNoProgress } return Report{ ID: rr.buf[0], LinkControl: LinkControl(rr.buf[1]), Data: rr.buf[2:n], }, nil } func NewReportReader(r io.Reader) ReportReader { return &rawReportReader{ r: r, buf: make([]byte, maxRawSize), } } type rawReportWriter struct { w io.Writer buf bytes.Buffer } func (rw *rawReportWriter) WriteReport(report Report) error { rw.buf.Reset() rw.buf.WriteByte(report.ID) rw.buf.WriteByte(byte(report.LinkControl)) rw.buf.Write(report.Data) _, err := rw.buf.WriteTo(rw.w) return err } func NewReportWriter(w io.Writer) ReportWriter { return &rawReportWriter{ w: w, } } <|start_filename|>lingo-general/handler.go<|end_filename|> package general import ( "bytes" "github.com/oandrew/ipod" ) type DeviceGeneral interface { UIMode() UIMode SetUIMode(UIMode) Name() string SoftwareVersion() (major, minor, rev uint8) SerialNum() string LingoProtocolVersion(lingo uint8) (major, minor uint8) LingoOptions(ling uint8) uint64 PrefSettingID(classID uint8) uint8 SetPrefSettingID(classID, settingID uint8, restoreOnExit bool) StartIDPS() EndIDPS(status AccEndIDPSStatus) SetToken(token FIDTokenValue) error AccAuthCert(cert []byte) SetEventNotificationMask(mask uint64) EventNotificationMask() uint64 SupportedEventNotificationMask() uint64 CancelCommand(lingo uint8, cmd uint16, transaction uint16) MaxPayload() uint16 } func ackSuccess(req *ipod.Command) *ACK { return &ACK{Status: ACKStatusSuccess, CmdID: uint8(req.ID.CmdID())} } func ackPending(req *ipod.Command, maxWait uint32) *ACKPending { return &ACKPending{Status: ACKStatusPending, CmdID: uint8(req.ID.CmdID()), MaxWait: maxWait} } func ack(req *ipod.Command, status ACKStatus) *ACK { return &ACK{Status: status, CmdID: uint8(req.ID.CmdID())} } func ackFIDTokenValue(tokenValue FIDTokenValue) FIDTokenValueACK { ackToken := func(token interface{}) interface{} { switch t := token.(type) { case *FIDIdentifyToken: return []byte{0x00} case *FIDAccCapsToken: return []byte{0x00} case *FIDAccInfoToken: return []byte{0x00, t.AccInfoType} case *FIDiPodPreferenceToken: return []byte{0x00, t.PrefClass} case *FIDEAProtocolToken: return []byte{0x00, t.ProtocolIndex} case *FIDBundleSeedIDPrefToken: return []byte{0x00} case *FIDScreenInfoToken: return []byte{0x00} case *FIDEAProtocolMetadataToken: return []byte{0x00} case *FIDMicrophoneCapsToken: return []byte{0x00} default: return nil } } return FIDTokenValueACK{ ID: tokenValue.ID, ACK: ackToken(tokenValue.Token), } } func ackFIDTokenValues(tokens *SetFIDTokenValues) *RetFIDTokenValueACKs { acks := make([]FIDTokenValueACK, len(tokens.FIDTokenValues)) for i := range tokens.FIDTokenValues { acks[i] = ackFIDTokenValue(tokens.FIDTokenValues[i]) } return &RetFIDTokenValueACKs{ FIDTokenValueACKs: acks, } } var accCertBuf bytes.Buffer func HandleGeneral(req *ipod.Command, tr ipod.CommandWriter, dev DeviceGeneral) error { switch msg := req.Payload.(type) { case *RequestRemoteUIMode: ipod.Respond(req, tr, &ReturnRemoteUIMode{ Mode: ipod.BoolToByte(dev.UIMode() == UIModeExtended), }) case *EnterRemoteUIMode: if dev.UIMode() == UIModeExtended { ipod.Respond(req, tr, ackSuccess(req)) } else { ipod.Respond(req, tr, ackPending(req, 300)) dev.SetUIMode(UIModeExtended) ipod.Respond(req, tr, ackSuccess(req)) } case *ExitRemoteUIMode: if dev.UIMode() != UIModeExtended { ipod.Respond(req, tr, ackSuccess(req)) } else { ipod.Respond(req, tr, ackPending(req, 300)) dev.SetUIMode(UIModeStandart) ipod.Respond(req, tr, ackSuccess(req)) } case *RequestiPodName: ipod.Respond(req, tr, &ReturniPodName{Name: ipod.StringToBytes(dev.Name())}) case *RequestiPodSoftwareVersion: var resp ReturniPodSoftwareVersion resp.Major, resp.Minor, resp.Rev = dev.SoftwareVersion() ipod.Respond(req, tr, &resp) case *RequestiPodSerialNum: ipod.Respond(req, tr, &ReturniPodSerialNum{Serial: ipod.StringToBytes(dev.SerialNum())}) case *RequestiPodModelNum: ipod.Respond(req, tr, &ReturniPodModelNum{ // iphone 4 ModelID: 0x00111349, Model: ipod.StringToBytes("MC676"), }) case *RequestLingoProtocolVersion: var resp ReturnLingoProtocolVersion resp.Lingo = msg.Lingo resp.Major, resp.Minor = dev.LingoProtocolVersion(msg.Lingo) ipod.Respond(req, tr, &resp) case *RequestTransportMaxPayloadSize: ipod.Respond(req, tr, &ReturnTransportMaxPayloadSize{MaxPayload: dev.MaxPayload()}) case *IdentifyDeviceLingoes: ipod.Respond(req, tr, ackSuccess(req)) if msg.DeviceID != 0x00 { //ipod.Send(tr, &GetDevAuthenticationInfo{}) ipod.Respond(req, tr, &GetDevAuthenticationInfo{}) } //GetDevAuthenticationInfo case *RetDevAuthenticationInfo: if msg.Major >= 2 { if msg.CertCurrentSection == 0 { accCertBuf.Reset() } accCertBuf.Write(msg.CertData) if msg.CertCurrentSection < msg.CertMaxSection { ipod.Respond(req, tr, ackSuccess(req)) } else { ipod.Respond(req, tr, &AckDevAuthenticationInfo{Status: DevAuthInfoStatusSupported}) dev.AccAuthCert(accCertBuf.Bytes()) ipod.Respond(req, tr, &GetDevAuthenticationSignatureV2{Counter: 0}) } } else { ipod.Respond(req, tr, &AckDevAuthenticationInfo{Status: DevAuthInfoStatusSupported}) } // GetDevAuthenticationSignatureV1 // case *RetDevAuthenticationSignatureV1: // ipod.Respond(req, tr, ackDevAuthenticationStatus{Status: DevAuthStatusPassed}) // // GetDevAuthenticationSignatureV2 // case *RetDevAuthenticationSignatureV2: // ipod.Respond(req, tr, ackDevAuthenticationStatus{Status: DevAuthStatusPassed}) case *RetDevAuthenticationSignature: ipod.Respond(req, tr, &AckDevAuthenticationStatus{Status: DevAuthStatusPassed}) case *GetiPodAuthenticationInfo: ipod.Respond(req, tr, &RetiPodAuthenticationInfo{ Major: 1, Minor: 1, CertCurrentSection: 0, CertMaxSection: 0, CertData: []byte{}, }) case *AckiPodAuthenticationInfo: // pass case *GetiPodAuthenticationSignature: ipod.Respond(req, tr, &RetiPodAuthenticationSignature{Signature: msg.Challenge}) case *AckiPodAuthenticationStatus: // pass // revisit case *GetiPodOptions: ipod.Respond(req, tr, &RetiPodOptions{Options: 0x00}) // GetAccessoryInfo // check back might be useful case *RetAccessoryInfo: // pass case *GetiPodPreferences: ipod.Respond(req, tr, &RetiPodPreferences{ PrefClassID: msg.PrefClassID, PrefClassSettingID: dev.PrefSettingID(msg.PrefClassID), }) case *SetiPodPreferences: dev.SetPrefSettingID(msg.PrefClassID, msg.PrefClassSettingID, ipod.ByteToBool(msg.RestoreOnExit)) ipod.Respond(req, tr, ackSuccess(req)) case *GetUIMode: ipod.Respond(req, tr, &RetUIMode{UIMode: dev.UIMode()}) case *SetUIMode: ipod.Respond(req, tr, ackSuccess(req)) case *StartIDPS: ipod.TrxReset() dev.StartIDPS() ipod.Respond(req, tr, ackSuccess(req)) case *SetFIDTokenValues: for _, token := range msg.FIDTokenValues { dev.SetToken(token) } ipod.Respond(req, tr, ackFIDTokenValues(msg)) case *EndIDPS: dev.EndIDPS(msg.AccEndIDPSStatus) switch msg.AccEndIDPSStatus { case AccEndIDPSStatusContinue: ipod.Respond(req, tr, &IDPSStatus{Status: IDPSStatusOK}) ipod.Send(tr, &GetDevAuthenticationInfo{}) // get dev auth info case AccEndIDPSStatusReset: ipod.Respond(req, tr, &IDPSStatus{Status: IDPSStatusTimeLimitNotExceeded}) case AccEndIDPSStatusAbandon: ipod.Respond(req, tr, &IDPSStatus{Status: IDPSStatusWillNotAccept}) case AccEndIDPSStatusNewLink: //pass } // SetAccStatusNotification, RetAccStatusNotification case *AccessoryStatusNotification: // iPodNotification later case *SetEventNotification: dev.SetEventNotificationMask(msg.EventMask) ipod.Respond(req, tr, ackSuccess(req)) case *GetiPodOptionsForLingo: ipod.Respond(req, tr, &RetiPodOptionsForLingo{ LingoID: msg.LingoID, Options: dev.LingoOptions(msg.LingoID), }) case *GetEventNotification: ipod.Respond(req, tr, &RetEventNotification{ EventMask: dev.EventNotificationMask(), }) case *GetSupportedEventNotification: ipod.Respond(req, tr, &RetSupportedEventNotification{ EventMask: dev.SupportedEventNotificationMask(), }) case *CancelCommand: dev.CancelCommand(msg.LingoID, msg.CmdID, msg.TransactionID) ipod.Respond(req, tr, ackSuccess(req)) case *SetAvailableCurrent: // notify acc case *RequestApplicationLaunch: ipod.Respond(req, tr, ack(req, ACKStatusFailed)) case *GetNowPlayingFocusApp: ipod.Respond(req, tr, &RetNowPlayingFocusApp{AppID: ipod.StringToBytes("")}) case ipod.UnknownPayload: ipod.Respond(req, tr, ack(req, ACKStatusUnkownID)) default: _ = msg } return nil } <|start_filename|>lingo-general/general.go<|end_filename|> package general import ( "bufio" "bytes" "encoding" "encoding/binary" "errors" "io/ioutil" "strings" "github.com/oandrew/ipod" ) func init() { ipod.RegisterLingos(ipod.LingoGeneralID, Lingos) } var Lingos struct { RequestIdentify `id:"0x00"` ACK `id:"0x02"` ACKPending `id:"0x02"` ACKDataDropped `id:"0x02"` RequestRemoteUIMode `id:"0x03"` ReturnRemoteUIMode `id:"0x04"` EnterRemoteUIMode `id:"0x05"` ExitRemoteUIMode `id:"0x06"` RequestiPodName `id:"0x07"` ReturniPodName `id:"0x08"` RequestiPodSoftwareVersion `id:"0x09"` ReturniPodSoftwareVersion `id:"0x0A"` RequestiPodSerialNum `id:"0x0B"` ReturniPodSerialNum `id:"0x0C"` RequestiPodModelNum `id:"0x0D"` ReturniPodModelNum `id:"0x0E"` RequestLingoProtocolVersion `id:"0x0F"` ReturnLingoProtocolVersion `id:"0x10"` RequestTransportMaxPayloadSize `id:"0x11"` ReturnTransportMaxPayloadSize `id:"0x12"` IdentifyDeviceLingoes `id:"0x13"` GetDevAuthenticationInfo `id:"0x14"` //RetDevAuthenticationInfoV1 `id:"0x15"` //RetDevAuthenticationInfoV2 `id:"0x15"` RetDevAuthenticationInfo `id:"0x15"` AckDevAuthenticationInfo `id:"0x16"` GetDevAuthenticationSignatureV1 `id:"0x17"` GetDevAuthenticationSignatureV2 `id:"0x17"` //RetDevAuthenticationSignatureV1 `id:"0x18"` //RetDevAuthenticationSignatureV2 `id:"0x18"` RetDevAuthenticationSignature `id:"0x18"` AckDevAuthenticationStatus `id:"0x19"` GetiPodAuthenticationInfo `id:"0x1A"` RetiPodAuthenticationInfo `id:"0x1B"` AckiPodAuthenticationInfo `id:"0x1C"` GetiPodAuthenticationSignature `id:"0x1D"` RetiPodAuthenticationSignature `id:"0x1E"` AckiPodAuthenticationStatus `id:"0x1F"` NotifyiPodStateChange `id:"0x23"` GetiPodOptions `id:"0x24"` RetiPodOptions `id:"0x25"` GetAccessoryInfo `id:"0x27"` RetAccessoryInfo `id:"0x28"` GetiPodPreferences `id:"0x29"` RetiPodPreferences `id:"0x2A"` SetiPodPreferences `id:"0x2B"` GetUIMode `id:"0x35"` RetUIMode `id:"0x36"` SetUIMode `id:"0x37"` StartIDPS `id:"0x38"` SetFIDTokenValues `id:"0x39"` RetFIDTokenValueACKs `id:"0x3A"` EndIDPS `id:"0x3B"` IDPSStatus `id:"0x3C"` OpenDataSessionForProtocol `id:"0x3F"` CloseDataSession `id:"0x40"` DevACK `id:"0x41"` DevDataTransfer `id:"0x42"` IPodDataTransfer `id:"0x43"` SetAccStatusNotification `id:"0x46"` RetAccStatusNotification `id:"0x47"` AccessoryStatusNotification `id:"0x48"` SetEventNotification `id:"0x49"` IPodNotification `id:"0x4A"` GetiPodOptionsForLingo `id:"0x4B"` RetiPodOptionsForLingo `id:"0x4C"` GetEventNotification `id:"0x4D"` RetEventNotification `id:"0x4E"` GetSupportedEventNotification `id:"0x4F"` CancelCommand `id:"0x50"` RetSupportedEventNotification `id:"0x51"` SetAvailableCurrent `id:"0x54"` RequestApplicationLaunch `id:"0x64"` GetNowPlayingFocusApp `id:"0x65"` RetNowPlayingFocusApp `id:"0x66"` } type RequestIdentify struct{} type ACKStatus uint8 const ( ACKStatusSuccess ACKStatus = 0x00 ACKStatusFailed ACKStatus = 0x02 ACKStatusUnkownID ACKStatus = 0x05 ACKStatusPending ACKStatus = 0x06 ) type ACK struct { Status ACKStatus CmdID uint8 } type ACKPending struct { Status ACKStatus CmdID uint8 MaxWait uint32 } type ACKDataDropped struct { Status ACKStatus CmdID uint8 SessionID uint16 NumBytesDropped uint32 } type RequestRemoteUIMode struct{} type ReturnRemoteUIMode struct { Mode byte } type EnterRemoteUIMode struct{} type ExitRemoteUIMode struct{} type RequestiPodName struct{} type ReturniPodName struct { Name []byte } func (s ReturniPodName) MarshalBinary() ([]byte, error) { return s.Name, nil } func (s *ReturniPodName) UnmarshalBinary(data []byte) error { s.Name = make([]byte, len(data)) copy(s.Name, data) return nil } type RequestiPodSoftwareVersion struct{} type ReturniPodSoftwareVersion struct { Major byte Minor byte Rev byte } type RequestiPodSerialNum struct { } type ReturniPodSerialNum struct { Serial []byte } func (s ReturniPodSerialNum) MarshalBinary() ([]byte, error) { return s.Serial, nil } func (s *ReturniPodSerialNum) UnmarshalBinary(data []byte) error { s.Serial = make([]byte, len(data)) copy(s.Serial, data) return nil } type RequestiPodModelNum struct { } type ReturniPodModelNum struct { ModelID uint32 Model []byte } func (s ReturniPodModelNum) MarshalBinary() ([]byte, error) { var buf bytes.Buffer binary.Write(&buf, binary.BigEndian, s.ModelID) buf.Write(s.Model) return buf.Bytes(), nil } func (s *ReturniPodModelNum) UnmarshalBinary(data []byte) error { buf := bytes.NewBuffer(data) binary.Read(buf, binary.BigEndian, &s.ModelID) model, err := ioutil.ReadAll(buf) if err != nil { return err } s.Model = model return nil } type RequestLingoProtocolVersion struct { Lingo byte } type ReturnLingoProtocolVersion struct { Lingo byte Major byte Minor byte } type RequestTransportMaxPayloadSize struct{} type ReturnTransportMaxPayloadSize struct { MaxPayload uint16 } //go:generate stringer -type=LingoBit type LingoBit uint32 const ( LingoGeneralBit LingoBit = 1 << ipod.LingoGeneralID LingoSimpleRemoteBit LingoBit = 1 << ipod.LingoSimpleRemoteID LingoDisplayRemoteBit LingoBit = 1 << ipod.LingoDisplayRemoteID LingoExtRemoteBit LingoBit = 1 << ipod.LingoExtRemoteID LingoUSBHostBit LingoBit = 1 << ipod.LingoUSBHostID LingoRFTunerBit LingoBit = 1 << ipod.LingoRFTunerID LingoEqBit LingoBit = 1 << ipod.LingoEqID LingoSportsBit LingoBit = 1 << ipod.LingoSportsID LingoDigitalAudioBit LingoBit = 1 << ipod.LingoDigitalAudioID LingoStorageBit LingoBit = 1 << ipod.LingoStorageID ) type LingoMask uint32 func (m *LingoMask) String() string { labels := make([]string, 0, 32) for i := 0; i < 32; i++ { bit := uint32(1 << i) if uint32(*m)&bit != 0 { labels = append(labels, LingoBit(bit).String()) } } return strings.Join(labels, " | ") } type IdentifyDeviceLingoes struct { Lingos LingoMask Options uint32 DeviceID uint32 } type GetDevAuthenticationInfo struct{} // type RetDevAuthenticationInfo struct { // Major byte // Minor byte // } type RetDevAuthenticationInfo struct { Major byte Minor byte CertCurrentSection byte CertMaxSection byte CertData []byte } func (s *RetDevAuthenticationInfo) UnmarshalBinary(r []byte) error { if len(r) < 2 { return errors.New("short packet") } s.Major, s.Minor = r[0], r[1] if s.Major >= 0x02 { if len(r) < 4 { return errors.New("short packet") } s.CertCurrentSection, s.CertMaxSection = r[2], r[3] data := r[4:] s.CertData = make([]byte, len(data)) copy(s.CertData, data) } return nil } type DevAuthInfoStatus uint8 const ( DevAuthInfoStatusSupported DevAuthInfoStatus = 0x00 ) type AckDevAuthenticationInfo struct { Status DevAuthInfoStatus } type GetDevAuthenticationSignatureV1 struct { Challenge [16]byte Counter byte } type GetDevAuthenticationSignatureV2 struct { Challenge [20]byte Counter byte } type RetDevAuthenticationSignature struct { Signature []byte } func (s *RetDevAuthenticationSignature) UnmarshalBinary(r []byte) error { s.Signature = make([]byte, len(r)) copy(s.Signature, r) return nil } type DevAuthStatus uint8 const ( DevAuthStatusPassed DevAuthStatus = 0x00 DevAuthStatusFailed DevAuthStatus = 0x01 ) type AckDevAuthenticationStatus struct { Status DevAuthStatus } type GetiPodAuthenticationInfo struct{} type RetiPodAuthenticationInfo struct { Major byte Minor byte CertCurrentSection byte CertMaxSection byte CertData []byte } type AckiPodAuthenticationInfo struct { Status byte } type GetiPodAuthenticationSignature struct { Challenge [20]byte Counter byte } type RetiPodAuthenticationSignature struct { Signature [20]byte } type AckiPodAuthenticationStatus struct { Status byte } type NotifyiPodStateChange struct { StateChange byte } type GetiPodOptions struct{} type RetiPodOptions struct { Options uint64 } type GetAccessoryInfo struct { InfoType byte } type GetAccessoryInfo2 struct { InfoType byte ModelID uint32 Major byte Minor byte Rev byte } type GetAccessoryInfo3 struct { InfoType byte LingoID byte } type RetAccessoryInfo struct { InfoType byte Data []byte } // type RetAccessoryInfo0 struct { // InfoType byte // Caps uint32 // } // type RetAccessoryInfo1678 struct { // InfoType byte // Data []byte // } // type RetAccessoryInfo2 struct { // InfoType byte // ModelID uint32 // MinMajor byte // MinMinor byte // MinRev byte // } // type RetAccessoryInfo3 struct { // InfoType byte // ModelID uint32 // MinMajor byte // MinMinor byte // MinRev byte // } type GetiPodPreferences struct { PrefClassID byte } type RetiPodPreferences struct { PrefClassID byte PrefClassSettingID byte } type SetiPodPreferences struct { PrefClassID byte PrefClassSettingID byte RestoreOnExit byte } type UIMode uint8 const ( UIModeStandart UIMode = 0x00 UIModeExtended UIMode = 0x01 UIModeiPodOut UIMode = 0x02 ) type GetUIMode struct{} type RetUIMode struct { UIMode UIMode } type SetUIMode struct { UIMode UIMode } type StartIDPS struct{} type FIDIdentifyToken struct { AccLingoes []uint8 DeviceOptions uint32 DeviceID uint32 } func (t *FIDIdentifyToken) MarshalBinary() ([]byte, error) { var buf bytes.Buffer binary.Write(&buf, binary.BigEndian, uint8(len(t.AccLingoes))) binary.Write(&buf, binary.BigEndian, t.AccLingoes) binary.Write(&buf, binary.BigEndian, t.DeviceOptions) binary.Write(&buf, binary.BigEndian, t.DeviceID) return buf.Bytes(), nil } func (t *FIDIdentifyToken) UnmarshalBinary(data []byte) error { r := bytes.NewReader(data) numLingoes, err := r.ReadByte() if err != nil { return err } t.AccLingoes = make([]uint8, numLingoes) binary.Read(r, binary.BigEndian, &t.AccLingoes) binary.Read(r, binary.BigEndian, &t.DeviceOptions) binary.Read(r, binary.BigEndian, &t.DeviceID) return nil } //go:generate stringer -type=AccCapBit type AccCapBit uint32 const ( AccCapAnalogLineOut AccCapBit = 1 << iota AccCapAnalogLineIn AccCapAnalogVideoOut _ AccCapUSBAudio _ _ _ _ AccCapAppComm _ AccCapCheckVolume ) var AccCaps = []AccCapBit{ AccCapAnalogLineOut, AccCapAnalogLineIn, AccCapAnalogVideoOut, AccCapUSBAudio, AccCapAppComm, AccCapCheckVolume, } type FIDAccCapsToken struct { AccCapsBitmask uint64 } func (t *FIDAccCapsToken) UnmarshalBinary(data []byte) error { r := bytes.NewReader(data) binary.Read(r, binary.BigEndian, &t.AccCapsBitmask) return nil } //go:generate stringer -type=AccInfoType type AccInfoType uint8 const ( AccInfoName AccInfoType = 0x01 AccInfoFirmware AccInfoType = 0x04 AccInfoHardware AccInfoType = 0x05 AccInfoMfr AccInfoType = 0x06 AccInfoModel AccInfoType = 0x07 AccInfoSerial AccInfoType = 0x08 AccInfoMaxPayload AccInfoType = 0x09 ) type FIDAccInfoToken struct { AccInfoType byte Value interface{} } func (t *FIDAccInfoToken) UnmarshalBinary(data []byte) error { r := bytes.NewReader(data) binary.Read(r, binary.BigEndian, &t.AccInfoType) switch t.AccInfoType { //name case 0x01, 0x06, 0x07, 0x08: t.Value, _ = bufio.NewReader(r).ReadBytes(0x00) case 0x04, 0x05: v := make([]byte, 3) r.Read(v) t.Value = v case 0x09: v := make([]byte, 2) r.Read(v) t.Value = v case 0x0b, 0x0c: v := make([]byte, 4) r.Read(v) t.Value = v default: return errors.New("unknown AccInfoToken type") } return nil } type FIDiPodPreferenceToken struct { PrefClass byte PrefClassSetting byte RestoreOnExit byte } type FIDEAProtocolToken struct { ProtocolIndex byte ProtocolString []byte } func (t *FIDEAProtocolToken) UnmarshalBinary(data []byte) error { t.ProtocolIndex = data[0] t.ProtocolString = data[1:] return nil } type FIDBundleSeedIDPrefToken struct { BundleSeedIDString [11]byte } type FIDScreenInfoToken struct { ScreenWidthInches uint16 ScreenHeightInches uint16 ScreenWidthPixels uint16 ScreenHeightPixels uint16 IpodScreenWidthPixels uint16 IpodScreenHeightPixels uint16 ScreenFeaturesMask byte ScreenGammaValue byte } type FIDEAProtocolMetadataToken struct { ProtocolIndex byte MetadataType byte } type FIDMicrophoneCapsToken struct { MicCapsBitmask uint32 } type TokenID struct { FIDType byte FIDSubtype byte } type FIDTokenValue struct { ID TokenID Token interface{} } func (v *FIDTokenValue) MarshalBinary() ([]byte, error) { var buf bytes.Buffer if err := binary.Write(&buf, binary.BigEndian, v.ID); err != nil { return nil, err } if bu, ok := v.Token.(encoding.BinaryMarshaler); ok { b, err := bu.MarshalBinary() if err != nil { return nil, err } buf.Write(b) } else if binary.Size(v.Token) != -1 { if err := binary.Write(&buf, binary.BigEndian, v.Token); err != nil { return nil, err } } else if b, ok := v.Token.([]byte); ok { buf.Write(b) } else { return nil, errors.New("unknown token") } return buf.Bytes(), nil } func (v *FIDTokenValue) UnmarshalBinary(data []byte) error { br := bytes.NewBuffer(data) if err := binary.Read(br, binary.BigEndian, &v.ID); err != nil { return err } switch v.ID.FIDType { case 0x00: switch v.ID.FIDSubtype { case 0x00: //identify v.Token = &FIDIdentifyToken{} case 0x01: //acc caps v.Token = &FIDAccCapsToken{} case 0x02: //accinfo v.Token = &FIDAccInfoToken{} case 0x03: //ipod pref v.Token = &FIDiPodPreferenceToken{} case 0x04: //sdk proto v.Token = &FIDEAProtocolToken{} case 0x05: // bundleseed v.Token = &FID<PASSWORD>Token{} case 0x07: // screen info v.Token = &FIDScreenInfoToken{} case 0x08: // eaprotometadata v.Token = &F<PASSWORD>Token{} } case 0x01: //mic v.Token = &F<PASSWORD>Token{} } if bu, ok := v.Token.(encoding.BinaryUnmarshaler); ok { if err := bu.UnmarshalBinary(br.Bytes()); err != nil { return err } } else if binary.Size(v.Token) != -1 { return binary.Read(br, binary.BigEndian, v.Token) } else { p := make([]byte, br.Len()) copy(p, br.Bytes()) v.Token = p } return nil } type SetFIDTokenValues struct { FIDTokenValues []FIDTokenValue } func (s *SetFIDTokenValues) MarshalBinary() ([]byte, error) { var buf bytes.Buffer buf.WriteByte(byte(len(s.FIDTokenValues))) for i := range s.FIDTokenValues { tokenBytes, err := s.FIDTokenValues[i].MarshalBinary() if err != nil { return nil, err } buf.WriteByte(byte(len(tokenBytes))) buf.Write(tokenBytes) } return buf.Bytes(), nil } func (s *SetFIDTokenValues) UnmarshalBinary(data []byte) error { br := bytes.NewBuffer(data) tokenCount, err := br.ReadByte() if err != nil { return err } s.FIDTokenValues = make([]FIDTokenValue, tokenCount) for i := range s.FIDTokenValues { tokenLen, err := br.ReadByte() if err != nil { return err } tokenValue := &s.FIDTokenValues[i] tokenBytes := br.Next(int(tokenLen)) if err := tokenValue.UnmarshalBinary(tokenBytes); err != nil { return err } } return nil } type FIDTokenValueACK struct { ID TokenID ACK interface{} } func (v *FIDTokenValueACK) MarshalBinary() ([]byte, error) { var buf bytes.Buffer if err := binary.Write(&buf, binary.BigEndian, v.ID); err != nil { return nil, err } if bu, ok := v.ACK.(encoding.BinaryMarshaler); ok { b, err := bu.MarshalBinary() if err != nil { return nil, err } buf.Write(b) } else if binary.Size(v.ACK) != -1 { if err := binary.Write(&buf, binary.BigEndian, v.ACK); err != nil { return nil, err } } else if b, ok := v.ACK.([]byte); ok { buf.Write(b) } else { return nil, errors.New("unknown ack") } return buf.Bytes(), nil } func (v *FIDTokenValueACK) UnmarshalBinary(data []byte) error { br := bytes.NewBuffer(data) if err := binary.Read(br, binary.BigEndian, &v.ID); err != nil { return err } p := make([]byte, br.Len()) copy(p, br.Bytes()) v.ACK = p return nil } type RetFIDTokenValueACKs struct { FIDTokenValueACKs []FIDTokenValueACK } func (s RetFIDTokenValueACKs) MarshalBinary() ([]byte, error) { var buf bytes.Buffer buf.WriteByte(byte(len(s.FIDTokenValueACKs))) for i := range s.FIDTokenValueACKs { ackBytes, err := s.FIDTokenValueACKs[i].MarshalBinary() if err != nil { return nil, err } buf.WriteByte(byte(len(ackBytes))) buf.Write(ackBytes) } return buf.Bytes(), nil } func (s *RetFIDTokenValueACKs) UnmarshalBinary(data []byte) error { br := bytes.NewBuffer(data) ackCount, err := br.ReadByte() if err != nil { return err } s.FIDTokenValueACKs = make([]FIDTokenValueACK, ackCount) for i := range s.FIDTokenValueACKs { ackLen, err := br.ReadByte() if err != nil { return err } ackValue := &s.FIDTokenValueACKs[i] ackBytes := br.Next(int(ackLen)) if err := ackValue.UnmarshalBinary(ackBytes); err != nil { return err } } return nil } type AccEndIDPSStatus uint8 const ( AccEndIDPSStatusContinue AccEndIDPSStatus = 0x00 AccEndIDPSStatusReset AccEndIDPSStatus = 0x01 AccEndIDPSStatusAbandon AccEndIDPSStatus = 0x02 AccEndIDPSStatusNewLink AccEndIDPSStatus = 0x03 ) type EndIDPS struct { AccEndIDPSStatus AccEndIDPSStatus } type IDPSStatusEnum uint8 const ( IDPSStatusOK IDPSStatusEnum = 0x00 IDPSStatusTimeLimitNotExceeded IDPSStatusEnum = 0x04 IDPSStatusWillNotAccept IDPSStatusEnum = 0x06 ) type IDPSStatus struct { Status IDPSStatusEnum } type OpenDataSessionForProtocol struct { SessionID uint16 ProtocolIndex byte } type CloseDataSession struct { SessionID uint16 } type DevACK struct { AckStatus byte CmdID byte } type DevDataTransfer struct { SessionID uint16 Data []byte } type IPodDataTransfer struct { SessionID uint16 Data []byte } type SetAccStatusNotification struct { StatusMask uint32 } type RetAccStatusNotification struct { StatusMask uint32 } type AccessoryStatusNotification struct { StatusType byte StatusParams []byte } type SetEventNotification struct { EventMask uint64 } type IPodNotification struct { NotificationType byte Data []byte } type GetiPodOptionsForLingo struct { LingoID byte } type RetiPodOptionsForLingo struct { LingoID byte Options uint64 } type GetEventNotification struct{} type RetEventNotification struct { EventMask uint64 } type GetSupportedEventNotification struct{} type CancelCommand struct { LingoID byte CmdID uint16 TransactionID uint16 } type RetSupportedEventNotification struct { EventMask uint64 } type SetAvailableCurrent struct { CurrentLimit uint16 } type RequestApplicationLaunch struct { Reserved0 byte Reserved1 byte Reserved2 byte AppID []byte } func (s *RequestApplicationLaunch) UnmarshalBinary(data []byte) error { s.Reserved0 = data[0] s.Reserved1 = data[1] s.Reserved2 = data[2] s.AppID = append([]byte(nil), data[3:]...) return nil } type GetNowPlayingFocusApp struct{} type RetNowPlayingFocusApp struct { AppID []byte } <|start_filename|>packet.go<|end_filename|> // Package ipod implements the iPod Accessory protocol (iap) package ipod import ( "bytes" "encoding/binary" "errors" "fmt" "io" ) const ( PacketStartByte byte = 0x55 ) const ( rawSmallPacketMinLen = 1 + 1 + 2 // start + len + ids rawLargePacketMinLen = 1 + 3 + 2 // start + len + ids largePacketMinLen = 256 minPacketBufSize = 1024 ) type PacketReader struct { frame []byte } func NewPacketReader(frame []byte) *PacketReader { return &PacketReader{ frame: frame, } } func parseHeader(data []byte) (payOff, payLen int, err error) { if len(data) < 3 { err = io.ErrUnexpectedEOF return } if data[0] == 0x00 { payOff = 3 payLen = int(binary.BigEndian.Uint16(data[1:3])) } else { payOff = 1 payLen = int(data[0]) } return } func parsePacket(data []byte) (int, []byte, error) { payOff, payLen, err := parseHeader(data) if err != nil { return 0, nil, err } pktLen := payOff + payLen + 1 pkt := data[:pktLen] if len(pkt) < pktLen { return pktLen, nil, io.ErrUnexpectedEOF } if Checksum(pkt) != 0x00 { return pktLen, nil, errors.New("invalid checksum") } return pktLen, pkt[payOff : payOff+payLen], nil } func (pd *PacketReader) ReadPacket() ([]byte, error) { next := bytes.IndexByte(pd.frame, PacketStartByte) if next == -1 { return nil, io.EOF } pd.frame = pd.frame[next+1:] pktLen, payload, err := parsePacket(pd.frame) if err != nil { return nil, err } pd.frame = pd.frame[pktLen:] return payload, nil } type PacketWriter struct { frame []byte } func NewPacketWriter() *PacketWriter { return &PacketWriter{ frame: make([]byte, 0, 512), } } func (pw *PacketWriter) WritePacket(payload []byte) error { if len(payload) == 0 { return fmt.Errorf("packet encode: empty packet") } pw.frame = append(pw.frame, PacketStartByte) pktStart := len(pw.frame) if len(payload) > largePacketMinLen { var pktLen [3]byte binary.BigEndian.PutUint16(pktLen[1:], uint16(len(payload))) pw.frame = append(pw.frame, pktLen[:]...) } else { pw.frame = append(pw.frame, byte(len(payload))) } pw.frame = append(pw.frame, payload...) pw.frame = append(pw.frame, Checksum(pw.frame[pktStart:])) return nil } func (pw *PacketWriter) Bytes() []byte { return pw.frame } <|start_filename|>lingo-extremote/handler.go<|end_filename|> package extremote import ( "github.com/oandrew/ipod" ) type DeviceExtRemote interface { PlaybackStatus() (trackLength, trackPos uint32, state PlayerState) } func ackSuccess(req *ipod.Command) *ACK { return &ACK{Status: ACKStatusSuccess, CmdID: req.ID.CmdID()} } // func ackPending(req ipod.Packet, maxWait uint32) ACKPending { // return ACKPending{Status: ACKStatusPending, CmdID: uint8(req.ID.CmdID()), MaxWait: maxWait} // } func HandleExtRemote(req *ipod.Command, tr ipod.CommandWriter, dev DeviceExtRemote) error { //log.Printf("Req: %#v", req) switch msg := req.Payload.(type) { case *GetCurrentPlayingTrackChapterInfo: ipod.Respond(req, tr, &ReturnCurrentPlayingTrackChapterInfo{ CurrentChapterIndex: 0, ChapterCount: 1, }) case *SetCurrentPlayingTrackChapter: ipod.Respond(req, tr, ackSuccess(req)) case *GetCurrentPlayingTrackChapterPlayStatus: ipod.Respond(req, tr, &ReturnCurrentPlayingTrackChapterPlayStatus{ ChapterPosition: 0, ChapterLength: 0, }) case *GetCurrentPlayingTrackChapterName: ipod.Respond(req, tr, &ReturnCurrentPlayingTrackChapterName{ ChapterName: ipod.StringToBytes("chapter"), }) case *GetAudiobookSpeed: ipod.Respond(req, tr, &ReturnAudiobookSpeed{ Speed: 0, }) case *SetAudiobookSpeed: ipod.Respond(req, tr, ackSuccess(req)) case *GetIndexedPlayingTrackInfo: var info interface{} switch msg.InfoType { case TrackInfoCaps: info = &TrackCaps{ Caps: 0x0, TrackLength: 300 * 1000, ChapterCount: 1, } case TrackInfoDescription, TrackInfoLyrics: info = &TrackLongText{ Flags: 0x0, PacketIndex: 0, Text: 0x00, } case TrackInfoArtworkCount: info = struct{}{} default: info = []byte{0x00} } ipod.Respond(req, tr, &ReturnIndexedPlayingTrackInfo{ InfoType: msg.InfoType, Info: info, }) case *GetArtworkFormats: ipod.Respond(req, tr, &RetArtworkFormats{}) case *GetTrackArtworkData: ipod.Respond(req, tr, &ACK{ Status: ACKStatusFailed, CmdID: req.ID.CmdID(), }) case *ResetDBSelection: ipod.Respond(req, tr, ackSuccess(req)) case *SelectDBRecord: ipod.Respond(req, tr, ackSuccess(req)) case *GetNumberCategorizedDBRecords: ipod.Respond(req, tr, &ReturnNumberCategorizedDBRecords{ RecordCount: 1, }) case *RetrieveCategorizedDatabaseRecords: ipod.Respond(req, tr, &ReturnCategorizedDatabaseRecord{}) case *GetPlayStatus: ipod.Respond(req, tr, &ReturnPlayStatus{ TrackLength: 300 * 1000, TrackPosition: 20 * 1000, State: PlayerStatePaused, }) case *GetCurrentPlayingTrackIndex: ipod.Respond(req, tr, &ReturnCurrentPlayingTrackIndex{ TrackIndex: 0, }) case *GetIndexedPlayingTrackTitle: ipod.Respond(req, tr, &ReturnIndexedPlayingTrackTitle{ Title: ipod.StringToBytes("title"), }) case *GetIndexedPlayingTrackArtistName: ipod.Respond(req, tr, &ReturnIndexedPlayingTrackArtistName{ ArtistName: ipod.StringToBytes("artist"), }) case *GetIndexedPlayingTrackAlbumName: ipod.Respond(req, tr, &ReturnIndexedPlayingTrackAlbumName{ AlbumName: ipod.StringToBytes("album"), }) case *SetPlayStatusChangeNotification: ipod.Respond(req, tr, ackSuccess(req)) case *SetPlayStatusChangeNotificationShort: ipod.Respond(req, tr, ackSuccess(req)) case *PlayCurrentSelection: ipod.Respond(req, tr, ackSuccess(req)) case *PlayControl: ipod.Respond(req, tr, ackSuccess(req)) case *GetTrackArtworkTimes: ipod.Respond(req, tr, &RetTrackArtworkTimes{}) case *GetShuffle: ipod.Respond(req, tr, &ReturnShuffle{Mode: ShuffleOff}) case *SetShuffle: ipod.Respond(req, tr, ackSuccess(req)) case *GetRepeat: ipod.Respond(req, tr, &ReturnRepeat{Mode: RepeatOff}) case *SetRepeat: ipod.Respond(req, tr, ackSuccess(req)) case *SetDisplayImage: ipod.Respond(req, tr, ackSuccess(req)) case *GetMonoDisplayImageLimits: ipod.Respond(req, tr, &ReturnMonoDisplayImageLimits{ MaxWidth: 640, MaxHeight: 960, PixelFormat: 0x01, }) case *GetNumPlayingTracks: ipod.Respond(req, tr, &ReturnNumPlayingTracks{ NumTracks: 1, }) case *SetCurrentPlayingTrack: case *SelectSortDBRecord: case *GetColorDisplayImageLimits: ipod.Respond(req, tr, &ReturnColorDisplayImageLimits{ MaxWidth: 640, MaxHeight: 960, PixelFormat: 0x01, }) case *ResetDBSelectionHierarchy: ipod.Respond(req, tr, &ACK{Status: ACKStatusFailed, CmdID: req.ID.CmdID()}) case *GetDBiTunesInfo: // RetDBiTunesInfo: case *GetUIDTrackInfo: // RetUIDTrackInfo: case *GetDBTrackInfo: // RetDBTrackInfo: case *GetPBTrackInfo: // RetPBTrackInfo: default: _ = msg } return nil } <|start_filename|>hid/hid_test.go<|end_filename|> package hid_test import ( "io" "io/ioutil" "reflect" "testing" "github.com/oandrew/ipod/hid" ) type testReportWriter struct { reports []hid.Report } func (rw *testReportWriter) WriteReport(report hid.Report) error { rw.reports = append(rw.reports, report) return nil } type testReportReader struct { offset int reports []hid.Report } func (rr *testReportReader) ReadReport() (hid.Report, error) { if rr.offset >= len(rr.reports) { return hid.Report{}, io.EOF } defer func() { rr.offset++ }() return rr.reports[rr.offset], nil } var testReportDefs1 = hid.ReportDefs{ hid.ReportDef{ID: 0x01, Len: 2, Dir: hid.ReportDirAccIn}, } var testReportDefs2 = hid.ReportDefs{ hid.ReportDef{ID: 0x01, Len: 2, Dir: hid.ReportDirAccIn}, hid.ReportDef{ID: 0x02, Len: 3, Dir: hid.ReportDirAccIn}, } var testReportDefs3 = hid.ReportDefs{ hid.ReportDef{ID: 0x01, Len: 4, Dir: hid.ReportDirAccIn}, } func TestEncoder(t *testing.T) { tests := []struct { name string reportDefs hid.ReportDefs data []byte want []hid.Report wantErr bool }{ {"report-1-pkt-1", testReportDefs1, []byte{0x01}, []hid.Report{ {ID: 0x01, LinkControl: hid.LinkControlDone, Data: []byte{0x01}}, }, false}, {"report-1-pkt-2", testReportDefs1, []byte{0x01, 0x02}, []hid.Report{ {ID: 0x01, LinkControl: hid.LinkControlMoreToFollow, Data: []byte{0x01}}, {ID: 0x01, LinkControl: hid.LinkControlContinue, Data: []byte{0x02}}, }, false}, {"report-1-pkt-3", testReportDefs1, []byte{0x01, 0x02, 0x03}, []hid.Report{ {ID: 0x01, LinkControl: hid.LinkControlMoreToFollow, Data: []byte{0x01}}, {ID: 0x01, LinkControl: hid.LinkControlContinue | hid.LinkControlMoreToFollow, Data: []byte{0x02}}, {ID: 0x01, LinkControl: hid.LinkControlContinue, Data: []byte{0x03}}, }, false}, {"report-2-pkt-1", testReportDefs2, []byte{0x01}, []hid.Report{ {ID: 0x01, LinkControl: hid.LinkControlDone, Data: []byte{0x01}}, }, false}, {"report-2-pkt-2", testReportDefs2, []byte{0x01, 0x02}, []hid.Report{ {ID: 0x02, LinkControl: hid.LinkControlDone, Data: []byte{0x01, 0x02}}, }, false}, {"report-2-pkt-3", testReportDefs2, []byte{0x01, 0x02, 0x03}, []hid.Report{ {ID: 0x02, LinkControl: hid.LinkControlMoreToFollow, Data: []byte{0x01, 0x02}}, {ID: 0x01, LinkControl: hid.LinkControlContinue, Data: []byte{0x03}}, }, false}, {"report-3-pkt-1", testReportDefs3, []byte{0x01, 0x02}, []hid.Report{ {ID: 0x01, LinkControl: hid.LinkControlDone, Data: []byte{0x01, 0x02, 0x00}}, }, false}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { rw := &testReportWriter{} enc := hid.NewEncoder(rw, tt.reportDefs) err := enc.WriteFrame(tt.data) if (err != nil) != tt.wantErr { t.Errorf("TestHidEncoder() error = %v, wantErr %v", err, tt.wantErr) return } if !reflect.DeepEqual(rw.reports, tt.want) { t.Errorf("TestHidEncoder() = [%+v], want [%+v]", rw.reports, tt.want) } }) } } func TestHidDecoder(t *testing.T) { tests := []struct { name string reportDefs hid.ReportDefs want []byte reports []hid.Report wantErr bool }{ {"report-1-pkt-1", testReportDefs1, []byte{0x01}, []hid.Report{ {ID: 0x01, LinkControl: hid.LinkControlDone, Data: []byte{0x01}}, }, false}, {"report-1-pkt-2", testReportDefs1, []byte{0x01, 0x02}, []hid.Report{ {ID: 0x01, LinkControl: hid.LinkControlMoreToFollow, Data: []byte{0x01}}, {ID: 0x01, LinkControl: hid.LinkControlContinue, Data: []byte{0x02}}, }, false}, {"report-1-pkt-3", testReportDefs1, []byte{0x01, 0x02, 0x03}, []hid.Report{ {ID: 0x01, LinkControl: hid.LinkControlMoreToFollow, Data: []byte{0x01}}, {ID: 0x01, LinkControl: hid.LinkControlContinue | hid.LinkControlMoreToFollow, Data: []byte{0x02}}, {ID: 0x01, LinkControl: hid.LinkControlContinue, Data: []byte{0x03}}, }, false}, {"report-2-pkt-1", testReportDefs2, []byte{0x01}, []hid.Report{ {ID: 0x01, LinkControl: hid.LinkControlDone, Data: []byte{0x01}}, }, false}, {"report-2-pkt-2", testReportDefs2, []byte{0x01, 0x02}, []hid.Report{ {ID: 0x02, LinkControl: hid.LinkControlDone, Data: []byte{0x01, 0x02}}, }, false}, {"report-2-pkt-3", testReportDefs2, []byte{0x01, 0x02, 0x03}, []hid.Report{ {ID: 0x02, LinkControl: hid.LinkControlMoreToFollow, Data: []byte{0x01, 0x02}}, {ID: 0x01, LinkControl: hid.LinkControlContinue, Data: []byte{0x03}}, }, false}, {"report-3-pkt-1", testReportDefs3, []byte{0x01, 0x02, 0x00}, []hid.Report{ {ID: 0x01, LinkControl: hid.LinkControlDone, Data: []byte{0x01, 0x02, 0x00}}, }, false}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { rr := &testReportReader{ reports: tt.reports, } dec := hid.NewDecoder(rr, tt.reportDefs) payload, err := dec.ReadFrame() if (err != nil) != tt.wantErr { t.Errorf("TestHidDecoder() error = %v, wantErr %v", err, tt.wantErr) return } if !reflect.DeepEqual(payload, tt.want) { t.Errorf("TestHidDecoder() = %v, want %v", payload, tt.want) } }) } } func BenchmarkDecoder(b *testing.B) { report := []byte{ 0x12, 0x00, 0x55, 0x28, 0x0a, 0x03, 0x03, 0xe7, 0x00, 0x00, 0x1f, 0x40, 0x00, 0x00, 0x2b, 0x11, 0x00, 0x00, 0x2e, 0xe0, 0x00, 0x00, 0x3e, 0x80, 0x00, 0x00, 0x56, 0x22, 0x00, 0x00, 0x5d, 0xc0, 0x00, 0x00, 0x7d, 0x00, 0x00, 0x00, 0xac, 0x44, 0x00, 0x00, 0xbb, 0x80, 0x3d, 0x00, 0x00, 0x00, 0x00, } r := hid.SingleReport(report) d := hid.NewDecoderDefault(r) for i := 0; i < b.N; i++ { d.ReadFrame() } } func BenchmarkEncoder(b *testing.B) { frame := []byte{ 0x55, 0x28, 0x0a, 0x03, 0x03, 0xe7, 0x00, 0x00, 0x1f, 0x40, 0x00, 0x00, 0x2b, 0x11, 0x00, 0x00, 0x2e, 0xe0, 0x00, 0x00, 0x3e, 0x80, 0x00, 0x00, 0x56, 0x22, 0x00, 0x00, 0x5d, 0xc0, 0x00, 0x00, 0x7d, 0x00, 0x00, 0x00, 0xac, 0x44, 0x00, 0x00, 0xbb, 0x80, 0x3d, 0x00, 0x00, 0x00, 0x00, } e := hid.NewEncoderDefault(hid.NewReportWriter(ioutil.Discard)) for i := 0; i < b.N; i++ { e.WriteFrame(frame) } } <|start_filename|>lingo-dispremote/handler.go<|end_filename|> package dispremote import ( "errors" "time" "github.com/oandrew/ipod" ) type DeviceDispRemote interface { } func ackSuccess(req *ipod.Command) *ACK { return &ACK{Status: ACKStatusSuccess, CmdID: uint8(req.ID.CmdID())} } func HandleDispRemote(req *ipod.Command, tr ipod.CommandWriter, dev DeviceDispRemote) error { switch msg := req.Payload.(type) { case *GetCurrentEQProfileIndex: ipod.Respond(req, tr, &RetCurrentEQProfileIndex{ CurrentEQIndex: 0, }) case *SetCurrentEQProfileIndex: ipod.Respond(req, tr, ackSuccess(req)) case *GetNumEQProfiles: ipod.Respond(req, tr, &RetNumEQProfiles{ NumEQProfiles: 1, }) case *GetIndexedEQProfileName: ipod.Respond(req, tr, &RetIndexedEQProfileName{ EQProfileName: ipod.StringToBytes("Default"), }) case *SetRemoteEventNotification: ipod.Respond(req, tr, ackSuccess(req)) case *GetRemoteEventStatus: ipod.Respond(req, tr, &RetRemoteEventStatus{ EventStatus: 0, }) case *GetiPodStateInfo: t := &RetiPodStateInfo{ InfoType: msg.InfoType, } switch msg.InfoType { case InfoTypeTrackPositionMs: t.InfoData = &InfoTrackPositionMs{TrackPositionMs: 0} case InfoTypeTrackIndex: t.InfoData = &InfoTrackIndex{TrackIndex: 1} case InfoTypeChapterIndex: t.InfoData = &InfoChapterIndex{ TrackIndex: 0, ChapterCount: 0, ChapterIndex: 0, } case InfoTypePlayStatus: t.InfoData = &InfoPlayStatus{ PlayStatus: PlayStatusPlaying, } case InfoTypeVolume: t.InfoData = &InfoVolume{MuteState: 0x00, UIVolumeLevel: 255} case InfoTypePower: t.InfoData = &InfoPower{PowerState: 0x05, BatteryLevel: 255} case InfoTypeEqualizer: t.InfoData = &InfoEqualizer{0x00} case InfoTypeShuffle: t.InfoData = &InfoShuffle{0x00} case InfoTypeRepeat: t.InfoData = &InfoRepeat{0x00} case InfoTypeDateTime: d := time.Now() t.InfoData = &InfoDateTime{ Year: uint16(d.Year()), Month: uint8(d.Month()), Day: uint8(d.Day()), Hour: uint8(d.Hour()), Minute: uint8(d.Minute()), } case InfoTypeBacklight: t.InfoData = &InfoBacklight{BacklightLevel: 255} case InfoTypeHoldSwitch: t.InfoData = &InfoHoldSwitch{HoldSwitchState: 0x00} case InfoTypeSoundCheck: t.InfoData = &InfoSoundCheck{SoundCheckState: 0x00} case InfoTypeAudiobookSpeed: t.InfoData = &InfoAudiobookSpeed{0x00} case InfoTypeTrackPositionSec: t.InfoData = &InfoTrackPositionSec{0} case InfoTypeVolume2: t.InfoData = &InfoVolume2{ MuteState: 0x00, UIVolumeLevel: 255, AbsoluteVolumeLevel: 255, } default: return errors.New("unknown info type") } ipod.Respond(req, tr, t) case *SetiPodStateInfo: ipod.Respond(req, tr, ackSuccess(req)) case *GetPlayStatus: ipod.Respond(req, tr, &RetPlayStatus{ PlayState: 0, //stopped }) case *SetCurrentPlayingTrack: ipod.Respond(req, tr, ackSuccess(req)) case *GetIndexedPlayingTrackInfo: t := &RetIndexedPlayingTrackInfo{ InfoType: msg.InfoType, } switch msg.InfoType { case TrackInfoTypeCaps: t.InfoData = &TrackInfoCaps{ Caps: 0x00, TrackTotalMs: 300000, ChapterCount: 0, } case TrackInfoTypeChapterTimeName: t.InfoData = &TrackInfoChapterTimeName{ ChapterTime: 0, ChapterName: ipod.StringToBytes(""), } case TrackInfoTypeArtist: t.InfoData = &TrackInfoArtist{ Name: ipod.StringToBytes(""), } case TrackInfoTypeAlbum: t.InfoData = &TrackInfoAlbum{ Name: ipod.StringToBytes(""), } case TrackInfoTypeGenre: t.InfoData = &TrackInfoGenre{ Name: ipod.StringToBytes(""), } case TrackInfoTypeTrack: t.InfoData = &TrackInfoTrack{ Title: ipod.StringToBytes("track"), } case TrackInfoTypeComposer: t.InfoData = &TrackInfoComposer{ Name: ipod.StringToBytes(""), } case TrackInfoTypeLyrics: t.InfoData = &TrackInfoLyrics{ Flags: 0x00, PacketIndex: 0, Lyrics: ipod.StringToBytes(""), } case TrackInfoTypeArtworkCount: t.InfoData = &TrackInfoArtworkCount{ None: 0x08, } default: return errors.New("unknown info type") } ipod.Respond(req, tr, t) case *GetNumPlayingTracks: ipod.Respond(req, tr, &RetNumPlayingTracks{ NumPlayTracks: 0, }) case *GetArtworkFormats: ipod.Respond(req, tr, &RetArtworkFormats{}) case *GetTrackArtworkData: // RetTrackArtworkData: //todo case *GetPowerBatteryState: ipod.Respond(req, tr, &RetPowerBatteryState{ BatteryLevel: 255, // 100% PowerState: 0x01, }) case *GetSoundCheckState: ipod.Respond(req, tr, &RetSoundCheckState{ Enabled: false, }) case *SetSoundCheckState: ipod.Respond(req, tr, ackSuccess(req)) case *GetTrackArtworkTimes: ipod.Respond(req, tr, &RetTrackArtworkTimes{}) default: _ = msg } return nil } <|start_filename|>lingo-dispremote/trackinfotype_string.go<|end_filename|> // Code generated by "stringer -type=TrackInfoType"; DO NOT EDIT. package dispremote import "strconv" func _() { // An "invalid array index" compiler error signifies that the constant values have changed. // Re-run the stringer command to generate them again. var x [1]struct{} _ = x[TrackInfoTypeCaps-0] _ = x[TrackInfoTypeChapterTimeName-1] _ = x[TrackInfoTypeArtist-2] _ = x[TrackInfoTypeAlbum-3] _ = x[TrackInfoTypeGenre-4] _ = x[TrackInfoTypeTrack-5] _ = x[TrackInfoTypeComposer-6] _ = x[TrackInfoTypeLyrics-7] _ = x[TrackInfoTypeArtworkCount-8] } const _TrackInfoType_name = "TrackInfoTypeCapsTrackInfoTypeChapterTimeNameTrackInfoTypeArtistTrackInfoTypeAlbumTrackInfoTypeGenreTrackInfoTypeTrackTrackInfoTypeComposerTrackInfoTypeLyricsTrackInfoTypeArtworkCount" var _TrackInfoType_index = [...]uint8{0, 17, 45, 64, 82, 100, 118, 139, 158, 183} func (i TrackInfoType) String() string { if i >= TrackInfoType(len(_TrackInfoType_index)-1) { return "TrackInfoType(" + strconv.FormatInt(int64(i), 10) + ")" } return _TrackInfoType_name[_TrackInfoType_index[i]:_TrackInfoType_index[i+1]] } <|start_filename|>lingo.go<|end_filename|> package ipod import ( "bytes" "encoding/binary" "fmt" "io" "reflect" "sort" "strconv" ) // LingoCmdID represents Lingo ID and Command ID type LingoCmdID uint32 func (id LingoCmdID) LingoID() uint8 { return uint8(id >> 16 & 0xff) } func (id LingoCmdID) CmdID() uint16 { return uint16(id & 0xffff) } func (id LingoCmdID) GoString() string { return fmt.Sprintf("(%#02x|%#0*x)", id.LingoID(), cmdIDLen(id.LingoID())*2, id.CmdID()) } func (id LingoCmdID) String() string { return fmt.Sprintf("%#02x,%#0*x", id.LingoID(), cmdIDLen(id.LingoID())*2, id.CmdID()) } func cmdIDLen(lingoID uint8) int { switch lingoID { case LingoExtRemoteID: return 2 default: return 1 } } func marshalLingoCmdID(w io.Writer, id LingoCmdID) error { err := binary.Write(w, binary.BigEndian, byte(id.LingoID())) if err != nil { return err } switch cmdIDLen(id.LingoID()) { case 2: return binary.Write(w, binary.BigEndian, uint16(id.CmdID())) default: return binary.Write(w, binary.BigEndian, byte(id.CmdID())) } } func unmarshalLingoCmdID(r io.Reader, id *LingoCmdID) error { var lingoID uint8 err := binary.Read(r, binary.BigEndian, &lingoID) if err != nil { return err } switch cmdIDLen(lingoID) { case 2: var cmdID uint16 err := binary.Read(r, binary.BigEndian, &cmdID) if err != nil { return err } *id = NewLingoCmdID(uint16(lingoID), uint16(cmdID)) return nil default: var cmdID uint8 err := binary.Read(r, binary.BigEndian, &cmdID) if err != nil { return err } *id = NewLingoCmdID(uint16(lingoID), uint16(cmdID)) return nil } } func NewLingoCmdID(lingo, cmd uint16) LingoCmdID { return LingoCmdID(uint32(lingo)<<16 | uint32(cmd)) } func parseIdTag(tag *reflect.StructTag) (uint16, error) { id, err := strconv.ParseUint(tag.Get("id"), 0, 16) return uint16(id), err } var mIDToType = make(map[LingoCmdID][]reflect.Type) var mTypeToID = make(map[reflect.Type]LingoCmdID) func storeMapping(cmd LingoCmdID, t reflect.Type) { mIDToType[cmd] = append(mIDToType[cmd], t) mTypeToID[t] = cmd } // RegisterLingos registers a set of lingo commands func RegisterLingos(lingoID uint8, m interface{}) error { lingos := reflect.TypeOf(m) for i := 0; i < lingos.NumField(); i++ { cmd := lingos.Field(i) cmdID, err := parseIdTag(&cmd.Tag) if err != nil { return fmt.Errorf("register lingos: parse id tag err: %v", err) } storeMapping(NewLingoCmdID(uint16(lingoID), cmdID), cmd.Type) } return nil } // DumpLingos returns a list of all registered lingos and commands func DumpLingos() string { type cmd struct { id LingoCmdID name string } var cmds []cmd for id, types := range mIDToType { cmds = append(cmds, cmd{id, types[0].String()}) } sort.Slice(cmds, func(i, j int) bool { return cmds[i].id < cmds[j].id }) buf := bytes.Buffer{} for _, cmd := range cmds { fmt.Fprintf(&buf, "%s\t%s\n", cmd.id.GoString(), cmd.name) } return buf.String() } // LookupID finds a registered LingoCmdID by the type of v // i.e. reverse to Lookup func LookupID(v interface{}) (id LingoCmdID, ok bool) { t := reflect.TypeOf(v) if t.Kind() != reflect.Ptr { panic(fmt.Sprintf("payload is not pointer: %v", v)) } id, ok = mTypeToID[t.Elem()] return } // LookupResult contains the result of a Lookup. // Payload is a pointer to a new zero value of the found type // Transaction specifies if the Transaction should be present in the packet. type LookupResult struct { Payload interface{} Transaction bool } // Lookup finds a the payload by LingoCmdID using payloadSize as a hint func Lookup(id LingoCmdID, payloadSize int, defaultTrxEnabled bool) (LookupResult, bool) { payloads, ok := mIDToType[id] if !ok { return LookupResult{}, false } for _, p := range payloads { v := reflect.New(p).Interface() cmdSize := binarySize(v) if cmdSize == -1 { continue } switch cmdSize { case payloadSize: return LookupResult{ Payload: v, Transaction: false, }, true case payloadSize - 2: return LookupResult{ Payload: v, Transaction: true, }, true } } // else assume transaction=true if len(payloads) == 1 { return LookupResult{ Payload: reflect.New(payloads[0]).Interface(), Transaction: defaultTrxEnabled, }, true } return LookupResult{}, false } func binarySize(v interface{}) int { return binary.Size(v) } const ( LingoGeneralID = 0x00 LingoSimpleRemoteID = 0x02 LingoDisplayRemoteID = 0x03 LingoExtRemoteID = 0x04 LingoUSBHostID = 0x06 LingoRFTunerID = 0x07 LingoEqID = 0x08 LingoSportsID = 0x09 LingoDigitalAudioID = 0x0A LingoStorageID = 0x0C ) <|start_filename|>lingo-general/acccapbit_string.go<|end_filename|> // Code generated by "stringer -type=AccCapBit"; DO NOT EDIT. package general import "strconv" func _() { // An "invalid array index" compiler error signifies that the constant values have changed. // Re-run the stringer command to generate them again. var x [1]struct{} _ = x[AccCapAnalogLineOut-1] _ = x[AccCapAnalogLineIn-2] _ = x[AccCapAnalogVideoOut-4] _ = x[AccCapUSBAudio-16] _ = x[AccCapAppComm-512] _ = x[AccCapCheckVolume-2048] } const ( _AccCapBit_name_0 = "AccCapAnalogLineOutAccCapAnalogLineIn" _AccCapBit_name_1 = "AccCapAnalogVideoOut" _AccCapBit_name_2 = "AccCapUSBAudio" _AccCapBit_name_3 = "AccCapAppComm" _AccCapBit_name_4 = "AccCapCheckVolume" ) var ( _AccCapBit_index_0 = [...]uint8{0, 19, 37} ) func (i AccCapBit) String() string { switch { case 1 <= i && i <= 2: i -= 1 return _AccCapBit_name_0[_AccCapBit_index_0[i]:_AccCapBit_index_0[i+1]] case i == 4: return _AccCapBit_name_1 case i == 16: return _AccCapBit_name_2 case i == 512: return _AccCapBit_name_3 case i == 2048: return _AccCapBit_name_4 default: return "AccCapBit(" + strconv.FormatInt(int64(i), 10) + ")" } } <|start_filename|>cmd/ipod/log.go<|end_filename|> package main import ( "fmt" "github.com/oandrew/ipod" "github.com/sirupsen/logrus" ) func FrameLogEntry(e *logrus.Entry, frame []byte) *logrus.Entry { return e.WithFields(logrus.Fields{ "len": len(frame), }) } func CommandLogEntry(e *logrus.Entry, cmd *ipod.Command) *logrus.Entry { if cmd == nil { return e } return e.WithFields(logrus.Fields{ "id": cmd.ID, "trx": cmd.Transaction, "type": fmt.Sprintf("%T", cmd.Payload), }) } <|start_filename|>transport.go<|end_filename|> package ipod type FrameReader interface { // ReadFrame reads a frame that contains // one or more iap packets ReadFrame() ([]byte, error) } type FrameWriter interface { // WriteFrame writes a frame that contains // one or more iap packets WriteFrame(data []byte) error } // FrameReadWriter is the interface // implemented by iap transports i.e. usbhid type FrameReadWriter interface { FrameReader FrameWriter } <|start_filename|>trace/trace_test.go<|end_filename|> package trace_test import ( "bytes" "io" "io/ioutil" "reflect" "strings" "testing" "github.com/oandrew/ipod/trace" ) func TestWriteRead(t *testing.T) { tests := []struct { name string m trace.Msg wantErr bool }{ {"simple-in", trace.Msg{Dir: trace.DirIn, Data: []byte{0x00}}, false}, {"simple-out", trace.Msg{Dir: trace.DirOut, Data: []byte{0x00}}, false}, {"bad-dir", trace.Msg{Dir: trace.Dir(0xaa), Data: []byte{0x00}}, true}, {"no-data", trace.Msg{Dir: trace.DirOut, Data: []byte{}}, true}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { buf := bytes.Buffer{} w := trace.NewWriter(&buf) t.Logf("msg: %#v", tt.m) if err := w.WriteMsg(&tt.m); (err != nil) != tt.wantErr { t.Errorf("Writer.WriteMsg() error = %v, wantErr %v", err, tt.wantErr) } if tt.wantErr { return } t.Logf("marshaled: %s", buf.String()) r := trace.NewReader(&buf) var mm trace.Msg if err := r.ReadMsg(&mm); err != nil { t.Error(err) } if !reflect.DeepEqual(tt.m, mm) { t.Errorf("msg1 != msg2: m1=%#v, m2=%#v", tt.m, mm) } }) } } func TestReadWrite(t *testing.T) { tests := []struct { name string t []byte wantErr bool }{ {"simple-in", []byte("< 01 02 03\n"), false}, {"simple-out", []byte("> 01 02 03\n"), false}, {"bad-dir", []byte("? 01 02 03\n"), true}, {"no-data", []byte(">\n"), true}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { buf1 := bytes.NewReader(tt.t) r := trace.NewReader(buf1) var m trace.Msg if err := r.ReadMsg(&m); (err != nil) != tt.wantErr { t.Errorf("Reader.ReadMsg() error = %v, wantErr %v", err, tt.wantErr) } if tt.wantErr { return } buf2 := bytes.Buffer{} w := trace.NewWriter(&buf2) if err := w.WriteMsg(&m); err != nil { t.Error(err) } if !reflect.DeepEqual(tt.t, buf2.Bytes()) { t.Errorf("msg1 != msg2: m1: %s, m2: %s", tt.t, buf2.Bytes()) } }) } } func TestTracer(t *testing.T) { tbuf := bytes.Buffer{} buf := bytes.Buffer{} tr := trace.NewTracer(&tbuf, &buf) t.Run("write", func(t *testing.T) { buf.Reset() tbuf.Reset() io.WriteString(tr, "ab") if buf.String() != "ab" { t.Errorf("dest: %s != %s", buf.String(), "ab") } if tbuf.String() != "> 61 62\n" { t.Errorf("trace: %s != %s", tbuf.String(), "> 61 62") } }) t.Run("read", func(t *testing.T) { buf.Reset() tbuf.Reset() buf.WriteString("ab") data, _ := ioutil.ReadAll(tr) if string(data) != "ab" { t.Errorf("dest: %s != %s", string(data), "ab") } if tbuf.String() != "< 61 62\n" { t.Errorf("trace: %s != %s", tbuf.String(), "< 61 62") } }) } var testReports = ` < 01 > 02 < 03 < 05 < 07 > 04 < 09 < 0A > 06 < 0B < 0C > 08 ` func TestTraceRead(t *testing.T) { r := trace.NewReader(strings.NewReader(testReports)) for { var msg trace.Msg err := r.ReadMsg(&msg) if err == io.EOF { break } t.Logf("msg: %#v", msg) } } func TestTraceQueue(t *testing.T) { r := trace.NewReader(strings.NewReader(testReports)) var q1 trace.Queue var q2 trace.Queue var q3 trace.Queue var q4 trace.Queue for { var msg trace.Msg err := r.ReadMsg(&msg) if err == io.EOF { break } q1.Enqueue(&msg) q2.Enqueue(&msg) q3.Enqueue(&msg) q4.Enqueue(&msg) } for { m := q1.Dequeue() if m == nil { break } t.Logf("msg: %#v", m) } t.Logf("in first") for { m := q2.DequeueDir(trace.DirIn) if m == nil { break } t.Logf("msg: %#v", m) } t.Logf("out first") for { m := q3.DequeueDir(trace.DirOut) if m == nil { break } t.Logf("msg: %#v", m) } t.Logf("in,out,in,...") dir := trace.DirIn for { m := q4.DequeueDir(dir) if m == nil && q4.Head() == nil { break } if dir == trace.DirIn { dir = trace.DirOut } else { dir = trace.DirIn } t.Logf("msg: %#v", m) } } <|start_filename|>crc.go<|end_filename|> package ipod import ( "hash" ) type CRC8 interface { hash.Hash Sum8() uint8 } type crc8 struct { crc byte } func (c *crc8) Write(p []byte) (n int, err error) { for _, v := range p { c.crc += v } return len(p), nil } func (c *crc8) Sum8() byte { return -c.crc } func (c *crc8) Sum(in []byte) []byte { return append(in, c.Sum8()) } func (c *crc8) Reset() { c.crc = 0x00 } func (c *crc8) Size() int { return 1 } func (c *crc8) BlockSize() int { return 1 } func NewCRC8() CRC8 { return &crc8{} } func Checksum(p []byte) uint8 { var crc byte for _, v := range p { crc += v } return -crc }
Kytech/ipod